text stringlengths 81 112k |
|---|
Return a pseudo prime number roughly between a and b,
(could be larger than b). Raise ValueError if cannot find a
pseudo prime after 10 * ln(x) + 3 tries.
def findAPrime(a, b, k):
"""Return a pseudo prime number roughly between a and b,
(could be larger than b). Raise ValueError if cannot find a
ps... |
Try to find two large pseudo primes roughly between a and b.
Generate public and private keys for RSA encryption.
Raises ValueError if it fails to find one
def newKey(a, b, k):
""" Try to find two large pseudo primes roughly between a and b.
Generate public and private keys for RSA encryption.
Rais... |
Take a list of integers(each between 0 and 127), and combines them
into block size n using base 256. If len(L) % n != 0, use some random
junk to fill L to make it.
def numList2blocks(l, n):
"""Take a list of integers(each between 0 and 127), and combines them
into block size n using base 256. If len(L)... |
inverse function of numList2blocks.
def blocks2numList(blocks, n):
"""inverse function of numList2blocks."""
toProcess = copy.copy(blocks)
returnList = []
for numBlock in toProcess:
inner = []
for i in range(0, n):
inner.append(numBlock % 256)
numBlock >>= 8
... |
given a string message, public keys and blockSize, encrypt using
RSA algorithms.
def encrypt(message, modN, e, blockSize):
"""given a string message, public keys and blockSize, encrypt using
RSA algorithms."""
numList = string2numList(message)
numBlocks = numList2blocks(numList, blockSize) # only ... |
reverse function of encrypt
def decrypt(secret, modN, d, blockSize):
"""reverse function of encrypt"""
numBlocks = [modExp(blocks, d, modN) for blocks in secret]
numList = blocks2numList(numBlocks, blockSize)
return numList2string(numList) |
Yields file name if matches a regular expression pattern.
def match_files(files, pattern: Pattern):
"""Yields file name if matches a regular expression pattern."""
for name in files:
if re.match(pattern, name):
yield name |
Match files to a pattern within a zip file's content.
def match_zipfile_members(zipfile_path: str, pattern: Pattern):
"""Match files to a pattern within a zip file's content."""
with ZipFile(zipfile_path, mode='r') as zfile:
members = zfile.namelist()
yield from match_files(members, pattern) |
Yield directory file names.
def directory_files(path):
"""Yield directory file names."""
for entry in os.scandir(path):
if not entry.name.startswith('.') and entry.is_file():
yield entry.name |
Return sha256 string for group of FTP listings.
def get_file_listing_sha(listing_paths: Iterable) -> str:
"""Return sha256 string for group of FTP listings."""
return sha256(''.join(sorted(listing_paths)).encode('utf-8')).hexdigest() |
Set the finger number to button number mapping for tap-to-click.
The default mapping on most devices is to have a 1, 2 and 3 finger tap
to map to the left, right and middle button, respectively. A device may
permit changing the button mapping but disallow specific maps. In this
case :attr:`~libinput.constant.C... |
Apply the 3x3 transformation matrix to absolute device coordinates.
This matrix has no effect on relative events.
Given a 6-element array [a, b, c, d, e, f], the matrix is applied as
::
[ a b c ] [ x ]
[ d e f ] * [ y ]
[ 0 0 1 ] [ 1 ]
The translation component (c, f) is expected to be no... |
The current calibration matrix for this device.
Returns:
(bool, (float, float, float, float, float, float)): :obj:`False` if
no calibration is set and
the returned matrix is the identity matrix, :obj:`True`
otherwise. :obj:`tuple` representing the first two rows of
a 3x3 matrix as described in :meth:`... |
The default calibration matrix for this device.
On most devices, this is the identity matrix. If the udev property
``LIBINPUT_CALIBRATION_MATRIX`` is set on the respective udev device,
that property's value becomes the default matrix, see
`Static device configuration via udev`_.
Returns:
(bool, (float, f... |
The system name of the device.
To get the descriptive device name, use :attr:`name`.
Returns:
str: System name of the device.
def sysname(self):
"""The system name of the device.
To get the descriptive device name, use :attr:`name`.
Returns:
str: System name of the device.
"""
pchar = self._li... |
The descriptive device name as advertised by the kernel
and/or the hardware itself.
To get the sysname for this device, use :attr:`sysname`.
Returns:
str: The device name.
def name(self):
"""The descriptive device name as advertised by the kernel
and/or the hardware itself.
To get the sysname for thi... |
Change the logical seat associated with this device by removing
the device and adding it to the new seat.
This command is identical to physically unplugging the device, then
re-plugging it as a member of the new seat. libinput will generate
a :attr:`~libinput.constant.EventType.DEVICE_REMOVED` event and this
... |
A tuple of capabilities this device supports.
Returns:
(~libinput.constant.DeviceCapability): Device capabilities.
def capabilities(self):
"""A tuple of capabilities this device supports.
Returns:
(~libinput.constant.DeviceCapability): Device capabilities.
"""
caps = []
for cap in DeviceCapability... |
The physical size of a device in mm, where meaningful.
This property is only valid on devices with the required data, i.e.
tablets, touchpads and touchscreens. For other devices this property
raises :exc:`AssertionError`.
Returns:
(float, float): (Width, Height) in mm.
Raises:
AssertionError
def size... |
Check if this device has a given button.
Args:
button (int): Button to check for, see ``input.h`` for button
definitions.
Returns:
bool: :obj:`True` if the device has this button, :obj:`False` if
it does not.
Raises:
AssertionError
def has_button(self, button):
"""Check if this device has a gi... |
Check if a :attr:`~libinput.constant.DeviceCapability.KEYBOARD`
device has a given key.
Args:
key (int): Key to check for, see ``input.h`` for key definitions.
Returns:
bool: :obj:`True` if the device has this key, :obj:`False` if
it does not.
Raises:
AssertionError
def has_key(self, key):
"""Ch... |
The number of buttons on a device with
the :attr:`~libinput.constant.DeviceCapability.TABLET_PAD` capability.
Buttons on a pad device are numbered sequentially, see
`Tablet pad button numbers`_ for details.
Returns:
int: The number of buttons supported by the device.
Raises:
AttributeError
def num_bu... |
The number of rings a device with
the :attr:`~libinput.constant.DeviceCapability.TABLET_PAD`
capability provides.
Returns:
int: The number of rings or 0 if the device has no rings.
Raises:
AttributeError
def num_rings(self):
"""The number of rings a device with
the :attr:`~libinput.constant.DeviceCa... |
The number of strips a device with
the :attr:`~libinput.constant.DeviceCapability.TABLET_PAD`
capability provides.
Returns:
int: The number of strips or 0 if the device has no strips.
Raises:
AttributeError
def num_strips(self):
"""The number of strips a device with
the :attr:`~libinput.constant.Dev... |
Most devices only provide a single mode group, however devices
such as the Wacom Cintiq 22HD provide two mode groups.
If multiple mode groups are available, a caller should use
:meth:`~libinput.define.TabletPadModeGroup.has_button`,
:meth:`~libinput.define.TabletPadModeGroup.has_ring`
and :meth:`~libinput.de... |
While a reference is kept by the caller, the returned mode group
will compare equal with mode group returned by each subsequent call of
this method with the same index and mode group returned from
:attr:`~libinput.event.TabletPadEvent.mode_group`, provided
the event was generated by this mode group.
Args:
... |
The physical name of the seat.
For libinput contexts created from udev, this is always the same value
as passed into :meth:`~libinput.LibInputUdev.assign_seat` and all
seats from that context will have the same physical name.
The physical name of the seat is one that is usually set by the system
or lower le... |
The logical name of the seat.
This is an identifier to group sets of devices within the compositor.
Returns:
str: The logical name of this seat.
def logical_name(self):
"""The logical name of the seat.
This is an identifier to group sets of devices within the compositor.
Returns:
str: The logical n... |
Load logging configuration from our own defaults.
def configure():
"""Load logging configuration from our own defaults."""
log_levels = {
5: logging.NOTSET,
4: logging.DEBUG,
3: logging.INFO,
2: logging.WARNING,
1: logging.ERROR,
0: logging.CRITICAL
}
lo... |
.. versionchanged:: 0.9.2
Add support for float exponent strings (e.g., ``3.435e-7``).
Fixes `issue #4 <https://github.com/wheeler-microfluidics/svg-model/issues/4>`.
def get_number(self):
'''
.. versionchanged:: 0.9.2
Add support for float exponent strings (e.g., `... |
path_data : string, from an svg path tag's 'd' attribute, eg:
'M 46,74 L 35,12 l 53,-13 z'
returns the same data collected in a list of tuples, eg:
[ ('M', 46, 74), ('L', 35, 12), ('l', 53, -13), ('z') ],
The input data may have floats instead of ints, this will be reflected
... |
commands : list of tuples, as output from to_tuples() method, eg:
[('M', 1, 2), ('L', 3, 4), ('L', 5, 6), ('z')]
Interprets the command characters at the start of each tuple to return
a list of loops, where each loop is a closed list of verts, and each
vert is a pair of ints or float... |
color : string, eg: '#rrggbb' or 'none'
(where rr, gg, bb are hex digits from 00 to ff)
returns a triple of unsigned bytes, eg: (0, 128, 255)
def parse_color(self, color):
'''
color : string, eg: '#rrggbb' or 'none'
(where rr, gg, bb are hex digits from 00 to ff)
returns... |
style : string, eg:
fill:#ff2a2a;fill-rule:evenodd;stroke:none;stroke-width:1px;
stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1
returns color as a triple of unsigned bytes: (r, g, b), or None
def parse_style(self, style):
'''
style : string, eg:
f... |
returns (id, path)
where: 'id' is the path tag's id attribute
'path' is a populated instance of SvgPath
>>> from lxml import etree
>>> from lxml.builder import E
>>> path_tag = etree.XML("""
... <path id="path0"
... style="fill:#0000ff;stroke... |
Alternative constructor to load from JSON file.
If auth_file_path is not specified, it tries to find `dish.json` in:
- DHIS_HOME
- Home folder
:param location: authentication file path
:param api_version: see Api
:param user_agent: see Api
:return: Api instance
d... |
Return response if ok, raise RequestException if not ok
:param response: requests.response object
:return: requests.response object
def _validate_response(response):
"""
Return response if ok, raise RequestException if not ok
:param response: requests.response object
:re... |
Validate request before calling API
:param endpoint: API endpoint
:param file_type: file type requested
:param data: payload
:param params: HTTP parameters
def _validate_request(endpoint, file_type='json', data=None, params=None):
"""
Validate request before calling API
... |
Do the actual request with supplied HTTP method
:param method: HTTP method
:param endpoint: DHIS2 API endpoint
:param kwargs: keyword args
:return: response if ok, RequestException if not
def _make_request(self, method, endpoint, **kwargs):
"""
Do the actual request with... |
GET from DHIS2
:param endpoint: DHIS2 API endpoint
:param file_type: DHIS2 API File Type (json, xml, csv), defaults to JSON
:param params: HTTP parameters
:param stream: use requests' stream parameter
:return: requests.Response object
def get(self, endpoint, file_type='json', pa... |
POST to DHIS2
:param endpoint: DHIS2 API endpoint
:param json: HTTP payload
:param params: HTTP parameters
:return: requests.Response object
def post(self, endpoint, json=None, params=None, **kwargs):
"""POST to DHIS2
:param endpoint: DHIS2 API endpoint
:param js... |
PUT to DHIS2
:param endpoint: DHIS2 API endpoint
:param json: HTTP payload
:param params: HTTP parameters
:return: requests.Response object
def put(self, endpoint, json=None, params=None, **kwargs):
"""
PUT to DHIS2
:param endpoint: DHIS2 API endpoint
:pa... |
PATCH to DHIS2
:param endpoint: DHIS2 API endpoint
:param json: HTTP payload
:param params: HTTP parameters (dict)
:return: requests.Response object
def patch(self, endpoint, json=None, params=None, **kwargs):
"""
PATCH to DHIS2
:param endpoint: DHIS2 API endpoin... |
DELETE from DHIS2
:param endpoint: DHIS2 API endpoint
:param json: HTTP payload
:param params: HTTP parameters (dict)
:return: requests.Response object
def delete(self, endpoint, json=None, params=None, **kwargs):
"""
DELETE from DHIS2
:param endpoint: DHIS2 API ... |
GET with paging (for large payloads).
:param page_size: how many objects per page
:param endpoint: DHIS2 API endpoint
:param params: HTTP parameters (dict), defaults to None
:param merge: If true, return a list containing all pages instead of one page. Defaults to False.
:return:... |
GET SQL View data
:param uid: sqlView UID
:param execute: materialize sqlView before downloading its data
:param var: for QUERY types, a dict of variables to query the sqlView
:param criteria: for VIEW / MATERIALIZED_VIEW types, a dict of criteria to filter the sqlView
:param mer... |
Post a payload in chunks to prevent 'Request Entity Too Large' Timeout errors
:param endpoint: the API endpoint to use
:param json: payload dict
:param params: request parameters
:param thresh: the maximum amount to partition into
:return: generator where __next__ is a requests.R... |
Parameters
----------
offset : pandas.Series
Cartesian ``(x, y)`` coordinate of offset origin.
scale : pandas.Series
Scaling factor for ``x`` and ``y`` dimensions.
Returns
-------
pandas.DataFrame
3x3 transformation matrix resulting in specified `x/y` offset and
... |
Look up shape based on canvas coordinates.
def find_shape(self, canvas_x, canvas_y):
'''
Look up shape based on canvas coordinates.
'''
shape_x, shape_y, w = self.canvas_to_shapes_transform.dot([canvas_x,
canvas_y,
... |
Return a `pandas.Series` indexed by `shape_i_columns` (i.e., each entry
corresponds to a single shape/polygon), containing the following columns
the area of each shape.
If `signed=True`, a positive area value corresponds to a clockwise loop,
whereas a negative area value corresponds to a counter-clockw... |
Return a `pandas.DataFrame` indexed by `shape_i_columns` (i.e., each row
corresponds to a single shape/polygon), containing the following columns:
- `width`: The width of the widest part of the shape.
- `height`: The height of the tallest part of the shape.
def get_bounding_boxes(df_shapes, shape_i_colu... |
Return a `pandas.DataFrame` indexed by `shape_i_columns` (i.e., each row
corresponds to a single shape/polygon), containing the following columns:
- `area`: The area of the shape.
- `width`: The width of the widest part of the shape.
- `height`: The height of the tallest part of the shape.
def get_... |
Calculate the bounding box of all points in a data frame.
def get_bounding_box(df_points):
'''
Calculate the bounding box of all points in a data frame.
'''
xy_min = df_points[['x', 'y']].min()
xy_max = df_points[['x', 'y']].max()
wh = xy_max - xy_min
wh.index = 'width', 'height'
bbox ... |
Decoder for parsing typical objects like uuid's and dates.
def json_decoder_hook(dct, str_decoders=STRING_DECODERS,
converters=MappingProxyType(dict())) -> dict:
"""Decoder for parsing typical objects like uuid's and dates."""
for k, v in dct.items():
if k in converters:
... |
Customize JSON string decoder hooks.
Object hook for typical deserialization scenarios.
Notes
-----
Specifying a field in converters will ensure custom decoding/passthrough.
Parameters
----------
str_decoders: functions for decoding strings to objects.
extra_str_decoders: appends addi... |
Wait for asynchronous jobs stil running in the given campaign.
:param report: memory representation of a campaign report
:type campaign: ReportNode
:param interval: wait interval
:type interval: int or float
:return: list of asynchronous job identifiers
def wait_for_completion(report, interval=10)... |
ben-wait entry point
def main(argv=None):
"""ben-wait entry point"""
arguments = cli_common(__doc__, argv=argv)
report = ReportNode(arguments['CAMPAIGN-DIR'])
jobs = wait_for_completion(report, float(arguments['--interval']))
status = ReportStatus(report, jobs)
if not arguments['--silent']:
... |
Create a palette with one main color and two opposite color evenly spread apart from the main one.
:param hue: A 0-1 float with the starting hue value.
:param sat: A 0-1 float with the palette saturation.
:param val: A 0-1 float with the palette value.
:param val: An int with the spread in degrees from the opposi... |
Slurm job name if not already specified
in the `sbatch` section
def default_job_name(self):
"""Slurm job name if not already specified
in the `sbatch` section"""
name = ''
if not self.root.existing_campaign:
campaign_file = osp.basename(self.root.campaign_file)
... |
:return Jinja sbatch template for the current tag
def sbatch_template(self):
""":return Jinja sbatch template for the current tag"""
template = self.sbatch_template_str
if template.startswith('#!'):
# script is embedded in YAML
return jinja_environment.from_string(templa... |
:return Jinja sbatch template for the current tag as string
def sbatch_template_str(self):
""":return Jinja sbatch template for the current tag as string"""
templates = self.campaign.process.sbatch_template
if isinstance(templates, Mapping):
# find proper template according to the t... |
Write sbatch template to output stream
:param ostr: opened file to write to
def _create_sbatch(self, ostr):
"""Write sbatch template to output stream
:param ostr: opened file to write to
"""
properties = dict(
sbatch_arguments=self.sbatch_args, hpcbench_command=self.... |
Schedule the sbatch file using the sbatch command
:returns the slurm job id
def _execute_sbatch(self):
"""Schedule the sbatch file using the sbatch command
:returns the slurm job id
"""
commands = self.campaign.process.get('commands', {})
sbatch = find_executable(command... |
ben-tpl entry point
def main(argv=None):
"""ben-tpl entry point"""
arguments = cli_common(__doc__, argv=argv)
plugin = 'benchmark' if arguments['benchmark'] else None
if arguments['-g']:
template.generate_config(plugin, arguments['<FILE>'])
else:
with open(arguments['<FILE>']) as i... |
Partition ordered sequence by key.
Sequence is expected to already be ordered.
Parameters
----------
sequence: iterable data.
key: partition key function
Yields
-------
iterable tuple(s) of partition key, data list pairs.
Examples
--------
1. By object attributes.
Pa... |
Use a predicate to partition true and false entries.
Reference
---------
Python itertools documentation.
def partition(predicate, iterable):
"""Use a predicate to partition true and false entries.
Reference
---------
Python itertools documentation.
"""
t1, t2 = tee(iterable)
... |
Create a new dynamic portage project.
Auto-Generated projects can only be used for compilie-time experiments,
because there simply is no run-time test defined for it. Therefore,
we implement the run symbol as a noop (with minor logging).
This way we avoid the default implementation for run() that all ... |
apply the unit schema to the data
Parameters
----------
data : dict
uschema : dict
units schema to apply
as_quantity : bool
if true, return values as pint.Quantity objects
raise_outerr : bool
raise error if a unit cannot be found in the outschema
convert_to_base : bo... |
split pint.Quantity objects into <unit,magnitude> pairs
Parameters
----------
data : dict
units : str
name for units key
magnitude : str
name for magnitude key
list_of_dicts: bool
treat list of dicts as additional branches
Examples
--------
>>> from pprint i... |
combine <unit,magnitude> pairs into pint.Quantity objects
Parameters
----------
data : dict
units : str
name of units key
magnitude : str
name of magnitude key
list_of_dicts: bool
treat list of dicts as additional branches
Examples
--------
>>> from pprint i... |
Creates a version for a project out of the hash.
The hash is taken from the directory of the source file.
Args:
src_file: The source file of the project using this function.
Returns:
Either returns the first 8 digits of the hash as string,
the entire hash as a string if the hash c... |
Get the git commit hash of HEAD from :from_url.
Args:
from_url: The file system url of our git repository.
Returns:
git commit hash of HEAD, or empty string.
def get_git_hash(from_url):
"""
Get the git commit hash of HEAD from :from_url.
Args:
from_url: The file system ur... |
Fetch the output /usr/bin/time from a.
Args:
marker: The marker that limits the time output
format_s: The format string used to parse the timings
ins: A list of lines we look for the output.
Returns:
A list of timing tuples
def fetch_time_output(marker, format_s, ins):
"""... |
Conver a path string to a list of path elements.
def path_to_list(pathstr):
"""Conver a path string to a list of path elements."""
return [elem for elem in pathstr.split(os.path.pathsep) if elem] |
Borrowed from wxglade.py
def determine_path():
"""Borrowed from wxglade.py"""
root = __file__
if os.path.islink(root):
root = os.path.realpath(root)
return os.path.dirname(os.path.abspath(root)) |
Return a list of filenames found at @path.
The list of filenames can be filtered by extensions.
Arguments:
path: Existing filepath we want to list.
exts: List of extensions to filter by.
Returns:
A list of filenames found in the path.
def template_files(path, exts=None):
"""
... |
Read a template file from the resources and return it as str.
def template_str(template):
"""Read a template file from the resources and return it as str."""
tmpl_file = os.path.join(determine_path(), template)
with open(tmpl_file, mode='r') as tmpl_strm:
return "".join(tmpl_strm.readlines()) |
Create a file inside a uchroot env.
You will want to use this when you need to create a file with apropriate
rights inside a uchroot container with subuid/subgid handling enabled.
Args:
filepath:
The filepath that should be created. Absolute inside the
uchroot container.
... |
Create a file inside a uchroot env.
You will want to use this when you need to create a file with apropriate
rights inside a uchroot container with subuid/subgid handling enabled.
Args:
dirpath:
The dirpath that should be created. Absolute inside the
uchroot container.
... |
Create a directory if required.
This will query the user for a confirmation.
Args:
dirname: The path to create.
def mkdir_interactive(dirpath):
"""
Create a directory if required.
This will query the user for a confirmation.
Args:
dirname: The path to create.
"""
fro... |
From MeasYaps XML root find next sibling of node matching 'search'.
MeasYaps looks like:
<value>Key</value>
<value>Value</value>
Thus 'search' is the Key and we want to find the node that has the Value.
We return the node containing the desired Value.
Arguments:
root (Element) r... |
From XML root, return value of node matching attribute 'name'.
Arguments:
root (Element) Root XML node (xml.etree.ElementTree Element).
This is the root of the entire XML document, not the YAPS
subtree.
name (String) name='name' attribute of Pa... |
Read raw data from Siemens MRI scanners with IDEA VB15.
Will return an array of measured k-space data from raw data from
Siemens MRI scanners using IDEA VB15 (single value). If the option
'-I' is used, then image space data will be returned instead.
Usage:
readMeasDataVB15 filename [ -t ] [ -rfft ... |
Function run when called from command line.
def main(args):
'''Function run when called from command line.'''
options = { '-rfft': ['resetFFTscale',False],
'-r1': ['readOneCoil',False],
'-rp': ['readPhaseCorInfo',False],
'-rn': ['readNavigator',Fal... |
get json keys from directory structure
e.g.
jdir
sub_dir1
data1.json
data2.json
sub_dir2
data.json
_get_keys_folder(jdir)
=> ['sub_dir1', 'sub_dir2']
_get_keys_folder(jdir,['sub_dir1'])
=> ['data1', 'data2']
NB: json files are identifie... |
get keys for initial json level, or at level after following key_path
Parameters
----------
jfile : str, file_like or path_like
if str, must be existing file or folder,
if file_like, must have 'read' method
if path_like, must have 'iterdir' method (see pathlib.Path)
key_path : l... |
read json with keys
Parameters
----------
file_obj : object
object with read method
key_path : list[str]
key to index befor parsing
parse_decimal : bool
whether to parse numbers as Decimal instances (retains exact precision)
Notes
-----
ijson outputs decimals as... |
read in folder structure as json
e.g.
jdir
sub_dir1
data.json
sub_dir2
data.json
_folder_to_json(jdir)
=> {'sub_dir1':{'data':{...}},
'sub_dir2':{'data':{...}}}
NB: json files are identified with .json extension
def _folder_to_json(jdir, key_path=... |
input json to dict
Parameters
----------
jfile : str, file_like or path_like
if str, must be existing file or folder,
if file_like, must have 'read' method
if path_like, must have 'iterdir' method (see pathlib.Path)
key_path : list[str]
a list of keys to index into the j... |
Turn generator sequence into sequence of chunks.
def chunks(items, chunksize):
"""Turn generator sequence into sequence of chunks."""
items = iter(items)
for first in items:
chunk = chain((first,), islice(items, chunksize - 1))
yield chunk
deque(chunk, 0) |
Decorator for the UnionFS feature.
This configures a unionfs for projects. The given base_dir and/or image_dir
are layered as follows:
image_dir=RW:base_dir=RO
All writes go to the image_dir, while base_dir delivers the (read-only)
versions of the rest of the filesystem.
The unified version w... |
Add the new path to the list of paths to clean up afterwards.
Args:
new_path: Path to the directory that need to be cleaned up.
def __update_cleanup_paths(new_path):
"""
Add the new path to the list of paths to clean up afterwards.
Args:
new_path: Path to the directory that need to be... |
Check if a project lies outside of its expected directory.
def __is_outside_of_builddir(project, path_to_check):
"""Check if a project lies outside of its expected directory."""
bdir = project.builddir
cprefix = os.path.commonprefix([path_to_check, bdir])
return cprefix != bdir |
Setup a unionfs via unionfs-fuse.
Args:
ro_base: base_directory of the project
rw_image: virtual image of actual file system
mountpoint: location where ro_base and rw_image merge
def __unionfs_set_up(ro_dir, rw_dir, mount_dir):
"""
Setup a unionfs via unionfs-fuse.
Args:
... |
Build regular expression used to extract precision
metric from command output
def get_precision_regex():
"""Build regular expression used to extract precision
metric from command output"""
expr = re.escape(PRECISION_FORMULA)
expr += r'=\s*(\S*)\s.*\s([A-Z]*)'
return re.compile(expr) |
Build HPL data from basic parameters
def _build_data(self):
"""Build HPL data from basic parameters"""
def baseN(nodes, mpn):
return int(math.sqrt(mpn * 0.80 * nodes * 1024 * 1024 / 8))
def nFromNb(baseN, nb):
factor = int(baseN / nb)
if factor % 2 != 0:
... |
Additional options passed as a list to the ``mpirun`` command
def mpirun(self):
"""Additional options passed as a list to the ``mpirun`` command"""
cmd = self.attributes['mpirun']
if cmd and cmd[0] != 'mpirun':
cmd = ['mpirun']
return [str(e) for e in cmd] |
Perform variable substitution on the given string
Supported syntax:
* $VARIABLE
* ${VARIABLE}
* ${#VARIABLE}
* ${VARIABLE:-default}
:param s: message to expand
:type s: str
:param vars: dictionary of variables. Default is ``os.environ``
:type vars: dict
:return: expanded stri... |
Query an object
:param obj:
object to test
:param kwargs: query specified in kwargssql
:return:
`True` if all `kwargs` expression are `True`, `False` otherwise.
:rtype: bool
def and_(cls, obj, **kwargs):
"""Query an object
:param obj:
ob... |
Query an object
:param obj:
object to test
:param kwargs: query specified in kwargssql
:return:
`True` if at leat one `kwargs` expression is `True`,
`False` otherwise.
:rtype: bool
def or_(cls, obj, **kwargs):
"""Query an object
:param o... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.