コード例 #1
0
def get_knot_hash(lengths):
    lengths.extend(LENGTHS_SUFFIX)
    skip_size = 0
    current_position = 0

    total_score = 0
    total_in_garbage = 0

    real_list = [x for x in range(256)]
    cl = CircularList(real_list)


    for length in lengths * NUM_ROUNDS:
        cl.reverse_portion(current_position, length)
        current_position += length
        current_position += skip_size
        skip_size += 1

    sparse_hashes = []

    for x in range(16):
        offset = 16 * x
        sh = 0
        for i in range(16):
            sh ^= cl[offset + i]

        sparse_hashes.append(sh)

    return "".join([format(sh, '02x') for sh in sparse_hashes])
コード例 #2
0
ファイル: room.py プロジェクト: RieCo432/projectSoleCubiculum
 def set_sequences(self, a1, a2, a3, a4, a5, a6, a7, a8, c1, c2, c3, c4, v1,
                   v2, v3, v4):
     # create circular lists for each set with corresponding edges
     self.all_edges_in_order = CircularList(
         (a1, a2, a3, a4, a5, a6, a7, a8))
     self.ceiling_edges_clockwise = CircularList((c1, c2, c3, c4))
     self.vertical_edges_up = CircularList((v1, v2, v3, v4))
コード例 #3
0
 def __init__(self, cache_size=None):
     self.required_updates = []
     # they are held here until it is synced with exchange candles timeframe
     self.pending_updates = []
     self.partial_candles = []
     self.cache_size = CandleBuilder.DEFAULT_CACHE_SIZE if cache_size is None else cache_size
     self.candles_list = CircularList(self.cache_size)
コード例 #4
0
def get_basic_section(start, classified_pixels, start_back=None):
    # 'gradient' vector
    delta = np.array([0, 0])

    last_gradients = CircularList()

    section = []
    section.append(start)

    x, y = start
    next, next_value = get_max_neighbor(classified_pixels, x, y, start_back)
    delta = np.subtract(next, start)

    while next_value == 2:  # edge pixel
        last_gradients.insert((delta[0], delta[1]))
        section.append(next)

        next = np.add(next, delta)
        next_value = classified_pixels[next[0], next[1]]

        if next_value < 2:  # blank pixel or miscellaneous pixel
            last = section[-1]  # get last element added in section
            x, y = last
            back = np.subtract(last, delta)

            # get max value in the neighborhood, unless the 'back'
            next, next_value = get_max_neighbor(classified_pixels, x, y, back)

            delta = np.subtract(next, last)

    last_gradients.insert((delta[0], delta[1]))
    section.append(next)
    last_element = next

    return section, last_gradients, last_element
コード例 #5
0
ファイル: room.py プロジェクト: RieCo432/projectSoleCubiculum
    def build_list_horizontal_circle(self, include_vertical=True):
        list_of_leds = CircularList()

        if include_vertical:
            # iterate through all edges in order and add LED numbers of ceiling strips to list, add list of LEDs in
            # vertical edges as list so they function as a single LED
            for edge in self.all_edges_in_order:
                if edge in self.ceiling_edges_clockwise:
                    for led in edge.leds:
                        list_of_leds.append([led])
                else:
                    list_of_leds.append(edge.leds)
        else:
            # iterate through edges and add the led numbers to the circular list
            for edge in self.ceiling_edges_clockwise:
                for led in edge.leds:
                    list_of_leds.append([led])

        return list_of_leds
コード例 #6
0
ファイル: room.py プロジェクト: RieCo432/projectSoleCubiculum
    def christmas_animation(self, duration=3600):

        startTime = datetime.now()

        ceiling_led_list = CircularList()

        for edge in self.ceiling_edges_clockwise:
            for led_number in edge.leds:
                ceiling_led_list.append(led_number)

        # print(ceiling_led_list._data)

        last_ceiling_stamp = datetime.now()
        last_vertical_stamp = datetime.now()
        update_necessary = False

        while (datetime.now() - startTime).total_seconds() <= duration:

            if (datetime.now() - last_ceiling_stamp).total_seconds() >= 1:
                for i in ceiling_led_list:
                    color = (0, 0, 0)
                    color_pick = randint(1, 10)
                    if color_pick == 0:
                        color = (0, 0, 255)
                    elif 1 <= color_pick <= 6:
                        color = (255, 0, 0)
                    elif 7 <= color_pick <= 10:
                        color = (0, 255, 0)
                    self.set_led(i, color)

                ceiling_led_list.shiftForward()
                last_ceiling_stamp = datetime.now()
                update_necessary = True

            if (datetime.now() - last_vertical_stamp).total_seconds() >= 0.05:
                for edge in self.vertical_edges_up:
                    for i in range(edge.length):
                        offset = 2 * i
                        self.set_led(
                            edge.leds[i],
                            (255, max(0, min(255,
                                             offset + randint(-15, 15))), 0))
                last_vertical_stamp = datetime.now()
                update_necessary = True

            if update_necessary:
                update_necessary = False
                self.update()

            time.sleep(0.1)
コード例 #7
0
ファイル: room.py プロジェクト: RieCo432/projectSoleCubiculum
    def build_list_vertical_straight(self, include_horizontal=True):
        list_of_leds = CircularList()

        for i in range(0, self.vertical_edges_up[0].length):
            list_of_leds.append([
                self.vertical_edges_up[0].leds[i],
                self.vertical_edges_up[1].leds[i],
                self.vertical_edges_up[2].leds[i],
                self.vertical_edges_up[3].leds[i]
            ])

        if include_horizontal:
            all_horizontal = []
            for edge in self.ceiling_edges_clockwise:
                for n in edge.leds:
                    all_horizontal.append(n)

            list_of_leds.append(all_horizontal)

        return list_of_leds
コード例 #8
0
def get_crossing_section_direction(classified_pixels, crossing_pixel,
                                   last_gradients, section):
    # counter gradients frequency
    cnt_gradient = Counter(last_gradients.get_list())
    # count in list
    grads = cnt_gradient.most_common()

    crossing_section_direction = []

    next = crossing_pixel
    next_value = classified_pixels[next[0], next[1]]

    # back is a edge pixel
    back = section[-2][0], section[-2][1]

    # avoid local minima
    iterations = 0
    loop_grads = CircularList(3)
    excluded_grad = None

    while next_value != 2:  # edge pixel
        aux_value = 0
        i = 0

        if iterations == 3:
            list_loop_grads = loop_grads.get_list()
            excluded_grad = list_loop_grads[1]
            crossing_section_direction[:] = []
            iterations = 0

        # blank pixel or miscellaneous and i < len
        while aux_value < 2 and i < len(grads):
            if grads[i][0] == excluded_grad:
                continue

            delta = grads[i][0]
            aux = np.add(next, delta)

            if aux[0] == back[0] and aux[1] == back[
                    1]:  # back[0] >= 0 and back[1] >= 0 and
                aux_value = 0
            else:
                aux_value = classified_pixels[aux[0], aux[1]]

            i += 1

        if aux_value < 2 and i == len(grads):
            delta = get_direction(classified_pixels, back, next, grads,
                                 excluded_grad)

            loop_grads.insert(delta)
            back = next[0], next[1]
            next = np.add(next, delta)
            next_value = classified_pixels[next[0], next[1]]
        else:
            loop_grads.insert(delta)
            back = next[0], next[1]
            next = aux
            next_value = aux_value

        crossing_section_direction.append(next)
        iterations += 1

    return crossing_section_direction
コード例 #9
0
from circular_list import CircularList
NUM_ROUNDS = 64

LENGTHS_SUFFIX = [17, 31, 73, 47, 23]

skip_size = 0
current_position = 0

total_score = 0
total_in_garbage = 0

real_list = [x for x in range(256)]
cl = CircularList(real_list)

with open("input.txt", "rb") as input_file:
    line = input_file.read()[:-1]
    lengths = [c for c in line]
    lengths.extend(LENGTHS_SUFFIX)

for length in lengths * NUM_ROUNDS:
    cl.reverse_portion(current_position, length)
    current_position += length
    current_position += skip_size
    skip_size += 1

sparse_hashes = []

for x in range(16):
    offset = 16 * x
    sh = 0
    for i in range(16):
コード例 #10
0
 def setUp(self):
     self.buffer = CircularList(self.buffer_size)
コード例 #11
0
class TestCircularList(TestCase):

    messages = ["Gentlemen, you can't fight in here! This is the War Room!",
                "Man who catch fly with chopstick accomplish anything.",
                "If you build it, he will come.",
                "I'm gonna make him an offer he can't refuse.",
                "Life is a box of chocolates, Forrest. You never know what you're gonna get.",
                "Nobody puts Baby in a corner.",
                "The cold never bothered me anyway.",
                "Well, what if there is no tomorrow? There wasn't one today.",
                "You talkin' to me?"
                ]

    buffer_size = 4

    def setUp(self):
        self.buffer = CircularList(self.buffer_size)

    def test_append(self):
        self.buffer.append(self.messages[1])

        self.assertEqual(self.buffer.get_newest()[1], self.messages[1])

    def test_get_newest(self):
        self.buffer.append(self.messages[1])
        self.buffer.append(self.messages[2])

        self.assertEqual(self.buffer.get_newest()[1], self.messages[2])

    def test_get_oldest(self):
        self.buffer.append(self.messages[0])
        self.buffer.append(self.messages[1])

        self.assertEqual(self.buffer.get_oldest()[1], self.messages[0])

    def test_get_oldest_empty(self):
        with self.assertRaises(LookupError):
            self.buffer.get_oldest()

    def test_get_oldest_overwritten(self):
        for i in range(5):
            self.buffer.append(self.messages[i])

        self.assertEqual(self.buffer.get_oldest()[1], self.messages[1])

    def test_get_next(self):
        id_packet = self.buffer.append(self.messages[1])
        self.buffer.append(self.messages[2])

        self.assertEqual(self.buffer.get_next(id_packet)[1], self.messages[2])

    def test_get_next_empty(self):
        with self.assertRaises(LookupError):
            self.buffer.get_next(None)

    def test_get_next_isLast(self):
        id_packet = self.buffer.append(self.messages[1])

        with self.assertRaises(EOFError):
            self.buffer.get_next(id_packet)

    def test_get_next_bufferFull(self):
        id_packet = None
        for i in range(self.buffer_size):
            id_packet = self.buffer.append(self.messages[i])

        with self.assertRaises(EOFError):
            self.buffer.get_next(id_packet)

    def test_get_next_overwritten(self):
        id_packet = self.buffer.append(self.messages[1])
        for i in range(self.buffer_size):
            self.buffer.append(self.messages[i])

        with self.assertRaises(LookupError):
            self.buffer.get_next(id_packet)

    def test_get_since(self):
        id_packet = self.buffer.append(self.messages[1])
        self.buffer.append(self.messages[2])
        self.buffer.append(self.messages[3])

        new_id_packet, received_messages = self.buffer.get_since(id_packet)
        self.assertEqual(received_messages, self.messages[2:4])

        with self.assertRaises(EOFError):
            self.buffer.get_since(new_id_packet)

    def test_get_since_overwritten(self):
        id_packet = self.buffer.append(self.messages[1])

        for i in range(1, 5):
            self.buffer.append(self.messages[i])

        with self.assertRaises(LookupError):
            self.buffer.get_since(id_packet)
コード例 #12
0
class CandleBuilder(object):
    DEFAULT_CACHE_SIZE = 1000

    def __init__(self, cache_size=None):
        self.required_updates = []
        # they are held here until it is synced with exchange candles timeframe
        self.pending_updates = []
        self.partial_candles = []
        self.cache_size = CandleBuilder.DEFAULT_CACHE_SIZE if cache_size is None else cache_size
        self.candles_list = CircularList(self.cache_size)

    def add_request_update(self, interval, requester):
        if self.candles_list.length(
        ) < interval or interval == 1:  # If interval is 1, we do not need headstart
            self.pending_updates.append(RequestUpdate(interval, requester))
        else:
            request_update = RequestUpdate(interval=interval,
                                           requester=requester)
            headstart_length = self.get_num_candles_for_headstart(interval)
            headstart_candles = self.candles_list.get_last_n_elements(
                headstart_length)
            for candle in headstart_candles:
                request_update.update(candle)
            self.required_updates.append(request_update)

    def remove_request_update(self, requester):
        for update in self.pending_updates:
            if update.requester == requester:
                self.pending_updates.remove(update)
                break

        for update in self.required_updates:
            if update.requester == requester:
                self.required_updates.remove(update)
                break

    def get_num_candles_for_headstart(self, interval):
        last_candle = self.candles_list.get_last_elemet()
        time = datetime.datetime.fromtimestamp(last_candle['open_time'] / 1000)
        minutes = time.hour * 60 + time.minute
        return minutes % interval

    def check_pending_updates(self, candle):
        if len(self.pending_updates) == 0:
            return

        tmp_updates = []
        time = datetime.datetime.fromtimestamp(candle['open_time'] / 1000)
        minutes = time.hour * 60 + time.minute
        for update in self.pending_updates:
            now = datetime.datetime.now()
            if minutes % update.interval == 0:
                tmp_updates.append(update)

        for tmp_update in tmp_updates:
            self.pending_updates.remove(tmp_update)
            self.required_updates.append(tmp_update)

    def on_new_candle(self, candle):
        self.candles_list.add(candle)
        if len(self.partial_candles) == 0:
            self.partial_candles.append(candle)
        self.check_pending_updates(candle)
        for request in self.required_updates:
            request.update(candle)

    def clone(self):
        cloned = CandleBuilder()
        all_candles = self.candles_list.get_ordered_elements()
        for candle in all_candles:
            cloned.candles_list.add(candle)
        for requester in self.pending_updates:
            cloned.pending_updates.append(requester.clone())
        for requester in self.required_updates:
            cloned.required_updates.append(requester.clone())
        return cloned

    def drop_all_requesters(self):
        self.pending_updates = []
        self.required_updates = []

    @staticmethod
    def get_candle_from_arrays(candles, idx):
        candle = dict()
        for candle_key in candles:
            candle[candle_key] = candles[candle_key][idx]
        return candle
コード例 #13
0
ファイル: day10.py プロジェクト: demanick/adventofcode
 def reset(self):
     '''Resets position and skip to 0'''
     self.circular_list = CircularList([i for i in range(256)])
     self.pos = 0
     self.skip = 0
コード例 #14
0
ファイル: day10.py プロジェクト: demanick/adventofcode
 def __init__(self):
     self.circular_list = CircularList([i for i in range(256)])
     self.pos = 0
     self.skip = 0
コード例 #15
0
ファイル: day10.py プロジェクト: demanick/adventofcode
class KnotHash(object):
    def __init__(self):
        self.circular_list = CircularList([i for i in range(256)])
        self.pos = 0
        self.skip = 0

    def create_hash(self, s):
        '''Creates a knot hash from a string of input'''

        # create lengths from ASCII conversions
        knot_lengths = [ord(c) for c in s]
        # append standard end lengths
        knot_lengths += [17, 31, 73, 47, 23]

        # perform ties of each lenght 64 times
        for i in range(64):
            for l in knot_lengths:
                self.tie(l)

        # reduce hash to dense hash
        dense_hash = self.__reduce()

        # create and return final string of hex values
        final_string = []
        for n in dense_hash:
            h = hex(n)
            final_string.append(h.replace('0x', '').zfill(2))

        return ''.join(final_string)

    def reset(self):
        '''Resets position and skip to 0'''
        self.circular_list = CircularList([i for i in range(256)])
        self.pos = 0
        self.skip = 0

    def tie(self, length):
        '''Reverse portion of array for user-passed length, increases positiona
        and skip tracker variables'''

        # identify end of list
        end = self.pos + length

        # creat sub-array and reverse
        sub = self.circular_list.index(self.pos, end)
        reverse = sub[::-1]

        # replace all values
        self.circular_list.replace(self.pos, reverse)

        # move position
        self.pos = end + self.skip
        if self.pos > len(self.circular_list.array):
            self.pos %= len(self.circular_list.array)

        # increase skip size
        self.skip += 1

    def __reduce(self):
        '''Reduces a hash to a dense hash'''

        # create empty list to populate with dense hash
        dense_hash = []

        # iterate through array in groups of 16
        pos = 0
        while pos < len(self.circular_list.array):
            num = xor(self.circular_list.index(pos, pos + 16))
            dense_hash.append(num)
            pos += 16

        return dense_hash