repository_name stringclasses 316
values | func_path_in_repository stringlengths 6 223 | func_name stringlengths 1 134 | language stringclasses 1
value | func_code_string stringlengths 57 65.5k | func_documentation_string stringlengths 1 46.3k | split_name stringclasses 1
value | func_code_url stringlengths 91 315 | called_functions listlengths 1 156 ⌀ | enclosing_scope stringlengths 2 1.48M |
|---|---|---|---|---|---|---|---|---|---|
anlutro/russell | russell/engine.py | BlogEngine.add_pages | python | def add_pages(self, path='pages'):
pages_path = os.path.join(self.root_path, path)
pages = []
for file in _listfiles(pages_path):
page_dir = os.path.relpath(os.path.dirname(file), pages_path)
if page_dir == '.':
page_dir = None
pages.append(self.cm.Page.from_file(file, directory=page_dir))
self.cm.... | Look through a directory for markdown files and add them as pages. | train | https://github.com/anlutro/russell/blob/6e4a95929f031926d3acd5d9e6c9ca7bb896b1b5/russell/engine.py#L98-L109 | [
"def _listfiles(root_dir):\n\tresults = set()\n\n\tfor root, _, files in os.walk(root_dir):\n\t\tfor file in files:\n\t\t\tresults.add(os.path.join(root, file))\n\n\treturn results\n",
"def add_pages(self, pages, resort=True):\n\tself.pages.extend(pages)\n\tif resort:\n\t\tself.pages.sort()\n"
] | class BlogEngine:
"""
The main instance that contains blog configuration and content, as well as
generating end results.
"""
def __init__(self, root_path, root_url, site_title, site_desc=None):
"""
Constructor.
Args:
root_path (str): Full path to the directory which contains the posts,
pages, temp... |
anlutro/russell | russell/engine.py | BlogEngine.add_posts | python | def add_posts(self, path='posts'):
path = os.path.join(self.root_path, path)
self.cm.add_posts([
self.cm.Post.from_file(file)
for file in _listfiles(path)
]) | Look through a directory for markdown files and add them as posts. | train | https://github.com/anlutro/russell/blob/6e4a95929f031926d3acd5d9e6c9ca7bb896b1b5/russell/engine.py#L111-L119 | [
"def _listfiles(root_dir):\n\tresults = set()\n\n\tfor root, _, files in os.walk(root_dir):\n\t\tfor file in files:\n\t\t\tresults.add(os.path.join(root, file))\n\n\treturn results\n",
"def add_posts(self, posts, resort=True):\n\tself.posts.extend(posts)\n\tfor post in posts:\n\t\tfor tag in post.tags:\n\t\t\tif ... | class BlogEngine:
"""
The main instance that contains blog configuration and content, as well as
generating end results.
"""
def __init__(self, root_path, root_url, site_title, site_desc=None):
"""
Constructor.
Args:
root_path (str): Full path to the directory which contains the posts,
pages, temp... |
anlutro/russell | russell/engine.py | BlogEngine.copy_assets | python | def copy_assets(self, path='assets'):
path = os.path.join(self.root_path, path)
for root, _, files in os.walk(path):
for file in files:
fullpath = os.path.join(root, file)
relpath = os.path.relpath(fullpath, path)
copy_to = os.path.join(self._get_dist_path(relpath, directory='assets'))
LOG.debug(... | Copy assets into the destination directory. | train | https://github.com/anlutro/russell/blob/6e4a95929f031926d3acd5d9e6c9ca7bb896b1b5/russell/engine.py#L121-L132 | [
"def _get_dist_path(self, path, directory=None):\n\tif isinstance(path, str):\n\t\tpath = [path]\n\tif directory:\n\t\tpath.insert(0, directory)\n\treturn os.path.join(self.root_path, 'dist', *path)\n"
] | class BlogEngine:
"""
The main instance that contains blog configuration and content, as well as
generating end results.
"""
def __init__(self, root_path, root_url, site_title, site_desc=None):
"""
Constructor.
Args:
root_path (str): Full path to the directory which contains the posts,
pages, temp... |
anlutro/russell | russell/engine.py | BlogEngine.add_asset_hashes | python | def add_asset_hashes(self, path='dist/assets'):
for fullpath in _listfiles(os.path.join(self.root_path, path)):
relpath = fullpath.replace(self.root_path + '/' + path + '/', '')
md5sum = hashlib.md5(open(fullpath, 'rb').read()).hexdigest()
LOG.debug('MD5 of %s (%s): %s', fullpath, relpath, md5sum)
self.as... | Scan through a directory and add hashes for each file found. | train | https://github.com/anlutro/russell/blob/6e4a95929f031926d3acd5d9e6c9ca7bb896b1b5/russell/engine.py#L134-L142 | [
"def _listfiles(root_dir):\n\tresults = set()\n\n\tfor root, _, files in os.walk(root_dir):\n\t\tfor file in files:\n\t\t\tresults.add(os.path.join(root, file))\n\n\treturn results\n"
] | class BlogEngine:
"""
The main instance that contains blog configuration and content, as well as
generating end results.
"""
def __init__(self, root_path, root_url, site_title, site_desc=None):
"""
Constructor.
Args:
root_path (str): Full path to the directory which contains the posts,
pages, temp... |
anlutro/russell | russell/engine.py | BlogEngine.get_posts | python | def get_posts(self, num=None, tag=None, private=False):
posts = self.posts
if not private:
posts = [post for post in posts if post.public]
if tag:
posts = [post for post in posts if tag in post.tags]
if num:
return posts[:num]
return posts | Get all the posts added to the blog.
Args:
num (int): Optional. If provided, only return N posts (sorted by date,
most recent first).
tag (Tag): Optional. If provided, only return posts that have a
specific tag.
private (bool): By default (if False), private posts are not included.
If s... | train | https://github.com/anlutro/russell/blob/6e4a95929f031926d3acd5d9e6c9ca7bb896b1b5/russell/engine.py#L144-L166 | null | class BlogEngine:
"""
The main instance that contains blog configuration and content, as well as
generating end results.
"""
def __init__(self, root_path, root_url, site_title, site_desc=None):
"""
Constructor.
Args:
root_path (str): Full path to the directory which contains the posts,
pages, temp... |
anlutro/russell | russell/engine.py | BlogEngine.generate_pages | python | def generate_pages(self):
for page in self.pages:
self.generate_page(page.slug, template='page.html.jinja', page=page) | Generate HTML out of the pages added to the blog. | train | https://github.com/anlutro/russell/blob/6e4a95929f031926d3acd5d9e6c9ca7bb896b1b5/russell/engine.py#L180-L185 | [
"def generate_page(self, path, template, **kwargs):\n\t\"\"\"\n\tGenerate the HTML for a single page. You usually don't need to call this\n\tmethod manually, it is used by a lot of other, more end-user friendly\n\tmethods.\n\n\tArgs:\n\t path (str): Where to place the page relative to the root URL. Usually\n\t ... | class BlogEngine:
"""
The main instance that contains blog configuration and content, as well as
generating end results.
"""
def __init__(self, root_path, root_url, site_title, site_desc=None):
"""
Constructor.
Args:
root_path (str): Full path to the directory which contains the posts,
pages, temp... |
anlutro/russell | russell/engine.py | BlogEngine.generate_posts | python | def generate_posts(self):
for post in self.posts:
self.generate_page(
['posts', post.slug],
template='post.html.jinja',
post=post,
) | Generate single-post HTML files out of posts added to the blog. Will not
generate front page, archives or tag files - those have to be generated
separately. | train | https://github.com/anlutro/russell/blob/6e4a95929f031926d3acd5d9e6c9ca7bb896b1b5/russell/engine.py#L187-L198 | [
"def generate_page(self, path, template, **kwargs):\n\t\"\"\"\n\tGenerate the HTML for a single page. You usually don't need to call this\n\tmethod manually, it is used by a lot of other, more end-user friendly\n\tmethods.\n\n\tArgs:\n\t path (str): Where to place the page relative to the root URL. Usually\n\t ... | class BlogEngine:
"""
The main instance that contains blog configuration and content, as well as
generating end results.
"""
def __init__(self, root_path, root_url, site_title, site_desc=None):
"""
Constructor.
Args:
root_path (str): Full path to the directory which contains the posts,
pages, temp... |
anlutro/russell | russell/engine.py | BlogEngine.generate_tags | python | def generate_tags(self):
for tag in self.tags:
posts = self.get_posts(tag=tag, private=True)
self.generate_page(['tags', tag.slug],
template='archive.html.jinja', posts=posts) | Generate one HTML page for each tag, each containing all posts that
match that tag. | train | https://github.com/anlutro/russell/blob/6e4a95929f031926d3acd5d9e6c9ca7bb896b1b5/russell/engine.py#L200-L208 | [
"def get_posts(self, num=None, tag=None, private=False):\n\t\"\"\"\n\tGet all the posts added to the blog.\n\n\tArgs:\n\t num (int): Optional. If provided, only return N posts (sorted by date,\n\t most recent first).\n\t tag (Tag): Optional. If provided, only return posts that have a\n\t specific tag.\n\t ... | class BlogEngine:
"""
The main instance that contains blog configuration and content, as well as
generating end results.
"""
def __init__(self, root_path, root_url, site_title, site_desc=None):
"""
Constructor.
Args:
root_path (str): Full path to the directory which contains the posts,
pages, temp... |
anlutro/russell | russell/engine.py | BlogEngine.generate_page | python | def generate_page(self, path, template, **kwargs):
directory = None
if kwargs.get('page'):
directory = kwargs['page'].dir
path = self._get_dist_path(path, directory=directory)
if not path.endswith('.html'):
path = path + '.html'
if not os.path.isdir(os.path.dirname(path)):
os.makedirs(os.path.dirna... | Generate the HTML for a single page. You usually don't need to call this
method manually, it is used by a lot of other, more end-user friendly
methods.
Args:
path (str): Where to place the page relative to the root URL. Usually
something like "index", "about-me", "projects/example", etc.
template (... | train | https://github.com/anlutro/russell/blob/6e4a95929f031926d3acd5d9e6c9ca7bb896b1b5/russell/engine.py#L210-L238 | [
"def _get_dist_path(self, path, directory=None):\n\tif isinstance(path, str):\n\t\tpath = [path]\n\tif directory:\n\t\tpath.insert(0, directory)\n\treturn os.path.join(self.root_path, 'dist', *path)\n",
"def _get_template(self, template):\n\tif isinstance(template, str):\n\t\ttemplate = self.jinja.get_template(te... | class BlogEngine:
"""
The main instance that contains blog configuration and content, as well as
generating end results.
"""
def __init__(self, root_path, root_url, site_title, site_desc=None):
"""
Constructor.
Args:
root_path (str): Full path to the directory which contains the posts,
pages, temp... |
anlutro/russell | russell/engine.py | BlogEngine.generate_index | python | def generate_index(self, num_posts=5):
posts = self.get_posts(num=num_posts)
self.generate_page('index', template='index.html.jinja', posts=posts) | Generate the front page, aka index.html. | train | https://github.com/anlutro/russell/blob/6e4a95929f031926d3acd5d9e6c9ca7bb896b1b5/russell/engine.py#L240-L245 | [
"def get_posts(self, num=None, tag=None, private=False):\n\t\"\"\"\n\tGet all the posts added to the blog.\n\n\tArgs:\n\t num (int): Optional. If provided, only return N posts (sorted by date,\n\t most recent first).\n\t tag (Tag): Optional. If provided, only return posts that have a\n\t specific tag.\n\t ... | class BlogEngine:
"""
The main instance that contains blog configuration and content, as well as
generating end results.
"""
def __init__(self, root_path, root_url, site_title, site_desc=None):
"""
Constructor.
Args:
root_path (str): Full path to the directory which contains the posts,
pages, temp... |
anlutro/russell | russell/engine.py | BlogEngine.generate_rss | python | def generate_rss(self, path='rss.xml', only_excerpt=True, https=False):
feed = russell.feed.get_rss_feed(self, only_excerpt=only_excerpt, https=https)
feed.rss_file(self._get_dist_path(path)) | Generate the RSS feed.
Args:
path (str): Where to save the RSS file. Make sure that your jinja
templates refer to the same path using <link>.
only_excerpt (bool): If True (the default), don't include the full
body of posts in the RSS. Instead, include the first paragraph and
a "read more" l... | train | https://github.com/anlutro/russell/blob/6e4a95929f031926d3acd5d9e6c9ca7bb896b1b5/russell/engine.py#L253-L268 | [
"def get_rss_feed(blog, only_excerpt=True, https=False):\n\tgenerator = FeedGenerator()\n\n\troot_href = schema_url(blog.root_url, https)\n\tgenerator.id(root_href)\n\tgenerator.link(href=root_href, rel='alternate')\n\tgenerator.title(blog.site_title)\n\tgenerator.subtitle(blog.site_desc or blog.site_title)\n\n\tfo... | class BlogEngine:
"""
The main instance that contains blog configuration and content, as well as
generating end results.
"""
def __init__(self, root_path, root_url, site_title, site_desc=None):
"""
Constructor.
Args:
root_path (str): Full path to the directory which contains the posts,
pages, temp... |
anlutro/russell | russell/engine.py | BlogEngine.generate_sitemap | python | def generate_sitemap(self, path='sitemap.xml', https=False):
sitemap = russell.sitemap.generate_sitemap(self, https=https)
self.write_file(path, sitemap) | Generate an XML sitemap.
Args:
path (str): The name of the file to write to.
https (bool): If True, links inside the sitemap with relative scheme
(e.g. example.com/something) will be set to HTTPS. If False (the
default), they will be set to plain HTTP. | train | https://github.com/anlutro/russell/blob/6e4a95929f031926d3acd5d9e6c9ca7bb896b1b5/russell/engine.py#L270-L281 | [
"def generate_sitemap(blog, https=True):\n\treturn SitemapGenerator(blog, https).generate_sitemap()\n",
"def write_file(self, path, contents):\n\t\"\"\"\n\tWrite a file of any type to the destination path. Useful for files like\n\trobots.txt, manifest.json, and so on.\n\n\tArgs:\n\t path (str): The name of the f... | class BlogEngine:
"""
The main instance that contains blog configuration and content, as well as
generating end results.
"""
def __init__(self, root_path, root_url, site_title, site_desc=None):
"""
Constructor.
Args:
root_path (str): Full path to the directory which contains the posts,
pages, temp... |
anlutro/russell | russell/engine.py | BlogEngine.write_file | python | def write_file(self, path, contents):
path = self._get_dist_path(path)
if not os.path.isdir(os.path.dirname(path)):
os.makedirs(os.path.dirname(path))
if isinstance(contents, bytes):
mode = 'wb+'
else:
mode = 'w'
with open(path, mode) as file:
file.write(contents) | Write a file of any type to the destination path. Useful for files like
robots.txt, manifest.json, and so on.
Args:
path (str): The name of the file to write to.
contents (str or bytes): The contents to write. | train | https://github.com/anlutro/russell/blob/6e4a95929f031926d3acd5d9e6c9ca7bb896b1b5/russell/engine.py#L283-L300 | [
"def _get_dist_path(self, path, directory=None):\n\tif isinstance(path, str):\n\t\tpath = [path]\n\tif directory:\n\t\tpath.insert(0, directory)\n\treturn os.path.join(self.root_path, 'dist', *path)\n"
] | class BlogEngine:
"""
The main instance that contains blog configuration and content, as well as
generating end results.
"""
def __init__(self, root_path, root_url, site_title, site_desc=None):
"""
Constructor.
Args:
root_path (str): Full path to the directory which contains the posts,
pages, temp... |
btr1975/persistentdatatools | persistentdatatools/persistentdatatools.py | verify_file_exists | python | def verify_file_exists(file_name, file_location):
return __os.path.isfile(__os.path.join(file_location, file_name)) | Function to verify if a file exists
Args:
file_name: The name of file to check
file_location: The location of the file, derive from the os module
Returns: returns boolean True or False | train | https://github.com/btr1975/persistentdatatools/blob/39e1294ce34a0a34363c65d94cdd592be5ad791b/persistentdatatools/persistentdatatools.py#L77-L87 | null | #!/usr/bin/env python3
##########################################################
# Script Name: modPersistentDataTools.py #
# Script Type: Python #
# Updated By: Benjamin P. Trachtenberg #
# Date Written 9/17/2015 #
# ... |
btr1975/persistentdatatools | persistentdatatools/persistentdatatools.py | file_name_increase | python | def file_name_increase(file_name, file_location):
add_one = 1
file_name_temp = file_name
while verify_file_exists(file_name_temp, file_location):
try:
name, file_extension = file_name.split('.')
file_name_temp = '%s-%i.%s' % (name, add_one, file_extension)
except Exce... | Function to increase a filename by a number 1
Args:
file_name: The name of file to check
file_location: The location of the file, derive from the os module
Returns: returns a good filename. | train | https://github.com/btr1975/persistentdatatools/blob/39e1294ce34a0a34363c65d94cdd592be5ad791b/persistentdatatools/persistentdatatools.py#L90-L112 | [
"def verify_file_exists(file_name, file_location):\n \"\"\"\n Function to verify if a file exists\n Args:\n file_name: The name of file to check\n file_location: The location of the file, derive from the os module\n\n Returns: returns boolean True or False\n\n \"\"\"\n return __os.pa... | #!/usr/bin/env python3
##########################################################
# Script Name: modPersistentDataTools.py #
# Script Type: Python #
# Updated By: Benjamin P. Trachtenberg #
# Date Written 9/17/2015 #
# ... |
btr1975/persistentdatatools | persistentdatatools/persistentdatatools.py | verify_directory | python | def verify_directory(directory_name, directory_location, directory_create=False):
if not directory_create:
return __os.path.exists(__os.path.join(directory_location, directory_name))
elif directory_create:
good = __os.path.exists(__os.path.join(directory_location, directory_name))
if not... | Function to verify if a directory exists
Args:
directory_name: The name of directory to check
directory_location: The location of the directory, derive from the os module
directory_create: If you want to create the directory
Returns: returns boolean True or False, but if you set directo... | train | https://github.com/btr1975/persistentdatatools/blob/39e1294ce34a0a34363c65d94cdd592be5ad791b/persistentdatatools/persistentdatatools.py#L115-L131 | null | #!/usr/bin/env python3
##########################################################
# Script Name: modPersistentDataTools.py #
# Script Type: Python #
# Updated By: Benjamin P. Trachtenberg #
# Date Written 9/17/2015 #
# ... |
btr1975/persistentdatatools | persistentdatatools/persistentdatatools.py | list_to_file | python | def list_to_file(orig_list, file_name, file_location):
file = __os.path.join(file_location, file_name)
def add_line_break(list_line):
"""
Create a line break at the end of a string
Args:
list_line: string
Returns: A string with a line break
"""
list... | Function to export a list to a text file
Args:
orig_list: The list you want exported
file_name: The name of the exported file
file_location: The location of the file, derive from the os module
Returns: returns the filename info | train | https://github.com/btr1975/persistentdatatools/blob/39e1294ce34a0a34363c65d94cdd592be5ad791b/persistentdatatools/persistentdatatools.py#L134-L162 | [
"def add_line_break(list_line):\n \"\"\"\n Create a line break at the end of a string\n Args:\n list_line: string\n\n Returns: A string with a line break\n\n \"\"\"\n list_line = ('%s\\n' % (list_line,))\n return list_line\n"
] | #!/usr/bin/env python3
##########################################################
# Script Name: modPersistentDataTools.py #
# Script Type: Python #
# Updated By: Benjamin P. Trachtenberg #
# Date Written 9/17/2015 #
# ... |
btr1975/persistentdatatools | persistentdatatools/persistentdatatools.py | file_to_list | python | def file_to_list(file_name, file_location):
file = __os.path.join(file_location, file_name)
read_file = open(file, "r")
temp_list = read_file.read().splitlines()
read_file.close()
return temp_list | Function to import a text file to a list
Args:
file_name: The name of file to be import
file_location: The location of the file, derive from the os module
Returns: returns a list | train | https://github.com/btr1975/persistentdatatools/blob/39e1294ce34a0a34363c65d94cdd592be5ad791b/persistentdatatools/persistentdatatools.py#L165-L179 | null | #!/usr/bin/env python3
##########################################################
# Script Name: modPersistentDataTools.py #
# Script Type: Python #
# Updated By: Benjamin P. Trachtenberg #
# Date Written 9/17/2015 #
# ... |
btr1975/persistentdatatools | persistentdatatools/persistentdatatools.py | csv_to_dict | python | def csv_to_dict(file_name, file_location):
file = __os.path.join(file_location, file_name)
try:
csv_read = open(file, "r")
except Exception as e:
LOGGER.critical('Function csv_to_dict Error {error} ignoring any errors'.format(error=e))
print('Error {error} ignoring any errors'.format... | Function to import a csv as a dictionary
Args:
file_name: The name of the csv file
file_location: The location of the file, derive from the os module
Returns: returns a dictionary | train | https://github.com/btr1975/persistentdatatools/blob/39e1294ce34a0a34363c65d94cdd592be5ad791b/persistentdatatools/persistentdatatools.py#L182-L206 | null | #!/usr/bin/env python3
##########################################################
# Script Name: modPersistentDataTools.py #
# Script Type: Python #
# Updated By: Benjamin P. Trachtenberg #
# Date Written 9/17/2015 #
# ... |
btr1975/persistentdatatools | persistentdatatools/persistentdatatools.py | dict_to_csv | python | def dict_to_csv(orig_dict, file_name, field_names_tuple, file_location):
file = __os.path.join(file_location, file_name)
csv_write = open(file, 'a')
writer = __csv.DictWriter(csv_write, fieldnames=field_names_tuple, lineterminator='\n')
headers = dict((n, n) for n in field_names_tuple)
writer.writer... | Function to export a dictionary to a csv file
Args:
orig_dict: The dictionary you want exported
file_name: The name of the exported file
field_names_tuple: The fieldnames in a tuple
file_location: The location of the file, derive from the os module
Returns: returns the filename ... | train | https://github.com/btr1975/persistentdatatools/blob/39e1294ce34a0a34363c65d94cdd592be5ad791b/persistentdatatools/persistentdatatools.py#L209-L229 | null | #!/usr/bin/env python3
##########################################################
# Script Name: modPersistentDataTools.py #
# Script Type: Python #
# Updated By: Benjamin P. Trachtenberg #
# Date Written 9/17/2015 #
# ... |
btr1975/persistentdatatools | persistentdatatools/persistentdatatools.py | store_object | python | def store_object(file_name, save_key, file_location, object_to_store=None):
file = __os.path.join(file_location, file_name)
try:
shelve_store = __shelve.open(file)
except Exception as e:
LOGGER.critical('Function store_object Error {error} ignoring any errors'.format(error=e))
print(... | Function to store objects in a shelve
Args:
file_name: Shelve storage file name
save_key: The name of the key to store the item to
file_location: The location of the file, derive from the os module
object_to_store: The object you want to store
Returns: | train | https://github.com/btr1975/persistentdatatools/blob/39e1294ce34a0a34363c65d94cdd592be5ad791b/persistentdatatools/persistentdatatools.py#L232-L253 | null | #!/usr/bin/env python3
##########################################################
# Script Name: modPersistentDataTools.py #
# Script Type: Python #
# Updated By: Benjamin P. Trachtenberg #
# Date Written 9/17/2015 #
# ... |
btr1975/persistentdatatools | persistentdatatools/persistentdatatools.py | retrieve_object_from_file | python | def retrieve_object_from_file(file_name, save_key, file_location):
shelve_store = None
file = __os.path.join(file_location, file_name)
try:
shelve_store = __shelve.open(file)
except Exception as e:
LOGGER.critical('Function retrieve_object_from_file Error {error} ignoring any errors'.for... | Function to retrieve objects from a shelve
Args:
file_name: Shelve storage file name
save_key: The name of the key the item is stored in
file_location: The location of the file, derive from the os module
Returns: Returns the stored object | train | https://github.com/btr1975/persistentdatatools/blob/39e1294ce34a0a34363c65d94cdd592be5ad791b/persistentdatatools/persistentdatatools.py#L256-L276 | null | #!/usr/bin/env python3
##########################################################
# Script Name: modPersistentDataTools.py #
# Script Type: Python #
# Updated By: Benjamin P. Trachtenberg #
# Date Written 9/17/2015 #
# ... |
btr1975/persistentdatatools | persistentdatatools/persistentdatatools.py | delete_object_from_file | python | def delete_object_from_file(file_name, save_key, file_location):
file = __os.path.join(file_location, file_name)
shelve_store = __shelve.open(file)
del shelve_store[save_key]
shelve_store.close() | Function to delete objects from a shelve
Args:
file_name: Shelve storage file name
save_key: The name of the key the item is stored in
file_location: The location of the file, derive from the os module
Returns: | train | https://github.com/btr1975/persistentdatatools/blob/39e1294ce34a0a34363c65d94cdd592be5ad791b/persistentdatatools/persistentdatatools.py#L279-L293 | null | #!/usr/bin/env python3
##########################################################
# Script Name: modPersistentDataTools.py #
# Script Type: Python #
# Updated By: Benjamin P. Trachtenberg #
# Date Written 9/17/2015 #
# ... |
btr1975/persistentdatatools | persistentdatatools/persistentdatatools.py | verify_key_in_shelve | python | def verify_key_in_shelve(file_name, save_key, file_location):
file = __os.path.join(file_location, file_name)
shelve_store = __shelve.open(file)
exists = shelve_store.get(save_key)
shelve_store.close()
if exists:
return True
elif not exists:
return False | Function to check for a key in a shelve
Args:
file_name: Shelve storage file name
save_key: The name of the key the item is stored in
file_location: The location of the file, derive from the os module
Returns: returns true or false | train | https://github.com/btr1975/persistentdatatools/blob/39e1294ce34a0a34363c65d94cdd592be5ad791b/persistentdatatools/persistentdatatools.py#L296-L315 | null | #!/usr/bin/env python3
##########################################################
# Script Name: modPersistentDataTools.py #
# Script Type: Python #
# Updated By: Benjamin P. Trachtenberg #
# Date Written 9/17/2015 #
# ... |
btr1975/persistentdatatools | persistentdatatools/persistentdatatools.py | get_keys_from_shelve | python | def get_keys_from_shelve(file_name, file_location):
temp_list = list()
file = __os.path.join(file_location, file_name)
shelve_store = __shelve.open(file)
for key in shelve_store:
temp_list.append(key)
shelve_store.close()
return temp_list | Function to retreive all keys in a shelve
Args:
file_name: Shelve storage file name
file_location: The location of the file, derive from the os module
Returns:
a list of the keys | train | https://github.com/btr1975/persistentdatatools/blob/39e1294ce34a0a34363c65d94cdd592be5ad791b/persistentdatatools/persistentdatatools.py#L318-L335 | null | #!/usr/bin/env python3
##########################################################
# Script Name: modPersistentDataTools.py #
# Script Type: Python #
# Updated By: Benjamin P. Trachtenberg #
# Date Written 9/17/2015 #
# ... |
btr1975/persistentdatatools | persistentdatatools/persistentdatatools.py | remove_symbol_add_symbol | python | def remove_symbol_add_symbol(string_item, remove_symbol, add_symbol):
string_item = add_symbol.join(string_item.split(remove_symbol))
return string_item | Remove a symbol from a string, and replace it with a different one
Args:
string_item: String that you want to replace symbols in
remove_symbol: Symbol to remove
add_symbol: Symbol to add
Returns: returns a string with symbols swapped | train | https://github.com/btr1975/persistentdatatools/blob/39e1294ce34a0a34363c65d94cdd592be5ad791b/persistentdatatools/persistentdatatools.py#L377-L389 | null | #!/usr/bin/env python3
##########################################################
# Script Name: modPersistentDataTools.py #
# Script Type: Python #
# Updated By: Benjamin P. Trachtenberg #
# Date Written 9/17/2015 #
# ... |
btr1975/persistentdatatools | persistentdatatools/persistentdatatools.py | list_files_in_directory | python | def list_files_in_directory(full_directory_path):
files = list()
for file_name in __os.listdir(full_directory_path):
if __os.path.isfile(__os.path.join(full_directory_path, file_name)):
files.append(file_name)
return files | List the files in a specified directory
Args:
full_directory_path: The full directory path to check, derive from the os module
Returns: returns a list of files | train | https://github.com/btr1975/persistentdatatools/blob/39e1294ce34a0a34363c65d94cdd592be5ad791b/persistentdatatools/persistentdatatools.py#L392-L405 | null | #!/usr/bin/env python3
##########################################################
# Script Name: modPersistentDataTools.py #
# Script Type: Python #
# Updated By: Benjamin P. Trachtenberg #
# Date Written 9/17/2015 #
# ... |
btr1975/persistentdatatools | persistentdatatools/persistentdatatools.py | list_directories_in_directory | python | def list_directories_in_directory(full_directory_path):
directories = list()
for directory_name in __os.listdir(full_directory_path):
if __os.path.isdir(__os.path.join(full_directory_path, directory_name)):
directories.append(directory_name)
return directories | List the directories in a specified directory
Args:
full_directory_path: The full directory path to check, derive from the os module
Returns: returns a list of directories | train | https://github.com/btr1975/persistentdatatools/blob/39e1294ce34a0a34363c65d94cdd592be5ad791b/persistentdatatools/persistentdatatools.py#L408-L421 | null | #!/usr/bin/env python3
##########################################################
# Script Name: modPersistentDataTools.py #
# Script Type: Python #
# Updated By: Benjamin P. Trachtenberg #
# Date Written 9/17/2015 #
# ... |
btr1975/persistentdatatools | persistentdatatools/persistentdatatools.py | split_strings_in_list_retain_spaces | python | def split_strings_in_list_retain_spaces(orig_list):
temp_list = list()
for line in orig_list:
line_split = __re.split(r'(\s+)', line)
temp_list.append(line_split)
return temp_list | Function to split every line in a list, and retain spaces for a rejoin
:param orig_list: Original list
:return:
A List with split lines | train | https://github.com/btr1975/persistentdatatools/blob/39e1294ce34a0a34363c65d94cdd592be5ad791b/persistentdatatools/persistentdatatools.py#L446-L459 | null | #!/usr/bin/env python3
##########################################################
# Script Name: modPersistentDataTools.py #
# Script Type: Python #
# Updated By: Benjamin P. Trachtenberg #
# Date Written 9/17/2015 #
# ... |
btr1975/persistentdatatools | persistentdatatools/persistentdatatools.py | random_line_data | python | def random_line_data(chars_per_line=80):
return ''.join(__random.choice(__string.ascii_letters) for x in range(chars_per_line)) | Function to create a line of a random string
Args:
chars_per_line: An integer that says how many characters to return
Returns:
A String | train | https://github.com/btr1975/persistentdatatools/blob/39e1294ce34a0a34363c65d94cdd592be5ad791b/persistentdatatools/persistentdatatools.py#L462-L472 | null | #!/usr/bin/env python3
##########################################################
# Script Name: modPersistentDataTools.py #
# Script Type: Python #
# Updated By: Benjamin P. Trachtenberg #
# Date Written 9/17/2015 #
# ... |
btr1975/persistentdatatools | persistentdatatools/persistentdatatools.py | random_data | python | def random_data(line_count=1, chars_per_line=80):
divide_lines = chars_per_line * line_count
return '\n'.join(random_line_data(chars_per_line) for x in range(int(divide_lines / chars_per_line))) | Function to creates lines of random string data
Args:
line_count: An integer that says how many lines to return
chars_per_line: An integer that says how many characters per line to return
Returns:
A String | train | https://github.com/btr1975/persistentdatatools/blob/39e1294ce34a0a34363c65d94cdd592be5ad791b/persistentdatatools/persistentdatatools.py#L475-L487 | null | #!/usr/bin/env python3
##########################################################
# Script Name: modPersistentDataTools.py #
# Script Type: Python #
# Updated By: Benjamin P. Trachtenberg #
# Date Written 9/17/2015 #
# ... |
btr1975/persistentdatatools | persistentdatatools/persistentdatatools.py | collect_and_zip_files | python | def collect_and_zip_files(dir_list, output_dir, zip_file_name, file_extension_list=None, file_name_list=None):
temp_list = list()
if isinstance(dir_list, list):
for dir_name in dir_list:
if not __os.path.isdir(dir_name):
error = 'Function collect_and_zip_files received an it... | Function to collect files and make a zip file
:param dir_list: A list of directories
:param output_dir: The output directory
:param zip_file_name: Zip file name
:param file_extension_list: A list of extensions of files to find
:param file_name_list: A list of file names to find
:return:
... | train | https://github.com/btr1975/persistentdatatools/blob/39e1294ce34a0a34363c65d94cdd592be5ad791b/persistentdatatools/persistentdatatools.py#L490-L569 | [
"def list_files_in_directory(full_directory_path):\n \"\"\"\n List the files in a specified directory\n Args:\n full_directory_path: The full directory path to check, derive from the os module\n\n Returns: returns a list of files\n\n \"\"\"\n files = list()\n for file_name in __os.listdi... | #!/usr/bin/env python3
##########################################################
# Script Name: modPersistentDataTools.py #
# Script Type: Python #
# Updated By: Benjamin P. Trachtenberg #
# Date Written 9/17/2015 #
# ... |
racker/torment | torment/contexts/docker/compose.py | up | python | def up(services: Iterable[str] = ()) -> int:
'''Start the specified docker-compose services.
Parameters
----------
:``services``: a list of docker-compose service names to start (must be
defined in docker-compose.yml)
Return Value(s)
---------------
The integer status ... | Start the specified docker-compose services.
Parameters
----------
:``services``: a list of docker-compose service names to start (must be
defined in docker-compose.yml)
Return Value(s)
---------------
The integer status of ``docker-compose up``. | train | https://github.com/racker/torment/blob/bd5d2f978324bf9b7360edfae76d853b226c63e1/torment/contexts/docker/compose.py#L54-L75 | [
"def _call(command: str, *args, **kwargs) -> int:\n '''Wrapper around ``subprocess.Popen`` that sends command output to logger.\n\n .. seealso::\n\n ``subprocess.Popen``_\n\n Parameters\n ----------\n\n :``command``: string form of the command to execute\n\n All other parameters are passed d... | # Copyright 2015 Alex Brandt
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
racker/torment | torment/contexts/docker/compose.py | _call | python | def _call(command: str, *args, **kwargs) -> int:
'''Wrapper around ``subprocess.Popen`` that sends command output to logger.
.. seealso::
``subprocess.Popen``_
Parameters
----------
:``command``: string form of the command to execute
All other parameters are passed directly to ``subp... | Wrapper around ``subprocess.Popen`` that sends command output to logger.
.. seealso::
``subprocess.Popen``_
Parameters
----------
:``command``: string form of the command to execute
All other parameters are passed directly to ``subprocess.Popen``.
Return Value(s)
---------------... | train | https://github.com/racker/torment/blob/bd5d2f978324bf9b7360edfae76d853b226c63e1/torment/contexts/docker/compose.py#L78-L118 | [
"def log():\n '''Send processes stdout and stderr to logger.'''\n\n for fh in select.select(( child.stdout, child.stderr, ), (), (), 0)[0]:\n line = fh.readline()[:-1]\n\n if len(line):\n getattr(logger, {\n child.stdout: 'debug',\n child.stderr: 'error',... | # Copyright 2015 Alex Brandt
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
racker/torment | torment/fixtures/__init__.py | of | python | def of(fixture_classes: Iterable[type], context: Union[None, 'torment.TestContext'] = None) -> Iterable['torment.fixtures.Fixture']:
'''Obtain all Fixture objects of the provided classes.
**Parameters**
:``fixture_classes``: classes inheriting from ``torment.fixtures.Fixture``
:``context``: a ... | Obtain all Fixture objects of the provided classes.
**Parameters**
:``fixture_classes``: classes inheriting from ``torment.fixtures.Fixture``
:``context``: a ``torment.TestContext`` to initialize Fixtures with
**Return Value(s)**
Instantiated ``torment.fixtures.Fixture`` objects for each... | train | https://github.com/racker/torment/blob/bd5d2f978324bf9b7360edfae76d853b226c63e1/torment/fixtures/__init__.py#L293-L320 | null | # Copyright 2015 Alex Brandt
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
racker/torment | torment/fixtures/__init__.py | register | python | def register(namespace, base_classes: Tuple[type], properties: Dict[str, Any]) -> None:
'''Register a Fixture class in namespace with the given properties.
Creates a Fixture class (not object) and inserts it into the provided
namespace. The properties is a dict but allows functions to reference other
... | Register a Fixture class in namespace with the given properties.
Creates a Fixture class (not object) and inserts it into the provided
namespace. The properties is a dict but allows functions to reference other
properties and acts like a small DSL (domain specific language). This is
really just a dec... | train | https://github.com/racker/torment/blob/bd5d2f978324bf9b7360edfae76d853b226c63e1/torment/fixtures/__init__.py#L323-L438 | [
"def _unique_class_name(namespace: Dict[str, Any], uuid: uuid.UUID) -> str:\n '''Generate unique to namespace name for a class using uuid.\n\n **Parameters**\n\n :``namespace``: the namespace to verify uniqueness against\n :``uuid``: the \"unique\" portion of the name\n\n **Return Value(s)**\n\n... | # Copyright 2015 Alex Brandt
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
racker/torment | torment/fixtures/__init__.py | _prepare_mock | python | def _prepare_mock(context: 'torment.contexts.TestContext', symbol: str, return_value = None, side_effect = None) -> None:
'''Sets return value or side effect of symbol's mock in context.
.. seealso:: :py:func:`_find_mocker`
**Parameters**
:``context``: the search context
:``symbol``: ... | Sets return value or side effect of symbol's mock in context.
.. seealso:: :py:func:`_find_mocker`
**Parameters**
:``context``: the search context
:``symbol``: the symbol to be located
:``return_value``: pass through to mock ``return_value``
:``side_effect``: pass through to m... | train | https://github.com/racker/torment/blob/bd5d2f978324bf9b7360edfae76d853b226c63e1/torment/fixtures/__init__.py#L441-L482 | null | # Copyright 2015 Alex Brandt
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
racker/torment | torment/fixtures/__init__.py | _find_mocker | python | def _find_mocker(symbol: str, context: 'torment.contexts.TestContext') -> Callable[[], bool]:
'''Find method within the context that mocks symbol.
Given a symbol (i.e. ``tornado.httpclient.AsyncHTTPClient.fetch``), find
the shortest ``mock_`` method that resembles the symbol. Resembles means
the lowerc... | Find method within the context that mocks symbol.
Given a symbol (i.e. ``tornado.httpclient.AsyncHTTPClient.fetch``), find
the shortest ``mock_`` method that resembles the symbol. Resembles means
the lowercased and periods replaced with underscores.
If no match is found, a dummy function (only returns... | train | https://github.com/racker/torment/blob/bd5d2f978324bf9b7360edfae76d853b226c63e1/torment/fixtures/__init__.py#L485-L534 | null | # Copyright 2015 Alex Brandt
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
racker/torment | torment/fixtures/__init__.py | _resolve_functions | python | def _resolve_functions(functions: Dict[str, Callable[[Any], Any]], fixture: Fixture) -> None:
'''Apply functions and collect values as properties on fixture.
Call functions and apply their values as properteis on fixture.
Functions will continue to get applied until no more functions resolve.
All unres... | Apply functions and collect values as properties on fixture.
Call functions and apply their values as properteis on fixture.
Functions will continue to get applied until no more functions resolve.
All unresolved functions are logged and the last exception to have
occurred is also logged. This function... | train | https://github.com/racker/torment/blob/bd5d2f978324bf9b7360edfae76d853b226c63e1/torment/fixtures/__init__.py#L537-L579 | null | # Copyright 2015 Alex Brandt
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
racker/torment | torment/fixtures/__init__.py | _unique_class_name | python | def _unique_class_name(namespace: Dict[str, Any], uuid: uuid.UUID) -> str:
'''Generate unique to namespace name for a class using uuid.
**Parameters**
:``namespace``: the namespace to verify uniqueness against
:``uuid``: the "unique" portion of the name
**Return Value(s)**
A unique stri... | Generate unique to namespace name for a class using uuid.
**Parameters**
:``namespace``: the namespace to verify uniqueness against
:``uuid``: the "unique" portion of the name
**Return Value(s)**
A unique string (in namespace) using uuid. | train | https://github.com/racker/torment/blob/bd5d2f978324bf9b7360edfae76d853b226c63e1/torment/fixtures/__init__.py#L582-L603 | null | # Copyright 2015 Alex Brandt
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
racker/torment | torment/fixtures/__init__.py | Fixture.category | python | def category(self) -> str:
'''Fixture's category (the containing testing module name)
**Examples**
:module: test_torment.test_unit.test_fixtures.fixture_a44bc6dda6654b1395a8c2cbd55d964d
:category: fixtures
'''
logger.debug('dir(self.__module__): %s', dir(self.__modu... | Fixture's category (the containing testing module name)
**Examples**
:module: test_torment.test_unit.test_fixtures.fixture_a44bc6dda6654b1395a8c2cbd55d964d
:category: fixtures | train | https://github.com/racker/torment/blob/bd5d2f978324bf9b7360edfae76d853b226c63e1/torment/fixtures/__init__.py#L166-L178 | null | class Fixture(object):
'''Collection of data and actions for a particular test case.
Intended as a base class for custom fixtures. Fixture provides an API
that simplifies writing scalable test cases.
Creating Fixture objects is broken into two parts. This keeps the logic for
a class of test case... |
racker/torment | torment/fixtures/__init__.py | Fixture.description | python | def description(self) -> str:
'''Test name in nose output (intended to be overridden).'''
return '{0.uuid.hex}—{1}'.format(self, self.context.module) | Test name in nose output (intended to be overridden). | train | https://github.com/racker/torment/blob/bd5d2f978324bf9b7360edfae76d853b226c63e1/torment/fixtures/__init__.py#L181-L184 | null | class Fixture(object):
'''Collection of data and actions for a particular test case.
Intended as a base class for custom fixtures. Fixture provides an API
that simplifies writing scalable test cases.
Creating Fixture objects is broken into two parts. This keeps the logic for
a class of test case... |
racker/torment | torment/fixtures/__init__.py | Fixture._execute | python | def _execute(self) -> None:
'''Run Fixture actions (setup, run, check).
Core test loop for Fixture. Executes setup, run, and check in order.
'''
if hasattr(self, '_last_resolver_exception'):
logger.warning('last exception from %s.%s:', self.__class__.__name__, self._last_... | Run Fixture actions (setup, run, check).
Core test loop for Fixture. Executes setup, run, and check in order. | train | https://github.com/racker/torment/blob/bd5d2f978324bf9b7360edfae76d853b226c63e1/torment/fixtures/__init__.py#L235-L247 | null | class Fixture(object):
'''Collection of data and actions for a particular test case.
Intended as a base class for custom fixtures. Fixture provides an API
that simplifies writing scalable test cases.
Creating Fixture objects is broken into two parts. This keeps the logic for
a class of test case... |
racker/torment | torment/fixtures/__init__.py | ErrorFixture.run | python | def run(self) -> None:
'''Calls sibling with exception expectation.'''
with self.context.assertRaises(self.error.__class__) as error:
super().run()
self.exception = error.exception | Calls sibling with exception expectation. | train | https://github.com/racker/torment/blob/bd5d2f978324bf9b7360edfae76d853b226c63e1/torment/fixtures/__init__.py#L283-L289 | null | class ErrorFixture(Fixture):
'''Common error checking for Fixture.
Intended as a mixin when registering a new Fixture (via register) that will
check an error case (one throwing an exception).
**Examples**
Using the AddFixture from the Examples in Fixture, we can create a Fixture
that handles ... |
racker/torment | torment/helpers.py | evert | python | def evert(iterable: Iterable[Dict[str, Tuple]]) -> Iterable[Iterable[Dict[str, Any]]]:
'''Evert dictionaries with tuples.
Iterates over the list of dictionaries and everts them with their tuple
values. For example:
``[ { 'a': ( 1, 2, ), }, ]``
becomes
``[ ( { 'a': 1, }, ), ( { 'a', 2, }, ) ... | Evert dictionaries with tuples.
Iterates over the list of dictionaries and everts them with their tuple
values. For example:
``[ { 'a': ( 1, 2, ), }, ]``
becomes
``[ ( { 'a': 1, }, ), ( { 'a', 2, }, ) ]``
The resulting iterable contains the same number of tuples as the
initial iterable... | train | https://github.com/racker/torment/blob/bd5d2f978324bf9b7360edfae76d853b226c63e1/torment/helpers.py#L32-L63 | null | # Copyright 2015 Alex Brandt <alex.brandt@rackspace.com>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law... |
racker/torment | torment/helpers.py | extend | python | def extend(base: Dict[Any, Any], extension: Dict[Any, Any]) -> Dict[Any, Any]:
'''Extend base by updating with the extension.
**Arguments**
:``base``: dictionary to have keys updated or added
:``extension``: dictionary to update base with
**Return Value(s)**
Resulting dictionary from up... | Extend base by updating with the extension.
**Arguments**
:``base``: dictionary to have keys updated or added
:``extension``: dictionary to update base with
**Return Value(s)**
Resulting dictionary from updating base with extension. | train | https://github.com/racker/torment/blob/bd5d2f978324bf9b7360edfae76d853b226c63e1/torment/helpers.py#L66-L83 | null | # Copyright 2015 Alex Brandt <alex.brandt@rackspace.com>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law... |
racker/torment | torment/helpers.py | merge | python | def merge(base: Dict[Any, Any], extension: Dict[Any, Any]) -> Dict[Any, Any]:
'''Merge extension into base recursively.
**Argumetnts**
:``base``: dictionary to overlay values onto
:``extension``: dictionary to overlay with
**Return Value(s)**
Resulting dictionary from overlaying extensi... | Merge extension into base recursively.
**Argumetnts**
:``base``: dictionary to overlay values onto
:``extension``: dictionary to overlay with
**Return Value(s)**
Resulting dictionary from overlaying extension on base. | train | https://github.com/racker/torment/blob/bd5d2f978324bf9b7360edfae76d853b226c63e1/torment/helpers.py#L86-L108 | [
"def merge(base: Dict[Any, Any], extension: Dict[Any, Any]) -> Dict[Any, Any]:\n '''Merge extension into base recursively.\n\n **Argumetnts**\n\n :``base``: dictionary to overlay values onto\n :``extension``: dictionary to overlay with\n\n **Return Value(s)**\n\n Resulting dictionary from ove... | # Copyright 2015 Alex Brandt <alex.brandt@rackspace.com>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law... |
racker/torment | torment/helpers.py | import_directory | python | def import_directory(module_basename: str, directory: str, sort_key = None) -> None:
'''Load all python modules in directory and directory's children.
Parameters
----------
:``module_basename``: module name prefix for loaded modules
:``directory``: directory to load python modules from
:... | Load all python modules in directory and directory's children.
Parameters
----------
:``module_basename``: module name prefix for loaded modules
:``directory``: directory to load python modules from
:``sort_key``: function to sort module names with before loading | train | https://github.com/racker/torment/blob/bd5d2f978324bf9b7360edfae76d853b226c63e1/torment/helpers.py#L112-L137 | [
"def _(function):\n @functools.wraps(function, assigned = functools.WRAPPER_ASSIGNMENTS + ( '__file__', ))\n def wrapper(*args, **kwargs):\n name, my_args = function.__name__, args\n\n if inspect.ismethod(function):\n name = function.__self__.__class__.__name__ + '.' + function.__name... | # Copyright 2015 Alex Brandt <alex.brandt@rackspace.com>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law... |
racker/torment | torment/helpers.py | _filenames_to_modulenames | python | def _filenames_to_modulenames(filenames: Iterable[str], modulename_prefix: str, filename_prefix: str = '') -> Iterable[str]:
'''Convert given filenames to module names.
Any filename that does not have a corresponding module name will be dropped
from the result (i.e. __init__.py).
Parameters
------... | Convert given filenames to module names.
Any filename that does not have a corresponding module name will be dropped
from the result (i.e. __init__.py).
Parameters
----------
:``filename_prefix``: a prefix to drop from all filenames (typically a
common directory); de... | train | https://github.com/racker/torment/blob/bd5d2f978324bf9b7360edfae76d853b226c63e1/torment/helpers.py#L158-L208 | null | # Copyright 2015 Alex Brandt <alex.brandt@rackspace.com>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law... |
racker/torment | torment/decorators.py | log | python | def log(prefix = ''):
'''Add start and stop logging messages to the function.
Parameters
----------
:``prefix``: a prefix for the function name (optional)
'''
function = None
if inspect.isfunction(prefix):
prefix, function = '', prefix
def _(function):
@functools.wr... | Add start and stop logging messages to the function.
Parameters
----------
:``prefix``: a prefix for the function name (optional) | train | https://github.com/racker/torment/blob/bd5d2f978324bf9b7360edfae76d853b226c63e1/torment/decorators.py#L28-L77 | null | # Copyright 2015 Alex Brandt
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
racker/torment | torment/decorators.py | mock | python | def mock(name: str) -> Callable[[Any], None]:
'''Setup properties indicating status of name mock.
This is designed to decorate ``torment.TestContext`` methods and is used to
provide a consistent interface for determining if name is mocked once and
only once.
Parameters
----------
:``name`... | Setup properties indicating status of name mock.
This is designed to decorate ``torment.TestContext`` methods and is used to
provide a consistent interface for determining if name is mocked once and
only once.
Parameters
----------
:``name``: symbol in context's module to mock
Return Val... | train | https://github.com/racker/torment/blob/bd5d2f978324bf9b7360edfae76d853b226c63e1/torment/decorators.py#L80-L128 | null | # Copyright 2015 Alex Brandt
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
carlosp420/dataset-creator | dataset_creator/base_dataset.py | DatasetBlock.split_data | python | def split_data(self):
this_gene_code = None
for seq_record in self.data.seq_records:
if this_gene_code is None or this_gene_code != seq_record.gene_code:
this_gene_code = seq_record.gene_code
self._blocks.append([])
list_length = len(self._blocks)
... | Splits the list of SeqRecordExpanded objects into lists, which are
kept into a bigger list.
If the file_format is Nexus, then it is only partitioned by gene. If it
is FASTA, then it needs partitioning by codon positions if required.
Example:
>>> blocks = [
... ... | train | https://github.com/carlosp420/dataset-creator/blob/ea27340b145cb566a36c1836ff42263f1b2003a0/dataset_creator/base_dataset.py#L61-L84 | null | class DatasetBlock(object):
"""
By default, the data sequences block generated is NEXUS and we use BioPython
tools to convert it to other formats such as FASTA.
However, sometimes the blo
Parameters:
data (named tuple): containing:
* gene_codes: list
... |
carlosp420/dataset-creator | dataset_creator/base_dataset.py | DatasetBlock.convert_to_string | python | def convert_to_string(self, block):
if self.partitioning != '1st-2nd, 3rd':
return self.make_datablock_by_gene(block)
else:
if self.format == 'FASTA':
return self.make_datablock_considering_codon_positions_as_fasta_format(block)
else:
r... | Makes gene_block as str from list of SeqRecordExpanded objects of a gene_code.
Override this function if the dataset block needs to be different
due to file format.
This block will need to be split further if the dataset is FASTA or
TNT and the partitioning scheme is 1st-2nd, 3rd.
... | train | https://github.com/carlosp420/dataset-creator/blob/ea27340b145cb566a36c1836ff42263f1b2003a0/dataset_creator/base_dataset.py#L86-L105 | [
"def make_datablock_considering_codon_positions_as_fasta_format(self, block):\n block_1st2nd = OrderedDict()\n block_1st = OrderedDict()\n block_2nd = OrderedDict()\n block_3rd = OrderedDict()\n\n for seq_record in block: # splitting each block in two\n if seq_record.gene_code not in block_1s... | class DatasetBlock(object):
"""
By default, the data sequences block generated is NEXUS and we use BioPython
tools to convert it to other formats such as FASTA.
However, sometimes the blo
Parameters:
data (named tuple): containing:
* gene_codes: list
... |
carlosp420/dataset-creator | dataset_creator/base_dataset.py | DatasetBlock.convert_block_dicts_to_string | python | def convert_block_dicts_to_string(self, block_1st2nd, block_1st, block_2nd, block_3rd):
out = ""
# We need 1st and 2nd positions
if self.codon_positions in ['ALL', '1st-2nd']:
for gene_code, seqs in block_1st2nd.items():
out += '>{0}_1st-2nd\n----\n'.format(gene_code)... | Takes into account whether we need to output all codon positions. | train | https://github.com/carlosp420/dataset-creator/blob/ea27340b145cb566a36c1836ff42263f1b2003a0/dataset_creator/base_dataset.py#L139-L165 | null | class DatasetBlock(object):
"""
By default, the data sequences block generated is NEXUS and we use BioPython
tools to convert it to other formats such as FASTA.
However, sometimes the blo
Parameters:
data (named tuple): containing:
* gene_codes: list
... |
carlosp420/dataset-creator | dataset_creator/base_dataset.py | DatasetFooter.make_charsets | python | def make_charsets(self):
count_start = 1
out = ''
for gene_code, lengths in self.data.gene_codes_and_lengths.items():
count_end = lengths[0] + count_start - 1
out += self.format_charset_line(gene_code, count_start, count_end)
count_start = count_end + 1
... | Override this function for Phylip dataset as the content is different and
goes into a separate file. | train | https://github.com/carlosp420/dataset-creator/blob/ea27340b145cb566a36c1836ff42263f1b2003a0/dataset_creator/base_dataset.py#L308-L319 | [
"def format_charset_line(self, gene_code, count_start, count_end):\n slash_number = self.make_slash_number()\n suffixes = self.make_gene_code_suffixes()\n corrected_count = self.correct_count_using_reading_frames(gene_code, count_start, count_end)\n\n out = ''\n for index, val in enumerate(suffixes):... | class DatasetFooter(object):
"""Builds charset block:
Parameters:
data (namedtuple): with necessary info for dataset creation.
codon_positions (str): `1st`, `2nd`, `3rd`, `1st-2nd`, `ALL`.
partitioning (str): `by gene`, `by codon position`, `1st-2nd, 3rd`.
outgroup (st... |
carlosp420/dataset-creator | dataset_creator/base_dataset.py | DatasetFooter.make_slash_number | python | def make_slash_number(self):
if self.partitioning == 'by codon position' and self.codon_positions == '1st-2nd':
return '\\2'
elif self.partitioning in ['by codon position', '1st-2nd, 3rd'] and self.codon_positions in ['ALL', None]:
return '\\3'
else:
return '' | Charset lines have \2 or \3 depending on type of partitioning and codon
positions requested for our dataset.
:return: | train | https://github.com/carlosp420/dataset-creator/blob/ea27340b145cb566a36c1836ff42263f1b2003a0/dataset_creator/base_dataset.py#L332-L344 | null | class DatasetFooter(object):
"""Builds charset block:
Parameters:
data (namedtuple): with necessary info for dataset creation.
codon_positions (str): `1st`, `2nd`, `3rd`, `1st-2nd`, `ALL`.
partitioning (str): `by gene`, `by codon position`, `1st-2nd, 3rd`.
outgroup (st... |
carlosp420/dataset-creator | dataset_creator/base_dataset.py | DatasetFooter.add_suffixes_to_gene_codes | python | def add_suffixes_to_gene_codes(self):
out = []
for gene_code in self.data.gene_codes:
for sufix in self.make_gene_code_suffixes():
out.append('{0}{1}'.format(gene_code, sufix))
return out | Appends pos1, pos2, etc to the gene_code if needed. | train | https://github.com/carlosp420/dataset-creator/blob/ea27340b145cb566a36c1836ff42263f1b2003a0/dataset_creator/base_dataset.py#L385-L391 | [
"def make_gene_code_suffixes(self):\n try:\n return self.suffix_for_one_codon_position()\n except KeyError:\n return self.suffix_for_several_codon_positions()\n"
] | class DatasetFooter(object):
"""Builds charset block:
Parameters:
data (namedtuple): with necessary info for dataset creation.
codon_positions (str): `1st`, `2nd`, `3rd`, `1st-2nd`, `ALL`.
partitioning (str): `by gene`, `by codon position`, `1st-2nd, 3rd`.
outgroup (st... |
carlosp420/dataset-creator | dataset_creator/base_dataset.py | DatasetFooter.get_outgroup | python | def get_outgroup(self):
if self.outgroup is not None:
outgroup_taxonomy = ''
for i in self.data.seq_records:
if self.outgroup == i.voucher_code:
outgroup_taxonomy = '{0}_{1}'.format(i.taxonomy['genus'],
... | Generates the outgroup line from the voucher code specified by the
user. | train | https://github.com/carlosp420/dataset-creator/blob/ea27340b145cb566a36c1836ff42263f1b2003a0/dataset_creator/base_dataset.py#L413-L428 | null | class DatasetFooter(object):
"""Builds charset block:
Parameters:
data (namedtuple): with necessary info for dataset creation.
codon_positions (str): `1st`, `2nd`, `3rd`, `1st-2nd`, `ALL`.
partitioning (str): `by gene`, `by codon position`, `1st-2nd, 3rd`.
outgroup (st... |
carlosp420/dataset-creator | dataset_creator/phylip.py | PhylipDatasetFooter.make_charsets | python | def make_charsets(self):
count_start = 1
out = ''
for gene_code, lengths in self.data.gene_codes_and_lengths.items():
count_end = lengths[0] + count_start - 1
formatted_line = self.format_charset_line(gene_code, count_start, count_end)
converted_line = formatt... | Overridden function for Phylip dataset as the content is different and
goes into a separate file. | train | https://github.com/carlosp420/dataset-creator/blob/ea27340b145cb566a36c1836ff42263f1b2003a0/dataset_creator/phylip.py#L13-L26 | [
"def format_charset_line(self, gene_code, count_start, count_end):\n slash_number = self.make_slash_number()\n suffixes = self.make_gene_code_suffixes()\n corrected_count = self.correct_count_using_reading_frames(gene_code, count_start, count_end)\n\n out = ''\n for index, val in enumerate(suffixes):... | class PhylipDatasetFooter(DatasetFooter):
def make_charset_block(self):
"""
Overridden function for Phylip dataset as the content is different and
goes into a separate file.
"""
out = self.make_charsets()
return out.strip()
|
carlosp420/dataset-creator | dataset_creator/genbank_fasta.py | GenBankFASTADatasetBlock.convert_to_string | python | def convert_to_string(self, block):
out = ""
for seq_record in block:
taxon_id = ">{0}_{1}_{2} [org={0} {1}] [Specimen-voucher={2}] " \
"[note={3} gene, partial cds.] [Lineage={4}]".format(
seq_record.taxonomy['genus'],
seq_record.taxono... | Takes a list of SeqRecordExpanded objects corresponding to a gene_code
and produces the gene_block as string.
:param block:
:return: str. | train | https://github.com/carlosp420/dataset-creator/blob/ea27340b145cb566a36c1836ff42263f1b2003a0/dataset_creator/genbank_fasta.py#L6-L33 | [
"def get_seq(seq_record, codon_positions, aminoacids=False, degenerate=None):\n \"\"\"\n Checks parameters such as codon_positions, aminoacids... to return the\n required sequence as string.\n\n Parameters:\n seq_record (SeqRecordExpanded object):\n codon_positions (str):\n aminoaci... | class GenBankFASTADatasetBlock(DatasetBlock):
|
carlosp420/dataset-creator | dataset_creator/utils.py | get_seq | python | def get_seq(seq_record, codon_positions, aminoacids=False, degenerate=None):
Sequence = namedtuple('Sequence', ['seq', 'warning'])
if codon_positions not in [None, '1st', '2nd', '3rd', '1st-2nd', 'ALL']:
raise WrongParameterFormat("`codon_positions` argument should be any of the following"
... | Checks parameters such as codon_positions, aminoacids... to return the
required sequence as string.
Parameters:
seq_record (SeqRecordExpanded object):
codon_positions (str):
aminoacids (boolean):
Returns:
Namedtuple containing ``seq (str)`` and ``warning (str)``. | train | https://github.com/carlosp420/dataset-creator/blob/ea27340b145cb566a36c1836ff42263f1b2003a0/dataset_creator/utils.py#L17-L56 | null | # -*- coding: UTF-8 -*-
import six
if six.PY2:
from StringIO import StringIO
else:
from io import StringIO
import os
from collections import namedtuple
import uuid
from Bio import AlignIO
from .exceptions import WrongParameterFormat
def convert_nexus_to_format(dataset_as_nexus, dataset_format):
"""
... |
carlosp420/dataset-creator | dataset_creator/utils.py | convert_nexus_to_format | python | def convert_nexus_to_format(dataset_as_nexus, dataset_format):
fake_handle = StringIO(dataset_as_nexus)
nexus_al = AlignIO.parse(fake_handle, 'nexus')
tmp_file = make_random_filename()
AlignIO.write(nexus_al, tmp_file, dataset_format)
dataset_as_fasta = read_and_delete_tmp_file(tmp_file)
return ... | Converts nexus format to Phylip and Fasta using Biopython tools.
:param dataset_as_nexus:
:param dataset_format:
:return: | train | https://github.com/carlosp420/dataset-creator/blob/ea27340b145cb566a36c1836ff42263f1b2003a0/dataset_creator/utils.py#L59-L72 | [
"def make_random_filename():\n return '{0}.txt'.format(uuid.uuid4().hex)\n",
"def read_and_delete_tmp_file(filename):\n with open(filename, \"r\") as handle:\n contents = handle.read()\n\n if os.path.isfile(filename):\n os.remove(filename)\n\n return contents\n"
] | # -*- coding: UTF-8 -*-
import six
if six.PY2:
from StringIO import StringIO
else:
from io import StringIO
import os
from collections import namedtuple
import uuid
from Bio import AlignIO
from .exceptions import WrongParameterFormat
def get_seq(seq_record, codon_positions, aminoacids=False, degenerate=None... |
carlosp420/dataset-creator | dataset_creator/utils.py | make_dataset_header | python | def make_dataset_header(data, file_format, aminoacids):
if aminoacids:
datatype = 'PROTEIN'
else:
datatype = 'DNA'
if file_format in ['NEXUS', 'PHYLIP', 'FASTA']:
header = """
#NEXUS
BEGIN DATA;
DIMENSIONS NTAX={0} NCHAR={1};
FORMAT INTERLEAVE DATATYPE={2} MISSING=? GAP=-;
MATRIX
"... | Creates the dataset header for NEXUS files from ``#NEXUS`` to ``MATRIX``.
Parameters:
data (namedtuple): with necessary info for dataset creation.
file_format (str): TNT, PHYLIP, NEXUS, FASTA
aminoacids (boolean): If ``aminoacids is True`` the header will show
... | train | https://github.com/carlosp420/dataset-creator/blob/ea27340b145cb566a36c1836ff42263f1b2003a0/dataset_creator/utils.py#L89-L126 | null | # -*- coding: UTF-8 -*-
import six
if six.PY2:
from StringIO import StringIO
else:
from io import StringIO
import os
from collections import namedtuple
import uuid
from Bio import AlignIO
from .exceptions import WrongParameterFormat
def get_seq(seq_record, codon_positions, aminoacids=False, degenerate=None... |
carlosp420/dataset-creator | dataset_creator/tnt.py | TntDatasetBlock.convert_to_string | python | def convert_to_string(self, block):
if self.aminoacids:
molecule_type = "protein"
else:
molecule_type = "dna"
out = None
for seq_record in block:
if not out:
out = '&[{0}]\n'.format(molecule_type, seq_record.gene_code)
taxo... | Takes a list of SeqRecordExpanded objects corresponding to a gene_code
and produces the gene_block as string.
:param block:
:return: str. | train | https://github.com/carlosp420/dataset-creator/blob/ea27340b145cb566a36c1836ff42263f1b2003a0/dataset_creator/tnt.py#L25-L53 | [
"def get_seq(seq_record, codon_positions, aminoacids=False, degenerate=None):\n \"\"\"\n Checks parameters such as codon_positions, aminoacids... to return the\n required sequence as string.\n\n Parameters:\n seq_record (SeqRecordExpanded object):\n codon_positions (str):\n aminoaci... | class TntDatasetBlock(DatasetBlock):
def dataset_block(self):
self.split_data()
out = []
for block in self._blocks:
if self.outgroup is not None:
block = self.put_outgroup_at_start_of_block(block)
out.append(self.convert_to_string(block))
retur... |
carlosp420/dataset-creator | dataset_creator/dataset.py | Dataset.sort_seq_records | python | def sort_seq_records(self, seq_records):
for seq_record in seq_records:
seq_record.voucher_code = seq_record.voucher_code.replace("-", "_")
unsorted_gene_codes = set([i.gene_code for i in seq_records])
sorted_gene_codes = list(unsorted_gene_codes)
sorted_gene_codes.sort(key=... | Checks that SeqExpandedRecords are sorted by gene_code and then by voucher code.
The dashes in taxon names need to be converted to underscores so the
dataset will be accepted by Biopython to do format conversions. | train | https://github.com/carlosp420/dataset-creator/blob/ea27340b145cb566a36c1836ff42263f1b2003a0/dataset_creator/dataset.py#L81-L109 | null | class Dataset(object):
"""User's class for making datasets of several formats. It needs as input
a list of SeqRecord-expanded objects with as much info as possible:
Parameters:
seq_records (list): SeqRecordExpanded objects. The list should be
sorted by gene_code ... |
carlosp420/dataset-creator | dataset_creator/dataset.py | Dataset._validate_outgroup | python | def _validate_outgroup(self, outgroup):
if outgroup:
outgroup = outgroup.replace("-", "_")
good_outgroup = False
for seq_record in self.seq_records:
if seq_record.voucher_code == outgroup:
good_outgroup = True
break
... | All voucher codes in our datasets have dashes converted to underscores. | train | https://github.com/carlosp420/dataset-creator/blob/ea27340b145cb566a36c1836ff42263f1b2003a0/dataset_creator/dataset.py#L131-L146 | null | class Dataset(object):
"""User's class for making datasets of several formats. It needs as input
a list of SeqRecord-expanded objects with as much info as possible:
Parameters:
seq_records (list): SeqRecordExpanded objects. The list should be
sorted by gene_code ... |
carlosp420/dataset-creator | dataset_creator/dataset.py | Dataset._prepare_data | python | def _prepare_data(self):
self._extract_genes()
self._extract_total_number_of_chars()
self._extract_number_of_taxa()
self._extract_reading_frames()
Data = namedtuple('Data', ['gene_codes', 'number_taxa', 'number_chars',
'seq_records', 'gene_code... | Creates named tuple with info needed to create a dataset.
:return: named tuple | train | https://github.com/carlosp420/dataset-creator/blob/ea27340b145cb566a36c1836ff42263f1b2003a0/dataset_creator/dataset.py#L148-L164 | [
"def _extract_genes(self):\n gene_codes = [i.gene_code for i in self.seq_records]\n unique_gene_codes = list(set(gene_codes))\n # this is better: unique_gene_codes.sort(key=str.lower)\n # but will not work in python2\n unique_gene_codes.sort(key=lambda x: x.lower())\n self.gene_codes = unique_gene... | class Dataset(object):
"""User's class for making datasets of several formats. It needs as input
a list of SeqRecord-expanded objects with as much info as possible:
Parameters:
seq_records (list): SeqRecordExpanded objects. The list should be
sorted by gene_code ... |
carlosp420/dataset-creator | dataset_creator/dataset.py | Dataset._extract_total_number_of_chars | python | def _extract_total_number_of_chars(self):
self._get_gene_codes_and_seq_lengths()
sum = 0
for seq_length in self._gene_codes_and_lengths.values():
sum += sorted(seq_length, reverse=True)[0]
self.number_chars = str(sum) | sets `self.number_chars` to the number of characters as string. | train | https://github.com/carlosp420/dataset-creator/blob/ea27340b145cb566a36c1836ff42263f1b2003a0/dataset_creator/dataset.py#L174-L183 | null | class Dataset(object):
"""User's class for making datasets of several formats. It needs as input
a list of SeqRecord-expanded objects with as much info as possible:
Parameters:
seq_records (list): SeqRecordExpanded objects. The list should be
sorted by gene_code ... |
carlosp420/dataset-creator | dataset_creator/dataset.py | Dataset._extract_number_of_taxa | python | def _extract_number_of_taxa(self):
n_taxa = dict()
for i in self.seq_records:
if i.gene_code not in n_taxa:
n_taxa[i.gene_code] = 0
n_taxa[i.gene_code] += 1
number_taxa = sorted([i for i in n_taxa.values()], reverse=True)[0]
self.number_taxa = str(... | sets `self.number_taxa` to the number of taxa as string | train | https://github.com/carlosp420/dataset-creator/blob/ea27340b145cb566a36c1836ff42263f1b2003a0/dataset_creator/dataset.py#L201-L211 | null | class Dataset(object):
"""User's class for making datasets of several formats. It needs as input
a list of SeqRecord-expanded objects with as much info as possible:
Parameters:
seq_records (list): SeqRecordExpanded objects. The list should be
sorted by gene_code ... |
carlosp420/dataset-creator | dataset_creator/mega.py | MegaDatasetBlock.convert_blocks_to_string | python | def convert_blocks_to_string(self):
taxa_ids = [[]] * int(self.data.number_taxa)
sequences = [''] * int(self.data.number_taxa)
for block in self._blocks:
for index, seq_record in enumerate(block):
taxa_ids[index] = '{0}_{1}_{2}'.format(seq_record.voucher_code,
... | New method, only in MegaDatasetBlock class.
:return: flattened data blocks as string | train | https://github.com/carlosp420/dataset-creator/blob/ea27340b145cb566a36c1836ff42263f1b2003a0/dataset_creator/mega.py#L10-L35 | [
"def get_seq(seq_record, codon_positions, aminoacids=False, degenerate=None):\n \"\"\"\n Checks parameters such as codon_positions, aminoacids... to return the\n required sequence as string.\n\n Parameters:\n seq_record (SeqRecordExpanded object):\n codon_positions (str):\n aminoaci... | class MegaDatasetBlock(DatasetBlock):
def dataset_block(self):
self.split_data()
return self.convert_blocks_to_string()
|
SeabornGames/Meta | seaborn_meta/calling_function.py | function_arguments | python | def function_arguments(func):
if getattr(inspect, 'signature', None) is None:
return list(inspect.getargspec(func).args)
else:
return list(inspect.signature(func).parameters.keys()) | This returns a list of all arguments
:param func: callable object
:return: list of str of the arguments for the function | train | https://github.com/SeabornGames/Meta/blob/f2a38ad8bcc5ac177e537645853593225895df46/seaborn_meta/calling_function.py#L13-L22 | null | """
This module is used to get the calling class, function, file, line_number, and locals
Issues:
builtin functions like eval, break this
pycharm will also break this, although it sometimes can recover
"""
import inspect
import os
import traceback
def function_defaults(func):
"""
Thi... |
SeabornGames/Meta | seaborn_meta/calling_function.py | function_defaults | python | def function_defaults(func):
if getattr(inspect, 'signature',None) is None:
return inspect.getargspec(func)[-1] or []
else:
return [v.default for k,v in list(
inspect.signature(func).parameters.items())
if v.default is not inspect._empty] | This returns a list of the default arguments
:param func: callable object
:return: list of obj of default parameters | train | https://github.com/SeabornGames/Meta/blob/f2a38ad8bcc5ac177e537645853593225895df46/seaborn_meta/calling_function.py#L25-L36 | null | """
This module is used to get the calling class, function, file, line_number, and locals
Issues:
builtin functions like eval, break this
pycharm will also break this, although it sometimes can recover
"""
import inspect
import os
import traceback
def function_arguments(func):
"""
Thi... |
SeabornGames/Meta | seaborn_meta/calling_function.py | function_doc | python | def function_doc(function_index=1, function_name=None):
frm = func_frame(function_index + 1, function_name)
try:
func = getattr(frm.f_locals['self'], frm.f_code.co_name)
except:
func = frm.f_globals[frm.f_code.co_name]
return func.__doc__ | This will return the doc of the calling function
:param function_index: int of how many frames back the program should look
:param function_name: str of what function to look for
:return: str of the doc from the target function | train | https://github.com/SeabornGames/Meta/blob/f2a38ad8bcc5ac177e537645853593225895df46/seaborn_meta/calling_function.py#L39-L51 | [
"def func_frame(function_index, function_name=None):\n \"\"\"\n This will return the class_name and function_name of the\n function traced back two functions.\n\n :param function_index: int of how many frames back the program \n should look (2 will give the parent of the caller... | """
This module is used to get the calling class, function, file, line_number, and locals
Issues:
builtin functions like eval, break this
pycharm will also break this, although it sometimes can recover
"""
import inspect
import os
import traceback
def function_arguments(func):
"""
Thi... |
SeabornGames/Meta | seaborn_meta/calling_function.py | function_path | python | def function_path(func):
if getattr(func, 'func_code', None):
return func.__code__.co_filename.replace('\\', '/')
else:
return func.__code__.co_filename.replace('\\', '/') | This will return the path to the calling function
:param func:
:return: | train | https://github.com/SeabornGames/Meta/blob/f2a38ad8bcc5ac177e537645853593225895df46/seaborn_meta/calling_function.py#L54-L63 | null | """
This module is used to get the calling class, function, file, line_number, and locals
Issues:
builtin functions like eval, break this
pycharm will also break this, although it sometimes can recover
"""
import inspect
import os
import traceback
def function_arguments(func):
"""
Thi... |
SeabornGames/Meta | seaborn_meta/calling_function.py | file_code | python | def file_code(function_index=1, function_name=None):
info = function_info(function_index + 1, function_name)
with open(info['file'], 'r') as fn:
return fn.read() | This will return the code of the calling function
function_index of 2 will give the parent of the caller
function_name should not be used with function_index
:param function_index: int of how many frames back the program should look
:param function_name: str of what function to look for
:return: st... | train | https://github.com/SeabornGames/Meta/blob/f2a38ad8bcc5ac177e537645853593225895df46/seaborn_meta/calling_function.py#L66-L78 | [
"def function_info(function_index=1, function_name=None, line_number=None):\n \"\"\"\n This will return the class_name and function_name of the\n function traced back two functions.\n\n :param function_index: int of how many frames back the program \n should look (2 will give t... | """
This module is used to get the calling class, function, file, line_number, and locals
Issues:
builtin functions like eval, break this
pycharm will also break this, although it sometimes can recover
"""
import inspect
import os
import traceback
def function_arguments(func):
"""
Thi... |
SeabornGames/Meta | seaborn_meta/calling_function.py | relevant_kwargs | python | def relevant_kwargs(function, exclude_keys='self', exclude_values=None,
extra_values=None):
args = function_args(function)
locals_values = function_kwargs(function_index=2, exclude_keys=exclude_keys)
if extra_values:
locals_values.update(extra_values)
return {k: v for k, v in... | This will return a dictionary of local variables that are parameters to the
function provided in the arg.
Example:
function(**relevant_kwargs(function))
:param function: function to select parameters for
:param exclude_keys: str,list,func if not a function it will be converted
... | train | https://github.com/SeabornGames/Meta/blob/f2a38ad8bcc5ac177e537645853593225895df46/seaborn_meta/calling_function.py#L81-L102 | [
"def function_args(function):\n \"\"\"\n This will return a list of the non-keyword arguments\n :param function: function to check arguments for\n :return: list of arguments\n \"\"\"\n try:\n return function.__code__.co_varnames\n except:\n return function.f_code.co_... | """
This module is used to get the calling class, function, file, line_number, and locals
Issues:
builtin functions like eval, break this
pycharm will also break this, although it sometimes can recover
"""
import inspect
import os
import traceback
def function_arguments(func):
"""
Thi... |
SeabornGames/Meta | seaborn_meta/calling_function.py | function_kwargs | python | def function_kwargs(function_index=1, function_name=None,
exclude_keys='self', exclude_values=None):
if not hasattr(exclude_values, '__call__'):
_exclude_values = isinstance(exclude_values, list) and\
exclude_values or [exclude_values]
exclude_values = l... | This will return a dict of the keyword
arguments of the function that calls it
:param function_index: int of how many frames back the program
should look (2 will give the parent of the caller)
:param function_name: str of the function name (should not
... | train | https://github.com/SeabornGames/Meta/blob/f2a38ad8bcc5ac177e537645853593225895df46/seaborn_meta/calling_function.py#L117-L147 | [
"def func_frame(function_index, function_name=None):\n \"\"\"\n This will return the class_name and function_name of the\n function traced back two functions.\n\n :param function_index: int of how many frames back the program \n should look (2 will give the parent of the caller... | """
This module is used to get the calling class, function, file, line_number, and locals
Issues:
builtin functions like eval, break this
pycharm will also break this, although it sometimes can recover
"""
import inspect
import os
import traceback
def function_arguments(func):
"""
Thi... |
SeabornGames/Meta | seaborn_meta/calling_function.py | function_info | python | def function_info(function_index=1, function_name=None, line_number=None):
frm = func_frame(function_index + 1, function_name)
file_ = os.path.abspath(frm.f_code.co_filename)
class_name = frm.f_locals.get('self', None)
if class_name is not None: # and not skip_class:
class_name = str(type(class... | This will return the class_name and function_name of the
function traced back two functions.
:param function_index: int of how many frames back the program
should look (2 will give the parent of the caller)
:param function_name: str of what function to look for (should
... | train | https://github.com/SeabornGames/Meta/blob/f2a38ad8bcc5ac177e537645853593225895df46/seaborn_meta/calling_function.py#L163-L202 | [
"def func_frame(function_index, function_name=None):\n \"\"\"\n This will return the class_name and function_name of the\n function traced back two functions.\n\n :param function_index: int of how many frames back the program \n should look (2 will give the parent of the caller... | """
This module is used to get the calling class, function, file, line_number, and locals
Issues:
builtin functions like eval, break this
pycharm will also break this, although it sometimes can recover
"""
import inspect
import os
import traceback
def function_arguments(func):
"""
Thi... |
SeabornGames/Meta | seaborn_meta/calling_function.py | function_history | python | def function_history():
ret = []
frm = inspect.currentframe()
for i in range(100):
try:
if frm.f_code.co_name != 'run_code': # this is pycharm debugger
# inserting middleware
ret.append(frm.f_code.co_name)
frm... | This will return a list of all function calls going back to the beginning
:return: list of str of function name | train | https://github.com/SeabornGames/Meta/blob/f2a38ad8bcc5ac177e537645853593225895df46/seaborn_meta/calling_function.py#L205-L220 | null | """
This module is used to get the calling class, function, file, line_number, and locals
Issues:
builtin functions like eval, break this
pycharm will also break this, although it sometimes can recover
"""
import inspect
import os
import traceback
def function_arguments(func):
"""
Thi... |
SeabornGames/Meta | seaborn_meta/calling_function.py | func_frame | python | def func_frame(function_index, function_name=None):
frm = inspect.currentframe()
if function_name is not None:
function_name = function_name.split('*')[0] # todo replace this
# todo with regex
for i in range(1000):
if frm.f_code.c... | This will return the class_name and function_name of the
function traced back two functions.
:param function_index: int of how many frames back the program
should look (2 will give the parent of the caller)
:param function_name: str of what function to look for (should
... | train | https://github.com/SeabornGames/Meta/blob/f2a38ad8bcc5ac177e537645853593225895df46/seaborn_meta/calling_function.py#L223-L249 | null | """
This module is used to get the calling class, function, file, line_number, and locals
Issues:
builtin functions like eval, break this
pycharm will also break this, although it sometimes can recover
"""
import inspect
import os
import traceback
def function_arguments(func):
"""
Thi... |
SeabornGames/Meta | seaborn_meta/calling_function.py | function_linenumber | python | def function_linenumber(function_index=1, function_name=None, width=5):
frm = func_frame(function_index + 1, function_name)
if width is None:
return frm._f_lineno
return str(frm.f_lineno).ljust(width) | This will return the line number of the indicated function in the stack
:param width:
:param function_index: int of how many frames back the program
should look (2 will give the parent of the caller)
:param function_name: str of what function to look for (should
... | train | https://github.com/SeabornGames/Meta/blob/f2a38ad8bcc5ac177e537645853593225895df46/seaborn_meta/calling_function.py#L252-L265 | [
"def func_frame(function_index, function_name=None):\n \"\"\"\n This will return the class_name and function_name of the\n function traced back two functions.\n\n :param function_index: int of how many frames back the program \n should look (2 will give the parent of the caller... | """
This module is used to get the calling class, function, file, line_number, and locals
Issues:
builtin functions like eval, break this
pycharm will also break this, although it sometimes can recover
"""
import inspect
import os
import traceback
def function_arguments(func):
"""
Thi... |
SeabornGames/Meta | seaborn_meta/calling_function.py | trace_error | python | def trace_error(function_index=2):
info = function_info(function_index)
traces = traceback.format_stack(limit=10)
for trace in traces:
file_, line_number, line_text = trace.split(',', 2)
if file_ == ' File "%s"' % info['file'] and\
line_number != 'line %s' % info['li... | This will return the line number and line text of the last error
:param function_index: int to tell what frame to look from
:return: int, str of the line number and line text | train | https://github.com/SeabornGames/Meta/blob/f2a38ad8bcc5ac177e537645853593225895df46/seaborn_meta/calling_function.py#L290-L303 | [
"def function_info(function_index=1, function_name=None, line_number=None):\n \"\"\"\n This will return the class_name and function_name of the\n function traced back two functions.\n\n :param function_index: int of how many frames back the program \n should look (2 will give t... | """
This module is used to get the calling class, function, file, line_number, and locals
Issues:
builtin functions like eval, break this
pycharm will also break this, although it sometimes can recover
"""
import inspect
import os
import traceback
def function_arguments(func):
"""
Thi... |
SeabornGames/Meta | seaborn_meta/parse_doc.py | parse_doc_dict | python | def parse_doc_dict(text=None, split_character="::"):
text = text or function_doc(2)
text = text.split(split_character, 1)[-1]
text = text.split(':param')[0].split(':return')[0]
text = text.strip().split('\n')
def clean(t): return t.split(':', 1)[0].strip(), t.split(':', 1)[1].strip()
return di... | Returns a dictionary of the parsed doc for
example the following would return {'a':'A','b':'B'} ::
a:A
b:B
:param split_character:
:param text: str of the text to parse, by default uses calling function doc
:param split_character: str of the characters to split on in the doc string
... | train | https://github.com/SeabornGames/Meta/blob/f2a38ad8bcc5ac177e537645853593225895df46/seaborn_meta/parse_doc.py#L14-L32 | [
"def function_doc(function_index=1, function_name=None):\n \"\"\"\n This will return the doc of the calling function\n :param function_index: int of how many frames back the program should look\n :param function_name: str of what function to look for\n :return: str of the doc from the target func... | """ This module is to provide support for auto parsing function doc.
It looks for the text in the doc string after :: but before :param
"""
from .calling_function import function_doc
from datetime import datetime
import sys
if sys.version_info[0] == 2:
STR = 'basestring'
else:
STR = 'str'
def parse_... |
SeabornGames/Meta | seaborn_meta/parse_doc.py | parse_doc_list | python | def parse_doc_list(text=None, is_stripped=True, split_character="::"):
text = text or function_doc(2)
text = text.split(split_character, 1)[-1]
text = text.split(':param')[0].split(':return')[0]
text = text.strip().split('\n')
def clean(t): return is_stripped and t.strip() or t
return [clean(l... | Returns a list of the parsed doc for
example the following would return ['a:A','b:'B] ::
a:A
b:B
:param text: str of the text to parse, by default uses calling function doc
:param is_stripped: bool if True each line will be stripped
:param split_character: str of the characters to split... | train | https://github.com/SeabornGames/Meta/blob/f2a38ad8bcc5ac177e537645853593225895df46/seaborn_meta/parse_doc.py#L35-L53 | [
"def function_doc(function_index=1, function_name=None):\n \"\"\"\n This will return the doc of the calling function\n :param function_index: int of how many frames back the program should look\n :param function_name: str of what function to look for\n :return: str of the doc from the target func... | """ This module is to provide support for auto parsing function doc.
It looks for the text in the doc string after :: but before :param
"""
from .calling_function import function_doc
from datetime import datetime
import sys
if sys.version_info[0] == 2:
STR = 'basestring'
else:
STR = 'str'
def parse_d... |
SeabornGames/Meta | seaborn_meta/parse_doc.py | parse_doc_str | python | def parse_doc_str(text=None, is_untabbed=True, is_stripped=True,
tab=None, split_character="::"):
text = text or function_doc(2)
text = text.split(split_character, 1)[-1]
text = text.split(':param')[0].split(':return')[0]
tab = is_untabbed and \
(tab or text[:-1 * len(text.ls... | Returns a str of the parsed doc for example
the following would return 'a:A\nb:B' ::
a:A
b:B
:param text: str of the text to parse, by
default uses calling function doc
:param is_untabbed: bool if True will untab the text
:param is_stripped: ... | train | https://github.com/SeabornGames/Meta/blob/f2a38ad8bcc5ac177e537645853593225895df46/seaborn_meta/parse_doc.py#L56-L78 | [
"def function_doc(function_index=1, function_name=None):\n \"\"\"\n This will return the doc of the calling function\n :param function_index: int of how many frames back the program should look\n :param function_name: str of what function to look for\n :return: str of the doc from the target func... | """ This module is to provide support for auto parsing function doc.
It looks for the text in the doc string after :: but before :param
"""
from .calling_function import function_doc
from datetime import datetime
import sys
if sys.version_info[0] == 2:
STR = 'basestring'
else:
STR = 'str'
def parse_d... |
SeabornGames/Meta | seaborn_meta/parse_doc.py | parse_arg_types | python | def parse_arg_types(text=None, is_return_included=False):
text = text or function_doc(2)
if is_return_included:
text = text.replace(':return:', ':param return:')
ret = {}
def evl(text_):
try:
return eval(text_)
except Exception as e:
return text_
if ... | :param text: str of the text to parse, by default
uses calling function doc
:param is_return_included: bool if True return will be return as well
:return: dict of args and variable types | train | https://github.com/SeabornGames/Meta/blob/f2a38ad8bcc5ac177e537645853593225895df46/seaborn_meta/parse_doc.py#L81-L109 | [
"def function_doc(function_index=1, function_name=None):\n \"\"\"\n This will return the doc of the calling function\n :param function_index: int of how many frames back the program should look\n :param function_name: str of what function to look for\n :return: str of the doc from the target func... | """ This module is to provide support for auto parsing function doc.
It looks for the text in the doc string after :: but before :param
"""
from .calling_function import function_doc
from datetime import datetime
import sys
if sys.version_info[0] == 2:
STR = 'basestring'
else:
STR = 'str'
def parse_d... |
SeabornGames/Meta | seaborn_meta/class_name.py | class_name_to_instant_name | python | def class_name_to_instant_name(name):
name = name.replace('/', '_')
ret = name[0].lower()
for i in range(1, len(name)):
if name[i] == '_':
ret += '.'
elif '9' < name[i] < 'a' and name[i - 1] != '_':
ret += '_' + name[i].lower()
else:
ret += name[i]... | This will convert from 'ParentName_ChildName' to
'parent_name.child_name' | train | https://github.com/SeabornGames/Meta/blob/f2a38ad8bcc5ac177e537645853593225895df46/seaborn_meta/class_name.py#L8-L20 | null | """ This module contains some functionality that would be helpful for
meta programming
"""
import glob
import os
def instant_name_to_class_name(name):
"""
This will convert from 'parent_name.child_name' to
'ParentName_ChildName'
:param name: str of the name to convert
:return: str of ... |
SeabornGames/Meta | seaborn_meta/class_name.py | instant_name_to_class_name | python | def instant_name_to_class_name(name):
name2 = ''.join([e.title() for e in name.split('_')])
return '_'.join([e[0].upper() + e[1:] for e in name2.split('.')]) | This will convert from 'parent_name.child_name' to
'ParentName_ChildName'
:param name: str of the name to convert
:return: str of the converted name | train | https://github.com/SeabornGames/Meta/blob/f2a38ad8bcc5ac177e537645853593225895df46/seaborn_meta/class_name.py#L23-L31 | null | """ This module contains some functionality that would be helpful for
meta programming
"""
import glob
import os
def class_name_to_instant_name(name):
""" This will convert from 'ParentName_ChildName' to
'parent_name.child_name' """
name = name.replace('/', '_')
ret = name[0].lower()
for i in ... |
SeabornGames/Meta | seaborn_meta/class_name.py | create_init_files | python | def create_init_files(path):
python_files = sorted([os.path.basename(file_)[:-3] for file_ in
glob.glob(os.path.join(path, '*.py'))
if not file_.endswith('__init__.py')])
folders = sorted([os.path.basename(folder) for folder in os.listdir(path)
... | This will create __init__.py for a module path and every subdirectory
:param path: str of the path to start adding __init__.py to
:return: None | train | https://github.com/SeabornGames/Meta/blob/f2a38ad8bcc5ac177e537645853593225895df46/seaborn_meta/class_name.py#L44-L61 | [
"def create_init_files(path):\n \"\"\"\n This will create __init__.py for a module path and every subdirectory\n :param path: str of the path to start adding __init__.py to\n :return: None\n \"\"\"\n python_files = sorted([os.path.basename(file_)[:-3] for file_ in\n g... | """ This module contains some functionality that would be helpful for
meta programming
"""
import glob
import os
def class_name_to_instant_name(name):
""" This will convert from 'ParentName_ChildName' to
'parent_name.child_name' """
name = name.replace('/', '_')
ret = name[0].lower()
for i in ... |
fakedrake/overlay_parse | overlay_parse/util.py | rx_int_extra | python | def rx_int_extra(rxmatch):
rxmatch = re.search("\d+", rxmatch.group(0))
return int(rxmatch.group(0)) | We didn't just match an int but the int is what we need. | train | https://github.com/fakedrake/overlay_parse/blob/9ac362d6aef1ea41aff7375af088c6ebef93d0cd/overlay_parse/util.py#L42-L48 | null | import re
class Rng(object):
"""
Open-closed range of numbers that supports `in'
"""
def __init__(self, s, e, rng=(True, False)):
self.s = s
self.e = e
self.sclosed, self.eclosed = rng
def __contains__(self, num):
return ((not self.eclosed and num < self.e) or
... |
fakedrake/overlay_parse | overlay_parse/matchers.py | mf | python | def mf(pred, props=None, value_fn=None, props_on_match=False, priority=None):
if isinstance(pred, BaseMatcher):
ret = pred if props_on_match else pred.props
if isinstance(pred, basestring) or \
type(pred).__name__ == 'SRE_Pattern':
ret = RegexMatcher(pred, props=props, value_fn=value_fn... | Matcher factory. | train | https://github.com/fakedrake/overlay_parse/blob/9ac362d6aef1ea41aff7375af088c6ebef93d0cd/overlay_parse/matchers.py#L255-L279 | null | import re
from .overlays import Overlay, OverlayedText
from functools import reduce
class BaseMatcher(object):
"""
An interface for Matcher objects.
"""
def offset_overlays(self, text, offset=0, **kw):
raise NotImplementedError("Class %s has not implemented \
offset_overlays" % type... |
fakedrake/overlay_parse | overlay_parse/matchers.py | RegexMatcher.offset_overlays | python | def offset_overlays(self, text, offset=0, **kw):
# This may be a bit slower but overlayedtext takes care of
# unicode issues.
if not isinstance(text, OverlayedText):
text = OverlayedText(text)
for m in self.regex.finditer(unicode(text)[offset:]):
yield Overlay(t... | Generate overlays after offset.
:param text: The text to be searched.
:param offset: Match starting that index. If none just search.
:returns: An overlay or None | train | https://github.com/fakedrake/overlay_parse/blob/9ac362d6aef1ea41aff7375af088c6ebef93d0cd/overlay_parse/matchers.py#L50-L66 | [
"def value(self, **kw):\n if hasattr(self, 'value_fn') and self.value_fn:\n return self.value_fn(**kw)\n"
] | class RegexMatcher(BaseMatcher):
"""
Regex matching for matching.
"""
def __init__(self, regex, props, value_fn=None):
"""
Provide the regex to be matched.
"""
if isinstance(regex, basestring):
self.regex = re.compile(regex, re.UNICODE)
else:
... |
fakedrake/overlay_parse | overlay_parse/matchers.py | RegexMatcher.fit_overlays | python | def fit_overlays(self, text, start=None, end=None, **kw):
_text = text[start or 0:]
if end:
_text = _text[:end]
m = self.regex.match(unicode(_text))
if m:
yield Overlay(text, (start + m.start(), start + m.end()),
props=self.props,
... | Get an overlay thet fits the range [start, end). | train | https://github.com/fakedrake/overlay_parse/blob/9ac362d6aef1ea41aff7375af088c6ebef93d0cd/overlay_parse/matchers.py#L68-L82 | [
"def value(self, **kw):\n if hasattr(self, 'value_fn') and self.value_fn:\n return self.value_fn(**kw)\n"
] | class RegexMatcher(BaseMatcher):
"""
Regex matching for matching.
"""
def __init__(self, regex, props, value_fn=None):
"""
Provide the regex to be matched.
"""
if isinstance(regex, basestring):
self.regex = re.compile(regex, re.UNICODE)
else:
... |
fakedrake/overlay_parse | overlay_parse/matchers.py | OverlayMatcher.offset_overlays | python | def offset_overlays(self, text, offset=0, **kw):
for ovl in text.overlays:
if ovl.match(offset=offset, props=self.props_match):
yield ovl.copy(props=self.props,
value=self.value(overlay=ovl)) | Get overlays for the text.
:param text: The text to be searched. This is an overlay
object.
:param offset: Match starting that index. If none just search.
:returns: A generator for overlays. | train | https://github.com/fakedrake/overlay_parse/blob/9ac362d6aef1ea41aff7375af088c6ebef93d0cd/overlay_parse/matchers.py#L105-L117 | [
"def value(self, **kw):\n if hasattr(self, 'value_fn') and self.value_fn:\n return self.value_fn(**kw)\n"
] | class OverlayMatcher(BaseMatcher):
"""
Match a matcher. A matcher matches in 3 ways:
- Freely with an offset
- Fitting in a range.
The value_fn should accept the `overlay' keyword.
"""
def __init__(self, props_match, props=None, value_fn=None):
"""
:param props: Set of pro... |
fakedrake/overlay_parse | overlay_parse/matchers.py | OverlayMatcher.fit_overlays | python | def fit_overlays(self, text, start=None, end=None, **kw):
for ovl in text.overlays:
if ovl.match(props=self.props_match, rng=(start, end)):
yield ovl | Get an overlay thet fits the range [start, end). | train | https://github.com/fakedrake/overlay_parse/blob/9ac362d6aef1ea41aff7375af088c6ebef93d0cd/overlay_parse/matchers.py#L119-L126 | null | class OverlayMatcher(BaseMatcher):
"""
Match a matcher. A matcher matches in 3 ways:
- Freely with an offset
- Fitting in a range.
The value_fn should accept the `overlay' keyword.
"""
def __init__(self, props_match, props=None, value_fn=None):
"""
:param props: Set of pro... |
fakedrake/overlay_parse | overlay_parse/matchers.py | ListMatcher._merge_ovls | python | def _merge_ovls(self, ovls):
ret = reduce(lambda x, y: x.merge(y), ovls)
ret.value = self.value(ovls=ovls)
ret.set_props(self.props)
return ret | Merge ovls and also setup the value and props. | train | https://github.com/fakedrake/overlay_parse/blob/9ac362d6aef1ea41aff7375af088c6ebef93d0cd/overlay_parse/matchers.py#L145-L153 | [
"def value(self, **kw):\n if hasattr(self, 'value_fn') and self.value_fn:\n return self.value_fn(**kw)\n"
] | class ListMatcher(BaseMatcher):
"""
Match as a concatenated series of other matchers. It is greedy in
the snse that it just matches everything.
value_fn should accept the `ovls' keyword which is a list of the
overlays that compose the result.
"""
def __init__(self, matchers, props=None, v... |
fakedrake/overlay_parse | overlay_parse/matchers.py | ListMatcher._fit_overlay_lists | python | def _fit_overlay_lists(self, text, start, matchers, **kw):
if matchers:
for o in matchers[0].fit_overlays(text, start):
for rest in self._fit_overlay_lists(text, o.end, matchers[1:]):
yield [o] + rest
else:
yield [] | Return a list of overlays that start at start. | train | https://github.com/fakedrake/overlay_parse/blob/9ac362d6aef1ea41aff7375af088c6ebef93d0cd/overlay_parse/matchers.py#L155-L166 | [
"def _fit_overlay_lists(self, text, start, matchers, **kw):\n \"\"\"\n Return a list of overlays that start at start.\n \"\"\"\n\n if matchers:\n for o in matchers[0].fit_overlays(text, start):\n for rest in self._fit_overlay_lists(text, o.end, matchers[1:]):\n yield [o]... | class ListMatcher(BaseMatcher):
"""
Match as a concatenated series of other matchers. It is greedy in
the snse that it just matches everything.
value_fn should accept the `ovls' keyword which is a list of the
overlays that compose the result.
"""
def __init__(self, matchers, props=None, v... |
fakedrake/overlay_parse | overlay_parse/matchers.py | ListMatcher.offset_overlays | python | def offset_overlays(self, text, offset=0, run_deps=True, **kw):
if run_deps and self.dependencies:
text.overlay(self.dependencies)
for ovlf in self.matchers[0].offset_overlays(text,
goffset=offset,
... | The heavy lifting is done by fit_overlays. Override just that for
alternatie implementation. | train | https://github.com/fakedrake/overlay_parse/blob/9ac362d6aef1ea41aff7375af088c6ebef93d0cd/overlay_parse/matchers.py#L168-L182 | [
"def _merge_ovls(self, ovls):\n \"\"\"\n Merge ovls and also setup the value and props.\n \"\"\"\n\n ret = reduce(lambda x, y: x.merge(y), ovls)\n ret.value = self.value(ovls=ovls)\n ret.set_props(self.props)\n return ret\n",
"def _fit_overlay_lists(self, text, start, matchers, **kw):\n \"... | class ListMatcher(BaseMatcher):
"""
Match as a concatenated series of other matchers. It is greedy in
the snse that it just matches everything.
value_fn should accept the `ovls' keyword which is a list of the
overlays that compose the result.
"""
def __init__(self, matchers, props=None, v... |
fakedrake/overlay_parse | overlay_parse/matchers.py | MatcherMatcher._maybe_run_matchers | python | def _maybe_run_matchers(self, text, run_matchers):
if run_matchers is True or \
(run_matchers is not False and text not in self._overlayed_already):
text.overlay(self.matchers)
self._overlayed_already.append(text) | OverlayedText should be smart enough to not run twice the same
matchers but this is an extra handle of control over that. | train | https://github.com/fakedrake/overlay_parse/blob/9ac362d6aef1ea41aff7375af088c6ebef93d0cd/overlay_parse/matchers.py#L218-L227 | null | class MatcherMatcher(BaseMatcher):
"""
Match the matchers.
"""
def __init__(self, matchers, props=None, value_fn=None):
self.matchers = matchers
self.props = props
self.value_fn = value_fn
self._list_match = ListMatcher(
[OverlayMatcher(m.props) for m in ma... |
fakedrake/overlay_parse | overlay_parse/matchers.py | MatcherMatcher.fit_overlays | python | def fit_overlays(self, text, run_matchers=None, **kw):
self._maybe_run_matchers(text, run_matchers)
for i in self._list_match.fit_overlay(text, **kw):
yield i | First all matchers will run and then I will try to combine
them. Use run_matchers to force running(True) or not
running(False) the matchers.
See ListMatcher for arguments. | train | https://github.com/fakedrake/overlay_parse/blob/9ac362d6aef1ea41aff7375af088c6ebef93d0cd/overlay_parse/matchers.py#L229-L239 | [
"def _maybe_run_matchers(self, text, run_matchers):\n \"\"\"\n OverlayedText should be smart enough to not run twice the same\n matchers but this is an extra handle of control over that.\n \"\"\"\n\n if run_matchers is True or \\\n (run_matchers is not False and text not in self._overlayed_alre... | class MatcherMatcher(BaseMatcher):
"""
Match the matchers.
"""
def __init__(self, matchers, props=None, value_fn=None):
self.matchers = matchers
self.props = props
self.value_fn = value_fn
self._list_match = ListMatcher(
[OverlayMatcher(m.props) for m in ma... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.