Search is not available for this dataset
text stringlengths 75 104k |
|---|
def crtPrfNrlTc(aryBoxCar, varNumMtDrctn, varNumVol, tplPngSize, varNumX,
varExtXmin, varExtXmax, varNumY, varExtYmin, varExtYmax,
varNumPrfSizes, varPrfStdMin, varPrfStdMax, varPar):
"""Create neural model time courses from pixel-wise boxcar functions.
Parameters
---------... |
def cnvlPwBoxCarFn(aryNrlTc, varNumVol, varTr, tplPngSize, varNumMtDrctn,
switchHrfSet, lgcOldSchoolHrf, varPar,):
"""Create 2D Gaussian kernel.
Parameters
----------
aryNrlTc : 5d numpy array, shape [n_x_pos, n_y_pos, n_sd, n_mtn_dir, n_vol]
Description of input 1.
varNu... |
def rsmplInHighRes(aryBoxCarConv,
tplPngSize,
tplVslSpcHighSze,
varNumMtDrctn,
varNumVol):
"""Resample pixel-time courses in high-res visual space.
Parameters
----------
input1 : 2d numpy array, shape [n_samples, n_measurements... |
def get_arg_parse():
"""Parses the Command Line Arguments using argparse."""
# Create parser object:
objParser = argparse.ArgumentParser()
# Add argument to namespace -strCsvPrf results file path:
objParser.add_argument('-strCsvPrf', required=True,
metavar='/path/to/my_pr... |
def main():
"""pyprf_sim entry point."""
# Get list of input arguments (without first one, which is the path to the
# function that is called): --NOTE: This is another way of accessing
# input arguments, but since we use 'argparse' it is redundant.
# lstArgs = sys.argv[1:]
strWelcome = 'pyprf_s... |
def login_required(wrapped):
"""
Requires that the user is logged in and authorized to execute requests
Except if the method is in authorized_methods of the auth_collection
Then he can execute the requests even not being authorized
"""
@wraps(wrapped)
def wrapper(*args, **kwargs):
re... |
def serializable(wrapped):
"""
If a keyword argument 'serialize' with a True value is passed to the
Wrapped function, the return of the wrapped function will be serialized.
Nothing happens if the argument is not passed or the value is not True
"""
@wraps(wrapped)
def wrapper(*args, **kwargs... |
def deserialize(to_deserialize, *args, **kwargs):
"""
Deserializes a string into a PyMongo BSON
"""
if isinstance(to_deserialize, string_types):
if re.match('^[0-9a-f]{24}$', to_deserialize):
return ObjectId(to_deserialize)
try:
return bson_loads(to_deserialize, *... |
def _doAtomicFileCreation(filePath):
"""Tries to atomically create the requested file."""
try:
_os.close(_os.open(filePath, _os.O_CREAT | _os.O_EXCL))
return True
except OSError as e:
if e.errno == _errno.EEXIST:
return False
else:
raise e |
def findNextFile(folder='.',
prefix=None,
suffix=None,
fnameGen=None,
base=0,
maxattempts=10):
"""Finds the next available file-name in a sequence.
This function will create a file of zero size and will return the path to
... |
def _run(passedArgs=None, stderr=None, stdout=None, exitFn=None):
"""Executes the script, gets prefix/suffix from the command prompt and
produces output on STDOUT. For help with command line options, invoke
script with '--help'.
"""
description = """Finds the next available file-name in a sequence.... |
def _errstr(value):
"""Returns the value str, truncated to MAX_ERROR_STR_LEN characters. If
it's truncated, the returned value will have '...' on the end.
"""
value = str(value) # We won't make the caller convert value to a string each time.
if len(value) > MAX_ERROR_STR_LEN:
return value[:... |
def _getStrippedValue(value, strip):
"""Like the strip() string method, except the strip argument describes
different behavior:
If strip is None, whitespace is stripped.
If strip is a string, the characters in the string are stripped.
If strip is False, nothing is stripped."""
if strip is Non... |
def _raiseValidationException(standardExcMsg, customExcMsg=None):
"""Raise ValidationException with standardExcMsg, unless customExcMsg is specified."""
if customExcMsg is None:
raise ValidationException(str(standardExcMsg))
else:
raise ValidationException(str(customExcMsg)) |
def _prevalidationCheck(value, blank, strip, allowlistRegexes, blocklistRegexes, excMsg=None):
"""Returns a tuple of two values: the first is a bool that tells the caller
if they should immediately return True, the second is a new, possibly stripped
value to replace the value passed for value parameter.
... |
def _validateGenericParameters(blank, strip, allowlistRegexes, blocklistRegexes):
"""Returns None if the blank, strip, and blocklistRegexes parameters are valid
of PySimpleValidate's validation functions have. Raises a PySimpleValidateException
if any of the arguments are invalid."""
# Check blank para... |
def _validateParamsFor_validateNum(min=None, max=None, lessThan=None, greaterThan=None):
"""Raises an exception if the arguments are invalid. This is called by
the validateNum(), validateInt(), and validateFloat() functions to
check its arguments. This code was refactored out to a separate function
so t... |
def validateStr(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, excMsg=None):
"""Raises ValidationException if value is not a string. This function
is identical to the built-in input() function, but also offers the
PySimpleValidate features of not allowing blank values by defau... |
def validateNum(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, _numType='num',
min=None, max=None, lessThan=None, greaterThan=None, excMsg=None):
"""Raises ValidationException if value is not a float or int.
Returns value, so it can be used inline in an expression... |
def validateInt(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None,
min=None, max=None, lessThan=None, greaterThan=None, excMsg=None):
"""Raises ValidationException if value is not a int.
Returns value, so it can be used inline in an expression:
print(2 + vali... |
def _validateParamsFor_validateChoice(choices, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None,
numbered=False, lettered=False, caseSensitive=False, excMsg=None):
"""Raises PySimpleValidateException if the arguments are invalid. This is called by
the validateChoice() fun... |
def validateChoice(value, choices, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None,
numbered=False, lettered=False, caseSensitive=False, excMsg=None):
"""Raises ValidationException if value is not one of the values in
choices. Returns the selected choice.
Returns th... |
def _validateParamsFor__validateToDateTimeFormat(formats, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, excMsg=None):
"""Raises PySimpleValidateException if the arguments are invalid. This is called by
the validateTime() function to check its arguments. This code was
refactored out ... |
def validateTime(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None,
formats=('%H:%M:%S', '%H:%M', '%X'), excMsg=None):
"""Raises ValidationException if value is not a time formatted in one
of the formats formats. Returns a datetime.time object of value.
* value (... |
def validateDate(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None,
formats=('%Y/%m/%d', '%y/%m/%d', '%m/%d/%Y', '%m/%d/%y', '%x'), excMsg=None):
"""Raises ValidationException if value is not a time formatted in one
of the formats formats. Returns a datetime.date obje... |
def validateDatetime(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None,
formats=('%Y/%m/%d %H:%M:%S', '%y/%m/%d %H:%M:%S', '%m/%d/%Y %H:%M:%S', '%m/%d/%y %H:%M:%S', '%x %H:%M:%S',
'%Y/%m/%d %H:%M', '%y/%m/%d %H:%M', '%m/%d/%Y %H:%M', '%m/%d/%... |
def validateFilename(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, excMsg=None):
"""Raises ValidationException if value is not a valid filename.
Filenames can't contain \\ / : * ? " < > | or end with a space.
Returns the value argument.
Note that this validates filenames... |
def validateFilepath(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, excMsg=None, mustExist=False):
r"""Raises ValidationException if value is not a valid filename.
Filenames can't contain \\ / : * ? " < > |
Returns the value argument.
* value (str): The value being valida... |
def validateIP(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, excMsg=None):
"""Raises ValidationException if value is not an IPv4 or IPv6 address.
Returns the value argument.
* value (str): The value being validated as an IP address.
* blank (bool): If True, a blank strin... |
def validateRegex(value, regex, flags=0, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, excMsg=None):
"""Raises ValidationException if value does not match the regular expression in regex.
Returns the value argument.
This is similar to calling inputStr() and using the allowlistRegex... |
def validateRegexStr(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, excMsg=None):
"""Raises ValidationException if value can't be used as a regular expression string.
Returns the value argument as a regex object.
If you want to check if a string matches a regular expression, ... |
def validateURL(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, excMsg=None):
"""Raises ValidationException if value is not a URL.
Returns the value argument.
The "http" or "https" protocol part of the URL is optional.
* value (str): The value being validated as a URL.
... |
def validateEmail(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, excMsg=None):
"""Raises ValidationException if value is not an email address.
Returns the value argument.
* value (str): The value being validated as an email address.
* blank (bool): If True, a blank strin... |
def validateYesNo(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, yesVal='yes', noVal='no', caseSensitive=False, excMsg=None):
"""Raises ValidationException if value is not a yes or no response.
Returns the yesVal or noVal argument, not value.
Note that value can be any case (... |
def validateBool(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, trueVal='True', falseVal='False', caseSensitive=False, excMsg=None):
"""Raises ValidationException if value is not an email address.
Returns the yesVal or noVal argument, not value.
* value (str): The value being... |
def validateState(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, excMsg=None, returnStateName=False):
"""Raises ValidationException if value is not a USA state.
Returns the capitalized state abbreviation, unless returnStateName is True
in which case it returns the titlecased s... |
def validateMonth(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, monthNames=ENGLISH_MONTHS, excMsg=None):
"""Raises ValidationException if value is not a month, like 'Jan' or 'March'.
Returns the titlecased month.
* value (str): The value being validated as an email address.
... |
def validateDayOfWeek(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, dayNames=ENGLISH_DAYS_OF_WEEK, excMsg=None):
"""Raises ValidationException if value is not a day of the week, such as 'Mon' or 'Friday'.
Returns the titlecased day of the week.
* value (str): The value being... |
def validateDayOfMonth(value, year, month, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, excMsg=None):
"""Raises ValidationException if value is not a day of the month, from
1 to 28, 29, 30, or 31 depending on the month and year.
Returns value.
* value (str): The value being va... |
def get_level(level_string):
"""
Returns an appropriate logging level integer from a string name
"""
levels = {'debug': logging.DEBUG, 'info': logging.INFO,
'warning': logging.WARNING, 'error': logging.ERROR,
'critical': logging.CRITICAL}
try:
level = levels[level... |
def config_logging(no_log_file, log_to, log_level, silent, verbosity):
"""
Configures and generates a Logger object, 'openaccess_epub' based on common
parameters used for console interface script execution in OpenAccess_EPUB.
These parameters are:
no_log_file
Boolean. Disables logging t... |
def replace_filehandler(logname, new_file, level=None, frmt=None):
"""
This utility function will remove a previous Logger FileHandler, if one
exists, and add a new filehandler.
Parameters:
logname
The name of the log to reconfigure, 'openaccess_epub' for example
new_file
... |
def rmp_pixel_deg_xys(vecX, vecY, vecPrfSd, tplPngSize,
varExtXmin, varExtXmax, varExtYmin, varExtYmax):
"""Remap x, y, sigma parameters from pixel to degree.
Parameters
----------
vecX : 1D numpy array
Array with possible x parametrs in pixels
vecY : 1D numpy array
... |
def crt_mdl_prms(tplPngSize, varNum1, varExtXmin, varExtXmax, varNum2,
varExtYmin, varExtYmax, varNumPrfSizes, varPrfStdMin,
varPrfStdMax, kwUnt='pix', kwCrd='crt'):
"""Create an array with all possible model parameter combinations
Parameters
----------
tplPngSize : t... |
def crt_mdl_rsp(arySptExpInf, tplPngSize, aryMdlParams, varPar, strCrd='crt',
lgcPrint=True):
"""Create responses of 2D Gauss models to spatial conditions.
Parameters
----------
arySptExpInf : 3d numpy array, shape [n_x_pix, n_y_pix, n_conditions]
All spatial conditions stacked ... |
def crt_nrl_tc(aryMdlRsp, aryCnd, aryOns, aryDrt, varTr, varNumVol,
varTmpOvsmpl, lgcPrint=True):
"""Create temporally upsampled neural time courses.
Parameters
----------
aryMdlRsp : 2d numpy array, shape [n_x_pos * n_y_pos * n_sd, n_cond]
Responses of 2D Gauss models to spatial... |
def crt_prf_tc(aryNrlTc, varNumVol, varTr, varTmpOvsmpl, switchHrfSet,
tplPngSize, varPar, dctPrm=None, lgcPrint=True):
"""Convolve every neural time course with HRF function.
Parameters
----------
aryNrlTc : 4d numpy array, shape [n_x_pos, n_y_pos, n_sd, n_vol]
Temporally upsamp... |
def crt_prf_ftr_tc(aryMdlRsp, aryTmpExpInf, varNumVol, varTr, varTmpOvsmpl,
switchHrfSet, tplPngSize, varPar, dctPrm=None,
lgcPrint=True):
"""Create all spatial x feature prf time courses.
Parameters
----------
aryMdlRsp : 2d numpy array, shape [n_x_pos * n_y_pos *... |
def fnd_unq_rws(A, return_index=False, return_inverse=False):
"""Find unique rows in 2D array.
Parameters
----------
A : 2d numpy array
Array for which unique rows should be identified.
return_index : bool
Bool to decide whether I is returned.
return_inverse : bool
Bool ... |
async def _request(
self, method: str, endpoint: str, *, headers: dict = None) -> dict:
"""Make a request against air-matters.com."""
url = '{0}/{1}'.format(API_URL_SCAFFOLD, endpoint)
if not headers:
headers = {}
headers.update({
'Host': DEFAULT_HOST... |
def filter_transform_response(get_response, params):
"""
This filter process the returned response. It does 3 things:
- If the response is a ``sanic.response.HTTPResponse`` and not a
:class:`rafter.http.Response`, return it immediately.
- If the response is not a :class:`rafter.http.Response` ins... |
def get_publisher(self):
"""
This method defines how the Article tries to determine the publisher of
the article.
This method relies on the success of the get_DOI method to fetch the
appropriate full DOI for the article. It then takes the DOI prefix
which corresponds to ... |
def get_DOI(self):
"""
This method defines how the Article tries to detect the DOI.
It attempts to determine the article DOI string by DTD-appropriate
inspection of the article metadata. This method should be made as
flexible as necessary to properly collect the DOI for any XML
... |
def np_lst_sq(vecMdl, aryFuncChnk):
"""Least squares fitting in numpy without cross-validation.
Notes
-----
This is just a wrapper function for np.linalg.lstsq to keep piping
consistent.
"""
aryTmpBts, vecTmpRes = np.linalg.lstsq(vecMdl,
aryFuncCh... |
def np_lst_sq_xval(vecMdl, aryFuncChnk, aryIdxTrn, aryIdxTst):
"""Least squares fitting in numpy with cross-validation.
"""
varNumXval = aryIdxTrn.shape[-1]
varNumVoxChnk = aryFuncChnk.shape[-1]
# pre-allocate ary to collect cross-validation
# error for every xval fold
aryResXval = np.emp... |
async def _raw_user_report_data(self) -> list:
"""Return user report data (if accompanied by latitude/longitude)."""
data = await self._request('get', 'map/markers')
return [
location for location in data
if location['latitude'] and location['longitude']
] |
async def _raw_state_data(self) -> list:
"""Return a list of states."""
data = await self._request('get', 'states')
return [
location for location in data
if location['name'] != 'United States'
] |
async def nearest_by_coordinates(
self, latitude: float, longitude: float) -> dict:
"""Get the nearest report (with local and state info) to a lat/lon."""
# Since user data is more granular than state or CDC data, find the
# user report whose coordinates are closest to the provided
... |
def initialize(self, maxsize, history=None):
'''size specifies the maximum amount of history to keep'''
super().__init__()
self.maxsize = int(maxsize)
self.history = deque(maxlen=self.maxsize) # Preserves order history
# If `items` are specified, then initialize with them
... |
def insert(self, key, value):
'''Adds a new key-value pair. Returns any discarded values.'''
# Add to history and catch expectorate
if len(self.history) == self.maxsize:
expectorate = self.history[0]
else:
expectorate = None
self.history.append((key, val... |
def up_to(self, key):
'''Gets the recently inserted values up to a key'''
for okey, ovalue in reversed(self.history):
if okey == key:
break
else:
yield ovalue |
def resource(self, uri, methods=frozenset({'GET'}), **kwargs):
"""
Decorates a function to be registered as a resource route.
:param uri: path of the URL
:param methods: list or tuple of methods allowed
:param host:
:param strict_slashes:
:param stream:
:... |
def add_resource(self, handler, uri, methods=frozenset({'GET'}),
**kwargs):
"""
Register a resource route.
:param handler: function or class instance
:param uri: path of the URL
:param methods: list or tuple of methods allowed
:param host:
:p... |
def check(session, rev_id, page_id=None, radius=defaults.RADIUS,
before=None, window=None, rvprop=None):
"""
Checks the revert status of a revision. With this method, you can
determine whether an edit is a 'reverting' edit, was 'reverted' by another
edit and/or was 'reverted_to' by another ed... |
def check_deleted(session, rev_id, title=None, timestamp=None,
radius=defaults.RADIUS, before=None, window=None,
rvprop=None):
"""
Checks the revert status of a deleted revision. With this method, you can
determine whether an edit is a 'reverting' edit, was 'reverted' by... |
def get_commits(repo_dir, old_commit, new_commit, hide_merges=True):
"""Find all commits between two commit SHAs."""
repo = Repo(repo_dir)
commits = repo.iter_commits(rev="{0}..{1}".format(old_commit, new_commit))
if hide_merges:
return [x for x in commits if not x.summary.startswith("Merge ")]
... |
def get_commit_url(repo_url):
"""Determine URL to view commits for repo."""
if "github.com" in repo_url:
return repo_url[:-4] if repo_url.endswith(".git") else repo_url
if "git.openstack.org" in repo_url:
uri = '/'.join(repo_url.split('/')[-2:])
return "https://github.com/{0}".format... |
def get_projects(osa_repo_dir, commit):
"""Get all projects from multiple YAML files."""
# Check out the correct commit SHA from the repository
repo = Repo(osa_repo_dir)
checkout(repo, commit)
yaml_files = glob.glob(
'{0}/playbooks/defaults/repo_packages/*.yml'.format(osa_repo_dir)
)
... |
def checkout(repo, ref):
"""Checkout a repoself."""
# Delete local branch if it exists, remote branch will be tracked
# automatically. This prevents stale local branches from causing problems.
# It also avoids problems with appending origin/ to refs as that doesn't
# work with tags, SHAs, and upstre... |
def get_roles(osa_repo_dir, commit, role_requirements):
"""Read OSA role information at a particular commit."""
repo = Repo(osa_repo_dir)
checkout(repo, commit)
log.info("Looking for file {f} in repo {r}".format(r=osa_repo_dir,
f=role_requirements... |
def make_osa_report(repo_dir, old_commit, new_commit,
args):
"""Create initial RST report header for OpenStack-Ansible."""
update_repo(repo_dir, args.osa_repo_url, args.update)
# Are these commits valid?
validate_commits(repo_dir, [old_commit, new_commit])
# Do we have a valid ... |
def make_report(storage_directory, old_pins, new_pins, do_update=False,
version_mappings=None):
"""Create RST report from a list of projects/roles."""
report = ""
version_mappings = version_mappings or {}
for new_pin in new_pins:
repo_name, repo_url, commit_sha = new_pin
... |
def normalize_yaml(yaml):
"""Normalize the YAML from project and role lookups.
These are returned as a list of tuples.
"""
if isinstance(yaml, list):
# Normalize the roles YAML data
normalized_yaml = [(x['name'], x['src'], x.get('version', 'HEAD'))
for x in ya... |
def post_gist(report_data, old_sha, new_sha):
"""Post the report to a GitHub Gist and return the URL of the gist."""
payload = {
"description": ("Changes in OpenStack-Ansible between "
"{0} and {1}".format(old_sha, new_sha)),
"public": True,
"files": {
... |
def prepare_storage_dir(storage_directory):
"""Prepare the storage directory."""
storage_directory = os.path.expanduser(storage_directory)
if not os.path.exists(storage_directory):
os.mkdir(storage_directory)
return storage_directory |
def render_template(template_file, template_vars):
"""Render a jinja template."""
# Load our Jinja templates
template_dir = "{0}/templates".format(
os.path.dirname(os.path.abspath(__file__))
)
jinja_env = jinja2.Environment(
loader=jinja2.FileSystemLoader(template_dir),
trim_... |
def repo_pull(repo_dir, repo_url, fetch=False):
"""Reset repository and optionally update it."""
# Make sure the repository is reset to the master branch.
repo = Repo(repo_dir)
repo.git.clean("-df")
repo.git.reset("--hard")
repo.git.checkout("master")
repo.head.reset(index=True, working_tree... |
def update_repo(repo_dir, repo_url, fetch=False):
"""Clone the repo if it doesn't exist already, otherwise update it."""
repo_exists = os.path.exists(repo_dir)
if not repo_exists:
log.info("Cloning repo {}".format(repo_url))
repo = repo_clone(repo_dir, repo_url)
# Make sure the repo is ... |
def validate_commits(repo_dir, commits):
"""Test if a commit is valid for the repository."""
log.debug("Validating {c} exist in {r}".format(c=commits, r=repo_dir))
repo = Repo(repo_dir)
for commit in commits:
try:
commit = repo.commit(commit)
except Exception:
msg... |
def validate_commit_range(repo_dir, old_commit, new_commit):
"""Check if commit range is valid. Flip it if needed."""
# Are there any commits between the two commits that were provided?
try:
commits = get_commits(repo_dir, old_commit, new_commit)
except Exception:
commits = []
if len... |
def get_release_notes(osa_repo_dir, osa_old_commit, osa_new_commit):
"""Get release notes between the two revisions."""
repo = Repo(osa_repo_dir)
# Get a list of tags, sorted
tags = repo.git.tag().split('\n')
tags = sorted(tags, key=LooseVersion)
# Currently major tags are being printed after r... |
def run_osa_differ():
"""Start here."""
# Get our arguments from the command line
args = parse_arguments()
# Set up DEBUG logging if needed
if args.debug:
log.setLevel(logging.DEBUG)
elif args.verbose:
log.setLevel(logging.INFO)
# Create the storage directory if it doesn't ... |
def append_new_text(destination, text, join_str=None):
"""
This method provides the functionality of adding text appropriately
underneath the destination node. This will be either to the destination's
text attribute or to the tail attribute of the last child.
"""
if join_str is None:
joi... |
def append_all_below(destination, source, join_str=None):
"""
Compared to xml.dom.minidom, lxml's treatment of text as .text and .tail
attributes of elements is an oddity. It can even be a little frustrating
when one is attempting to copy everything underneath some element to
another element; one ha... |
def all_text(element):
"""
A method for extending lxml's functionality, this will find and concatenate
all text data that exists one level immediately underneath the given
element. Unlike etree.tostring(element, method='text'), this will not
recursively walk the entire underlying tree. It merely com... |
def remove_all_attributes(element, exclude=None):
"""
This method will remove all attributes of any provided element.
A list of strings may be passed to the keyward-argument "exclude", which
will serve as a list of attributes which will not be removed.
"""
if exclude is None:
exclude = ... |
def ns_format(element, namespaced_string):
"""
Provides a convenient method for adapting a tag or attribute name to
use lxml's format. Use this for tags like ops:switch or attributes like
xlink:href.
"""
if ':' not in namespaced_string:
print('This name contains no namespace, returning i... |
def rename_attributes(element, attrs):
"""
Renames the attributes of the element. Accepts the element and a dictionary
of string values. The keys are the original names, and their values will be
the altered names. This method treats all attributes as optional and will
not fail on missing attributes.... |
def elevate_element(node, adopt_name=None, adopt_attrs=None):
"""
This method serves a specialized function. It comes up most often when
working with block level elements that may not be contained within
paragraph elements, which are presented in the source document as
inline ele... |
def replace(old, new):
"""
A simple way to replace one element node with another.
"""
parent = old.getparent()
parent.replace(old, new) |
def insert_before(old, new):
"""
A simple way to insert a new element node before the old element node among
its siblings.
"""
parent = old.getparent()
parent.insert(parent.index(old), new) |
def comment(node):
"""
Converts the node received to a comment, in place, and will also return the
comment element.
"""
parent = node.parentNode
comment = node.ownerDocument.createComment(node.toxml())
parent.replaceChild(comment, node)
return comment |
def uncomment(comment):
"""
Converts the comment node received to a non-commented element, in place,
and will return the new node.
This may fail, primarily due to special characters within the comment that
the xml parser is unable to handle. If it fails, this method will log an
error and return... |
def serialize(element, strip=False):
"""
A handy way to serialize an element to text.
"""
text = etree.tostring(element, method='text', encoding='utf-8')
if strip:
text = text.strip()
return str(text, encoding='utf-8') |
def get_arg_parse():
"""Parses the Command Line Arguments using argparse."""
# Create parser object:
objParser = argparse.ArgumentParser()
# Add argument to namespace -config file path:
objParser.add_argument('-config', required=True,
metavar='/path/to/config.csv',
... |
def main():
"""pyprf_opt_brute entry point."""
# Get list of input arguments (without first one, which is the path to the
# function that is called): --NOTE: This is another way of accessing
# input arguments, but since we use 'argparse' it is redundant.
# lstArgs = sys.argv[1:]
strWelcome = 'p... |
def _homogenize_data_filter(dfilter):
"""
Make data filter definition consistent.
Create a tuple where first element is the row filter and the second element
is the column filter
"""
if isinstance(dfilter, tuple) and (len(dfilter) == 1):
dfilter = (dfilter[0], None)
if (dfilter is N... |
def _tofloat(obj):
"""Convert to float if object is a float string."""
if "inf" in obj.lower().strip():
return obj
try:
return int(obj)
except ValueError:
try:
return float(obj)
except ValueError:
return obj |
def _in_header(self, col):
"""Validate column identifier(s)."""
# pylint: disable=R1704
if not self._has_header:
# Conditionally register exceptions so that they do not appear
# in situations where has_header is always True. In this way
# they are not auto-doc... |
def _validate_frow(self, frow):
"""Validate frow argument."""
is_int = isinstance(frow, int) and (not isinstance(frow, bool))
pexdoc.exh.addai("frow", not (is_int and (frow >= 0)))
return frow |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.