Walks through open worksheets and transition them to 'verified' or
    'to_be_verified' if all their analyses are not in an open status
329570
def fix_worksheet_status_inconsistencies(portal):
    
    logger.info("Fixing worksheet inconsistencies ...")
    query = dict(portal_type="Worksheet",
                 review_state=["open", "to_be_verified"])
    brains = api.search(query, CATALOG_WORKSHEET_LISTING)
    total = len(brains)
    for num, brain in enumerate(brains):
        success = False
        if num % 100 == 0:
            logger.info("Fixing worksheet inconsistencies: {}/{}"
                        .format(num, total))
        # Note we don't check anything, WS guards for "submit" and "verify"
        # will take care of checking if the status of contained analyses allows
        # the transition.
        worksheet = api.get_object(brain)
        if api.get_workflow_status_of(worksheet) == "open":
            success, msg = do_action_for(worksheet, "submit")
        elif api.get_workflow_status_of(worksheet) == "to_be_verified":
            success, msg = do_action_for(worksheet, "verify")

        if success:
            logger.info("Worksheet {} transitioned to 'to_be_verified'"
                        .format(worksheet.getId()))
            success, msg = do_action_for(worksheet, "verify")
            if success:
                logger.info("Worksheet {} transitioned to 'verified'"
                            .format(worksheet.getId()))
    commit_transaction(portal)
1129862
def _check_interpret_cell(self, cell, prior_cell, row_index, column_index):
        '''
        
        '''
        changed = False
        if (not is_empty_cell(cell) and
            not is_text_cell(cell)):
            self.flag_change(self.flags, 'interpreted', (row_index, column_index),
                             self.worksheet, self.FLAGS['converted-to-string'])
            cell = str(cell)
            changed = True
        # If we find a blank cell, propagate the prior title
        elif is_empty_cell(cell):
            self.flag_change(self.flags, 'interpreted', (row_index, column_index),
                             self.worksheet, self.FLAGS['copied-title'])
            cell = prior_cell
            changed = True
        return cell, changed
1161195
def verify(self):
        
        collections = self.get_data_collections()

        allIDs = []
        for coll in collections:
            IDs = self.noteDB[coll].find({"ID": {"$exists": True}},
                                         {"ID": 1, "_id": 0})
            for ID in IDs:
                allIDs.append(int(ID["ID"]))

        query = {"currentMax": {"$exists": True}}
        maxID = int(self.noteDB['IDs'].find_one(query)["currentMax"])
        query = {"unusedIDs": {"$exists": True}}
        unusedIDs = self.noteDB['IDs'].find_one(query)["unusedIDs"]
        unusedIDs = [int(ii) for ii in unusedIDs]

        unusedIDsMatch = True
        for ID in allIDs:
            if ID in unusedIDs:
                unusedIDsMatch = False

        maxIDMatch = True
        if maxID is not max(allIDs):
            maxIDMatch = False

        if maxIDMatch and unusedIDsMatch:
            print "Database is valid"
        elif not maxIDMatch and not unusedIDsMatch:
            print "Database not valid, max ID and unused IDs are incorrent"
        elif not maxIDMatch:
            print "Database not valid, max ID is incorrent"
        elif not unusedIDsMatch:
            print "Database not valid, unusedIDs is incorrent"
231399
def guard_assign(analysis):
    
    # Only if the request was done from worksheet context.
    if not is_worksheet_context():
        return False

    # Cannot assign if the Sample has not been received
    if not analysis.isSampleReceived():
        return False

    # Cannot assign if the analysis has a worksheet assigned already
    if analysis.getWorksheet():
        return False

    # Cannot assign if user does not have permissions to manage worksheets
    return user_can_manage_worksheets()
437030
def _open_sheet(self):
        
        if self.sheet_name and not self.header:
            self._sheet = self._file.worksheet(self.sheet_name.title)
            self.ncols = self._sheet.col_count
            self.nrows = self._sheet.row_count
            for i in range(1, self.ncols+1):
                self.header = self.header + [self._sheet.cell(1, i).value]
1263970
def verify(self, otp, for_time=None, valid_window=0):
        
        if for_time is None:
            for_time = datetime.datetime.now()

        if valid_window:
            for i in range(-valid_window, valid_window + 1):
                if utils.strings_equal(str(otp), str(self.at(for_time, i))):
                    return True
            return False

        return utils.strings_equal(str(otp), str(self.at(for_time)))
261597
def is_analysis_attachment_allowed(self, analysis):
        
        if analysis.getAttachmentOption() not in ["p", "r"]:
            return False
        if api.get_workflow_status_of(analysis) in ["retracted"]:
            return False
        return True
103558
def __check_file_status(self, index):
        """"""
        if self.__file_status_flag:
            # Avoid infinite loop: when the QMessageBox.question pops, it
            # gets focus and then give it back to the CodeEditor instance,
            # triggering a refresh cycle which calls this method
            return
        self.__file_status_flag = True

        finfo = self.data[index]
        name = osp.basename(finfo.filename)

        if finfo.newly_created:
            # File was just created (not yet saved): do nothing
            # (do not return because of the clean-up at the end of the method)
            pass

        elif not osp.isfile(finfo.filename):
            # File doesn't exist (removed, moved or offline):
            self.msgbox = QMessageBox(
                    QMessageBox.Warning,
                    self.title,
                    _("<b>%s</b> is unavailable "
                      "(this file may have been removed, moved "
                      "or renamed outside Spyder)."
                      "<br>Do you want to close it?") % name,
                    QMessageBox.Yes | QMessageBox.No,
                    self)
            answer = self.msgbox.exec_()
            if answer == QMessageBox.Yes:
                self.close_file(index)
            else:
                finfo.newly_created = True
                finfo.editor.document().setModified(True)
                self.modification_changed(index=index)

        else:
            # Else, testing if it has been modified elsewhere:
            lastm = QFileInfo(finfo.filename).lastModified()
            if to_text_string(lastm.toString()) \
               != to_text_string(finfo.lastmodified.toString()):
                if finfo.editor.document().isModified():
                    self.msgbox = QMessageBox(
                        QMessageBox.Question,
                        self.title,
                        _("<b>%s</b> has been modified outside Spyder."
                          "<br>Do you want to reload it and lose all "
                          "your changes?") % name,
                        QMessageBox.Yes | QMessageBox.No,
                        self)
                    answer = self.msgbox.exec_()
                    if answer == QMessageBox.Yes:
                        self.reload(index)
                    else:
                        finfo.lastmodified = lastm
                else:
                    self.reload(index)

        # Finally, resetting temporary flag:
        self.__file_status_flag = False
238004
def get_worksheets_section(self):
        
        out = []
        bc = getToolByName(self.context, CATALOG_WORKSHEET_LISTING)
        query = {'portal_type': "Worksheet", }

        # Check if dashboard_cookie contains any values to query
        # elements by
        query = self._update_criteria_with_filters(query, 'worksheets')

        # Active Worksheets (all)
        total = self.search_count(query, bc.id)

        # Open worksheets
        name = _('Results pending')
        desc = _('Results pending')
        purl = 'worksheets?list_review_state=open'
        query['review_state'] = ['open', 'attachment_due']
        out.append(self._getStatistics(name, desc, purl, bc, query, total))

        # Worksheets to be verified
        name = _('To be verified')
        desc = _('To be verified')
        purl = 'worksheets?list_review_state=to_be_verified'
        query['review_state'] = ['to_be_verified', ]
        out.append(self._getStatistics(name, desc, purl, bc, query, total))

        # Worksheets verified
        name = _('Verified')
        desc = _('Verified')
        purl = 'worksheets?list_review_state=verified'
        query['review_state'] = ['verified', ]
        out.append(self._getStatistics(name, desc, purl, bc, query, total))

        # Chart with the evolution of WSs over a period, grouped by
        # periodicity
        outevo = self.fill_dates_evo(bc, query)
        out.append({'type':         'bar-chart-panel',
                    'name':         _('Evolution of Worksheets'),
                    'class':        'informative',
                    'description':  _('Evolution of Worksheets'),
                    'data':         json.dumps(outevo),
                    'datacolors':   json.dumps(self.get_colors_palette())})

        return {'id': 'worksheets',
                'title': _('Worksheets'),
                'panels': out}
255838
def _mod_run_check(cmd_kwargs, onlyif, unless):
    '''
    
    '''
    if onlyif:
        if __salt__['cmd.retcode'](onlyif, **cmd_kwargs) != 0:
            return {'comment': 'onlyif condition is false',
                    'skip_watch': True,
                    'result': True}

    if unless:
        if __salt__['cmd.retcode'](unless, **cmd_kwargs) == 0:
            return {'comment': 'unless condition is true',
                    'skip_watch': True,
                    'result': True}

    # No reason to stop, return True
    return True
795579
def before_reject(analysis):
    
    worksheet = analysis.getWorksheet()
    if not worksheet:
        return

    # Rejection of a routine analysis causes the removal of their duplicates
    for dup in worksheet.get_duplicates_for(analysis):
        doActionFor(dup, "unassign")
428565
def after_reject(analysis):
    """"""
    # Remove from the worksheet
    remove_analysis_from_worksheet(analysis)

    # Reject our dependents (analyses that depend on this analysis)
    cascade_to_dependents(analysis, "reject")

    if IRequestAnalysis.providedBy(analysis):
        # Try verify (for when remaining analyses are in 'verified')
        doActionFor(analysis.getRequest(), "verify")

        # Try submit (remaining analyses are in 'to_be_verified')
        doActionFor(analysis.getRequest(), "submit")

        # Try rollback (no remaining analyses or some not submitted)
        doActionFor(analysis.getRequest(), "rollback_to_receive")
        reindex_request(analysis)
1334033
def _verify(function):
    """"""
    # @functools.wraps
    def wrapped(pin, *args, **kwargs):
        pin = int(pin)
        if pin not in _open:
            ppath = gpiopath(pin)
            if not os.path.exists(ppath):
                log.debug("Creating Pin {0}".format(pin))
                with _export_lock:
                    with open(pjoin(gpio_root, 'export'), 'w') as f:
                        _write(f, pin)
            value = open(pjoin(ppath, 'value'), FMODE)
            direction = open(pjoin(ppath, 'direction'), FMODE)
            _open[pin] = PinState(value=value, direction=direction)
        return function(pin, *args, **kwargs)
    return wrapped
1358692
def _validate_rows(self):
        '''
        
        '''
        for row_index in range(self.start[0], self.end[0]):
            table_row = self.table[row_index]
            used_row = self.used_cells[row_index]

            row_type = None
            if self.end[1] > self.start[1]:
                row_type = get_cell_type(table_row[self.start[1]])

            num_type_changes = 0
            for column_index in range(self.start[1], self.end[1]):
                if used_row[column_index]:
                    self.flag_change(self.flags, 'error', (row_index, column_index),
                                     self.worksheet, self.FLAGS['used'])
                if not check_cell_type(table_row[column_index], row_type):
                    row_type = get_cell_type(table_row[column_index])
                    num_type_changes += 1
                if num_type_changes > 1:
                    self.flag_change(self.flags, 'warning', (row_index, column_index-1),
                                     self.worksheet, self.FLAGS['unexpected-change'])
                    # Decrement this to catch other cells which change again
                    num_type_changes -= 1
                # Mark this cell as used
                used_row[column_index] = True
1104454
def detect_worksheets(archive):
    """"""
    # content types has a list of paths but no titles
    # workbook has a list of titles and relIds but no paths
    # workbook_rels has a list of relIds and paths but no titles
    # rels = {'id':{'title':'', 'path':''} }
    content_types = read_content_types(archive)
    valid_sheets = dict((path, ct) for ct, path in content_types if ct == WORKSHEET_TYPE)
    rels = dict(read_rels(archive))
    for sheet in read_sheets(archive):
        rel = rels[sheet['id']]
        rel['title'] = sheet['name']
        rel['sheet_id'] = sheet['sheetId']
        rel['state'] = sheet.get('state', 'visible')
        if ("/" + rel['path'] in valid_sheets
            or "worksheets" in rel['path']): # fallback in case content type is missing
            yield rel
477608
def verify_all(num):
    

    # Define various problem statuses
    keys = ('correct', 'incorrect', 'error', 'skipped', 'missing')
    symbols = ('C', 'I', 'E', 'S', '.')
    colours = ('green', 'red', 'yellow', 'cyan', 'white')

    status = OrderedDict(
        (key, click.style(symbol, fg=colour, bold=True))
        for key, symbol, colour in zip(keys, symbols, colours)
    )

    overview = {}

    # Search through problem files using glob module
    files = problem_glob()

    # No Project Euler files in the current directory
    if not files:
        click.echo("No Project Euler files found in the current directory.")
        sys.exit(1)

    for file in files:
        # Catch KeyboardInterrupt during verification to allow the user to
        # skip the verification of a specific problem if it takes too long
        try:
            is_correct = verify(file.num, filename=str(file), exit=False)
        except KeyboardInterrupt:
            overview[file.num] = status['skipped']
        else:
            if is_correct is None:  # error was returned by problem file
                overview[file.num] = status['error']
            elif is_correct:
                overview[file.num] = status['correct']
            elif not is_correct:
                overview[file.num] = status['incorrect']

                # Attempt to add "skipped" suffix to the filename if the
                # problem file is not the current problem. This is useful
                # when the --verify-all is used in a directory containing
                # files generated pre-v1.1 (before files with suffixes)
                if file.num != num:
                    file.change_suffix('-skipped')

        # Separate each verification with a newline
        click.echo()

    # Print overview of the status of each problem
    legend = ', '.join('{} = {}'.format(v, k) for k, v in status.items())

    click.echo('-' * 63)
    click.echo(legend + '\n')

    # Rows needed for overview is based on the current problem number
    num_of_rows = (num + 19) // 20

    for row in range(1, num_of_rows + 1):
        low, high = (row * 20) - 19, (row * 20)
        click.echo("Problems {:03d}-{:03d}: ".format(low, high), nl=False)

        for problem in range(low, high + 1):
            # Add missing status to problems with no corresponding file
            status = overview[problem] if problem in overview else '.'

            # Separate problem indicators into groups of 5
            spacer = '   ' if (problem % 5 == 0) else ' '

            # Start a new line at the end of each row
            click.secho(status + spacer, nl=(problem % 20 == 0))

    click.echo()
492398
def is_submitted_or_submittable(analysis):
    
    if ISubmitted.providedBy(analysis):
        return True
    if wf.isTransitionAllowed(analysis, "submit"):
        return True
    return False