code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
for k, v in D1_ENV_DICT:
if v['base_url'].startswith(cn_base_url):
return D1_ENV_DICT[k] | def get_d1_env_by_base_url(cn_base_url) | Given the BaseURL for a CN, return the DataONE environment dict for the CN's
environemnt. | 3.456685 | 3.394222 | 1.018403 |
p = default_parameters.copy()
if parameters is not None:
# if parameters are passed in, overwrite the default values
p.update(parameters)
C = wilson.util.smeftutil.wcxf2arrays_symmetrized(d_SMEFT)
C['vT'] = 246.22
C_WET = match_all_array(C, p)
C_WET = wilson.translate.wet.ro... | def match_all(d_SMEFT, parameters=None) | Match the SMEFT Warsaw basis onto the WET JMS basis. | 5.196017 | 4.518575 | 1.149924 |
if django.conf.settings.DEBUG_GMN:
if 'pretty' in request.GET:
response['Content-Type'] = d1_common.const.CONTENT_TYPE_TEXT
if (
'HTTP_VENDOR_PROFILE_SQL' in request.META
or django.conf.settings.DEBUG_PROFILE_SQL
):
... | def _debug_mode_responses(self, request, response) | Extra functionality available in debug mode.
- If pretty printed output was requested, force the content type to text. This
causes the browser to not try to format the output in any way.
- If SQL profiling is turned on, return a page with SQL query timing
information instead of the ... | 3.863192 | 3.419312 | 1.129816 |
self._log.debug(
'Solr query: {}'.format(
', '.join(['{}={}'.format(k, v) for (k, v) in list(locals().items())])
)
)
return (self.POST if do_post else self.GET)(
['query', queryEngine, query_str], headers=vendorSpecific, **kwargs
... | def queryResponse(
self, queryEngine, query_str, vendorSpecific=None, do_post=False, **kwargs
) | CNRead.query(session, queryEngine, query) → OctetStream
https://releases.dataone.org/online/api-
documentation-v2.0.1/apis/CN_APIs.html#CNRead.query MNQuery.query(session,
queryEngine, query) → OctetStream http://jenkins.
-1.dataone.org/jenkins/job/API%20Documentation%20-%20trunk/ws/api... | 4.104337 | 4.50571 | 0.910919 |
response = self.queryResponse(
queryEngine, query_str, vendorSpecific, do_post, **kwargs
)
if self._content_type_is_json(response):
return self._read_json_response(response)
else:
return self._read_stream_response(response) | def query(
self, queryEngine, query_str, vendorSpecific=None, do_post=False, **kwargs
) | See Also: queryResponse()
Args:
queryEngine:
query_str:
vendorSpecific:
do_post:
**kwargs:
Returns: | 3.040309 | 3.101913 | 0.98014 |
return self.GET(['query', queryEngine], query=kwargs, headers=vendorSpecific) | def getQueryEngineDescriptionResponse(self, queryEngine, vendorSpecific=None, **kwargs) | CNRead.getQueryEngineDescription(session, queryEngine) →
QueryEngineDescription https://releases.dataone.org/online/api-
documentation-v2.0.1/apis/CN_APIs.html#CNRead.getQueryEngineDescription
MNQuery.getQueryEngineDescription(session, queryEngine) → QueryEngineDescription
http://jenkins... | 13.858088 | 35.246307 | 0.393178 |
response = self.getQueryEngineDescriptionResponse(queryEngine, **kwargs)
return self._read_dataone_type_response(response, 'QueryEngineDescription') | def getQueryEngineDescription(self, queryEngine, **kwargs) | See Also: getQueryEngineDescriptionResponse()
Args:
queryEngine:
**kwargs:
Returns: | 7.667552 | 8.952433 | 0.856477 |
if obj is not None:
# Make sure that key is REALLY unique.
return '{}-{}'.format(id(self), obj.pk)
return "{}-None".format(id(self)) | def _get_cache_key(self, obj) | Derive cache key for given object. | 6.716291 | 5.969231 | 1.125152 |
if build_kwargs is None:
build_kwargs = {}
cached = {}
if 'queryset' in build_kwargs:
cached = {
'model': build_kwargs['queryset'].model,
'pks': list(build_kwargs['queryset'].values_list('pk', flat=True)),
}
e... | def set(self, obj, build_kwargs) | Set cached value. | 2.437471 | 2.250442 | 1.083108 |
cached = self._thread_local.cache[self._get_cache_key(obj)]
build_kwargs = {}
if 'model' in cached and 'pks' in cached:
build_kwargs['queryset'] = cached['model'].objects.filter(pk__in=cached['pks'])
elif 'obj' in cached:
if cached['obj'].__class__.obje... | def take(self, obj) | Get cached value and clean cache. | 3.301339 | 3.009408 | 1.097006 |
signal.connect(self, **kwargs)
self.connections.append((signal, kwargs)) | def connect(self, signal, **kwargs) | Connect a specific signal type to this receiver. | 4.26813 | 4.013675 | 1.063397 |
for signal, kwargs in self.connections:
signal.disconnect(self, **kwargs) | def disconnect(self) | Disconnect all connected signal types from this receiver. | 10.018825 | 7.550576 | 1.326895 |
self.index = index
signal = ElasticSignal(self, 'process', pass_kwargs=True)
signal.connect(post_save, sender=self.model)
signal.connect(pre_delete, sender=self.model)
pre_delete_signal = ElasticSignal(self, 'process_predelete', pass_kwargs=True)
pre_delete_sig... | def connect(self, index) | Connect signals needed for dependency updates.
Pre- and post-delete signals have to be handled separately, as:
* in the pre-delete signal we have the information which
objects to rebuild, but affected relations are still
presented, so rebuild would reflect in the wrong (outda... | 2.557897 | 2.469906 | 1.035625 |
# Determine which model is the target model as either side of the relation
# may be passed as `field`.
if index.object_type == self.field.rel.model:
self.model = self.field.rel.related_model
self.accessor = self.field.rel.field.attname
else:
s... | def connect(self, index) | Connect signals needed for dependency updates. | 3.293751 | 3.201996 | 1.028656 |
for obj in objects:
if self.filter(obj, **kwargs) is False:
return False
return True | def _filter(self, objects, **kwargs) | Determine if dependent object should be processed. | 4.231653 | 3.453796 | 1.225218 |
if action is None:
# Check filter before rebuilding index.
if not self._filter([obj], update_fields=update_fields):
return
queryset = getattr(obj, self.accessor).all()
# Special handling for relations to self.
if self.field.r... | def _get_build_kwargs(self, obj, pk_set=None, action=None, update_fields=None, reverse=None, **kwargs) | Prepare arguments for rebuilding indices. | 3.550844 | 3.377554 | 1.051306 |
build_kwargs = self._get_build_kwargs(obj, pk_set, action, update_fields, **kwargs)
self.delete_cache.set(obj, build_kwargs) | def process_predelete(self, obj, pk_set=None, action=None, update_fields=None, **kwargs) | Render the queryset of influenced objects and cache it. | 4.079608 | 3.646019 | 1.118921 |
build_kwargs = self.delete_cache.take(obj)
if build_kwargs:
self.index.build(**build_kwargs) | def process_delete(self, obj, pk_set=None, action=None, update_fields=None, **kwargs) | Recreate queryset from the index and rebuild the index. | 11.871756 | 9.231616 | 1.285989 |
if action not in (None, 'post_add', 'pre_remove', 'post_remove', 'post_clear'):
return
if action == 'post_remove':
build_kwargs = self.remove_cache.take(cache_key)
else:
build_kwargs = self._get_build_kwargs(obj, pk_set, action, update_fields, **kwar... | def process_m2m(self, obj, pk_set=None, action=None, update_fields=None, cache_key=None, **kwargs) | Process signals from dependencies.
Remove signal is processed in two parts. For details see:
:func:`~Dependency.connect` | 2.74891 | 3.033952 | 0.906049 |
source = getattr(obj, self.field.rel.field.m2m_field_name())
target = getattr(obj, self.field.rel.field.m2m_reverse_field_name())
pk_set = set()
if target:
pk_set.add(target.pk)
self.process_m2m(source, pk_set, action=action, reverse=False, cache_key=obj) | def _process_m2m_through(self, obj, action) | Process custom M2M through model actions. | 3.220545 | 3.159869 | 1.019202 |
# We are only interested in signals that establish relations.
if not created:
return
self._process_m2m_through(obj, 'post_add') | def process_m2m_through_save(self, obj, created=False, **kwargs) | Process M2M post save for custom through model. | 8.341665 | 7.640999 | 1.091698 |
build_kwargs = self._get_build_kwargs(obj, pk_set, action, update_fields, **kwargs)
if build_kwargs:
self.index.build(**build_kwargs) | def process(self, obj, pk_set=None, action=None, update_fields=None, **kwargs) | Process signals from dependencies. | 3.625623 | 3.47704 | 1.042733 |
post_save_signal = ElasticSignal(index, 'build')
post_save_signal.connect(post_save, sender=index.object_type)
self.signals.append(post_save_signal)
post_delete_signal = ElasticSignal(index, 'remove_object')
post_delete_signal.connect(post_delete, sender=index.object_ty... | def _connect_signal(self, index) | Create signals for building indexes. | 3.389472 | 3.217811 | 1.053347 |
for index in self.indexes:
if index.object_type:
self._connect_signal(index) | def register_signals(self) | Register signals for all indexes. | 10.130908 | 6.138616 | 1.650357 |
self.indexes = []
for app_config in apps.get_app_configs():
indexes_path = '{}.elastic_indexes'.format(app_config.name)
try:
indexes_module = import_module(indexes_path)
for attr_name in dir(indexes_module):
attr = ge... | def discover_indexes(self) | Save list of index builders into ``_index_builders``. | 3.860413 | 3.816246 | 1.011573 |
for index in self.indexes:
index.build(obj, queryset, push) | def build(self, obj=None, queryset=None, push=True) | Trigger building of the indexes.
Support passing ``obj`` parameter to the indexes, so we can
trigger build only for one object. | 5.343317 | 3.881892 | 1.376472 |
for ind in self.indexes:
if index and not isinstance(ind, index):
continue
ind.push() | def push(self, index=None) | Push built documents to ElasticSearch.
If ``index`` is specified, only that index will be pushed. | 8.425422 | 7.975979 | 1.056349 |
for index in self.indexes:
index.destroy()
if not skip_mapping:
index.create_mapping() | def delete(self, skip_mapping=False) | Delete all entries from ElasticSearch. | 5.996921 | 4.140447 | 1.448375 |
self.unregister_signals()
for index in self.indexes:
index.destroy()
self.indexes = [] | def destroy(self) | Delete all indexes from Elasticsearch and index builder. | 6.285444 | 4.519195 | 1.390833 |
r
self.C_in = C_in
self.scale_in = scale_in | def _set_initial(self, C_in, scale_in) | r"""Set the initial values for parameters and Wilson coefficients at
the scale `scale_in`. | 4.951603 | 4.500916 | 1.100132 |
if wc.eft != 'SMEFT':
raise ValueError("Wilson coefficients use wrong EFT.")
if wc.basis != 'Warsaw':
raise ValueError("Wilson coefficients use wrong basis.")
self.scale_in = wc.scale
C = wilson.util.smeftutil.wcxf2arrays_symmetrized(wc.dict)
# fi... | def _set_initial_wcxf(self, wc, get_smpar=True) | Load the initial values for Wilson coefficients from a
wcxf.WC instance.
Parameters:
- `get_smpar`: boolean, optional, defaults to True. If True, an attempt
is made to determine the SM parameters from the requirement of
reproducing the correct SM masses and mixings at the e... | 4.560747 | 4.313325 | 1.057362 |
C = self._rotate_defaultbasis(C_out)
d = wilson.util.smeftutil.arrays2wcxf_nonred(C)
basis = wcxf.Basis['SMEFT', 'Warsaw']
all_wcs = set(basis.all_wcs) # to speed up lookup
d = {k: v for k, v in d.items() if k in all_wcs and v != 0}
d = wcxf.WC.dict2values(d)
... | def _to_wcxf(self, C_out, scale_out) | Return the Wilson coefficients `C_out` as a wcxf.WC instance.
Note that the Wilson coefficients are rotated into the Warsaw basis
as defined in WCxf, i.e. to the basis where the down-type and charged
lepton mass matrices are diagonal. | 6.389134 | 5.807938 | 1.100069 |
self._check_initial()
return rge.smeft_evolve(C_in=self.C_in,
scale_in=self.scale_in,
scale_out=scale_out,
**kwargs) | def _rgevolve(self, scale_out, **kwargs) | Solve the SMEFT RGEs from the initial scale to `scale_out`.
Returns a dictionary with parameters and Wilson coefficients at
`scale_out`. Additional keyword arguments will be passed to
the ODE solver `scipy.integrate.odeint`. | 6.264764 | 4.741418 | 1.321285 |
self._check_initial()
return rge.smeft_evolve_leadinglog(C_in=self.C_in,
scale_in=self.scale_in,
scale_out=scale_out) | def _rgevolve_leadinglog(self, scale_out) | Compute the leading logarithmic approximation to the solution
of the SMEFT RGEs from the initial scale to `scale_out`.
Returns a dictionary with parameters and Wilson coefficients.
Much faster but less precise that `rgevolve`. | 6.6505 | 5.144496 | 1.292741 |
# initialize an empty SMEFT instance
smeft_sm = SMEFT(wc=None)
C_in_sm = smeftutil.C_array2dict(np.zeros(9999))
# set the SM parameters to the values obtained from smpar.smeftpar
C_SM = smpar.smeftpar(scale_sm, C_out, basis='Warsaw')
SM_keys = set(smeftutil.SM_ke... | def _run_sm_scale_in(self, C_out, scale_sm=91.1876) | Get the SM parameters at the EW scale, using an estimate `C_out`
of the Wilson coefficients at that scale, and run them to the
input scale. | 5.736006 | 5.142532 | 1.115405 |
if accuracy == 'integrate':
C_out = self._rgevolve(scale_sm)
elif accuracy == 'leadinglog':
C_out = self._rgevolve_leadinglog(scale_sm)
else:
raise ValueError("'{}' is not a valid value of 'accuracy' (must be either 'integrate' or 'leadinglog').".form... | def get_smpar(self, accuracy='integrate', scale_sm=91.1876) | Compute the SM MS-bar parameters at the electroweak scale.
This method can be used to validate the accuracy of the iterative
extraction of SM parameters. If successful, the values returned by this
method should agree with the values in the dictionary
`wilson.run.smeft.smpar.p`. | 3.868759 | 4.093503 | 0.945098 |
# intialize a copy of ourselves
_smeft = SMEFT(self.wc, get_smpar=False)
# Step 1: run the SM up, using the WCs at scale_input as (constant) estimate
_smeft.C_in.update(self._run_sm_scale_in(self.C_in, scale_sm=scale_sm))
# Step 2: run the WCs down in LL approximation
... | def _get_sm_scale_in(self, scale_sm=91.1876) | Get an estimate of the SM parameters at the input scale by running
them from the EW scale using constant values for the Wilson coefficients
(corresponding to their leading log approximated values at the EW
scale).
Note that this is not guaranteed to work and will fail if some of the
... | 8.047848 | 6.92046 | 1.162906 |
if accuracy == 'integrate':
C_out = self._rgevolve(scale, **kwargs)
elif accuracy == 'leadinglog':
C_out = self._rgevolve_leadinglog(scale)
else:
raise ValueError("'{}' is not a valid value of 'accuracy' (must be either 'integrate' or 'leadinglog').".... | def run(self, scale, accuracy='integrate', **kwargs) | Return the Wilson coefficients (as wcxf.WC instance) evolved to the
scale `scale`.
Parameters:
- `scale`: scale in GeV
- accuracy: whether to use the numerical solution to the RGE
('integrate', the default, slow but precise) or the leading logarithmic
approximation ('l... | 3.797065 | 3.029465 | 1.253378 |
if scale == self.scale_in:
raise ValueError("The scale must be different from the input scale")
elif scale < self.scale_in:
scale_min = scale
scale_max = self.scale_in
elif scale > self.scale_in:
scale_max = scale
scale_min = s... | def run_continuous(self, scale) | Return a continuous solution to the RGE as `RGsolution` instance. | 4.603165 | 3.436258 | 1.339587 |
name, path, args, kwargs = super().deconstruct()
if self.populate_from is not None:
kwargs['populate_from'] = self.populate_from
if self.unique_with != ():
kwargs['unique_with'] = self.unique_with
kwargs.pop('unique', None)
return name, pat... | def deconstruct(self) | Deconstruct method. | 3.308412 | 3.253912 | 1.016749 |
constraints_expression = []
constraints_values = {}
for field_name in self.unique_with:
if constants.LOOKUP_SEP in field_name:
raise NotImplementedError(
'`unique_with` constraint does not support lookups by related models.'
... | def _get_unique_constraints(self, instance) | Return SQL filter for filtering by fields in ``unique_with`` attribute.
Filter is returned as tuple of two elements where first one is
placeholder which is safe to insert into SQL query and second
one may include potentially dangerous values and must be passed
to SQL query in ``params``... | 3.145586 | 2.996381 | 1.049795 |
if hasattr(self.populate_from, '__call__'):
# ResolweSlugField(populate_from=lambda instance: ...)
return self.populate_from(instance)
else:
# ResolweSlugField(populate_from='foo')
attr = getattr(instance, self.populate_from)
return at... | def _get_populate_from_value(self, instance) | Get the value from ``populate_from`` attribute. | 3.452029 | 3.050105 | 1.131774 |
slug = self.value_from_object(instance)
# We don't want to change slug defined by user.
predefined_slug = bool(slug)
if not slug and self.populate_from:
slug = self._get_populate_from_value(instance)
if slug:
slug = slugify(slug)
if no... | def pre_save(self, instance, add) | Ensure slug uniqunes before save. | 4.430104 | 4.356072 | 1.016995 |
if not path.lower().endswith(('.yml', '.yaml')):
return []
with open(path) as fn:
schemas = yaml.load(fn, Loader=yaml.FullLoader)
if not schemas:
# TODO: Logger.
# self.stderr.write("Could not read YAML file {}".format(schema_file))
... | def discover_process(self, path) | Perform process discovery in given path.
This method will be called during process registration and
should return a list of dictionaries with discovered process
schemas. | 4.109159 | 4.224604 | 0.972673 |
if expression_engine is None:
return values
processed = {}
for name, value in values.items():
if isinstance(value, str):
value = value.strip()
try:
expression = expression_engine.get_inline_expression(value)
... | def _evaluate_expressions(self, expression_engine, step_id, values, context) | Recursively evaluate expressions in a dictionary of values. | 2.465764 | 2.354588 | 1.047217 |
expression_engine = data.process.requirements.get('expression-engine', None)
if expression_engine is not None:
expression_engine = self.get_expression_engine(expression_engine)
# Parse steps.
steps = data.process.run.get('program', None)
if steps is None:
... | def evaluate(self, data) | Evaluate the code needed to compute a given Data object. | 3.204462 | 3.173276 | 1.009828 |
global redis_conn # pylint: disable=global-statement,invalid-name
conn = await aioredis.create_connection(
'redis://{}:{}'.format(
SETTINGS.get('FLOW_EXECUTOR', {}).get('REDIS_CONNECTION', {}).get('host', 'localhost'),
SETTINGS.get('FLOW_EXECUTOR', {}).get('REDIS_CONNECTION... | async def init() | Create a connection to the Redis server. | 2.808866 | 2.557834 | 1.098142 |
packet = {
ExecutorProtocol.DATA_ID: DATA['id'],
ExecutorProtocol.COMMAND: cmd,
}
packet.update(extra_fields)
logger.debug("Sending command to listener: {}".format(json.dumps(packet)))
# TODO what happens here if the push fails? we don't have any realistic recourse,
# so j... | async def send_manager_command(cmd, expect_reply=True, extra_fields={}) | Send a properly formatted command to the manager.
:param cmd: The command to send (:class:`str`).
:param expect_reply: If ``True``, wait for the manager to reply
with an acknowledgement packet.
:param extra_fields: A dictionary of extra information that's
merged into the packet body (i.e. n... | 5.130078 | 5.211312 | 0.984412 |
lookup_dict, generate_dict = _split_field_list(field_list)
query, annotate_key_list = _annotate_query(query, generate_dict)
# return query, annotate_key_list
#
# query, annotate_key_list = _create_query(filter_arg_dict, generate_dict)
lookup_list = [v["lookup_str"] for k, v in lookup_dict... | def extract_values_query(query, field_list, out_stream=None) | Get list of dicts where each dict holds values from one SciObj.
Args:
field_list: list of str
List of field names for which to return values. Must be strings from
FIELD_NAME_TO_generate_dict.keys().
If None, return all fields.
filter_arg_dict: dict
... | 3.943483 | 3.64583 | 1.081642 |
lookup_dict, generate_dict = _split_field_list(field_list)
query, annotate_key_list = _create_query(filter_arg_dict, generate_dict)
lookup_list = [v["lookup_str"] for k, v in lookup_dict.items()] + annotate_key_list
if out_stream is None:
return _create_sciobj_list(query, lookup_list, loo... | def extract_values(field_list=None, filter_arg_dict=None, out_stream=None) | Get list of dicts where each dict holds values from one SciObj.
Args:
field_list: list of str
List of field names for which to return values. Must be strings from
FIELD_NAME_TO_generate_dict.keys().
If None, return all fields.
filter_arg_dict: dict
... | 3.798983 | 3.82733 | 0.992594 |
if field_list is not None:
invalid_field_list = [
v for v in field_list if v not in get_valid_field_name_list()
]
if invalid_field_list:
raise d1_common.types.exceptions.InvalidRequest(
0, "Invalid fields: {}".format(", ".join(invalid_field_list))... | def assert_invalid_field_list(field_list) | raise d1_common.types.exceptions.InvalidRequest() if ``field_list`` contains any
invalid field names. A list of the invalid fields is included in the exception.
- Implicitly called by ``extract_values()``. | 2.653968 | 2.480161 | 1.070079 |
annotate_key_list = []
for field_name, annotate_dict in generate_dict.items():
for annotate_name, annotate_func in annotate_dict["annotate_dict"].items():
query = annotate_func(query)
annotate_key_list.append(annotate_name)
return query, annotate_key_list | def _annotate_query(query, generate_dict) | Add annotations to the query to retrieve values required by field value generate
functions. | 2.881129 | 2.886462 | 0.998152 |
sciobj_dict = {}
# for sciobj_value, lookup_str in zip(sciobj_value_list, lookup_list):
lookup_to_value_dict = {k: v for k, v in zip(lookup_list, sciobj_value_list)}
for field_name, r_dict in lookup_dict.items():
if r_dict["lookup_str"] in lookup_to_value_dict.keys():
sciobj_... | def _value_list_to_sciobj_dict(
sciobj_value_list, lookup_list, lookup_dict, generate_dict
) | Create a dict where the keys are the requested field names, from the values
returned by Django. | 2.235278 | 2.272427 | 0.983653 |
lookup_dict = {}
generate_dict = {}
for field_name in field_list or FIELD_NAME_TO_EXTRACT_DICT.keys():
try:
extract_dict = FIELD_NAME_TO_EXTRACT_DICT[field_name]
except KeyError:
assert_invalid_field_list(field_list)
else:
if "lookup_str" in ... | def _split_field_list(field_list) | Split the list of fields for which to extract values into lists by extraction
methods.
- Remove any duplicated field names.
- Raises ValueError with list of any invalid field names in ``field_list``. | 3.100661 | 3.123098 | 0.992816 |
if is_v1_api(request):
return d1_common.types.dataoneTypes_v1_1
elif is_v2_api(request) or is_diag_api(request):
return d1_common.types.dataoneTypes_v2_0
else:
raise d1_common.types.exceptions.ServiceFailure(
0, 'Unknown version designator in URL. url="{}"'.format(re... | def dataoneTypes(request) | Return the PyXB binding to use when handling a request. | 3.236586 | 3.317024 | 0.97575 |
if date_str is None:
return None
try:
return d1_common.date_time.dt_from_iso8601_str(date_str)
except d1_common.date_time.iso8601.ParseError as e:
raise d1_common.types.exceptions.InvalidRequest(
0,
'Invalid date format for URL parameter. date="{}" error=... | def parse_and_normalize_url_date(date_str) | Parse a ISO 8601 date-time with optional timezone.
- Return as datetime with timezone adjusted to UTC.
- Return naive date-time set to UTC. | 2.701631 | 2.779961 | 0.971823 |
resp_dict = self._get_query(q='id:{}'.format(doc_id))
if resp_dict['response']['numFound'] > 0:
return resp_dict['response']['docs'][0] | def get(self, doc_id) | Retrieve the specified document. | 3.57751 | 3.499913 | 1.022171 |
resp_dict = self._get_query(start=start, rows=rows, **query_dict)
return {
'matches': resp_dict['response']['numFound'],
'start': start,
'ids': [d['id'] for d in resp_dict['response']['docs']],
} | def get_ids(self, start=0, rows=1000, **query_dict) | Retrieve a list of identifiers for documents matching the query. | 3.010158 | 2.814557 | 1.069496 |
param_dict = query_dict.copy()
param_dict['count'] = 0
resp_dict = self._get_query(**param_dict)
return resp_dict['response']['numFound'] | def count(self, **query_dict) | Return the number of entries that match query. | 4.156432 | 3.632072 | 1.144369 |
param_dict = query_dict.copy()
param_dict.update(
{
'rows': '0',
'facet': 'true',
'facet.field': name,
'facet.limit': str(maxvalues),
'facet.zeros': 'false',
'facet.sort': str(sort).lower... | def get_field_values(self, name, maxvalues=-1, sort=True, **query_dict) | Retrieve the unique values for a field, along with their usage counts.
:param name: Name of field for which to retrieve values
:type name: string
:param sort: Sort the result
:param maxvalues: Maximum number of values to retrieve. Default is -1,
which causes retrieval of all... | 2.688812 | 2.82201 | 0.952801 |
param_dict = query_dict.copy()
param_dict.update({'rows': 1, 'fl': name, 'sort': '%s asc' % name})
try:
min_resp_dict = self._post_query(**param_dict)
param_dict['sort'] = '%s desc' % name
max_resp_dict = self._post_query(**param_dict)
ret... | def get_field_min_max(self, name, **query_dict) | 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 identifying range of records for min and max values
@param... | 2.584069 | 2.616162 | 0.987733 |
return self.query(
'solr',
'<add>{}</add>'.format(
''.join([self._format_add(fields) for fields in docs])
),
do_post=True,
) | def add_docs(self, docs) | docs is a list of fields that are a dictionary of name:value for a record. | 7.110256 | 5.892234 | 1.206716 |
if value is None:
return None
if field_type == 'string':
return str(value)
elif field_type == 'text':
return str(value)
elif field_type == 'int':
try:
v = int(value)
return str(v)
except:... | def _coerce_type(self, field_type, value) | Returns unicode(value) after trying to coerce it into the Solr field type.
@param field_type(string) The Solr field type for the value
@param value(any) The value that is to be represented as Unicode text. | 1.700875 | 1.691072 | 1.005797 |
field_type = 'string'
try:
field_type = FIELD_TYPE_CONVERSION_MAP[field]
return field_type
except:
pass
fta = field.split('_')
if len(fta) > 1:
ft = fta[len(fta) - 1]
try:
field_type = FIELD_TYPE... | def _get_solr_type(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. | 2.952515 | 2.888364 | 1.02221 |
param_dict = query_dict.copy()
return self._send_query(do_post=False, **param_dict) | def _get_query(self, **query_dict) | Perform a GET query against Solr and return the response as a Python dict. | 7.143762 | 4.231119 | 1.688386 |
param_dict = query_dict.copy()
return self._send_query(do_post=True, **param_dict) | def _post_query(self, **query_dict) | Perform a POST query against Solr and return the response as a Python
dict. | 5.896648 | 5.076228 | 1.16162 |
# self._prepare_query_term()
param_dict = query_dict.copy()
param_dict.setdefault('wt', 'json')
param_dict.setdefault('q', '*.*')
param_dict.setdefault('fl', '*')
return self.query('solr', '', do_post=do_post, query=param_dict) | def _send_query(self, do_post=False, **query_dict) | Perform a query against Solr and return the response as a Python dict. | 4.974232 | 4.201079 | 1.184037 |
if term == "*":
return term
add_star = False
if term[len(term) - 1] == '*':
add_star = True
term = term[0 : len(term) - 1]
term = self._escape_query_term(term)
if add_star:
term = '{}*'.format(term)
if self._get_sol... | def _prepare_query_term(self, field, term) | Prepare a query term for inclusion in a query.
This escapes the term and if necessary, wraps the term in quotes. | 2.90108 | 2.828893 | 1.025518 |
term = term.replace('\\', '\\\\')
for c in RESERVED_CHAR_LIST:
term = term.replace(c, r'\{}'.format(c))
return term | def _escape_query_term(self, term) | Escape a query term for inclusion in a query.
- Also see: prepare_query_term(). | 3.4004 | 3.982164 | 0.853908 |
self._log.debug("Iterator c_record={}".format(self.c_record))
page_size = self.page_size
if (offset + page_size) > self.max_records:
page_size = self.max_records - offset
param_dict = self.query_dict.copy()
param_dict.update(
{
'st... | def _next_page(self, offset) | Retrieves the next set of results from the service. | 4.062079 | 3.983458 | 1.019737 |
self._log.debug("Iterator c_record={}".format(self.c_record))
param_dict = self.query_dict.copy()
param_dict.update(
{
'rows': '0',
'facet': 'true',
'facet.limit': str(self.page_size),
'facet.offset': str(offset... | def _next_page(self, offset) | Retrieves the next set of results from the service. | 3.374964 | 3.334763 | 1.012055 |
Process = apps.get_model('flow', 'Process')
DescriptorSchema = apps.get_model('flow', 'DescriptorSchema')
for process in Process.objects.all():
process.entity_type = process.flow_collection
process.entity_descriptor_schema = process.flow_collection
if (process.entity_descripto... | def migrate_flow_collection(apps, schema_editor) | Migrate 'flow_collection' field to 'entity_type'. | 3.298087 | 2.991389 | 1.102527 |
try:
return VERSION_TO_BINDING_DICT[api_major, api_minor]
except KeyError:
raise ValueError(
'Unknown DataONE API version: {}.{}'.format(api_major, api_minor)
) | def get_pyxb_binding_by_api_version(api_major, api_minor=0) | Map DataONE API version tag to PyXB binding.
Given a DataONE API major version number, return PyXB binding that can
serialize and deserialize DataONE XML docs of that version.
Args:
api_major, api_minor: str or int
DataONE API major and minor version numbers.
- If ``api_major`` is a... | 3.267913 | 3.222455 | 1.014107 |
m = re.match(r'(/|^)(v\d)(/|$)', url)
if not m:
return None
return m.group(2) | def extract_version_tag_from_url(url) | Extract a DataONE API version tag from a MN or CN service endpoint URL.
Args:
url : str
Service endpoint URL. E.g.: ``https://mn.example.org/path/v2/object/pid``.
Returns:
str : Valid version tags are currently ``v1`` or ``v2``. | 3.406085 | 4.243395 | 0.802679 |
if str_is_v1(xml_str):
return xml_str
etree_obj = str_to_etree(xml_str)
strip_v2_elements(etree_obj)
etree_replace_namespace(etree_obj, d1_common.types.dataoneTypes_v1.Namespace)
return etree_to_str(etree_obj) | def str_to_v1_str(xml_str) | Convert a API v2 XML doc to v1 XML doc.
Removes elements that are only valid for v2 and changes namespace to v1.
If doc is already v1, it is returned unchanged.
Args:
xml_str : str
API v2 XML doc. E.g.: ``SystemMetadata v2``.
Returns:
str : API v1 XML doc. E.g.: ``SystemMetadata ... | 3.946683 | 4.099473 | 0.962729 |
if str_is_v2(xml_str):
return xml_str
etree_obj = str_to_etree(xml_str)
etree_replace_namespace(etree_obj, d1_common.types.dataoneTypes_v2_0.Namespace)
return etree_to_str(etree_obj) | def str_to_v2_str(xml_str) | Convert a API v1 XML doc to v2 XML doc.
All v1 elements are valid for v2, so only changes namespace.
Args:
xml_str : str
API v1 XML doc. E.g.: ``SystemMetadata v1``.
Returns:
str : API v2 XML doc. E.g.: ``SystemMetadata v2``. | 3.690361 | 4.301557 | 0.857913 |
try:
str_to_etree(xml_str)
except xml.etree.ElementTree.ParseError:
return False
else:
return True | def str_is_well_formed(xml_str) | Args:
xml_str : str
DataONE API XML doc.
Returns:
bool: **True** if XML doc is well formed. | 2.884296 | 3.573674 | 0.807095 |
# TODO: Will not detect v1.2 as v1.
return (
pyxb_obj._element().name().namespace()
== d1_common.types.dataoneTypes_v1.Namespace
) | def pyxb_is_v1(pyxb_obj) | Args:
pyxb_obj : PyXB object
PyXB object holding an unknown type.
Returns:
bool: **True** if ``pyxb_obj`` holds an API v1 type. | 9.819345 | 11.195069 | 0.877113 |
return (
pyxb_obj._element().name().namespace()
== d1_common.types.dataoneTypes_v2_0.Namespace
) | def pyxb_is_v2(pyxb_obj) | Args:
pyxb_obj : PyXB object
PyXB object holding an unknown type.
Returns:
bool: **True** if ``pyxb_obj`` holds an API v2 type. | 7.893575 | 10.598076 | 0.744812 |
parser = xml.etree.ElementTree.XMLParser(encoding=encoding)
return xml.etree.ElementTree.fromstring(xml_str, parser=parser) | def str_to_etree(xml_str, encoding='utf-8') | Deserialize API XML doc to an ElementTree.
Args:
xml_str: bytes
DataONE API XML doc
encoding: str
Decoder to use when converting the XML doc ``bytes`` to a Unicode str.
Returns:
ElementTree: Matching the API version of the XML doc. | 2.021307 | 2.539539 | 0.795935 |
ns_reverse_dict = ns_reverse_dict or NS_REVERSE_DICT
for namespace_str, prefix_str in ns_reverse_dict.items():
tag_str = tag_str.replace(
'{{{}}}'.format(namespace_str), '{}:'.format(prefix_str)
)
return tag_str | def replace_namespace_with_prefix(tag_str, ns_reverse_dict=None) | Convert XML tag names with namespace on the form ``{namespace}tag`` to form
``prefix:tag``.
Args:
tag_str: str
Tag name with namespace. E.g.:
``{http://www.openarchives.org/ore/terms/}ResourceMap``.
ns_reverse_dict : dict
A dictionary of namespace to prefix to use for the c... | 2.086345 | 2.814067 | 0.741398 |
def _replace_recursive(el, n):
el.tag = re.sub(r'{.*\}', '{{{}}}'.format(n), el.tag)
el.text = el.text.strip() if el.text else None
el.tail = el.tail.strip() if el.tail else None
for child_el in el:
_replace_recursive(child_el, n)
_replace_recursive(etree_obj, ... | def etree_replace_namespace(etree_obj, ns_str) | In-place change the namespace of elements in an ElementTree.
Args:
etree_obj: ElementTree
ns_str : str
The namespace to set. E.g.: ``http://ns.dataone.org/service/types/v1``. | 2.644194 | 2.596371 | 1.018419 |
if etree_obj.tag == v2_0_tag('logEntry'):
strip_logEntry(etree_obj)
elif etree_obj.tag == v2_0_tag('log'):
strip_log(etree_obj)
elif etree_obj.tag == v2_0_tag('node'):
strip_node(etree_obj)
elif etree_obj.tag == v2_0_tag('nodeList'):
strip_node_list(etree_obj)
el... | def strip_v2_elements(etree_obj) | In-place remove elements and attributes that are only valid in v2 types.
Args: etree_obj: ElementTree ElementTree holding one of the DataONE API types
that changed between v1 and v2. | 1.978039 | 1.961719 | 1.008319 |
for series_id_el in etree_obj.findall('seriesId'):
etree_obj.remove(series_id_el)
for media_type_el in etree_obj.findall('mediaType'):
etree_obj.remove(media_type_el)
for file_name_el in etree_obj.findall('fileName'):
etree_obj.remove(file_name_el) | def strip_system_metadata(etree_obj) | In-place remove elements and attributes that are only valid in v2 types from v1
System Metadata.
Args: etree_obj: ElementTree ElementTree holding a v1 SystemMetadata. | 2.052488 | 2.047196 | 1.002585 |
pid = d1_common.xml.get_req_val(sysmeta_pyxb.identifier)
self._assert_is_pid_of_local_unprocessed_replica(pid)
self._check_and_create_replica_revision(sysmeta_pyxb, "obsoletes")
self._check_and_create_replica_revision(sysmeta_pyxb, "obsoletedBy")
sciobj_url = d1_gmn.app.... | def _create_replica(self, sysmeta_pyxb, sciobj_bytestream) | GMN handles replicas differently from native objects, with the main
differences being related to handling of restrictions related to revision chains
and SIDs.
So this create sequence differs significantly from the regular one that is
accessed through MNStorage.create(). | 4.061699 | 4.089784 | 0.993133 |
item_task_name = "Importing objects"
pid_path = self.options['pid_path']
if not os.path.exists(pid_path):
raise ConnectionError('File does not exist: {}'.format(pid_path))
with open(pid_path, encoding='UTF-8') as pid_file:
self.progress_logger.start_tas... | async def restricted_import(self, async_client, node_type) | Import only the Science Objects specified by a text file.
The file must be UTF-8 encoded and contain one PIDs or SIDs per line. | 3.744221 | 3.230736 | 1.158937 |
self._logger.info('Importing: {}'.format(pid))
task_set = set()
object_info_pyxb = d1_common.types.dataoneTypes.ObjectInfo()
object_info_pyxb.identifier = pid
task_set.add(self.import_object(async_client, object_info_pyxb))
result_set, task_set = await asyncio... | async def import_aggregated(self, async_client, pid) | Import the SciObj at {pid}.
If the SciObj is a Resource Map, also recursively import the aggregated objects. | 3.648446 | 3.302976 | 1.104594 |
try:
return (await client.describe(pid)).get("DataONE-Proxy")
except d1_common.types.exceptions.DataONEException:
# Workaround for older GMNs that return 500 instead of 404 for describe()
pass | async def get_object_proxy_location(self, client, pid) | If object is proxied, return the proxy location URL.
If object is local, return None. | 10.313087 | 8.780538 | 1.174539 |
arg_dict = {
# Restrict query for faster debugging
# "fromDate": datetime.datetime(2017, 1, 1),
# "toDate": datetime.datetime(2017, 1, 10),
}
if node_type == "cn":
arg_dict["nodeId"] = django.conf.settings.NODE_IDENTIFIER
return ar... | def get_list_objects_arg_dict(self, node_type) | Create a dict of arguments that will be passed to listObjects().
If {node_type} is a CN, add filtering to include only objects from this GMN
instance in the ObjectList returned by CNCore.listObjects(). | 5.181153 | 4.557133 | 1.136933 |
arg_dict = {
# Restrict query for faster debugging
# "fromDate": datetime.datetime(2017, 1, 1),
# "toDate": datetime.datetime(2017, 1, 3),
}
if node_type == "cn":
arg_dict["nodeId"] = django.conf.settings.NODE_IDENTIFIER
return arg... | def get_log_records_arg_dict(self, node_type) | Create a dict of arguments that will be passed to getLogRecords().
If {node_type} is a CN, add filtering to include only objects from this GMN
instance in the ObjectList returned by CNCore.listObjects(). | 4.866624 | 4.654666 | 1.045537 |
node_pyxb = await client.get_capabilities()
return d1_common.type_conversions.pyxb_get_type_name(node_pyxb) == "NodeList" | async def is_cn(self, client) | Return True if node at {base_url} is a CN, False if it is an MN.
Raise a DataONEException if it's not a functional CN or MN. | 14.098791 | 9.203913 | 1.531826 |
try:
node_pyxb = await self.get_node_doc(client)
except d1_common.types.exceptions.DataONEException as e:
raise django.core.management.base.CommandError(
"Could not find a functional CN or MN at the provided BaseURL. "
'base_url="{}" error... | async def probe_node_type_major(self, client) | Determine if import source node is a CN or MN and which major version API to
use. | 4.429537 | 3.99541 | 1.108656 |
for node_pyxb in node_list_pyxb.node:
if node_pyxb.baseURL == base_url:
return node_pyxb | def find_node(self, node_list_pyxb, base_url) | Search NodeList for Node that has {base_url}.
Return matching Node or None | 2.262053 | 2.325004 | 0.972924 |
node_pyxb = self.find_node_by_id(node_list_pyxb, node_id)
assert node_pyxb is not None, (
"The NodeID of this GMN instance is unknown to the CN at the provided BaseURL. "
'node_id="{}" base_url="{}"'.format(node_id, self.options["baseurl"])
) | def assert_is_known_node_id(self, node_list_pyxb, node_id) | When importing from a CN, ensure that the NodeID which the ObjectList will be
filtered by is known to the CN. | 5.473344 | 4.554581 | 1.201723 |
max_major = 0
for s in node_pyxb.services.service:
max_major = max(max_major, int(s.version[1:]))
return max_major | def find_node_api_version(self, node_pyxb) | Find the highest API major version supported by node. | 3.559986 | 2.850192 | 1.249034 |
for node_pyxb in node_list_pyxb.node:
# if node_pyxb.baseURL == base_url:
if d1_common.xml.get_req_val(node_pyxb.identifier) == node_id:
return node_pyxb | def find_node_by_id(self, node_list_pyxb, node_id) | Search NodeList for Node with {node_id}.
Return matching Node or None | 3.673594 | 4.037583 | 0.90985 |
subprocess.Popen(
argv,
cwd=runtime_dir,
stdin=subprocess.DEVNULL
).wait() | def celery_run(data_id, runtime_dir, argv) | Run process executor.
:param data_id: The id of the :class:`~resolwe.flow.models.Data`
object to be processed.
:param runtime_dir: The directory from which to run the executor.
:param argv: The argument vector used to run the executor.
:param verbosity: The logging verbosity level. | 3.817326 | 6.093679 | 0.62644 |
sciobj_model = d1_gmn.app.model_util.get_sci_model(pid)
sciobj_model.is_archived = True
sciobj_model.save()
_update_modified_timestamp(sciobj_model) | def archive_sciobj(pid) | Set the status of an object to archived.
Preconditions:
- The object with the pid is verified to exist.
- The object is not a replica.
- The object is not archived. | 3.648782 | 4.081347 | 0.894014 |
# TODO: Make sure that old sections are removed if not included in update.
pid = d1_common.xml.get_req_val(sysmeta_pyxb.identifier)
if sciobj_url is None:
sciobj_url = d1_gmn.app.sciobj_store.get_rel_sciobj_file_url_by_pid(pid)
try:
sci_model = d1_gmn.app.model_util.get_sci_model... | def create_or_update(sysmeta_pyxb, sciobj_url=None) | Create or update database representation of a System Metadata object and closely
related internal state.
- If ``sciobj_url`` is not passed on create, storage in the internal sciobj store
is assumed
- If ``sciobj_url`` is passed on create, it can reference a location in the
internal sciobj store... | 2.504572 | 2.59171 | 0.966378 |
_delete_existing_access_policy(sysmeta_pyxb)
# Add an implicit allow rule with all permissions for the rights holder.
allow_rights_holder = d1_common.types.dataoneTypes.AccessRule()
permission = d1_common.types.dataoneTypes.Permission(
d1_gmn.app.auth.CHANGEPERMISSION_STR
)
allow_ri... | def _access_policy_pyxb_to_model(sci_model, sysmeta_pyxb) | Create or update the database representation of the sysmeta_pyxb access policy.
If called without an access policy, any existing permissions on the object
are removed and the access policy for the rights holder is recreated.
Preconditions:
- Each subject has been verified to a valid DataONE account.... | 3.642725 | 3.327927 | 1.094593 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.