/r/learnpython

Photograph via snooOG

Subreddit for posting questions and asking for general advice about your python code.


Rules

1: Be polite

2: Posts to this subreddit must be requests for help learning python.

3: Replies on this subreddit must be pertinent to the question OP asked.

4: No replies copy / pasted from ChatGPT or similar.

5: No advertising. No blogs/tutorials/videos/books/recruiting attempts.

This means no posts advertising blogs/videos/tutorials/etc, no recruiting/hiring/seeking others posts. We're here to help, not to be advertised to.

Please, no "hit and run" posts, if you make a post, engage with people that answer you. Please do not delete your post after you get an answer, others might have a similar question or want to continue the conversation.


Learning resources

Wiki and FAQ: /r/learnpython/w/index


Discord

Join the Python Discord chat

/r/learnpython

810,002 Subscribers

3

OOP is really confusing

Mainly because I don't get it's purpose. Functions are just fine.

I assume when I get more advanced, I will understand. According to my understanding, I will attain beginner level as I have finished CS50P and am learning from Python Crash Course.

The CS50P lecture for OOP felt really rushed for a beginner. From where could I study this concept that is detailed enough for me to understand it?

9 Comments
2024/05/12
20:11 UTC

1

Do you know any 1D perlin/simplex noise function modules for python? If not can tell me how they work>

What the title says, preferably it should have a way to change frequencies and amplitudes (for octaves to make fractal noise) and a way to redistribute values to edit the terrain.

If you can't find any perlin/simplex noise any type of noise that can make terrain is fine, as long as it's 1D

0 Comments
2024/05/12
20:03 UTC

2

Tensorflow* TextVectorization vs Tokenizer

def fit_tokenizer(train_sentences, num_words, oov_token):    
    tokenizer = Tokenizer(num_words=num_words, oov_token=oov_token)
    tokenizer.fit_on_texts(train_sentences)
    
    return tokenizer
     

tokenizer = fit_tokenizer(train_sentences, NUM_WORDS, OOV_TOKEN)
word_index = tokenizer.word_index
print(f"Number of words in the vocabulary: {len(word_index)}\n")

Edit: This code runs as expected. The number of words in the word_index != the number of words in the vocabulary. Now, what doesn't make sense to me is how to implement a similar functionality using TextVectorization, as Tokenizer was deprecated in an earlier release. So far, I have:

def fit_text_vectorizer(train_sentences:list, max_tokens):
    vectorizer = layers.TextVectorization(max_tokens=max_tokens, output_mode='int')
    vectorizer.adapt(train_sentences)
    return vectorizer

vectorizer = fit_text_vectorizer(train_sentences, NUM_WORDS)

vocabulary = vectorizer.get_vocabulary()
word_index = {word: index for index, word in enumerate(vocabulary)}

print(f"Number of words in the vocabulary: {len(vocabulary)}\n")   
print(f"Number of words in the word_index: {len(word_index)}")

but the lengths are equal when the word index should be larger

0 Comments
2024/05/12
19:31 UTC

1

where is the indentation

it keeps giving me the unexpected indentation error on audio2 and I fail to see where the indent is

import speech_recognition as sr
import pyttsx3

# Initialize the recognizer
r = sr.Recognizer()

def record_text():
    # loop incase of errors
            while(1):
                try:
                   # use the microphone as source for input.
                   with sr.Microphone() as source2:
                        # Prepare recognizer to recieve input
                        r.adjust_for_ambient_noise(source2, duration=0.2)

                        # listens for the users input
                        audio2 = r.listen(source2)

                        # using google to recognize audio
                        MyText = r.recognize_google(audio2)

                        return MyText

                except sr.RequestError as e:
                    print("could not request results;  {0}".format(e))

                except sr.UnknownValueError:
                    print("unknown error occured")

            return

def output_text(text):
    f = open("output.txt", "a")
    f.write(str(text))
    f.write("\n")
    f.close()

    return

while(1):
    text = record_text
    output_text(text)

    print("Wrote text")


    # loop incase of errors
            while(1):
                try:
                   # use the microphone as source for input.
                   with sr.Microphone() as source2:
                        # Prepare recognizer to recieve input
                       r.adjust_for_ambient_noise(source2, duration=0.2)

                        # listens for the users input
                        audio2 = r.listen(source2)

                        # using google to recognize audio
                        MyText = r.recognize_google(audio2)

                    return MyText

                except sr.RequestError as e:
                    print("could not request results;  {0}".format(e))

                except sr.UnknownValueError:
                    print("unknown error occured")

            return
9 Comments
2024/05/12
18:48 UTC

1

I can't get the interpreter to open after downloading.

I'm a new Python user and just downloaded version 3.12.3 to my desktop (Windows 11 64-bit). I've tried all of the tips and troubleshooting options that Microsoft and Chat GPT have to offer. Every time I open the download, the only options are "modify", "repair", or "uninstall". I've tried repairing and restarting but am never able to open the interpreter so I can continue learning.

Any advice for a beginner who can't even begin?

5 Comments
2024/05/12
18:32 UTC

0

For the needy - Coursera Plus worth $430 at $20 (Limited invites only)

Willing to help anyone who is looking to Upskill or just seeking a better job at this point of time. I will make an invite on your own mail for you to use Coursera Plus worth $430 at just $20. Dm for Proof or questions and this would be for a very limited people only, thanks!

8 Comments
2024/05/12
18:08 UTC

1

Struggling with relative imports. Please help me to confirm that my understanding of "attempted relative import beyond top-level package" error is correct

In my folder named project, this is my directory structure.

.
├── folder_1
│   ├── folder_3
│   │   ├── module_3.py
│   │   └── module_4.py
│   └── module_1.py
├── folder_2
│   └── module_2.py
└── script.py

I am trying to do relative imports inside module_3.py

# module_3.py
print("Code is currently in module_3.py file")
print("\n File name of module_3.py :",__name__)

from . import module_4
from .. import module_1
from ...folder_2 import module_2
  1. When I do python3 -m project.folder_1.folder_3.module_3, it runs successfully.

  2. When I run python3 -m folder_1.folder_3.module_3, I am getting below error:

    Traceback (most recent call last):   File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/runpy.py", line 197, in _run_module_as_main     return _run_code(code, main_globals, None,   File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/runpy.py", line 87, in _run_code     exec(code, run_globals)   File "/Users/admin/Desktop/remote/project/folder_1/folder_3/module_3.py", line 13, in <module>     from ...folder_2 import module_2 ImportError: attempted relative import beyond top-level package

What I know is that relative imports works inside packages only.

QUESTION - Is my understanding correct that giving project in command helps python understand that project is also a package, otherwise it considers only folder_1 a package and cannot findfolder_2 even if it is at same level as folder_1 becauses it does not recognize its parent folder project directory as a package since I am running the command excluding project word from it.

Does that mean it is always better to run the your program at the top most parent folder?

If not so, what is the reason it cannot traverse folder_2 which is a sibling directory at same level as folder_1

1 Comment
2024/05/12
17:56 UTC

1

Course selection

Hello, I have bumped into MIT python course and harvards one, im an absolute beginner, which one should i pick up?

0 Comments
2024/05/12
17:45 UTC

2

Im a bit confused as to how for loops work

So I just started learning Python and the website im on is getting into for loops. So I get the basic for loop like this

name = 'World'
for character in name: print(character)

I get that the loop outputs one letter per line until it finishes the string but what Im having trouble understanding is how ones like this work.

   name = 'World'
line = ''
for char in name:
    line = line + char
    print(line)

I dont understand how that outputs the string like this

W
Wo
Wor
Worl
World

Instead of how it originally did with the first for loop.

W
o
r
l
d
9 Comments
2024/05/12
17:32 UTC

0

Can't clear Angela Yu's python course Lesson 15 Day 4 - Treasure Map even though my output is same as the expected output.

[SOLVED]- Was using the lower case "x" instead of the upper case!!

I am guessing that my code is different than hers so I can't complete. I haven't looked at the solution yet.

I will check her code now but I wanted to know if I missed something or is it just because of the code being different.

My Code:

line1 = ["⬜️","️⬜️","️⬜️"]

line2 = ["⬜️","⬜️","️⬜️"]

line3 = ["⬜️️","⬜️️","⬜️️"]

map = [line1, line2, line3]

print("Hiding your treasure! X marks the spot.")

position = input()

a = position[0]

b = int(position[1]) - 1

if a == "A":

map[b][0] = "x"

elif a == "B":

map[b][1] = "x"

else:

map[b][2] = "x"

print(f"{line1}\n{line2}\n{line3}")

0 Comments
2024/05/12
17:16 UTC

1

Need help with the scapy module

Hello, i have a problem with the scapy module that i cannot send any packets outside of my subnet, if i try to send a packet to a pc in my subnet it works but i try to send a packet to google of to facebook it doesnt work can someone help me here is the code:

from scapy.all import *

req = IP(dst='google.com')

ans = sr1(req)

print(ans.show())

0 Comments
2024/05/12
17:12 UTC

2

How do you arrange your functions?

I've got a bad habit of writing spaghetti and I'm trying to relearn my process into separating out functions and writing proper code. This has led me to wonder... How do you arrange your functions, or is there a "standard" way?

Like if some_function_a() calls some_function_b(), do you put b just below a? Do you move the "secondary" functions to the bottom of the file? Do you alphabetize them, or group them by some other factor? Or do you not even consider where it is in the file?

I've been using comment lines to say things like "These functions are for (whatever task)" and then grouping related functions together.

7 Comments
2024/05/12
17:08 UTC

1

hello, how i can resolve this problem

im using yolo v8 for a game , i need that yolov8 just recgonize persons, no dogs no chairs just persons, this the code

import ultralytics

from ultralytics import YOLO

#Cargar el modelo preentrenado

modelo = YOLO('yolov8n.pt')

#Realizar la detección en una imagen

resultados = modelo.track('persona.jpeg')
if resultados == 0:
  print("Persona detectada") 

else: print("aun no hay nada")
3 Comments
2024/05/12
16:55 UTC

0

Need help please with tic tac toe

So for my final project we have to code tic tac toe. I'm so close but when the game ties with the computer the game doesn't end. Could anyone help, I can send the pictures

7 Comments
2024/05/12
16:41 UTC

4

How do I explain this code?

Hi everyone. I need help with understanding a chunk of code.

Basically I am tasked to create a simple psychological semantic experiment. Participants will be shown target words and are required to select one out of 3 word choices that matches best in different conditions (i.e., meaning (high and low semantic associations), colour, shape, size, texture). This means there are 6 conditions in total. Below is an example of the target-word associations, but under each condition there are 10 trials each.

ConditionTargetChoice1Choice2Choice3CorrectAnswer
highbeehoneypillowscience1
lowgiraffehousesongzoo3
colourfirewoodrosetree2
shapeantsugarflyhole2
sizebookfileboxspear1
texturepenpaperscissorwater2

When presenting the stimuli to participants, I want the order of the condition blocks and trials within the blocks to be randomised. This is my code, which somehow works:

# Get unique conditions from 'Condition' column and randomise
unique_conditions = stimuli['Condition'].unique()
random.shuffle(unique_conditions)

# Randomise the order of condition block
stimuli['Condition'] = pd.Categorical(stimuli['Condition'], categories=unique_conditions, ordered=True)

# Randomize order of trials within each block
blocks = stimuli.groupby('Condition').apply(lambda x: x.sample(frac=1)).reset_index(drop=True)

But for documentation, I'm not sure how to explain why the 'Condition' column has to be converted into categorical to be properly randomised. Is this because within each condition, there is already a fixed internal order (i.e., pre-determined matchings of target words & choice words with correct answers) and specifying ordered = True will preserve this?

Any clarification would be much appreciated. Thank you in advance!

3 Comments
2024/05/12
16:27 UTC

2

Why is it so hard for me to break my code down into functions?

Title. I know what functions are, and what their purposes are. But I cannot seem to wrap my head around on how I could implement it in my script. How to make myself write more functions and de-clutter my code? I feel like my 100 lines of code could be lessen down to 40+ with functions..

16 Comments
2024/05/12
16:26 UTC

5

Pythonic in essence

Hello! What would you call "pythonic in essence" while coding?

4 Comments
2024/05/12
16:03 UTC

0

Reverse a list help

I have an assignment where I must define a function that reverses a list. I cannot use the reverse function, slicing, and it must modify the original list and not create a new one.

Any tips or suggestions to help me out? I’m at a loss on where to start.

7 Comments
2024/05/12
15:37 UTC

2

What is the better way to run functions asynchronously in flask than using Threading module

So, I am basically creating a simple chat system using official WhatsApp Cloud API.

To send reply to a message, I am using send_message function which doesn't run by calling it. I read somewhere that I have to call it asynchronously, so I ran it using Threading module.

I want to know the better way to do this. Is using Threading okay even if the thousands of people using my bot at the same time.

This is my typical code. It works but I need to know the better and efficient way to do this, so I need help from experience Python programmers.

Thanks

from flask import Flask, request, jsonify
import logging
import requests
import threading
phone_id='XXXXXX'
token='XXXXXX'
app = Flask(__name__)
# Configure Flask logging
app.logger.setLevel(logging.DEBUG)  # Set log level to INFO
handler = logging.FileHandler('app.log')  # Log to a file
app.logger.addHandler(handler)
def send_message(phone_id, token, recipient_number, message_body, messaging_product="whatsapp", recipient_type="individual", preview_url=False):
    url = f'https://graph.facebook.com/v19.0/{phone_id}/messages'
    headers = {
        'Content-Type': 'application/json',
        'Authorization': f'Bearer {token}'
    }
    data = {
        "messaging_product": messaging_product,
        "recipient_type": recipient_type,
        "to": recipient_number,
        "type": "text",
        "text": {
            "preview_url": preview_url,
            "body": message_body
        }
    }
    response = requests.post(url, headers=headers, json=data)
    return response.json()
def update_message_status(phone_id, token, message_id, messaging_product="whatsapp", status="read"):
    url = f'https://graph.facebook.com/v19.0/{phone_id}/messages'
    headers = {
        'Authorization': f'Bearer {token}',
        'Content-Type': 'application/json'
    }
    data = {
        "messaging_product": messaging_product,
        "status": status,
        "message_id": message_id
    }
    response = requests.post(url, headers=headers, json=data)
    return response.json()
u/app.route('/webhook', methods=['GET', 'POST'])
def verify_webhook():
    if request.method == 'POST':
        try:
            if request.json["entry"][0]["changes"][0]["value"]["messages"][0]["type"] == "text":
                thr = threading.Thread(target=update_message_status, args=[phone_id, token, request.json["entry"][0]["changes"][0]["value"]["messages"][0]["id"]])
                thr.start()
                thr = threading.Thread(target=send_message, args=[phone_id, token, request.json["entry"][0]["changes"][0]["value"]["messages"][0]["from"], "Hey thanks for reaching out"])
                thr.start()
                return "OK", 200
            else:
                pass    
        except KeyError:
            pass        
    else:
        return "HELLO GET"
    return "OK", 200    
u/app.before_request
def log_request_info():
    app.logger.debug('Body: %s', request.get_data())
if __name__ == '__main__':
    app.run(debug=True, port=8000)
1 Comment
2024/05/12
15:22 UTC

1

What is the better way to run functions asynchronously in flask than using Threading module

So, I am basically creating a simple chat system using official WhatsApp Cloud API.

To send reply to a message, I am using send_message function which doesn't run by calling it. I read somewhere that I have to call it asynchronously, so I ran it using Threading module.

I want to know the better way to do this. Is using Threading okay even if the thousands of people using my bot at the same time.

This is my typical code. It works but I need to know the better and efficient way to do this, so I need help from experience Python programmers.

Thanks

from flask import Flask, request, jsonify
import logging
import requests
import threading
phone_id='XXXXXX'
token='XXXXXX'
app = Flask(__name__)
# Configure Flask logging
app.logger.setLevel(logging.DEBUG)  # Set log level to INFO
handler = logging.FileHandler('app.log')  # Log to a file
app.logger.addHandler(handler)
def send_message(phone_id, token, recipient_number, message_body, messaging_product="whatsapp", recipient_type="individual", preview_url=False):
    url = f'https://graph.facebook.com/v19.0/{phone_id}/messages'
    headers = {
        'Content-Type': 'application/json',
        'Authorization': f'Bearer {token}'
    }
    data = {
        "messaging_product": messaging_product,
        "recipient_type": recipient_type,
        "to": recipient_number,
        "type": "text",
        "text": {
            "preview_url": preview_url,
            "body": message_body
        }
    }
    response = requests.post(url, headers=headers, json=data)
    return response.json()
def update_message_status(phone_id, token, message_id, messaging_product="whatsapp", status="read"):
    url = f'https://graph.facebook.com/v19.0/{phone_id}/messages'
    headers = {
        'Authorization': f'Bearer {token}',
        'Content-Type': 'application/json'
    }
    data = {
        "messaging_product": messaging_product,
        "status": status,
        "message_id": message_id
    }
    response = requests.post(url, headers=headers, json=data)
    return response.json()
u/app.route('/webhook', methods=['GET', 'POST'])
def verify_webhook():
    if request.method == 'POST':
        try:
            if request.json["entry"][0]["changes"][0]["value"]["messages"][0]["type"] == "text":
                thr = threading.Thread(target=update_message_status, args=[phone_id, token, request.json["entry"][0]["changes"][0]["value"]["messages"][0]["id"]])
                thr.start()
                thr = threading.Thread(target=send_message, args=[phone_id, token, request.json["entry"][0]["changes"][0]["value"]["messages"][0]["from"], "Hey thanks for reaching out"])
                thr.start()
                return "OK", 200
            else:
                pass    
        except KeyError:
            pass        
    else:
        return "HELLO GET"
    return "OK", 200    
u/app.before_request
def log_request_info():
    app.logger.debug('Body: %s', request.get_data())
if __name__ == '__main__':
    app.run(debug=True, port=8000)
0 Comments
2024/05/12
15:22 UTC

3

I want to build my programming logic systematically. Where do I begin?

By systematically, I don't want to dive into ocean of problems which aren't sorted in increasing order of difficulty. I want a structured, systematic and sorted way to learn programming logic, problem solving. I welcome any exercises types. I am at advanced beginner phase.

I welcome any thing.

Books, courses, projects to do (structured it should be), exercises etc.

2 Comments
2024/05/12
14:46 UTC

1

AWS s3 bucket presigned url download error - SSL: UNEXPECTED_EOF_WHILE_READING

Hey,

I am having occasional errors while trying to download image uploaded to my s3 bucket. The error happens on ~ 10k out of 100k requests. I am sending images between api and gpu worker through s3 bucket using presigned urls.

Errors I am getting:

ssl.SSLEOFError: [SSL: UNEXPECTED_EOF_WHILE_READING] EOF occurred in violation of protocol (_ssl.c:1007)" DDuring handling of the above exception, another exception occurred: urllib3.exceptions.MaxRetryError: HTTPSConnectionPool(host='bucketname.s3-accelerate.amazonaws.com', port=443): Max retries exceeded with url: /my_path/8fa39771.png?AWSAccessKeyId=AWSAccessKeyId&Signature=Signature&Expires=1715552122 (Caused by SSLError(SSLEOFError(8, '[SSL: UNEXPECTED_EOF_WHILE_READING] EOF occurred in violation of protocol (_ssl.c:1007)')))

This is how I upload the images:

boto_client.put_object(
    Bucket=bucket,
    Key=key,
    Body=BytesIO().getvalue(),
    ContentType=f"image/png",
)

This is how I generate presigned urls:

 boto_client.generate_presigned_url(
    "get_object",
    Params={
        "Bucket": bucket,
        "Key": key,
    },
    ExpiresIn=36000,  # 10 hours
)

This is how I download image using presigned url:

response = requests.get(fileUrl)
image = Image.open(BytesIO(response.content))

All above seems to be pretty straightforward. And the errors are not happening very often. That's why I am having really hard times figuring out the potential reasons of those failures

Hey,

I am having occasional errors while trying to download image uploaded to my s3 bucket. The error happens on ~ 10k out of 100k requests. I am sending images between api and gpu worker through s3 bucket using presigned urls.

Errors I am getting:

ssl.SSLEOFError: [SSL: UNEXPECTED_EOF_WHILE_READING] EOF occurred in violation of protocol (_ssl.c:1007)" DDuring handling of the above exception, another exception occurred: urllib3.exceptions.MaxRetryError: HTTPSConnectionPool(host='bucketname.s3-accelerate.amazonaws.com', port=443): Max retries exceeded with url: /my_path/8fa39771.png?AWSAccessKeyId=AWSAccessKeyId&Signature=Signature&Expires=1715552122 (Caused by SSLError(SSLEOFError(8, '[SSL: UNEXPECTED_EOF_WHILE_READING] EOF occurred in violation of protocol (_ssl.c:1007)')))

This is how I upload the images:

boto_client.put_object(
    Bucket=bucket,
    Key=key,
    Body=BytesIO().getvalue(),
    ContentType=f"image/png",
)

This is how I generate presigned urls:

 boto_client.generate_presigned_url(
    "get_object",
    Params={
        "Bucket": bucket,
        "Key": key,
    },
    ExpiresIn=36000,  # 10 hours
)

This is how I download image using presigned url:

response = requests.get(fileUrl)
image = Image.open(BytesIO(response.content))

All above seems to be pretty straightforward. And the errors are not happening very often. That's why I am having really hard times figuring out the potential reasons of those failures

0 Comments
2024/05/12
14:38 UTC

0

I spent many months learning python after work and got good in the basics like decorators, object oriented programming etc. But, it has been two years and I'm barely using it, instead I use postgresql much more which I gave much less time to learn.

I work in middle management and I've a lot of data to work on Edited: sorry, written in a hurry. Just wanted to share my situation as I want to use it more but use cases for middle management guys in individual capacity is limited

7 Comments
2024/05/12
14:34 UTC

3

(Pyside6 / Python) Making a program to catalog stuff, need some direction

So im trying to make a program that catalogs my shaders. (shader name and an image of it, and when i click the name it opens the file)

I have managed to do this by hard coding it and having the gui to navigate.

im curious to know how does one maybe have a button that gives the user the ability to add in new items in instead of going into the code manually adding it in. Appreciate some direction how this is done.

1 Comment
2024/05/12
13:41 UTC

1

Indentation on Mac

After switching from JavaScript on Windows to Python programming on Mac, I'm a bit confused about the indentation in Python. As I understand, it's very important for the code to work correctly. But on Mac, there is no delete button, and for me, it's a bit difficult and unusual to make correct indentation using only backspace or fn+backspace. How do you solve this issue?

13 Comments
2024/05/12
13:04 UTC

3

Exe files created with pyinstaller take long time to boot

I noticed that after packaging my python project into one .exe it takes too long to starts however it was much faster when I was running as .py files l, any idea why ?

8 Comments
2024/05/12
12:41 UTC

3

Extracting hashtags from trending TikTok videos

Hey folks, I am trying to extract hashtags and possibly other metadata from trending videos on TikTok. Does anyone have experience with this and can provide some documentation or anything?

Greatly appreciate your help :)

0 Comments
2024/05/12
12:34 UTC

1

Xmpp chat client help !!

Hi guys ! i'am trying to make a simple xmpp chat client in pure python without using existed xmpp libraries ! it seems it connects to the server but the stanza status doesnt work and my account looks offline also sending messages doesnt work too. plz need help this is the code :

you can use this testing accounts :

gojo123@xmpp.is ....password : test123456789

gojo456@xmpp.is ....password : test123456789

import socket
import ssl
import base64
import hashlib
import os

def base64_encode(data):
    if isinstance(data, str):
        data = data.encode()
    return base64.b64encode(data).decode()

def create_nonce():
    return base64_encode(os.urandom(16))

def create_client_first_message(username, nonce):
    return "n={},r={}".format(username, nonce)

def create_client_final_message(nonce, salted_password):
    return "c=biws,r={},p={}".format(nonce, base64_encode(salted_password))

def create_scram_message(username, password, nonce):
    client_first_message = create_client_first_message(username, nonce)
    salted_password = hashlib.pbkdf2_hmac('sha1', password.encode(), base64.b64decode(nonce.encode()), 4096)
    client_final_message = create_client_final_message(nonce, salted_password)
    return client_first_message, client_final_message

def send_message(sock, message):
    sock.sendall(message.encode())

def receive_response(sock):
    return sock.recv(4096).decode()

def xmpp_client():
    server = "xmpp.is"
    port = 5223

    context = ssl.create_default_context()

    with socket.create_connection((server, port)) as sock:
        with context.wrap_socket(sock, server_hostname=server) as secure_sock:
            print("Connected to server securely.")

            response = receive_response(secure_sock)
            print("Initial response:", response)

            nonce = create_nonce()
            username = "gojo123@xmpp.is"
            password = "test123456789"
            client_first_message, client_final_message = create_scram_message(username, password, nonce)

            print("Authenticating with server...")
            send_message(secure_sock, '<auth xmlns="urn:ietf:params:xml:ns:xmpp-sasl" mechanism="SCRAM-SHA-1">{}</auth>'.format(base64_encode(client_first_message)))
            send_message(secure_sock, '<response xmlns="urn:ietf:params:xml:ns:xmpp-sasl">{}</response>'.format(base64_encode(client_final_message)))

            print("Setting presence to 'online'...")
            presence_xml = '<presence><show>chat</show><status>Online</status></presence>'
            send_message(secure_sock, presence_xml)

            print("Sending message to 'gojo456@xmpp.is'...")
            message_xml = '<message to="gojo456@xmpp.is" type="chat"><body>Hi there!</body></message>'
            send_message(secure_sock, message_xml)

            print("Waiting for server responses...")
            while True:
                response = receive_response(secure_sock)
                print("Received data:", response)

if __name__ == "__main__":
    xmpp_client()
                                                                                
0 Comments
2024/05/12
11:49 UTC

0

Is this normal python, or is this an unusual solution? (Working w/ chatgpt)

I'm working on learning the data visualization library Manim, and I'm asking chatgpt to walk me through a solution that I thought I'd use object oriented programming for (I'm familiar but not solid with it, and I want to take this opportunity as the first of many instances to strengthen my understanding).

I want to create multiple bargraphs, and those are created using the BarChart class in Manim. ChatGPT said that there two solutions; the only one I could think of was one where I inherited properties from the BarChart class and instantiate a subsclass (GPT's words, those may be wrong). I couldn't think of an alternative, and asked what the alternative solution was that it thought of.

It suggested that I use a 'configuration dictionary.' It gave me this code:

from manim import *

class MultipleBarCharts(Scene):
    def construct(self):
        common_config = {
            'y_range': [0, 1000, 50],
            'y_length': 6,
            'x_length': 10,
            'x_axis_config': {'font_size': 24}
        }

        # Data for charts
        data_values1 = [200, 450, 800, 600]
        data_values2 = [150, 400, 650, 550]

        # Create charts
        chart1 = BarChart(values=data_values1, **common_config)
        chart1.to_edge(LEFT)

        chart2 = BarChart(values=data_values2, **common_config)
        chart2.next_to(chart1, RIGHT, buff=1)

        # Add charts to the scene
        self.add(chart1, chart2)from manim import *

I'm learning python, but it sort of strikes me as unusual. I get the feeling that this is something used to configure a project, as opposed to using this sort of paradigm in business logic.

I don't remember where I heard or read of this idea recently, that the use of AI for coding would lead to 'unusual', or 'unique' (I'm forgetting the precise word that was used) solutions. I'm wondering if this is one of these instances, or if it's normal python?

To end, I'm not asking ChatGPT to give me code to just copy and paste somewhere, in fact I'm explicitly asking it not to do that, and to help walk me through the process of coming to a solution. I even looked up 'configuration dictionary' to try and see if it's a thing. But yeah, I'm curious to know what more experienced python programmers think.

5 Comments
2024/05/12
10:37 UTC

3

The Pawns dont Move properly

The pawns just act weird. Sometimes they disappear, change colour or not even move. Any help would be appreaciated

This is the code

import customtkinter as ctk

ctk.set_appearance_mode("Dark")        
ctk.set_default_color_theme("blue")    

class App(ctk.CTk):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.count = 0
        self.title("PyChess")    
        self.geometry("400x530")    

        pieces = [
            "♜", "♞", "♝", "♚", "♛", "♝", "♞", "♜",
            "♟", "♟", "♟", "♟", "♟", "♟", "♟", "♟",
            " ", " ", " ", " ", " ", " ", " ", " ",
            " ", " ", " ", " ", " ", " ", " ", " ",
            " ", " ", " ", " ", " ", " ", " ", " ",
            " ", " ", " ", " ", " ", " ", " ", " ",
            "♙", "♙", "♙", "♙", "♙", "♙", "♙", "♙",
            "♖", "♘", "♗", "♔", "♕", "♗", "♘", "♖"
        ]
        movement_tally={}        
        self.buttons={}
        self.frame=ctk.CTkFrame(self)
        self.frame.pack()
        self.title_label = ctk.CTkLabel(self.frame, text="PyChess", font=("Arial",80))
        self.title_label.grid(row=0, columnspan=8, pady=20)
        button_width = 50
        button_height = 50
        self.selection_counter = 0
        self.selected_pawn = None

        for i in range(8):
            for j in range(8):
                button_name = f"{chr(ord('a') + i)}{1 + j}"
                if i>3:
                    tc="#000000"
                else:
                    tc="#FFFFFF"

                if (i+j)%2==0:
                    colour='#ebca7c'
                else:
                    colour='#654321'
                button = ctk.CTkButton(self.frame, text=pieces[i*8+j], font=  ("Arial",30), bg_color=colour, text_color=tc, fg_color='transparent', width=button_width, height=button_height, border_width=1)
                button.grid(row=i+1, column=j, padx=0, pady=0)
                button.bind("<Button-1>", self.create_button_click_handler(button_name))
                self.buttons[button_name]=[button, pieces[i*8+j],tc]
      
    def create_button_click_handler(self, button_name):
        def on_button_click(event):
            if self.selection_counter == 0:
                self.selected_pawn = button_name
                self.selection_counter = 1
            elif self.selection_counter == 1:
                self.move_pawn(button_name)
                self.selection_counter = 0
    
        return on_button_click
            
    def move_pawn(self, end_position):
        start_button = self.buttons[self.selected_pawn][0]
        end_button = self.buttons[end_position][0]
        start_text = self.buttons[self.selected_pawn][1]
        start_text_color = self.buttons[self.selected_pawn][2]
        end_text = self.buttons[end_position][1]
        end_text_color = self.buttons[end_position][2]

        start_button.configure(text=" ")
        start_button.configure(text_color=end_text_color)

        end_button.configure(text=start_text)
        end_button.configure(text_color=start_text_color)
        

if __name__ == "__main__":
    app = App()
    app.mainloop()



5 Comments
2024/05/12
10:25 UTC

Back To Top