Figure out the sections in drbdadm status
312
def _analyse_status_type(line):
    '''
    
    '''
    spaces = _count_spaces_startswith(line)

    if spaces is None:
        return ''

    switch = {
        0: 'RESOURCE',
        2: {' disk:': 'LOCALDISK', ' role:': 'PEERNODE', ' connection:': 'PEERNODE'},
        4: {' peer-disk:': 'PEERDISK'}
    }

    ret = switch.get(spaces, 'UNKNOWN')

    # isinstance(ret, str) only works when run directly, calling need unicode(six)
    if isinstance(ret, six.text_type):
        return ret

    for x in ret:
        if x in line:
            return ret[x]

    return 'UNKNOWN'
311652
def get_d1str(self, goobj, reverse=False):
        """"""
        return "".join(sorted(self.get_parents_letters(goobj), reverse=reverse))
814040
def _update_control_section(self):
        
        self.control_data.npar = self.npar
        self.control_data.nobs = self.nobs
        self.control_data.npargp = self.parameter_groups.shape[0]
        self.control_data.nobsgp = self.observation_data.obgnme.\
            value_counts().shape[0] + self.prior_information.obgnme.\
            value_counts().shape[0]

        self.control_data.nprior = self.prior_information.shape[0]
        self.control_data.ntplfle = len(self.template_files)
        self.control_data.ninsfle = len(self.instruction_files)
        self.control_data.numcom = len(self.model_command)
326682
def _algo_check_for_section_problems(self, ro_rw_zi):
        """"""
        s_ro, s_rw, s_zi = ro_rw_zi
        if s_ro is None:
            return "RO section is missing"
        if s_rw is None:
            return "RW section is missing"
        if s_zi is None:
            return "ZI section is missing"
        if s_ro.start != 0:
            return "RO section does not start at address 0"
        if s_ro.start + s_ro.length != s_rw.start:
            return "RW section does not follow RO section"
        if s_rw.start + s_rw.length != s_zi.start:
            return "ZI section does not follow RW section"
        return None
1337964
def pdb(self):
        """"""
        header_title = '{:<80}\n'.format('HEADER    {}'.format(self.id))
        data_type = '{:<80}\n'.format('EXPDTA    ISAMBARD Model')
        pdb_strs = []
        for ampal in self:
            if isinstance(ampal, Assembly):
                pdb_str = ampal.make_pdb(header=False, footer=False)
            else:
                pdb_str = ampal.make_pdb()
            pdb_strs.append(pdb_str)
        merged_strs = 'ENDMDL\n'.join(pdb_strs) + 'ENDMDL\n'
        merged_pdb = ''.join([header_title, data_type, merged_strs])
        return merged_pdb
919838
def generate_sections(self):
        """"""
        sources = Dataset.objects.values(
            'source', 'source_slug'
        ).annotate(source_count=Count('source_slug'))

        return sorted([
            {
                'slug': source['source_slug'],
                'name': source['source'],
                'count': source['source_count']
            }
            for source in sources
        ], key=lambda k: k['count'], reverse=True)
38223
def list_sections(self):
        """"""
        if not os.path.exists(self._full_base):
            return []
        return [
            name for name in os.listdir(self._full_base)
            if os.path.isdir(os.path.join(self._full_base, name))
        ]
128179
function(resp){

	// Who was this?
	var qval = resp.parameter('q');
	var two_part = bbop.first_split(':', qval);
	var acc = bbop.dequote(two_part[1]);
	ll(' Looking at info for: ' + acc);
	term_info[acc] = {
	    id : acc,
	    name: acc,
	    source : 'n/a',
	    index : term_user_order[acc]
	};

	// Dig out names and the like.
	var doc = resp.get_doc(0);
	if( doc ){
	    term_info[acc]['name'] = doc['annotation_class_label'];
	    term_info[acc]['source'] = doc['source'];
	}

    }
776761
def get_nts_sections(self, sections, sortby=None):
        """"""
        goids = self.get_goids_sections(sections)
        gosubdag = GoSubDag(goids, self.go2obj)
        return [(sec, gosubdag.get_nts(gos, sortby)) for sec, gos in sections]
443916
def overview():
    '''
    
    '''
    cmd = 'drbd-overview'
    for line in __salt__['cmd.run'](cmd).splitlines():
        ret = {}
        fields = line.strip().split()
        minnum = fields[0].split(':')[0]
        device = fields[0].split(':')[1]
        connstate, _ = _analyse_overview_field(fields[1])
        localrole, partnerrole = _analyse_overview_field(fields[2])
        localdiskstate, partnerdiskstate = _analyse_overview_field(fields[3])
        if localdiskstate.startswith("UpTo"):
            if partnerdiskstate.startswith("UpTo"):
                if len(fields) >= 5:
                    mountpoint = fields[4]
                    fs_mounted = fields[5]
                    totalsize = fields[6]
                    usedsize = fields[7]
                    remainsize = fields[8]
                    perc = fields[9]
                    ret = {
                        'minor number': minnum,
                        'device': device,
                        'connection state': connstate,
                        'local role': localrole,
                        'partner role': partnerrole,
                        'local disk state': localdiskstate,
                        'partner disk state': partnerdiskstate,
                        'mountpoint': mountpoint,
                        'fs': fs_mounted,
                        'total size': totalsize,
                        'used': usedsize,
                        'remains': remainsize,
                        'percent': perc,
                    }
                else:
                    ret = {
                        'minor number': minnum,
                        'device': device,
                        'connection state': connstate,
                        'local role': localrole,
                        'partner role': partnerrole,
                        'local disk state': localdiskstate,
                        'partner disk state': partnerdiskstate,
                    }
            else:
                syncbar = fields[4]
                synced = fields[6]
                syncedbytes = fields[7]
                sync = synced+syncedbytes
                ret = {
                    'minor number': minnum,
                    'device': device,
                    'connection state': connstate,
                    'local role': localrole,
                    'partner role': partnerrole,
                    'local disk state': localdiskstate,
                    'partner disk state': partnerdiskstate,
                    'synchronisation: ': syncbar,
                    'synched': sync,
                }
    return ret
1131828
def find_fragments(base_directory, sections, fragment_directory, definitions):
    
    content = OrderedDict()
    fragment_filenames = []

    for key, val in sections.items():

        if fragment_directory is not None:
            section_dir = os.path.join(base_directory, val, fragment_directory)
        else:
            section_dir = os.path.join(base_directory, val)

        files = os.listdir(section_dir)

        file_content = {}

        for basename in files:
            parts = basename.split(u".")

            counter = 0
            if len(parts) == 1:
                continue
            else:
                ticket, category = parts[:2]

            # If there is a number after the category then use it as a counter,
            # otherwise ignore it.
            # This means 1.feature.1 and 1.feature do not conflict but
            # 1.feature.rst and 1.feature do.
            if len(parts) > 2:
                try:
                    counter = int(parts[2])
                except ValueError:
                    pass

            if category not in definitions:
                continue

            full_filename = os.path.join(section_dir, basename)
            fragment_filenames.append(full_filename)
            with open(full_filename, "rb") as f:
                data = f.read().decode("utf8", "replace")

            if (ticket, category, counter) in file_content:
                raise ValueError(
                    "multiple files for {}.{} in {}".format(
                        ticket, category, section_dir
                    )
                )
            file_content[ticket, category, counter] = data

        content[key] = file_content

    return content, fragment_filenames
1233509
def section_names(self, ordkey="wall_time"):
        
        section_names = []

        # FIXME this is not trivial
        for idx, timer in enumerate(self.timers()):
            if idx == 0:
                section_names = [s.name for s in timer.order_sections(ordkey)]
                #check = section_names
                #else:
                #  new_set = set( [s.name for s in timer.order_sections(ordkey)])
                #  section_names.intersection_update(new_set)
                #  check = check.union(new_set)

        #if check != section_names:
        #  print("sections", section_names)
        #  print("check",check)

        return section_names
1139186
def sections(self):
    '''
    
    '''

    if not getattr(self, '_sections', False):
      query_params = {
        'action': 'parse',
        'prop': 'sections',
      }
      query_params.update(self.__title_query_param)

      request = _wiki_request(query_params)
      self._sections = [section['line'] for section in request['parse']['sections']]

    return self._sections
868877
def get_sections_for_student(id, opts = {})
      data, _status_code, _headers = get_sections_for_student_with_http_info(id, opts)
      return data
    end
878969
def get_single_submission_sections(self, user_id, section_id, assignment_id, include=None):
        
        path = {}
        data = {}
        params = {}

        # REQUIRED - PATH - section_id
        """ID"""
        path["section_id"] = section_id

        # REQUIRED - PATH - assignment_id
        """ID"""
        path["assignment_id"] = assignment_id

        # REQUIRED - PATH - user_id
        """ID"""
        path["user_id"] = user_id

        # OPTIONAL - include
        """Associations to include with the group."""
        if include is not None:
            self._validate_enum(include, ["submission_history", "submission_comments", "rubric_assessment", "visibility", "course", "user"])
            params["include"] = include

        self.logger.debug("GET /api/v1/sections/{section_id}/assignments/{assignment_id}/submissions/{user_id} with query params: {params} and form data: {data}".format(params=params, data=data, **path))
        return self.generic_request("GET", "/api/v1/sections/{section_id}/assignments/{assignment_id}/submissions/{user_id}".format(**path), data=data, params=params, no_data=True)
588594
def wr_txt_section_hdrgos(self, fout_txt, sortby=None, prt_section=True):
        """"""
        sec2d_go = self.grprobj.get_sections_2d()    # lists of GO IDs
        sec2d_nt = self.get_sections_2dnt(sec2d_go)  # lists of GO Grouper namedtuples
        if sortby is None:
            sortby = self.fncsortnt
        with open(fout_txt, 'w') as prt:
            self.prt_ver(prt)
            prt.write("# GROUP NAME: {NAME}\n".format(NAME=self.grprobj.grpname))
            for section_name, nthdrgos_actual in sec2d_nt:
                if prt_section:
                    prt.write("# SECTION: {SECTION}\n".format(SECTION=section_name))
                self.prt_ntgos(prt, nthdrgos_actual)
                if prt_section:
                    prt.write("\n")
            dat = SummarySec2dHdrGos().summarize_sec2hdrgos(sec2d_go)
            sys.stdout.write(self.grprobj.fmtsum.format(
                GO_DESC='hdr', SECs=len(dat['S']), GOs=len(dat['G']),
                UNGRP=len(dat['U']), undesc="unused",
                ACTION="WROTE:", FILE=fout_txt))
        return sec2d_nt
836613
def sections_count(self):
        """"""
        # This should match the 'sections' attribute length so instead should
        # use :
        #
        #   len(bfd.sections)
        #
        if not self._ptr:
            raise BfdException("BFD not initialized")

        return _bfd.get_bfd_attribute(self._ptr, BfdAttributes.COUNT_SECTIONS)