code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
abs_path = get_abs_sciobj_file_path_by_pid(pid) with open_sciobj_file_by_path_ctx(abs_path, write) as sciobj_file: yield sciobj_file
def open_sciobj_file_by_pid_ctx(pid, write=False)
Open the file containing the Science Object bytes of ``pid`` in the default location within the tree of the local SciObj store. If ``write`` is True, the file is opened for writing and any missing directories are created. Return the file handle and file_url with the file location in a suitable form for...
2.272991
2.930929
0.775519
if write: d1_common.utils.filesystem.create_missing_directories_for_file(abs_path) try: with open(abs_path, 'wb' if write else 'rb') as sciobj_file: yield sciobj_file finally: if os.path.exists(abs_path) and not os.path.getsize(abs_path): os.unlink(abs_pa...
def open_sciobj_file_by_path_ctx(abs_path, write=False)
Open the file containing the Science Object bytes at the custom location ``abs_path`` in the local filesystem. If ``write`` is True, the file is opened for writing and any missing directores are created. Return the file handle and file_url with the file location in a suitable form for storing in the DB...
2.376676
2.648676
0.897307
abs_path = get_abs_sciobj_file_path_by_pid(pid) if write: d1_common.utils.filesystem.create_missing_directories_for_file(abs_path) return open_sciobj_file_by_path(abs_path, write)
def open_sciobj_file_by_pid(pid, write=False)
Open the file containing the Science Object bytes at the custom location ``abs_path`` in the local filesystem for read.
2.808498
3.03273
0.926063
if write: d1_common.utils.filesystem.create_missing_directories_for_file(abs_path) return open(abs_path, 'wb' if write else 'rb')
def open_sciobj_file_by_path(abs_path, write=False)
Open a SciObj file for read or write. If opened for write, create any missing directories. For a SciObj stored in the default SciObj store, the path includes the PID hash based directory levels. This is the only method in GMN that opens SciObj files, so can be modified to customize the SciObj storage l...
3.520842
5.124735
0.687029
hash_str = hashlib.sha1(pid.encode('utf-8')).hexdigest() return os.path.join(hash_str[:2], hash_str[2:4], hash_str)
def get_rel_sciobj_file_path(pid)
Get the relative local path to the file holding an object's bytes. - The path is relative to settings.OBJECT_STORE_PATH - There is a one-to-one mapping between pid and path - The path is based on a SHA1 hash. It's now possible to craft SHA1 collisions, but it's so unlikely that we ignore it for now ...
2.659605
2.96105
0.898197
assert_sciobj_store_exists() m = re.match(r'file://(.*?)/(.*)', file_url, re.IGNORECASE) if m.group(1) == RELATIVE_PATH_MAGIC_HOST_STR: return os.path.join(get_abs_sciobj_store_path(), m.group(2)) assert os.path.isabs(m.group(2)) return m.group(2)
def get_abs_sciobj_file_path_by_url(file_url)
Get the absolute path to the file holding an object's bytes. - ``file_url`` is an absolute or relative file:// url as stored in the DB.
3.338491
3.630703
0.919516
home_url = d1_common.url.joinPathElements(base_url, 'home') try: response = requests.get(home_url, verify=False) except requests.exceptions.ConnectionError as e: return False, str(e) if not response.ok: return False, 'invalid /home. status={}'.format(response.status_code) ...
def get_gmn_version(base_url)
Return the version currently running on a GMN instance. (is_gmn, version_or_error)
2.783415
2.795683
0.995612
subject_info_pyxb = deserialize_subject_info(subject_info_xml) subject_info_tree = gen_subject_info_tree(subject_info_pyxb, primary_str) return subject_info_tree.get_subject_set()
def extract_subjects(subject_info_xml, primary_str)
Extract a set of authenticated subjects from a DataONE SubjectInfo. - See subject_info_tree for details. Args: subject_info_xml : str A SubjectInfo XML document. primary_str : str A DataONE subject, typically a DataONE compliant serialization of the DN of t...
3.598102
3.915593
0.918916
try: return d1_common.xml.deserialize(subject_info_xml) except ValueError as e: raise d1_common.types.exceptions.InvalidToken( 0, 'Could not deserialize SubjectInfo. subject_info="{}", error="{}"'.format( subject_info_xml, str(e) ), ...
def deserialize_subject_info(subject_info_xml)
Deserialize SubjectInfo XML doc to native object. Args: subject_info_xml: str SubjectInfo XML doc Returns: SubjectInfo PyXB object
3.512228
3.888673
0.903194
class State: pass state = State() state.subject_info_pyxb = subject_info_pyxb state.include_duplicates = include_duplicates state.visited_set = set() state.tree = SubjectInfoNode("Root", TYPE_NODE_TAG) _add_subject(state, state.tree, authn_subj) symbolic_node =...
def gen_subject_info_tree(subject_info_pyxb, authn_subj, include_duplicates=False)
Convert the flat, self referential lists in the SubjectInfo to a tree structure. Args: subject_info_pyxb: SubjectInfo PyXB object authn_subj: str The authenticated subject that becomes the root subject in the tree of subjects built from the SubjectInfo. Only su...
5.012133
4.997998
1.002828
for n in list(state.tree.leaf_node_gen): if n.type_str == TYPE_NODE_TAG: n.parent.child_list.remove(n) return _trim_tree(state)
def _trim_tree(state)
Trim empty leaf nodes from the tree. - To simplify the tree conversion, empty nodes are added before it is known if they will contain items that connect back to the authenticated subject. If there are no connections, the nodes remain empty, which causes them to be removed here. - Removing a leaf n...
7.199714
7.805899
0.922343
child_node = SubjectInfoNode(label_str, type_str) child_node.parent = self self.child_list.append(child_node) return child_node
def add_child(self, label_str, type_str)
Add a child node.
3.249739
2.947424
1.102569
return sep.join( list( reversed( [ v.label_str for v in self.parent_gen if type_str in (None, v.type_str) ] ) ) )
def get_path_str(self, sep=os.path.sep, type_str=None)
Get path from root to this node. Args: sep: str One or more characters to insert between each element in the path. Defaults to "/" on Unix and "\" on Windows. type_str: SUBJECT_NODE_TAG, TYPE_NODE_TAG or None. If set, only include ...
4.736064
5.807296
0.815537
return [v.get_path_str(sep, type_str) for v in self.leaf_node_gen]
def get_leaf_node_path_list(self, sep=os.path.sep, type_str=None)
Get paths for all leaf nodes for the tree rooted at this node. Args: sep: str One or more characters to insert between each element in the path. Defaults to "/" on Unix and "\" on Windows. type_str: SUBJECT_NODE_TAG, TYPE_NODE_TAG or None...
5.827504
9.012048
0.646635
return list( reversed( [v.label_str for v in self.parent_gen if type_str in (None, v.type_str)] ) )
def get_path_list(self, type_str=None)
Get list of the labels of the nodes leading up to this node from the root. Args: type_str: SUBJECT_NODE_TAG, TYPE_NODE_TAG or None. If set, only include information from nodes of that type. Returns: list of str: The labels of the nodes leading up...
8.285977
8.755405
0.946384
return {v.label_str for v in self.node_gen if type_str in (None, v.type_str)}
def get_label_set(self, type_str=None)
Get a set of label_str for the tree rooted at this node. Args: type_str: SUBJECT_NODE_TAG, TYPE_NODE_TAG or None. If set, only include information from nodes of that type. Returns: set: The labels of the nodes leading up to this node from the roo...
7.889313
8.518565
0.926132
assert ( task_type_str not in self._task_dict ), "Task type has already been started" self._task_dict[task_type_str] = { "start_time": time.time(), "total_task_count": total_task_count, "task_idx": 0, }
def start_task_type(self, task_type_str, total_task_count)
Call when about to start processing a new type of task, typically just before entering a loop that processes many task of the given type. Args: task_type_str (str): The name of the task, used as a dict key and printed in the progress updates. tot...
2.47105
2.51808
0.981323
assert ( task_type_str in self._task_dict ), "Task type has not been started yet: {}".format(task_type_str) self._log_progress() del self._task_dict[task_type_str]
def end_task_type(self, task_type_str)
Call when processing of all tasks of the given type is completed, typically just after exiting a loop that processes many tasks of the given type. Progress messages logged at intervals will typically not include the final entry which shows that processing is 100% complete, so a final progress m...
4.091134
3.957734
1.033706
assert ( task_type_str in self._task_dict ), "Task type has not been started yet: {}".format(task_type_str) if current_task_index is not None: self._task_dict[task_type_str]["task_idx"] = current_task_index else: self._task_dict[task_type_str]...
def start_task(self, task_type_str, current_task_index=None)
Call when processing is about to start on a single task of the given task type, typically at the top inside of the loop that processes the tasks. Args: task_type_str (str): The name of the task, used as a dict key and printed in the progress updates. ...
2.789714
2.801316
0.995858
self._event_dict.setdefault(event_name, 0) self._event_dict[event_name] += 1 self._log_progress_if_interval_elapsed()
def event(self, event_name)
Register an event that occurred during processing of a task of the given type. Args: event_name: str A name for a type of events. Events of the same type are displayed as a single entry and a total count of occurences.
4.469062
4.671524
0.95666
r # these are the problematic sectors classes = ['cu', 'db', 'sb', 'sd', 'mue', 'mutau', 'taue', 'dF0'] if classname not in classes or f == 5: # for 5-flavour WET, nothing to do. # Neither for other classes (I, II, ...) because they exist either all # or not at all in WET-3 and W...
def get_permissible_wcs(classname, f)
r"""For some classes (in particular $\Delta F=1$), only a subset of Wilson coefficients exist in WET-3 and WET-4. Therefore, depending on the number of flavours `f`, the dimensionality of the ADM has to be reduced.
11.195537
8.426271
1.328647
args = f, m_u, m_d, m_s, m_c, m_b, m_e, m_mu, m_tau A = getattr(adm, 'adm_s_' + classname)(*args) perm_keys = get_permissible_wcs(classname, f) if perm_keys != 'all': # remove disallowed rows & columns if necessary A = A[perm_keys][:, perm_keys] w, v = np.linalg.eig(A.T) ret...
def admeig(classname, f, m_u, m_d, m_s, m_c, m_b, m_e, m_mu, m_tau)
Compute the eigenvalues and eigenvectors for a QCD anomalous dimension matrix that is defined in `adm.adm_s_X` where X is the name of the sector. Supports memoization. Output analogous to `np.linalg.eig`.
4.573183
4.07164
1.12318
w, v = admeig(classname, f, m_u, m_d, m_s, m_c, m_b, m_e, m_mu, m_tau) b0s = 11 - 2 * f / 3 a = w / (2 * b0s) return v @ np.diag(eta_s**a) @ np.linalg.inv(v)
def getUs(classname, eta_s, f, alpha_s, alpha_e, m_u, m_d, m_s, m_c, m_b, m_e, m_mu, m_tau)
Get the QCD evolution matrix.
4.600235
4.638784
0.99169
args = f, m_u, m_d, m_s, m_c, m_b, m_e, m_mu, m_tau A = getattr(adm, 'adm_e_' + classname)(*args) perm_keys = get_permissible_wcs(classname, f) if perm_keys != 'all': # remove disallowed rows & columns if necessary A = A[perm_keys][:, perm_keys] w, v = admeig(classname, *args) ...
def getUe(classname, eta_s, f, alpha_s, alpha_e, m_u, m_d, m_s, m_c, m_b, m_e, m_mu, m_tau)
Get the QCD evolution matrix.
4.094017
4.025353
1.017058
r Cdictout = OrderedDict() classname = sectors[sector] keylist = coeffs[sector] if sector == 'dF=0': perm_keys = get_permissible_wcs('dF0', f) else: perm_keys = get_permissible_wcs(sector, f) if perm_keys != 'all': # remove disallowed keys if necessary keylist...
def run_sector(sector, C_in, eta_s, f, p_in, p_out, qed_order=1, qcd_order=1)
r"""Solve the WET RGE for a specific sector. Parameters: - sector: sector of interest - C_in: dictionary of Wilson coefficients - eta_s: ratio of $\alpha_s$ at input and output scale - f: number of active quark flavours - p_in: running parameters at the input scale - p_out: running paramet...
3.670437
3.739733
0.98147
for k, v in list(src_tree.items()): # Prepend an underscore to the administrative area names, to make them # sort separately from the identifiers. # k = '_' + k if k not in dst_tree or dst_tree[k] is None: dst_tree[k] = {} dst_...
def _merge_region_trees(self, dst_tree, src_tree, pid)
Merge conflicts occur if a folder in one tree is a file in the other. As the files are PIDs, this can only happen if a PID matches one of the geographical areas that the dataset covers and should be very rare. In such conflicts, the destination wins.
3.976719
3.831207
1.037981
# Handle valid item within region tree. if not path: if region_tree is None: return parent_key, [] else: return region_tree, [] # Handle valid exit through PID. if region_tree is None: return parent_key, path ...
def _get_region_tree_item_and_unconsumed_path( self, region_tree, path, parent_key='' )
Return the region_tree item specified by path. An item can be a a folder (represented by a dictionary) or a PID (represented by None). This function is also used for determining which section of a path is within the region tree and which section should be passed to the next resolver. To ...
3.902625
3.380839
1.154336
try: return super().save(**kwargs) except SlugError as error: raise ParseError(error)
def save(self, **kwargs)
Override save method to catch handled errors and repackage them as 400 errors.
7.009856
4.248146
1.650098
api_major = 0 client = d1_client.mnclient.MemberNodeClient( base_url, *client_arg_list, **client_arg_dict ) node_pyxb = client.getCapabilities() for service_pyxb in node_pyxb.services.service: if service_pyxb.available: api_major = max(api_major, int(service_pyxb.ver...
def get_api_major_by_base_url(base_url, *client_arg_list, **client_arg_dict)
Read the Node document from a node and return an int containing the latest D1 API version supported by the node. The Node document can always be reached through the v1 API and will list services for v1 and any later APIs versions supported by the node.
3.169372
2.783369
1.138682
# This causes Django to create a single join (check with query.query) query = d1_gmn.app.models.Subject.objects.all() query = query.filter(scienceobject_submitter__isnull=True) query = query.filter(scienceobject_rights_holder__isnull=True) query = query.filter(eventlog__isnull=True) query =...
def delete_unused_subjects()
Delete any unused subjects from the database. This is not strictly required as any unused subjects will automatically be reused if needed in the future.
5.739402
5.987087
0.95863
return ",".join( "{}={}".format( OID_TO_SHORT_NAME_DICT.get(v.oid.dotted_string, v.oid.dotted_string), rdn_escape(v.value), ) for v in reversed(list(cert_obj.subject)) )
def extract_subject_from_dn(cert_obj)
Serialize a DN to a DataONE subject string. Args: cert_obj: cryptography.Certificate Returns: str: Primary subject extracted from the certificate DN. The certificate DN (DistinguishedName) is a sequence of RDNs (RelativeDistinguishedName). Each RDN is a set of AVAs (AttributeValue...
3.924399
3.905449
1.004852
return cryptography.x509.Name( [ cryptography.x509.NameAttribute( cryptography.x509.oid.NameOID.COUNTRY_NAME, "US" ), cryptography.x509.NameAttribute( cryptography.x509.oid.NameOID.STATE_OR_PROVINCE_NAME, "California" ), ...
def create_d1_dn_subject(common_name_str)
Create the DN Subject for certificate that will be used in a DataONE environment. The DN is formatted into a DataONE subject, which is used in authentication, authorization and event tracking. Args: common_name_str: str DataONE uses simple DNs without physical location information, so ...
1.40893
1.53252
0.919355
return ( cryptography.x509.CertificateSigningRequestBuilder() .subject_name(subject_name) .add_extension( extension=cryptography.x509.SubjectAlternativeName( [cryptography.x509.DNSName(v) for v in fqdn_list] ), critical=False, ...
def generate_csr(private_key_bytes, subject_name, fqdn_list)
Generate a Certificate Signing Request (CSR). Args: private_key_bytes: bytes Private key with which the CSR will be signed. subject_name: str Certificate Subject Name fqdn_list: List of Fully Qualified Domain Names (FQDN) and/or IP addresses for which ...
1.522031
1.622994
0.937792
if isinstance(cert_pem, str): cert_pem = cert_pem.encode("utf-8") return cryptography.x509.load_pem_x509_certificate( data=cert_pem, backend=cryptography.hazmat.backends.default_backend() )
def deserialize_pem(cert_pem)
Deserialize PEM (Base64) encoded X.509 v3 certificate. Args: cert_pem: str or bytes PEM (Base64) encoded X.509 v3 certificate Returns: cert_obj: cryptography.Certificate
1.80348
2.175245
0.829093
return cert_obj.public_bytes( encoding=cryptography.hazmat.primitives.serialization.Encoding.PEM )
def serialize_cert_to_pem(cert_obj)
Serialize certificate to PEM. The certificate can be also be a Certificate Signing Request (CSR). Args: cert_obj: cryptography.Certificate Returns: bytes: PEM encoded certificate
2.827969
4.044032
0.699295
try: subject_info_der = cert_obj.extensions.get_extension_for_oid( cryptography.x509.oid.ObjectIdentifier(DATAONE_SUBJECT_INFO_OID) ).value.value return str(pyasn1.codec.der.decoder.decode(subject_info_der)[0]) except Exception as e: logging.debug('SubjectInfo no...
def extract_subject_info_extension(cert_obj)
Extract DataONE SubjectInfo XML doc from certificate. Certificates issued by DataONE may include an embedded XML doc containing additional information about the subject specified in the certificate DN. If present, the doc is stored as an extension with an OID specified by DataONE and formatted as speci...
3.594406
2.955936
1.215996
# TODO: It is unclear which SSL and TLS protocols are supported by the method # currently being used. The current method and the two commented out below # should be compared to determine which has the best compatibility with current # versions of Python and current best practices for protocol selec...
def download_as_der( base_url=d1_common.const.URL_DATAONE_ROOT, timeout_sec=d1_common.const.DEFAULT_HTTP_TIMEOUT, )
Download public certificate from a TLS/SSL web server as DER encoded ``bytes``. If the certificate is being downloaded in order to troubleshoot validation issues, the download itself may fail due to the validation issue that is being investigated. To work around such chicken-and-egg problems, temporarily w...
4.791167
4.468799
1.072138
return ssl.DER_cert_to_PEM_cert(download_as_der(base_url, timeout_sec))
def download_as_pem( base_url=d1_common.const.URL_DATAONE_ROOT, timeout_sec=d1_common.const.DEFAULT_HTTP_TIMEOUT, )
Download public certificate from a TLS/SSL web server as PEM encoded string. Also see download_as_der(). Args: base_url : str A full URL to a DataONE service endpoint or a server hostname timeout_sec : int or float Timeout for the SSL socket operations Returns: s...
4.929869
4.686379
1.051957
return decode_der(download_as_der(base_url, timeout_sec))
def download_as_obj( base_url=d1_common.const.URL_DATAONE_ROOT, timeout_sec=d1_common.const.DEFAULT_HTTP_TIMEOUT, )
Download public certificate from a TLS/SSL web server as Certificate object. Also see download_as_der(). Args: base_url : str A full URL to a DataONE service endpoint or a server hostname timeout_sec : int or float Timeout for the SSL socket operations Returns: c...
10.910332
8.170217
1.335379
return cryptography.x509.load_der_x509_certificate( data=cert_der, backend=cryptography.hazmat.backends.default_backend() )
def decode_der(cert_der)
Decode cert DER string to Certificate object. Args: cert_der : Certificate as a DER encoded string Returns: cryptography.Certificate()
2.166081
2.699565
0.802382
current_context = ssl._create_default_https_context ssl._create_default_https_context = ssl._create_unverified_context try: yield finally: ssl._create_default_https_context = current_context
def disable_cert_validation()
Context manager to temporarily disable certificate validation in the standard SSL library. Note: This should not be used in production code but is sometimes useful for troubleshooting certificate validation issues. By design, the standard SSL library does not provide a way to disable verification ...
1.782153
2.152244
0.828044
for extension in cert_obj.extensions: if extension.oid.dotted_string == AUTHORITY_INFO_ACCESS_OID: authority_info_access = extension.value for access_description in authority_info_access: if access_description.access_method.dotted_string == CA_ISSUERS_OID: ...
def extract_issuer_ca_cert_url(cert_obj)
Extract issuer CA certificate URL from certificate. Certificates may include a URL where the root certificate for the CA which was used for signing the certificate can be downloaded. This function returns the URL if present. The primary use for this is to fix validation failure due to non-trusted issu...
2.196005
2.433489
0.90241
return private_key.private_bytes( encoding=cryptography.hazmat.primitives.serialization.Encoding.PEM, format=cryptography.hazmat.primitives.serialization.PrivateFormat.TraditionalOpenSSL, encryption_algorithm=cryptography.hazmat.primitives.serialization.BestAvailableEncryption( ...
def serialize_private_key_to_pem(private_key, passphrase_bytes=None)
Serialize private key to PEM. Args: private_key: passphrase_bytes: Returns: bytes: PEM encoded private key
1.599311
1.774908
0.901067
return cryptography.hazmat.primitives.asymmetric.rsa.generate_private_key( public_exponent=65537, key_size=key_size, backend=cryptography.hazmat.backends.default_backend(), )
def generate_private_key(key_size=2048)
Generate a private key
1.627498
1.582882
1.028186
return cert_obj.public_key().public_bytes( encoding=cryptography.hazmat.primitives.serialization.Encoding.PEM, format=cryptography.hazmat.primitives.serialization.PublicFormat.PKCS1, )
def get_public_key_pem(cert_obj)
Extract public key from certificate as PEM encoded PKCS#1. Args: cert_obj: cryptography.Certificate Returns: bytes: PEM encoded PKCS#1 public key.
1.796995
2.085637
0.861605
with open(pem_path, "rb") as f: return cryptography.x509.load_pem_x509_csr( data=f.read(), backend=cryptography.hazmat.backends.default_backend() )
def load_csr(pem_path)
Load CSR from PEM encoded file
1.834273
1.760767
1.041747
with open(pem_path, "rb") as f: return cryptography.hazmat.primitives.serialization.load_pem_private_key( data=f.read(), password=passphrase_bytes, backend=cryptography.hazmat.backends.default_backend(), )
def load_private_key(pem_path, passphrase_bytes=None)
Load private key from PEM encoded file
1.699553
1.611978
1.054328
return cert_obj.public_bytes( cryptography.hazmat.primitives.serialization.Encoding.DER )
def serialize_cert_to_der(cert_obj)
Serialize certificate to DER. Args: cert_obj: cryptography.Certificate Returns: bytes: DER encoded certificate
2.82955
4.304329
0.657373
list( map( logger, ["{}:".format(msg_str)] + [ " {}".format(v) for v in [ "Subject: {}".format( _get_val_str(cert_obj, ["subject", "value"], reverse=True) ), ...
def log_cert_info(logger, msg_str, cert_obj)
Dump basic certificate values to the log. Args: logger: Logger Logger to which to write the certificate values. msg_str: str A message to write to the log before the certificate values. cert_obj: cryptography.Certificate Certificate containing values to log. Returns...
2.440805
2.61369
0.933854
try: return cert_obj.extensions.get_extension_for_oid( getattr(cryptography.x509.oid.ExtensionOID, extension_name) ) except cryptography.x509.ExtensionNotFound: pass
def get_extension_by_name(cert_obj, extension_name)
Get a standard certificate extension by attribute name. Args: cert_obj: cryptography.Certificate Certificate containing a standard extension. extension_name : str Extension name. E.g., 'SUBJECT_DIRECTORY_ATTRIBUTES'. Returns: Cryptography.Extension
2.405518
2.534809
0.948994
try: y = getattr(obj, path_list[0]) except AttributeError: return [] if len(path_list) == 1: return [y] else: val_list = [x for a in y for x in _get_val_list(a, path_list[1:], reverse)] if reverse: val_list.reverse() return val_list
def _get_val_list(obj, path_list, reverse=False)
Extract values from nested objects by attribute names. Objects contain attributes which are named references to objects. This will descend down a tree of nested objects, starting at the given object, following the given path. Args: obj: object Any type of object path_list: list ...
2.110146
2.434996
0.866591
val_list = _get_val_list(obj, path_list or [], reverse) return "<not found>" if obj is None else " / ".join(map(str, val_list))
def _get_val_str(obj, path_list=None, reverse=False)
Extract values from nested objects by attribute names and concatenate their string representations. Args: obj: object Any type of object path_list: list Attribute names reverse: bool Reverse the list of values before concatenation. Returns: str: Concatenat...
4.74202
7.122944
0.665739
if qq in ['sb', 'db', 'ds']: dd = 'dd' ij = tuple(dflav[q] for q in qq) elif qq == 'cu': dd = 'uu' ij = tuple(uflav[q] for q in qq) else: raise ValueError("not in Bern_I: ".format(qq)) ji = (ij[1], ij[0]) d = { '1' + 2 * qq : C["V{}LL".format(dd)]...
def _JMS_to_Bern_I(C, qq)
From JMS to BernI basis (= traditional SUSY basis in this case) for $\Delta F=2$ operators. `qq` should be 'sb', 'db', 'ds' or 'cu
3.025399
2.89517
1.044982
if qq in ['sb', 'db', 'ds']: dd = 'dd' ij = '{}{}'.format(dflav[qq[0]] + 1, dflav[qq[1]] + 1) elif qq == 'cu': dd = 'uu' ij = '{}{}'.format(uflav[qq[0]] + 1, uflav[qq[1]] + 1) else: raise ValueError("not in Bern_I: ".format(qq)) ji = ij[1] + ij[0] d = {"V...
def _Bern_to_JMS_I(C, qq)
From Bern to JMS basis for $\Delta F=2$ operators. `qq` should be 'sb', 'db', 'ds' or 'cu
3.023808
2.858637
1.05778
qqf = qq[::-1] # flavio uses "bs" instead of "sb" etc. if qq in ['sb', 'db', 'ds', 'cu']: return { 'CVLL_' + 2*qqf: C["1" + 2*qq], 'CSLL_' + 2*qqf: C["2" + 2*qq] - 1 / 2 * C["3" + 2*qq], 'CTLL_' + 2*qqf: -1 / 8 * C["3" + 2*qq], 'CVLR_' + 2*qqf: -1 / ...
def _BernI_to_Flavio_I(C, qq)
From BernI to FlavioI basis for $\Delta F=2$ operators. `qq` should be 'sb', 'db', 'ds' or 'uc
2.859712
2.693401
1.061748
qqb = qq[::-1] # flavio uses "bs" instead of "sb" etc. if qq in ['bs', 'bd', 'sd', 'uc']: return { '1' + 2*qqb: C["CVLL_" + 2*qq], '2' + 2*qqb: C["CSLL_" + 2*qq] - 4 * C["CTLL_" + 2*qq], '3' + 2*qqb: -8 * C["CTLL_" + 2*qq], '4' + 2*qqb: C["CSLR_" + 2...
def _FlavioI_to_Bern_I(C, qq)
From FlavioI to BernI basis for $\Delta F=2$ operators. `qq` should be 'sb', 'db', 'ds' or 'uc
2.868833
2.708625
1.059147
qqf = qq[::-1] # FormFlavour uses "bs" instead of "sb" etc. if qq in ['sb', 'db', 'ds']: return { 'CVLL_' + 2*qqf: C["1" + 2*qq], 'CSLL_' + 2*qqf: C["2" + 2*qq] + 1 / 2 * C["3" + 2*qq], 'CTLL_' + 2*qqf: -1 / 8 * C["3" + 2*qq], 'CVLR_' + 2*qqf: -1 / 2 ...
def _BernI_to_FormFlavor_I(C, qq)
From BernI to FormFlavorI basis for $\Delta F=2$ operators. `qq` should be 'sb', 'db', 'ds' or 'uc
1.865852
1.797696
1.037913
u = uflav[udlnu[0]] d = dflav[udlnu[1]] l = lflav[udlnu[4:udlnu.find('n')]] lp = lflav[udlnu[udlnu.find('_',5)+1:len(udlnu)]] ind = udlnu[0]+udlnu[1]+udlnu[4:udlnu.find('n')]+udlnu[udlnu.find('_',5)+1 :len(udlnu)] return { ...
def _JMS_to_Bern_II(C, udlnu)
From JMS to BernII basis for charged current process semileptonic operators. `udlnu` should be of the form 'udl_enu_tau', 'cbl_munu_e' etc.
3.463924
3.201432
1.081992
u = uflav[udlnu[0]] d = dflav[udlnu[1]] l = lflav[udlnu[4:udlnu.find('n')]] lp = lflav[udlnu[udlnu.find('_',5)+1:len(udlnu)]] ind = udlnu[0]+udlnu[1]+udlnu[4:udlnu.find('n')]+udlnu[udlnu.find('_',5)+1 :len(udlnu)] return { ...
def _Bern_to_JMS_II(C, udlnu)
From BernII to JMS basis for charged current process semileptonic operators. `udlnu` should be of the form 'udl_enu_tau', 'cbl_munu_e' etc.
2.649276
2.518691
1.051846
p = parameters u = uflav[udlnu[0]] d = dflav[udlnu[1]] l = lflav[udlnu[4:udlnu.find('n')]] lp = lflav[udlnu[udlnu.find('_',5)+1:len(udlnu)]] ind = udlnu[0]+udlnu[1]+udlnu[4:udlnu.find('n')]+udlnu[udlnu.find('_',5)+1 :len(ud...
def _BernII_to_Flavio_II(C, udlnu, parameters)
From BernII to FlavioII basis for charged current process semileptonic operators. `udlnu` should be of the form 'udl_enu_tau', 'cbl_munu_e' etc.
3.91341
3.824966
1.023123
if ddll[:2] == 'uc': s = uflav[ddll[0]] b = uflav[ddll[1]] q = 'u' else: s = dflav[ddll[0]] b = dflav[ddll[1]] q = 'd' l = lflav[ddll[4:ddll.find('n')]] lp = lflav[ddll[ddll.find('_',5)+1:len(ddll)]] ind = ddll.replace('l_','').replace('nu_','') ...
def JMS_to_Fierz_lep(C, ddll)
From JMS to semileptonic Fierz basis for Class V. `ddll` should be of the form 'sbl_enu_tau', 'dbl_munu_e' etc.
1.996344
1.958842
1.019145
s = dflav[ddll[0]] b = dflav[ddll[1]] l = lflav[ddll[4:ddll.find('n')]] lp = lflav[ddll[ddll.find('_',5)+1:len(ddll)]] ind = ddll.replace('l_','').replace('nu_','') return { 'F' + ind + 'nu' : C["VnudLL"][l, lp, s, b], 'F' + ind + 'nup' : C["VnudLR"][l, lp, s, b] }
def JMS_to_Fierz_nunu(C, ddll)
From JMS to semileptonic Fierz basis for Class V. `ddll` should be of the form 'sbl_enu_tau', 'dbl_munu_e' etc.
5.807525
4.999221
1.161686
if ddll[:2] == 'uc': s = str(uflav[ddll[0]] + 1) b = str(uflav[ddll[1]] + 1) q = 'u' else: s = str(dflav[ddll[0]] + 1) b = str(dflav[ddll[1]] + 1) q = 'd' l = str(lflav[ddll[4:ddll.find('n')]] + 1) lp = str(lflav[ddll[ddll.find('_',5)+1:len(ddll)]] + ...
def Fierz_to_JMS_lep(C, ddll)
From Fierz to semileptonic JMS basis for Class V. `ddll` should be of the form 'sbl_enu_tau', 'dbl_munu_e' etc.
2.319236
2.292866
1.011501
s = str(dflav[ddll[0]] + 1) b = str(dflav[ddll[1]] + 1) l = str(lflav[ddll[4:ddll.find('n')]] + 1) lp = str(lflav[ddll[ddll.find('_',5)+1:len(ddll)]] + 1) ind = ddll.replace('l_','').replace('nu_','') d = { "VnudLL" + '_' + l + lp + s + b : C['F' + ind + 'nu'], "VnudLR" + '_...
def Fierz_to_JMS_nunu(C, ddll)
From Fierz to semileptonic JMS basis for Class V. `ddll` should be of the form 'sbl_enu_tau', 'dbl_munu_e' etc.
5.323055
4.876279
1.091622
ind = ddll.replace('l_','').replace('nu_','') dic = { '1' + ind : 5 * C['F'+ ind + '10'] / 3 + C['F'+ ind + '9'], '3' + ind : -C['F' + ind + '10'] / 6, '5' + ind : C['F' + ind + 'S'] - 5 * C['F' + ind + 'P'] / 3, '7' + ind : 2 * C['F' + ind + 'P'] / 3 + C['F' + ind + 'T'] ...
def Fierz_to_Bern_lep(C, ddll)
From semileptonic Fierz basis to Bern semileptonic basis for Class V. C should be the corresponding leptonic Fierz basis and `ddll` should be of the form 'sbl_enu_tau', 'dbl_munu_e' etc.
2.340751
2.341097
0.999852
ind = ddll.replace('l_','').replace('nu_','') dic = { 'nu1' + ind : C['F' + ind + 'nu'], 'nu1p' + ind : C['F' + ind + 'nup'] } return dic
def Fierz_to_Bern_nunu(C, ddll)
From semileptonic Fierz basis to Bern semileptonic basis for Class V. C should be the corresponding leptonic Fierz basis and `ddll` should be of the form 'sbl_enu_tau', 'dbl_munu_e' etc.
6.575459
6.560218
1.002323
ind = ddll.replace('l_','').replace('nu_','') return {'F' + ind + '9': C['1' + ind] + 10 * C['3' + ind], 'F' + ind + '10': -6 * C['3' + ind], 'F' + ind + 'S': C['5' + ind] + 40 * C['9' + ind], 'F' + ind + 'P': 24 * C['9' + ind], 'F' + ind + 'T': C['7' + ind] ...
def Bern_to_Fierz_lep(C,ddll)
From semileptonic Bern basis to Fierz semileptonic basis for Class V. C should be the corresponding leptonic Fierz basis and `ddll` should be of the form 'sbl_enu_tau', 'dbl_munu_e' etc.
2.184433
2.148716
1.016623
ind = ddll.replace('l_','').replace('nu_','') return { 'F' + ind + 'nu': C['nu1' + ind], 'F' + ind + 'nup': C['nu1p' + ind], }
def Bern_to_Fierz_nunu(C,ddll)
From semileptonic Bern basis to Fierz semileptonic basis for Class V. C should be the corresponding leptonic Fierz basis and `ddll` should be of the form 'sbl_enu_tau', 'dbl_munu_e' etc.
6.470082
6.211817
1.041576
p = parameters V = ckmutil.ckm.ckm_tree(p["Vus"], p["Vub"], p["Vcb"], p["delta"]) if ddll[:2] == 'sb': xi = V[2, 2] * V[2, 1].conj() elif ddll[:2] == 'db': xi = V[2, 2] * V[2, 0].conj() elif ddll[:2] == 'ds': xi = V[2, 1] * V[2, 0].conj() elif ddll[:2] == 'uc': ...
def Fierz_to_Flavio_lep(C, ddll, parameters, norm_gf=True)
From semileptonic Fierz basis to Flavio semileptonic basis for Class V. C should be the corresponding leptonic Fierz basis and `ddll` should be of the form 'sbl_enu_tau', 'dbl_munu_e' etc.
2.623576
2.631011
0.997174
p = parameters V = ckmutil.ckm.ckm_tree(p["Vus"], p["Vub"], p["Vcb"], p["delta"]) if ddll[:2] == 'sb': xi = V[2, 2] * V[2, 1].conj() elif ddll[:2] == 'db': xi = V[2, 2] * V[2, 0].conj() elif ddll[:2] == 'ds': xi = V[2, 1] * V[2, 0].conj() else: raise ValueErr...
def Flavio_to_Fierz_nunu(C, ddll, parameters, norm_gf=True)
From Flavio semileptonic basis to semileptonic Fierz basis for Class V. C should be the corresponding leptonic Fierz basis and `ddll` should be of the form 'sbl_enu_tau', 'dbl_munu_e' etc.
4.464768
4.418193
1.010542
p = parameters V = ckmutil.ckm.ckm_tree(p["Vus"], p["Vub"], p["Vcb"], p["delta"]) Vtb = V[2,2] Vts = V[2,1] ind = ddll.replace('l_','').replace('nu_','') ind2 = ddll.replace('l_','').replace('nu_','')[2::] e = sqrt(4* pi * parameters['alpha_e']) dic = { 'b->s' + ind2 + '::c9...
def Fierz_to_EOS_lep(C, ddll, parameters)
From semileptonic Fierz basis to EOS semileptonic basis for Class V. C should be the corresponding leptonic Fierz basis and `ddll` should be of the form 'sbl_enu_tau', 'dbl_munu_e' etc.
2.486035
2.469277
1.006787
b = dflav[dd[0]] s = dflav[dd[1]] return { 'CVLL_' + dd + 'mm' : C["VedLL"][1, 1, s, b], 'CVRR_' + dd + 'mm' : C["VedRR"][1, 1, s, b], 'CVLR_' + dd + 'mm' : C["VdeLR"][s, b, 1, 1], 'CVRL_' + dd + 'mm' : C["VedLR"][1, 1, s, b], 'CSLL_' + dd + 'mm' : C["SedRR"][1,...
def JMS_to_FormFlavor_lep(C, dd)
From JMS to semileptonic Fierz basis for Classes V. C should be the JMS basis and `ddll` should be of the form 'sbl_eni_tau', 'dbl_munu_e' etc.
2.163627
2.10933
1.025741
if qq[0] in dflav: s = dflav[qq[0]] b = dflav[qq[1]] return { 'F7gamma' + qq : C['dgamma'][s, b], 'F8g' + qq : C['dG'][s, b], 'F7pgamma' + qq : C['dgamma'][b, s].conj(), 'F8pg' + qq : C['dG'][b, s].conj() ...
def JMS_to_Fierz_chrom(C, qq)
From JMS to chromomagnetic Fierz basis for Class V. qq should be of the form 'sb', 'ds' etc.
2.697423
2.622462
1.028584
if qq[0] in dflav: s = dflav[qq[0]] + 1 b = dflav[qq[1]] + 1 return {'dgamma_{}{}'.format(s, b): C['F7gamma' + qq], 'dG_{}{}'.format(s, b): C['F8g' + qq], 'dgamma_{}{}'.format(b, s): C['F7pgamma' + qq].conjugate(), 'dG_{}{}'.format(b, s): ...
def Fierz_to_JMS_chrom(C, qq)
From chromomagnetic Fierz to JMS basis for Class V. qq should be of the form 'sb', 'ds' etc.
2.23263
2.188805
1.020022
e = sqrt(4 * pi * parameters['alpha_e']) gs = sqrt(4 * pi * parameters['alpha_s']) if dd == 'sb' or dd == 'db': mq = parameters['m_b'] elif dd == 'ds': mq = parameters['m_s'] else: KeyError("Not sure what to do with quark mass for flavour {}".format(dd)) return { ...
def Fierz_to_Bern_chrom(C, dd, parameters)
From Fierz to chromomagnetic Bern basis for Class V. dd should be of the form 'sb', 'ds' etc.
5.118157
4.709043
1.086879
p = parameters V = ckmutil.ckm.ckm_tree(p["Vus"], p["Vub"], p["Vcb"], p["delta"]) if qq == 'sb': xi = V[2, 2] * V[2, 1].conj() elif qq == 'db': xi = V[2, 2] * V[2, 0].conj() elif qq == 'ds': xi = V[2, 1] * V[2, 0].conj() elif qq == 'uc': xi = V[1, 2].conj() *...
def Flavio_to_Fierz_chrom(C, qq, parameters)
From Flavio to chromomagnetic Fierz basis for Class V. qq should be of the form 'sb', 'db' etc.
3.452417
3.347676
1.031288
p = parameters V = ckmutil.ckm.ckm_tree(p["Vus"], p["Vub"], p["Vcb"], p["delta"]) Vtb = V[2,2] Vts = V[2,1] e = sqrt(4 * pi * parameters['alpha_e']) gs = sqrt(4 * pi * parameters['alpha_s']) mb = parameters['m_b'] dic = {"b->s::c7": 16 * pi**2 / mb / e * C["F7gamma" + dd], ...
def Fierz_to_EOS_chrom(C, dd, parameters)
From Fierz to chromomagnetic EOS basis for Class V. dd should be of the form 'sb', 'ds' etc.
5.420891
5.204883
1.041501
e = sqrt(4 * pi * parameters['alpha_e']) gs = sqrt(4 * pi * parameters['alpha_s']) if qq[0] in dflav.keys(): s = dflav[qq[0]] b = dflav[qq[1]] return { 'CAR_' + qq : C['dgamma'][s, b] / e, 'CGR_' + qq : C['dG'][s, b] / gs, 'CAL_' + qq : C['dg...
def JMS_to_FormFlavor_chrom(C, qq, parameters)
From JMS to chromomagnetic FormFlavor basis for Class V. qq should be of the form 'sb', 'ds', 'uu', mt (mu tau), em (e mu) etc.
2.525198
2.473927
1.020725
d = {} dtrans = json.loads(pkgutil.get_data('wilson', 'data/flavio_jms_vii.json').decode('utf8')) for cj, cf in dtrans.items(): d[cf] = C.get(cj, 0) gs = sqrt(4 * pi * parameters['alpha_s']) e = sqrt(4 * pi * parameters['alpha_e']) preC7 = 16 * pi**2 / e preC8 = 16 * pi**2 / gs ...
def _JMS_to_Flavio_VII(C, parameters)
From JMS to flavio basis for class VII, i.e. flavour blind operators.
1.970685
1.964432
1.003183
p = default_parameters.copy() if input_parameters is not None: # if parameters are passed in, overwrite the default values p.update(input_parameters) parameters = {} # running quark masses and alpha_s parameters['m_b'] = m_b(p['m_b'], scale, f, p['alpha_s']) parameters['m_c'...
def get_parameters(scale, f=5, input_parameters=None)
Get parameters (masses, coupling constants, ...) at the scale `scale` in QCD with `f` dynamical quark flavours. Optionally takes a dictionary of inputs (otherwise, defaults are used).
2.728661
2.680432
1.017993
if _is_head(sciobj_model): old_pid = sciobj_model.obsoletes.did _cut_head_from_chain(sciobj_model) elif _is_tail(sciobj_model): old_pid = sciobj_model.obsoleted_by.did _cut_tail_from_chain(sciobj_model) else: old_pid = sciobj_model.obsoleted_by.did _cut_e...
def cut_from_chain(sciobj_model)
Remove an object from a revision chain. The object can be at any location in the chain, including the head or tail. Preconditions: - The object with the pid is verified to exist and to be a member of an revision chain. E.g., with: d1_gmn.app.views.asserts.is_existing_object(pid) d1_gmn.app.vi...
2.808173
2.563272
1.095543
return d1_gmn.app.models.Chain.objects.get(sid__did=sid).head_pid.did
def resolve_sid(sid)
Get the PID to which the ``sid`` currently maps. Preconditions: - ``sid`` is verified to exist. E.g., with d1_gmn.app.views.asserts.is_sid().
21.2612
14.188181
1.498515
return d1_gmn.app.models.ScienceObject.objects.filter(obsoletes__did=pid).exists()
def is_obsoletes_pid(pid)
Return True if ``pid`` is referenced in the obsoletes field of any object. This will return True even if the PID is in the obsoletes field of an object that does not exist on the local MN, such as replica that is in an incomplete chain.
6.52046
8.722038
0.747584
return d1_gmn.app.models.ScienceObject.objects.filter( obsoleted_by__did=pid ).exists()
def is_obsoleted_by_pid(pid)
Return True if ``pid`` is referenced in the obsoletedBy field of any object. This will return True even if the PID is in the obsoletes field of an object that does not exist on the local MN, such as replica that is in an incomplete chain.
5.626065
7.387196
0.761597
_set_chain_sid( chain_model_a, d1_gmn.app.did.get_did_by_foreign_key(chain_model_b.sid) ) for member_model in _get_all_chain_member_queryset_by_chain(chain_model_b): member_model.chain = chain_model_a member_model.save() chain_model_b.delete()
def _merge_chains(chain_model_a, chain_model_b)
Merge two chains. For use when it becomes known that two chains that were created separately actually are separate sections of the same chain E.g.: - A obsoleted by X is created. A has no SID. X does not exist yet. A chain is created for A. - B obsoleting Y is created. B has SID. Y does not...
4.442031
4.639126
0.957515
if not sid: return if chain_model.sid and chain_model.sid.did != sid: raise d1_common.types.exceptions.ServiceFailure( 0, 'Attempted to modify existing SID. ' 'existing_sid="{}", new_sid="{}"'.format(chain_model.sid.did, sid), ) chain_model.si...
def _set_chain_sid(chain_model, sid)
Set or update SID for chain. If the chain already has a SID, ``sid`` must either be None or match the existing SID.
3.064264
3.071386
0.997681
try: return d1_gmn.app.models.ChainMember.objects.get(pid__did=pid).chain except d1_gmn.app.models.ChainMember.DoesNotExist: pass
def _get_chain_by_pid(pid)
Find chain by pid. Return None if not found.
4.517292
4.872313
0.927135
try: return d1_gmn.app.models.Chain.objects.get(sid__did=sid) except d1_gmn.app.models.Chain.DoesNotExist: pass
def _get_chain_by_sid(sid)
Return None if not found.
4.196588
3.920924
1.070306
last_pid = _find_head_or_latest_connected(pid) chain_model = _get_chain_by_pid(last_pid) if not chain_model: return chain_model.head_pid = d1_gmn.app.did.get_or_create_did(last_pid) chain_model.save()
def _update_sid_to_last_existing_pid_map(pid)
Set chain head PID to the last existing object in the chain to which ``pid`` belongs. If SID has been set for chain, it resolves to chain head PID. Intended to be called in MNStorage.delete() and other chain manipulation. Preconditions: - ``pid`` must exist and be verified to be a PID. d1_gmn.ap...
5.511404
4.42978
1.244171
chain_model = d1_gmn.app.models.Chain( # sid=d1_gmn.app.models.did(sid) if sid else None, head_pid=d1_gmn.app.did.get_or_create_did(pid) ) chain_model.save() _add_pid_to_chain(chain_model, pid) _set_chain_sid(chain_model, sid) return chain_model
def _create_chain(pid, sid)
Create the initial chain structure for a new standalone object. Intended to be called in MNStorage.create(). Preconditions: - ``sid`` must be verified to be available to be assigned to a new standalone object. E.g., with is_valid_sid_for_new_standalone().
3.678005
4.582594
0.802603
Entity = apps.get_model('flow', 'Entity') for entity in Entity.objects.all(): if entity.descriptor_schema is not None: entity.type = entity.descriptor_schema.slug entity.save()
def populate_entity_type(apps, schema_editor)
Populate entity type from attached descriptor schema.
3.06691
2.369323
1.294425
pyxb_binding = pyxb_binding or d1_common.types.dataoneTypes try: return pyxb_binding.CreateFromDocument(doc_xml) except pyxb.ValidationError as e: raise ValueError( 'Unable to deserialize XML to PyXB. error="{}" xml="{}"'.format( e.details(), doc_xml ...
def deserialize(doc_xml, pyxb_binding=None)
Deserialize DataONE XML types to PyXB. Args: doc_xml: UTF-8 encoded ``bytes`` pyxb_binding: PyXB binding object. If not specified, the correct one should be selected automatically. Returns: PyXB object See Also: ``deserialize_d1_exception()`` for deserializing DataONE Excep...
2.259963
2.529001
0.893619
assert d1_common.type_conversions.is_pyxb(obj_pyxb) assert encoding in (None, 'utf-8', 'UTF-8') try: obj_dom = obj_pyxb.toDOM() except pyxb.ValidationError as e: raise ValueError( 'Unable to serialize PyXB to XML. error="{}"'.format(e.details()) ) except pyxb...
def serialize_gen( obj_pyxb, encoding='utf-8', pretty=False, strip_prolog=False, xslt_url=None )
Serialize PyXB object to XML. Args: obj_pyxb: PyXB object PyXB object to serialize. encoding: str Encoding to use for XML doc bytes pretty: bool True: Use pretty print formatting for human readability. strip_prolog: True: remove any XML prolog (e.g., ``<?x...
2.147236
2.204583
0.973987
return serialize_gen(obj_pyxb, 'utf-8', pretty, strip_prolog, xslt_url)
def serialize_for_transport(obj_pyxb, pretty=False, strip_prolog=False, xslt_url=None)
Serialize PyXB object to XML ``bytes`` with UTF-8 encoding for transport over the network, filesystem storage and other machine usage. Args: obj_pyxb: PyXB object PyXB object to serialize. pretty: bool True: Use pretty print formatting for human readability. strip_prolog: ...
3.424523
6.73197
0.508695
return serialize_gen(obj_pyxb, None, pretty, strip_prolog, xslt_url)
def serialize_to_xml_str(obj_pyxb, pretty=True, strip_prolog=False, xslt_url=None)
Serialize PyXB object to pretty printed XML ``str`` for display. Args: obj_pyxb: PyXB object PyXB object to serialize. pretty: bool False: Disable pretty print formatting. XML will not have line breaks. strip_prolog: True: remove any XML prolog (e.g., ``<?xml version="1....
4.10059
9.451653
0.433849
assert isinstance(doc_xml, str) dom_obj = xml.dom.minidom.parseString(doc_xml) pretty_xml = dom_obj.toprettyxml(indent=' ') # Remove empty lines in the result caused by a bug in toprettyxml() return re.sub(r'^\s*$\n', r'', pretty_xml, flags=re.MULTILINE)
def reformat_to_pretty_xml(doc_xml)
Pretty print XML doc. Args: doc_xml : str Well formed XML doc Returns: str: Pretty printed XML doc
2.987623
3.270264
0.913573
assert isinstance(a_xml, str) assert isinstance(b_xml, str) a_tree = str_to_etree(a_xml, encoding) b_tree = str_to_etree(b_xml, encoding) return are_equal_or_superset(a_tree, b_tree) and are_equal_or_superset( b_tree, a_tree )
def are_equivalent(a_xml, b_xml, encoding=None)
Return True if two XML docs are semantically equivalent, else False. - TODO: Include test for tails. Skipped for now because tails are not used in any D1 types.
2.203315
2.414151
0.912667
try: _compare_attr(superset_tree, base_tree) _compare_text(superset_tree, base_tree) except CompareError as e: logger.debug(str(e)) return False return True
def are_equal_or_superset(superset_tree, base_tree)
Return True if ``superset_tree`` is equal to or a superset of ``base_tree`` - Checks that all elements and attributes in ``superset_tree`` are present and contain the same values as in ``base_tree``. For elements, also checks that the order is the same. - Can be used for checking if one XML documen...
3.388194
3.30942
1.023803
a_dom = xml.dom.minidom.parseString(a_xml) b_dom = xml.dom.minidom.parseString(b_xml) return are_equal_elements(a_dom.documentElement, b_dom.documentElement)
def are_equal_xml(a_xml, b_xml)
Normalize and compare XML documents for equality. The document may or may not be a DataONE type. Args: a_xml: str b_xml: str XML documents to compare for equality. Returns: bool: ``True`` if the XML documents are semantically equivalent.
1.756375
2.209867
0.794787
if a_el.tagName != b_el.tagName: return False if sorted(a_el.attributes.items()) != sorted(b_el.attributes.items()): return False if len(a_el.childNodes) != len(b_el.childNodes): return False for a_child_el, b_child_el in zip(a_el.childNodes, b_el.childNodes): if a_c...
def are_equal_elements(a_el, b_el)
Normalize and compare ElementTrees for equality. Args: a_el: ElementTree b_el: ElementTree ElementTrees to compare for equality. Returns: bool: ``True`` if the ElementTrees are semantically equivalent.
1.474195
1.566077
0.94133