Example #1
0
def test_unhashable_types():
    import System
    class OldUserClass:
        def foo(): pass
    import _weakref
    from _collections import deque
    
    AssertError(TypeError, hash, slice(None))
    hashcode = System.Object.GetHashCode(slice(None))
    
    # weakproxy
    AssertError(TypeError, hash, _weakref.proxy(OldUserClass()))
    hashcode = System.Object.GetHashCode(_weakref.proxy(OldUserClass()))
    
    # weakcallableproxy
    AssertError(TypeError, hash, _weakref.proxy(OldUserClass().foo))
    hashcode = System.Object.GetHashCode(_weakref.proxy(OldUserClass().foo))
    
    AssertError(TypeError, hash, deque())
    hashcode = System.Object.GetHashCode(deque())
    
    AssertError(TypeError, hash, dict())
    hashcode = System.Object.GetHashCode(dict())
    
    AssertError(TypeError, hash, list())
    hashcode = System.Object.GetHashCode(list())
    
    AssertError(TypeError, hash, set())
    hashcode = System.Object.GetHashCode(set())
Example #2
0
 def test_maxlen_attribute(self):
     from _collections import deque
     assert deque().maxlen is None
     assert deque('abc').maxlen is None
     assert deque('abc', maxlen=4).maxlen == 4
     assert deque('abc', maxlen=0).maxlen == 0
     raises((AttributeError, TypeError), "deque('abc').maxlen = 10")
Example #3
0
 def test_roundtrip_iter_init(self):
     from _collections import deque
     d = deque(xrange(200))
     e = deque(d)
     assert d is not e
     assert d == e
     assert list(d) == list(e)
Example #4
0
 def test_remove(self):
     from _collections import deque
     d = deque('abcdefghcij')
     d.remove('c')
     assert d == deque('abdefghcij')
     d.remove('c')
     assert d == deque('abdefghij')
     raises(ValueError, d.remove, 'c')
     assert d == deque('abdefghij')
Example #5
0
 def test_count(self):
     from _collections import deque
     for s in ('', 'abracadabra', 'simsalabim'*50+'abc'):
         s = list(s)
         d = deque(s)
         for letter in 'abcdeilmrs':
             assert s.count(letter) == d.count(letter)
     class MutatingCompare:
         def __eq__(self, other):
             d.pop()
             return True
     m = MutatingCompare()
     d = deque([1, 2, 3, m, 4, 5])
     raises(RuntimeError, d.count, 3)
Example #6
0
 def test_reverse(self):
     from _collections import deque
     d = deque(xrange(1000, 1200))
     d.reverse()
     assert list(d) == list(reversed(range(1000, 1200)))
     #
     n = 100
     data = map(str, range(n))
     for i in range(n):
         d = deque(data[:i])
         r = d.reverse()
         assert list(d) == list(reversed(data[:i]))
         assert r is None
         d.reverse()
         assert list(d) == data[:i]
Example #7
0
def join(graph):
    processed = set()
    end = graph.end
    queue = deque()
    for (_, neighbor) in graph.out_edges(graph.start):
        queue.appendleft(neighbor)
    while queue:
        vertex = queue.popleft()
        out_edges = graph.out_edges(vertex)
        if len(out_edges) is 1:
            (_, join_candidate) = next(iter(out_edges))
            can_join = join_candidate != end and len(graph.in_edges(join_candidate)) == 1
            if can_join:
                join_vertex_and_join_candidate(graph, join_candidate, vertex)
                for (_, neighbor, data) in list(graph.out_edges(join_candidate, data=True)):
                    graph.remove_edge(join_candidate, neighbor)
                    graph.connect(vertex, neighbor, data["label"])
                graph.remove_edge(vertex, join_candidate)
                graph.remove_node(join_candidate)
                queue.appendleft(vertex)
                continue
        processed.add(vertex)
        for (_, neighbor) in out_edges:
            # FIXME: Why do we run out of memory in some cases here, if this is not checked?
            if neighbor not in processed:
                queue.appendleft(neighbor)
Example #8
0
    def test_comparisons(self):
        from _collections import deque
        d = deque('xabc'); d.popleft()
        for e in [d, deque('abc'), deque('ab'), deque(), list(d)]:
            assert (d==e) == (type(d)==type(e) and list(d)==list(e))
            assert (d!=e) == (not(type(d)==type(e) and list(d)==list(e)))

        args = map(deque, ('', 'a', 'b', 'ab', 'ba', 'abc', 'xba', 'xabc', 'cba'))
        for x in args:
            for y in args:
                assert (x == y) == (list(x) == list(y))
                assert (x != y) == (list(x) != list(y))
                assert (x <  y) == (list(x) <  list(y))
                assert (x <= y) == (list(x) <= list(y))
                assert (x >  y) == (list(x) >  list(y))
                assert (x >= y) == (list(x) >= list(y))
Example #9
0
 def __init__(self, canvas, params={}):
     '''
     Constructor
     :param iface: An interface instance that will be passed to this class
         which provides the hook by which you can manipulate the QGIS
         application at run time.
     :type iface: QgsInterface
     :param params: A dictionary defining all the properties of the position marker
     :type params: dictionary
     '''
     self.canvas = canvas
     self.type = params.get('type', 'BOX').upper()
     self.size = int(params.get('size', 16))
     self.bounding = 1.414213562 * self.size
     self.length = float(params.get('length', 98.0))
     self.width = float(params.get('width', 17.0))
     self.shape = params.get('shape', ((0.0, -0.5), (0.5, -0.3), (0.5, 0.5), (-0.5, 0.50), (-0.5, -0.3)))
     s = (self.size - 1) / 2
     self.paintShape = QPolygonF([QPointF(-s, -s), QPointF(s, -s), QPointF(s, s), QPointF(-s, s)])
     self.color = self.getColor(params.get('color', 'black'))
     self.fillColor = self.getColor(params.get('fillColor', 'lime'))
     self.penWidth = int(params.get('penWidth', 1))
     if self.type in ('CROSS', 'X'):
         self.penWidth = 5
     self.trackLen = int(params.get('trackLength', 100))
     self.trackColor = self.getColor(params.get('trackColor', self.fillColor))
     self.track = deque()
     self.pos = None
     self.heading = 0
     super(PositionMarker, self).__init__(canvas)
     self.setZValue(int(params.get('zValue', 100)))
     self.distArea = QgsDistanceArea()
     self.distArea.setEllipsoid(u'WGS84')
     self.distArea.setEllipsoidalMode(True)
     self.updateSize()
Example #10
0
def getTrappedAmountWater(li):
    if len(li) > 2:
        left = []
        leftMax = li[0]
        for i, v in enumerate(li):
            if i == 0:
                left.append(v)
            else:
                left.append(leftMax)
                if v > leftMax:
                    leftMax = v
           
        print left         
        right = deque([])
        rightMax = li[-1]
        
        for i, v in reversed(list(enumerate(li))):
            if i == len(li) - 1:
                right.append(v)
            else:
                right.append(rightMax)
                if v > rightMax:
                    rightMax = v
        
        print right
        
        value = 0
        for i in xrange(1, len(li) - 1):
            minimum = min(left[i], right[i])
            if minimum > li[i]:
                value += (minimum - li[i])
        return value
    else:
        return 0
Example #11
0
    def _genericSuffixStripper(self, initialState, word, stems, machine):
        """
        Given the initial state of a state machine, it adds possible stems to a set of stems.

        Args:
        initialState (State): an initial state
        word (str): the word to stem
        stems (set): the set to populate
        machine (str): a string representing the name of the state machine. It is used for debugging reasons only.
        """
        transitions = deque()
        initialState.AddTransitions(word, transitions, False)

        while transitions:
            transition = transitions.popleft()
            wordToStem = transition.word
            stem = self.stemWord(wordToStem, transition.suffix)
            if stem != wordToStem:
                if transition.nextState.finalState:
                    for transitionToRemove in tuple(transitions):
                        if ((transitionToRemove.startState == transition.startState and 
                            transitionToRemove.nextState == transition.nextState) or 
                            transitionToRemove.marked):
                            transitions.remove(transitionToRemove)
                    stems.add(stem)
                    transition.nextState.AddTransitions(stem, transitions, False)
                else:
                    for similarTransition in transition.similarTransitions(transitions):
                        similarTransition.marked = True
                    transition.nextState.AddTransitions(stem, transitions, True)
Example #12
0
 def _start_threads(self):
     processed_frags = deque(maxlen=PROCESSED_FRAGMENT_INDEX_LENGTH)
     # File / fragment processor
     for _ in xrange(FILE_PROCESSOR_THREAD_COUNT):
         file_processor = FileProcessor(self.file_processor_queue,
                                        self.file_send_queue,
                                        processed_frags=processed_frags)
         self.log.info("Starting File Processor Thread")
         file_processor.start()
         self.threads.append(file_processor)
         
     # S3 Uploader
     for _ in xrange(S3_UPLOADER_THREAD_COUNT):
         s3_adapter = S3UploadAdapter(bucket_name=self.args.bucket, 
                                      access_key=self.args.access_key,
                                      secret=self.args.secret)
         
         s3_uploader = UploadQueueProcessor(base_directory="/",
                                            file_send_queue=self.file_send_queue,
                                            file_adapter=s3_adapter) 
                                              
         self.log.info("Starting S3 Uploader Thread")
         s3_uploader.start()
         self.threads.append(s3_uploader)
         
         
     wm = pyinotify.WatchManager()  # Watch Manager
     mask = pyinotify.IN_CLOSE_WRITE | pyinotify.IN_MOVED_TO | pyinotify.IN_MODIFY # watched events
     notifier = pyinotify.ThreadedNotifier(wm, EventHandler(file_queue=self.file_processor_queue))
     wm.add_watch(self.args.source_dir, mask, rec=False)
     self.log.info("Starting inotify thread")
     notifier.start()
     self.threads.append(notifier)
Example #13
0
 def test_runtimeerror(self):
     from _collections import deque
     d = deque('abcdefg')
     it = iter(d)
     d.pop()
     raises(RuntimeError, it.next)
     #
     d = deque('abcdefg')
     it = iter(d)
     d.append(d.pop())
     raises(RuntimeError, it.next)
     #
     d = deque()
     it = iter(d)
     d.append(10)
     raises(RuntimeError, it.next)
Example #14
0
def printBoundry(root):
    q = deque([root,None])
    prev = None
    s = []
    s1 = []
    while len(q):
        printed = False
        item = q.popleft()
        if item:
            if prev is None:
                print item.data,
                printed = True
            if item.left:
                q.append(item.left)
            if item.right:
                q.append(item.right)
                
            if item.left is None and item.right is None:
                if not printed:
                    s1.append(item.data)
                    printed = True
            prev = item
        else:
            s.append(prev.data)
            if len(q):
                q.append(None)
            prev = None
            
    print s1
    print s 
Example #15
0
    def test_startbit(self):
        u = self.u
        u.cntrl._ag.data.extend([(START, 0), (NOP, 0)])
        u.clk_cnt_initVal._ag.data.append(4)
        self.runSim(600 * Time.ns)

        self.assertEqual(u.i2c._ag.bits, deque([I2cAgent.START]))
def checkWhetherTreeIsCompleteOrNot(root):
    if root is None:
        return True
    else:
        q = deque([root])
        noMoreNodes = False
        while len(q):
            item = q.popleft()
            if item.left is not None:
                if not noMoreNodes:
                    q.append(item.left)
                else:
                    return False
            else:
                noMoreNodes = True
                
            if item.right is not None:
                if not noMoreNodes:
                    q.append(item.right)
                else:
                    return False
            else:
                noMoreNodes = True
                
    return True
Example #17
0
 def test_extend(self):
     from _collections import deque
     d = deque('a')
     d.extend('bcd')
     assert list(d) == list('abcd')
     d.extend(d)
     assert list(d) == list('abcdabcd')
Example #18
0
def join(graph):
    processed = set()
    end = graph.end
    queue = deque()
    for (_, neighbor) in graph.out_edges(graph.start):
        queue.appendleft(neighbor)
    while queue:
        vertex = queue.popleft()
        out_edges = graph.out_edges(vertex)
        if len(out_edges) is 1:
            (_, join_candidate) = out_edges[0]
            can_join = join_candidate != end and len(graph.in_edges(join_candidate))==1
            if can_join:
                # Note: since there is no normalized/non normalized content in the graph
                # a space character is added here for non punctuation tokens
                label = graph.vertex_attributes(join_candidate)["label"]
                if re.match(r'^\W', label):
                    graph.vertex_attributes(vertex)["label"] += label
                else:
                    graph.vertex_attributes(vertex)["label"] += " "+label
                for (_, neighbor, data) in graph.out_edges(join_candidate, data=True):
                    graph.remove_edge(join_candidate, neighbor)
                    graph.connect(vertex, neighbor, data["label"])
                graph.remove_edge(vertex, join_candidate)
                graph.remove_node(join_candidate)
                queue.appendleft(vertex);
                continue;
        processed.add(vertex)
        for (_, neighbor) in out_edges:
            # FIXME: Why do we run out of memory in some cases here, if this is not checked?
            if neighbor not in processed:
                queue.appendleft(neighbor)
Example #19
0
 def test_extendleft(self):
     from _collections import deque
     d = deque('a')
     d.extendleft('bcd')
     assert list(d) == list(reversed('abcd'))
     d.extendleft(d)
     assert list(d) == list('abcddcba')
Example #20
0
 def test_repr(self):
     from _collections import deque
     d = deque(xrange(20))
     e = eval(repr(d))
     assert d == e
     d.append(d)
     assert '...' in repr(d)
Example #21
0
 def __init__(self, maxsize=None):
     '''
     @maxsize:表示队列的最大长度,如果有,则必须大于零,如果没有,队列将无限增长,
     '''
     super(Queue, self).__init__()
     self.mutex=threading.Lock()
     self.to_put=threading.Condition(self.mutex)
     self.to_get=threading.Condition(self.mutex)
     self.all_task_do=threading.Condition(self.mutex)
     if maxsize:
         if maxsize<=0:
             raise ValueError("'maxsize' must be gather zero")
         else:
             self.queue=deque(maxlen=maxsize)
     else:
         self.queue=deque()
     self.maxsize = maxsize
Example #22
0
def moving_average(iterable, n=3):
    it = iter(iterable)
    d = deque(itertools.islice(it, n - 1))
    d.appendleft(0)
    s = sum(d)
    for elem in it:
        s += elem - d.popleft()
        d.append(elem)
        yield s / n
Example #23
0
 def __init__(self, clustered_trace, bb_func, ctx_reg_size, title='Clustering Analysis Result', save_func=None):
     # context should be a dictionary containing the backward traced result of each relevant register
     super(ClusterViewer, self).__init__(title)
     self.orig_trace = clustered_trace
     self.trace = deepcopy(self.orig_trace)
     self.bb_func = bb_func
     self.ctx_reg_size = ctx_reg_size
     self.save = save_func
     self.undo_stack = deque([deepcopy(self.trace)], maxlen=3)
Example #24
0
 def __init__(self):
     self._speed = 0.0
     self.current_deque = deque([0.0] * 3, 3)  # Used to average currents over last n readings
     self.log_queue = []
     self.velocity_queue = []
     self.previous_velocity = 0.0
     self.shoot_time = None
     self.sd = NetworkTable.getTable("SmartDashboard")
     self.write_log = False
Example #25
0
 def test_iadd(self):
     from _collections import deque
     d = deque('a')
     original_d = d
     d += 'bcd'
     assert list(d) == list('abcd')
     d += d
     assert list(d) == list('abcdabcd')
     assert original_d is d
 def __init__(self):
     '''
     Constructor
     '''
     self.execCommand = ""
     self.executionQueueList = deque()
     self.executionQueueListInProgress = False;
     self.console = eConsoleAppContainer()
     self.console.appClosed.append(self.__runFinished)
Example #27
0
 def test_getitem(self):
     from _collections import deque
     n = 200
     l = xrange(1000, 1000 + n)
     d = deque(l)
     for j in xrange(-n, n):
         assert d[j] == l[j]
     raises(IndexError, "d[-n-1]")
     raises(IndexError, "d[n]")
 def __init__(self, item_name, subscription_mgr):
     self._item_name = item_name
     self._tasks_deq = deque()
     self._code = None
     self._isrunning = False
     self._lock = threading.Lock()
     self._queued = 0
     self._last_subscribe_outcome = False
     self._subscription_mgr = subscription_mgr
Example #29
0
 def test_maxlen_zero(self):
     from _collections import deque
     it = iter(range(100))
     d = deque(it, maxlen=0)
     assert list(d) == []
     assert list(it) == []
     d.extend(range(100))
     assert list(d) == []
     d.extendleft(range(100))
     assert list(d) == []
Example #30
0
 def __init__(self, trace, title='Optimizations', **kwargs):
     # context should be a dictionary containing the backward traced result of each relevant register
     super(OptimizationViewer, self).__init__(title)
     self.orig_trace = trace
     self.trace = deepcopy(trace)
     self.undo_stack = deque([deepcopy(trace), deepcopy(trace), deepcopy(trace)], maxlen=3)
     self.opti_map = dict(zip(optimization_names, optimizations))
     self.order = []
     self.foldable_regs = []
     self.save = kwargs.get('save', None)
Example #31
0
from _collections import namedtuple

a = namedtuple('courses', 'name, tech, place')
s = a('mahesh', 'python', 'delhi')
t = a._make(['neha', 'go', 'delhi'])

print(s)
print(t)

#####################################################################
from _collections import deque

a = ['e', 'd', 'u', 't', 'a', 'm', 'h']
d = deque(a)

d.appendleft('w')  #append at begining
d.append('w')  #append at last
print(d)

d.pop()  #pop from last
d.popleft()  #pop from start

print(d)

#####################################################################
from _collections import ChainMap

a = {1: 'Mahesh', 2: 'Python'}
a = {1: 'Neha', 2: 'GoLang'}

c = ChainMap(a, b)
Example #32
0
metric = nn_matching.NearestNeighborDistanceMetric('cosine',
                                                   max_cosine_distance,
                                                   nn_budget)
tracker = Tracker(metric)

# Video
vid = cv2.VideoCapture('data/test.mp4')
codec = cv2.VideoWriter_fourcc(*'XVID')
vid_fps = int(vid.get(cv2.CAP_PROP_FPS))
vid_width, vid_height = int(vid.get(cv2.CAP_PROP_FRAME_WIDTH)), int(
    vid.get(cv2.CAP_PROP_FRAME_HEIGHT))
out = cv2.VideoWriter('./data/results.avi', codec, vid_fps,
                      (vid_width, vid_height))

from _collections import deque
pts = [deque(maxlen=30) for _ in range(1000)]

counter = []

while True:
    _, img = vid.read()
    if img is None:
        print('Completed')
        break

    img_in = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    img_in = tf.expand_dims(img_in, 0)
    img_in = transform_images(img_in, 416)

    t1 = time.time()
    boxes, scores, classes, nums = yolo.predict(img_in)
Example #33
0
from _collections import deque

green_light = int(input())
free_window = int(input())
command = input()

cars = deque()
current_seconds = green_light

cars_passed = 0

while command != "END":
    if command != "green":
        cars.append(command)
    else:
        current_seconds = green_light
        ongoing_ch = deque()
        while cars and current_seconds:
            car = cars.popleft()
            for x in car:
                ongoing_ch.append(x)
            while ongoing_ch:
                ongoing_ch.popleft()
                current_seconds -= 1

                if len(ongoing_ch) == 0:
                    cars_passed += 1

        command = input()

    command = input()
Example #34
0
from _collections import deque
a, b = map(int, input().split())
res = -1
q = deque()
q.append((a, 1))
while q:
    num, cnt = q.popleft()
    if num == b:
        res = cnt
        print(res)
        exit()
    if num * 2 <= b:
        q.append((num * 2, cnt + 1))
    if int(str(num) + '1') <= b:
        q.append((int(str(num) + '1'), cnt + 1))
print(res)
Example #35
0
from _collections import deque

my_dict = {}
toy = None
materials = list(map(int, input().split()))
magic_values = deque(list(map(int, input().split())))

while magic_values and materials:
    current_material = materials.pop()
    if current_material == 0:
        if magic_values[0] == 0:
            magic_values.popleft()
        continue
    current_magic_value = magic_values.popleft()
    if current_magic_value == 0:

        continue

    magic_level = current_material * current_magic_value

    if magic_level > 0:
        if magic_level == 150:
            toy = "Doll"
            if toy not in my_dict:
                my_dict[toy] = 0
            my_dict[toy] += 1

        elif magic_level == 250:
            toy = "Wooden train"
            if toy not in my_dict:
                my_dict[toy] = 0
Example #36
0
 def __init__(self, intervals, alphabet):
     self.intervals = deque()
     self.__index = None
     self.__str = None
     for interval in intervals:
         self.append(interval, alphabet)
Example #37
0
            vc = open(path, 'rb')
            bot.send_voice(msg.chat.id, voice=vc)
            vc.close()
            os.remove(path)
            settings[0] += 1
        bot.send_message(msg.chat.id, joke)
    elif "генерировать аудио" not in msg.text or "генерировать картинку" not in msg.text:
        keybd = telebot.types.ReplyKeyboardMarkup(True)
        btn1 = telebot.types.KeyboardButton(text=advice)
        btn4 = telebot.types.KeyboardButton(text="не генерировать аудио" if settings[1] else "генерировать аудио")
        btn5 = telebot.types.KeyboardButton(text="не генерировать картинку" if settings[2] else "генерировать картинку")
        btn3 = telebot.types.KeyboardButton(text=what_is_good)
        btn2 = telebot.types.KeyboardButton(text=what_is_bad)
        keybd.add(btn1)
        keybd.add(btn2)
        keybd.add(btn3)
        keybd.add(btn4)
        keybd.add(btn5)
        bot.send_message(msg.chat.id, "Как прикажешь!", reply_markup=keybd)
    else:
        bot.send_message(msg.chat.id, "Моя твоя не понимать. Щёлкай по предложенным кнопкам!")

    personal_settings[msg.chat.id] = settings


# personal_settings[user_id] = (i, gen_audio, gen_pics)
personal_settings = {} # хранятся настройки для каждого id отдельно
Q5 = deque() # содержатся последние 5 высказываний (чтобы не было частых повторов)

bot.polling()
Example #38
0
    temp = json.loads(req.text)
    return temp['calls']


def action(token, cmd):
    url = 'http://localhost:8000/action'
    req = requests.post(url,
                        headers={'X-Auth-Token': token},
                        json={'commands': cmd})
    temp = json.loads(req.text)
    return temp


st = start('tester', '2', '4')
token = st['token']
target = [deque() for _ in range(4)]
passen = [[] for _ in range(4)]
cmd = [{
    'elevator_id': 0,
    'command': 'STOP'
}, {
    'elevator_id': 1,
    'command': 'STOP'
}, {
    'elevator_id': 2,
    'command': 'STOP'
}, {
    'elevator_id': 3,
    'command': 'STOP'
}]
time = 0
Example #39
0
import sys
from _collections import deque
sys.stdin = open('5249.txt', 'r')

T = int(input())

for test_case in range(1, T+1):

    V , M = map(int,input().split())

    node_lst = [list(map(int,input().split())) for __ in range(M)]
    node_lst.sort(key=lambda x: x[2])
    node_lst =deque(node_lst)
    visit_lst = [0] * (M)
    stack = deque()
    weight = 0

    while node_lst:
        k = node_lst.popleft()
        if 0 not in visit_lst:
            break
        if visit_lst[k[0]] == 1 and visit_lst[k[1]] == 1:
            pass
        elif visit_lst[k[0]] == 0 and visit_lst[k[1]] == 0:
            visit_lst[k[0]] = 1
            visit_lst[k[1]] = 1
            stack.append(k[0])
            stack.append(k[1])
            weight = weight + k[2]
        elif visit_lst[k[0]] == 0 and visit_lst[k[1]] == 1:
            visit_lst[k[0]] = 1
from _collections import deque
from types import coroutine

friends = deque(('Rolf', 'Jose', 'Charlie', 'Jen', 'Anna'))


@coroutine
def friend_upper():
    while friends:
        friend = friends.popleft().upper()
        greeting = yield
        print(f'{greeting} {friend}')


async def greet(g):
    print('Startind ... ')
    await g
    print('Ending ... ')


greeter = greet(friend_upper())
greeter.send(None)
greeter.send('Hello')

greeting = input('Enter greeting: ')
greeter.send(greeting)

greeting = input('Enter greeting: ')
greeter.send(greeting)
Example #41
0
from _collections import deque


def Tohex(n):
    return int(n, 16)


T = int(input())
for ll in range(1, T + 1):
    N, K = map(int, input().split())
    number = deque(input())
    length = N // 4
    li = set()

    for _ in range(length):  # during length..  rotation
        t = []
        i = 0
        temp = ""
        while i < N:
            if len(temp) < length:
                temp += number[i]
            else:
                t.append(temp)
                temp = f'{number[i]}'
            i += 1
        t.append(temp)  # last
        for num in t:
            li.add(Tohex(num))
        number.appendleft(number.pop())  # rotation
    result = sorted(list(li), reverse=True)
    print(f'#{ll} {result[K-1]}')
server_addr = ''
server_port = 3004
client = None
rx_handle = None

# GRAMMAR
DISCONNECT = ""
SET_VTX_POS = "SET_VTX_POS"
GET_VTX_POS = "GET_VTX_POS"
GET_VTX_COUNT = "GET_VTX_COUNT"

SET_VTX_POS_VEC_SIZE = 4
GET_VTX_POS_VEC_SIZE = 1
GET_VTX_COUNT_VEC_SIZE = 1

data_queue = deque()
callback_idx = 0
th_handle = None
exit_thread = False
update_handle = None


def pack_vector(vec, precission=3):
    vec_rounded = [round(v, precission) for v in vec]
    data = '('
    idx = 0
    size = len(vec_rounded)
    for v in vec_rounded:
        data = data + str(v)
        idx = idx + 1
        if idx < size:
Example #43
0
    for tmp in itertool_list:
        original = copy.deepcopy(data)
        for t in tmp:
            data[t[0]][t[1]] = -1
        virus_time = spread()
        cnt = 0
        for i in data:
            cnt += i.count(0)
        if cnt == 0:
            check = 1
            time = min(time, virus_time)
        data = copy.deepcopy(original)


N, M = map(int, (sys.stdin.readline().split()))
data = []
virus = deque()
for i in range(N):
    data.append(list(map(int, sys.stdin.readline().split())))
    for j in range(N):
        if data[i][j] == 2:
            virus.append([i, j])
itertool_list = list(itertools.combinations(virus, M))
time = sys.maxsize
check = 0
solve(0)
if check == 0:
    print(-1)
else:
    print(time)
Example #44
0
import sys
import os
from _collections import deque

browser_history = deque()

args = sys.argv
saved_tabs_directory = args[1]
nytimes_com = '''
This New Liquid Is Magnetic, and Mesmerizing

Scientists have created “soft” magnets that can flow 
and change shape, and that could be a boon to medicine 
and robotics. (Source: New York Times)


Most Wikipedia Profiles Are of Men. This Scientist Is Changing That.

Jessica Wade has added nearly 700 Wikipedia biographies for
 important female and minority scientists in less than two 
 years.

'''
bloomberg_com = '''
The Space Race: From Apollo 11 to Elon Musk

It's 50 years since the world was gripped by historic images
 of Apollo 11, and Neil Armstrong -- the first man to walk 
 on the moon. It was the height of the Cold War, and the charts
 were filled with David Bowie's Space Oddity, and Creedence's 
 Bad Moon Rising. The world is a very different place than 
Example #45
0
import sys

input = sys.stdin.readline

N, K, M = map(int, input().split())
G = [[] for _ in range(N + M + 1)]
D = [0 for _ in range(N + M + 1)]
ans = False

for i in range(M):
    tube = list(map(int, input().split()))
    G[N + i + 1] = tube
    for j in range(K):
        G[tube[j]].append(N + i + 1)

Q = deque()
Q.append(1)
D[1] = 1
while Q:
    u = Q.popleft()
    if u == N:
        ans = D[u]
        break
    for w in G[u]:
        if not D[w]:
            if w > N:  # 하이퍼링크일때는 D 변화 없음
                D[w] = D[u]
                Q.append(w)
            else:
                D[w] = D[u] + 1
                Q.append(w)
Example #46
0
import sys
from _collections import deque

n, m = map(int, sys.stdin.readline().split())
miro = []
visited = [[0] * m for _ in range(n)]
for _ in range(n):
    miro.append(list(sys.stdin.readline().strip()))

dx = [0, 1, 0, -1]  #RDLU
dy = [1, 0, -1, 0]

cnt = 0

#탈출구들을 queue에 추가시키는 부분
queue = deque()
for i in range(n):
    for j in range(m):
        if miro[i][j] == 'R':
            miro[i][j] = 0
        elif miro[i][j] == 'D':
            miro[i][j] = 1
        elif miro[i][j] == 'L':
            miro[i][j] = 2
        elif miro[i][j] == 'U':
            miro[i][j] = 3

        x = i + dx[miro[i][j]]
        y = j + dy[miro[i][j]]

        if x < 0 or x >= n or y < 0 or y >= m:
Example #47
0
def test_deque():
    if is_cli or is_silverlight:
        from _collections import deque
    else:
        from collections import deque
    x = deque([2, 3, 4, 5, 6])
    x.remove(2)
    AreEqual(x, deque([3, 4, 5, 6]))
    x.remove(6)
    AreEqual(x, deque([3, 4, 5]))
    x.remove(4)
    AreEqual(x, deque([3, 5]))

    # get a deque w/ head/tail backwards...
    x = deque([1, 2, 3, 4, 5, 6, 7, 8])
    x.popleft()
    x.popleft()
    x.popleft()
    x.popleft()
    x.append(1)
    x.append(2)
    x.append(3)
    x.append(4)
    AreEqual(x, deque([5, 6, 7, 8, 1, 2, 3, 4]))
    x.remove(5)
    AreEqual(x, deque([6, 7, 8, 1, 2, 3, 4]))
    x.remove(4)
    AreEqual(x, deque([6, 7, 8, 1, 2, 3]))
    x.remove(8)
    AreEqual(x, deque([6, 7, 1, 2, 3]))
    x.remove(2)
    AreEqual(x, deque([6, 7, 1, 3]))

    class BadCmp:
        def __eq__(self, other):
            raise RuntimeError

    d = deque([1, 2, BadCmp()])
    AssertError(RuntimeError, d.remove, 3)

    x = deque()

    class y(object):
        def __eq__(self, other):
            return True

    x.append(y())
    AreEqual(y() in x, True)

    x = deque({}, None)
    AreEqual(x, deque([]))

    AssertErrorWithPartialMessage(TypeError,
                                  "takes at most 2 arguments (3 given)", deque,
                                  'abc', 2, 2)
        elif row[j] == 1:
            wall.append((i, j))
    arr.append(row)

# 가능한 모든 바이러스 시작 위치 조합에 대해
for comb in combinations(virus, M):

    # 바이러스가 퍼지지 않은 곳은 -1
    visited = [[-1] * N for _ in range(N)]

    # 벽은 0으로 세팅해준다.
    for r, c in wall:
        visited[r][c] = 0

    # 시작 위치들을 큐에 넣고, 그 자리들은 0
    queue = deque(comb)
    for r, c in comb:
        visited[r][c] = 0

    # 소요 시간
    cnt = 0

    while queue:

        # 현재 큐에서 모두 퍼지면 1초 증가
        cnt += 1
        for _ in range(len(queue)):
            r, c = queue.popleft()
            for dr, dc in move:
                nr, nc = r + dr, c + dc
                if 0 <= nr < N and 0 <= nc < N:
from _collections import deque
n,k=map(int,input().split())
res=[i for i in range(1,n+1)]
des=deque(res)
for i in range(n):
    cnt=1
    while k!=cnt:
        node=des.popleft()
        des.append(node)
        cnt+=1
    n=des.popleft()
print(n)
Example #50
0
sys.stdin = open("공주구하기.txt", "rt")
'''
n, k = map(int, input().split())
a = list(range(1,n+1))

cnt = 0
res = 0
while a:
    cnt+=1
    if cnt != k :
        a.append(a.pop(0))
    else:
        res = a.pop(0)
        cnt=0

print(res)
'''
from _collections import deque

n, k = map(int, input().split())
dq = list(range(1, n + 1))
dq = deque(dq)

while dq:
    for _ in range(k - 1):
        cur = dq.popleft()
        dq.append(cur)
    dq.popleft()
    if len(dq) == 1:
        print(dq[0])
        dq.popleft()
Example #51
0
 def get_retry_changes(self, exportid):
     return deque(Utils.default(self.export_items_db.get('retry-' + exportid), []))
from _collections import deque

n, m, k, x = map(int, input().split())
arr = [[] for _ in range(n + 1)]
for i in range(m):
    a, b = map(int, input().split())
    arr[a].append(b)

dis = [-1] * (n + 1)
dis[x] = 0
q = deque([x])

while q:
    tmp = q.popleft()
    for next_value in arr[tmp]:
        if dis[next_value] == -1:
            dis[next_value] = dis[tmp] + 1
            q.append(next_value)

check = False

for i in range(1, n + 1):
    if dis[i] == k:
        print(i)
        check = True
if check == False:
    print(-1)
Example #53
0
def main(_argv):

    class_names = [c.strip() for c in open('coco.names').readlines()]
    # class_names=['car', 'truck','bus', 'bicycle','motorbike']
    yolo = YoloV3(classes=len(class_names))
    yolo.load_weights('./weights/yolov3.tf')

    max_cosine_distance = 0.5
    nn_budget = None
    nms_max_overlap = 0.8

    model_filename = 'mars-small128.pb'
    encoder = gdet.create_box_encoder(model_filename, batch_size=1)
    metric = nn_matching.NearestNeighborDistanceMetric('cosine',
                                                       max_cosine_distance,
                                                       nn_budget)
    tracker = Tracker(metric)

    try:
        vid = cv2.VideoCapture(int(FLAGS.video))
    except:
        vid = cv2.VideoCapture(FLAGS.video)

    out = None

    if FLAGS.output:
        codec = cv2.VideoWriter_fourcc(*FLAGS.output_format)
        vid_fps = int(vid.get(cv2.CAP_PROP_FPS))
        vid_width, vid_height = int(vid.get(cv2.CAP_PROP_FRAME_WIDTH)), int(
            vid.get(cv2.CAP_PROP_FRAME_HEIGHT))
        out = cv2.VideoWriter(FLAGS.output, codec, vid_fps,
                              (vid_width, vid_height))

    from _collections import deque
    pts = [deque(maxlen=30) for _ in range(1000)]

    counter = []

    while True:
        _, img = vid.read()
        if img is None:
            print('Completed')
            break

        img_in = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
        img_in = tf.expand_dims(img_in, 0)
        img_in = transform_images(img_in, 416)

        t1 = time.time()

        boxes, scores, classes, nums = yolo.predict(img_in)

        classes = classes[0]
        names = []
        for i in range(len(classes)):

            names.append(class_names[int(classes[i])])
        names = np.array(names)
        converted_boxes = convert_boxes(img, boxes[0])
        features = encoder(img, converted_boxes)

        detections = [
            Detection(bbox, score, class_name, feature)
            for bbox, score, class_name, feature in zip(
                converted_boxes, scores[0], names, features)
        ]

        boxs, scores, classes = [], [], []
        f = ['car', 'truck', 'bus', 'bicycle', 'motorbike']
        for d in detections:
            if d.class_name in f:
                boxs.append(d.tlwh)
                scores.append(d.confidence)
                classes.append(d.class_name)

        boxs = np.array(boxs)
        scores = np.array(scores)
        classes = np.array(classes)
        indices = preprocessing.non_max_suppression(boxs, classes,
                                                    nms_max_overlap, scores)
        detections = [detections[i] for i in indices]

        tracker.predict()
        tracker.update(detections)

        cmap = plt.get_cmap('tab20b')
        colors = [cmap(i)[:3] for i in np.linspace(0, 1, 20)]

        for track in tracker.tracks:
            if track.class_name in f:
                # print("new track")

                if not track.is_confirmed() or track.time_since_update > 1:
                    continue
                bbox = track.to_tlbr()
                class_name = track.get_class()
                color = colors[int(track.track_id) % len(colors)]
                color = [i * 255 for i in color]

                cv2.rectangle(img, (int(bbox[0]), int(bbox[1])),
                              (int(bbox[2]), int(bbox[3])), color, 2)

                center = (int(((bbox[0]) + (bbox[2])) / 2),
                          int(((bbox[1]) + (bbox[3])) / 2))
                pts[track.track_id].append(center)

                for j in range(1, len(pts[track.track_id])):
                    if pts[track.track_id][j - 1] is None or pts[
                            track.track_id][j] is None:
                        continue
                    thickness = int(np.sqrt(64 / float(j + 1)) * 2)
                    cv2.line(img, (pts[track.track_id][j - 1]),
                             (pts[track.track_id][j]), color, thickness)

                height, width, _ = img.shape
                # print("p",height,width)
                # print(int(3*height/6+height/20))

                oo = [int(x) for x in FLAGS.line_coordinates]
                print(oo)
                cv2.line(img, (oo[0], oo[1]), (oo[2], oo[3]), (0, 255, 0),
                         thickness=2)

                center_y = int(((bbox[1]) + (bbox[3])) / 2)

                if center_y <= int(3 * height / 6 + height /
                                   20) and center_y >= int(3 * height / 6 -
                                                           height / 20):

                    counter.append(int(track.track_id))

                    print(int(track.track_id))

        total_count = len(set(counter))
        h, w = img.shape[0:2]
        img[0:70, 0:500] = [0, 0, 0]

        cv2.putText(img, "Total Vehicle Count: " + str(total_count), (7, 56),
                    cv2.FONT_HERSHEY_SIMPLEX, 1.25, (255, 255, 255), 2)

        cv2.resizeWindow('output', 1024, 768)
        cv2.imshow('output', img)
        out.write(img)

        if cv2.waitKey(1) == ord('q'):
            break
    vid.release()
    out.release()
    cv2.destroyAllWindows()
Example #54
0
def main():

    # Files to output the data to
    ONE_REGISTER_OUTPUT = open("ONE_REG.txt", 'w')  # One register
    FOUR_REGISTER_OUTPUT = open("FOUR_REG.txt", 'w')  # 4 Registers
    INTPUT_DATA = open("INPUT.txt", 'w')  # Input data used
    ONE_TO_FOUR = open("ONE_TO_FOUR_REG.txt",
                       'w')  # One input register, 4 output registers
    FOUR_TO_ONE = open("FOUR_TO_ONE_REG.txt",
                       'w')  # Four input registers, one output register

    # Output data
    output_data1 = []
    output_data2 = []
    output_data3 = []
    output_data4 = []

    # Queues to be populated and used
    priority_queue = []
    sorted_queue = linkedList.LinkedList()
    FIFO = deque()
    LIFO = Stack()

    # Input and output registers
    clock_in = 0
    clock_out = 0

    # Data to be used - @ params low - high values
    data_priority = get_random(0, 99)
    data_fifo = get_random(0, 99)
    data_lifo = get_random(0, 99)
    data_sorted = get_random(0, 99)
    priority_num = get_random(1, 3)

    #   Prints and formats input data to output file
    format_data('FIFO input data: ', data_fifo, INTPUT_DATA)
    INTPUT_DATA.write("\n")
    INTPUT_DATA.write("\n")

    format_data('LIFO input data: ', data_lifo, INTPUT_DATA)
    INTPUT_DATA.write("\n")
    INTPUT_DATA.write("\n")

    format_data('Sorted input data: ', data_sorted, INTPUT_DATA)
    INTPUT_DATA.write("\n")
    INTPUT_DATA.write("\n")

    format_data('Priority input data: ', data_priority, INTPUT_DATA)
    INTPUT_DATA.write("\n")
    INTPUT_DATA.write("\n")
    count = 0

    # One register input - One register output
    for i in range(9):
        # Adds to queue
        input1 = data_fifo[i]
        FIFO.append(input1)
        clock_in += 1

        # Adds to stack
        input1 = data_lifo[i]
        LIFO.push(input1)
        clock_in += 1

        # Adds to Sorted Queue
        input1 = data_sorted[i]
        sorted_queue.add_sorted(input1)
        clock_in += 1

        # Adds to Priority queue
        input1 = data_priority[i]
        heap.heappush(priority_queue, (priority_num[i], count, input1))
        count += 1
        clock_in += 1

    for i in range(9, 100):
        # FIFO output
        output1 = FIFO.popleft()
        output_data1.append(output1)
        clock_out += 1

        # LIFO output
        output1 = LIFO.pop()
        output_data2.append(output1)
        clock_out += 1

        # Sorted output
        output1 = sorted_queue.pop()
        output_data3.append(output1)
        clock_out += 1

        # Priority Output
        output1 = heap.heappop(priority_queue)[2]
        output_data4.append(output1)
        clock_out += 1

        # FIFO input
        input1 = data_fifo[i]
        FIFO.append(input1)
        clock_in += 1

        # LIFO input
        input1 = data_lifo[i]
        LIFO.push(input1)
        clock_in += 1

        # Sorted input
        input1 = data_sorted[i]
        sorted_queue.add_sorted(input1)
        clock_in += 1

        # Priority Input
        input1 = data_priority[i]
        heap.heappush(priority_queue, (priority_num[i], count, input1))
        count += 1
        clock_in += 1

    for i in range(9):
        # FIFO output
        output1 = FIFO.popleft()
        output_data1.append(output1)
        clock_out += 1

        # LIFO output
        output1 = LIFO.pop()
        output_data2.append(output1)
        clock_out += 1

        # Sorted output
        output1 = sorted_queue.pop()
        output_data3.append(output1)
        clock_out += 1

        # Priority output
        output1 = heap.heappop(priority_queue)[2]
        output_data4.append(output1)
        clock_out += 1

    print(str(clock_in) + " in " + str(clock_out) + " out")
    format_data('FIFO Output Data: ', output_data1, ONE_REGISTER_OUTPUT)
    ONE_REGISTER_OUTPUT.write("\n")
    ONE_REGISTER_OUTPUT.write("\n")

    format_data('LIFO Output Data: ', output_data2, ONE_REGISTER_OUTPUT)
    ONE_REGISTER_OUTPUT.write("\n")
    ONE_REGISTER_OUTPUT.write("\n")

    format_data('Sorted Output Data: ', output_data3, ONE_REGISTER_OUTPUT)
    ONE_REGISTER_OUTPUT.write("\n")
    ONE_REGISTER_OUTPUT.write("\n")

    format_data('Priority Output Data: ', output_data4, ONE_REGISTER_OUTPUT)
    ONE_REGISTER_OUTPUT.write("\n")
    ONE_REGISTER_OUTPUT.write("\n" + str(clock_in) + " in " + str(clock_out) +
                              " out")

    # Clearing output data for next run
    output_data1.clear()
    output_data2.clear()
    output_data3.clear()
    output_data4.clear()

    clock_in = 0
    clock_out = 0
    count = 0

    # This a 4 register input - 4 Register Output
    for i in range(9):
        input1 = data_fifo[i]
        input2 = data_lifo[i]
        input3 = data_sorted[i]
        input4 = data_priority[i]
        # FIFO input
        FIFO.append(input1)
        LIFO.push(input2)
        sorted_queue.add_sorted(input3)
        # Priority Input
        heap.heappush(priority_queue, (priority_num[i], count, input4))
        count += 1
        clock_in += 1

    for i in range(9, 100):
        # Register inputs
        input1 = data_fifo[i]
        input2 = data_lifo[i]
        input3 = data_sorted[i]
        input4 = data_priority[i]

        # FIFO, LIFO, sorted, and priority output to output registers
        output1 = FIFO.popleft()
        output2 = LIFO.pop()
        output3 = sorted_queue.pop()
        output4 = heap.heappop(priority_queue)[2]
        clock_out += 1

        # Stores output data from register
        output_data1.append(output1)
        output_data2.append(output2)
        output_data3.append(output3)
        output_data4.append(output4)

        # FIFO, LIFO, sorted, and priority input from input registers
        FIFO.append(input1)
        LIFO.push(input2)
        sorted_queue.add_sorted(input3)
        heap.heappush(priority_queue, (priority_num[i], count, input4))
        count += 1
        clock_in += 1

    for j in range(9):
        # FIFO, LIFO, sorted, and priority output to output registers
        output1 = FIFO.popleft()
        output2 = LIFO.pop()
        output3 = sorted_queue.pop()
        output4 = heap.heappop(priority_queue)[2]

        # Stores output data from register
        output_data1.append(output1)
        output_data2.append(output2)
        output_data3.append(output3)
        output_data4.append(output4)
        clock_out += 1

    print(str(clock_in) + " in " + str(clock_out) + " out")

    format_data('FIFO output data: ', output_data1, FOUR_REGISTER_OUTPUT)
    FOUR_REGISTER_OUTPUT.write("\n")
    FOUR_REGISTER_OUTPUT.write("\n")

    format_data('LIFO output data: ', output_data2, FOUR_REGISTER_OUTPUT)
    FOUR_REGISTER_OUTPUT.write("\n")
    FOUR_REGISTER_OUTPUT.write("\n")

    format_data('Sorted output data: ', output_data3, FOUR_REGISTER_OUTPUT)
    FOUR_REGISTER_OUTPUT.write("\n")
    FOUR_REGISTER_OUTPUT.write("\n")

    format_data('Priority output data: ', output_data4, FOUR_REGISTER_OUTPUT)
    FOUR_REGISTER_OUTPUT.write("\n")

    FOUR_REGISTER_OUTPUT.write("\n" + str(clock_in) + " in " + str(clock_out) +
                               " out")

    # Clearing output data for next run
    output_data1.clear()
    output_data2.clear()
    output_data3.clear()
    output_data4.clear()

    clock_in = 0
    clock_out = 0
    count = 0

    #   One input register, 4 output registers
    for i in range(9):
        #FIFO input
        input1 = data_fifo[i]
        FIFO.append(input1)
        clock_in += 1

        # LIFO input
        input1 = data_lifo[i]
        LIFO.push(input1)
        clock_in += 1

        # Sorted input
        input1 = data_sorted[i]
        sorted_queue.add_sorted(input1)
        clock_in += 1

        # Priority Input
        input1 = data_priority[i]
        heap.heappush(priority_queue, (priority_num[i], count, input1))
        count += 1
        clock_in += 1

    for i in range(9, 100):
        # FIFO, LIFO, sorted, and priority output to output registers
        output1 = FIFO.popleft()
        output2 = LIFO.pop()
        output3 = sorted_queue.pop()
        output4 = heap.heappop(priority_queue)[2]

        # Stores output data from register
        output_data1.append(output1)
        output_data2.append(output2)
        output_data3.append(output3)
        output_data4.append(output4)
        clock_out += 1

        # FIFO input
        input1 = data_fifo[i]
        FIFO.append(input1)
        clock_in += 1

        # LIFO input
        input1 = data_lifo[i]
        LIFO.push(input1)
        clock_in += 1

        # Sorted input
        input1 = data_sorted[i]
        sorted_queue.add_sorted(input1)
        clock_in += 1

        # Priority Input
        input1 = data_priority[i]
        heap.heappush(priority_queue, (priority_num[i], count, input1))
        count += 1
        clock_in += 1

    for i in range(9):
        # FIFO, LIFO, sorted, and priority output to output registers
        output1 = FIFO.popleft()
        output2 = LIFO.pop()
        output3 = sorted_queue.pop()
        output4 = heap.heappop(priority_queue)[2]

        # Stores output data from register
        output_data1.append(output1)
        output_data2.append(output2)
        output_data3.append(output3)
        output_data4.append(output4)
        clock_out += 1

    print(str(clock_in) + " in " + str(clock_out) + " out")

    format_data('FIFO Output Data: ', output_data1, ONE_TO_FOUR)
    ONE_TO_FOUR.write("\n")
    ONE_TO_FOUR.write("\n")

    format_data('LIFO Output Data: ', output_data2, ONE_TO_FOUR)
    ONE_TO_FOUR.write("\n")
    ONE_TO_FOUR.write("\n")

    format_data('Sorted Output Data: ', output_data3, ONE_TO_FOUR)
    ONE_TO_FOUR.write("\n")
    ONE_TO_FOUR.write("\n")

    format_data('Priority Output Data: ', output_data4, ONE_TO_FOUR)
    ONE_TO_FOUR.write("\n")
    ONE_TO_FOUR.write("\n" + str(clock_in) + " in " + str(clock_out) + " out")

    # Clears output data for next run
    output_data1.clear()
    output_data2.clear()
    output_data3.clear()
    output_data4.clear()

    clock_in = 0
    clock_out = 0
    count = 0

    # Four Registers Input, One register output
    for i in range(9):
        # Input registers
        input1 = data_fifo[i]
        input2 = data_lifo[i]
        input3 = data_sorted[i]
        input4 = data_priority[i]

        # FIFO, LIFO, sorted, and priority input from input registers
        FIFO.append(input1)
        LIFO.push(input2)
        sorted_queue.add_sorted(input3)
        heap.heappush(priority_queue, (priority_num[i], count, input4))
        count += 1
        clock_in += 1

    for i in range(9, 100):
        # FIFO output
        output1 = FIFO.popleft()
        output_data1.append(output1)
        clock_out += 1

        # LIFO output
        output1 = LIFO.pop()
        output_data2.append(output1)
        clock_out += 1

        # Sorted output
        output1 = sorted_queue.pop()
        output_data3.append(output1)
        clock_out += 1

        # Priority output
        output1 = heap.heappop(priority_queue)[2]
        output_data4.append(output1)
        clock_out += 1

        # Input registers
        input1 = data_fifo[i]
        input2 = data_lifo[i]
        input3 = data_sorted[i]
        input4 = data_priority[i]

        # FIFO, LIFO, sorted, and priority input from input registers
        FIFO.append(input1)
        LIFO.push(input2)
        sorted_queue.add_sorted(input3)
        heap.heappush(priority_queue, (priority_num[i], count, input4))
        count += 1
        clock_in += 1

    for i in range(9):
        # FIFO output
        output1 = FIFO.popleft()
        output_data1.append(output1)
        clock_out += 1
        # LIFO output
        output1 = LIFO.pop()
        output_data2.append(output1)
        clock_out += 1
        # Sorted output
        output1 = sorted_queue.pop()
        output_data3.append(output1)
        clock_out += 1
        # Priority output
        output1 = heap.heappop(priority_queue)[2]
        output_data4.append(output1)
        clock_out += 1

    print(str(clock_in) + " in " + str(clock_out) + " out")

    format_data('FIFO Output Data: ', output_data1, FOUR_TO_ONE)
    FOUR_TO_ONE.write("\n")
    FOUR_TO_ONE.write("\n")

    format_data('LIFO Output Data: ', output_data2, FOUR_TO_ONE)
    FOUR_TO_ONE.write("\n")
    FOUR_TO_ONE.write("\n")

    format_data('Sorted Output Data: ', output_data3, FOUR_TO_ONE)
    FOUR_TO_ONE.write("\n")
    FOUR_TO_ONE.write("\n")

    format_data('Priority Output Data: ', output_data4, FOUR_TO_ONE)
    FOUR_TO_ONE.write("\n")
    FOUR_TO_ONE.write("\n" + str(clock_in) + " in " + str(clock_out) + " out")
        # cv2.putText(img, class_name+"-"+str(track.track_id), (int(bbox[0]), int(bbox[1]-10)), 0, 0.75,
        #             (255, 255, 255), 2)

        # Merkez bul
        center = (int(
            ((bbox[0]) + (bbox[2])) / 2), int(
                ((bbox[1]) + (bbox[3])) / 2))  # (665, 113),  class = tuple
        # center = (int(((tbox[0]) + (tbox[2]/2.0))), int(((tbox[1])+(tbox[3]/2.0))))
        # track_id => sürekli artıyor sınırsız şekilde, yavaş yavaş artıyor

        # Yeni kod
        if (is_init_frame == True):
            # prev_frame_objects.append([(center[0], center[1]), ot.get_init_index(), 0, deque(), -1, 0, bbox])
            prev_frame_objects.append([(center[0], center[1]),
                                       ot.find_next_free_index(), 0,
                                       deque(), -1, 0, bbox])
        else:
            cur_frame_objects.append([(center[0], center[1]), 0, 0,
                                      deque(), -1, 0, bbox])

    if (is_init_frame == False):
        # We only run when we have had at least 1 object detected in the previous (initial) frame
        if (len(prev_frame_objects) != 0):
            cur_frame_objects = ot.sort_cur_objects(prev_frame_objects,
                                                    cur_frame_objects)
            p.print(cur_frame_objects)

    # FPS hesapla
    fps = 1. / (time.time() - t1)
    cv2.putText(img, "FPS: {:.2f}".format(fps), (0, 30), 0, 1, (0, 0, 255), 2)
    cv2.resizeWindow('output', 1024, 768)
'''

from _collections import deque


def search(lines, pattern, history=5):
    previous_lines = deque(maxlen=history)

    for line in lines:
        if pattern in line:
            yield line, previous_lines
        previous_lines.append(line)


# Example use on a file
if __name__ == '__main__':
    with open('\123.txt') as f:
        # with open('123.txt') as f: # FileNotFoundError: [Errno 2] No such file or directory: '123.txt'
        for line, prevlines in search(f, 'python', 5):
            for pline in prevlines:
                print(pline)  # print (pline, end='')
            print(line)  # print (pline, end='')
            print('-' * 20)
q = deque(maxlen=3)
q.append(1)
q.append(2)
q.append(3)
print(q)
q.append(4)
print(q)
Example #57
0
from _collections import deque

spisok = [2, 14, 'gdsgsdg']

ochered = deque(spisok)  # преобразуем список в очередь
# ochered = deque([1, 2, 'dsdasd'])  # очередь
ochered.append(22)  # добавление в конец очереди
ochered.appendleft('108dd')  # добавление в начало очереди
ochered.pop()  # удаление с конца очереди
ochered.popleft()  # удаление с начала очереди
print(ochered)
Example #58
0
from _collections import deque
edges = [[1,2,3],[0,4],[0,3],[0,2,4],[1,3]];
weights = [[1,1,0],[1,0],[0,0],[0,0,0],[0,0]];
ini = float('inf');
s = 0;
index = s;
count = 0;
foundNode = False;
d = deque();
d.append(s);
dis = [ini, ini, ini, ini, ini];
dis[s] = 0;
while d:
    v = d.popleft();
    for i in range(len(edges[v])):
        if (dis[edges[v][i]] > dis[v] + weights[v][i]):
            dis[edges[v][i]] = dis[v] + weights[v][i];
            if(weights[v][i] == 0):
                d.appendleft(edges[v][i]);
            else:
                d.append(edges[v][i]);
print(dis);
Example #59
0
from _collections import deque

N, Q = map(int, input().split())
graph = [[] for _ in range(N + 1)]
for i in range(N - 1):
    u, v = map(int, input().split())
    graph[u].append(v)
    graph[v].append(u)

points = [0] * (N + 1)
for i in range(Q):
    p, x = map(int, input().split())
    points[p] += x

stack = deque()
stack.append(1)
score = 0
score_array = [0] * (N + 1)
is_checked = [0] * (N + 1)
#print(graph)
while stack:
    node = stack.pop()
    is_checked[node] = 1

    #print("node=" + str(node))
    score_array[node] += points[node]
    #print("score=" + str(score_array[node]))
    for goto in graph[node]:
        if not is_checked[goto]:
            #print("goto=" + str(goto))
            stack.append(goto)
Example #60
0
 def get_pending_changes(self, exportid):
     return deque(Utils.default(self.export_items_db.get('pending-' + exportid), []))