text stringlengths 81 112k |
|---|
Gets the argument spec of the given function, returning defaults as a dict of param names to values
def _get_arg_spec(func):
"""
Gets the argument spec of the given function, returning defaults as a dict of param names to values
"""
args, varargs, keywords, defaults = inspect.getargspec... |
Run ocrmypdf and confirmed that a valid file was created
def check_ocrmypdf(input_file, output_file, *args, env=None):
"Run ocrmypdf and confirmed that a valid file was created"
p, out, err = run_ocrmypdf(input_file, output_file, *args, env=env)
if p.returncode != 0:
print('stdout\n======')
... |
Run ocrmypdf and let caller deal with results
def run_ocrmypdf(input_file, output_file, *args, env=None):
"Run ocrmypdf and let caller deal with results"
if env is None:
env = os.environ
p_args = OCRMYPDF + list(args) + [input_file, output_file]
p = Popen(
p_args, close_fds=True, stdo... |
pretty-fy the name for pysc2 map lookup
def standardizeMapName(mapName):
"""pretty-fy the name for pysc2 map lookup"""
#print("foreignName: %s (%s)"%(mapName, mapName in c.mapNameTranslations))
#if mapName in c.mapNameTranslations:
# return c.mapNameTranslations[mapName]
newName = os.path.basen... |
Returns a string that contains the Python version and runtime path.
def env_info():
'''
Returns a string that contains the Python version and runtime path.
'''
v = sys.version_info
pyver = f'Python {v.major}.{v.minor}.{v.micro}'
if v.releaselevel == 'alpha':
pyver += 'a'
if v.releas... |
Serializes a dict-like object into a generator of the flatten list of
repeating key-value pairs. It is useful when using HMSET method in Redis.
Example:
>>> list(dict2kvlist({'a': 1, 'b': 2}))
['a', 1, 'b', 2]
def dict2kvlist(o):
'''
Serializes a dict-like object into a generator of the flatt... |
A short-hand for retrieving a value from nested mappings
("nested-mapping-get"). At each level it checks if the given "path"
component in the given key exists and return the default value whenever
fails.
Example:
>>> o = {'a':{'b':1}, 'x': None}
>>> nmget(o, 'a', 0)
{'b': 1}
>>> nmget(... |
Patch __init__.py to remove version check and append hard-coded version.
def patch_init_py(base_dir, name, version):
"""Patch __init__.py to remove version check and append hard-coded version."""
# Ensure main package dir is there (may be absent in script-only packages)
package_dir = os.path.join(base_dir,... |
Setuptools entry point for setting version and baking it into package.
def setuptools_entry(dist, keyword, value):
"""Setuptools entry point for setting version and baking it into package."""
# If 'use_katversion' is False, ignore the rest
if not value:
return
# Enforce the version obtained by ... |
Check if machine is in given state.
def is_(self, state):
"""Check if machine is in given state."""
translator = self._meta['translator']
state = translator.translate(state)
return self.actual_state == state |
Check if machine can transit to given state.
def can_be_(self, state):
"""Check if machine can transit to given state."""
translator = self._meta['translator']
state = translator.translate(state)
if self._meta['complete']:
return True
if self.actual_state is None:
return True
... |
Set new state without checking if transition is allowed.
def force_set(self, state):
"""Set new state without checking if transition is allowed."""
translator = self._meta['translator']
state = translator.translate(state)
attr = self._meta['state_attribute_name']
setattr(self, attr, state) |
Set new state for machine.
def set_(self, state):
"""Set new state for machine."""
if not self.can_be_(state):
state = self._meta['translator'].translate(state)
raise TransitionError(
"Cannot transit from '{actual_value}' to '{value}'."
.format(actual_value=self.actual_s... |
Generate getter for given value.
def generate_getter(value):
"""Generate getter for given value."""
@property
@wraps(is_)
def getter(self):
return self.is_(value)
return getter |
Generate state checker for given value.
def generate_checker(value):
"""Generate state checker for given value."""
@property
@wraps(can_be_)
def checker(self):
return self.can_be_(value)
return checker |
Generate setter for given value.
def generate_setter(value):
"""Generate setter for given value."""
@wraps(set_)
def setter(self):
self.set_(value)
return setter |
Translate value to enum instance.
If value is already enum instance, check if this value belongs to base
enum.
def translate(self, value):
"""Translate value to enum instance.
If value is already enum instance, check if this value belongs to base
enum.
"""
if ... |
Takes natural language text and information as query parameters and returns information as JSON.
def _query(self, text):
"""
Takes natural language text and information as query parameters and returns information as JSON.
"""
params = (
('v', self.api_version),
(... |
Check whether if this workspace is a virtualenv.
def is_venv():
"""Check whether if this workspace is a virtualenv.
"""
dir_path = os.path.dirname(SRC)
is_venv_flag = True
if SYS_NAME == "Windows":
executable_list = ["activate", "pip.exe", "python.exe"]
elif SYS_NAME in ["Darwin", "Lin... |
Find python version name used in this virtualenv.
For example: ``python2.7``, ``python3.4``
def find_linux_venv_py_version():
"""Find python version name used in this virtualenv.
For example: ``python2.7``, ``python3.4``
"""
available_python_version = [
"python2.6",
"python2.7",
... |
Find where this package should be installed to in this virtualenv.
For example: ``/path-to-venv/lib/python2.7/site-packages/package-name``
def find_venv_DST():
"""Find where this package should be installed to in this virtualenv.
For example: ``/path-to-venv/lib/python2.7/site-packages/package-name``
... |
Find where this package should be installed to.
def find_DST():
"""Find where this package should be installed to.
"""
if SYS_NAME == "Windows":
return os.path.join(site.getsitepackages()[1], PKG_NAME)
elif SYS_NAME in ["Darwin", "Linux"]:
return os.path.join(site.getsitepackages()[0], ... |
Md5 value of a file.
def md5_of_file(abspath):
"""Md5 value of a file.
"""
chunk_size = 1024 * 1024
m = hashlib.md5()
with open(abspath, "rb") as f:
while True:
data = f.read(chunk_size)
if not data:
break
m.update(data)
return m.hexdi... |
Check if installed package are exactly the same to this one.
By checking md5 value of all files.
def check_need_install():
"""Check if installed package are exactly the same to this one.
By checking md5 value of all files.
"""
need_install_flag = False
for root, _, basename_list in os.walk(SRC)... |
Manual install main script.
def install():
"""Manual install main script.
"""
# check installed package
print("Compare to '%s' ..." % DST)
need_install_flag = check_need_install()
if not need_install_flag:
print(" package is up-to-date, no need to install.")
return
print(... |
Authorize to the docker registry using the given credentials and token scope, and returns a set
of required aiohttp.ClientSession.request() keyword arguments for further API requests.
Some registry servers only rely on HTTP Basic Authentication without token-based access controls
(usually via nginx proxy).... |
Return True if this is a git repo.
def is_git(path):
"""Return True if this is a git repo."""
try:
repo_dir = run_cmd(path, 'git', 'rev-parse', '--git-dir')
return True if repo_dir else False
except (OSError, RuntimeError):
return False |
Generate a version string based on the SCM type and the date.
def date_version(scm=None):
"""Generate a version string based on the SCM type and the date."""
dt = str(time.strftime('%Y%m%d%H%M'))
if scm:
version = "0.0+unknown.{0}.{1}".format(scm, dt)
else:
version = "0.0+unknown." + dt... |
Get the git branch name of the current HEAD in path. The branch name is
scrubbed to conform to PEP-440.
PEP-440 Local version identifiers shall only consist out of:
- ASCII letters ( [a-zA-Z] )
- ASCII digits ( [0-9] )
- periods ( . )
https://www.python.org/dev/peps/pep-0440/#local-version-iden... |
Get the GIT version.
def get_git_version(path):
"""Get the GIT version."""
branch_name = get_git_cleaned_branch_name(path)
# Determine whether working copy is dirty (i.e. contains modified files)
mods = run_cmd(path, 'git', 'status', '--porcelain', '--untracked-files=no')
dirty = '.dirty' if mods e... |
Get the current version string of this package using SCM tool.
Parameters
----------
path : None or string, optional
The SCM checkout path (default is current directory)
Returns
-------
version : string
The version string for this package
def get_version_from_scm(path=None):
... |
Use pkg_resources to get version of installed module by name.
def get_version_from_module(module):
"""Use pkg_resources to get version of installed module by name."""
if module is not None:
# Setup.py will not pass in a module, but creating __version__ from
# __init__ will.
module = str... |
Copied from pkginfo 1.4.1, _compat module.
def _must_decode(value):
"""Copied from pkginfo 1.4.1, _compat module."""
if type(value) is bytes:
try:
return value.decode('utf-8')
except UnicodeDecodeError:
return value.decode('latin1')
return value |
Assume path points to unpacked source distribution and get version.
def get_version_from_unpacked_sdist(path):
"""Assume path points to unpacked source distribution and get version."""
# This is a condensed version of the relevant code in pkginfo 1.4.1
try:
with open(os.path.join(path, 'PKG-INFO'))... |
Find the VERSION_FILE and return its contents.
Returns
-------
version : string or None
def get_version_from_file(path):
"""Find the VERSION_FILE and return its contents.
Returns
-------
version : string or None
"""
filename = os.path.join(path, VERSION_FILE)
if not os.path.i... |
Normalise a version string according to PEP 440, if possible.
def normalised(version):
"""Normalise a version string according to PEP 440, if possible."""
norm_version = pkg_resources.parse_version(version)
if not isinstance(norm_version, tuple):
# Let setuptools (>= 8) do the normalisation
... |
Return the version string.
This function ensures that the version string complies with PEP 440.
The format of our version string is:
- for RELEASE builds:
<major>.<minor>
e.g.
0.1
2.4
- for DEVELOPMENT builds:
<major>.<minor>.dev<num_b... |
Ensure the major and minor are int.
Parameters
----------
version: list
Version components
Returns
-------
version: list
List of components where first two components has been sanitised
def _sane_version_list(version):
"""Ensure the major and minor are int.
Parameters... |
Return the version information as a tuple.
This uses get_version and breaks the string up. Would make more sense if
the version was a tuple throughout katversion.
def get_version_list(path=None, module=None):
"""Return the version information as a tuple.
This uses get_version and breaks the string up... |
Return the build info tuple.
def build_info(name, path=None, module=None):
"""Return the build info tuple."""
verlist = get_version_list(path, module)
verlist[0] = name
return tuple(verlist) |
return all of the indices of particles of groupid
def find(self, groupid):
""" return all of the indices of particles of groupid """
return self.indices[self.offset[groupid]
:self.offset[groupid]+ self.length[groupid]] |
return the sum of weights of each object
def sum(self, weights=None):
""" return the sum of weights of each object """
if weights is None:
weights = self.data.weights
return utils.bincount(self.labels, weights, self.N) |
return the center of each object
def center(self, weights=None):
""" return the center of each object """
if weights is None:
weights = self.data.weights
mass = utils.bincount(self.labels, weights, self.N)
cp = numpy.empty((len(mass), self.data.pos.shape[-1]), 'f8')
... |
Return the rows of sampleDF that are associated to the parameter
specified in paramName.
def getParamValues(self, paramName=None, paramId=None, useOnlyValids=True):
"""
Return the rows of sampleDF that are associated to the parameter
specified in paramName.
"""
... |
interpValues should be a dictionnary where the keys are the parameter names
for the independant variable for which interpolation should be run and
the values are the value to which the parameter should be interpolated.
def interpolate(self, interpValues):
"""
interpValues should be a di... |
Compares two models using pointwise approximate leave-one-out cross validation.
For the method to be valid, the two models should have been fit on the same input data.
Parameters
-------------------
psisloo1 : Psisloo object for model1
psisloo2 : Psisloo object for model2
Returns
---... |
Graphical summary of pointwise pareto-k importance-sampling indices
Pareto-k tail indices are plotted (on the y axis) for each observation unit (on the x axis)
def plot(self):
""" Graphical summary of pointwise pareto-k importance-sampling indices
Pareto-k tail indices are plotted (on the y a... |
provide another way to define the layers (stack)
Parameters:
===========
formula: string
ex: 'CoAg2'
ex: 'Al'
thickness: float (in mm)
density: float (g/cm3)
def add_layer(self, formula='', thickness=np.NaN, density=np.NaN):
"""provide another way ... |
returns the list of isotopes for the element of the compound defined with their stoichiometric values
Parameters:
===========
compound: string (default is empty). If empty, all the stoichiometric will be displayed
element: string (default is same as compound).
Raises:
=... |
defines the new set of ratio of the compound/element and trigger the calculation to update the density
Parameters:
===========
compound: string (default is ''). Name of compound
element: string (default is ''). Name of element
list_ratio: list (default is []). list of new stoich... |
returns the list of isotopes for the element of the compound defined with their density
Parameters:
===========
compound: string (default is empty). If empty, all the stoichiometric will be displayed
element: string (default is same as compound).
Raises:
=======
... |
will perform all the various update of the stack, such as populating the stack_sigma, caluclate the density of the
layers....etc.
def __math_on_stack(self, used_lock=False):
"""will perform all the various update of the stack, such as populating the stack_sigma, caluclate the density of the
lay... |
lock (True) the density lock if the density has been been defined during initialization
Store the resulting dictionary into density_lock
Parameters:
===========
stack: dictionary (optional)
if not provided, the entire stack will be used
def __lock_density_if_defined(self, sta... |
calculate for each element, the atoms per cm3
def __calculate_atoms_per_cm3(self, used_lock=False):
"""calculate for each element, the atoms per cm3"""
stack = self.stack
_density_lock = self.density_lock
for _name_of_compound in stack.keys():
if used_lock and _density_lock... |
retrieve the isotopes, isotopes file names, mass and atomic_ratio from each element in stack
def __update_stack_with_isotopes_infos(self, stack: dict):
"""retrieve the isotopes, isotopes file names, mass and atomic_ratio from each element in stack"""
for _key in stack:
_elements = stack[_ke... |
calculate or update the layer density
def __update_layer_density(self):
"""calculate or update the layer density"""
_stack = self.stack
_density_lock = self.density_lock
list_compound = _stack.keys()
for _key in list_compound:
if _density_lock[_key]:
... |
Re-calculate the density of the element given due to stoichiometric changes as
well as the compound density (if density is not locked)
Parameters:
===========
compound: string (default is '') name of compound
element: string (default is '') name of element
def __update_density(... |
Re-calculate the molar mass of the element given due to stoichiometric changes
Parameters:
==========
compound: string (default is '') name of compound
element: string (default is '') name of element
def __update_molar_mass(self, compound='', element=''):
"""Re-calculate the mo... |
will populate the stack_sigma dictionary with the energy and sigma array
for all the compound/element and isotopes
def __get_sigmas(self):
"""will populate the stack_sigma dictionary with the energy and sigma array
for all the compound/element and isotopes"""
stack_sigma = {}
_s... |
display the transmission or attenuation of compound, element and/or isotopes specified
Parameters:
===========
:param x_axis: x type for export. Must be either ['energy'|'lambda'|'time'|'number']
:type x_axis: str
:param y_axis: y type for export. Must be either ['transmission'|... |
output x and y values to clipboard or .csv file
output the transmission or attenuation or sigma of compound, element and/or isotopes specified
'sigma_b' exported for each isotope is the product resulted from (sigma * isotopic ratio)
'atoms_per_cm3' of each element is also exported in 'sigma' mod... |
Builds a yaml file
def main():
"""Builds a yaml file"""
parser = argparse.ArgumentParser(description='Compose a yaml file.')
parser.add_argument(
'root',
type=argparse.FileType('r'),
help='The root yaml file to compose.'
)
args = parser.parse_args()
result = yaml.load(... |
Returns a date, datetime or time depending on what information is available
def _parse(self, text, mode):
"""
Returns a date, datetime or time depending on what information is available
"""
if text is None or not text.strip():
return None
# first try to parse as an ... |
Gets possible component sequences in the given mode
:param mode: the mode
:param length: the length (only returns sequences of this length)
:param date_style: whether dates are usually entered day first or month first
:return:
def _get_possible_sequences(cls, mode, length, date_style):
... |
Returns all possible component types of a token without regard to its context. For example "26" could be year,
date or minute, but can't be a month or an hour.
:param token: the token to classify
:param mode: the parse mode
:return: the dict of possible types and values if token was of t... |
Makes a date or datetime or time object from a map of component values
:param values: the component values
:param now: the current now
:param timezone: the current timezone
:return: the date, datetime, time or none if values are invalid
def _make_result(cls, values, now, timezone):
... |
Converts a relative 2-digit year to an absolute 4-digit year
:param short_year: the relative year
:param current_year: the current year
:return: the absolute year
def _year_from_2digits(short_year, current_year):
"""
Converts a relative 2-digit year to an absolute 4-digit year
... |
Create black/white lists and default / project waivers
and iterates over patchset file
def prepare_patchset(project, patchset, binaries, ips, urls):
""" Create black/white lists and default / project waivers
and iterates over patchset file """
# Get Various Lists / Project Waivers
lists = g... |
Scan actions for each commited file in patch set
def scan_patch(project, patch_file, binaries, ips, urls, file_audit_list,
file_audit_project_list, flag_list, ignore_list, file_ignore,
ignore_directories, url_ignore, ip_ignore, apikey):
"""
Scan actions for each commited file in ... |
Sends Binary (sha256hash) to Virus Total API
def scan_binary(patch_file, project, sha256hash, apikey):
"""
Sends Binary (sha256hash) to Virus Total API
"""
v_api = virus_total.VirusTotal()
while True:
binary_report = v_api.binary_report(sha256hash, apikey)
response_code = binary_re... |
If no match is made and file is clean
def negative_report(binary_report, sha256hash, project, patch_file):
"""
If no match is made and file is clean
"""
report_url = binary_report['permalink']
scan_date = binary_report['scan_date']
logger.info('File scan date for %s shows a clean status on: %s'... |
If a Positive match is found
def positive_report(binary_report, sha256hash, project, patch_file):
"""
If a Positive match is found
"""
failure = True
report_url = binary_report['permalink']
scan_date = binary_report['scan_date']
logger.error("Virus Found!")
logger.info('File scan date f... |
If an IP Address is found, scan it
def scan_ipaddr(ipaddr, apikey):
"""
If an IP Address is found, scan it
"""
logger.info('Query VirusTotal API for Public IP Found: %s', ipaddr)
v_api = virus_total.VirusTotal()
scan_ip = v_api.send_ip(ipaddr, apikey)
response_code = scan_ip['response_code'... |
If URL is found, scan it
def scan_url(url, apikey):
"""
If URL is found, scan it
"""
logger.info('Found what I believe is a URL: %s', url)
v_api = virus_total.VirusTotal()
while True:
url_report = v_api.url_report(url, apikey)
response_code = url_report['response_code']
... |
If any scan operations register a failure, sys.exit(1) is called
to allow build to register a failure
def process_failure(project):
"""
If any scan operations register a failure, sys.exit(1) is called
to allow build to register a failure
"""
if failure:
lists = get_lists.GetLists()
... |
Compute average gradient norm of an image
def average_gradient(data, *kwargs):
""" Compute average gradient norm of an image
"""
return np.average(np.array(np.gradient(data))**2) |
Compute RMS contrast norm of an image
def contrast_rms(data, *kwargs):
""" Compute RMS contrast norm of an image
"""
av = np.average(data, *kwargs)
mal = 1 / (data.shape[0] * data.shape[1])
return np.sqrt(mal * np.sum(np.square(data - av))) |
Compute spectral contrast of image
Performs bandpass filtering in Fourier space according to optical
limit of detection system, approximated by twice the wavelength.
Parameters
----------
data : 2d ndarray
the image to compute the norm from
lambd : float
wavelength of the ligh... |
Parse file extension.
- *.json: uncompressed, utf-8 encode json file
- *.gz: compressed, utf-8 encode json file
def is_gzip_file(abspath):
"""Parse file extension.
- *.json: uncompressed, utf-8 encode json file
- *.gz: compressed, utf-8 encode json file
"""
abspath = abspath.lower()
_... |
Write string to text file.
def write(s, path, encoding="utf-8"):
"""Write string to text file.
"""
is_gzip = is_gzip_file(path)
with open(path, "wb") as f:
if is_gzip:
f.write(zlib.compress(s.encode(encoding)))
else:
f.write(s.encode(encoding)) |
Read string from text file.
def read(path, encoding="utf-8"):
"""Read string from text file.
"""
is_gzip = is_gzip_file(path)
with open(path, "rb") as f:
if is_gzip:
return zlib.decompress(f.read()).decode(encoding)
else:
return f.read().decode(encoding) |
Read text from file, automatically detect encoding. ``chardet`` required.
def smartread(path):
"""Read text from file, automatically detect encoding. ``chardet`` required.
"""
with open(path, "rb") as f:
content = f.read()
result = chardet.detect(content)
return content.decode(resul... |
Convert any text file to utf8 encoding.
def to_utf8(path, output_path=None):
"""Convert any text file to utf8 encoding.
"""
if output_path is None:
basename, ext = os.path.splitext(path)
output_path = basename + "-UTF8Encode" + ext
text = smartread(path)
write(text, output_path... |
skip n lines and fetch the next n lines.
:param skiplines: default None, skip first n lines
:param nlines: default None, yield next n lines
:param strip: default None, available option 'left', 'right', 'both'
**中文文档**
跳过前#skiplines行, 然后读取#nlines行。可对字符串进行strip预处理。
def readlines(path, ... |
skip n lines and fetch the next n lines as a chunk, and repeat fetching.
:param skiplines: default None, skip first n lines
:param chunksize: default None (size-1 chunk), lines chunk size
:param strip: default None, avaliable option 'left', 'right', 'both'
**中文文档**
跳过前#skiplines行, 每次读... |
Since we let users populate the context with whatever they want, this ensures the resolved value is something
which the expression engine understands.
:param value: the resolved value
:return: the value converted to a supported data type
def _coerce_to_supported_type(cls, value):
"""
... |
Evaluates a template string, e.g. "Hello @contact.name you have @(contact.reports * 2) reports"
:param template: the template string
:param context: the evaluation context
:param url_encode: whether or not values should be URL encoded
:return: a tuple of the evaluated template and a list... |
Resolves an expression block found in the template, e.g. @(...). If an evaluation error occurs, expression is
returned as is.
def _resolve_expression_block(self, expression, context, url_encode, strategy, errors):
"""
Resolves an expression block found in the template, e.g. @(...). If an evalua... |
Evaluates a single expression, e.g. "contact.reports * 2"
:param expression: the expression string
:param context: the evaluation context
:param strategy: the evaluation strategy
:return: the evaluated expression value
def evaluate_expression(self, expression, context, strategy=Evaluati... |
Checks the token stream for context references and if there are missing references - substitutes available
references and returns a partially evaluated expression.
:param tokens: the token stream (all tokens fetched)
:param context: the evaluation context
:return: the partially evaluated... |
expression : fnname LPAREN parameters? RPAREN
def visitFunctionCall(self, ctx):
"""
expression : fnname LPAREN parameters? RPAREN
"""
func_name = ctx.fnname().getText()
if ctx.parameters() is not None:
parameters = self.visit(ctx.parameters())
else:
... |
expression: MINUS expression
def visitNegation(self, ctx):
"""
expression: MINUS expression
"""
return -conversions.to_decimal(self.visit(ctx.expression()), self._eval_context) |
expression: expression EXPONENT expression
def visitExponentExpression(self, ctx):
"""
expression: expression EXPONENT expression
"""
arg1 = conversions.to_decimal(self.visit(ctx.expression(0)), self._eval_context)
arg2 = conversions.to_decimal(self.visit(ctx.expression(1)), sel... |
expression: expression (TIMES | DIVIDE) expression
def visitMultiplicationOrDivisionExpression(self, ctx):
"""
expression: expression (TIMES | DIVIDE) expression
"""
is_mul = ctx.TIMES() is not None
arg1 = conversions.to_decimal(self.visit(ctx.expression(0)), self._eval_context... |
expression: expression (PLUS | MINUS) expression
def visitAdditionOrSubtractionExpression(self, ctx):
"""
expression: expression (PLUS | MINUS) expression
"""
is_add = ctx.PLUS() is not None
arg1 = self.visit(ctx.expression(0))
arg2 = self.visit(ctx.expression(1))
... |
expression: expression (LTE | LT | GTE | GT) expression
def visitComparisonExpression(self, ctx):
"""
expression: expression (LTE | LT | GTE | GT) expression
"""
arg1, arg2 = conversions.to_same(self.visit(ctx.expression(0)), self.visit(ctx.expression(1)), self._eval_context)
i... |
expression: expression (EQ | NEQ) expression
def visitEqualityExpression(self, ctx):
"""
expression: expression (EQ | NEQ) expression
"""
arg1, arg2 = conversions.to_same(self.visit(ctx.expression(0)), self.visit(ctx.expression(1)), self._eval_context)
if isinstance(arg1, str):... |
expression: expression AMPERSAND expression
def visitConcatenation(self, ctx):
"""
expression: expression AMPERSAND expression
"""
arg1 = conversions.to_string(self.visit(ctx.expression(0)), self._eval_context)
arg2 = conversions.to_string(self.visit(ctx.expression(1)), self._ev... |
expression: NAME
def visitContextReference(self, ctx):
"""
expression: NAME
"""
identifier = ctx.NAME().getText()
return self._eval_context.resolve_variable(identifier) |
Load the cached Zotero data.
def load_cache(self):
"""Load the cached Zotero data."""
with open(self.cache_path, "rb") as f:
print("Loading cached Zotero data...")
cache = pickle.load(f)
self._references = cache[self.CACHE_REFERENCE_LIST]
self.reference_t... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.