_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 31 13.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q21400 | PartitionMagicView.get_number_of_partitions_for | train | def get_number_of_partitions_for(self, ar):
"""Return the number of selected partitions
"""
# fetch the number of partitions from the request
uid = api.get_uid(ar)
num = self.request.get("primary", {}).get(uid)
if num is None:
# get the number of partitions from the template
template = ar.getTemplate()
if template:
num = len(template.getPartitions())
| python | {
"resource": ""
} |
q21401 | PartitionMagicView.get_base_info | train | def get_base_info(self, obj):
"""Extract the base info from the given object
"""
obj = api.get_object(obj)
review_state = api.get_workflow_status_of(obj)
state_title = review_state.capitalize().replace("_", " ")
| python | {
"resource": ""
} |
q21402 | AccreditationView.selected_cats | train | def selected_cats(self, items):
"""return a list of all categories with accredited services
"""
| python | {
"resource": ""
} |
q21403 | AnalysisRequestPublishedResults.contentsMethod | train | def contentsMethod(self, contentFilter):
"""
ARReport objects associated to the current Analysis request.
If the user is not a Manager or LabManager or Client, no items are
displayed.
"""
allowedroles = ['Manager', 'LabManager', 'Client', 'LabClerk']
pm = getToolByName(self.context, "portal_membership")
member = | python | {
"resource": ""
} |
q21404 | Report.add_filter_by_client | train | def add_filter_by_client(self, query, out_params):
"""Applies the filter by client to the search query
"""
current_client = logged_in_client(self.context)
if current_client:
query['getClientUID'] = api.get_uid(current_client)
elif self.request.form.get("ClientUID", ""):
query['getClientUID'] = self.request.form['ClientUID']
| python | {
"resource": ""
} |
q21405 | Report.add_filter_by_date | train | def add_filter_by_date(self, query, out_params):
"""Applies the filter by Requested date to the search query
"""
date_query = formatDateQuery(self.context, 'Requested')
if date_query:
query['created'] = date_query
| python | {
"resource": ""
} |
q21406 | Report.add_filter_by_review_state | train | def add_filter_by_review_state(self, query, out_params):
"""Applies the filter by review_state to the search query
"""
self.add_filter_by_wf_state(query=query, out_params=out_params,
| python | {
"resource": ""
} |
q21407 | Import | train | def Import(context, request):
""" Beckman Coulter Access 2 analysis results
"""
infile = request.form['rochecobas_taqman_model48_file']
fileformat = request.form['rochecobas_taqman_model48_format']
artoapply = request.form['rochecobas_taqman_model48_artoapply']
override = request.form['rochecobas_taqman_model48_override']
instrument = request.form.get('instrument', None)
errors = []
logs = []
warns = []
# Load the most suitable parser according to file extension/options/etc...
parser = None
if not hasattr(infile, 'filename'):
errors.append(_("No file selected"))
if fileformat == 'rsf':
parser = RocheCobasTaqmanParser(infile)
if fileformat == 'csv':
parser = RocheCobasTaqmanParser(infile, "csv")
else:
errors.append(t(_("Unrecognized file format ${fileformat}",
mapping={"fileformat": fileformat})))
if parser:
# Load the importer
status = ['sample_received', 'attachment_due', 'to_be_verified']
if artoapply == 'received':
status = ['sample_received']
elif artoapply == 'received_tobeverified':
status = ['sample_received', 'attachment_due', 'to_be_verified']
over = [False, False]
if override == 'nooverride':
over = [False, False]
elif override == 'override':
| python | {
"resource": ""
} |
q21408 | Attachment.getClientUID | train | def getClientUID(self):
"""Return the UID of the client
"""
client = api.get_parent(self)
if | python | {
"resource": ""
} |
q21409 | Attachment.getLinkedRequests | train | def getLinkedRequests(self):
"""Lookup linked Analysis Requests
:returns: sorted list of ARs, where the latest AR comes first
"""
rc = api.get_tool("reference_catalog")
refs = rc.getBackReferences(self, "AnalysisRequestAttachment")
# fetch the objects by UID and handle nonexisting UIDs gracefully
ars = map(lambda ref: api.get_object_by_uid(ref.sourceUID, None), refs)
# filter out None values (nonexisting UIDs)
| python | {
"resource": ""
} |
q21410 | Attachment.getLinkedAnalyses | train | def getLinkedAnalyses(self):
"""Lookup linked Analyses
:returns: sorted list of ANs, where the latest AN comes first
"""
# Fetch the linked Analyses UIDs
refs = get_backreferences(self, "AnalysisAttachment")
# fetch the objects by UID and handle nonexisting UIDs gracefully
ans = map(lambda uid: api.get_object_by_uid(uid, None), refs)
# filter out None values (nonexisting UIDs)
| python | {
"resource": ""
} |
q21411 | Attachment.getTextTitle | train | def getTextTitle(self):
"""Return a title for texts and listings
"""
request_id = self.getRequestID()
if not request_id:
return ""
analysis = self.getAnalysis()
| python | {
"resource": ""
} |
q21412 | Attachment.getRequest | train | def getRequest(self):
"""Return the primary AR this attachment is linked
"""
ars = self.getLinkedRequests()
if len(ars) > 1:
# Attachment is assigned to more than one Analysis Request.
# This might happen when the AR was invalidated
ar_ids = ", ".join(map(api.get_id, ars))
logger.info("Attachment assigned to more than one AR: [{}]. "
"The first AR will be returned".format(ar_ids))
# return the first AR
| python | {
"resource": ""
} |
q21413 | Attachment.getAnalysis | train | def getAnalysis(self):
"""Return the primary analysis this attachment is linked
"""
analysis = None
ans = self.getLinkedAnalyses()
if len(ans) > 1:
# Attachment is assigned to more than one Analysis. This might
# happen when the AR was invalidated
an_ids = | python | {
"resource": ""
} |
q21414 | Method.getInstrumentsDisplayList | train | def getInstrumentsDisplayList(self):
"""Instruments capable to perform this method
"""
items | python | {
"resource": ""
} |
q21415 | FrontPageView.get_user_roles | train | def get_user_roles(self):
"""Returns a list of roles for the current user
"""
if self.is_anonymous_user():
return []
| python | {
"resource": ""
} |
q21416 | FrontPageView.set_versions | train | def set_versions(self):
"""Configure a list of product versions from portal.quickinstaller
"""
self.versions = {}
self.upgrades = {}
qi = getToolByName(self.context, "portal_quickinstaller")
for key in qi.keys():
self.versions[key] = qi.getProductVersion(key)
| python | {
"resource": ""
} |
q21417 | SamplingRound.getAnalysisRequests | train | def getAnalysisRequests(self):
""" Return all the Analysis Request brains linked to the Sampling Round
"""
# I have to get the catalog in this way because I can't do it with 'self'...
pc = getToolByName(api.portal.get(), 'portal_catalog')
| python | {
"resource": ""
} |
q21418 | SamplingRound.getClientContact | train | def getClientContact(self):
"""
Returns info from the Client contact who coordinates with the lab
"""
pc = getToolByName(api.portal.get(), 'portal_catalog')
contentFilter = {'portal_type': 'Contact',
'id': self.client_contact}
cnt = pc(contentFilter)
cntdict = {'uid': '', 'id': '', 'fullname': '', 'url': ''}
if len(cnt) == 1:
cnt = cnt[0].getObject()
cntdict = {
'uid': cnt.id,
| python | {
"resource": ""
} |
q21419 | SamplingRound.workflow_script_cancel | train | def workflow_script_cancel(self):
"""
When the round is cancelled, all its associated Samples and ARs are cancelled by the system.
"""
if skip(self, "cancel"):
return
self.reindexObject(idxs=["is_active", ])
# deactivate all analysis requests in this sampling round.
analysis_requests = self.getAnalysisRequests()
| python | {
"resource": ""
} |
q21420 | AnalysisRequestAddView.get_view_url | train | def get_view_url(self):
"""Return the current view url including request parameters
"""
request = self.request
url = request.getURL()
| python | {
"resource": ""
} |
q21421 | AnalysisRequestAddView.get_currency | train | def get_currency(self):
"""Returns the configured currency
"""
bika_setup = api.get_bika_setup()
currency = bika_setup.getCurrency()
| python | {
"resource": ""
} |
q21422 | AnalysisRequestAddView.get_ar_count | train | def get_ar_count(self):
"""Return the ar_count request paramteter
"""
ar_count = 1
try:
| python | {
"resource": ""
} |
q21423 | AnalysisRequestAddView.get_ar | train | def get_ar(self):
"""Create a temporary AR to fetch the fields from
"""
if not self.tmp_ar:
logger.info("*** CREATING TEMPORARY AR ***")
self.tmp_ar = | python | {
"resource": ""
} |
q21424 | AnalysisRequestAddView.generate_specifications | train | def generate_specifications(self, count=1):
"""Returns a mapping of count -> specification
"""
out = {}
# mapping of UID index to AR objects {1: <AR1>, 2: <AR2> ...}
copy_from = self.get_copy_from()
for arnum in range(count):
# get the source object
source = copy_from.get(arnum)
if source is None:
out[arnum] = {}
continue
| python | {
"resource": ""
} |
q21425 | AnalysisRequestAddView.get_copy_from | train | def get_copy_from(self):
"""Returns a mapping of UID index -> AR object
"""
# Create a mapping of source ARs for copy
copy_from = self.request.form.get("copy_from", "").split(",")
# clean out empty strings
copy_from_uids = filter(lambda x: x, copy_from)
out = dict().fromkeys(range(len(copy_from_uids)))
for n, uid in | python | {
"resource": ""
} |
q21426 | AnalysisRequestAddView.get_default_value | train | def get_default_value(self, field, context, arnum):
"""Get the default value of the field
"""
name = field.getName()
default = field.getDefault(context)
if name == "Batch":
batch = self.get_batch()
if batch is not None:
default = batch
if name == "Client":
client = self.get_client()
if client is not None:
default = client
# only set default contact for first column
if name == "Contact" and arnum == 0:
contact = self.get_default_contact()
if contact is not None:
default = contact
if name == "Sample":
sample = self.get_sample()
if sample is not None:
default = sample
# Querying for adapters to get default values from add-ons':
# We don't know which fields the form will render since
# some of them may come from add-ons. In order to obtain the default
# value for those fields we take advantage of adapters. Adapters
# registration should have the following format:
# < adapter
| python | {
"resource": ""
} |
q21427 | AnalysisRequestAddView.get_field_value | train | def get_field_value(self, field, context):
"""Get the stored value of the field
"""
name = field.getName()
value = context.getField(name).get(context)
| python | {
"resource": ""
} |
q21428 | AnalysisRequestAddView.get_client | train | def get_client(self):
"""Returns the Client
"""
context = self.context
parent = api.get_parent(context)
if context.portal_type == "Client":
return context
elif parent.portal_type == "Client":
return parent
| python | {
"resource": ""
} |
q21429 | AnalysisRequestAddView.get_batch | train | def get_batch(self):
"""Returns the Batch
"""
context = self.context
parent = api.get_parent(context)
if context.portal_type == "Batch":
| python | {
"resource": ""
} |
q21430 | AnalysisRequestAddView.get_parent_ar | train | def get_parent_ar(self, ar):
"""Returns the parent AR
"""
parent = ar.getParentAnalysisRequest()
# Return immediately if we have no parent
if parent is None:
return None
# Walk back the chain until we reach the source AR
| python | {
"resource": ""
} |
q21431 | AnalysisRequestAddView.is_field_visible | train | def is_field_visible(self, field):
"""Check if the field is visible
"""
context = self.context
fieldname = field.getName()
# hide the Client field on client and batch contexts
if fieldname == "Client" and context.portal_type in ("Client", ):
return False
| python | {
"resource": ""
} |
q21432 | AnalysisRequestAddView.get_fields_with_visibility | train | def get_fields_with_visibility(self, visibility, mode="add"):
"""Return the AR fields with the current visibility
"""
ar = self.get_ar()
mv = api.get_view("ar_add_manage", context=ar)
mv.get_field_order()
out = []
for field in mv.get_fields_with_visibility(visibility, mode):
| python | {
"resource": ""
} |
q21433 | AnalysisRequestAddView.get_service_categories | train | def get_service_categories(self, restricted=True):
"""Return all service categories in the right order
:param restricted: Client settings restrict categories
:type restricted: bool
:returns: Category catalog results
:rtype: brains
"""
bsc = api.get_tool("bika_setup_catalog")
query = {
"portal_type": "AnalysisCategory",
"is_active": True,
"sort_on": "sortable_title",
}
categories = bsc(query)
client = self.get_client()
if client and restricted:
| python | {
"resource": ""
} |
q21434 | AnalysisRequestAddView.get_services | train | def get_services(self, poc="lab"):
"""Return all Services
:param poc: Point of capture (lab/field)
:type poc: string
:returns: Mapping of category -> list of services
:rtype: dict
"""
bsc = api.get_tool("bika_setup_catalog")
query = {
"portal_type": "AnalysisService",
"getPointOfCapture": poc,
"is_active": True,
"sort_on": "sortable_title",
}
services = bsc(query)
categories = self.get_service_categories(restricted=False)
analyses = {key: [] for | python | {
"resource": ""
} |
q21435 | AnalysisRequestAddView.get_service_uid_from | train | def get_service_uid_from(self, analysis):
"""Return the service from the analysis
"""
analysis | python | {
"resource": ""
} |
q21436 | AnalysisRequestAddView.is_service_selected | train | def is_service_selected(self, service):
"""Checks if the given service is selected by one of the ARs.
This is used to make the whole line visible or not.
"""
service_uid = api.get_uid(service)
for arnum in range(self.ar_count):
analyses = self.fieldvalues.get("Analyses-{}".format(arnum))
| python | {
"resource": ""
} |
q21437 | AnalysisRequestManageView.get_sorted_fields | train | def get_sorted_fields(self):
"""Return the sorted fields
"""
inf = float("inf")
order = self.get_field_order()
def field_cmp(field1, field2):
_n1 = field1.getName()
_n2 = field2.getName()
| python | {
"resource": ""
} |
q21438 | AnalysisRequestManageView.get_fields_with_visibility | train | def get_fields_with_visibility(self, visibility="edit", mode="add"):
"""Return the fields with visibility
"""
fields = self.get_sorted_fields()
out = []
for field in fields:
v = field.widget.isVisible(
self.context, mode, default='invisible', field=field)
if self.is_field_visible(field) is False:
v = "hidden"
visibility_guard = True
# visibility_guard is a widget field defined in the schema in order
# to know the visibility of the widget when the field is related to
# a dynamically changing content such as workflows. For | python | {
"resource": ""
} |
q21439 | ajaxAnalysisRequestAddView.to_iso_date | train | def to_iso_date(self, dt):
"""Return the ISO representation of a date object
"""
if dt is None:
return ""
if isinstance(dt, DateTime):
return dt.ISO8601()
if isinstance(dt, datetime):
| python | {
"resource": ""
} |
q21440 | ajaxAnalysisRequestAddView.get_records | train | def get_records(self):
"""Returns a list of AR records
Fields coming from `request.form` have a number prefix, e.g. Contact-0.
Fields with the same suffix number are grouped together in a record.
Each record represents the data for one column in the AR Add form and
contains a mapping of the fieldName (w/o prefix) -> value.
Example:
[{"Contact": "Rita Mohale", ...}, {Contact: "Neil Standard"} ...]
"""
form = self.request.form
ar_count = self.get_ar_count()
records = []
# Group belonging AR fields together
for | python | {
"resource": ""
} |
q21441 | ajaxAnalysisRequestAddView.get_uids_from_record | train | def get_uids_from_record(self, record, key):
"""Returns a list of parsed UIDs from a single form field identified by
the given key.
A form field ending with `_uid` can contain an empty value, a
single UID or multiple UIDs separated by a comma.
This method parses the UID value and returns a list of non-empty UIDs.
| python | {
"resource": ""
} |
q21442 | ajaxAnalysisRequestAddView.get_objs_from_record | train | def get_objs_from_record(self, record, key):
"""Returns a mapping of UID -> object
"""
uids = self.get_uids_from_record(record, key)
| python | {
"resource": ""
} |
q21443 | ajaxAnalysisRequestAddView.get_base_info | train | def get_base_info(self, obj):
"""Returns the base info of an object
"""
if obj is None:
return {}
info = {
"id": obj.getId(),
"uid": obj.UID(),
| python | {
"resource": ""
} |
q21444 | ajaxAnalysisRequestAddView.get_service_info | train | def get_service_info(self, obj):
"""Returns the info for a Service
"""
info = self.get_base_info(obj)
info.update({
"short_title": obj.getShortTitle(),
"scientific_name": obj.getScientificName(),
"unit": obj.getUnit(),
"keyword": obj.getKeyword(),
"methods": map(self.get_method_info, obj.getMethods()),
"calculation": self.get_calculation_info(obj.getCalculation()),
"price": obj.getPrice(),
| python | {
"resource": ""
} |
q21445 | ajaxAnalysisRequestAddView.get_template_info | train | def get_template_info(self, obj):
"""Returns the info for a Template
"""
client = self.get_client()
client_uid = api.get_uid(client) if client else ""
profile = obj.getAnalysisProfile()
profile_uid = api.get_uid(profile) if profile else ""
profile_title = profile.Title() if profile else ""
sample_type = obj.getSampleType()
sample_type_uid = api.get_uid(sample_type) if sample_type else ""
sample_type_title = sample_type.Title() if sample_type else ""
sample_point = obj.getSamplePoint()
sample_point_uid = api.get_uid(sample_point) if sample_point else ""
sample_point_title = sample_point.Title() if sample_point else ""
| python | {
"resource": ""
} |
q21446 | ajaxAnalysisRequestAddView.get_profile_info | train | def get_profile_info(self, obj):
"""Returns the info for a Profile
"""
info | python | {
"resource": ""
} |
q21447 | ajaxAnalysisRequestAddView.get_method_info | train | def get_method_info(self, obj):
"""Returns the info for a Method
"""
info | python | {
"resource": ""
} |
q21448 | ajaxAnalysisRequestAddView.get_calculation_info | train | def get_calculation_info(self, obj):
"""Returns the info for a Calculation
"""
| python | {
"resource": ""
} |
q21449 | ajaxAnalysisRequestAddView.get_sampletype_info | train | def get_sampletype_info(self, obj):
"""Returns the info for a Sample Type
"""
info = self.get_base_info(obj)
# Bika Setup folder
bika_setup = api.get_bika_setup()
# bika samplepoints
bika_samplepoints = bika_setup.bika_samplepoints
bika_samplepoints_uid = api.get_uid(bika_samplepoints)
# bika analysisspecs
bika_analysisspecs = bika_setup.bika_analysisspecs
bika_analysisspecs_uid = api.get_uid(bika_analysisspecs)
# client
client = self.get_client()
client_uid = client and api.get_uid(client) or ""
# sample matrix
sample_matrix = obj.getSampleMatrix()
sample_matrix_uid = sample_matrix and sample_matrix.UID() or ""
sample_matrix_title = sample_matrix and sample_matrix.Title() or ""
# container type
container_type = obj.getContainerType()
container_type_uid = container_type and container_type.UID() or ""
container_type_title = container_type and container_type.Title() or ""
# sample points
sample_points = obj.getSamplePoints()
sample_point_uids = map(lambda sp: sp.UID(), sample_points)
sample_point_titles = map(lambda sp: sp.Title(), sample_points)
info.update({
"prefix": obj.getPrefix(),
"minimum_volume": obj.getMinimumVolume(),
"hazardous": obj.getHazardous(),
"retention_period": obj.getRetentionPeriod(),
| python | {
"resource": ""
} |
q21450 | ajaxAnalysisRequestAddView.get_sample_info | train | def get_sample_info(self, obj):
"""Returns the info for a Sample
"""
info = self.get_base_info(obj)
# sample type
sample_type = obj.getSampleType()
sample_type_uid = sample_type and sample_type.UID() or ""
sample_type_title = sample_type and sample_type.Title() or ""
# sample condition
sample_condition = obj.getSampleCondition()
sample_condition_uid = sample_condition \
and sample_condition.UID() or ""
sample_condition_title = sample_condition \
and sample_condition.Title() or ""
# storage location
storage_location = obj.getStorageLocation()
storage_location_uid = storage_location \
and storage_location.UID() or ""
storage_location_title = storage_location \
and storage_location.Title() or ""
# sample point
sample_point = obj.getSamplePoint()
sample_point_uid = sample_point and sample_point.UID() or ""
sample_point_title = sample_point and sample_point.Title() or ""
# container type
container_type = sample_type and sample_type.getContainerType() or None
container_type_uid = container_type and container_type.UID() or ""
container_type_title = container_type and container_type.Title() or ""
# Sampling deviation
deviation = obj.getSamplingDeviation()
deviation_uid = deviation and deviation.UID() or ""
deviation_title = deviation and deviation.Title() or ""
info.update({
"sample_id": obj.getId(),
"batch_uid": obj.getBatchUID() or None,
"date_sampled": self.to_iso_date(obj.getDateSampled()),
"sampling_date": self.to_iso_date(obj.getSamplingDate()),
| python | {
"resource": ""
} |
q21451 | ajaxAnalysisRequestAddView.get_specification_info | train | def get_specification_info(self, obj):
"""Returns the info for a Specification
"""
info = self.get_base_info(obj)
results_range = obj.getResultsRange()
info.update({
"results_range": results_range,
"sample_type_uid": obj.getSampleTypeUID(),
"sample_type_title": obj.getSampleTypeTitle(),
"client_uid": obj.getClientUID(),
})
bsc = api.get_tool("bika_setup_catalog")
def get_service_by_keyword(keyword):
if keyword is None:
return []
return map(api.get_object, bsc({
"portal_type": "AnalysisService",
"getKeyword": keyword
}))
# append a mapping of service_uid -> specification
specifications = {}
for spec in results_range:
service_uid = spec.get("uid")
if service_uid is None:
| python | {
"resource": ""
} |
q21452 | ajaxAnalysisRequestAddView.get_container_info | train | def get_container_info(self, obj):
"""Returns the info for a Container
"""
info | python | {
"resource": ""
} |
q21453 | ajaxAnalysisRequestAddView.get_preservation_info | train | def get_preservation_info(self, obj):
"""Returns the info for a Preservation
"""
| python | {
"resource": ""
} |
q21454 | ajaxAnalysisRequestAddView.ajax_get_service | train | def ajax_get_service(self):
"""Returns the services information
"""
uid = self.request.form.get("uid", None)
if uid is None:
| python | {
"resource": ""
} |
q21455 | ajaxAnalysisRequestAddView.ajax_recalculate_prices | train | def ajax_recalculate_prices(self):
"""Recalculate prices for all ARs
"""
# When the option "Include and display pricing information" in
# Bika Setup Accounting tab is not selected
if not self.show_recalculate_prices():
return {}
# The sorted records from the request
records = self.get_records()
client = self.get_client()
bika_setup = api.get_bika_setup()
member_discount = float(bika_setup.getMemberDiscount())
member_discount_applies = False
if client:
member_discount_applies = client.getMemberDiscountApplies()
prices = {}
for n, record in enumerate(records):
ardiscount_amount = 0.00
arservices_price = 0.00
arprofiles_price = 0.00
arprofiles_vat_amount = 0.00
arservice_vat_amount = 0.00
services_from_priced_profile = []
profile_uids = record.get("Profiles_uid", "").split(",")
profile_uids = filter(lambda x: x, profile_uids)
profiles = map(self.get_object_by_uid, profile_uids)
services = map(self.get_object_by_uid, record.get("Analyses", []))
# ANALYSIS PROFILES PRICE
for profile in profiles:
use_profile_price = profile.getUseAnalysisProfilePrice()
if not use_profile_price:
continue
profile_price = float(profile.getAnalysisProfilePrice())
arprofiles_price += profile_price
arprofiles_vat_amount += profile.getVATAmount()
profile_services = profile.getService()
services_from_priced_profile.extend(profile_services)
# ANALYSIS SERVICES PRICE
for service in services:
if service in services_from_priced_profile:
continue
service_price = float(service.getPrice())
# service_vat = float(service.getVAT())
service_vat_amount = float(service.getVATAmount())
| python | {
"resource": ""
} |
q21456 | GeneXpertParser._handle_header | train | def _handle_header(self, sline):
"""
A function for lines with only ONE COLUMN.
If line has only one column, then it is either a Section or
Subsection name.
"""
# All characters UPPER CASE means it is a Section.
if sline[0].isupper():
self._cur_section = sline[0]
self._cur_sub_section = ''
return 0
else:
self._cur_sub_section = sline[0]
if sline[0] == SUBSECTION_ANALYTE_RESULT:
# This is Analyte Result Line, next line will | python | {
"resource": ""
} |
q21457 | GeneXpertParser._submit_result | train | def _submit_result(self):
"""
Adding current values as a Raw Result and Resetting everything.
Notice that we are not calculating final result of assay. We just set
NP and GP values and in Bika, AS will have a Calculation to generate
final result based on NP and GP values.
"""
if self._cur_res_id and self._cur_values:
# Setting DefaultResult just because it is obligatory. However,
# it won't be used because AS must have a Calculation based on
# GP and NP results.
self._cur_values[self._keyword]['DefaultResult'] = 'DefResult'
| python | {
"resource": ""
} |
q21458 | GeneXpertParser._format_keyword | train | def _format_keyword(self, keyword):
"""
Removing special character from a keyword. Analysis Services must have
this kind of keywords. E.g. if assay name from GeneXpert Instrument is
| python | {
"resource": ""
} |
q21459 | ManageResultsView.get_instrument_title | train | def get_instrument_title(self):
"""Return the current instrument title
"""
instrument = self.context.getInstrument()
if | python | {
"resource": ""
} |
q21460 | ManageResultsView.is_assignment_allowed | train | def is_assignment_allowed(self):
"""Check if analyst assignment is allowed
"""
if not self.is_manage_allowed():
| python | {
"resource": ""
} |
q21461 | ManageResultsView.get_wide_interims | train | def get_wide_interims(self):
"""Returns a dictionary with the analyses services from the current
worksheet which have at least one interim with 'Wide' attribute set to
true and that have not been yet submitted
The structure of the returned dictionary is the following:
<Analysis_keyword>: {
'analysis': <Analysis_name>,
'keyword': <Analysis_keyword>,
'interims': {
<Interim_keyword>: {
'value': <Interim_default_value>,
'keyword': <Interim_key>,
'title': <Interim_title>
}
}
}
"""
outdict = {}
allowed_states = ['assigned', 'unassigned']
for analysis in self.context.getAnalyses():
# TODO Workflow - Analysis Use a query instead of this
if api.get_workflow_status_of(analysis) not in allowed_states:
continue
if analysis.getKeyword() in outdict.keys():
continue
calculation = analysis.getCalculation()
if not calculation:
continue
| python | {
"resource": ""
} |
q21462 | editableFields | train | def editableFields(self, instance, visible_only=False):
"""Returns a list of editable fields for the given instance
"""
ret = []
portal = getToolByName(instance, 'portal_url').getPortalObject()
for field in self.fields():
| python | {
"resource": ""
} |
q21463 | isVisible | train | def isVisible(self, instance, mode='view', default="visible", field=None):
"""decide if a field is visible in a given mode -> 'state'.
"""
# Emulate Products.Archetypes.Widget.TypesWidget#isVisible first
vis_dic = getattr(aq_base(self), 'visible', _marker)
state = default
if vis_dic is _marker:
return state
if type(vis_dic) is DictType:
state = vis_dic.get(mode, state)
elif not vis_dic:
state = 'invisible'
elif vis_dic < 0:
state = 'hidden'
# Our custom code starts here
if not field:
return state
# Look for visibility from the adapters provided by IATWidgetVisibility
adapters = sorted(getAdapters([instance], IATWidgetVisibility),
key=lambda adapter: getattr(adapter[1], "sort", 1000),
reverse=True) | python | {
"resource": ""
} |
q21464 | skip | train | def skip(instance, action, peek=False, unskip=False):
"""Returns True if the transition is to be SKIPPED
peek - True just checks the value, does not set.
unskip - remove skip key (for manual overrides).
called with only (instance, action_id), this will set the request variable preventing the
cascade's from re-transitioning the object and return None.
"""
uid = callable(instance.UID) and instance.UID() or instance.UID
skipkey = "%s_%s" % (uid, action)
if 'workflow_skiplist' not in instance.REQUEST:
if not peek and not unskip:
instance.REQUEST['workflow_skiplist'] = [skipkey, ]
else:
if skipkey | python | {
"resource": ""
} |
q21465 | call_workflow_event | train | def call_workflow_event(instance, event, after=True):
"""Calls the instance's workflow event
"""
if not event.transition:
return False
portal_type = instance.portal_type
wf_module = _load_wf_module('{}.events'.format(portal_type.lower()))
if not wf_module:
return False
# Inspect if event_<transition_id> function exists in the module
prefix = after and "after" or "before"
| python | {
"resource": ""
} |
q21466 | get_workflow_actions | train | def get_workflow_actions(obj):
""" Compile a list of possible workflow transitions for this object
"""
def translate(id):
return t(PMF(id + "_transition_title"))
transids | python | {
"resource": ""
} |
q21467 | get_review_history_statuses | train | def get_review_history_statuses(instance, reverse=False):
"""Returns a list with the statuses of the instance from | python | {
"resource": ""
} |
q21468 | get_prev_status_from_history | train | def get_prev_status_from_history(instance, status=None):
"""Returns the previous status of the object. If status is set, returns the
previous status before the object reached the status passed in.
If instance has reached the status passed in more than once, only the last
one is considered.
"""
target = status or api.get_workflow_status_of(instance)
history = getReviewHistory(instance, reverse=True)
| python | {
"resource": ""
} |
q21469 | in_state | train | def in_state(obj, states, stateflowid='review_state'):
""" Returns if the object passed matches with the states passed in
"""
if not states:
| python | {
"resource": ""
} |
q21470 | getTransitionDate | train | def getTransitionDate(obj, action_id, return_as_datetime=False):
"""
Returns date of action for object. Sometimes we need this date in Datetime
format and that's why added return_as_datetime param.
"""
review_history = getReviewHistory(obj)
for event in review_history:
if event.get('action') == action_id:
evtime = event.get('time')
if return_as_datetime:
return evtime
| python | {
"resource": ""
} |
q21471 | guard_handler | train | def guard_handler(instance, transition_id):
"""Generic workflow guard handler that returns true if the transition_id
passed in can be performed to the instance passed in.
This function is called automatically by a Script (Python) located at
bika/lims/skins/guard_handler.py, which in turn is fired by Zope when an
expression like "python:here.guard_handler('<transition_id>')" is set to
any given guard (used by default in all bika's DC Workflow guards).
Walks through bika.lims.workflow.<obj_type>.guards and looks for a function
that matches with 'guard_<transition_id>'. If found, calls the function and
returns its value (true or false). If not found, returns True by default.
:param instance: the object for which the transition_id has to be evaluated
:param transition_id: the id of the transition
:type instance: ATContentType
:type transition_id: string
:return: true if the transition can be performed to | python | {
"resource": ""
} |
q21472 | _load_wf_module | train | def _load_wf_module(module_relative_name):
"""Loads a python module based on the module relative name passed in.
At first, tries to get the module from sys.modules. If not found there, the
function tries to load it by using importlib. Returns None if no module
found or importlib is unable to load it because of errors.
Eg:
_load_wf_module('sample.events')
will try to load the module 'bika.lims.workflow.sample.events'
:param modrelname: relative name of the module to be loaded
:type modrelname: string
:return: the module
:rtype: module
"""
if not module_relative_name:
return None
if not isinstance(module_relative_name, basestring):
return None
rootmodname = __name__
modulekey = '{0}.{1}'.format(rootmodname, module_relative_name)
| python | {
"resource": ""
} |
q21473 | push_reindex_to_actions_pool | train | def push_reindex_to_actions_pool(obj, idxs=None):
"""Push a reindex job to the actions handler pool
"""
indexes = idxs and idxs or []
| python | {
"resource": ""
} |
q21474 | ActionHandlerPool.push | train | def push(self, instance, action, success, idxs=_marker):
"""Adds an instance into the pool, to be reindexed on resume
"""
| python | {
"resource": ""
} |
q21475 | ActionHandlerPool.succeed | train | def succeed(self, instance, action):
"""Returns if the task for the instance took place successfully
"""
| python | {
"resource": ""
} |
q21476 | ActionHandlerPool.resume | train | def resume(self):
"""Resumes the pool and reindex all objects processed
"""
self.num_calls -= 1
if self.num_calls > 0:
return
logger.info("Resume actions for {} objects".format(len(self)))
# Fetch the objects from the pool
processed = list()
for brain in api.search(dict(UID=self.objects.keys()), UID_CATALOG):
uid = api.get_uid(brain)
if uid in processed:
# This object has been processed already, do nothing
continue
# Reindex | python | {
"resource": ""
} |
q21477 | WorkflowMenu.getMenuItems | train | def getMenuItems(self, context, request):
"""Overrides the workflow actions menu displayed top right in the
object's view. Displays the current state of the object, as well as a
list with the actions that can be performed.
The option "Advanced.." is not displayed and the list is populated with
all allowed transitions for the object.
"""
| python | {
"resource": ""
} |
q21478 | WorkflowActionReceiveAdapter.is_auto_partition_required | train | def is_auto_partition_required(self, brain_or_object):
"""Returns whether the passed in object needs to be partitioned
"""
| python | {
"resource": ""
} |
q21479 | WorkflowActionInvalidateAdapter.notify_ar_retract | train | def notify_ar_retract(self, sample):
"""Sends an email notification to sample's client contact if the sample
passed in has a retest associated
"""
retest = sample.getRetest()
if not retest:
logger.warn("No retest found for {}. And it should!"
.format(api.get_id(sample)))
return
# Email fields
sample_id = api.get_id(sample)
subject = t(_("Erroneous result publication from {}").format(sample_id))
emails_lab = self.get_lab_managers_formatted_emails()
emails_sample = self.get_sample_contacts_formatted_emails(sample)
recipients = list(set(emails_lab + emails_sample))
msg = MIMEMultipart("related")
msg["Subject"] = subject
msg["From"] = self.get_laboratory_formatted_email()
msg["To"] = ", ".join(recipients)
body = self.get_email_body(sample)
| python | {
"resource": ""
} |
q21480 | WorkflowActionInvalidateAdapter.get_email_body | train | def get_email_body(self, sample):
"""Returns the email body text
"""
retest = sample.getRetest()
lab_address = api.get_bika_setup().laboratory.getPrintAddress()
setup = api.get_setup()
body = Template(setup.getEmailBodySampleInvalidation())\
.safe_substitute(
dict(sample_link=self.get_html_link(sample),
| python | {
"resource": ""
} |
q21481 | WorkflowActionInvalidateAdapter.get_laboratory_formatted_email | train | def get_laboratory_formatted_email(self):
"""Returns the laboratory email formatted
"""
lab | python | {
"resource": ""
} |
q21482 | WorkflowActionInvalidateAdapter.get_lab_managers_formatted_emails | train | def get_lab_managers_formatted_emails(self):
"""Returns a list with lab managers formatted emails
"""
users = api.get_users_by_roles("LabManager")
users = map(lambda user: (user.getProperty("fullname"),
| python | {
"resource": ""
} |
q21483 | WorkflowActionInvalidateAdapter.get_contact_formatted_email | train | def get_contact_formatted_email(self, contact):
"""Returns a string with the formatted email for the given contact
"""
contact_name | python | {
"resource": ""
} |
q21484 | WorkflowActionInvalidateAdapter.get_sample_contacts_formatted_emails | train | def get_sample_contacts_formatted_emails(self, sample):
"""Returns a list with the formatted emails from sample contacts
"""
| python | {
"resource": ""
} |
q21485 | WorkflowActionInvalidateAdapter.get_html_link | train | def get_html_link(self, obj):
"""Returns an html formatted link for the given object
"""
| python | {
"resource": ""
} |
q21486 | WorkflowActionPrintSampleAdapter.set_printed_time | train | def set_printed_time(self, sample):
"""Updates the printed time of the last results report from the sample
"""
if api.get_workflow_status_of(sample) != "published":
return False
reports = sample.objectValues("ARReport")
reports = sorted(reports, key=lambda report: report.getDatePublished())
last_report = reports[-1]
| python | {
"resource": ""
} |
q21487 | WorkflowActionSampleAdapter.set_sampler_info | train | def set_sampler_info(self, sample):
"""Updates the Sampler and the Sample Date with the values provided in
the request. If neither Sampler nor SampleDate are present in the
request, returns False
"""
if sample.getSampler() and sample.getDateSampled():
# Sampler and Date Sampled already set. This is correct
return True
sampler = self.get_form_value("Sampler", | python | {
"resource": ""
} |
q21488 | WorkflowActionPreserveAdapter.set_preserver_info | train | def set_preserver_info(self, sample):
"""Updates the Preserver and the Date Preserved with the values provided
in the request. If neither Preserver nor DatePreserved are present in
the request, returns False
"""
if sample.getPreserver() and sample.getDatePreserved():
# Preserver and Date Preserved already set. This is correct
return True
preserver = self.get_form_value("Preserver", sample,
| python | {
"resource": ""
} |
q21489 | WorkflowActionScheduleSamplingAdapter.set_sampling_info | train | def set_sampling_info(self, sample):
"""Updates the scheduled Sampling sampler and the Sampling Date with the
values provided in the request. If neither Sampling sampler nor Sampling
Date are present in the request, returns False
"""
if sample.getScheduledSamplingSampler() and sample.getSamplingDate():
return True
sampler = self.get_form_value("getScheduledSamplingSampler", sample,
sample.getScheduledSamplingSampler())
| python | {
"resource": ""
} |
q21490 | WorkflowActionSaveAnalysesAdapter.is_hidden | train | def is_hidden(self, service):
"""Returns whether the request Hidden param for the given obj is True
"""
uid | python | {
"resource": ""
} |
q21491 | WorkflowActionSaveAnalysesAdapter.get_specs | train | def get_specs(self, service):
"""Returns the analysis specs available in the request for the given uid
"""
uid = api.get_uid(service)
keyword = service.getKeyword()
specs = ResultsRangeDict(keyword=keyword, uid=uid).copy()
for key in specs.keys():
| python | {
"resource": ""
} |
q21492 | DefaultReferenceWidgetVocabulary.search_fields | train | def search_fields(self):
"""Returns the object field names to search against
"""
search_fields = self.request.get("search_fields", None)
if not search_fields:
| python | {
"resource": ""
} |
q21493 | DefaultReferenceWidgetVocabulary.search_term | train | def search_term(self):
"""Returns the search term
"""
search_term | python | {
"resource": ""
} |
q21494 | DefaultReferenceWidgetVocabulary.get_query_from_request | train | def get_query_from_request(self, name):
"""Returns the query inferred from the request
"""
query = self.request.get(name, "{}")
# json.loads does unicode conversion, which will fail in the catalog
# search | python | {
"resource": ""
} |
q21495 | DefaultReferenceWidgetVocabulary.get_raw_query | train | def get_raw_query(self):
"""Returns the raw query to use for current search, based on the
base query + update query
"""
query = self.base_query.copy()
search_query = self.search_query.copy()
query.update(search_query)
# Add sorting criteria
sorting = self.resolve_sorting(query)
query.update(sorting)
# Check if sort_on is an | python | {
"resource": ""
} |
q21496 | DefaultReferenceWidgetVocabulary.resolve_sorting | train | def resolve_sorting(self, query):
"""Resolves the sorting criteria for the given query
"""
sorting = {}
# Sort on
sort_on = query.get("sidx", None)
sort_on = sort_on or query.get("sort_on", None)
sort_on = sort_on == "Title" and "sortable_title" or sort_on
if sort_on:
sorting["sort_on"] = sort_on
# Sort order
sort_order = query.get("sord", None)
sort_order = sort_order or query.get("sort_order", None)
if sort_order in ["desc", "reverse", "rev", "descending"]:
| python | {
"resource": ""
} |
q21497 | DefaultReferenceWidgetVocabulary.is_sortable_index | train | def is_sortable_index(self, index_name, catalog):
"""Returns whether the index is sortable
"""
index = self.get_index(index_name, catalog)
| python | {
"resource": ""
} |
q21498 | DefaultReferenceWidgetVocabulary.get_index | train | def get_index(self, field_name, catalog):
"""Returns the index of the catalog for the given field_name, if any
"""
index = catalog.Indexes.get(field_name, None)
if not | python | {
"resource": ""
} |
q21499 | DefaultReferenceWidgetVocabulary.search | train | def search(self, query, search_term, search_field, catalog):
"""Performs a search against the catalog and returns the brains
"""
logger.info("Reference Widget Catalog: {}".format(catalog.id))
if not search_term:
return catalog(query)
index = self.get_index(search_field, catalog)
if not index:
logger.warn("*** Index not found: '{}'".format(search_field))
return []
meta = index.meta_type
if meta == "TextIndexNG3":
query[index.id] = "{}*".format(search_term)
elif meta == "ZCTextIndex":
logger.warn("*** Field '{}' ({}). Better use TextIndexNG3"
.format(meta, search_field)) | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.