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
solocompt/plugs-mail
plugs_mail/utils.py
to_email
python
def to_email(email_class, email, language=None, **data): if language: email_class().send([email], language=language, **data) else: email_class().send([email], translation.get_language(), **data)
Send email to specified email address
train
https://github.com/solocompt/plugs-mail/blob/6139fa79ddb437562db1769d03bd3098c25a06fa/plugs_mail/utils.py#L8-L15
null
""" Plugs Mail Utils """ from django.utils import translation from django.contrib.auth import get_user_model def to_user(email_class, user, **data): """ Email user """ try: email_class().send([user.email], user.language, **data) except AttributeError: # this is a fallback in case ...
solocompt/plugs-mail
plugs_mail/utils.py
to_user
python
def to_user(email_class, user, **data): try: email_class().send([user.email], user.language, **data) except AttributeError: # this is a fallback in case the user model does not have the language field email_class().send([user.email], translation.get_language(), **data)
Email user
train
https://github.com/solocompt/plugs-mail/blob/6139fa79ddb437562db1769d03bd3098c25a06fa/plugs_mail/utils.py#L17-L25
null
""" Plugs Mail Utils """ from django.utils import translation from django.contrib.auth import get_user_model def to_email(email_class, email, language=None, **data): """ Send email to specified email address """ if language: email_class().send([email], language=language, **data) else: ...
solocompt/plugs-mail
plugs_mail/utils.py
to_staff
python
def to_staff(email_class, **data): for user in get_user_model().objects.filter(is_staff=True): try: email_class().send([user.email], user.language, **data) except AttributeError: email_class().send([user.email], translation.get_language(), **data)
Email staff users
train
https://github.com/solocompt/plugs-mail/blob/6139fa79ddb437562db1769d03bd3098c25a06fa/plugs_mail/utils.py#L27-L35
null
""" Plugs Mail Utils """ from django.utils import translation from django.contrib.auth import get_user_model def to_email(email_class, email, language=None, **data): """ Send email to specified email address """ if language: email_class().send([email], language=language, **data) else: ...
solocompt/plugs-mail
plugs_mail/utils.py
to_superuser
python
def to_superuser(email_class, **data): for user in get_user_model().objects.filter(is_superuser=True): try: email_class().send([user.email], user.language, **data) except AttributeError: email_class().send([user.email], translation.get_language(), **data)
Email superusers
train
https://github.com/solocompt/plugs-mail/blob/6139fa79ddb437562db1769d03bd3098c25a06fa/plugs_mail/utils.py#L37-L45
null
""" Plugs Mail Utils """ from django.utils import translation from django.contrib.auth import get_user_model def to_email(email_class, email, language=None, **data): """ Send email to specified email address """ if language: email_class().send([email], language=language, **data) else: ...
solocompt/plugs-mail
plugs_mail/mail.py
PlugsMail.validate_context
python
def validate_context(self): if self.context and len(self.context) != len(set(self.context)): LOGGER.error('Cannot have duplicated context objects') raise Exception('Cannot have duplicated context objects.')
Make sure there are no duplicate context objects or we might end up with switched data Converting the tuple to a set gets rid of the eventual duplicate objects, comparing the length of the original tuple and set tells us if we have duplicates in the tuple or not
train
https://github.com/solocompt/plugs-mail/blob/6139fa79ddb437562db1769d03bd3098c25a06fa/plugs_mail/mail.py#L33-L45
null
class PlugsMail(object): """ Solo mail is the class responsible for getting and validating the context and prepare the email for sending """ template = None context = None context_data = {} data = None def __init__(self): self.validate_context() assert self.templ...
solocompt/plugs-mail
plugs_mail/mail.py
PlugsMail.get_instance_of
python
def get_instance_of(self, model_cls): for obj in self.data.values(): if isinstance(obj, model_cls): return obj LOGGER.error('Context Not Found') raise Exception('Context Not Found')
Search the data to find a instance of a model specified in the template
train
https://github.com/solocompt/plugs-mail/blob/6139fa79ddb437562db1769d03bd3098c25a06fa/plugs_mail/mail.py#L47-L56
null
class PlugsMail(object): """ Solo mail is the class responsible for getting and validating the context and prepare the email for sending """ template = None context = None context_data = {} data = None def __init__(self): self.validate_context() assert self.templ...
solocompt/plugs-mail
plugs_mail/mail.py
PlugsMail.get_context
python
def get_context(self): if not self.context: return else: assert isinstance(self.context, tuple), 'Expected a Tuple not {0}'.format(type(self.context)) for model in self.context: model_cls = utils.get_model_class(model) key = utils.camel_to_snake(mo...
Create a dict with the context data context is not required, but if it is defined it should be a tuple
train
https://github.com/solocompt/plugs-mail/blob/6139fa79ddb437562db1769d03bd3098c25a06fa/plugs_mail/mail.py#L58-L71
[ "def get_instance_of(self, model_cls):\n \"\"\"\n Search the data to find a instance\n of a model specified in the template\n \"\"\"\n for obj in self.data.values():\n if isinstance(obj, model_cls):\n return obj\n LOGGER.error('Context Not Found')\n raise Exception('Context No...
class PlugsMail(object): """ Solo mail is the class responsible for getting and validating the context and prepare the email for sending """ template = None context = None context_data = {} data = None def __init__(self): self.validate_context() assert self.templ...
solocompt/plugs-mail
plugs_mail/mail.py
PlugsMail.get_context_data
python
def get_context_data(self): self.get_context() self.context_data.update(self.get_extra_context()) return self.context_data
Context Data is equal to context + extra_context Merge the dicts context_data and extra_context and update state
train
https://github.com/solocompt/plugs-mail/blob/6139fa79ddb437562db1769d03bd3098c25a06fa/plugs_mail/mail.py#L82-L90
[ "def get_context(self):\n \"\"\"\n Create a dict with the context data\n context is not required, but if it\n is defined it should be a tuple\n \"\"\"\n if not self.context:\n return\n else:\n assert isinstance(self.context, tuple), 'Expected a Tuple not {0}'.format(type(self.cont...
class PlugsMail(object): """ Solo mail is the class responsible for getting and validating the context and prepare the email for sending """ template = None context = None context_data = {} data = None def __init__(self): self.validate_context() assert self.templ...
solocompt/plugs-mail
plugs_mail/mail.py
PlugsMail.send
python
def send(self, to, language=None, **data): self.data = data self.get_context_data() if app_settings['SEND_EMAILS']: try: if language: mail.send(to, template=self.template, context=self.context_data, language=language) else: ...
This is the method to be called
train
https://github.com/solocompt/plugs-mail/blob/6139fa79ddb437562db1769d03bd3098c25a06fa/plugs_mail/mail.py#L92-L106
[ "def get_context_data(self):\n \"\"\"\n Context Data is equal to context + extra_context\n Merge the dicts context_data and extra_context and\n update state\n \"\"\"\n self.get_context()\n self.context_data.update(self.get_extra_context())\n return self.context_data\n" ]
class PlugsMail(object): """ Solo mail is the class responsible for getting and validating the context and prepare the email for sending """ template = None context = None context_data = {} data = None def __init__(self): self.validate_context() assert self.templ...
solocompt/plugs-mail
plugs_mail/management/commands/load_email_templates.py
Command.override_default_templates
python
def override_default_templates(self): if plugs_mail_settings['OVERRIDE_TEMPLATE_DIR']: dir_ = plugs_mail_settings['OVERRIDE_TEMPLATE_DIR'] for file_ in os.listdir(dir_): if file_.endswith(('.html', 'txt')): self.overrides[file_] = dir_
Override the default emails already defined by other apps
train
https://github.com/solocompt/plugs-mail/blob/6139fa79ddb437562db1769d03bd3098c25a06fa/plugs_mail/management/commands/load_email_templates.py#L29-L37
null
class Command(BaseCommand): overrides = {} def handle(self, *args, **options): self.override_default_templates() templates = self.get_apps() count = self.create_templates(templates) if count: self.stdout.write(self.style.SUCCESS('Successfully loaded %s email templat...
solocompt/plugs-mail
plugs_mail/management/commands/load_email_templates.py
Command.get_apps
python
def get_apps(self): templates = [] for app in settings.INSTALLED_APPS: try: app = import_module(app + '.emails') templates += self.get_plugs_mail_classes(app) except ImportError: pass return templates
Get the list of installed apps and return the apps that have an emails module
train
https://github.com/solocompt/plugs-mail/blob/6139fa79ddb437562db1769d03bd3098c25a06fa/plugs_mail/management/commands/load_email_templates.py#L39-L52
null
class Command(BaseCommand): overrides = {} def handle(self, *args, **options): self.override_default_templates() templates = self.get_apps() count = self.create_templates(templates) if count: self.stdout.write(self.style.SUCCESS('Successfully loaded %s email templat...
solocompt/plugs-mail
plugs_mail/management/commands/load_email_templates.py
Command.get_template_files
python
def get_template_files(self, location, class_name): template_name = utils.camel_to_snake(class_name) dir_ = location[:-9] + 'templates/emails/' files_ = [] for file_ in self.get_templates_files_in_dir(dir_): if file_.startswith(template_name) and file_.endswith(('.html', '.tx...
Multilanguage support means that for each template we can have multiple templtate files, this methods returns all the template (html and txt) files that match the (class) template name
train
https://github.com/solocompt/plugs-mail/blob/6139fa79ddb437562db1769d03bd3098c25a06fa/plugs_mail/management/commands/load_email_templates.py#L60-L76
null
class Command(BaseCommand): overrides = {} def handle(self, *args, **options): self.override_default_templates() templates = self.get_apps() count = self.create_templates(templates) if count: self.stdout.write(self.style.SUCCESS('Successfully loaded %s email templat...
solocompt/plugs-mail
plugs_mail/management/commands/load_email_templates.py
Command.get_plugs_mail_classes
python
def get_plugs_mail_classes(self, app): classes = [] members = self.get_members(app) for member in members: name, cls = member if inspect.isclass(cls) and issubclass(cls, PlugsMail) and name != 'PlugsMail': files_ = self.get_template_files(app.__file__, nam...
Returns a list of tuples, but it should return a list of dicts
train
https://github.com/solocompt/plugs-mail/blob/6139fa79ddb437562db1769d03bd3098c25a06fa/plugs_mail/management/commands/load_email_templates.py#L78-L97
null
class Command(BaseCommand): overrides = {} def handle(self, *args, **options): self.override_default_templates() templates = self.get_apps() count = self.create_templates(templates) if count: self.stdout.write(self.style.SUCCESS('Successfully loaded %s email templat...
solocompt/plugs-mail
plugs_mail/management/commands/load_email_templates.py
Command.get_template_language
python
def get_template_language(self, file_): stem = Path(file_).stem language_code = stem.split('_')[-1:][0] if len(language_code) != 2: # TODO naive and temp implementation # check if the two chars correspond to one of the # available languages raise E...
Return the template language Every template file must end in with the language code, and the code must match the ISO_6301 lang code https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes valid examples: account_created_pt.html payment_created_en.txt
train
https://github.com/solocompt/plugs-mail/blob/6139fa79ddb437562db1769d03bd3098c25a06fa/plugs_mail/management/commands/load_email_templates.py#L99-L118
null
class Command(BaseCommand): overrides = {} def handle(self, *args, **options): self.override_default_templates() templates = self.get_apps() count = self.create_templates(templates) if count: self.stdout.write(self.style.SUCCESS('Successfully loaded %s email templat...
solocompt/plugs-mail
plugs_mail/management/commands/load_email_templates.py
Command.get_subject
python
def get_subject(self, text): first_line = text.splitlines(True)[0] # TODO second line should be empty if first_line.startswith('SUBJECT:'): subject = first_line[len('SUBJECT:'):] else: subject = first_line return subject.strip()
Email template subject is the first line of the email template, we can optionally add SUBJECT: to make it clearer
train
https://github.com/solocompt/plugs-mail/blob/6139fa79ddb437562db1769d03bd3098c25a06fa/plugs_mail/management/commands/load_email_templates.py#L120-L132
null
class Command(BaseCommand): overrides = {} def handle(self, *args, **options): self.override_default_templates() templates = self.get_apps() count = self.create_templates(templates) if count: self.stdout.write(self.style.SUCCESS('Successfully loaded %s email templat...
solocompt/plugs-mail
plugs_mail/management/commands/load_email_templates.py
Command.create_templates
python
def create_templates(self, templates): count = 0 for template in templates: if not self.template_exists_db(template): name, location, description, language = template text = self.open_file(location) html_content = self.get_html_content(text) ...
Gets a list of templates to insert into the database
train
https://github.com/solocompt/plugs-mail/blob/6139fa79ddb437562db1769d03bd3098c25a06fa/plugs_mail/management/commands/load_email_templates.py#L141-L161
null
class Command(BaseCommand): overrides = {} def handle(self, *args, **options): self.override_default_templates() templates = self.get_apps() count = self.create_templates(templates) if count: self.stdout.write(self.style.SUCCESS('Successfully loaded %s email templat...
solocompt/plugs-mail
plugs_mail/management/commands/load_email_templates.py
Command.open_file
python
def open_file(self, file_): with open(file_, 'r', encoding='utf-8') as file: text = '' for line in file: text += line return text
Receives a file path has input and returns a string with the contents of the file
train
https://github.com/solocompt/plugs-mail/blob/6139fa79ddb437562db1769d03bd3098c25a06fa/plugs_mail/management/commands/load_email_templates.py#L171-L180
null
class Command(BaseCommand): overrides = {} def handle(self, *args, **options): self.override_default_templates() templates = self.get_apps() count = self.create_templates(templates) if count: self.stdout.write(self.style.SUCCESS('Successfully loaded %s email templat...
solocompt/plugs-mail
plugs_mail/management/commands/load_email_templates.py
Command.template_exists_db
python
def template_exists_db(self, template): name = utils.camel_to_snake(template[0]).upper() language = utils.camel_to_snake(template[3]) try: models.EmailTemplate.objects.get(name=name, language=language) except models.EmailTemplate.DoesNotExist: return False ...
Receives a template and checks if it exists in the database using the template name and language
train
https://github.com/solocompt/plugs-mail/blob/6139fa79ddb437562db1769d03bd3098c25a06fa/plugs_mail/management/commands/load_email_templates.py#L183-L194
null
class Command(BaseCommand): overrides = {} def handle(self, *args, **options): self.override_default_templates() templates = self.get_apps() count = self.create_templates(templates) if count: self.stdout.write(self.style.SUCCESS('Successfully loaded %s email templat...
tetframework/Tonnikala
tonnikala/ir/generate.py
BaseIRGenerator.merge_text_nodes_on
python
def merge_text_nodes_on(self, node): if not isinstance(node, ContainerNode) or not node.children: return new_children = [] text_run = [] for i in node.children: if isinstance(i, Text) and not i.translatable: text_run.append(i.escaped()) ...
Merges all consecutive non-translatable text nodes into one
train
https://github.com/tetframework/Tonnikala/blob/99d168657da1b2372ff898254f80808ea8d1b83f/tonnikala/ir/generate.py#L57-L80
[ "def merge_text_nodes_on(self, node):\n \"\"\"Merges all consecutive non-translatable text nodes into one\"\"\"\n\n if not isinstance(node, ContainerNode) or not node.children:\n return\n\n new_children = []\n text_run = []\n for i in node.children:\n if isinstance(i, Text) and not i.tr...
class BaseIRGenerator(object): def __init__(self, filename=None, source=None, *a, **kw): super(BaseIRGenerator, self).__init__(*a, **kw) self.filename = filename self.source = source self.states = [{}] self.tree = IRTree() def syntax_error(self, message, lineno=None): ...
tetframework/Tonnikala
tonnikala/ir/generate.py
BaseIRGenerator.push_state
python
def push_state(self): new = dict(self.states[-1]) self.states.append(new) return self.state
Push a copy of the topmost state on top of the state stack, returns the new top.
train
https://github.com/tetframework/Tonnikala/blob/99d168657da1b2372ff898254f80808ea8d1b83f/tonnikala/ir/generate.py#L95-L103
null
class BaseIRGenerator(object): def __init__(self, filename=None, source=None, *a, **kw): super(BaseIRGenerator, self).__init__(*a, **kw) self.filename = filename self.source = source self.states = [{}] self.tree = IRTree() def syntax_error(self, message, lineno=None): ...
tetframework/Tonnikala
tonnikala/ir/generate.py
BaseDOMIRGenerator.enter_node
python
def enter_node(self, ir_node): this_is_cdata = (isinstance(ir_node, Element) and ir_node.name in self.cdata_elements) self.state['is_cdata'] = bool(self.state.get('is_cdata')) or this_is_cdata
Enter the given element; keeps track of `cdata`; subclasses may extend by overriding
train
https://github.com/tetframework/Tonnikala/blob/99d168657da1b2372ff898254f80808ea8d1b83f/tonnikala/ir/generate.py#L162-L169
null
class BaseDOMIRGenerator(BaseIRGenerator): def __init__(self, document=None, mode='html5', *a, **kw): super(BaseDOMIRGenerator, self).__init__(*a, **kw) self.dom_document = document self.mode = mode if mode in ['html', 'html5', 'xhtml']: self.empty_elements = html5_empty...
tetframework/Tonnikala
tonnikala/i18n/__init__.py
extract_tonnikala
python
def extract_tonnikala(fileobj, keywords, comment_tags, options): extractor = TonnikalaExtractor() for msg in extractor(filename=None, fileobj=fileobj, options=Options()): msgid = msg.msgid, prefix = '' if msg.msgid_plural: msgid = (msg.msgid_plural,) + msgid pref...
Extract messages from Tonnikala files. :param fileobj: the file-like object the messages should be extracted from :param keywords: a list of keywords (i.e. function names) that should be recognized as translation functions :param comment_tags: a list of translator t...
train
https://github.com/tetframework/Tonnikala/blob/99d168657da1b2372ff898254f80808ea8d1b83f/tonnikala/i18n/__init__.py#L57-L84
null
import io from lingua.extractors import Extractor from lingua.extractors import Message from lingua.extractors.python import _extract_python from tonnikala.ir.nodes import TranslatableText, Expression from tonnikala.loader import parsers class TonnikalaExtractor(Extractor): "Extract strings from tonnikala templa...
tetframework/Tonnikala
tonnikala/languages/javascript/generator.py
FreeVariableAnalyzerVisitor.visit_Identifier
python
def visit_Identifier(self, node): if not self._is_mangle_candidate(node): return name = node.value symbol = node.scope.resolve(node.value) if symbol is None: self.free_variables.add(name)
Mangle names.
train
https://github.com/tetframework/Tonnikala/blob/99d168657da1b2372ff898254f80808ea8d1b83f/tonnikala/languages/javascript/generator.py#L49-L58
null
class FreeVariableAnalyzerVisitor(Visitor): """Mangles names. Walks over a parsed tree and changes ID values to corresponding mangled names. """ def __init__(self): self.free_variables = set() @staticmethod def _is_mangle_candidate(id_node): """Return True if Identifier no...
tetframework/Tonnikala
tonnikala/ir/nodes.py
Extends.add_child
python
def add_child(self, child): if isinstance(child, Comment): return # ignore Text nodes with whitespace-only content if isinstance(child, Text) and not child.text.strip(): return super(Extends, self).add_child(child)
Add a child to the tree. Extends discards all comments and whitespace Text. On non-whitespace Text, and any other nodes, raise a syntax error.
train
https://github.com/tetframework/Tonnikala/blob/99d168657da1b2372ff898254f80808ea8d1b83f/tonnikala/ir/nodes.py#L334-L348
[ "def add_child(self, child):\n \"\"\"\n Add a child to the tree. Subclasses may raise SyntaxError\n \"\"\"\n self.children.append(child)\n" ]
class Extends(ContainerNode): def __init__(self, href): super(Extends, self).__init__() self.href = href def __str__(self): # pragma: no cover children = str(self.children) return ', '.join([("(%s)" % self.expression), children]) def validate(self, validator): fo...
tetframework/Tonnikala
tonnikala/expr.py
_strip_dollars_fast
python
def _strip_dollars_fast(text): def _sub(m): if m.group(0) == '$$': return '$' raise HasExprException() return _dollar_strip_re.sub(_sub, text)
Replace `$$` with `$`. raise immediately if `$` starting an interpolated expression is found. @param text: the source text @return: the text with dollars replaced, or raise HasExprException if there are interpolated expressions
train
https://github.com/tetframework/Tonnikala/blob/99d168657da1b2372ff898254f80808ea8d1b83f/tonnikala/expr.py#L17-L32
null
# -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function """Tonnikala compiler. Produces source code from XML.""" import re from tonnikala.ir.nodes import Text, DynamicText, TranslatableText from tonnikala.languages import python _dollar_strip_re = re.compile(r'\$[a-zA-Z_{$]') class...
tetframework/Tonnikala
tonnikala/languages/python/generator.py
adjust_locations
python
def adjust_locations(ast_node, first_lineno, first_offset): line_delta = first_lineno - 1 def _fix(node): if 'lineno' in node._attributes: lineno = node.lineno col = node.col_offset # adjust the offset on the first line if lineno == 1: c...
Adjust the locations of the ast nodes, offsetting them to the new lineno and column offset
train
https://github.com/tetframework/Tonnikala/blob/99d168657da1b2372ff898254f80808ea8d1b83f/tonnikala/languages/python/generator.py#L72-L97
[ "def _fix(node):\n if 'lineno' in node._attributes:\n lineno = node.lineno\n col = node.col_offset\n\n # adjust the offset on the first line\n if lineno == 1:\n col += first_offset\n\n lineno += line_delta\n\n node.lineno = lineno\n node.col_offset = co...
# -*- coding: utf-8 -*- # notice: this module cannot be sanely written to take use of # unicode_literals, bc some of the arguments need to be str on # both python2 and 3 from __future__ import absolute_import, division, print_function import ast from ast import * from collections import Iterable from .astalyzer imp...
tetframework/Tonnikala
tonnikala/languages/python/generator.py
coalesce_outputs
python
def coalesce_outputs(tree): coalesce_all_outputs = True if coalesce_all_outputs: should_coalesce = lambda n: True else: should_coalesce = lambda n: n.output_args[0].__class__ is Str class OutputCoalescer(NodeVisitor): def visit(self, node): # if - else expression al...
Coalesce the constant output expressions __output__('foo') __output__('bar') __output__(baz) __output__('xyzzy') into __output__('foobar', baz, 'xyzzy')
train
https://github.com/tetframework/Tonnikala/blob/99d168657da1b2372ff898254f80808ea8d1b83f/tonnikala/languages/python/generator.py#L560-L651
null
# -*- coding: utf-8 -*- # notice: this module cannot be sanely written to take use of # unicode_literals, bc some of the arguments need to be str on # both python2 and 3 from __future__ import absolute_import, division, print_function import ast from ast import * from collections import Iterable from .astalyzer imp...
tetframework/Tonnikala
tonnikala/languages/python/generator.py
remove_locations
python
def remove_locations(node): def fix(node): if 'lineno' in node._attributes and hasattr(node, 'lineno'): del node.lineno if 'col_offset' in node._attributes and hasattr(node, 'col_offset'): del node.col_offset for child in iter_child_nodes(node): fix(chi...
Removes locations from the given AST tree completely
train
https://github.com/tetframework/Tonnikala/blob/99d168657da1b2372ff898254f80808ea8d1b83f/tonnikala/languages/python/generator.py#L654-L669
[ "def fix(node):\n if 'lineno' in node._attributes and hasattr(node, 'lineno'):\n del node.lineno\n\n if 'col_offset' in node._attributes and hasattr(node, 'col_offset'):\n del node.col_offset\n\n for child in iter_child_nodes(node):\n fix(child)\n" ]
# -*- coding: utf-8 -*- # notice: this module cannot be sanely written to take use of # unicode_literals, bc some of the arguments need to be str on # both python2 and 3 from __future__ import absolute_import, division, print_function import ast from ast import * from collections import Iterable from .astalyzer imp...
tetframework/Tonnikala
tonnikala/runtime/python.py
bind
python
def bind(context, block=False): if block: def decorate(func): name = func.__name__.replace('__TK__block__', '') if name not in context: context[name] = func return context[name] return decorate def decorate(func): name = func.__name_...
Given the context, returns a decorator wrapper; the binder replaces the wrapped func with the value from the context OR puts this function in the context with the name.
train
https://github.com/tetframework/Tonnikala/blob/99d168657da1b2372ff898254f80808ea8d1b83f/tonnikala/runtime/python.py#L87-L110
null
from __future__ import absolute_import, division, print_function, \ unicode_literals from collections import Mapping from markupsafe import escape from ..compat import text_type, PY3 NoneType = type(None) class _TKPythonBufferImpl(object): def __init__(self): self._buffer = buffer = [] e = ...
tetframework/Tonnikala
tonnikala/languages/javascript/jslex.py
literals
python
def literals(choices, prefix="", suffix=""): return "|".join(prefix + re.escape(c) + suffix for c in choices.split())
Create a regex from a space-separated list of literal `choices`. If provided, `prefix` and `suffix` will be attached to each choice individually.
train
https://github.com/tetframework/Tonnikala/blob/99d168657da1b2372ff898254f80808ea8d1b83f/tonnikala/languages/javascript/jslex.py#L24-L31
null
# -*- coding: utf8 -*- from __future__ import absolute_import, division, print_function, \ unicode_literals """JsLex: a lexer for Javascript""" # From https://bitbucket.org/ned/jslex import re class Tok(object): """A specification for a token class.""" num = 0 def __init__(self, name, regex, next=...
tetframework/Tonnikala
tonnikala/languages/javascript/jslex.py
Lexer.lex
python
def lex(self, text, start=0): max = len(text) eaten = start s = self.state r = self.regexes toks = self.toks while eaten < max: for match in r[s].finditer(text, eaten): name = match.lastgroup tok = toks[name] tok...
Lexically analyze `text`. Yields pairs (`name`, `tokentext`).
train
https://github.com/tetframework/Tonnikala/blob/99d168657da1b2372ff898254f80808ea8d1b83f/tonnikala/languages/javascript/jslex.py#L52-L75
null
class Lexer(object): """A generic multi-state regex-based lexer.""" def __init__(self, states, first): self.regexes = {} self.toks = {} for state, rules in states.items(): parts = [] for tok in rules: groupid = "t%d" % tok.id self...
tetframework/Tonnikala
tonnikala/loader.py
handle_exception
python
def handle_exception(exc_info=None, source_hint=None, tb_override=_NO): global _make_traceback if exc_info is None: # pragma: no cover exc_info = sys.exc_info() # the debugging module is imported when it's used for the first time. # we're doing a lot of stuff there and for applications that d...
Exception handling helper. This is used internally to either raise rewritten exceptions or return a rendered traceback for the template.
train
https://github.com/tetframework/Tonnikala/blob/99d168657da1b2372ff898254f80808ea8d1b83f/tonnikala/loader.py#L71-L93
[ "def reraise(tp, value, tb=None): # pragma: no cover\n if value is None:\n value = tp()\n if value.__traceback__ is not tb:\n raise value.with_traceback(tb)\n raise value\n" ]
import errno import sys import time import codecs import os from .compat import reraise from .languages.javascript.generator import Generator as JavascriptGenerator from .languages.python.generator import Generator as PythonGenerator from .runtime import python, exceptions from .syntaxes.chameleon import parse as par...
tetframework/Tonnikala
tonnikala/loader.py
FileLoader._maybe_purge_cache
python
def _maybe_purge_cache(self): if self._last_reload_check + MIN_CHECK_INTERVAL > time.time(): return for name, tmpl in list(self.cache.items()): if not os.stat(tmpl.path): self.cache.pop(name) continue if os.stat(tmpl.path).st_mtime >...
If enough time since last check has elapsed, check if any of the cached templates has changed. If any of the template files were deleted, remove that file only. If any were changed, then purge the entire cache.
train
https://github.com/tetframework/Tonnikala/blob/99d168657da1b2372ff898254f80808ea8d1b83f/tonnikala/loader.py#L231-L251
null
class FileLoader(Loader): def __init__(self, paths=[], debug=False, syntax='tonnikala', *args, **kwargs): super(FileLoader, self).__init__(*args, debug=debug, syntax=syntax, **kwargs) self.cache = {} self.paths = list(paths) self.reload = False self._last_reload_check = time...
tetframework/Tonnikala
tonnikala/loader.py
FileLoader.load
python
def load(self, name): if self.reload: self._maybe_purge_cache() template = self.cache.get(name) if template: return template path = self.resolve(name) if not path: raise OSError(errno.ENOENT, "File not found: %s" % name) with codecs...
If not yet in the cache, load the named template and compiles it, placing it into the cache. If in cache, return the cached template.
train
https://github.com/tetframework/Tonnikala/blob/99d168657da1b2372ff898254f80808ea8d1b83f/tonnikala/loader.py#L253-L281
[ "def load_string(self, string, filename=\"<string>\"):\n parser_func = parsers.get(self.syntax)\n if not parser_func:\n raise ValueError(\"Invalid parser syntax %s: valid syntaxes: %r\"\n % sorted(parsers.keys()))\n\n try:\n tree = parser_func(filename, string, transla...
class FileLoader(Loader): def __init__(self, paths=[], debug=False, syntax='tonnikala', *args, **kwargs): super(FileLoader, self).__init__(*args, debug=debug, syntax=syntax, **kwargs) self.cache = {} self.paths = list(paths) self.reload = False self._last_reload_check = time...
tetframework/Tonnikala
tonnikala/runtime/debug.py
translate_exception
python
def translate_exception(exc_info, initial_skip=0): tb = exc_info[2] frames = [] # skip some internal frames if wanted for x in range(initial_skip): if tb is not None: tb = tb.tb_next initial_tb = tb while tb is not None: # skip frames decorated with @internalcode. ...
If passed an exc_info it will automatically rewrite the exceptions all the way down to the correct line numbers and frames.
train
https://github.com/tetframework/Tonnikala/blob/99d168657da1b2372ff898254f80808ea8d1b83f/tonnikala/runtime/debug.py#L162-L201
[ "def reraise(tp, value, tb=None): # pragma: no cover\n if value is None:\n value = tp()\n if value.__traceback__ is not tb:\n raise value.with_traceback(tb)\n raise value\n", "def make_frame_proxy(frame):\n proxy = TracebackFrameProxy(frame)\n if tproxy is None:\n return proxy...
# -*- coding: utf-8 -*- """ tonnikala.runtime.debug ~~~~~~~~~~~~~~~~~~~~~~~ Implements the debug interface for Tonnikala. This module does some pretty ugly stuff with the Python traceback system in order to achieve tracebacks with correct line numbers, locals and contents. Based on Jinja2 modu...
tetframework/Tonnikala
tonnikala/runtime/debug.py
fake_exc_info
python
def fake_exc_info(exc_info, filename, lineno): exc_type, exc_value, tb = exc_info # figure the real context out if tb is not None: # if there is a local called __tonnikala_exception__, we get # rid of it to not break the debug functionality. locals = tb.tb_frame.f_locals.copy() ...
Helper for `translate_exception`.
train
https://github.com/tetframework/Tonnikala/blob/99d168657da1b2372ff898254f80808ea8d1b83f/tonnikala/runtime/debug.py#L204-L278
null
# -*- coding: utf-8 -*- """ tonnikala.runtime.debug ~~~~~~~~~~~~~~~~~~~~~~~ Implements the debug interface for Tonnikala. This module does some pretty ugly stuff with the Python traceback system in order to achieve tracebacks with correct line numbers, locals and contents. Based on Jinja2 modu...
collectiveacuity/jsonModel
jsonmodel/extensions.py
tabulate
python
def tabulate(json_model): ''' a function to add the tabulate method to a jsonModel object :param json_model: jsonModel object :return: jsonModel object ''' import types from jsonmodel._extensions import tabulate as _tabulate try: from tabulate import tabulate ...
a function to add the tabulate method to a jsonModel object :param json_model: jsonModel object :return: jsonModel object
train
https://github.com/collectiveacuity/jsonModel/blob/1ea64c36d78add3faa7b85ff82c5ec685458c940/jsonmodel/extensions.py#L6-L26
null
''' a package of extensions to a jsonModel class object ''' __author__ = 'rcj1492' __created__ = '2018.03' __license__ = 'MIT' def tabulate(json_model): ''' a function to add the tabulate method to a jsonModel object :param json_model: jsonModel object :return: jsonModel object ''' impor...
collectiveacuity/jsonModel
jsonmodel/validators.py
jsonModel._evaluate_field
python
def _evaluate_field(self, record_dict, field_name, field_criteria): ''' a helper method for evaluating record values based upon query criteria :param record_dict: dictionary with model valid data to evaluate :param field_name: string with path to root of query field :param field_criter...
a helper method for evaluating record values based upon query criteria :param record_dict: dictionary with model valid data to evaluate :param field_name: string with path to root of query field :param field_criteria: dictionary with query operators and qualifiers :return: boolean (True...
train
https://github.com/collectiveacuity/jsonModel/blob/1ea64c36d78add3faa7b85ff82c5ec685458c940/jsonmodel/validators.py#L548-L730
null
class jsonModel(object): __rules__ = jsonLoader('jsonmodel', 'models/model-rules.json') def __init__(self, data_model, query_rules=None): ''' a method for testing data model declaration & initializing the class :param data_model: dictionary with json model architecture :p...
collectiveacuity/jsonModel
jsonmodel/validators.py
jsonModel._validate_dict
python
def _validate_dict(self, input_dict, schema_dict, path_to_root, object_title=''): ''' a helper method for recursively validating keys in dictionaries :return input_dict ''' # reconstruct key path to current dictionary in model rules_top_level_key = re.sub('\[\d+\]', '[0]', path_to...
a helper method for recursively validating keys in dictionaries :return input_dict
train
https://github.com/collectiveacuity/jsonModel/blob/1ea64c36d78add3faa7b85ff82c5ec685458c940/jsonmodel/validators.py#L732-L904
null
class jsonModel(object): __rules__ = jsonLoader('jsonmodel', 'models/model-rules.json') def __init__(self, data_model, query_rules=None): ''' a method for testing data model declaration & initializing the class :param data_model: dictionary with json model architecture :p...
collectiveacuity/jsonModel
jsonmodel/validators.py
jsonModel._validate_list
python
def _validate_list(self, input_list, schema_list, path_to_root, object_title=''): ''' a helper method for recursively validating items in a list :return: input_list ''' # construct rules for list and items rules_path_to_root = re.sub('\[\d+\]', '[0]', path_to_root) ...
a helper method for recursively validating items in a list :return: input_list
train
https://github.com/collectiveacuity/jsonModel/blob/1ea64c36d78add3faa7b85ff82c5ec685458c940/jsonmodel/validators.py#L906-L998
null
class jsonModel(object): __rules__ = jsonLoader('jsonmodel', 'models/model-rules.json') def __init__(self, data_model, query_rules=None): ''' a method for testing data model declaration & initializing the class :param data_model: dictionary with json model architecture :p...
collectiveacuity/jsonModel
jsonmodel/validators.py
jsonModel._validate_number
python
def _validate_number(self, input_number, path_to_root, object_title=''): ''' a helper method for validating properties of a number :return: input_number ''' rules_path_to_root = re.sub('\[\d+\]', '[0]', path_to_root) input_criteria = self.keyMap[rules_path_to_root]...
a helper method for validating properties of a number :return: input_number
train
https://github.com/collectiveacuity/jsonModel/blob/1ea64c36d78add3faa7b85ff82c5ec685458c940/jsonmodel/validators.py#L1000-L1064
null
class jsonModel(object): __rules__ = jsonLoader('jsonmodel', 'models/model-rules.json') def __init__(self, data_model, query_rules=None): ''' a method for testing data model declaration & initializing the class :param data_model: dictionary with json model architecture :p...
collectiveacuity/jsonModel
jsonmodel/validators.py
jsonModel._validate_string
python
def _validate_string(self, input_string, path_to_root, object_title=''): ''' a helper method for validating properties of a string :return: input_string ''' rules_path_to_root = re.sub('\[\d+\]', '[0]', path_to_root) input_criteria = self.keyMap[rules_path_to_root]...
a helper method for validating properties of a string :return: input_string
train
https://github.com/collectiveacuity/jsonModel/blob/1ea64c36d78add3faa7b85ff82c5ec685458c940/jsonmodel/validators.py#L1066-L1169
null
class jsonModel(object): __rules__ = jsonLoader('jsonmodel', 'models/model-rules.json') def __init__(self, data_model, query_rules=None): ''' a method for testing data model declaration & initializing the class :param data_model: dictionary with json model architecture :p...
collectiveacuity/jsonModel
jsonmodel/validators.py
jsonModel._validate_boolean
python
def _validate_boolean(self, input_boolean, path_to_root, object_title=''): ''' a helper method for validating properties of a boolean :return: input_boolean ''' rules_path_to_root = re.sub('\[\d+\]', '[0]', path_to_root) input_criteria = self.keyMap[rules_path_to_r...
a helper method for validating properties of a boolean :return: input_boolean
train
https://github.com/collectiveacuity/jsonModel/blob/1ea64c36d78add3faa7b85ff82c5ec685458c940/jsonmodel/validators.py#L1171-L1200
null
class jsonModel(object): __rules__ = jsonLoader('jsonmodel', 'models/model-rules.json') def __init__(self, data_model, query_rules=None): ''' a method for testing data model declaration & initializing the class :param data_model: dictionary with json model architecture :p...
collectiveacuity/jsonModel
jsonmodel/validators.py
jsonModel._ingest_dict
python
def _ingest_dict(self, input_dict, schema_dict, path_to_root): ''' a helper method for ingesting keys, value pairs in a dictionary :return: valid_dict ''' valid_dict = {} # construct path to root for rules rules_path_to_root = re.sub('\[\d+\]', '[0]', path_to_...
a helper method for ingesting keys, value pairs in a dictionary :return: valid_dict
train
https://github.com/collectiveacuity/jsonModel/blob/1ea64c36d78add3faa7b85ff82c5ec685458c940/jsonmodel/validators.py#L1202-L1272
[ "def _ingest_dict(self, input_dict, schema_dict, path_to_root):\n\n '''\n a helper method for ingesting keys, value pairs in a dictionary\n\n :return: valid_dict\n '''\n\n valid_dict = {}\n\n# construct path to root for rules\n rules_path_to_root = re.sub('\\[\\d+\\]', '[0]', path_to_root)\n\n...
class jsonModel(object): __rules__ = jsonLoader('jsonmodel', 'models/model-rules.json') def __init__(self, data_model, query_rules=None): ''' a method for testing data model declaration & initializing the class :param data_model: dictionary with json model architecture :p...
collectiveacuity/jsonModel
jsonmodel/validators.py
jsonModel._ingest_list
python
def _ingest_list(self, input_list, schema_list, path_to_root): ''' a helper method for ingesting items in a list :return: valid_list ''' valid_list = [] # construct max list size max_size = None rules_path_to_root = re.sub('\[\d+\]', '[0]', path_to_roo...
a helper method for ingesting items in a list :return: valid_list
train
https://github.com/collectiveacuity/jsonModel/blob/1ea64c36d78add3faa7b85ff82c5ec685458c940/jsonmodel/validators.py#L1274-L1325
null
class jsonModel(object): __rules__ = jsonLoader('jsonmodel', 'models/model-rules.json') def __init__(self, data_model, query_rules=None): ''' a method for testing data model declaration & initializing the class :param data_model: dictionary with json model architecture :p...
collectiveacuity/jsonModel
jsonmodel/validators.py
jsonModel._ingest_number
python
def _ingest_number(self, input_number, path_to_root): ''' a helper method for ingesting a number :return: valid_number ''' valid_number = 0.0 try: valid_number = self._validate_number(input_number, path_to_root) except: rules_path_t...
a helper method for ingesting a number :return: valid_number
train
https://github.com/collectiveacuity/jsonModel/blob/1ea64c36d78add3faa7b85ff82c5ec685458c940/jsonmodel/validators.py#L1327-L1347
null
class jsonModel(object): __rules__ = jsonLoader('jsonmodel', 'models/model-rules.json') def __init__(self, data_model, query_rules=None): ''' a method for testing data model declaration & initializing the class :param data_model: dictionary with json model architecture :p...
collectiveacuity/jsonModel
jsonmodel/validators.py
jsonModel._ingest_string
python
def _ingest_string(self, input_string, path_to_root): ''' a helper method for ingesting a string :return: valid_string ''' valid_string = '' try: valid_string = self._validate_string(input_string, path_to_root) except: rules_path_to...
a helper method for ingesting a string :return: valid_string
train
https://github.com/collectiveacuity/jsonModel/blob/1ea64c36d78add3faa7b85ff82c5ec685458c940/jsonmodel/validators.py#L1349-L1366
null
class jsonModel(object): __rules__ = jsonLoader('jsonmodel', 'models/model-rules.json') def __init__(self, data_model, query_rules=None): ''' a method for testing data model declaration & initializing the class :param data_model: dictionary with json model architecture :p...
collectiveacuity/jsonModel
jsonmodel/validators.py
jsonModel._ingest_boolean
python
def _ingest_boolean(self, input_boolean, path_to_root): ''' a helper method for ingesting a boolean :return: valid_boolean ''' valid_boolean = False try: valid_boolean = self._validate_boolean(input_boolean, path_to_root) except: ru...
a helper method for ingesting a boolean :return: valid_boolean
train
https://github.com/collectiveacuity/jsonModel/blob/1ea64c36d78add3faa7b85ff82c5ec685458c940/jsonmodel/validators.py#L1368-L1385
null
class jsonModel(object): __rules__ = jsonLoader('jsonmodel', 'models/model-rules.json') def __init__(self, data_model, query_rules=None): ''' a method for testing data model declaration & initializing the class :param data_model: dictionary with json model architecture :p...
collectiveacuity/jsonModel
jsonmodel/validators.py
jsonModel._reconstruct
python
def _reconstruct(self, path_to_root): ''' a helper method for finding the schema endpoint from a path to root :param path_to_root: string with dot path to root from :return: list, dict, string, number, or boolean at path to root ''' # split path to root into segments ...
a helper method for finding the schema endpoint from a path to root :param path_to_root: string with dot path to root from :return: list, dict, string, number, or boolean at path to root
train
https://github.com/collectiveacuity/jsonModel/blob/1ea64c36d78add3faa7b85ff82c5ec685458c940/jsonmodel/validators.py#L1387-L1412
null
class jsonModel(object): __rules__ = jsonLoader('jsonmodel', 'models/model-rules.json') def __init__(self, data_model, query_rules=None): ''' a method for testing data model declaration & initializing the class :param data_model: dictionary with json model architecture :p...
collectiveacuity/jsonModel
jsonmodel/validators.py
jsonModel._walk
python
def _walk(self, path_to_root, record_dict): ''' a helper method for finding the record endpoint from a path to root :param path_to_root: string with dot path to root from :param record_dict: :return: list, dict, string, number, or boolean at path to root ''' # ...
a helper method for finding the record endpoint from a path to root :param path_to_root: string with dot path to root from :param record_dict: :return: list, dict, string, number, or boolean at path to root
train
https://github.com/collectiveacuity/jsonModel/blob/1ea64c36d78add3faa7b85ff82c5ec685458c940/jsonmodel/validators.py#L1414-L1468
null
class jsonModel(object): __rules__ = jsonLoader('jsonmodel', 'models/model-rules.json') def __init__(self, data_model, query_rules=None): ''' a method for testing data model declaration & initializing the class :param data_model: dictionary with json model architecture :p...
collectiveacuity/jsonModel
jsonmodel/validators.py
jsonModel.validate
python
def validate(self, input_data, path_to_root='', object_title=''): ''' a core method for validating input against the model input_data is only returned if all data is valid :param input_data: list, dict, string, number, or boolean to validate :param path_to_root: [optio...
a core method for validating input against the model input_data is only returned if all data is valid :param input_data: list, dict, string, number, or boolean to validate :param path_to_root: [optional] string with dot-path of model component :param object_title: [optional] string...
train
https://github.com/collectiveacuity/jsonModel/blob/1ea64c36d78add3faa7b85ff82c5ec685458c940/jsonmodel/validators.py#L1470-L1540
[ "def _validate_dict(self, input_dict, schema_dict, path_to_root, object_title=''):\n\n ''' a helper method for recursively validating keys in dictionaries\n\n :return input_dict\n '''\n\n# reconstruct key path to current dictionary in model\n rules_top_level_key = re.sub('\\[\\d+\\]', '[0]', path_to_roo...
class jsonModel(object): __rules__ = jsonLoader('jsonmodel', 'models/model-rules.json') def __init__(self, data_model, query_rules=None): ''' a method for testing data model declaration & initializing the class :param data_model: dictionary with json model architecture :p...
collectiveacuity/jsonModel
jsonmodel/validators.py
jsonModel.ingest
python
def ingest(self, **kwargs): ''' a core method to ingest and validate arbitrary keyword data **NOTE: data is always returned with this method** for each key in the model, a value is returned according to the following priority: 1. value in kwar...
a core method to ingest and validate arbitrary keyword data **NOTE: data is always returned with this method** for each key in the model, a value is returned according to the following priority: 1. value in kwargs if field passes validation test 2....
train
https://github.com/collectiveacuity/jsonModel/blob/1ea64c36d78add3faa7b85ff82c5ec685458c940/jsonmodel/validators.py#L1542-L1578
[ "def _ingest_dict(self, input_dict, schema_dict, path_to_root):\n\n '''\n a helper method for ingesting keys, value pairs in a dictionary\n\n :return: valid_dict\n '''\n\n valid_dict = {}\n\n# construct path to root for rules\n rules_path_to_root = re.sub('\\[\\d+\\]', '[0]', path_to_root)\n\n...
class jsonModel(object): __rules__ = jsonLoader('jsonmodel', 'models/model-rules.json') def __init__(self, data_model, query_rules=None): ''' a method for testing data model declaration & initializing the class :param data_model: dictionary with json model architecture :p...
collectiveacuity/jsonModel
jsonmodel/validators.py
jsonModel.query
python
def query(self, query_criteria, valid_record=None): ''' a core method for querying model valid data with criteria **NOTE: input is only returned if all fields & qualifiers are valid for model :param query_criteria: dictionary with model field names and query qualifiers ...
a core method for querying model valid data with criteria **NOTE: input is only returned if all fields & qualifiers are valid for model :param query_criteria: dictionary with model field names and query qualifiers :param valid_record: dictionary with model valid record ...
train
https://github.com/collectiveacuity/jsonModel/blob/1ea64c36d78add3faa7b85ff82c5ec685458c940/jsonmodel/validators.py#L1580-L1666
[ "def _validate_fields(self, fields_dict, fields_rules, declared_value=True):\n\n# validate key names in fields\n for key, value in fields_dict.items():\n\n # convert javascript dot_path to class dot_path\n if not key:\n key = '.'\n else:\n if key[0] != '.':\n ...
class jsonModel(object): __rules__ = jsonLoader('jsonmodel', 'models/model-rules.json') def __init__(self, data_model, query_rules=None): ''' a method for testing data model declaration & initializing the class :param data_model: dictionary with json model architecture :p...
collectiveacuity/jsonModel
jsonmodel/_extensions.py
tabulate
python
def tabulate(self, format='html', syntax=''): ''' a function to create a table from the class model keyMap :param format: string with format for table output :param syntax: [optional] string with linguistic syntax :return: string with table ''' from tabulate import tabulate as _tabula...
a function to create a table from the class model keyMap :param format: string with format for table output :param syntax: [optional] string with linguistic syntax :return: string with table
train
https://github.com/collectiveacuity/jsonModel/blob/1ea64c36d78add3faa7b85ff82c5ec685458c940/jsonmodel/_extensions.py#L34-L209
[ "def _segment_path(dot_path):\n import re\n digit_pat = re.compile('\\[(\\d+)\\]')\n key_list = dot_path.split('.')\n segment_list = []\n for key in key_list:\n if key:\n item_list = digit_pat.split(key)\n for item in item_list:\n if item:\n ...
''' a package of helper functions for extensions.py ''' __author__ = 'rcj1492' __created__ = '2018.03' __license__ = 'MIT' def _segment_path(dot_path): import re digit_pat = re.compile('\[(\d+)\]') key_list = dot_path.split('.') segment_list = [] for key in key_list: if key: ite...
fchauvel/MAD
mad/simulation/tasks.py
Task._execute
python
def _execute(self, worker): self._assert_status_is(TaskStatus.RUNNING) operation = worker.look_up(self.operation) operation.invoke(self, [], worker=worker)
This method is ASSIGNED during the evaluation to control how to resume it once it has been paused
train
https://github.com/fchauvel/MAD/blob/806d5174848b1a502e5c683894995602478c448b/mad/simulation/tasks.py#L252-L258
[ "def _assert_status_is(self, *legal_states):\n assert self.status in legal_states, \\\n \"Found status == {0.name} (expecting {1!s})\".format(self.status, [ s.name for s in legal_states ])\n" ]
class Task: def __init__(self, service, request=None): self.service = service self.worker = None self.request = request self.status = TaskStatus.CREATED @property def priority(self): return self.request.priority @property def identifier(self): retur...
fchauvel/MAD
mad/evaluation.py
Evaluation.of_think
python
def of_think(self, think): return self._compute( duration=think.duration, after=self.continuation)
Simulate the worker processing the task for the specified amount of time. The worker is not released and the task is not paused.
train
https://github.com/fchauvel/MAD/blob/806d5174848b1a502e5c683894995602478c448b/mad/evaluation.py#L209-L216
[ "def _compute(self, duration, after):\n task = self._look_up(Symbols.TASK)\n task.compute(duration, continuation=lambda: after(Success()))\n return Busy()\n" ]
class Evaluation: """ Represent the future evaluation of an expression within a given environment. The expression is bound to a continuation, that is the next evaluation to carry out. """ def __init__(self, environment, expression, factory, continuation=lambda x: x): self.environment = envi...
fchauvel/MAD
mad/parsing.py
p_definition_list
python
def p_definition_list(p): if len(p) == 3: p[0] = p[1] + p[2] elif len(p) == 2: p[0] = p[1] else: raise RuntimeError("Invalid production rules 'p_action_list'")
definition_list : definition definition_list | definition
train
https://github.com/fchauvel/MAD/blob/806d5174848b1a502e5c683894995602478c448b/mad/parsing.py#L122-L132
null
#!/usr/bin/env python # # This file is part of MAD. # # MAD is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # MAD is distributed in ...
fchauvel/MAD
mad/parsing.py
p_define_service
python
def p_define_service(p): if len(p) == 7: body = p[4] + p[5] else: body = p[4] p[0] = DefineService(p[2], body)
define_service : SERVICE IDENTIFIER OPEN_CURLY_BRACKET settings operation_list CLOSE_CURLY_BRACKET | SERVICE IDENTIFIER OPEN_CURLY_BRACKET operation_list CLOSE_CURLY_BRACKET
train
https://github.com/fchauvel/MAD/blob/806d5174848b1a502e5c683894995602478c448b/mad/parsing.py#L143-L152
null
#!/usr/bin/env python # # This file is part of MAD. # # MAD is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # MAD is distributed in ...
fchauvel/MAD
mad/parsing.py
p_setting_list
python
def p_setting_list(p): if len(p) == 3: p[0] = merge_map(p[1], p[2]) elif len(p) == 2: p[0] = p[1] else: raise RuntimeError("Invalid production rules 'p_setting_list'")
setting_list : setting setting_list | setting
train
https://github.com/fchauvel/MAD/blob/806d5174848b1a502e5c683894995602478c448b/mad/parsing.py#L162-L172
[ "def merge_map(map_A, map_B):\n tmp = map_A.copy()\n tmp.update(map_B)\n return tmp\n" ]
#!/usr/bin/env python # # This file is part of MAD. # # MAD is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # MAD is distributed in ...
fchauvel/MAD
mad/parsing.py
p_queue
python
def p_queue(p): if p[3] == "LIFO": p[0] = {"queue": LIFO()} elif p[3] == "FIFO": p[0] = {"queue": FIFO()} else: raise RuntimeError("Queue discipline '%s' is not supported!" % p[1])
queue : QUEUE COLON LIFO | QUEUE COLON FIFO
train
https://github.com/fchauvel/MAD/blob/806d5174848b1a502e5c683894995602478c448b/mad/parsing.py#L184-L196
null
#!/usr/bin/env python # # This file is part of MAD. # # MAD is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # MAD is distributed in ...
fchauvel/MAD
mad/parsing.py
p_throttling
python
def p_throttling(p): throttling = NoThrottlingSettings() if len(p) == 7: throttling = TailDropSettings(int(p[5])) p[0] = {"throttling": throttling}
throttling : THROTTLING COLON NONE | THROTTLING COLON TAIL_DROP OPEN_BRACKET NUMBER CLOSE_BRACKET
train
https://github.com/fchauvel/MAD/blob/806d5174848b1a502e5c683894995602478c448b/mad/parsing.py#L199-L207
null
#!/usr/bin/env python # # This file is part of MAD. # # MAD is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # MAD is distributed in ...
fchauvel/MAD
mad/parsing.py
p_autoscaling_setting_list
python
def p_autoscaling_setting_list(p): if len(p) == 3: p[0] = merge_map(p[1], p[2]) elif len(p) == 2: p[0] = p[1] else: raise RuntimeError("Invalid production in 'autoscaling_setting_list'")
autoscaling_setting_list : autoscaling_setting autoscaling_setting_list | autoscaling_setting
train
https://github.com/fchauvel/MAD/blob/806d5174848b1a502e5c683894995602478c448b/mad/parsing.py#L217-L227
[ "def merge_map(map_A, map_B):\n tmp = map_A.copy()\n tmp.update(map_B)\n return tmp\n" ]
#!/usr/bin/env python # # This file is part of MAD. # # MAD is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # MAD is distributed in ...
fchauvel/MAD
mad/parsing.py
p_autoscaling_setting
python
def p_autoscaling_setting(p): if len(p) == 8: p[0] = {"limits": (int(p[4]), int(p[6]))} elif len(p) == 4: p[0] = {"period": int(p[3])} else: raise RuntimeError("Invalid product in 'autoscaling_setting'")
autoscaling_setting : PERIOD COLON NUMBER | LIMITS COLON OPEN_SQUARE_BRACKET NUMBER COMMA NUMBER CLOSE_SQUARE_BRACKET
train
https://github.com/fchauvel/MAD/blob/806d5174848b1a502e5c683894995602478c448b/mad/parsing.py#L230-L240
null
#!/usr/bin/env python # # This file is part of MAD. # # MAD is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # MAD is distributed in ...
fchauvel/MAD
mad/parsing.py
p_operation_list
python
def p_operation_list(p): if len(p) == 3: p[0] = p[1] + p[2] elif len(p) == 2: p[0] = p[1] else: raise RuntimeError("Invalid production rules 'p_operation_list'")
operation_list : define_operation operation_list | define_operation
train
https://github.com/fchauvel/MAD/blob/806d5174848b1a502e5c683894995602478c448b/mad/parsing.py#L243-L253
null
#!/usr/bin/env python # # This file is part of MAD. # # MAD is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # MAD is distributed in ...
fchauvel/MAD
mad/parsing.py
p_action_list
python
def p_action_list(p): if len(p) == 3: p[0] = p[1] + p[2] elif len(p) == 2: p[0] = p[1] else: raise RuntimeError("Invalid production rules 'p_action_list'")
action_list : action action_list | action
train
https://github.com/fchauvel/MAD/blob/806d5174848b1a502e5c683894995602478c448b/mad/parsing.py#L270-L280
null
#!/usr/bin/env python # # This file is part of MAD. # # MAD is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # MAD is distributed in ...
fchauvel/MAD
mad/parsing.py
p_fail
python
def p_fail(p): if len(p) > 2: p[0] = Fail(float(p[2])) else: p[0] = Fail()
fail : FAIL NUMBER | FAIL
train
https://github.com/fchauvel/MAD/blob/806d5174848b1a502e5c683894995602478c448b/mad/parsing.py#L302-L310
null
#!/usr/bin/env python # # This file is part of MAD. # # MAD is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # MAD is distributed in ...
fchauvel/MAD
mad/parsing.py
p_query
python
def p_query(p): parameters = {"service": p[2], "operation": p[4]} if len(p) > 5: parameters = merge_map(parameters, p[6]) p[0] = Query(**parameters)
query : QUERY IDENTIFIER SLASH IDENTIFIER | QUERY IDENTIFIER SLASH IDENTIFIER OPEN_CURLY_BRACKET query_option_list CLOSE_CURLY_BRACKET
train
https://github.com/fchauvel/MAD/blob/806d5174848b1a502e5c683894995602478c448b/mad/parsing.py#L312-L320
[ "def merge_map(map_A, map_B):\n tmp = map_A.copy()\n tmp.update(map_B)\n return tmp\n" ]
#!/usr/bin/env python # # This file is part of MAD. # # MAD is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # MAD is distributed in ...
fchauvel/MAD
mad/parsing.py
p_query_option_list
python
def p_query_option_list(p): if len(p) == 2: p[0] = p[1] elif len(p) == 4: p[0] = merge_map(p[1], p[3]) else: raise RuntimeError("Invalid product rules for 'query_option_list'")
query_option_list : query_option COMMA query_option_list | query_option
train
https://github.com/fchauvel/MAD/blob/806d5174848b1a502e5c683894995602478c448b/mad/parsing.py#L323-L333
[ "def merge_map(map_A, map_B):\n tmp = map_A.copy()\n tmp.update(map_B)\n return tmp\n" ]
#!/usr/bin/env python # # This file is part of MAD. # # MAD is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # MAD is distributed in ...
fchauvel/MAD
mad/parsing.py
p_invoke
python
def p_invoke(p): priority = None if len(p) > 5: priority = int(p[8]) p[0] = Trigger(p[2], p[4], priority)
invoke : INVOKE IDENTIFIER SLASH IDENTIFIER | INVOKE IDENTIFIER SLASH IDENTIFIER OPEN_CURLY_BRACKET PRIORITY COLON NUMBER CLOSE_CURLY_BRACKET
train
https://github.com/fchauvel/MAD/blob/806d5174848b1a502e5c683894995602478c448b/mad/parsing.py#L358-L366
null
#!/usr/bin/env python # # This file is part of MAD. # # MAD is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # MAD is distributed in ...
fchauvel/MAD
mad/parsing.py
p_retry
python
def p_retry(p): if len(p) == 5: p[0] = Retry(p[3]) elif len(p) == 8: p[0] = Retry(p[6], **p[3]) else: raise RuntimeError("Invalid product rules for 'retry_option_list'")
retry : RETRY OPEN_CURLY_BRACKET action_list CLOSE_CURLY_BRACKET | RETRY OPEN_BRACKET retry_option_list CLOSE_BRACKET OPEN_CURLY_BRACKET action_list CLOSE_CURLY_BRACKET
train
https://github.com/fchauvel/MAD/blob/806d5174848b1a502e5c683894995602478c448b/mad/parsing.py#L369-L379
null
#!/usr/bin/env python # # This file is part of MAD. # # MAD is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # MAD is distributed in ...
fchauvel/MAD
mad/parsing.py
p_retry_option_list
python
def p_retry_option_list(p): if len(p) == 4: p[0] = merge_map(p[1], p[3]) elif len(p) == 2: p[0] = p[1] else: raise RuntimeError("Invalid production in 'retry_option_list'")
retry_option_list : retry_option COMMA retry_option_list | retry_option
train
https://github.com/fchauvel/MAD/blob/806d5174848b1a502e5c683894995602478c448b/mad/parsing.py#L382-L392
[ "def merge_map(map_A, map_B):\n tmp = map_A.copy()\n tmp.update(map_B)\n return tmp\n" ]
#!/usr/bin/env python # # This file is part of MAD. # # MAD is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # MAD is distributed in ...
fchauvel/MAD
mad/parsing.py
p_retry_option
python
def p_retry_option(p): if len(p) == 4: p[0] = {"limit": int(p[3]) } elif len(p) == 7: p[0] = {"delay": Delay(int(p[5]), p[3])} else: raise RuntimeError("Invalid production in 'retry_option'")
retry_option : LIMIT COLON NUMBER | DELAY COLON IDENTIFIER OPEN_BRACKET NUMBER CLOSE_BRACKET
train
https://github.com/fchauvel/MAD/blob/806d5174848b1a502e5c683894995602478c448b/mad/parsing.py#L395-L405
null
#!/usr/bin/env python # # This file is part of MAD. # # MAD is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # MAD is distributed in ...
DomBennett/TaxonNamesResolver
taxon_names_resolver/manip_tools.py
stringClade
python
def stringClade(taxrefs, name, at): '''Return a Newick string from a list of TaxRefs''' string = [] for ref in taxrefs: # distance is the difference between the taxonomic level of the ref # and the current level of the tree growth d = float(at-ref.level) # ensure no spaces i...
Return a Newick string from a list of TaxRefs
train
https://github.com/DomBennett/TaxonNamesResolver/blob/a2556cc0f8b7442d83990715c92fdf6f787e1f41/taxon_names_resolver/manip_tools.py#L192-L205
null
#! /usr/bin/env python # D.J. Bennett # 24/03/2014 """ misc tools """ from __future__ import absolute_import # PACKAGES import re from six.moves import range # GLOBALS # nodes on a taxonomic tree default_taxonomy = ['subspecies', 'species', 'subgenus', 'genus', 'tribe', 'subfamily', 'family', 'sup...
DomBennett/TaxonNamesResolver
taxon_names_resolver/manip_tools.py
taxTree
python
def taxTree(taxdict): # the taxonomic dictionary holds the lineage of each ident in # the same order as the taxonomy # use hierarchy to construct a taxonomic tree for rank in taxdict.taxonomy: current_level = float(taxdict.taxonomy.index(rank)) # get clades at this rank in hierarchy ...
Return taxonomic Newick tree
train
https://github.com/DomBennett/TaxonNamesResolver/blob/a2556cc0f8b7442d83990715c92fdf6f787e1f41/taxon_names_resolver/manip_tools.py#L208-L241
[ "def stringClade(taxrefs, name, at):\n '''Return a Newick string from a list of TaxRefs'''\n string = []\n for ref in taxrefs:\n # distance is the difference between the taxonomic level of the ref\n # and the current level of the tree growth\n d = float(at-ref.level)\n # ensure...
#! /usr/bin/env python # D.J. Bennett # 24/03/2014 """ misc tools """ from __future__ import absolute_import # PACKAGES import re from six.moves import range # GLOBALS # nodes on a taxonomic tree default_taxonomy = ['subspecies', 'species', 'subgenus', 'genus', 'tribe', 'subfamily', 'family', 'sup...
DomBennett/TaxonNamesResolver
taxon_names_resolver/manip_tools.py
TaxRef.change
python
def change(self, ident, rank=None): '''Change ident''' self.ident = ident if rank: self.rank = rank self.level = self._getLevel(rank, self.taxonomy) # count changes made to instance self.counter += 1
Change ident
train
https://github.com/DomBennett/TaxonNamesResolver/blob/a2556cc0f8b7442d83990715c92fdf6f787e1f41/taxon_names_resolver/manip_tools.py#L35-L42
[ "def _getLevel(self, rank, taxonomy):\n if rank in taxonomy:\n return taxonomy.index(rank)\n # else find its closest by using the default taxonomy\n dlevel = default_taxonomy.index(rank)\n i = 1\n d = dlevel + i\n up = True\n while i <= len(default_taxonomy):\n if d > 0:\n ...
class TaxRef(object): '''Reference for taxonimic identities''' def __init__(self, ident, rank, taxonomy=default_taxonomy): super(TaxRef, self).__setattr__('taxonomy', taxonomy) super(TaxRef, self).__setattr__('ident', ident) super(TaxRef, self).__setattr__('rank', rank) # level i...
DomBennett/TaxonNamesResolver
taxon_names_resolver/manip_tools.py
TaxDict._additional
python
def _additional(self, idents, kwargs): '''Add additional data slots from **kwargs''' if kwargs: for name, value in list(kwargs.items()): if not isinstance(value, list): raise ValueError('Additional arguments must be lists of \ same length as idents') ...
Add additional data slots from **kwargs
train
https://github.com/DomBennett/TaxonNamesResolver/blob/a2556cc0f8b7442d83990715c92fdf6f787e1f41/taxon_names_resolver/manip_tools.py#L122-L130
null
class TaxDict(dict): '''Taxonomic Dictionary : hold and return taxonomic information''' def __init__(self, idents, ranks, lineages, taxonomy=default_taxonomy, **kwargs): # add entry for each ident of lineages ordered by taxonomy # ranks without corresponding lineage are given '...
DomBennett/TaxonNamesResolver
taxon_names_resolver/manip_tools.py
TaxDict._slice
python
def _slice(self, level): '''Return list of tuples of ident and lineage ident for given level (numbered rank)''' if level >= len(self.taxonomy): raise IndexError('Level greater than size of taxonomy') res = [] for ident in sorted(list(self.keys())): res.append((sel...
Return list of tuples of ident and lineage ident for given level (numbered rank)
train
https://github.com/DomBennett/TaxonNamesResolver/blob/a2556cc0f8b7442d83990715c92fdf6f787e1f41/taxon_names_resolver/manip_tools.py#L132-L140
null
class TaxDict(dict): '''Taxonomic Dictionary : hold and return taxonomic information''' def __init__(self, idents, ranks, lineages, taxonomy=default_taxonomy, **kwargs): # add entry for each ident of lineages ordered by taxonomy # ranks without corresponding lineage are given '...
DomBennett/TaxonNamesResolver
taxon_names_resolver/manip_tools.py
TaxDict._group
python
def _group(self, taxslice): '''Return list of lists of idents grouped by shared rank''' res = [] while taxslice: taxref, lident = taxslice.pop() if lident == '': res.append(([taxref], lident)) else: # identify idents in the same...
Return list of lists of idents grouped by shared rank
train
https://github.com/DomBennett/TaxonNamesResolver/blob/a2556cc0f8b7442d83990715c92fdf6f787e1f41/taxon_names_resolver/manip_tools.py#L142-L160
null
class TaxDict(dict): '''Taxonomic Dictionary : hold and return taxonomic information''' def __init__(self, idents, ranks, lineages, taxonomy=default_taxonomy, **kwargs): # add entry for each ident of lineages ordered by taxonomy # ranks without corresponding lineage are given '...
DomBennett/TaxonNamesResolver
taxon_names_resolver/manip_tools.py
TaxDict._hierarchy
python
def _hierarchy(self): '''Generate dictionary of referenced idents grouped by shared rank''' self.hierarchy = {} for rank in self.taxonomy: # extract lineage idents for this rank taxslice = self._slice(level=self.taxonomy.index(rank)) # group idents by shared g...
Generate dictionary of referenced idents grouped by shared rank
train
https://github.com/DomBennett/TaxonNamesResolver/blob/a2556cc0f8b7442d83990715c92fdf6f787e1f41/taxon_names_resolver/manip_tools.py#L162-L169
[ " def _slice(self, level):\n '''Return list of tuples of ident and lineage ident for given level\n(numbered rank)'''\n if level >= len(self.taxonomy):\n raise IndexError('Level greater than size of taxonomy')\n res = []\n for ident in sorted(list(self.keys())):\n ...
class TaxDict(dict): '''Taxonomic Dictionary : hold and return taxonomic information''' def __init__(self, idents, ranks, lineages, taxonomy=default_taxonomy, **kwargs): # add entry for each ident of lineages ordered by taxonomy # ranks without corresponding lineage are given '...
DomBennett/TaxonNamesResolver
taxon_names_resolver/manip_tools.py
TaxDict._contextualise
python
def _contextualise(self): '''Determine contextual idents (cidents)''' # loop through hierarchy identifying unique lineages # TODO: gain other contextual information, not just ident deja_vues = [] for rank in reversed(self.taxonomy): # return named clades -- '' are ign...
Determine contextual idents (cidents)
train
https://github.com/DomBennett/TaxonNamesResolver/blob/a2556cc0f8b7442d83990715c92fdf6f787e1f41/taxon_names_resolver/manip_tools.py#L171-L188
null
class TaxDict(dict): '''Taxonomic Dictionary : hold and return taxonomic information''' def __init__(self, idents, ranks, lineages, taxonomy=default_taxonomy, **kwargs): # add entry for each ident of lineages ordered by taxonomy # ranks without corresponding lineage are given '...
DomBennett/TaxonNamesResolver
taxon_names_resolver/gnr_tools.py
safeReadJSON
python
def safeReadJSON(url, logger, max_check=6, waittime=30): '''Return JSON object from URL''' counter = 0 # try, try and try again .... while counter < max_check: try: with contextlib.closing(urllib.request.urlopen(url)) as f: res = json.loads(f.read().decode('utf8')) ...
Return JSON object from URL
train
https://github.com/DomBennett/TaxonNamesResolver/blob/a2556cc0f8b7442d83990715c92fdf6f787e1f41/taxon_names_resolver/gnr_tools.py#L18-L32
null
#! /usr/bin/env python # D. J. Bennett # 16/05/2014 """ Tools for interacting with the GNR. """ from __future__ import absolute_import import time import contextlib import json import os import six from six.moves import urllib # FUNCTIONS # CLASSES class GnrDataSources(object): """GNR data sources class: extr...
DomBennett/TaxonNamesResolver
taxon_names_resolver/gnr_tools.py
GnrResolver.search
python
def search(self, terms, prelim=True): # TODO: There are now lots of additional data sources, make additional # searching optional (11/01/2017) if prelim: # preliminary search res = self._resolve(terms, self.Id) self._write(res) return res else: # sea...
Search terms against GNR. If prelim = False, search other datasources \ for alternative names (i.e. synonyms) with which to search main datasource.\ Return JSON object.
train
https://github.com/DomBennett/TaxonNamesResolver/blob/a2556cc0f8b7442d83990715c92fdf6f787e1f41/taxon_names_resolver/gnr_tools.py#L67-L97
[ "def _parseNames(self, jobj):\n # return a list of tuples (term, name) from second search\n # TODO(07/06/2013): record DSs used\n alt_terms = []\n for record in jobj:\n if 'results' not in list(record.keys()):\n pass\n else:\n term = record['supplied_name_string']\n ...
class GnrResolver(object): """GNR resolver class: search the GNR""" def __init__(self, logger, datasource='NCBI'): self.logger = logger ds = GnrDataSources(logger) self.write_counter = 1 self.Id = ds.byName(datasource) self.otherIds = ds.byName(datasource, invert=True) ...
DomBennett/TaxonNamesResolver
TaxonNamesResolver.py
parseArgs
python
def parseArgs(): parser = argparse.ArgumentParser() parser.add_argument("-names", "-n", help=".txt file of taxonomic names") parser.add_argument("-datasource", "-d", help="taxonomic datasource by \ which names will be resolved (default NCBI)") parser.add_argument("-taxonid", "-t", help="parent taxonomic...
Read arguments
train
https://github.com/DomBennett/TaxonNamesResolver/blob/a2556cc0f8b7442d83990715c92fdf6f787e1f41/TaxonNamesResolver.py#L30-L41
null
#! /usr/bin/env python # D.J. Bennett # 16/05/2014 # Import from __future__ import absolute_import from __future__ import print_function import os import sys import argparse import logging import platform from datetime import datetime from taxon_names_resolver import Resolver from taxon_names_resolver import __version...
DomBennett/TaxonNamesResolver
TaxonNamesResolver.py
logSysInfo
python
def logSysInfo(): logger.info('#' * 70) logger.info(datetime.today().strftime("%A, %d %B %Y %I:%M%p")) logger.info('Running on [{0}] [{1}]'.format(platform.node(), platform.platform())) logger.info('Python [{0}]'.format(sys.version)) logger.info('#' * ...
Write system info to log file
train
https://github.com/DomBennett/TaxonNamesResolver/blob/a2556cc0f8b7442d83990715c92fdf6f787e1f41/TaxonNamesResolver.py#L44-L51
null
#! /usr/bin/env python # D.J. Bennett # 16/05/2014 # Import from __future__ import absolute_import from __future__ import print_function import os import sys import argparse import logging import platform from datetime import datetime from taxon_names_resolver import Resolver from taxon_names_resolver import __version...
DomBennett/TaxonNamesResolver
TaxonNamesResolver.py
logEndTime
python
def logEndTime(): logger.info('\n' + '#' * 70) logger.info('Complete') logger.info(datetime.today().strftime("%A, %d %B %Y %I:%M%p")) logger.info('#' * 70 + '\n')
Write end info to log
train
https://github.com/DomBennett/TaxonNamesResolver/blob/a2556cc0f8b7442d83990715c92fdf6f787e1f41/TaxonNamesResolver.py#L54-L59
null
#! /usr/bin/env python # D.J. Bennett # 16/05/2014 # Import from __future__ import absolute_import from __future__ import print_function import os import sys import argparse import logging import platform from datetime import datetime from taxon_names_resolver import Resolver from taxon_names_resolver import __version...
DomBennett/TaxonNamesResolver
taxon_names_resolver/resolver.py
Resolver._check
python
def _check(self, terms): for t in terms: try: _ = urllib.parse.quote(six.text_type(t).encode('utf8')) except: self.logger.error('Unknown character in [{0}]!'.format(t)) self.logger.error('.... remove character and try again.') ...
Check terms do not contain unknown characters
train
https://github.com/DomBennett/TaxonNamesResolver/blob/a2556cc0f8b7442d83990715c92fdf6f787e1f41/taxon_names_resolver/resolver.py#L72-L80
null
class Resolver(object): """Taxon Names Resovler class : Automatically resolves taxon names \ through GNR. All output written in 'resolved_names' folder. See https://github.com/DomBennett/TaxonNamesResolver for details.""" def __init__(self, input_file=None, datasource='NCBI', taxon_id=None, te...
DomBennett/TaxonNamesResolver
taxon_names_resolver/resolver.py
Resolver.main
python
def main(self): # TODO: Break up, too complex primary_bool = True no_records = True nsearch = 1 search_terms = self.terms original_names = [] while True: if primary_bool: self.logger.info('Searching [{0}] ...'.format( ...
Search and sieve query names.
train
https://github.com/DomBennett/TaxonNamesResolver/blob/a2556cc0f8b7442d83990715c92fdf6f787e1f41/taxon_names_resolver/resolver.py#L82-L127
[ " def search(self, terms, prelim=True):\n \"\"\"Search terms against GNR. If prelim = False, search other datasources \\\nfor alternative names (i.e. synonyms) with which to search main datasource.\\\nReturn JSON object.\"\"\"\n # TODO: There are now lots of additional data sources, make additional...
class Resolver(object): """Taxon Names Resovler class : Automatically resolves taxon names \ through GNR. All output written in 'resolved_names' folder. See https://github.com/DomBennett/TaxonNamesResolver for details.""" def __init__(self, input_file=None, datasource='NCBI', taxon_id=None, te...
DomBennett/TaxonNamesResolver
taxon_names_resolver/resolver.py
Resolver._sieve
python
def _sieve(self, multiple_records): # TODO: Break up, too complex GnrStore = self._store def writeAsJson(term, results): record = {'supplied_name_string': term} if len(results) > 0: record['results'] = results return record def boolRe...
Return json object without multiple returns per resolved name.\ Names with multiple records are reduced by finding the name in the clade of\ interest, have the highest score, have the lowest taxonomic rank (if lowrank is true) and/or are the first item returned.
train
https://github.com/DomBennett/TaxonNamesResolver/blob/a2556cc0f8b7442d83990715c92fdf6f787e1f41/taxon_names_resolver/resolver.py#L159-L222
null
class Resolver(object): """Taxon Names Resovler class : Automatically resolves taxon names \ through GNR. All output written in 'resolved_names' folder. See https://github.com/DomBennett/TaxonNamesResolver for details.""" def __init__(self, input_file=None, datasource='NCBI', taxon_id=None, te...
DomBennett/TaxonNamesResolver
taxon_names_resolver/resolver.py
Resolver.write
python
def write(self): csv_file = os.path.join(self.outdir, 'search_results.csv') txt_file = os.path.join(self.outdir, 'unresolved.txt') headers = self.key_terms unresolved = [] with open(csv_file, 'w') as file: writer = csv.writer(file) writer.writerow(headers)...
Write csv file of resolved names and txt file of unresolved names.
train
https://github.com/DomBennett/TaxonNamesResolver/blob/a2556cc0f8b7442d83990715c92fdf6f787e1f41/taxon_names_resolver/resolver.py#L224-L258
null
class Resolver(object): """Taxon Names Resovler class : Automatically resolves taxon names \ through GNR. All output written in 'resolved_names' folder. See https://github.com/DomBennett/TaxonNamesResolver for details.""" def __init__(self, input_file=None, datasource='NCBI', taxon_id=None, te...
DomBennett/TaxonNamesResolver
taxon_names_resolver/resolver.py
Resolver.retrieve
python
def retrieve(self, key_term): """Return data for key term specified for each resolved name as a list. Possible terms (02/12/2013): 'query_name', 'classification_path', 'data_source_title', 'match_type', 'score', 'classification_path_ranks', 'name_string', 'canonical_form',\ 'classification_path_ids', 'prescore'...
Return data for key term specified for each resolved name as a list. Possible terms (02/12/2013): 'query_name', 'classification_path', 'data_source_title', 'match_type', 'score', 'classification_path_ranks', 'name_string', 'canonical_form',\ 'classification_path_ids', 'prescore', 'data_source_id', 'taxon_id', 'gni_uuid
train
https://github.com/DomBennett/TaxonNamesResolver/blob/a2556cc0f8b7442d83990715c92fdf6f787e1f41/taxon_names_resolver/resolver.py#L260-L283
null
class Resolver(object): """Taxon Names Resovler class : Automatically resolves taxon names \ through GNR. All output written in 'resolved_names' folder. See https://github.com/DomBennett/TaxonNamesResolver for details.""" def __init__(self, input_file=None, datasource='NCBI', taxon_id=None, te...
planetlabs/es_fluent
es_fluent/filters/core.py
Generic.add_filter
python
def add_filter(self, filter_or_string, *args, **kwargs): self.filters.append(build_filter(filter_or_string, *args, **kwargs)) return self
Appends a filter.
train
https://github.com/planetlabs/es_fluent/blob/74f8db3a1bf9aa1d54512cf2d5e0ec58ee2f4b1c/es_fluent/filters/core.py#L27-L33
[ "def build_filter(filter_or_string, *args, **kwargs):\n \"\"\"\n Overloaded filter construction. If ``filter_or_string`` is a string\n we look up it's corresponding class in the filter registry and return it.\n Otherwise, assume ``filter_or_string`` is an instance of a filter.\n\n :return: :class:`~e...
class Generic(Filter): """ Contains a generic list of filters. Serialized as a dictionary. """ def __init__(self): self.filters = [] def is_empty(self): """ :return: ``True`` if this filter has nested clauses ``False``. """ return all(_filter.is_empty() for _...
planetlabs/es_fluent
es_fluent/filters/core.py
Generic.and_filter
python
def and_filter(self, filter_or_string, *args, **kwargs): and_filter = self.find_filter(And) if and_filter is None: and_filter = And() self.filters.append(and_filter) and_filter.add_filter(build_filter( filter_or_string, *args, **kwargs)) return and_...
Adds a list of :class:`~es_fluent.filters.core.And` clauses, automatically generating :class:`~es_fluent.filters.core.And` filter if it does not exist.
train
https://github.com/planetlabs/es_fluent/blob/74f8db3a1bf9aa1d54512cf2d5e0ec58ee2f4b1c/es_fluent/filters/core.py#L35-L50
[ "def build_filter(filter_or_string, *args, **kwargs):\n \"\"\"\n Overloaded filter construction. If ``filter_or_string`` is a string\n we look up it's corresponding class in the filter registry and return it.\n Otherwise, assume ``filter_or_string`` is an instance of a filter.\n\n :return: :class:`~e...
class Generic(Filter): """ Contains a generic list of filters. Serialized as a dictionary. """ def __init__(self): self.filters = [] def is_empty(self): """ :return: ``True`` if this filter has nested clauses ``False``. """ return all(_filter.is_empty() for _...
planetlabs/es_fluent
es_fluent/filters/core.py
Generic.or_filter
python
def or_filter(self, filter_or_string, *args, **kwargs): or_filter = self.find_filter(Or) if or_filter is None: or_filter = Or() self.filters.append(or_filter) or_filter.add_filter(build_filter( filter_or_string, *args, **kwargs )) return or_...
Adds a list of :class:`~es_fluent.filters.core.Or` clauses, automatically generating the an :class:`~es_fluent.filters.core.Or` filter if it does not exist.
train
https://github.com/planetlabs/es_fluent/blob/74f8db3a1bf9aa1d54512cf2d5e0ec58ee2f4b1c/es_fluent/filters/core.py#L52-L68
[ "def build_filter(filter_or_string, *args, **kwargs):\n \"\"\"\n Overloaded filter construction. If ``filter_or_string`` is a string\n we look up it's corresponding class in the filter registry and return it.\n Otherwise, assume ``filter_or_string`` is an instance of a filter.\n\n :return: :class:`~e...
class Generic(Filter): """ Contains a generic list of filters. Serialized as a dictionary. """ def __init__(self): self.filters = [] def is_empty(self): """ :return: ``True`` if this filter has nested clauses ``False``. """ return all(_filter.is_empty() for _...
planetlabs/es_fluent
es_fluent/filters/core.py
Generic.find_filter
python
def find_filter(self, filter_cls): for filter_instance in self.filters: if isinstance(filter_instance, filter_cls): return filter_instance return None
Find or create a filter instance of the provided ``filter_cls``. If it is found, use remaining arguments to augment the filter otherwise create a new instance of the desired type and add it to the current :class:`~es_fluent.builder.QueryBuilder` accordingly.
train
https://github.com/planetlabs/es_fluent/blob/74f8db3a1bf9aa1d54512cf2d5e0ec58ee2f4b1c/es_fluent/filters/core.py#L70-L81
null
class Generic(Filter): """ Contains a generic list of filters. Serialized as a dictionary. """ def __init__(self): self.filters = [] def is_empty(self): """ :return: ``True`` if this filter has nested clauses ``False``. """ return all(_filter.is_empty() for _...
planetlabs/es_fluent
es_fluent/filters/core.py
Dict.to_query
python
def to_query(self): query = {} for filter_instance in self.filters: if filter_instance.is_empty(): continue filter_query = filter_instance.to_query() query.update(filter_query) return query
Iterates over all filters and converts them to an Elastic HTTP API suitable query. Note: each :class:`~es_fluent.filters.Filter` is free to set it's own filter dictionary. ESFluent does not attempt to guard against filters that may clobber one another. If you wish to ensure that filter...
train
https://github.com/planetlabs/es_fluent/blob/74f8db3a1bf9aa1d54512cf2d5e0ec58ee2f4b1c/es_fluent/filters/core.py#L93-L112
null
class Dict(Generic): """ Contains a generic dictionary of filters e.g. in a top level ES Query we may have:: { "filtered": {"filter": {"and": {...}, "or": {...}, "exists": {...} } The Dict filter may represent the dictionary inside of "filtered.filter". """ def is_empty(self): ...
planetlabs/es_fluent
es_fluent/filters/geometry.py
prepare_geojson
python
def prepare_geojson(geojson): # TODO CW orientation. geojson = deepcopy(geojson) if geojson["type"] == "Feature": geojson = geojson["geometry"] if hasattr(geojson, 'properties'): del geojson['properties'] if geojson["type"] == "FeatureCollection": geojson["type"] = ...
Modifies incoming GeoJSON to make it Elastic friendly. This means: 1. CW orientation of polygons. 2. Re-casting of Features and FeatureCollections to Geometry and GeometryCollections.
train
https://github.com/planetlabs/es_fluent/blob/74f8db3a1bf9aa1d54512cf2d5e0ec58ee2f4b1c/es_fluent/filters/geometry.py#L9-L32
null
""" Geometry related filters require additional dependencies. Hence they're broken out into their own module. """ from copy import deepcopy from .core import Terminal class GeoJSON(Terminal): """ Manages querying by GeoJSON. Automatically converts incoming GeoJSON to elasticsearch friendly geometry. Thi...
planetlabs/es_fluent
es_fluent/filters/geometry.py
IndexedShape.to_query
python
def to_query(self): return { "geo_shape": { self.name: { "indexed_shape": { "index": self.index_name, "type": self.doc_type, "id": self.shape_id, "path": self.path ...
Returns a json-serializable representation.
train
https://github.com/planetlabs/es_fluent/blob/74f8db3a1bf9aa1d54512cf2d5e0ec58ee2f4b1c/es_fluent/filters/geometry.py#L84-L99
null
class IndexedShape(Terminal): """ Searches by a previously indexed Geometry. """ name = "indexed_geometry" def __init__(self, name, shape_id, index_name, doc_type, path): """ :param string name: The field to match against the target shape. :param string shape_id: The id of t...
planetlabs/es_fluent
es_fluent/builder.py
QueryBuilder.and_filter
python
def and_filter(self, filter_or_string, *args, **kwargs): self.root_filter.and_filter(filter_or_string, *args, **kwargs) return self
Convenience method to delegate to the root_filter to generate an :class:`~es_fluent.filters.core.And` clause. :return: :class:`~es_fluent.builder.QueryBuilder`
train
https://github.com/planetlabs/es_fluent/blob/74f8db3a1bf9aa1d54512cf2d5e0ec58ee2f4b1c/es_fluent/builder.py#L37-L45
[ "def and_filter(self, filter_or_string, *args, **kwargs):\n \"\"\"\n Adds a list of :class:`~es_fluent.filters.core.And` clauses, automatically\n generating :class:`~es_fluent.filters.core.And` filter if it does not\n exist.\n \"\"\"\n and_filter = self.find_filter(And)\n\n if and_filter is Non...
class QueryBuilder(object): def __init__(self): self.root_filter = Dict() self.script_fields = ScriptFields() self.fields = Fields() self.sorts = [] self.source = True self._size = None @property def size(self): """ Sets current size limit of...
planetlabs/es_fluent
es_fluent/builder.py
QueryBuilder.or_filter
python
def or_filter(self, filter_or_string, *args, **kwargs): self.root_filter.or_filter(filter_or_string, *args, **kwargs) return self
Convenience method to delegate to the root_filter to generate an `or` clause. :return: :class:`~es_fluent.builder.QueryBuilder`
train
https://github.com/planetlabs/es_fluent/blob/74f8db3a1bf9aa1d54512cf2d5e0ec58ee2f4b1c/es_fluent/builder.py#L47-L55
[ "def or_filter(self, filter_or_string, *args, **kwargs):\n \"\"\"\n Adds a list of :class:`~es_fluent.filters.core.Or` clauses, automatically\n generating the an :class:`~es_fluent.filters.core.Or` filter if it does not\n exist.\n \"\"\"\n or_filter = self.find_filter(Or)\n\n if or_filter is No...
class QueryBuilder(object): def __init__(self): self.root_filter = Dict() self.script_fields = ScriptFields() self.fields = Fields() self.sorts = [] self.source = True self._size = None @property def size(self): """ Sets current size limit of...
planetlabs/es_fluent
es_fluent/builder.py
QueryBuilder.add_filter
python
def add_filter(self, filter_or_string, *args, **kwargs): self.root_filter.add_filter(filter_or_string, *args, **kwargs) return self
Adds a filter to the query builder's filters. :return: :class:`~es_fluent.builder.QueryBuilder`
train
https://github.com/planetlabs/es_fluent/blob/74f8db3a1bf9aa1d54512cf2d5e0ec58ee2f4b1c/es_fluent/builder.py#L57-L64
[ "def add_filter(self, filter_or_string, *args, **kwargs):\n \"\"\"\n Appends a filter.\n \"\"\"\n self.filters.append(build_filter(filter_or_string, *args, **kwargs))\n\n return self\n" ]
class QueryBuilder(object): def __init__(self): self.root_filter = Dict() self.script_fields = ScriptFields() self.fields = Fields() self.sorts = [] self.source = True self._size = None @property def size(self): """ Sets current size limit of...