Python bisect.insort() Examples
The following are 30
code examples of bisect.insort().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
bisect
, or try the search function
.
Example #1
Source File: common.py From linux-kernel-module-cheat with GNU General Public License v3.0 | 6 votes |
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.
Example #2
Source File: local_scores.py From browserscope with Apache License 2.0 | 6 votes |
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
Example #3
Source File: result_ranker.py From browserscope with Apache License 2.0 | 6 votes |
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)
Example #4
Source File: Timeline.py From nfi with GNU General Public License v3.0 | 6 votes |
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
Example #5
Source File: orderbook3.py From pyziabm with BSD 3-Clause "New" or "Revised" License | 6 votes |
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}}
Example #6
Source File: optimiser.py From freegs with GNU Lesser General Public License v3.0 | 6 votes |
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
Example #7
Source File: neural_interaction_detection.py From neural-interaction-detection with Apache License 2.0 | 6 votes |
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
Example #8
Source File: memory.py From cle with BSD 2-Clause "Simplified" License | 6 votes |
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()
Example #9
Source File: heap.py From Splunking-Crime with GNU Affero General Public License v3.0 | 5 votes |
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
Example #10
Source File: heap.py From ironpython3 with Apache License 2.0 | 5 votes |
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
Example #11
Source File: util.py From holoviews with BSD 3-Clause "New" or "Revised" License | 5 votes |
def register_cmaps(category, provider, source, bg, names): """ Maintain descriptions of colormaps that include the following information: name - string name for the colormap category - intended use or purpose, mostly following matplotlib provider - package providing the colormap directly source - original source or creator of the colormaps bg - base/background color expected for the map ('light','dark','medium','any' (unknown or N/A)) """ for name in names: bisect.insort(cmap_info, CMapInfo(name=name, provider=provider, category=category, source=source, bg=bg))
Example #12
Source File: timer.py From untwisted with MIT License | 5 votes |
def __init__(self, inc, callback, *args, **kwargs): self.args = args self.kwargs = kwargs self.inc = inc self.time = time.time() self.callback = callback core.gear.pool.append(self) bisect.insort(Timer.base, inc) self.set_reactor_timeout()
Example #13
Source File: aggregation.py From aggregation with Apache License 2.0 | 5 votes |
def __readin_users__(self): for user_record in self.user_collection.find(): if "name" in user_record: user = user_record["name"] bisect.insort(self.all_users,user)
Example #14
Source File: _opener.py From yalih with Apache License 2.0 | 5 votes |
def add_handler(self, handler): if not hasattr(handler, "add_parent"): raise TypeError("expected BaseHandler instance, got %r" % type(handler)) if handler in self.handlers: return # XXX why does self.handlers need to be sorted? bisect.insort(self.handlers, handler) handler.add_parent(self) self._handler_index_valid = False
Example #15
Source File: porthawk-server-log.py From Forensics with BSD 2-Clause "Simplified" License | 5 votes |
def insertPacket(protocol): if protocol == 'ICMP': if packet['icmp_type'] not in database[engagement][hostname]['ICMP_type']: bisect.insort(database[engagement][hostname]['ICMP_type'], packet['icmp_type']) elif protocol == 'UDP': if packet['dest_port'] not in database[engagement][hostname]['UDP_dest_port']: bisect.insort(database[engagement][hostname]['UDP_dest_port'], packet['dest_port']) elif protocol == 'TCP': if packet['dest_port'] not in database[engagement][hostname]['TCP_dest_port']: bisect.insort(database[engagement][hostname]['TCP_dest_port'], packet['dest_port']) # has the database seen the engagement before
Example #16
Source File: build_encoding.py From DeepFMPO with MIT License | 5 votes |
def find_pairs(distance_matrix): left = np.ones(distance_matrix.shape[0]) pairs = [] candidates = sorted(zip(distance_matrix.max(1),zip(range(distance_matrix.shape[0]), distance_matrix.argmax(1)))) use_next = [] while len(candidates) > 0: v, (c1,c2) = candidates.pop() if left[c1] + left[c2] == 2: left[c1] = 0 left[c2] = 0 pairs.append([c1,c2]) elif np.sum(left) == 1: # Just one sample left sampl = np.argmax(left) pairs.append([sampl]) left[sampl] = 0 elif left[c1] == 1: row = distance_matrix[c1,:] * left c2_new = row.argmax() v_new = row[c2_new] new = (v_new, (c1, c2_new)) bisect.insort(candidates, new) return pairs # Create a new similarity matrix from a given set of pairs # The new similarity is the maximal similarity of any fragment in the sets that are combined.
Example #17
Source File: build_encoding.py From DeepFMPO with MIT License | 5 votes |
def find_pairs(distance_matrix): left = np.ones(distance_matrix.shape[0]) pairs = [] candidates = sorted(zip(distance_matrix.max(1),zip(range(distance_matrix.shape[0]), distance_matrix.argmax(1)))) use_next = [] while len(candidates) > 0: v, (c1,c2) = candidates.pop() if left[c1] + left[c2] == 2: left[c1] = 0 left[c2] = 0 pairs.append([c1,c2]) elif np.sum(left) == 1: # Just one sample left sampl = np.argmax(left) pairs.append([sampl]) left[sampl] = 0 elif left[c1] == 1: row = distance_matrix[c1,:] * left c2_new = row.argmax() v_new = row[c2_new] new = (v_new, (c1, c2_new)) bisect.insort(candidates, new) return pairs # Create a new similarity matrix from a given set of pairs # The new similarity is the maximal similarity of any fragment in the sets that are combined.
Example #18
Source File: _opener.py From Vaile with GNU General Public License v3.0 | 5 votes |
def add_handler(self, handler): if not hasattr(handler, "add_parent"): raise TypeError("expected BaseHandler instance, got %r" % type(handler)) if handler in self.handlers: return # XXX why does self.handlers need to be sorted? bisect.insort(self.handlers, handler) handler.add_parent(self) self._handler_index_valid = False
Example #19
Source File: wcsp.py From pracmln with BSD 2-Clause "Simplified" License | 5 votes |
def _compute_divisor(self): ''' Computes a divisor for making all constraint costs integers. ''' # store all costs in a sorted list costs = [] minWeight = None if len(self.constraints) == 0: raise NoConstraintsError('There are no satisfiable constraints.') for constraint in list(self.constraints.values()): for value in [constraint.defcost] + list(constraint.tuples.values()): if value == self.top: continue value = eval('{:.6f}'.format(value)) if value in costs: continue bisect.insort(costs, value) if (minWeight is None or value < minWeight) and value > 0: minWeight = value # no smallest real-valued weight -> all constraints are hard if minWeight is None: return None # compute the smallest difference between subsequent costs deltaMin = None w1 = costs[0] if len(costs) == 1: deltaMin = costs[0] for w2 in costs[1:]: diff = w2 - w1 if deltaMin is None or diff < deltaMin: deltaMin = diff w1 = w2 divisor = 1.0 if minWeight < 1.0: divisor *= minWeight if deltaMin < 1.0: divisor *= deltaMin return divisor
Example #20
Source File: heap.py From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 | 5 votes |
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
Example #21
Source File: node.py From bplustree with MIT License | 5 votes |
def insert_entry(self, entry: Entry): bisect.insort(self.entries, entry)
Example #22
Source File: recipe-68435.py From code with MIT License | 5 votes |
def append(self,data,priority): """append a new element to the queue according to its priority""" bisect.insort(self.queue,(priority,data))
Example #23
Source File: utils.py From aima with MIT License | 5 votes |
def append(self, item): bisect.insort(self.A, (self.f(item), item))
Example #24
Source File: ioloop.py From honeything with GNU General Public License v3.0 | 5 votes |
def add_timeout(self, deadline, callback): """Calls the given callback at the time deadline from the I/O loop.""" timeout = _Timeout(deadline, callback) bisect.insort(self._timeouts, timeout) return timeout
Example #25
Source File: changes.py From gitinspector with GNU General Public License v3.0 | 5 votes |
def __iadd__(self, other): try: self.authors.update(other.authors) self.authors_dateinfo.update(other.authors_dateinfo) self.authors_by_email.update(other.authors_by_email) self.emails_by_author.update(other.emails_by_author) for commit in other.commits: bisect.insort(self.commits, commit) if not self.commits and not other.commits: self.commits = [] return self except AttributeError: return other
Example #26
Source File: test_simulation.py From packet-queue with Apache License 2.0 | 5 votes |
def callLater(self, delay, callback): bisect.insort(self.queue, (self.time + delay, callback))
Example #27
Source File: heap.py From Fluid-Designer with GNU General Public License v3.0 | 5 votes |
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
Example #28
Source File: Timeline.py From nfi with GNU General Public License v3.0 | 5 votes |
def add_item(self, item): bisect.insort(self.items, item)
Example #29
Source File: utils.py From robocup-soccer with MIT License | 5 votes |
def append(self, item): bisect.insort(self.A, (self.f(item), item))
Example #30
Source File: heap.py From Imogen with MIT License | 5 votes |
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