Python源码示例:bisect.insort()

示例1
def _release(self, offset, width):
        # Coalesce
        while True:
            f,b,ndx = self._buddy(offset, width)

            if ndx is None:
                break
            
            offset &= b
            width += 1
            del f[ndx]
            
        # Add to the list
        bisect.insort(f, offset)

        # Mark as dirty
        self._dirty = True 
示例2
def Add(self, score):
    """Add a score into the last N scores.

    If needed, drops the score that is furthest away from the given score.
    """
    num_sampled_scores = len(self.scores)
    if num_sampled_scores < self.MAX_NUM_SAMPLED_SCORES:
      bisect.insort(self.scores, score)
    else:
      index_left = bisect.bisect_left(self.scores, score)
      index_right = bisect.bisect_right(self.scores, score)
      index_center = index_left + (index_right - index_left) / 2
      self.scores.insert(index_left, score)
      if index_center < num_sampled_scores / 2:
        self.scores.pop()
      else:
        self.scores.pop(0)
    self.num_scores += 1 
示例3
def Add(self, score):
    """Add a score into the last N scores.

    If needed, drops the score that is furthest away from the given score.
    """
    num_sampled_scores = len(self.scores)
    if num_sampled_scores < self.MAX_NUM_SAMPLED_SCORES:
      bisect.insort(self.scores, score)
    else:
      index_left = bisect.bisect_left(self.scores, score)
      index_right = bisect.bisect_right(self.scores, score)
      index_center = index_left + (index_right - index_left) / 2
      self.scores.insert(index_left, score)
      if index_center < num_sampled_scores / 2:
        self.scores.pop()
      else:
        self.scores.pop(0)
    self.num_scores += 1
    RankerCacher.CachePut(self) 
示例4
def interpret_interactions(w_input, w_later, get_main_effects=False):
    interaction_strengths = {}
    for i in range(w_later.shape[1]):
        sorted_hweights = sorted(
            enumerate(w_input[i]), key=lambda x: x[1], reverse=True
        )
        interaction_candidate = []
        candidate_weights = []
        for j in range(w_input.shape[1]):
            bisect.insort(interaction_candidate, sorted_hweights[j][0])
            candidate_weights.append(sorted_hweights[j][1])

            if not get_main_effects and len(interaction_candidate) == 1:
                continue
            interaction_tup = tuple(interaction_candidate)
            if interaction_tup not in interaction_strengths:
                interaction_strengths[interaction_tup] = 0
            interaction_strength = (min(candidate_weights)) * (np.sum(w_later[:, i]))
            interaction_strengths[interaction_tup] += interaction_strength

    interaction_ranking = sorted(
        interaction_strengths.items(), key=operator.itemgetter(1), reverse=True
    )

    return interaction_ranking 
示例5
def add_order_to_book(self, order):
        '''
        Use insort to maintain on ordered list of prices which serve as pointers
        to the orders.
        '''
        book_order = {'order_id': order['order_id'], 'timestamp': order['timestamp'], 'type': order['type'], 
                      'quantity': order['quantity'], 'side': order['side'], 'price': order['price']}
        if order['side'] == 'buy':
            book_prices = self._bid_book_prices
            book = self._bid_book
        else:
            book_prices = self._ask_book_prices
            book = self._ask_book 
        if order['price'] in book_prices:
            book[order['price']]['num_orders'] += 1
            book[order['price']]['size'] += order['quantity']
            book[order['price']]['order_ids'].append(order['order_id'])
            book[order['price']]['orders'][order['order_id']] = book_order
        else:
            bisect.insort(book_prices, order['price'])
            book[order['price']] = {'num_orders': 1, 'size': order['quantity'], 'order_ids': [order['order_id']],
                                    'orders': {order['order_id']: book_order}} 
示例6
def add_item(self, item):
        item.date = self._convertunix(item.date)
        if item.date == None: return
        dt = datetime.fromtimestamp(item.date)
        try:
            item_day = dt.strftime('%d')
            item_month = dt.strftime('%b')
            item_year = dt.strftime('%Y')
        except:
            return
        
        key = self._DATES_KEYFORM.format(day=item_day,month=item_month,
                                         year=item_year)
        if key in self.timeline_dates:
            self.timeline_dates[key].add_item(item)
        else:
            day_date = datetime.fromtimestamp(item.date).date()
            day_tsmp = time.mktime(day_date.timetuple())
            timeline_date = TimelineDate( day_tsmp, item_day, item_month, 
                                          item_year, [item] )
            bisect.insort(self.items, timeline_date)
            self.timeline_dates[key] = timeline_date
        return 
示例7
def pickUnique(N, m, e):
    """Pick m random values from the range 0...(N-1), excluding those in list e
    The returned values should be in a random order (not sorted)
    """
    assert m <= N - len(e)
    
    inds = sorted(e) # Sorted list of indices. Used to avoid clashes
    others = [] # The list of three agents
    for i in range(m):
        newind = random.randint(0, N-1-i-len(e))
        for ind in inds:
            if newind == ind:
                newind += 1
        bisect.insort(inds, newind)
        others.append(newind)
    return others 
示例8
def add_backer(self, start, data):
        """
        Adds a backer to the memory.

        :param start:   The address where the backer should be loaded.
        :param data:    The backer itself. Can be either a bytestring or another :class:`Clemory`.
        """
        if not data:
            raise ValueError("Backer is empty!")

        if not isinstance(data, (bytes, bytearray, list, Clemory)):
            raise TypeError("Data must be a bytes, list, or Clemory object.")
        if start in self:
            raise ValueError("Address %#x is already backed!" % start)
        if isinstance(data, Clemory) and data._root:
            raise ValueError("Cannot add a root clemory as a backer!")
        if type(data) is bytes:
            data = bytearray(data)
        bisect.insort(self._backers, (start, data))
        self._update_min_max() 
示例9
def teardown(self):
        '''
        :return: 1 if any test failed, 0 otherwise
        '''
        self.log_info('\nTest result summary:')
        passes = []
        fails = []
        while not self.test_results.empty():
            test = self.test_results.get()
            if test.status in (TestStatus.PASS, None):
                bisect.insort(passes, test)
            else:
                bisect.insort(fails, test)
        for test in itertools.chain(passes, fails):
            self.log_info(test)
        if fails:
            self.log_error('A test failed')
            return 1
        return 0

# IO format. 
示例10
def update(self, entry_id, label):
        bisect.insort(a=self.Lindex, x=entry_id)
        self.Uindex.remove(entry_id)
        self.y[entry_id] = label 
示例11
def qkchash(header: bytes, nonce: bytes, cache: List) -> Dict[str, bytes]:
    s = sha3_512(header + nonce[::-1])
    lcache = cache[:]
    lcache_set = set(cache)

    mix = []
    for i in range(2):
        mix.extend(s)

    for i in range(ACCESS_ROUND):
        new_data = []

        p = fnv64(i ^ s[0], mix[i % len(mix)])
        for j in range(len(mix)):
            # Find the pth element and remove it
            remove_idx = p % len(lcache)
            new_data.append(lcache[remove_idx])
            lcache_set.remove(lcache[remove_idx])
            del lcache[remove_idx]

            # Generate random data and insert it
            p = fnv64(p, new_data[j])
            if p not in lcache_set:
                bisect.insort(lcache, p)
                lcache_set.add(p)

            # Find the next element
            p = fnv64(p, new_data[j])

        for j in range(len(mix)):
            mix[j] = fnv64(mix[j], new_data[j])

    cmix = []
    for i in range(0, len(mix), 4):
        cmix.append(fnv64(fnv64(fnv64(mix[i], mix[i + 1]), mix[i + 2]), mix[i + 3]))
    return {
        "mix digest": serialize_hash(cmix),
        "result": serialize_hash(sha3_256(s + cmix)),
    } 
示例12
def add_transaction(self, tx: TypedTransaction):
        evm_tx = tx.tx.to_evm_tx()
        if len(self.txs) >= self.limit:
            if evm_tx.gasprice < self.txs[-1].tx.tx.to_evm_tx().gasprice:
                return  # no-op
            pop_tx = self.txs.pop(-1).tx  # type: TypedTransaction
            self.tx_dict.pop(pop_tx.get_hash(), None)
        prio = -evm_tx.gasprice
        ordered_tx = OrderableTx(prio, self.counter, tx)
        # amortized O(n) cost, ~9x slower than heapq push, may need optimization if becoming a bottleneck
        bisect.insort(self.txs, ordered_tx)
        self.tx_dict[tx.get_hash()] = ordered_tx
        self.counter += 1 
示例13
def nsmallest(n, iterable):
    """Find the n smallest elements in a dataset.

    Equivalent to:  sorted(iterable)[:n]
    """
    if hasattr(iterable, '__len__') and n * 10 <= len(iterable):
        # For smaller values of n, the bisect method is faster than a minheap.
        # It is also memory efficient, consuming only n elements of space.
        it = iter(iterable)
        result = sorted(islice(it, 0, n))
        if not result:
            return result
        insort = bisect.insort
        pop = result.pop
        los = result[-1]    # los --> Largest of the nsmallest
        for elem in it:
            if cmp_lt(elem, los):
                insort(result, elem)
                pop()
                los = result[-1]
        return result
    # An alternative approach manifests the whole iterable in memory but
    # saves comparisons by heapifying all at once.  Also, saves time
    # over bisect.insort() which has O(n) data movement time for every
    # insertion.  Finding the n smallest of an m length iterable requires
    #    O(m) + O(n log m) comparisons.
    h = list(iterable)
    heapify(h)
    return map(heappop, repeat(h, min(n, len(h))))

# 'heap' is a heap at all indices >= startpos, except possibly for pos.  pos
# is the index of a leaf with a possibly out-of-order value.  Restore the
# heap invariant. 
示例14
def _free(self, block):
        # free location and try to merge with neighbours
        (arena, start, stop) = block

        try:
            prev_block = self._stop_to_block[(arena, start)]
        except KeyError:
            pass
        else:
            start, _ = self._absorb(prev_block)

        try:
            next_block = self._start_to_block[(arena, stop)]
        except KeyError:
            pass
        else:
            _, stop = self._absorb(next_block)

        block = (arena, start, stop)
        length = stop - start

        try:
            self._len_to_seq[length].append(block)
        except KeyError:
            self._len_to_seq[length] = [block]
            bisect.insort(self._lengths, length)

        self._start_to_block[(arena, start)] = block
        self._stop_to_block[(arena, stop)] = block 
示例15
def __setitem__(self, key, value):
        assert key not in self, "MetersDict doesn't support reassignment"
        priority, value = value
        bisect.insort(self.priorities, (priority, len(self.priorities), key))
        super().__setitem__(key, value)
        for _, _, key in self.priorities:  # reorder dict to match priorities
            self.move_to_end(key) 
示例16
def rerank_nbest_compressions(self):
        """
        Function that reranks the nbest compressions according to the keyphrases
        they contain. The cummulative score (original score) is normalized by 
        (compression length * Sum of keyphrase scores).
        """

        reranked_compressions = []

        # Loop over the compression candidates
        for cummulative_score, path in self.nbest_compressions:

            # Generate the sentence form the path
            compression = ' '.join([u[0] for u in path])

            # Initialize total keyphrase score
            total_keyphrase_score = 1.0

            # Loop over the keyphrases and sum the scores
            for keyphrase in self.keyphrase_candidates:
                if keyphrase in compression:
                    total_keyphrase_score += self.keyphrase_scores[keyphrase]

            score = ( cummulative_score / (len(path) * total_keyphrase_score) )

            bisect.insort( reranked_compressions, 
                           (score, path) )

        return reranked_compressions
    #-B-----------------------------------------------------------------------B-

    #-T-----------------------------------------------------------------------T- 
示例17
def insort_filtered(self, name):
        if self._compiled_filter is None or self._compiled_filter.search(name):
            bisect.insort(self._filtered_sorted_message_names,
                          name) 
示例18
def _free(self, block):
        # free location and try to merge with neighbours
        (arena, start, stop) = block

        try:
            prev_block = self._stop_to_block[(arena, start)]
        except KeyError:
            pass
        else:
            start, _ = self._absorb(prev_block)

        try:
            next_block = self._start_to_block[(arena, stop)]
        except KeyError:
            pass
        else:
            _, stop = self._absorb(next_block)

        block = (arena, start, stop)
        length = stop - start

        try:
            self._len_to_seq[length].append(block)
        except KeyError:
            self._len_to_seq[length] = [block]
            bisect.insort(self._lengths, length)

        self._start_to_block[(arena, start)] = block
        self._stop_to_block[(arena, stop)] = block 
示例19
def nsmallest(n, iterable):
    """Find the n smallest elements in a dataset.

    Equivalent to:  sorted(iterable)[:n]
    """
    if hasattr(iterable, '__len__') and n * 10 <= len(iterable):
        # For smaller values of n, the bisect method is faster than a minheap.
        # It is also memory efficient, consuming only n elements of space.
        it = iter(iterable)
        result = sorted(islice(it, 0, n))
        if not result:
            return result
        insort = bisect.insort
        pop = result.pop
        los = result[-1]    # los --> Largest of the nsmallest
        for elem in it:
            if los <= elem:
                continue
            insort(result, elem)
            pop()
            los = result[-1]
        return result
    # An alternative approach manifests the whole iterable in memory but
    # saves comparisons by heapifying all at once.  Also, saves time
    # over bisect.insort() which has O(n) data movement time for every
    # insertion.  Finding the n smallest of an m length iterable requires
    #    O(m) + O(n log m) comparisons.
    h = list(iterable)
    heapify(h)
    return map(heappop, repeat(h, min(n, len(h))))

# 'heap' is a heap at all indices >= startpos, except possibly for pos.  pos
# is the index of a leaf with a possibly out-of-order value.  Restore the
# heap invariant. 
示例20
def _free(self, block):
        # free location and try to merge with neighbours
        (arena, start, stop) = block

        try:
            prev_block = self._stop_to_block[(arena, start)]
        except KeyError:
            pass
        else:
            start, _ = self._absorb(prev_block)

        try:
            next_block = self._start_to_block[(arena, stop)]
        except KeyError:
            pass
        else:
            _, stop = self._absorb(next_block)

        block = (arena, start, stop)
        length = stop - start

        try:
            self._len_to_seq[length].append(block)
        except KeyError:
            self._len_to_seq[length] = [block]
            bisect.insort(self._lengths, length)

        self._start_to_block[(arena, start)] = block
        self._stop_to_block[(arena, stop)] = block 
示例21
def add(self, cluster):
        '''Add a new :class:`SpectrumCluster` to the collection,
        preserving sorted order.

        Parameters
        ----------
        cluster: :class:`SpectrumCluster`
            The cluster to add
        '''
        bisect.insort(self.clusters, cluster) 
示例22
def on_delete(self, req, res, model_name):  # pylint: disable=W0613
        if model_name not in self._model_tfs_pid:
            res.status = falcon.HTTP_404
            res.body = json.dumps({
                'error': 'Model {} is not loaded yet'.format(model_name)
            })
        else:
            try:
                self._model_tfs_pid[model_name].kill()
                os.remove('/sagemaker/tfs-config/{}/model-config.cfg'.format(model_name))
                os.rmdir('/sagemaker/tfs-config/{}'.format(model_name))
                release_rest_port = self._model_tfs_rest_port[model_name]
                release_grpc_port = self._model_tfs_grpc_port[model_name]
                with lock():
                    bisect.insort(self._tfs_ports['rest_port'], release_rest_port)
                    bisect.insort(self._tfs_ports['grpc_port'], release_grpc_port)
                del self._model_tfs_rest_port[model_name]
                del self._model_tfs_grpc_port[model_name]
                del self._model_tfs_pid[model_name]
                res.status = falcon.HTTP_200
                res.body = json.dumps({
                    'success': 'Successfully unloaded model {}.'.format(model_name)
                })
            except OSError as error:
                res.status = falcon.HTTP_500
                res.body = json.dumps({
                    'error': str(error)
                }).encode('utf-8') 
示例23
def nsmallest(n, iterable):
    """Find the n smallest elements in a dataset.

    Equivalent to:  sorted(iterable)[:n]
    """
    if n < 0:
        return []
    if hasattr(iterable, '__len__') and n * 10 <= len(iterable):
        # For smaller values of n, the bisect method is faster than a minheap.
        # It is also memory efficient, consuming only n elements of space.
        it = iter(iterable)
        result = sorted(islice(it, 0, n))
        if not result:
            return result
        insort = bisect.insort
        pop = result.pop
        los = result[-1]    # los --> Largest of the nsmallest
        for elem in it:
            if cmp_lt(elem, los):
                insort(result, elem)
                pop()
                los = result[-1]
        return result
    # An alternative approach manifests the whole iterable in memory but
    # saves comparisons by heapifying all at once.  Also, saves time
    # over bisect.insort() which has O(n) data movement time for every
    # insertion.  Finding the n smallest of an m length iterable requires
    #    O(m) + O(n log m) comparisons.
    h = list(iterable)
    heapify(h)
    return map(heappop, repeat(h, min(n, len(h))))

# 'heap' is a heap at all indices >= startpos, except possibly for pos.  pos
# is the index of a leaf with a possibly out-of-order value.  Restore the
# heap invariant. 
示例24
def add_events(self, events: List[Union[Event, TIME_FORMAT]]):
        for event in events:
            if not isinstance(event, Event):
                event = Event(event)
            bisect.insort(self, event) 
示例25
def append(self, item):
        bisect.insort(self.A, (self.f(item), item)) 
示例26
def append(self, item):
        bisect.insort(self.A, (self.f(item), item)) 
示例27
def add_item(self, item):
        bisect.insort(self.items, item) 
示例28
def _free(self, block):
        # free location and try to merge with neighbours
        (arena, start, stop) = block

        try:
            prev_block = self._stop_to_block[(arena, start)]
        except KeyError:
            pass
        else:
            start, _ = self._absorb(prev_block)

        try:
            next_block = self._start_to_block[(arena, stop)]
        except KeyError:
            pass
        else:
            _, stop = self._absorb(next_block)

        block = (arena, start, stop)
        length = stop - start

        try:
            self._len_to_seq[length].append(block)
        except KeyError:
            self._len_to_seq[length] = [block]
            bisect.insort(self._lengths, length)

        self._start_to_block[(arena, start)] = block
        self._stop_to_block[(arena, stop)] = block 
示例29
def _free(self, block):
        # free location and try to merge with neighbours
        (arena, start, stop) = block

        try:
            prev_block = self._stop_to_block[(arena, start)]
        except KeyError:
            pass
        else:
            start, _ = self._absorb(prev_block)

        try:
            next_block = self._start_to_block[(arena, stop)]
        except KeyError:
            pass
        else:
            _, stop = self._absorb(next_block)

        block = (arena, start, stop)
        length = stop - start

        try:
            self._len_to_seq[length].append(block)
        except KeyError:
            self._len_to_seq[length] = [block]
            bisect.insort(self._lengths, length)

        self._start_to_block[(arena, start)] = block
        self._stop_to_block[(arena, stop)] = block 
示例30
def callLater(self, delay, callback):
    bisect.insort(self.queue, (self.time + delay, callback))