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 |
|---|---|---|---|---|---|---|---|---|---|---|
OCR-D/core | ocrd_models/ocrd_models/ocrd_mets.py | OcrdMets.unique_identifier | def unique_identifier(self, purl):
"""
Set the unique identifier by looking through ``mods:identifier``
See `specs <https://ocr-d.github.io/mets#unique-id-for-the-document-processed>`_ for details.
"""
id_el = None
for t in IDENTIFIER_PRIORITY:
id_el = self._... | python | def unique_identifier(self, purl):
"""
Set the unique identifier by looking through ``mods:identifier``
See `specs <https://ocr-d.github.io/mets#unique-id-for-the-document-processed>`_ for details.
"""
id_el = None
for t in IDENTIFIER_PRIORITY:
id_el = self._... | [
"def",
"unique_identifier",
"(",
"self",
",",
"purl",
")",
":",
"id_el",
"=",
"None",
"for",
"t",
"in",
"IDENTIFIER_PRIORITY",
":",
"id_el",
"=",
"self",
".",
"_tree",
".",
"getroot",
"(",
")",
".",
"find",
"(",
"'.//mods:identifier[@type=\"%s\"]'",
"%",
"... | Set the unique identifier by looking through ``mods:identifier``
See `specs <https://ocr-d.github.io/mets#unique-id-for-the-document-processed>`_ for details. | [
"Set",
"the",
"unique",
"identifier",
"by",
"looking",
"through",
"mods",
":",
"identifier"
] | train | https://github.com/OCR-D/core/blob/57e68c578526cb955fd2e368207f5386c459d91d/ocrd_models/ocrd_models/ocrd_mets.py#L72-L87 |
OCR-D/core | ocrd_models/ocrd_models/ocrd_mets.py | OcrdMets.agents | def agents(self):
"""
List all `OcrdAgent </../../ocrd_models/ocrd_models.ocrd_agent.html>`_
"""
return [OcrdAgent(el_agent) for el_agent in self._tree.getroot().findall('mets:metsHdr/mets:agent', NS)] | python | def agents(self):
"""
List all `OcrdAgent </../../ocrd_models/ocrd_models.ocrd_agent.html>`_
"""
return [OcrdAgent(el_agent) for el_agent in self._tree.getroot().findall('mets:metsHdr/mets:agent', NS)] | [
"def",
"agents",
"(",
"self",
")",
":",
"return",
"[",
"OcrdAgent",
"(",
"el_agent",
")",
"for",
"el_agent",
"in",
"self",
".",
"_tree",
".",
"getroot",
"(",
")",
".",
"findall",
"(",
"'mets:metsHdr/mets:agent'",
",",
"NS",
")",
"]"
] | List all `OcrdAgent </../../ocrd_models/ocrd_models.ocrd_agent.html>`_ | [
"List",
"all",
"OcrdAgent",
"<",
"/",
"..",
"/",
"..",
"/",
"ocrd_models",
"/",
"ocrd_models",
".",
"ocrd_agent",
".",
"html",
">",
"_"
] | train | https://github.com/OCR-D/core/blob/57e68c578526cb955fd2e368207f5386c459d91d/ocrd_models/ocrd_models/ocrd_mets.py#L90-L94 |
OCR-D/core | ocrd_models/ocrd_models/ocrd_mets.py | OcrdMets.add_agent | def add_agent(self, *args, **kwargs):
"""
Add an `OcrdAgent </../../ocrd_models/ocrd_models.ocrd_agent.html>`_ to the list of agents in the metsHdr.
"""
el_metsHdr = self._tree.getroot().find('.//mets:metsHdr', NS)
if el_metsHdr is None:
el_metsHdr = ET.Element(TAG_ME... | python | def add_agent(self, *args, **kwargs):
"""
Add an `OcrdAgent </../../ocrd_models/ocrd_models.ocrd_agent.html>`_ to the list of agents in the metsHdr.
"""
el_metsHdr = self._tree.getroot().find('.//mets:metsHdr', NS)
if el_metsHdr is None:
el_metsHdr = ET.Element(TAG_ME... | [
"def",
"add_agent",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"el_metsHdr",
"=",
"self",
".",
"_tree",
".",
"getroot",
"(",
")",
".",
"find",
"(",
"'.//mets:metsHdr'",
",",
"NS",
")",
"if",
"el_metsHdr",
"is",
"None",
":",
"... | Add an `OcrdAgent </../../ocrd_models/ocrd_models.ocrd_agent.html>`_ to the list of agents in the metsHdr. | [
"Add",
"an",
"OcrdAgent",
"<",
"/",
"..",
"/",
"..",
"/",
"ocrd_models",
"/",
"ocrd_models",
".",
"ocrd_agent",
".",
"html",
">",
"_",
"to",
"the",
"list",
"of",
"agents",
"in",
"the",
"metsHdr",
"."
] | train | https://github.com/OCR-D/core/blob/57e68c578526cb955fd2e368207f5386c459d91d/ocrd_models/ocrd_models/ocrd_mets.py#L96-L107 |
OCR-D/core | ocrd_models/ocrd_models/ocrd_mets.py | OcrdMets.file_groups | def file_groups(self):
"""
List the ``USE`` attributes of all ``mets:fileGrp``.
"""
return [el.get('USE') for el in self._tree.getroot().findall('.//mets:fileGrp', NS)] | python | def file_groups(self):
"""
List the ``USE`` attributes of all ``mets:fileGrp``.
"""
return [el.get('USE') for el in self._tree.getroot().findall('.//mets:fileGrp', NS)] | [
"def",
"file_groups",
"(",
"self",
")",
":",
"return",
"[",
"el",
".",
"get",
"(",
"'USE'",
")",
"for",
"el",
"in",
"self",
".",
"_tree",
".",
"getroot",
"(",
")",
".",
"findall",
"(",
"'.//mets:fileGrp'",
",",
"NS",
")",
"]"
] | List the ``USE`` attributes of all ``mets:fileGrp``. | [
"List",
"the",
"USE",
"attributes",
"of",
"all",
"mets",
":",
"fileGrp",
"."
] | train | https://github.com/OCR-D/core/blob/57e68c578526cb955fd2e368207f5386c459d91d/ocrd_models/ocrd_models/ocrd_mets.py#L110-L114 |
OCR-D/core | ocrd_models/ocrd_models/ocrd_mets.py | OcrdMets.find_files | def find_files(self, ID=None, fileGrp=None, pageId=None, mimetype=None, url=None, local_only=False):
"""
Search ``mets:file`` in this METS document.
Args:
ID (string) : ID of the file
fileGrp (string) : USE of the fileGrp to list files of
pageId (string) : ID... | python | def find_files(self, ID=None, fileGrp=None, pageId=None, mimetype=None, url=None, local_only=False):
"""
Search ``mets:file`` in this METS document.
Args:
ID (string) : ID of the file
fileGrp (string) : USE of the fileGrp to list files of
pageId (string) : ID... | [
"def",
"find_files",
"(",
"self",
",",
"ID",
"=",
"None",
",",
"fileGrp",
"=",
"None",
",",
"pageId",
"=",
"None",
",",
"mimetype",
"=",
"None",
",",
"url",
"=",
"None",
",",
"local_only",
"=",
"False",
")",
":",
"ret",
"=",
"[",
"]",
"fileGrp_clau... | Search ``mets:file`` in this METS document.
Args:
ID (string) : ID of the file
fileGrp (string) : USE of the fileGrp to list files of
pageId (string) : ID of physical page manifested by matching files
url (string) : @xlink:href of mets:Flocat of mets:file
... | [
"Search",
"mets",
":",
"file",
"in",
"this",
"METS",
"document",
"."
] | train | https://github.com/OCR-D/core/blob/57e68c578526cb955fd2e368207f5386c459d91d/ocrd_models/ocrd_models/ocrd_mets.py#L116-L162 |
OCR-D/core | ocrd_models/ocrd_models/ocrd_mets.py | OcrdMets.add_file_group | def add_file_group(self, fileGrp):
"""
Add a new ``mets:fileGrp``.
Arguments:
fileGrp (string): ``USE`` attribute of the new filegroup.
"""
el_fileSec = self._tree.getroot().find('mets:fileSec', NS)
if el_fileSec is None:
el_fileSec = ET.SubElemen... | python | def add_file_group(self, fileGrp):
"""
Add a new ``mets:fileGrp``.
Arguments:
fileGrp (string): ``USE`` attribute of the new filegroup.
"""
el_fileSec = self._tree.getroot().find('mets:fileSec', NS)
if el_fileSec is None:
el_fileSec = ET.SubElemen... | [
"def",
"add_file_group",
"(",
"self",
",",
"fileGrp",
")",
":",
"el_fileSec",
"=",
"self",
".",
"_tree",
".",
"getroot",
"(",
")",
".",
"find",
"(",
"'mets:fileSec'",
",",
"NS",
")",
"if",
"el_fileSec",
"is",
"None",
":",
"el_fileSec",
"=",
"ET",
".",
... | Add a new ``mets:fileGrp``.
Arguments:
fileGrp (string): ``USE`` attribute of the new filegroup. | [
"Add",
"a",
"new",
"mets",
":",
"fileGrp",
"."
] | train | https://github.com/OCR-D/core/blob/57e68c578526cb955fd2e368207f5386c459d91d/ocrd_models/ocrd_models/ocrd_mets.py#L164-L178 |
OCR-D/core | ocrd_models/ocrd_models/ocrd_mets.py | OcrdMets.add_file | def add_file(self, fileGrp, mimetype=None, url=None, ID=None, pageId=None, force=False, local_filename=None, **kwargs):
"""
Add a `OcrdFile </../../ocrd_models/ocrd_models.ocrd_file.html>`_.
Arguments:
fileGrp (string): Add file to ``mets:fileGrp`` with this ``USE`` attribute
... | python | def add_file(self, fileGrp, mimetype=None, url=None, ID=None, pageId=None, force=False, local_filename=None, **kwargs):
"""
Add a `OcrdFile </../../ocrd_models/ocrd_models.ocrd_file.html>`_.
Arguments:
fileGrp (string): Add file to ``mets:fileGrp`` with this ``USE`` attribute
... | [
"def",
"add_file",
"(",
"self",
",",
"fileGrp",
",",
"mimetype",
"=",
"None",
",",
"url",
"=",
"None",
",",
"ID",
"=",
"None",
",",
"pageId",
"=",
"None",
",",
"force",
"=",
"False",
",",
"local_filename",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",... | Add a `OcrdFile </../../ocrd_models/ocrd_models.ocrd_file.html>`_.
Arguments:
fileGrp (string): Add file to ``mets:fileGrp`` with this ``USE`` attribute
mimetype (string):
url (string):
ID (string):
pageId (string):
force (boolean): Whethe... | [
"Add",
"a",
"OcrdFile",
"<",
"/",
"..",
"/",
"..",
"/",
"ocrd_models",
"/",
"ocrd_models",
".",
"ocrd_file",
".",
"html",
">",
"_",
"."
] | train | https://github.com/OCR-D/core/blob/57e68c578526cb955fd2e368207f5386c459d91d/ocrd_models/ocrd_models/ocrd_mets.py#L180-L213 |
OCR-D/core | ocrd_models/ocrd_models/ocrd_mets.py | OcrdMets.set_physical_page_for_file | def set_physical_page_for_file(self, pageId, ocrd_file, order=None, orderlabel=None):
"""
Create a new physical page
"""
# print(pageId, ocrd_file)
# delete any page mapping for this file.ID
for el_fptr in self._tree.getroot().findall(
'mets:structMap[@TY... | python | def set_physical_page_for_file(self, pageId, ocrd_file, order=None, orderlabel=None):
"""
Create a new physical page
"""
# print(pageId, ocrd_file)
# delete any page mapping for this file.ID
for el_fptr in self._tree.getroot().findall(
'mets:structMap[@TY... | [
"def",
"set_physical_page_for_file",
"(",
"self",
",",
"pageId",
",",
"ocrd_file",
",",
"order",
"=",
"None",
",",
"orderlabel",
"=",
"None",
")",
":",
"# print(pageId, ocrd_file)",
"# delete any page mapping for this file.ID",
"for",
"el_fptr",
"in",
"self",
".",
... | Create a new physical page | [
"Create",
"a",
"new",
"physical",
"page"
] | train | https://github.com/OCR-D/core/blob/57e68c578526cb955fd2e368207f5386c459d91d/ocrd_models/ocrd_models/ocrd_mets.py#L224-L254 |
OCR-D/core | ocrd_models/ocrd_models/ocrd_mets.py | OcrdMets.get_physical_page_for_file | def get_physical_page_for_file(self, ocrd_file):
"""
Get the pageId for a ocrd_file
"""
ret = self._tree.getroot().xpath(
'/mets:mets/mets:structMap[@TYPE="PHYSICAL"]/mets:div[@TYPE="physSequence"]/mets:div[@TYPE="page"][./mets:fptr[@FILEID="%s"]]/@ID' %
ocrd_file... | python | def get_physical_page_for_file(self, ocrd_file):
"""
Get the pageId for a ocrd_file
"""
ret = self._tree.getroot().xpath(
'/mets:mets/mets:structMap[@TYPE="PHYSICAL"]/mets:div[@TYPE="physSequence"]/mets:div[@TYPE="page"][./mets:fptr[@FILEID="%s"]]/@ID' %
ocrd_file... | [
"def",
"get_physical_page_for_file",
"(",
"self",
",",
"ocrd_file",
")",
":",
"ret",
"=",
"self",
".",
"_tree",
".",
"getroot",
"(",
")",
".",
"xpath",
"(",
"'/mets:mets/mets:structMap[@TYPE=\"PHYSICAL\"]/mets:div[@TYPE=\"physSequence\"]/mets:div[@TYPE=\"page\"][./mets:fptr[@... | Get the pageId for a ocrd_file | [
"Get",
"the",
"pageId",
"for",
"a",
"ocrd_file"
] | train | https://github.com/OCR-D/core/blob/57e68c578526cb955fd2e368207f5386c459d91d/ocrd_models/ocrd_models/ocrd_mets.py#L256-L264 |
OCR-D/core | ocrd_validators/ocrd_validators/workspace_validator.py | WorkspaceValidator._validate | def _validate(self):
"""
Actual validation.
"""
try:
self._resolve_workspace()
if 'mets_unique_identifier' not in self.skip:
self._validate_mets_unique_identifier()
if 'mets_file_group_names' not in self.skip:
self._vali... | python | def _validate(self):
"""
Actual validation.
"""
try:
self._resolve_workspace()
if 'mets_unique_identifier' not in self.skip:
self._validate_mets_unique_identifier()
if 'mets_file_group_names' not in self.skip:
self._vali... | [
"def",
"_validate",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"_resolve_workspace",
"(",
")",
"if",
"'mets_unique_identifier'",
"not",
"in",
"self",
".",
"skip",
":",
"self",
".",
"_validate_mets_unique_identifier",
"(",
")",
"if",
"'mets_file_group_names'... | Actual validation. | [
"Actual",
"validation",
"."
] | train | https://github.com/OCR-D/core/blob/57e68c578526cb955fd2e368207f5386c459d91d/ocrd_validators/ocrd_validators/workspace_validator.py#L66-L85 |
OCR-D/core | ocrd_validators/ocrd_validators/workspace_validator.py | WorkspaceValidator._resolve_workspace | def _resolve_workspace(self):
"""
Clone workspace from mets_url unless workspace was provided.
"""
if self.workspace is None:
self.workspace = self.resolver.workspace_from_url(self.mets_url, baseurl=self.src_dir, download=self.download)
self.mets = self.workspace.... | python | def _resolve_workspace(self):
"""
Clone workspace from mets_url unless workspace was provided.
"""
if self.workspace is None:
self.workspace = self.resolver.workspace_from_url(self.mets_url, baseurl=self.src_dir, download=self.download)
self.mets = self.workspace.... | [
"def",
"_resolve_workspace",
"(",
"self",
")",
":",
"if",
"self",
".",
"workspace",
"is",
"None",
":",
"self",
".",
"workspace",
"=",
"self",
".",
"resolver",
".",
"workspace_from_url",
"(",
"self",
".",
"mets_url",
",",
"baseurl",
"=",
"self",
".",
"src... | Clone workspace from mets_url unless workspace was provided. | [
"Clone",
"workspace",
"from",
"mets_url",
"unless",
"workspace",
"was",
"provided",
"."
] | train | https://github.com/OCR-D/core/blob/57e68c578526cb955fd2e368207f5386c459d91d/ocrd_validators/ocrd_validators/workspace_validator.py#L87-L93 |
OCR-D/core | ocrd_validators/ocrd_validators/workspace_validator.py | WorkspaceValidator._validate_pixel_density | def _validate_pixel_density(self):
"""
Validate image pixel density
See `spec <https://ocr-d.github.io/mets#pixel-density-of-images-must-be-explicit-and-high-enough>`_.
"""
for f in [f for f in self.mets.find_files() if f.mimetype.startswith('image/')]:
if not f.loca... | python | def _validate_pixel_density(self):
"""
Validate image pixel density
See `spec <https://ocr-d.github.io/mets#pixel-density-of-images-must-be-explicit-and-high-enough>`_.
"""
for f in [f for f in self.mets.find_files() if f.mimetype.startswith('image/')]:
if not f.loca... | [
"def",
"_validate_pixel_density",
"(",
"self",
")",
":",
"for",
"f",
"in",
"[",
"f",
"for",
"f",
"in",
"self",
".",
"mets",
".",
"find_files",
"(",
")",
"if",
"f",
".",
"mimetype",
".",
"startswith",
"(",
"'image/'",
")",
"]",
":",
"if",
"not",
"f"... | Validate image pixel density
See `spec <https://ocr-d.github.io/mets#pixel-density-of-images-must-be-explicit-and-high-enough>`_. | [
"Validate",
"image",
"pixel",
"density"
] | train | https://github.com/OCR-D/core/blob/57e68c578526cb955fd2e368207f5386c459d91d/ocrd_validators/ocrd_validators/workspace_validator.py#L104-L118 |
OCR-D/core | ocrd_validators/ocrd_validators/workspace_validator.py | WorkspaceValidator._validate_mets_file_group_names | def _validate_mets_file_group_names(self):
"""
Ensure ``USE`` attributes of ``mets:fileGrp`` conform to OCR-D naming schema..
See `spec <https://ocr-d.github.io/mets#file-group-use-syntax>`_.
"""
for fileGrp in self.mets.file_groups:
if not fileGrp.startswith(FILE_GR... | python | def _validate_mets_file_group_names(self):
"""
Ensure ``USE`` attributes of ``mets:fileGrp`` conform to OCR-D naming schema..
See `spec <https://ocr-d.github.io/mets#file-group-use-syntax>`_.
"""
for fileGrp in self.mets.file_groups:
if not fileGrp.startswith(FILE_GR... | [
"def",
"_validate_mets_file_group_names",
"(",
"self",
")",
":",
"for",
"fileGrp",
"in",
"self",
".",
"mets",
".",
"file_groups",
":",
"if",
"not",
"fileGrp",
".",
"startswith",
"(",
"FILE_GROUP_PREFIX",
")",
":",
"self",
".",
"report",
".",
"add_notice",
"(... | Ensure ``USE`` attributes of ``mets:fileGrp`` conform to OCR-D naming schema..
See `spec <https://ocr-d.github.io/mets#file-group-use-syntax>`_. | [
"Ensure",
"USE",
"attributes",
"of",
"mets",
":",
"fileGrp",
"conform",
"to",
"OCR",
"-",
"D",
"naming",
"schema",
".."
] | train | https://github.com/OCR-D/core/blob/57e68c578526cb955fd2e368207f5386c459d91d/ocrd_validators/ocrd_validators/workspace_validator.py#L120-L142 |
OCR-D/core | ocrd_validators/ocrd_validators/workspace_validator.py | WorkspaceValidator._validate_mets_files | def _validate_mets_files(self):
"""
Validate ``mets:file`` URLs are sane.
"""
if not self.mets.find_files():
self.report.add_error("No files")
for f in self.mets.find_files():
if f._el.get('GROUPID'): # pylint: disable=protected-access
self... | python | def _validate_mets_files(self):
"""
Validate ``mets:file`` URLs are sane.
"""
if not self.mets.find_files():
self.report.add_error("No files")
for f in self.mets.find_files():
if f._el.get('GROUPID'): # pylint: disable=protected-access
self... | [
"def",
"_validate_mets_files",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"mets",
".",
"find_files",
"(",
")",
":",
"self",
".",
"report",
".",
"add_error",
"(",
"\"No files\"",
")",
"for",
"f",
"in",
"self",
".",
"mets",
".",
"find_files",
"(",
... | Validate ``mets:file`` URLs are sane. | [
"Validate",
"mets",
":",
"file",
"URLs",
"are",
"sane",
"."
] | train | https://github.com/OCR-D/core/blob/57e68c578526cb955fd2e368207f5386c459d91d/ocrd_validators/ocrd_validators/workspace_validator.py#L144-L160 |
OCR-D/core | ocrd_validators/ocrd_validators/workspace_validator.py | WorkspaceValidator._validate_page | def _validate_page(self):
"""
Run PageValidator on the PAGE-XML documents referenced in the METS.
"""
for ocrd_file in self.mets.find_files(mimetype=MIMETYPE_PAGE, local_only=True):
self.workspace.download_file(ocrd_file)
page_report = PageValidator.validate(ocrd_... | python | def _validate_page(self):
"""
Run PageValidator on the PAGE-XML documents referenced in the METS.
"""
for ocrd_file in self.mets.find_files(mimetype=MIMETYPE_PAGE, local_only=True):
self.workspace.download_file(ocrd_file)
page_report = PageValidator.validate(ocrd_... | [
"def",
"_validate_page",
"(",
"self",
")",
":",
"for",
"ocrd_file",
"in",
"self",
".",
"mets",
".",
"find_files",
"(",
"mimetype",
"=",
"MIMETYPE_PAGE",
",",
"local_only",
"=",
"True",
")",
":",
"self",
".",
"workspace",
".",
"download_file",
"(",
"ocrd_fi... | Run PageValidator on the PAGE-XML documents referenced in the METS. | [
"Run",
"PageValidator",
"on",
"the",
"PAGE",
"-",
"XML",
"documents",
"referenced",
"in",
"the",
"METS",
"."
] | train | https://github.com/OCR-D/core/blob/57e68c578526cb955fd2e368207f5386c459d91d/ocrd_validators/ocrd_validators/workspace_validator.py#L162-L169 |
shtalinberg/django-actions-logger | actionslog/models.py | LogActionManager.create_log_action | def create_log_action(self, **kwargs):
"""
Helper method to create a new log entry.
This method automatically populates some fields when no explicit value is given.
:param instance: The model instance to log a change for.
:type instance: Model
:param kwargs: Field overrid... | python | def create_log_action(self, **kwargs):
"""
Helper method to create a new log entry.
This method automatically populates some fields when no explicit value is given.
:param instance: The model instance to log a change for.
:type instance: Model
:param kwargs: Field overrid... | [
"def",
"create_log_action",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"instance",
"=",
"kwargs",
".",
"get",
"(",
"'instance'",
",",
"None",
")",
"if",
"instance",
"is",
"not",
"None",
":",
"del",
"kwargs",
"[",
"'instance'",
"]",
"request",
"=",... | Helper method to create a new log entry.
This method automatically populates some fields when no explicit value is given.
:param instance: The model instance to log a change for.
:type instance: Model
:param kwargs: Field overrides for the :py:class:`LogAction` object.
:return: T... | [
"Helper",
"method",
"to",
"create",
"a",
"new",
"log",
"entry",
".",
"This",
"method",
"automatically",
"populates",
"some",
"fields",
"when",
"no",
"explicit",
"value",
"is",
"given",
".",
":",
"param",
"instance",
":",
"The",
"model",
"instance",
"to",
"... | train | https://github.com/shtalinberg/django-actions-logger/blob/2a7200bfb277ace47464a77b57aa475a9710271a/actionslog/models.py#L28-L96 |
shtalinberg/django-actions-logger | actionslog/models.py | LogActionManager.get_for_objects | def get_for_objects(self, queryset):
"""
Get log entries for the objects in the specified queryset.
:param queryset: The queryset to get the log entries for.
:type queryset: QuerySet
:return: The LogAction objects for the objects in the given queryset.
:rtype: QuerySet
... | python | def get_for_objects(self, queryset):
"""
Get log entries for the objects in the specified queryset.
:param queryset: The queryset to get the log entries for.
:type queryset: QuerySet
:return: The LogAction objects for the objects in the given queryset.
:rtype: QuerySet
... | [
"def",
"get_for_objects",
"(",
"self",
",",
"queryset",
")",
":",
"if",
"not",
"isinstance",
"(",
"queryset",
",",
"QuerySet",
")",
"or",
"queryset",
".",
"count",
"(",
")",
"==",
"0",
":",
"return",
"self",
".",
"none",
"(",
")",
"content_type",
"=",
... | Get log entries for the objects in the specified queryset.
:param queryset: The queryset to get the log entries for.
:type queryset: QuerySet
:return: The LogAction objects for the objects in the given queryset.
:rtype: QuerySet | [
"Get",
"log",
"entries",
"for",
"the",
"objects",
"in",
"the",
"specified",
"queryset",
".",
":",
"param",
"queryset",
":",
"The",
"queryset",
"to",
"get",
"the",
"log",
"entries",
"for",
".",
":",
"type",
"queryset",
":",
"QuerySet",
":",
"return",
":",... | train | https://github.com/shtalinberg/django-actions-logger/blob/2a7200bfb277ace47464a77b57aa475a9710271a/actionslog/models.py#L114-L131 |
shtalinberg/django-actions-logger | actionslog/registry.py | ActionslogModelRegistry.register | def register(self, model, include_fields=[], exclude_fields=[]):
"""
Register a model with actionslog. Actionslog will then track mutations on this model's instances.
:param model: The model to register.
:type model: Model
:param include_fields: The fields to include. Implicitly... | python | def register(self, model, include_fields=[], exclude_fields=[]):
"""
Register a model with actionslog. Actionslog will then track mutations on this model's instances.
:param model: The model to register.
:type model: Model
:param include_fields: The fields to include. Implicitly... | [
"def",
"register",
"(",
"self",
",",
"model",
",",
"include_fields",
"=",
"[",
"]",
",",
"exclude_fields",
"=",
"[",
"]",
")",
":",
"if",
"issubclass",
"(",
"model",
",",
"Model",
")",
":",
"self",
".",
"_registry",
"[",
"model",
"]",
"=",
"{",
"'i... | Register a model with actionslog. Actionslog will then track mutations on this model's instances.
:param model: The model to register.
:type model: Model
:param include_fields: The fields to include. Implicitly excludes all other fields.
:type include_fields: list
:param exclude... | [
"Register",
"a",
"model",
"with",
"actionslog",
".",
"Actionslog",
"will",
"then",
"track",
"mutations",
"on",
"this",
"model",
"s",
"instances",
"."
] | train | https://github.com/shtalinberg/django-actions-logger/blob/2a7200bfb277ace47464a77b57aa475a9710271a/actionslog/registry.py#L27-L45 |
shtalinberg/django-actions-logger | actionslog/diff.py | track_field | def track_field(field):
"""
Returns whether the given field should be tracked by Actionslog.
Untracked fields are many-to-many relations and relations to the Actionslog LogAction model.
:param field: The field to check.
:type field: Field
:return: Whether the given field should be tracked.
... | python | def track_field(field):
"""
Returns whether the given field should be tracked by Actionslog.
Untracked fields are many-to-many relations and relations to the Actionslog LogAction model.
:param field: The field to check.
:type field: Field
:return: Whether the given field should be tracked.
... | [
"def",
"track_field",
"(",
"field",
")",
":",
"from",
"actionslog",
".",
"models",
"import",
"LogAction",
"# Do not track many to many relations",
"if",
"field",
".",
"many_to_many",
":",
"return",
"False",
"# Do not track relations to LogAction",
"if",
"getattr",
"(",
... | Returns whether the given field should be tracked by Actionslog.
Untracked fields are many-to-many relations and relations to the Actionslog LogAction model.
:param field: The field to check.
:type field: Field
:return: Whether the given field should be tracked.
:rtype: bool | [
"Returns",
"whether",
"the",
"given",
"field",
"should",
"be",
"tracked",
"by",
"Actionslog",
"."
] | train | https://github.com/shtalinberg/django-actions-logger/blob/2a7200bfb277ace47464a77b57aa475a9710271a/actionslog/diff.py#L8-L28 |
shtalinberg/django-actions-logger | actionslog/diff.py | model_instance_diff | def model_instance_diff(old, new):
"""
Calculates the differences between two model instances. One of the instances may be ``None`` (i.e., a newly
created model or deleted model). This will cause all fields with a value to have changed (from ``None``).
:param old: The old state of the model instance.
... | python | def model_instance_diff(old, new):
"""
Calculates the differences between two model instances. One of the instances may be ``None`` (i.e., a newly
created model or deleted model). This will cause all fields with a value to have changed (from ``None``).
:param old: The old state of the model instance.
... | [
"def",
"model_instance_diff",
"(",
"old",
",",
"new",
")",
":",
"from",
"actionslog",
".",
"registry",
"import",
"actionslog",
"if",
"not",
"(",
"old",
"is",
"None",
"or",
"isinstance",
"(",
"old",
",",
"Model",
")",
")",
":",
"raise",
"TypeError",
"(",
... | Calculates the differences between two model instances. One of the instances may be ``None`` (i.e., a newly
created model or deleted model). This will cause all fields with a value to have changed (from ``None``).
:param old: The old state of the model instance.
:type old: Model
:param new: The new sta... | [
"Calculates",
"the",
"differences",
"between",
"two",
"model",
"instances",
".",
"One",
"of",
"the",
"instances",
"may",
"be",
"None",
"(",
"i",
".",
"e",
".",
"a",
"newly",
"created",
"model",
"or",
"deleted",
"model",
")",
".",
"This",
"will",
"cause",... | train | https://github.com/shtalinberg/django-actions-logger/blob/2a7200bfb277ace47464a77b57aa475a9710271a/actionslog/diff.py#L51-L116 |
shtalinberg/django-actions-logger | actionslog/middleware.py | ActionslogMiddleware.process_request | def process_request(self, request):
"""
Gets the current user from the request and prepares and connects a signal receiver with the user already
attached to it.
"""
# Initialize thread local storage
threadlocal.actionslog = {
'signal_duid': (self.__class__, ti... | python | def process_request(self, request):
"""
Gets the current user from the request and prepares and connects a signal receiver with the user already
attached to it.
"""
# Initialize thread local storage
threadlocal.actionslog = {
'signal_duid': (self.__class__, ti... | [
"def",
"process_request",
"(",
"self",
",",
"request",
")",
":",
"# Initialize thread local storage",
"threadlocal",
".",
"actionslog",
"=",
"{",
"'signal_duid'",
":",
"(",
"self",
".",
"__class__",
",",
"time",
".",
"time",
"(",
")",
")",
",",
"'remote_ip'",
... | Gets the current user from the request and prepares and connects a signal receiver with the user already
attached to it. | [
"Gets",
"the",
"current",
"user",
"from",
"the",
"request",
"and",
"prepares",
"and",
"connects",
"a",
"signal",
"receiver",
"with",
"the",
"user",
"already",
"attached",
"to",
"it",
"."
] | train | https://github.com/shtalinberg/django-actions-logger/blob/2a7200bfb277ace47464a77b57aa475a9710271a/actionslog/middleware.py#L28-L46 |
shtalinberg/django-actions-logger | actionslog/middleware.py | ActionslogMiddleware.process_response | def process_response(self, request, response):
"""
Disconnects the signal receiver to prevent it from staying active.
"""
if hasattr(threadlocal, 'actionslog'):
pre_save.disconnect(sender=LogAction, dispatch_uid=threadlocal.actionslog['signal_duid'])
return response | python | def process_response(self, request, response):
"""
Disconnects the signal receiver to prevent it from staying active.
"""
if hasattr(threadlocal, 'actionslog'):
pre_save.disconnect(sender=LogAction, dispatch_uid=threadlocal.actionslog['signal_duid'])
return response | [
"def",
"process_response",
"(",
"self",
",",
"request",
",",
"response",
")",
":",
"if",
"hasattr",
"(",
"threadlocal",
",",
"'actionslog'",
")",
":",
"pre_save",
".",
"disconnect",
"(",
"sender",
"=",
"LogAction",
",",
"dispatch_uid",
"=",
"threadlocal",
".... | Disconnects the signal receiver to prevent it from staying active. | [
"Disconnects",
"the",
"signal",
"receiver",
"to",
"prevent",
"it",
"from",
"staying",
"active",
"."
] | train | https://github.com/shtalinberg/django-actions-logger/blob/2a7200bfb277ace47464a77b57aa475a9710271a/actionslog/middleware.py#L48-L55 |
shtalinberg/django-actions-logger | actionslog/middleware.py | ActionslogMiddleware.process_exception | def process_exception(self, request, exception):
"""
Disconnects the signal receiver to prevent it from staying active in case of an exception.
"""
if hasattr(threadlocal, 'actionslog'):
pre_save.disconnect(sender=LogAction, dispatch_uid=threadlocal.actionslog['signal_duid'])... | python | def process_exception(self, request, exception):
"""
Disconnects the signal receiver to prevent it from staying active in case of an exception.
"""
if hasattr(threadlocal, 'actionslog'):
pre_save.disconnect(sender=LogAction, dispatch_uid=threadlocal.actionslog['signal_duid'])... | [
"def",
"process_exception",
"(",
"self",
",",
"request",
",",
"exception",
")",
":",
"if",
"hasattr",
"(",
"threadlocal",
",",
"'actionslog'",
")",
":",
"pre_save",
".",
"disconnect",
"(",
"sender",
"=",
"LogAction",
",",
"dispatch_uid",
"=",
"threadlocal",
... | Disconnects the signal receiver to prevent it from staying active in case of an exception. | [
"Disconnects",
"the",
"signal",
"receiver",
"to",
"prevent",
"it",
"from",
"staying",
"active",
"in",
"case",
"of",
"an",
"exception",
"."
] | train | https://github.com/shtalinberg/django-actions-logger/blob/2a7200bfb277ace47464a77b57aa475a9710271a/actionslog/middleware.py#L57-L64 |
shtalinberg/django-actions-logger | actionslog/middleware.py | ActionslogMiddleware.set_user | def set_user(user, sender, instance, **kwargs):
"""
Signal receiver with an extra, required 'user' kwarg. This method becomes a real (valid) signal receiver when
it is curried with the user.
"""
try:
app_label, model_name = settings.AUTH_USER_MODEL.split('.')
... | python | def set_user(user, sender, instance, **kwargs):
"""
Signal receiver with an extra, required 'user' kwarg. This method becomes a real (valid) signal receiver when
it is curried with the user.
"""
try:
app_label, model_name = settings.AUTH_USER_MODEL.split('.')
... | [
"def",
"set_user",
"(",
"user",
",",
"sender",
",",
"instance",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"app_label",
",",
"model_name",
"=",
"settings",
".",
"AUTH_USER_MODEL",
".",
"split",
"(",
"'.'",
")",
"auth_user_model",
"=",
"apps",
".",
... | Signal receiver with an extra, required 'user' kwarg. This method becomes a real (valid) signal receiver when
it is curried with the user. | [
"Signal",
"receiver",
"with",
"an",
"extra",
"required",
"user",
"kwarg",
".",
"This",
"method",
"becomes",
"a",
"real",
"(",
"valid",
")",
"signal",
"receiver",
"when",
"it",
"is",
"curried",
"with",
"the",
"user",
"."
] | train | https://github.com/shtalinberg/django-actions-logger/blob/2a7200bfb277ace47464a77b57aa475a9710271a/actionslog/middleware.py#L67-L80 |
shtalinberg/django-actions-logger | actionslog/receivers.py | action_log_create | def action_log_create(sender, instance, created, **kwargs):
"""
Signal receiver that creates a log entry when a model instance is first saved to the database.
Direct use is discouraged, connect your model through :py:func:`actionslog.registry.register` instead.
"""
if created:
changes = mod... | python | def action_log_create(sender, instance, created, **kwargs):
"""
Signal receiver that creates a log entry when a model instance is first saved to the database.
Direct use is discouraged, connect your model through :py:func:`actionslog.registry.register` instead.
"""
if created:
changes = mod... | [
"def",
"action_log_create",
"(",
"sender",
",",
"instance",
",",
"created",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"created",
":",
"changes",
"=",
"model_instance_diff",
"(",
"None",
",",
"instance",
")",
"log_entry",
"=",
"LogAction",
".",
"objects",
".... | Signal receiver that creates a log entry when a model instance is first saved to the database.
Direct use is discouraged, connect your model through :py:func:`actionslog.registry.register` instead. | [
"Signal",
"receiver",
"that",
"creates",
"a",
"log",
"entry",
"when",
"a",
"model",
"instance",
"is",
"first",
"saved",
"to",
"the",
"database",
"."
] | train | https://github.com/shtalinberg/django-actions-logger/blob/2a7200bfb277ace47464a77b57aa475a9710271a/actionslog/receivers.py#L9-L22 |
shtalinberg/django-actions-logger | actionslog/receivers.py | action_log_update | def action_log_update(sender, instance, **kwargs):
"""
Signal receiver that creates a log entry when a model instance is changed and saved to the database.
Direct use is discouraged, connect your model through :py:func:`actionslog.registry.register` instead.
"""
if instance.pk is not None:
... | python | def action_log_update(sender, instance, **kwargs):
"""
Signal receiver that creates a log entry when a model instance is changed and saved to the database.
Direct use is discouraged, connect your model through :py:func:`actionslog.registry.register` instead.
"""
if instance.pk is not None:
... | [
"def",
"action_log_update",
"(",
"sender",
",",
"instance",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"instance",
".",
"pk",
"is",
"not",
"None",
":",
"try",
":",
"old",
"=",
"sender",
".",
"objects",
".",
"get",
"(",
"pk",
"=",
"instance",
".",
"pk... | Signal receiver that creates a log entry when a model instance is changed and saved to the database.
Direct use is discouraged, connect your model through :py:func:`actionslog.registry.register` instead. | [
"Signal",
"receiver",
"that",
"creates",
"a",
"log",
"entry",
"when",
"a",
"model",
"instance",
"is",
"changed",
"and",
"saved",
"to",
"the",
"database",
"."
] | train | https://github.com/shtalinberg/django-actions-logger/blob/2a7200bfb277ace47464a77b57aa475a9710271a/actionslog/receivers.py#L25-L47 |
shtalinberg/django-actions-logger | actionslog/receivers.py | action_log_delete | def action_log_delete(sender, instance, **kwargs):
"""
Signal receiver that creates a log entry when a model instance is deleted from the database.
Direct use is discouraged, connect your model through :py:func:`actionslog.registry.register` instead.
"""
if instance.pk is not None:
changes ... | python | def action_log_delete(sender, instance, **kwargs):
"""
Signal receiver that creates a log entry when a model instance is deleted from the database.
Direct use is discouraged, connect your model through :py:func:`actionslog.registry.register` instead.
"""
if instance.pk is not None:
changes ... | [
"def",
"action_log_delete",
"(",
"sender",
",",
"instance",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"instance",
".",
"pk",
"is",
"not",
"None",
":",
"changes",
"=",
"model_instance_diff",
"(",
"instance",
",",
"None",
")",
"log_entry",
"=",
"LogAction",
... | Signal receiver that creates a log entry when a model instance is deleted from the database.
Direct use is discouraged, connect your model through :py:func:`actionslog.registry.register` instead. | [
"Signal",
"receiver",
"that",
"creates",
"a",
"log",
"entry",
"when",
"a",
"model",
"instance",
"is",
"deleted",
"from",
"the",
"database",
"."
] | train | https://github.com/shtalinberg/django-actions-logger/blob/2a7200bfb277ace47464a77b57aa475a9710271a/actionslog/receivers.py#L50-L63 |
a10networks/acos-client | acos_client/v21/axapi_http.py | HttpClient.request | def request(self, method, api_url, params={}, **kwargs):
"""Generate the API call to the device."""
LOG.debug("axapi_http: full url = %s", self.url_base + api_url)
LOG.debug("axapi_http: %s url = %s", method, api_url)
LOG.debug("axapi_http: params = %s", json.dumps(logutils.clean(params... | python | def request(self, method, api_url, params={}, **kwargs):
"""Generate the API call to the device."""
LOG.debug("axapi_http: full url = %s", self.url_base + api_url)
LOG.debug("axapi_http: %s url = %s", method, api_url)
LOG.debug("axapi_http: params = %s", json.dumps(logutils.clean(params... | [
"def",
"request",
"(",
"self",
",",
"method",
",",
"api_url",
",",
"params",
"=",
"{",
"}",
",",
"*",
"*",
"kwargs",
")",
":",
"LOG",
".",
"debug",
"(",
"\"axapi_http: full url = %s\"",
",",
"self",
".",
"url_base",
"+",
"api_url",
")",
"LOG",
".",
"... | Generate the API call to the device. | [
"Generate",
"the",
"API",
"call",
"to",
"the",
"device",
"."
] | train | https://github.com/a10networks/acos-client/blob/14d1fff589650650c9a65047d54c6c8c1d6b75f2/acos_client/v21/axapi_http.py#L108-L173 |
a10networks/acos-client | acos_client/v30/license_manager.py | LicenseManager.create | def create(self, host_list=[], serial=None, instance_name=None, use_mgmt_port=False,
interval=None, bandwidth_base=None, bandwidth_unrestricted=None):
"""Creates a license manager entry
Keyword arguments:
instance_name -- license manager instance name
host_list -- list(di... | python | def create(self, host_list=[], serial=None, instance_name=None, use_mgmt_port=False,
interval=None, bandwidth_base=None, bandwidth_unrestricted=None):
"""Creates a license manager entry
Keyword arguments:
instance_name -- license manager instance name
host_list -- list(di... | [
"def",
"create",
"(",
"self",
",",
"host_list",
"=",
"[",
"]",
",",
"serial",
"=",
"None",
",",
"instance_name",
"=",
"None",
",",
"use_mgmt_port",
"=",
"False",
",",
"interval",
"=",
"None",
",",
"bandwidth_base",
"=",
"None",
",",
"bandwidth_unrestricted... | Creates a license manager entry
Keyword arguments:
instance_name -- license manager instance name
host_list -- list(dict) a list of dictionaries of the format:
{'ip': '127.0.0.1', 'port': 443}
serial - (str) appliance serial number
use_mgmt_port - (bool) use manageme... | [
"Creates",
"a",
"license",
"manager",
"entry"
] | train | https://github.com/a10networks/acos-client/blob/14d1fff589650650c9a65047d54c6c8c1d6b75f2/acos_client/v30/license_manager.py#L34-L54 |
a10networks/acos-client | acos_client/v30/license_manager.py | LicenseManager.update | def update(self, host_list=[], serial=None, instance_name=None, use_mgmt_port=False,
interval=None, bandwidth_base=None, bandwidth_unrestricted=None):
"""Update a license manager entry
Keyword arguments:
instance_name -- license manager instance name
host_list -- list(dic... | python | def update(self, host_list=[], serial=None, instance_name=None, use_mgmt_port=False,
interval=None, bandwidth_base=None, bandwidth_unrestricted=None):
"""Update a license manager entry
Keyword arguments:
instance_name -- license manager instance name
host_list -- list(dic... | [
"def",
"update",
"(",
"self",
",",
"host_list",
"=",
"[",
"]",
",",
"serial",
"=",
"None",
",",
"instance_name",
"=",
"None",
",",
"use_mgmt_port",
"=",
"False",
",",
"interval",
"=",
"None",
",",
"bandwidth_base",
"=",
"None",
",",
"bandwidth_unrestricted... | Update a license manager entry
Keyword arguments:
instance_name -- license manager instance name
host_list -- list(dict) a list of dictionaries of the format:
{'ip': '127.0.0.1', 'port': 443}
serial - (str) appliance serial number
use_mgmt_port - (bool) use managemen... | [
"Update",
"a",
"license",
"manager",
"entry"
] | train | https://github.com/a10networks/acos-client/blob/14d1fff589650650c9a65047d54c6c8c1d6b75f2/acos_client/v30/license_manager.py#L56-L75 |
a10networks/acos-client | acos_client/v30/device_context.py | DeviceContext.switch | def switch(self, device_id, obj_slot_id):
"""Switching of device-context"""
payload = {
"device-context": self._build_payload(device_id, obj_slot_id)
}
return self._post(self.url_prefix, payload) | python | def switch(self, device_id, obj_slot_id):
"""Switching of device-context"""
payload = {
"device-context": self._build_payload(device_id, obj_slot_id)
}
return self._post(self.url_prefix, payload) | [
"def",
"switch",
"(",
"self",
",",
"device_id",
",",
"obj_slot_id",
")",
":",
"payload",
"=",
"{",
"\"device-context\"",
":",
"self",
".",
"_build_payload",
"(",
"device_id",
",",
"obj_slot_id",
")",
"}",
"return",
"self",
".",
"_post",
"(",
"self",
".",
... | Switching of device-context | [
"Switching",
"of",
"device",
"-",
"context"
] | train | https://github.com/a10networks/acos-client/blob/14d1fff589650650c9a65047d54c6c8c1d6b75f2/acos_client/v30/device_context.py#L24-L30 |
a10networks/acos-client | acos_client/v30/route.py | RIB.create | def create(self, destination, mask, next_hops=[]):
"""Create route to {destination} {mask} using {next_hops} expressed as (gateway, distance)"""
payload = {
"rib": self._build_payload(destination, mask, next_hops)
}
return self._post(self.url_prefix, payload) | python | def create(self, destination, mask, next_hops=[]):
"""Create route to {destination} {mask} using {next_hops} expressed as (gateway, distance)"""
payload = {
"rib": self._build_payload(destination, mask, next_hops)
}
return self._post(self.url_prefix, payload) | [
"def",
"create",
"(",
"self",
",",
"destination",
",",
"mask",
",",
"next_hops",
"=",
"[",
"]",
")",
":",
"payload",
"=",
"{",
"\"rib\"",
":",
"self",
".",
"_build_payload",
"(",
"destination",
",",
"mask",
",",
"next_hops",
")",
"}",
"return",
"self",... | Create route to {destination} {mask} using {next_hops} expressed as (gateway, distance) | [
"Create",
"route",
"to",
"{",
"destination",
"}",
"{",
"mask",
"}",
"using",
"{",
"next_hops",
"}",
"expressed",
"as",
"(",
"gateway",
"distance",
")"
] | train | https://github.com/a10networks/acos-client/blob/14d1fff589650650c9a65047d54c6c8c1d6b75f2/acos_client/v30/route.py#L25-L31 |
materialsproject/pymatgen-db | matgendb/creator.py | contains_vasp_input | def contains_vasp_input(dir_name):
"""
Checks if a directory contains valid VASP input.
Args:
dir_name:
Directory name to check.
Returns:
True if directory contains all four VASP input files (INCAR, POSCAR,
KPOINTS and POTCAR).
"""
for f in ["INCAR", "POSCAR... | python | def contains_vasp_input(dir_name):
"""
Checks if a directory contains valid VASP input.
Args:
dir_name:
Directory name to check.
Returns:
True if directory contains all four VASP input files (INCAR, POSCAR,
KPOINTS and POTCAR).
"""
for f in ["INCAR", "POSCAR... | [
"def",
"contains_vasp_input",
"(",
"dir_name",
")",
":",
"for",
"f",
"in",
"[",
"\"INCAR\"",
",",
"\"POSCAR\"",
",",
"\"POTCAR\"",
",",
"\"KPOINTS\"",
"]",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"os",
".",
"path",
".",
"join",
"(",
... | Checks if a directory contains valid VASP input.
Args:
dir_name:
Directory name to check.
Returns:
True if directory contains all four VASP input files (INCAR, POSCAR,
KPOINTS and POTCAR). | [
"Checks",
"if",
"a",
"directory",
"contains",
"valid",
"VASP",
"input",
"."
] | train | https://github.com/materialsproject/pymatgen-db/blob/02e4351c2cea431407644f49193e8bf43ed39b9a/matgendb/creator.py#L692-L708 |
materialsproject/pymatgen-db | matgendb/creator.py | get_coordination_numbers | def get_coordination_numbers(d):
"""
Helper method to get the coordination number of all sites in the final
structure from a run.
Args:
d:
Run dict generated by VaspToDbTaskDrone.
Returns:
Coordination numbers as a list of dict of [{"site": site_dict,
"coordinat... | python | def get_coordination_numbers(d):
"""
Helper method to get the coordination number of all sites in the final
structure from a run.
Args:
d:
Run dict generated by VaspToDbTaskDrone.
Returns:
Coordination numbers as a list of dict of [{"site": site_dict,
"coordinat... | [
"def",
"get_coordination_numbers",
"(",
"d",
")",
":",
"structure",
"=",
"Structure",
".",
"from_dict",
"(",
"d",
"[",
"\"output\"",
"]",
"[",
"\"crystal\"",
"]",
")",
"f",
"=",
"VoronoiNN",
"(",
")",
"cn",
"=",
"[",
"]",
"for",
"i",
",",
"s",
"in",
... | Helper method to get the coordination number of all sites in the final
structure from a run.
Args:
d:
Run dict generated by VaspToDbTaskDrone.
Returns:
Coordination numbers as a list of dict of [{"site": site_dict,
"coordination": number}, ...]. | [
"Helper",
"method",
"to",
"get",
"the",
"coordination",
"number",
"of",
"all",
"sites",
"in",
"the",
"final",
"structure",
"from",
"a",
"run",
"."
] | train | https://github.com/materialsproject/pymatgen-db/blob/02e4351c2cea431407644f49193e8bf43ed39b9a/matgendb/creator.py#L711-L734 |
materialsproject/pymatgen-db | matgendb/creator.py | get_uri | def get_uri(dir_name):
"""
Returns the URI path for a directory. This allows files hosted on
different file servers to have distinct locations.
Args:
dir_name:
A directory name.
Returns:
Full URI path, e.g., fileserver.host.com:/full/path/of/dir_name.
"""
fullpa... | python | def get_uri(dir_name):
"""
Returns the URI path for a directory. This allows files hosted on
different file servers to have distinct locations.
Args:
dir_name:
A directory name.
Returns:
Full URI path, e.g., fileserver.host.com:/full/path/of/dir_name.
"""
fullpa... | [
"def",
"get_uri",
"(",
"dir_name",
")",
":",
"fullpath",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"dir_name",
")",
"try",
":",
"hostname",
"=",
"socket",
".",
"gethostbyaddr",
"(",
"socket",
".",
"gethostname",
"(",
")",
")",
"[",
"0",
"]",
"exce... | Returns the URI path for a directory. This allows files hosted on
different file servers to have distinct locations.
Args:
dir_name:
A directory name.
Returns:
Full URI path, e.g., fileserver.host.com:/full/path/of/dir_name. | [
"Returns",
"the",
"URI",
"path",
"for",
"a",
"directory",
".",
"This",
"allows",
"files",
"hosted",
"on",
"different",
"file",
"servers",
"to",
"have",
"distinct",
"locations",
"."
] | train | https://github.com/materialsproject/pymatgen-db/blob/02e4351c2cea431407644f49193e8bf43ed39b9a/matgendb/creator.py#L737-L754 |
materialsproject/pymatgen-db | matgendb/creator.py | VaspToDbTaskDrone.assimilate | def assimilate(self, path):
"""
Parses vasp runs. Then insert the result into the db. and return the
task_id or doc of the insertion.
Returns:
If in simulate_mode, the entire doc is returned for debugging
purposes. Else, only the task_id of the inserted doc is re... | python | def assimilate(self, path):
"""
Parses vasp runs. Then insert the result into the db. and return the
task_id or doc of the insertion.
Returns:
If in simulate_mode, the entire doc is returned for debugging
purposes. Else, only the task_id of the inserted doc is re... | [
"def",
"assimilate",
"(",
"self",
",",
"path",
")",
":",
"try",
":",
"d",
"=",
"self",
".",
"get_task_doc",
"(",
"path",
")",
"if",
"self",
".",
"mapi_key",
"is",
"not",
"None",
"and",
"d",
"[",
"\"state\"",
"]",
"==",
"\"successful\"",
":",
"self",
... | Parses vasp runs. Then insert the result into the db. and return the
task_id or doc of the insertion.
Returns:
If in simulate_mode, the entire doc is returned for debugging
purposes. Else, only the task_id of the inserted doc is returned. | [
"Parses",
"vasp",
"runs",
".",
"Then",
"insert",
"the",
"result",
"into",
"the",
"db",
".",
"and",
"return",
"the",
"task_id",
"or",
"doc",
"of",
"the",
"insertion",
"."
] | train | https://github.com/materialsproject/pymatgen-db/blob/02e4351c2cea431407644f49193e8bf43ed39b9a/matgendb/creator.py#L169-L187 |
materialsproject/pymatgen-db | matgendb/creator.py | VaspToDbTaskDrone.get_task_doc | def get_task_doc(self, path):
"""
Get the entire task doc for a path, including any post-processing.
"""
logger.info("Getting task doc for base dir :{}".format(path))
files = os.listdir(path)
vasprun_files = OrderedDict()
if "STOPCAR" in files:
#Stoppe... | python | def get_task_doc(self, path):
"""
Get the entire task doc for a path, including any post-processing.
"""
logger.info("Getting task doc for base dir :{}".format(path))
files = os.listdir(path)
vasprun_files = OrderedDict()
if "STOPCAR" in files:
#Stoppe... | [
"def",
"get_task_doc",
"(",
"self",
",",
"path",
")",
":",
"logger",
".",
"info",
"(",
"\"Getting task doc for base dir :{}\"",
".",
"format",
"(",
"path",
")",
")",
"files",
"=",
"os",
".",
"listdir",
"(",
"path",
")",
"vasprun_files",
"=",
"OrderedDict",
... | Get the entire task doc for a path, including any post-processing. | [
"Get",
"the",
"entire",
"task",
"doc",
"for",
"a",
"path",
"including",
"any",
"post",
"-",
"processing",
"."
] | train | https://github.com/materialsproject/pymatgen-db/blob/02e4351c2cea431407644f49193e8bf43ed39b9a/matgendb/creator.py#L202-L241 |
materialsproject/pymatgen-db | matgendb/creator.py | VaspToDbTaskDrone.post_process | def post_process(self, dir_name, d):
"""
Simple post-processing for various files other than the vasprun.xml.
Called by generate_task_doc. Modify this if your runs have other
kinds of processing requirements.
Args:
dir_name:
The dir_name.
... | python | def post_process(self, dir_name, d):
"""
Simple post-processing for various files other than the vasprun.xml.
Called by generate_task_doc. Modify this if your runs have other
kinds of processing requirements.
Args:
dir_name:
The dir_name.
... | [
"def",
"post_process",
"(",
"self",
",",
"dir_name",
",",
"d",
")",
":",
"logger",
".",
"info",
"(",
"\"Post-processing dir:{}\"",
".",
"format",
"(",
"dir_name",
")",
")",
"fullpath",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"dir_name",
")",
"# VASP... | Simple post-processing for various files other than the vasprun.xml.
Called by generate_task_doc. Modify this if your runs have other
kinds of processing requirements.
Args:
dir_name:
The dir_name.
d:
Current doc generated. | [
"Simple",
"post",
"-",
"processing",
"for",
"various",
"files",
"other",
"than",
"the",
"vasprun",
".",
"xml",
".",
"Called",
"by",
"generate_task_doc",
".",
"Modify",
"this",
"if",
"your",
"runs",
"have",
"other",
"kinds",
"of",
"processing",
"requirements",
... | train | https://github.com/materialsproject/pymatgen-db/blob/02e4351c2cea431407644f49193e8bf43ed39b9a/matgendb/creator.py#L299-L395 |
materialsproject/pymatgen-db | matgendb/creator.py | VaspToDbTaskDrone.process_killed_run | def process_killed_run(self, dir_name):
"""
Process a killed vasp run.
"""
fullpath = os.path.abspath(dir_name)
logger.info("Processing Killed run " + fullpath)
d = {"dir_name": fullpath, "state": "killed", "oszicar": {}}
for f in os.listdir(dir_name):
... | python | def process_killed_run(self, dir_name):
"""
Process a killed vasp run.
"""
fullpath = os.path.abspath(dir_name)
logger.info("Processing Killed run " + fullpath)
d = {"dir_name": fullpath, "state": "killed", "oszicar": {}}
for f in os.listdir(dir_name):
... | [
"def",
"process_killed_run",
"(",
"self",
",",
"dir_name",
")",
":",
"fullpath",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"dir_name",
")",
"logger",
".",
"info",
"(",
"\"Processing Killed run \"",
"+",
"fullpath",
")",
"d",
"=",
"{",
"\"dir_name\"",
":... | Process a killed vasp run. | [
"Process",
"a",
"killed",
"vasp",
"run",
"."
] | train | https://github.com/materialsproject/pymatgen-db/blob/02e4351c2cea431407644f49193e8bf43ed39b9a/matgendb/creator.py#L397-L479 |
materialsproject/pymatgen-db | matgendb/creator.py | VaspToDbTaskDrone.process_vasprun | def process_vasprun(self, dir_name, taskname, filename):
"""
Process a vasprun.xml file.
"""
vasprun_file = os.path.join(dir_name, filename)
if self.parse_projected_eigen and (self.parse_projected_eigen != 'final' or \
taskname == self.runs[-1]):
... | python | def process_vasprun(self, dir_name, taskname, filename):
"""
Process a vasprun.xml file.
"""
vasprun_file = os.path.join(dir_name, filename)
if self.parse_projected_eigen and (self.parse_projected_eigen != 'final' or \
taskname == self.runs[-1]):
... | [
"def",
"process_vasprun",
"(",
"self",
",",
"dir_name",
",",
"taskname",
",",
"filename",
")",
":",
"vasprun_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"dir_name",
",",
"filename",
")",
"if",
"self",
".",
"parse_projected_eigen",
"and",
"(",
"self",
... | Process a vasprun.xml file. | [
"Process",
"a",
"vasprun",
".",
"xml",
"file",
"."
] | train | https://github.com/materialsproject/pymatgen-db/blob/02e4351c2cea431407644f49193e8bf43ed39b9a/matgendb/creator.py#L481-L511 |
materialsproject/pymatgen-db | matgendb/creator.py | VaspToDbTaskDrone.generate_doc | def generate_doc(self, dir_name, vasprun_files):
"""
Process aflow style runs, where each run is actually a combination of
two vasp runs.
"""
try:
fullpath = os.path.abspath(dir_name)
# Defensively copy the additional fields first. This is a MUST.
... | python | def generate_doc(self, dir_name, vasprun_files):
"""
Process aflow style runs, where each run is actually a combination of
two vasp runs.
"""
try:
fullpath = os.path.abspath(dir_name)
# Defensively copy the additional fields first. This is a MUST.
... | [
"def",
"generate_doc",
"(",
"self",
",",
"dir_name",
",",
"vasprun_files",
")",
":",
"try",
":",
"fullpath",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"dir_name",
")",
"# Defensively copy the additional fields first. This is a MUST.",
"# Otherwise, parallel updates ... | Process aflow style runs, where each run is actually a combination of
two vasp runs. | [
"Process",
"aflow",
"style",
"runs",
"where",
"each",
"run",
"is",
"actually",
"a",
"combination",
"of",
"two",
"vasp",
"runs",
"."
] | train | https://github.com/materialsproject/pymatgen-db/blob/02e4351c2cea431407644f49193e8bf43ed39b9a/matgendb/creator.py#L513-L587 |
materialsproject/pymatgen-db | matgendb/creator.py | VaspToDbTaskDrone.get_valid_paths | def get_valid_paths(self, path):
"""
There are some restrictions on the valid directory structures:
1. There can be only one vasp run in each directory. Nested directories
are fine.
2. Directories designated "relax1", "relax2" are considered to be 2
parts of an afl... | python | def get_valid_paths(self, path):
"""
There are some restrictions on the valid directory structures:
1. There can be only one vasp run in each directory. Nested directories
are fine.
2. Directories designated "relax1", "relax2" are considered to be 2
parts of an afl... | [
"def",
"get_valid_paths",
"(",
"self",
",",
"path",
")",
":",
"(",
"parent",
",",
"subdirs",
",",
"files",
")",
"=",
"path",
"if",
"set",
"(",
"self",
".",
"runs",
")",
".",
"intersection",
"(",
"subdirs",
")",
":",
"return",
"[",
"parent",
"]",
"i... | There are some restrictions on the valid directory structures:
1. There can be only one vasp run in each directory. Nested directories
are fine.
2. Directories designated "relax1", "relax2" are considered to be 2
parts of an aflow style run.
3. Directories containing vasp ... | [
"There",
"are",
"some",
"restrictions",
"on",
"the",
"valid",
"directory",
"structures",
":"
] | train | https://github.com/materialsproject/pymatgen-db/blob/02e4351c2cea431407644f49193e8bf43ed39b9a/matgendb/creator.py#L589-L606 |
materialsproject/pymatgen-db | matgendb/vv/util.py | total_size | def total_size(o, handlers={}, verbose=False, count=False):
"""Returns the approximate memory footprint an object and all of its contents.
Automatically finds the contents of the following builtin containers and
their subclasses: tuple, list, deque, dict, set and frozenset.
To search other containers,... | python | def total_size(o, handlers={}, verbose=False, count=False):
"""Returns the approximate memory footprint an object and all of its contents.
Automatically finds the contents of the following builtin containers and
their subclasses: tuple, list, deque, dict, set and frozenset.
To search other containers,... | [
"def",
"total_size",
"(",
"o",
",",
"handlers",
"=",
"{",
"}",
",",
"verbose",
"=",
"False",
",",
"count",
"=",
"False",
")",
":",
"# How to make different types of objects iterable",
"dict_handler",
"=",
"lambda",
"d",
":",
"chain",
".",
"from_iterable",
"(",... | Returns the approximate memory footprint an object and all of its contents.
Automatically finds the contents of the following builtin containers and
their subclasses: tuple, list, deque, dict, set and frozenset.
To search other containers, add handlers to iterate over their contents:
handlers = {... | [
"Returns",
"the",
"approximate",
"memory",
"footprint",
"an",
"object",
"and",
"all",
"of",
"its",
"contents",
"."
] | train | https://github.com/materialsproject/pymatgen-db/blob/02e4351c2cea431407644f49193e8bf43ed39b9a/matgendb/vv/util.py#L44-L84 |
materialsproject/pymatgen-db | matgendb/vv/util.py | args_kvp_nodup | def args_kvp_nodup(s):
"""Parse argument string as key=value pairs separated by commas.
:param s: Argument string
:return: Parsed value
:rtype: dict
:raises: ValueError for format violations or a duplicated key.
"""
if s is None:
return {}
d = {}
for item in [e.strip() for e... | python | def args_kvp_nodup(s):
"""Parse argument string as key=value pairs separated by commas.
:param s: Argument string
:return: Parsed value
:rtype: dict
:raises: ValueError for format violations or a duplicated key.
"""
if s is None:
return {}
d = {}
for item in [e.strip() for e... | [
"def",
"args_kvp_nodup",
"(",
"s",
")",
":",
"if",
"s",
"is",
"None",
":",
"return",
"{",
"}",
"d",
"=",
"{",
"}",
"for",
"item",
"in",
"[",
"e",
".",
"strip",
"(",
")",
"for",
"e",
"in",
"s",
".",
"split",
"(",
"\",\"",
")",
"]",
":",
"try... | Parse argument string as key=value pairs separated by commas.
:param s: Argument string
:return: Parsed value
:rtype: dict
:raises: ValueError for format violations or a duplicated key. | [
"Parse",
"argument",
"string",
"as",
"key",
"=",
"value",
"pairs",
"separated",
"by",
"commas",
"."
] | train | https://github.com/materialsproject/pymatgen-db/blob/02e4351c2cea431407644f49193e8bf43ed39b9a/matgendb/vv/util.py#L210-L235 |
materialsproject/pymatgen-db | matgendb/vv/util.py | JsonWalker.walk | def walk(self, o):
"""Walk a dict & transform.
"""
if isinstance(o, dict):
d = o if self._dx is None else self._dx(o)
return {k: self.walk(v) for k, v in d.items()}
elif isinstance(o, list):
return [self.walk(v) for v in o]
else:
re... | python | def walk(self, o):
"""Walk a dict & transform.
"""
if isinstance(o, dict):
d = o if self._dx is None else self._dx(o)
return {k: self.walk(v) for k, v in d.items()}
elif isinstance(o, list):
return [self.walk(v) for v in o]
else:
re... | [
"def",
"walk",
"(",
"self",
",",
"o",
")",
":",
"if",
"isinstance",
"(",
"o",
",",
"dict",
")",
":",
"d",
"=",
"o",
"if",
"self",
".",
"_dx",
"is",
"None",
"else",
"self",
".",
"_dx",
"(",
"o",
")",
"return",
"{",
"k",
":",
"self",
".",
"wa... | Walk a dict & transform. | [
"Walk",
"a",
"dict",
"&",
"transform",
"."
] | train | https://github.com/materialsproject/pymatgen-db/blob/02e4351c2cea431407644f49193e8bf43ed39b9a/matgendb/vv/util.py#L140-L149 |
materialsproject/pymatgen-db | matgendb/vv/util.py | JsonWalker.dict_expand | def dict_expand(o):
"""Expand keys in a dict with '.' in them into
sub-dictionaries, e.g.
{'a.b.c': 'foo'} ==> {'a': {'b': {'c': 'foo'}}}
"""
r = {}
for k, v in o.items():
if isinstance(k, str):
k = k.replace('$', '_')
if "." in k:... | python | def dict_expand(o):
"""Expand keys in a dict with '.' in them into
sub-dictionaries, e.g.
{'a.b.c': 'foo'} ==> {'a': {'b': {'c': 'foo'}}}
"""
r = {}
for k, v in o.items():
if isinstance(k, str):
k = k.replace('$', '_')
if "." in k:... | [
"def",
"dict_expand",
"(",
"o",
")",
":",
"r",
"=",
"{",
"}",
"for",
"k",
",",
"v",
"in",
"o",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
"(",
"k",
",",
"str",
")",
":",
"k",
"=",
"k",
".",
"replace",
"(",
"'$'",
",",
"'_'",
")",
"i... | Expand keys in a dict with '.' in them into
sub-dictionaries, e.g.
{'a.b.c': 'foo'} ==> {'a': {'b': {'c': 'foo'}}} | [
"Expand",
"keys",
"in",
"a",
"dict",
"with",
".",
"in",
"them",
"into",
"sub",
"-",
"dictionaries",
"e",
".",
"g",
"."
] | train | https://github.com/materialsproject/pymatgen-db/blob/02e4351c2cea431407644f49193e8bf43ed39b9a/matgendb/vv/util.py#L161-L181 |
materialsproject/pymatgen-db | matgendb/builders/incr.py | TrackedQueryEngine.collection_name | def collection_name(self, value):
"""Switch to another collection.
Note that you may have to set the aliases and default properties if the
schema of the new collection differs from the current collection.
"""
self._collection_name = value
self._mongo_coll = self.db[value]... | python | def collection_name(self, value):
"""Switch to another collection.
Note that you may have to set the aliases and default properties if the
schema of the new collection differs from the current collection.
"""
self._collection_name = value
self._mongo_coll = self.db[value]... | [
"def",
"collection_name",
"(",
"self",
",",
"value",
")",
":",
"self",
".",
"_collection_name",
"=",
"value",
"self",
".",
"_mongo_coll",
"=",
"self",
".",
"db",
"[",
"value",
"]",
"self",
".",
"collection",
"=",
"TrackedCollection",
"(",
"self",
".",
"_... | Switch to another collection.
Note that you may have to set the aliases and default properties if the
schema of the new collection differs from the current collection. | [
"Switch",
"to",
"another",
"collection",
".",
"Note",
"that",
"you",
"may",
"have",
"to",
"set",
"the",
"aliases",
"and",
"default",
"properties",
"if",
"the",
"schema",
"of",
"the",
"new",
"collection",
"differs",
"from",
"the",
"current",
"collection",
"."... | train | https://github.com/materialsproject/pymatgen-db/blob/02e4351c2cea431407644f49193e8bf43ed39b9a/matgendb/builders/incr.py#L128-L136 |
materialsproject/pymatgen-db | matgendb/builders/incr.py | TrackedCollection.tracked_find | def tracked_find(self, *args, **kwargs):
"""Replacement for regular ``find()``.
"""
_log.info("tracked_find.begin")
# if tracking is off, just call find (ie do nothing)
if self._tracking_off:
_log.info("tracked_find.end, tracking=off")
return self._coll_fi... | python | def tracked_find(self, *args, **kwargs):
"""Replacement for regular ``find()``.
"""
_log.info("tracked_find.begin")
# if tracking is off, just call find (ie do nothing)
if self._tracking_off:
_log.info("tracked_find.end, tracking=off")
return self._coll_fi... | [
"def",
"tracked_find",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"_log",
".",
"info",
"(",
"\"tracked_find.begin\"",
")",
"# if tracking is off, just call find (ie do nothing)",
"if",
"self",
".",
"_tracking_off",
":",
"_log",
".",
"info"... | Replacement for regular ``find()``. | [
"Replacement",
"for",
"regular",
"find",
"()",
"."
] | train | https://github.com/materialsproject/pymatgen-db/blob/02e4351c2cea431407644f49193e8bf43ed39b9a/matgendb/builders/incr.py#L179-L199 |
materialsproject/pymatgen-db | matgendb/builders/incr.py | Mark.update | def update(self):
"""Update the position of the mark in the collection.
:return: this object, for chaining
:rtype: Mark
"""
rec = self._c.find_one({}, {self._fld: 1}, sort=[(self._fld, -1)], limit=1)
if rec is None:
self._pos = self._empty_pos()
elif ... | python | def update(self):
"""Update the position of the mark in the collection.
:return: this object, for chaining
:rtype: Mark
"""
rec = self._c.find_one({}, {self._fld: 1}, sort=[(self._fld, -1)], limit=1)
if rec is None:
self._pos = self._empty_pos()
elif ... | [
"def",
"update",
"(",
"self",
")",
":",
"rec",
"=",
"self",
".",
"_c",
".",
"find_one",
"(",
"{",
"}",
",",
"{",
"self",
".",
"_fld",
":",
"1",
"}",
",",
"sort",
"=",
"[",
"(",
"self",
".",
"_fld",
",",
"-",
"1",
")",
"]",
",",
"limit",
"... | Update the position of the mark in the collection.
:return: this object, for chaining
:rtype: Mark | [
"Update",
"the",
"position",
"of",
"the",
"mark",
"in",
"the",
"collection",
"."
] | train | https://github.com/materialsproject/pymatgen-db/blob/02e4351c2cea431407644f49193e8bf43ed39b9a/matgendb/builders/incr.py#L249-L265 |
materialsproject/pymatgen-db | matgendb/builders/incr.py | Mark.as_dict | def as_dict(self):
"""Representation as a dict for JSON serialization.
"""
return {self.FLD_OP: self._op.name,
self.FLD_MARK: self._pos,
self.FLD_FLD: self._fld} | python | def as_dict(self):
"""Representation as a dict for JSON serialization.
"""
return {self.FLD_OP: self._op.name,
self.FLD_MARK: self._pos,
self.FLD_FLD: self._fld} | [
"def",
"as_dict",
"(",
"self",
")",
":",
"return",
"{",
"self",
".",
"FLD_OP",
":",
"self",
".",
"_op",
".",
"name",
",",
"self",
".",
"FLD_MARK",
":",
"self",
".",
"_pos",
",",
"self",
".",
"FLD_FLD",
":",
"self",
".",
"_fld",
"}"
] | Representation as a dict for JSON serialization. | [
"Representation",
"as",
"a",
"dict",
"for",
"JSON",
"serialization",
"."
] | train | https://github.com/materialsproject/pymatgen-db/blob/02e4351c2cea431407644f49193e8bf43ed39b9a/matgendb/builders/incr.py#L274-L279 |
materialsproject/pymatgen-db | matgendb/builders/incr.py | Mark.from_dict | def from_dict(cls, coll, d):
"""Construct from dict
:param coll: Collection for the mark
:param d: Input
:type d: dict
:return: new instance
:rtype: Mark
"""
return Mark(collection=coll, operation=Operation[d[cls.FLD_OP]],
pos=d[cls.FL... | python | def from_dict(cls, coll, d):
"""Construct from dict
:param coll: Collection for the mark
:param d: Input
:type d: dict
:return: new instance
:rtype: Mark
"""
return Mark(collection=coll, operation=Operation[d[cls.FLD_OP]],
pos=d[cls.FL... | [
"def",
"from_dict",
"(",
"cls",
",",
"coll",
",",
"d",
")",
":",
"return",
"Mark",
"(",
"collection",
"=",
"coll",
",",
"operation",
"=",
"Operation",
"[",
"d",
"[",
"cls",
".",
"FLD_OP",
"]",
"]",
",",
"pos",
"=",
"d",
"[",
"cls",
".",
"FLD_MARK... | Construct from dict
:param coll: Collection for the mark
:param d: Input
:type d: dict
:return: new instance
:rtype: Mark | [
"Construct",
"from",
"dict"
] | train | https://github.com/materialsproject/pymatgen-db/blob/02e4351c2cea431407644f49193e8bf43ed39b9a/matgendb/builders/incr.py#L284-L294 |
materialsproject/pymatgen-db | matgendb/builders/incr.py | Mark.query | def query(self):
"""A mongdb query expression to find all records with higher values
for this mark's fields in the collection.
:rtype: dict
"""
q = {}
for field, value in self._pos.items():
if value is None:
q.update({field: {'$exists': True}}... | python | def query(self):
"""A mongdb query expression to find all records with higher values
for this mark's fields in the collection.
:rtype: dict
"""
q = {}
for field, value in self._pos.items():
if value is None:
q.update({field: {'$exists': True}}... | [
"def",
"query",
"(",
"self",
")",
":",
"q",
"=",
"{",
"}",
"for",
"field",
",",
"value",
"in",
"self",
".",
"_pos",
".",
"items",
"(",
")",
":",
"if",
"value",
"is",
"None",
":",
"q",
".",
"update",
"(",
"{",
"field",
":",
"{",
"'$exists'",
"... | A mongdb query expression to find all records with higher values
for this mark's fields in the collection.
:rtype: dict | [
"A",
"mongdb",
"query",
"expression",
"to",
"find",
"all",
"records",
"with",
"higher",
"values",
"for",
"this",
"mark",
"s",
"fields",
"in",
"the",
"collection",
"."
] | train | https://github.com/materialsproject/pymatgen-db/blob/02e4351c2cea431407644f49193e8bf43ed39b9a/matgendb/builders/incr.py#L297-L309 |
materialsproject/pymatgen-db | matgendb/builders/incr.py | CollectionTracker.create | def create(self):
"""Create tracking collection.
Does nothing if tracking collection already exists.
"""
if self._track is None:
self._track = self.db[self.tracking_collection_name] | python | def create(self):
"""Create tracking collection.
Does nothing if tracking collection already exists.
"""
if self._track is None:
self._track = self.db[self.tracking_collection_name] | [
"def",
"create",
"(",
"self",
")",
":",
"if",
"self",
".",
"_track",
"is",
"None",
":",
"self",
".",
"_track",
"=",
"self",
".",
"db",
"[",
"self",
".",
"tracking_collection_name",
"]"
] | Create tracking collection.
Does nothing if tracking collection already exists. | [
"Create",
"tracking",
"collection",
".",
"Does",
"nothing",
"if",
"tracking",
"collection",
"already",
"exists",
"."
] | train | https://github.com/materialsproject/pymatgen-db/blob/02e4351c2cea431407644f49193e8bf43ed39b9a/matgendb/builders/incr.py#L348-L353 |
materialsproject/pymatgen-db | matgendb/builders/incr.py | CollectionTracker.save | def save(self, mark):
"""Save a position in this collection.
:param mark: The position to save
:type mark: Mark
:raises: DBError, NoTrackingCollection
"""
self._check_exists()
obj = mark.as_dict()
try:
# Make a 'filter' to find/update existing... | python | def save(self, mark):
"""Save a position in this collection.
:param mark: The position to save
:type mark: Mark
:raises: DBError, NoTrackingCollection
"""
self._check_exists()
obj = mark.as_dict()
try:
# Make a 'filter' to find/update existing... | [
"def",
"save",
"(",
"self",
",",
"mark",
")",
":",
"self",
".",
"_check_exists",
"(",
")",
"obj",
"=",
"mark",
".",
"as_dict",
"(",
")",
"try",
":",
"# Make a 'filter' to find/update existing record, which uses",
"# the field name and operation (but not the position).",... | Save a position in this collection.
:param mark: The position to save
:type mark: Mark
:raises: DBError, NoTrackingCollection | [
"Save",
"a",
"position",
"in",
"this",
"collection",
"."
] | train | https://github.com/materialsproject/pymatgen-db/blob/02e4351c2cea431407644f49193e8bf43ed39b9a/matgendb/builders/incr.py#L355-L371 |
materialsproject/pymatgen-db | matgendb/builders/incr.py | CollectionTracker.retrieve | def retrieve(self, operation, field=None):
"""Retrieve a position in this collection.
:param operation: Name of an operation
:type operation: :class:`Operation`
:param field: Name of field for sort order
:type field: str
:return: The position for this operation
:... | python | def retrieve(self, operation, field=None):
"""Retrieve a position in this collection.
:param operation: Name of an operation
:type operation: :class:`Operation`
:param field: Name of field for sort order
:type field: str
:return: The position for this operation
:... | [
"def",
"retrieve",
"(",
"self",
",",
"operation",
",",
"field",
"=",
"None",
")",
":",
"obj",
"=",
"self",
".",
"_get",
"(",
"operation",
",",
"field",
")",
"if",
"obj",
"is",
"None",
":",
"# empty Mark instance",
"return",
"Mark",
"(",
"collection",
"... | Retrieve a position in this collection.
:param operation: Name of an operation
:type operation: :class:`Operation`
:param field: Name of field for sort order
:type field: str
:return: The position for this operation
:rtype: Mark
:raises: NoTrackingCollection | [
"Retrieve",
"a",
"position",
"in",
"this",
"collection",
"."
] | train | https://github.com/materialsproject/pymatgen-db/blob/02e4351c2cea431407644f49193e8bf43ed39b9a/matgendb/builders/incr.py#L373-L388 |
materialsproject/pymatgen-db | matgendb/builders/incr.py | CollectionTracker._get | def _get(self, operation, field):
"""Get tracked position for a given operation and field."""
self._check_exists()
query = {Mark.FLD_OP: operation.name,
Mark.FLD_MARK + "." + field: {"$exists": True}}
return self._track.find_one(query) | python | def _get(self, operation, field):
"""Get tracked position for a given operation and field."""
self._check_exists()
query = {Mark.FLD_OP: operation.name,
Mark.FLD_MARK + "." + field: {"$exists": True}}
return self._track.find_one(query) | [
"def",
"_get",
"(",
"self",
",",
"operation",
",",
"field",
")",
":",
"self",
".",
"_check_exists",
"(",
")",
"query",
"=",
"{",
"Mark",
".",
"FLD_OP",
":",
"operation",
".",
"name",
",",
"Mark",
".",
"FLD_MARK",
"+",
"\".\"",
"+",
"field",
":",
"{... | Get tracked position for a given operation and field. | [
"Get",
"tracked",
"position",
"for",
"a",
"given",
"operation",
"and",
"field",
"."
] | train | https://github.com/materialsproject/pymatgen-db/blob/02e4351c2cea431407644f49193e8bf43ed39b9a/matgendb/builders/incr.py#L390-L395 |
materialsproject/pymatgen-db | matgendb/vv/diff.py | Differ.diff | def diff(self, c1, c2, only_missing=False, only_values=False, allow_dup=False):
"""Perform a difference between the 2 collections.
The first collection is treated as the previous one, and the second
is treated as the new one.
Note: this is not 'big data'-ready; we assume all the records... | python | def diff(self, c1, c2, only_missing=False, only_values=False, allow_dup=False):
"""Perform a difference between the 2 collections.
The first collection is treated as the previous one, and the second
is treated as the new one.
Note: this is not 'big data'-ready; we assume all the records... | [
"def",
"diff",
"(",
"self",
",",
"c1",
",",
"c2",
",",
"only_missing",
"=",
"False",
",",
"only_values",
"=",
"False",
",",
"allow_dup",
"=",
"False",
")",
":",
"# Connect.",
"_log",
".",
"info",
"(",
"\"connect.start\"",
")",
"if",
"isinstance",
"(",
... | Perform a difference between the 2 collections.
The first collection is treated as the previous one, and the second
is treated as the new one.
Note: this is not 'big data'-ready; we assume all the records can fit in memory.
:param c1: Collection (1) config file, or QueryEngine object
... | [
"Perform",
"a",
"difference",
"between",
"the",
"2",
"collections",
".",
"The",
"first",
"collection",
"is",
"treated",
"as",
"the",
"previous",
"one",
"and",
"the",
"second",
"is",
"treated",
"as",
"the",
"new",
"one",
"."
] | train | https://github.com/materialsproject/pymatgen-db/blob/02e4351c2cea431407644f49193e8bf43ed39b9a/matgendb/vv/diff.py#L70-L219 |
materialsproject/pymatgen-db | matgendb/query_engine.py | QueryEngine.collection_name | def collection_name(self, value):
"""Switch to another collection.
Note that you may have to set the aliases and default properties if the
schema of the new collection differs from the current collection.
"""
self._collection_name = value
self.collection = self.db[value] | python | def collection_name(self, value):
"""Switch to another collection.
Note that you may have to set the aliases and default properties if the
schema of the new collection differs from the current collection.
"""
self._collection_name = value
self.collection = self.db[value] | [
"def",
"collection_name",
"(",
"self",
",",
"value",
")",
":",
"self",
".",
"_collection_name",
"=",
"value",
"self",
".",
"collection",
"=",
"self",
".",
"db",
"[",
"value",
"]"
] | Switch to another collection.
Note that you may have to set the aliases and default properties if the
schema of the new collection differs from the current collection. | [
"Switch",
"to",
"another",
"collection",
".",
"Note",
"that",
"you",
"may",
"have",
"to",
"set",
"the",
"aliases",
"and",
"default",
"properties",
"if",
"the",
"schema",
"of",
"the",
"new",
"collection",
"differs",
"from",
"the",
"current",
"collection",
"."... | train | https://github.com/materialsproject/pymatgen-db/blob/02e4351c2cea431407644f49193e8bf43ed39b9a/matgendb/query_engine.py#L151-L157 |
materialsproject/pymatgen-db | matgendb/query_engine.py | QueryEngine.set_aliases_and_defaults | def set_aliases_and_defaults(self, aliases_config=None,
default_properties=None):
"""
Set the alias config and defaults to use. Typically used when
switching to a collection with a different schema.
Args:
aliases_config:
An al... | python | def set_aliases_and_defaults(self, aliases_config=None,
default_properties=None):
"""
Set the alias config and defaults to use. Typically used when
switching to a collection with a different schema.
Args:
aliases_config:
An al... | [
"def",
"set_aliases_and_defaults",
"(",
"self",
",",
"aliases_config",
"=",
"None",
",",
"default_properties",
"=",
"None",
")",
":",
"if",
"aliases_config",
"is",
"None",
":",
"with",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
... | Set the alias config and defaults to use. Typically used when
switching to a collection with a different schema.
Args:
aliases_config:
An alias dict to use. Defaults to None, which means the default
aliases defined in "aliases.json" is used. See constructor
... | [
"Set",
"the",
"alias",
"config",
"and",
"defaults",
"to",
"use",
".",
"Typically",
"used",
"when",
"switching",
"to",
"a",
"collection",
"with",
"a",
"different",
"schema",
"."
] | train | https://github.com/materialsproject/pymatgen-db/blob/02e4351c2cea431407644f49193e8bf43ed39b9a/matgendb/query_engine.py#L175-L205 |
materialsproject/pymatgen-db | matgendb/query_engine.py | QueryEngine.get_entries_in_system | def get_entries_in_system(self, elements, inc_structure=False,
optional_data=None, additional_criteria=None):
"""
Gets all entries in a chemical system, e.g. Li-Fe-O will return all
Li-O, Fe-O, Li-Fe, Li-Fe-O compounds.
.. note::
The get_entrie... | python | def get_entries_in_system(self, elements, inc_structure=False,
optional_data=None, additional_criteria=None):
"""
Gets all entries in a chemical system, e.g. Li-Fe-O will return all
Li-O, Fe-O, Li-Fe, Li-Fe-O compounds.
.. note::
The get_entrie... | [
"def",
"get_entries_in_system",
"(",
"self",
",",
"elements",
",",
"inc_structure",
"=",
"False",
",",
"optional_data",
"=",
"None",
",",
"additional_criteria",
"=",
"None",
")",
":",
"chemsys_list",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"len",
"(... | Gets all entries in a chemical system, e.g. Li-Fe-O will return all
Li-O, Fe-O, Li-Fe, Li-Fe-O compounds.
.. note::
The get_entries_in_system and get_entries methods should be used
with care. In essence, all entries, GGA, GGA+U or otherwise,
are returned. The data... | [
"Gets",
"all",
"entries",
"in",
"a",
"chemical",
"system",
"e",
".",
"g",
".",
"Li",
"-",
"Fe",
"-",
"O",
"will",
"return",
"all",
"Li",
"-",
"O",
"Fe",
"-",
"O",
"Li",
"-",
"Fe",
"Li",
"-",
"Fe",
"-",
"O",
"compounds",
"."
] | train | https://github.com/materialsproject/pymatgen-db/blob/02e4351c2cea431407644f49193e8bf43ed39b9a/matgendb/query_engine.py#L220-L261 |
materialsproject/pymatgen-db | matgendb/query_engine.py | QueryEngine.get_entries | def get_entries(self, criteria, inc_structure=False, optional_data=None):
"""
Get ComputedEntries satisfying a particular criteria.
.. note::
The get_entries_in_system and get_entries methods should be used
with care. In essence, all entries, GGA, GGA+U or otherwise,
... | python | def get_entries(self, criteria, inc_structure=False, optional_data=None):
"""
Get ComputedEntries satisfying a particular criteria.
.. note::
The get_entries_in_system and get_entries methods should be used
with care. In essence, all entries, GGA, GGA+U or otherwise,
... | [
"def",
"get_entries",
"(",
"self",
",",
"criteria",
",",
"inc_structure",
"=",
"False",
",",
"optional_data",
"=",
"None",
")",
":",
"all_entries",
"=",
"list",
"(",
")",
"optional_data",
"=",
"[",
"]",
"if",
"not",
"optional_data",
"else",
"list",
"(",
... | Get ComputedEntries satisfying a particular criteria.
.. note::
The get_entries_in_system and get_entries methods should be used
with care. In essence, all entries, GGA, GGA+U or otherwise,
are returned. The dataset is very heterogeneous and not
directly compa... | [
"Get",
"ComputedEntries",
"satisfying",
"a",
"particular",
"criteria",
"."
] | train | https://github.com/materialsproject/pymatgen-db/blob/02e4351c2cea431407644f49193e8bf43ed39b9a/matgendb/query_engine.py#L263-L327 |
materialsproject/pymatgen-db | matgendb/query_engine.py | QueryEngine._parse_criteria | def _parse_criteria(self, criteria):
"""
Internal method to perform mapping of criteria to proper mongo queries
using aliases, as well as some useful sanitization. For example, string
formulas such as "Fe2O3" are auto-converted to proper mongo queries of
{"Fe":2, "O":3}.
... | python | def _parse_criteria(self, criteria):
"""
Internal method to perform mapping of criteria to proper mongo queries
using aliases, as well as some useful sanitization. For example, string
formulas such as "Fe2O3" are auto-converted to proper mongo queries of
{"Fe":2, "O":3}.
... | [
"def",
"_parse_criteria",
"(",
"self",
",",
"criteria",
")",
":",
"if",
"criteria",
"is",
"None",
":",
"return",
"dict",
"(",
")",
"parsed_crit",
"=",
"dict",
"(",
")",
"for",
"k",
",",
"v",
"in",
"self",
".",
"default_criteria",
".",
"items",
"(",
"... | Internal method to perform mapping of criteria to proper mongo queries
using aliases, as well as some useful sanitization. For example, string
formulas such as "Fe2O3" are auto-converted to proper mongo queries of
{"Fe":2, "O":3}.
If 'criteria' is None, returns an empty dict. Putting th... | [
"Internal",
"method",
"to",
"perform",
"mapping",
"of",
"criteria",
"to",
"proper",
"mongo",
"queries",
"using",
"aliases",
"as",
"well",
"as",
"some",
"useful",
"sanitization",
".",
"For",
"example",
"string",
"formulas",
"such",
"as",
"Fe2O3",
"are",
"auto",... | train | https://github.com/materialsproject/pymatgen-db/blob/02e4351c2cea431407644f49193e8bf43ed39b9a/matgendb/query_engine.py#L329-L362 |
materialsproject/pymatgen-db | matgendb/query_engine.py | QueryEngine.ensure_index | def ensure_index(self, key, unique=False):
"""Wrapper for pymongo.Collection.ensure_index
"""
return self.collection.ensure_index(key, unique=unique) | python | def ensure_index(self, key, unique=False):
"""Wrapper for pymongo.Collection.ensure_index
"""
return self.collection.ensure_index(key, unique=unique) | [
"def",
"ensure_index",
"(",
"self",
",",
"key",
",",
"unique",
"=",
"False",
")",
":",
"return",
"self",
".",
"collection",
".",
"ensure_index",
"(",
"key",
",",
"unique",
"=",
"unique",
")"
] | Wrapper for pymongo.Collection.ensure_index | [
"Wrapper",
"for",
"pymongo",
".",
"Collection",
".",
"ensure_index"
] | train | https://github.com/materialsproject/pymatgen-db/blob/02e4351c2cea431407644f49193e8bf43ed39b9a/matgendb/query_engine.py#L364-L367 |
materialsproject/pymatgen-db | matgendb/query_engine.py | QueryEngine.query | def query(self, properties=None, criteria=None, distinct_key=None,
**kwargs):
"""
Convenience method for database access. All properties and criteria
can be specified using simplified names defined in Aliases. You can
use the supported_properties property to get the list ... | python | def query(self, properties=None, criteria=None, distinct_key=None,
**kwargs):
"""
Convenience method for database access. All properties and criteria
can be specified using simplified names defined in Aliases. You can
use the supported_properties property to get the list ... | [
"def",
"query",
"(",
"self",
",",
"properties",
"=",
"None",
",",
"criteria",
"=",
"None",
",",
"distinct_key",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"properties",
"is",
"not",
"None",
":",
"props",
",",
"prop_dict",
"=",
"self",
".",... | Convenience method for database access. All properties and criteria
can be specified using simplified names defined in Aliases. You can
use the supported_properties property to get the list of supported
properties.
Results are returned as an iterator of dicts to ensure memory and cpu
... | [
"Convenience",
"method",
"for",
"database",
"access",
".",
"All",
"properties",
"and",
"criteria",
"can",
"be",
"specified",
"using",
"simplified",
"names",
"defined",
"in",
"Aliases",
".",
"You",
"can",
"use",
"the",
"supported_properties",
"property",
"to",
"g... | train | https://github.com/materialsproject/pymatgen-db/blob/02e4351c2cea431407644f49193e8bf43ed39b9a/matgendb/query_engine.py#L369-L417 |
materialsproject/pymatgen-db | matgendb/query_engine.py | QueryEngine._parse_properties | def _parse_properties(self, properties):
"""Make list of properties into 2 things:
(1) dictionary of { 'aliased-field': 1, ... } for a mongodb query eg. {''}
(2) dictionary, keyed by aliased field, for display
"""
props = {}
# TODO: clean up prop_dict?
prop_dict =... | python | def _parse_properties(self, properties):
"""Make list of properties into 2 things:
(1) dictionary of { 'aliased-field': 1, ... } for a mongodb query eg. {''}
(2) dictionary, keyed by aliased field, for display
"""
props = {}
# TODO: clean up prop_dict?
prop_dict =... | [
"def",
"_parse_properties",
"(",
"self",
",",
"properties",
")",
":",
"props",
"=",
"{",
"}",
"# TODO: clean up prop_dict?",
"prop_dict",
"=",
"OrderedDict",
"(",
")",
"# We use a dict instead of list to provide for a richer syntax",
"for",
"p",
"in",
"properties",
":",... | Make list of properties into 2 things:
(1) dictionary of { 'aliased-field': 1, ... } for a mongodb query eg. {''}
(2) dictionary, keyed by aliased field, for display | [
"Make",
"list",
"of",
"properties",
"into",
"2",
"things",
":",
"(",
"1",
")",
"dictionary",
"of",
"{",
"aliased",
"-",
"field",
":",
"1",
"...",
"}",
"for",
"a",
"mongodb",
"query",
"eg",
".",
"{",
"}",
"(",
"2",
")",
"dictionary",
"keyed",
"by",
... | train | https://github.com/materialsproject/pymatgen-db/blob/02e4351c2cea431407644f49193e8bf43ed39b9a/matgendb/query_engine.py#L419-L449 |
materialsproject/pymatgen-db | matgendb/query_engine.py | QueryEngine.query_one | def query_one(self, *args, **kwargs):
"""Return first document from :meth:`query`, with same parameters.
"""
for r in self.query(*args, **kwargs):
return r
return None | python | def query_one(self, *args, **kwargs):
"""Return first document from :meth:`query`, with same parameters.
"""
for r in self.query(*args, **kwargs):
return r
return None | [
"def",
"query_one",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"r",
"in",
"self",
".",
"query",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"r",
"return",
"None"
] | Return first document from :meth:`query`, with same parameters. | [
"Return",
"first",
"document",
"from",
":",
"meth",
":",
"query",
"with",
"same",
"parameters",
"."
] | train | https://github.com/materialsproject/pymatgen-db/blob/02e4351c2cea431407644f49193e8bf43ed39b9a/matgendb/query_engine.py#L451-L456 |
materialsproject/pymatgen-db | matgendb/query_engine.py | QueryEngine.get_structure_from_id | def get_structure_from_id(self, task_id, final_structure=True):
"""
Returns a structure from the database given the task id.
Args:
task_id:
The task_id to query for.
final_structure:
Whether to obtain the final or initial structure. Defaul... | python | def get_structure_from_id(self, task_id, final_structure=True):
"""
Returns a structure from the database given the task id.
Args:
task_id:
The task_id to query for.
final_structure:
Whether to obtain the final or initial structure. Defaul... | [
"def",
"get_structure_from_id",
"(",
"self",
",",
"task_id",
",",
"final_structure",
"=",
"True",
")",
":",
"args",
"=",
"{",
"'task_id'",
":",
"task_id",
"}",
"field",
"=",
"'output.crystal'",
"if",
"final_structure",
"else",
"'input.crystal'",
"results",
"=",
... | Returns a structure from the database given the task id.
Args:
task_id:
The task_id to query for.
final_structure:
Whether to obtain the final or initial structure. Defaults to
True. | [
"Returns",
"a",
"structure",
"from",
"the",
"database",
"given",
"the",
"task",
"id",
"."
] | train | https://github.com/materialsproject/pymatgen-db/blob/02e4351c2cea431407644f49193e8bf43ed39b9a/matgendb/query_engine.py#L458-L478 |
materialsproject/pymatgen-db | matgendb/query_engine.py | QueryEngine.from_config | def from_config(config_file, use_admin=False):
"""
Initialize a QueryEngine from a JSON config file generated using mgdb
init.
Args:
config_file:
Filename of config file.
use_admin:
If True, the admin user and password in the confi... | python | def from_config(config_file, use_admin=False):
"""
Initialize a QueryEngine from a JSON config file generated using mgdb
init.
Args:
config_file:
Filename of config file.
use_admin:
If True, the admin user and password in the confi... | [
"def",
"from_config",
"(",
"config_file",
",",
"use_admin",
"=",
"False",
")",
":",
"with",
"open",
"(",
"config_file",
")",
"as",
"f",
":",
"d",
"=",
"json",
".",
"load",
"(",
"f",
")",
"user",
"=",
"d",
"[",
"\"admin_user\"",
"]",
"if",
"use_admin"... | Initialize a QueryEngine from a JSON config file generated using mgdb
init.
Args:
config_file:
Filename of config file.
use_admin:
If True, the admin user and password in the config file is
used. Otherwise, the readonly_user and pa... | [
"Initialize",
"a",
"QueryEngine",
"from",
"a",
"JSON",
"config",
"file",
"generated",
"using",
"mgdb",
"init",
"."
] | train | https://github.com/materialsproject/pymatgen-db/blob/02e4351c2cea431407644f49193e8bf43ed39b9a/matgendb/query_engine.py#L485-L509 |
materialsproject/pymatgen-db | matgendb/query_engine.py | QueryEngine.get_dos_from_id | def get_dos_from_id(self, task_id):
"""
Overrides the get_dos_from_id for the MIT gridfs format.
"""
args = {'task_id': task_id}
fields = ['calculations']
structure = self.get_structure_from_id(task_id)
dosid = None
for r in self.query(fields, args):
... | python | def get_dos_from_id(self, task_id):
"""
Overrides the get_dos_from_id for the MIT gridfs format.
"""
args = {'task_id': task_id}
fields = ['calculations']
structure = self.get_structure_from_id(task_id)
dosid = None
for r in self.query(fields, args):
... | [
"def",
"get_dos_from_id",
"(",
"self",
",",
"task_id",
")",
":",
"args",
"=",
"{",
"'task_id'",
":",
"task_id",
"}",
"fields",
"=",
"[",
"'calculations'",
"]",
"structure",
"=",
"self",
".",
"get_structure_from_id",
"(",
"task_id",
")",
"dosid",
"=",
"None... | Overrides the get_dos_from_id for the MIT gridfs format. | [
"Overrides",
"the",
"get_dos_from_id",
"for",
"the",
"MIT",
"gridfs",
"format",
"."
] | train | https://github.com/materialsproject/pymatgen-db/blob/02e4351c2cea431407644f49193e8bf43ed39b9a/matgendb/query_engine.py#L517-L549 |
materialsproject/pymatgen-db | matgendb/query_engine.py | QueryResults._wrapper | def _wrapper(self, func):
"""
This function wraps all callable objects returned by self.__getattr__.
If the result is a cursor, wrap it into a QueryResults object
so that you can invoke postprocess functions in self._pproc
"""
def wrapped(*args, **kwargs):
ret... | python | def _wrapper(self, func):
"""
This function wraps all callable objects returned by self.__getattr__.
If the result is a cursor, wrap it into a QueryResults object
so that you can invoke postprocess functions in self._pproc
"""
def wrapped(*args, **kwargs):
ret... | [
"def",
"_wrapper",
"(",
"self",
",",
"func",
")",
":",
"def",
"wrapped",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"ret_val",
"=",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"if",
"isinstance",
"(",
"ret_val",
",",
"pymong... | This function wraps all callable objects returned by self.__getattr__.
If the result is a cursor, wrap it into a QueryResults object
so that you can invoke postprocess functions in self._pproc | [
"This",
"function",
"wraps",
"all",
"callable",
"objects",
"returned",
"by",
"self",
".",
"__getattr__",
".",
"If",
"the",
"result",
"is",
"a",
"cursor",
"wrap",
"it",
"into",
"a",
"QueryResults",
"object",
"so",
"that",
"you",
"can",
"invoke",
"postprocess"... | train | https://github.com/materialsproject/pymatgen-db/blob/02e4351c2cea431407644f49193e8bf43ed39b9a/matgendb/query_engine.py#L574-L586 |
materialsproject/pymatgen-db | matgendb/query_engine.py | QueryResults._mapped_result | def _mapped_result(self, r):
"""Transform/map a result.
"""
# Apply result_post funcs for pulling out sandbox properties
for func in self._pproc:
func(r)
# If we haven't asked for specific properties, just return object
if not self._prop_dict:
resu... | python | def _mapped_result(self, r):
"""Transform/map a result.
"""
# Apply result_post funcs for pulling out sandbox properties
for func in self._pproc:
func(r)
# If we haven't asked for specific properties, just return object
if not self._prop_dict:
resu... | [
"def",
"_mapped_result",
"(",
"self",
",",
"r",
")",
":",
"# Apply result_post funcs for pulling out sandbox properties",
"for",
"func",
"in",
"self",
".",
"_pproc",
":",
"func",
"(",
"r",
")",
"# If we haven't asked for specific properties, just return object",
"if",
"no... | Transform/map a result. | [
"Transform",
"/",
"map",
"a",
"result",
"."
] | train | https://github.com/materialsproject/pymatgen-db/blob/02e4351c2cea431407644f49193e8bf43ed39b9a/matgendb/query_engine.py#L623-L640 |
materialsproject/pymatgen-db | matgendb/builders/schema.py | add_schemas | def add_schemas(path, ext="json"):
"""Add schemas from files in 'path'.
:param path: Path with schema files. Schemas are named by their file,
with the extension stripped. e.g., if path is "/tmp/foo",
then the schema in "/tmp/foo/bar.json" will be named "bar".
:type path: s... | python | def add_schemas(path, ext="json"):
"""Add schemas from files in 'path'.
:param path: Path with schema files. Schemas are named by their file,
with the extension stripped. e.g., if path is "/tmp/foo",
then the schema in "/tmp/foo/bar.json" will be named "bar".
:type path: s... | [
"def",
"add_schemas",
"(",
"path",
",",
"ext",
"=",
"\"json\"",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"raise",
"SchemaPathError",
"(",
")",
"filepat",
"=",
"\"*.\"",
"+",
"ext",
"if",
"ext",
"else",
"\"*\"",
... | Add schemas from files in 'path'.
:param path: Path with schema files. Schemas are named by their file,
with the extension stripped. e.g., if path is "/tmp/foo",
then the schema in "/tmp/foo/bar.json" will be named "bar".
:type path: str
:param ext: File extension that ide... | [
"Add",
"schemas",
"from",
"files",
"in",
"path",
"."
] | train | https://github.com/materialsproject/pymatgen-db/blob/02e4351c2cea431407644f49193e8bf43ed39b9a/matgendb/builders/schema.py#L55-L78 |
materialsproject/pymatgen-db | matgendb/builders/schema.py | load_schema | def load_schema(file_or_fp):
"""Load schema from file.
:param file_or_fp: File name or file object
:type file_or_fp: str, file
:raise: IOError if file cannot be opened or read, ValueError if
file is not valid JSON or JSON is not a valid schema.
"""
fp = open(file_or_fp, 'r') if isin... | python | def load_schema(file_or_fp):
"""Load schema from file.
:param file_or_fp: File name or file object
:type file_or_fp: str, file
:raise: IOError if file cannot be opened or read, ValueError if
file is not valid JSON or JSON is not a valid schema.
"""
fp = open(file_or_fp, 'r') if isin... | [
"def",
"load_schema",
"(",
"file_or_fp",
")",
":",
"fp",
"=",
"open",
"(",
"file_or_fp",
",",
"'r'",
")",
"if",
"isinstance",
"(",
"file_or_fp",
",",
"str",
")",
"else",
"file_or_fp",
"obj",
"=",
"json",
".",
"load",
"(",
"fp",
")",
"schema",
"=",
"S... | Load schema from file.
:param file_or_fp: File name or file object
:type file_or_fp: str, file
:raise: IOError if file cannot be opened or read, ValueError if
file is not valid JSON or JSON is not a valid schema. | [
"Load",
"schema",
"from",
"file",
"."
] | train | https://github.com/materialsproject/pymatgen-db/blob/02e4351c2cea431407644f49193e8bf43ed39b9a/matgendb/builders/schema.py#L93-L104 |
materialsproject/pymatgen-db | matgendb/builders/schema.py | Schema.json_schema | def json_schema(self, **add_keys):
"""Convert our compact schema representation to the standard, but more verbose,
JSON Schema standard.
Example JSON schema: http://json-schema.org/examples.html
Core standard: http://json-schema.org/latest/json-schema-core.html
:param add_keys:... | python | def json_schema(self, **add_keys):
"""Convert our compact schema representation to the standard, but more verbose,
JSON Schema standard.
Example JSON schema: http://json-schema.org/examples.html
Core standard: http://json-schema.org/latest/json-schema-core.html
:param add_keys:... | [
"def",
"json_schema",
"(",
"self",
",",
"*",
"*",
"add_keys",
")",
":",
"self",
".",
"_json_schema_keys",
"=",
"add_keys",
"if",
"self",
".",
"_json_schema",
"is",
"None",
":",
"self",
".",
"_json_schema",
"=",
"self",
".",
"_build_schema",
"(",
"self",
... | Convert our compact schema representation to the standard, but more verbose,
JSON Schema standard.
Example JSON schema: http://json-schema.org/examples.html
Core standard: http://json-schema.org/latest/json-schema-core.html
:param add_keys: Key, default value pairs to add in,
... | [
"Convert",
"our",
"compact",
"schema",
"representation",
"to",
"the",
"standard",
"but",
"more",
"verbose",
"JSON",
"Schema",
"standard",
"."
] | train | https://github.com/materialsproject/pymatgen-db/blob/02e4351c2cea431407644f49193e8bf43ed39b9a/matgendb/builders/schema.py#L180-L193 |
materialsproject/pymatgen-db | matgendb/builders/schema.py | Schema._build_schema | def _build_schema(self, s):
"""Recursive schema builder, called by `json_schema`.
"""
w = self._whatis(s)
if w == self.IS_LIST:
w0 = self._whatis(s[0])
js = {"type": "array",
"items": {"type": self._jstype(w0, s[0])}}
elif w == self.IS_DI... | python | def _build_schema(self, s):
"""Recursive schema builder, called by `json_schema`.
"""
w = self._whatis(s)
if w == self.IS_LIST:
w0 = self._whatis(s[0])
js = {"type": "array",
"items": {"type": self._jstype(w0, s[0])}}
elif w == self.IS_DI... | [
"def",
"_build_schema",
"(",
"self",
",",
"s",
")",
":",
"w",
"=",
"self",
".",
"_whatis",
"(",
"s",
")",
"if",
"w",
"==",
"self",
".",
"IS_LIST",
":",
"w0",
"=",
"self",
".",
"_whatis",
"(",
"s",
"[",
"0",
"]",
")",
"js",
"=",
"{",
"\"type\"... | Recursive schema builder, called by `json_schema`. | [
"Recursive",
"schema",
"builder",
"called",
"by",
"json_schema",
"."
] | train | https://github.com/materialsproject/pymatgen-db/blob/02e4351c2cea431407644f49193e8bf43ed39b9a/matgendb/builders/schema.py#L195-L214 |
materialsproject/pymatgen-db | matgendb/builders/schema.py | Schema._jstype | def _jstype(self, stype, sval):
"""Get JavaScript name for given data type, called by `_build_schema`.
"""
if stype == self.IS_LIST:
return "array"
if stype == self.IS_DICT:
return "object"
if isinstance(sval, Scalar):
return sval.jstype
... | python | def _jstype(self, stype, sval):
"""Get JavaScript name for given data type, called by `_build_schema`.
"""
if stype == self.IS_LIST:
return "array"
if stype == self.IS_DICT:
return "object"
if isinstance(sval, Scalar):
return sval.jstype
... | [
"def",
"_jstype",
"(",
"self",
",",
"stype",
",",
"sval",
")",
":",
"if",
"stype",
"==",
"self",
".",
"IS_LIST",
":",
"return",
"\"array\"",
"if",
"stype",
"==",
"self",
".",
"IS_DICT",
":",
"return",
"\"object\"",
"if",
"isinstance",
"(",
"sval",
",",... | Get JavaScript name for given data type, called by `_build_schema`. | [
"Get",
"JavaScript",
"name",
"for",
"given",
"data",
"type",
"called",
"by",
"_build_schema",
"."
] | train | https://github.com/materialsproject/pymatgen-db/blob/02e4351c2cea431407644f49193e8bf43ed39b9a/matgendb/builders/schema.py#L216-L227 |
materialsproject/pymatgen-db | matgendb/builders/util.py | get_schema_dir | def get_schema_dir(db_version=1):
"""Get path to directory with schemata.
:param db_version: Version of the database
:type db_version: int
:return: Path
:rtype: str
"""
v = str(db_version)
return os.path.join(_top_dir, '..', 'schemata', 'versions', v) | python | def get_schema_dir(db_version=1):
"""Get path to directory with schemata.
:param db_version: Version of the database
:type db_version: int
:return: Path
:rtype: str
"""
v = str(db_version)
return os.path.join(_top_dir, '..', 'schemata', 'versions', v) | [
"def",
"get_schema_dir",
"(",
"db_version",
"=",
"1",
")",
":",
"v",
"=",
"str",
"(",
"db_version",
")",
"return",
"os",
".",
"path",
".",
"join",
"(",
"_top_dir",
",",
"'..'",
",",
"'schemata'",
",",
"'versions'",
",",
"v",
")"
] | Get path to directory with schemata.
:param db_version: Version of the database
:type db_version: int
:return: Path
:rtype: str | [
"Get",
"path",
"to",
"directory",
"with",
"schemata",
"."
] | train | https://github.com/materialsproject/pymatgen-db/blob/02e4351c2cea431407644f49193e8bf43ed39b9a/matgendb/builders/util.py#L36-L45 |
materialsproject/pymatgen-db | matgendb/builders/util.py | get_schema_file | def get_schema_file(db_version=1, db="mg_core", collection="materials"):
"""Get file with appropriate schema.
:param db_version: Version of the database
:type db_version: int
:param db: Name of database, e.g. 'mg_core'
:type db: str
:param collection: Name of collection, e.g. 'materials'
:t... | python | def get_schema_file(db_version=1, db="mg_core", collection="materials"):
"""Get file with appropriate schema.
:param db_version: Version of the database
:type db_version: int
:param db: Name of database, e.g. 'mg_core'
:type db: str
:param collection: Name of collection, e.g. 'materials'
:t... | [
"def",
"get_schema_file",
"(",
"db_version",
"=",
"1",
",",
"db",
"=",
"\"mg_core\"",
",",
"collection",
"=",
"\"materials\"",
")",
":",
"d",
"=",
"get_schema_dir",
"(",
"db_version",
"=",
"db_version",
")",
"schemafile",
"=",
"\"{}.{}.json\"",
".",
"format",
... | Get file with appropriate schema.
:param db_version: Version of the database
:type db_version: int
:param db: Name of database, e.g. 'mg_core'
:type db: str
:param collection: Name of collection, e.g. 'materials'
:type collection: str
:return: File with schema
:rtype: file
:raise: I... | [
"Get",
"file",
"with",
"appropriate",
"schema",
"."
] | train | https://github.com/materialsproject/pymatgen-db/blob/02e4351c2cea431407644f49193e8bf43ed39b9a/matgendb/builders/util.py#L48-L64 |
materialsproject/pymatgen-db | matgendb/dbconfig.py | get_settings | def get_settings(infile):
"""Read settings from input file.
:param infile: Input file for JSON settings.
:type infile: file or str path
:return: Settings parsed from file
:rtype: dict
"""
settings = yaml.load(_as_file(infile))
if not hasattr(settings, 'keys'):
raise ValueError("... | python | def get_settings(infile):
"""Read settings from input file.
:param infile: Input file for JSON settings.
:type infile: file or str path
:return: Settings parsed from file
:rtype: dict
"""
settings = yaml.load(_as_file(infile))
if not hasattr(settings, 'keys'):
raise ValueError("... | [
"def",
"get_settings",
"(",
"infile",
")",
":",
"settings",
"=",
"yaml",
".",
"load",
"(",
"_as_file",
"(",
"infile",
")",
")",
"if",
"not",
"hasattr",
"(",
"settings",
",",
"'keys'",
")",
":",
"raise",
"ValueError",
"(",
"\"Settings not found in {}\"",
".... | Read settings from input file.
:param infile: Input file for JSON settings.
:type infile: file or str path
:return: Settings parsed from file
:rtype: dict | [
"Read",
"settings",
"from",
"input",
"file",
"."
] | train | https://github.com/materialsproject/pymatgen-db/blob/02e4351c2cea431407644f49193e8bf43ed39b9a/matgendb/dbconfig.py#L135-L155 |
materialsproject/pymatgen-db | matgendb/dbconfig.py | auth_aliases | def auth_aliases(d):
"""Interpret user/password aliases.
"""
for alias, real in ((USER_KEY, "readonly_user"),
(PASS_KEY, "readonly_password")):
if alias in d:
d[real] = d[alias]
del d[alias] | python | def auth_aliases(d):
"""Interpret user/password aliases.
"""
for alias, real in ((USER_KEY, "readonly_user"),
(PASS_KEY, "readonly_password")):
if alias in d:
d[real] = d[alias]
del d[alias] | [
"def",
"auth_aliases",
"(",
"d",
")",
":",
"for",
"alias",
",",
"real",
"in",
"(",
"(",
"USER_KEY",
",",
"\"readonly_user\"",
")",
",",
"(",
"PASS_KEY",
",",
"\"readonly_password\"",
")",
")",
":",
"if",
"alias",
"in",
"d",
":",
"d",
"[",
"real",
"]"... | Interpret user/password aliases. | [
"Interpret",
"user",
"/",
"password",
"aliases",
"."
] | train | https://github.com/materialsproject/pymatgen-db/blob/02e4351c2cea431407644f49193e8bf43ed39b9a/matgendb/dbconfig.py#L157-L164 |
materialsproject/pymatgen-db | matgendb/dbconfig.py | normalize_auth | def normalize_auth(settings, admin=True, readonly=True, readonly_first=False):
"""Transform the readonly/admin user and password to simple user/password,
as expected by QueryEngine. If return value is true, then
admin or readonly password will be in keys "user" and "password".
:param settings: Connecti... | python | def normalize_auth(settings, admin=True, readonly=True, readonly_first=False):
"""Transform the readonly/admin user and password to simple user/password,
as expected by QueryEngine. If return value is true, then
admin or readonly password will be in keys "user" and "password".
:param settings: Connecti... | [
"def",
"normalize_auth",
"(",
"settings",
",",
"admin",
"=",
"True",
",",
"readonly",
"=",
"True",
",",
"readonly_first",
"=",
"False",
")",
":",
"U",
",",
"P",
"=",
"USER_KEY",
",",
"PASS_KEY",
"# If user/password, un-prefixed, exists, do nothing.",
"if",
"U",
... | Transform the readonly/admin user and password to simple user/password,
as expected by QueryEngine. If return value is true, then
admin or readonly password will be in keys "user" and "password".
:param settings: Connection settings
:type settings: dict
:param admin: Check for admin password
:p... | [
"Transform",
"the",
"readonly",
"/",
"admin",
"user",
"and",
"password",
"to",
"simple",
"user",
"/",
"password",
"as",
"expected",
"by",
"QueryEngine",
".",
"If",
"return",
"value",
"is",
"true",
"then",
"admin",
"or",
"readonly",
"password",
"will",
"be",
... | train | https://github.com/materialsproject/pymatgen-db/blob/02e4351c2cea431407644f49193e8bf43ed39b9a/matgendb/dbconfig.py#L166-L207 |
materialsproject/pymatgen-db | matgendb/vv/report.py | Emailer.send | def send(self, text, fmt):
"""Send the email message.
:param text: The text to send
:type text: str
:param fmt: The name of the format of the text
:type fmt: str
:return: Number of recipients it was sent to
:rtype: int
"""
main_fmt, sub_fmt = fmt.... | python | def send(self, text, fmt):
"""Send the email message.
:param text: The text to send
:type text: str
:param fmt: The name of the format of the text
:type fmt: str
:return: Number of recipients it was sent to
:rtype: int
"""
main_fmt, sub_fmt = fmt.... | [
"def",
"send",
"(",
"self",
",",
"text",
",",
"fmt",
")",
":",
"main_fmt",
",",
"sub_fmt",
"=",
"fmt",
".",
"split",
"(",
"'/'",
")",
"if",
"sub_fmt",
".",
"lower",
"(",
")",
"==",
"\"text\"",
":",
"msg",
"=",
"MIMEText",
"(",
"text",
",",
"\"pla... | Send the email message.
:param text: The text to send
:type text: str
:param fmt: The name of the format of the text
:type fmt: str
:return: Number of recipients it was sent to
:rtype: int | [
"Send",
"the",
"email",
"message",
"."
] | train | https://github.com/materialsproject/pymatgen-db/blob/02e4351c2cea431407644f49193e8bf43ed39b9a/matgendb/vv/report.py#L376-L414 |
materialsproject/pymatgen-db | matgendb/vv/report.py | DiffFormatter.result_subsets | def result_subsets(self, rs):
"""Break a result set into subsets with the same keys.
:param rs: Result set, rows of a result as a list of dicts
:type rs: list of dict
:return: A set with distinct keys (tuples), and a dict, by these tuples, of max. widths for each column
"""
... | python | def result_subsets(self, rs):
"""Break a result set into subsets with the same keys.
:param rs: Result set, rows of a result as a list of dicts
:type rs: list of dict
:return: A set with distinct keys (tuples), and a dict, by these tuples, of max. widths for each column
"""
... | [
"def",
"result_subsets",
"(",
"self",
",",
"rs",
")",
":",
"keyset",
",",
"maxwid",
"=",
"set",
"(",
")",
",",
"{",
"}",
"for",
"r",
"in",
"rs",
":",
"key",
"=",
"tuple",
"(",
"sorted",
"(",
"r",
".",
"keys",
"(",
")",
")",
")",
"keyset",
"."... | Break a result set into subsets with the same keys.
:param rs: Result set, rows of a result as a list of dicts
:type rs: list of dict
:return: A set with distinct keys (tuples), and a dict, by these tuples, of max. widths for each column | [
"Break",
"a",
"result",
"set",
"into",
"subsets",
"with",
"the",
"same",
"keys",
"."
] | train | https://github.com/materialsproject/pymatgen-db/blob/02e4351c2cea431407644f49193e8bf43ed39b9a/matgendb/vv/report.py#L449-L465 |
materialsproject/pymatgen-db | matgendb/vv/report.py | DiffFormatter.ordered_cols | def ordered_cols(self, columns, section):
"""Return ordered list of columns, from given columns and the name of the section
"""
columns = list(columns) # might be a tuple
fixed_cols = [self.key]
if section.lower() == "different":
fixed_cols.extend([Differ.CHANGED_MAT... | python | def ordered_cols(self, columns, section):
"""Return ordered list of columns, from given columns and the name of the section
"""
columns = list(columns) # might be a tuple
fixed_cols = [self.key]
if section.lower() == "different":
fixed_cols.extend([Differ.CHANGED_MAT... | [
"def",
"ordered_cols",
"(",
"self",
",",
"columns",
",",
"section",
")",
":",
"columns",
"=",
"list",
"(",
"columns",
")",
"# might be a tuple",
"fixed_cols",
"=",
"[",
"self",
".",
"key",
"]",
"if",
"section",
".",
"lower",
"(",
")",
"==",
"\"different\... | Return ordered list of columns, from given columns and the name of the section | [
"Return",
"ordered",
"list",
"of",
"columns",
"from",
"given",
"columns",
"and",
"the",
"name",
"of",
"the",
"section"
] | train | https://github.com/materialsproject/pymatgen-db/blob/02e4351c2cea431407644f49193e8bf43ed39b9a/matgendb/vv/report.py#L467-L476 |
materialsproject/pymatgen-db | matgendb/vv/report.py | DiffFormatter.sort_rows | def sort_rows(self, rows, section):
"""Sort the rows, as appropriate for the section.
:param rows: List of tuples (all same length, same values in each position)
:param section: Name of section, should match const in Differ class
:return: None; rows are sorted in-place
"""
... | python | def sort_rows(self, rows, section):
"""Sort the rows, as appropriate for the section.
:param rows: List of tuples (all same length, same values in each position)
:param section: Name of section, should match const in Differ class
:return: None; rows are sorted in-place
"""
... | [
"def",
"sort_rows",
"(",
"self",
",",
"rows",
",",
"section",
")",
":",
"#print(\"@@ SORT ROWS:\\n{}\".format(rows))",
"# Section-specific determination of sort key",
"if",
"section",
".",
"lower",
"(",
")",
"==",
"Differ",
".",
"CHANGED",
".",
"lower",
"(",
")",
... | Sort the rows, as appropriate for the section.
:param rows: List of tuples (all same length, same values in each position)
:param section: Name of section, should match const in Differ class
:return: None; rows are sorted in-place | [
"Sort",
"the",
"rows",
"as",
"appropriate",
"for",
"the",
"section",
"."
] | train | https://github.com/materialsproject/pymatgen-db/blob/02e4351c2cea431407644f49193e8bf43ed39b9a/matgendb/vv/report.py#L478-L492 |
materialsproject/pymatgen-db | matgendb/vv/report.py | DiffJsonFormatter.document | def document(self, result):
"""Build dict for MongoDB, expanding result keys as we go.
"""
self._add_meta(result)
walker = JsonWalker(JsonWalker.value_json, JsonWalker.dict_expand)
r = walker.walk(result)
return r | python | def document(self, result):
"""Build dict for MongoDB, expanding result keys as we go.
"""
self._add_meta(result)
walker = JsonWalker(JsonWalker.value_json, JsonWalker.dict_expand)
r = walker.walk(result)
return r | [
"def",
"document",
"(",
"self",
",",
"result",
")",
":",
"self",
".",
"_add_meta",
"(",
"result",
")",
"walker",
"=",
"JsonWalker",
"(",
"JsonWalker",
".",
"value_json",
",",
"JsonWalker",
".",
"dict_expand",
")",
"r",
"=",
"walker",
".",
"walk",
"(",
... | Build dict for MongoDB, expanding result keys as we go. | [
"Build",
"dict",
"for",
"MongoDB",
"expanding",
"result",
"keys",
"as",
"we",
"go",
"."
] | train | https://github.com/materialsproject/pymatgen-db/blob/02e4351c2cea431407644f49193e8bf43ed39b9a/matgendb/vv/report.py#L530-L536 |
materialsproject/pymatgen-db | matgendb/vv/report.py | DiffHtmlFormatter.format | def format(self, result):
"""Generate HTML report.
:return: Report body
:rtype: str
"""
css = "\n".join(self.css)
content = "{}{}".format(self._header(), self._body(result))
if self._email:
text = """<!DOCTYPE html>
<html>
<div... | python | def format(self, result):
"""Generate HTML report.
:return: Report body
:rtype: str
"""
css = "\n".join(self.css)
content = "{}{}".format(self._header(), self._body(result))
if self._email:
text = """<!DOCTYPE html>
<html>
<div... | [
"def",
"format",
"(",
"self",
",",
"result",
")",
":",
"css",
"=",
"\"\\n\"",
".",
"join",
"(",
"self",
".",
"css",
")",
"content",
"=",
"\"{}{}\"",
".",
"format",
"(",
"self",
".",
"_header",
"(",
")",
",",
"self",
".",
"_body",
"(",
"result",
"... | Generate HTML report.
:return: Report body
:rtype: str | [
"Generate",
"HTML",
"report",
"."
] | train | https://github.com/materialsproject/pymatgen-db/blob/02e4351c2cea431407644f49193e8bf43ed39b9a/matgendb/vv/report.py#L595-L615 |
materialsproject/pymatgen-db | matgendb/vv/report.py | DiffTextFormatter.format | def format(self, result):
"""Generate plain text report.
:return: Report body
:rtype: str
"""
m = self.meta
lines = ['-' * len(self.TITLE),
self.TITLE,
'-' * len(self.TITLE),
"Compared: {db1} <-> {db2}".format(**m),
... | python | def format(self, result):
"""Generate plain text report.
:return: Report body
:rtype: str
"""
m = self.meta
lines = ['-' * len(self.TITLE),
self.TITLE,
'-' * len(self.TITLE),
"Compared: {db1} <-> {db2}".format(**m),
... | [
"def",
"format",
"(",
"self",
",",
"result",
")",
":",
"m",
"=",
"self",
".",
"meta",
"lines",
"=",
"[",
"'-'",
"*",
"len",
"(",
"self",
".",
"TITLE",
")",
",",
"self",
".",
"TITLE",
",",
"'-'",
"*",
"len",
"(",
"self",
".",
"TITLE",
")",
","... | Generate plain text report.
:return: Report body
:rtype: str | [
"Generate",
"plain",
"text",
"report",
"."
] | train | https://github.com/materialsproject/pymatgen-db/blob/02e4351c2cea431407644f49193e8bf43ed39b9a/matgendb/vv/report.py#L689-L725 |
materialsproject/pymatgen-db | matgendb/dbgroup.py | create_query_engine | def create_query_engine(config, clazz):
"""Create and return new query engine object from the
given `DBConfig` object.
:param config: Database configuration
:type config: dbconfig.DBConfig
:param clazz: Class to use for creating query engine. Should
act like query_engine.QueryEngi... | python | def create_query_engine(config, clazz):
"""Create and return new query engine object from the
given `DBConfig` object.
:param config: Database configuration
:type config: dbconfig.DBConfig
:param clazz: Class to use for creating query engine. Should
act like query_engine.QueryEngi... | [
"def",
"create_query_engine",
"(",
"config",
",",
"clazz",
")",
":",
"try",
":",
"qe",
"=",
"clazz",
"(",
"*",
"*",
"config",
".",
"settings",
")",
"except",
"Exception",
"as",
"err",
":",
"raise",
"CreateQueryEngineError",
"(",
"clazz",
",",
"config",
"... | Create and return new query engine object from the
given `DBConfig` object.
:param config: Database configuration
:type config: dbconfig.DBConfig
:param clazz: Class to use for creating query engine. Should
act like query_engine.QueryEngine.
:type clazz: class
:return: New que... | [
"Create",
"and",
"return",
"new",
"query",
"engine",
"object",
"from",
"the",
"given",
"DBConfig",
"object",
"."
] | train | https://github.com/materialsproject/pymatgen-db/blob/02e4351c2cea431407644f49193e8bf43ed39b9a/matgendb/dbgroup.py#L244-L259 |
materialsproject/pymatgen-db | matgendb/dbgroup.py | ConfigGroup.add_path | def add_path(self, path, pattern="*.json"):
"""Add configuration file(s)
in `path`. The path can be a single file or a directory.
If path is a directory, then `pattern`
(Unix glob-style) will be used to get a list of all config
files in the directory.
The name given to e... | python | def add_path(self, path, pattern="*.json"):
"""Add configuration file(s)
in `path`. The path can be a single file or a directory.
If path is a directory, then `pattern`
(Unix glob-style) will be used to get a list of all config
files in the directory.
The name given to e... | [
"def",
"add_path",
"(",
"self",
",",
"path",
",",
"pattern",
"=",
"\"*.json\"",
")",
":",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"path",
")",
":",
"configs",
"=",
"glob",
".",
"glob",
"(",
"_opj",
"(",
"path",
",",
"pattern",
")",
")",
"else... | Add configuration file(s)
in `path`. The path can be a single file or a directory.
If path is a directory, then `pattern`
(Unix glob-style) will be used to get a list of all config
files in the directory.
The name given to each file is the database name
and collection na... | [
"Add",
"configuration",
"file",
"(",
"s",
")",
"in",
"path",
".",
"The",
"path",
"can",
"be",
"a",
"single",
"file",
"or",
"a",
"directory",
".",
"If",
"path",
"is",
"a",
"directory",
"then",
"pattern",
"(",
"Unix",
"glob",
"-",
"style",
")",
"will",... | train | https://github.com/materialsproject/pymatgen-db/blob/02e4351c2cea431407644f49193e8bf43ed39b9a/matgendb/dbgroup.py#L41-L69 |
materialsproject/pymatgen-db | matgendb/dbgroup.py | ConfigGroup.add | def add(self, name, cfg, expand=False):
"""Add a configuration object.
:param name: Name for later retrieval
:param cfg: Configuration object
:param expand: Flag for adding sub-configs for each sub-collection.
See discussion in method doc.
:return: self, f... | python | def add(self, name, cfg, expand=False):
"""Add a configuration object.
:param name: Name for later retrieval
:param cfg: Configuration object
:param expand: Flag for adding sub-configs for each sub-collection.
See discussion in method doc.
:return: self, f... | [
"def",
"add",
"(",
"self",
",",
"name",
",",
"cfg",
",",
"expand",
"=",
"False",
")",
":",
"self",
".",
"_d",
"[",
"name",
"]",
"=",
"cfg",
"if",
"expand",
":",
"self",
".",
"expand",
"(",
"name",
")",
"return",
"self"
] | Add a configuration object.
:param name: Name for later retrieval
:param cfg: Configuration object
:param expand: Flag for adding sub-configs for each sub-collection.
See discussion in method doc.
:return: self, for chaining
:raises: CreateQueryEngineError... | [
"Add",
"a",
"configuration",
"object",
"."
] | train | https://github.com/materialsproject/pymatgen-db/blob/02e4351c2cea431407644f49193e8bf43ed39b9a/matgendb/dbgroup.py#L71-L84 |
materialsproject/pymatgen-db | matgendb/dbgroup.py | ConfigGroup.expand | def expand(self, name):
"""Expand config for `name` by adding a sub-configuration for every
dot-separated collection "below" the given one (or all, if none given).
For example, for a database 'mydb' with collections
['spiderman.amazing', 'spiderman.spectacular', 'spiderman2']
... | python | def expand(self, name):
"""Expand config for `name` by adding a sub-configuration for every
dot-separated collection "below" the given one (or all, if none given).
For example, for a database 'mydb' with collections
['spiderman.amazing', 'spiderman.spectacular', 'spiderman2']
... | [
"def",
"expand",
"(",
"self",
",",
"name",
")",
":",
"if",
"self",
".",
"_is_pattern",
"(",
"name",
")",
":",
"expr",
"=",
"re",
".",
"compile",
"(",
"self",
".",
"_pattern_to_regex",
"(",
"name",
")",
")",
"for",
"cfg_name",
"in",
"self",
".",
"_d... | Expand config for `name` by adding a sub-configuration for every
dot-separated collection "below" the given one (or all, if none given).
For example, for a database 'mydb' with collections
['spiderman.amazing', 'spiderman.spectacular', 'spiderman2']
and a configuration
{... | [
"Expand",
"config",
"for",
"name",
"by",
"adding",
"a",
"sub",
"-",
"configuration",
"for",
"every",
"dot",
"-",
"separated",
"collection",
"below",
"the",
"given",
"one",
"(",
"or",
"all",
"if",
"none",
"given",
")",
"."
] | train | https://github.com/materialsproject/pymatgen-db/blob/02e4351c2cea431407644f49193e8bf43ed39b9a/matgendb/dbgroup.py#L86-L108 |
materialsproject/pymatgen-db | matgendb/dbgroup.py | ConfigGroup._expand | def _expand(self, name):
"""Perform real work of `expand()` function."""
cfg = self._d[name]
if cfg.collection is None:
base_coll = ''
else:
base_coll = cfg.collection + self.SEP
qe = self._get_qe(name, cfg)
coll, db = qe.collection, qe.db
... | python | def _expand(self, name):
"""Perform real work of `expand()` function."""
cfg = self._d[name]
if cfg.collection is None:
base_coll = ''
else:
base_coll = cfg.collection + self.SEP
qe = self._get_qe(name, cfg)
coll, db = qe.collection, qe.db
... | [
"def",
"_expand",
"(",
"self",
",",
"name",
")",
":",
"cfg",
"=",
"self",
".",
"_d",
"[",
"name",
"]",
"if",
"cfg",
".",
"collection",
"is",
"None",
":",
"base_coll",
"=",
"''",
"else",
":",
"base_coll",
"=",
"cfg",
".",
"collection",
"+",
"self",
... | Perform real work of `expand()` function. | [
"Perform",
"real",
"work",
"of",
"expand",
"()",
"function",
"."
] | train | https://github.com/materialsproject/pymatgen-db/blob/02e4351c2cea431407644f49193e8bf43ed39b9a/matgendb/dbgroup.py#L110-L126 |
materialsproject/pymatgen-db | matgendb/dbgroup.py | ConfigGroup.uncache | def uncache(self, name):
"""Remove all created query engines that match `name` from
the cache (this disconnects from MongoDB, which is the point).
:param name: Name used for :meth:`add`, or pattern
:return: None
"""
delme = []
if self._is_pattern(name):
... | python | def uncache(self, name):
"""Remove all created query engines that match `name` from
the cache (this disconnects from MongoDB, which is the point).
:param name: Name used for :meth:`add`, or pattern
:return: None
"""
delme = []
if self._is_pattern(name):
... | [
"def",
"uncache",
"(",
"self",
",",
"name",
")",
":",
"delme",
"=",
"[",
"]",
"if",
"self",
".",
"_is_pattern",
"(",
"name",
")",
":",
"expr",
"=",
"re",
".",
"compile",
"(",
"self",
".",
"_pattern_to_regex",
"(",
"name",
")",
")",
"for",
"key",
... | Remove all created query engines that match `name` from
the cache (this disconnects from MongoDB, which is the point).
:param name: Name used for :meth:`add`, or pattern
:return: None | [
"Remove",
"all",
"created",
"query",
"engines",
"that",
"match",
"name",
"from",
"the",
"cache",
"(",
"this",
"disconnects",
"from",
"MongoDB",
"which",
"is",
"the",
"point",
")",
"."
] | train | https://github.com/materialsproject/pymatgen-db/blob/02e4351c2cea431407644f49193e8bf43ed39b9a/matgendb/dbgroup.py#L128-L145 |
materialsproject/pymatgen-db | matgendb/dbgroup.py | ConfigGroup.set_prefix | def set_prefix(self, prefix=None):
"""Set prefix to use as a namespace for item lookup.
A dot (.) will be automatically added to the given string.
:param prefix: Prefix, or None to unset
:return: None
"""
if prefix is None:
self._pfx = None
else:
... | python | def set_prefix(self, prefix=None):
"""Set prefix to use as a namespace for item lookup.
A dot (.) will be automatically added to the given string.
:param prefix: Prefix, or None to unset
:return: None
"""
if prefix is None:
self._pfx = None
else:
... | [
"def",
"set_prefix",
"(",
"self",
",",
"prefix",
"=",
"None",
")",
":",
"if",
"prefix",
"is",
"None",
":",
"self",
".",
"_pfx",
"=",
"None",
"else",
":",
"self",
".",
"_pfx",
"=",
"prefix",
"+",
"self",
".",
"SEP"
] | Set prefix to use as a namespace for item lookup.
A dot (.) will be automatically added to the given string.
:param prefix: Prefix, or None to unset
:return: None | [
"Set",
"prefix",
"to",
"use",
"as",
"a",
"namespace",
"for",
"item",
"lookup",
".",
"A",
"dot",
"(",
".",
")",
"will",
"be",
"automatically",
"added",
"to",
"the",
"given",
"string",
"."
] | train | https://github.com/materialsproject/pymatgen-db/blob/02e4351c2cea431407644f49193e8bf43ed39b9a/matgendb/dbgroup.py#L184-L194 |
materialsproject/pymatgen-db | matgendb/dbgroup.py | ConfigGroup._get_qe | def _get_qe(self, key, obj):
"""Instantiate a query engine, or retrieve a cached one.
"""
if key in self._cached:
return self._cached[key]
qe = create_query_engine(obj, self._class)
self._cached[key] = qe
return qe | python | def _get_qe(self, key, obj):
"""Instantiate a query engine, or retrieve a cached one.
"""
if key in self._cached:
return self._cached[key]
qe = create_query_engine(obj, self._class)
self._cached[key] = qe
return qe | [
"def",
"_get_qe",
"(",
"self",
",",
"key",
",",
"obj",
")",
":",
"if",
"key",
"in",
"self",
".",
"_cached",
":",
"return",
"self",
".",
"_cached",
"[",
"key",
"]",
"qe",
"=",
"create_query_engine",
"(",
"obj",
",",
"self",
".",
"_class",
")",
"self... | Instantiate a query engine, or retrieve a cached one. | [
"Instantiate",
"a",
"query",
"engine",
"or",
"retrieve",
"a",
"cached",
"one",
"."
] | train | https://github.com/materialsproject/pymatgen-db/blob/02e4351c2cea431407644f49193e8bf43ed39b9a/matgendb/dbgroup.py#L206-L213 |
materialsproject/pymatgen-db | matgendb/dbgroup.py | RegexDict.re_keys | def re_keys(self, pattern):
"""Find keys matching `pattern`.
:param pattern: Regular expression
:return: Matching keys or empty list
:rtype: list
"""
if not pattern.endswith("$"):
pattern += "$"
expr = re.compile(pattern)
return list(filter(ex... | python | def re_keys(self, pattern):
"""Find keys matching `pattern`.
:param pattern: Regular expression
:return: Matching keys or empty list
:rtype: list
"""
if not pattern.endswith("$"):
pattern += "$"
expr = re.compile(pattern)
return list(filter(ex... | [
"def",
"re_keys",
"(",
"self",
",",
"pattern",
")",
":",
"if",
"not",
"pattern",
".",
"endswith",
"(",
"\"$\"",
")",
":",
"pattern",
"+=",
"\"$\"",
"expr",
"=",
"re",
".",
"compile",
"(",
"pattern",
")",
"return",
"list",
"(",
"filter",
"(",
"expr",
... | Find keys matching `pattern`.
:param pattern: Regular expression
:return: Matching keys or empty list
:rtype: list | [
"Find",
"keys",
"matching",
"pattern",
"."
] | train | https://github.com/materialsproject/pymatgen-db/blob/02e4351c2cea431407644f49193e8bf43ed39b9a/matgendb/dbgroup.py#L224-L234 |
materialsproject/pymatgen-db | matgendb/dbgroup.py | RegexDict.re_get | def re_get(self, pattern):
"""Return values whose key matches `pattern`
:param pattern: Regular expression
:return: Found values, as a dict.
"""
return {k: self[k] for k in self.re_keys(pattern)} | python | def re_get(self, pattern):
"""Return values whose key matches `pattern`
:param pattern: Regular expression
:return: Found values, as a dict.
"""
return {k: self[k] for k in self.re_keys(pattern)} | [
"def",
"re_get",
"(",
"self",
",",
"pattern",
")",
":",
"return",
"{",
"k",
":",
"self",
"[",
"k",
"]",
"for",
"k",
"in",
"self",
".",
"re_keys",
"(",
"pattern",
")",
"}"
] | Return values whose key matches `pattern`
:param pattern: Regular expression
:return: Found values, as a dict. | [
"Return",
"values",
"whose",
"key",
"matches",
"pattern"
] | train | https://github.com/materialsproject/pymatgen-db/blob/02e4351c2cea431407644f49193e8bf43ed39b9a/matgendb/dbgroup.py#L236-L242 |
materialsproject/pymatgen-db | matgendb/builders/examples/copy_builder.py | CopyBuilder.get_items | def get_items(self, source=None, target=None, crit=None):
"""Copy records from source to target collection.
:param source: Input collection
:type source: QueryEngine
:param target: Output collection
:type target: QueryEngine
:param crit: Filter criteria, e.g. "{ 'flag': ... | python | def get_items(self, source=None, target=None, crit=None):
"""Copy records from source to target collection.
:param source: Input collection
:type source: QueryEngine
:param target: Output collection
:type target: QueryEngine
:param crit: Filter criteria, e.g. "{ 'flag': ... | [
"def",
"get_items",
"(",
"self",
",",
"source",
"=",
"None",
",",
"target",
"=",
"None",
",",
"crit",
"=",
"None",
")",
":",
"self",
".",
"_target_coll",
"=",
"target",
".",
"collection",
"if",
"not",
"crit",
":",
"# reduce any False-y crit value to None",
... | Copy records from source to target collection.
:param source: Input collection
:type source: QueryEngine
:param target: Output collection
:type target: QueryEngine
:param crit: Filter criteria, e.g. "{ 'flag': True }".
:type crit: dict | [
"Copy",
"records",
"from",
"source",
"to",
"target",
"collection",
"."
] | train | https://github.com/materialsproject/pymatgen-db/blob/02e4351c2cea431407644f49193e8bf43ed39b9a/matgendb/builders/examples/copy_builder.py#L28-L44 |
materialsproject/pymatgen-db | matgendb/builders/core.py | parse_fn_docstring | def parse_fn_docstring(fn):
"""Get parameter and return types from function's docstring.
Docstrings must use this format::
:param foo: What is foo
:type foo: int
:return: What is returned
:rtype: double
:return: A map of names, each with keys 'type' and 'desc'.
:rtype: tup... | python | def parse_fn_docstring(fn):
"""Get parameter and return types from function's docstring.
Docstrings must use this format::
:param foo: What is foo
:type foo: int
:return: What is returned
:rtype: double
:return: A map of names, each with keys 'type' and 'desc'.
:rtype: tup... | [
"def",
"parse_fn_docstring",
"(",
"fn",
")",
":",
"doc",
"=",
"fn",
".",
"__doc__",
"params",
",",
"return_",
"=",
"{",
"}",
",",
"{",
"}",
"param_order",
"=",
"[",
"]",
"for",
"line",
"in",
"doc",
".",
"split",
"(",
"\"\\n\"",
")",
":",
"line",
... | Get parameter and return types from function's docstring.
Docstrings must use this format::
:param foo: What is foo
:type foo: int
:return: What is returned
:rtype: double
:return: A map of names, each with keys 'type' and 'desc'.
:rtype: tuple(dict) | [
"Get",
"parameter",
"and",
"return",
"types",
"from",
"function",
"s",
"docstring",
"."
] | train | https://github.com/materialsproject/pymatgen-db/blob/02e4351c2cea431407644f49193e8bf43ed39b9a/matgendb/builders/core.py#L45-L80 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.