text
stringlengths
81
112k
Inserts a horizontal (commented) line tot the generated code. def _write_separator(self): """ Inserts a horizontal (commented) line tot the generated code. """ tmp = self._page_width - ((4 * self.__indent_level) + 2) self._write_line('# ' + ('-' * tmp))
Returns a complete wrapper method. :param dict[str,*] routine: The routine metadata. :rtype: str def write_routine_method(self, routine): """ Returns a complete wrapper method. :param dict[str,*] routine: The routine metadata. :rtype: str """ if self....
Writes the parameters part of the docstring for the wrapper method of a stored routine. :param dict routine: The metadata of the stored routine. def _write_docstring_parameters(self, routine): """ Writes the parameters part of the docstring for the wrapper method of a stored routine. ...
Writes the return type part of the docstring for the wrapper method of a stored routine. def __write_docstring_return_type(self): """ Writes the return type part of the docstring for the wrapper method of a stored routine. """ rtype = self._get_docstring_return_type() if rtype: ...
Writes the docstring for the wrapper method of a stored routine. :param dict routine: The metadata of the stored routine. def __write_docstring(self, routine): """ Writes the docstring for the wrapper method of a stored routine. :param dict routine: The metadata of the stored routine....
Returns code for the parameters of the wrapper method for the stored routine. :param dict[str,*] routine: The routine metadata. :rtype: str def _get_wrapper_args(routine): """ Returns code for the parameters of the wrapper method for the stored routine. :param dict[str,*] rou...
Generate ld-relay.conf file. Given a list of environments of a project, this will generate a ``ld-relay.conf`` file in the current working directory. The conf file follows the specification that is documented in the main `ld-relay`_ documentation. .. _ld-relay: https://github.c...
Loads dynamically the class that acts like a namespace for constants. def __load(self): """ Loads dynamically the class that acts like a namespace for constants. """ parts = self.__class_name.split('.') module_name = ".".join(parts[:-1]) module = __import__(module_name) ...
Gets the constants from the class that acts like a namespace for constants. :rtype: dict<str,*> def constants(self): """ Gets the constants from the class that acts like a namespace for constants. :rtype: dict<str,*> """ ret = {} name = self.__class_name.split...
Extracts the following info from the source of the module with the class that acts like a namespace for constants: * Start line with constants * Last line with constants * Indent for constants :param list[str] lines: The source of the module with the class that acts like a names...
Returns the source of the module with the class that acts like a namespace for constants with new constants. :param dict[str,int] constants: The new constants. :rtype: str def source_with_constants(self, constants): """ Returns the source of the module with the class that acts like a ...
return the full path for the user configuration file. If doesn't exist, create it for the user. def get_configfile_user(): '''return the full path for the user configuration file. If doesn't exist, create it for the user. ''' from helpme.defaults import HELPME_CLIENT_SECRETS # The inital...
remove a setting from the global config def _remove_setting(section, name, configfile, save=False): '''remove a setting from the global config ''' removed = False config = _load_config(configfile) if section in config: if name.lower() in config[section]: removed = config.remove_...
remove a setting from the global config def remove_setting(self, section, name, save=False): '''remove a setting from the global config ''' configfile = get_configfile() return _remove_setting(section, name, configfile, save)
remove a setting from the user config def remove_user_setting(self, section, name, save=False): '''remove a setting from the user config ''' configfile = get_configfile_user() return _remove_setting(section, name, configfile, save)
general function to load and return a configuration given a helper name. This function is used for both the user config and global help me config files. def _load_config(configfile, section=None): '''general function to load and return a configuration given a helper name. This function is used...
load a tuple of environment variables, to add to the user settings Example: items = [('HELPME_DISCOURSE_BOARD', 'user_prompt_board'), ('HELPME_DISCOURSE_CATEGORY', 'user_prompt_category')] # Note that it's added to the client with an underscore: self._load_envars...
return a setting from the environment (first priority) and then secrets (second priority) if one can be found. If not, return None. Parameters ========== section: the section in the config, defaults to self.name name: they key (index) of the setting to look up default: (option...
get all settings for a client, if defined in config. def get_settings(self): '''get all settings for a client, if defined in config. ''' config = self._load_config_user() if self.name in config: return config[self.name]
update client secrets will update the data structure for a particular authentication. This should only be used for a (quasi permanent) token or similar. The secrets file, if found, is updated and saved by default. Parameters ========== helper: the name of the helper to look up in the...
Look for a setting in the environment (first priority) and then the settings file (second). If something is found, the settings file is updated. The order of operations works as follows: 1. The user config file is used as a cache for the variable 2. the environment variable always takes pri...
Run commands in a plain django environment :param app: application :param argv: arguments (default to sys.argv) :param extra_args: list of extra arguments def run(app, argv=sys.argv, extra_args=None): """ Run commands in a plain django environment :param app: application :param argv: argu...
Run commands in a django cMS environment :param app: application :param argv: arguments (default to sys.argv) :param extra_args: list of extra arguments def cms(app, argv=sys.argv, extra_args=None): """ Run commands in a django cMS environment :param app: application :param argv: argument...
Setup the Django / django CMS environment and return the environment settings. :param app: application :param helper_module: helper module :param extra_args: list of extra arguments :param use_cms: setup a django CMS environemtn :return: Django settings module def setup(app, helper_module, extra_a...
Returns a cleaned lxml ElementTree :returns: Whether the cleaned HTML has matches or not :rtype: bool def parse(self): """ Returns a cleaned lxml ElementTree :returns: Whether the cleaned HTML has matches or not :rtype: bool """ # Create the element tre...
Converts relative links from html contents to absolute links def rel_to_abs(self, base_url): """ Converts relative links from html contents to absolute links """ # Delete target attributes strip_attributes(self.tree, 'target') # Absolute links self.tree.rewrite_...
Returns the list of HtmlElements for the source :param source: The source list to parse :type source: list :returns: A list of HtmlElements :rtype: list def _get_elements(self, source): """ Returns the list of HtmlElements for the source :param source: The sour...
Parses an Element recursively :param elt: HtmlElement to parse :type elt: lxml.html.HtmlElement :param parent_is_keep: Whether the element is inside a keep element or not :type parent_is_keep: bool def _parse_element(self, elt, parent_is_keep=False): """ Parses an Eleme...
Returns whether the element has a descendant to keep or not :param elt: The HtmlElement to check :type elt: lxml.html.HtmlElement :returns: True if the element has a keep element in its descendants :rtype: bool def _has_keep_elt_in_descendants(self, elt): """ Returns wh...
Removes flagged elements from the ElementTree def _remove_elements(self, elts_to_remove): """ Removes flagged elements from the ElementTree """ for e in elts_to_remove: # Get the element parent parent = e.getparent() # lxml also remove the element t...
Execute GetInfo action to get information's about the System on the device. :return: information's about the System on the device. :rtype: SystemInfo def getSystemInfo(self, timeout=1): """Execute GetInfo action to get information's about the System on the device. :return: information...
Reboot the device def reboot(self, timeout=1): """Reboot the device""" namespace = System.getServiceType("reboot") uri = self.getControlURL(namespace) self.execute(uri, namespace, "Reboot", timeout=timeout)
Execute GetInfo action to get information's about the time on the device. :return: information's about the time on the device. :rtype: TimeInfo def getTimeInfo(self, timeout=1): """Execute GetInfo action to get information's about the time on the device. :return: information's about t...
Returns if a software update is available :return: if a software update is available :rtype: bool def softwareUpdateAvailable(self, timeout=1): """Returns if a software update is available :return: if a software update is available :rtype: bool """ namespace = ...
Make the cache control headers based on a previous request's response headers def make_headers(headers): """ Make the cache control headers based on a previous request's response headers """ out = {} if 'etag' in headers: out['if-none-match'] = headers['etag'] if 'last-modified' in ...
Get the cached object def get(self, prefix, url, schema_version=None): """ Get the cached object """ if not self.cache_dir: return None filename = self._get_cache_file(prefix, url) try: with open(filename, 'rb') as file: item = pickle.load(file)...
Add an object into the cache def set(self, prefix, url, obj): """ Add an object into the cache """ if not self.cache_dir: return filename = self._get_cache_file(prefix, url) try: os.makedirs(os.path.join(self.cache_dir, prefix)) except OSError: ...
Join input path to sample data path (usually in ~/lisa_data) :param path_to_join: one or more paths :param get_root: return dataset root path. If false, the path would be into "medical/orig" :return: joined path def join_path(*path_to_join, **kwargs): """Join input path to sample data path (usually in...
Sets path to dataset. Warning: function with side effects! :param path: path you want to store dataset :param cache: CacheFile object :param cachefile: default '~/.io3d_cache.yaml' def set_dataset_path(path, cache=None, cachefile="~/.io3d_cache.yaml"): """Sets path to dataset. Warning: function with s...
Get dataset path. :param cache: CacheFile object :param cachefile: cachefile path, default '~/.io3d_cache.yaml' :return: path to dataset def dataset_path(cache=None, cachefile="~/.io3d_cache.yaml", get_root=False): """Get dataset path. :param cache: CacheFile object :param cachefile: cachefil...
Gives you metadata for dataset chosen via 'label' param :param label: label = key in data_url dict (that big dict containing all possible datasets) :return: tuple (data_url, url, expected_hash, hash_path, relative_download_dir) relative_download_dir says where will be downloaded the file from url and event...
Returns list of possible packages contained in dataset, in case the dataset is multi dataset, eg. 'lisa'. In case the param is not pointing to multidataset returns only that label in a list. :param str dataset_label_dict: label of multi dataset :return: list of labels def _expand_dataset_packages(dataset...
Download sample data by data label. Warning: function with side effect! Labels can be listed by sample_data.data_urls.keys(). Returns downloaded files. :param dataset_label: label of data. If it is set to None, all data are downloaded :param destination_dir: output dir for data :param dry_run: runs fu...
Get the 3D data from specified dataset with specified id. Download data if necessary. :param dataset_label: :param data_id: integer or wildcards file pattern :param destination_dir: :return: def get_old(dataset_label, data_id, destination_dir=None): """Get the 3D data from specified dataset w...
Return checksum of files given by path. Wildcards can be used in check sum. Function is strongly dependent on checksumdir package by 'cakepietoast'. :param path: path of files to get hash from :param hashfunc: function used to get hash, default 'md5' :return: (str) hash of the file/files given by path...
Generate donut like shape with stick inside :return: dict {'data3d': '', 'segmentation': '', 'voxelsize_mm': ''} def generate_donut(): """Generate donut like shape with stick inside :return: dict {'data3d': '', 'segmentation': '', 'voxelsize_mm': ''} """ segmentation = np.zeros([20, 30, 40]) ...
Generate data with two sphere objects. :param sz: output data shape is [sz, sz+1, sz+2] :param offset: :param radius: :param seedsz: :param add_object_without_seeds: Add also one cube-like object in the corner. :return: def generate_round_data( sz=32, offset=0, radius=7, seedsz=3, add_objec...
Create synthetic data. There is some liver and porta -like object. :return data3d, segmentation, voxelsize_mm, slab, seeds_liver, seeds_porta: def generate_synthetic_liver(return_dataplus=False): """ Create synthetic data. There is some liver and porta -like object. :return data3d, segmentation, voxels...
Create 2D binar face :param shape: :param face_r: :param smile_r1: :param smile_r2: :param eye_r: :return: def _get_face2(shape=None, face_r=1.0, smile_r1=0.5, smile_r2=0.7, eye_r=0.2): """ Create 2D binar face :param shape: :param face_r: :param smile_r1: :param smile_r...
Create 2D or 3D binar data with smile face. :param shape: 2D or 3D shape of data :param face_r: :param smile_r1: :param smile_r2: :param eye_r: :return: binar ndarray def generate_face(shape=None, face_r=1.0, smile_r1=0.5, smile_r2=0.7, eye_r=0.2): """ Create 2D or 3D binar data with s...
Function attempts to remove file, if failure occures -> print exception :param local_file_name: name of file to remove def remove(local_file_name): """Function attempts to remove file, if failure occures -> print exception :param local_file_name: name of file to remove """ try: os.remove(...
Download, unzip and delete. Warning: function with strong side effects! Returns downloaded data. :param str url: url from which data should be donloaded :param destination: destination to which data should be downloaded def downzip(url, destination="./sample_data/"): """Download, unzip and delete. Wa...
Unzips one file and deletes it. Warning: function with side effects! :param str local_file_name: file name of zip file :return: list of archive members by name. def unzip_one(local_file_name): """Unzips one file and deletes it. Warning: function with side effects! :param str local_file_name: file nam...
Unzip file with all recursive zip files inside and delete zip files after that. :param zip_file_name: file name of zip file :return: list of archive members by name. def unzip_recursive(zip_file_name): """Unzip file with all recursive zip files inside and delete zip files after that. :param zip_file_...
a wrapper around generation of an asciinema.api.Api to call the upload command given an already existing asciinema file. Parameters ========== filename: the asciinema file to upload, can be generated with function record_asciinema in record.py def upload_asciinema(filen...
Creates TLS configuration object. def make_tls_config(app_config): """Creates TLS configuration object.""" if not app_config['DOCKER_TLS']: return False cert_path = app_config['DOCKER_TLS_CERT_PATH'] if cert_path: client_cert = '{0}:{1}'.format( os.path.join(cert_path, 'ce...
Parses the client cert pair from config item. :param config_value: the string value of config item. :returns: tuple or none. def parse_client_cert_pair(config_value): """Parses the client cert pair from config item. :param config_value: the string value of config item. :returns: tuple or none. ...
Initializes an application for using :class:`docker.Client`. :param app: an instance of :class:`~flask.Flask`. def init_app(self, app): """Initializes an application for using :class:`docker.Client`. :param app: an instance of :class:`~flask.Flask`. """ app.extensions = getatt...
The original :class:`docker.Client` object. All docker operation calling will be forwarded here. :: docker.create_container('ubuntu') docker.client.create_container('ubuntu') # equivalent def client(self): """The original :class:`docker.Client` object. All docker operation ...
process a feed async def process_feed(self, url, send_mentions=True): """ process a feed """ self._feed_domains.add(utils.get_domain(url)) if url in self._processed_feeds: LOGGER.debug("Skipping already processed feed %s", url) return self._processed_feeds.add(...
process an entry async def process_entry(self, url, add_domain=False, send_mentions=True): """ process an entry """ if add_domain: self._feed_domains.add(utils.get_domain(url)) if url in self._processed_entries: LOGGER.debug("Skipping already processed entry %s", url) ...
send a webmention from an entry to a URL async def send_webmention(self, entry, url): """ send a webmention from an entry to a URL """ if (entry.url, url) in self._processed_mentions: LOGGER.debug( "Skipping already processed mention %s -> %s", entry.url, url) self....
Compiles locale messages def compilemessages(application): """ Compiles locale messages """ from django.core.management import call_command with work_in(application): if DJANGO_1_11: call_command('compilemessages', all=True) else: call_command('compilemessag...
Updates the locale message files def makemessages(application, locale): """ Updates the locale message files """ from django.core.management import call_command if not locale: locale = 'en' with work_in(application): call_command('makemessages', locale=(locale,))
Runs the django CMS ``cms check`` command def cms_check(migrate_cmd=False): """ Runs the django CMS ``cms check`` command """ from django.core.management import call_command try: import cms # NOQA # nopyflakes _create_db(migrate_cmd) call_command('cms', 'check') except ...
Generate migrations def makemigrations(application, merge=False, dry_run=False, empty=False, extra_applications=None): """ Generate migrations """ from django.core.management import call_command apps = [application] if extra_applications: if isinstance(extra_applications, text_type): ...
Updates the authors list def generate_authors(): """ Updates the authors list """ print('Generating AUTHORS') # Get our list of authors print('Collecting author names') r = subprocess.Popen(['git', 'log', '--use-mailmap', '--format=%aN'], stdout=subprocess.PIPE) ...
Performs a pyflakes static analysis with the same configuration as django CMS testsuite def static_analisys(application): """ Performs a pyflakes static analysis with the same configuration as django CMS testsuite """ try: from cms.test_utils.util.static_analysis import pyflakes ...
Initial parse setup. Call at start of `self.parse()`. def setup_parse(self, inputstring, document): """Initial parse setup. Call at start of `self.parse()`.""" self.inputstring = inputstring self.document = document
Make sure the package version in setuptools matches what we expect it to be def check_version(expected_version): """ Make sure the package version in setuptools matches what we expect it to be """ with open(os.path.join(root_folder, 'VERSION'), 'r') as version_file: version = version_file.read().strip...
Create a wheel def build_wheel(platform): """Create a wheel""" if platform in ['x86_64', 'i686']: system = 'manylinux1' else: system = 'linux' setuptools.sandbox.run_setup( 'setup.py', ['-q', 'clean', '--all', 'bdist_wheel', '--plat-name', '{}_{}'.format(system, platfo...
Upload a given component to pypi The pypi username and password must either be specified in a ~/.pypirc file or in environment variables PYPI_USER and PYPI_PASS def upload(dist_dir): """Upload a given component to pypi The pypi username and password must either be specified in a ~/.pypirc file or i...
``Deprecated``: Not better than ``fire`` -> pip install fire def simple_cmd(): """ ``Deprecated``: Not better than ``fire`` -> pip install fire """ parser = argparse.ArgumentParser( prog="Simple command-line function toolkit.", description="""Input function name and args and kwargs. ...
Show the proc-mem-cost with psutil, use this only for lazinesssss. :param unit: B, KB, MB, GB. def print_mem(unit="MB"): """Show the proc-mem-cost with psutil, use this only for lazinesssss. :param unit: B, KB, MB, GB. """ try: import psutil B = float(psutil.Process(os.getpid())....
Translate curl-string into dict of request. :param string: standard curl-string, like `r'''curl ...'''`. :param encoding: encoding for post-data encoding. Basic Usage:: >>> from torequests.utils import curlparse >>> curl_string = '''curl 'https://p.3.cn?skuIds=1&nonsense=1&nonce=0' -H ...
Slice a sequence into `n` pieces, return a generation of n pieces def slice_into_pieces(seq, n): """Slice a sequence into `n` pieces, return a generation of n pieces""" length = len(seq) if length % n == 0: size = length // n else: size = length // n + 1 for it in slice_by_size(seq,...
Slice a sequence into chunks, return as a generation of chunks with `size`. def slice_by_size(seq, size): """Slice a sequence into chunks, return as a generation of chunks with `size`.""" filling = null for it in zip(*(itertools_chain(seq, [filling] * size),) * size): if filling in it: ...
Translate timestamp into human-readable: %Y-%m-%d %H:%M:%S. :param timestamp: the timestamp float, or `time.time()` by default. :param tzone: time compensation, int(-time.timezone / 3600) by default, (can be set with Config.TIMEZONE). :param fail: while raising an exception, return it. ...
Translate %Y-%m-%d %H:%M:%S into timestamp. :param timestr: string like 2018-03-15 01:27:56, or time.time() if not set. :param tzone: time compensation, int(-time.timezone / 3600) by default, (can be set with Config.TIMEZONE). :param fail: while raising an exception, return it. :param f...
Split seconds into [day, hour, minute, second, ms] `divisor: 1, 24, 60, 60, 1000` `units: day, hour, minute, second, ms` >>> split_seconds(6666666) [77, 3, 51, 6, 0] def split_seconds(seconds): """Split seconds into [day, hour, minute, second, ms] `divisor: 1, 24, 60, 60, 1000` ...
Translate seconds into human-readable. :param seconds: seconds (float/int). :param accuracy: 4 by default (units[:accuracy]), determine the length of elements. :param format: index of [led, literal, dict]. :param lang: en or cn. :param units: day, hour, minute, second, ms. ...
str(obj) -> md5_string :param string: string to operate. :param n: md5_str length. >>> from torequests.utils import md5 >>> md5(1, 10) '923820dcc5' >>> md5('test') '098f6bcd4621d373cade4e832627b4f6' def md5(string, n=32, encoding="utf-8", skip_encode=False): """str(obj) -> md5_string ...
Unique the seq and keep the order. Instead of the slow way: `lambda seq: (x for index, x in enumerate(seq) if seq.index(x)==index)` :param seq: raw sequence. :param return_as: generator for default, or list / set / str... >>> from torequests.utils import unique >>> a = [1,2,3,4,2,3,4] ...
Reverse conversion for parse_qs def unparse_qs(qs, sort=False, reverse=False): """Reverse conversion for parse_qs""" result = [] items = qs.items() if sort: items = sorted(items, key=lambda x: x[0], reverse=reverse) for keys, values in items: query_name = quote(keys) for val...
Reverse conversion for parse_qsl def unparse_qsl(qsl, sort=False, reverse=False): """Reverse conversion for parse_qsl""" result = [] items = qsl if sort: items = sorted(items, key=lambda x: x[0], reverse=reverse) for keys, values in items: query_name = quote(keys) result.app...
Kill self after seconds def kill_after(seconds, timeout=2): """Kill self after seconds""" pid = os.getpid() kill = os.kill run_after_async(seconds, kill, pid, signal.SIGTERM) run_after_async(seconds + timeout, kill, pid, 9)
Try import module_name, except ImportError and return default, sometimes to be used for catch ImportError and lazy-import. def try_import(module_name, names=None, default=ImportErrorModule, warn=True): """Try import module_name, except ImportError and return default, sometimes to be used for catch ...
Used for requests.request / Requests.request with **ensure_request(request) :param request: dict or curl-string or url >>> from torequests.utils import ensure_request >>> ensure_request('''curl http://test.com''') {'url': 'http://test.com', 'method': 'get'} >>> ensure_request('http://test.com') ...
Set the dict key as key.title(); keys should be str. Always be used to headers. >>> from torequests.utils import ensure_dict_key_title >>> ensure_dict_key_title({'hello-world':1, 'HELLOWORLD':2}) {'Hello-World': 1, 'Helloworld': 2} def ensure_dict_key_title(dict_obj): """Set the dict k...
Given a seq of number, return the median, only calculate interval >= accuracy. :: from torequests.utils import guess_interval import random seq = [random.randint(1, 100) for i in range(20)] print(guess_interval(seq, 5)) # sorted_seq: [2, 10, 12, 19, 19, 29, 30, 32, 38, 40,...
r"""Split strings into n-dimensional list. :: from torequests.utils import split_n ss = '''a b c d e f 1 2 3 4 5 6 a b c d e f 1 2 3 4 5 6 a b c d e f 1 2 3 4 5 6''' print(split_n(ss, ('\n', ' ', ' '))) # [[['a', 'b', 'c'], ['d', 'e', 'f'], ['1', '2', '3...
Run a function in background, will not block main thread's exit.(thread.daemon=True) :: from torequests.utils import bg, print_info import time def test1(n): time.sleep(n) print_info(n, 'done') @bg def test2(n): time.sleep(n) ...
Run a countdown function to wait something, similar to threading.Timer, but will show the detail tick by tick_callback. :: from torequests.utils import countdown countdown(3) # 3 2 1 # countdown finished [3 seconds]: 2018-06-13 00:12:55 => 2018-06-13 00:12:58. countd...
Like print_function at python3, support flush, but not support file. :param sep: space by default :param end: '\\n' by default :param flush: True by default :: import time from torequests.utils import flush_print flush_print("=" * 10) for _ in range(10): t...
Use tPool to request for curl string. If kwargs contains the req which hasattr request method, like req=requests. :param curl_string: standard curl string. :type curl_string: str :param kwargs: valid kwargs for tPool. :type curl_string: dict Basic Usage:: from torequests.utils import ...
Register one object which can be matched/searched by regex. :param patterns: a list/tuple/set of regex-pattern. :param obj: return it while search/match success. :param instances: instance list will search/match the patterns. :param reg_kwargs: kwargs for re.compile. def register(self,...
Decorator for register. def register_function(self, patterns, instances=None, **reg_kwargs): """Decorator for register.""" def wrapper(function): self.register(patterns, function, instances=instances, **reg_kwargs) return function return wrapper
Return match or search result. :rtype: list def find(self, string, default=None): """Return match or search result. :rtype: list""" return self.match(string) or self.search(string) or default
Use re.search to find the result :rtype: list def search(self, string, default=None): """Use re.search to find the result :rtype: list""" default = default if default else [] result = [item[1] for item in self.container if item[0].search(string)] if self.ensure_mapping...
Give suggestion from all instances. def fuzzy(self, key, limit=5): """Give suggestion from all instances.""" instances = [i[2] for i in self.container if i[2]] if not instances: return instances = sum(instances, []) from fuzzywuzzy import process maybe = pro...