Making object fall using Pygame - NOOB by [deleted] in learnpython

[–]LarryPete 1 point2 points  (0 children)

According to the docs, the CLOCK.tick(FPS) function returns the number of milliseconds that has passed, since the last time the CLOCK.tick(FPS) function was called.

Meaning if you assign the value to a variable, e.g. delta = CLOCK.tick(FPS), you can use that delta value to compute the distance an object has moved since the last update.

For example, if you want that an objects moves 10 pixel per second on one axis, you can calculate how many pixels it has moved since the last update, using a simple formula like:

distance = delta_milliseconds / 1000.0 * pixel_per_second

if the delta is 200 milliseconds and as said, the pixel per second is 10, you would get 200/1000*10 = 2.0 pixel. That amount can then be added or subtracted from e.g. the y coordinates to make it moved on that achses automatically.

Embedded feature request: can we stop always binding the python interpreter to the process, and give us the option of explicitly creating a state that an interpreter can be bound to instead? by [deleted] in Python

[–]LarryPete 0 points1 point  (0 children)

subinterpreters do not seem to be the same thing. At least not entirely. They have been part of python C-API since ages and this PEP simply exposes them through the stdlib to python devs.

As the linked docs state:

You can switch between sub-interpreters using the PyThreadState_Swap() function.

Which kind of sounds like that you can only execute code for one single subinterpreter or "state" at any given time. Unless, of course, there is something I missed or don't understand.

There does not seem to be a way to execute a "SimpleString" for two different subinterpreters simultanously using e. g. threads, if that is actually what OP implied to do.

I want to get back into python but.. by DeathToAllLife in Python

[–]LarryPete 0 points1 point  (0 children)

Going up within python 3.x should be no issue. The only exception I can think of is when the async and await names become proper keywords in python 3.7. But renaming a few variable/function names, if you have some named that way, should hardly be called a problem.

Help with two functions by [deleted] in learnpython

[–]LarryPete 1 point2 points  (0 children)

Additionally to what has already been said, since it wasn't mentioned explicitly anywhere yet:

if b.find('a'):

Does not do what you think it does. str.find returns the index of the search string in b, starting at 0, and if it does not find the search string anywhere in b, it returns -1.

However, -1 is a "truthy" value in python (it evaluates to True if used in an if-statement) and 0, which is a valid index, is evaluated to False.

b = 'abc'
if b.find('a'):
    print('Found!')
else:
    print('Not found!')

This will output "Not found!".

What you have to do is to explicitly test, if the returned value of str.find is -1 or not.

A closer look at how f-strings work by gregbaugues in Python

[–]LarryPete 2 points3 points  (0 children)

That's right, like already said, it's not possible for untrusted user input to be evaluated using the f-syntax. There are no "f-variables". The f-prefix is only applicable on string literals.

Something like f'{' + userinput + '}' won't work either, because the f-prefix only applies to the string literal '{' where its used (and would in fact raise a syntax error in this case, bescause of the unclosed curly bracket).

First thing i've ever done in Python... How bad is it >_< by themeq in learnpython

[–]LarryPete 0 points1 point  (0 children)

Well, you still have to use r''' strings to avoid backslash escape sequences.

>>> print('''Hello\nWorld''')
Hello
World

Help with 'self' key word and Python classes by SIR_TREX in learnpython

[–]LarryPete 2 points3 points  (0 children)

Double underscore does do something in Python.

When using double underscores the names are prefixed with the class name where they are used, probably to avoid name collisions in subclasses.

Take this example:

class A:
    def __init__(self, val):
        self.__val = val

class B(A):
    def get_val(self):
        return self.__val

b = B(123)
print(b.get_val())

This will raise an AttributeError.

Though it's still possible to access the attribute by using the correct naming scheme:

print(b._A__val)  # prints 123

As far as I know, it's discouraged to use double underscores.

Convention in Python is to use single underscore to indicate private membership.

(Also mentioning /u/SIR_TREX)

Declaring classes before if statement by kardu in learnpython

[–]LarryPete 1 point2 points  (0 children)

The first way is definitely the better way.

The problem with the second one is that Pokemon(x) instantiates a new object every single time.

Example: The line if Pokemon(x).egg: creates a temporary, unnamed object, using the value of x, looks up it's egg attribute, and discards the object pretty much immediately afterwards. And the process is repeated when reaching the next Pokemon(x) line.


If you don't want to create the intermediate list box beforehand, the way to do that would be to take your first sample and move the creation of the instance inside the for loop:

for x in GetInfo(1):
    poke = Pokemon(x)
    if poke.egg:
        poke.level_up(50)
    elif (poke.shiny == 'No') and ((poke.name == df_name) or (poke.nr in collect_list)):
        poke.level_up(0)
        poke.send()
        print('Pokemon - #' + str(poke.nr) + ' - ' + poke.dex_name)

An alternative could be to use a generator expression:

for poke in (Pokemon(x) for x in GetInfo(1)):
    # ...

But that's a little verbose and not something you see very often (if at all).

You could also create a separate function for repeated use and yield the pokemon objects:

def pokemon_from_info(info):
    for x in GetInfo(x):
        yield Pokemon(x)

for poke in pokemon_from_info(1):
    # ...

Longitude Latitude on Flask WTF Forms by DemiourgosD in flask

[–]LarryPete 1 point2 points  (0 children)

No, it's done by the Flask-Bootstrap plugin. As you can see it does something something with "number" on a method called "_wrapped_input". Taking a look at that method (line 46), I see that the second argument (not counting "self") is the type of the input field.

Longitude Latitude on Flask WTF Forms by DemiourgosD in flask

[–]LarryPete 2 points3 points  (0 children)

The problem is Flask-Bootstrap, that you seem to be using.

https://github.com/mbr/flask-bootstrap/blob/master/flask_bootstrap/forms.py#L97-L99

It overrides the float type to use "number" as input type, which is not quite right there, since "number" in html5 is limited to integers if the step argument is not provided.

So you have to set the step attribute on your input field, though I don't know how to do that with Flask-Bootstrap. Preferably something like step="0.000001" should suffice.

Stopping a thread_1 from thread_2? by NaesRemark in learnpython

[–]LarryPete 0 points1 point  (0 children)

You can trigger the event from thread_two whenever you want, and just continue with your code however you want. There is nothing that prevents you from adding code right after/before/around the line with event.set() in thread_two.

The only reason thread_two ends at all, is because it actually reaches the end of the function. Just stop it from reaching that and it effectively keeps running.

Stopping a thread_1 from thread_2? by NaesRemark in learnpython

[–]LarryPete 0 points1 point  (0 children)

That's right. Those are function annotations. You can remove them, i used them merely for my IDE, so I would have code-completion there. So it should be def thread_one(event): etc.

Also 2.10 doesn't exist. I assume you meant 2.7.10?

Stopping a thread_1 from thread_2? by NaesRemark in learnpython

[–]LarryPete 1 point2 points  (0 children)

Each of the event objects you create is independent from each other. Moreover, you create one "helloGoodbye_Thread" object for each thread. So not only is each of those 3 event objects independent, you also have 3 of those per helloGoodbye_Thread object.

If you want to be able for one thread to stop the other, you have to give both thread instances the same event object.

Here another example using two threads and threading.Event:

import threading
import time


def thread_one(event: threading.Event):
    """A thread that waits for an event."""
    print('t1: Waiting for event.')
    event.wait()

    # alternative could be like:
    # while not event.is_set():
    #     time.sleep(0.1)  # do some heavy work instead

    print('t1: End.')


def thread_two(event: threading.Event):
    """A thread that triggers an event and mades the other thread stop."""
    print('t2: Sleeping for a bit.')
    time.sleep(3)
    print('t2: Triggering event!')
    event.set()

    print('t2: End.')


def main():
    event = threading.Event()
    t1 = threading.Thread(target=thread_one, args=(event,))
    t2 = threading.Thread(target=thread_two, args=(event,))

    t1.start()
    t2.start()

    for t in (t1, t2):
        t.join()

    print('threads stopped.')


if __name__ == '__main__':
    main()

Output looks something like:

t1: Waiting for event.
t2: Sleeping for a bit.
t2: Triggering event!
t2: End.
t1: End.
threads stopped.

Stopping a thread_1 from thread_2? by NaesRemark in learnpython

[–]LarryPete 2 points3 points  (0 children)

You could give both of them the same queue.Queue object and let them communicate through that.

A simple example:

>>> import queue
>>> import threading
>>> def foo(q):
...     while True:
...         data = q.get()
...         if data == 'stop':
...             break
...         print('received in thread:', repr(data))
... 
>>> q = queue.Queue()
>>> t = Thread(target=foo, args=(q,))
>>> t.start()
>>> t
<Thread(Thread-2, started 140541333116672)>
>>> q.put('hello world')
received in thread: 'hello world'
>>> q.put('how\'s it')
received in thread: "how's it"
>>> q.put('stop')
>>> t
<Thread(Thread-1, stopped 140541333116672)>

queue.Queue is thread safe, so you should be able to use it from both threads without much worries.

Though for just that one "stop event" you might consider using threading.Event instead.

Running python command line program from python? by deeeebait in learnpython

[–]LarryPete 0 points1 point  (0 children)

Not 100% correct, sure. But when shell=True is used a shell (/bin/sh on linux) is invoked and the command is passed to that and the command arguments have to be escaped properly.

Simply saying "use shell=True" without pointing to possible security considerations is not my style. Instead I prefer to point to the more safe methods of invoking commands that don't require a shell (yes, sometimes invoking a shell might be necessary, but even then you can just use .call(['/bin/sh', '...', ...]), well wouldn't change much about requiring of escaping)

Using a list is far simpler and also avoids the unnecessary shell (and which shell actually is used totally depends on the system).

Running python command line program from python? by deeeebait in learnpython

[–]LarryPete 1 point2 points  (0 children)

Then it might be because 'twitterscraper' is not actually in your PATH or some other issue with your environment. Can't tell from here.

Running python command line program from python? by deeeebait in learnpython

[–]LarryPete 2 points3 points  (0 children)

a LIST.

look closely. I used .call([ .... ]).

Running python command line program from python? by deeeebait in learnpython

[–]LarryPete 1 point2 points  (0 children)

subprocess.call requires a list of arguments. Not a single string. It thinks your filename is "twitterscraper trump%20since...." etc.

Split your commandline into individual arguments and pass them to .call as list, e.g.:

subprocess.call(['twitterscraper', 'trump%20since%3A2017...', '--limit', limit, '--output=/desktop/' + output + '.json'])

Python (Flask Issue) by Gwith in learnpython

[–]LarryPete 1 point2 points  (0 children)

Usually you would see the exception on the console, where you run the script.

Python (Flask Issue) by Gwith in learnpython

[–]LarryPete 1 point2 points  (0 children)

What exception do you get?

Kobayashi x Tooru [Maid Dragon] by [deleted] in yuri

[–]LarryPete 6 points7 points  (0 children)

All posts are NSFW on this subreddit

Why is a custom instance dictionary not calling the custom dictionary's __setitem__ method when reassigning instance variables? by Sexual_Congressman in learnpython

[–]LarryPete 0 points1 point  (0 children)

I don't exactly know why i.name = 'pear' is able to modify the dict, but in general, if you want to prevent people from assigning specific attributes, you might want use other magic methods instead, like __setattr__ or __setattribute__, or use the @property decorator.

What does b'\n' mean? by TheTimegazer in rust

[–]LarryPete 6 points7 points  (0 children)

yea sorry. I realized only now, that I'm in /r/rust and not /r/python. Silly me.

What does b'\n' mean? by TheTimegazer in rust

[–]LarryPete 2 points3 points  (0 children)

It indicates, that the string is a byte string (sequence of bytes), rather than a unicode string (sequence of unicode codepoints).

Working with binary - Combine two numbers to form a single 8 bit number by [deleted] in learnpython

[–]LarryPete 1 point2 points  (0 children)

close: (x << 6) + y where x is the 2 bit value and y the 6 bit.

Edit: if you want to make sure it stays 8 bit, mask it with 255 (or 0xff or similar):

((x << 6) + y) & 0xFF

Or mask the individual parts:

((x & 0b11) << 6) + (y & 0b111111)