Count lines in a file
1139
def count_lines_in(filename):
    ""
    f = open(filename)                  
    lines = 0
    buf_size = 1024 * 1024
    read_f = f.read # loop optimization
    
    buf = read_f(buf_size)
    while buf:
        lines += buf.count('\n')
        buf = read_f(buf_size)
    
    return lines
989125
def numberify_file(self, filename):
        '''
        '''
        try:
            fd = open(filename, 'r+')
            lines = fd.readlines()
            for i in range(len(lines)):
                if lines[i][0:len(str(i+1))] != str(i+1):
                    lines[i] = str(i+1) + ' ' + lines[i]
                else:
                    print "File already numbered"
                    return False
            fd.seek(0)
            fd.writelines(lines)
            fd.close()
            return True
        except IOError as e:
            print 'I/O error({0}): {1}'.format(e.errno, e.strerror)
        except:
            print 'Unexpected error:', exc_info()[0]
            raise
1140192
def _count_spaces_startswith(line):
    '''
    
    '''
    if line.split('#')[0].strip() == "":
        return None

    spaces = 0
    for i in line:
        if i.isspace():
            spaces += 1
        else:
            return spaces
1094351
def _process_plan_lines(self, final_line_count):
        """"""
        if not self._lines_seen["plan"]:
            self._add_error(_("Missing a plan."))
            return

        if len(self._lines_seen["plan"]) > 1:
            self._add_error(_("Only one plan line is permitted per file."))
            return

        plan, at_line = self._lines_seen["plan"][0]
        if not self._plan_on_valid_line(at_line, final_line_count):
            self._add_error(
                _("A plan must appear at the beginning or end of the file.")
            )
            return

        if plan.expected_tests != self._lines_seen["test"]:
            self._add_error(
                _("Expected {expected_count} tests but only {seen_count} ran.").format(
                    expected_count=plan.expected_tests,
                    seen_count=self._lines_seen["test"],
                )
            )
1091678
function line_number(index, source) {
  // To speed things up, remember the index until which we counted,
  // then next time just begin counting from there.  This way we
  // only count each line once.
  var i = start_index;
  var count = 0;
  while (i < index) {
    if (source[i] === "\n") {
      count++;
    }
    i++;
  }

  start_linenr = count + start_linenr;
  start_index = index;

  return start_linenr;
}
1349058
def _strip_counters(self, sub_line):
        """"""
        try:
            end = sub_line.rindex('}')
        except ValueError:
            return sub_line
        else:
            return sub_line[:(end + 1)]
739826
def read_lines(in_file):
    """"""

    with open(in_file, 'r') as inf:
        in_contents = inf.read().split('\n')
    return in_contents
957907
def ReadLines(self, file_object):
    
    lines_size = len(self.lines)
    if lines_size < self._buffer_size:
      lines_size = self._buffer_size - lines_size
      while lines_size > 0:
        line = self._ReadLine(file_object)
        if not line:
          break

        self.lines = ''.join([self.lines, line])
        lines_size -= len(line)
843575
private static void countFile(String fname) throws Exception {
    // large buffers pay off
    final int bufSize = 50 * 1024 * 1024;
    Queue<Future<WorkUnit>> work = new ArrayDeque<>();
    Path path = Paths.get(new URI(fname));
    long size = Files.size(path);
    System.out.println(fname + ": " + size + " bytes.");
    int nThreads = (int) Math.ceil(size / (double) bufSize);
    if (nThreads > 4) nThreads = 4;
    System.out.println("Reading the whole file using " + nThreads + " threads...");
    Stopwatch sw = Stopwatch.createStarted();
    long total = 0;
    MessageDigest md = MessageDigest.getInstance("MD5");

    ExecutorService exec = Executors.newFixedThreadPool(nThreads);
    int blockIndex;
    for (blockIndex = 0; blockIndex < nThreads; blockIndex++) {
      work.add(exec.submit(new WorkUnit(Files.newByteChannel(path), bufSize, blockIndex)));
    }
    while (!work.isEmpty()) {
      WorkUnit full = work.remove().get();
      md.update(full.buf.array(), 0, full.buf.position());
      total += full.buf.position();
      if (full.buf.hasRemaining()) {
        full.close();
      } else {
        work.add(exec.submit(full.resetForIndex(blockIndex++)));
      }
    }
    exec.shutdown();

    long elapsed = sw.elapsed(TimeUnit.SECONDS);
    System.out.println("Read all " + total + " bytes in " + elapsed + "s. ");
    String hex = String.valueOf(BaseEncoding.base16().encode(md.digest()));
    System.out.println("The MD5 is: 0x" + hex);
    if (total != size) {
      System.out.println(
          "Wait, this doesn't match! We saw "
              + total
              + " bytes, "
              + "yet the file size is listed at "
              + size
              + " bytes.");
    }
  }
189004
def gather_lines(self):
        
        total_lines = 0
        for file in self.all_files:
            full_path = os.path.join(self.paths["role"], file)

            with open(full_path, "r") as f:
                for line in f:
                    total_lines += 1

            if full_path.endswith(".yml"):
                self.yaml_files.append(full_path)

        return total_lines
1026276
def get_lines_from_file(filename, lineno, context_lines):
    

    def get_lines(start, end):
        return [linecache.getline(filename, l).rstrip() for l in range(start, end)]

    lower_bound = max(1, lineno - context_lines)
    upper_bound = lineno + context_lines
    linecache.checkcache(filename)
    pre_context = get_lines(lower_bound, lineno)
    context_line = linecache.getline(filename, lineno).rstrip()
    post_context = get_lines(lineno + 1, upper_bound)
    return lower_bound, pre_context, context_line, post_context
756768
def count_range(hash_a, hash_b, cmd_options={})
      hg_to_array([%Q[log -r ?:? --template "{node}\n"], hash_a, hash_b], {}, cmd_options) do |line|
        line
      end.size
    end
71008
def _leading_space_count(line):
    """"""
    i = 0
    while i < len(line) and line[i] == ' ':
        i += 1
    return i
820554
def total_reads_from_grabix(in_file):
    
    gbi_file = _get_grabix_index(in_file)
    if gbi_file:
        with open(gbi_file) as in_handle:
            next(in_handle)  # throw away
            num_lines = int(next(in_handle).strip())
        assert num_lines % 4 == 0, "Expected lines to be multiple of 4"
        return num_lines // 4
    else:
        return 0
94325
def _format_file_lines(files):
    ''''''
    LINES_TO_SHOW = 10
    if len(files) <= LINES_TO_SHOW:
        lines = '\n'.join(files)
    else:
        lines = ('\n'.join(files[:LINES_TO_SHOW - 1]) + '\n...{} total'.format(
            len(files)))
    return lines
76103
def txt_line_iterator(path):
  """"""
  with tf.gfile.Open(path) as f:
    for line in f:
      yield line.strip()
119440
function lineCount(value) {
        var rows = 0;
        if (value) {
            rows = 1;
            value.toString().each(/\n/, function () { return rows++; });
        }
        return rows;
    }