text
stringlengths
81
112k
Calls `find_executable` from distuils for provided candidates and returns first hit. If no candidate mathces, a RuntimeError is raised def find_binary_of_command(candidates): """ Calls `find_executable` from distuils for provided candidates and returns first hit. If no candidate mathces, a Runt...
Inspect a Cython source file (.pyx) and look for comment line like: # distutils: language = c++ Returns True if such a file is present in the file, else False. def pyx_is_cplus(path): """ Inspect a Cython source file (.pyx) and look for comment line like: # distutils: language = c++ Returns...
Uniquify a list (skip duplicate items). def uniquify(l): """ Uniquify a list (skip duplicate items). """ result = [] for x in l: if x not in result: result.append(x) return result
Get value of key in metadata file dict. def get_from_metadata_file(cls, dirpath, key): """ Get value of key in metadata file dict. """ fullpath = os.path.join(dirpath, cls.metadata_filename) if os.path.exists(fullpath): d = pickle.load(open(fullpath, 'rb')) ...
Store `key: value` in metadata file dict. def save_to_metadata_file(cls, dirpath, key, value): """ Store `key: value` in metadata file dict. """ fullpath = os.path.join(dirpath, cls.metadata_filename) if os.path.exists(fullpath): d = pickle.load(open(fullpath, 'rb'))...
return a view of the plugin minimal class attribute interface(s) Parameters ---------- category : None or str if str, apply for single plugin category Examples -------- >>> from pprint import pprint >>> pprint(view_interfaces()) {'decoders': ['plugin_name', 'plugin_descript', ...
return a view of the loaded plugin names and descriptions Parameters ---------- category : None or str if str, apply for single plugin category Examples -------- >>> from pprint import pprint >>> pprint(view_plugins()) {'decoders': {}, 'encoders': {}, 'parsers': {}} >>> c...
remove single plugin Parameters ---------- name : str plugin name category : str plugin category Examples -------- >>> from pprint import pprint >>> pprint(view_plugins()) {'decoders': {}, 'encoders': {}, 'parsers': {}} >>> class DecoderPlugin(object): ......
load plugins from class objects Parameters ---------- classes: list list of classes category : None or str if str, apply for single plugin category overwrite : bool if True, allow existing plugins to be overwritten Examples -------- >>> from pprint import pprin...
context manager to load plugin class(es) then unload on exit Parameters ---------- classes: list list of classes category : None or str if str, apply for single plugin category Examples -------- >>> from pprint import pprint >>> class DecoderPlugin(object): ... ...
load plugins from a directory Parameters ---------- path : str or path_like category : None or str if str, apply for single plugin category overwrite : bool if True, allow existing plugins to be overwritten def load_plugins_dir(path, category=None, overwrite=False): """ load pl...
load plugins from builtin directories Parameters ---------- name: None or str category : None or str if str, apply for single plugin category Examples -------- >>> from pprint import pprint >>> pprint(view_plugins()) {'decoders': {}, 'encoders': {}, 'parsers': {}} >>>...
encode objects, via encoder plugins, to new types Parameters ---------- outtype: str use encoder method to_<outtype> to encode raise_error : bool if True, raise ValueError if no suitable plugin found Examples -------- >>> load_builtin_plugins('encoders') [] >>> fro...
decode dict objects, via decoder plugins, to new type Parameters ---------- intype: str use decoder method from_<intype> to encode raise_error : bool if True, raise ValueError if no suitable plugin found Examples -------- >>> load_builtin_plugins('decoders') [] >>>...
test if parser plugin available for fpath Examples -------- >>> load_builtin_plugins('parsers') [] >>> test_file = StringIO('{"a":[1,2,3.4]}') >>> test_file.name = 'test.json' >>> parser_available(test_file) True >>> test_file.name = 'test.other' >>> parser_available(test_file)...
parse file contents, via parser plugins, to dict like object NB: the longest file regex will be used from plugins Parameters ---------- fpath : file_like string, object with 'open' and 'name' attributes, or object with 'readline' and 'name' attributes kwargs : to pass to p...
Colorize text. Available text colors: red, green, yellow, blue, magenta, cyan, white. Available text highlights: on_red, on_green, on_yellow, on_blue, on_magenta, on_cyan, on_white. Available attributes: bold, dark, underline, blink, reverse, concealed. Examples -------- ...
Read delimited text from zipfile. def from_zipfile(cls, path, filename, encoding, dialect, fields, converters): """Read delimited text from zipfile.""" stream = ZipReader(path, filename).readlines(encoding) return cls(stream, dialect, fields, converters)
Read delimited text from a text file. def from_file(cls, path, encoding, dialect, fields, converters, field_index): """Read delimited text from a text file.""" return cls(open(path, 'r', encoding=encoding), dialect, fields, converters, field_index)
Read content into byte string. def read_bytes(self): """Read content into byte string.""" with ZipFile(self.path, mode='r') as archive: return archive.read(self.filename)
Read content into byte str line iterator. def readlines_bytes(self): """Read content into byte str line iterator.""" with open_zipfile_archive(self.path, self.filename) as file: for line in file: yield line.rstrip(b'\r\n')
Parse a XML file :param file: Opened File :return: Tree def xmlparse(self, file): """ Parse a XML file :param file: Opened File :return: Tree """ if self.CACHE_FULL_TEI is True: return self.get_or( _cache_key("Nautilus", self.name, "...
Get or set the cache using callback and arguments :param cache_key: Cache key for given resource :param callback: Callback if object does not exist :param args: Ordered Argument for the callback :param kwargs: Keyword argument for the callback :return: Output of the callback de...
Read a text object given an identifier and a path :param identifier: Identifier of the text :param path: Path of the text files :return: Text def read(self, identifier, path=None): """ Read a text object given an identifier and a path :param identifier: Identifier of the text ...
Parse a list of directories ans :param resource: List of folders def parse(self, resource=None): """ Parse a list of directories ans :param resource: List of folders """ if resource is None: resource = self.__resources__ self.inventory = self.dispatcher.co...
Retrieve the siblings of a textual node :param textId: PrototypeText Identifier :type textId: str :param level: Depth for retrieval :type level: int :param subreference: Passage Reference :type subreference: str :return: List of references :rtype: [str] ...
Retrieve a text node from the API :param textId: PrototypeText Identifier :type textId: str :param subreference: Passage Reference :type subreference: str :param prevnext: Retrieve graph representing previous and next passage :type prevnext: boolean :param metada...
Retrieve the siblings of a textual node :param textId: PrototypeText Identifier :type textId: str :param subreference: Passage Reference :type subreference: str :return: Tuple of references :rtype: (str, str) def getSiblings(self, textId, subreference): """ Retr...
Request metadata about a text or a collection :param objectId: Object Identifier to filter on :type objectId: str :param filters: Kwargs parameters. :type filters: dict :return: Collection def getMetadata(self, objectId=None, **filters): """ Request metadata about a tex...
Sparql dispatcher do not need to dispatch works, as the link is DB stored through Textgroup :param textgroup: A Textgroup object :param directory: The path in which we found the textgroup :return: def _dispatch(self, textgroup, directory): """ Sparql dispatcher do not need to dispatch ...
Ask for user input. This asks a yes/no question with a preset default. You can bypass the user-input and fetch the default answer, if you set Args: question: The question to ask on stdout. default_answer: The default value to return. default_answer_str: The default ...
Load CSV file from path and yield CSV rows Usage: for row in load_csv('/path/to/file'): print(row) or list(load_csv('/path/to/file')) :param path: file path :param delimiter: CSV delimiter :return: a generator where __next__ is a row of the CSV def load_csv(path, delimiter=','): ...
Load JSON file from path :param path: file path :return: A Python object (e.g. a dict) def load_json(path): """ Load JSON file from path :param path: file path :return: A Python object (e.g. a dict) """ try: with open(path, 'r') as json_file: return json.load(json_fi...
Yield partitions of a payload e.g. with a threshold of 2: { "dataElements": [1, 2, 3] } --> { "dataElements": [1, 2] } and { "dataElements": [3] } :param data: the payload :param key: the key of the dict to partition :param thresh: the maximum value of a chunk :return: a ge...
Search filename in - A) DHIS_HOME (env variable) - B) current user's home folder :param filename: the filename to search for :return: full path of filename def search_auth_file(filename='dish.json'): """ Search filename in - A) DHIS_HOME (env variable) - B) current user's home folder ...
Convert version info to integer :param value: the version received from system/info, e.g. "2.28" :return: integer from version, e.g. 28, None if it couldn't be parsed def version_to_int(value): """ Convert version info to integer :param value: the version received from system/info, e.g. "2.28" ...
Create DHIS2 UID matching to Regex ^[A-Za-z][A-Za-z0-9]{10}$ :return: UID string def generate_uid(): """ Create DHIS2 UID matching to Regex ^[A-Za-z][A-Za-z0-9]{10}$ :return: UID string """ # first must be a letter first = random.choice(string.ascii_letters) # rest must be lette...
:return: True if it is a valid DHIS2 UID, False if not def is_valid_uid(uid): """ :return: True if it is a valid DHIS2 UID, False if not """ pattern = r'^[A-Za-z][A-Za-z0-9]{10}$' if not isinstance(uid, string_types): return False return bool(re.compile(pattern).match(uid))
Print JSON with indentation and colours :param obj: the object to print - can be a dict or a string def pretty_json(obj): """ Print JSON with indentation and colours :param obj: the object to print - can be a dict or a string """ if isinstance(obj, string_types): try: obj = ...
Recursively remove keys from list/dict/dict-of-lists/list-of-keys/nested ..., e.g. remove all sharing keys or remove all 'user' fields This should result in the same as if running in bash: `jq del(.. | .publicAccess?, .userGroupAccesses?)` :param obj: the dict to remove keys from :param remove: keys to...
Get all commands of the benchmark category :return generator of string def commands(self): """Get all commands of the benchmark category :return generator of string """ for child in self._children: with open(osp.join(child, YAML_REPORT_FILE)) as istr: ...
Set current process environment according to execution `environment` and `modules` def _module_env(self, execution): """Set current process environment according to execution `environment` and `modules` """ env = copy.copy(os.environ) try: for mod in executio...
Write a JSON file with the result of every runs def gather_metrics(self, runs): """Write a JSON file with the result of every runs """ for run_dirs in runs.values(): with open(JSON_METRICS_FILE, 'w') as ostr: ostr.write('[\n') for i in range(len(run_d...
Ensure that returned metrics are properly exposed def _check_metrics(cls, schema, metrics): """Ensure that returned metrics are properly exposed """ for name, value in metrics.items(): metric = schema.get(name) if not metric: message = "Unexpected metric ...
A generic function to load object parameters based on a dictionary list. :param obj: Object :param values: Dictionary :return: def add_inputs_to_object(obj, values): """ A generic function to load object parameters based on a dictionary list. :param obj: Object :param values: Dictionary ...
Sample data for the SoilStructureSystem object :param sss: :return: def load_sample_data(sss): """ Sample data for the SoilStructureSystem object :param sss: :return: """ load_soil_sample_data(sss.sp) # soil load_foundation_sample_data(sss.fd) # foundation load_structure_samp...
Sample data for the Soil object :param sp: Soil Object :return: def load_soil_sample_data(sp): """ Sample data for the Soil object :param sp: Soil Object :return: """ # soil sp.g_mod = 60.0e6 # [Pa] sp.phi = 30 # [degrees] sp.relative_density = .40 # [decimal] sp.gwl ...
Sample data for the Foundation object :param fd: Foundation Object :return: def load_foundation_sample_data(fd): """ Sample data for the Foundation object :param fd: Foundation Object :return: """ # foundation fd.width = 16.0 # m fd.length = 18.0 # m fd.depth = 0.0 # m ...
Sample data for the Structure object :param st: Structure Object :return: def load_structure_sample_data(st): """ Sample data for the Structure object :param st: Structure Object :return: """ # structure st.h_eff = 9.0 # m st.mass_eff = 120e3 # kg st.t_eff = 1.0 # s s...
Sample data for the Hazard object :param hz: Hazard Object :return: def load_hazard_sample_data(hz): """ Sample data for the Hazard object :param hz: Hazard Object :return: """ # hazard hz.z_factor = 0.3 # Hazard factor hz.r_factor = 1.0 # Return period factor hz.n_factor ...
Sample data for the Building object :param bd: :return: def load_building_sample_data(bd): """ Sample data for the Building object :param bd: :return: """ number_of_storeys = 6 interstorey_height = 3.4 # m masses = 40.0e3 # kg bd.interstorey_heights = interstorey_height *...
Sample data for the BuildingFrame object :return: def load_frame_building_sample_data(): """ Sample data for the BuildingFrame object :return: """ number_of_storeys = 6 interstorey_height = 3.4 # m masses = 40.0e3 # kg n_bays = 3 fb = models.BuildingFrame(number_of_storeys,...
生成随机的原始指纹列表 def _get_random_fp_raw(): ''' 生成随机的原始指纹列表 ''' fp_list = [] fp_list.append(get_random_ua()) # ua fp_list.append('zh-CN') # language fp_list.append('24') # color depth fp_list.append(__get_random_screen_resolution()) fp_list.append('-480') # time zone offsite f...
生成fp_raw_str def get_fp_raw(): ''' 生成fp_raw_str ''' fp_file_path = os.path.expanduser('~/.xunleipy_fp') fp_list = [] try: with open(fp_file_path, 'r') as fp_file: fp_str = fp_file.readline() if len(fp_str) > 0: fp_list = fp_str.split('###') ...
Define functions composition like f ∘ g ∘ h :return: callable object that will perform function composition of callables given in argument. def compose(*functions): """Define functions composition like f ∘ g ∘ h :return: callable object that will perform function composition of callables given in a...
Split an iterator into chunks with `size` elements each. Warning: ``size`` must be an actual iterator, if you pass this a concrete sequence will get you repeating elements. So ``chunks(iter(range(1000)), 10)`` is fine, but ``chunks(range(1000), 10)`` is not. Example: # si...
A decorator which wraps a function's return value in ``list(...)``. Useful when an algorithm can be expressed more cleanly as a generator but the function should return an list. Example:: >>> @listify ... def get_lengths(iterable): ... for i in iterable: ... yield...
Yield the sub-group element dictionary that match a regex pattern. def match_subgroup(sequence, pattern): """Yield the sub-group element dictionary that match a regex pattern.""" for element in sequence: match = re.match(pattern, element) if match: yield match.groupdict()
Decorator for adding regex pattern start and end characters. def add_regex_start_end(pattern_function): """Decorator for adding regex pattern start and end characters.""" @wraps(pattern_function) def func_wrapper(*args, **kwargs): return r'^{}$'.format(pattern_function(*args, **kwargs)) return...
Converts a foundation stress to an equivalent mass. :param q: applied stress [Pa] :param width: foundation width [m] :param length: foundation length [m] :param gravity: applied gravitational acceleration [m/s2] :return: def convert_stress_to_mass(q, width, length, gravity): """ Converts a...
Cycles through a dictionary and adds the key-value pairs to an object. :param obj: :param dictionary: :param exceptions: :param verbose: :return: def add_to_obj(obj, dictionary, objs=None, exceptions=None, verbose=0): """ Cycles through a dictionary and adds the key-value pairs to an objec...
Create quantile start and end boundaries. def create_quantiles(items: Sequence, lower_bound, upper_bound): """Create quantile start and end boundaries.""" interval = (upper_bound - lower_bound) / len(items) quantiles = ((g, (x - interval, x)) for g, x in zip(items, accumulate(repeat(inte...
Cast a single element to a tuple. def tupleize(element, ignore_types=(str, bytes)): """Cast a single element to a tuple.""" if hasattr(element, '__iter__') and not isinstance(element, ignore_types): return element else: return tuple((element,))
Create dictionaries mapping fields to record data. def dictionize(fields: Sequence, records: Sequence) -> Generator: """Create dictionaries mapping fields to record data.""" return (dict(zip(fields, rec)) for rec in records)
Transform dictionary to unpack values to map to respective key. def flip_iterable_dict(d: dict) -> dict: """Transform dictionary to unpack values to map to respective key.""" value_keys = disjoint_union((cartesian_product((v, k)) for k, v in d.items())) return dict(value_k...
Return area of a simple (ie. non-self-intersecting) polygon. If verts wind anti-clockwise, this returns a negative number. Assume y-axis points up. def get_signed_area(self): """ Return area of a simple (ie. non-self-intersecting) polygon. If verts wind anti-clockwise, this retu...
Call all child extensions with the given arguments. This calls all child extensions and collects the results for our own parent. Use this to control the execution of your nested extensions from your own extension. Returns: :obj:`list` of :obj:`RunInfo`: A list of collected ...
Print a structural view of the registered extensions. def print(self, indent=0): """Print a structural view of the registered extensions.""" LOG.info("%s:: %s", indent * " ", self.__class__) for ext in self.next_extensions: ext.print(indent=indent + 2)
:param matches: a list of tuples. def print_results(matches): """ :param matches: a list of tuples. """ output = "" for n, match in enumerate(matches): matched_text = match[0][:40]+"..." if len(match[0]) > 40 else match[0] search_result = match[1] if search_result.uri==surf....
TODO def show_result(resource, verbose=False): """ TODO """ if resource.uri == surf.ns.EFRBROO['F10_Person']: print("\n{} ({})\n".format(unicode(resource), resource.get_urn())) works = resource.get_works() print("Works by {} ({}):\n".format(resource, len(works))) [show_r...
Define the CLI inteface/commands. def main(): """Define the CLI inteface/commands.""" arguments = docopt(__doc__) cfg_filename = pkg_resources.resource_filename( 'knowledge_base', 'config/virtuoso.ini' ) kb = KnowledgeBase(cfg_filename) # the user has issued a `find` command ...
Memoize a function result. def cached(func): """Memoize a function result.""" ret = None def call_or_cache(*args, **kwargs): nonlocal ret if ret is None: ret = func(*args, **kwargs) return ret return call_or_cache
Checks if a container exists and is unpacked. Args: path: The location where the container is expected. Returns: True if the container is valid, False if the container needs to unpacked or if the path does not exist yet. def is_valid(container, path): """ Checks if a container...
Unpack a container usable by uchroot. Method that checks if a directory for the container exists, checks if erlent support is needed and then unpacks the container accordingly. Args: path: The location where the container is, that needs to be unpacked. def unpack(container, path): """ ...
Finds the current location of a container. Also unpacks the project if necessary. Returns: target: The path, where the container lies in the end. def local(self): """ Finds the current location of a container. Also unpacks the project if necessary. Returns:...
Get the latest src_uri for a stage 3 tarball. Returns (str): Latest src_uri from gentoo's distfiles mirror. def src_file(self): """ Get the latest src_uri for a stage 3 tarball. Returns (str): Latest src_uri from gentoo's distfiles mirror. """ t...
Return the build date of the gentoo container. def version(self): """Return the build date of the gentoo container.""" try: _version = (curl[Gentoo._LATEST_TXT] | \ awk['NR==2{print}'] | \ cut["-f2", "-d="])().strip() _version = datetime.u...
ben-csv entry point def main(argv=None): """ben-csv entry point""" arguments = cli_common(__doc__, argv=argv) csv_export = CSVExporter(arguments['CAMPAIGN-DIR'], arguments['--output']) if arguments['--peek']: csv_export.peek() else: fieldsstr = arguments.get('--fields') fiel...
Determine the new start and end indices of the time series. :param npts: Number of points in original time series :param dt: Time step of original time series :param start: int or float, optional, New start point :param end: int or float, optional, New end point :param index: bool, optional, if Fal...
The method cuts the time series to reduce its length. :param start: int or float, optional, New start point :param end: int or float, optional, New end point :param index: bool, optional, if False then start and end are considered values in time. def cut(self, start=0, end=-1, index=False): ...
Check whether a SLURM job is finished or not def finished(cls, jobid): """Check whether a SLURM job is finished or not""" output = subprocess.check_output( [SACCT, '-n', '-X', '-o', "end", '-j', str(jobid)] ) end = output.strip().decode() return end not in {'Unknown'...
Begin a run_group in the database. A run_group groups a set of runs for a given project. This models a series of runs that form a complete binary runtime test. Args: project: The project we begin a new run_group for. Returns: ``(group, session)`` where group is the created group in th...
End the run_group successfully. Args: group: The run_group we want to complete. session: The database transaction we will finish. def end_run_group(group, session): """ End the run_group successfully. Args: group: The run_group we want to complete. session: The databas...
End the run_group unsuccessfully. Args: group: The run_group we want to complete. session: The database transaction we will finish. def fail_run_group(group, session): """ End the run_group unsuccessfully. Args: group: The run_group we want to complete. session: The da...
Generate a single exit code from a list of RunInfo objects. Takes a list of RunInfos and returns the exit code that is furthest away from 0. Args: run_infos (t.List[RunInfo]): [description] Returns: int: [description] def exit_code_from_run_infos(run_infos: t.List[RunInfo]) -> int: ...
Guard the execution of the given command. The given command (`cmd`) will be executed inside a database context. As soon as you leave the context we will commit the transaction. Any necessary modifications to the database can be identified inside the context with the RunInfo object. Args: c...
Recursively updates the environment of cmd and all its subcommands. Args: cmd - A plumbum command-like object **envvars - The environment variables to update Returns: The updated command. def with_env_recursive(cmd, **envvars): """ Recursively updates the environment of cmd an...
Decorate a project phase with a local working directory change. Args: sub: An optional subdirectory to change into. def in_builddir(sub='.'): """ Decorate a project phase with a local working directory change. Args: sub: An optional subdirectory to change into. """ from functo...
Decorator for storing the configuration in the project's builddir. def store_config(func): """Decorator for storing the configuration in the project's builddir.""" from functools import wraps @wraps(func) def wrap_store_config(self, *args, **kwargs): """Wrapper that contains the actual storage...
Remove the in and out of the container if confirmed by the user. def clean_directories(builddir, in_dir=True, out_dir=True): """Remove the in and out of the container if confirmed by the user.""" container_in = local.path(builddir) / "container-in" container_out = local.path(builddir) / "container-out" ...
Create the in and out directories of the container. def setup_directories(builddir): """Create the in and out directories of the container.""" build_dir = local.path(builddir) in_dir = build_dir / "container-in" out_dir = build_dir / "container-out" if not in_dir.exists(): in_dir.mkdir() ...
Prepare the container and returns the path where it can be found. def setup_container(builddir, _container): """Prepare the container and returns the path where it can be found.""" build_dir = local.path(builddir) in_dir = build_dir / "container-in" container_path = local.path(_container) with loca...
Run a given command inside a container. Mounts a directory as a container at the given mountpoint and tries to run the given command inside the new container. def run_in_container(command, container_dir): """ Run a given command inside a container. Mounts a directory as a container at the given m...
Pack a container image into a .tar.bz2 archive. Args: in_container (str): Path string to the container image. out_file (str): Output file name. def pack_container(in_container, out_file): """ Pack a container image into a .tar.bz2 archive. Args: in_container (str): Path string...
Setup a bash environment inside a container. Creates a new chroot, which the user can use as a bash to run the wanted projects inside the mounted container, that also gets returned afterwards. def setup_bash_in_container(builddir, _container, outfile, shell): """ Setup a bash environment inside a cont...
Save the input for the container in the configurations. def set_input_container(_container, cfg): """Save the input for the container in the configurations.""" if not _container: return False if _container.exists(): cfg["container"]["input"] = str(_container) return True return ...
Setup a gentoo container suitable for PolyJIT. def run(self, context): """Setup a gentoo container suitable for PolyJIT.""" # Don't do something when running non-interactive. if not sys.stdout.isatty(): return with local.cwd(context.in_container): from benchbuil...
Find the input path of a uchroot container. def input_file(self, _container): """Find the input path of a uchroot container.""" p = local.path(_container) if set_input_container(p, CFG): return p = find_hash(CFG["container"]["known"].value, container) if set_input_c...
Find and writes the output path of a chroot container. def output_file(self, _container): """Find and writes the output path of a chroot container.""" p = local.path(_container) if p.exists(): if not ui.ask("Path '{0}' already exists." " Overwrite?".format(...
Splits the soil profile into slices and stores as dictionary :param sp: SoilProfile :param incs: array_like, increments of depth to use for each layer :param target: target depth increment size :return: dict def discretize_soil_profile(sp, incs=None, target=1.0): """ Splits the soil profile in...