signature stringlengths 8 3.44k | body stringlengths 0 1.41M | docstring stringlengths 1 122k | id stringlengths 5 17 |
|---|---|---|---|
def __init__(self, extension=None): | if extension is None:<EOL><INDENT>extension = defaults.TEMPLATE_EXTENSION<EOL><DEDENT>self.template_extension = extension<EOL> | Construct a template locator.
Arguments:
extension: the template file extension, without the leading dot.
Pass False for no extension (e.g. to use extensionless template
files). Defaults to the package default. | f815:c0:m0 |
def get_object_directory(self, obj): | if not hasattr(obj, '<STR_LIT>'):<EOL><INDENT>return None<EOL><DEDENT>module = sys.modules[obj.__module__]<EOL>if not hasattr(module, '<STR_LIT>'):<EOL><INDENT>return None<EOL><DEDENT>path = module.__file__<EOL>return os.path.dirname(path)<EOL> | Return the directory containing an object's defining class.
Returns None if there is no such directory, for example if the
class was defined in an interactive Python session, or in a
doctest that appears in a text file (rather than a Python file). | f815:c0:m1 |
def make_template_name(self, obj): | template_name = obj.__class__.__name__<EOL>def repl(match):<EOL><INDENT>return '<STR_LIT:_>' + match.group(<NUM_LIT:0>).lower()<EOL><DEDENT>return re.sub('<STR_LIT>', repl, template_name)[<NUM_LIT:1>:]<EOL> | Return the canonical template name for an object instance.
This method converts Python-style class names (PEP 8's recommended
CamelCase, aka CapWords) to lower_case_with_underscords. Here
is an example with code:
>>> class HelloWorld(object):
... pass
>>> hi = HelloWorld()
>>>
>>> locator = Locator()
>>> locator... | f815:c0:m2 |
def make_file_name(self, template_name, template_extension=None): | file_name = template_name<EOL>if template_extension is None:<EOL><INDENT>template_extension = self.template_extension<EOL><DEDENT>if template_extension is not False:<EOL><INDENT>file_name += os.path.extsep + template_extension<EOL><DEDENT>return file_name<EOL> | Generate and return the file name for the given template name.
Arguments:
template_extension: defaults to the instance's extension. | f815:c0:m3 |
def _find_path(self, search_dirs, file_name): | for dir_path in search_dirs:<EOL><INDENT>file_path = os.path.join(dir_path, file_name)<EOL>if os.path.exists(file_path):<EOL><INDENT>return file_path<EOL><DEDENT><DEDENT>return None<EOL> | Search for the given file, and return the path.
Returns None if the file is not found. | f815:c0:m4 |
def _find_path_required(self, search_dirs, file_name): | path = self._find_path(search_dirs, file_name)<EOL>if path is None:<EOL><INDENT>raise TemplateNotFoundError('<STR_LIT>' %<EOL>(repr(file_name), repr(search_dirs)))<EOL><DEDENT>return path<EOL> | Return the path to a template with the given file name. | f815:c0:m5 |
def find_file(self, file_name, search_dirs): | return self._find_path_required(search_dirs, file_name)<EOL> | Return the path to a template with the given file name.
Arguments:
file_name: the file name of the template.
search_dirs: the list of directories in which to search. | f815:c0:m6 |
def find_name(self, template_name, search_dirs): | file_name = self.make_file_name(template_name)<EOL>return self._find_path_required(search_dirs, file_name)<EOL> | Return the path to a template with the given name.
Arguments:
template_name: the name of the template.
search_dirs: the list of directories in which to search. | f815:c0:m7 |
def find_object(self, obj, search_dirs, file_name=None): | if file_name is None:<EOL><INDENT>template_name = self.make_template_name(obj)<EOL>file_name = self.make_file_name(template_name)<EOL><DEDENT>dir_path = self.get_object_directory(obj)<EOL>if dir_path is not None:<EOL><INDENT>search_dirs = [dir_path] + search_dirs<EOL><DEDENT>path = self._find_path_required(search_dirs,... | Return the path to a template associated with the given object. | f815:c0:m8 |
def read(path): | <EOL>f = open(path, '<STR_LIT:rb>')<EOL>try:<EOL><INDENT>b = f.read()<EOL><DEDENT>finally:<EOL><INDENT>f.close()<EOL><DEDENT>return b.decode(FILE_ENCODING)<EOL> | Read and return the contents of a text file as a unicode string. | f817:m0 |
def write(u, path): | print("<STR_LIT>" % path)<EOL>f = open(path, "<STR_LIT:wb>")<EOL>try:<EOL><INDENT>b = u.encode(FILE_ENCODING)<EOL>f.write(b)<EOL><DEDENT>finally:<EOL><INDENT>f.close()<EOL><DEDENT> | Write a unicode string to a file (as utf-8). | f817:m1 |
def make_temp_path(path, new_ext=None): | root, ext = os.path.splitext(path)<EOL>if new_ext is None:<EOL><INDENT>new_ext = ext<EOL><DEDENT>temp_path = root + TEMP_EXTENSION + new_ext<EOL>return temp_path<EOL> | Arguments:
new_ext: the new file extension, including the leading dot.
Defaults to preserving the existing file extension. | f817:m2 |
def strip_html_comments(text): | lines = text.splitlines(True) <EOL>new_lines = filter(lambda line: not line.startswith("<STR_LIT>"), lines)<EOL>return "<STR_LIT>".join(new_lines)<EOL> | Strip HTML comments from a unicode string. | f817:m3 |
def convert_md_to_rst(md_path, rst_temp_path): | <EOL>command = "<STR_LIT>" % (rst_temp_path, md_path)<EOL>print("<STR_LIT>" % (md_path, rst_temp_path,<EOL>command))<EOL>if os.path.exists(rst_temp_path):<EOL><INDENT>os.remove(rst_temp_path)<EOL><DEDENT>os.system(command)<EOL>if not os.path.exists(rst_temp_path):<EOL><INDENT>s = ("<STR_LIT>"<EOL>"<STR_LIT>" % (command... | Convert the contents of a file from Markdown to reStructuredText.
Returns the converted text as a Unicode string.
Arguments:
md_path: a path to a UTF-8 encoded Markdown file to convert.
rst_temp_path: a temporary path to which to write the converted contents. | f817:m4 |
def make_long_description(): | readme_path = README_PATH<EOL>readme_md = strip_html_comments(read(readme_path))<EOL>history_md = strip_html_comments(read(HISTORY_PATH))<EOL>license_md = | Generate the reST long_description for setup() from source files.
Returns the generated long_description as a unicode string. | f817:m5 |
def prep(): | long_description = make_long_description()<EOL>write(long_description, RST_DESCRIPTION_PATH)<EOL> | Update the reST long_description file. | f817:m6 |
def publish(): | long_description = make_long_description()<EOL>if long_description != read(RST_DESCRIPTION_PATH):<EOL><INDENT>print( | Publish this package to PyPI (aka "the Cheeseshop"). | f817:m7 |
def get_extra_args(): | extra = {}<EOL>if py_version >= (<NUM_LIT:3>, ):<EOL><INDENT>extra['<STR_LIT>'] = True<EOL><DEDENT>return extra<EOL> | Return a dictionary of extra args to pass to setup(). | f817:m8 |
def wait(animation='<STR_LIT>', text='<STR_LIT>', speed=<NUM_LIT>): | def decorator(func):<EOL><INDENT>func.animation = animation<EOL>func.speed = speed<EOL>func.text = text<EOL>@wraps(func)<EOL>def wrapper(*args, **kwargs):<EOL><INDENT>animation = func.animation<EOL>text = func.text<EOL>if not isinstance(animation, (list, tuple)) andnot hasattr(animations, animation):<EOL><INDENT>text =... | Decorator for adding wait animation to long running
functions.
Args:
animation (str, tuple): String reference to animation or tuple
with custom animation.
speed (float): Number of seconds each cycle of animation.
Examples:
>>> @animation.wait('bar')
>>> def long_running_function():
>>> ... | f822:m1 |
def simple_wait(func): | @wraps(func)<EOL>def wrapper(*args, **kwargs):<EOL><INDENT>wait = Wait()<EOL>wait.start()<EOL>try:<EOL><INDENT>ret = func(*args, **kwargs)<EOL><DEDENT>finally:<EOL><INDENT>wait.stop()<EOL><DEDENT>sys.stdout.write('<STR_LIT:\n>')<EOL>return ret<EOL><DEDENT>return wrapper<EOL> | Decorator for adding simple text wait animation to
long running functions.
Examples:
>>> @animation.simple_wait
>>> def long_running_function():
>>> ... 5 seconds later ...
>>> return | f822:m2 |
def start(self): | self.thread = threading.Thread(target=self._animate)<EOL>self.thread.start()<EOL>return<EOL> | Start animation thread. | f822:c0:m2 |
def stop(self): | time.sleep(self.speed)<EOL>self._count = -<NUM_LIT><EOL>sys.stdout.write(self.reverser + '<STR_LIT>')<EOL>sys.stdout.flush()<EOL>return<EOL> | Stop animation thread. | f822:c0:m3 |
def expand_collection_in_dict(d, key, new_items, no_duplicates=True): | if key in d:<EOL><INDENT>if no_duplicates:<EOL><INDENT>new_items = filter(lambda x: x not in d[key], new_items)<EOL><DEDENT>if isinstance(d[key], set):<EOL><INDENT>map(d[key].add, new_items)<EOL><DEDENT>elif isinstance(d[key], list):<EOL><INDENT>map(d[key].append, new_items)<EOL><DEDENT>else:<EOL><INDENT>d[key] = d[key... | Parameters
d: dict
dict in which a key will be inserted/expanded
key: hashable
key in d
new_items: iterable
d[key] will be extended with items in new_items
no_duplicates: bool
avoid inserting duplicates in d[key] (default: True) | f825:m0 |
def copy(src, dst, only_update=False, copystat=True, cwd=None,<EOL>dest_is_dir=False, create_dest_dirs=False, logger=None): | <EOL>if cwd:<EOL><INDENT>if not os.path.isabs(src):<EOL><INDENT>src = os.path.join(cwd, src)<EOL><DEDENT>if not os.path.isabs(dst):<EOL><INDENT>dst = os.path.join(cwd, dst)<EOL><DEDENT><DEDENT>if not os.path.exists(src):<EOL><INDENT>msg = "<STR_LIT>".format(src)<EOL>raise FileNotFoundError(msg)<EOL><DEDENT>if dest_is_d... | Augmented shutil.copy with extra options and slightly
modified behaviour
Parameters
==========
src: string
path to source file
dst: string
path to destingation
only_update: bool
only copy if source is newer than destination
(returns None if it was newer), default: False
copystat: bool
See shutil.co... | f825:m4 |
def md5_of_file(path, nblocks=<NUM_LIT>): | md = md5()<EOL>with open(path, '<STR_LIT:rb>') as f:<EOL><INDENT>for chunk in iter(lambda: f.read(nblocks*md.block_size), b'<STR_LIT>'):<EOL><INDENT>md.update(chunk)<EOL><DEDENT><DEDENT>return md<EOL> | Computes the md5 hash of a file.
Parameters
==========
path: string
path to file to compute hash of
Returns
=======
hashlib md5 hash object. Use .digest() or .hexdigest()
on returned object to get binary or hex encoded string. | f825:m5 |
def missing_or_other_newer(path, other_path, cwd=None): | cwd = cwd or '<STR_LIT:.>'<EOL>path = get_abspath(path, cwd=cwd)<EOL>other_path = get_abspath(other_path, cwd=cwd)<EOL>if not os.path.exists(path):<EOL><INDENT>return True<EOL><DEDENT>if os.path.getmtime(other_path) - <NUM_LIT> >= os.path.getmtime(path):<EOL><INDENT>return True<EOL><DEDENT>return False<EOL> | Investigate if path is non-existant or older than provided reference
path.
Parameters
==========
path: string
path to path which might be missing or too old
other_path: string
reference path
cwd: string
working directory (root of relative paths)
Returns
=======
True if path is older or missing. | f825:m7 |
def import_module_from_file(filename, only_if_newer_than=None): | import imp<EOL>path, name = os.path.split(filename)<EOL>name, ext = os.path.splitext(name)<EOL>name = name.split('<STR_LIT:.>')[<NUM_LIT:0>]<EOL>fobj, filename, data = imp.find_module(name, [path])<EOL>if only_if_newer_than:<EOL><INDENT>for dep in only_if_newer_than:<EOL><INDENT>if os.path.getmtime(filename) < os.path.... | Imports (cython generated) shared object file (.so)
Provide a list of paths in `only_if_newer_than` to check
timestamps of dependencies. import_ raises an ImportError
if any is newer.
Word of warning: Python's caching or the OS caching (unclear to author)
is horrible for reimporting same path of an .so file. It will
... | f825:m9 |
def find_binary_of_command(candidates): | from distutils.spawn import find_executable<EOL>for c in candidates:<EOL><INDENT>binary_path = find_executable(c)<EOL>if c and binary_path:<EOL><INDENT>return c, binary_path<EOL><DEDENT><DEDENT>raise RuntimeError('<STR_LIT>'.format(<EOL>candidates))<EOL> | Calls `find_executable` from distuils for
provided candidates and returns first hit.
If no candidate mathces, a RuntimeError is raised | f825:m10 |
def pyx_is_cplus(path): | for line in open(path, '<STR_LIT>'):<EOL><INDENT>if line.startswith('<STR_LIT:#>') and '<STR_LIT:=>' in line:<EOL><INDENT>splitted = line.split('<STR_LIT:=>')<EOL>if len(splitted) != <NUM_LIT:2>:<EOL><INDENT>continue<EOL><DEDENT>lhs, rhs = splitted<EOL>if lhs.strip().split()[-<NUM_LIT:1>].lower() == '<STR_LIT>' andrhs.... | Inspect a Cython source file (.pyx) and look for comment line like:
# distutils: language = c++
Returns True if such a file is present in the file, else False. | f825:m11 |
def uniquify(l): | result = []<EOL>for x in l:<EOL><INDENT>if x not in result:<EOL><INDENT>result.append(x)<EOL><DEDENT><DEDENT>return result<EOL> | Uniquify a list (skip duplicate items). | f825:m12 |
@classmethod<EOL><INDENT>def _get_metadata_key(cls, kw):<DEDENT> | return cls.__name__+'<STR_LIT:_>'+kw<EOL> | kw could be e.g. 'compiler | f825:c2:m0 |
@classmethod<EOL><INDENT>def get_from_metadata_file(cls, dirpath, key):<DEDENT> | fullpath = os.path.join(dirpath, cls.metadata_filename)<EOL>if os.path.exists(fullpath):<EOL><INDENT>d = pickle.load(open(fullpath, '<STR_LIT:rb>'))<EOL>return d[key]<EOL><DEDENT>else:<EOL><INDENT>raise FileNotFoundError(<EOL>"<STR_LIT>".format(fullpath))<EOL><DEDENT> | Get value of key in metadata file dict. | f825:c2:m1 |
@classmethod<EOL><INDENT>def save_to_metadata_file(cls, dirpath, key, value):<DEDENT> | fullpath = os.path.join(dirpath, cls.metadata_filename)<EOL>if os.path.exists(fullpath):<EOL><INDENT>d = pickle.load(open(fullpath, '<STR_LIT:rb>'))<EOL>d.update({key: value})<EOL>pickle.dump(d, open(fullpath, '<STR_LIT:wb>'))<EOL><DEDENT>else:<EOL><INDENT>pickle.dump({key: value}, open(fullpath, '<STR_LIT:wb>'))<EOL><... | Store `key: value` in metadata file dict. | f825:c2:m2 |
def compile_sources(files, CompilerRunner_=None,<EOL>destdir=None, cwd=None,<EOL>keep_dir_struct=False,<EOL>per_file_kwargs=None,<EOL>**kwargs): | _per_file_kwargs = {}<EOL>if per_file_kwargs is not None:<EOL><INDENT>for k, v in per_file_kwargs.items():<EOL><INDENT>if isinstance(k, Glob):<EOL><INDENT>for path in glob.glob(k.pathname):<EOL><INDENT>_per_file_kwargs[path] = v<EOL><DEDENT><DEDENT>elif isinstance(k, ArbitraryDepthGlob):<EOL><INDENT>for path in glob_at... | Compile source code files to object files.
Parameters
----------
files: iterable of path strings
source files, if cwd is given, the paths are taken as relative.
CompilerRunner_: CompilerRunner instance (optional)
could be e.g. pycompilation.FortranCompilerRunner
Will be inferred from filename extensions if... | f827:m1 |
def link(obj_files, out_file=None, shared=False, CompilerRunner_=None,<EOL>cwd=None, cplus=False, fort=False, **kwargs): | if out_file is None:<EOL><INDENT>out_file, ext = os.path.splitext(os.path.basename(obj_files[-<NUM_LIT:1>]))<EOL>if shared:<EOL><INDENT>out_file += sharedext<EOL><DEDENT><DEDENT>if not CompilerRunner_:<EOL><INDENT>if fort:<EOL><INDENT>CompilerRunner_, extra_kwargs, vendor =get_mixed_fort_c_linker(<EOL>vendor=kwargs.get... | Link object files.
Parameters
----------
obj_files: iterable of path strings
out_file: path string (optional)
path to executable/shared library, if missing
it will be deduced from the last item in obj_files.
shared: bool
Generate a shared library? default: False
CompilerRunner_: pycompilation.CompilerRunne... | f827:m2 |
def link_py_so(obj_files, so_file=None, cwd=None, libraries=None,<EOL>cplus=False, fort=False, **kwargs): | libraries = libraries or []<EOL>include_dirs = kwargs.pop('<STR_LIT>', [])<EOL>library_dirs = kwargs.pop('<STR_LIT>', [])<EOL>if sys.platform == "<STR_LIT:win32>":<EOL><INDENT>warnings.warn("<STR_LIT>")<EOL><DEDENT>elif sys.platform == '<STR_LIT>':<EOL><INDENT>pass<EOL><DEDENT>elif sys.platform[:<NUM_LIT:3>] == '<STR_L... | Link python extension module (shared object) for importing
Parameters
----------
obj_files: iterable of path strings
object files to be linked
so_file: path string
Name (path) of shared object file to create. If
not specified it will have the basname of the last object
file in `obj_files` but with the ... | f827:m3 |
def simple_cythonize(src, destdir=None, cwd=None, logger=None,<EOL>full_module_name=None, only_update=False,<EOL>**cy_kwargs): | from Cython.Compiler.Main import (<EOL>default_options, CompilationOptions<EOL>)<EOL>from Cython.Compiler.Main import compile as cy_compile<EOL>assert src.lower().endswith('<STR_LIT>') or src.lower().endswith('<STR_LIT>')<EOL>cwd = cwd or '<STR_LIT:.>'<EOL>destdir = destdir or '<STR_LIT:.>'<EOL>ext = '<STR_LIT>' if cy_... | Generates a C file from a Cython source file.
Parameters
----------
src: path string
path to Cython source
destdir: path string (optional)
Path to output directory (default: '.')
cwd: path string (optional)
Root of relative paths (default: '.')
logger: logging.Logger
info level used.
full_module_name: ... | f827:m4 |
def src2obj(srcpath, CompilerRunner_=None, objpath=None,<EOL>only_update=False, cwd=None, out_ext=None, inc_py=False,<EOL>**kwargs): | name, ext = os.path.splitext(os.path.basename(srcpath))<EOL>if objpath is None:<EOL><INDENT>if os.path.isabs(srcpath):<EOL><INDENT>objpath = '<STR_LIT:.>'<EOL><DEDENT>else:<EOL><INDENT>objpath = os.path.dirname(srcpath)<EOL>objpath = objpath or '<STR_LIT:.>' <EOL><DEDENT><DEDENT>out_ext = out_ext or objext<EOL>if os.p... | Compiles a source code file to an object file.
Files ending with '.pyx' assumed to be cython files and
are dispatched to pyx2obj.
Parameters
----------
srcpath: path string
path to source file
CompilerRunner_: pycompilation.CompilerRunner subclass (optional)
Default: deduced from extension of srcpath
objpath: ... | f827:m5 |
def pyx2obj(pyxpath, objpath=None, interm_c_dir=None, cwd=None,<EOL>logger=None, full_module_name=None, only_update=False,<EOL>metadir=None, include_numpy=False, include_dirs=None,<EOL>cy_kwargs=None, gdb=False, cplus=None, **kwargs): | assert pyxpath.endswith('<STR_LIT>')<EOL>cwd = cwd or '<STR_LIT:.>'<EOL>objpath = objpath or '<STR_LIT:.>'<EOL>interm_c_dir = interm_c_dir or os.path.dirname(objpath)<EOL>abs_objpath = get_abspath(objpath, cwd=cwd)<EOL>if os.path.isdir(abs_objpath):<EOL><INDENT>pyx_fname = os.path.basename(pyxpath)<EOL>name, ext = os.p... | Convenience function
If cwd is specified, pyxpath and dst are taken to be relative
If only_update is set to `True` the modification time is checked
and compilation is only run if the source is newer than the
destination
Parameters
----------
pyxpath: path string
path to Cython source file
objpath: path string (op... | f827:m6 |
def compile_link_import_py_ext(<EOL>srcs, extname=None, build_dir=None, compile_kwargs=None,<EOL>link_kwargs=None, **kwargs): | build_dir = build_dir or '<STR_LIT:.>'<EOL>if extname is None:<EOL><INDENT>extname = os.path.splitext(os.path.basename(srcs[-<NUM_LIT:1>]))[<NUM_LIT:0>]<EOL><DEDENT>compile_kwargs = compile_kwargs or {}<EOL>compile_kwargs.update(kwargs)<EOL>link_kwargs = link_kwargs or {}<EOL>link_kwargs.update(kwargs)<EOL>try:<EOL><IN... | Compiles sources in `srcs` to a shared object (python extension)
which is imported. If shared object is newer than the sources, they
are not recompiled but instead it is imported.
Parameters
----------
srcs: string
list of paths to sources
extname: string
name of extension (default: None)
(taken from the l... | f827:m10 |
def compile_link_import_strings(codes, build_dir=None, **kwargs): | build_dir = build_dir or tempfile.mkdtemp()<EOL>if not os.path.isdir(build_dir):<EOL><INDENT>raise OSError("<STR_LIT>", build_dir)<EOL><DEDENT>source_files = []<EOL>if kwargs.get('<STR_LIT>', False) is True:<EOL><INDENT>import logging<EOL>logging.basicConfig(level=logging.DEBUG)<EOL>kwargs['<STR_LIT>'] = logging.getLog... | Creates a temporary directory and dumps, compiles and links
provided source code.
Parameters
----------
codes: iterable of name/source pair tuples
build_dir: string (default: None)
path to cache_dir. None implies use a temporary directory.
**kwargs:
keyword arguments passed onto `compile_link_import_py_ext` | f827:m11 |
def PCExtension(*args, **kwargs): | vals = {}<EOL>intercept = {<EOL>'<STR_LIT>': (), <EOL>'<STR_LIT>': True,<EOL>'<STR_LIT>': (),<EOL>'<STR_LIT>': (), <EOL>'<STR_LIT>': [],<EOL>'<STR_LIT>': False, <EOL>'<STR_LIT>': {},<EOL>'<STR_LIT>': {},<EOL>}<EOL>for k, v in intercept.items():<EOL><INDENT>vals[k] = kwargs.pop(k, v)<EOL><DEDENT>intercept2 = {<EOL>'<... | Parameters
==========
template_regexps: list of 3-tuples
e.g. [(pattern1, target1, subsd1), ...], used to generate
templated code
pass_extra_compile_args: bool
should ext.extra_compile_args be passed along? default: False | f830:m0 |
def _copy_or_render_source(ext, f, output_dir, render_callback,<EOL>skip_copy=False): | <EOL>dirname = os.path.dirname(f)<EOL>filename = os.path.basename(f)<EOL>for pattern, target, subsd in ext.template_regexps:<EOL><INDENT>if re.match(pattern, filename):<EOL><INDENT>tgt = os.path.join(dirname, re.sub(<EOL>pattern, target, filename))<EOL>rw = MetaReaderWriter('<STR_LIT>')<EOL>try:<EOL><INDENT>prev_subsd ... | Tries to do regex match for each (pattern, target, subsd) tuple
in ext.template_regexps for file f. | f830:m1 |
def render_python_template_to(src, dest, subsd, only_update=False,<EOL>prev_subsd=None, create_dest_dirs=True,<EOL>logger=None): | if only_update:<EOL><INDENT>if subsd == prev_subsd:<EOL><INDENT>if not missing_or_other_newer(dest, src):<EOL><INDENT>if logger:<EOL><INDENT>msg = ("<STR_LIT>"<EOL>"<STR_LIT>")<EOL>logger.info(msg.format(src))<EOL><DEDENT>return<EOL><DEDENT><DEDENT><DEDENT>with open(src, '<STR_LIT>') as ifh:<EOL><INDENT>data = ifh.read... | Overload this function if you want to use a template engine such as
e.g. mako. | f830:m2 |
@classmethod<EOL><INDENT>def find_compiler(cls, preferred_vendor, metadir, cwd,<EOL>use_meta=True):<DEDENT> | cwd = cwd or '<STR_LIT:.>'<EOL>metadir = metadir or '<STR_LIT:.>'<EOL>metadir = os.path.join(cwd, metadir)<EOL>used_metafile = False<EOL>if not preferred_vendor and use_meta:<EOL><INDENT>try:<EOL><INDENT>preferred_vendor = cls.get_from_metadata_file(<EOL>metadir, '<STR_LIT>')<EOL>used_metafile = True<EOL><DEDENT>except... | Identify a suitable C/fortran/other compiler
When it is possible that the user (un)installs a compiler
inbetween compilations of object files we want to catch
that. This method allows compiler choice to be stored in a
pickled metadata file. Provide metadir a dirpath to
make the class save choice there in a file with
... | f831:c0:m1 |
def cmd(self): | cmd = (<EOL>[self.compiler_binary] +<EOL>self.flags +<EOL>['<STR_LIT>'+x for x in self.undef] +<EOL>['<STR_LIT>'+x for x in self.define] +<EOL>['<STR_LIT>'+x for x in self.include_dirs] +<EOL>self.sources<EOL>)<EOL>if self.run_linker:<EOL><INDENT>cmd += (['<STR_LIT>'+x for x in self.library_dirs] +<EOL>[(x if os.path.e... | The command below covers most cases, if you need
someting more complex subclass this. | f831:c0:m2 |
def DiskCache(cachedir, methods): | class _DiskCache(object):<EOL><INDENT>cached_methods = methods<EOL>def __init__(self, *args, **kwargs):<EOL><INDENT>from tempfile import mkdtemp<EOL>from joblib import Memory<EOL>self.cachedir = cachedir or mkdtemp()<EOL>self.memory = Memory(cachedir=self.cachedir)<EOL>for method in self.cached_methods:<EOL><INDENT>set... | Class factory for mixin class to help with caching.
The _DiskCache mixin class uses joblib to pickle results. | f835:m0 |
def main(coeffs="<STR_LIT>", diff=<NUM_LIT:0>, xmin=<NUM_LIT:0>, xmax=<NUM_LIT:3>, N=<NUM_LIT:4>, clean=False): | coeffs = tuple(map(float, coeffs.split('<STR_LIT:U+002C>')))<EOL>poly = MyPoly(coeffs)<EOL>Dpoly = poly.diff(diff)<EOL>mod = Dpoly.compile_link_import_py_ext()<EOL>x = np.linspace(xmin, xmax, N)<EOL>result = mod.callback(x)<EOL>for _ in range(diff, <NUM_LIT:0>, -<NUM_LIT:1>):<EOL><INDENT>coeffs = tuple((p*c for p, c in... | Compile a native callback of a polynomial | f837:m0 |
def run_compilation(**kwargs): | for f in files:<EOL><INDENT>shutil.copy(f, kwargs['<STR_LIT>'])<EOL><DEDENT>objs = [<EOL>src2obj('<STR_LIT>',<EOL>options=options_omp,<EOL>**kwargs),<EOL>src2obj('<STR_LIT>',<EOL>std='<STR_LIT>',<EOL>options=options,<EOL>**kwargs),<EOL>src2obj('<STR_LIT>',<EOL>cplus=True, **kwargs)<EOL>]<EOL>return link_py_so(objs, cpl... | Compiles and links Cython wrapped C++ function
(which calls into an OpenMP enabled Fortran 2003 routine) | f838:m0 |
def __init__(self, access_token, **kwargs): | self.api_version = kwargs.get('<STR_LIT>') or DEFAULT_API_VERSION<EOL>self.app_secret = kwargs.get('<STR_LIT>')<EOL>self.graph_url = '<STR_LIT>'.format(self.api_version)<EOL>self.access_token = access_token<EOL> | @required:
access_token
@optional:
api_version
app_secret | f841:c1:m0 |
def send_attachment(self, recipient_id, attachment_type, attachment_path,<EOL>notification_type=NotificationType.regular): | payload = {<EOL>'<STR_LIT>': {<EOL>{<EOL>'<STR_LIT:id>': recipient_id<EOL>}<EOL>},<EOL>'<STR_LIT>': notification_type,<EOL>'<STR_LIT:message>': {<EOL>{<EOL>'<STR_LIT>': {<EOL>'<STR_LIT:type>': attachment_type,<EOL>'<STR_LIT>': {}<EOL>}<EOL>}<EOL>},<EOL>'<STR_LIT>': (os.path.basename(attachment_path), open(attachment_pa... | Send an attachment to the specified recipient using local path.
Input:
recipient_id: recipient id to send to
attachment_type: type of attachment (image, video, audio, file)
attachment_path: Path of attachment
Output:
Response from API as <dict> | f841:c1:m4 |
def send_attachment_url(self, recipient_id, attachment_type, attachment_url,<EOL>notification_type=NotificationType.regular): | return self.send_message(recipient_id, {<EOL>'<STR_LIT>': {<EOL>'<STR_LIT:type>': attachment_type,<EOL>'<STR_LIT>': {<EOL>'<STR_LIT:url>': attachment_url<EOL>}<EOL>}<EOL>}, notification_type)<EOL> | Send an attachment to the specified recipient using URL.
Input:
recipient_id: recipient id to send to
attachment_type: type of attachment (image, video, audio, file)
attachment_url: URL of attachment
Output:
Response from API as <dict> | f841:c1:m5 |
def send_text_message(self, recipient_id, message, notification_type=NotificationType.regular): | return self.send_message(recipient_id, {<EOL>'<STR_LIT:text>': message<EOL>}, notification_type)<EOL> | Send text messages to the specified recipient.
https://developers.facebook.com/docs/messenger-platform/send-api-reference/text-message
Input:
recipient_id: recipient id to send to
message: message to send
Output:
Response from API as <dict> | f841:c1:m6 |
def send_generic_message(self, recipient_id, elements, notification_type=NotificationType.regular): | return self.send_message(recipient_id, {<EOL>"<STR_LIT>": {<EOL>"<STR_LIT:type>": "<STR_LIT>",<EOL>"<STR_LIT>": {<EOL>"<STR_LIT>": "<STR_LIT>",<EOL>"<STR_LIT>": elements<EOL>}<EOL>}<EOL>}, notification_type)<EOL> | Send generic messages to the specified recipient.
https://developers.facebook.com/docs/messenger-platform/send-api-reference/generic-template
Input:
recipient_id: recipient id to send to
elements: generic message elements to send
Output:
Response from API as <... | f841:c1:m7 |
def send_button_message(self, recipient_id, text, buttons, notification_type=NotificationType.regular): | return self.send_message(recipient_id, {<EOL>"<STR_LIT>": {<EOL>"<STR_LIT:type>": "<STR_LIT>",<EOL>"<STR_LIT>": {<EOL>"<STR_LIT>": "<STR_LIT>",<EOL>"<STR_LIT:text>": text,<EOL>"<STR_LIT>": buttons<EOL>}<EOL>}<EOL>}, notification_type)<EOL> | Send text messages to the specified recipient.
https://developers.facebook.com/docs/messenger-platform/send-api-reference/button-template
Input:
recipient_id: recipient id to send to
text: text of message to send
buttons: buttons to send
Output:
Re... | f841:c1:m8 |
def send_action(self, recipient_id, action, notification_type=NotificationType.regular): | return self.send_recipient(recipient_id, {<EOL>'<STR_LIT>': action<EOL>}, notification_type)<EOL> | Send typing indicators or send read receipts to the specified recipient.
https://developers.facebook.com/docs/messenger-platform/send-api-reference/sender-actions
Input:
recipient_id: recipient id to send to
action: action type (mark_seen, typing_on, typing_off)
Output:
... | f841:c1:m9 |
def send_image(self, recipient_id, image_path, notification_type=NotificationType.regular): | return self.send_attachment(recipient_id, "<STR_LIT:image>", image_path, notification_type)<EOL> | Send an image to the specified recipient.
Image must be PNG or JPEG or GIF (more might be supported).
https://developers.facebook.com/docs/messenger-platform/send-api-reference/image-attachment
Input:
recipient_id: recipient id to send to
image_path: path to image to be s... | f841:c1:m10 |
def send_image_url(self, recipient_id, image_url, notification_type=NotificationType.regular): | return self.send_attachment_url(recipient_id, "<STR_LIT:image>", image_url, notification_type)<EOL> | Send an image to specified recipient using URL.
Image must be PNG or JPEG or GIF (more might be supported).
https://developers.facebook.com/docs/messenger-platform/send-api-reference/image-attachment
Input:
recipient_id: recipient id to send to
image_url: url of image to ... | f841:c1:m11 |
def send_audio(self, recipient_id, audio_path, notification_type=NotificationType.regular): | return self.send_attachment(recipient_id, "<STR_LIT>", audio_path, notification_type)<EOL> | Send audio to the specified recipient.
Audio must be MP3 or WAV
https://developers.facebook.com/docs/messenger-platform/send-api-reference/audio-attachment
Input:
recipient_id: recipient id to send to
audio_path: path to audio to be sent
Output:
Respon... | f841:c1:m12 |
def send_audio_url(self, recipient_id, audio_url, notification_type=NotificationType.regular): | return self.send_attachment_url(recipient_id, "<STR_LIT>", audio_url, notification_type)<EOL> | Send audio to specified recipient using URL.
Audio must be MP3 or WAV
https://developers.facebook.com/docs/messenger-platform/send-api-reference/audio-attachment
Input:
recipient_id: recipient id to send to
audio_url: url of audio to be sent
Output:
Re... | f841:c1:m13 |
def send_video(self, recipient_id, video_path, notification_type=NotificationType.regular): | return self.send_attachment(recipient_id, "<STR_LIT>", video_path, notification_type)<EOL> | Send video to the specified recipient.
Video should be MP4 or MOV, but supports more (https://www.facebook.com/help/218673814818907).
https://developers.facebook.com/docs/messenger-platform/send-api-reference/video-attachment
Input:
recipient_id: recipient id to send to
v... | f841:c1:m14 |
def send_video_url(self, recipient_id, video_url, notification_type=NotificationType.regular): | return self.send_attachment_url(recipient_id, "<STR_LIT>", video_url, notification_type)<EOL> | Send video to specified recipient using URL.
Video should be MP4 or MOV, but supports more (https://www.facebook.com/help/218673814818907).
https://developers.facebook.com/docs/messenger-platform/send-api-reference/video-attachment
Input:
recipient_id: recipient id to send to
... | f841:c1:m15 |
def send_file(self, recipient_id, file_path, notification_type=NotificationType.regular): | return self.send_attachment(recipient_id, "<STR_LIT:file>", file_path, notification_type)<EOL> | Send file to the specified recipient.
https://developers.facebook.com/docs/messenger-platform/send-api-reference/file-attachment
Input:
recipient_id: recipient id to send to
file_path: path to file to be sent
Output:
Response from API as <dict> | f841:c1:m16 |
def send_file_url(self, recipient_id, file_url, notification_type=NotificationType.regular): | return self.send_attachment_url(recipient_id, "<STR_LIT:file>", file_url, notification_type)<EOL> | Send file to the specified recipient.
https://developers.facebook.com/docs/messenger-platform/send-api-reference/file-attachment
Input:
recipient_id: recipient id to send to
file_url: url of file to be sent
Output:
Response from API as <dict> | f841:c1:m17 |
def get_user_info(self, recipient_id, fields=None): | params = {}<EOL>if fields is not None and isinstance(fields, (list, tuple)):<EOL><INDENT>params['<STR_LIT>'] = "<STR_LIT:U+002C>".join(fields)<EOL><DEDENT>params.update(self.auth_args)<EOL>request_endpoint = '<STR_LIT>'.format(self.graph_url, recipient_id)<EOL>response = requests.get(request_endpoint, params=params)<EO... | Getting information about the user
https://developers.facebook.com/docs/messenger-platform/user-profile
Input:
recipient_id: recipient id to send to
Output:
Response from API as <dict> | f841:c1:m18 |
def _send_payload(self, payload): | return self.send_raw(payload)<EOL> | Deprecated, use send_raw instead | f841:c1:m20 |
def validate_hub_signature(app_secret, request_payload, hub_signature_header): | try:<EOL><INDENT>hash_method, hub_signature = hub_signature_header.split('<STR_LIT:=>')<EOL><DEDENT>except:<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>digest_module = getattr(hashlib, hash_method)<EOL>hmac_object = hmac.new(str(app_secret), unicode(request_payload), digest_module)<EOL>generated_hash = hmac_object.h... | @inputs:
app_secret: Secret Key for application
request_payload: request body
hub_signature_header: X-Hub-Signature header sent with request
@outputs:
boolean indicated that hub signature is validated | f843:m0 |
def generate_appsecret_proof(access_token, app_secret): | if six.PY2:<EOL><INDENT>hmac_object = hmac.new(str(app_secret), unicode(access_token), hashlib.sha256)<EOL><DEDENT>else:<EOL><INDENT>hmac_object = hmac.new(bytearray(app_secret, '<STR_LIT:utf8>'), str(access_token).encode('<STR_LIT:utf8>'), hashlib.sha256)<EOL><DEDENT>generated_hash = hmac_object.hexdigest()<EOL>return... | @inputs:
access_token: page access token
app_secret_token: app secret key
@outputs:
appsecret_proof: HMAC-SHA256 hash of page access token
using app_secret as the key | f843:m1 |
def get_app_template_dir(app_name): | if app_name in _cache:<EOL><INDENT>return _cache[app_name]<EOL><DEDENT>template_dir = None<EOL>if django.VERSION >= (<NUM_LIT:1>, <NUM_LIT:7>):<EOL><INDENT>from django.apps import apps<EOL>for app in apps.get_app_configs():<EOL><INDENT>if app.label == app_name:<EOL><INDENT>template_dir = join(app.path, '<STR_LIT>')<EOL... | Get the template directory for an application
Uses apps interface available in django 1.7+
Returns a full path, or None if the app was not found. | f849:m0 |
def get_template_sources(self, template_name, template_dirs=None): | if '<STR_LIT::>' not in template_name:<EOL><INDENT>return []<EOL><DEDENT>app_name, template_name = template_name.split("<STR_LIT::>", <NUM_LIT:1>)<EOL>template_dir = get_app_template_dir(app_name)<EOL>if template_dir:<EOL><INDENT>if django.VERSION >= (<NUM_LIT:1>, <NUM_LIT:9>):<EOL><INDENT>from django.template import O... | Returns the absolute paths to "template_name" in the specified app.
If the name does not contain an app name (no colon), an empty list
is returned.
The parent FilesystemLoader.load_template_source() will take care
of the actual loading for us. | f849:c0:m0 |
@register.tag<EOL>def placeholder(parser, token): | return Placeholder.parse(parser, token)<EOL> | A dummy placeholder template tag. | f851:m0 |
def _is_variable_extends(extend_node): | if django.VERSION < (<NUM_LIT:1>, <NUM_LIT:4>):<EOL><INDENT>return extend_node.parent_name_expr <EOL><DEDENT>else:<EOL><INDENT>return not isinstance(extend_node.parent_name.var, six.string_types)<EOL><DEDENT> | Check whether an ``{% extends variable %}`` is used in the template.
:type extend_node: ExtendsNode | f852:m0 |
def _extend_blocks(extend_node, blocks, context): | try:<EOL><INDENT>parent = extend_node.get_parent(_get_extend_context(context))<EOL><DEDENT>except TemplateSyntaxError:<EOL><INDENT>if _is_variable_extends(extend_node):<EOL><INDENT>return<EOL><DEDENT>else:<EOL><INDENT>raise<EOL><DEDENT><DEDENT>for parent_block in parent.nodelist.get_nodes_by_type(BlockNode):<EOL><INDEN... | Extends the dictionary `blocks` with *new* blocks in the parent node (recursive)
:param extend_node: The ``{% extends .. %}`` node object.
:type extend_node: ExtendsNode
:param blocks: dict of all block names found in the template.
:type blocks: dict | f852:m1 |
def _extend_nodelist(extends_node, context, instance_types): | results = []<EOL>blocks = extends_node.blocks.copy() <EOL>_extend_blocks(extends_node, blocks, context)<EOL>all_block_names = list(blocks.keys())<EOL>for block in list(blocks.values()):<EOL><INDENT>results += _scan_nodes(block.nodelist, context, instance_types, block, ignore_blocks=all_block_names)<EOL><DEDENT>parent_... | Returns a list of results found in the parent template(s)
:type extends_node: ExtendsNode | f852:m3 |
def _scan_nodes(nodelist, context, instance_types, current_block=None, ignore_blocks=None): | results = []<EOL>for node in nodelist:<EOL><INDENT>if isinstance(node, instance_types):<EOL><INDENT>results.append(node)<EOL><DEDENT>elif isinstance(node, IncludeNode):<EOL><INDENT>if node.template:<EOL><INDENT>if not callable(getattr(node.template, '<STR_LIT>', None)):<EOL><INDENT>template = get_template(node.template... | Loop through all nodes of a single scope level.
:type nodelist: django.template.base.NodeList
:type current_block: BlockNode
:param instance_types: The instance to look for | f852:m4 |
def get_node_instances(nodelist, instances): | context = _get_main_context(nodelist)<EOL>if TemplateAdapter is not None and isinstance(nodelist, TemplateAdapter):<EOL><INDENT>nodelist = nodelist.template<EOL><DEDENT>return _scan_nodes(nodelist, context, instances)<EOL> | Find the nodes of a given instance.
In contract to the standard ``template.nodelist.get_nodes_by_type()`` method,
this also looks into ``{% extends %}`` and ``{% include .. %}`` nodes
to find all possible nodes of the given type.
:param instances: A class Type, or tuple of types to find.
:param nodelist: The Templat... | f852:m7 |
def configure(): | root_logger = logging.getLogger()<EOL>root_logger.addHandler(logging.NullHandler())<EOL>root_logger.setLevel(<NUM_LIT>)<EOL>_display_logger.setLevel(<NUM_LIT>)<EOL>_debug_logger.setLevel(<NUM_LIT:10>)<EOL>display_handlers = [h.get_name() for h in _display_logger.handlers]<EOL>if '<STR_LIT>' not in display_handlers:<EOL... | Configures the logging facility
This function will setup an initial logging facility for handling display
and debug outputs. The default facility will send display messages to
stdout and the default debug facility will do nothing.
:returns: None | f857:m5 |
def prepare(self): | <EOL>if self.private_data_dir is None:<EOL><INDENT>raise ConfigurationError("<STR_LIT>")<EOL><DEDENT>if self.module and self.playbook:<EOL><INDENT>raise ConfigurationError("<STR_LIT>")<EOL><DEDENT>if not os.path.exists(self.artifact_dir):<EOL><INDENT>os.makedirs(self.artifact_dir, mode=<NUM_LIT>)<EOL><DEDENT>if self.di... | Performs basic checks and then properly invokes
- prepare_inventory
- prepare_env
- prepare_command
It's also responsible for wrapping the command with the proper ssh agent invocation
and setting early ANSIBLE_ environment variables. | f859:c1:m1 |
def prepare_inventory(self): | if self.inventory is None:<EOL><INDENT>self.inventory = os.path.join(self.private_data_dir, "<STR_LIT>")<EOL><DEDENT> | Prepares the inventory default under ``private_data_dir`` if it's not overridden by the constructor. | f859:c1:m2 |
def prepare_env(self): | try:<EOL><INDENT>passwords = self.loader.load_file('<STR_LIT>', Mapping)<EOL>self.expect_passwords = {<EOL>re.compile(pattern, re.M): password<EOL>for pattern, password in iteritems(passwords)<EOL>}<EOL><DEDENT>except ConfigurationError:<EOL><INDENT>output.debug('<STR_LIT>')<EOL>self.expect_passwords = dict()<EOL><DEDE... | Manages reading environment metadata files under ``private_data_dir`` and merging/updating
with existing values so the :py:class:`ansible_runner.runner.Runner` object can read and use them easily | f859:c1:m3 |
def prepare_command(self): | try:<EOL><INDENT>cmdline_args = self.loader.load_file('<STR_LIT:args>', string_types)<EOL>self.command = shlex.split(cmdline_args.decode('<STR_LIT:utf-8>'))<EOL>self.execution_mode = ExecutionMode.RAW<EOL><DEDENT>except ConfigurationError:<EOL><INDENT>self.command = self.generate_ansible_command()<EOL><DEDENT> | Determines if the literal ``ansible`` or ``ansible-playbook`` commands are given
and if not calls :py:meth:`ansible_runner.runner_config.RunnerConfig.generate_ansible_command` | f859:c1:m4 |
def generate_ansible_command(self): | if self.binary is not None:<EOL><INDENT>base_command = self.binary<EOL>self.execution_mode = ExecutionMode.RAW<EOL><DEDENT>elif self.module is not None:<EOL><INDENT>base_command = '<STR_LIT>'<EOL>self.execution_mode = ExecutionMode.ANSIBLE<EOL><DEDENT>else:<EOL><INDENT>base_command = '<STR_LIT>'<EOL>self.execution_mode... | Given that the ``RunnerConfig`` preparation methods have been run to gather the inputs this method
will generate the ``ansible`` or ``ansible-playbook`` command that will be used by the
:py:class:`ansible_runner.runner.Runner` object to start the process | f859:c1:m5 |
def build_process_isolation_temp_dir(self): | path = tempfile.mkdtemp(prefix='<STR_LIT>', dir=self.process_isolation_path)<EOL>os.chmod(path, stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR)<EOL>atexit.register(shutil.rmtree, path)<EOL>return path<EOL> | Create a temporary directory for process isolation to use. | f859:c1:m6 |
def wrap_args_with_process_isolation(self, args): | cwd = os.path.realpath(self.cwd)<EOL>pi_temp_dir = self.build_process_isolation_temp_dir()<EOL>new_args = [self.process_isolation_executable or '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT:/>', '<STR_LIT:/>', '<STR_LIT>', '<STR_LIT>']<EOL>for path in sorted(set(self.process_isolation_hide_paths or [])):<EOL><INDENT... | Wrap existing command line with bwrap to restrict access to:
- self.process_isolation_path (generally, /tmp) (except for own /tmp files) | f859:c1:m7 |
def wrap_args_with_ssh_agent(self, args, ssh_key_path, ssh_auth_sock=None, silence_ssh_add=False): | if ssh_key_path:<EOL><INDENT>ssh_add_command = args2cmdline('<STR_LIT>', ssh_key_path)<EOL>if silence_ssh_add:<EOL><INDENT>ssh_add_command = '<STR_LIT:U+0020>'.join([ssh_add_command, '<STR_LIT>'])<EOL><DEDENT>cmd = '<STR_LIT>'.join([ssh_add_command,<EOL>args2cmdline('<STR_LIT>', '<STR_LIT>', ssh_key_path),<EOL>args2cmd... | Given an existing command line and parameterization this will return the same command line wrapped with the
necessary calls to ``ssh-agent`` | f859:c1:m8 |
def _load_json(self, contents): | try:<EOL><INDENT>return json.loads(contents)<EOL><DEDENT>except ValueError:<EOL><INDENT>pass<EOL><DEDENT> | Attempts to deserialize the contents of a JSON object
Args:
contents (string): The contents to deserialize
Returns:
dict: If the contents are JSON serialized
None: If the contents are not JSON serialized | f860:c0:m1 |
def _load_yaml(self, contents): | try:<EOL><INDENT>return safe_load(contents)<EOL><DEDENT>except YAMLError:<EOL><INDENT>pass<EOL><DEDENT> | Attempts to deserialize the contents of a YAML object
Args:
contents (string): The contents to deserialize
Returns:
dict: If the contents are YAML serialized
None: If the contents are not YAML serialized | f860:c0:m2 |
def get_contents(self, path): | try:<EOL><INDENT>if not os.path.exists(path):<EOL><INDENT>raise ConfigurationError('<STR_LIT>' % path)<EOL><DEDENT>with open(path) as f:<EOL><INDENT>data = f.read()<EOL><DEDENT>return data<EOL><DEDENT>except (IOError, OSError) as exc:<EOL><INDENT>raise ConfigurationError('<STR_LIT>' % exc)<EOL><DEDENT> | Loads the contents of the file specified by path
Args:
path (string): The relative or absolute path to the file to
be loaded. If the path is relative, then it is combined
with the base_path to generate a full path string
Returns:
string: The contents of the file as a string
Raises:
Confi... | f860:c0:m3 |
def abspath(self, path): | if not path.startswith(os.path.sep) or path.startswith('<STR_LIT>'):<EOL><INDENT>path = os.path.expanduser(os.path.join(self.base_path, path))<EOL><DEDENT>return path<EOL> | Transform the path to an absolute path
Args:
path (string): The path to transform to an absolute path
Returns:
string: The absolute path to the file | f860:c0:m4 |
def isfile(self, path): | return os.path.isfile(self.abspath(path))<EOL> | Check if the path is a file
:params path: The path to the file to check. If the path is relative
it will be exanded to an absolute path
:returns: boolean | f860:c0:m5 |
def load_file(self, path, objtype=None, encoding='<STR_LIT:utf-8>'): | path = self.abspath(path)<EOL>debug('<STR_LIT>' % path)<EOL>if path in self._cache:<EOL><INDENT>return self._cache[path]<EOL><DEDENT>try:<EOL><INDENT>debug('<STR_LIT>' % path)<EOL>contents = parsed_data = self.get_contents(path)<EOL>if encoding:<EOL><INDENT>parsed_data = contents.encode(encoding)<EOL><DEDENT><DEDENT>ex... | Load the file specified by path
This method will first try to load the file contents from cache and
if there is a cache miss, it will load the contents from disk
Args:
path (string): The full or relative path to the file to be loaded
encoding (string): The file contents text encoding
objtype (object): T... | f860:c0:m6 |
def isplaybook(obj): | return isinstance(obj, Iterable) and (not isinstance(obj, string_types) and not isinstance(obj, Mapping))<EOL> | Inspects the object and returns if it is a playbook
Args:
obj (object): The object to be inspected by this function
Returns:
boolean: True if the object is a list and False if it is not | f870:m0 |
def isinventory(obj): | return isinstance(obj, Mapping) or isinstance(obj, string_types)<EOL> | Inspects the object and returns if it is an inventory
Args:
obj (object): The object to be inspected by this function
Returns:
boolean: True if the object is an inventory dict and False if it is not | f870:m1 |
def check_isolation_executable_installed(isolation_executable): | cmd = [isolation_executable, '<STR_LIT>']<EOL>try:<EOL><INDENT>proc = subprocess.Popen(cmd, stdout=subprocess.PIPE,<EOL>stderr=subprocess.PIPE)<EOL>proc.communicate()<EOL>return bool(proc.returncode == <NUM_LIT:0>)<EOL><DEDENT>except (OSError, ValueError) as e:<EOL><INDENT>if isinstance(e, ValueError) or getattr(e, '<S... | Check that proot is installed. | f870:m2 |
def dump_artifact(obj, path, filename=None): | p_sha1 = None<EOL>if not os.path.exists(path):<EOL><INDENT>os.makedirs(path, mode=<NUM_LIT>)<EOL><DEDENT>else:<EOL><INDENT>p_sha1 = hashlib.sha1()<EOL>p_sha1.update(obj.encode(encoding='<STR_LIT>'))<EOL><DEDENT>if filename is None:<EOL><INDENT>fd, fn = tempfile.mkstemp(dir=path)<EOL><DEDENT>else:<EOL><INDENT>fn = os.pa... | Write the artifact to disk at the specified path
Args:
obj (string): The string object to be dumped to disk in the specified
path. The artifact filename will be automatically created
path (string): The full path to the artifacts data directory.
filename (string, optional): The name of file to wr... | f870:m3 |
def dump_artifacts(kwargs): | private_data_dir = kwargs.get('<STR_LIT>')<EOL>if not private_data_dir:<EOL><INDENT>private_data_dir = tempfile.mkdtemp()<EOL>kwargs['<STR_LIT>'] = private_data_dir<EOL><DEDENT>if not os.path.exists(private_data_dir):<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if '<STR_LIT>' in kwargs:<EOL><INDENT>role = {'<... | Introspect the kwargs and dump objects to disk | f870:m5 |
def open_fifo_write(path, data): | os.mkfifo(path, stat.S_IRUSR | stat.S_IWUSR)<EOL>threading.Thread(target=lambda p, d: open(p, '<STR_LIT:wb>').write(d),<EOL>args=(path, data)).start()<EOL> | open_fifo_write opens the fifo named pipe in a new thread.
This blocks the thread until an external process (such as ssh-agent)
reads data from the pipe. | f870:m6 |
def ensure_str(s, encoding='<STR_LIT:utf-8>', errors='<STR_LIT:strict>'): | if not isinstance(s, (text_type, binary_type)):<EOL><INDENT>raise TypeError("<STR_LIT>" % type(s))<EOL><DEDENT>if PY2 and isinstance(s, text_type):<EOL><INDENT>s = s.encode(encoding, errors)<EOL><DEDENT>elif PY3 and isinstance(s, binary_type):<EOL><INDENT>s = s.decode(encoding, errors)<EOL><DEDENT>return s<EOL> | Copied from six==1.12
Coerce *s* to `str`.
For Python 2:
- `unicode` -> encoded to `str`
- `str` -> `str`
For Python 3:
- `str` -> `str`
- `bytes` -> decoded to `str` | f870:m8 |
def init_runner(**kwargs): | dump_artifacts(kwargs)<EOL>debug = kwargs.pop('<STR_LIT>', None)<EOL>logfile = kwargs.pop('<STR_LIT>', None)<EOL>if not kwargs.pop("<STR_LIT>", True):<EOL><INDENT>output.configure()<EOL>if debug in (True, False):<EOL><INDENT>output.set_debug('<STR_LIT>' if debug is True else '<STR_LIT>')<EOL><DEDENT>if logfile:<EOL><IN... | Initialize the Runner() instance
This function will properly initialize both run() and run_async()
functions in the same way and return a value instance of Runner.
See parameters given to :py:func:`ansible_runner.interface.run` | f871:m0 |
def run(**kwargs): | r = init_runner(**kwargs)<EOL>r.run()<EOL>return r<EOL> | Run an Ansible Runner task in the foreground and return a Runner object when complete.
:param private_data_dir: The directory containing all runner metadata needed to invoke the runner
module. Output artifacts will also be stored here for later consumption.
:param ident: The run identifier for... | f871:m1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.