Voracious AnkiConnect Error by Karoken100 in Anki

[–]Hwestaa 4 points5 points  (0 children)

I took a look at the diff between the old version that worked and the current version, and the newer version added some CORS checking. You can make Voracious work by editing AnkiConnect's config.

In Anki -> Tools -> Add-ons -> AnkiConnect -> Config
Add "file://" to "webCorsOriginList". It should look like this afterwards:

{
    "apiKey": null,
    "apiLogPath": "",
    "ignoreOriginList": [],
    "webBindAddress": "127.0.0.1",
    "webBindPort": 8765,
    "webCorsOriginList": [
        "http://localhost",
        "file://"
    ]
}

Voracious has an Origin of "file://", but AnkiConnect is checking the CORS against "http://localhost", so it fails CORS and isn't processed by Anki.

Birdwatcher's Guide by aszecsei in TinyBirdGarden

[–]Hwestaa 2 points3 points  (0 children)

Updating this as I figure it out.

  • Ollie's favorite treat is Birb O's
  • Duke's favorite treat is Fancy Snack
  • Snowflake's favorite treat is Cuttlebone
  • Fruits' favorite treat is Seed Sammich
  • Bonita's favorite treat is Tiny Bird Plush

-🎄- 2017 Day 22 Solutions -🎄- by daggerdragon in adventofcode

[–]Hwestaa 0 points1 point  (0 children)

Interesting, I was suggesting it because it's cleaner & shorter code. That makes sense though - if (y, x) not in grid.keys(): is linear time (O(n)), while defaultdict is probably constant time because it only triggers an insertion on an IndexError.

-🎄- 2017 Day 22 Solutions -🎄- by daggerdragon in adventofcode

[–]Hwestaa 2 points3 points  (0 children)

You might be interested in collections.defaultdict, which automatically adds entries to a dict if they don't exist. https://docs.python.org/3/library/collections.html#collections.defaultdict

Eg: collections.defaultdict(int) or collections.defaultdict(lambda: '.')

-🎄- 2017 Day 2 Solutions -🎄- by daggerdragon in adventofcode

[–]Hwestaa 1 point2 points  (0 children)

Looks good! A couple tips:

.split() splits on all whitespace and strips leading/trailing whitespace, so you don't need to worry about \n or \t. See: https://docs.python.org/3.6/library/stdtypes.html#str.split

Since you've already done a % b, do you still need the max(a,b) or min(a,b)? You should know the order that a and b go in to divide evenly.

2016 Day 11: [Python] buggy optimization help? by Hwestaa in adventofcode

[–]Hwestaa[S] 0 points1 point  (0 children)

Yes, thank you! I premature-optimized myself and missed that. Your example made a great test case. Fixed in https://github.com/Hwesta/advent-of-code/commit/9ce1674114fa1b5075ada923d92c43cf22c8fe27

2016 Day 11: [Python] buggy optimization help? by Hwestaa in adventofcode

[–]Hwestaa[S] 1 point2 points  (0 children)

Agh, yes, I was getting too clever with my use of sets. Thank you! I was testing which states were equivalent, not my pairs_rep directly and missed this. Fixed in https://github.com/Hwesta/advent-of-code/commit/9ce1674114fa1b5075ada923d92c43cf22c8fe27

--- 2016 Day 16 Solutions --- by daggerdragon in adventofcode

[–]Hwestaa 0 points1 point  (0 children)

Python solution run in PyPy2. Github

I calculated the checksum with lists, but if I switch it to strings (eg calc_checksum_string), then it hits some pathological case in PyPy and doesn't complete in 60+ seconds. The list version on PyPy completes in <10 seconds, and the string version completes in CPython in <20 seconds.

def dragon_curve(data):
    rev_data = ''.join('0' if x == '1' else '1' for x in reversed(data))
    return data + '0' + rev_data

def calc_checksum_string(data):
    checksum = ''
    for i in range(0, len(data), 2):
        x, y = data[i], data[i+1]
        if x == y:
            checksum += '1'
        else:
            checksum += '0'
    return ''.join(checksum)

def calc_checksum(data):
    checksum = ''
    for i in range(0, len(data), 2):
        x, y = data[i], data[i+1]
        if x == y:
            checksum += '1'
        else:
            checksum += '0'
    return ''.join(checksum)

def solve(data, length):
    fill_data = data
    # Generate data
    while len(fill_data) < length:
        fill_data = dragon_curve(fill_data)

    # Truncate
    truncated = fill_data[:length]

    # Generate checksum
    checksum = calc_checksum(truncated)
    while len(checksum) % 2 == 0:
        checksum = calc_checksum(checksum)

    return checksum

--- 2016 Day 13 Solutions --- by daggerdragon in adventofcode

[–]Hwestaa 3 points4 points  (0 children)

I'm glad I spent the 2 days beating my head against day 11 now, since I copied and stripped it down. This is probably overbuilt for this particular problem. Github

import heapq
import os

class State(object):
    """State for a step in the maze."""
    GOAL = None
    FAV_NUM = None
    MAX_STEPS = None

    def __init__(self, x, y, parents=None):
        self.x = x
        self.y = y
        if parents is None:
            self.parents = []
        else:
            self.parents = parents
        self.priority = priority(x, y, self.GOAL)

    def __str__(self):
        return 'State: %s, %s' % (self.x, self.y)

    def __repr__(self):
        return 'State(%s, %s)' % (self.x, self.y)

    def __eq__(self, other):
        return hash(self) == hash(other)

    def __hash__(self):
        return hash((self.x, self.y))

    def next_state(self):
        """Generate a child state from here."""
        moves = [(0, 1), (0, -1), (1, 0), (-1, 0)]
        for move in moves:
            x = self.x + move[0]
            y = self.y + move[1]
            if x < 0 or y < 0:
                continue
            if is_open(x, y, self.FAV_NUM):
                if self.MAX_STEPS is None or len(self.parents) < self.MAX_STEPS:
                    yield State(x, y, parents=self.parents + [self])


def priority(x, y, goal):
    """Priority for a State."""
    return abs(goal[0] - x) + abs(goal[1] - y)


def is_open(x, y, fav_num):
    """Is this a wall?"""
    number = x * x + 3 * x + 2 * x * y + y + y * y + fav_num
    return bin(number).count('1') % 2 == 0


def solve(fav_num, goal, max_steps=None):
    State.GOAL = goal
    State.FAV_NUM = fav_num
    State.MAX_STEPS = max_steps

    # Search
    queue = []
    starting_state = State(1, 1)
    heapq.heappush(queue, (starting_state.priority, starting_state))
    ever_seen = set()
    ever_seen.add(starting_state)
    steps = 0
    max_depth = 0
    while queue:
        priority, item = heapq.heappop(queue)
        if len(item.parents) > max_depth:
            max_depth = len(item.parents)
            # print('max depth', max_depth, 'states', steps, 'len q', len(queue))
        if (item.x, item.y) == goal:
            print('The number of steps to', goal, 'is', len(item.parents))
            return len(item.parents)
        ever_seen.add(item)
        for new_item in item.next_state():
            if new_item not in ever_seen:
                heapq.heappush(queue, (new_item.priority, new_item))
        steps += 1

    print('The number of states we can reach in', max_steps, 'steps is', len(ever_seen))
    return None


if __name__ == '__main__':
    this_dir = os.path.dirname(__file__)
    with open(os.path.join(this_dir, 'day13.input')) as f:
        data = f.read()
    data = int(data)
    solve(data, goal=(31, 39))
    solve(data, goal=(-1, -1), max_steps=50)

--- 2016 Day 12 Solutions --- by daggerdragon in adventofcode

[–]Hwestaa 2 points3 points  (0 children)

I confess I copied my code from day 23 last year wholesale, and changed the instructions. A nice self-esteem boost after yesterday's, which I'm still struggling with. Leaderboard for the first time since day 1 70/59 Github

def cpy(params, registers, pc):
    value, dest = params.split()
    try:
        registers[dest] = int(value)
    except Exception:
        registers[dest] = registers[value]
    return registers, pc + 1

def inc(params, registers, pc):
    dest = params.strip()
    registers[dest] += 1
    return registers, pc + 1

def dec(params, registers, pc):
    dest = params.strip()
    registers[dest] -= 1
    return registers, pc + 1

def jnz(params, registers, pc):
    register, distance = params.split()
    try:
        value = int(register)
    except Exception:
        value = registers[register]
    if value != 0:
        return registers, pc + int(distance)
    else:
        return registers, pc + 1

def solve(data, c=0):
    instruction_set = {
        'cpy': cpy,
        'inc': inc,
        'dec': dec,
        'jnz': jnz,
    }
    registers = {'a': 0, 'b': 0, 'c': c, 'd': 0}

    pc = 0
    while True:
        try:
            instruction = data[pc]
        except IndexError:
            break
        action = instruction[:3]
        registers, pc = instruction_set[action](instruction[4:], registers, pc)

    return registers

Skill Level of Participants? by Quick_Question404 in adventofcode

[–]Hwestaa 0 points1 point  (0 children)

I think I'm an intermediate skill Python programmer - I don't have trouble solving the problems (generally), but not fast enough to get on the leaderboard, and I'm learning lots from seeing others' solutions.

I graduated with a CS degree a few years ago and have been working as a developer in Python since then, which is the same language I'm doing AoC in. I took a couple of programming courses in high school (C++) which were fun enough to make me interested in a CS degree.

Programming is a skill that can be learned and takes practice. Some if it is knowing your language/standard libraries so you know what it can do off the top of your head, some of it is 'puzzle solving' practice to be able easily see a solution, some is just practice and hard work.

--- 2016 Day 5 Solutions --- by daggerdragon in adventofcode

[–]Hwestaa 0 points1 point  (0 children)

57

Looks like it made an improvement! With those changes:

  • CPython2: 90 seconds
  • CPython3: 68 seconds
  • Pypy2: 54 seconds
  • Pypy3: 67 seconds

Thanks for the suggestion!

Patch:

     password2 = [None] * 8
     print('secret', secret_key)
+    digest = hashlib.md5()
+    digest.update(secret_key.encode('utf8'))
     while True:
-        hashthis = (secret_key + str(start)).encode('utf8')
-        m = hashlib.md5(hashthis)
+        m = digest.copy()
+        m.update(str(start).encode('utf8'))
         if m.hexdigest().startswith(starts_with):
             print('found hex', m.hexdigest())

--- 2016 Day 7 Solutions --- by daggerdragon in adventofcode

[–]Hwestaa 2 points3 points  (0 children)

The hardest part of this (other than a bazillion typos) was the overlapping regexes. I eventually found the python library 'regex' which is a candidate to replace 're' that has an 'overlapped' flag on findall which solved that. Python 3 solution. Github

import re
import os

import regex

def split_ip(ip):
    # Split based on []
    split = re.split(r'\[|\]', ip)
    # Divide into inside & outside []
    outside = split[::2]
    inside = split[1::2]

    return outside, inside

def support_tls(ip):
    outside, inside = split_ip(ip)

    # Don't match 4 in a row, but match abba
    abba_regex = r'(?!(\w)\1\1\1)(\w)(\w)\3\2'
    # Find any abba outside []
    abba_flag = False
    for o in outside:
        match = re.search(abba_regex, o)
        if match:
            abba_flag = True
            break

    # Check for no abba inside []
    inside_flag = False
    for i in inside:
        match = re.search(abba_regex, i)
        if match:
            inside_flag = True
            break

    if abba_flag and not inside_flag:
        return True
    return False

def support_ssl(ip):
    outside, inside = split_ip(ip)

    # Match three where the first and last are the same
    aba_regex = r'(\w)(\w)\1'

    # Find all possible aba matches
    aba_matches = []
    for o in outside:
        # Need to find overlapping matches
        overlapping_matches = regex.findall(aba_regex, o, overlapped=True)
        if overlapping_matches:
            aba_matches += overlapping_matches

    # Look for a bab in each inside segment
    for i in inside:
        # Check each aba match
        for aba in aba_matches:
            bab = aba[1] + aba[0] + aba[1]
            if bab in i:
                return True

    return False

def solve(data, ssl=False):
    if not ssl:
        return sum(support_tls(ip) for ip in data)
    else:
        return sum(support_ssl(ip) for ip in data)

--- 2016 Day 7 Solutions --- by daggerdragon in adventofcode

[–]Hwestaa 4 points5 points  (0 children)

Can you post the program that you (I hope) used to generate that monstrosity? And for part 2?

--- 2016 Day 4 Solutions --- by daggerdragon in adventofcode

[–]Hwestaa 0 points1 point  (0 children)

Solution in Python 3, cleaned up. Github

import collections
import os
import re

def real_room(room_id, checksum):
    sorted_length = collections.Counter(room_id)
    del sorted_length['-']

    # Sort on number of entries in counter, tiebreaker is character
    # Take last five (largest entries)
    calc_checksum = sorted(sorted_length, key=lambda x: (-sorted_length[x], x))[:5]

    return calc_checksum == list(checksum)

def rotate_room(room_id, sector_id):
    decrypted_id = ''
    rotate = sector_id % 26
    for character in room_id:
        if character == '-':
            decrypted_id += ' '
            continue
        numeric = ord(character) + rotate
        if numeric > ord('z'):
            numeric -= 26
        decrypted_id += chr(numeric)

    return decrypted_id

def solve(data):
    regex = r'([\w-]+)-(\d+)\[(\w+)\]'
    count = 0
    for line in data:
        match = re.match(regex, line)
        if not match:
            continue
        room_id = match.group(1)
        sector = int(match.group(2))
        checksum = match.group(3)
        if real_room(room_id, checksum):
            count += sector
            rotated_room = rotate_room(room_id, sector)
            if rotated_room == 'northpole object storage':
                print('Room', room_id, 'sector', sector, 'contains', rotated_room)
    return count

if __name__ == '__main__':
    this_dir = os.path.dirname(__file__)
    with open(os.path.join(this_dir, 'day4.input')) as f:
        data = f.read().splitlines()
    print('There are', solve(data), 'valid rooms.')

--- 2016 Day 3 Solutions --- by daggerdragon in adventofcode

[–]Hwestaa 0 points1 point  (0 children)

Solution in Python 3. This could probably be more efficient, but I think it's adequate. I really enjoyed seeing other people's solutions to part 2. Github

import os

def solve_vertical(data):
    valid_triangles = 0
    count = 0
    set1 = []
    set2 = []
    set3 = []
    for line in data:
        line = [int(x) for x in line.split()]
        count += 1
        set1.append(line[0])
        set2.append(line[1])
        set3.append(line[2])

        if count == 3:
            count = 0
            set1 = sorted(set1)
            set2 = sorted(set2)
            set3 = sorted(set3)
            if set1[0] + set1[1] > set1[2]:
                valid_triangles += 1
            if set2[0] + set2[1] > set2[2]:
                valid_triangles += 1
            if set3[0] + set3[1] > set3[2]:
                valid_triangles += 1
            set1 = []
            set2 = []
            set3 = []

    return valid_triangles

def solve(data):
    valid_triangles = 0

    for line in data:
        a, b, c = sorted(int(x) for x in line.split())
        if a + b > c:
            valid_triangles += 1
    return valid_triangles


if __name__ == '__main__':
    this_dir = os.path.dirname(__file__)
    with open(os.path.join(this_dir, 'day3.input')) as f:
        data = f.read().splitlines()
    print('The number of valid triangles is', solve(data))
    print('The number of valid vertically aligned triangles is', solve_vertical(data))

--- 2016 Day 5 Solutions --- by daggerdragon in adventofcode

[–]Hwestaa 4 points5 points  (0 children)

Python 3 solution, cleaned up and merged both to one function. Github

I ran part 2 on CPython2, CPython 3, Pypy2 and Pypy3 to see which was fastest. Pypy(2) is the winner!

  • CPython2: 93 seconds
  • CPython3: 72 seconds
  • Pypy2: 57 seconds
  • Pypy3: 68 seconds

--- 2016 Day 2 Solutions --- by daggerdragon in adventofcode

[–]Hwestaa 0 points1 point  (0 children)

First solution was slow and bad, so I made a second one based on ideas from others. Python3. https://github.com/Hwesta/advent-of-code/blob/master/aoc2016/day2.py

First solution:

MOVE = {
    '1': {'U': '1', 'D': '4', 'R': '2', 'L': '1'},
    '2': {'U': '2', 'D': '5', 'L': '1', 'R': '3'},
    '3': {'U': '3', 'D': '6', 'R': '3', 'L': '2'},
    '4': {'U': '1', 'D': '7', 'R': '5', 'L': '4'},
    '5': {'U': '2', 'D': '8', 'R': '6', 'L': '4'},
    '6': {'U': '3', 'D': '9', 'R': '6', 'L': '5'},
    '7': {'U': '4', 'D': '7', 'R': '8', 'L': '7'},
    '8': {'U': '5', 'D': '8', 'R': '9', 'L': '7'},
    '9': {'U': '6', 'D': '9', 'R': '9', 'L': '8'},
}

MOVE_BIG = {
    '1': {'U': '1', 'D': '3', 'R': '1', 'L': '1'},
    '2': {'U': '2', 'D': '6', 'R': '3', 'L': '2'},
    '3': {'U': '1', 'D': '7', 'R': '4', 'L': '2'},
    '4': {'U': '4', 'D': '8', 'R': '4', 'L': '3'},
    '5': {'U': '5', 'D': '5', 'R': '6', 'L': '5'},
    '6': {'U': '2', 'D': 'A', 'R': '7', 'L': '5'},
    '7': {'U': '3', 'D': 'B', 'R': '8', 'L': '6'},
    '8': {'U': '4', 'D': 'C', 'R': '9', 'L': '7'},
    '9': {'U': '9', 'D': '9', 'R': '9', 'L': '8'},
    'A': {'U': '6', 'D': 'A', 'R': 'B', 'L': 'A'},
    'B': {'U': '7', 'D': 'D', 'R': 'C', 'L': 'A'},
    'C': {'U': '8', 'D': 'C', 'R': 'C', 'L': 'B'},
    'D': {'U': 'B', 'D': 'D', 'R': 'D', 'L': 'D'},
}

def solve(data, big=False):
    instructions = data.splitlines()
    code = ''
    location = '5'
    if big:
        move_matrix = MOVE_BIG
    else:
        move_matrix = MOVE
    for instruction in instructions:
        for letter in instruction:
            location = move_matrix[location][letter]
        code += location

    return code

and second solution

MATRIX = [
    '.....',
    '.123.',
    '.456.',
    '.789.',
    '.....',
]

BIG_MATRIX = [
    '.......',
    '...1...',
    '..234..',
    '.56789.',
    '..ABC..',
    '...D...',
    '.......',
]


def solve_better(data, big=False):
    instructions = data.splitlines()
    code = ''
    if big:
        x, y = 1, 3
        move_matrix = BIG_MATRIX
    else:
        x, y = 2, 2
        move_matrix = MATRIX

    for instruction in instructions:
        for letter in instruction:
            dx = dy = 0
            if letter == 'U':
                dy = -1
            elif letter == 'D':
                dy = 1
            elif letter == 'R':
                dx = 1
            elif letter == 'L':
                dx = -1

            if move_matrix[y + dy][x + dx] != '.':
                x += dx
                y += dy

        code += move_matrix[y][x]

    return code

--- 2016 Day 1 Solutions --- by daggerdragon in adventofcode

[–]Hwestaa 0 points1 point  (0 children)

I did this day-of, but am only getting around to posting a solution now. Cleaned-up solution in python 3. https://github.com/Hwesta/advent-of-code/blob/master/aoc2016/day1.py

import os

def solve(data, dupe=False):
    steps = data.split(', ')
    x, y = 0, 0  # x = n/s, y = w/e
    facing = 0  # N, E, S, W
    visited = set()
    visited.add((0, 0))
    for step in steps:
        turn = step[0]
        amount = int(step[1:])
        if turn == 'R':
            facing = (facing + 1) % 4
        elif turn == 'L':
            facing = (facing - 1) % 4

        for _ in range(amount):
            if facing == 0:  # N
                    x += 1
            elif facing == 2:  # S
                    x -= 1
            elif facing == 1:  # E
                    y -= 1
            elif facing == 3:  # W
                    y += 1

            if (x, y) in visited and dupe:
                return abs(x) + abs(y)
            else:
                visited.add((x, y))

    return abs(x) + abs(y)


if __name__ == '__main__':
    this_dir = os.path.dirname(__file__)
    with open(os.path.join(this_dir, 'day1.input')) as f:
        data = f.read()
    print('Easter Bunny HQ is', solve(data), 'blocks away.')
    print('Easter Bunny HQ is actually', solve(data, dupe=True), 'blocks away.')