INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Check arguments passed by user that are not checked by argparse itself. | def check_arguments(args, parser):
"""Check arguments passed by user that are not checked by argparse itself."""
if args.asm_block not in ['auto', 'manual']:
try:
args.asm_block = int(args.asm_block)
except ValueError:
parser.error('--asm-block can only be "auto", "manual... |
Run command line interface. | def run(parser, args, output_file=sys.stdout):
"""Run command line interface."""
# Try loading results file (if requested)
result_storage = {}
if args.store:
args.store.seek(0)
try:
result_storage = pickle.load(args.store)
except EOFError:
pass
arg... |
Initialize and run command line interface. | def main():
"""Initialize and run command line interface."""
# Create and populate parser
parser = create_parser()
# Parse given arguments
args = parser.parse_args()
# Checking arguments
check_arguments(args, parser)
# BUSINESS LOGIC IS FOLLOWING
run(parser, args) |
Comand line interface of picklemerge. | def main():
"""Comand line interface of picklemerge."""
parser = argparse.ArgumentParser(
description='Recursively merges two or more pickle files. Only supports pickles consisting '
'of a single dictionary object.')
parser.add_argument('destination', type=argparse.FileType('r+b'),
... |
Create a sympy. Symbol with positive and integer assumptions. | def symbol_pos_int(*args, **kwargs):
"""Create a sympy.Symbol with positive and integer assumptions."""
kwargs.update({'positive': True,
'integer': True})
return sympy.Symbol(*args, **kwargs) |
Prefix and indent all lines in * textblock *. | def prefix_indent(prefix, textblock, later_prefix=' '):
"""
Prefix and indent all lines in *textblock*.
*prefix* is a prefix string
*later_prefix* is used on all but the first line, if it is a single character
it will be repeated to match length of *prefix*
"""
textblock = te... |
Transform ast of multidimensional declaration to a single dimension declaration. | def transform_multidim_to_1d_decl(decl):
"""
Transform ast of multidimensional declaration to a single dimension declaration.
In-place operation!
Returns name and dimensions of array (to be used with transform_multidim_to_1d_ref())
"""
dims = []
type_ = decl.type
while type(type_) is c... |
Transform ast of multidimensional reference to a single dimension reference. | def transform_multidim_to_1d_ref(aref, dimension_dict):
"""
Transform ast of multidimensional reference to a single dimension reference.
In-place operation!
"""
dims = []
name = aref
while type(name) is c_ast.ArrayRef:
dims.append(name.subscript)
name = name.name
subscr... |
Transform ast of type var_name [ N ] to type * var_name = aligned_malloc ( sizeof ( type ) * N 32 ) | def transform_array_decl_to_malloc(decl, with_init=True):
"""
Transform ast of "type var_name[N]" to "type* var_name = aligned_malloc(sizeof(type)*N, 32)"
In-place operation.
:param with_init: if False, ommit malloc
"""
if type(decl.type) is not c_ast.ArrayDecl:
# Not an array declarat... |
Return list of array references in AST. | def find_node_type(ast, node_type):
"""Return list of array references in AST."""
if type(ast) is node_type:
return [ast]
elif type(ast) is list:
return reduce(operator.add, list(map(lambda a: find_node_type(a, node_type), ast)), [])
elif ast is None:
return []
else:
... |
Will make any functions return an iterable objects by wrapping its result in a list. | def force_iterable(f):
"""Will make any functions return an iterable objects by wrapping its result in a list."""
def wrapper(*args, **kwargs):
r = f(*args, **kwargs)
if hasattr(r, '__iter__'):
return r
else:
return [r]
return wrapper |
Reduce absolute path to relative ( if shorter ) for easier readability. | def reduce_path(path):
"""Reduce absolute path to relative (if shorter) for easier readability."""
relative_path = os.path.relpath(path)
if len(relative_path) < len(path):
return relative_path
else:
return path |
Check that information about kernel makes sens and is valid. | def check(self):
"""Check that information about kernel makes sens and is valid."""
datatypes = [v[0] for v in self.variables.values()]
assert len(set(datatypes)) <= 1, 'mixing of datatypes within a kernel is not supported.' |
Set constant of name to value. | def set_constant(self, name, value):
"""
Set constant of name to value.
:param name: may be a str or a sympy.Symbol
:param value: must be an int
"""
assert isinstance(name, str) or isinstance(name, sympy.Symbol), \
"constant name needs to be of type str, unic... |
Register variable of name and type_ with a ( multidimensional ) size. | def set_variable(self, name, type_, size):
"""
Register variable of name and type_, with a (multidimensional) size.
:param name: variable name as it appears in code
:param type_: may be any key from Kernel.datatypes_size (typically float or double)
:param size: either None for s... |
Substitute constants in expression unless it is already a number. | def subs_consts(self, expr):
"""Substitute constants in expression unless it is already a number."""
if isinstance(expr, numbers.Number):
return expr
else:
return expr.subs(self.constants) |
Return a dictionary with all arrays sizes. | def array_sizes(self, in_bytes=False, subs_consts=False):
"""
Return a dictionary with all arrays sizes.
:param in_bytes: If True, output will be in bytes, not element counts.
:param subs_consts: If True, output will be numbers and not symbolic.
Scalar variables are ignored.
... |
Return the offset from the iteration center in number of elements. | def _calculate_relative_offset(self, name, access_dimensions):
"""
Return the offset from the iteration center in number of elements.
The order of indices used in access is preserved.
"""
# TODO to be replaced with compile_global_offsets
offset = 0
base_dims = se... |
Remove duplicate source and destination accesses | def _remove_duplicate_accesses(self):
"""
Remove duplicate source and destination accesses
"""
self.destinations = {var_name: set(acs) for var_name, acs in self.destinations.items()}
self.sources = {var_name: set(acs) for var_name, acs in self.sources.items()} |
Transform a ( multidimensional ) variable access to a flattend sympy expression. | def access_to_sympy(self, var_name, access):
"""
Transform a (multidimensional) variable access to a flattend sympy expression.
Also works with flat array accesses.
"""
base_sizes = self.variables[var_name][1]
expr = sympy.Number(0)
for dimension, a in enumerat... |
Return the number of global loop iterations that are performed. | def iteration_length(self, dimension=None):
"""
Return the number of global loop iterations that are performed.
If dimension is not None, it is the loop dimension that is returned
(-1 is the inner most loop and 0 the outermost)
"""
total_length = 1
if dimension ... |
Yield loop stack dictionaries in order from outer to inner. | def get_loop_stack(self, subs_consts=False):
"""Yield loop stack dictionaries in order from outer to inner."""
for l in self._loop_stack:
if subs_consts:
yield {'index': l[0],
'start': self.subs_consts(l[1]),
'stop': self.subs_con... |
Return the order of indices as they appear in array references. | def index_order(self, sources=True, destinations=True):
"""
Return the order of indices as they appear in array references.
Use *source* and *destination* to filter output
"""
if sources:
arefs = chain(*self.sources.values())
else:
arefs = []
... |
Return a dictionary of lists of sympy accesses for each variable. | def compile_sympy_accesses(self, sources=True, destinations=True):
"""
Return a dictionary of lists of sympy accesses, for each variable.
Use *source* and *destination* to filter output
"""
sympy_accesses = defaultdict(list)
# Compile sympy accesses
for var_name ... |
Return load and store distances between accesses. | def compile_relative_distances(self, sympy_accesses=None):
"""
Return load and store distances between accesses.
:param sympy_accesses: optionally restrict accesses, default from compile_sympy_accesses()
e.g. if accesses are to [+N, +1, -1, -N], relative distances are [N-1, 2, N-1]
... |
Return sympy expressions translating global_iterator to loop indices. | def global_iterator_to_indices(self, git=None):
"""
Return sympy expressions translating global_iterator to loop indices.
If global_iterator is given, an integer is returned
"""
# unwind global iteration count into loop counters:
base_loop_counters = {}
global_it... |
Return global iterator sympy expression | def global_iterator(self):
"""
Return global iterator sympy expression
"""
global_iterator = sympy.Integer(0)
total_length = sympy.Integer(1)
for var_name, start, end, incr in reversed(self._loop_stack):
loop_var = symbol_pos_int(var_name)
length =... |
Transform a dictionary of indices to a global iterator integer. | def indices_to_global_iterator(self, indices):
"""
Transform a dictionary of indices to a global iterator integer.
Inverse of global_iterator_to_indices().
"""
global_iterator = self.subs_consts(self.global_iterator().subs(indices))
return global_iterator |
Return global iterator with last iteration number | def max_global_iteration(self):
"""Return global iterator with last iteration number"""
return self.indices_to_global_iterator({
symbol_pos_int(var_name): end-1 for var_name, start, end, incr in self._loop_stack
}) |
Return load and store offsets on a virtual address space. | def compile_global_offsets(self, iteration=0, spacing=0):
"""
Return load and store offsets on a virtual address space.
:param iteration: controls the inner index counter
:param spacing: sets a spacing between the arrays, default is 0
All array variables (non scalars) are laid ... |
Consecutive bytes written out per high - level iterations ( as counted by loop stack ). | def bytes_per_iteration(self):
"""
Consecutive bytes written out per high-level iterations (as counted by loop stack).
Is used to compute number of iterations per cacheline.
"""
# TODO Find longst consecutive writes to any variable and use as basis
var_name = list(self.d... |
Print kernel information in human readble format. | def print_kernel_info(self, output_file=sys.stdout):
"""Print kernel information in human readble format."""
table = (' idx | min max step\n' +
'---------+---------------------------------\n')
for l in self._loop_stack:
table += '{:>8} | {!r:>... |
Print variables information in human readble format. | def print_variables_info(self, output_file=sys.stdout):
"""Print variables information in human readble format."""
table = (' name | type size \n' +
'---------+-------------------------\n')
for name, var_info in list(self.variables.items()):
table +=... |
Print constants information in human readble format. | def print_constants_info(self, output_file=sys.stdout):
"""Print constants information in human readble format."""
table = (' name | value \n' +
'---------+-----------\n')
for name, value in list(self.constants.items()):
table += '{!s:>8} | {:<10}\n'.format(na... |
Create or open intermediate file ( may be used for caching ). | def _get_intermediate_file(self, name, machine_and_compiler_dependent=True, binary=False,
fp=True):
"""
Create or open intermediate file (may be used for caching).
Will replace files older than kernel file, machine file or kerncraft version.
:param machin... |
Print source code of kernel. | def print_kernel_code(self, output_file=sys.stdout):
"""Print source code of kernel."""
print(self.kernel_code, file=output_file) |
Convert mathematical expressions to a sympy representation. | def conv_ast_to_sym(self, math_ast):
"""
Convert mathematical expressions to a sympy representation.
May only contain paranthesis, addition, subtraction and multiplication from AST.
"""
if type(math_ast) is c_ast.ID:
return symbol_pos_int(math_ast.name)
elif ... |
Return a tuple of offsets of an ArrayRef object in all dimensions. | def _get_offsets(self, aref, dim=0):
"""
Return a tuple of offsets of an ArrayRef object in all dimensions.
The index order is right to left (c-code order).
e.g. c[i+1][j-2] -> (-2, +1)
If aref is actually a c_ast.ID, None will be returned.
"""
if isinstance(are... |
Return base name of ArrayRef object. | def _get_basename(cls, aref):
"""
Return base name of ArrayRef object.
e.g. c[i+1][j-2] -> 'c'
"""
if isinstance(aref.name, c_ast.ArrayRef):
return cls._get_basename(aref.name)
elif isinstance(aref.name, str):
return aref.name
else:
... |
Return index type used in loop nest. | def get_index_type(self, loop_nest=None):
"""
Return index type used in loop nest.
If index type between loops differ, an exception is raised.
"""
if loop_nest is None:
loop_nest = self.get_kernel_loop_nest()
if type(loop_nest) is c_ast.For:
loop_... |
Generate constants declarations | def _build_const_declartions(self, with_init=True):
"""
Generate constants declarations
:return: list of declarations
"""
decls = []
# Use type as provided by user in loop indices
index_type = self.get_index_type()
i = 2 # subscript for cli input, 1 is... |
Return array declarations. | def get_array_declarations(self):
"""Return array declarations."""
return [d for d in self.kernel_ast.block_items
if type(d) is c_ast.Decl and type(d.type) is c_ast.ArrayDecl] |
Return kernel loop nest including any preceding pragmas and following swaps. | def get_kernel_loop_nest(self):
"""Return kernel loop nest including any preceding pragmas and following swaps."""
loop_nest = [s for s in self.kernel_ast.block_items
if type(s) in [c_ast.For, c_ast.Pragma, c_ast.FuncCall]]
assert len(loop_nest) >= 1, "Found to few for state... |
Generate declaration statements for arrays. | def _build_array_declarations(self, with_init=True):
"""
Generate declaration statements for arrays.
Also transforming multi-dim to 1d arrays and initializing with malloc.
:param with_init: ommit malloc initialization
:return: list of declarations nodes, dictionary of array na... |
Return inner most for loop in loop nest | def _find_inner_most_loop(self, loop_nest):
"""Return inner most for loop in loop nest"""
r = None
for s in loop_nest:
if type(s) is c_ast.For:
return self._find_inner_most_loop(s) or s
else:
r = r or self._find_inner_most_loop(s)
r... |
Generate initialization statements for arrays. | def _build_array_initializations(self, array_dimensions):
"""
Generate initialization statements for arrays.
:param array_dimensions: dictionary of array dimensions
:return: list of nodes
"""
kernel = deepcopy(deepcopy(self.get_kernel_loop_nest()))
# traverse to... |
Generate false if branch with dummy calls | def _build_dummy_calls(self):
"""
Generate false if branch with dummy calls
Requires kerncraft.h to be included, which defines dummy(...) and var_false.
:return: dummy statement
"""
# Make sure nothing gets removed by inserting dummy calls
dummy_calls = []
... |
Build and return kernel function declaration | def _build_kernel_function_declaration(self, name='kernel'):
"""Build and return kernel function declaration"""
array_declarations, array_dimensions = self._build_array_declarations(with_init=False)
scalar_declarations = self._build_scalar_declarations(with_init=False)
const_declarations... |
Build and return scalar variable declarations | def _build_scalar_declarations(self, with_init=True):
"""Build and return scalar variable declarations"""
# copy scalar declarations from from kernel ast
scalar_declarations = [deepcopy(d) for d in self.kernel_ast.block_items
if type(d) is c_ast.Decl and type(d.typ... |
Generate and return compilable source code with kernel function from AST. | def get_kernel_code(self, openmp=False, as_filename=False, name='kernel'):
"""
Generate and return compilable source code with kernel function from AST.
:param openmp: if true, OpenMP code will be generated
:param as_filename: if true, will save to file and return filename
:para... |
Generate and return kernel call ast. | def _build_kernel_call(self, name='kernel'):
"""Generate and return kernel call ast."""
return c_ast.FuncCall(name=c_ast.ID(name=name), args=c_ast.ExprList(exprs=[
c_ast.ID(name=d.name) for d in (
self._build_array_declarations()[0] +
self._build_scala... |
Generate and return compilable source code from AST. | def get_main_code(self, as_filename=False, kernel_function_name='kernel'):
"""
Generate and return compilable source code from AST.
"""
# TODO produce nicer code, including help text and other "comfort features".
assert self.kernel_ast is not None, "AST does not exist, this could... |
Assemble * in_filename * assembly into * out_filename * object. | def assemble_to_object(self, in_filename, verbose=False):
"""
Assemble *in_filename* assembly into *out_filename* object.
If *iaca_marked* is set to true, markers are inserted around the block with most packed
instructions or (if no packed instr. were found) the largest block and modifi... |
Compile source ( from as_code ( type_ )) to assembly or object and return ( fileptr filename ). | def compile_kernel(self, openmp=False, assembly=False, verbose=False):
"""
Compile source (from as_code(type_)) to assembly or object and return (fileptr, filename).
Output can be used with Kernel.assemble()
"""
compiler, compiler_args = self._machine.get_compiler()
in_... |
Run an IACA analysis and return its outcome. | def iaca_analysis(self, micro_architecture, asm_block='auto',
pointer_increment='auto_with_manual_fallback', verbose=False):
"""
Run an IACA analysis and return its outcome.
*asm_block* controls how the to-be-marked block is chosen. "auto" (default) results in
the ... |
Compile source to executable with likwid capabilities and return the executable name. | def build_executable(self, lflags=None, verbose=False, openmp=False):
"""Compile source to executable with likwid capabilities and return the executable name."""
compiler, compiler_args = self._machine.get_compiler()
kernel_obj_filename = self.compile_kernel(openmp=openmp, verbose=verbose)
... |
Convert any string to a sympy object or None. | def string_to_sympy(cls, s):
"""Convert any string to a sympy object or None."""
if isinstance(s, int):
return sympy.Integer(s)
elif isinstance(s, list):
return tuple([cls.string_to_sympy(e) for e in s])
elif s is None:
return None
else:
... |
Return identifier which is either the machine file name or sha256 checksum of data. | def get_identifier(self):
"""Return identifier which is either the machine file name or sha256 checksum of data."""
if self._path:
return os.path.basename(self._path)
else:
return hashlib.sha256(hashlib.sha256(repr(self._data).encode())).hexdigest() |
Return datetime object of modified time of machine file. Return now if not a file. | def get_last_modified_datetime(self):
"""Return datetime object of modified time of machine file. Return now if not a file."""
if self._path:
statbuf = os.stat(self._path)
return datetime.utcfromtimestamp(statbuf.st_mtime)
else:
return datetime.now() |
Return a cachesim. CacheSimulator object based on the machine description. | def get_cachesim(self, cores=1):
"""
Return a cachesim.CacheSimulator object based on the machine description.
:param cores: core count (default: 1)
"""
cache_dict = {}
for c in self['memory hierarchy']:
# Skip main memory
if 'cache per group' not... |
Return best fitting bandwidth according to number of threads read and write streams. | def get_bandwidth(self, cache_level, read_streams, write_streams, threads_per_core, cores=None):
"""
Return best fitting bandwidth according to number of threads, read and write streams.
:param cache_level: integer of cache (0 is L1, 1 is L2 ...)
:param read_streams: number of read stre... |
Return tuple of compiler and compiler flags. | def get_compiler(self, compiler=None, flags=None):
"""
Return tuple of compiler and compiler flags.
Selects compiler and flags from machine description file, commandline arguments or call
arguements.
"""
if self._args:
compiler = compiler or self._args.compil... |
Parse events in machine description to tuple representation used in Benchmark module. | def parse_perfctr_event(perfctr):
"""
Parse events in machine description to tuple representation used in Benchmark module.
Examples:
>>> parse_perfctr_event('PERF_EVENT:REG[0-3]')
('PERF_EVENT', 'REG[0-3]')
>>> parse_perfctr_event('PERF_EVENT:REG[0-3]:STAY:FOO=23:BAR=0x... |
Return ( sympy expressions event names and symbols dict ) from performance metric str. | def parse_perfmetric(metric):
"""Return (sympy expressions, event names and symbols dict) from performance metric str."""
# Find all perfs counter references
perfcounters = re.findall(r'[A-Z0-9_]+:[A-Z0-9\[\]|\-]+(?::[A-Za-z0-9\-_=]+)*', metric)
# Build a temporary metric, with parser-f... |
Enforce that no ranges overlap in internal storage. | def _enforce_no_overlap(self, start_at=0):
"""Enforce that no ranges overlap in internal storage."""
i = start_at
while i+1 < len(self.data):
if self.data[i][1] >= self.data[i+1][0]:
# beginning of i+1-th range is contained in i-th range
if self.data[i... |
Return local folder path of header files. | def get_header_path() -> str:
"""Return local folder path of header files."""
import os
return os.path.abspath(os.path.dirname(os.path.realpath(__file__))) + '/headers/' |
Align iteration with cacheline boundary. | def _align_iteration_with_cl_boundary(self, iteration, subtract=True):
"""Align iteration with cacheline boundary."""
# FIXME handle multiple datatypes
element_size = self.kernel.datatypes_size[self.kernel.datatype]
cacheline_size = self.machine['cacheline size']
elements_per_cac... |
Return a list with number of loaded cache lines per memory hierarchy level. | def get_loads(self):
"""Return a list with number of loaded cache lines per memory hierarchy level."""
return [self.stats[cache_level]['LOAD_count'] / self.first_dim_factor
for cache_level in range(len(self.machine['memory hierarchy']))] |
Return a list with number of hit cache lines per memory hierarchy level. | def get_hits(self):
"""Return a list with number of hit cache lines per memory hierarchy level."""
return [self.stats[cache_level]['HIT_count']/self.first_dim_factor
for cache_level in range(len(self.machine['memory hierarchy']))] |
Return a list with number of missed cache lines per memory hierarchy level. | def get_misses(self):
"""Return a list with number of missed cache lines per memory hierarchy level."""
return [self.stats[cache_level]['MISS_count']/self.first_dim_factor
for cache_level in range(len(self.machine['memory hierarchy']))] |
Return a list with number of stored cache lines per memory hierarchy level. | def get_stores(self):
"""Return a list with number of stored cache lines per memory hierarchy level."""
return [self.stats[cache_level]['STORE_count']/self.first_dim_factor
for cache_level in range(len(self.machine['memory hierarchy']))] |
Return a list with number of evicted cache lines per memory hierarchy level. | def get_evicts(self):
"""Return a list with number of evicted cache lines per memory hierarchy level."""
return [self.stats[cache_level]['EVICT_count']/self.first_dim_factor
for cache_level in range(len(self.machine['memory hierarchy']))] |
Return verbose information about the predictor. | def get_infos(self):
"""Return verbose information about the predictor."""
first_dim_factor = self.first_dim_factor
infos = {'memory hierarchy': [], 'cache stats': self.stats,
'cachelines in stats': first_dim_factor}
for cache_level, cache_info in list(enumerate(self.mac... |
* size * is given in kilo bytes | def measure_bw(type_, total_size, threads_per_core, max_threads_per_core, cores_per_socket,
sockets):
"""*size* is given in kilo bytes"""
groups = []
for s in range(sockets):
groups += [
'-w',
'S' + str(s) + ':' + str(total_size) + 'kB:' +
str(threa... |
Fix environment variable to a value within context. Unset if value is None. | def fix_env_variable(name, value):
"""Fix environment variable to a value within context. Unset if value is None."""
orig = os.environ.get(name, None)
if value is not None:
# Set if value is not None
os.environ[name] = value
elif name in os.environ:
# Unset if value is None
... |
Configure argument parser. | def configure_arggroup(cls, parser):
"""Configure argument parser."""
parser.add_argument(
'--no-phenoecm', action='store_true',
help='Disables the phenomenological ECM model building.')
parser.add_argument(
'--iterations', type=int, default=10,
he... |
Run * cmd * with likwid - perfctr and returns result as dict. | def perfctr(self, cmd, group='MEM', code_markers=True):
"""
Run *cmd* with likwid-perfctr and returns result as dict.
*group* may be a performance group known to likwid-perfctr or an event string.
if CLI argument cores > 1, running with multi-core, otherwise single-core
"""
... |
Run analysis. | def analyze(self):
"""Run analysis."""
bench = self.kernel.build_executable(verbose=self.verbose > 1, openmp=self._args.cores > 1)
element_size = self.kernel.datatypes_size[self.kernel.datatype]
# Build arguments to pass to command:
args = [str(s) for s in list(self.kernel.const... |
Report gathered analysis data in human readable form. | def report(self, output_file=sys.stdout):
"""Report gathered analysis data in human readable form."""
if self.verbose > 1:
with pprint_nosort():
pprint.pprint(self.results)
if self.verbose > 0:
print('Runtime (per repetition): {:.2g} s'.format(
... |
Parse the description in the README file | def parse_description():
"""
Parse the description in the README file
CommandLine:
python -c "import setup; print(setup.parse_description())"
"""
from os.path import dirname, join, exists
readme_fpath = join(dirname(__file__), 'README.md')
# print('readme_fpath = %r' % (readme_fpath... |
Schedule a retry | def schedule_retry(self, config):
"""Schedule a retry"""
raise self.retry(countdown=config.get('SAILTHRU_RETRY_SECONDS'),
max_retries=config.get('SAILTHRU_RETRY_ATTEMPTS')) |
Build and return Sailthru purchase item object | def _build_purchase_item(course_id, course_url, cost_in_cents, mode, course_data, sku):
"""Build and return Sailthru purchase item object"""
# build item description
item = {
'id': "{}-{}".format(course_id, mode),
'url': course_url,
'price': cost_in_cents,
'qty': 1,
}
... |
Record a purchase in Sailthru | def _record_purchase(sailthru_client, email, item, purchase_incomplete, message_id, options):
"""Record a purchase in Sailthru
Arguments:
sailthru_client (object): SailthruClient
email (str): user's email address
item (dict): Sailthru required information about the course
purcha... |
Get course information using the Sailthru content api or from cache. | def _get_course_content(course_id, course_url, sailthru_client, site_code, config):
"""Get course information using the Sailthru content api or from cache.
If there is an error, just return with an empty response.
Arguments:
course_id (str): course key of the course
course_url (str): LMS u... |
Get course information using the Ecommerce course api. | def _get_course_content_from_ecommerce(course_id, site_code=None):
"""
Get course information using the Ecommerce course api.
In case of error returns empty response.
Arguments:
course_id (str): course key of the course
site_code (str): site code
Returns:
course information... |
Maintain a list of courses the user has unenrolled from in the Sailthru user record | def _update_unenrolled_list(sailthru_client, email, course_url, unenroll):
"""Maintain a list of courses the user has unenrolled from in the Sailthru user record
Arguments:
sailthru_client (object): SailthruClient
email (str): user's email address
course_url (str): LMS url for course in... |
Adds/ updates Sailthru when a user adds to cart/ purchases/ upgrades a course | def update_course_enrollment(self, email, course_url, purchase_incomplete, mode, unit_cost=None, course_id=None,
currency=None, message_id=None, site_code=None, sku=None):
"""Adds/updates Sailthru when a user adds to cart/purchases/upgrades a course
Args:
email(str): The u... |
Sends the course refund email. | def send_course_refund_email(self, email, refund_id, amount, course_name, order_number, order_url, site_code=None):
""" Sends the course refund email.
Args:
self: Ignore.
email (str): Recipient's email address.
refund_id (int): ID of the refund that initiated this task.
amount (... |
Sends the offer assignment email. Args: self: Ignore. user_email ( str ): Recipient s email address. offer_assignment_id ( str ): Key of the entry in the offer_assignment model. subject ( str ): Email subject. email_body ( str ): The body of the email. site_code ( str ): Identifier of the site sending the email. | def send_offer_assignment_email(self, user_email, offer_assignment_id, subject, email_body, site_code=None):
""" Sends the offer assignment email.
Args:
self: Ignore.
user_email (str): Recipient's email address.
offer_assignment_id (str): Key of the entry in the offer_assignment model.
... |
Handles sending offer assignment notification emails and retrying failed emails when appropriate. | def _send_offer_assignment_notification_email(config, user_email, subject, email_body, site_code, task):
"""Handles sending offer assignment notification emails and retrying failed emails when appropriate."""
try:
sailthru_client = get_sailthru_client(site_code)
except SailthruError:
logger.... |
Update the offer_assignment and offer_assignment_email model using the Ecommerce assignmentemail api. Arguments: offer_assignment_id ( str ): Key of the entry in the offer_assignment model. send_id ( str ): Unique message id from Sailthru status ( str ): status to be sent to the api site_code ( str ): site code Returns... | def _update_assignment_email_status(offer_assignment_id, send_id, status, site_code=None):
"""
Update the offer_assignment and offer_assignment_email model using the Ecommerce assignmentemail api.
Arguments:
offer_assignment_id (str): Key of the entry in the offer_assignment model.
send_id (... |
Sends the offer emails after assignment either for revoking or reminding. Args: self: Ignore. user_email ( str ): Recipient s email address. subject ( str ): Email subject. email_body ( str ): The body of the email. site_code ( str ): Identifier of the site sending the email. | def send_offer_update_email(self, user_email, subject, email_body, site_code=None):
""" Sends the offer emails after assignment, either for revoking or reminding.
Args:
self: Ignore.
user_email (str): Recipient's email address.
subject (str): Email subject.
email_body (str): The ... |
Returns a dictionary containing logging configuration. | def get_logger_config(log_dir='/var/tmp',
logging_env='no_env',
edx_filename='edx.log',
dev_env=False,
debug=False,
local_loglevel='INFO',
service_variant='ecomworker'):
"""
Retur... |
Retry with exponential backoff until fulfillment succeeds or the retry limit is reached. If the retry limit is exceeded the exception is re - raised. | def _retry_order(self, exception, max_fulfillment_retries, order_number):
"""
Retry with exponential backoff until fulfillment
succeeds or the retry limit is reached. If the retry limit is exceeded,
the exception is re-raised.
"""
retries = self.request.retries
if retries == max_fulfillment_... |
Fulfills an order. | def fulfill_order(self, order_number, site_code=None, email_opt_in=False):
"""Fulfills an order.
Arguments:
order_number (str): Order number indicating which order to fulfill.
Returns:
None
"""
max_fulfillment_retries = get_configuration('MAX_FULFILLMENT_RETRIES', site_code=site_co... |
Returns a Sailthru client for the specified site. | def get_sailthru_client(site_code):
"""
Returns a Sailthru client for the specified site.
Args:
site_code (str): Site for which the client should be configured.
Returns:
SailthruClient
Raises:
SailthruNotEnabled: If Sailthru is not enabled for the specified site.
C... |
Get an object from the cache | def get(self, key):
"""Get an object from the cache
Arguments:
key (str): Cache key
Returns:
Cached object
"""
lock.acquire()
try:
if key not in self:
return None
current_time = time.time()
if ... |
Save an object in the cache | def set(self, key, value, duration):
"""Save an object in the cache
Arguments:
key (str): Cache key
value (object): object to cache
duration (int): time in seconds to keep object in cache
"""
lock.acquire()
try:
self[key] = CacheO... |
Get a value from configuration. | def get_configuration(variable, site_code=None):
"""
Get a value from configuration.
Retrieves the value corresponding to the given variable from the configuration module
currently in use by the app. Specify a site_code value to check for a site-specific override.
Arguments:
variable (str... |
Get client for fetching data from ecommerce API. Arguments: site_code ( str ): ( Optional ) The SITE_OVERRIDES key to inspect for site - specific values url_postfix ( str ): ( Optional ) The URL postfix value to append to the ECOMMERCE_API_ROOT value. | def get_ecommerce_client(url_postfix='', site_code=None):
"""
Get client for fetching data from ecommerce API.
Arguments:
site_code (str): (Optional) The SITE_OVERRIDES key to inspect for site-specific values
url_postfix (str): (Optional) The URL postfix value to append to the ECOMMERCE_API_... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.