code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
payload = {
"device-context": self._build_payload(device_id, obj_slot_id)
}
return self._post(self.url_prefix, payload) | def switch(self, device_id, obj_slot_id) | Switching of device-context | 5.388583 | 3.928224 | 1.371761 |
payload = {
"rib": self._build_payload(destination, mask, next_hops)
}
return self._post(self.url_prefix, payload) | def create(self, destination, mask, next_hops=[]) | Create route to {destination} {mask} using {next_hops} expressed as (gateway, distance) | 5.722727 | 5.437198 | 1.052514 |
for f in ["INCAR", "POSCAR", "POTCAR", "KPOINTS"]:
if not os.path.exists(os.path.join(dir_name, f)) and \
not os.path.exists(os.path.join(dir_name, f + ".orig")):
return False
return True | 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). | 2.021113 | 2.447448 | 0.825804 |
structure = Structure.from_dict(d["output"]["crystal"])
f = VoronoiNN()
cn = []
for i, s in enumerate(structure.sites):
try:
n = f.get_cn(structure, i)
number = int(round(n))
cn.append({"site": s.as_dict(), "coordination": number})
except Exceptio... | 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,
"coordination": number}, ...]. | 5.422363 | 4.716802 | 1.149585 |
fullpath = os.path.abspath(dir_name)
try:
hostname = socket.gethostbyaddr(socket.gethostname())[0]
except:
hostname = socket.gethostname()
return "{}:{}".format(hostname, fullpath) | 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. | 2.479531 | 3.048292 | 0.813416 |
try:
d = self.get_task_doc(path)
if self.mapi_key is not None and d["state"] == "successful":
self.calculate_stability(d)
tid = self._insert_doc(d)
return tid
except Exception as ex:
import traceback
logger.... | 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 returned. | 6.328373 | 5.690033 | 1.112186 |
logger.info("Getting task doc for base dir :{}".format(path))
files = os.listdir(path)
vasprun_files = OrderedDict()
if "STOPCAR" in files:
#Stopped runs. Try to parse as much as possible.
logger.info(path + " contains stopped run")
for r in self.... | def get_task_doc(self, path) | Get the entire task doc for a path, including any post-processing. | 3.874005 | 3.857425 | 1.004298 |
logger.info("Post-processing dir:{}".format(dir_name))
fullpath = os.path.abspath(dir_name)
# VASP input generated by pymatgen's alchemy has a
# transformations.json file that keeps track of the origin of a
# particular structure. This is extremely useful for tracing b... | 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.
d:
Current doc generated. | 3.669685 | 3.605777 | 1.017724 |
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):
filename = os.path.join(dir_name, f)
if fnmatch(f, "INCAR*"):
... | def process_killed_run(self, dir_name) | Process a killed vasp run. | 2.134681 | 2.103819 | 1.014669 |
vasprun_file = os.path.join(dir_name, filename)
if self.parse_projected_eigen and (self.parse_projected_eigen != 'final' or \
taskname == self.runs[-1]):
parse_projected_eigen = True
else:
parse_projected_eigen = False
r = Vas... | def process_vasprun(self, dir_name, taskname, filename) | Process a vasprun.xml file. | 3.105601 | 3.088836 | 1.005428 |
try:
fullpath = os.path.abspath(dir_name)
# Defensively copy the additional fields first. This is a MUST.
# Otherwise, parallel updates will see the same object and inserts
# will be overridden!!
d = {k: v for k, v in self.additional_fields.i... | def generate_doc(self, dir_name, vasprun_files) | Process aflow style runs, where each run is actually a combination of
two vasp runs. | 3.996917 | 3.988844 | 1.002024 |
(parent, subdirs, files) = path
if set(self.runs).intersection(subdirs):
return [parent]
if not any([parent.endswith(os.sep + r) for r in self.runs]) and \
len(glob.glob(os.path.join(parent, "vasprun.xml*"))) > 0:
return [parent]
return [] | 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 aflow style run.
3. Directories containing vasp ... | 5.024497 | 4.545501 | 1.105378 |
# How to make different types of objects iterable
dict_handler = lambda d: chain.from_iterable(d.items())
all_handlers = {tuple: iter,
list: iter,
deque: iter,
dict: dict_handler,
set: iter,
frozenset: i... | 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, add handlers to iterate over their contents:
handlers = {... | 2.687706 | 2.50705 | 1.072059 |
if s is None:
return {}
d = {}
for item in [e.strip() for e in s.split(",")]:
try:
key, value = item.split("=", 1)
except ValueError:
msg = "argument item '{}' not in form key=value".format(item)
if _argparse_is_dumb:
_alog.war... | 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. | 2.868493 | 2.822174 | 1.016412 |
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:
return o if self._vx is None else self._vx(o) | def walk(self, o) | Walk a dict & transform. | 2.377748 | 2.195105 | 1.083205 |
r = {}
for k, v in o.items():
if isinstance(k, str):
k = k.replace('$', '_')
if "." in k:
sub_r, keys = r, k.split('.')
# create sub-dicts until last part of key
for k2 in keys[:-1]:
sub_... | 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'}}} | 3.172555 | 3.385201 | 0.937184 |
self._collection_name = value
self._mongo_coll = self.db[value]
self.collection = TrackedCollection(self._mongo_coll, operation=self._t_op,
field=self._t_field) | 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. | 6.799148 | 6.937899 | 0.980001 |
_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_find(*args, **kwargs)
# otherwise do somethin' real
# fish 'filter' out of ar... | def tracked_find(self, *args, **kwargs) | Replacement for regular ``find()``. | 4.954377 | 4.843614 | 1.022868 |
rec = self._c.find_one({}, {self._fld: 1}, sort=[(self._fld, -1)], limit=1)
if rec is None:
self._pos = self._empty_pos()
elif not self._fld in rec:
_log.error("Tracking field not found. field={} collection={}"
.format(self._fld, self._c.na... | def update(self) | Update the position of the mark in the collection.
:return: this object, for chaining
:rtype: Mark | 4.320442 | 4.512583 | 0.957421 |
return {self.FLD_OP: self._op.name,
self.FLD_MARK: self._pos,
self.FLD_FLD: self._fld} | def as_dict(self) | Representation as a dict for JSON serialization. | 6.741901 | 5.863218 | 1.149864 |
return Mark(collection=coll, operation=Operation[d[cls.FLD_OP]],
pos=d[cls.FLD_MARK], field=d[cls.FLD_FLD]) | 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 | 9.803516 | 9.76625 | 1.003816 |
q = {}
for field, value in self._pos.items():
if value is None:
q.update({field: {'$exists': True}})
else:
q.update({field: {'$gt': value}})
return q | def query(self) | A mongdb query expression to find all records with higher values
for this mark's fields in the collection.
:rtype: dict | 3.635252 | 3.588473 | 1.013036 |
if self._track is None:
self._track = self.db[self.tracking_collection_name] | def create(self) | Create tracking collection.
Does nothing if tracking collection already exists. | 10.076819 | 4.923018 | 2.046879 |
self._check_exists()
obj = mark.as_dict()
try:
# Make a 'filter' to find/update existing record, which uses
# the field name and operation (but not the position).
filt = {k: obj[k] for k in (mark.FLD_FLD, mark.FLD_OP)}
_log.debug("save: up... | def save(self, mark) | Save a position in this collection.
:param mark: The position to save
:type mark: Mark
:raises: DBError, NoTrackingCollection | 7.441741 | 7.068297 | 1.052834 |
obj = self._get(operation, field)
if obj is None:
# empty Mark instance
return Mark(collection=self.collection, operation=operation, field=field)
return Mark.from_dict(self.collection, obj) | 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
:rtype: Mark
:raises: NoTrackingCollection | 5.98779 | 5.932572 | 1.009307 |
self._check_exists()
query = {Mark.FLD_OP: operation.name,
Mark.FLD_MARK + "." + field: {"$exists": True}}
return self._track.find_one(query) | def _get(self, operation, field) | Get tracked position for a given operation and field. | 8.816965 | 7.269589 | 1.212856 |
self._collection_name = value
self.collection = self.db[value] | 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. | 5.927942 | 5.416451 | 1.094433 |
if aliases_config is None:
with open(os.path.join(os.path.dirname(__file__),
"aliases.json")) as f:
d = json.load(f)
self.aliases = d.get("aliases", {})
self.default_criteria = d.get("defaults", {})
e... | 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 alias dict to use. Defaults to None, which means the default
aliases defined in "aliases.json" is used. See constructor
... | 2.069711 | 2.197824 | 0.941709 |
chemsys_list = []
for i in range(len(elements)):
for combi in itertools.combinations(elements, i + 1):
chemsys = "-".join(sorted(combi))
chemsys_list.append(chemsys)
crit = {"chemsys": {"$in": chemsys_list}}
if additional_criteria is n... | 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_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... | 2.350423 | 2.796924 | 0.84036 |
all_entries = list()
optional_data = [] if not optional_data else list(optional_data)
optional_data.append("oxide_type")
fields = [k for k in optional_data]
fields.extend(["task_id", "unit_cell_formula", "energy", "is_hubbard",
"hubbards", "pseudo_... | 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,
are returned. The dataset is very heterogeneous and not
directly compa... | 2.751872 | 2.673329 | 1.02938 |
if criteria is None:
return dict()
parsed_crit = dict()
for k, v in self.default_criteria.items():
if k not in criteria:
parsed_crit[self.aliases.get(k, k)] = v
for key, crit in list(criteria.items()):
if key in ["normalized_f... | 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}.
If 'criteria' is None, returns an empty dict. Putting th... | 2.995147 | 2.809079 | 1.066238 |
return self.collection.ensure_index(key, unique=unique) | def ensure_index(self, key, unique=False) | Wrapper for pymongo.Collection.ensure_index | 3.814793 | 3.611785 | 1.056207 |
if properties is not None:
props, prop_dict = self._parse_properties(properties)
else:
props, prop_dict = None, None
crit = self._parse_criteria(criteria)
if self.query_post:
for func in self.query_post:
func(crit, props)
... | 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 of supported
properties.
Results are returned as an iterator of dicts to ensure memory and cpu
... | 3.207715 | 3.089604 | 1.038228 |
props = {}
# TODO: clean up prop_dict?
prop_dict = OrderedDict()
# We use a dict instead of list to provide for a richer syntax
for p in properties:
if p in self.aliases:
if isinstance(properties, dict):
props[self.aliases[... | 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 | 5.526664 | 5.115977 | 1.080275 |
for r in self.query(*args, **kwargs):
return r
return None | def query_one(self, *args, **kwargs) | Return first document from :meth:`query`, with same parameters. | 4.438764 | 3.404433 | 1.303819 |
args = {'task_id': task_id}
field = 'output.crystal' if final_structure else 'input.crystal'
results = tuple(self.query([field], args))
if len(results) > 1:
raise QueryError("More than one result found for task_id {}!".format(task_id))
elif len(results) == 0... | 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. Defaults to
True. | 3.003772 | 3.159487 | 0.950715 |
with open(config_file) as f:
d = json.load(f)
user = d["admin_user"] if use_admin else d["readonly_user"]
password = d["admin_password"] if use_admin \
else d["readonly_password"]
return QueryEngine(
host=d["host"], port=d[... | 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 config file is
used. Otherwise, the readonly_user and pa... | 2.727985 | 2.360053 | 1.1559 |
args = {'task_id': task_id}
fields = ['calculations']
structure = self.get_structure_from_id(task_id)
dosid = None
for r in self.query(fields, args):
dosid = r['calculations'][-1]['dos_fs_id']
if dosid is not None:
self._fs = gridfs.GridFS... | def get_dos_from_id(self, task_id) | Overrides the get_dos_from_id for the MIT gridfs format. | 3.507074 | 3.327745 | 1.053889 |
def wrapped(*args, **kwargs):
ret_val = func(*args, **kwargs)
if isinstance(ret_val, pymongo.cursor.Cursor):
ret_val = self.from_cursor(ret_val)
return ret_val
return wrapped | 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 | 2.638056 | 2.617975 | 1.00767 |
# 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:
result = r
else:
result = dict()
# Map ... | def _mapped_result(self, r) | Transform/map a result. | 7.065177 | 7.182022 | 0.983731 |
if not os.path.exists(path):
raise SchemaPathError()
filepat = "*." + ext if ext else "*"
for f in glob.glob(os.path.join(path, filepat)):
with open(f, 'r') as fp:
try:
schema = json.load(fp)
except ValueError:
raise SchemaParseErr... | 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: str
:param ext: File extension that ide... | 2.697139 | 2.54092 | 1.061481 |
fp = open(file_or_fp, 'r') if isinstance(file_or_fp, str) else file_or_fp
obj = json.load(fp)
schema = Schema(obj)
return 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. | 2.188089 | 2.736925 | 0.79947 |
self._json_schema_keys = add_keys
if self._json_schema is None:
self._json_schema = self._build_schema(self._schema)
return self._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: Key, default value pairs to add in,
... | 3.198109 | 3.572671 | 0.895159 |
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_DICT:
js = {"type": "object",
"properties": {key: self._build_sch... | def _build_schema(self, s) | Recursive schema builder, called by `json_schema`. | 2.67095 | 2.515979 | 1.061595 |
if stype == self.IS_LIST:
return "array"
if stype == self.IS_DICT:
return "object"
if isinstance(sval, Scalar):
return sval.jstype
# it is a Schema, so return type of contents
v = sval._schema
return self._jstype(self._whatis(v... | def _jstype(self, stype, sval) | Get JavaScript name for given data type, called by `_build_schema`. | 6.143893 | 5.226649 | 1.175494 |
v = str(db_version)
return os.path.join(_top_dir, '..', 'schemata', 'versions', v) | 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 | 5.961636 | 7.285122 | 0.81833 |
d = get_schema_dir(db_version=db_version)
schemafile = "{}.{}.json".format(db, collection)
f = open(os.path.join(d, schemafile), "r")
return f | 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'
:type collection: str
:return: File with schema
:rtype: file
:raise: I... | 3.195648 | 3.88748 | 0.822036 |
settings = yaml.load(_as_file(infile))
if not hasattr(settings, 'keys'):
raise ValueError("Settings not found in {}".format(infile))
# Processing of namespaced parameters in .pmgrc.yaml.
processed_settings = {}
for k, v in settings.items():
if k.startswith("PMG_DB_"):
... | 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 | 5.4054 | 6.140615 | 0.88027 |
for alias, real in ((USER_KEY, "readonly_user"),
(PASS_KEY, "readonly_password")):
if alias in d:
d[real] = d[alias]
del d[alias] | def auth_aliases(d) | Interpret user/password aliases. | 4.571385 | 4.138709 | 1.104544 |
U, P = USER_KEY, PASS_KEY
# If user/password, un-prefixed, exists, do nothing.
if U in settings and P in settings:
return True
# Set prefixes
prefixes = []
if readonly_first:
if readonly:
prefixes.append("readonly_")
if admin:
prefixes.append... | 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: Connection settings
:type settings: dict
:param admin: Check for admin password
:p... | 2.85235 | 2.757812 | 1.03428 |
main_fmt, sub_fmt = fmt.split('/')
if sub_fmt.lower() == "text":
msg = MIMEText(text, "plain")
elif sub_fmt.lower() == "html":
msg = MIMEText(text, "html")
else:
raise ValueError("Unknown message format: {}".format(fmt))
msg['Subject']... | 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 | 2.461065 | 2.393669 | 1.028156 |
keyset, maxwid = set(), {}
for r in rs:
key = tuple(sorted(r.keys()))
keyset.add(key)
if key not in maxwid:
maxwid[key] = [len(k) for k in key]
for i, k in enumerate(key):
strlen = len("{}".format(r[k]))
... | 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 | 3.265946 | 2.491223 | 1.310981 |
columns = list(columns) # might be a tuple
fixed_cols = [self.key]
if section.lower() == "different":
fixed_cols.extend([Differ.CHANGED_MATCH_KEY, Differ.CHANGED_OLD, Differ.CHANGED_NEW])
map(columns.remove, fixed_cols)
columns.sort()
return fixed_co... | def ordered_cols(self, columns, section) | Return ordered list of columns, from given columns and the name of the section | 6.825232 | 6.715484 | 1.016343 |
#print("@@ SORT ROWS:\n{}".format(rows))
# Section-specific determination of sort key
if section.lower() == Differ.CHANGED.lower():
sort_key = Differ.CHANGED_DELTA
else:
sort_key = None
if sort_key is not None:
rows.sort(key=itemgetter... | 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 | 6.035353 | 5.084216 | 1.187077 |
self._add_meta(result)
walker = JsonWalker(JsonWalker.value_json, JsonWalker.dict_expand)
r = walker.walk(result)
return r | def document(self, result) | Build dict for MongoDB, expanding result keys as we go. | 9.801039 | 8.303707 | 1.180321 |
css = "\n".join(self.css)
content = "{}{}".format(self._header(), self._body(result))
if self._email:
text = .format(css=css, content=content, sty=self.styles["content"]["_"])
else:
text = .format(css=css, content=content)
return text | def format(self, result) | Generate HTML report.
:return: Report body
:rtype: str | 6.658585 | 7.011383 | 0.949682 |
m = self.meta
lines = ['-' * len(self.TITLE),
self.TITLE,
'-' * len(self.TITLE),
"Compared: {db1} <-> {db2}".format(**m),
"Filter: {filter}".format(**m),
"Run time: {start_time} -- {end_time} ({elapsed:.1f} sec... | def format(self, result) | Generate plain text report.
:return: Report body
:rtype: str | 4.116481 | 4.067521 | 1.012037 |
try:
qe = clazz(**config.settings)
except Exception as err:
raise CreateQueryEngineError(clazz, config.settings, err)
return qe | 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.QueryEngine.
:type clazz: class
:return: New que... | 4.270379 | 5.595614 | 0.763165 |
if os.path.isdir(path):
configs = glob.glob(_opj(path, pattern))
else:
configs = [path]
for config in configs:
cfg = dbconfig.DBConfig(config_file=config)
cs = cfg.settings
if dbconfig.DB_KEY not in cs:
... | 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 each file is the database name
and collection na... | 3.396121 | 3.025057 | 1.122664 |
self._d[name] = cfg
if expand:
self.expand(name)
return self | 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, for chaining
:raises: CreateQueryEngineError... | 4.523746 | 7.116201 | 0.635697 |
if self._is_pattern(name):
expr = re.compile(self._pattern_to_regex(name))
for cfg_name in self._d.keys():
if expr.match(cfg_name):
self._expand(cfg_name)
else:
self._expand(name) | 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']
and a configuration
{... | 3.282487 | 3.06913 | 1.069517 |
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
cur_coll = coll.name
for coll_name in db.collection_names():
... | def _expand(self, name) | Perform real work of `expand()` function. | 3.793854 | 3.733743 | 1.016099 |
delme = []
if self._is_pattern(name):
expr = re.compile(self._pattern_to_regex(name))
for key, obj in self._cached.items():
if expr.match(key):
delme.append(key)
else:
if name in self._cached:
delme.... | 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 | 2.569784 | 2.73123 | 0.940889 |
if prefix is None:
self._pfx = None
else:
self._pfx = prefix + self.SEP | 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 | 4.772971 | 5.147606 | 0.927221 |
if key in self._cached:
return self._cached[key]
qe = create_query_engine(obj, self._class)
self._cached[key] = qe
return qe | def _get_qe(self, key, obj) | Instantiate a query engine, or retrieve a cached one. | 3.536996 | 2.68769 | 1.315998 |
if not pattern.endswith("$"):
pattern += "$"
expr = re.compile(pattern)
return list(filter(expr.match, self.keys())) | def re_keys(self, pattern) | Find keys matching `pattern`.
:param pattern: Regular expression
:return: Matching keys or empty list
:rtype: list | 3.305141 | 4.014382 | 0.823325 |
return {k: self[k] for k in self.re_keys(pattern)} | def re_get(self, pattern) | Return values whose key matches `pattern`
:param pattern: Regular expression
:return: Found values, as a dict. | 6.575634 | 6.480856 | 1.014624 |
self._target_coll = target.collection
if not crit: # reduce any False-y crit value to None
crit = None
cur = source.query(criteria=crit)
_log.info("source.collection={} crit={} source_records={:d}"
.format(source.collection, crit, len(cur)))
... | 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': True }".
:type crit: dict | 8.021866 | 8.448709 | 0.949478 |
doc = fn.__doc__
params, return_ = {}, {}
param_order = []
for line in doc.split("\n"):
line = line.strip()
if line.startswith(":param"):
_, name, desc = line.split(":", 2)
name = name[6:].strip() # skip 'param '
params[name] = {'desc': desc.stri... | 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: tuple(dict) | 2.068426 | 2.066459 | 1.000952 |
merged = copy.copy(sandbox_collections)
# create/clear target collection
target = merged.database[new_tasks]
if wipe:
_log.debug("merge_tasks.wipe.begin")
target.remove()
merged.database['counter'].remove()
_log.debug("merge_tasks.wipe.end")
# perform the merge
... | def merge_tasks(core_collections, sandbox_collections, id_prefix, new_tasks, batch_size=100, wipe=False) | Merge core and sandbox collections into a temporary collection in the sandbox.
:param core_collections: Core collection info
:type core_collections: Collections
:param sandbox_collections: Sandbox collection info
:type sandbox_collections: Collections | 2.622543 | 2.773457 | 0.945586 |
sep = '\n' + ' ' * depth * indent
return ''.join(
("{}: {}{}".format(
k,
alphadump(d[k], depth=depth+1) if isinstance(d[k], dict)
else str(d[k]),
sep)
for k in sorted(d.keys()))
) | def alphadump(d, indent=2, depth=0) | Dump a dict to a str,
with keys in alphabetical order. | 2.970417 | 3.02683 | 0.981362 |
for collection, doc in self.examples():
_log.debug("validating example in collection {}".format(collection))
sch = schema.get_schema(collection) # with more err. checking
result = sch.validate(doc)
_log.debug("validation result: {}".format("OK" if result... | def validate_examples(self, fail_fn) | Check the examples against the schema.
:param fail_fn: Pass failure messages to this function
:type fail_fn: function(str) | 5.96017 | 5.873982 | 1.014673 |
user_kw = {} if user_kw is None else user_kw
build_kw = {} if build_kw is None else build_kw
n = self._build(self.get_items(**user_kw), **build_kw)
finalized = self.finalize(self._status.has_failures())
if not finalized:
_log.error("Finalization failed")
... | def run(self, user_kw=None, build_kw=None) | Run the builder.
:param user_kw: keywords from user
:type user_kw: dict
:param build_kw: internal settings
:type build_kw: dict
:return: Number of items processed
:rtype: int | 3.928772 | 4.105263 | 0.957009 |
if isinstance(config, str):
conn = dbutil.get_database(config_file=config)
elif isinstance(config, dict):
conn = dbutil.get_database(settings=config)
else:
raise ValueError("Configuration, '{}', must be a path to "
"a con... | def connect(self, config) | Connect to database with given configuration, which may be a dict or
a path to a pymatgen-db configuration. | 4.070602 | 3.655414 | 1.113582 |
_log.debug("_build, chunk_size={:d}".format(chunk_size))
n, i = 0, 0
for i, item in enumerate(items):
if i == 0:
_log.debug("_build, first item")
if 0 == (i + 1) % chunk_size:
if self._seq:
self._run(0)
... | def _build(self, items, chunk_size=10000) | Build the output, in chunks.
:return: Number of items processed
:rtype: int | 3.386686 | 3.353618 | 1.00986 |
_log.debug("run.parallel.multiprocess.start")
processes = []
ProcRunner.instance = self
for i in range(self._ncores):
self._status.running(i)
proc = multiprocessing.Process(target=ProcRunner.run, args=(i,))
proc.start()
processes.a... | def _run_parallel_multiprocess(self) | Run processes from queue | 3.201176 | 3.050891 | 1.049259 |
while 1:
try:
item = self._queue.get(timeout=2)
self.process_item(item)
except Queue.Empty:
break
except Exception as err:
_log.error("In _run(): {}".format(err))
if _log.isEnabledFor(log... | def _run(self, index) | Run method for one thread or process
Just pull an item off the queue and process it,
until the queue is empty.
:param index: Sequential index of this process or thread
:type index: int | 3.189753 | 3.133356 | 1.017999 |
def _keys(x, pre=''):
for k in x:
yield (pre + k)
if isinstance(x[k], dict):
for nested in _keys(x[k], pre + k + sep):
yield nested
return list(_keys(coll.find_one())) | def collection_keys(coll, sep='.') | Get a list of all (including nested) keys in a collection.
Examines the first document in the collection.
:param sep: Separator for nested keys
:return: List of str | 3.925681 | 3.656138 | 1.073723 |
if len(d) == 0:
return "{}"
return "{" + ', '.join(["'{}': {}".format(k, quotable(v))
for k, v in d.items()]) + "}" | def csv_dict(d) | Format dict to a string with comma-separated values. | 3.679791 | 3.571558 | 1.030304 |
return ', '.join(
["{}={}".format(k, quotable(v)) for k, v in d.items()]) | def kvp_dict(d) | Format dict to key=value pairs. | 4.828007 | 4.573187 | 1.05572 |
self._groups = self.shared_dict()
self._target_coll = target.collection
self._src = source
return source.query() | def get_items(self, source=None, target=None) | Get all records from source collection to add to target.
:param source: Input collection
:type source: QueryEngine
:param target: Output collection
:type target: QueryEngine | 17.708933 | 15.037261 | 1.17767 |
group, value = item['group'], item['value']
if group in self._groups:
cur_val = self._groups[group]
self._groups[group] = max(cur_val, value)
else:
# New group. Could fetch old max. from target collection,
# but for the sake of illustratio... | def process_item(self, item) | Calculate new maximum value for each group,
for "new" items only. | 5.810564 | 5.053009 | 1.149921 |
for group, value in self._groups.items():
doc = {'group': group, 'value': value}
self._target_coll.update({'group': group}, doc, upsert=True)
return True | def finalize(self, errs) | Update target collection with calculated maximum values. | 6.316765 | 3.754188 | 1.682591 |
if not rec:
return default
if not isinstance(rec, collections.Mapping):
raise ValueError('input record must act like a dict')
if not '.' in key:
return rec.get(key, default)
for key_part in key.split('.'):
if not isinstance(rec, collections.Mapping):
retu... | def mongo_get(rec, key, default=None) | Get value from dict using MongoDB dot-separated path semantics.
For example:
>>> assert mongo_get({'a': {'b': 1}, 'x': 2}, 'a.b') == 1
>>> assert mongo_get({'a': {'b': 1}, 'x': 2}, 'x') == 2
>>> assert mongo_get({'a': {'b': 1}, 'x': 2}, 'a.b.c') is None
:param rec: mongodb document
:param key:... | 2.486252 | 2.539134 | 0.979173 |
if field.has_subfield():
self._fields[field.full_name] = 1
else:
self._fields[field.name] = 1
if op and op.is_size() and not op.is_variable():
# get minimal part of array with slicing,
# but cannot use slice with variables
self... | def add(self, field, op=None, val=None) | Update report fields to include new one, if it doesn't already.
:param field: The field to include
:type field: Field
:param op: Operation
:type op: ConstraintOperator
:return: None | 7.287474 | 7.776165 | 0.937155 |
d = copy.copy(self._fields)
for k, v in self._slices.items():
d[k] = {'$slice': v}
return d | def to_mongo(self) | Translate projection to MongoDB query form.
:return: Dictionary to put into a MongoDB JSON query
:rtype: dict | 4.883687 | 5.801854 | 0.841746 |
rec = {} if record is None else record
for v in violations:
self._viol.append((v, rec)) | def add_violations(self, violations, record=None) | Add constraint violations and associated record.
:param violations: List of violations
:type violations: list(ConstraintViolation)
:param record: Associated record
:type record: dict
:rtype: None | 6.368894 | 9.079464 | 0.701461 |
# extract filter and constraints
try:
fltr = item[self.FILTER_SECT]
except KeyError:
raise ValueError("configuration requires '{}'".format(self.FILTER_SECT))
sample = item.get(self.SAMPLE_SECT, None)
constraints = item.get(self.CONSTRAINT_SECT, No... | def _add_complex_section(self, item) | Add a section that has a filter and set of constraints
:raise: ValueError if filter or constraints is missing | 3.788126 | 3.278013 | 1.155616 |
self._spec = constraint_spec
self._progress.set_subject(subject)
self._build(constraint_spec)
for sect_parts in self._sections:
cvg = self._validate_section(subject, coll, sect_parts)
if cvg is not None:
yield cvg | def validate(self, coll, constraint_spec, subject='collection') | Validation of a collection.
This is a generator that yields ConstraintViolationGroups.
:param coll: Mongo collection
:type coll: pymongo.Collection
:param constraint_spec: Constraint specification
:type constraint_spec: ConstraintSpec
:param subject: Name of the thing b... | 6.475328 | 5.487815 | 1.179946 |
cvgroup = ConstraintViolationGroup()
cvgroup.subject = subject
# If the constraint is an 'import' of code, treat it differently here
# if self._is_python(parts):
# num_found = self._run_python(cvgroup, coll, parts)
# return None if num_found == 0 else cvgr... | def _validate_section(self, subject, coll, parts) | Validate one section of a spec.
:param subject: Name of subject
:type subject: str
:param coll: The collection to validate
:type coll: pymongo.Collection
:param parts: Section parts
:type parts: Validator.SectionParts
:return: Group of constraint violations, if a... | 4.255668 | 4.050648 | 1.050614 |
# special case, when no constraints are given
if len(query.all_clauses) == 0:
return [NullConstraintViolation()]
# normal case, check all the constraints
reasons = []
for clause in query.all_clauses:
var_name = None
key = clause.constr... | def _get_violations(self, query, record) | Reverse-engineer the query to figure out why a record was selected.
:param query: MongoDB query
:type query: MongQuery
:param record: Record in question
:type record: dict
:return: Reasons why bad
:rtype: list(ConstraintViolation) | 3.351036 | 3.224913 | 1.039109 |
self._sections = []
# For each condition in the spec
for sval in constraint_spec:
rpt_fld = self._base_report_fields.copy()
#print("@@ CONDS = {}".format(sval.filters))
#print("@@ MAIN = {}".format(sval.constraints))
# Constraints
... | def _build(self, constraint_spec) | Generate queries to execute.
Sets instance variables so that Mongo query strings, etc. can now
be extracted from the object.
:param constraint_spec: Constraint specification
:type constraint_spec: ConstraintSpec | 4.866354 | 4.772777 | 1.019606 |
# process expressions, grouping by field
groups = {}
for expr in expr_list:
field, raw_op, val = parse_expr(expr)
op = ConstraintOperator(raw_op)
if field not in groups:
groups[field] = ConstraintGroup(Field(field, self._aliases))
... | def _process_constraint_expressions(self, expr_list, conflict_check=True, rev=True) | Create and return constraints from expressions in expr_list.
:param expr_list: The expressions
:conflict_check: If True, check for conflicting expressions within each field
:return: Constraints grouped by field (the key is the field name)
:rtype: dict | 3.336076 | 3.304276 | 1.009624 |
if len(constraint_list) == 1 and \
PythonMethod.constraint_is_method(constraint_list[0]):
return True
if len(constraint_list) > 1 and \
any(filter(PythonMethod.constraint_is_method, constraint_list)):
condensed_list = '/'.join(constraint_l... | def _is_python(self, constraint_list) | Check whether constraint is an import of Python code.
:param constraint_list: List of raw constraints from YAML file
:type constraint_list: list(str)
:return: True if this refers to an import of code, False otherwise
:raises: ValidatorSyntaxError | 4.436063 | 4.475821 | 0.991117 |
"Set aliases and wrap errors in ValueError"
try:
self.aliases = new_value
except Exception as err:
raise ValueError("invalid value: {}".format(err)) | def set_aliases(self, new_value) | Set aliases and wrap errors in ValueError | 7.743413 | 4.195139 | 1.845806 |
count = cursor.count()
# special case: empty collection
if count == 0:
self._empty = True
raise ValueError("Empty collection")
# special case: entire collection
if self.p >= 1 and self.max_items <= 0:
for item in cursor:
... | def sample(self, cursor) | Extract records randomly from the database.
Continue until the target proportion of the items have been
extracted, or until `min_items` if this is larger.
If `max_items` is non-negative, do not extract more than these.
This function is a generator, yielding items incrementally.
... | 3.938018 | 3.540545 | 1.112263 |
print 'The following LiveSync agents are available:'
for name, backend in current_plugin.backend_classes.iteritems():
print cformat(' - %{white!}{}%{reset}: {} ({})').format(name, backend.title, backend.description) | def available_backends() | Lists the currently available backend types | 12.005801 | 12.448941 | 0.964403 |
print 'The following LiveSync agents are active:'
agent_list = LiveSyncAgent.find().order_by(LiveSyncAgent.backend_name, db.func.lower(LiveSyncAgent.name)).all()
table_data = [['ID', 'Name', 'Backend', 'Initial Export', 'Queue']]
for agent in agent_list:
initial = (cformat('%{green!}done%{r... | def agents() | Lists the currently active agents | 4.043992 | 3.972431 | 1.018014 |
agent = LiveSyncAgent.find_first(id=agent_id)
if agent is None:
print 'No such agent'
return
if agent.backend is None:
print cformat('Cannot run agent %{red!}{}%{reset} (backend not found)').format(agent.name)
return
print cformat('Selected agent: %{white!}{}%{reset}... | def initial_export(agent_id, force) | Performs the initial data export for an agent | 4.856945 | 4.800968 | 1.011659 |
if agent_id is None:
agent_list = LiveSyncAgent.find_all()
else:
agent = LiveSyncAgent.find_first(id=agent_id)
if agent is None:
print 'No such agent'
return
agent_list = [agent]
for agent in agent_list:
if agent.backend is None:
... | def run(agent_id, force=False) | Runs the livesync agent | 3.003202 | 2.807198 | 1.069822 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.