Hammerheart

joined 2 years ago
[โ€“] Hammerheart 1 points 1 day ago* (last edited 1 day ago)

Python

(Part 1) omg I can't believe this actually worked first try!

with open('input') as data:
    parts = data.read().rstrip().split("\n\n")
    ordering_rules = parts[0].split("\n")
    updates = parts[1].split("\n")

correct_updates = []
middle_updates = []

def find_relevant_rules(pg_num: str, rules: list[str]) -> list[str] | None:
    for rule in rules:
        return list(filter(lambda x: x.split("|")[0] == pg_num, rules))

def interpret_rule(rule: str) -> list[str]:
    return rule.split("|")

def interpret_update(update: str) -> list[str]:
    return update.split(",")

def find_middle_update_index(update: list[str]) -> int:
    num_of_elements = len(update)
    return num_of_elements // 2

for update in updates:
    is_correct = True
    for i, page in enumerate(interpret_update(update)):
       rules_to_check = find_relevant_rules(page, ordering_rules) 
       for rule in rules_to_check:
           if rule.split("|")[1] in interpret_update(update)[:i]:
               is_correct = False
    if is_correct:
        correct_updates.append(update)

for update in correct_updates:
    split_update = update.split(",")
    middle_updates.append(int(split_update[find_middle_update_index(split_update)]))
print(sum(middle_updates))
[โ€“] Hammerheart 1 points 3 days ago* (last edited 1 day ago)

Part 1:

with open('input') as data:
    lines = [l.strip() for l in data.readlines()]
# Remove empty line
class Result():
    def __init__(self):
        self.count = 0


def analyze_lines(lines: list[str]):
    ans.count += get_rights(lines)
    ans.count += get_ups(lines)
    ans.count += get_downs(lines)
    ans.count += get_down_rights(lines)
    ans.count += get_down_lefts(lines)
    ans.count += get_up_lefts(lines)
    ans.count += get_up_rights(lines)
    for line in lines:
        ans.count += get_lefts(line)




def get_ups(lines: list[str]) -> int:
    up_count = 0
    for i_l, line in enumerate(lines):
        result = ""
        if i_l < 3:
            continue
        for i_c, char in enumerate(line):
            if char == "X":
                result = char
                result += "".join([lines[i_l - n][i_c] for n in range(1, 4)])
                if result == "XMAS":
                    up_count += 1
                else:
                    result = ""
    return up_count


def get_downs(lines: list[str]) -> int:
    down_count = 0
    for i_l, l in enumerate(lines):
        result = ""
        for i_c, c in enumerate(l):
            if c == "X":
                result += c
                try:
                    result += "".join([lines[i_l + n][i_c] for n in range(1, 4)])
                except IndexError:
                    result = ""
                    continue
                finally:
                    if result == "XMAS":
                        down_count += 1
                    result = ""
    return down_count


        
def get_lefts(line: str) -> int:
    left_count = 0
    for i, char in enumerate(line):
        if i < 3:
            continue
        elif char == "X" and line[i-1] == "M" and line[i-2] == "A" and line[i-3] == "S":
            left_count += 1
    return left_count


def get_rights(lines: list[str]) -> int:
    right_counts = 0
    for l in lines:
        right_counts += l.count("XMAS")
    return right_counts

def get_down_rights(lines: list[str]) -> int:
    down_right_count = 0
    for i_l, l in enumerate(lines):
        result = ""
        for i_c, c in enumerate(l):
            if c == "X":
                result += c
                try:
                    result += "".join(
                            [lines[i_l + n][i_c + n] for n in range(1,4)]
                            )
                except IndexError:
                    result = ""
                    continue
                finally:
                    if result == "XMAS":
                        down_right_count += 1
                    result = ""
    return down_right_count

def get_down_lefts(lines: list[str]) -> int:
    down_left_count = 0
    for i_l, l in enumerate(lines):
        result = ""
        for i_c, c in enumerate(l):
            if i_c < 3:
                continue
            if c == "X":
                result += c
                try:
                    result += "".join(
                            [lines[i_l + n][i_c - n] for n in range(1,4)]
                            )
                except IndexError:
                    result = ""
                    continue
                finally:
                    if result == "XMAS":
                        down_left_count += 1
                    result = ""
    return down_left_count

def get_up_rights(lines: list[str]) -> int:
    up_right_count = 0
    for i_l, l in enumerate(lines):
        result = ""
        if i_l < 3:
            continue
        for i_c, c in enumerate(l):
            if c == "X":
                result += c
                try:
                    result += "".join(
                            [lines[i_l - n][i_c + n] for n in range(1,4)]
                            )
                except IndexError:
                    result = ""
                    continue
                finally:
                    if result == "XMAS":
                        up_right_count += 1
                    result = ""
    return up_right_count


def get_up_lefts(lines: list[str]) -> int:
    up_left_count = 0
    for i_l, l in enumerate(lines):
        result = ""
        if i_l < 3:
            continue
        for i_c, c in enumerate(l):
            if i_c < 3:
                continue
            if c == "X":
                result = c
                try:
                    result += "".join(
                            [lines[i_l - n][i_c - n] for n in range(1,4)]
                            )
                except IndexError as e:
                    result = ""
                    continue
                finally:
                    if result == "XMAS":
                        up_left_count += 1
                    result = ""
    return up_left_count

ans = Result()
analyze_lines(lines)
print(ans.count)

Part 2:

with open('input') as data:
    lines = list(filter(lambda x: x != '', [l.strip() for l in data.readlines()]))
    
xmases = 0
for i in range(1, len(lines)):
    for j in range(1, len(lines[i])):
        if lines[i][j] == "A":
            try:
                up_back = lines[i-1][j-1]
                down_over = lines[i+1][j+1]
                up_over = lines[i-1][j+1]
                down_back = lines[i+1][j-1]
            except IndexError:
                continue
            else:
                if {up_back, down_over} == set("MS") and {up_over, down_back} == set("MS"):
                    xmases += 1

print(xmases)

I actually found part two A LOT easier than part 1.

5
submitted 1 week ago* (last edited 1 week ago) by Hammerheart to c/advent_of_code
 

So this is really kind of tangential, I am just messing around with the data and trying to at least nail down some basics so I can do sanity checks in my actual code. I am running into an odd discrepancy when trying to determine the number of times "XMAS" occurs in the input. I am only concerned with the straight forward matches, the instances of the substring "XMAS" appearing in the raw data.

When i do "grep -c XMAS input" or "rg -c XMAS input" they both show 107. But when I use regex101.com and search for the pattern XMAS, it shows 191 matches. Please help, I am truly at a loss here. While writing this, it occurred to me to just try using string.count("XMAS") in python on the data as a raw string, and it also returns 191. So really this question is more about grep and rp than anything. why are they only returning 107?

[โ€“] Hammerheart 2 points 1 week ago

I needed to read this. Thank you.

[โ€“] Hammerheart 1 points 2 weeks ago

My first insinct was similar, add line breaks to the do and dont modifiers. But I got toa caught up thinking id have to keep track of the added characters, I wound up just abusing split()-

[โ€“] Hammerheart 1 points 2 weeks ago

I did part 2 live with the python interactive shell. I deleted all the stuff where I was just exploring ideas.

part 1:

import re

def multiply_and_add(data: "str") -> int:
    digit_matches = re.findall(r"mul\(\d{0,3},\d{0,3}\)", data)
    result = 0
    for _ in digit_matches:
        first = _.split("(")[1].split(")")[0].split(",")[0]
        second = _.split("(")[1].split(")")[0].split(",")[1]
        result += int(first) * int(second)

    return result

with open("input") as file:
    data = file.read()


answer = multiply_and_add(data)
print(answer)

part 2:

Python 3.11.2 (main, Aug 26 2024, 07:20:54) [GCC 12.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import solution2
<re.Match object; span=(647, 651), match='do()'>
>>> from solution2 import *
>>> split_on_dont = data.split("don't()")
>>> valid = []
>>> valid.append(split_on_dont[0])
>>> for substring in split_on_dont[1:]:
...     subsubstrings = substring.split("do()", maxsplit=1)
...     for subsubstring in subsubstrings[1:]:
...             valid.append(subsubstring)
...
>>> answer = 0
>>> for _ in valid:
...     answer += multiply_and_add(_)
...
>>> answer
103811193
[โ€“] Hammerheart 1 points 2 weeks ago

this took me so fucking long and in the end i just went for brute force anyway. there are still remnants of some of previous, overly complicated, failed attempts, like the hideous global removed. In the end, I realized I was fucking up by using remove() instead of pop(), it was causing cases with duplicates where the removal of one would yield a safe result to count as unsafe.

[โ€“] Hammerheart 1 points 2 weeks ago (1 children)
def is_safe(report: list[int]) -> bool:
    global removed
    acceptable_range = [_ for _ in range(-3,4) if _ != 0]
    diffs = []
    if any([report.count(x) > 2 for x in report]):
        return False
    for i, num in enumerate(report[:-1]):
        cur = num
        next = report[i+1]
        difference = cur - next
        diffs.append(difference)
        if difference not in acceptable_range:
            return False
        if len(diffs) > 1:
            if diffs[-1] * diffs[-2] <= 0:
                return False
    return True

with open('input') as reports:
    list_of_reports = reports.readlines()[:-1]


count = 0

failed_first_pass = []
failed_twice = []

for reportsub in list_of_reports:
    levels = [int(l) for l in reportsub.split()]
    original = levels.copy()
    if is_safe(levels):
        safe = True
        count += 1
    else:
        failed_first_pass.append(levels)

for report in failed_first_pass:
    print(report)
    working_copy = report.copy()
    for i in range(len(report)):
        safe = False
        working_copy.pop(i)
        print("checking", working_copy)
        if is_safe(working_copy):
            count += 1
            safe = True
            break
        else:
            working_copy = report.copy()

print(count)
[โ€“] Hammerheart 2 points 3 weeks ago

I like that, might try it myself, since I actually use those keys, but never wanted to jump to the highest or lowest visible line. Closest I get is gg and G.

 

I am working on a rudimentary Breakout clone, and I was doing the wall collision. I have a function that I initially treated as a Boolean, but I changed it to return a different value depending on which wall the ball hit. I used the walrus operator to capture this value while still treating the function like a bool. I probably could have just defined a variable as the function's return value, then used it in an if statement. But it felt good to use this new thing I'd only heard about, and didn't really understand what it did. I was honestly kind of surprised when it actually worked like I was expecting it to! Pretty cool.

[โ€“] Hammerheart 2 points 2 months ago

The wire mad men

[โ€“] Hammerheart 10 points 2 months ago

I fucking love halloween. If this is true, it's one of the few redeeming aspects of USA culture.

[โ€“] Hammerheart 0 points 2 months ago (1 children)

Because it's not downloading, which is the thing every one thinks is normal. It's different, and potentially dangerous, which your phone will remind you any time you try to do it.

 

All I want to do is put a still image over a MP3 so I can upload a song to Youtube. (Sidenote: It feels really good to find a song I want to show someone that isn't already on Youtube. It used to be a somewhat regular thing i'd do, I have about a dozen Youtube videos that are just songs I uploaded because I wanted to show them to someone, but I guess Youtube got more stuff and my taste got more pedestrian, so I haven't felt the need to do it until now. Feels good!)

I used VEED, a web editor, and it produced a >300mb file. That seems a bit excessive. For the curious, this is the song: https://youtu.be/iLz7VXhCrnk

7
submitted 6 months ago* (last edited 6 months ago) by Hammerheart to c/[email protected]
 

Every so often, I accidentally activate .... what ever this is... I can't seem to find any info on what it's called, or exactly what hotkey makes it happen. It kinda bugs me because tonight I wanted to turn it on, because I wanted to access something from my history that it would have been tedious to up arrow to. I thought windowsKey + , did it, but when I tried it in a new tab, it didn't work. Someone must know what this is and how to toggle it.

 

I started working through the 100 Days of Code course of Udemy last February, and I'm in the home stretch. I'm on the final lessons, which are really just prompts for projects. No hand holding, just a brief description of the goal. I recently finished a tkinter GUI program, the goal of which was to enable adding text watermarks.

I took a few liberties--mainly, I made it possible to layer a png on top of the background. It was a really fun project and quickly grew more complicated than I expected it to. I got some hands on experience with the Single Responsibility Principle, as I started off doing everything in my Layout class.

Eventually, I moved all the stuff that actually involved manipulating the Image objects to an ImageManager class. I feel like I could have gotten even more granular. That's one thing I would love to get some feedback on. How would a more experienced programmer have architected this program?

Anyway, I guess this preamble is long enough. I'm going to leave a link to the repository here. I would have so much appreciation for anyone who took the time to look at the code, or even clone the repo and see if my instructions for getting it to run on your machine work.

Watermark GUI Repo

 

cross-posted from: https://programming.dev/post/14680192

I have a VPS, but no root access so I can't use apt, or even read a lot of the system files. I would like to get jellyfin (or any media server, really) running on it. Jellyfin has a portable installation option, so I followed the instructions in the docs to install it from the .tar.gz.

But it says I have to install ffmpeg-jellyfin, and I can't find a portable installation of that. My VPS already has ffmpeg installed on it. Will jellyfin work if I just point it to that instead? Or, how can I go about installing ffmpeg-jellyfin without root access?

 

I have a VPS, but no root access so I can't use apt, or even read a lot of the system files. I would like to get jellyfin (or any media server, really) running on it. Jellyfin has a portable installation option, so I followed the instructions in the docs to install it from the .tar.gz.

But it says I have to install ffmpeg-jellyfin, and I can't find a portable installation of that. My VPS already has ffmpeg installed on it. Will jellyfin work if I just point it to that instead? Or, how can I go about installing ffmpeg-jellyfin without root access?

 

I recently got ssh set up so I can do stuff in powershell on my desktop from my laptop. I want to be able to start a movie on my desktop from my laptop, instead of having to reach for my wireless keyboard. I was researching how to do this with SSH, and it looks like OpenSSH no longer allows you to run the server as a user, it can only be ran as a service which doesn't have access to the desktop.

What's the best way to achieve this functionality?

 

I have been using sway (basically i3 for Wayland) instead of a traditional desktop environment because it really makes a difference in my laptops performance.

But apparently sway ignores .desktop files which was how i was autostarting things on KDE.

Is the best way to handle this by going through the sway config? If not, how would you do it.

Bonus points if you can tell me how to get the autostart programs to also open in specific workspaces.

14
submitted 7 months ago* (last edited 7 months ago) by Hammerheart to c/learn_programming
 

I'm working on a little gui app that will eventually (hopefully) add a watermark to a photo. But right now I'm focused on just messing around with tkinter and trying to get some basic functionality down.

I've managed to display an image. Now I want to change the image to whatever is in the Entry widget (ideally, the user would put an absolute path to an image and nothing else). When I click the button, it makes the image disappear. I made it also create a plain text label to see if that would show up. It did.

Okay, time to break out the big guns. Add a breakpoint. py -m pdb main.py. it works. wtf?

def change_image():
    new_image = Image.open(image_path.get()).resize((480, 270))
    new_tk_image = ImageTk.PhotoImage(new_image)
    test_image_label.configure(image=new_tk_image)
    breakpoint()

with the breakpoint, the button that calls change_image works as expected. But without the breakpoint, it just makes the original image disappear. Please help me understand what is happening!

edit: all the code

import io
import tkinter as tk
from pathlib import Path
from tkinter import ttk

from PIL import ImageTk
from PIL import Image

from LocalImage import Localimage
from Layout import Layout

class State:
    def __init__(self) -> None:
        self.chosen_image_path = ""

    def update_image_path(self):
        self.chosen_image_path = image_path.get()



def change_image():
    new_image = Image.open(image_path.get()).resize((480, 270))
    new_tk_image = ImageTk.PhotoImage(new_image)
    test_image_label.configure(image=new_tk_image)
    breakpoint()

TEST_PHOTO_PATH = "/home/me/bg/space.png"
PIL_TEST_PHOTO_PATH = "/home/me/bg/cyberpunkcity.jpg"
pil_test_img = Image.open(PIL_TEST_PHOTO_PATH).resize((480,270))
# why does the resize method call behave differently when i inline it
# instead of doing pil_test_img.resize() on a separate line?


root = tk.Tk()

root.title("Watermark Me")
mainframe = ttk.Frame(root, padding="3 3 12 12")
mainframe.grid(column=0, row=0, sticky="NWES")

layout = Layout(mainframe)

image_path = tk.StringVar()
tk_image = ImageTk.PhotoImage(pil_test_img)
test_image_label = ttk.Label(image=tk_image)

entry_label = ttk.Label(mainframe, text="Choose an image to watermark:")
image_path_entry = ttk.Entry(mainframe, textvariable=image_path)
select_button = ttk.Button(mainframe, text="Select",
                           command=change_image)
hide_button = ttk.Button(mainframe, text="Hide", command= lambda x=test_image_label:
                  layout.hide_image(x))
test_text_label = ttk.Label(mainframe, text="here i am")
empty_label = ttk.Label(mainframe, text="")

for child in mainframe.winfo_children():
    child.grid_configure(padx=5, pady=5)

entry_label.grid(column=0, row=0)
image_path_entry.grid(column=1, row=0)
hide_button.grid(column=0, row=3)
select_button.grid(column=0, row=4)
test_image_label.grid(column=0, row=5)
empty_label.grid(column=0, row=6)


image_path_entry.insert(0,TEST_PHOTO_PATH)
image_path_entry.focus()
breakpoint()



root.mainloop()
 

Sometimes my CMUS will randomly stop playing a track or it won't play the next track until I manually go in and hit c (for resume) or otherwise initiate playback. I would like to be able to see what happened before these instances so i could either fix my config or, if its a problem beyond the scope of my local environment, get info to write up a proper bug report with. Where can I find such logs? Would they be in the systemd journal or somewhere in /var ?

12
submitted 11 months ago by Hammerheart to c/neovim
 

So I just had an issue where my shebang lines weren't parsing properly for a python script I was attempting to execute. A quick google revealed that it was probably because I wrote the scripts on windows and now I was trying to run them on Linux (so happy i finally made the switch btw. using the computer is fun again!). So i took the advice I found and tried to run :%s/^M/ (using C-v, C-m to insert the escape character), and it failed to find any matches. I tried the same command in vanilla vi and it worked.

Is there some setting I don't have configured properly? I would prefer to be able to do this sort of thing within neovim.

view more: next โ€บ