Giter Site home page Giter Site logo

advent_of_code's People

Contributors

yyolk avatar

Watchers

 avatar  avatar

advent_of_code's Issues

prompts

js console script for extracting:
copy(document.getElementsByTagName("main")[0].outerHTML)
stripping out the success portion and converting it to markdown (even though html is valid markdown):
async function convertToMarkdown(htmlContent) { 
return fetch('https://cdn.jsdelivr.net/npm/[email protected]/dist/turndown.js')
  .then(response => response.text())
  .then(scriptText => {
    // Execute the script in the global context
    eval(scriptText);
    // Create a Turndown instance
    let turndownService = new TurndownService();

    // Convert HTML to Markdown
    let markdownContent = turndownService.turndown(htmlContent);

    // Log the Markdown content
    return markdownContent
  })
  .catch(error => console.error('Failed to fetch turndown library', error));
}
let arrayFromChildren = [...document.getElementsByTagName("main")[0].children]
    
// Get the HTML content
let htmlContent = arrayFromChildren.slice(0, arrayFromChildren.findIndex(el => el.className == "day-success")).map(el => el.outerHTML).join("")


copy(await convertToMarkdown(htmlContent))
grabbing all days from the console's logged in session:
JavaScript in the inspector console
/* 
   expected to be run after completing the 25th puzzle:
   https://adventofcode.com/2023/day/25
   but was written using an earlier puzzle page, the code expects to be on a puzzle page of any day ;P
*/
// intended to be run after completing all puzzles after all puzzles were released
const ADVENT_DAYS = 25;
let PersistedTurndownService = await fetch('https://cdn.jsdelivr.net/npm/[email protected]/dist/turndown.js')
  .then(response => response.text())
  .then(moduleSource => {
    eval(moduleSource);
    return TurndownService;
  })
  .catch(error => console.error('Error loading module:', error));


function convertToMarkdown(htmlContent) {
    // Create a Turndown instance
    let turndownService = new PersistedTurndownService();
    
    // Convert HTML to Markdown
    let markdownContent = turndownService.turndown(htmlContent);
    
    // Log the Markdown content
    return markdownContent;
}

async function getCompletedDay(day) {
    // we expect this code is running in the js console on any day's puzzle page, like:
    // https://adventofcode.com/2023/day/15
    // this could just as well be hardcoded
    const basePath = document.location.pathname.replace(/\d+$/, '');
    const stem = `${basePath}${day}`
    const fullURL = `${document.location.origin}${stem}`;
    return fetch(stem).then(response => response.text()).then(domString => {
        const parser = new DOMParser();
        const arrayFromChildren = [...parser.parseFromString(domString, 'text/html').getElementsByTagName("main")[0].children];
        const htmlContent = arrayFromChildren.slice(0, arrayFromChildren.findIndex(el => el.className == "day-success")).map(el => el.outerHTML).join("");
        const yamlFrontMatter = [];
        yamlFrontMatter.push('---');
        yamlFrontMatter.push(`permalink: ${fullURL}`);
        yamlFrontMatter.push(`puzzle_input: ./${day}.txt`);
        yamlFrontMatter.push(`solution: ./${day}.py`);
        yamlFrontMatter.push('---\n');
        return yamlFrontMatter.join('\n') + convertToMarkdown(htmlContent);
    });
}

const allDaysPrompts = [];

for (const day of [...Array(ADVENT_DAYS).keys()].map(k => k + 1)) {
    allDaysPrompts.push(await getCompletedDay(day));   
}

let htmlContent = "";
htmlContent += "<html><body><ol>";
for (const dayPrompt of allDaysPrompts) {
    htmlContent += `<li><textarea>${dayPrompt}</textarea></li>`;
}
htmlContent += "</ol></body></html>";
const newTab = window.open();
newTab.document.write(htmlContent);
// alternatively copy this JSON and dump write each file with python script
JSON.stringify(allDaysPrompts);
Python with extracted `session` Cookie
BeautifulSoup4
markdownify
uritemplate
requests
from textwrap import dedent
from typing import Iterable

import requests

from bs4 import BeautifulSoup
from markdownify import markdownify
from uritemplate import URITemplate

try:
    from google.colab import userdata

    AOC_SESSION = userdata.get("aoc_session")
except ImportError:
    import os

    AOC_SESSION = os.environ.get("AOC_SESSION", "SECRET")

AOC_YEAR = 2023
BASE_URL = f"https://adventofcode.com/{AOC_YEAR}/day"
URI_TEMPLATE = URITemplate(f"{BASE_URL}/{{day}}")

ADVENT_DAYS = 25
# ADVENT_DAYS = 8  # Use a lower number while testing ;P


def generate_markdown_prompt(day_prompt_html, day) -> str:
    full_url = URI_TEMPLATE.expand(day=day)
    yaml_front_matter = dedent(f"""\
    ---
    permalink: {full_url}
    puzzle_input: ./{day}.txt
    solution: ./{day}.py
    ---
    """)
    return yaml_front_matter + markdownify(day_prompt_html)


def get_prompts(days: Iterable[int]) -> list[str]:
    prompts = []
    with requests.Session() as s:
        for day in days:
            full_url = URI_TEMPLATE.expand(day=day)

            resp = s.get(full_url, cookies={"session": AOC_SESSION})

            soup = BeautifulSoup(resp.text, "html.parser")
            day_success_element = soup.main.find(class_="day-success")

            # Extract all content before the 'day-success' element
            content_before_day_success = []
            for element in soup.main.contents:
                if element == day_success_element:
                    break
                content_before_day_success.append(str(element))

            # Concatenate back all the content from our soup.main
            result_html = "".join(content_before_day_success)
            # Turn the HTML into Markdown with the yaml frontmatter we're after
            final_markdown = generate_markdown_prompt(result_html, day)
            # Append to our prompts list
            prompts.append(final_markdown)

    return prompts


if __name__ == "__main__":
    all_markdown_prompts = [prompt for prompt in get_prompts(range(1, ADVENT_DAYS + 1))]
    for day_number, prompt in enumerate(all_markdown_prompts, start=1):
        with open(f"{AOC_YEAR}/{day_number}.md", "w") as fp:
            fp.write(prompt)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.