Extracts a section of a string and returns a new string.
9589
function slice(str, beginSlice, endSlice) {
  return GraphemeBreaker.break(str)
    .slice(beginSlice, endSlice)
    .join('');
}
121087
def from_string(cls, s):
        """"""
        stream = cStringIO(s)
        stream.seek(0)
        return cls(**yaml.safe_load(stream))
349512
def import_from_string(self, text, title=None):
        """"""
        data = self.model.get_data()
        # Check if data is a dict
        if not hasattr(data, "keys"):
            return
        editor = ImportWizard(self, text, title=title,
                              contents_title=_("Clipboard contents"),
                              varname=fix_reference_name("data",
                                                         blacklist=list(data.keys())))
        if editor.exec_():
            var_name, clip_data = editor.get_data()
            self.new_value(var_name, clip_data)
1120648
def _get_section(self, name, create=True):
        """"""
        try:
            return self.sections[name]
        except KeyError:
            if not create:
                raise

            section = Section(name)
            self.sections[name] = section
            return section
1111579
def get_chunk_path_from_string(string, chunk=3):
    """"""
    return os.path.join(
        *list(generate_chunks(
            string,
            chunk
        ))
    )
207204
def from_string(string, _or=''):
        
        if _or:
            and_or = 'or'
        else:
            and_or = ''
        return Input(string, and_or=and_or)
869814
def from_str(string):
        
        match = re.match(r'^READ (\w+) FOR (\d+) \w+S$', string)
        if match:
            return ReadEvent(match.group(1), int(match.group(2)))
        else:
            raise EventParseError
1249849
def from_string(string):
        
        lines = list(clean_lines(string.splitlines()))
        params = {}
        for line in lines:
            for sline in line.split(';'):
                m = re.match(r'(\w+)\s*=\s*(.*)', sline.strip())
                if m:
                    key = m.group(1).strip()
                    val = m.group(2).strip()
                    val = Incar.proc_val(key, val)
                    params[key] = val
        return Incar(params)
567192
def _parse_section(token_iter):
    '''
    '''
    sexp = []
    for token in token_iter:
        if token == '(':
            new_sexp = _parse_section(token_iter)
            if not _match_section(new_sexp, UNWANTED_SECTIONS):
                sexp.append(new_sexp)
        elif token == ')':
            return sexp
        else:
            sexp.append(token)
    return sexp
318123
def from_str(string):
        
        match = re.match(r'^START READING (\w+) FROM \w+ (\d+)$', string)
        if match:
            return SetReadingEvent(match.group(1), int(match.group(2)))
        else:
            raise EventParseError
654733
def fromstring(cls, string):
        
        parser = etree.XMLParser(remove_blank_text=True)
        root = etree.fromstring(string, parser)
        tree = root.getroottree()

        return cls.fromtree(tree)
1297071
def from_string(string):
        
        lines = list(clean_lines(string.splitlines()))

        def input_mode(line):
            if line[0] == "&":
                return ("sections", line[1:].lower())
            elif "ATOMIC_SPECIES" in line:
                return ("pseudo", )
            elif "K_POINTS" in line:
                return ("kpoints", line.split("{")[1][:-1])
            elif "CELL_PARAMETERS" in line or "ATOMIC_POSITIONS" in line:
                return ("structure", line.split("{")[1][:-1])
            elif line == "/":
                return None
            else:
                return mode

        sections = {"control": {}, "system": {}, "electrons": {}, 
                    "ions": {}, "cell":{}}
        pseudo = {}
        pseudo_index = 0
        lattice = []
        species = []
        coords = []
        structure = None
        site_properties = {"pseudo":[]}
        mode = None
        for line in lines:
            mode = input_mode(line)
            if mode == None:
                pass
            elif mode[0] == "sections":
                section = mode[1]
                m = re.match(r'(\w+)\(?(\d*?)\)?\s*=\s*(.*)', line)
                if m:
                    key = m.group(1).strip()
                    key_ = m.group(2).strip()
                    val = m.group(3).strip()
                    if key_ != "":
                        if sections[section].get(key, None) == None:
                            val_ = [0.0]*20 # MAX NTYP DEFINITION
                            val_[int(key_)-1] = PWInput.proc_val(key, val)
                            sections[section][key] = val_

                            site_properties[key] = []
                        else:
                            sections[section][key][int(key_)-1] = PWInput.proc_val(key, val) 
                    else:
                        sections[section][key] = PWInput.proc_val(key, val)

            elif mode[0] == "pseudo":
                m = re.match(r'(\w+)\s+(\d*.\d*)\s+(.*)', line)
                if m:
                    pseudo[m.group(1).strip()] = {}
                    pseudo[m.group(1).strip()]["index"] = pseudo_index
                    pseudo[m.group(1).strip()]["pseudopot"] = m.group(3).strip()
                    pseudo_index += 1
            elif mode[0] == "kpoints":
                m = re.match(r'(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)', line)
                if m:
                    kpoints_grid = (int(m.group(1)), int(m.group(2)), int(m.group(3)))
                    kpoints_shift = (int(m.group(4)), int(m.group(5)), int(m.group(6)))
                else:
                    kpoints_mode = mode[1]
            elif mode[0] == "structure":
                m_l = re.match(r'(-?\d+\.?\d*)\s+(-?\d+\.?\d*)\s+(-?\d+\.?\d*)', line)
                m_p = re.match(r'(\w+)\s+(-?\d+\.\d*)\s+(-?\d+\.?\d*)\s+(-?\d+\.?\d*)', line)
                if m_l:
                    lattice += [ float(m_l.group(1)), float(m_l.group(2)), float(m_l.group(3)) ]
                elif m_p:
                    site_properties["pseudo"].append(pseudo[m_p.group(1)]["pseudopot"])
                    species += [pseudo[m_p.group(1)]["pseudopot"].split(".")[0]]
                    coords += [[float(m_p.group(2)), float(m_p.group(3)), float(m_p.group(4))]]

                    for k, v in site_properties.items():
                        if k != "pseudo":
                            site_properties[k].append(sections['system'][k][pseudo[m_p.group(1)]["index"]])
                if mode[1] == "angstrom":
                    coords_are_cartesian = True
                elif mode[1] == "crystal":
                    coords_are_cartesian = False

        structure = Structure(Lattice(lattice), species, coords, 
                              coords_are_cartesian=coords_are_cartesian,
                              site_properties=site_properties)
        return PWInput(structure=structure, control=sections["control"],
                       system=sections["system"], electrons=sections["electrons"], 
                       ions=sections["ions"], cell=sections["cell"], kpoints_mode=kpoints_mode,
                       kpoints_grid=kpoints_grid, kpoints_shift=kpoints_shift)
1261991
def from_string(cls, s):
        
        # Extract num and unit string.
        s = s.strip()
        for i, char in enumerate(s):
            if char.isalpha() or char.isspace():
                break
        else:
            raise Exception("Unit is missing in string %s" % s)
        num, unit = float(s[:i]), s[i:]

        # Find unit type (set it to None if it cannot be detected)
        for unit_type, d in BASE_UNITS.items():
            if unit in d:
                break
        else:
            unit_type = None

        return cls(num, unit, unit_type=unit_type)
939734
function processSection(section) {
  var result = {};
  var bookRegexp = new RegExp(language.bookRegexp, 'i');
  var match = section.match(bookRegexp);
  var book = match && match.length ? match[0] : '';
  var noBook = book ? section.replace(book, '').replace(' ', '') : section;
  var chapterVerseSplit = noBook.split(':').filter(valid);
  // TODO: match '.' or ':' for seperator
  // '1.2'.match(/(\d+)(:|\.)*(\d+)*/) => ["1.2", "1", ".", "2"]

  currentSection++;

  if (book) {
    result.book = bookKey(book);
  }

  if (chapterVerseSplit[0]) {
    result[currentSection === 2 && isNum(lastSection.verse) && chapterVerseSplit.length === 1 ? 'verse' : 'chapter'] = Number(chapterVerseSplit[0]);
  }

  if (chapterVerseSplit[1] && !isNum(result.verse)) {
    result.verse = Number(chapterVerseSplit[1]);
  }

  lastSection = result;
  return result;
}
283084
def parse(text: str) -> Docstring:
    
    ret = Docstring()
    if not text:
        return ret

    # Clean according to PEP-0257
    text = inspect.cleandoc(text)

    # Find first title and split on its position
    match = _titles_re.search(text)
    if match:
        desc_chunk = text[: match.start()]
        meta_chunk = text[match.start() :]
    else:
        desc_chunk = text
        meta_chunk = ""

    # Break description into short and long parts
    parts = desc_chunk.split("\n", 1)
    ret.short_description = parts[0] or None
    if len(parts) > 1:
        long_desc_chunk = parts[1] or ""
        ret.blank_after_short_description = long_desc_chunk.startswith("\n")
        ret.blank_after_long_description = long_desc_chunk.endswith("\n\n")
        ret.long_description = long_desc_chunk.strip() or None

    # Split by sections determined by titles
    matches = list(_titles_re.finditer(meta_chunk))
    if not matches:
        return ret
    splits = []
    for j in range(len(matches) - 1):
        splits.append((matches[j].end(), matches[j + 1].start()))
    splits.append((matches[-1].end(), len(meta_chunk)))

    chunks = {}
    for j, (start, end) in enumerate(splits):
        title = matches[j].group(1)
        if title not in _valid:
            continue
        chunks[title] = meta_chunk[start:end].strip("\n")
    if not chunks:
        return ret

    # Add elements from each chunk
    for title, chunk in chunks.items():
        # Determine indent
        indent_match = re.search(r"^\s+", chunk)
        if not indent_match:
            raise ParseError(f'Can\'t infer indent from "{chunk}"')
        indent = indent_match.group()

        # Check for returns/yeilds (only one element)
        if _sections[title] in ("returns", "yields"):
            part = inspect.cleandoc(chunk)
            ret.meta.append(_build_meta(part, title))
            continue

        # Split based on lines which have exactly that indent
        _re = "^" + indent + r"(?=\S)"
        c_matches = list(re.finditer(_re, chunk, flags=re.M))
        if not c_matches:
            raise ParseError(f'No specification for "{title}": "{chunk}"')
        c_splits = []
        for j in range(len(c_matches) - 1):
            c_splits.append((c_matches[j].end(), c_matches[j + 1].start()))
        c_splits.append((c_matches[-1].end(), len(chunk)))
        for j, (start, end) in enumerate(c_splits):
            part = chunk[start:end].strip("\n")
            ret.meta.append(_build_meta(part, title))

    return ret
1220086
def _slice(expr, start=None, stop=None, step=None):
    

    return _string_op(expr, Slice, _start=start, _end=stop, _step=step)
1317898
def from_string(cls, s):
        """"""
        tables = []
        seen = set()
        current_table = None
        lines = list(reversed(s.splitlines()))  # to pop() in right order
        while lines:
            line = lines.pop().strip()
            table_m = re.match(r'^(?P<table>\w.+):$', line)
            field_m = re.match(r'\s*(?P<name>\S+)'
                               r'(\s+(?P<attrs>[^#]+))?'
                               r'(\s*#\s*(?P<comment>.*)$)?',
                               line)
            if table_m is not None:
                table_name = table_m.group('table')
                if table_name in seen:
                    raise ItsdbError(
                        'Table {} already defined.'.format(table_name)
                    )
                current_table = (table_name, [])
                tables.append(current_table)
                seen.add(table_name)
            elif field_m is not None and current_table is not None:
                name = field_m.group('name')
                attrs = field_m.group('attrs').split()
                datatype = attrs.pop(0)
                key = ':key' in attrs
                partial = ':partial' in attrs
                comment = field_m.group('comment')
                current_table[1].append(
                    Field(name, datatype, key, partial, comment)
                )
            elif line != '':
                raise ItsdbError('Invalid line: ' + line)
        return cls(tables)