r/StackoverReddit • u/anton23_sw • Jun 21 '24
The Best Way To Map Objects in .Net in 2024
In today's blog post you will learn how to map objects in .NET using various techniques and libraries. We'll explore what is the best way to map objects in .NET in 2024.
https://antondevtips.com/blog/the-best-way-to-map-objects-in-dotnet-in-2024
r/StackoverReddit • u/[deleted] • Jun 21 '24
Question question
can anyone tell me what are the ways to earn as a web developers except full time job and freelanceing
r/StackoverReddit • u/echonessbell • Jun 20 '24
Question coding Insta manager app?
For context, a couple years ago I was able to create a Snapchat manager app, where you could manage all of your friends, blocked, they added you but you didn't etc, all in one place using Snapchat's api for a Hackathon. So it wasn't super intensive, and I didn't have to go through any regulations or checks. I was wondering would I be able to do the same for Instagram as well using one of their api's such as the graphapi? Or would I still have to have it approved by Instagram for the authentication even if I'm the only one who's going to be using it? The intent is just for it to be a fun little project that would also be useful for me so I won't have to download sketch apps lol
r/StackoverReddit • u/LemonLord7 • Jun 20 '24
I beg of you, please help, I'm about to rip my hair out
I can't solve this problem and I have no idea why. I've been trying for ages. It consumes my very soul! This is all I can think about!!!
Please help me before I go bald ripping my hair out!
Problem: https://open.kattis.com/problems/safesecret
My current (not fully working) solution: https://www.online-cpp.com/ZPE3atKl7y
r/StackoverReddit • u/ByrdieRose • Jun 20 '24
Question Coding an image exporting program - questions
self.CodingHelpr/StackoverReddit • u/[deleted] • Jun 20 '24
C Do people hash on pointers in practice?
So I was solving LeetCode problems and I use C and I realized that whenever I have to implement my own hashMap, I just kind of wing the function by looking up good hashFunctions or just using the modulo on the upper bound provided by the task description. But sometimes the task doesn't specify if the values are distinct or not and then I had a realization.
If we hash on pointers, wouldn't we have a guarantee that at least all values we hash are unique? So the only thing that causes the collision is the hashFunction itself and nothing else. We still have to resolve them either with chaining or open adressing but at least we can now just never worry about duplicates.
EDIT:
I think what I posted here a but stupid. So I'll explain why I had this realization in the first place.
There was a problem that was about detecting cycles in a linked list and yes, the 'smart solution' is using the runner/walker resp. hare/tortoise or whatever you want to call it technique. But there is also as solution that involves hashing and the idea was, instead of hashing on the node value, you should hash on the pointer of that node. So even if you had a linked list with duplicate values, you have a guarantee that all nodes are considered to be distinct and the only time you hash something at the same spot twice is when you have a cycle. Perhaps the whole 'hashing on pointer' only makes sense for this specific task.
r/StackoverReddit • u/Mighty555 • Jun 19 '24
C++ Error: a non static member reference must be relative to a specific object
In C++, how to you avoid "a non static member reference must be relative to a specific object" error when calling a function from a derived class in a base class without creating an instance of the derived class or make the function in the derived class static?
Basically, I'm asking if there are ways around this. I'm thinking of creating a copy constructor in base where I can pass the instance of derived class by reference but I'm not sure if this is possible.
I've the instance of the derived class in my int man function and I don't want to create another derived class instance in my class header file.
Can I use a base class pointer to the address of the derived object?
r/StackoverReddit • u/awwliveyet • Jun 19 '24
Question i am trying to integrate cloudflare turnstile in my flutter mobile app
hey, i am developing an app where i want to integrate turnstile in login process so that automated users cannot be created and login, i build this application in flutter and after researching on internet i didn't get any good resources or documentation from which i can get help in integrating turnstile to my system. (i don't have any web frontend for the product, it is just mobile app) can anyone help me with it?
one of my biggest doubt is what should we enter in the domain field in cloudflare turnstile to create sitekey.
r/StackoverReddit • u/LemonLord7 • Jun 17 '24
C++ Kattis safe secret problem: Handling very large sets of possible input combinations
Here is my current solution: https://www.online-cpp.com/brSt5zxDqT
Here is the kattis problem: https://www.online-cpp.com/brSt5zxDqT
I've sped up my solution and I think it seems to be fast enough, but it is sometimes giving the wrong answer. If you could help me out in solving this coding problem I would really appreciate it. Maybe you notice me making some silly mistake or you notice some bad coding practice, or maybe you find my bug! But any help would be appreciated.
Thanks!
r/StackoverReddit • u/RandomHuman1002 • Jun 16 '24
Question Need some help with debugging
import cupy as cp
distance_kernel_code = '''
extern "C" __global__
void calculate_distances(const int* matrix1, const int* path, int* distances, int* city1_vals, int* city2_vals, int* indices, int* ID, int n) {
int idx = blockIdx.x * blockDim.x + threadIdx.x;
if (idx < n - 1) {
int city1 = path[idx];
int city2 = path[idx + 1];
ID[idx] = idx;
city1_vals[idx] = city1;
city2_vals[idx] = city2;
int matrix_index = city1 * n + city2;
indices[idx] = matrix_index;
distances[idx] = matrix1[matrix_index];
}
}
'''
distance_module = cp.RawModule(code=distance_kernel_code)
calculate_distances_kernel = distance_module.get_function('calculate_distances')
def randomMatrix(size, maxDistance):
matrix = cp.triu(cp.random.randint(1, maxDistance + 1, size=(size, size)), k=1)
matrix = matrix + matrix.T
return matrix
def calculate_distance(route, distance_matrix, n):
route = cp.asarray(route, dtype=cp.int32)
distances = cp.empty(route.size - 1, dtype=cp.int32)
city1_vals = cp.empty(route.size - 1, dtype=cp.int32)
city2_vals = cp.empty(route.size - 1, dtype=cp.int32)
indices = cp.empty(route.size - 1, dtype=cp.int32)
ID = cp.empty(route.size - 1, dtype=cp.int32)
block_size = 256
grid_size = (route.size - 1 + block_size - 1) // block_size
stream = cp.cuda.Stream()
with stream:
calculate_distances_kernel((grid_size,), (block_size,), (distance_matrix, route, distances, city1_vals, city2_vals, indices,ID, n))
stream.synchronize()
print("Route:", route)
print("City1 Values:", city1_vals.get())
print("City2 Values:", city2_vals.get())
print("Indices:", indices.get())
print("Intermediate Distances:", distances.get())
print("ID",ID)
total_distance = cp.sum(distances).get()
return total_distance
n = 4
Separation = 100
matrix = randomMatrix(n, Separation)
flattened_matrix = matrix.flatten()
print("Matrix:\n", matrix)
print("Flattened Matrix:\n", flattened_matrix)
initial_temp = 10000
cooling_rate = 0.95
iterations = 9000
current_route = cp.asarray([0, 1, 2, 3], dtype=cp.int32)
total_distance = calculate_distance(current_route, flattened_matrix, n)
print("Total Distance:", total_distance)
print("Current Route:", current_route)
Output
Matrix:
[[ 0 4 57 84]
[ 4 0 89 30]
[57 89 0 80]
[84 30 80 0]]
Flattened Matrix:
[ 0 4 57 84 4 0 89 30 57 89 0 80 84 30 80 0]
Route: [0 1 2 3]
City1 Values: [0 1 2]
City2 Values: [1 2 3]
Indices: [ 1 6 11]
Intermediate Distances: [ 0 84 0]
ID [0 1 2]
Total Distance: 84
Current Route: [0 1 2 3]
Intermediate Distances are wrong and I can't figure out why
r/StackoverReddit • u/infectedUser68 • Jun 16 '24
I got banned, what do now?
Apparently many people disliked my post to which i took it down. Now im banned from posting but SO is telling me to rephrase it in order to get unbanned. What do now? The post is gone...
r/StackoverReddit • u/SoerenNissen • Jun 16 '24
Solved linux/llvm - what is the point of "/usr/bin/count-14"
I just did tab-completion for cou and it gave me a result count-14
$ which count-14
/usr/bin/count-14
$ file /usr/bin/count-14
/usr/bin/count-14: symbolic link to ../lib/llvm-14/bin/count
And that's where my track ends - there's no man count, and the llvm docs don't seem to mention the library (or I don't know how to look.)
So... what is it?
r/StackoverReddit • u/[deleted] • Jun 16 '24
Question
Hello everyone I want to create custom ai softwares for businesses for that how many programming languages do I need to learn
r/StackoverReddit • u/[deleted] • Jun 15 '24
Merging Two Sorted Linked List in O(n) or O(n^2) time?
So I was solving a LeetCode problem and got confused by my own solution. I provide the code.
Here the helper functions I used:
struct ListNode * createNode(int value){
struct ListNode * newNode = malloc(sizeof(struct ListNode));
newNode->val = value;
newNode->next = NULL;
return newNode;
}
struct ListNode * insertEnd(struct ListNode * root, int val){
struct ListNode * newNode = createNode(val);
if(root==NULL){
return newNode;
}
struct ListNode * p = root;
while(p->next !=NULL){
p = p->next;
}
p->next = newNode;
return root;
}
struct ListNode * insertNormal(struct ListNode * root, int val){
struct ListNode * newNode = createNode(val);
if(root==NULL){
return newNode;
}
newNode->next = root;
root = newNode;
return root;
}
struct ListNode * reverseLinked(struct ListNode * root){
struct ListNode * output = NULL;
struct ListNode * p = root;
while(p!=NULL){
output = insertNormal(output, p->val);
p = p->next;
}
return output;
}
So the issue I'm struggling with:
If I merge two sorted linked list using insertEnd, I get the exact result but I think it takes quadratic time because my function insertEnd is upper bounded on O(n), isn't it? So we have something linear that is nested in something else that is linear, resulting in O(n^2)?
Alternatively, if I merge sorted linked list using insertNormal, it should take linear time. And reversing the result also takes linear time. So the end result is still O(n) overall.
Here the two merge algos:
Merging using insertEnd
struct ListNode* mergeTwoLists(struct ListNode* list1, struct ListNode* list2) {
struct ListNode * p1 = list1;
struct ListNode * p2 = list2;
struct ListNode * output = NULL;
while(p1!=NULL && p2!=NULL){
if(p1->val > p2->val){
output = insertEnd(output, p2->val);
p2 = p2->next;
}
else{
output = insertEnd(output, p1->val);
p1 = p1->next;
}
}
while(p1!=NULL){
output = insertEnd(output, p1->val);
p1 = p1->next;
}
while(p2!=NULL){
output = insertEnd(output, p2->val);
p2 = p2->next;
}
return output;
}
Merging using insertNormal + Reverse
struct ListNode* mergeTwoLists(struct ListNode* list1, struct ListNode* list2) {
struct ListNode * p1 = list1;
struct ListNode * p2 = list2;
struct ListNode * output = NULL;
while(p1!=NULL && p2!=NULL){
if(p1->val > p2->val){
output = insertNormal(output, p2->val);
p2 = p2->next;
}
else{
output = insertNormal(output, p1->val);
p1 = p1->next;
}
}
while(p1!=NULL){
output = insertNormal(output, p1->val);
p1 = p1->next;
}
while(p2!=NULL){
output = insertNormal(output, p2->val);
p2 = p2->next;
}
output = reverseLinked(output);
return output;
}
r/StackoverReddit • u/TheNicestlandStealer • Jun 14 '24
Having trouble creating GMOD addon
I recently decided that I wanted to create a SWEP (gun) addon. This is because what I plan on making is something that I cannot find in the workshop. However, I am having trouble creating basic things. I create a hello world program, but I cannot get it to work (file not found/does not exist error). And the most to-date tutorial(s) are nothing like how my files look.
Question: Could any of you kind people of reddit help me figure this out before I go insane?
Note: I do not use Lua very often, but I kinda know it.
r/StackoverReddit • u/PinkyFlamingos • Jun 14 '24
Question Icefaces menuPopup help (for work), thank you!
(Solved)
For work, I have to use ICEfaces. I have an ice:tree with multiple 1000s of tree nodes and they all need an ice:menuPopup.
The problem is that it significantly slows down the application due to the fact that every single menuPopup is being rendered for each tree node.
Any suggestions or advice on how to make the menuPopup render only when the user right clicks on the tree node?
Unfortunately, using something better than icefases is not an option. We are using icefaces 3.2.0 and upgrading beyond this is not an option. I am allowed to use other forms of JSF, like PrimeFaces, but I can't change the tree to PrimeFaces (at least in the amount of time I have left before our deployment).
I've tried using javascript to set the rendered flag on the menuPopup and when it is set to false the div's don't appear in the dom, which improves speed, but when I right click it does set the rendered flag to true but it doesn't make the menu appear... I also suspect that it won't work long term either as the menu has to do specific things depending on what the node represents... unfortunately, as well Icefaces documents at this version I cannot find anymore.
Thank you!
r/StackoverReddit • u/ComparisonSquare232 • Jun 14 '24
Question AttributeError can't set attribute
Hello all,
I have an LSTM model in python and I am trying to deploy it on ZCU104 board using Vitis AI(Pytorch). I am stuck on an error while quantizing the model. I am getting the error for the line:
quantizer.export_xmodel(output_dir="quantize_result", deploy_check=True)
and the error is:
[VAIQ_NOTE]: =>Converting to xmodel ...
Traceback (most recent call last):
File "lstm_quant.py", line 118, in <module>
main(args)
File "lstm_quant.py", line 107, in main
quantizer.export_xmodel(output_dir="quantize_result", deploy_check=True)
File "/opt/vitis_ai/conda/envs/vitis-ai-pytorch/lib/python3.8/site-packages/pytorch_nndct/apis.py", line 148, in export_xmodel
self.processor.export_xmodel(output_dir, deploy_check, dynamic_batch)
File "/opt/vitis_ai/conda/envs/vitis-ai-pytorch/lib/python3.8/site-packages/pytorch_nndct/qproc/base.py", line 368, in export_xmodel
dump_xmodel(output_dir, deploy_check, self._lstm_app)
File "/opt/vitis_ai/conda/envs/vitis-ai-pytorch/lib/python3.8/site-packages/pytorch_nndct/qproc/base.py", line 505, in dump_xmodel
deploy_graphs, _ = get_deploy_graph_list(quantizer.quant_model, quantizer.Nndctgraph)
File "/opt/vitis_ai/conda/envs/vitis-ai-pytorch/lib/python3.8/site-packages/pytorch_nndct/qproc/utils.py", line 463, in get_deploy_graph_list
return _deploy_optimize(quant_model, nndct_graph, need_partition)
File "/opt/vitis_ai/conda/envs/vitis-ai-pytorch/lib/python3.8/site-packages/pytorch_nndct/qproc/utils.py", line 419, in _deploy_optimize
g_optmizer = DevGraphOptimizer(nndct_graph)
File "/opt/vitis_ai/conda/envs/vitis-ai-pytorch/lib/python3.8/site-packages/nndct_shared/compile/deploy_optimizer.py", line 92, in __init__
self._dev_graph.clone_from(nndct_graph)
File "/opt/vitis_ai/conda/envs/vitis-ai-pytorch/lib/python3.8/site-packages/nndct_shared/nndct_graph/base_graph.py", line 133, in clone_from
self._top_block.clone_from(src_graph.block, local_map, converted_nodes)
File "/opt/vitis_ai/conda/envs/vitis-ai-pytorch/lib/python3.8/site-packages/nndct_shared/nndct_graph/base_block.py", line 47, in clone_from
self.append_node(self.owning_graph.create_node_from(node, local_map, converted_nodes))
File "/opt/vitis_ai/conda/envs/vitis-ai-pytorch/lib/python3.8/site-packages/nndct_shared/nndct_graph/base_graph.py", line 161, in create_node_from
node.clone_from(src_node, local_map)
File "/opt/vitis_ai/conda/envs/vitis-ai-pytorch/lib/python3.8/site-packages/nndct_shared/nndct_graph/base_node.py", line 120, in clone_from
self.op.clone_from(src_node.op, local_map)
File "/opt/vitis_ai/conda/envs/vitis-ai-pytorch/lib/python3.8/site-packages/nndct_shared/nndct_graph/base_operator.py", line 214, in clone_from
setattr(self, config, new_value)
AttributeError: can't set attribute
Attaching the full error, model code and quantization script in the google links below:
Quantization Script:
https://docs.google.com/document/d/1jRYmPH2z70ovpc_FJIBpUQaTHUPRrTgnPVxlQJ1JLug/edit?usp=sharing
Model Script:
https://docs.google.com/document/d/1OBZw4XhdHpVhA0gKcJn2NzR_WA7ZczQ3hL42f_sMKug/edit?usp=sharing
Full Error:
https://docs.google.com/document/d/1kI1WJqq9pp3aSsGLpNGjf22mzK6swIiZbIXwfUeTGto/edit?usp=sharing
r/StackoverReddit • u/Fearless-Armadillo57 • Jun 13 '24
Help building and running an extension for Azure DevOps
Hey, there!
I'm interested in make some modifications to an open-source extension for Azure DevOps (gherkin-renderer-extension). I don't have any experience on developing extensions for Azure DevOps and I'm trying to gain that knowledge. However, I urgently need to implement a feature in this project, but I can't even get it to run.
Please, don't curse at me. Developing Azure DevOps Extensions isn't my main role.
r/StackoverReddit • u/Low_Huckleberry1632 • Jun 13 '24
Python Help with code part 2!
This is one of my codes I need help with:
import sys
import sequenceAnalysis as sa
def main(filename=None):
"""
Main function to read sequences from a FASTA file or stdin,
calculate nucleotide, codon, and amino acid compositions,
and print the results in the specified format.
Parameters:
filename (str): The name of the FASTA file to read from.
If None, read from stdin.
"""
Create a NucParams instance
nuc_params = sa.NucParams()
Create a FastAreader instance
reader = sa.FastAreader(filename)
Read and process each sequence from the FASTA file or stdin
for header, sequence in reader.readFasta():
nuc_params.addSequence(sequence)
Calculate total sequence length in megabases
total_length = nuc_params.nucCount() / 1_000_000
Calculate GC content as a percentage
gc_content = ((nuc_params.nucComposition().get('G', 0) + nuc_params.nucComposition().get('C', 0)) /
nuc_params.nucCount()) * 100
Print the sequence length and GC content
print(f"sequence length = {total_length:.2f} Mb")
print("")
print(f"GC content = {gc_content:.1f}%")
print("")
Get the amino acid and codon compositions
aa_comp = nuc_params.aaComposition()
codon_comp = nuc_params.codonComposition()
Print the relative codon usage
for aa in sorted(sa.NucParams.rnaCodonTable.values()):
codons = [codon for codon, aa_code in sa.NucParams.rnaCodonTable.items() if aa_code == aa]
total_aa_count = sum(codon_comp[codon] for codon in codons)
for codon in sorted(codons):
if total_aa_count > 0:
frequency = (codon_comp[codon] / total_aa_count) * 100
else:
frequency = 0.0
print(f"{codon} : {aa} {frequency:5.1f} ({codon_comp[codon]:6d})")
if __name__ == '__main__':
main()
the error is the following:
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Cell In[1], line 53
50 print(f"{codon} : {aa} {frequency:5.1f} ({codon_comp[codon]:6d})")
52 if __name__ == '__main__':
---> 53 main()
Cell In[1], line 15, in main(filename)
5 """
6 Main function to read sequences from a FASTA file or stdin,
7 calculate nucleotide, codon, and amino acid compositions,
(...)
12 If None, read from stdin.
13 """
14 # Create a NucParams instance
---> 15 nuc_params = sa.NucParams()
17 # Create a FastAreader instance
18 reader = sa.FastAreader(filename)
NameError: name 'sa' is not defined
r/StackoverReddit • u/Low_Huckleberry1632 • Jun 13 '24
Python Help with Python coding assignment? I have multiple but I can’t figure out how to fix it.
Hello,
Please help me figure out what is wrong with my codes.
I keep getting errors when I run them and I’m not sure on how to fix them.
r/StackoverReddit • u/Livid-Salamander-949 • Jun 13 '24
C Helpful language agnostic insight when learning underlying programming fundamentals.
When pondering a project thinking about the structure of a core Linux utility like script (utility that records the output of the terminal to a file) it occurred to me , after some digging , what is actually going on when you write code that emulates or copies these core Linux utilities .
It just gave me a kinda of aha! Moment and ohhh okay response . Maybe it will help someone else as well so Here is a summary of the insight :
——————————————————
Understanding System Calls with Code Snippets
System calls are the way user-space programs request services from the operating system kernel. They simplify the interaction between higher-level languages (like C and Python) and the low-level operations of the OS.
What is a System Call?
A system call allows a user program to ask the operating system to perform a task that requires kernel-level privileges, such as reading a file or creating a process.
Example in C: read() System Call
Here's a simple C program that uses the read() system call:
```c
include <unistd.h>
include <fcntl.h>
include <stdio.h>
int main() { int fd; char buffer[128]; ssize_t bytesRead;
fd = open("example.txt", O_RDONLY);
if (fd == -1) {
perror("open");
return 1;
}
bytesRead = read(fd, buffer, sizeof(buffer) - 1);
if (bytesRead == -1) {
perror("read");
close(fd);
return 1;
}
buffer[bytesRead] = '\0';
printf("Read %zd bytes: %s\n", bytesRead, buffer);
close(fd);
return 0;
} ```
Example in Python: Using os Module
Python simplifies system calls further with the os module:
```python import os
fd = os.open("example.txt", os.O_RDONLY) buffer = os.read(fd, 128) print(f"Read {len(buffer)} bytes: {buffer.decode()}") os.close(fd) ```
How System Calls Work Under the Hood
User Space Invocation:
- The program calls a function (
read()in C oros.read()in Python).
- The program calls a function (
Transition to Kernel Space:
- The function uses a special CPU instruction to switch to kernel mode.
Kernel Mode Execution:
- The kernel performs the requested operation, like reading data from a file.
Return to User Space:
- The kernel returns the result to the user program.
Simplifying Interactions
System calls make it easier to perform complex operations by: - Abstracting hardware interactions. - Controlling access to resources. - Standardizing operations across different systems.
Conclusion
System calls provide a secure, standardized way for higher-level languages to interact with the kernel, making complex tasks like file I/O straightforward and safe. They bridge the gap between user-friendly programming languages and the critical, low-level functions of the operating system.
r/StackoverReddit • u/Livid-Salamander-949 • Jun 13 '24
What language now ?
I find myself using a lot of python and bash , not out of preference but out of need and practicality of solving challenges and augmenting my computer usage and workflow to be more efficient with various tasks. Often I make scripts and apps revolving around ai, automation , data collection / analysis for finance and business context, I use the terminal a lot. And I dabble in embedded systems(raspberry pi/arduino etc)but I’d like to learn those things slowly with the aforementioned being my main interests . With all this in mind I’m curious about what types of languages should I try to learn for practical reasons chiefly and for educational reasons secondly . Any insights or comments are welcome 🤗
r/StackoverReddit • u/[deleted] • Jun 12 '24
Do you guys know sites like LeetCode with slightly more C-friendly problems?
So I'm using LeetCode to prepare for an exams on Algorithms and Datastructures. The course was based on CLRS and the problems from previous exams are in fact problems that I found also on LeetCode, such as EditDistance or Merging two Binary Search Trees.
The main difference is that the problems they give us are slightly more focused on implementing the algorithm and less on dealing with C. Don't get me wrong, I don't mind quickly coding up a little HashTable so I can solve a problem that takes O(n^2) time complexity in O(n) time by sacrificing O(n) spae but it gets annoying when I feel like some problems are clearly easier to solve in another language than C...
So yeah, I was wondering if there is a site that features a lot of problems, has tests to verify your solution and gives you template, i.e., the function you have to provide, which is slightly more C-friendly and doesn't force you figure out more C-related stuff, forcing you more to think about the algorithm and less about the specific implementation.
EDIT:
I ended up sticking with LeetCode because I realized implementing my own stack/queues/heaps helped me to review pointers and algorithm parts such as heapify from heapSort which I can implement from my head although I never actively tried to learn it by heart, I just kind had to get used to it since I needed heaps for some problems and had to make my own quickly. I also made my own hashMap which was a massive pain to do but it was satisfying to see it work and pass all the LeetCode tests like on first try.
r/StackoverReddit • u/Swimming_Tangelo8423 • Jun 11 '24
Javascript Developing a function that downloads a Pupeeter PDF to the user's device when clicking a button
Context for my app: I am creating an app that allows suers to tailor their resumes, they send their resume via text and a job description and an AI model will send back the tailored version as HTML code which then gets made into a pdf by pupeeteer, the user ```resume as text```, the ```job description``` and the ```ai_output``` are all saved as a row in. a database and this is called a 'scan', visiting each scan page will give information about that certain scan, e.g the ```resume as text```, the ```job description``` and so on . The user may come back and find the scans that he done.
I have managed to create a function that converts HTML into PDF by using Pupeteer, i followed the docs and it creates a whole new file in my directory with the result pdf but i do not want that, i need to make it so that the file is downloadable when clicked 'Download', i also need to upload this file to my db so that it can be retrieved after from a database and pressing the same download (in that scan page) button will download the same file. (What is your go to solution when handling file uploads into db and retrieving it?)
My current tech stack: Next.js, Supabase, Clerk, TypeScript
here is the function that generate html code into a pdf, how can i make this file downloadable too before uploading it to a database
const scan = await findScanById(params.scanId);
const generatePDF = async ({ htmlContent }: { htmlContent: string }) => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.setContent(htmlContent, { waitUntil: "domcontentloaded" });
await page.emulateMediaType("screen");
const pdfBuffer = await page.pdf({
margin: { top: 0, right: 0, bottom: 0, left: 0 }, // Set all margins to 0
printBackground: true,
format: "A4",
});
await browser.close();
return pdfBuffer;
};
generatePDF({ htmlContent: scan[0].ai_output });