Find offset of the line which matches a given 'key' using binary search
    If key is not found, the offset is of the line after the key

    File is subdivided into block_size (default 8192) sized blocks
    Optional compare_func may be specified
974447
def binsearch_offset(reader, key, compare_func=cmp, block_size=8192):
    
    min_ = 0

    reader.seek(0, 2)
    max_ = int(reader.tell() / block_size)

    while max_ - min_ > 1:
        mid = int(min_ + ((max_ - min_) / 2))
        reader.seek(mid * block_size)

        if mid > 0:
            reader.readline()  # skip partial line

        line = reader.readline()

        if compare_func(key, line) > 0:
            min_ = mid
        else:
            max_ = mid

    return min_ * block_size
429074
def match_to_key(match, path, location)
      key   = super
      scope = match[1]
      if scope
        scope_parts = extract_literal_or_array_of_literals(scope)
        return nil if scope_parts.nil? || scope_parts.empty?
        "#{scope_parts.join('.')}.#{key}"
      else
        key unless match[0] =~ /\A\w/
      end
    end
407238
def getKey(k)
      return nil if k > @nitems || k <= 0
      pos = SIZEOF_BLOCK_HEADER + (SIZEOF_KEY * (k - 1))
      keydata = @data[pos, SIZEOF_KEY]
      data2key(keydata)
    end
50569
def function_offsets(file, functions)
      arch = architecture(file)
      objdump_bin = find_objdump(arch)
      objdump_cmd = ::Shellwords.join([objdump_bin, '-T', file])
      functions.map! { |f| '\\b' + f + '\\b' }
      ret = {}
      `#{objdump_cmd} | grep -iP '(#{functions.join('|')})'`.lines.map(&:chomp).each do |line|
        tokens = line.split
        ret[tokens.last] = tokens.first.to_i(16)
      end
      ret
    end
1116052
def matching_key_for(self, key):
		
		try:
			return next(e_key for e_key in self.keys() if e_key == key)
		except StopIteration:
			raise KeyError(key)
1132667
def _get_line_offset(self):
        
        # Get line offset from the file
        nlines = int(self.mda['number_of_lines'])
        loff = np.float32(self.mda['loff'])

        # Adapt it to the current segment
        if self.is_segmented:
            # loff in the file specifies the offset of the full disk image
            # centre (1375/2750 for VIS/IR)
            segment_number = self.mda['segment_sequence_number'] - 1
            loff -= (self.mda['total_no_image_segm'] - segment_number - 1) * nlines
        elif self.area_id in (NORTH_HEMIS, SOUTH_HEMIS):
            # loff in the file specifies the start line of the half disk image
            # in the full disk image
            loff = nlines - loff
        elif self.area_id == UNKNOWN_AREA:
            logger.error('Cannot compute line offset for unknown area')

        return loff
596310
private int matchNextHeader(int i, String key)
  {
    int size = _headerSize;
    int length = key.length();

    char []keyBuf = _headerBuffer;
    char []toLowerAscii = _toLowerAscii;

    for (; i < size; i++) {
      CharSegment header = _headerKeys[i];

      if (header.length() != length)
        continue;

      int offset = header.offset();

      int j;
      for (j = 0; j < length; j++) {
        char a = key.charAt(j);
        char b = keyBuf[offset + j];
        
        if (a == b) {
          continue;
        }
        else if (toLowerAscii[a] != toLowerAscii[b]) {
          break;
        }
      }

      if (j == length) {
        return i;
      }
    }

    return -1;
  }
794597
def __slice_key_val(line):
        
        position = line.find(":")
        # If value is -1, that means the item was not found in the string.
        if position != -1:
            key = line[:position]
            value = line[position + 1:]
            value = value.lstrip()
            return key, value
        else:
            key = line
            value = None
            return key, value
889986
def determine_end_offset(block, tokens, source, expected_matcher)
      lines = source.lines
      last_line_number = lines.length
      end_offset = nil
      tokens.reverse_each do |token|
        # Break once we're through with the last line.
        break if token[0][0] != last_line_number

        # Look for expected match to block opener
        next if token[1] != expected_matcher
        next if token[1] == :on_kw && token[2] != END_STR

        # Raise if we've already found something that looks like a block end.
        raise AmbiguousSourceError.from_proc(block) if end_offset
        # Ending offset is the position of the ending token, plus the length of
        # that token.
        end_offset = token[0][1] + token[2].length
      end
      raise AmbiguousSourceError.from_proc(block) unless end_offset
      determine_end_offset_relative_to_source(end_offset, lines.last.length)
    end
484021
public boolean compare( byte buf[], int offset ) {
     if ( size == 4 ) {
       int checksum = ( (buf[offset+0] & 0xff) << 24 ) | 
                      ( (buf[offset+1] & 0xff) << 16 ) |
                      ( (buf[offset+2] & 0xff) << 8 )  |
                      ( (buf[offset+3] & 0xff) );
       return checksum == (int) summer.getValue();
     }
     return size == 0;
   }
321396
def sorted_puts(line)
      if line == nil || line.size == 0
        raise ArgumentError, 'Line cannot be blank!'
      end
      if line.index($/)
        raise ArgumentError, "Cannot `puts` a line with extra line endings. Make sure the line does not contain `#{$/.inspect}`"
      end

      matched, idx = binary_seek(line)

      if matched
        # an exact match was found, nothing to do
      else
        if idx == nil
          # append to end of file
          self.seek(0, IO::SEEK_END)
          puts(line)
        else
          self.seek(cached_positions[idx][0], IO::SEEK_SET)
          do_at_current_position{puts(line)}
        end
        update_cached_position(idx, line)
      end
      nil
    end
655037
private int findIndexByKey(Object key)
    {
        // Traverse the vector from the back. Given proper locking done at
        // a higher level, this will ensure that the cache gets to the same
        // element in the presence of duplicates.
        // Traversing the vector from the first element causes a problem since
        // elements are inserted at the end of the vector (for efficiency).
        // Consequently after inserting duplicate element 1.2, if another
        // operation is performed on the same key 1, we will get to 1.1 instead
        // of 1.2
        for (int i = (size() - 1); i >= 0; --i) {
            Element element = (Element) get(i);
            if (element.key.equals(key)) {
                return i;
            }
        }

        return -1;
    }
449320
def get(self, key) -> str:
        
        # TODO: get is creating files when a key is given which is more than
        # the store size
        chunk_no, offset = self._get_key_location(key)
        with self._openChunk(chunk_no) as chunk:
            return chunk.get(str(offset))
1235293
final bbBlock findBlockHelper(int pos, int lo, int hi)
    {
        bbBlock block;
        int     ii;
        if ((hi - lo) <= 3) {
            for (ii=lo; ii<hi; ii++) {
                block = this._blocks.get(ii);
                if (pos > block._offset + block._limit) continue;
                if (block.containsForRead(pos)) {
                    return block;
                }
                if (block._offset >= pos) break;
            }
            return this._blocks.get(ii - 1);    // this will always be > 0
        }
        int mid = (hi + lo) / 2;
        block = this._blocks.get(mid);
        assert block != null;
        if (block._offset > pos) {
            return findBlockHelper(pos, lo, mid);
        }
        return findBlockHelper(pos, mid, hi);
    }
1271019
def find_newline(self, size=-1):
    
    if size < 0:
      return self._buffer.find('\n', self._offset)
    return self._buffer.find('\n', self._offset, self._offset + size)
1238883
static int binarySearch(long keys[], int start, int len, long key) {
        int high = start + len, low = start - 1, guess;
        while (high - low > 1) {
            // use >>> for average or we could get an integer overflow.
            guess = (high + low) >>> 1;
            long guessedKey = keys[guess];
            if (guessedKey < key) {
                low = guess;
            } else {
                high = guess;
            }
        }

        if (high == start + len) {
            return ~(start + len);
        }

        long highKey = keys[high];
        if (highKey == key) {
            return high;
        } else {
            return ~high;
        }
    }
694172
private int binarySearch(T record) {
		int low = 0;
		int high = this.boundaries.length - 1;
		typeComparator.extractKeys(record, keys, 0);

		while (low <= high) {
			final int mid = (low + high) >>> 1;
			final int result = compareKeys(flatComparators, keys, this.boundaries[mid]);

			if (result > 0) {
				low = mid + 1;
			} else if (result < 0) {
				high = mid - 1;
			} else {
				return mid;
			}
		}
		// key not found, but the low index is the target
		// bucket, since the boundaries are the upper bound
		return low;
	}