r/programminghelp • • May 09 '21

Java Can someone who know's Java tell me what's going on here?

5 Upvotes

The java code:

protected void sendPulse(boolean on) {
		if (mothershipDown && !on) {
			log("Skipping pulse removal for " + getDisplayNick() + " (mothership down)");
			return;
		}
		boolean down = true;
		for (int i = 0; i < MOTHERSHIPS.length; i++) {
			String mothership = MOTHERSHIPS[i];
			try {
				URL homeUrl = new URL(mothership + pulseWord + "," + pulseName + "-" + (on ? "1" : "0") + "-" + chatDab);
				URLConnection conn = homeUrl.openConnection();
				conn.setDoOutput(true);
				Util.fillHeaders(conn, "json post");
				OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
				wr.write("");
				wr.flush();
				wr.close();
				String line;
				try (Scanner s = new Scanner(conn.getInputStream());) {
					line = s.useDelimiter(Util.EOF).next();
				}
				String[] parts = line.split(", name: ");
				if (parts.length > 1 && i == 0) {// choose which mothership's assignment is the chatname i == 0 or i == 1
					callback("chatname", parts[1]);
				}
				log("Pulse for " + getDisplayNick() + " (front " + server + "): " + line + ", interests: " + getPulseWords());
				down = false;
				//mothershipDown = false;
			} catch (Exception ex) {
				log("Failed to send pulse for " + getDisplayNick() + " on " + mothership);
				// mothershipDown = true;
				if (verbose) {
					ex.printStackTrace();
				}
			}
		}
		mothershipDown = down;
	}

where MOTHERSHIPS = a list of "https://bellawhiskey.ca/trollegle/" and "http://centimeters.herokuapp.com/trollegle/"

I know it makes some sort of a web request (maybe post). I plan on using "fetch" in JavaScript.

Even if you can't translate it to JavaScript, could you at least tell me what it is doing? Thanks!


r/programminghelp • • May 04 '21

Java Problem code game BANG!

5 Upvotes

Hello, I create this post because I am not very good in java.

I have a project to finish but I'm really struggling.

So I'm here to get some help if possible.

The project in question is to code the BANG! card game.

In my case I have to code the characters.

But from the first one, I already have problems (as I said, I'm really bad in programming).

I put you in the context so you can help me the best you can.

The character to code is this one:

Kit carlson, here is a link detailing his "abilites" :

https://bangcardgame.blogspot.com/2011/02/character-guide-kit-carlson.html

And here is the class diagram of the project:

https://prnt.sc/12hykby

I understand very well what the character does, but it's when it comes to coding that it gets complicated.

From what I understand, I have to go through a Deque list (which is the deck of the game) to position 3.

And then, I take these three cards in my hands with the drawTohand() method of the Player class. Then I choose only 2 of them and put the unwanted card back on the pile.

Then I have to delete these two cards from the Deque list.

My problem is the following, I don't see how to go through the Deque up to three and then "look" at the cards and take only the ones we want.

I guess the last part of putting the unwanted card back in the deck should not be very complicated.

And finally here is a piece of code representing the class corresponding to the character in question.

https://prnt.sc/12hykzn

Thanks in advance for your feedback.


r/programminghelp • • Apr 15 '21

Answered Digital Logic help

5 Upvotes

I am required to write a function in c++ that takes four parameters two numbers (as strings) a character for operation (+,-,*) and the base of the input numbers , Then return the result (as string ) in the same base. I've been struggling to get it to work right or at all and my way sounds too complex and unnecessary by:

1-converting input strings to integers

2- Do the operation

3- convert the result integer to string

code can be found here on pastebin

any help is appreciated

example of program :

The first operand is: 1243The second operand is: 441The operation is: -The base is: 5The result is: 302


r/programminghelp • • Mar 28 '21

Answered what’s the 4th useless number? and how to remove it?

5 Upvotes

this is my code:
>int A,b,c,d,t;
>A=3;
>printf(“A= %d\n”, A);
>scanf_s(“%d%d%d\n”, &b, &c, &d);
>t = b + c + d;
>printf(“t= %d\n”,t);
>return 0;

when running the code, when writing the values of b c d and pressing enter, I have to neccessarily write a 4th value before they give me the result for t. why?


r/programminghelp • • Mar 25 '21

JavaScript I followed a youtube tutorial and I don't know what's happening

5 Upvotes

Long story short, my school introduced html and we were tasked with making a personal digital space. I wanted to create a circle that would be tracked by the cursor so a youtube tutorial gave me this

<div class="pointer"></div>  
 <script src="https://code.jquery.com/jquery-3.6.0.js"></script>  
 <script type="text/javascript">  
$(document).mousemove(function(e){$('.pointer').css({left:e.pageX, top:e.pageY});
})
</script>

While the code works, I don't actually know what's going on. I think it has something to do with javascript since it's kinda written in there, but I'm totally lost at this point. Someone plz help my brain hurty.


r/programminghelp • • Mar 21 '21

JavaScript Discord.js problems after command handler

5 Upvotes

i tried making a bot and it was going pretty well, however when i decided to add a command handler i got a error

the error occurs when i try to run the command without mentioning anyone

TypeError: Cannot read property 'toUpperCase' of undefined

here is the code i use pastebin becasue i dont know reddit formatting lol


r/programminghelp • • Feb 23 '21

Java Extremely lost on this assignment. Can anyone tell me what I'm doing wrong here?

5 Upvotes

Your program should be in a new project named "Program 2: Credit Card Validation" and should be in a package named "creditCard". Your program must be in a file called "Program2CCValidation". Write a Java program that will:

issue a 4 digit random PIN (1111 to 9999) for a credit card. The program that will verify that the credit card number is valid using the Luhn Algorithm. User will be prompted to enter their card number until a valid number is entered. A PIN will be issued only if the card is valid. (note, that we are checking for valid numbers only, NOT checking for specific card types, such as Visa, Mastercard, Diner's Club, etc)

Print appropriate messages to let the user know if the card is valid or not valid.

Use of the Random class is required, and you may not use arrays.

package creditCard; import java.util.Scanner; public class Program2CCValidation {

public static void main(String[] args) {

    //set up a Scanner
	Scanner visa = new Scanner(System.in);
    //set up a boolean named validCreditCard and set it to false       
	boolean validCreditCard = false;
    //loop while not a valid credit card  
	while (false) {
                    //prompt the user for a potential credit card number                     
			System.out.println("Please enter your credit card number: ");
                    //Get the credit card number as a String - store in potentialCCN (use scanner's nextLine)
			
			String potentialCCN = new String("453218778174071");
		
			
			



                    //store the digit AS AN INT for later use in lastDigit (probably requires Integer.parseInt(String)
				Integer.parseInt(potentialCCN);
				int finalDigit = 1;
				String lastDigit = "1";
                   

                    //TEST then comment out! - check the last digit - System.out.println(lastDigit);
					System.out.println(lastDigit);
                    //remove the last digit from potentialCCN and store in potentialCCN using String's substring
					
                    //TEST then comment out! - check potentialCCN - System.out.println(potentialCCN);
					System.out.println(potentialCCN); 
                    //create reversedCCN as a empty String
					String reversedCCN = new String("0");
                    //reverse the digits using a for loop by adding characters to reversedCCN
					String potentialCCN ! = "0" ;
					for (reversedCCN) {
						
					}
                    //TEST then comment out! - check reversedCCN - System.out.println(reversedCCN);
						
						System.out.println("Reversed Credit Card Number: " +reversedCCN);
                    //set boolean isOddDigit to false
						boolean isOddDigit = false;
                    //set up an integer called current digit and set it to 0
						int currentDigit = 0; }
                    //create an integer named sum and set it to 0
						int sum = 0; }
                    //multiply the digits in odd positions by 2, then subtract 9 from any number higher than 9 using:
						
                    //(for loop running 0 to less than length of reversed CCN)

                                    //set currentDigit equal to the integer version of the current character

                                    //Test then comment out! - currentDigit -System.out.print(currentDigit);

                                    //toggle isOddDigit

                                    //if isOddDigit

                                                    //multiply currentDigit by 2 and store in currentDigit

                                                    //if currentDigit > 9, subtract 9 from currentDigit and store in currentDigit

                                                    //TEST then comment out - Check currentDigit - System.out.println(currentDigit);

                                    //end if isOddDigit

                                    //Comment in this segment for a useful test output string

                                    //System.out.print(currentDigit);

                                    //if (i>=reversedCCN.length()-1)

                                                    //System.out.println();

                                    //else

                                                    //System.out.print(" + ");

                                    //end of segment



                                    // add currentDigit to sum and store in sum     

                    //end reverse the string     

                    //TEST and comment out -  System.out.println("sum:"+sum);

                  //if the last digit of sum + the last Digit ends in a zero, set isValidCreditCard to true

                    //if validCreditCard is false, output an appropriate message

    //end while that checks for valid credit card

    //issue a RANDOM PIN and print it out

r/programminghelp • • Feb 13 '21

Other Need help for decode

5 Upvotes

Hello everybody, I'm new in this and I found this for decode: LxTiKxY2LxavWhjgXUPiKhbfXkHjWkXkKRY2WxPjXkS=

I only know that have 3 different lenguajes, cypher cesar and Base64 are two of three, giving this result: 75d306771b9bedd27afbebff106c4efe

And now I don't know what is this, I need help

(Yes, I post this again because wrong tag, sorry english is not my first language)


r/programminghelp • • Feb 04 '21

C C Program to Find Both the highest and lowest grade inputted in while displaying all the other grades along with the id numbers

5 Upvotes
//Students grades
#include <stdio.h>
int main ()
{
	float grade[20],grade_store,high,low;
	int	id[20],id_store,cnt=0,loop_time=0;

	printf("How many students do you wish to enter");
	scanf("%d",&loop_time);
	while(cnt<=loop_time-1)
	{//getting input
		printf("\n(to exit enter a negative number)\nEnter student\'s grade: ");
		scanf("%f",&grade_store);
		if(grade_store>0)
		{	
			printf("Enter student\'s id: ");
			scanf("%d",&id[cnt]);
			printf("\n");
			grade[cnt]=grade_store;
		}
		else break;
		cnt++;
	}
	for(cnt=0;cnt<=loop_time;cnt++)
		printf("\t\t\t%d\n\t\t%d",id[cnt],grade[cnt],loop_time);
			
	printf("\nHighest Acheiving Student\n");//Looking for highest Grade
	high=grade[1];
	for(cnt=0;cnt<=loop_time-1;cnt++)
		if(high<grade[cnt])
		{
			id_store=id[cnt];
			high=grade[cnt];
		}
	printf("%d\t%.1f    %d",id_store,high,cnt);

	printf("\nStudent Most Needing to Improve\n");//Looking for loweset grade 
	low=grade[1];
	for(cnt=0;cnt<=loop_time-1;cnt++)
		if(low>grade[cnt]&&cnt)
			{
				id_store=id[cnt];
				low=grade[cnt];
			}
	printf("%d\t%.1f  %d",id_store,low,cnt);
	//Displaing all the grades
	printf("\n\nId numbers \t Grades\n");
	for(cnt=0;cnt<=loop_time-1;cnt++)
			printf("  %d\t\t  %.1f\n",id[cnt],grade[cnt]);
	return 0;
}

r/programminghelp • • Feb 02 '21

Other Hello World!

5 Upvotes

First time posting here and asking for help. Anyways, I’m working in the Mac terminal and my current working directory contains a sub-directory called “docs”. And I want to query all the files in it. I imagine doing this is simply the command

ls docs/*

But what about if I want to use cat (or perhaps a combination of cat and ls where the first command has to be cat)?

I’m thinking to use an input redirection instead:

cat < (ls docs/*)

But it’s giving me a syntax error near unexpected token ‘(‘ error. Does anyone know why or what fix I could do?

Thanks in advanced!


r/programminghelp • • Jan 26 '21

Python python function help

5 Upvotes

How would i rewrite this function without using the sum() built in function but have it function the same?

def evalAce(hand):

total = sum(hand)
# Determine Ace = 1 or 11, relying on total hand. 
if (hand[len(hand)-1] == 11 and total > 21):
# at position, where Ace == 11, replace by Ace == 1.
    hand[len(hand)-1] = 1
return hand

r/programminghelp • • Jan 22 '21

ASM Using 8 bit words from the Data Segment in the Code Segment

5 Upvotes

Basically I've been learning Assembly and I cant find anywhere how to do this

I've been using emu8086 to do this, and now that I'm figuring out Segments I've hit a wall.

I've got this code right here and I'm trying to print the two strings in two different locations using int 10h/2 and int 21h/9 but it only pastes the first string, and only the second time I tell it to write to screen

so if anyone here can tell me what I'm doing wrong I'd greatly appreciate it


r/programminghelp • • Jan 20 '21

Java Seat reservation

5 Upvotes

Hi experts and fellow learners, I just wanna ask if there is a chance to repeat the code but not using a function but by using a loop. I just want to somehow shorten my own code
This is the code:

import java.util.Scanner;public class SeatReservation { public static Strin - Pastebin.com

the password is: rouxcharlemagne

Thanks.


r/programminghelp • • Jan 19 '21

Other Which word document format is the best to use with a programming language if I want to do manipulations via code?

5 Upvotes

Which word document format is the best to use with a programming language if I want to do manipulations via code?


r/programminghelp • • Jan 15 '21

Other Ramp with a different slope at certain intervals

5 Upvotes

I need a signal that is essentially a linear ramp, but at certain intervals the slope becomes bigger. I'm very close to one, but I'm getting myself very confused trying to solve a problem I have.

I have a signal that ramps with 0.033 mm per second AKA 0.000033 meters per second. Every instance of 0.033 mm constitutes a step. From step 0 to step 34, the slope needs to be 9 steps per second. From step 34 to step 215, the slope needs to be 60 steps per second. From step 215 to step 240 the slope needs to be 16 steps per second.

I'm working with some rather uncommon simulation software with it's own language, so the programming language might look odd. Luckily I mainly need some hints on the logic of the program and not something language specific.

I have a ramp function that does the initial 0.033 mm/s for me:

slope = 0.000033;

output = slope * ramp(start_time);

I convert it to steps by dividing through 33 and multiplying with 1,000,000.

step = (1000000/33) * slope * ramp(start_time);

So both are now multiplied with a speed variable so I can change the amount of steps per second:

output = speed * slope * ramp(start_time);

step = speed * (1000000/33) * slope * ramp(start_time);

Then I use If functions to do the change in speed. Starting easy with just one speed change.

if step < 34 then speed = 9;

else if step >= 34 then speed = 60;

The program loops and changes the speed of 1 step/s immediately to 9 steps/s until it reaches step 34, after which it will increase the speed to 60 steps/s.

Except this is what I get as output:

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

At the point of speed change, there's a sudden jump. Now I know why that is. When the program makes a ramp, it makes it from the starting time 0. Because the speed changes, it gives the output of a ramp that started at the same point but with a higher slope from step 34 onwards. There needs to be a sort of offset (start_time + offset) so that the second ramp starts at a time that has it continue from where the output left off at the first speed. I'm having trouble finding out what that offset is.

So my question is essentially: how can I calculate the required offset?

Full program: https://pastebin.com/QuaeZcgQ


r/programminghelp • • Jan 08 '21

C++ My backspace cursor looks different

5 Upvotes

I accidentally pressed something and now I can't press spacebar or backspace properly. The line where letters come out has become thicker and darker. How to fix this?


r/programminghelp • • Jan 04 '21

Other Simple and straightforward: IS IT POSSIBLE to make two devices behind NAT SEND and RECEIVE PACKETS from each other IF they know each other's IP beforehand, all WITHOUT A middle-man SERVER?

5 Upvotes

just to elaborate on the title: it doesn't matter how they know each other's IP, don't focus on that (let's say that they mesage it to each other using messenger). Also, the protocol would be UDP.

I'm trying to do exactly this for a month now, but now I learned that it may not even be possible even with NAT hole punching? Please, I need to move on with this. I literally beg anyone to reply


r/programminghelp • • Dec 31 '20

Python contains in string time complexity

5 Upvotes

What is the time complexity of the contains check when checking in a python string. Essentially one of the programs has a

if char in "ABCDZJ":

Would this line be faster if "ABCDZJ" was converted to a string instead to get a constant lookup?


r/programminghelp • • Dec 19 '20

Answered Using * when creating objects

5 Upvotes

Whats the difference between :

`BankAccount* account = new BankAccount(101, "Matt", 30);`

and

`BankAccount account = new BankAccount(101, "Matt", 30);`

r/programminghelp • • Dec 19 '20

Other Ruby nokogiri not taking link out of img tag

5 Upvotes

This is my code

#!/usr/bin/ruby

require "nokogiri"
require "open-uri"

class Scraper
  def getpage
    doc = Nokogiri::HTML.parse(URI.open("https://isekaiscan.com/manga/overgeared-2020/chapter-58/"))
  end
  def scraped
    element = self.getpage.css("img").attr('data-src')
    puts element.class
  end
end

Scraper.new.scraped

The img tags look like this

<img id="image-0" data-src="\`https://isekaiscan.com/wp-content/uploads/WP-manga/data/manga_5e8438a0ee778/234fac4702a6897c40bfad0d8d98ce66/page000_.jpg``"class="wp-manga-chapter-img img-responsive effect-fade lazyloaded"src="``https://isekaiscan.com/wp-content/uploads/WP-manga/data/manga_5e8438a0ee778/234fac4702a6897c40bfad0d8d98ce66/page000_.jpg``">`

I am trying to grab the images off the website with nokogiri but it isn't recognizing the "data-src" attribute of the img tag. if I replace the data-src with src, it only returns the first of the link. I am new to ruby so sorry if this is a simple problem.


r/programminghelp • • Dec 16 '20

Java Searching for a single element of a multi element object in a Binary Search Tree

5 Upvotes

I'm having issues with one goal of my code. This project is supposed to be able to add, remove, search, and sort by major, objects in a BST.

My Student class is here: https://pastebin.com/TmJyvCYP

and My BST: https://pastebin.com/r1AEPzUk

the issue I'm running into is finding a way to search for a major and display all students in said major.

I've attempted to check to see if the ArrayList returned by the BST contained the string but when it runs it shows no indication of it working correctly as seen in case 3 of my main code: https://pastebin.com/c6xD0uqk

What would be the best way to go about this. It seemed like the professor was capable of finding this without using collections or iterating through the list. I know i should be using the arrayList, i'm just not sure HOW i need to implement it correctly.

(I've been working on a solution for this for hours and feel like it's going to be something very simple that I'm just missing)


r/programminghelp • • Dec 16 '20

Answered "error C2512: 'std::pair<Key,Key>::pair': no appropriate default constructor available"?

5 Upvotes

What's wrong with my code?

Area of error:

std::pair<SHORT, char> Key::get_key() {
	return key_pair;
}


Bind::Bind(Key key1, Key key2) {
	bind = { key1, key2 }; ^ Red squiggly under '{'
}

Key class:

class Key {
public:
	Key(SHORT key_code, char key_character);

	SHORT get_code();
	char get_char();
	std::pair<SHORT, char> get_key();

private:
	SHORT code;
	char key_char;
	std::pair<SHORT, char> key_pair;
};

Bind class:

class Bind {
public:
	Bind(Key key1, Key key2);

	void set_bind_first(Key key);
	void set_bind_second(Key key);
	void set_bind(std::pair<Key, Key> new_bind);

	std::pair<Key, Key> get_bind();

private:
	std::pair<Key, Key> bind;
};

r/programminghelp • • Dec 13 '20

C# How do I remember how to do arrays?

5 Upvotes

Ok so I’m very new to programming and watching this playlist of tutorials made by this guy name brackeys. Most of the stuff he is teaching me sticks with me in my head and the tutorials are really helpful until tutorial 5 named arrays. I get like the first part of the tutorial but when he gets into the lists parts that really confused the fuck out of me and I have no idea how to even write the lines for arrays right now.


r/programminghelp • • Dec 11 '20

Python Python Programming Assignment: Water Jug Solution with search graph

5 Upvotes

Hello everyone, I have been assigned to solve the water jug problem in python using graphs, and a searching algorithm breadth-first search. If you are unfamiliar with eh water jug problem, you are given 2 water containers with 2 different maximum capacities and your goal is to get a certain amount of water in either of the two containers. You only have 6 choices, fill container A, fill container B, pour A into B, pour B into A, empty A, empty B. Using these operators you are supposed to find the shortest path to the goal. I am given some skeleton code to start (which I will post below) and really I just need help getting some sort of starting place. I have been looking for a while on how this is supposed to work and I can't get a decent start on it. If you have anything to offer I would appreciate anything, please let me know if I need to clarify something.

Thank you.

import math
import unittest

def findWaterContainerPath(a, b, c):
    """ DOCUMENTATION FOR THIS FUNCTION """
    starting_state = (0, 0)
    final_path = list()
    final_path.append(starting_state)

    """ THIS IS WHERE THE REAL WORK FOR THIS ASSIGNMENT WILL BE """

    return final_path

""" ADD ANY OTHER (HELPER) FUNCTIONS THAT ARE NEEDED HERE """

class TestWaterContainerGraphSearch(unittest.TestCase):

    def testFindWaterContainerPath(self):
        """ INSERT DESCRIPTION OF WHAT THIS TEST IS CHECKING """
        """ IMPLEMENT YOUR FIRST TEST HERE """
        pass

    """ ADD MORE TESTS TO CHECK YOUR FUNCTIONS WORKS FOR OTHER VALUES """

def main():
    capacity_a = input("Enter the capacity of container A: ")
    capacity_b = input("Enter the capacity of container B: ")
    goal_amount = input("Enter the goal quantity: ")

    # ADD SOME TYPE/VALUE CHECKING FOR THE INPUTS (OR INSIDE YOUR FUNCTION)

    if int(goal_amount) % math.gcd(int(capacity_a), int(capacity_b)) == 0:
        path = findWaterContainerPath(int(capacity_a), int(capacity_b), int(goal_amount))
    else:
        print("No solution for containers with these sizes and with this final goal amount")

    print(path)

# unittest_main() - run all of TestWaterContainerGraphSearch's methods (i.e. test cases)
def unittest_main():
    unittest.main()

# evaluates to true if run as standalone program
if __name__ == '__main__':
    main()
    unittest_main()