_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q14800 | workspace_backup_add | train | def workspace_backup_add(ctx):
"""
Create a new backup
"""
backup_manager = WorkspaceBackupManager(Workspace(ctx.resolver, directory=ctx.directory, mets_basename=ctx.mets_basename, automatic_backup=ctx.automatic_backup))
backup_manager.add() | python | {
"resource": ""
} |
q14801 | workspace_backup_restore | train | def workspace_backup_restore(ctx, choose_first, bak):
"""
Restore backup BAK
"""
backup_manager = WorkspaceBackupManager(Workspace(ctx.resolver, directory=ctx.directory, mets_basename=ctx.mets_basename, automatic_backup=ctx.automatic_backup))
backup_manager.restore(bak, choose_first) | python | {
"resource": ""
} |
q14802 | workspace_backup_undo | train | def workspace_backup_undo(ctx):
"""
Restore the last backup
"""
backup_manager = WorkspaceBackupManager(Workspace(ctx.resolver, directory=ctx.directory, mets_basename=ctx.mets_basename, automatic_backup=ctx.automatic_backup))
backup_manager.undo() | python | {
"resource": ""
} |
q14803 | extend_with_default | train | def extend_with_default(validator_class):
"""
Add a default-setting mechanism to a ``jsonschema`` validation class.
"""
validate_properties = validator_class.VALIDATORS["properties"]
def set_defaults(validator, properties, instance, schema):
"""
Set defaults in subschemas
""... | python | {
"resource": ""
} |
q14804 | JsonValidator.validate | train | def validate(obj, schema):
"""
Validate an object against a schema
Args:
obj (dict):
schema (dict):
"""
if isinstance(obj, str):
obj = json.loads(obj)
return JsonValidator(schema)._validate(obj) | python | {
"resource": ""
} |
q14805 | run_processor | train | def run_processor(
processorClass,
ocrd_tool=None,
mets_url=None,
resolver=None,
workspace=None,
page_id=None,
log_level=None,
input_file_grp=None,
output_file_grp=None,
parameter=None,
working_dir=None,
): # pylint: disable=too-man... | python | {
"resource": ""
} |
q14806 | run_cli | train | def run_cli(
executable,
mets_url=None,
resolver=None,
workspace=None,
page_id=None,
log_level=None,
input_file_grp=None,
output_file_grp=None,
parameter=None,
working_dir=None,
):
"""
Create a workspace for mets_url and run MP CLI ... | python | {
"resource": ""
} |
q14807 | Processor.input_files | train | def input_files(self):
"""
List the input files
"""
return self.workspace.mets.find_files(fileGrp=self.input_file_grp, pageId=self.page_id) | python | {
"resource": ""
} |
q14808 | page_from_file | train | def page_from_file(input_file):
"""
Create a new PAGE-XML from a METS file representing a PAGE-XML or an image.
Arguments:
* input_file (OcrdFile):
"""
# print("PARSING PARSING '%s'" % input_file)
if input_file.mimetype.startswith('image'):
return page_from_image(input_file)
... | python | {
"resource": ""
} |
q14809 | concat_padded | train | def concat_padded(base, *args):
"""
Concatenate string and zero-padded 4 digit number
"""
ret = base
for n in args:
if is_string(n):
ret = "%s_%s" % (ret, n)
else:
ret = "%s_%04i" % (ret, n + 1)
return ret | python | {
"resource": ""
} |
q14810 | points_from_xywh | train | def points_from_xywh(box):
"""
Constructs a polygon representation from a rectangle described as a dict with keys x, y, w, h.
"""
x, y, w, h = box['x'], box['y'], box['w'], box['h']
# tesseract uses a different region representation format
return "%i,%i %i,%i %i,%i %i,%i" % (
x, y,
... | python | {
"resource": ""
} |
q14811 | polygon_from_points | train | def polygon_from_points(points):
"""
Constructs a numpy-compatible polygon from a page representation.
"""
polygon = []
for pair in points.split(" "):
x_y = pair.split(",")
polygon.append([float(x_y[0]), float(x_y[1])])
return polygon | python | {
"resource": ""
} |
q14812 | unzip_file_to_dir | train | def unzip_file_to_dir(path_to_zip, output_directory):
"""
Extract a ZIP archive to a directory
"""
z = ZipFile(path_to_zip, 'r')
z.extractall(output_directory)
z.close() | python | {
"resource": ""
} |
q14813 | xywh_from_points | train | def xywh_from_points(points):
"""
Constructs an dict representing a rectangle with keys x, y, w, h
"""
xys = [[int(p) for p in pair.split(',')] for pair in points.split(' ')]
minx = sys.maxsize
miny = sys.maxsize
maxx = 0
maxy = 0
for xy in xys:
if xy[0] < minx:
m... | python | {
"resource": ""
} |
q14814 | OcrdZipValidator.validate | train | def validate(self, skip_checksums=False, skip_bag=False, skip_unzip=False, skip_delete=False, processes=2):
"""
Validate an OCRD-ZIP file for profile, bag and workspace conformance
Arguments:
skip_bag (boolean): Whether to skip all checks of manifests and files
skip_chec... | python | {
"resource": ""
} |
q14815 | quote_xml | train | def quote_xml(inStr):
"Escape markup chars, but do not modify CDATA sections."
if not inStr:
return ''
s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr)
s2 = ''
pos = 0
matchobjects = CDATA_pattern_.finditer(s1)
for mo in matchobjects:
s3 = s1[pos:mo.start()]
... | python | {
"resource": ""
} |
q14816 | parseString | train | def parseString(inString, silence=False):
'''Parse a string, create the object tree, and export it.
Arguments:
- inString -- A string. This XML fragment should not start
with an XML declaration containing an encoding.
- silence -- A boolean. If False, export the object.
Returns -- The root ... | python | {
"resource": ""
} |
q14817 | ocrd_tool_tool_parse_params | train | def ocrd_tool_tool_parse_params(ctx, parameters, json):
"""
Parse parameters with fallback to defaults and output as shell-eval'able assignments to params var.
"""
if parameters is None or parameters == "":
parameters = {}
else:
with open(parameters, 'r') as f:
parameters... | python | {
"resource": ""
} |
q14818 | OcrdAgent.othertype | train | def othertype(self, othertype):
"""
Set the ``OTHERTYPE`` attribute value.
"""
if othertype is not None:
self._el.set('TYPE', 'OTHER')
self._el.set('OTHERTYPE', othertype) | python | {
"resource": ""
} |
q14819 | OcrdAgent.otherrole | train | def otherrole(self, otherrole):
"""
Get the ``OTHERROLE`` attribute value.
"""
if otherrole is not None:
self._el.set('ROLE', 'OTHER')
self._el.set('OTHERROLE', otherrole) | python | {
"resource": ""
} |
q14820 | ParameterValidator.validate | train | def validate(self, *args, **kwargs): # pylint: disable=arguments-differ
"""
Validate a parameter dict against a parameter schema from an ocrd-tool.json
Args:
obj (dict):
schema (dict):
"""
return super(ParameterValidator, self)._validate(*args, **kwargs) | python | {
"resource": ""
} |
q14821 | handle_inconsistencies | train | def handle_inconsistencies(node, strictness, strategy, report):
"""
Check whether the text results on an element is consistent with its child element text results.
"""
if isinstance(node, PcGtsType):
node = node.get_Page()
elif isinstance(node, GlyphType):
return report
_, tag, ... | python | {
"resource": ""
} |
q14822 | get_text | train | def get_text(node, strategy):
"""
Get the most confident text results, either those with @index = 1 or the first text results or empty string.
"""
textEquivs = node.get_TextEquiv()
if not textEquivs:
log.debug("No text results on %s %s", node, node.id)
return ''
# elif strategy ... | python | {
"resource": ""
} |
q14823 | set_text | train | def set_text(node, text, strategy):
"""
Set the most confident text results, either those with @index = 1, the first text results or add new one.
"""
text = text.strip()
textEquivs = node.get_TextEquiv()
if not textEquivs:
node.add_TextEquiv(TextEquivType(Unicode=text))
# elif strat... | python | {
"resource": ""
} |
q14824 | PageValidator.validate | train | def validate(filename=None, ocrd_page=None, ocrd_file=None, strictness='strict', strategy='index1'):
"""
Validates a PAGE file for consistency by filename, OcrdFile or passing OcrdPage directly.
Arguments:
filename (string): Path to PAGE
ocrd_page (OcrdPage): OcrdPage in... | python | {
"resource": ""
} |
q14825 | ocrd_cli_options | train | def ocrd_cli_options(f):
"""
Implement MP CLI.
Usage::
import ocrd_click_cli from ocrd.utils
@click.command()
@ocrd_click_cli
def cli(mets_url):
print(mets_url)
"""
params = [
click.option('-m', '--mets', help="METS URL to validate"),
cl... | python | {
"resource": ""
} |
q14826 | ValidationReport.merge_report | train | def merge_report(self, otherself):
"""
Merge another report into this one.
"""
self.notices += otherself.notices
self.warnings += otherself.warnings
self.errors += otherself.errors | python | {
"resource": ""
} |
q14827 | process_cli | train | def process_cli(log_level, mets, page_id, tasks):
"""
Process a series of tasks
"""
log = getLogger('ocrd.cli.process')
run_tasks(mets, log_level, page_id, tasks)
log.info("Finished") | python | {
"resource": ""
} |
q14828 | bag | train | def bag(directory, mets_basename, dest, identifier, in_place, manifestation_depth, mets, base_version_checksum, tag_file, skip_zip, processes):
"""
Bag workspace as OCRD-ZIP at DEST
"""
resolver = Resolver()
workspace = Workspace(resolver, directory=directory, mets_basename=mets_basename)
worksp... | python | {
"resource": ""
} |
q14829 | validate | train | def validate(src, **kwargs):
"""
Validate OCRD-ZIP
SRC must exist an be an OCRD-ZIP, either a ZIP file or a directory.
"""
resolver = Resolver()
validator = OcrdZipValidator(resolver, src)
report = validator.validate(**kwargs)
print(report)
if not report.is_valid:
sys.exit(1... | python | {
"resource": ""
} |
q14830 | WorkspaceBackupManager.restore | train | def restore(self, chksum, choose_first=False):
"""
Restore mets.xml to previous state
"""
log = getLogger('ocrd.workspace_backup.restore')
bak = None
candidates = glob(join(self.backup_directory, '%s*' % chksum))
if not candidates:
log.error("No backup... | python | {
"resource": ""
} |
q14831 | WorkspaceBackupManager.list | train | def list(self):
"""
List all backups as WorkspaceBackup objects, sorted descending by lastmod.
"""
backups = []
for d in glob(join(self.backup_directory, '*')):
backups.append(WorkspaceBackup.from_path(d))
backups.sort(key=lambda b: b.lastmod, reverse=True)
... | python | {
"resource": ""
} |
q14832 | WorkspaceBackupManager.undo | train | def undo(self):
"""
Restore to last version
"""
log = getLogger('ocrd.workspace_backup.undo')
backups = self.list()
if backups:
last_backup = backups[0]
self.restore(last_backup.chksum, choose_first=True)
else:
log.info("No back... | python | {
"resource": ""
} |
q14833 | setOverrideLogLevel | train | def setOverrideLogLevel(lvl):
"""
Override all logger filter levels to include lvl and above.
- Set root logger level
- iterates all existing loggers and sets their log level to ``NOTSET``.
Args:
lvl (string): Log level name.
"""
if lvl is None:
return
logging.info('Ov... | python | {
"resource": ""
} |
q14834 | initLogging | train | def initLogging():
"""
Sets logging defaults
"""
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s.%(msecs)03d %(levelname)s %(name)s - %(message)s',
datefmt='%H:%M:%S')
logging.getLogger('').setLevel(logging.INFO)
# logging.getLogger('ocrd.resolver').setLevel... | python | {
"resource": ""
} |
q14835 | WorkspaceBagger.bag | train | def bag(self,
workspace,
ocrd_identifier,
dest=None,
ocrd_mets='mets.xml',
ocrd_manifestation_depth='full',
ocrd_base_version_checksum=None,
processes=1,
skip_zip=False,
in_place=False,
tag_files=None... | python | {
"resource": ""
} |
q14836 | WorkspaceBagger.spill | train | def spill(self, src, dest):
"""
Spill a workspace, i.e. unpack it and turn it into a workspace.
See https://ocr-d.github.com/ocrd_zip#unpacking-ocrd-zip-to-a-workspace
Arguments:
src (string): Path to OCRD-ZIP
dest (string): Path to directory to unpack data fold... | python | {
"resource": ""
} |
q14837 | Workspace.download_url | train | def download_url(self, url, **kwargs):
"""
Download a URL to the workspace.
Args:
url (string): URL to download to directory
**kwargs : See :py:mod:`ocrd.resolver.Resolver`
Returns:
The local filename of the downloaded file
"""
if sel... | python | {
"resource": ""
} |
q14838 | Workspace.save_mets | train | def save_mets(self):
"""
Write out the current state of the METS file.
"""
log.info("Saving mets '%s'" % self.mets_target)
if self.automatic_backup:
WorkspaceBackupManager(self).add()
with open(self.mets_target, 'wb') as f:
f.write(self.mets.to_xml... | python | {
"resource": ""
} |
q14839 | Workspace.resolve_image_as_pil | train | def resolve_image_as_pil(self, image_url, coords=None):
"""
Resolve an image URL to a PIL image.
Args:
coords (list) : Coordinates of the bounding box to cut from the image
Returns:
Image or region in image as PIL.Image
"""
files = self.mets.find... | python | {
"resource": ""
} |
q14840 | OcrdExif.to_xml | train | def to_xml(self):
"""
Serialize all properties as XML
"""
ret = '<exif>'
for k in self.__dict__:
ret += '<%s>%s</%s>' % (k, self.__dict__[k], k)
ret += '</exif>'
return ret | python | {
"resource": ""
} |
q14841 | OcrdFile.basename_without_extension | train | def basename_without_extension(self):
"""
Get the ``os.path.basename`` of the local file, if any, with extension removed.
"""
ret = self.basename.rsplit('.', 1)[0]
if ret.endswith('.tar'):
ret = ret[0:len(ret)-4]
return ret | python | {
"resource": ""
} |
q14842 | OcrdFile.pageId | train | def pageId(self):
"""
Get the ID of the physical page this file manifests.
"""
if self.mets is None:
raise Exception("OcrdFile %s has no member 'mets' pointing to parent OcrdMets" % self)
return self.mets.get_physical_page_for_file(self) | python | {
"resource": ""
} |
q14843 | OcrdFile.pageId | train | def pageId(self, pageId):
"""
Set the ID of the physical page this file manifests.
"""
if pageId is None:
return
if self.mets is None:
raise Exception("OcrdFile %s has no member 'mets' pointing to parent OcrdMets" % self)
self.mets.set_physical_pag... | python | {
"resource": ""
} |
q14844 | OcrdMets.empty_mets | train | def empty_mets():
"""
Create an empty METS file from bundled template.
"""
tpl = METS_XML_EMPTY.decode('utf-8')
tpl = tpl.replace('{{ VERSION }}', VERSION)
tpl = tpl.replace('{{ NOW }}', '%s' % datetime.now())
return OcrdMets(content=tpl.encode('utf-8')) | python | {
"resource": ""
} |
q14845 | OcrdMets.set_physical_page_for_file | train | 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 | {
"resource": ""
} |
q14846 | OcrdMets.get_physical_page_for_file | train | 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 | {
"resource": ""
} |
q14847 | WorkspaceValidator._validate | train | 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 | {
"resource": ""
} |
q14848 | WorkspaceValidator._resolve_workspace | train | 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 | {
"resource": ""
} |
q14849 | WorkspaceValidator._validate_pixel_density | train | 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 | {
"resource": ""
} |
q14850 | WorkspaceValidator._validate_page | train | 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 | {
"resource": ""
} |
q14851 | ActionslogModelRegistry.register | train | 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 | {
"resource": ""
} |
q14852 | track_field | train | 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 | {
"resource": ""
} |
q14853 | HttpClient.request | train | 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 | {
"resource": ""
} |
q14854 | LicenseManager.create | train | 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 | {
"resource": ""
} |
q14855 | LicenseManager.update | train | 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 | {
"resource": ""
} |
q14856 | DeviceContext.switch | train | 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 | {
"resource": ""
} |
q14857 | contains_vasp_input | train | 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 | {
"resource": ""
} |
q14858 | get_coordination_numbers | train | 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 | {
"resource": ""
} |
q14859 | get_uri | train | 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 | {
"resource": ""
} |
q14860 | VaspToDbTaskDrone.assimilate | train | 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 | {
"resource": ""
} |
q14861 | VaspToDbTaskDrone.get_task_doc | train | 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 | {
"resource": ""
} |
q14862 | VaspToDbTaskDrone.post_process | train | 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 | {
"resource": ""
} |
q14863 | VaspToDbTaskDrone.process_vasprun | train | 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 | {
"resource": ""
} |
q14864 | total_size | train | 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 | {
"resource": ""
} |
q14865 | args_kvp_nodup | train | 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 | {
"resource": ""
} |
q14866 | JsonWalker.walk | train | 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 | {
"resource": ""
} |
q14867 | Mark.update | train | 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 | {
"resource": ""
} |
q14868 | Mark.as_dict | train | 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 | {
"resource": ""
} |
q14869 | Mark.from_dict | train | 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 | {
"resource": ""
} |
q14870 | Mark.query | train | 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 | {
"resource": ""
} |
q14871 | CollectionTracker.create | train | 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 | {
"resource": ""
} |
q14872 | CollectionTracker.save | train | 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 | {
"resource": ""
} |
q14873 | CollectionTracker.retrieve | train | 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 | {
"resource": ""
} |
q14874 | CollectionTracker._get | train | 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 | {
"resource": ""
} |
q14875 | QueryEngine.set_aliases_and_defaults | train | 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 | {
"resource": ""
} |
q14876 | QueryEngine.get_entries | train | 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 | {
"resource": ""
} |
q14877 | QueryEngine.ensure_index | train | def ensure_index(self, key, unique=False):
"""Wrapper for pymongo.Collection.ensure_index
"""
return self.collection.ensure_index(key, unique=unique) | python | {
"resource": ""
} |
q14878 | QueryEngine.query | train | 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 | {
"resource": ""
} |
q14879 | QueryEngine.get_structure_from_id | train | 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 | {
"resource": ""
} |
q14880 | QueryEngine.from_config | train | 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 | {
"resource": ""
} |
q14881 | QueryEngine.get_dos_from_id | train | 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 | {
"resource": ""
} |
q14882 | add_schemas | train | 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 | {
"resource": ""
} |
q14883 | load_schema | train | 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 | {
"resource": ""
} |
q14884 | Schema.json_schema | train | 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 | {
"resource": ""
} |
q14885 | Schema._build_schema | train | 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 | {
"resource": ""
} |
q14886 | Schema._jstype | train | 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 | {
"resource": ""
} |
q14887 | get_schema_dir | train | 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 | {
"resource": ""
} |
q14888 | get_schema_file | train | 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 | {
"resource": ""
} |
q14889 | get_settings | train | 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 | {
"resource": ""
} |
q14890 | DiffFormatter.result_subsets | train | 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 | {
"resource": ""
} |
q14891 | DiffFormatter.ordered_cols | train | 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 | {
"resource": ""
} |
q14892 | DiffFormatter.sort_rows | train | 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 | {
"resource": ""
} |
q14893 | DiffJsonFormatter.document | train | 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 | {
"resource": ""
} |
q14894 | DiffTextFormatter.format | train | 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 | {
"resource": ""
} |
q14895 | create_query_engine | train | 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 | {
"resource": ""
} |
q14896 | ConfigGroup.add | train | 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 | {
"resource": ""
} |
q14897 | ConfigGroup._get_qe | train | 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 | {
"resource": ""
} |
q14898 | RegexDict.re_keys | train | 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 | {
"resource": ""
} |
q14899 | RegexDict.re_get | train | 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 | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.