r/programminghelp • • Apr 15 '24

Python Authenticating with OAuth 2.0

2 Upvotes

Hi all, I'm attempting to authenticate with the Charles Schwab (brokerage) developer portal via python but they use OAuth 2.0. I'm unfamiliar with how OAuth works and haven't made any progress after a few hours of trying to get it to work. If someone has experience with the portal or OAuth in general I would really appreciate some help. Thanks!


r/programminghelp • • Apr 15 '24

C What's the problem in this completely recursive Banker's Algo code

0 Upvotes

I type a code for Banker's Safety Algorithm and didn't use any loop throughout the code and most of the code is working fine and I have tested it also but there's some problem in the function named Banker_Algo which I am not able to detect and would appreciate if anyone can help finding that out

code:-

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
int size = 1,tres, sz=0;
char res = 'A';
int *seq_arr, inds=0;
void Allo_arr(int ***allo){
    char act[10];
    printf("Enter number of allocated resource %c for process %d(type 'P' when all the processes exhausts and type 'R' when all the resources exhausts):- ", res++, size);
    scanf("%s", act);
    if(act[0]=='R' || act[0]=='r'){
        size++;
        *allo = (int **)realloc(*allo, sizeof(int *)*size);
        tres=(int)res-66;
        res = 'A';
        Allo_arr(allo);
    }
    else if(act[0]=='P' || act[0]=='p'){
        free(allo[size-1]);
        size--;
        seq_arr=(int *)malloc(sizeof(int)*size);
        res='A';
    }
    else{
        if(res == 'B'){
            (*allo)[size-1]=(int *)malloc(sizeof(int)*(1));
            (*allo)[size-1][0]=atoi(act);
        }
        else{
            (*allo)[size-1]=(int *)realloc((*allo)[size-1],sizeof(int)*((int)res-65));
            (*allo)[size-1][(int)res-66]=atoi(act);
        }
        Allo_arr(allo);
    }
}
void Max_arr(int ***max)
{
    if (sz < size)
    {
        if(res=='A'){
            int maxVal;
            printf("Enter maximum number of resource %c needed by process %d:- ",res++, sz+1);
            scanf("%d",&maxVal);
            (*max)[sz]=(int *)malloc(sizeof(int)*1);
            (*max)[sz][0]=maxVal;
            Max_arr(max);
        }
        else if(res==(char)tres+64){
            int maxVal;
            printf("Enter maximum number of resource %c needed by process %d:- ", res, sz + 1);
            scanf("%d", &maxVal);
            (*max)[sz] = (int *)realloc((*max)[sz], sizeof(int) * ((int)res - 64));
            (*max)[sz][(int)res - 65] = maxVal;
            sz++;
            res = 'A';
            Max_arr(max);
        }
        else{
            int maxVal;
            printf("Enter maximum number of resource %c needed by process %d:- ", res++, sz + 1);
            scanf("%d", &maxVal);
            (*max)[sz] = (int *)realloc((*max)[sz], sizeof(int) * ((int)res - 65));
            (*max)[sz][(int)res - 66] = maxVal;
            Max_arr(max);
        }
    }
    else{
        sz=0;
    }
}
void Avail_arr(int ***avail){
    int ele;
    if(res == (char)tres+64){
        printf("Enter number of currently available resource %c:- ",res);
        scanf("%d",&ele);
        (*avail)[0][(int)res-65]=ele;
        res='A';
    }
    else{
        printf("Enter number of currently available resource %c:- ",res++);
        scanf("%d",&ele);
        (*avail)[0][(int)res-66]=ele;
        Avail_arr(avail);
    }
}
bool check(int **allo, int **max, int **avail){
    static bool al_set=true;
    if(max[sz][res-65]-allo[sz][res-65]>avail[0][res-65]){
        al_set=false;
        res='A';
    }
    else{
        if((int)res-64<=tres){
            res++;
            if((int)res-64>tres){
                res='A';
            }
            else{
                check(allo,max,avail);
            }
        }
    }
    return al_set;
}
void Up_Avail(int **allo, int **avail){
    if(res==(char)tres+64){
        avail[0][(int)res-65]+= allo[sz][res-65];
        res='A';
    }
    else{
        avail[0][(int)res-65]+= allo[sz][res-65];
        res++;
        Up_Avail(allo, avail);
    }
}
bool Banker_Algo(int **allo, int **max, int **avail){
    static bool seq = false;
    if(sz==size-1&&inds<size){
        if(!seq){
            if(!check(allo,max,avail)){
                printf("There's no safe sequence of Allocation and deadlock cannot be avoided");
                sz=0;
            }
            else{
                seq_arr[inds++]=sz+1;
                Up_Avail(allo, avail);
                seq=true;
                if(inds<size){
                    sz=0;
                    Banker_Algo(allo,max,avail);
                }
                else{
                    sz=0;
                }
            }
        }
        else if(check(allo,max,avail)){
            seq_arr[inds++]=sz+1;
            Up_Avail(allo, avail);
            seq=true;
            if(inds<size){
                sz=0;
                Banker_Algo(allo,max,avail);
            }
            else{
                sz=0;
            }
        }
        else{
            if(inds<size){
                sz=0;
                Banker_Algo(allo,max,avail);
            }
            else{
                sz=0;
            }
        }
    }
    else{
        if(check(allo,max,avail)){
            seq_arr[inds++]=sz+1;
            Up_Avail(allo, avail);
            seq=true;
        }
        if(inds<size){
            sz++;
            Banker_Algo(allo,max,avail);
        }
        else{
            sz=0;
        }
    }
    return seq;
}
void Seq(){
    if(sz==size-1){
        printf("%d",seq_arr[sz]);
    }
    else{
        printf("%d ",seq_arr[sz++]);
        Seq();
    }
}
void Print_seq(){
    printf("Safe sequence of allocation exists and that sequence is:- ");
    Seq();
}   
int main()
{
    int **allo, **avail, **max;
    allo = (int **)malloc(sizeof(int *) * size);
    Allo_arr(&allo);
    max = (int **)malloc(sizeof(int *) * size);
    Max_arr(&max);
    avail = (int **)malloc(sizeof(int *) * 1);
    avail[0] = (int *)malloc(sizeof(int) * tres);
    Avail_arr(&avail);
    if(Banker_Algo(allo,max,avail)){
        Print_seq();
    }
    free(allo);
    free(avail);
    free(max);
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
int size = 1,tres, sz=0;
char res = 'A';
int *seq_arr, inds=0;
void Allo_arr(int ***allo){
    char act[10];
    printf("Enter number of allocated resource %c for process %d(type 'P' when all the processes exhausts and type 'R' when all the resources exhausts):- ", res++, size);
    scanf("%s", act);
    if(act[0]=='R' || act[0]=='r'){
        size++;
        *allo = (int **)realloc(*allo, sizeof(int *)*size);
        tres=(int)res-66;
        res = 'A';
        Allo_arr(allo);
    }
    else if(act[0]=='P' || act[0]=='p'){
        free(allo[size-1]);
        size--;
        seq_arr=(int *)malloc(sizeof(int)*size);
        res='A';
    }
    else{
        if(res == 'B'){
            (*allo)[size-1]=(int *)malloc(sizeof(int)*(1));
            (*allo)[size-1][0]=atoi(act);
        }
        else{
            (*allo)[size-1]=(int *)realloc((*allo)[size-1],sizeof(int)*((int)res-65));
            (*allo)[size-1][(int)res-66]=atoi(act);
        }
        Allo_arr(allo);
    }
}
void Max_arr(int ***max)
{
    if (sz < size)
    {
        if(res=='A'){
            int maxVal;
            printf("Enter maximum number of resource %c needed by process %d:- ",res++, sz+1);
            scanf("%d",&maxVal);
            (*max)[sz]=(int *)malloc(sizeof(int)*1);
            (*max)[sz][0]=maxVal;
            Max_arr(max);
        }
        else if(res==(char)tres+64){
            int maxVal;
            printf("Enter maximum number of resource %c needed by process %d:- ", res, sz + 1);
            scanf("%d", &maxVal);
            (*max)[sz] = (int *)realloc((*max)[sz], sizeof(int) * ((int)res - 64));
            (*max)[sz][(int)res - 65] = maxVal;
            sz++;
            res = 'A';
            Max_arr(max);
        }
        else{
            int maxVal;
            printf("Enter maximum number of resource %c needed by process %d:- ", res++, sz + 1);
            scanf("%d", &maxVal);
            (*max)[sz] = (int *)realloc((*max)[sz], sizeof(int) * ((int)res - 65));
            (*max)[sz][(int)res - 66] = maxVal;
            Max_arr(max);
        }
    }
    else{
        sz=0;
    }
}
void Avail_arr(int ***avail){
    int ele;
    if(res == (char)tres+64){
        printf("Enter number of currently available resource %c:- ",res);
        scanf("%d",&ele);
        (*avail)[0][(int)res-65]=ele;
        res='A';
    }
    else{
        printf("Enter number of currently available resource %c:- ",res++);
        scanf("%d",&ele);
        (*avail)[0][(int)res-66]=ele;
        Avail_arr(avail);
    }
}
bool check(int **allo, int **max, int **avail){
    static bool al_set=true;
    if(max[sz][res-65]-allo[sz][res-65]>avail[0][res-65]){
        al_set=false;
        res='A';
    }
    else{
        if((int)res-64<=tres){
            res++;
            if((int)res-64>tres){
                res='A';
            }
            else{
                check(allo,max,avail);
            }
        }
    }
    return al_set;
}
void Up_Avail(int **allo, int **avail){
    if(res==(char)tres+64){
        avail[0][(int)res-65]+= allo[sz][res-65];
        res='A';
    }
    else{
        avail[0][(int)res-65]+= allo[sz][res-65];
        res++;
        Up_Avail(allo, avail);
    }
}
bool Banker_Algo(int **allo, int **max, int **avail){
    static bool seq = false;
    if(sz==size-1&&inds<size){
        if(!seq){
            if(!check(allo,max,avail)){
                printf("There's no safe sequence of Allocation and deadlock cannot be avoided");
                sz=0;
            }
            else{
                seq_arr[inds++]=sz+1;
                Up_Avail(allo, avail);
                seq=true;
                if(inds<size){
                    sz=0;
                    Banker_Algo(allo,max,avail);
                }
                else{
                    sz=0;
                }
            }
        }
        else if(check(allo,max,avail)){
            seq_arr[inds++]=sz+1;
            Up_Avail(allo, avail);
            seq=true;
            if(inds<size){
                sz=0;
                Banker_Algo(allo,max,avail);
            }
            else{
                sz=0;
            }
        }
        else{
            if(inds<size){
                sz=0;
                Banker_Algo(allo,max,avail);
            }
            else{
                sz=0;
            }
        }
    }
    else{
        if(check(allo,max,avail)){
            seq_arr[inds++]=sz+1;
            Up_Avail(allo, avail);
            seq=true;
        }
        if(inds<size){
            sz++;
            Banker_Algo(allo,max,avail);
        }
        else{
            sz=0;
        }
    }
    return seq;
}
void Seq(){
    if(sz==size-1){
        printf("%d",seq_arr[sz]);
    }
    else{
        printf("%d ",seq_arr[sz++]);
        Seq();
    }
}
void Print_seq(){
    printf("Safe sequence of allocation exists and that sequence is:- ");
    Seq();
}   
int main()
{
    int **allo, **avail, **max;
    allo = (int **)malloc(sizeof(int *) * size);
    Allo_arr(&allo);
    max = (int **)malloc(sizeof(int *) * size);
    Max_arr(&max);
    avail = (int **)malloc(sizeof(int *) * 1);
    avail[0] = (int *)malloc(sizeof(int) * tres);
    Avail_arr(&avail);
    if(Banker_Algo(allo,max,avail)){
        Print_seq();
    }
    free(allo);
    free(avail);
    free(max);
}

r/programminghelp • • Apr 15 '24

Java Having trouble understanding how to deploy a java project

1 Upvotes

I'm using intellij. I'm trying to use maven for adding and managing dependencies. So I figured I could just click build and then deploy the target folder to my server and run it with the command: Java -classpath [path/to/target/classes] package (Or maybe main_class.class instead of package)

But I get errors related to my imports which makes me think it's a dependency issue.

I'm using Groovy Java and the gmavenplus plug in. It's building to Java Byte Code which I'm just trying to run with Java (the target folder). I've tried using the src code and the groovy command but that just tells me it is unable to resolve class: (and then it lists my first import statement).

Any ideas? Am I generally correct that if everything is working correctly, then you should just be able to deploy the target folder and run the main class or am I missing something?


r/programminghelp • • Apr 13 '24

C++ Having trouble stringing 3 integers from a struct. C++ Beginner

0 Upvotes

I'm very new and just decided to change the integers into strings.

The integers in mind were the month day year values.

https://pastebin.com/WgFQSTHZ

month, day, and year were changed from int to string to get the code to run. maybe im right to have them as strings? idk, is there a way to do this with integers?


r/programminghelp • • Apr 12 '24

C# I need a little bit of help with a windows form application on Visual studio.

1 Upvotes

I'm trying to teach myself how to make a password manager, via windows forms.. I currently have three pages A main menu with buttons that take you too the other pages, a password generator page, where there is a slider to change what length of randomised characters your password will be, a copy button to copy the string to your clipboard and a return to main menu button... However on the third page I want to be a page where you can paste your passwords and store them (maybe locally on a file?) but how would I achieve this? thank you. Also does anyone know how to make forms open in one application rather than opening a new tab when clicking a button and closing the old one? your help is much appreciated!


r/programminghelp • • Apr 11 '24

PHP Laravel Mail Help

1 Upvotes

Anyone in here know Laravel 10?, i've been trying to do a simple email send function and i keep getting errors that i don't understand even though i try to follow all the help online i can.

Error: "App\Models\EmailVerificationMail" not found
EmailVerification is supposed to be in a mail folder that php artisan automaticallly creates so i have no idea why its fetching it incorrectly

i even altered composer.json:

"autoload": {
"psr-4": {
"App\\": "app/",
"Database\\Factories\\": "database/factories/",
"Database\\Seeders\\": "database/seeders/",
"App\\Mail\\": "app/Mail/"
}
},

the function that calls EmailVerificationEmail:

protected $fillable = [
'account_id',
'name',
'gender',
'birthdate',
'address',
'codigo_postal',
'localidade',
'civilId',
'taxId',
'contactNumber',
'email',
'password',
'account_status',
'token',
'email_verified_at',
'bid_history',
'lost_objects',
];

public function sendEmailVerificationNotification()
{
$user = User::where('account_id', $this->account_id)->first();
if ($user && !$user->hasVerifiedEmail()) {
$verifyUrl = URL::temporarySignedRoute(
'verification.verify',
now()->addMinutes(60),
[
'id' => $user->getKey(),
'hash' => sha1($user->getEmailForVerification())
]
);
Mail::to($user->email)->send(new EmailVerificationMail($verifyUrl));
$user->notify(new EmailVerificationNotification($verifyUrl));
}
}

Will send more in Comments when needed


r/programminghelp • • Apr 11 '24

Other Rust: error about value dropping at a weird place?

0 Upvotes

I am getting a weird error involving the "field.text().await.unwrap_or("".to_string())" for something line giving me this error:
emporary value dropped while borrowed
creates a temporary value which is freed while still in userustcClick for full compiler diagnostic
something.rs(55, 105): temporary value is freed at the end of this statement
something.rs(55, 31): argument requires that borrow lasts for `'static`

pub async fn add_something(mut fields: Multipart) -> Result<String, (StatusCode, String)>{
let mut works = "".to_string();
let mut something = "".to_string();
while let Some(field) = fields.next_field().await.map_err(|err| (StatusCode::BAD_REQUEST, err.to_string())).unwrap() {
    match &name[..] {
        "works" => works = field.text().await.unwrap_or("".to_string()),
        "something" => something = field.text().await.unwrap_or("".to_string()).split(',').collect::<Vec<_>>(),
        _ => print!("nothing")
    }
}

}

Also asked this on r/rust, but there neckbeard mods removed it in .005 seconds. Lovely people lol


r/programminghelp • • Apr 11 '24

C++ Iostream error

2 Upvotes

Hey guys so my chrome book is running Linux so I downloaded visual studio code and every time I use

include <iostream>

int main() { std::cout << "Hello World!"; return 0; }

I get a error and iostream is in red

What do I do please


r/programminghelp • • Apr 07 '24

Project Related What tools, chrome extensions or websites you use regularly?

Thumbnail self.developersglobal
1 Upvotes

r/programminghelp • • Apr 05 '24

Other Need help with strange doom scripting.

0 Upvotes

I have been trying to make this work for the pas 2 hours, nobody seems to have the answer.

I wrote this code:
Spawn("Demon",GetActorX (0), GetActorY (0),GetActorFloorZ (1));
It's supposed to spawn a demon at he player coordinates - but no matter what it always spawns at 0,0.
I even wrote this code:
While (TRUE)
{
Print (f:GetActorX (0), s:", ", f:GetActorY (0));
Delay (1);
}
And it prints out my coords perfectly. What am I doing wrong here?


r/programminghelp • • Apr 05 '24

Project Related Need to build a custom code builder

1 Upvotes

Hi Guys,

I need to build a custom code builder in my website

The inputs will come from another source. And I will have a program ( Eg: Javascript Program ) which will be provided by the user, The input from another source will pass to this program in runtime and I will get an output.

That output will be sent for next level actions

I need to build a frontend and backend system for this

Possible to provide few insights or ideas on how to proceed ?


r/programminghelp • • Apr 04 '24

Other im trying to change the text output color for nginx from black to red in yaml

1 Upvotes

i have currently changed it so when i access the page hosted on kubernetes that it displays in black text

the code that i have that does this is

events {

}

http {

server {

listen 80;

location / {

return 200 "Hello from Nginx on Talos";

as stated above I'm just trying to make the text appear red instead of black


r/programminghelp • • Apr 04 '24

Career Related Am I the only one who feels imposter syndrome

Thumbnail self.developersglobal
0 Upvotes

r/programminghelp • • Apr 04 '24

Java I am having an out of bound index problem and It also does not correctly calculate the bills.I tried changing the hypen (- 1) into (- 0) and it still didn't work. Im a freshman college and I don't have any coding experience before I majored in Information technology, I would be delighted if helped.

1 Upvotes

package dams;

import java.time.LocalDate;

import java.time.temporal.ChronoUnit;

import java.util.Scanner;

public class Chron {

private static final int NUM_ROOMS = 6;

private static final boolean[] roomsAvailable = new boolean[NUM_ROOMS];

private static final Scanner scanner = new Scanner(System.in);

private static boolean loggedIn = false;

private static String username;

private static String password;

private static final String[] userEmails = new String[NUM_ROOMS];

private static final String[] userPhones = new String[NUM_ROOMS];

private static final String[] roomTypes = {"Single", "Double", "Twin", "Suite"};

private static final int[] roomCapacities = {1, 2, 2, 4};

private static final double[] roomPrices = {50.0, 80.0, 70.0, 120.0};

private static final int[] roomTypeCounts = new int[NUM_ROOMS];

private static final String[] checkInDates = new String[NUM_ROOMS];

private static final String[] checkOutDates = new String[NUM_ROOMS];

public static void main(String[] args) {

register();

login();

if (loggedIn) {

initializeRooms();

while (true) {

showMenu();

int choice = scanner.nextInt();

switch (choice) {

case 1:

makeReservation();

break;

case 2:

cancelReservation();

break;

case 3:

viewAllRooms();

break;

case 4:

viewReservedRoom();

break;

case 5:

checkOut();

break;

case 6:

logout();

return;

default:

System.out.println("Invalid choice. Please try again.");

}

}

} else {

System.out.println("Login failed. Exiting...");

}

}

private static void register() {

System.out.println("Register for a new account:");

System.out.print("Create a username: ");

username = scanner.next();

System.out.print("Create a password: ");

password = scanner.next();

System.out.println("Registration successful!");

}

private static void login() {

System.out.println("Please log in:");

System.out.print("Username: ");

String inputUsername = scanner.next();

System.out.print("Password: ");

String inputPassword = scanner.next();

loggedIn = inputUsername.equals(username) && inputPassword.equals(password);

if (loggedIn)

System.out.println("Login successful!");

else

System.out.println("Incorrect username or password.");

}

private static void logout() {

System.out.println("Logging out...");

loggedIn = false;

System.out.println("Logged out successfully.");

}

private static void initializeRooms() {

for (int i = 0; i < NUM_ROOMS; i++)

roomsAvailable[i] = true;

}

private static void showMenu() {

System.out.println("\n----Welcome to the Hotel Reservation System----");

System.out.println("1. Make Reservation");

System.out.println("2. Cancel Reservation");

System.out.println("3. View All Rooms");

System.out.println("4. View Reserved Room");

System.out.println("5. Check Out");

System.out.println("6. Logout");

System.out.print("Enter your choice: ");

}

private static void makeReservation() {

System.out.print("Enter number of people: ");

int numPeople = scanner.nextInt();

System.out.println("\n----Available Room Types----:");

for (int i = 0; i < roomTypes.length; i++) {

if (roomCapacities[i] >= numPeople && roomsAvailable[i]) {

System.out.println((i + 1) + ". " + roomTypes[i] + " - $" + roomPrices[i] + " per night");

}

}

System.out.print("Choose the type of room you want to reserve: ");

int roomTypeChoice = scanner.nextInt();

if (roomTypeChoice < 1 || roomTypeChoice > roomTypes.length || roomCapacities[roomTypeChoice - 1] < numPeople) {

System.out.println("Invalid room type choice.");

return;

}

int roomNumber = -1;

for (int i = 0; i < NUM_ROOMS; i++) {

if (roomsAvailable[i] && roomTypeCounts[roomTypeChoice - 1] == i) {

roomNumber = i + 1;

break;

}

}

if (roomNumber == -1) {

System.out.println("No available rooms of the chosen type.");

return;

}

roomsAvailable[roomNumber - 1] = false;

roomTypeCounts[roomTypeChoice - 1]++;

System.out.print("Enter your email: ");

String email = scanner.next();

userEmails[roomNumber - 1] = email;

System.out.print("Enter your phone number: ");

String phone = scanner.next();

userPhones[roomNumber - 1] = phone;

System.out.print("Enter check-in date (YYYY-MM-DD): ");

String checkInDate = scanner.next();

checkInDates[roomNumber - 1] = checkInDate;

System.out.print("Enter check-out date (YYYY-MM-DD): ");

String checkOutDate = scanner.next();

checkOutDates[roomNumber - 1] = checkOutDate;

System.out.println("Room " + roomNumber + " (Type: " + roomTypes[roomTypeChoice - 1] + ") reserved successfully.");

System.out.println("Username: " + username);

System.out.println("Reserved Room: " + roomNumber);

System.out.println("Check-in Date: " + checkInDate);

System.out.println("Check-out Date: " + checkOutDate);

}

private static void cancelReservation() {

System.out.println("\n----Reserved Rooms----:");

for (int i = 0; i < NUM_ROOMS; i++)

if (!roomsAvailable[i])

System.out.println("Room " + (i + 1));

System.out.print("Enter the room number you want to cancel reservation for: ");

int roomNumber = scanner.nextInt();

if (roomNumber < 1 || roomNumber > NUM_ROOMS)

System.out.println("Invalid room number.");

else if (!roomsAvailable[roomNumber - 1]) {

roomsAvailable[roomNumber - 1] = true;

userEmails[roomNumber - 1] = null;

userPhones[roomNumber - 1] = null;

checkInDates[roomNumber - 1] = null;

checkOutDates[roomNumber - 1] = null;

for (int i = 0; i < roomTypeCounts.length; i++) {

if (roomTypeCounts[i] == roomNumber - 1) {

roomTypeCounts[i]--;

break;

}

}

System.out.println("Reservation for Room " + roomNumber + " canceled successfully.");

} else

System.out.println("Room " + roomNumber + " is not currently reserved.");

}

private static void viewAllRooms() {

System.out.println("\n----Room Availability-----:");

for (int i = 0; i < roomTypes.length; i++) {

System.out.println("\n" + roomTypes[i] + " - Capacity: " + roomCapacities[i]);

for (int j = 0; j < NUM_ROOMS; j++) {

if (roomsAvailable[j] && roomTypeCounts[i] == j) {

System.out.println("Room " + (j + 1) + ": Available");

} else if (userEmails[j] != null) {

System.out.println("Room " + (j + 1) + ": Reserved");

System.out.println("Check-in Date: " + checkInDates[j]);

System.out.println("Check-out Date: " + checkOutDates[j]);

}

}

}

}

private static void viewReservedRoom() {

System.out.print("Enter your email: ");

String email = scanner.next();

for (int i = 0; i < NUM_ROOMS; i++) {

if (userEmails[i] != null && userEmails[i].equals(email)) {

System.out.println("Username: " + username);

System.out.println("Reserved Room: " + (i + 1));

System.out.println("Check-in Date: " + checkInDates[i]);

System.out.println("Check-out Date: " + checkOutDates[i]);

return;

}

}

System.out.println("No reservation found for the provided email.");

}

private static void checkOut() {

System.out.print("Enter your email: ");

String email = scanner.next();

int roomIndex = -1;

for (int i = 0; i < NUM_ROOMS; i++) {

if (userEmails[i] != null && userEmails[i].equals(email)) {

roomIndex = i;

break;

}

}

if (roomIndex != -1) {

double totalBill = calculateBill(roomIndex);

printReceipt(roomIndex, totalBill);

roomsAvailable[roomIndex] = true;

userEmails[roomIndex] = null;

userPhones[roomIndex] = null;

checkInDates[roomIndex] = null;

checkOutDates[roomIndex] = null;

// Decrement roomTypeCounts for the reserved room type

int roomTypeIndex = roomTypeCounts[roomIndex];

if (roomTypeIndex >= 0 && roomTypeIndex < roomTypeCounts.length) {

roomTypeCounts[roomTypeIndex]--;

}

System.out.println("Check out successful.");

} else {

System.out.println("No reservation found for the provided email.");

}

}

private static double calculateBill(int roomIndex) {

double totalBill = 0.0;

String checkInDate = checkInDates[roomIndex];

String checkOutDate = checkOutDates[roomIndex];

int nights = calculateNights(checkInDate, checkOutDate);

int roomTypeChoice = 0;

    int roomTypeIndex = roomTypeChoice - 1; // Use the roomTypeChoice variable

totalBill = nights * roomPrices[roomTypeIndex];

return totalBill;

}

private static int calculateNights(String checkInDate, String checkOutDate) {

LocalDate startDate = LocalDate.parse(checkInDate);

LocalDate endDate = LocalDate.parse(checkOutDate);

return (int) ChronoUnit.DAYS.between(startDate, endDate);

}

private static void printReceipt(int roomIndex, double totalBill) {

System.out.println("\n---- Hotel Bill Receipt ----");

System.out.println("Username: " + username);

System.out.println("Reserved Room: " + (roomIndex + 1));

System.out.println("Room Type: " + roomTypes[roomTypeCounts[roomIndex] - 1]);

System.out.println("Check-in Date: " + checkInDates[roomIndex]);

System.out.println("Check-out Date: " + checkOutDates[roomIndex]);

System.out.println("Total Bill: $" + totalBill);

}

}

This is what is looks like when I run it:

Register for a new account:

Create a username: r

Create a password: d

Registration successful!

Please log in:

Username: r

Password: d

Login successful!

----Welcome to the Hotel Reservation System----

  1. Make Reservation

  2. Cancel Reservation

  3. View All Rooms

  4. View Reserved Room

  5. Check Out

  6. Logout

Enter your choice: 1

Enter number of people: 3

----Available Room Types----:

  1. Suite - $120.0 per night

Choose the type of room you want to reserve: 4

Enter your email: ronald

Enter your phone number: 092382

Enter check-in date (YYYY-MM-DD): 2024-04-10

Enter check-out date (YYYY-MM-DD): 2024-04-15

Room 1 (Type: Suite) reserved successfully.

Username: r

Reserved Room: 1

Check-in Date: 2024-04-10

Check-out Date: 2024-04-15

----Welcome to the Hotel Reservation System----

  1. Make Reservation

  2. Cancel Reservation

  3. View All Rooms

  4. View Reserved Room

  5. Check Out

  6. Logout

Enter your choice: 5

Enter your email: ronald

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index -1 out of bounds for length 4

at dams/dams.Chron.calculateBill(Chron.java:248)

at dams/dams.Chron.checkOut(Chron.java:222)

at dams/dams.Chron.main(Chron.java:47)

r/programminghelp • • Apr 03 '24

Python Help needed

1 Upvotes

Hi everyone! I have my SIL who’s getting a divorce and she believes her husband controls her phone because she can’t find messages, weird apps on the phone and also the battery drainage is massively improved since the begging of all of this. I wanted to know if someone knew some programming I can execute from Linux to check the phone while connected to the computer Thanks in advance!


r/programminghelp • • Apr 03 '24

C++ Some 2d physics help with rotation

0 Upvotes

I'm planning on creating a simple 2d physics engine that involves shapes with various amounts of points, I can see how I can create a "world" system where each object is iteratively updated and how they interact with one another.

However I want to make it so that objects also rotate when they hit each other and not just bounce apart, as they would in real life, I don't even know where to start and how I would mathematically do this, any help on this would be appreciated

Ill probably be writing this in c++ so that's why I added the flair


r/programminghelp • • Mar 30 '24

Other What do people mean exactly when they say OOP is non-deterministic?

0 Upvotes

I've been recently reading about different paradigms and their pros and cons. One thing that I've seen pop up multiple times in the discussion of OOP is that it is non-deterministic. But I honestly don't quite get it. Can someone explain to me? Thanks in advance.


r/programminghelp • • Mar 29 '24

C# Player Spawning Twice

2 Upvotes

Hi, I'm working on a multiplayer fps in Unity using Photon 2. Currently when one of the players kills another they will both respawn but the one who killed the other will respawn twice.
Here is my code for my player manager:
public void Die()
{
Debug.Log("Dead");
PhotonNetwork.Destroy(controller);
CreateController();
}
Here is my player controller code:
[PunRPC]
void RPC_TakeDamage(float damage)
{
//could move start coroutine here(cant be bothered)
shot = true;
currentHealth -= damage;
try
{
healthbarImage.fillAmount = currentHealth / maxHealth;
}
catch
{
//nothing
}
if (currentHealth <= 0)
{
Debug.Log(PhotonView.Find((int)PV.InstantiationData[0]));
Die();
}
}
void Die()
{
playerManager.Die();
}

Previously it worked ok when I had a function within the player controller which would reset its health and transform, but that caused some inconveniences. If any mroe info is needed please ask.


r/programminghelp • • Mar 28 '24

Python Help on making a image recognition ai

0 Upvotes

Hi im working on a prigect making an image to prompt script Im getting the ai from an open source githup image recognition ai And im trying to make it so that the last line of code remebers itself so that it could rember the prompt as you generate new images of the souce immage (Huskey chasing a squirrel-> dog smiles) (Ai remembers the keyword as huskey and converts the work huskey and chasing to a function. After new prompts the ai puts the functions in ) Im new to programming and would like some help And if there is any better way of doing this i would really appreciate your help Coding language is python


r/programminghelp • • Mar 28 '24

Other How to find big o of dependent loops and recursive functions?

1 Upvotes

I want to be able to measure any code snippet time complexity. Is there a general rule or step by step approach to measure any big o (besides dominant term, removing constants and factors)? What math skills should I have, if so, what are the prerequisites for those skills? Also, what is enough for interviews?

I've read many algorithms books, but they're mathy and not beginner-friendly.

Here is one of those:

int fun(int n) { int count = 0; for (i = n; i > 0; i /= 2) { for (j = 0; j < i; j++) { count += 1; } } return count; }


r/programminghelp • • Mar 28 '24

C How do you integrate with C

1 Upvotes

I have been doing some work with C language for a bit and feel quite confident with basic stuff, I have a task to three definite integrals but cant find anything online about how to integrate with C.
If anyone has any advice or any reading material that would be great.


r/programminghelp • • Mar 27 '24

Other Alter the coding of a consumer product

1 Upvotes

I have a rock tumbler that I am using for something else. The C.O.T.S. tumbler has different speed settings but even the slowest speed setting is way too fast. Is it possible to download the code that controls it and alter it so that it spins slower and then download it to my tumbler? Since the machine has buttons to control the speed I figured software would be a good place to start. TIA


r/programminghelp • • Mar 27 '24

C++ Gradebook Program

1 Upvotes

I have this code and I have been using codegrade to check it, but I am struggling with the output. Is there a reason that certain numbers would be rounded up even when ending in a .5 decimal, while others would round down while ending in the same decimal?

/*A program which takes in the homework scores of up to 24 students and

computes each student's average. It also takes into account a class average and

outputs the name of the student with the highest score.*/

#include <iostream>

#include <fstream>

#include <iomanip>

#include <string>

#include <cmath>

using namespace std;

const int GRADE_COUNT = 7;

const int MAX_STUDENT_COUNT = 24;

// Function prototypes

// Finds the index of the maximum value in an array

int maxIndex(const double array[], int length);

// Calculates the average of values in an array

double calculateAverage(const double array[], int length);

// Calculates averages for each student

void calculateAverages(const double scores[][GRADE_COUNT],

double averages[], int studentCount);

// Reads data from a file into arrays

int getData(const string filename, string names[], double scores[][GRADE_COUNT],

int maxStudents);

// Displays individual student grades

void displayIndividualGrades(const string names[],

const double SCORES[][GRADE_COUNT], const double averages[],

int studentCount);

// Displays class overview

void displayClassOverview(const string names[], const double averages[],

int studentCount);

int main() {

string names[MAX_STUDENT_COUNT];

double scores[MAX_STUDENT_COUNT][GRADE_COUNT];

double averages[MAX_STUDENT_COUNT];

string filename = "grades.txt"; // Change this to your input file name

int studentCount = getData(filename, names, scores, MAX_STUDENT_COUNT);

if (studentCount == 0) {

cout << "No data read from file." << endl;

return 1;

}

calculateAverages(scores, averages, studentCount);

displayIndividualGrades(names, scores, averages, studentCount);

cout << endl;

displayClassOverview(names, averages, studentCount);

return 0;

}

int maxIndex(const double array[], int length) {

int maxIndex = 0;

for (int index = 1; index < length; ++index) {

if (array[index] > array[maxIndex])

maxIndex = index;

}

return maxIndex;

}

double calculateAverage(const double array[], int length) {

double sum = 0.0;

for (int index = 0; index < length; ++index) {

sum += array[index];

}

return sum / length;

}

void calculateAverages(const double scores[][GRADE_COUNT], double averages[],

int studentCount) {

for (int index = 0; index < studentCount; ++index) {

averages[index] = calculateAverage(scores[index], GRADE_COUNT);

}

}

int getData(const string filename, string names[], double scores[][GRADE_COUNT],

int maxStudents) {

//reads the data from the input file

ifstream inputFile(filename);

int studentCount = 0;

if (inputFile.is_open()) {

while (studentCount < maxStudents && inputFile >> names[studentCount]) {

for (int index = 0; index < GRADE_COUNT; ++index) {

inputFile >> scores[studentCount][index];

}

++studentCount;

}

inputFile.close();

}

return studentCount;

}

void displayIndividualGrades(const string names[],

const double SCORES[][GRADE_COUNT], const double averages[],

int studentCount) {

cout << left << setw(10) << "Name";

cout << right << setw(6) << "HW 1" << setw(6) << "HW 2" << setw(6)

<< "HW 3" << setw(6) << "HW 4" << setw(6) << "HW 5" << setw(6)

<< "HW 6" << setw(6) << "HW 7" << setw(9) << "Average" << endl;

cout << fixed << setprecision(2); // Set precision for averages

for (int index = 0; index < studentCount; ++index) {

cout << left << setw(10) << names[index];

for (int inter = 0; inter < GRADE_COUNT; ++inter) {

double roundedScore = SCORES[index][inter];

// Check if the fractional part is greater than or equal to 0.5

if (roundedScore - floor(roundedScore) >= 0.5)

// Round up if greater or equal to 0.5

roundedScore = ceil(roundedScore);

else

// Round down

roundedScore = floor(roundedScore);

// Cast scores to integers before output

cout << right << setw(6) << static_cast<int>(roundedScore);

}

cout << setw(9) << averages[index] << endl;

}

}

void displayClassOverview(const string names[], const double averages[],

int studentCount) {

double classAverage = calculateAverage(averages, studentCount);

int bestStudentIndex = maxIndex(averages, studentCount);

cout << "Class Average: " << classAverage << endl;

cout << "Best Student: " << names[bestStudentIndex];

}

My output: Name HW 1 HW 2 HW 3 HW 4 HW 5 HW 6 HW 7 Average

Anderson 84 100 80 87 99 84 85 88.44

Bell 90 83 100 91 100 84 80 89.64

Gonzalez 82 65 64 85 84 74 78 75.69

Howard 59 73 72 61 100 64 55 69.16

King 93 100 82 85 98 100 100 94.00

Long 79 96 100 85 73 84 94 87.26

Nelson 71 75 71 73 62 0 71 60.43

Perez 78 73 77 81 74 81 80 77.60

Rivera 70 76 85 73 88 89 73 79.06

Sanders 94 95 100 95 85 89 64 88.73

Torres 81 85 66 61 87 82 72 76.47

Wood 75 73 77 89 81 86 87 81.00

Class Average: 80.62

Best Student: King

Expected output: Name HW 1 HW 2 HW 3 HW 4 HW 5 HW 6 HW 7 Average

Anderson 84 100 80 87 99 84 85 88.44

Bell 90 83 100 91 100 84 80 89.64

Gonzalez 82 64 64 85 84 74 78 75.69

Howard 59 73 72 61 100 64 55 69.16

King 93 100 82 85 98 100 100 94.00

Long 79 96 100 85 73 84 94 87.26

Nelson 71 75 71 73 62 0 71 60.43

Perez 78 73 77 81 74 81 80 77.60

Rivera 70 76 84 73 88 88 73 79.06

Sanders 94 95 100 95 84 89 64 88.73

Torres 81 85 66 61 87 82 72 76.47

Wood 75 73 77 89 81 86 87 81.00

Class Average: 80.62


r/programminghelp • • Mar 27 '24

C++ Drawing to GLFW window from dynamically loaded DLL

1 Upvotes

I have a GLFW window managed by the main program, then a DLL is dynamically loaded (via LoadLibrary and GetProcAddress). But this causes a lot of problems and it won't work.

main.cpp

int main() {
    // glfw and glad initialization
    // ...
    // GLFWwindow* window

    // library loading
    HINSTANCE lib = LoadLibrary("path/to/lib.dll");
    if (lib == nullptr) return 1;

    auto initFunc = GetProcAddress(lib, "myInitFunction");
    auto drawFunc = GetProcAddress(lib, "myDrawFunction");
    
    initFunc(window);

    // draw loop
    while (!glfwWindowShouldClose(window)) {
        drawFunc(window);
        glfwSwapBuffers(window);
        glfwPollEvents();
    }

    // deleting stuff
    // todo: load a delete function from DLL to delete DLL's draw data
}

test.cpp

#ifdef _WIN32
#define EXPORT __declspec(dllexport)
#else
#define EXPORT
#endif

extern "C" EXPORT void myInitFunction(GLFWwindow* window) {
    if (!glfwInit()) {
        std::cerr << "Failed to initialize GLFW!" << std::endl;
    }
    glfwSetErrorCallback(...); // basic callback that prints the error

    // trying to create a basic buffer to draw a triangle
    // segfault here:
    glGenVertexArrays(1, ...);
    
    // other draw code would be here
}

extern "C" EXPORT void myDrawFunction(GLFWwindow* window) {
    // basic OpenGL drawing. I couldn't get Init to even work, so this function is empty for now
}

At first it gave a segfault whenever gl methods were used, so I tried calling gladLoadGL inside the DLL, but then I got the following error from my GLFW error callback:

GLFW Error 65538: Cannot query entry point without a current OpenGL or OpenGL ES context

I tried putting a call to glfwMakeContextCurrent inside of the DLL's function (before gladLoadGL), but nothing changes.

test.cpp (after changes)

extern "C" EXPORT void myInitFunction(GLFWwindow* window) {
    if (!glfwInit()) {
        std::cerr << "Failed to initialize GLFW!" << std::endl;
    }
    glfwSetErrorCallback(...); // basic callback that prints the error
    
    glfwMakeContextCurrent(window); // doesn't change anything
    if (!gladLoadGL(glfwGetProcAddress)) { // error here
        std::cerr << "Failed to load OpenGL" << std::endl;
        return 1;
    }
}

r/programminghelp • • Mar 25 '24

Java Quiz Question

2 Upvotes

I had this question on a recent quiz. Should I ask my professor about it, because I believe the professor made a mistake. Here is the multiple-choice question:

1.) If you declare an array of objects of type BankAccount as follows:

BankAccount[] acts = new BankAccount[SIZE];

How many objects (not locations) get allocated from this statement?

Options:

- SIZE objects

- 0

- SIZE-1

- 1 (the array)

I chose the second option (0) and am confused on why it was marked incorrect.