text stringlengths 18 773k |
|---|
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."""
if ddll[:2] == 'uc':
s = uflav[ddll[0]]
b = uflav[ddll[1]]
q = 'u'
else:
s = dflav[ddll[0]]
b = dflav[ddll[1]]
... |
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."""
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_'... |
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."""
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)
... |
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."""
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... |
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."""
ind = ddll.replace('l_','').replace('nu_','')
dic = {
'1' + ind : 5... |
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."""
ind = ddll.replace('l_','').replace('nu_','')
dic = {
'nu1' + 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."""
ind = ddll.replace('l_','').replace('nu_','')
return {'F' + ind + '9': C['1'... |
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."""
ind = ddll.replace('l_','').replace('nu_','')
return {
'F' + in... |
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."""
p = parameters
V = ckmutil.ckm.ckm_tree(p["Vu... |
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."""
p = parameters
V = ckmutil.ckm.ckm_tree(p["... |
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."""
p = parameters
V = ckmutil.ckm.ckm_tree(p["Vus"], p["Vub"], p["Vc... |
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."""
b = dflav[dd[0]]
s = dflav[dd[1]]
return {
'CVLL_' + dd + 'mm' : C["VedLL"][1, 1, s, b],
'CVRR_'... |
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."""
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, ... |
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."""
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)... |
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."""
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 =... |
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."""
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 == 'd... |
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."""
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'])
... |
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."""
e = sqrt(4 * pi * parameters['alpha_e'])
gs = sqrt(4 * pi * parameters['alpha_s'])
if qq[0] in dflav.keys():
s... |
def _JMS_to_Flavio_VII(C, parameters):
"""From JMS to flavio basis for class VII, i.e. flavour blind operators."""
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 * parameter... |
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)."""
p = default_parameters.copy()
if input_parameters is no... |
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.... |
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().
"""
return d1_gmn.app.models.Chain.objects.get(sid__did=sid).head_pid.did |
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.
"""
return d1_gmn.app.models.Sc... |
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.
"""
return d1_gmn.app.mode... |
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... |
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.
"""
if not sid:
return
if chain_model.sid and chain_model.sid.did != sid:
raise d1_common.types.exceptions.ServiceFailure... |
def _get_chain_by_pid(pid):
"""Find chain by pid.
Return None if not found.
"""
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_sid(sid):
"""Return None if not found."""
try:
return d1_gmn.app.models.Chain.objects.get(sid__did=sid)
except d1_gmn.app.models.Chain.DoesNotExist:
pass |
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`` m... |
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().
"""
... |
def populate_entity_type(apps, schema_editor):
"""Populate entity type from attached descriptor schema."""
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
entit... |
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:
``deserial... |
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 ... |
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... |
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 ... |
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
"""
assert isinstance(doc_xml, str)
dom_obj = xml.dom.minidom.parseString(doc_xml)
pretty_xml = dom_obj.toprettyxml(indent=' ')
... |
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.
"""
assert isinstance(a_xml, str)
assert isinstance(b_xml, str)
a_tree = st... |
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... |
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.
... |
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.
"""
if a_el.tagName != b_el.ta... |
def sort_elements_by_child_values(obj_pyxb, child_name_list):
"""In-place sort simple or complex elements in a PyXB object by values they contain
in child elements.
Args:
obj_pyxb: PyXB object
child_name_list: list of str
List of element names that are direct children of the PyXB objec... |
def format_diff_pyxb(a_pyxb, b_pyxb):
"""Create a diff between two PyXB objects.
Args:
a_pyxb: PyXB object
b_pyxb: PyXB object
Returns:
str : `Differ`-style delta
"""
return '\n'.join(
difflib.ndiff(
serialize_to_xml_str(a_pyxb).splitlines(),
seri... |
def format_diff_xml(a_xml, b_xml):
"""Create a diff between two XML documents.
Args:
a_xml: str
b_xml: str
Returns:
str : `Differ`-style delta
"""
return '\n'.join(
difflib.ndiff(
reformat_to_pretty_xml(a_xml).splitlines(),
reformat_to_pretty_xml(... |
def get_opt_attr(obj_pyxb, attr_str, default_val=None):
"""Get an optional attribute value from a PyXB element.
The attributes for elements that are optional according to the schema and
not set in the PyXB object are present and set to None.
PyXB validation will fail if required elements are missing.
... |
def get_opt_val(obj_pyxb, attr_str, default_val=None):
"""Get an optional Simple Content value from a PyXB element.
The attributes for elements that are optional according to the schema and
not set in the PyXB object are present and set to None.
PyXB validation will fail if required elements are missi... |
def resolwe_exception_handler(exc, context):
"""Handle exceptions raised in API and make them nicer.
To enable this, you have to add it to the settings:
.. code:: python
REST_FRAMEWORK = {
'EXCEPTION_HANDLER': 'resolwe.flow.utils.exceptions.resolwe_exception_handler',
... |
def validate_and_decode(jwt_bu64, cert_obj):
"""Example for validating the signature of a JWT using only the cryptography
library.
Note that this does NOT validate the claims in the claim set.
"""
public_key = cert_obj.public_key()
message = '.'.join(d1_common.cert.jwt.get_bu64_tup(jwt_bu64)[:... |
def find_valid_combinations(cert_file_name_list, jwt_file_name_list):
"""Given a list of cert and JWT file names, print a list showing each combination
along with indicators for combinations where the JWT signature was successfully
validated with the cert."""
for cert_file_name in cert_file_name_list:
... |
def parseUrl(url):
"""Return a dict containing scheme, netloc, url, params, query, fragment keys.
query is a dict where the values are always lists. If the query key appears only
once in the URL, the list will have a single value.
"""
scheme, netloc, url, params, query, fragment = urllib.parse.url... |
def encodePathElement(element):
"""Encode a URL path element according to RFC3986."""
return urllib.parse.quote(
(
element.encode('utf-8')
if isinstance(element, str)
else str(element)
if isinstance(element, int)
else element
),
... |
def encodeQueryElement(element):
"""Encode a URL query element according to RFC3986."""
return urllib.parse.quote(
(
element.encode('utf-8')
if isinstance(element, str)
else str(element)
if isinstance(element, int)
else element
),
... |
def urlencode(query, doseq=0):
"""Modified version of the standard urllib.urlencode that is conforms to RFC3986.
The urllib version encodes spaces as '+' which can lead to inconsistency. This
version will always encode spaces as '%20'.
Encode a sequence of two-element tuples or dictionary into a URL qu... |
def makeCNBaseURL(url):
"""Attempt to create a valid CN BaseURL when one or more sections of the URL are
missing."""
o = urllib.parse.urlparse(url, scheme=d1_common.const.DEFAULT_CN_PROTOCOL)
if o.netloc and o.path:
netloc = o.netloc
path = o.path
elif o.netloc:
netloc = o.ne... |
def makeMNBaseURL(url):
"""Attempt to create a valid MN BaseURL when one or more sections of the URL are
missing."""
o = urllib.parse.urlparse(url, scheme=d1_common.const.DEFAULT_MN_PROTOCOL)
if o.netloc and o.path:
netloc = o.netloc
path = o.path
elif o.netloc:
netloc = o.ne... |
def find_url_mismatches(a_url, b_url):
"""Given two URLs, return a list of any mismatches.
If the list is empty, the URLs are equivalent. Implemented by parsing and comparing
the elements. See RFC 1738 for details.
"""
diff_list = []
a_parts = urllib.parse.urlparse(a_url)
b_parts = urllib.... |
def main():
"""Run the program."""
args = parse_arguments()
ext = os.path.splitext(args.input_file)[-1].lower()
with gzip.open(args.output_file, mode='wt') as outfile:
csvwriter = csv.writer(outfile, delimiter=str('\t'), lineterminator='\n')
try:
if ext in ('.tab', '.txt', ... |
def search(self, line):
"""CN search."""
if self._session.get(d1_cli.impl.session.QUERY_ENGINE_NAME) == "solr":
return self._search_solr(line)
raise d1_cli.impl.exceptions.InvalidArguments(
"Unsupported query engine: {}".format(
self._session.get(d1_cli.im... |
def resolve(self, pid):
"""Get Object Locations for Object."""
client = d1_cli.impl.client.CLICNClient(
**self._cn_client_connect_params_from_session()
)
object_location_list_pyxb = client.resolve(pid)
for location in object_location_list_pyxb.objectLocation:
... |
def science_object_get(self, pid, path):
"""First try the MN set in the session.
Then try to resolve via the CN set in the session.
"""
mn_client = d1_cli.impl.client.CLIMNClient(
**self._mn_client_connect_params_from_session()
)
try:
response = ... |
def science_object_create(self, pid, path, format_id=None):
"""Create a new Science Object on a Member Node."""
self._queue_science_object_create(pid, path, format_id) |
def science_object_update(self, pid_old, path, pid_new, format_id=None):
"""Obsolete a Science Object on a Member Node with a different one."""
self._queue_science_object_update(pid_old, path, pid_new, format_id) |
def _output(self, file_like_object, path=None):
"""Display or save file like object."""
if not path:
self._output_to_display(file_like_object)
else:
self._output_to_file(file_like_object, path) |
def _search_solr(self, line):
"""Perform a SOLR search."""
try:
query_str = self._create_solr_query(line)
client = d1_cli.impl.client.CLICNClient(
**self._cn_client_connect_params_from_session()
)
object_list_pyxb = client.search(
... |
def _create_solr_query(self, line):
"""Actual search - easier to test. """
p0 = ""
if line:
p0 = line.strip()
p1 = self._query_string_to_solr_filter(line)
p2 = self._object_format_to_solr_filter(line)
p3 = self._time_span_to_solr_filter()
result = p0 +... |
def apply_filter_list(func, obj):
"""Apply `func` to list or tuple `obj` element-wise and directly otherwise."""
if isinstance(obj, (list, tuple)):
return [func(item) for item in obj]
return func(obj) |
def _get_data_attr(data, attr):
"""Get data object field."""
if isinstance(data, dict):
# `Data` object's id is hydrated as `__id` in expression engine
data = data['__id']
data_obj = Data.objects.get(id=data)
return getattr(data_obj, attr) |
def input_(data, field_path):
"""Return a hydrated value of the ``input`` field."""
data_obj = Data.objects.get(id=data['__id'])
inputs = copy.deepcopy(data_obj.input)
# XXX: Optimize by hydrating only the required field (major refactoring).
hydrate_input_references(inputs, data_obj.process.input_s... |
def _get_hydrated_path(field):
"""Return HydratedPath object for file-type field."""
# Get only file path if whole file object is given.
if isinstance(field, str) and hasattr(field, 'file_name'):
# field is already actually a HydratedPath object
return field
if isinstance(field, dict) a... |
def get_url(field):
"""Return file's url based on base url set in settings."""
hydrated_path = _get_hydrated_path(field)
base_url = getattr(settings, 'RESOLWE_HOST_URL', 'localhost')
return "{}/data/{}/{}".format(base_url, hydrated_path.data_id, hydrated_path.file_name) |
def descriptor(obj, path=''):
"""Return descriptor of given object.
If ``path`` is specified, only the content on that path is
returned.
"""
if isinstance(obj, dict):
# Current object is hydrated, so we need to get descriptor from
# dict representation.
desc = obj['__descrip... |
def _close_open_date_ranges(self, record):
"""If a date range is missing the start or end date, close it by copying the
date from the existing value."""
date_ranges = (('beginDate', 'endDate'),)
for begin, end in date_ranges:
if begin in record and end in record:
... |
def escapeQueryTerm(self, term):
"""
+ - && || ! ( ) { } [ ] ^ " ~ * ? : \
"""
reserved = [
'+',
'-',
'&',
'|',
'!',
'(',
')',
'{',
'}',
'[',
']',
'^',
... |
def prepareQueryTerm(self, field, term):
"""Prepare a query term for inclusion in a query.
This escapes the term and if necessary, wraps the term in quotes.
"""
if term == "*":
return term
addstar = False
if term[len(term) - 1] == '*':
addstar = ... |
def coerceType(self, ftype, value):
"""Returns unicode(value) after trying to coerce it into the SOLR field type.
@param ftype(string) The SOLR field type for the value
@param value(any) The value that is to be represented as Unicode text.
"""
if value is None:
retu... |
def getSolrType(self, field):
"""Returns the SOLR type of the specified field name.
Assumes the convention of dynamic fields using an underscore + type character
code for the field name.
"""
ftype = 'string'
try:
ftype = self.fieldtypes[field]
re... |
def addDocs(self, docs):
"""docs is a list of fields that are a dictionary of name:value for a record."""
lst = ['<add>']
for fields in docs:
self.__add(lst, fields)
lst.append('</add>')
xstr = ''.join(lst)
return self.doUpdateXML(xstr) |
def count(self, q='*:*', fq=None):
"""Return the number of entries that match query."""
params = {'q': q, 'rows': '0'}
if fq is not None:
params['fq'] = fq
res = self.search(params)
hits = res['response']['numFound']
return hits |
def getIds(self, query='*:*', fq=None, start=0, rows=1000):
"""Returns a dictionary of: matches: number of matches failed: if true, then an
exception was thrown start: starting index ids: [id, id, ...]
See also the SOLRSearchResponseIterator class
"""
params = {'q': query, 'sta... |
def get(self, id):
"""Retrieves the specified document."""
params = {'q': 'id:%s' % str(id), 'wt': 'python'}
request = urllib.parse.urlencode(params, doseq=True)
data = None
try:
rsp = self.doPost(self.solrBase + '', request, self.formheaders)
data = eval(... |
def getFields(self, numTerms=1):
"""Retrieve a list of fields. The response looks something like:
{
'responseHeader':{
'status':0,
'QTime':44},
'index':{
'numDocs':2000,
'maxDoc':2000,
'numTerms':23791,
'version':1227298371173,
'optimized':True,
'current':True,
'hasDeletio... |
def fieldValues(self, name, q="*:*", fq=None, maxvalues=-1):
"""Retrieve the unique values for a field, along with their usage counts.
http://localhost:8080/solr/select/?q=*:*&rows=0&facet=true&inde
nt=on&wt=python&facet.field=genus_s&facet.limit=10&facet.zeros=false&fa
cet.sort=false.
... |
def fieldMinMax(self, name, q='*:*', fq=None):
"""Returns the minimum and maximum values of the specified field. This requires
two search calls to the service, each requesting a single value of a single
field.
@param name(string) Name of the field
@param q(string) Query identify... |
def getftype(self, name):
"""Returns the python type for the specified field name. The field list is
cached so multiple calls do not invoke a getFields request each time.
@param name(string) The name of the SOLR field
@returns Python type of the field.
"""
fields = sel... |
def fieldAlphaHistogram(
self, name, q='*:*', fq=None, nbins=10, includequeries=True
):
"""Generates a histogram of values from a string field. Output is:
[[low, high, count, query], ... ] Bin edges is determined by equal division
of the fields
"""
oldpersist = s... |
def fieldHistogram(
self, name, q="*:*", fq=None, nbins=10, minmax=None, includequeries=True
):
"""Generates a histogram of values. Expects the field to be integer or floating
point.
@param name(string) Name of the field to compute
@param q(string) The query identifying the ... |
def fieldHistogram2d(self, colname, rowname, q="*:*", fq=None, ncols=10, nrows=10):
"""Generates a 2d histogram of values. Expects the field to be integer or
floating point.
@param name1(string) Name of field1 columns to compute
@param name2(string) Name of field2 rows to compute
... |
def _nextPage(self, offset):
"""Retrieves the next set of results from the service."""
self.logger.debug("Iterator crecord=%s" % str(self.crecord))
params = {
'q': self.q,
'start': str(offset),
'rows': str(self.pagesize),
'fl': self.fields,
... |
def _nextPage(self, offset):
"""Retrieves the next set of results from the service."""
self.logger.debug("Iterator crecord=%s" % str(self.crecord))
params = {
'q': self.q,
'rows': '0',
'facet': 'true',
'facet.field': self.field,
'facet... |
def get_monitor_ping(request):
"""MNCore.ping() → Boolean."""
response = d1_gmn.app.views.util.http_response_with_boolean_true_type()
d1_gmn.app.views.headers.add_http_date_header(response)
return response |
def get_log(request):
"""MNCore.getLogRecords(session[, fromDate][, toDate][, idFilter][, event]
[, start=0][, count=1000]) → Log
Sorted by timestamp, id.
"""
query = d1_gmn.app.models.EventLog.objects.all().order_by('timestamp', 'id')
if not d1_gmn.app.auth.is_trusted_subject(request):
... |
def get_node(request):
"""MNCore.getCapabilities() → Node."""
api_major_int = 2 if d1_gmn.app.views.util.is_v2_api(request) else 1
node_pretty_xml = d1_gmn.app.node.get_pretty_xml(api_major_int)
return django.http.HttpResponse(node_pretty_xml, d1_common.const.CONTENT_TYPE_XML) |
def get_object(request, pid):
"""MNRead.get(session, did) → OctetStream."""
sciobj = d1_gmn.app.models.ScienceObject.objects.get(pid__did=pid)
content_type_str = d1_gmn.app.object_format_cache.get_content_type(
sciobj.format.format
)
# Return local or proxied SciObj bytes
response = djan... |
def get_meta(request, pid):
"""MNRead.getSystemMetadata(session, pid) → SystemMetadata."""
d1_gmn.app.event_log.log_read_event(pid, request)
return django.http.HttpResponse(
d1_gmn.app.views.util.generate_sysmeta_xml_matching_api_version(request, pid),
d1_common.const.CONTENT_TYPE_XML,
) |
def head_object(request, pid):
"""MNRead.describe(session, did) → DescribeResponse."""
sciobj = d1_gmn.app.models.ScienceObject.objects.get(pid__did=pid)
response = django.http.HttpResponse()
d1_gmn.app.views.headers.add_sciobj_properties_headers_to_response(response, sciobj)
d1_gmn.app.event_log.lo... |
def get_checksum(request, pid):
"""MNRead.getChecksum(session, did[, checksumAlgorithm]) → Checksum."""
# MNRead.getChecksum() requires that a new checksum be calculated. Cannot
# simply return the checksum from the sysmeta.
#
# If the checksumAlgorithm argument was not provided, it defaults to
... |
def post_error(request):
"""MNRead.synchronizationFailed(session, message)"""
d1_gmn.app.views.assert_db.post_has_mime_parts(request, (('file', 'message'),))
try:
synchronization_failed = d1_gmn.app.views.util.deserialize(
request.FILES['message']
)
except d1_common.types.exc... |
def get_replica(request, pid):
"""MNReplication.getReplica(session, did) → OctetStream."""
_assert_node_is_authorized(request, pid)
sciobj = d1_gmn.app.models.ScienceObject.objects.get(pid__did=pid)
content_type_str = d1_gmn.app.object_format_cache.get_content_type(
sciobj.format.format
)
... |
def put_meta(request):
"""MNStorage.updateSystemMetadata(session, pid, sysmeta) → boolean.
TODO: Currently, this call allows making breaking changes to SysMeta. We need to
clarify what can be modified and what the behavior should be when working with SIDs
and chains.
"""
if django.conf.setting... |
def get_is_authorized(request, pid):
"""MNAuthorization.isAuthorized(did, action) -> Boolean."""
if 'action' not in request.GET:
raise d1_common.types.exceptions.InvalidRequest(
0, 'Missing required parameter. required="action"'
)
# Convert action string to action level. Raises I... |
def post_refresh_system_metadata(request):
"""MNStorage.systemMetadataChanged(session, did, serialVersion,
dateSysMetaLastModified) → boolean."""
d1_gmn.app.views.assert_db.post_has_mime_parts(
request,
(
('field', 'pid'),
('field', 'serialVersion'),
('fie... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.