repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_code_tokens
listlengths
15
672k
func_documentation_string
stringlengths
1
47.2k
func_documentation_tokens
listlengths
1
3.92k
split_name
stringclasses
1 value
func_code_url
stringlengths
85
339
iblancasa/GitHubCity
src/githubcity/ghuser.py
GitHubUser.getRealContributions
def getRealContributions(self): """Get the real number of contributions (private + public).""" datefrom = datetime.now() - relativedelta(days=366) dateto = datefrom + relativedelta(months=1) - relativedelta(days=1) private = 0 while datefrom < datetime.now(): fromstr...
python
def getRealContributions(self): """Get the real number of contributions (private + public).""" datefrom = datetime.now() - relativedelta(days=366) dateto = datefrom + relativedelta(months=1) - relativedelta(days=1) private = 0 while datefrom < datetime.now(): fromstr...
[ "def", "getRealContributions", "(", "self", ")", ":", "datefrom", "=", "datetime", ".", "now", "(", ")", "-", "relativedelta", "(", "days", "=", "366", ")", "dateto", "=", "datefrom", "+", "relativedelta", "(", "months", "=", "1", ")", "-", "relativedelt...
Get the real number of contributions (private + public).
[ "Get", "the", "real", "number", "of", "contributions", "(", "private", "+", "public", ")", "." ]
train
https://github.com/iblancasa/GitHubCity/blob/c5299c6859dbefbd869e2ac6ff2faff2a39cf32f/src/githubcity/ghuser.py#L276-L325
iblancasa/GitHubCity
src/githubcity/ghuser.py
GitHubUser.__getDataFromURL
def __getDataFromURL(url): """Read HTML data from an user GitHub profile. :param url: URL of the webpage to download. :type url: str. :return: webpage donwloaded. :rtype: str. """ code = 0 while code != 200: req = Request(url) try...
python
def __getDataFromURL(url): """Read HTML data from an user GitHub profile. :param url: URL of the webpage to download. :type url: str. :return: webpage donwloaded. :rtype: str. """ code = 0 while code != 200: req = Request(url) try...
[ "def", "__getDataFromURL", "(", "url", ")", ":", "code", "=", "0", "while", "code", "!=", "200", ":", "req", "=", "Request", "(", "url", ")", "try", ":", "response", "=", "urlopen", "(", "req", ")", "code", "=", "response", ".", "code", "sleep", "(...
Read HTML data from an user GitHub profile. :param url: URL of the webpage to download. :type url: str. :return: webpage donwloaded. :rtype: str.
[ "Read", "HTML", "data", "from", "an", "user", "GitHub", "profile", "." ]
train
https://github.com/iblancasa/GitHubCity/blob/c5299c6859dbefbd869e2ac6ff2faff2a39cf32f/src/githubcity/ghuser.py#L328-L353
sveetch/boussole
boussole/conf/model.py
Settings.clean
def clean(self, settings): """ Filter given settings to keep only key names available in ``DEFAULT_SETTINGS``. Args: settings (dict): Loaded settings. Returns: dict: Settings object filtered. """ return {k: v for k, v in settings.items()...
python
def clean(self, settings): """ Filter given settings to keep only key names available in ``DEFAULT_SETTINGS``. Args: settings (dict): Loaded settings. Returns: dict: Settings object filtered. """ return {k: v for k, v in settings.items()...
[ "def", "clean", "(", "self", ",", "settings", ")", ":", "return", "{", "k", ":", "v", "for", "k", ",", "v", "in", "settings", ".", "items", "(", ")", "if", "k", "in", "DEFAULT_SETTINGS", "}" ]
Filter given settings to keep only key names available in ``DEFAULT_SETTINGS``. Args: settings (dict): Loaded settings. Returns: dict: Settings object filtered.
[ "Filter", "given", "settings", "to", "keep", "only", "key", "names", "available", "in", "DEFAULT_SETTINGS", "." ]
train
https://github.com/sveetch/boussole/blob/22cc644e9d633f41ebfc167d427a71c1726cee21/boussole/conf/model.py#L52-L64
sveetch/boussole
boussole/conf/model.py
Settings.set_settings
def set_settings(self, settings): """ Set every given settings as object attributes. Args: settings (dict): Dictionnary of settings. """ for k, v in settings.items(): setattr(self, k, v)
python
def set_settings(self, settings): """ Set every given settings as object attributes. Args: settings (dict): Dictionnary of settings. """ for k, v in settings.items(): setattr(self, k, v)
[ "def", "set_settings", "(", "self", ",", "settings", ")", ":", "for", "k", ",", "v", "in", "settings", ".", "items", "(", ")", ":", "setattr", "(", "self", ",", "k", ",", "v", ")" ]
Set every given settings as object attributes. Args: settings (dict): Dictionnary of settings.
[ "Set", "every", "given", "settings", "as", "object", "attributes", "." ]
train
https://github.com/sveetch/boussole/blob/22cc644e9d633f41ebfc167d427a71c1726cee21/boussole/conf/model.py#L66-L75
sveetch/boussole
boussole/conf/model.py
Settings.update
def update(self, settings): """ Update object attributes from given settings Args: settings (dict): Dictionnary of elements to update settings. Returns: dict: Dictionnary of all current saved settings. """ settings = self.clean(settings) ...
python
def update(self, settings): """ Update object attributes from given settings Args: settings (dict): Dictionnary of elements to update settings. Returns: dict: Dictionnary of all current saved settings. """ settings = self.clean(settings) ...
[ "def", "update", "(", "self", ",", "settings", ")", ":", "settings", "=", "self", ".", "clean", "(", "settings", ")", "# Update internal dict", "self", ".", "_settings", ".", "update", "(", "settings", ")", "# Push every setting items as class object attributes", ...
Update object attributes from given settings Args: settings (dict): Dictionnary of elements to update settings. Returns: dict: Dictionnary of all current saved settings.
[ "Update", "object", "attributes", "from", "given", "settings" ]
train
https://github.com/sveetch/boussole/blob/22cc644e9d633f41ebfc167d427a71c1726cee21/boussole/conf/model.py#L77-L96
aiidateam/aiida-nwchem
aiida_nwchem/parsers/__init__.py
BasenwcParser.parse_with_retrieved
def parse_with_retrieved(self, retrieved): """ Receives in input a dictionary of retrieved nodes. Does all the logic here. """ from aiida.common.exceptions import InvalidOperation import os output_path = None error_path = None try: out...
python
def parse_with_retrieved(self, retrieved): """ Receives in input a dictionary of retrieved nodes. Does all the logic here. """ from aiida.common.exceptions import InvalidOperation import os output_path = None error_path = None try: out...
[ "def", "parse_with_retrieved", "(", "self", ",", "retrieved", ")", ":", "from", "aiida", ".", "common", ".", "exceptions", "import", "InvalidOperation", "import", "os", "output_path", "=", "None", "error_path", "=", "None", "try", ":", "output_path", ",", "err...
Receives in input a dictionary of retrieved nodes. Does all the logic here.
[ "Receives", "in", "input", "a", "dictionary", "of", "retrieved", "nodes", ".", "Does", "all", "the", "logic", "here", "." ]
train
https://github.com/aiidateam/aiida-nwchem/blob/21034e7f8ea8249948065c28030f4b572a6ecf05/aiida_nwchem/parsers/__init__.py#L15-L37
aiidateam/aiida-nwchem
aiida_nwchem/parsers/__init__.py
BasenwcParser._fetch_output_files
def _fetch_output_files(self, retrieved): """ Checks the output folder for standard output and standard error files, returns their absolute paths on success. :param retrieved: A dictionary of retrieved nodes, as obtained from the parser. """ from aiida.common.d...
python
def _fetch_output_files(self, retrieved): """ Checks the output folder for standard output and standard error files, returns their absolute paths on success. :param retrieved: A dictionary of retrieved nodes, as obtained from the parser. """ from aiida.common.d...
[ "def", "_fetch_output_files", "(", "self", ",", "retrieved", ")", ":", "from", "aiida", ".", "common", ".", "datastructures", "import", "calc_states", "from", "aiida", ".", "common", ".", "exceptions", "import", "InvalidOperation", "import", "os", "# check in orde...
Checks the output folder for standard output and standard error files, returns their absolute paths on success. :param retrieved: A dictionary of retrieved nodes, as obtained from the parser.
[ "Checks", "the", "output", "folder", "for", "standard", "output", "and", "standard", "error", "files", "returns", "their", "absolute", "paths", "on", "success", "." ]
train
https://github.com/aiidateam/aiida-nwchem/blob/21034e7f8ea8249948065c28030f4b572a6ecf05/aiida_nwchem/parsers/__init__.py#L39-L75
1flow/python-ftr
ftr/extractor.py
ContentExtractor.reset
def reset(self): """ (re)set all instance attributes to default. Every attribute is set to ``None``, except :attr:`author` and :attr:`failures` which are set to ``[]``. """ self.config = None self.html = None self.parsed_tree = None self.tidied = False ...
python
def reset(self): """ (re)set all instance attributes to default. Every attribute is set to ``None``, except :attr:`author` and :attr:`failures` which are set to ``[]``. """ self.config = None self.html = None self.parsed_tree = None self.tidied = False ...
[ "def", "reset", "(", "self", ")", ":", "self", ".", "config", "=", "None", "self", ".", "html", "=", "None", "self", ".", "parsed_tree", "=", "None", "self", ".", "tidied", "=", "False", "self", ".", "next_page_link", "=", "None", "self", ".", "title...
(re)set all instance attributes to default. Every attribute is set to ``None``, except :attr:`author` and :attr:`failures` which are set to ``[]``.
[ "(", "re", ")", "set", "all", "instance", "attributes", "to", "default", "." ]
train
https://github.com/1flow/python-ftr/blob/90a2108c5ee005f1bf66dbe8cce68f2b7051b839/ftr/extractor.py#L100-L120
1flow/python-ftr
ftr/extractor.py
ContentExtractor._process_replacements
def _process_replacements(self, html): """ Do raw string replacements on :param:`html`. """ if self.config.find_string: for find_pattern, replace_pattern in self.config.replace_patterns: html = html.replace(find_pattern, replace_pattern) LOGGER.info(u'Done repla...
python
def _process_replacements(self, html): """ Do raw string replacements on :param:`html`. """ if self.config.find_string: for find_pattern, replace_pattern in self.config.replace_patterns: html = html.replace(find_pattern, replace_pattern) LOGGER.info(u'Done repla...
[ "def", "_process_replacements", "(", "self", ",", "html", ")", ":", "if", "self", ".", "config", ".", "find_string", ":", "for", "find_pattern", ",", "replace_pattern", "in", "self", ".", "config", ".", "replace_patterns", ":", "html", "=", "html", ".", "r...
Do raw string replacements on :param:`html`.
[ "Do", "raw", "string", "replacements", "on", ":", "param", ":", "html", "." ]
train
https://github.com/1flow/python-ftr/blob/90a2108c5ee005f1bf66dbe8cce68f2b7051b839/ftr/extractor.py#L122-L132
1flow/python-ftr
ftr/extractor.py
ContentExtractor._tidy
def _tidy(self, html, smart_tidy): """ Tidy HTML if we have a tidy method. This fixes problems with some sites which would otherwise trouble DOMDocument's HTML parsing. Although sometimes it makes the problem worse, which is why we can override it in site config files. ...
python
def _tidy(self, html, smart_tidy): """ Tidy HTML if we have a tidy method. This fixes problems with some sites which would otherwise trouble DOMDocument's HTML parsing. Although sometimes it makes the problem worse, which is why we can override it in site config files. ...
[ "def", "_tidy", "(", "self", ",", "html", ",", "smart_tidy", ")", ":", "if", "self", ".", "config", ".", "tidy", "and", "tidylib", "and", "smart_tidy", ":", "try", ":", "document", ",", "errors", "=", "tidylib", ".", "tidy_document", "(", "html", ",", ...
Tidy HTML if we have a tidy method. This fixes problems with some sites which would otherwise trouble DOMDocument's HTML parsing. Although sometimes it makes the problem worse, which is why we can override it in site config files.
[ "Tidy", "HTML", "if", "we", "have", "a", "tidy", "method", "." ]
train
https://github.com/1flow/python-ftr/blob/90a2108c5ee005f1bf66dbe8cce68f2b7051b839/ftr/extractor.py#L134-L165
1flow/python-ftr
ftr/extractor.py
ContentExtractor._parse_html
def _parse_html(self): """ Load the parser and parse `self.html`. """ if self.config.parser != 'lxml': raise NotImplementedError('%s parser not implemented' % self.config.parser) self.parser = etree.HTMLParser() try: self.p...
python
def _parse_html(self): """ Load the parser and parse `self.html`. """ if self.config.parser != 'lxml': raise NotImplementedError('%s parser not implemented' % self.config.parser) self.parser = etree.HTMLParser() try: self.p...
[ "def", "_parse_html", "(", "self", ")", ":", "if", "self", ".", "config", ".", "parser", "!=", "'lxml'", ":", "raise", "NotImplementedError", "(", "'%s parser not implemented'", "%", "self", ".", "config", ".", "parser", ")", "self", ".", "parser", "=", "e...
Load the parser and parse `self.html`.
[ "Load", "the", "parser", "and", "parse", "self", ".", "html", "." ]
train
https://github.com/1flow/python-ftr/blob/90a2108c5ee005f1bf66dbe8cce68f2b7051b839/ftr/extractor.py#L167-L191
1flow/python-ftr
ftr/extractor.py
ContentExtractor._extract_next_page_link
def _extract_next_page_link(self): """ Try to get next page link. """ # HEADS UP: we do not abort if next_page_link is already set: # we try to find next (eg. find 3 if already at page 2). for pattern in self.config.next_page_link: items = self.parsed_tree.xpath(p...
python
def _extract_next_page_link(self): """ Try to get next page link. """ # HEADS UP: we do not abort if next_page_link is already set: # we try to find next (eg. find 3 if already at page 2). for pattern in self.config.next_page_link: items = self.parsed_tree.xpath(p...
[ "def", "_extract_next_page_link", "(", "self", ")", ":", "# HEADS UP: we do not abort if next_page_link is already set:", "# we try to find next (eg. find 3 if already at page 2).", "for", "pattern", "in", "self", ".", "config", ".", "next_page_link", ":", "items", "=",...
Try to get next page link.
[ "Try", "to", "get", "next", "page", "link", "." ]
train
https://github.com/1flow/python-ftr/blob/90a2108c5ee005f1bf66dbe8cce68f2b7051b839/ftr/extractor.py#L199-L229
1flow/python-ftr
ftr/extractor.py
ContentExtractor._extract_title
def _extract_title(self): """ Extract the title and remove it from the document. If title has already been extracted, this method will do nothing. If removal cannot happen or fails, the document is left untouched. """ if self.title: return for pattern in s...
python
def _extract_title(self): """ Extract the title and remove it from the document. If title has already been extracted, this method will do nothing. If removal cannot happen or fails, the document is left untouched. """ if self.title: return for pattern in s...
[ "def", "_extract_title", "(", "self", ")", ":", "if", "self", ".", "title", ":", "return", "for", "pattern", "in", "self", ".", "config", ".", "title", ":", "items", "=", "self", ".", "parsed_tree", ".", "xpath", "(", "pattern", ")", "if", "not", "it...
Extract the title and remove it from the document. If title has already been extracted, this method will do nothing. If removal cannot happen or fails, the document is left untouched.
[ "Extract", "the", "title", "and", "remove", "it", "from", "the", "document", "." ]
train
https://github.com/1flow/python-ftr/blob/90a2108c5ee005f1bf66dbe8cce68f2b7051b839/ftr/extractor.py#L231-L290
1flow/python-ftr
ftr/extractor.py
ContentExtractor._extract_author
def _extract_author(self): """ Extract author(s) if not already done. """ if bool(self.author): return for pattern in self.config.author: items = self.parsed_tree.xpath(pattern) if isinstance(items, basestring): # In case xpath returns only...
python
def _extract_author(self): """ Extract author(s) if not already done. """ if bool(self.author): return for pattern in self.config.author: items = self.parsed_tree.xpath(pattern) if isinstance(items, basestring): # In case xpath returns only...
[ "def", "_extract_author", "(", "self", ")", ":", "if", "bool", "(", "self", ".", "author", ")", ":", "return", "for", "pattern", "in", "self", ".", "config", ".", "author", ":", "items", "=", "self", ".", "parsed_tree", ".", "xpath", "(", "pattern", ...
Extract author(s) if not already done.
[ "Extract", "author", "(", "s", ")", "if", "not", "already", "done", "." ]
train
https://github.com/1flow/python-ftr/blob/90a2108c5ee005f1bf66dbe8cce68f2b7051b839/ftr/extractor.py#L292-L323
1flow/python-ftr
ftr/extractor.py
ContentExtractor._extract_language
def _extract_language(self): """ Extract language from the HTML ``<head>`` tags. """ if self.language: return found = False for pattern in self.config.language: for item in self.parsed_tree.xpath(pattern): stripped_language = item.strip() ...
python
def _extract_language(self): """ Extract language from the HTML ``<head>`` tags. """ if self.language: return found = False for pattern in self.config.language: for item in self.parsed_tree.xpath(pattern): stripped_language = item.strip() ...
[ "def", "_extract_language", "(", "self", ")", ":", "if", "self", ".", "language", ":", "return", "found", "=", "False", "for", "pattern", "in", "self", ".", "config", ".", "language", ":", "for", "item", "in", "self", ".", "parsed_tree", ".", "xpath", ...
Extract language from the HTML ``<head>`` tags.
[ "Extract", "language", "from", "the", "HTML", "<head", ">", "tags", "." ]
train
https://github.com/1flow/python-ftr/blob/90a2108c5ee005f1bf66dbe8cce68f2b7051b839/ftr/extractor.py#L325-L345
1flow/python-ftr
ftr/extractor.py
ContentExtractor._extract_date
def _extract_date(self): """ Extract date from HTML. """ if self.date: return found = False for pattern in self.config.date: items = self.parsed_tree.xpath(pattern) if isinstance(items, basestring): # In case xpath returns only one...
python
def _extract_date(self): """ Extract date from HTML. """ if self.date: return found = False for pattern in self.config.date: items = self.parsed_tree.xpath(pattern) if isinstance(items, basestring): # In case xpath returns only one...
[ "def", "_extract_date", "(", "self", ")", ":", "if", "self", ".", "date", ":", "return", "found", "=", "False", "for", "pattern", "in", "self", ".", "config", ".", "date", ":", "items", "=", "self", ".", "parsed_tree", ".", "xpath", "(", "pattern", "...
Extract date from HTML.
[ "Extract", "date", "from", "HTML", "." ]
train
https://github.com/1flow/python-ftr/blob/90a2108c5ee005f1bf66dbe8cce68f2b7051b839/ftr/extractor.py#L347-L388
1flow/python-ftr
ftr/extractor.py
ContentExtractor._extract_body
def _extract_body(self): """ Extract the body content from HTML. """ def is_descendant_node(parent, node): node = node.getparent() while node is not None: if node == parent: return True node = node.getparent() retur...
python
def _extract_body(self): """ Extract the body content from HTML. """ def is_descendant_node(parent, node): node = node.getparent() while node is not None: if node == parent: return True node = node.getparent() retur...
[ "def", "_extract_body", "(", "self", ")", ":", "def", "is_descendant_node", "(", "parent", ",", "node", ")", ":", "node", "=", "node", ".", "getparent", "(", ")", "while", "node", "is", "not", "None", ":", "if", "node", "==", "parent", ":", "return", ...
Extract the body content from HTML.
[ "Extract", "the", "body", "content", "from", "HTML", "." ]
train
https://github.com/1flow/python-ftr/blob/90a2108c5ee005f1bf66dbe8cce68f2b7051b839/ftr/extractor.py#L432-L524
1flow/python-ftr
ftr/extractor.py
ContentExtractor._auto_extract_if_failed
def _auto_extract_if_failed(self): """ Try to automatically extract as much as possible. """ if not self.config.autodetect_on_failure: return readabilitized = Document(self.html) if self.title is None: if bool(self.config.title): self.failures.a...
python
def _auto_extract_if_failed(self): """ Try to automatically extract as much as possible. """ if not self.config.autodetect_on_failure: return readabilitized = Document(self.html) if self.title is None: if bool(self.config.title): self.failures.a...
[ "def", "_auto_extract_if_failed", "(", "self", ")", ":", "if", "not", "self", ".", "config", ".", "autodetect_on_failure", ":", "return", "readabilitized", "=", "Document", "(", "self", ".", "html", ")", "if", "self", ".", "title", "is", "None", ":", "if",...
Try to automatically extract as much as possible.
[ "Try", "to", "automatically", "extract", "as", "much", "as", "possible", "." ]
train
https://github.com/1flow/python-ftr/blob/90a2108c5ee005f1bf66dbe8cce68f2b7051b839/ftr/extractor.py#L526-L569
1flow/python-ftr
ftr/extractor.py
ContentExtractor.process
def process(self, html, url=None, smart_tidy=True): u""" Process HTML content or URL. For automatic extraction patterns and cleanups, :mod:`readability-lxml` is used, to stick as much as possible to the original PHP implementation and produce at least similar results with the same ...
python
def process(self, html, url=None, smart_tidy=True): u""" Process HTML content or URL. For automatic extraction patterns and cleanups, :mod:`readability-lxml` is used, to stick as much as possible to the original PHP implementation and produce at least similar results with the same ...
[ "def", "process", "(", "self", ",", "html", ",", "url", "=", "None", ",", "smart_tidy", "=", "True", ")", ":", "# TODO: re-implement URL handling with self.reset() here.", "if", "self", ".", "config", "is", "None", ":", "raise", "RuntimeError", "(", "u'extractor...
u""" Process HTML content or URL. For automatic extraction patterns and cleanups, :mod:`readability-lxml` is used, to stick as much as possible to the original PHP implementation and produce at least similar results with the same site config on the same article/content. :param ...
[ "u", "Process", "HTML", "content", "or", "URL", "." ]
train
https://github.com/1flow/python-ftr/blob/90a2108c5ee005f1bf66dbe8cce68f2b7051b839/ftr/extractor.py#L572-L662
bradmontgomery/django-staticflatpages
staticflatpages/views.py
staticflatpage
def staticflatpage(request, path): """Load/render a template corresponding to the path (a URL)""" # Don't render a base.html template. if path.replace("/", '').lower() == "base": raise Http404 if not path.startswith('/'): path = "/{0}".format(path) if path.endswith('/'): pat...
python
def staticflatpage(request, path): """Load/render a template corresponding to the path (a URL)""" # Don't render a base.html template. if path.replace("/", '').lower() == "base": raise Http404 if not path.startswith('/'): path = "/{0}".format(path) if path.endswith('/'): pat...
[ "def", "staticflatpage", "(", "request", ",", "path", ")", ":", "# Don't render a base.html template.", "if", "path", ".", "replace", "(", "\"/\"", ",", "''", ")", ".", "lower", "(", ")", "==", "\"base\"", ":", "raise", "Http404", "if", "not", "path", ".",...
Load/render a template corresponding to the path (a URL)
[ "Load", "/", "render", "a", "template", "corresponding", "to", "the", "path", "(", "a", "URL", ")" ]
train
https://github.com/bradmontgomery/django-staticflatpages/blob/76dbed40fa1af0434bf5d8012cb86b8139bb3256/staticflatpages/views.py#L6-L26
planetlabs/datalake-common
datalake_common/record.py
DatalakeRecord.list_from_url
def list_from_url(cls, url): '''return a list of DatalakeRecords for the specified url''' key = cls._get_key(url) metadata = cls._get_metadata_from_key(key) ct = cls._get_create_time(key) time_buckets = cls.get_time_buckets_from_metadata(metadata) return [cls(url, metadat...
python
def list_from_url(cls, url): '''return a list of DatalakeRecords for the specified url''' key = cls._get_key(url) metadata = cls._get_metadata_from_key(key) ct = cls._get_create_time(key) time_buckets = cls.get_time_buckets_from_metadata(metadata) return [cls(url, metadat...
[ "def", "list_from_url", "(", "cls", ",", "url", ")", ":", "key", "=", "cls", ".", "_get_key", "(", "url", ")", "metadata", "=", "cls", ".", "_get_metadata_from_key", "(", "key", ")", "ct", "=", "cls", ".", "_get_create_time", "(", "key", ")", "time_buc...
return a list of DatalakeRecords for the specified url
[ "return", "a", "list", "of", "DatalakeRecords", "for", "the", "specified", "url" ]
train
https://github.com/planetlabs/datalake-common/blob/f0864732ac8cf26df4bea62600aee13b19321a93/datalake_common/record.py#L65-L71
planetlabs/datalake-common
datalake_common/record.py
DatalakeRecord.list_from_metadata
def list_from_metadata(cls, url, metadata): '''return a list of DatalakeRecords for the url and metadata''' key = cls._get_key(url) metadata = Metadata(**metadata) ct = cls._get_create_time(key) time_buckets = cls.get_time_buckets_from_metadata(metadata) return [cls(url, ...
python
def list_from_metadata(cls, url, metadata): '''return a list of DatalakeRecords for the url and metadata''' key = cls._get_key(url) metadata = Metadata(**metadata) ct = cls._get_create_time(key) time_buckets = cls.get_time_buckets_from_metadata(metadata) return [cls(url, ...
[ "def", "list_from_metadata", "(", "cls", ",", "url", ",", "metadata", ")", ":", "key", "=", "cls", ".", "_get_key", "(", "url", ")", "metadata", "=", "Metadata", "(", "*", "*", "metadata", ")", "ct", "=", "cls", ".", "_get_create_time", "(", "key", "...
return a list of DatalakeRecords for the url and metadata
[ "return", "a", "list", "of", "DatalakeRecords", "for", "the", "url", "and", "metadata" ]
train
https://github.com/planetlabs/datalake-common/blob/f0864732ac8cf26df4bea62600aee13b19321a93/datalake_common/record.py#L75-L81
planetlabs/datalake-common
datalake_common/record.py
DatalakeRecord.get_time_buckets_from_metadata
def get_time_buckets_from_metadata(metadata): '''return a list of time buckets in which the metadata falls''' start = metadata['start'] end = metadata.get('end') or start buckets = DatalakeRecord.get_time_buckets(start, end) if len(buckets) > DatalakeRecord.MAXIMUM_BUCKET_SPAN: ...
python
def get_time_buckets_from_metadata(metadata): '''return a list of time buckets in which the metadata falls''' start = metadata['start'] end = metadata.get('end') or start buckets = DatalakeRecord.get_time_buckets(start, end) if len(buckets) > DatalakeRecord.MAXIMUM_BUCKET_SPAN: ...
[ "def", "get_time_buckets_from_metadata", "(", "metadata", ")", ":", "start", "=", "metadata", "[", "'start'", "]", "end", "=", "metadata", ".", "get", "(", "'end'", ")", "or", "start", "buckets", "=", "DatalakeRecord", ".", "get_time_buckets", "(", "start", ...
return a list of time buckets in which the metadata falls
[ "return", "a", "list", "of", "time", "buckets", "in", "which", "the", "metadata", "falls" ]
train
https://github.com/planetlabs/datalake-common/blob/f0864732ac8cf26df4bea62600aee13b19321a93/datalake_common/record.py#L165-L175
planetlabs/datalake-common
datalake_common/record.py
DatalakeRecord.get_time_buckets
def get_time_buckets(start, end): '''get the time buckets spanned by the start and end times''' d = DatalakeRecord.TIME_BUCKET_SIZE_IN_MS first_bucket = start / d last_bucket = end / d return list(range( int(first_bucket), int(last_bucket) + 1))
python
def get_time_buckets(start, end): '''get the time buckets spanned by the start and end times''' d = DatalakeRecord.TIME_BUCKET_SIZE_IN_MS first_bucket = start / d last_bucket = end / d return list(range( int(first_bucket), int(last_bucket) + 1))
[ "def", "get_time_buckets", "(", "start", ",", "end", ")", ":", "d", "=", "DatalakeRecord", ".", "TIME_BUCKET_SIZE_IN_MS", "first_bucket", "=", "start", "/", "d", "last_bucket", "=", "end", "/", "d", "return", "list", "(", "range", "(", "int", "(", "first_b...
get the time buckets spanned by the start and end times
[ "get", "the", "time", "buckets", "spanned", "by", "the", "start", "and", "end", "times" ]
train
https://github.com/planetlabs/datalake-common/blob/f0864732ac8cf26df4bea62600aee13b19321a93/datalake_common/record.py#L178-L185
isambard-uob/ampal
src/ampal/base_ampal.py
write_pdb
def write_pdb(residues, chain_id=' ', alt_states=False, strip_states=False): """Writes a pdb file for a list of residues. Parameters ---------- residues : list List of Residue objects. chain_id : str String of the chain id, defaults to ' '. alt_states : bool, optional If...
python
def write_pdb(residues, chain_id=' ', alt_states=False, strip_states=False): """Writes a pdb file for a list of residues. Parameters ---------- residues : list List of Residue objects. chain_id : str String of the chain id, defaults to ' '. alt_states : bool, optional If...
[ "def", "write_pdb", "(", "residues", ",", "chain_id", "=", "' '", ",", "alt_states", "=", "False", ",", "strip_states", "=", "False", ")", ":", "pdb_atom_col_dict", "=", "PDB_ATOM_COLUMNS", "out_pdb", "=", "[", "]", "if", "len", "(", "str", "(", "chain_id"...
Writes a pdb file for a list of residues. Parameters ---------- residues : list List of Residue objects. chain_id : str String of the chain id, defaults to ' '. alt_states : bool, optional If true, include all occupancy states of residues, else outputs primary state only. ...
[ "Writes", "a", "pdb", "file", "for", "a", "list", "of", "residues", "." ]
train
https://github.com/isambard-uob/ampal/blob/906e2afacb435ffb129b381f262ff8e7bfb324c5/src/ampal/base_ampal.py#L61-L129
isambard-uob/ampal
src/ampal/base_ampal.py
BaseAmpal.centre_of_mass
def centre_of_mass(self): """Returns the centre of mass of AMPAL object. Notes ----- All atoms are included in calculation, call `centre_of_mass` manually if another selection is require. Returns ------- centre_of_mass : numpy.array 3D coordi...
python
def centre_of_mass(self): """Returns the centre of mass of AMPAL object. Notes ----- All atoms are included in calculation, call `centre_of_mass` manually if another selection is require. Returns ------- centre_of_mass : numpy.array 3D coordi...
[ "def", "centre_of_mass", "(", "self", ")", ":", "elts", "=", "set", "(", "[", "x", ".", "element", "for", "x", "in", "self", ".", "get_atoms", "(", ")", "]", ")", "masses_dict", "=", "{", "e", ":", "ELEMENT_DATA", "[", "e", "]", "[", "'atomic mass'...
Returns the centre of mass of AMPAL object. Notes ----- All atoms are included in calculation, call `centre_of_mass` manually if another selection is require. Returns ------- centre_of_mass : numpy.array 3D coordinate for the centre of mass.
[ "Returns", "the", "centre", "of", "mass", "of", "AMPAL", "object", "." ]
train
https://github.com/isambard-uob/ampal/blob/906e2afacb435ffb129b381f262ff8e7bfb324c5/src/ampal/base_ampal.py#L150-L167
isambard-uob/ampal
src/ampal/base_ampal.py
Monomer.get_atoms
def get_atoms(self, inc_alt_states=False): """Returns all atoms in the `Monomer`. Parameters ---------- inc_alt_states : bool, optional If `True`, will return `Atoms` for alternate states. """ if inc_alt_states: return itertools.chain(*[x[1].value...
python
def get_atoms(self, inc_alt_states=False): """Returns all atoms in the `Monomer`. Parameters ---------- inc_alt_states : bool, optional If `True`, will return `Atoms` for alternate states. """ if inc_alt_states: return itertools.chain(*[x[1].value...
[ "def", "get_atoms", "(", "self", ",", "inc_alt_states", "=", "False", ")", ":", "if", "inc_alt_states", ":", "return", "itertools", ".", "chain", "(", "*", "[", "x", "[", "1", "]", ".", "values", "(", ")", "for", "x", "in", "sorted", "(", "list", "...
Returns all atoms in the `Monomer`. Parameters ---------- inc_alt_states : bool, optional If `True`, will return `Atoms` for alternate states.
[ "Returns", "all", "atoms", "in", "the", "Monomer", "." ]
train
https://github.com/isambard-uob/ampal/blob/906e2afacb435ffb129b381f262ff8e7bfb324c5/src/ampal/base_ampal.py#L587-L597
isambard-uob/ampal
src/ampal/base_ampal.py
Monomer.make_pdb
def make_pdb(self): """Generates a PDB string for the `Monomer`.""" pdb_str = write_pdb( [self], ' ' if not self.parent else self.parent.id) return pdb_str
python
def make_pdb(self): """Generates a PDB string for the `Monomer`.""" pdb_str = write_pdb( [self], ' ' if not self.parent else self.parent.id) return pdb_str
[ "def", "make_pdb", "(", "self", ")", ":", "pdb_str", "=", "write_pdb", "(", "[", "self", "]", ",", "' '", "if", "not", "self", ".", "parent", "else", "self", ".", "parent", ".", "id", ")", "return", "pdb_str" ]
Generates a PDB string for the `Monomer`.
[ "Generates", "a", "PDB", "string", "for", "the", "Monomer", "." ]
train
https://github.com/isambard-uob/ampal/blob/906e2afacb435ffb129b381f262ff8e7bfb324c5/src/ampal/base_ampal.py#L599-L603
isambard-uob/ampal
src/ampal/base_ampal.py
Monomer.close_monomers
def close_monomers(self, group, cutoff=4.0): """Returns a list of Monomers from within a cut off distance of the Monomer Parameters ---------- group: BaseAmpal or Subclass Group to be search for Monomers that are close to this Monomer. cutoff: float Dista...
python
def close_monomers(self, group, cutoff=4.0): """Returns a list of Monomers from within a cut off distance of the Monomer Parameters ---------- group: BaseAmpal or Subclass Group to be search for Monomers that are close to this Monomer. cutoff: float Dista...
[ "def", "close_monomers", "(", "self", ",", "group", ",", "cutoff", "=", "4.0", ")", ":", "nearby_residues", "=", "[", "]", "for", "self_atom", "in", "self", ".", "atoms", ".", "values", "(", ")", ":", "nearby_atoms", "=", "group", ".", "is_within", "("...
Returns a list of Monomers from within a cut off distance of the Monomer Parameters ---------- group: BaseAmpal or Subclass Group to be search for Monomers that are close to this Monomer. cutoff: float Distance cut off. Returns ------- ne...
[ "Returns", "a", "list", "of", "Monomers", "from", "within", "a", "cut", "off", "distance", "of", "the", "Monomer" ]
train
https://github.com/isambard-uob/ampal/blob/906e2afacb435ffb129b381f262ff8e7bfb324c5/src/ampal/base_ampal.py#L605-L626
isambard-uob/ampal
src/ampal/base_ampal.py
Atom.unique_id
def unique_id(self): """Creates a unique ID for the `Atom` based on its parents. Returns ------- unique_id : (str, str, str) (polymer.id, residue.id, atom.id) """ chain = self.parent.parent.id residue = self.parent.id return chain, residue, se...
python
def unique_id(self): """Creates a unique ID for the `Atom` based on its parents. Returns ------- unique_id : (str, str, str) (polymer.id, residue.id, atom.id) """ chain = self.parent.parent.id residue = self.parent.id return chain, residue, se...
[ "def", "unique_id", "(", "self", ")", ":", "chain", "=", "self", ".", "parent", ".", "parent", ".", "id", "residue", "=", "self", ".", "parent", ".", "id", "return", "chain", ",", "residue", ",", "self", ".", "id" ]
Creates a unique ID for the `Atom` based on its parents. Returns ------- unique_id : (str, str, str) (polymer.id, residue.id, atom.id)
[ "Creates", "a", "unique", "ID", "for", "the", "Atom", "based", "on", "its", "parents", "." ]
train
https://github.com/isambard-uob/ampal/blob/906e2afacb435ffb129b381f262ff8e7bfb324c5/src/ampal/base_ampal.py#L746-L756
isambard-uob/ampal
src/ampal/base_ampal.py
Atom.translate
def translate(self, vector): """Translates `Atom`. Parameters ---------- vector : 3D Vector (tuple, list, numpy.array) Vector used for translation. inc_alt_states : bool, optional If true, will rotate atoms in all states i.e. includes alternat...
python
def translate(self, vector): """Translates `Atom`. Parameters ---------- vector : 3D Vector (tuple, list, numpy.array) Vector used for translation. inc_alt_states : bool, optional If true, will rotate atoms in all states i.e. includes alternat...
[ "def", "translate", "(", "self", ",", "vector", ")", ":", "vector", "=", "numpy", ".", "array", "(", "vector", ")", "self", ".", "_vector", "+=", "numpy", ".", "array", "(", "vector", ")", "return" ]
Translates `Atom`. Parameters ---------- vector : 3D Vector (tuple, list, numpy.array) Vector used for translation. inc_alt_states : bool, optional If true, will rotate atoms in all states i.e. includes alternate conformations for sidechains.
[ "Translates", "Atom", "." ]
train
https://github.com/isambard-uob/ampal/blob/906e2afacb435ffb129b381f262ff8e7bfb324c5/src/ampal/base_ampal.py#L776-L789
dmgass/baseline
baseline/__main__.py
main
def main(args=None): """Command line interface. :param list args: command line options (defaults to sys.argv) :returns: exit code :rtype: int """ parser = ArgumentParser( prog='baseline', description=DESCRIPTION) parser.add_argument( 'path', nargs='*', help...
python
def main(args=None): """Command line interface. :param list args: command line options (defaults to sys.argv) :returns: exit code :rtype: int """ parser = ArgumentParser( prog='baseline', description=DESCRIPTION) parser.add_argument( 'path', nargs='*', help...
[ "def", "main", "(", "args", "=", "None", ")", ":", "parser", "=", "ArgumentParser", "(", "prog", "=", "'baseline'", ",", "description", "=", "DESCRIPTION", ")", "parser", ".", "add_argument", "(", "'path'", ",", "nargs", "=", "'*'", ",", "help", "=", "...
Command line interface. :param list args: command line options (defaults to sys.argv) :returns: exit code :rtype: int
[ "Command", "line", "interface", "." ]
train
https://github.com/dmgass/baseline/blob/1f7988e8c9fafa83eb3a1ce73b1601d2afdbb2cd/baseline/__main__.py#L43-L120
theiviaxx/photoshopConnection
pyps/_pyps.py
Connection.recv
def recv(self): """Receives a message from PS and decrypts it and returns a Message""" LOGGER.debug('Receiving') try: message_length = struct.unpack('>i', self._socket.recv(4))[0] message_length -= Connection.COMM_LENGTH LOGGER.debug('Length: %i', message_leng...
python
def recv(self): """Receives a message from PS and decrypts it and returns a Message""" LOGGER.debug('Receiving') try: message_length = struct.unpack('>i', self._socket.recv(4))[0] message_length -= Connection.COMM_LENGTH LOGGER.debug('Length: %i', message_leng...
[ "def", "recv", "(", "self", ")", ":", "LOGGER", ".", "debug", "(", "'Receiving'", ")", "try", ":", "message_length", "=", "struct", ".", "unpack", "(", "'>i'", ",", "self", ".", "_socket", ".", "recv", "(", "4", ")", ")", "[", "0", "]", "message_le...
Receives a message from PS and decrypts it and returns a Message
[ "Receives", "a", "message", "from", "PS", "and", "decrypts", "it", "and", "returns", "a", "Message" ]
train
https://github.com/theiviaxx/photoshopConnection/blob/ab5e3715d3bdc69601bc6dd0f29348f59fa3d612/pyps/_pyps.py#L110-L141
theiviaxx/photoshopConnection
pyps/_pyps.py
Connection.send
def send(self, content): """Sends a JavaScript command to PS :param content: Script content :type content: str :yields: :class:`.Message` """ LOGGER.debug('Sending: %s', content) all_bytes = struct.pack('>i', Connection.PROTOCOL_VERSION) all_bytes += stru...
python
def send(self, content): """Sends a JavaScript command to PS :param content: Script content :type content: str :yields: :class:`.Message` """ LOGGER.debug('Sending: %s', content) all_bytes = struct.pack('>i', Connection.PROTOCOL_VERSION) all_bytes += stru...
[ "def", "send", "(", "self", ",", "content", ")", ":", "LOGGER", ".", "debug", "(", "'Sending: %s'", ",", "content", ")", "all_bytes", "=", "struct", ".", "pack", "(", "'>i'", ",", "Connection", ".", "PROTOCOL_VERSION", ")", "all_bytes", "+=", "struct", "...
Sends a JavaScript command to PS :param content: Script content :type content: str :yields: :class:`.Message`
[ "Sends", "a", "JavaScript", "command", "to", "PS" ]
train
https://github.com/theiviaxx/photoshopConnection/blob/ab5e3715d3bdc69601bc6dd0f29348f59fa3d612/pyps/_pyps.py#L143-L172
sveetch/boussole
boussole/cli/watch.py
watch_command
def watch_command(context, backend, config, poll): """ Watch for change on your Sass project sources then compile them to CSS. Watched events are: \b * Create: when a new source file is created; * Change: when a source is changed; * Delete: when a source is deleted; * Move: When a sour...
python
def watch_command(context, backend, config, poll): """ Watch for change on your Sass project sources then compile them to CSS. Watched events are: \b * Create: when a new source file is created; * Change: when a source is changed; * Delete: when a source is deleted; * Move: When a sour...
[ "def", "watch_command", "(", "context", ",", "backend", ",", "config", ",", "poll", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", "\"boussole\"", ")", "logger", ".", "info", "(", "\"Watching project\"", ")", "# Discover settings file", "try", ":",...
Watch for change on your Sass project sources then compile them to CSS. Watched events are: \b * Create: when a new source file is created; * Change: when a source is changed; * Delete: when a source is deleted; * Move: When a source file is moved in watched dirs. Also occurs with editor...
[ "Watch", "for", "change", "on", "your", "Sass", "project", "sources", "then", "compile", "them", "to", "CSS", "." ]
train
https://github.com/sveetch/boussole/blob/22cc644e9d633f41ebfc167d427a71c1726cee21/boussole/cli/watch.py#L32-L122
robertpeteuil/aws-shortcuts
awss/debg.py
init
def init(deb1, deb2=False): """Initialize DEBUG and DEBUGALL. Allows other modules to set DEBUG and DEBUGALL, so their call to dprint or dprintx generate output. Args: deb1 (bool): value of DEBUG to set deb2 (bool): optional - value of DEBUGALL to set, defaults to ...
python
def init(deb1, deb2=False): """Initialize DEBUG and DEBUGALL. Allows other modules to set DEBUG and DEBUGALL, so their call to dprint or dprintx generate output. Args: deb1 (bool): value of DEBUG to set deb2 (bool): optional - value of DEBUGALL to set, defaults to ...
[ "def", "init", "(", "deb1", ",", "deb2", "=", "False", ")", ":", "global", "DEBUG", "# pylint: disable=global-statement", "global", "DEBUGALL", "# pylint: disable=global-statement", "DEBUG", "=", "deb1", "DEBUGALL", "=", "deb2" ]
Initialize DEBUG and DEBUGALL. Allows other modules to set DEBUG and DEBUGALL, so their call to dprint or dprintx generate output. Args: deb1 (bool): value of DEBUG to set deb2 (bool): optional - value of DEBUGALL to set, defaults to False.
[ "Initialize", "DEBUG", "and", "DEBUGALL", "." ]
train
https://github.com/robertpeteuil/aws-shortcuts/blob/cf453ca996978a4d88015d1cf6125bce8ca4873b/awss/debg.py#L39-L54
robertpeteuil/aws-shortcuts
awss/debg.py
dprintx
def dprintx(passeditem, special=False): """Print Text if DEBUGALL set, optionally with PrettyPrint. Args: passeditem (str): item to print special (bool): determines if item prints with PrettyPrint or regular print. """ if DEBUGALL: if special: ...
python
def dprintx(passeditem, special=False): """Print Text if DEBUGALL set, optionally with PrettyPrint. Args: passeditem (str): item to print special (bool): determines if item prints with PrettyPrint or regular print. """ if DEBUGALL: if special: ...
[ "def", "dprintx", "(", "passeditem", ",", "special", "=", "False", ")", ":", "if", "DEBUGALL", ":", "if", "special", ":", "from", "pprint", "import", "pprint", "pprint", "(", "passeditem", ")", "else", ":", "print", "(", "\"%s%s%s\"", "%", "(", "C_TI", ...
Print Text if DEBUGALL set, optionally with PrettyPrint. Args: passeditem (str): item to print special (bool): determines if item prints with PrettyPrint or regular print.
[ "Print", "Text", "if", "DEBUGALL", "set", "optionally", "with", "PrettyPrint", "." ]
train
https://github.com/robertpeteuil/aws-shortcuts/blob/cf453ca996978a4d88015d1cf6125bce8ca4873b/awss/debg.py#L69-L83
svven/summary
summary/request.py
get
def get(url, **kwargs): """ Wrapper for `request.get` function to set params. """ headers = kwargs.get('headers', {}) headers['User-Agent'] = config.USER_AGENT # overwrite kwargs['headers'] = headers timeout = kwargs.get('timeout', config.TIMEOUT) kwargs['timeout'] = timeout kwargs...
python
def get(url, **kwargs): """ Wrapper for `request.get` function to set params. """ headers = kwargs.get('headers', {}) headers['User-Agent'] = config.USER_AGENT # overwrite kwargs['headers'] = headers timeout = kwargs.get('timeout', config.TIMEOUT) kwargs['timeout'] = timeout kwargs...
[ "def", "get", "(", "url", ",", "*", "*", "kwargs", ")", ":", "headers", "=", "kwargs", ".", "get", "(", "'headers'", ",", "{", "}", ")", "headers", "[", "'User-Agent'", "]", "=", "config", ".", "USER_AGENT", "# overwrite", "kwargs", "[", "'headers'", ...
Wrapper for `request.get` function to set params.
[ "Wrapper", "for", "request", ".", "get", "function", "to", "set", "params", "." ]
train
https://github.com/svven/summary/blob/3a6c43d2da08a7452f6b76d1813aa70ba36b8a54/summary/request.py#L11-L25
svven/summary
summary/request.py
phantomjs_get
def phantomjs_get(url): """ Perform the request via PhantomJS. """ from selenium import webdriver from selenium.webdriver.common.desired_capabilities import DesiredCapabilities dcap = dict(DesiredCapabilities.PHANTOMJS) dcap["phantomjs.page.settings.userAgent"] = config.USER_AGENT dcap[...
python
def phantomjs_get(url): """ Perform the request via PhantomJS. """ from selenium import webdriver from selenium.webdriver.common.desired_capabilities import DesiredCapabilities dcap = dict(DesiredCapabilities.PHANTOMJS) dcap["phantomjs.page.settings.userAgent"] = config.USER_AGENT dcap[...
[ "def", "phantomjs_get", "(", "url", ")", ":", "from", "selenium", "import", "webdriver", "from", "selenium", ".", "webdriver", ".", "common", ".", "desired_capabilities", "import", "DesiredCapabilities", "dcap", "=", "dict", "(", "DesiredCapabilities", ".", "PHANT...
Perform the request via PhantomJS.
[ "Perform", "the", "request", "via", "PhantomJS", "." ]
train
https://github.com/svven/summary/blob/3a6c43d2da08a7452f6b76d1813aa70ba36b8a54/summary/request.py#L27-L45
aiidateam/aiida-nwchem
aiida_nwchem/tools/dbexporters/tcod_plugins/nwcpymatgen.py
NwcpymatgenTcodtranslator.get_software_package_compilation_timestamp
def get_software_package_compilation_timestamp(cls,calc,**kwargs): """ Returns the timestamp of package/program compilation in ISO 8601 format. """ from dateutil.parser import parse try: date = calc.out.job_info.get_dict()['compiled'] return parse(...
python
def get_software_package_compilation_timestamp(cls,calc,**kwargs): """ Returns the timestamp of package/program compilation in ISO 8601 format. """ from dateutil.parser import parse try: date = calc.out.job_info.get_dict()['compiled'] return parse(...
[ "def", "get_software_package_compilation_timestamp", "(", "cls", ",", "calc", ",", "*", "*", "kwargs", ")", ":", "from", "dateutil", ".", "parser", "import", "parse", "try", ":", "date", "=", "calc", ".", "out", ".", "job_info", ".", "get_dict", "(", ")", ...
Returns the timestamp of package/program compilation in ISO 8601 format.
[ "Returns", "the", "timestamp", "of", "package", "/", "program", "compilation", "in", "ISO", "8601", "format", "." ]
train
https://github.com/aiidateam/aiida-nwchem/blob/21034e7f8ea8249948065c28030f4b572a6ecf05/aiida_nwchem/tools/dbexporters/tcod_plugins/nwcpymatgen.py#L33-L43
aiidateam/aiida-nwchem
aiida_nwchem/tools/dbexporters/tcod_plugins/nwcpymatgen.py
NwcpymatgenTcodtranslator.get_atom_type_symbol
def get_atom_type_symbol(cls,calc,**kwargs): """ Returns a list of atom types. Each atom site MUST occur only once in this list. List MUST be sorted. """ parameters = calc.out.output dictionary = parameters.get_dict() if 'basis_set' not in dictionary.keys(): ...
python
def get_atom_type_symbol(cls,calc,**kwargs): """ Returns a list of atom types. Each atom site MUST occur only once in this list. List MUST be sorted. """ parameters = calc.out.output dictionary = parameters.get_dict() if 'basis_set' not in dictionary.keys(): ...
[ "def", "get_atom_type_symbol", "(", "cls", ",", "calc", ",", "*", "*", "kwargs", ")", ":", "parameters", "=", "calc", ".", "out", ".", "output", "dictionary", "=", "parameters", ".", "get_dict", "(", ")", "if", "'basis_set'", "not", "in", "dictionary", "...
Returns a list of atom types. Each atom site MUST occur only once in this list. List MUST be sorted.
[ "Returns", "a", "list", "of", "atom", "types", ".", "Each", "atom", "site", "MUST", "occur", "only", "once", "in", "this", "list", ".", "List", "MUST", "be", "sorted", "." ]
train
https://github.com/aiidateam/aiida-nwchem/blob/21034e7f8ea8249948065c28030f4b572a6ecf05/aiida_nwchem/tools/dbexporters/tcod_plugins/nwcpymatgen.py#L46-L55
aiidateam/aiida-nwchem
aiida_nwchem/tools/dbexporters/tcod_plugins/nwcpymatgen.py
NwcpymatgenTcodtranslator.get_atom_type_basisset
def get_atom_type_basisset(cls,calc,**kwargs): """ Returns a list of basisset names for each atom type. The list order MUST be the same as of get_atom_type_symbol(). """ parameters = calc.out.output dictionary = parameters.get_dict() if 'basis_set' not in dictiona...
python
def get_atom_type_basisset(cls,calc,**kwargs): """ Returns a list of basisset names for each atom type. The list order MUST be the same as of get_atom_type_symbol(). """ parameters = calc.out.output dictionary = parameters.get_dict() if 'basis_set' not in dictiona...
[ "def", "get_atom_type_basisset", "(", "cls", ",", "calc", ",", "*", "*", "kwargs", ")", ":", "parameters", "=", "calc", ".", "out", ".", "output", "dictionary", "=", "parameters", ".", "get_dict", "(", ")", "if", "'basis_set'", "not", "in", "dictionary", ...
Returns a list of basisset names for each atom type. The list order MUST be the same as of get_atom_type_symbol().
[ "Returns", "a", "list", "of", "basisset", "names", "for", "each", "atom", "type", ".", "The", "list", "order", "MUST", "be", "the", "same", "as", "of", "get_atom_type_symbol", "()", "." ]
train
https://github.com/aiidateam/aiida-nwchem/blob/21034e7f8ea8249948065c28030f4b572a6ecf05/aiida_nwchem/tools/dbexporters/tcod_plugins/nwcpymatgen.py#L58-L68
jelmer/python-fastimport
fastimport/processors/filter_processor.py
FilterProcessor.blob_handler
def blob_handler(self, cmd): """Process a BlobCommand.""" # These never pass through directly. We buffer them and only # output them if referenced by an interesting command. self.blobs[cmd.id] = cmd self.keep = False
python
def blob_handler(self, cmd): """Process a BlobCommand.""" # These never pass through directly. We buffer them and only # output them if referenced by an interesting command. self.blobs[cmd.id] = cmd self.keep = False
[ "def", "blob_handler", "(", "self", ",", "cmd", ")", ":", "# These never pass through directly. We buffer them and only", "# output them if referenced by an interesting command.", "self", ".", "blobs", "[", "cmd", ".", "id", "]", "=", "cmd", "self", ".", "keep", "=", ...
Process a BlobCommand.
[ "Process", "a", "BlobCommand", "." ]
train
https://github.com/jelmer/python-fastimport/blob/5cef9e037b7d7b37f58f522ac9ea4e343e6a1dff/fastimport/processors/filter_processor.py#L82-L87
jelmer/python-fastimport
fastimport/processors/filter_processor.py
FilterProcessor.commit_handler
def commit_handler(self, cmd): """Process a CommitCommand.""" # These pass through if they meet the filtering conditions interesting_filecmds = self._filter_filecommands(cmd.iter_files) if interesting_filecmds or not self.squash_empty_commits: # If all we have is a single del...
python
def commit_handler(self, cmd): """Process a CommitCommand.""" # These pass through if they meet the filtering conditions interesting_filecmds = self._filter_filecommands(cmd.iter_files) if interesting_filecmds or not self.squash_empty_commits: # If all we have is a single del...
[ "def", "commit_handler", "(", "self", ",", "cmd", ")", ":", "# These pass through if they meet the filtering conditions", "interesting_filecmds", "=", "self", ".", "_filter_filecommands", "(", "cmd", ".", "iter_files", ")", "if", "interesting_filecmds", "or", "not", "se...
Process a CommitCommand.
[ "Process", "a", "CommitCommand", "." ]
train
https://github.com/jelmer/python-fastimport/blob/5cef9e037b7d7b37f58f522ac9ea4e343e6a1dff/fastimport/processors/filter_processor.py#L94-L129
jelmer/python-fastimport
fastimport/processors/filter_processor.py
FilterProcessor.reset_handler
def reset_handler(self, cmd): """Process a ResetCommand.""" if cmd.from_ is None: # We pass through resets that init a branch because we have to # assume the branch might be interesting. self.keep = True else: # Keep resets if they indirectly refer...
python
def reset_handler(self, cmd): """Process a ResetCommand.""" if cmd.from_ is None: # We pass through resets that init a branch because we have to # assume the branch might be interesting. self.keep = True else: # Keep resets if they indirectly refer...
[ "def", "reset_handler", "(", "self", ",", "cmd", ")", ":", "if", "cmd", ".", "from_", "is", "None", ":", "# We pass through resets that init a branch because we have to", "# assume the branch might be interesting.", "self", ".", "keep", "=", "True", "else", ":", "# Ke...
Process a ResetCommand.
[ "Process", "a", "ResetCommand", "." ]
train
https://github.com/jelmer/python-fastimport/blob/5cef9e037b7d7b37f58f522ac9ea4e343e6a1dff/fastimport/processors/filter_processor.py#L131-L140
jelmer/python-fastimport
fastimport/processors/filter_processor.py
FilterProcessor.tag_handler
def tag_handler(self, cmd): """Process a TagCommand.""" # Keep tags if they indirectly reference something we kept cmd.from_ = self._find_interesting_from(cmd.from_) self.keep = cmd.from_ is not None
python
def tag_handler(self, cmd): """Process a TagCommand.""" # Keep tags if they indirectly reference something we kept cmd.from_ = self._find_interesting_from(cmd.from_) self.keep = cmd.from_ is not None
[ "def", "tag_handler", "(", "self", ",", "cmd", ")", ":", "# Keep tags if they indirectly reference something we kept", "cmd", ".", "from_", "=", "self", ".", "_find_interesting_from", "(", "cmd", ".", "from_", ")", "self", ".", "keep", "=", "cmd", ".", "from_", ...
Process a TagCommand.
[ "Process", "a", "TagCommand", "." ]
train
https://github.com/jelmer/python-fastimport/blob/5cef9e037b7d7b37f58f522ac9ea4e343e6a1dff/fastimport/processors/filter_processor.py#L142-L146
jelmer/python-fastimport
fastimport/processors/filter_processor.py
FilterProcessor._print_command
def _print_command(self, cmd): """Wrapper to avoid adding unnecessary blank lines.""" text = helpers.repr_bytes(cmd) self.outf.write(text) if not text.endswith(b'\n'): self.outf.write(b'\n')
python
def _print_command(self, cmd): """Wrapper to avoid adding unnecessary blank lines.""" text = helpers.repr_bytes(cmd) self.outf.write(text) if not text.endswith(b'\n'): self.outf.write(b'\n')
[ "def", "_print_command", "(", "self", ",", "cmd", ")", ":", "text", "=", "helpers", ".", "repr_bytes", "(", "cmd", ")", "self", ".", "outf", ".", "write", "(", "text", ")", "if", "not", "text", ".", "endswith", "(", "b'\\n'", ")", ":", "self", ".",...
Wrapper to avoid adding unnecessary blank lines.
[ "Wrapper", "to", "avoid", "adding", "unnecessary", "blank", "lines", "." ]
train
https://github.com/jelmer/python-fastimport/blob/5cef9e037b7d7b37f58f522ac9ea4e343e6a1dff/fastimport/processors/filter_processor.py#L157-L162
jelmer/python-fastimport
fastimport/processors/filter_processor.py
FilterProcessor._filter_filecommands
def _filter_filecommands(self, filecmd_iter): """Return the filecommands filtered by includes & excludes. :return: a list of FileCommand objects """ if self.includes is None and self.excludes is None: return list(filecmd_iter()) # Do the filtering, adjusting for the...
python
def _filter_filecommands(self, filecmd_iter): """Return the filecommands filtered by includes & excludes. :return: a list of FileCommand objects """ if self.includes is None and self.excludes is None: return list(filecmd_iter()) # Do the filtering, adjusting for the...
[ "def", "_filter_filecommands", "(", "self", ",", "filecmd_iter", ")", ":", "if", "self", ".", "includes", "is", "None", "and", "self", ".", "excludes", "is", "None", ":", "return", "list", "(", "filecmd_iter", "(", ")", ")", "# Do the filtering, adjusting for ...
Return the filecommands filtered by includes & excludes. :return: a list of FileCommand objects
[ "Return", "the", "filecommands", "filtered", "by", "includes", "&", "excludes", "." ]
train
https://github.com/jelmer/python-fastimport/blob/5cef9e037b7d7b37f58f522ac9ea4e343e6a1dff/fastimport/processors/filter_processor.py#L164-L193
jelmer/python-fastimport
fastimport/processors/filter_processor.py
FilterProcessor._path_to_be_kept
def _path_to_be_kept(self, path): """Does the given path pass the filtering criteria?""" if self.excludes and (path in self.excludes or helpers.is_inside_any(self.excludes, path)): return False if self.includes: return (path in self.includes ...
python
def _path_to_be_kept(self, path): """Does the given path pass the filtering criteria?""" if self.excludes and (path in self.excludes or helpers.is_inside_any(self.excludes, path)): return False if self.includes: return (path in self.includes ...
[ "def", "_path_to_be_kept", "(", "self", ",", "path", ")", ":", "if", "self", ".", "excludes", "and", "(", "path", "in", "self", ".", "excludes", "or", "helpers", ".", "is_inside_any", "(", "self", ".", "excludes", ",", "path", ")", ")", ":", "return", ...
Does the given path pass the filtering criteria?
[ "Does", "the", "given", "path", "pass", "the", "filtering", "criteria?" ]
train
https://github.com/jelmer/python-fastimport/blob/5cef9e037b7d7b37f58f522ac9ea4e343e6a1dff/fastimport/processors/filter_processor.py#L195-L203
jelmer/python-fastimport
fastimport/processors/filter_processor.py
FilterProcessor._adjust_for_new_root
def _adjust_for_new_root(self, path): """Adjust a path given the new root directory of the output.""" if self.new_root is None: return path elif path.startswith(self.new_root): return path[len(self.new_root):] else: return path
python
def _adjust_for_new_root(self, path): """Adjust a path given the new root directory of the output.""" if self.new_root is None: return path elif path.startswith(self.new_root): return path[len(self.new_root):] else: return path
[ "def", "_adjust_for_new_root", "(", "self", ",", "path", ")", ":", "if", "self", ".", "new_root", "is", "None", ":", "return", "path", "elif", "path", ".", "startswith", "(", "self", ".", "new_root", ")", ":", "return", "path", "[", "len", "(", "self",...
Adjust a path given the new root directory of the output.
[ "Adjust", "a", "path", "given", "the", "new", "root", "directory", "of", "the", "output", "." ]
train
https://github.com/jelmer/python-fastimport/blob/5cef9e037b7d7b37f58f522ac9ea4e343e6a1dff/fastimport/processors/filter_processor.py#L205-L212
jelmer/python-fastimport
fastimport/processors/filter_processor.py
FilterProcessor._convert_rename
def _convert_rename(self, fc): """Convert a FileRenameCommand into a new FileCommand. :return: None if the rename is being ignored, otherwise a new FileCommand based on the whether the old and new paths are inside or outside of the interesting locations. """ old = ...
python
def _convert_rename(self, fc): """Convert a FileRenameCommand into a new FileCommand. :return: None if the rename is being ignored, otherwise a new FileCommand based on the whether the old and new paths are inside or outside of the interesting locations. """ old = ...
[ "def", "_convert_rename", "(", "self", ",", "fc", ")", ":", "old", "=", "fc", ".", "old_path", "new", "=", "fc", ".", "new_path", "keep_old", "=", "self", ".", "_path_to_be_kept", "(", "old", ")", "keep_new", "=", "self", ".", "_path_to_be_kept", "(", ...
Convert a FileRenameCommand into a new FileCommand. :return: None if the rename is being ignored, otherwise a new FileCommand based on the whether the old and new paths are inside or outside of the interesting locations.
[ "Convert", "a", "FileRenameCommand", "into", "a", "new", "FileCommand", "." ]
train
https://github.com/jelmer/python-fastimport/blob/5cef9e037b7d7b37f58f522ac9ea4e343e6a1dff/fastimport/processors/filter_processor.py#L241-L270
jelmer/python-fastimport
fastimport/processors/filter_processor.py
FilterProcessor._convert_copy
def _convert_copy(self, fc): """Convert a FileCopyCommand into a new FileCommand. :return: None if the copy is being ignored, otherwise a new FileCommand based on the whether the source and destination paths are inside or outside of the interesting locations. """ s...
python
def _convert_copy(self, fc): """Convert a FileCopyCommand into a new FileCommand. :return: None if the copy is being ignored, otherwise a new FileCommand based on the whether the source and destination paths are inside or outside of the interesting locations. """ s...
[ "def", "_convert_copy", "(", "self", ",", "fc", ")", ":", "src", "=", "fc", ".", "src_path", "dest", "=", "fc", ".", "dest_path", "keep_src", "=", "self", ".", "_path_to_be_kept", "(", "src", ")", "keep_dest", "=", "self", ".", "_path_to_be_kept", "(", ...
Convert a FileCopyCommand into a new FileCommand. :return: None if the copy is being ignored, otherwise a new FileCommand based on the whether the source and destination paths are inside or outside of the interesting locations.
[ "Convert", "a", "FileCopyCommand", "into", "a", "new", "FileCommand", "." ]
train
https://github.com/jelmer/python-fastimport/blob/5cef9e037b7d7b37f58f522ac9ea4e343e6a1dff/fastimport/processors/filter_processor.py#L272-L300
Clinical-Genomics/housekeeper
housekeeper/cli/delete.py
bundle
def bundle(context, yes, bundle_name): """Delete the latest bundle version.""" bundle_obj = context.obj['store'].bundle(bundle_name) if bundle_obj is None: click.echo(click.style('bundle not found', fg='red')) context.abort() version_obj = bundle_obj.versions[0] if version_obj.includ...
python
def bundle(context, yes, bundle_name): """Delete the latest bundle version.""" bundle_obj = context.obj['store'].bundle(bundle_name) if bundle_obj is None: click.echo(click.style('bundle not found', fg='red')) context.abort() version_obj = bundle_obj.versions[0] if version_obj.includ...
[ "def", "bundle", "(", "context", ",", "yes", ",", "bundle_name", ")", ":", "bundle_obj", "=", "context", ".", "obj", "[", "'store'", "]", ".", "bundle", "(", "bundle_name", ")", "if", "bundle_obj", "is", "None", ":", "click", ".", "echo", "(", "click",...
Delete the latest bundle version.
[ "Delete", "the", "latest", "bundle", "version", "." ]
train
https://github.com/Clinical-Genomics/housekeeper/blob/a7d10d327dc9f06274bdef5504ed1b9413f2c8c1/housekeeper/cli/delete.py#L20-L36
Clinical-Genomics/housekeeper
housekeeper/cli/delete.py
files
def files(context, yes, tag, bundle, before, notondisk): """Delete files based on tags.""" file_objs = [] if not tag and not bundle: click.echo("I'm afraid I can't let you do that.") context.abort() if bundle: bundle_obj = context.obj['store'].bundle(bundle) if bundle_o...
python
def files(context, yes, tag, bundle, before, notondisk): """Delete files based on tags.""" file_objs = [] if not tag and not bundle: click.echo("I'm afraid I can't let you do that.") context.abort() if bundle: bundle_obj = context.obj['store'].bundle(bundle) if bundle_o...
[ "def", "files", "(", "context", ",", "yes", ",", "tag", ",", "bundle", ",", "before", ",", "notondisk", ")", ":", "file_objs", "=", "[", "]", "if", "not", "tag", "and", "not", "bundle", ":", "click", ".", "echo", "(", "\"I'm afraid I can't let you do tha...
Delete files based on tags.
[ "Delete", "files", "based", "on", "tags", "." ]
train
https://github.com/Clinical-Genomics/housekeeper/blob/a7d10d327dc9f06274bdef5504ed1b9413f2c8c1/housekeeper/cli/delete.py#L46-L78
Clinical-Genomics/housekeeper
housekeeper/cli/delete.py
file_cmd
def file_cmd(context, yes, file_id): """Delete a file.""" file_obj = context.obj['store'].File.get(file_id) if file_obj.is_included: question = f"remove file from file system and database: {file_obj.full_path}" else: question = f"remove file from database: {file_obj.full_path}" if ye...
python
def file_cmd(context, yes, file_id): """Delete a file.""" file_obj = context.obj['store'].File.get(file_id) if file_obj.is_included: question = f"remove file from file system and database: {file_obj.full_path}" else: question = f"remove file from database: {file_obj.full_path}" if ye...
[ "def", "file_cmd", "(", "context", ",", "yes", ",", "file_id", ")", ":", "file_obj", "=", "context", ".", "obj", "[", "'store'", "]", ".", "File", ".", "get", "(", "file_id", ")", "if", "file_obj", ".", "is_included", ":", "question", "=", "f\"remove f...
Delete a file.
[ "Delete", "a", "file", "." ]
train
https://github.com/Clinical-Genomics/housekeeper/blob/a7d10d327dc9f06274bdef5504ed1b9413f2c8c1/housekeeper/cli/delete.py#L85-L98
MuxZeroNet/leaflet
leaflet/samtools.py
sam_readline
def sam_readline(sock, partial = None): """read a line from a sam control socket""" response = b'' exception = None while True: try: c = sock.recv(1) if not c: raise EOFError('SAM connection died. Partial response %r %r' % (partial, response)) ...
python
def sam_readline(sock, partial = None): """read a line from a sam control socket""" response = b'' exception = None while True: try: c = sock.recv(1) if not c: raise EOFError('SAM connection died. Partial response %r %r' % (partial, response)) ...
[ "def", "sam_readline", "(", "sock", ",", "partial", "=", "None", ")", ":", "response", "=", "b''", "exception", "=", "None", "while", "True", ":", "try", ":", "c", "=", "sock", ".", "recv", "(", "1", ")", "if", "not", "c", ":", "raise", "EOFError",...
read a line from a sam control socket
[ "read", "a", "line", "from", "a", "sam", "control", "socket" ]
train
https://github.com/MuxZeroNet/leaflet/blob/e4e59005aea4e30da233dca24479b1d8a36e32c6/leaflet/samtools.py#L65-L90
MuxZeroNet/leaflet
leaflet/samtools.py
sam_parse_reply
def sam_parse_reply(line): """parse a reply line into a dict""" parts = line.split(' ') opts = {k: v for (k, v) in split_kv(parts[2:])} return SAMReply(parts[0], opts)
python
def sam_parse_reply(line): """parse a reply line into a dict""" parts = line.split(' ') opts = {k: v for (k, v) in split_kv(parts[2:])} return SAMReply(parts[0], opts)
[ "def", "sam_parse_reply", "(", "line", ")", ":", "parts", "=", "line", ".", "split", "(", "' '", ")", "opts", "=", "{", "k", ":", "v", "for", "(", "k", ",", "v", ")", "in", "split_kv", "(", "parts", "[", "2", ":", "]", ")", "}", "return", "SA...
parse a reply line into a dict
[ "parse", "a", "reply", "line", "into", "a", "dict" ]
train
https://github.com/MuxZeroNet/leaflet/blob/e4e59005aea4e30da233dca24479b1d8a36e32c6/leaflet/samtools.py#L151-L155
MuxZeroNet/leaflet
leaflet/samtools.py
sam_send
def sam_send(sock, line_and_data): """Send a line to the SAM controller, but don't read it""" if isinstance(line_and_data, tuple): line, data = line_and_data else: line, data = line_and_data, b'' line = bytes(line, encoding='ascii') + b' \n' # print('-->', line, data) sock.senda...
python
def sam_send(sock, line_and_data): """Send a line to the SAM controller, but don't read it""" if isinstance(line_and_data, tuple): line, data = line_and_data else: line, data = line_and_data, b'' line = bytes(line, encoding='ascii') + b' \n' # print('-->', line, data) sock.senda...
[ "def", "sam_send", "(", "sock", ",", "line_and_data", ")", ":", "if", "isinstance", "(", "line_and_data", ",", "tuple", ")", ":", "line", ",", "data", "=", "line_and_data", "else", ":", "line", ",", "data", "=", "line_and_data", ",", "b''", "line", "=", ...
Send a line to the SAM controller, but don't read it
[ "Send", "a", "line", "to", "the", "SAM", "controller", "but", "don", "t", "read", "it" ]
train
https://github.com/MuxZeroNet/leaflet/blob/e4e59005aea4e30da233dca24479b1d8a36e32c6/leaflet/samtools.py#L157-L166
MuxZeroNet/leaflet
leaflet/samtools.py
sam_cmd
def sam_cmd(sock, line, parse=True): """Send a line to the SAM controller, returning the parsed response""" sam_send(sock, line) reply_line = sam_readline(sock) if parse: return sam_parse_reply(reply_line) else: return reply_line
python
def sam_cmd(sock, line, parse=True): """Send a line to the SAM controller, returning the parsed response""" sam_send(sock, line) reply_line = sam_readline(sock) if parse: return sam_parse_reply(reply_line) else: return reply_line
[ "def", "sam_cmd", "(", "sock", ",", "line", ",", "parse", "=", "True", ")", ":", "sam_send", "(", "sock", ",", "line", ")", "reply_line", "=", "sam_readline", "(", "sock", ")", "if", "parse", ":", "return", "sam_parse_reply", "(", "reply_line", ")", "e...
Send a line to the SAM controller, returning the parsed response
[ "Send", "a", "line", "to", "the", "SAM", "controller", "returning", "the", "parsed", "response" ]
train
https://github.com/MuxZeroNet/leaflet/blob/e4e59005aea4e30da233dca24479b1d8a36e32c6/leaflet/samtools.py#L168-L175
MuxZeroNet/leaflet
leaflet/samtools.py
handshake
def handshake(timeout, sam_api, max_version): """handshake with sam via a socket.socket instance""" sock = controller_connect(sam_api, timeout=timeout) response = sam_cmd(sock, greet(max_version)) if response.ok: return sock else: raise HandshakeError("Failed to handshake with SAM: %...
python
def handshake(timeout, sam_api, max_version): """handshake with sam via a socket.socket instance""" sock = controller_connect(sam_api, timeout=timeout) response = sam_cmd(sock, greet(max_version)) if response.ok: return sock else: raise HandshakeError("Failed to handshake with SAM: %...
[ "def", "handshake", "(", "timeout", ",", "sam_api", ",", "max_version", ")", ":", "sock", "=", "controller_connect", "(", "sam_api", ",", "timeout", "=", "timeout", ")", "response", "=", "sam_cmd", "(", "sock", ",", "greet", "(", "max_version", ")", ")", ...
handshake with sam via a socket.socket instance
[ "handshake", "with", "sam", "via", "a", "socket", ".", "socket", "instance" ]
train
https://github.com/MuxZeroNet/leaflet/blob/e4e59005aea4e30da233dca24479b1d8a36e32c6/leaflet/samtools.py#L206-L213
MuxZeroNet/leaflet
leaflet/samtools.py
lookup
def lookup(sock, domain, cache = None): """lookup an I2P domain name, returning a Destination instance""" domain = normalize_domain(domain) # cache miss, perform lookup reply = sam_cmd(sock, "NAMING LOOKUP NAME=%s" % domain) b64_dest = reply.get('VALUE') if b64_dest: dest = Dest(b64_de...
python
def lookup(sock, domain, cache = None): """lookup an I2P domain name, returning a Destination instance""" domain = normalize_domain(domain) # cache miss, perform lookup reply = sam_cmd(sock, "NAMING LOOKUP NAME=%s" % domain) b64_dest = reply.get('VALUE') if b64_dest: dest = Dest(b64_de...
[ "def", "lookup", "(", "sock", ",", "domain", ",", "cache", "=", "None", ")", ":", "domain", "=", "normalize_domain", "(", "domain", ")", "# cache miss, perform lookup", "reply", "=", "sam_cmd", "(", "sock", ",", "\"NAMING LOOKUP NAME=%s\"", "%", "domain", ")",...
lookup an I2P domain name, returning a Destination instance
[ "lookup", "an", "I2P", "domain", "name", "returning", "a", "Destination", "instance" ]
train
https://github.com/MuxZeroNet/leaflet/blob/e4e59005aea4e30da233dca24479b1d8a36e32c6/leaflet/samtools.py#L236-L250
Robin8Put/pmes
history/ClickHouse/views.py
create_table
async def create_table(**data): """ RPC method for creating table with custom name and fields :return event id """ table = data.get('table') try: clickhouse_queries.create_table(table, data) return 'Table was successfully created' except ServerException as e: excep...
python
async def create_table(**data): """ RPC method for creating table with custom name and fields :return event id """ table = data.get('table') try: clickhouse_queries.create_table(table, data) return 'Table was successfully created' except ServerException as e: excep...
[ "async", "def", "create_table", "(", "*", "*", "data", ")", ":", "table", "=", "data", ".", "get", "(", "'table'", ")", "try", ":", "clickhouse_queries", ".", "create_table", "(", "table", ",", "data", ")", "return", "'Table was successfully created'", "exce...
RPC method for creating table with custom name and fields :return event id
[ "RPC", "method", "for", "creating", "table", "with", "custom", "name", "and", "fields", ":", "return", "event", "id" ]
train
https://github.com/Robin8Put/pmes/blob/338bec94162098f05b75bad035417317e1252fd2/history/ClickHouse/views.py#L13-L31
Robin8Put/pmes
history/ClickHouse/views.py
insert
async def insert(**data): """ RPC method for inserting data to the table :return: None """ table = data.get('table') try: clickhouse_queries.insert_into_table(table, data) return 'Data was successfully inserted into table' except ServerException as e: exception_cod...
python
async def insert(**data): """ RPC method for inserting data to the table :return: None """ table = data.get('table') try: clickhouse_queries.insert_into_table(table, data) return 'Data was successfully inserted into table' except ServerException as e: exception_cod...
[ "async", "def", "insert", "(", "*", "*", "data", ")", ":", "table", "=", "data", ".", "get", "(", "'table'", ")", "try", ":", "clickhouse_queries", ".", "insert_into_table", "(", "table", ",", "data", ")", "return", "'Data was successfully inserted into table'...
RPC method for inserting data to the table :return: None
[ "RPC", "method", "for", "inserting", "data", "to", "the", "table", ":", "return", ":", "None" ]
train
https://github.com/Robin8Put/pmes/blob/338bec94162098f05b75bad035417317e1252fd2/history/ClickHouse/views.py#L35-L53
Robin8Put/pmes
history/ClickHouse/views.py
select
async def select(**data): """ RPC method for selecting data from the database :return selected data """ try: select_data = clickhouse_queries.select_from_table(table=data['table'], query=data['query'], fields=data['fields']) return str(select_data) except ServerException as e: ...
python
async def select(**data): """ RPC method for selecting data from the database :return selected data """ try: select_data = clickhouse_queries.select_from_table(table=data['table'], query=data['query'], fields=data['fields']) return str(select_data) except ServerException as e: ...
[ "async", "def", "select", "(", "*", "*", "data", ")", ":", "try", ":", "select_data", "=", "clickhouse_queries", ".", "select_from_table", "(", "table", "=", "data", "[", "'table'", "]", ",", "query", "=", "data", "[", "'query'", "]", ",", "fields", "=...
RPC method for selecting data from the database :return selected data
[ "RPC", "method", "for", "selecting", "data", "from", "the", "database", ":", "return", "selected", "data" ]
train
https://github.com/Robin8Put/pmes/blob/338bec94162098f05b75bad035417317e1252fd2/history/ClickHouse/views.py#L57-L73
Robin8Put/pmes
history/ClickHouse/views.py
drop
async def drop(**data): """ RPC method for deleting table from the database :return None """ table = data['table'] try: clickhouse_queries.drop_table(table) return 'Table was successfully deleted' except ServerException as e: exception_code = int(str(e)[5:8].strip(...
python
async def drop(**data): """ RPC method for deleting table from the database :return None """ table = data['table'] try: clickhouse_queries.drop_table(table) return 'Table was successfully deleted' except ServerException as e: exception_code = int(str(e)[5:8].strip(...
[ "async", "def", "drop", "(", "*", "*", "data", ")", ":", "table", "=", "data", "[", "'table'", "]", "try", ":", "clickhouse_queries", ".", "drop_table", "(", "table", ")", "return", "'Table was successfully deleted'", "except", "ServerException", "as", "e", ...
RPC method for deleting table from the database :return None
[ "RPC", "method", "for", "deleting", "table", "from", "the", "database", ":", "return", "None" ]
train
https://github.com/Robin8Put/pmes/blob/338bec94162098f05b75bad035417317e1252fd2/history/ClickHouse/views.py#L77-L92
Robin8Put/pmes
history/ClickHouse/views.py
HistoryHandler.post
async def post(self): """ Accepts json-rpc post request. Retrieves data from request body. Calls defined method in field 'method_name' """ request = self.request.body.decode() response = await methods.dispatch(request) if not response.is_notification: ...
python
async def post(self): """ Accepts json-rpc post request. Retrieves data from request body. Calls defined method in field 'method_name' """ request = self.request.body.decode() response = await methods.dispatch(request) if not response.is_notification: ...
[ "async", "def", "post", "(", "self", ")", ":", "request", "=", "self", ".", "request", ".", "body", ".", "decode", "(", ")", "response", "=", "await", "methods", ".", "dispatch", "(", "request", ")", "if", "not", "response", ".", "is_notification", ":"...
Accepts json-rpc post request. Retrieves data from request body. Calls defined method in field 'method_name'
[ "Accepts", "json", "-", "rpc", "post", "request", ".", "Retrieves", "data", "from", "request", "body", ".", "Calls", "defined", "method", "in", "field", "method_name" ]
train
https://github.com/Robin8Put/pmes/blob/338bec94162098f05b75bad035417317e1252fd2/history/ClickHouse/views.py#L101-L111
jsoa/django-formfield
setup.py
read_file
def read_file(filename): """Read a file into a string""" p = path.abspath(path.dirname(__file__)) filepath = path.join(p, filename) try: return open(filepath).read() except IOError: return ''
python
def read_file(filename): """Read a file into a string""" p = path.abspath(path.dirname(__file__)) filepath = path.join(p, filename) try: return open(filepath).read() except IOError: return ''
[ "def", "read_file", "(", "filename", ")", ":", "p", "=", "path", ".", "abspath", "(", "path", ".", "dirname", "(", "__file__", ")", ")", "filepath", "=", "path", ".", "join", "(", "p", ",", "filename", ")", "try", ":", "return", "open", "(", "filep...
Read a file into a string
[ "Read", "a", "file", "into", "a", "string" ]
train
https://github.com/jsoa/django-formfield/blob/7fbe8e9aa3e587588a8ed80063e4692e7e0608fe/setup.py#L8-L15
bradmontgomery/django-staticflatpages
staticflatpages/util.py
get_template_directories
def get_template_directories(): """This function tries to figure out where template directories are located. It first inspects the TEMPLATES setting, and if that exists and is not empty, uses its values. Otherwise, the values from all of the defined DIRS within TEMPLATES are used. Returns a set of...
python
def get_template_directories(): """This function tries to figure out where template directories are located. It first inspects the TEMPLATES setting, and if that exists and is not empty, uses its values. Otherwise, the values from all of the defined DIRS within TEMPLATES are used. Returns a set of...
[ "def", "get_template_directories", "(", ")", ":", "templates", "=", "set", "(", ")", "for", "t", "in", "settings", ".", "TEMPLATES", ":", "templates", "=", "templates", ".", "union", "(", "set", "(", "t", ".", "get", "(", "'DIRS'", ",", "[", "]", ")"...
This function tries to figure out where template directories are located. It first inspects the TEMPLATES setting, and if that exists and is not empty, uses its values. Otherwise, the values from all of the defined DIRS within TEMPLATES are used. Returns a set of template directories.
[ "This", "function", "tries", "to", "figure", "out", "where", "template", "directories", "are", "located", ".", "It", "first", "inspects", "the", "TEMPLATES", "setting", "and", "if", "that", "exists", "and", "is", "not", "empty", "uses", "its", "values", "." ...
train
https://github.com/bradmontgomery/django-staticflatpages/blob/76dbed40fa1af0434bf5d8012cb86b8139bb3256/staticflatpages/util.py#L8-L21
bradmontgomery/django-staticflatpages
staticflatpages/util.py
_format_as_url
def _format_as_url(path): """Make sure ``path`` takes the form of ``/some/url/``.""" path = sub(r"\.html$", '', path) # remove any ending .html # Make sure it starts/ends with a slash. if not path.startswith("/"): path = "/{0}".format(path) if not path.endswith("/"): path = "{0}/"....
python
def _format_as_url(path): """Make sure ``path`` takes the form of ``/some/url/``.""" path = sub(r"\.html$", '', path) # remove any ending .html # Make sure it starts/ends with a slash. if not path.startswith("/"): path = "/{0}".format(path) if not path.endswith("/"): path = "{0}/"....
[ "def", "_format_as_url", "(", "path", ")", ":", "path", "=", "sub", "(", "r\"\\.html$\"", ",", "''", ",", "path", ")", "# remove any ending .html", "# Make sure it starts/ends with a slash.", "if", "not", "path", ".", "startswith", "(", "\"/\"", ")", ":", "path"...
Make sure ``path`` takes the form of ``/some/url/``.
[ "Make", "sure", "path", "takes", "the", "form", "of", "/", "some", "/", "url", "/", "." ]
train
https://github.com/bradmontgomery/django-staticflatpages/blob/76dbed40fa1af0434bf5d8012cb86b8139bb3256/staticflatpages/util.py#L24-L34
bradmontgomery/django-staticflatpages
staticflatpages/util.py
urls_from_file_tree
def urls_from_file_tree(template_dir): """Generates a list of URL strings that would match each staticflatpage.""" urls = [] # keep a list of of all the files/paths # Should be somethign like: # /path/to/myproject/templates/staticflatpages root_dir = join(template_dir, 'staticflatpages') for ...
python
def urls_from_file_tree(template_dir): """Generates a list of URL strings that would match each staticflatpage.""" urls = [] # keep a list of of all the files/paths # Should be somethign like: # /path/to/myproject/templates/staticflatpages root_dir = join(template_dir, 'staticflatpages') for ...
[ "def", "urls_from_file_tree", "(", "template_dir", ")", ":", "urls", "=", "[", "]", "# keep a list of of all the files/paths", "# Should be somethign like:", "# /path/to/myproject/templates/staticflatpages", "root_dir", "=", "join", "(", "template_dir", ",", "'staticflatpages'"...
Generates a list of URL strings that would match each staticflatpage.
[ "Generates", "a", "list", "of", "URL", "strings", "that", "would", "match", "each", "staticflatpage", "." ]
train
https://github.com/bradmontgomery/django-staticflatpages/blob/76dbed40fa1af0434bf5d8012cb86b8139bb3256/staticflatpages/util.py#L37-L53
cimatosa/progression
progression/terminal.py
get_terminal_size
def get_terminal_size(defaultw=80): """ Checks various methods to determine the terminal size Methods: - shutil.get_terminal_size (only Python3) - fcntl.ioctl - subprocess.check_output - os.environ Parameters ---------- defaultw : int Default width of terminal. Retur...
python
def get_terminal_size(defaultw=80): """ Checks various methods to determine the terminal size Methods: - shutil.get_terminal_size (only Python3) - fcntl.ioctl - subprocess.check_output - os.environ Parameters ---------- defaultw : int Default width of terminal. Retur...
[ "def", "get_terminal_size", "(", "defaultw", "=", "80", ")", ":", "if", "hasattr", "(", "shutil_get_terminal_size", ",", "\"__call__\"", ")", ":", "return", "shutil_get_terminal_size", "(", ")", "else", ":", "try", ":", "import", "fcntl", ",", "termios", ",", ...
Checks various methods to determine the terminal size Methods: - shutil.get_terminal_size (only Python3) - fcntl.ioctl - subprocess.check_output - os.environ Parameters ---------- defaultw : int Default width of terminal. Returns ------- width, height : int ...
[ "Checks", "various", "methods", "to", "determine", "the", "terminal", "size" ]
train
https://github.com/cimatosa/progression/blob/82cf74a25a47f9bda96157cc2c88e5975c20b41d/progression/terminal.py#L40-L82
cimatosa/progression
progression/terminal.py
terminal_reserve
def terminal_reserve(progress_obj, terminal_obj=None, identifier=None): """ Registers the terminal (stdout) for printing. Useful to prevent multiple processes from writing progress bars to stdout. One process (server) prints to stdout and a couple of subprocesses do not print to the same stdout, b...
python
def terminal_reserve(progress_obj, terminal_obj=None, identifier=None): """ Registers the terminal (stdout) for printing. Useful to prevent multiple processes from writing progress bars to stdout. One process (server) prints to stdout and a couple of subprocesses do not print to the same stdout, b...
[ "def", "terminal_reserve", "(", "progress_obj", ",", "terminal_obj", "=", "None", ",", "identifier", "=", "None", ")", ":", "if", "terminal_obj", "is", "None", ":", "terminal_obj", "=", "sys", ".", "stdout", "if", "identifier", "is", "None", ":", "identifier...
Registers the terminal (stdout) for printing. Useful to prevent multiple processes from writing progress bars to stdout. One process (server) prints to stdout and a couple of subprocesses do not print to the same stdout, because the server has reserved it. Of course, the clients have to be nice an...
[ "Registers", "the", "terminal", "(", "stdout", ")", "for", "printing", "." ]
train
https://github.com/cimatosa/progression/blob/82cf74a25a47f9bda96157cc2c88e5975c20b41d/progression/terminal.py#L95-L131
cimatosa/progression
progression/terminal.py
terminal_unreserve
def terminal_unreserve(progress_obj, terminal_obj=None, verbose=0, identifier=None): """ Unregisters the terminal (stdout) for printing. an instance (progress_obj) can only unreserve the tty (terminal_obj) when it also reserved it see terminal_reserved for more information Returns ------- Non...
python
def terminal_unreserve(progress_obj, terminal_obj=None, verbose=0, identifier=None): """ Unregisters the terminal (stdout) for printing. an instance (progress_obj) can only unreserve the tty (terminal_obj) when it also reserved it see terminal_reserved for more information Returns ------- Non...
[ "def", "terminal_unreserve", "(", "progress_obj", ",", "terminal_obj", "=", "None", ",", "verbose", "=", "0", ",", "identifier", "=", "None", ")", ":", "if", "terminal_obj", "is", "None", ":", "terminal_obj", "=", "sys", ".", "stdout", "if", "identifier", ...
Unregisters the terminal (stdout) for printing. an instance (progress_obj) can only unreserve the tty (terminal_obj) when it also reserved it see terminal_reserved for more information Returns ------- None
[ "Unregisters", "the", "terminal", "(", "stdout", ")", "for", "printing", "." ]
train
https://github.com/cimatosa/progression/blob/82cf74a25a47f9bda96157cc2c88e5975c20b41d/progression/terminal.py#L134-L163
jsoa/django-formfield
formfield/fields.py
FormField.compress
def compress(self, data_list): """ Return the cleaned_data of the form, everything should already be valid """ data = {} if data_list: return dict( (f.name, data_list[i]) for i, f in enumerate(self.form)) return data
python
def compress(self, data_list): """ Return the cleaned_data of the form, everything should already be valid """ data = {} if data_list: return dict( (f.name, data_list[i]) for i, f in enumerate(self.form)) return data
[ "def", "compress", "(", "self", ",", "data_list", ")", ":", "data", "=", "{", "}", "if", "data_list", ":", "return", "dict", "(", "(", "f", ".", "name", ",", "data_list", "[", "i", "]", ")", "for", "i", ",", "f", "in", "enumerate", "(", "self", ...
Return the cleaned_data of the form, everything should already be valid
[ "Return", "the", "cleaned_data", "of", "the", "form", "everything", "should", "already", "be", "valid" ]
train
https://github.com/jsoa/django-formfield/blob/7fbe8e9aa3e587588a8ed80063e4692e7e0608fe/formfield/fields.py#L82-L90
jsoa/django-formfield
formfield/fields.py
FormField.clean
def clean(self, value): """ Call the form is_valid to ensure every value supplied is valid """ if not value: raise ValidationError( 'Error found in Form Field: Nothing to validate') data = dict((bf.name, value[i]) for i, bf in enumerate(self.form)) ...
python
def clean(self, value): """ Call the form is_valid to ensure every value supplied is valid """ if not value: raise ValidationError( 'Error found in Form Field: Nothing to validate') data = dict((bf.name, value[i]) for i, bf in enumerate(self.form)) ...
[ "def", "clean", "(", "self", ",", "value", ")", ":", "if", "not", "value", ":", "raise", "ValidationError", "(", "'Error found in Form Field: Nothing to validate'", ")", "data", "=", "dict", "(", "(", "bf", ".", "name", ",", "value", "[", "i", "]", ")", ...
Call the form is_valid to ensure every value supplied is valid
[ "Call", "the", "form", "is_valid", "to", "ensure", "every", "value", "supplied", "is", "valid" ]
train
https://github.com/jsoa/django-formfield/blob/7fbe8e9aa3e587588a8ed80063e4692e7e0608fe/formfield/fields.py#L92-L109
grahambell/pymoc
lib/pymoc/util/tool.py
MOCTool.run
def run(self, params): """Main run method for PyMOC tool. Takes a list of command line arguments to process. Each operation is performed on a current "running" MOC object. """ self.params = list(reversed(params)) if not self.params: self.help() ...
python
def run(self, params): """Main run method for PyMOC tool. Takes a list of command line arguments to process. Each operation is performed on a current "running" MOC object. """ self.params = list(reversed(params)) if not self.params: self.help() ...
[ "def", "run", "(", "self", ",", "params", ")", ":", "self", ".", "params", "=", "list", "(", "reversed", "(", "params", ")", ")", "if", "not", "self", ".", "params", ":", "self", ".", "help", "(", ")", "return", "while", "self", ".", "params", ":...
Main run method for PyMOC tool. Takes a list of command line arguments to process. Each operation is performed on a current "running" MOC object.
[ "Main", "run", "method", "for", "PyMOC", "tool", "." ]
train
https://github.com/grahambell/pymoc/blob/0e2e57ce07ff3de6ac024627c1fb6ad30c2fde48/lib/pymoc/util/tool.py#L91-L119
grahambell/pymoc
lib/pymoc/util/tool.py
MOCTool.read_moc
def read_moc(self, filename): """Read a file into the current running MOC object. If the running MOC object has not yet been created, then it is created by reading the file, which will import the MOC metadata. Otherwise the metadata are not imported. """ if self.moc is...
python
def read_moc(self, filename): """Read a file into the current running MOC object. If the running MOC object has not yet been created, then it is created by reading the file, which will import the MOC metadata. Otherwise the metadata are not imported. """ if self.moc is...
[ "def", "read_moc", "(", "self", ",", "filename", ")", ":", "if", "self", ".", "moc", "is", "None", ":", "self", ".", "moc", "=", "MOC", "(", "filename", "=", "filename", ")", "else", ":", "self", ".", "moc", ".", "read", "(", "filename", ")" ]
Read a file into the current running MOC object. If the running MOC object has not yet been created, then it is created by reading the file, which will import the MOC metadata. Otherwise the metadata are not imported.
[ "Read", "a", "file", "into", "the", "current", "running", "MOC", "object", "." ]
train
https://github.com/grahambell/pymoc/blob/0e2e57ce07ff3de6ac024627c1fb6ad30c2fde48/lib/pymoc/util/tool.py#L121-L133
grahambell/pymoc
lib/pymoc/util/tool.py
MOCTool.catalog
def catalog(self): """Create MOC from catalog of coordinates. This command requires that the Healpy and Astropy libraries be available. It attempts to load the given catalog, and merges it with the running MOC. The name of an ASCII catalog file should be given. The file ...
python
def catalog(self): """Create MOC from catalog of coordinates. This command requires that the Healpy and Astropy libraries be available. It attempts to load the given catalog, and merges it with the running MOC. The name of an ASCII catalog file should be given. The file ...
[ "def", "catalog", "(", "self", ")", ":", "from", ".", "catalog", "import", "catalog_to_moc", ",", "read_ascii_catalog", "filename", "=", "self", ".", "params", ".", "pop", "(", ")", "order", "=", "12", "radius", "=", "3600", "unit", "=", "None", "format_...
Create MOC from catalog of coordinates. This command requires that the Healpy and Astropy libraries be available. It attempts to load the given catalog, and merges it with the running MOC. The name of an ASCII catalog file should be given. The file should contain either "RA" ...
[ "Create", "MOC", "from", "catalog", "of", "coordinates", "." ]
train
https://github.com/grahambell/pymoc/blob/0e2e57ce07ff3de6ac024627c1fb6ad30c2fde48/lib/pymoc/util/tool.py#L136-L206
grahambell/pymoc
lib/pymoc/util/tool.py
MOCTool.help
def help(self): """Display command usage information.""" if self.params: command = self.params.pop().lstrip('-') if command in self.command.documentation: (aliases, doc) = self.command.documentation[command] (synopsis, body) = self._split_docstri...
python
def help(self): """Display command usage information.""" if self.params: command = self.params.pop().lstrip('-') if command in self.command.documentation: (aliases, doc) = self.command.documentation[command] (synopsis, body) = self._split_docstri...
[ "def", "help", "(", "self", ")", ":", "if", "self", ".", "params", ":", "command", "=", "self", ".", "params", ".", "pop", "(", ")", ".", "lstrip", "(", "'-'", ")", "if", "command", "in", "self", ".", "command", ".", "documentation", ":", "(", "a...
Display command usage information.
[ "Display", "command", "usage", "information", "." ]
train
https://github.com/grahambell/pymoc/blob/0e2e57ce07ff3de6ac024627c1fb6ad30c2fde48/lib/pymoc/util/tool.py#L209-L238
grahambell/pymoc
lib/pymoc/util/tool.py
MOCTool.identifier
def identifier(self): """Set the identifier of the current MOC. The new identifier should be given after this option. :: pymoctool ... --id 'New MOC identifier' --output new_moc.fits """ if self.moc is None: self.moc = MOC() self.moc.id = self...
python
def identifier(self): """Set the identifier of the current MOC. The new identifier should be given after this option. :: pymoctool ... --id 'New MOC identifier' --output new_moc.fits """ if self.moc is None: self.moc = MOC() self.moc.id = self...
[ "def", "identifier", "(", "self", ")", ":", "if", "self", ".", "moc", "is", "None", ":", "self", ".", "moc", "=", "MOC", "(", ")", "self", ".", "moc", ".", "id", "=", "self", ".", "params", ".", "pop", "(", ")" ]
Set the identifier of the current MOC. The new identifier should be given after this option. :: pymoctool ... --id 'New MOC identifier' --output new_moc.fits
[ "Set", "the", "identifier", "of", "the", "current", "MOC", "." ]
train
https://github.com/grahambell/pymoc/blob/0e2e57ce07ff3de6ac024627c1fb6ad30c2fde48/lib/pymoc/util/tool.py#L241-L254
grahambell/pymoc
lib/pymoc/util/tool.py
MOCTool.display_info
def display_info(self): """Display basic information about the running MOC.""" if self.moc is None: print('No MOC information present') return if self.moc.name is not None: print('Name:', self.moc.name) if self.moc.id is not None: print('...
python
def display_info(self): """Display basic information about the running MOC.""" if self.moc is None: print('No MOC information present') return if self.moc.name is not None: print('Name:', self.moc.name) if self.moc.id is not None: print('...
[ "def", "display_info", "(", "self", ")", ":", "if", "self", ".", "moc", "is", "None", ":", "print", "(", "'No MOC information present'", ")", "return", "if", "self", ".", "moc", ".", "name", "is", "not", "None", ":", "print", "(", "'Name:'", ",", "self...
Display basic information about the running MOC.
[ "Display", "basic", "information", "about", "the", "running", "MOC", "." ]
train
https://github.com/grahambell/pymoc/blob/0e2e57ce07ff3de6ac024627c1fb6ad30c2fde48/lib/pymoc/util/tool.py#L257-L270
grahambell/pymoc
lib/pymoc/util/tool.py
MOCTool.intersection
def intersection(self): """Compute the intersection with the given MOC. This command takes the name of a MOC file and forms the intersection of the running MOC with that file. :: pymoctool a.fits --intersection b.fits --output intersection.fits """ if self...
python
def intersection(self): """Compute the intersection with the given MOC. This command takes the name of a MOC file and forms the intersection of the running MOC with that file. :: pymoctool a.fits --intersection b.fits --output intersection.fits """ if self...
[ "def", "intersection", "(", "self", ")", ":", "if", "self", ".", "moc", "is", "None", ":", "raise", "CommandError", "(", "'No MOC information present for intersection'", ")", "filename", "=", "self", ".", "params", ".", "pop", "(", ")", "self", ".", "moc", ...
Compute the intersection with the given MOC. This command takes the name of a MOC file and forms the intersection of the running MOC with that file. :: pymoctool a.fits --intersection b.fits --output intersection.fits
[ "Compute", "the", "intersection", "with", "the", "given", "MOC", "." ]
train
https://github.com/grahambell/pymoc/blob/0e2e57ce07ff3de6ac024627c1fb6ad30c2fde48/lib/pymoc/util/tool.py#L273-L288
grahambell/pymoc
lib/pymoc/util/tool.py
MOCTool.name
def name(self): """Set the name of the current MOC. The new name should be given after this option. :: pymoctool ... --name 'New MOC name' --output new_moc.fits """ if self.moc is None: self.moc = MOC() self.moc.name = self.params.pop()
python
def name(self): """Set the name of the current MOC. The new name should be given after this option. :: pymoctool ... --name 'New MOC name' --output new_moc.fits """ if self.moc is None: self.moc = MOC() self.moc.name = self.params.pop()
[ "def", "name", "(", "self", ")", ":", "if", "self", ".", "moc", "is", "None", ":", "self", ".", "moc", "=", "MOC", "(", ")", "self", ".", "moc", ".", "name", "=", "self", ".", "params", ".", "pop", "(", ")" ]
Set the name of the current MOC. The new name should be given after this option. :: pymoctool ... --name 'New MOC name' --output new_moc.fits
[ "Set", "the", "name", "of", "the", "current", "MOC", "." ]
train
https://github.com/grahambell/pymoc/blob/0e2e57ce07ff3de6ac024627c1fb6ad30c2fde48/lib/pymoc/util/tool.py#L291-L304
grahambell/pymoc
lib/pymoc/util/tool.py
MOCTool.normalize
def normalize(self): """Normalize the MOC to a given order. This command takes a MOC order (0-29) and normalizes the MOC so that its maximum order is the given order. :: pymoctool a.fits --normalize 10 --output a_10.fits """ if self.moc is None: ...
python
def normalize(self): """Normalize the MOC to a given order. This command takes a MOC order (0-29) and normalizes the MOC so that its maximum order is the given order. :: pymoctool a.fits --normalize 10 --output a_10.fits """ if self.moc is None: ...
[ "def", "normalize", "(", "self", ")", ":", "if", "self", ".", "moc", "is", "None", ":", "raise", "CommandError", "(", "'No MOC information present for normalization'", ")", "order", "=", "int", "(", "self", ".", "params", ".", "pop", "(", ")", ")", "self",...
Normalize the MOC to a given order. This command takes a MOC order (0-29) and normalizes the MOC so that its maximum order is the given order. :: pymoctool a.fits --normalize 10 --output a_10.fits
[ "Normalize", "the", "MOC", "to", "a", "given", "order", "." ]
train
https://github.com/grahambell/pymoc/blob/0e2e57ce07ff3de6ac024627c1fb6ad30c2fde48/lib/pymoc/util/tool.py#L307-L322
grahambell/pymoc
lib/pymoc/util/tool.py
MOCTool.write_moc
def write_moc(self): """Write the MOC to a given file.""" if self.moc is None: raise CommandError('No MOC information present for output') filename = self.params.pop() self.moc.write(filename)
python
def write_moc(self): """Write the MOC to a given file.""" if self.moc is None: raise CommandError('No MOC information present for output') filename = self.params.pop() self.moc.write(filename)
[ "def", "write_moc", "(", "self", ")", ":", "if", "self", ".", "moc", "is", "None", ":", "raise", "CommandError", "(", "'No MOC information present for output'", ")", "filename", "=", "self", ".", "params", ".", "pop", "(", ")", "self", ".", "moc", ".", "...
Write the MOC to a given file.
[ "Write", "the", "MOC", "to", "a", "given", "file", "." ]
train
https://github.com/grahambell/pymoc/blob/0e2e57ce07ff3de6ac024627c1fb6ad30c2fde48/lib/pymoc/util/tool.py#L325-L332
grahambell/pymoc
lib/pymoc/util/tool.py
MOCTool.subtract
def subtract(self): """Subtract the given MOC from the running MOC. This command takes the name of a MOC file to be subtracted from the running MOC. :: pymoctool a.fits --subtract b.fits --output difference.fits """ if self.moc is None: raise C...
python
def subtract(self): """Subtract the given MOC from the running MOC. This command takes the name of a MOC file to be subtracted from the running MOC. :: pymoctool a.fits --subtract b.fits --output difference.fits """ if self.moc is None: raise C...
[ "def", "subtract", "(", "self", ")", ":", "if", "self", ".", "moc", "is", "None", ":", "raise", "CommandError", "(", "'No MOC information present for subtraction'", ")", "filename", "=", "self", ".", "params", ".", "pop", "(", ")", "self", ".", "moc", "-="...
Subtract the given MOC from the running MOC. This command takes the name of a MOC file to be subtracted from the running MOC. :: pymoctool a.fits --subtract b.fits --output difference.fits
[ "Subtract", "the", "given", "MOC", "from", "the", "running", "MOC", "." ]
train
https://github.com/grahambell/pymoc/blob/0e2e57ce07ff3de6ac024627c1fb6ad30c2fde48/lib/pymoc/util/tool.py#L335-L350
grahambell/pymoc
lib/pymoc/util/tool.py
MOCTool.plot
def plot(self): """Show the running MOC on an all-sky map. This command requires that the Healpy and matplotlib libraries be available. It plots the running MOC, which should be normalized to a lower order first if it would generate an excessively large pixel array. ::...
python
def plot(self): """Show the running MOC on an all-sky map. This command requires that the Healpy and matplotlib libraries be available. It plots the running MOC, which should be normalized to a lower order first if it would generate an excessively large pixel array. ::...
[ "def", "plot", "(", "self", ")", ":", "if", "self", ".", "moc", "is", "None", ":", "raise", "CommandError", "(", "'No MOC information present for plotting'", ")", "from", ".", "plot", "import", "plot_moc", "order", "=", "self", ".", "moc", ".", "order", "a...
Show the running MOC on an all-sky map. This command requires that the Healpy and matplotlib libraries be available. It plots the running MOC, which should be normalized to a lower order first if it would generate an excessively large pixel array. :: pymoctool a.m...
[ "Show", "the", "running", "MOC", "on", "an", "all", "-", "sky", "map", "." ]
train
https://github.com/grahambell/pymoc/blob/0e2e57ce07ff3de6ac024627c1fb6ad30c2fde48/lib/pymoc/util/tool.py#L353-L400
grahambell/pymoc
lib/pymoc/util/tool.py
MOCTool._split_docstring
def _split_docstring(self, docstring): """Separate a docstring into the synopsis (first line) and body.""" lines = docstring.strip().splitlines() synopsis = lines[0].strip() body = textwrap.dedent('\n'.join(lines[2:])) # Remove RST preformatted text markers. body = bod...
python
def _split_docstring(self, docstring): """Separate a docstring into the synopsis (first line) and body.""" lines = docstring.strip().splitlines() synopsis = lines[0].strip() body = textwrap.dedent('\n'.join(lines[2:])) # Remove RST preformatted text markers. body = bod...
[ "def", "_split_docstring", "(", "self", ",", "docstring", ")", ":", "lines", "=", "docstring", ".", "strip", "(", ")", ".", "splitlines", "(", ")", "synopsis", "=", "lines", "[", "0", "]", ".", "strip", "(", ")", "body", "=", "textwrap", ".", "dedent...
Separate a docstring into the synopsis (first line) and body.
[ "Separate", "a", "docstring", "into", "the", "synopsis", "(", "first", "line", ")", "and", "body", "." ]
train
https://github.com/grahambell/pymoc/blob/0e2e57ce07ff3de6ac024627c1fb6ad30c2fde48/lib/pymoc/util/tool.py#L408-L420
davisp/jsonical
jsonical.py
Encoder.default
def default(self, obj): """This is slightly different than json.JSONEncoder.default(obj) in that it should returned the serialized representation of the passed object, not a serializable representation. """ if isinstance(obj, (datetime.date, datetime.time, datetime.datetime)): ...
python
def default(self, obj): """This is slightly different than json.JSONEncoder.default(obj) in that it should returned the serialized representation of the passed object, not a serializable representation. """ if isinstance(obj, (datetime.date, datetime.time, datetime.datetime)): ...
[ "def", "default", "(", "self", ",", "obj", ")", ":", "if", "isinstance", "(", "obj", ",", "(", "datetime", ".", "date", ",", "datetime", ".", "time", ",", "datetime", ".", "datetime", ")", ")", ":", "return", "'\"%s\"'", "%", "obj", ".", "isoformat",...
This is slightly different than json.JSONEncoder.default(obj) in that it should returned the serialized representation of the passed object, not a serializable representation.
[ "This", "is", "slightly", "different", "than", "json", ".", "JSONEncoder", ".", "default", "(", "obj", ")", "in", "that", "it", "should", "returned", "the", "serialized", "representation", "of", "the", "passed", "object", "not", "a", "serializable", "represent...
train
https://github.com/davisp/jsonical/blob/e41b2bebeb53b1feebf0cf682b47c82cd019c2b3/jsonical.py#L64-L75
seung-lab/AnnotationEngine
synapse_example.py
load_synapses
def load_synapses(path=HOME + "/Downloads/pinky100_final.df", scaling=(1, 1, 1)): """ Test scenario using real synapses """ scaling = np.array(list(scaling)) df = pd.read_csv(path) locs = np.array(df[["presyn_x", "centroid_x", "postsyn_x"]]) mask = ~np.any(np.isnan(locs), axis=...
python
def load_synapses(path=HOME + "/Downloads/pinky100_final.df", scaling=(1, 1, 1)): """ Test scenario using real synapses """ scaling = np.array(list(scaling)) df = pd.read_csv(path) locs = np.array(df[["presyn_x", "centroid_x", "postsyn_x"]]) mask = ~np.any(np.isnan(locs), axis=...
[ "def", "load_synapses", "(", "path", "=", "HOME", "+", "\"/Downloads/pinky100_final.df\"", ",", "scaling", "=", "(", "1", ",", "1", ",", "1", ")", ")", ":", "scaling", "=", "np", ".", "array", "(", "list", "(", "scaling", ")", ")", "df", "=", "pd", ...
Test scenario using real synapses
[ "Test", "scenario", "using", "real", "synapses" ]
train
https://github.com/seung-lab/AnnotationEngine/blob/9819b4df83c748503b4195739a83a13bcfc00f52/synapse_example.py#L12-L32
Clinical-Genomics/housekeeper
housekeeper/cli/include.py
include
def include(context, bundle_name, version): """Include a bundle of files into the internal space. Use bundle name if you simply want to inlcude the latest version. """ store = Store(context.obj['database'], context.obj['root']) if version: version_obj = store.Version.get(version) if...
python
def include(context, bundle_name, version): """Include a bundle of files into the internal space. Use bundle name if you simply want to inlcude the latest version. """ store = Store(context.obj['database'], context.obj['root']) if version: version_obj = store.Version.get(version) if...
[ "def", "include", "(", "context", ",", "bundle_name", ",", "version", ")", ":", "store", "=", "Store", "(", "context", ".", "obj", "[", "'database'", "]", ",", "context", ".", "obj", "[", "'root'", "]", ")", "if", "version", ":", "version_obj", "=", ...
Include a bundle of files into the internal space. Use bundle name if you simply want to inlcude the latest version.
[ "Include", "a", "bundle", "of", "files", "into", "the", "internal", "space", "." ]
train
https://github.com/Clinical-Genomics/housekeeper/blob/a7d10d327dc9f06274bdef5504ed1b9413f2c8c1/housekeeper/cli/include.py#L15-L39
mayfield/syndicate
syndicate/client.py
Service.ingress_filter
def ingress_filter(self, response): """ Flatten a response with meta and data keys into an object. """ data = self.data_getter(response) if isinstance(data, dict): data = m_data.DictResponse(data) elif isinstance(data, list): data = m_data.ListResponse(data) ...
python
def ingress_filter(self, response): """ Flatten a response with meta and data keys into an object. """ data = self.data_getter(response) if isinstance(data, dict): data = m_data.DictResponse(data) elif isinstance(data, list): data = m_data.ListResponse(data) ...
[ "def", "ingress_filter", "(", "self", ",", "response", ")", ":", "data", "=", "self", ".", "data_getter", "(", "response", ")", "if", "isinstance", "(", "data", ",", "dict", ")", ":", "data", "=", "m_data", ".", "DictResponse", "(", "data", ")", "elif"...
Flatten a response with meta and data keys into an object.
[ "Flatten", "a", "response", "with", "meta", "and", "data", "keys", "into", "an", "object", "." ]
train
https://github.com/mayfield/syndicate/blob/917af976dacb7377bdf0cb616f47e0df5afaff1a/syndicate/client.py#L86-L96
mayfield/syndicate
syndicate/client.py
Service.get_pager
def get_pager(self, *path, **kwargs): """ A generator for all the results a resource can provide. The pages are lazily loaded. """ page_arg = kwargs.pop('page_size', None) limit_arg = kwargs.pop('limit', None) kwargs['limit'] = page_arg or limit_arg or self.default_page_size ...
python
def get_pager(self, *path, **kwargs): """ A generator for all the results a resource can provide. The pages are lazily loaded. """ page_arg = kwargs.pop('page_size', None) limit_arg = kwargs.pop('limit', None) kwargs['limit'] = page_arg or limit_arg or self.default_page_size ...
[ "def", "get_pager", "(", "self", ",", "*", "path", ",", "*", "*", "kwargs", ")", ":", "page_arg", "=", "kwargs", ".", "pop", "(", "'page_size'", ",", "None", ")", "limit_arg", "=", "kwargs", ".", "pop", "(", "'limit'", ",", "None", ")", "kwargs", "...
A generator for all the results a resource can provide. The pages are lazily loaded.
[ "A", "generator", "for", "all", "the", "results", "a", "resource", "can", "provide", ".", "The", "pages", "are", "lazily", "loaded", "." ]
train
https://github.com/mayfield/syndicate/blob/917af976dacb7377bdf0cb616f47e0df5afaff1a/syndicate/client.py#L114-L120
jelmer/python-fastimport
fastimport/reftracker.py
RefTracker.track_heads
def track_heads(self, cmd): """Track the repository heads given a CommitCommand. :param cmd: the CommitCommand :return: the list of parents in terms of commit-ids """ # Get the true set of parents if cmd.from_ is not None: parents = [cmd.from_] else: ...
python
def track_heads(self, cmd): """Track the repository heads given a CommitCommand. :param cmd: the CommitCommand :return: the list of parents in terms of commit-ids """ # Get the true set of parents if cmd.from_ is not None: parents = [cmd.from_] else: ...
[ "def", "track_heads", "(", "self", ",", "cmd", ")", ":", "# Get the true set of parents", "if", "cmd", ".", "from_", "is", "not", "None", ":", "parents", "=", "[", "cmd", ".", "from_", "]", "else", ":", "last_id", "=", "self", ".", "last_ids", ".", "ge...
Track the repository heads given a CommitCommand. :param cmd: the CommitCommand :return: the list of parents in terms of commit-ids
[ "Track", "the", "repository", "heads", "given", "a", "CommitCommand", "." ]
train
https://github.com/jelmer/python-fastimport/blob/5cef9e037b7d7b37f58f522ac9ea4e343e6a1dff/fastimport/reftracker.py#L38-L57
sgillies/rio-plugin-example
metasay/scripts/cli.py
metasay
def metasay(ctx, inputfile, item): """Moo some dataset metadata to stdout. Python module: rio-metasay (https://github.com/sgillies/rio-plugin-example). """ with rasterio.open(inputfile) as src: meta = src.profile click.echo(moothedata(meta, key=item))
python
def metasay(ctx, inputfile, item): """Moo some dataset metadata to stdout. Python module: rio-metasay (https://github.com/sgillies/rio-plugin-example). """ with rasterio.open(inputfile) as src: meta = src.profile click.echo(moothedata(meta, key=item))
[ "def", "metasay", "(", "ctx", ",", "inputfile", ",", "item", ")", ":", "with", "rasterio", ".", "open", "(", "inputfile", ")", "as", "src", ":", "meta", "=", "src", ".", "profile", "click", ".", "echo", "(", "moothedata", "(", "meta", ",", "key", "...
Moo some dataset metadata to stdout. Python module: rio-metasay (https://github.com/sgillies/rio-plugin-example).
[ "Moo", "some", "dataset", "metadata", "to", "stdout", "." ]
train
https://github.com/sgillies/rio-plugin-example/blob/31e7383e9f0ee7d7fc07d3ba4f2fe2a1602c9579/metasay/scripts/cli.py#L18-L26
isambard-uob/ampal
src/ampal/pdb_parser.py
load_pdb
def load_pdb(pdb, path=True, pdb_id='', ignore_end=False): """Converts a PDB file into an AMPAL object. Parameters ---------- pdb : str Either a path to a PDB file or a string containing PDB format structural data. path : bool, optional If `true`, flags `pdb` as a path and n...
python
def load_pdb(pdb, path=True, pdb_id='', ignore_end=False): """Converts a PDB file into an AMPAL object. Parameters ---------- pdb : str Either a path to a PDB file or a string containing PDB format structural data. path : bool, optional If `true`, flags `pdb` as a path and n...
[ "def", "load_pdb", "(", "pdb", ",", "path", "=", "True", ",", "pdb_id", "=", "''", ",", "ignore_end", "=", "False", ")", ":", "pdb_p", "=", "PdbParser", "(", "pdb", ",", "path", "=", "path", ",", "pdb_id", "=", "pdb_id", ",", "ignore_end", "=", "ig...
Converts a PDB file into an AMPAL object. Parameters ---------- pdb : str Either a path to a PDB file or a string containing PDB format structural data. path : bool, optional If `true`, flags `pdb` as a path and not a PDB string. pdb_id : str, optional Identifier for...
[ "Converts", "a", "PDB", "file", "into", "an", "AMPAL", "object", "." ]
train
https://github.com/isambard-uob/ampal/blob/906e2afacb435ffb129b381f262ff8e7bfb324c5/src/ampal/pdb_parser.py#L16-L41
isambard-uob/ampal
src/ampal/pdb_parser.py
PdbParser.proc_line_coordinate
def proc_line_coordinate(self, line): """Extracts data from columns in ATOM/HETATM record.""" at_type = line[0:6].strip() # 0 at_ser = int(line[6:11].strip()) # 1 at_name = line[12:16].strip() # 2 alt_loc = line[16].strip() # 3 res_name = line[17:20].strip() # 4 ...
python
def proc_line_coordinate(self, line): """Extracts data from columns in ATOM/HETATM record.""" at_type = line[0:6].strip() # 0 at_ser = int(line[6:11].strip()) # 1 at_name = line[12:16].strip() # 2 alt_loc = line[16].strip() # 3 res_name = line[17:20].strip() # 4 ...
[ "def", "proc_line_coordinate", "(", "self", ",", "line", ")", ":", "at_type", "=", "line", "[", "0", ":", "6", "]", ".", "strip", "(", ")", "# 0", "at_ser", "=", "int", "(", "line", "[", "6", ":", "11", "]", ".", "strip", "(", ")", ")", "# 1", ...
Extracts data from columns in ATOM/HETATM record.
[ "Extracts", "data", "from", "columns", "in", "ATOM", "/", "HETATM", "record", "." ]
train
https://github.com/isambard-uob/ampal/blob/906e2afacb435ffb129b381f262ff8e7bfb324c5/src/ampal/pdb_parser.py#L171-L192
isambard-uob/ampal
src/ampal/pdb_parser.py
PdbParser.gen_states
def gen_states(self, monomer_data, parent): """Generates the `states` dictionary for a `Monomer`. monomer_data : list A list of atom data parsed from the input PDB. parent : ampal.Monomer `Monomer` used to assign `parent` on created `Atoms`. """ ...
python
def gen_states(self, monomer_data, parent): """Generates the `states` dictionary for a `Monomer`. monomer_data : list A list of atom data parsed from the input PDB. parent : ampal.Monomer `Monomer` used to assign `parent` on created `Atoms`. """ ...
[ "def", "gen_states", "(", "self", ",", "monomer_data", ",", "parent", ")", ":", "states", "=", "{", "}", "for", "atoms", "in", "monomer_data", ":", "for", "atom", "in", "atoms", ":", "state", "=", "'A'", "if", "not", "atom", "[", "3", "]", "else", ...
Generates the `states` dictionary for a `Monomer`. monomer_data : list A list of atom data parsed from the input PDB. parent : ampal.Monomer `Monomer` used to assign `parent` on created `Atoms`.
[ "Generates", "the", "states", "dictionary", "for", "a", "Monomer", "." ]
train
https://github.com/isambard-uob/ampal/blob/906e2afacb435ffb129b381f262ff8e7bfb324c5/src/ampal/pdb_parser.py#L344-L383
isambard-uob/ampal
src/ampal/pdb_parser.py
PdbParser.check_for_non_canonical
def check_for_non_canonical(residue): """Checks to see if the residue is non-canonical.""" res_label = list(residue[0])[0][2] atom_labels = {x[2] for x in itertools.chain( *residue[1].values())} # Used to find unnatural aas if (all(x in atom_labels for x in ['N', 'CA', 'C', ...
python
def check_for_non_canonical(residue): """Checks to see if the residue is non-canonical.""" res_label = list(residue[0])[0][2] atom_labels = {x[2] for x in itertools.chain( *residue[1].values())} # Used to find unnatural aas if (all(x in atom_labels for x in ['N', 'CA', 'C', ...
[ "def", "check_for_non_canonical", "(", "residue", ")", ":", "res_label", "=", "list", "(", "residue", "[", "0", "]", ")", "[", "0", "]", "[", "2", "]", "atom_labels", "=", "{", "x", "[", "2", "]", "for", "x", "in", "itertools", ".", "chain", "(", ...
Checks to see if the residue is non-canonical.
[ "Checks", "to", "see", "if", "the", "residue", "is", "non", "-", "canonical", "." ]
train
https://github.com/isambard-uob/ampal/blob/906e2afacb435ffb129b381f262ff8e7bfb324c5/src/ampal/pdb_parser.py#L387-L395
robertpeteuil/aws-shortcuts
awss/awsc.py
get_inst_info
def get_inst_info(qry_string): """Get details for instances that match the qry_string. Execute a query against the AWS EC2 client object, that is based on the contents of qry_string. Args: qry_string (str): the query to be used against the aws ec2 client. Returns: qry_results (dict...
python
def get_inst_info(qry_string): """Get details for instances that match the qry_string. Execute a query against the AWS EC2 client object, that is based on the contents of qry_string. Args: qry_string (str): the query to be used against the aws ec2 client. Returns: qry_results (dict...
[ "def", "get_inst_info", "(", "qry_string", ")", ":", "qry_prefix", "=", "\"EC2C.describe_instances(\"", "qry_real", "=", "qry_prefix", "+", "qry_string", "+", "\")\"", "qry_results", "=", "eval", "(", "qry_real", ")", "# pylint: disable=eval-used", "return", "qry_resu...
Get details for instances that match the qry_string. Execute a query against the AWS EC2 client object, that is based on the contents of qry_string. Args: qry_string (str): the query to be used against the aws ec2 client. Returns: qry_results (dict): raw information returned from AWS.
[ "Get", "details", "for", "instances", "that", "match", "the", "qry_string", "." ]
train
https://github.com/robertpeteuil/aws-shortcuts/blob/cf453ca996978a4d88015d1cf6125bce8ca4873b/awss/awsc.py#L53-L68