code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def maybe_gzip_open(path, *args, **kwargs): """ Open file with either open or gzip.open, depending on file extension. This function doesn't handle json lines format, just opens a file in a way it is decoded transparently if needed. """ path = path_to_str(path) if path.endswith('.gz') or pat...
Open file with either open or gzip.open, depending on file extension. This function doesn't handle json lines format, just opens a file in a way it is decoded transparently if needed.
def __get_data_en_intervalo(self, d0=None, df=None): """ Obtiene los datos en bruto de la red realizando múltiples requests al tiempo Procesa los datos en bruto obtenidos de la red convirtiendo a Pandas DataFrame """ params = {'date_fmt': self.DATE_FMT, 'usar_m...
Obtiene los datos en bruto de la red realizando múltiples requests al tiempo Procesa los datos en bruto obtenidos de la red convirtiendo a Pandas DataFrame
def match(self, regex, flags=0): """ Matches the specified *regex* from the current character of the *scanner* and returns the result. The Scanners column and line numbers are updated respectively. # Arguments regex (str, Pattern): The regex to match. flags (int): The flags to use when comp...
Matches the specified *regex* from the current character of the *scanner* and returns the result. The Scanners column and line numbers are updated respectively. # Arguments regex (str, Pattern): The regex to match. flags (int): The flags to use when compiling the pattern.
def _sample_mvn(mean, cov, cov_structure=None, num_samples=None): """ Returns a sample from a D-dimensional Multivariate Normal distribution :param mean: [..., N, D] :param cov: [..., N, D] or [..., N, D, D] :param cov_structure: "diag" or "full" - "diag": cov holds the diagonal elements of the ...
Returns a sample from a D-dimensional Multivariate Normal distribution :param mean: [..., N, D] :param cov: [..., N, D] or [..., N, D, D] :param cov_structure: "diag" or "full" - "diag": cov holds the diagonal elements of the covariance matrix - "full": cov holds the full covariance matrix (without ...
def _process_witness(self, witness, matches): """Return the counts of total tokens and matching tokens in `witness`. :param witness: witness text :type witness: `tacl.WitnessText` :param matches: n-gram matches :type matches: `pandas.DataFrame` :rtype: `tuple` of `int` ...
Return the counts of total tokens and matching tokens in `witness`. :param witness: witness text :type witness: `tacl.WitnessText` :param matches: n-gram matches :type matches: `pandas.DataFrame` :rtype: `tuple` of `int`
def append_this_package_path(depth=1): """ this_package.py 에서 사용 import snipy.this_package """ from .caller import caller logg.debug('caller module %s', caller.modulename(depth + 1)) c = caller.abspath(depth + 1) logg.debug('caller path %s', c) p = guess_package_path(dirname(c)) ...
this_package.py 에서 사용 import snipy.this_package
def getpackagepath(): """ *Get the root path for this python package - used in unit testing code* """ moduleDirectory = os.path.dirname(__file__) packagePath = os.path.dirname(__file__) + "/../" return packagePath
*Get the root path for this python package - used in unit testing code*
def subsample_n(X, n=0, seed=0): """Subsample n samples from rows of array. Parameters ---------- X : np.ndarray Data array. seed : int Seed for sampling. Returns ------- Xsampled : np.ndarray Subsampled X. rows : np.ndarray Indices of rows that are ...
Subsample n samples from rows of array. Parameters ---------- X : np.ndarray Data array. seed : int Seed for sampling. Returns ------- Xsampled : np.ndarray Subsampled X. rows : np.ndarray Indices of rows that are stored in Xsampled.
def load_metadata_for_topics(self, *topics, **kwargs): """Fetch broker and topic-partition metadata from the server. Updates internal data: broker list, topic/partition list, and topic/partition -> broker map. This method should be called after receiving any error. Note: Except...
Fetch broker and topic-partition metadata from the server. Updates internal data: broker list, topic/partition list, and topic/partition -> broker map. This method should be called after receiving any error. Note: Exceptions *will not* be raised in a full refresh (i.e. no topic ...
def tls_session_update(self, msg_str): """ XXX Something should be done about the session ID here. """ super(SSLv2ServerHello, self).tls_session_update(msg_str) s = self.tls_session client_cs = s.sslv2_common_cs css = [cs for cs in client_cs if cs in self.ciphers...
XXX Something should be done about the session ID here.
def map_alignment(self, prot_seq, nucl_seq): """ Use aligned prot_seq to align nucl_seq """ if prot_seq.id != nucl_seq.id: logging.warning( 'ID mismatch: %s != %s. Are the sequences in the same order?', prot_seq.id, nucl_seq.id) # Unga...
Use aligned prot_seq to align nucl_seq
def lessons(self): """ 返回lessons,如果未调用过``get_lesson()``会自动调用 :return: list of lessons :rtype: list """ if hasattr(self, '_lessons'): return self._lessons else: self.get_lesson() return self._lessons
返回lessons,如果未调用过``get_lesson()``会自动调用 :return: list of lessons :rtype: list
def mme_matches(case_obj, institute_obj, mme_base_url, mme_token): """Show Matchmaker submission data for a sample and eventual matches. Args: case_obj(dict): a scout case object institute_obj(dict): an institute object mme_base_url(str) base url of the MME server mme_token(str)...
Show Matchmaker submission data for a sample and eventual matches. Args: case_obj(dict): a scout case object institute_obj(dict): an institute object mme_base_url(str) base url of the MME server mme_token(str) auth token of the MME server Returns: data(dict): data to di...
def rug(x, label=None, opacity=None): """Rug chart. Parameters ---------- x : array-like, optional label : TODO, optional opacity : TODO, optional Returns ------- Chart """ x = _try_pydatetime(x) x = np.atleast_1d(x) data = [ go.Scatter( x=x, ...
Rug chart. Parameters ---------- x : array-like, optional label : TODO, optional opacity : TODO, optional Returns ------- Chart
def get_application_access_token(application_id, application_secret_key, api_version=None): """ Get an OAuth access token for the given application. :param application_id: An integer describing a Facebook application's ID. :param application_secret_key: A string describing a Facebook application's secr...
Get an OAuth access token for the given application. :param application_id: An integer describing a Facebook application's ID. :param application_secret_key: A string describing a Facebook application's secret key.
def other_supplementary_files(self): """The supplementary files of this notebook""" if self._other_supplementary_files is not None: return self._other_supplementary_files return getattr(self.nb.metadata, 'other_supplementary_files', None)
The supplementary files of this notebook
def transformToRef(self): """ Transform reference catalog sky positions (self.all_radec) to reference tangent plane (self.wcs) to create output X,Y positions. """ if 'refxyunits' in self.pars and self.pars['refxyunits'] == 'pixels': log.info('Creating RA/Dec positions for ref...
Transform reference catalog sky positions (self.all_radec) to reference tangent plane (self.wcs) to create output X,Y positions.
def main(): """ Slowly writes to stdout, without emitting a newline so any output buffering (or input for next pipeline command) can be detected. """ now = datetime.datetime.now try: while True: sys.stdout.write(str(now()) + ' ') time.sleep(1) except KeyboardI...
Slowly writes to stdout, without emitting a newline so any output buffering (or input for next pipeline command) can be detected.
def tree_build(self): """Build a tree from the taxonomy data present in this `ClassificationsDataFrame` or `SampleCollection`. Returns ------- `skbio.tree.TreeNode`, the root node of a tree that contains all the taxa in the current analysis and their parents leading back...
Build a tree from the taxonomy data present in this `ClassificationsDataFrame` or `SampleCollection`. Returns ------- `skbio.tree.TreeNode`, the root node of a tree that contains all the taxa in the current analysis and their parents leading back to the root node.
def read_full(data, size): """ read_full reads exactly `size` bytes from reader. returns `size` bytes. :param data: Input stream to read from. :param size: Number of bytes to read from `data`. :return: Returns :bytes:`part_data` """ default_read_size = 32768 # 32KiB per read operation. ...
read_full reads exactly `size` bytes from reader. returns `size` bytes. :param data: Input stream to read from. :param size: Number of bytes to read from `data`. :return: Returns :bytes:`part_data`
def get_other_props(all_props, reserved_props): # type: (Dict, Tuple) -> Optional[Dict] """ Retrieve the non-reserved properties from a dictionary of properties @args reserved_props: The set of reserved properties to exclude """ if hasattr(all_props, 'items') and callable(all_props.items): ...
Retrieve the non-reserved properties from a dictionary of properties @args reserved_props: The set of reserved properties to exclude
def add_model(self, model_type: str, model_uuid: str, meta: dict, template_model: Template, update_default: bool=False): """Add a new model to the registry. Call `upload()` to update the remote side.""" if update_default or model_type not in self.meta: self.meta[model_type]...
Add a new model to the registry. Call `upload()` to update the remote side.
def file_checksum(filepath): """Calculate md5 checksum on file :param filepath: Full path to file (e.g. /home/stack/image.qcow2) :type filepath: string """ checksum = hashlib.md5() with open(filepath, 'rb') as f: for fragment in iter(lambda: f.read(65536), ''): checksum.up...
Calculate md5 checksum on file :param filepath: Full path to file (e.g. /home/stack/image.qcow2) :type filepath: string
def script(script, interpreter='', suffix='', args='', **kwargs): '''Execute specified script using specified interpreter. This action accepts common action arguments such as input, active, workdir, docker_image and args. In particular, content of one or more files specified by option input would be prepend...
Execute specified script using specified interpreter. This action accepts common action arguments such as input, active, workdir, docker_image and args. In particular, content of one or more files specified by option input would be prepended before the specified script.
def execute(self, sql, args): """Execute sql :param sql string: the sql stamtement like 'select * from %s' :param args list: Wen set None, will use dbi execute(sql), else db execute(sql, args), the args keep the original rules, it shuld be tuple or list of list """ ...
Execute sql :param sql string: the sql stamtement like 'select * from %s' :param args list: Wen set None, will use dbi execute(sql), else db execute(sql, args), the args keep the original rules, it shuld be tuple or list of list
def xmoe_dense_4k(): """Series of architectural experiments on cheap language models. For all of these architectures, we run on languagemodel_lm1b8k_packed for 32000 steps. All log-perplexities are per-token - multiply by 1.298 for per-word Results: model params(M) einsum alltoall mxu-util...
Series of architectural experiments on cheap language models. For all of these architectures, we run on languagemodel_lm1b8k_packed for 32000 steps. All log-perplexities are per-token - multiply by 1.298 for per-word Results: model params(M) einsum alltoall mxu-util log-ppl xmoe_dense_4k ...
def local_path(self, url, filename=None, decompress=False, download=False): """ What will the full local path be if we download the given file? """ if download: return self.fetch(url=url, filename=filename, decompress=decompress) else: filename = self.loca...
What will the full local path be if we download the given file?
def get_resolved_res_configs(self, rid, config=None): """ Return a list of resolved resource IDs with their corresponding configuration. It has a similar return type as :meth:`get_res_configs` but also handles complex entries and references. Also instead of returning :class:`ARSC...
Return a list of resolved resource IDs with their corresponding configuration. It has a similar return type as :meth:`get_res_configs` but also handles complex entries and references. Also instead of returning :class:`ARSCResTableEntry` in the tuple, the actual values are resolved. This...
def save_formset_with_author(formset, user): """ Проставляет моделям из набора форм автора :param formset: набор форм :param user: автор :return: """ instances = formset.save(commit=False) for obj in formset.deleted_objects: obj.delete() for instance in instances: if ...
Проставляет моделям из набора форм автора :param formset: набор форм :param user: автор :return:
def keep_on_one_line(): """ Keep all the output generated within a with-block on one line. Whenever a new line would be printed, instead reset the cursor to the beginning of the line and print the new line without a line break. """ class CondensedStream: def __init__(self): ...
Keep all the output generated within a with-block on one line. Whenever a new line would be printed, instead reset the cursor to the beginning of the line and print the new line without a line break.
def create(annot=None, config=None, id=None, ui=None): """ :type annot: dict :type config: NetworkConfig :type id: str :type ui: dict :rtype: Network """ return Network( annot=annot, config=config, id=id, ui...
:type annot: dict :type config: NetworkConfig :type id: str :type ui: dict :rtype: Network
def qft(circ, q, n): """n-qubit QFT on q in circ.""" for j in range(n): for k in range(j): circ.cu1(math.pi / float(2**(j - k)), q[j], q[k]) circ.h(q[j])
n-qubit QFT on q in circ.
def _ParseBooleanValue(self, byte_stream): """Parses a boolean value. Args: byte_stream (bytes): byte stream. Returns: bool: boolean value. Raises: ParseError: when the boolean value cannot be parsed. """ if byte_stream == b'\x00': return False if byte_stream == b...
Parses a boolean value. Args: byte_stream (bytes): byte stream. Returns: bool: boolean value. Raises: ParseError: when the boolean value cannot be parsed.
def delete_profile_extension_members(self, profile_extension, query_column, ids_to_delete): """ Responsys.deleteProfileExtensionRecords call Accepts: InteractObject profile_extension list field_list list ids_to_retrieve string query_column ...
Responsys.deleteProfileExtensionRecords call Accepts: InteractObject profile_extension list field_list list ids_to_retrieve string query_column default: 'RIID' Returns list of DeleteResults
def load(pattern, *args, **kw): ''' Given a package asset-spec glob-pattern `pattern`, returns an :class:`AssetGroup` object, which in turn can act as a generator of :class:`Asset` objects that match the pattern. Example: .. code-block:: python import asset # concatenate all 'css' files into one...
Given a package asset-spec glob-pattern `pattern`, returns an :class:`AssetGroup` object, which in turn can act as a generator of :class:`Asset` objects that match the pattern. Example: .. code-block:: python import asset # concatenate all 'css' files into one string: css = asset.load('mypackage...
def main(arguments=None): """ *The main function used when ``cl_utils.py`` is run as a single script from the cl, or when installed as a cl command* """ # setup the command-line util settings su = tools( arguments=arguments, docString=__doc__, logLevel="WARNING", opti...
*The main function used when ``cl_utils.py`` is run as a single script from the cl, or when installed as a cl command*
def str_eta(self): """Returns a formatted ETA value for the progress bar.""" if self.done: return eta_hms(self._eta.elapsed, always_show_hours=True, hours_leading_zero=True) if not self._eta_string: return '' return '{0} ETA'.format(self._eta_string)
Returns a formatted ETA value for the progress bar.
def convert_zero_consonant(pinyin): """零声母转换,还原原始的韵母 i行的韵母,前面没有声母的时候,写成yi(衣),ya(呀),ye(耶),yao(腰), you(忧),yan(烟),yin(因),yang(央),ying(英),yong(雍)。 u行的韵母,前面没有声母的时候,写成wu(乌),wa(蛙),wo(窝),wai(歪), wei(威),wan(弯),wen(温),wang(汪),weng(翁)。 ü行的韵母,前面没有声母的时候,写成yu(迂),yue(约),yuan(冤), yun(晕);ü上两点省略。 """ ...
零声母转换,还原原始的韵母 i行的韵母,前面没有声母的时候,写成yi(衣),ya(呀),ye(耶),yao(腰), you(忧),yan(烟),yin(因),yang(央),ying(英),yong(雍)。 u行的韵母,前面没有声母的时候,写成wu(乌),wa(蛙),wo(窝),wai(歪), wei(威),wan(弯),wen(温),wang(汪),weng(翁)。 ü行的韵母,前面没有声母的时候,写成yu(迂),yue(约),yuan(冤), yun(晕);ü上两点省略。
def as_tuple(ireq): """ Pulls out the (name: str, version:str, extras:(str)) tuple from the pinned InstallRequirement. """ if not is_pinned_requirement(ireq): raise TypeError("Expected a pinned InstallRequirement, got {}".format(ireq)) name = key_from_req(ireq.req) version = first(ireq...
Pulls out the (name: str, version:str, extras:(str)) tuple from the pinned InstallRequirement.
def clusterStatus(self): """ Returns a dict of cluster nodes and their status information """ servers = yield self.getClusterServers() d = { 'workers': {}, 'crons': {}, 'queues': {} } now = time.time() reverse_map = {...
Returns a dict of cluster nodes and their status information
def calcKYratioDifference(self): ''' Returns the difference between the simulated capital to income ratio and the target ratio. Can only be run after solving all AgentTypes and running makeHistory. Parameters ---------- None Returns ------- diff ...
Returns the difference between the simulated capital to income ratio and the target ratio. Can only be run after solving all AgentTypes and running makeHistory. Parameters ---------- None Returns ------- diff : float Difference between simulated and ...
def SunLongitude(jdn): '''def SunLongitude(jdn): Compute the longitude of the sun at any time. Parameter: floating number jdn, the number of days since 1/1/4713 BC noon. ''' T = (jdn - 2451545.0) / 36525. # Time in Julian centuries # from 2000-01-01 12:00:00 GMT T2 = T * T dr = math.pi /...
def SunLongitude(jdn): Compute the longitude of the sun at any time. Parameter: floating number jdn, the number of days since 1/1/4713 BC noon.
def _parse_stsd(self, atom, fileobj): """Sets channels, bits_per_sample, sample_rate and optionally bitrate. Can raise MP4StreamInfoError. """ assert atom.name == b"stsd" ok, data = atom.read(fileobj) if not ok: raise MP4StreamInfoError("Invalid stsd") ...
Sets channels, bits_per_sample, sample_rate and optionally bitrate. Can raise MP4StreamInfoError.
def PrintFieldValue(self, field, value): """Print a single field value (not including name). For repeated fields, the value should be a single element. Args: field: The descriptor of the field to be printed. value: The value of the field. """ out = self.out if self.pointy_brackets:...
Print a single field value (not including name). For repeated fields, the value should be a single element. Args: field: The descriptor of the field to be printed. value: The value of the field.
def restart_on_change(restart_map, stopstart=False, restart_functions=None): """Restart services based on configuration files changing This function is used a decorator, for example:: @restart_on_change({ '/etc/ceph/ceph.conf': [ 'cinder-api', 'cinder-volume' ] '/etc/apache/sit...
Restart services based on configuration files changing This function is used a decorator, for example:: @restart_on_change({ '/etc/ceph/ceph.conf': [ 'cinder-api', 'cinder-volume' ] '/etc/apache/sites-enabled/*': [ 'apache2' ] }) def config_changed(): ...
def run_benchmark(monitor): '''Run the benchmarks ''' url = urlparse(monitor.cfg.test_url) name = slugify(url.path) or 'home' name = '%s_%d.csv' % (name, monitor.cfg.workers) monitor.logger.info('WRITING RESULTS ON "%s"', name) total = REQUESTS//monitor.cfg.workers with open(name, 'w') ...
Run the benchmarks
def get_income_in_period(self, start: datetime, end: datetime) -> Decimal: """ Returns all income in the given period """ accounts = self.get_income_accounts() income = Decimal(0) for acct in accounts: acc_agg = AccountAggregate(self.book, acct) acc_bal = acc_agg....
Returns all income in the given period
def FULL_TEXT(val): ''' This is a basic full-text index keygen function. Words are lowercased, split by whitespace, and stripped of punctuation from both ends before an inverted index is created for term searching. ''' if isinstance(val, float): val = repr(val) elif val in (None, '')...
This is a basic full-text index keygen function. Words are lowercased, split by whitespace, and stripped of punctuation from both ends before an inverted index is created for term searching.
def _merge_update_item(self, model_item, data): """ Merge a model with a python data structure This is useful to turn PUT method into a PATCH also :param model_item: SQLA Model :param data: python data structure :return: python data structure """ d...
Merge a model with a python data structure This is useful to turn PUT method into a PATCH also :param model_item: SQLA Model :param data: python data structure :return: python data structure
def retrieve(self, request, project, pk=None): """ Returns a job_log_url object given its ID """ log = JobLog.objects.get(id=pk) return Response(self._log_as_dict(log))
Returns a job_log_url object given its ID
def get_project_config_file(path, default_config_file_name): """Attempts to extract the project config file's absolute path from the given path. If the path is a directory, it automatically assumes a "config.yml" file will be in that directory. If the path is to a .yml file, it assumes that that is the root...
Attempts to extract the project config file's absolute path from the given path. If the path is a directory, it automatically assumes a "config.yml" file will be in that directory. If the path is to a .yml file, it assumes that that is the root configuration file for the project.
def language(self): """ Get the language :class:`language_tags.Subtag.Subtag` of the tag. :return: language :class:`language_tags.Subtag.Subtag` that is part of the tag. The return can be None. """ language_item = [subtag for subtag in self.subtags if subtag.type ==...
Get the language :class:`language_tags.Subtag.Subtag` of the tag. :return: language :class:`language_tags.Subtag.Subtag` that is part of the tag. The return can be None.
def extract_meta(self, text): """ Takes input as the entire file. Reads the first yaml document as metadata. and the rest of the document as text """ first_line = True metadata = [] content = [] metadata_parsed = False for line in text.spl...
Takes input as the entire file. Reads the first yaml document as metadata. and the rest of the document as text
def _job_completed(self, job_name, success, message): """ Internal method. Called when a job of a long running task completes. """ job = self._objects[job_name][Interface['Job']] action = self._action_by_operation.get(job['Operation']) if not action: ...
Internal method. Called when a job of a long running task completes.
async def wait_event(signals: Sequence['Signal[T_Event]'], filter: Callable[[T_Event], bool] = None) -> T_Event: """ Wait until any of the given signals dispatches an event that satisfies the filter (if any). If no filter has been given, the first event dispatched from the signal is re...
Wait until any of the given signals dispatches an event that satisfies the filter (if any). If no filter has been given, the first event dispatched from the signal is returned. :param signals: the signals to get events from :param filter: a callable that takes an event object as an argument and returns ``...
def _adjust_beforenext(self, real_wave_mfcc, algo_parameters): """ BEFORENEXT """ def new_time(nsi): """ The new boundary time value is ``delay`` before the end of the nonspeech interval ``nsi``. If ``nsi`` has length less than ``delay``, ...
BEFORENEXT
def parseprint(code, filename="<string>", mode="exec", **kwargs): """Parse some code from a string and pretty-print it.""" node = parse(code, mode=mode) # An ode to the code print(dump(node, **kwargs))
Parse some code from a string and pretty-print it.
def _run(self): """Discovers the health of a service. Runs until it is being killed from main program and is responsible to put an item into the queue based on the status of the health check. The status of service is consider UP after a number of consecutive successful health ch...
Discovers the health of a service. Runs until it is being killed from main program and is responsible to put an item into the queue based on the status of the health check. The status of service is consider UP after a number of consecutive successful health checks, in that case it asks ...
def calc_mean_time(timepoints, weights): """Return the weighted mean of the given timepoints. With equal given weights, the result is simply the mean of the given time points: >>> from hydpy import calc_mean_time >>> calc_mean_time(timepoints=[3., 7.], ... weights=[2., 2.]) ...
Return the weighted mean of the given timepoints. With equal given weights, the result is simply the mean of the given time points: >>> from hydpy import calc_mean_time >>> calc_mean_time(timepoints=[3., 7.], ... weights=[2., 2.]) 5.0 With different weights, the resulting m...
def split(self, file): """Split a file into records using a specific strategy This RecordIOSplitter splits the data into individual RecordIO records. Args: file (str): path to the file to split Returns: generator for the individual records that were split from the file ...
Split a file into records using a specific strategy This RecordIOSplitter splits the data into individual RecordIO records. Args: file (str): path to the file to split Returns: generator for the individual records that were split from the file
def publish(): """Publishes Formic to PyPi (don't run unless you are the maintainer)""" print("To be ready for release, remember:") print(" 1) Update the version number (and associated test)") print(" 2) Update the ChangeLog.rst (and other documentation)") print( " ChangeLo...
Publishes Formic to PyPi (don't run unless you are the maintainer)
def lambda_A_calc(classes, table, P, POP): """ Calculate Goodman and Kruskal's lambda A. :param classes: confusion matrix classes :type classes : list :param table: confusion matrix table :type table : dict :param P: condition positive :type P : dict :param POP: population :type...
Calculate Goodman and Kruskal's lambda A. :param classes: confusion matrix classes :type classes : list :param table: confusion matrix table :type table : dict :param P: condition positive :type P : dict :param POP: population :type POP : int :return: Goodman and Kruskal's lambda A ...
def handle_log_data(self, m): '''handling incoming log data''' if self.download_file is None: return # lose some data # import random # if random.uniform(0,1) < 0.05: # print('dropping ', str(m)) # return if m.ofs != self.download_ofs: ...
handling incoming log data
def set_global_fontsize_from_fig(fig, scale=1.5): """ Set matplotlib.rcParams['font.size'] value so that all texts on a plot would look nice in terms of fontsize. [NOTE] The formula for the font size is: fontsize = sqrt(fig_area) * 'scale' where fig_area = fig_height * fig_width (in inch) ...
Set matplotlib.rcParams['font.size'] value so that all texts on a plot would look nice in terms of fontsize. [NOTE] The formula for the font size is: fontsize = sqrt(fig_area) * 'scale' where fig_area = fig_height * fig_width (in inch)
def pre_render(self): """Last things to do before rendering""" self.add_styles() self.add_scripts() self.root.set( 'viewBox', '0 0 %d %d' % (self.graph.width, self.graph.height) ) if self.graph.explicit_size: self.root.set('width', str(self.graph.w...
Last things to do before rendering
def set_cpuid_leaf(self, idx, idx_sub, val_eax, val_ebx, val_ecx, val_edx): """Sets the virtual CPU cpuid information for the specified leaf. Note that these values are not passed unmodified. VirtualBox clears features that it doesn't support. Currently supported index values for cpuid:...
Sets the virtual CPU cpuid information for the specified leaf. Note that these values are not passed unmodified. VirtualBox clears features that it doesn't support. Currently supported index values for cpuid: Standard CPUID leaves: 0 - 0x1f Extended CPUID leaves: 0x80000000 - 0x...
def get_monitor(self, topics): """Attempts to find a Monitor in device cloud that matches the provided topics :param topics: a string list of topics (e.g. ``['DeviceCore[U]', 'FileDataCore'])``) Returns a :class:`DeviceCloudMonitor` if found, otherwise None. """ for monitor in ...
Attempts to find a Monitor in device cloud that matches the provided topics :param topics: a string list of topics (e.g. ``['DeviceCore[U]', 'FileDataCore'])``) Returns a :class:`DeviceCloudMonitor` if found, otherwise None.
def beholder_ng(func): """Behold analysis procedure.""" @functools.wraps(func) def behold(file, length, *args, **kwargs): seek_cur = file.tell() try: return func(file, length, *args, **kwargs) except Exception: # from pcapkit.foundation.analysis import analyse...
Behold analysis procedure.
def _transpose_chars(text, pos): """ Drag the character before pos forward over the character at pos, moving pos forward as well. If pos is at the end of text, then this transposes the two characters before pos. """ if len(text) < 2 or pos == 0: return text, pos if pos == len(text): ...
Drag the character before pos forward over the character at pos, moving pos forward as well. If pos is at the end of text, then this transposes the two characters before pos.
def _getLayer(self, name, **kwargs): """ This is the environment implementation of :meth:`BaseFont.getLayer`. **name** will be a :ref:`type-string`. It will have been normalized with :func:`normalizers.normalizeLayerName` and it will have been verified as an existing laye...
This is the environment implementation of :meth:`BaseFont.getLayer`. **name** will be a :ref:`type-string`. It will have been normalized with :func:`normalizers.normalizeLayerName` and it will have been verified as an existing layer. This must return an instance of :class:`BaseLa...
def next(self): """ Get the next child. @return: The next child. @rtype: L{Element} @raise StopIterator: At the end. """ try: child = self.children[self.pos] self.pos += 1 return child except: raise StopItera...
Get the next child. @return: The next child. @rtype: L{Element} @raise StopIterator: At the end.
def sync(self, command, arguments, tags=None, id=None): """ Same as self.raw except it do a response.get() waiting for the command execution to finish and reads the result :param command: Command name to execute supported by the node (ex: core.system, info.cpu, etc...) ch...
Same as self.raw except it do a response.get() waiting for the command execution to finish and reads the result :param command: Command name to execute supported by the node (ex: core.system, info.cpu, etc...) check documentation for list of built in commands :param arguments: A ...
def get_paying_proxy_contract(w3: Web3, address=None): """ Get Paying Proxy Contract. This should be used just for contract creation/changing master_copy If you want to call Safe methods you should use `get_safe_contract` with the Proxy address, so you can access every method of the Safe :param w3: ...
Get Paying Proxy Contract. This should be used just for contract creation/changing master_copy If you want to call Safe methods you should use `get_safe_contract` with the Proxy address, so you can access every method of the Safe :param w3: Web3 instance :param address: address of the proxy contract ...
def remove_metadata_key(self, container, key): """ Removes the specified key from the container's metadata. If the key does not exist in the metadata, nothing is done. """ meta_dict = {key: ""} return self.set_metadata(container, meta_dict)
Removes the specified key from the container's metadata. If the key does not exist in the metadata, nothing is done.
def _kvmatrix2d(km,vm): ''' km = [[[1], [3]], [[1, 2], [3, 'a']], [[1, 2, 22]]] show_kmatrix(km) vm = [[[222]], ['b']] show_vmatrix(vm) d = _kvmatrix2d(km,vm) ''' d = {} kmwfs = get_kmwfs(km) vmwfs = elel.get_wfs(vm) lngth = vmwfs.__len__...
km = [[[1], [3]], [[1, 2], [3, 'a']], [[1, 2, 22]]] show_kmatrix(km) vm = [[[222]], ['b']] show_vmatrix(vm) d = _kvmatrix2d(km,vm)
def background_knowledge(self): ''' Emits the background knowledge in prolog form for Aleph. ''' modeslist, getters = [self.mode(self.__target_predicate(), [('+', self.db.target_table)], head=True)], [] determinations, types = [], [] for (table, ref_table) in self.db.conn...
Emits the background knowledge in prolog form for Aleph.
def _get_migrate_funcs(cls, orig_version, target_version): """ >>> @Manager.register ... def v1_to_2(manager, doc): ... doc['foo'] = 'bar' >>> @Manager.register ... def v2_to_1(manager, doc): ... del doc['foo'] >>> @Manager.register ... def v2_to_3(manager, doc): ... doc['foo'] = doc['fo...
>>> @Manager.register ... def v1_to_2(manager, doc): ... doc['foo'] = 'bar' >>> @Manager.register ... def v2_to_1(manager, doc): ... del doc['foo'] >>> @Manager.register ... def v2_to_3(manager, doc): ... doc['foo'] = doc['foo'] + ' baz' >>> funcs = list(Manager._get_migrate_funcs(1, 3)) ...
def read_multiple( self, points_list, *, points_per_request=1, discover_request=(None, 6) ): """ Functions to read points from a device using the ReadPropertyMultiple request. Using readProperty request can be very slow to read a lot of data. :param points_list: (list...
Functions to read points from a device using the ReadPropertyMultiple request. Using readProperty request can be very slow to read a lot of data. :param points_list: (list) a list of all point_name as str :param points_per_request: (int) number of points in the request Using too ...
def mgf1(mgf_seed, mask_len, hash_class=hashlib.sha1): ''' Mask Generation Function v1 from the PKCS#1 v2.0 standard. mgs_seed - the seed, a byte string mask_len - the length of the mask to generate hash_class - the digest algorithm to use, default is SHA1 Return value: a pseudo...
Mask Generation Function v1 from the PKCS#1 v2.0 standard. mgs_seed - the seed, a byte string mask_len - the length of the mask to generate hash_class - the digest algorithm to use, default is SHA1 Return value: a pseudo-random mask, as a byte string
def get_url_kwargs(self, request_kwargs=None, **kwargs): """ Get the kwargs needed to reverse this url. :param request_kwargs: The kwargs from the current request. \ These keyword arguments are only retained if they are present \ in this bundle's known url_parameters. :p...
Get the kwargs needed to reverse this url. :param request_kwargs: The kwargs from the current request. \ These keyword arguments are only retained if they are present \ in this bundle's known url_parameters. :param kwargs: Keyword arguments that will always be kept.
def addFromTex(self,name,img,category): """ Adds a new texture from the given image. ``img`` may be any object that supports Pyglet-style copying in form of the ``blit_to_texture()`` method. This can be used to add textures that come from non-file sources, e.g. Render-t...
Adds a new texture from the given image. ``img`` may be any object that supports Pyglet-style copying in form of the ``blit_to_texture()`` method. This can be used to add textures that come from non-file sources, e.g. Render-to-texture.
def regroup(self, group): """Deprecated method to apply new group to items. Equivalent functionality possible using: ViewableTree(tree.relabel(group='Group').values()) """ if util.config.future_deprecations: self.param.warning('%s.regroup is deprecated, use rela...
Deprecated method to apply new group to items. Equivalent functionality possible using: ViewableTree(tree.relabel(group='Group').values())
def engagement_context(self): """ Access the engagement_context :returns: twilio.rest.studio.v1.flow.engagement.engagement_context.EngagementContextList :rtype: twilio.rest.studio.v1.flow.engagement.engagement_context.EngagementContextList """ if self._engagement_context...
Access the engagement_context :returns: twilio.rest.studio.v1.flow.engagement.engagement_context.EngagementContextList :rtype: twilio.rest.studio.v1.flow.engagement.engagement_context.EngagementContextList
def drawing_end(self): '''end line drawing''' from MAVProxy.modules.mavproxy_map import mp_slipmap if self.draw_callback is None: return self.draw_callback(self.draw_line) self.draw_callback = None self.map.add_object(mp_slipmap.SlipDefaultPopup(self.default_p...
end line drawing
def altitudes_encode(self, time_boot_ms, alt_gps, alt_imu, alt_barometric, alt_optical_flow, alt_range_finder, alt_extra): ''' The altitude measured by sensors and IMU time_boot_ms : Timestamp (milliseconds since system boot) (uint32_t) alt_g...
The altitude measured by sensors and IMU time_boot_ms : Timestamp (milliseconds since system boot) (uint32_t) alt_gps : GPS altitude in meters, expressed as * 1000 (millimeters), above MSL (int32_t) alt_imu : IMU altitude ...
def apply_filter(self, expr, value): """ Returns the given expression filtered by the given value. Args: expr (xpath.expression.AbstractExpression): The expression to filter. value (object): The desired value with which the expression should be filtered. Returns...
Returns the given expression filtered by the given value. Args: expr (xpath.expression.AbstractExpression): The expression to filter. value (object): The desired value with which the expression should be filtered. Returns: xpath.expression.AbstractExpression: The fi...
def GetFile(message=None, title=None, directory=None, fileName=None, allowsMultipleSelection=False, fileTypes=None): """ An get file dialog. Optionally a `message`, `title`, `directory`, `fileName` and `allowsMultipleSelection` can be provided. :: from fontParts.ui import GetFi...
An get file dialog. Optionally a `message`, `title`, `directory`, `fileName` and `allowsMultipleSelection` can be provided. :: from fontParts.ui import GetFile print(GetFile())
def calculate(self, film, substrate, elasticity_tensor=None, film_millers=None, substrate_millers=None, ground_state_energy=0, lowest=False): """ Finds all topological matches for the substrate and calculates elastic strain energy and total energy for the film...
Finds all topological matches for the substrate and calculates elastic strain energy and total energy for the film if elasticity tensor and ground state energy are provided: Args: film(Structure): conventional standard structure for the film substrate(Structure): convent...
def unicode_symbol(self, *, invert_color: bool = False) -> str: """ Gets the Unicode character for the piece. """ symbol = self.symbol().swapcase() if invert_color else self.symbol() return UNICODE_PIECE_SYMBOLS[symbol]
Gets the Unicode character for the piece.
def authenticate_application(self, api_token, admin_token, override=False, fetch=True): """Set credentials for Application authentication. Important Note: Do not use Application auth on any end-user device. Application auth provides read-access to all Users who h...
Set credentials for Application authentication. Important Note: Do not use Application auth on any end-user device. Application auth provides read-access to all Users who have authorized an Application. Use on a secure application server only. Args: api_token (str): Token issu...
def create_server(self, loop=None, as_coroutine=False, protocol_factory=None, **server_config): """ Helper function which constructs a listening server, using the default growler.http.protocol.Protocol which ...
Helper function which constructs a listening server, using the default growler.http.protocol.Protocol which responds to this app. This function exists only to remove boilerplate code for starting up a growler app when using asyncio. Args: as_coroutine (bool): If Tru...
def properties(obj, type=None, set=None): ''' List properties for given btrfs object. The object can be path of BTRFS device, mount point, or any directories/files inside the BTRFS filesystem. General options: * **type**: Possible types are s[ubvol], f[ilesystem], i[node] and d[evice]. * **for...
List properties for given btrfs object. The object can be path of BTRFS device, mount point, or any directories/files inside the BTRFS filesystem. General options: * **type**: Possible types are s[ubvol], f[ilesystem], i[node] and d[evice]. * **force**: Force overwrite existing filesystem on the disk ...
def create(self, name, img_format=None, data=None, container=None, obj=None, metadata=None): """ Creates a new image with the specified name. The image data can either be supplied directly in the 'data' parameter, or it can be an image stored in the object storage service. In...
Creates a new image with the specified name. The image data can either be supplied directly in the 'data' parameter, or it can be an image stored in the object storage service. In the case of the latter, you can either supply the container and object names, or simply a StorageObject refe...
def default_instance(): """ For use like a singleton, return the existing instance of the object or a new instance """ if ConfigManager._instance is None: with threading.Lock(): if ConfigManager._instance is None: ConfigManager._ins...
For use like a singleton, return the existing instance of the object or a new instance
def remote_log_data_block_encode(self, target_system, target_component, seqno, data): ''' Send a block of log data to remote location target_system : System ID (uint8_t) target_component : Component ID (uint8_t) seqno ...
Send a block of log data to remote location target_system : System ID (uint8_t) target_component : Component ID (uint8_t) seqno : log data block sequence number (uint32_t) data : log data block...
def dict_to_object(self, obj): # pylint: disable=no-self-use """Return object from dict.""" if not isinstance(obj, dict): return obj if 'sensor_id' in obj: sensor = Sensor(obj['sensor_id']) for key, val in obj.items(): setattr(sensor, key, val...
Return object from dict.
def _get_generators(self): """Get installed banana plugins. :return: dictionary of installed generators name: distribution """ # on using entrypoints: # http://stackoverflow.com/questions/774824/explain-python-entry-points # TODO: make sure we do not have conflicting gen...
Get installed banana plugins. :return: dictionary of installed generators name: distribution
def kill(self): """Kill the child.""" self.process.kill() self.set_status(self.S_ERROR, "status set to Error by task.kill") self._returncode = self.process.returncode
Kill the child.
def _manage_args(parser, args): """ Checks and validate provided input """ for item in data.CONFIGURABLE_OPTIONS: action = parser._option_string_actions[item] choices = default = '' input_value = getattr(args, action.dest) new_val = None # cannot count this until...
Checks and validate provided input
def patterson_f3(acc, aca, acb): """Unbiased estimator for F3(C; A, B), the three-population test for admixture in population C. Parameters ---------- acc : array_like, int, shape (n_variants, 2) Allele counts for the test population (C). aca : array_like, int, shape (n_variants, 2) ...
Unbiased estimator for F3(C; A, B), the three-population test for admixture in population C. Parameters ---------- acc : array_like, int, shape (n_variants, 2) Allele counts for the test population (C). aca : array_like, int, shape (n_variants, 2) Allele counts for the first source ...