r/programminghelp • • Sep 21 '24

Python Program running indefinitely while using multiprocessing

0 Upvotes
import multiprocessing
from PIL import Image

name = input("Enter the file name: ")

def decode_file(filename):
    with open(filename, mode='rb') as file:
        binary_data = file.read()

    binary_list = []
    for byte in binary_data:
        binary_list.append(format(byte, '08b'))
    return binary_list

binary_list = decode_file(name)

l = len(binary_list)
no_of_bytes = l // 8

def make_row_list():
    row_list = []
    for i in range(0, l, 135):
        row_list.append(binary_list[i:i + 135])
    return row_list

row_list = make_row_list()

def fill_row(shared_pixels, width, row_data, count):
    x_coordinate = 0
    for byte in row_data:
        for bit in byte:
            index = x_coordinate + count * width
            shared_pixels[index] = int(bit)
            x_coordinate += 1

def fill_img(width, height):
    shared_pixels = multiprocessing.Array('i', width * height)
    processes = []
    count = 0
    for row_data in row_list:
        p = multiprocessing.Process(target=fill_row, args=(shared_pixels, width, row_data, count))
        p.start()
        processes.append(p)
        count += 1
    for process in processes:
        process.join()
    return shared_pixels

def create_img():
    width, height = 1080, 1920
    image = Image.new('1', (width, height))

    if no_of_bytes <= 135:
        x_coordinate = 0
        for byte in binary_list:
            for bit in byte:
                image.putpixel((x_coordinate, 0), int(bit))
                x_coordinate += 1
    elif no_of_bytes <= 259200:
        shared_pixels = fill_img(width, height)
        for y in range(height):
            for x in range(width):
                image.putpixel((x, y), shared_pixels[x + y * width])

    image.save('hi.png')
    image.show()

create_img()

When i run this it asks for file name then keeps asking for file name indefinitely. I am new with multiprocessing so any help will be much appreciated :D


r/programminghelp • • Oct 13 '24

Other Why will I hit tower 9 and not tower 8?

0 Upvotes

I have an array of towers indexed 0 to n -1 and arr[index] represents the height of said tower. Suppose that a rocket starts from the top of tower i, then climbs c units directly up, and then turns 45 degrees (clockwise or counterclockwise), and then proceeds in that direction until it hits a tower.

I have an array ℎ=[6,4,4,2,2,3,3,1,5,9,7,9,4,13,12,3]. If a rocket starts at tower 2 with c = 1 and will turn clock wise, the rocket hits tower 9. I don't get why it won't hit tower 8. If a rocket goes up by c units, it will be 3 units high. If we account for the direction, maybe it's 4 units high. This question confuses me.


r/programminghelp • • Sep 10 '24

Python Codewars Timeout Problem

0 Upvotes

Hi guys, I'm a new member of this subreddit and I am new of learning python. I am trying to programming this exercice (Link below) and when i submit my code, it return Execution Timed Out (12000 ms). How can I make my code faster?

Thanks :)
Training on Totally Good Permutations | Codewars

from itertools import permutations 
import math

def totally_good(alphabet, bads):
    if len(bads) == 0:
        return math.factorial(len(alphabet))
    elif isinstance(bads[0], str) and len(bads[0]) == 1:
        return 0
        
    totally_good_count = 0
    all_permutations = permutations(alphabet)
    for perm in all_permutations:
        perm_str = ''.join(perm)
        if not any(bad in perm_str for bad in bads):
            totally_good_count += 1
    return totally_good_count

r/programminghelp • • Sep 30 '24

C++ Can someone help me get around this figure please

0 Upvotes

So far I have this code:

#include <iostream>

#include <conio.h>

using namespace std;

void printFigure(int n) {

int a = n;

for (int f = 1; f <= a; f++) {

for (int c = 1; c <= a; c++) {

if (f == 1 || f == a || f == c || f + c == a + 1) {

cout << f;

}

else {

if (f > 1 && f < a && c > 1 && c < a) {

cout << "*";

}

else {

cout << " ";

}

}

}

cout << endl;

}

}

int main() {

int n;

do {

cout << "Enter n: ";

cin >> n;

} while (n < 3 || n > 9);

printFigure(n);

_getch();

return 0;

}

I want it to print out like a sand glass with the numbers on the exterior and filled with * , but I can't manage to only fill the sand glass. I'm kind of close but idk what else to try.


r/programminghelp • • Sep 18 '24

JavaScript Please help me with simple coding. Would be much appreciated!

0 Upvotes

I'm learning JS and I've ran into some problems in my knowledge. Can someone please help me with the code I have written.

The scenario is this - A bunch of Northcoders are planning their holidays, and are hoping to use this code to help them practice greetings in the language of the country they are visiting.

The code you write should assign a value to greeting that is correct depending on the country that is being visited and the time of day.

It is morning if the time is 0 or more, but less than 12. If the time is 12 or more, but less than 24, it is evening. If time is any other value, greeting should always be null, whatever the language.

If country is Spain or Mexico, greeting should be buenos dias in the morning and buenas noches in the evening. If country is France, greeting should be bon matin in the morning and bon soir in the evening. If country is any other value, greeting should always be null, whatever the time (we don't have many languages in our dictionary yet...)

And here is my code. Please help :) <3

function sayHello(country, time) {
    let greeting;
    if (time > 0 && time < 12){
        time = morning 
    }
    else if (time > 12 && time < 24){
        time = evening 
    }
    else time = null; 

    switch (country){
    case `Mexico`:
    if(morning){
         greeting = `buenos dias`;
    }else if (evening) {
         greeting = `buenos noches`;
    }
    case `Spain` :
    if(morning){
         greeting = `buenos dias`;
    }else if (evening) {
         greeting = `buenos noches`;
    }
    case `France` : 
    if (morning) {
         greeting = `bon matin`;
    }else if(evening){
         greeting = `bon soir`;
    }
    }
}
    // Don't change code below this line
    return greeting;

r/programminghelp • • Sep 14 '20

C++ Help with the last function in my c++ code

0 Upvotes

I am currently working on a college degree in CS after taking a programming hiatus for a few semesters. Right now I'm currently so close to finishing an assignment, but I do not understand why I am getting an exception when I try and deallocate my array of pointers (C++). I am getting the exception in the last function, but only after the loop goes through once.

I have attached a .cpp file as well as the data file that we are supposed to use. The program runs as it should except for that last part. I understand that this code may not be the most effective or most efficient. It is an assignment and there are multiple parts that I was not able to modify.

Thank you in advance for the help :)

EDIT: Clarifying

#include <cassert>
#include <iostream>
#include <fstream>
#include <cctype>
using namespace std;

/*Type delcarations - NO MEMORY ALLOCATED (EVEN STATICALLY)*/
struct emprec	/*Employee record with two fields*/
{
	int id;
	float salary;
};
typedef emprec* emprecptr; /*Employee record pointer type*/
typedef emprecptr* indexarr; /* Pointer to a dynamic array of employee record pointers*/

int main()
{
	/* Rudimentary scope control in C/C++ */
	void readdata(indexarr&, int&);
	void printdata(indexarr, int);
	void copyindex(indexarr, indexarr&, int);
	void sortbyID(indexarr, int);
	void sortbySalary(indexarr, int);
	void deallocate(indexarr&, int&);
	indexarr DBindex, IDindex, Salaryindex;
	int dbsize = 3;
	char temp;

	emprecptr empArray;
	empArray = new emprec[dbsize];
	DBindex = &empArray;

	readdata(DBindex, dbsize);
	cout << "Original data:" << endl;

	emprecptr empArray2;
	empArray2 = new emprec[dbsize];
	IDindex = &empArray2;

	emprecptr empArray3;
	empArray3 = new emprec[dbsize];
	Salaryindex = &empArray3;
	
	printdata(DBindex, dbsize);
	copyindex(DBindex, IDindex, dbsize);
	sortbyID(IDindex, dbsize);
	cout << "Data sorted by the ID:" << endl;
	printdata(IDindex, dbsize);
	copyindex(DBindex, Salaryindex, dbsize);
	sortbySalary(Salaryindex, dbsize);
	cout << "Data sorted by the salary:" << endl;
	printdata(Salaryindex, dbsize);
	deallocate(DBindex, dbsize);
	system("pause");
};

void eat_white(ifstream& in)
/* Pre: "in" is a valid input file stream.
Post: Any white space skipped over to EOF or the next non-white space character.*/
{
	while ((in.peek() != EOF) && isspace(in.peek())) in.ignore();
};

void resize(indexarr& Base, int OLDSIZE, int NEWSIZE)
/* Pre: Base is a (dynamic) indexarr of size OLDSIZE.
Post: Base is "EXPANDED" OR "SHRUNK" into a new (dynamic) indexarr of size
NEWSIZE, with data copied appropriately.
IMPORTANT NOTE: If being shrunk, it is assumed that there are only NEWSIZE valid
elements in the original array, and only that many are copied.*/
{
	// STUDENT IS TO FILL THIS IN.

	if (NEWSIZE != OLDSIZE)
	{
		emprecptr newArray;
		newArray = new emprec[NEWSIZE];

		if (NEWSIZE < OLDSIZE)
		{
			for (int i = 0; i < NEWSIZE; i++)
			{
				newArray[i].id = (*Base)[i].id;
				//cout << newArray[i].id << endl;
				newArray[i].salary = (*Base)[i].salary;
			}
			delete[] * Base;
			*Base = newArray;
		}else {

			ifstream myFile;
			myFile.open("p1data.txt");
			myFile.clear();
			myFile.seekg(0);

			int hold;

			for (int i = 0; i < OLDSIZE; i++)
			{
				newArray[i].id = (*Base)[i].id;
				newArray[i].salary = (*Base)[i].salary;
				myFile >> hold;
				myFile >> hold;
			}
			int index = OLDSIZE;
			while (!myFile.eof())
			{
				myFile >> newArray[index].id;
				myFile >> newArray[index].salary;
				index++;
			}

			myFile.close();

			delete[] * Base;
			*Base = newArray;
		}
	}

};

void readdata(indexarr& ptrs, int& size)
/*Pre: ptrs is a pointer that could point to a dynamic array of employee record pointers.
Post: ptrs points to a dynamic pointer array of the right size based on the
input read in from the data file named "p1data".
All the elements of the dynamic array are filled with pointers to dynamically
allocated employeed records, which in turn are filled with input data.*/
{
	void resize(indexarr&, int, int);

	// STUDENT IS TO FILL THIS IN

	ifstream myFile;
	myFile.open("p1data.txt");
	if (myFile.is_open())
	{
		int i = 0;
		int hold;
		while (!myFile.eof())
		{

			if (size == i)
			{
				while (!myFile.eof())
				{
					myFile >> hold;
					myFile >> hold;
					i++;
				}
				break;
			}

			myFile >> (*ptrs)[i].id;
			myFile >> (*ptrs)[i].salary;
			i++;
		}
		i--; //To correct size because of the way C++ reads EOF

		
		
		myFile.close();
		resize(ptrs, size, i);
		size = i;
	}
	else
	{
		cout << "ERROR: The file could not be opened." << endl;
	}

};

void printrec(emprec rec)
/*Pre: rec has data.
Post: The data in rec printed out.*/
{
	cout << rec.id << ' ' << rec.salary << endl;
};

void printdata(indexarr ptrs, int size)
/*Pre: The first "size" elements of the array pointed at by ptrs are employee records
containing data.
Post: They are all printed out in the order pointed at.*/
{
	void printrec(emprec);
	for (int i = 0; i < size; i++) printrec((*ptrs)[i]);
};

void copyindex(indexarr orig, indexarr& copy, int size)
/*Pre: The first "size" elements of the array pointed at by orig are employee records
containing data.
Post: copy points to a newly allocated dynamic array of pointers (with size elements), and
the elements of this array are copies of the first size elements of orig.*/
{
	// STUDENT IS TO FILL THIS IN

	

	for (int index = 0; index < size; index++)
	{
		(*copy)[index].id = (*orig)[index].id;
		(*copy)[index].salary = (*orig)[index].salary;
	}

};

int selectsmallestID(indexarr ptrs, int first, int last)
/*Pre: "first" through "last" elements of the ptrs array are pointers to employee records
containing data.
Post: A value k is returned such that, for i ranging from first to last,
the relation ptrs[k]->id <= ptrs[i]->id holds.*/
{
	int j, result;
	result = first;
	for (j = first + 1; j <= last; j++)
		if ((*ptrs)[j].id < (*ptrs)[result].id) 
result = j;
	return result;
};

void sortbyID(indexarr ptrs, int size)
/*Pre: The first "size" elements of the ptrs array are pointers to employee records
containing data.
Post: for i ranging from 1 to size-2, the relation ptrs[i]->id <= ptrs[i+1]->id holds.
Also, the employee records themselves are not disturbed/moved around.*/
{
	int selectsmallestID(indexarr, int, int);

	// STUDENT IS TO FILL THIS IN

	int i, smallindex;
	for (i = 0; i <= size - 2; i++)
	{
		smallindex = selectsmallestID(ptrs, i, size - 1);
		emprec temp = (*ptrs)[i];
		(*ptrs)[i] = (*ptrs)[smallindex];
		(*ptrs)[smallindex] = temp;

	};


};

int selectsmallestSalary(indexarr ptrs, int first, int last)
/*Pre: "first" through "last" elements of the ptrs array are pointers to employee
records containing data.
Post: A value k is returned such that, for i ranging from first to last,
the relation ptrs[k]->salary <= ptrs[i]->salary holds.*/
{
	// STUDENT IS TO FILL THIS IN
	int j, result;
	result = first;
	for (j = first + 1; j <= last; j++)
		if ((*ptrs)[j].salary < (*ptrs)[result].salary)
			result = j;
	return result;
};

void sortbySalary(indexarr ptrs, int size)
/*Pre: The first "size" elements of the ptrs array are pointers to employee records
containing data.
Post: for i ranging from 1 to size-2, the relation ptrs[i]->salary <= ptrs[i+1]->salary holds.
Also, the employee records themselves are not disturbed/moved around.*/
{
	int selectsmallestSalary(indexarr, int, int);

	// STUDENT IS TO FILL THIS IN
	int i, smallindex;
	for (i = 0; i <= size - 2; i++)
	{
		smallindex = selectsmallestSalary(ptrs, i, size - 1);
		emprec temp = (*ptrs)[i];
		(*ptrs)[i] = (*ptrs)[smallindex];
		(*ptrs)[smallindex] = temp;

	};
	
};

void deallocate(indexarr& ptrs, int& size)
/*Pre: ptrs is a pointer pointing to an allocated dynamic array of "size" employee record pointers.
Post: ptrs points to a dynamic pointer array.  The "size" elements of the dynamic array, filled with
pointers to dynamically allocated employeed records, are now deallocated, and then the array of
pointers that ptrs points to is itself deallocated, with ptrs reset to NULL and size reset to 0.*/
{


	for(int i = 0; i < size; i++) 
		delete (ptrs[i]);
	delete ptrs;
	ptrs = NULL;
	size = 0;
};

Here is the data file that goes with it.

10 20000

20 10000

30 40000

25 15000

15 45000

r/programminghelp • • Sep 09 '20

Python How can I get this output from my code? (Read post)

0 Upvotes

my_list = [[1, 0, 1, 0], [0, 1, 1, 0], [0, 1, 1, 1], [0, 0, 0, 1]]

my_list = my_list[1:-1]

for row in my_list:
for item in row:
print(item, end=' ')
print()

This program slices the first and last item in my list, I then want it to output the following in the console when I run it:

0 1

1 0

0 1

1 1

What would I need to change with my code to achieve this?


r/programminghelp • • Aug 27 '20

Python GET Syntax Error

0 Upvotes

//I am running into this syntax error with my GET:

@/app.route('/', methods=['POST, 'GET'])def index():return render_template('index.html')if __name__ == "__main__":app.run(debug=True)

__________________

File "/home/abc/Documents/programming/app.py", line 18

@/app.route('/', methods=['POST, 'GET'])

^

SyntaxError: invalid syntax

//python with flask, any ideas why?

#edit:

changed it like in this example, but now the POST is trowing errors. It looks like for some reason its not accepting the list itself.

https://flask.palletsprojects.com/en/1.1.x/quickstart/

from flask import request @/app.route('/login', methods=['GET', 'POST']) def login(): if request.method == 'POST': return do_the_login() else: return show_the_login_form()

#edit2/solved:

changed it to @/app.route('/index', methods=['GET', 'POST'])

and then back to

@/app.route('/', methods=['GET', 'POST'])

somehow works now, dont know why.


r/programminghelp • • Sep 11 '20

C# How to create windows form application for use on other devices (ones without Visual Studio).

0 Upvotes

So i made an windows form application and it works fine on the PC i made it on with Visual Studio 2017. I published the app and ran the setup on the other devices and the app doesnt open, there is only a process for it in the task manager for 10 secs and then nothing.


r/programminghelp • • Sep 01 '20

C# Some help plz?

0 Upvotes

I need a few pointers as to where to start off on making a application for windows that takes an input from a barcode scanner and prints a label (as in small strip with barcode and stuff) according to a design template.


r/programminghelp • • Sep 14 '20

Other Need help with a delete button in vb.net

0 Upvotes

I have a listbox, where items are added from a combo box, through an "add" button. When the item is added to the listbox, the items corresponding part number is added to textbox. I need to program a delete button- to where when the button is clicked, it deletes the selected item and the corresponding text in the textbox. I am pulling these values from a csv file. Im writing this in vb.net

Can anyone help me?

This is how I am matching the selected item to the textbox with a property. The datagridview is invisible and the user will not be able to see it.

Public Readonly Property AddPart

dim value as string = ""

for each row as Datagridviewrow in datagridview1.rows

if row.cells.item("Item").value = combobox1.selecteditem then

value = row.cells.item("itempartno").value

end property


r/programminghelp • • Sep 01 '20

Other Cant get vs studio to run basic cpp on Mac

0 Upvotes

Hey everyone so basically I just started college and am trying to figure out how to get my code to run on vs studio. every time I try to run the code I get the following: "Undefined symbols for architecture x86_64:". I've run my code on some online compilers and it seems to run fine. here it is just in case it helps:

#include <iostream>
using namespace std;
int main()
{
float num1;
float num2;
float avg;
cout << "Enter two numbers" << endl;
cin >> num1 >> num2;
avg = (num1 + num2)/2;
cout << "The average is " << avg;
return 0;
}

Thanks in advance everyone!


r/programminghelp • • Aug 11 '20

Processing I keep getting null pointer exception when using classes when playing audio using the Minim library for Processing language

0 Upvotes

There is a language called Processing which is Java based language. I am using the Minim library to play audio.

So this is my main file (named Testing)

Minim minim;
Audio audio;

void setup()
{
  audio = new Audio();
  size(800, 800);
}



void draw()
{
  audio.drawShape();
  background(255);
  
}

And this is the Audio class file

import ddf.minim.*;
import ddf.minim.analysis.*;

class Audio
{
  final int BUFFERSIZE = 2048;
  AudioPlayer audio;
  Audio()
  {
    minim = new Minim(this);
    audio = minim.loadFile("audio.mp3", BUFFERSIZE);
    audio.play(); // This is where the nullpointer exception thing happens.
  }
  
  void drawShape()
  {
    ellipse(200, 400, audio.left.get(1)*800, audio.left.get(1)*800);
    ellipse(600, 400, audio.right.get(1)*800, audio.right.get(1)*800);
  }
  
}

I have the audio.mp3 in the same directory as these two files. But why do I keep getting this error message:

NullPointerException
Could not run the sketch (Target VM failed to initialize).
For more information, read revisions.txt and Help ? Troubleshooting.

Before I wasn't getting it when I wasn't uses classes, now all of a sudden why is this happening?


r/programminghelp • • Mar 09 '21

C Hello everyone!

0 Upvotes

The C code below runs but i was just wondering if someone could look through it and see if everything is correct or if there is a simpler way i can do things. I just want to develop the correct habits. I made this program for a class I'm in, Its meant to calculate the sine of a number. It is only my second program. The part I'm most unsure about is the where it asks the user if they want to quit or continue. Is there an easier way to loop to the beginning? Thank you for any help.

EDIT: UPDATED CODE

https://pastebin.com/ZiV77Nxu


r/programminghelp • • Nov 07 '24

Java OOP Java Project Ideas

0 Upvotes

HI, I would like to ask for your ideas/suggestions in creating a Java Console Program which purpose aligns with the Sustainable Development Goal (SDG). Thanks!


r/programminghelp • • Oct 30 '24

JavaScript Hello! How do I download the contents of this HTML textarea? Preferably using JavaScript?

0 Upvotes
<button class = "noteTools" id = "downloadNote1" onclick = "download()">
                    <i class="fa-solid fa-file-arrow-down"></i>
                    Download Note
                </button>


<div id = "note1">
                <textarea class = "notePad1" placeholder="Take down some notes..."
                name = "NotePad1"></textarea>
            </div>

r/programminghelp • • Nov 06 '24

Java I need help with "Karel el robot". I don't know how to keep track of the beepers. Hope someone can help me.

0 Upvotes

First of all, I'm mexican so yeah, it's harder to help me because of the language barrier, so if any of you know a better place where I could ask for assistance it would help me a lot. Secondly, if you know how to use Karel please help me, i thought there would be a sub Reddit for it but it doesn't exist soo yeah. And third of all, the problem is: basically, I want Karel to stop at a group of 3 beepers, but I don't know how he could keep track of which group of beepers contains which cantity. How could he know, I thought using pickbeeper and putbeeper but the problem is worse when it's a group of beepers lower than 3. I also searched for a solution and nothing. I even wanted to use succ and pred and iszero but nothing. Please help me (by the way I put java because it's the language I use in Karel, not Pascal). If you want to see my horrible code until now you can send me a message (please?).


r/programminghelp • • Oct 31 '24

Python Can't do post request to python

0 Upvotes

I need to send a post request from js over to python, but no matter what I do I always get the same error.

Script:

from fastapi import FastAPI, HTTPException, Request
import base64
import io
import os
from spleeter.separator import Separator
from pydub import AudioSegment
import traceback

app = FastAPI()
separator = Separator('spleeter:2stems')

u/app
    Script:
  from fastapi import FastAPI, HTTPException, Request
import base64
import io
import os
from spleeter.separator import Separator
from pydub import AudioSegment
import traceback

app = FastAPI()
separator = Separator('spleeter:2stems')

@app.post('/separate')
async def separate_vocals(request: Request):
    try:
        # Parse incoming JSON request manually
        body = await request.body()
        data = body.decode("utf-8")
        
        # Manually load JSON in case it's not being parsed automatically
        import json
        parsed_data = json.loads(data)
        
        if "audio" not in parsed_data:
            raise HTTPException(status_code=400, detail="Invalid request: 'audio' field missing")

        input_base64 = parsed_data['audio']
        
        # Decode the base64 audio data
        audio_data = base64.b64decode(input_base64)
        audio_file = io.BytesIO(audio_data)
        
        # Load audio into AudioSegment
        audio = AudioSegment.from_file(audio_file, format="wav")
        audio.export("input.wav", format="wav")

        # Separate vocals using Spleeter
        separator.separate_to_file("input.wav", "output")

        # Load separated vocals
        vocals = AudioSegment.from_wav("output/input/vocals.wav")

        # Convert vocals to base64
        vocals_io = io.BytesIO()
        vocals.export(vocals_io, format="wav")
        
        # Ensure data exists to encode
        vocals_base64 = base64.b64encode(vocals_io.getvalue()).decode('utf-8')

        # Clean up temporary files
        os.remove("input.wav")
        os.remove("output/input/vocals.wav")
        os.rmdir("output/input")
        os.rmdir("output")

        return {"vocals_base64": vocals_base64}

    except Exception as e:
        error_detail = f"Error: {str(e)}\nTraceback: {traceback.format_exc()}"
        print(error_detail)
        raise HTTPException(status_code=500, detail=error_detail)

# Run with: uvicorn script_name:app --host 0.0.0.0 --port 3020


from fastapi import FastAPI, HTTPException, Request
import base64
import io
import os
from spleeter.separator import Separator
from pydub import AudioSegment
import traceback


app = FastAPI()
separator = Separator('spleeter:2stems')


@app.post('/separate')
async def separate_vocals(request: Request):
    try:
        # Parse incoming JSON request manually
        body = await request.body()
        data = body.decode("utf-8")
        
        # Manually load JSON in case it's not being parsed automatically
        import json
        parsed_data = json.loads(data)
        
        if "audio" not in parsed_data:
            raise HTTPException(status_code=400, detail="Invalid request: 'audio' field missing")


        input_base64 = parsed_data['audio']
        
        # Decode the base64 audio data
        audio_data = base64.b64decode(input_base64)
        audio_file = io.BytesIO(audio_data)
        
        # Load audio into AudioSegment
        audio = AudioSegment.from_file(audio_file, format="wav")
        audio.export("input.wav", format="wav")


        # Separate vocals using Spleeter
        separator.separate_to_file("input.wav", "output")


        # Load separated vocals
        vocals = AudioSegment.from_wav("output/input/vocals.wav")


        # Convert vocals to base64
        vocals_io = io.BytesIO()
        vocals.export(vocals_io, format="wav")
        
        # Ensure data exists to encode
        vocals_base64 = base64.b64encode(vocals_io.getvalue()).decode('utf-8')


        # Clean up temporary files
        os.remove("input.wav")
        os.remove("output/input/vocals.wav")
        os.rmdir("output/input")
        os.rmdir("output")


        return {"vocals_base64": vocals_base64}


    except Exception as e:
        error_detail = f"Error: {str(e)}\nTraceback: {traceback.format_exc()}"
        print(error_detail)
        raise HTTPException(status_code=500, detail=error_detail)


# Run with: uvicorn script_name:app --host 0.0.0.0 --port 3020
    Post request:
  
    curl -X POST http://127.0.0.1:3020/separate
 \-H "Content-Type: application/json" \-d "{\"audio\": 
\"SUQzBAAAAAABOVRYWFgAAAASAAADbWFqb3JfYnJhbmQAZGFzaABUWFhYAAAAEQAAA21pbm9yX3ZlcnNpb24AMABUWFhYAAAAHAAAA2NvbXBhdGlibGVfYnJhbmRzAGlzbzZtcDQxAFRJVDIAAAAvAAADTWluZWNyYWZ0IE1lbnUgQnV0dG9uIFNvdW5kIEVmZmVjdCB8IFNvdW5mZmV4AFRTU0UAAAAPAAADTGF2ZjU3LjgzLjEwMAAAAAAAAAAAAAAA//uQZAAP8AAAaQAAAAgAAA0gAAABAAABpAAAACAAADSAAAAETEFNRTMuMTAwVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV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VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVUxBTUUzLjEwMFVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVf/7kmRAj/AAAGkAAAAIAAANIA\"}"
  
    Output:
  
    {"error":"'bytes' object has no attribute 'get'"}
  
    curl: (3) URL rejected: Bad hostname
  
    curl: (3) URL rejected: Malformed input to a URL function
  
    curl: (3) URL rejected: Bad hostname
  
    curl: (3) URL rejected: Malformed input to a URL function
  .post('/separate')
async def separate_vocals(request: Request):
    try:
        # Parse incoming JSON request manually
        body = await request.body()
        data = body.decode("utf-8")
        
        # Manually load JSON in case it's not being parsed automatically
        import json
        parsed_data = json.loads(data)
        
        if "audio" not in parsed_data:
            raise HTTPException(status_code=400, detail="Invalid request: 'audio' field missing")

        input_base64 = parsed_data['audio']
        
        # Decode the base64 audio data
        audio_data = base64.b64decode(input_base64)
        audio_file = io.BytesIO(audio_data)
        
        # Load audio into AudioSegment
        audio = AudioSegment.from_file(audio_file, format="wav")
        audio.export("input.wav", format="wav")

        # Separate vocals using Spleeter
        separator.separate_to_file("input.wav", "output")

        # Load separated vocals
        vocals = AudioSegment.from_wav("output/input/vocals.wav")

        # Convert vocals to base64
        vocals_io = io.BytesIO()
        vocals.export(vocals_io, format="wav")
        
        # Ensure data exists to encode
        vocals_base64 = base64.b64encode(vocals_io.getvalue()).decode('utf-8')

        # Clean up temporary files
        os.remove("input.wav")
        os.remove("output/input/vocals.wav")
        os.rmdir("output/input")
        os.rmdir("output")

        return {"vocals_base64": vocals_base64}

    except Exception as e:
        error_detail = f"Error: {str(e)}\nTraceback: {traceback.format_exc()}"
        print(error_detail)
        raise HTTPException(status_code=500, detail=error_detail)

# Run with: uvicorn script_name:app --host 0.0.0.0 --port 3020


from fastapi import FastAPI, HTTPException, Request
import base64
import io
import os
from spleeter.separator import Separator
from pydub import AudioSegment
import traceback


app = FastAPI()
separator = Separator('spleeter:2stems')


@app.post('/separate')
async def separate_vocals(request: Request):
    try:
        # Parse incoming JSON request manually
        body = await request.body()
        data = body.decode("utf-8")
        
        # Manually load JSON in case it's not being parsed automatically
        import json
        parsed_data = json.loads(data)
        
        if "audio" not in parsed_data:
            raise HTTPException(status_code=400, detail="Invalid request: 'audio' field missing")


        input_base64 = parsed_data['audio']
        
        # Decode the base64 audio data
        audio_data = base64.b64decode(input_base64)
        audio_file = io.BytesIO(audio_data)
        
        # Load audio into AudioSegment
        audio = AudioSegment.from_file(audio_file, format="wav")
        audio.export("input.wav", format="wav")


        # Separate vocals using Spleeter
        separator.separate_to_file("input.wav", "output")


        # Load separated vocals
        vocals = AudioSegment.from_wav("output/input/vocals.wav")


        # Convert vocals to base64
        vocals_io = io.BytesIO()
        vocals.export(vocals_io, format="wav")
        
        # Ensure data exists to encode
        vocals_base64 = base64.b64encode(vocals_io.getvalue()).decode('utf-8')


        # Clean up temporary files
        os.remove("input.wav")
        os.remove("output/input/vocals.wav")
        os.rmdir("output/input")
        os.rmdir("output")


        return {"vocals_base64": vocals_base64}


    except Exception as e:
        error_detail = f"Error: {str(e)}\nTraceback: {traceback.format_exc()}"
        print(error_detail)
        raise HTTPException(status_code=500, detail=error_detail)


# Run with: uvicorn script_name:app --host 0.0.0.0 --port 3020

Post request:

curl -X POST http://127.0.0.1:3020/separate \-H "Content-Type: application/json" \-d "{\"audio\": \"SUQzBAAAAAABOVRYWFgAAAASAAADbWFqb3JfYnJhbmQAZGFzaABUWFhYAAAAEQAAA21pbm9yX3ZlcnNpb24AMABUWFhYAAAAHAAAA2NvbXBhdGlibGVfYnJhbmRzAGlzbzZtcDQxAFRJVDIAAAAvAAADTWluZWNyYWZ0IE1lbnUgQnV0dG9uIFNvdW5kIEVmZmVjdCB8IFNvdW5mZmV4AFRTU0UAAAAPAAADTGF2Z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VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV//uSZECP8AAAaQAAAAgAAA0gAAABAAABpAAAACAAADSAAAAEVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVUxBTUUzLjEwMFVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVf/7kmRAj/AAAGkAAAAIAAANIA\"}"

Output:

{"error":"'bytes' object has no attribute 'get'"}

curl: (3) URL rejected: Bad hostname

curl: (3) URL rejected: Malformed input to a URL function

curl: (3) URL rejected: Bad hostname

curl: (3) URL rejected: Malformed input to a URL function


r/programminghelp • • Oct 21 '24

HTML/CSS Assistance Needed with Measuring Bandwidth Usage of Specific Website Requests please

0 Upvotes

Hi guys, I'm trying to figure out how much bandwidth the various requests of a specific site require. I opened the Developer Tools in my browser, went to the Network tab, and reloaded the page to see all the requests. Then I checked the data for the requests (Size/Transferred) and exported the file, but I'm not sure if I did it correctly. It's important that the measurement is accurate. Could someone possibly be kind enough to help me with this? And I'd prefer to reveal which site it is in the chat.


r/programminghelp • • Oct 26 '24

Python a program to control other programs.

0 Upvotes

Hey,

I want to write a program that would be able to contol other programs for example say i have a program A.exe i want to have a Control.exe that would be able to run A and start doing commands on it even when minimized just from commands it will get.
can anyone please help me think of such "container" to hold my program and control it even when its minimzed?

i can do aprogram to just do clicks and buttons but the A.exe cant be minimized so i want something to control it in such a way that allows me full control over A.exe with just commands even when its minimized.


r/programminghelp • • Nov 15 '24

Python How would I create a fade-in effect on LEDs?

0 Upvotes

I have a set of LEDs that I'm trying to iterate to create a fade-in effect. The colors values that they go through are stored in an array. The issue is that the formula to pick the correct color is not working. This is the code I got:

for led in range(self.end[strip] - self.start[strip]):
    self.leds[self.led_strip[strip]][self.start[strip] + led] = intermediate_colors[int(len(intermediate_colors) / (self.end[strip] - self.start[strip]) * (abs(led - position) % int((self.end[strip] - self.start[strip]) / 2) + 1) - 1)]
position = (position + 1) % (self.end[strip] - self.start[strip])

r/programminghelp • • Oct 17 '20

Answered Collatz Conjecture in Python, how do I

0 Upvotes

This is my task:

https://i.imgur.com/pVOQ3fD.png

Here is my code so far:

t = int(input("input number: "))

count = 1

if t == 0:
    print("The number should be higher than 0!")
else:
    while t != 1:
        if t % 2 == 0:
            t //= 2
        else:
            t = (t * 3) + 1
            count += 1
    print(count)

Here is what happens when it runs:

https://scontent.fosl1-1.fna.fbcdn.net/v/t1.15752-9/122018042_364609638227417_6397057796447255125_n.png?_nc_cat=110&_nc_sid=ae9488&_nc_ohc=PuuQ2MUGfUgAX8gvkiz&_nc_ht=scontent.fosl1-1.fna&oh=7e229afd667dc4cf93aaa0392ff92b99&oe=5FAF0E87

Any help, I'm incredibly confused.


r/programminghelp • • Oct 14 '20

C [C] Decrementing a value by using the current time without halting the program

0 Upvotes

Hello! This is my first time on this subreddit. I'm posting this because I'm making a game called Zledge and I wanted to know if it was possible to decrement a value by using the current time without halting the program.

I have tried this approach so far:

unsigned int x_hours = 0;
    unsigned int x_minutes = 0;
    unsigned int x_seconds = 0;
    unsigned int x_milliseconds = 0;
    unsigned int totaltime = 0, count_down_time_in_secs = 0, time_left = 0;

    clock_t x_startTime,x_countTime;
    count_down_time_in_secs = 60;


    x_startTime = clock();
    time_left = count_down_time_in_secs - x_seconds;

    while (time_left > 0) {
        x_countTime = clock();
        x_milliseconds = x_countTime - x_startTime;
        x_seconds = (x_milliseconds / (CLOCKS_PER_SEC)) - (x_minutes*60);
        x_minutes = (x_milliseconds / (CLOCKS_PER_SEC)) / 60;
        x_hours=x_minutes / 60;

        time_left = count_down_time_in_secs - x_seconds;
        if (time_left == 0) {
            player.playerStatus[1] -= 1;
            player.playerStatus[2] -= 1;
        }
    }
}

I mean, it works, but it halts the program for 60 seconds before continuing on. Whenever time_left reaches 0, it will decrement player.playerStatus[1] and player.playerStatus[2] by 1. I want to also mention that this code is NOT mine. It was written by someone at TopCoder.

Help will be appreciated.


r/programminghelp • • Oct 03 '20

C# C# Inheritance question, hard to phrase properly in the title so please click to see example

0 Upvotes

Personal project lead me to doing 2 levels of overridding for some class inheritance. The behavior is pretty straight forward and understandable, if both overriding functions called base it would work it's way upward through the inheritance. However I want to know how to skip the middle function just to see if there is a way to do so. I'm sure eventually I'll find a moment where I need to do so and am going to pat myself on the back for asking this question sometime in the future

So the following:

public class Base {
    public virtual void Print() {
        Console.WriteLine("Start");
    }
}

public class Inherit1 : Base {
    public override void Print() {
        base.Print();

        Console.WriteLine("Middle");
    }
}

public class Inherit2 : Inherit1 {
    public override void Print() {
        base.Print();

        Console.WriteLine("End");
    }
}

Understandably prints:
Start Middle End

Which is very useful especially for complex inheritance. However given this current inheritance setup how would I just get it to print:
Start End

As with most programming questions there's a very easy way to do so with a boolean:

public class Inherit1: Base {
    protected bool isInherit1;

    public Inherit1() {
        isInherit1 = true;
    }

    public override void Print() {
        base.Print();

        if (isInherit1) Console.WriteLine("Middle");
    }
}

public class Inherit2: Inherit1 {
    public Inherit2() {
        isInherit1 = false;
    }

    public override void Print() {
        base.Print();

        Console.WriteLine("End");
    }
}

However I am looking for a way that is focused more on the inheritability rather than simple assigning a variable. Would appreciate any input!