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_documentation_string
stringlengths
1
47.2k
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._...
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.
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)]
List all `OcrdAgent </../../ocrd_models/ocrd_models.ocrd_agent.html>`_
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...
Add an `OcrdAgent </../../ocrd_models/ocrd_models.ocrd_agent.html>`_ to the list of agents in the metsHdr.
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)]
List the ``USE`` attributes of all ``mets:fileGrp``.
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...
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 ...
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...
Add a new ``mets:fileGrp``. Arguments: fileGrp (string): ``USE`` attribute of the new filegroup.
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 ...
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...
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...
Create a new physical page
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...
Get the pageId for a ocrd_file
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...
Actual validation.
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....
Clone workspace from mets_url unless workspace was provided.
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...
Validate image pixel density See `spec <https://ocr-d.github.io/mets#pixel-density-of-images-must-be-explicit-and-high-enough>`_.
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...
Ensure ``USE`` attributes of ``mets:fileGrp`` conform to OCR-D naming schema.. See `spec <https://ocr-d.github.io/mets#file-group-use-syntax>`_.
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...
Validate ``mets:file`` URLs are sane.
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_...
Run PageValidator on the PAGE-XML documents referenced in the METS.
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...
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...
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 ...
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
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...
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...
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. ...
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
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. ...
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...
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...
Gets the current user from the request and prepares and connects a signal receiver with the user already attached to it.
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
Disconnects the signal receiver to prevent it from staying active.
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'])...
Disconnects the signal receiver to prevent it from staying active in case of an exception.
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('.') ...
Signal receiver with an extra, required 'user' kwarg. This method becomes a real (valid) signal receiver when it is curried with the user.
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...
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.
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: ...
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.
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 ...
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.
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...
Generate the API call to the device.
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...
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...
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...
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...
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)
Switching of device-context
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)
Create route to {destination} {mask} using {next_hops} expressed as (gateway, distance)
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...
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).
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...
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}, ...].
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...
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.
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...
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.
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...
Get the entire task doc for a path, including any post-processing.
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. ...
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.
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): ...
Process a killed vasp run.
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]): ...
Process a vasprun.xml file.
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. ...
Process aflow style runs, where each run is actually a combination of two vasp runs.
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...
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 ...
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,...
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 = {...
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...
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.
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...
Walk a dict & transform.
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:...
Expand keys in a dict with '.' in them into sub-dictionaries, e.g. {'a.b.c': 'foo'} ==> {'a': {'b': {'c': 'foo'}}}
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]...
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.
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...
Replacement for regular ``find()``.
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 ...
Update the position of the mark in the collection. :return: this object, for chaining :rtype: Mark
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}
Representation as a dict for JSON serialization.
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...
Construct from dict :param coll: Collection for the mark :param d: Input :type d: dict :return: new instance :rtype: Mark
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}}...
A mongdb query expression to find all records with higher values for this mark's fields in the collection. :rtype: dict
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]
Create tracking collection. Does nothing if tracking collection already exists.
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...
Save a position in this collection. :param mark: The position to save :type mark: Mark :raises: DBError, NoTrackingCollection
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 :...
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
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)
Get tracked position for a given operation and field.
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...
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 ...
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]
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.
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...
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 ...
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...
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...
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, ...
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...
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}. ...
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...
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)
Wrapper for pymongo.Collection.ensure_index
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 ...
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 ...
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 =...
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
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
Return first document from :meth:`query`, with same parameters.
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...
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.
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...
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...
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): ...
Overrides the get_dos_from_id for the MIT gridfs format.
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...
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
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...
Transform/map a result.
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...
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...
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...
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.
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:...
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, ...
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...
Recursive schema builder, called by `json_schema`.
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 ...
Get JavaScript name for given data type, called by `_build_schema`.
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)
Get path to directory with schemata. :param db_version: Version of the database :type db_version: int :return: Path :rtype: str
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...
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...
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("...
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
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]
Interpret user/password aliases.
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...
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...
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....
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
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 """ ...
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
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...
Return ordered list of columns, from given columns and the name of the section
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 """ ...
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
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
Build dict for MongoDB, expanding result keys as we go.
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...
Generate HTML report. :return: Report body :rtype: str
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), ...
Generate plain text report. :return: Report body :rtype: str
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...
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...
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...
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...
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...
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...
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'] ...
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 {...
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 ...
Perform real work of `expand()` function.
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): ...
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
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: ...
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
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
Instantiate a query engine, or retrieve a cached one.
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...
Find keys matching `pattern`. :param pattern: Regular expression :return: Matching keys or empty list :rtype: list
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)}
Return values whose key matches `pattern` :param pattern: Regular expression :return: Found values, as a dict.
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': ...
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
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...
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)
https://github.com/materialsproject/pymatgen-db/blob/02e4351c2cea431407644f49193e8bf43ed39b9a/matgendb/builders/core.py#L45-L80