Try to extract lines from the invoice
491674
def extract(self, content, output):
    """"""

    # First apply default options.
    plugin_settings = DEFAULT_OPTIONS.copy()
    plugin_settings.update(self['lines'])
    self['lines'] = plugin_settings

    # Validate settings
    assert 'start' in self['lines'], 'Lines start regex missing'
    assert 'end' in self['lines'], 'Lines end regex missing'
    assert 'line' in self['lines'], 'Line regex missing'

    start = re.search(self['lines']['start'], content)
    end = re.search(self['lines']['end'], content)
    if not start or not end:
        logger.warning('no lines found - start %s, end %s', start, end)
        return
    content = content[start.end(): end.start()]
    lines = []
    current_row = {}
    if 'first_line' not in self['lines'] and 'last_line' not in self['lines']:
        self['lines']['first_line'] = self['lines']['line']
    for line in re.split(self['lines']['line_separator'], content):
        # if the line has empty lines in it , skip them
        if not line.strip('').strip('\n') or not line:
            continue
        if 'first_line' in self['lines']:
            match = re.search(self['lines']['first_line'], line)
            if match:
                if 'last_line' not in self['lines']:
                    if current_row:
                        lines.append(current_row)
                    current_row = {}
                if current_row:
                    lines.append(current_row)
                current_row = {
                    field: value.strip() if value else ''
                    for field, value in match.groupdict().items()
                }
                continue
        if 'last_line' in self['lines']:
            match = re.search(self['lines']['last_line'], line)
            if match:
                for field, value in match.groupdict().items():
                    current_row[field] = '%s%s%s' % (
                        current_row.get(field, ''),
                        current_row.get(field, '') and '\n' or '',
                        value.strip() if value else '',
                    )
                if current_row:
                    lines.append(current_row)
                current_row = {}
                continue
        match = re.search(self['lines']['line'], line)
        if match:
            for field, value in match.groupdict().items():
                current_row[field] = '%s%s%s' % (
                    current_row.get(field, ''),
                    current_row.get(field, '') and '\n' or '',
                    value.strip() if value else '',
                )
            continue
        logger.debug('ignoring *%s* because it doesn\'t match anything', line)
    if current_row:
        lines.append(current_row)

    types = self['lines'].get('types', [])
    for row in lines:
        for name in row.keys():
            if name in types:
                row[name] = self.coerce_type(row[name], types[name])

    if lines:
        output['lines'] = lines
303439
protected function completeLineTotals()
    {
        $linesAmount = 0.0;
        $linesAmountInc = 0.0;
        $linesVatAmount = 0.0;
        $this->lineTotalsStates = array(
            'incomplete' => array(),
            'equal' => array(),
            'differ' => array(),
        );

        $invoiceLines = $this->invoice[Tag::Customer][Tag::Invoice][Tag::Line];
        foreach ($invoiceLines as $line) {
            if (isset($line[Meta::LineAmount])) {
                $linesAmount += $line[Meta::LineAmount];
            } elseif (isset($line[Tag::UnitPrice])) {
                $linesAmount += $line[Tag::Quantity] * $line[Tag::UnitPrice];
            } else {
                $this->lineTotalsStates['incomplete'][Meta::LinesAmount] = Meta::LinesAmount;
            }

            if (isset($line[Meta::LineAmountInc])) {
                $linesAmountInc += $line[Meta::LineAmountInc];
            } elseif (isset($line[Meta::UnitPriceInc])) {
                $linesAmountInc += $line[Tag::Quantity] * $line[Meta::UnitPriceInc];
            } else {
                $this->lineTotalsStates['incomplete'][Meta::LinesAmountInc] = Meta::LinesAmountInc;
            }

            if (isset($line[Meta::LineVatAmount])) {
                $linesVatAmount += $line[Meta::LineVatAmount];
            } elseif (isset($line[Meta::VatAmount])) {
                $linesVatAmount += $line[Tag::Quantity] * $line[Meta::VatAmount];
            } else {
                $this->lineTotalsStates['incomplete'][Meta::LinesVatAmount] = Meta::LinesVatAmount;
            }
        }

        $this->invoice[Tag::Customer][Tag::Invoice][Meta::LinesAmount ] = $linesAmount;
        $this->invoice[Tag::Customer][Tag::Invoice][Meta::LinesAmountInc] = $linesAmountInc;
        $this->invoice[Tag::Customer][Tag::Invoice][Meta::LinesVatAmount] = $linesVatAmount;
        if (!empty($this->lineTotalsStates['incomplete'])) {
            sort($this->lineTotalsStates['incomplete']);
            $this->invoice[Tag::Customer][Tag::Invoice][Meta::LinesIncomplete] = implode(',', $this->lineTotalsStates['incomplete']);
        }
    }
465744
function extractJavadoc(str) {
  var lines = str
    .replace(/^[ \t]+|[ \t]+$/g, '') // Trim whitespace.
    .split('\n').map(function (line, i) {
      return i ? line.replace(/^\s*\*\s?/, '') : line;
    });
  while (!lines[0]) {
    lines.shift();
  }
  while (!lines[lines.length - 1]) {
    lines.pop();
  }
  return lines.join('\n');
}
1205414
def _line_iter(self, in_handle):
        
        reader = csv.reader(in_handle, dialect="excel-tab")
        for line in reader:
            if len(line) > 0 and line[0]:
                # check for section headers; all uppercase and a single value
                if line[0].upper() == line[0] and "".join(line[1:]) == "":
                    line = [line[0]]
                yield line
1344656
def extract_blocks( lines )
      init_doc_lines = lines.each_index.select{ |i| lines[i].include? "=begin" }
      end_doc_lines = lines.each_index.select{ |i| lines[i].include? "=end" }

      blocks = init_doc_lines.each_index.map do |i|
        { :init => init_doc_lines[i], :end => end_doc_lines[i] }
      end
    end
1263041
def _get_lines_from_node_text(cls, node):
        
        # TODO more robust parsing
        from lxml import etree
        parts = ([node.text] + list(chain(*([etree.tostring(c, with_tail=False), c.tail] for c in node.getchildren()))) + [node.tail])
        parts = [gf.safe_unicode(p) for p in parts]
        parts = [p.strip() for p in parts if not p.startswith(u"<br ")]
        parts = [p for p in parts if len(p) > 0]
        uparts = []
        for part in parts:
            uparts.append(gf.safe_unicode(part))
        return uparts
978560
def all(self, data={}, **kwargs):
        "
        return super(Invoice, self).all(data, **kwargs)
123195
def parse_lines(log_parsers, fileinp):
    """"""
    while 1:
        logentry = fileinp.readline()
        if not logentry:
            break
        elif not logentry.rstrip():
            continue  # skip newlines

        processed = False
        for lp in log_parsers:
            if lp.grok(logentry):
                processed = True
        if not processed:
            # error: none of the logparsers worked on the line
            logger = logging.getLogger('logparser')
            logger.warning(
                #'Could not parse line %s, in file %s >>>%s<<<',
                #fileinp.lineno(), fileinp.filename(), line.rstrip())
                'Could not parse line >>>%s<<<', logentry.rstrip())
            print('Could not parse line >>>%s<<<' % logentry.rstrip())
472421
def invoice(self, **kwargs):
        """"""
        url = urljoin(self._url, '/invoices')

        if kwargs:
            response = self.http_request(url, 'POST', Invoice(**kwargs), {'Content-Type':
                'application/xml; charset=utf-8'})
        else:
            response = self.http_request(url, 'POST')

        if response.status != 201:
            self.raise_http_error(response)

        response_xml = response.read()
        logging.getLogger('recurly.http.response').debug(response_xml)
        elem = ElementTree.fromstring(response_xml)

        invoice_collection = InvoiceCollection.from_element(elem)
        return invoice_collection
791363
def doc_to_lines(self, doc, format_func=None):
        
        if format_func:
            for l in format_func(doc).splitlines():
                yield l
        elif self.pretty_print:
            for l in pprint.pformat(doc).splitlines():
                yield l
        else:
            for l in str(doc).splitlines():
                yield l
1090716
def read_line(line):
        """"""
        name, value = '', ''

        if '=' in line:
            name, value = line.split('=', 1)

        return [name.strip(), value.strip()]
1098267
def lines(self, code):
        """"""
        if isinstance(code, str):
            fix_indentation = self.fix_indentation
            if fix_indentation:
                code = fix_indentation(code)
            return self.append(code)
        else:
            return self.append(code)
101401
def process_line(self, line):
        ""
        cleaned = []
        columns = line.split(self.indel)
        # Populate indices if not defined
        if not self.indices:
            self.indices = range(len(columns))
        for i in self.indices:
            # Support turning an in col into multiple out cols
            out = self.process_column(i, columns[i])
            if isinstance(out, (list, tuple)):
                cleaned.extend(out)
            else:
                cleaned.append(out)
        return self.outdel.join(cleaned) + '\n'
752676
def create_invoice_from_albaran(pk, list_lines):
        
        context = {}
        if list_lines:
            new_list_lines = [x[0] for x in SalesLineAlbaran.objects.values_list('line_order__pk').filter(
                pk__in=[int(x) for x in list_lines]
            ).exclude(invoiced=True)]
            if new_list_lines:
                lo = SalesLineOrder.objects.values_list('order__pk').filter(pk__in=new_list_lines)[:1]
                if lo and lo[0] and lo[0][0]:
                    new_pk = lo[0][0]
                    context = GenLineProduct.create_invoice_from_order(new_pk, new_list_lines)
                    if 'error' not in context or not context['error']:
                        SalesLineAlbaran.objects.filter(
                            pk__in=[int(x) for x in list_lines]
                        ).exclude(invoiced=True).update(invoiced=True)
                    return context
                else:
                    error = _('Pedido no encontrado')
            else:
                error = _('Lineas no relacionadas con pedido')
        else:
            error = _('Lineas no seleccionadas')
        context['error'] = error
        return context
1156256
def get_lines_from_file(filename, lineno, context_lines, loader=None, module_name=None):
    
    lineno = lineno - 1
    lower_bound = max(0, lineno - context_lines)
    upper_bound = lineno + context_lines

    source = None
    if loader is not None and hasattr(loader, "get_source"):
        result = get_source_lines_from_loader(loader, module_name, lineno, lower_bound, upper_bound)
        if result is not None:
            return result

    if source is None:
        try:
            with open(filename, "rb") as file_obj:
                encoding = "utf8"
                # try to find encoding of source file by "coding" header
                # if none is found, utf8 is used as a fallback
                for line in itertools.islice(file_obj, 0, 2):
                    match = _coding_re.search(line.decode("utf8"))
                    if match:
                        encoding = match.group(1)
                        break
                file_obj.seek(0)
                lines = [
                    compat.text_type(line, encoding, "replace")
                    for line in itertools.islice(file_obj, lower_bound, upper_bound + 1)
                ]
                offset = lineno - lower_bound
                return (
                    [l.strip("\r\n") for l in lines[0:offset]],
                    lines[offset].strip("\r\n"),
                    [l.strip("\r\n") for l in lines[offset + 1 :]] if len(lines) > offset else [],
                )
        except (OSError, IOError, IndexError):
            pass
    return None, None, None
332862
def parse_line(line):
    '''  '''
    line = line.rstrip()
    line_type = _get_line_type(line)
    return TabLine(
        type=line_type,
        data=_DATA_PARSERS[line_type](line),
        original=line,
    )
881789
def get_lines(self):
        
        code = [self.FILE_HEADER.strip()]

        # Queue and process the required models
        for model_class in self._queue_models(self.models, context=self.context):
            msg = 'Processing model: %s.%s\n' % (model_class.model.__module__, model_class.model.__name__)
            self.stderr.write(msg)
            code.append("    # " + msg)
            code.append(model_class.import_lines)
            code.append("")
            code.append(model_class.lines)

        # Process left over foreign keys from cyclic models
        for model in self.models:
            msg = 'Re-processing model: %s.%s\n' % (model.model.__module__, model.model.__name__)
            self.stderr.write(msg)
            code.append("    # " + msg)
            for instance in model.instances:
                if instance.waiting_list or instance.many_to_many_waiting_list:
                    code.append(instance.get_lines(force=True))

        code.insert(1, "    # Initial Imports")
        code.insert(2, "")
        for key, value in self.context["__extra_imports"].items():
            code.insert(2, "    from %s import %s" % (value, key))

        return code