r/AskPython

307 archived posts · Nov 2013 – Aug 2024

Random post

u/stvaccount•

I have the following code, identical in Julia and R:

λ = rand(Gamma(dn, 1 / bn)) # Julia
σ² = rand(InverseGamma(cn, Cn)) # Julia

lambda <- rgamma(1, shape = dn, rate = bn) # R
sigma2 <- 1 / rgamma(1, shape = cn, rate = Cn) # R

How do I translate those two lines to Python?

31

u/lolinux•

Hello,

I would like to learn how to automate logins to various systems. For example, I would like to scrape my Deco S4 device for various information.

However, while there are a lot of code examples online, I admit I personally do not understand most of them. Are there guides on the internet that also explain the WHY and not only the HOW in various scenarios? (For example, the Deco S4 login page is all JavaScript)

Thank you

30

u/Ninjafox1224•

I've created a code where it will list my txt files and then i can select one and it will open a new window and it'll let me edit the files. i have

os.chdir(r'C:\Users\...')
my_files = glob.glob('*.txt')
root = tk.Tk()
yvar = 0
root.geometry("240x200")
for note in my_files:
    btn = tk.Button(root, text=note[:-4], anchor=tk.W, command=lambda: editselectnote(note))
    btn.place(x=0, y=yvar, relwidth=1)
    yvar += 26

so it grabs each file name and makes a button out of it. The function of the button is:

def editselectnote(note):
    opennote = open(note)
    starttext = opennote.read()
    editor = tk.Tk()
    editor.geometry('500x2
32

Hello everyone,

I am learning about decorators in Python but not understanding the below code.

​

def make_pretty(func):
    def inner():
        print("I got decorated")     # This one doesn't seem to get called T_T
        func()
    return inner


def ordinary():
    print("I am ordinary")

make_pretty(ordinary())
# Output: I am ordinary

My understanding was the output should be below instead because the order of the call is make_pretty() -> inner() -> ordinary():

I got decorated
I am ordinary

​

Any advice or explanation would be great.

23

Im using the rules of counter point.

import music21

​

# Input: 8-beat melody in a standard music notation format

melody = music21.converter.parse('melody.xml')

​

# Key analysis: Determine the key of the melody

key = melody.analyze('key')

​

# Bass line generation: Generate a contrapuntal bass line

bass_line = music21.stream.Part()

​

# Define the first note of the bass line as the tonic of the key

bass_note = music21.note.Note()

bass_note.pitch = key.tonic

bass_line.append(bass_note)

​

# Generate the remaining notes of the bass line by following the guidelines above

for i in range(1, 8):

prev_note = bass_lin

20

u/the_boiiss•

I'm trying to communicate between two apps, both of which have python embeddings. The solutions I've found are mostly related to the multiprocessing module where the processes are started and easily accessed from the parent process. In this case though these are two completely separate applications, and so far I haven't been able to get anything to work.

My current solution is just having app 1 write a tmp file to disk and then reading it in app 2. It works but I was curious if there's a cleaner solution out there I'm missing. Thanks!

20

u/ilsapo•

Hi, we learend then when we do slicing, its actually create a "new" list in the memory, and dosent change the original, so why does this work?

L=[1,2,3,4,5]
L[3:]=[5,6]

now when we check the value of L

[1, 2, 3, 5, 6]

so why did the original list changed?
if I check the memory ID of L[3:] and L its a diffrenet one

24

u/badg35•

I am working with an API that returns data in pages, as an array of dictionaries:

def get_drivers():

    query = {}
    
    hasNextPage = True # ensure process once
    while hasNextPage == True:

        qs = urllib.parse.urlencode(query)
        url = f"https://api.samsara.com/fleet/drivers?{qs}" if query else f"https://api.samsara.com/fleet/drivers"

        response = requests.get(url, timeout=self.timeout, headers=self.headers)

        # {
        #     "data": [
        #         {},
        #         {}
        #     ],
        #     "pagination": {
        #         "endCursor": "558e5038-ad3c-47b8-a11e-f
21

Hello everyone,

Can anyone help me with this code?

It is supposed to congratulate your birthday by the age you enter holding in mind the suffix of the numbers. For example: 1st, 2nd, 3rd, 25th, 32nd birthday.

When I enter the number 32, it doesn't display the correct suffix.

Does anybody know why?

Does anybody know a better way to make this.

Your critics, explanations, point are very welcome.

This is the code:

​

age = float(input('What is your age? '))
print(type(age))
if age == float(age) or int(age):
    if len(age) == 0:
        print('Please enter a something (a number)')
    elif len(age) == 1:
        if age == 1:
            print(f'
22

u/coconut_maan•

given a package structure

|-python3.8
    |- dist-packages
        |-Module_1
            |- script_1
            |- __init__.py
            |- __main__.py
        |- other_stuff

what is the difference between:

  • python -m Module_1.script_1.py --arg1 val1
  • and
  • python ./python3.8/dist-packages/Module_1/script_1.py --arg1 val1

because I am working in the wbia code base from github and its very different.

Thanks !!!

20

u/walksonair•

I'd like to make sure I'm writing the best code possible so requesting feedback on the following and asking whether anyway to cast the function argument as a string always? (EDIT - refactored slightly)

def mask_account(account_info):
    account_info = str(account_info)
    acclength = len(account_info)
    if acclength > 4:
        masklength = acclength - 4
    else:
        masklength = acclength - 2
    
    return 'X' * masklength + account_info[masklength:]
21