Actions to be done when an analysis is added in an Analysis Request
174088
def ObjectInitializedEventHandler(analysis, event):
    

    # Initialize the analysis if it was e.g. added by Manage Analysis
    wf.doActionFor(analysis, "initialize")

    # Try to transition the analysis_request to "sample_received". There are
    # some cases that can end up with an inconsistent state between the AR
    # and the analyses it contains: retraction of an analysis when the state
    # of the AR was "to_be_verified", addition of a new analysis when the
    # state was "to_be_verified", etc.
    request = analysis.getRequest()
    wf.doActionFor(request, "rollback_to_receive")

    # Reindex the indexes for UIDReference fields on creation!
    analysis.reindexObject(idxs="getServiceUID")
    return
127055
def change_analysis_requests_id_formatting(portal, p_type="AnalysisRequest"):
    
    ar_id_format = dict(
        form='{sampleType}-{seq:04d}',
        portal_type='AnalysisRequest',
        prefix='analysisrequest',
        sequence_type='generated',
        counter_type='',
        split_length=1)

    bs = portal.bika_setup
    id_formatting = bs.getIDFormatting()
    ar_format = filter(lambda id: id["portal_type"] == p_type, id_formatting)
    if p_type=="AnalysisRequest":
        logger.info("Set ID Format for Analysis Request portal_type ...")
        if not ar_format or "sample" in ar_format[0]["form"]:
            # Copy the ID formatting set for Sample
            change_analysis_requests_id_formatting(portal, p_type="Sample")
            return
        else:
            logger.info("ID Format for Analysis Request already set: {} [SKIP]"
                        .format(ar_format[0]["form"]))
            return
    else:
        ar_format = ar_format and ar_format[0].copy() or ar_id_format

    # Set the Analysis Request ID Format
    ar_id_format.update(ar_format)
    ar_id_format["portal_type"] ="AnalysisRequest"
    ar_id_format["prefix"] = "analysisrequest"
    set_id_format(portal, ar_id_format)

    # Find out the last ID for Sample and reseed AR to prevent ID already taken
    # errors on AR creation
    if p_type == "Sample":
        number_generator = getUtility(INumberGenerator)
        ar_keys = dict()
        ar_keys_prev = dict()
        for key, value in number_generator.storage.items():
            if "sample-" in key:
                ar_key = key.replace("sample-", "analysisrequest-")
                ar_keys[ar_key] = api.to_int(value, 0)
            elif "analysisrequest-" in key:
                ar_keys_prev[key] = api.to_int(value, 0)

        for key, value in ar_keys.items():
            if key in ar_keys_prev:
                # Maybe this upgrade step has already been run, so we don't
                # want the ar IDs to be reseeded again!
                if value <= ar_keys_prev[key]:
                    logger.info("ID for '{}' already seeded to '{}' [SKIP]"
                                .format(key, ar_keys_prev[key]))
                    continue
            logger.info("Seeding {} to {}".format(key, value))
            number_generator.set_number(key, value)
1143434
def guard_cancel(analysis_request):
    
    # Ask to partitions
    for partition in analysis_request.getDescendants(all_descendants=False):
        if not isTransitionAllowed(partition, "cancel"):
            return False

    # Look through analyses. We've checked the partitions already, so there is
    # no need to look through analyses from partitions again, but through the
    # analyses directly bound to the current Analysis Request.
    cancellable_states = ["unassigned", "registered"]
    for analysis in analysis_request.objectValues("Analysis"):
        if api.get_workflow_status_of(analysis) not in cancellable_states:
            return False

    return True
1140234
def before_render(self):
        
        # If the current user is a client contact, display those analysis
        # requests that belong to same client only
        super(AnalysisRequestsView, self).before_render()
        client = api.get_current_client()
        if client:
            self.contentFilter['path'] = {
                "query": "/".join(client.getPhysicalPath()),
                "level": 0}
            # No need to display the Client column
            self.remove_column('Client')
1285652
def remove_not_requested_analyses_view(portal):
    
    logger.info("Removing 'Analyses not requested' view ...")
    ar_ptype = portal.portal_types.AnalysisRequest
    ar_ptype._actions = filter(lambda act: act.id != "analyses_not_requested",
                               ar_ptype.listActions())
601791
function checkAnalytics() {
  if (_enableCheck && typeof window[_gaGlobal] === 'function') {
    for (var i = 0; i < _analyticsQueue.length; i++) {
      _analyticsQueue[i].call();
    }

    // override push to execute the command immediately from now on
    _analyticsQueue.push = function (fn) {
      fn.call();
    };

    // turn check into NOOP
    _enableCheck = false;
  }

  utils.logMessage('event count sent to GA: ' + _eventCount);
}
1205046
def guard_rollback_to_receive(analysis_request):
    
    skipped = 0
    valid_states = ['unassigned', 'assigned']
    skip_states = ['retracted', 'rejected']
    analyses = analysis_request.getAnalyses()
    for analysis in analyses:
        analysis = api.get_object(analysis)
        status = api.get_workflow_status_of(analysis)
        if status in valid_states:
            return True
        elif status in skip_states:
            skipped += 1
    return len(analyses) == skipped
1093759
public void analyze(Analyzer analyzer, boolean allowFlow)
    throws Exception
  {
    _pendingTargets = new IntArray();
    _completedTargets = new IntArray();
    
    analyzeImpl(analyzer, allowFlow, _pendingTargets, _completedTargets);
  }
1050940
def getAnalysisRequestsBrains(self, **kwargs):
        
        kwargs['getBatchUID'] = self.UID()
        catalog = getToolByName(self, CATALOG_ANALYSIS_REQUEST_LISTING)
        brains = catalog(kwargs)
        return brains
785719
def analyze(self):
        
        key = '/library/sections/%s/analyze' % self.key
        self._server.query(key, method=self._server._session.put)
1034026
function analyze (actions) {
  if (!Array.isArray(actions)) {
    throw new Error('State: Signal actions should be array');
  }

  actions.forEach((action, index) => {
    if (typeof action === 'undefined' || typeof action === 'string') {
      throw new Error(
        `
            State: Action number "${index}" in signal does not exist.
            Check that you have spelled it correctly!
          `
      );
    }

    if (Array.isArray(action)) {
      analyze(action);
    } else if (Object.prototype.toString.call(action) === "[object Object]") {
      Object.keys(action).forEach(function (output) {
        analyze(action[output]);
      });
    }
  });
}
66071
@Whitelisted
    public List<Action> getStaticAnalysisActions() {
        if (isPluginInstalled("analysis-core")) {
            return new StaticAnalysisUtilities().getActions(build);
        } else {
            return Collections.emptyList();
        }
    }
26188
def action_add(self):
        

        form = self.request.form
        parent = api.get_parent(self.context)
        attachment_file = form.get('AttachmentFile_file', None)
        AttachmentType = form.get('AttachmentType', '')
        AttachmentKeys = form.get('AttachmentKeys', '')
        ReportOption = form.get('ReportOption', 'r')

        # nothing to do if the attachment file is missing
        if attachment_file is None:
            logger.warn("AttachmentView.action_add_attachment: Attachment file is missing")
            return

        # create attachment
        attachment = self.create_attachment(
            parent,
            attachment_file,
            AttachmentType=AttachmentType,
            AttachmentKeys=AttachmentKeys,
            ReportOption=ReportOption)

        # append the new UID to the end of the current order
        self.set_attachments_order(api.get_uid(attachment))

        # handle analysis attachment
        analysis_uid = form.get("Analysis", None)
        if analysis_uid:
            analysis = api.get_object_by_uid(analysis_uid)
            others = analysis.getAttachment()
            attachments = []
            for other in others:
                attachments.append(other.UID())
            attachments.append(attachment.UID())
            analysis.setAttachment(attachments)
            # The metadata for getAttachmentUIDs need to get updated,
            # otherwise the attachments are not displayed
            # https://github.com/senaite/bika.lims/issues/521
            analysis.reindexObject()

        else:
            others = self.context.getAttachment()
            attachments = []
            for other in others:
                attachments.append(other.UID())
            attachments.append(attachment.UID())

            self.context.setAttachment(attachments)

        if self.request['HTTP_REFERER'].endswith('manage_results'):
            self.request.response.redirect('{}/manage_results'.format(
                self.context.absolute_url()))
        else:
            self.request.response.redirect(self.context.absolute_url())
1355982
def analyze_script(self, index=None):
        """"""
        if self.is_analysis_done:
            return
        if index is None:
            index = self.get_stack_index()
        if self.data:
            finfo = self.data[index]
            if self.todolist_enabled:
                finfo.run_todo_finder()
        self.is_analysis_done = True
1222650
public void addAnalyzer(CmsSearchAnalyzer analyzer) {

        m_analyzers.put(analyzer.getLocale(), analyzer);

        if (CmsLog.INIT.isInfoEnabled()) {
            CmsLog.INIT.info(
                Messages.get().getBundle().key(
                    Messages.INIT_ADD_ANALYZER_2,
                    analyzer.getLocale(),
                    analyzer.getClassName()));
        }
    }
647393
def analyse(self, demand_item, demand_item_code):
        
        my_analysis = Bw2Analysis(self)
        self.result_set = my_analysis.run_analyses(demand_item, demand_item_code, **self.analysis_settings)

        return True
697233
def _keep_analyses( analyses, keep_forms, target_forms ):
    '''  '''
    to_delete = []
    for aid, analysis in enumerate(analyses):
        delete = False
        for target in target_forms:
            if (target == analysis[FORM] and not analysis[FORM] in keep_forms):
               delete = True
        if delete:
            to_delete.append( aid )
    if to_delete:
       to_delete.reverse()
       for aid in to_delete:
           del analyses[aid]