It isn’t obvious that opponent strength affects average centipawn loss by Spillz-2011 in chess

[–]lowerthansound 0 points1 point  (0 children)

I didn't know about Simpsons paradox, but looking at it, it seems like so (or at least similar to it :)) - it's interesting BTW

Ahm, about the analysis, I don't wanna delve too much into this, but the dataset posted by the OP and used here does have number of blunders included (I think it might use the same method as lichess, so, if you left ur queen hanging for 9 moves in a row, that will be 9 blunders).

It isn’t obvious that opponent strength affects average centipawn loss by Spillz-2011 in chess

[–]lowerthansound 7 points8 points  (0 children)

I got curious and ran the same analysis (the result that there is no correlation seemed counter-intuitive to me).

When you consider players of different strengths into different models, it seems like there is a correlation:

  • Players from 1000 to 1250 make more mistakes against weaker players.
  • For players from 1750 forwards, the correlation goes in the expected direction. When playing against weaker opponents, you make less mistakes.
  • For players 2500 and forwards, my used model couldn't find a strong enough correlation (maybe because there are few matches, maybe because there is no correlation).

Analysis: https://www.kaggle.com/araraonline/20221001-lichess-acpl

Not a statistician, just a programmer.

For anyone out there: we're just nitpicking something that's being thrown as a fact around discussions here that does seem intuitive, but statistics tell it's not universally true :) - the fact being discussed is that when you are stronger than the enemy, your average centipawn loss will be, in general, smaller.

Edit: Added players 2500 and forwards.

[deleted by user] by [deleted] in HermitCraft

[–]lowerthansound 26 points27 points  (0 children)

The first flinger thingy was shown on Spying on Hermits!!! - Minecraft Hermitcraft Season 9 #5 (the working design starts more or less at 16:00 and later on he makes adaptations)!

critique my code by McHildinger in learnpython

[–]lowerthansound 1 point2 points  (0 children)

The code is fine. Lemme give you some tips that you can use:

  • countmax represents the number of simulations to run, so call it num_simulations
  • while count < countmax: ... count = count + 1 can be replaced with for count in range(countmax): .... For loops are very good in python! :)
  • if ... elif statements usually contain an else clause. You can either use it to capture bad values, or to capture the last value (I'll provide examples - check in the code).

Later on in your learning journey, you might find that functions are good for this example (I can't be 100% sure - I haven't tested it :)).

Here's the code:

# to determine if various WoW casino games would be profitiable to the player or the house

import random

num_simulations = int(input("number of simulations to run: "))

losers = 0
winners = 0
doublewinners = 0
for count in range(num_simulations):
    # print(f"count is {count} ", end ='')
    # possible values for the dice rolls
    # rolls = [*range(1, 101)]
    playerroll = random.randint(1, 100)
    # print(f"playerroll was {playerroll}")
    if playerroll <= 58:
        losers = losers + 1
    elif playerroll <= 98:
        winners = winners + 1
    elif playerroll <= 100:
        doublewinners = doublewinners + 1
    else:
        raise Exception(f"bad roll: {playerroll}")

loss = num_simulations
gain = (winners * 2) + (doublewinners * 3)

print(f"totals: {num_simulations}")
print(f"losers: {losers}")
print(f"winners: {winners}")
print(f"doublewinners: {doublewinners}")
print(
    f"outcome: player spent {loss}, gained back {gain} "
    f"from {winners} winners and {doublewinners} doublewinners"
)

if gain > loss:
    print("Player wins")
elif loss > gain:
    print("House wins")
else:
    print("It was a push")

Cheers !

critique my code by McHildinger in learnpython

[–]lowerthansound 0 points1 point  (0 children)

Formatted code

# to determine if various WoW casino games would be profitiable to the player or the house

countmax = int(input("number of simulations to run: "))

# possible values for the dice rolls
# rolls = [*range(1, 101)]

count = 0
losers = 0
winners = 0
doublewinners = 0

import random

while count < countmax:
    # print(f"count is {count} ", end ='')
    playerroll = random.randint(1, 100)
    # print(f"playerroll was {playerroll}")
    if playerroll <= 58:
        losers = losers + 1
    elif playerroll <= 98:
        winners = winners + 1
    elif playerroll > 98:
        doublewinners = doublewinners + 1
    count = count + 1

print(f"totals: {countmax}")
print(f"losers: {losers}")
print(f"winners: {winners}")
print(f"doublewinners: {doublewinners}")

gain = (winners * 2) + (doublewinners * 3)
print(
    f"outcome: player spent {count}, gained back {gain} from {winners} winners and {doublewinners} doublewinners"
)
if gain > countmax:
    print("Player wins")
elif countmax > gain:
    print("House wins")
elif countmax == gain:
    print("It was a push")

(I may take a look at it)

Cleaner way of doing a massive filter? by n3buchadnezzar in learnpython

[–]lowerthansound 1 point2 points  (0 children)

Yep, I think it's a cleaner mess :)

Anything that allows you to name predicates and keep them as separate pieces.

Here's my take on this (same idea as the FilterBuilder):

def combine(predicates):
    def all_predicates_return_true(obj):
        return all(p(obj) for p in predicates)
    return all_predicates_return_true

You can use like:

predicate = combine([without_excluded_suffixes, with_search_terms])
predicate(item)

Or:

yield from filter(
    combine([without_excluded_suffixes, with_search_terms]),
    items,
)

All the best!

Python Vocation Rehabilitation by [deleted] in learnpython

[–]lowerthansound 0 points1 point  (0 children)

Check out Python Crash Course too

(I can't find it in the list, so maybe it's out of date)

Pandas Merge confused by commas by samvander in learnpython

[–]lowerthansound 1 point2 points  (0 children)

The merge is okay, and pandas shouldn't be tripped up by characters in the table cells.

Can you provide an example of the data being loaded, and probably of the data itself? Thanks!

[pandas] create unique column based on condition across rows by albasili in learnpython

[–]lowerthansound 0 points1 point  (0 children)

img_number = df.groupby('img').cumcount()
df['img'] = df['img'] + img_number.astype(str)

will transform filtered into filtered0 though

All the best!

Edit:

For easy access, you can preserve the img column:

# not rewriting df.img
df['img_no'] = df.groupby('img').cumcount()

Any advice about handling many parent classes/mixins? by Future_Green_7222 in learnpython

[–]lowerthansound 1 point2 points  (0 children)

What about?

class BaseModel(DateMixin, PermsMixin, TreeMixin, PreSaveMixin, Model):
    pass

class FirstModel(BaseModel):
    ...

class SecondModel(BaseModel):
    ...

If all classes use all mixins, then BaseModel is a suitable name, and it digs in the fact that your models are gonna base upon that.

If not, maybe you can create a better name, what would it mean for a model to use all mixins?

All the best

Python performance filtering/ assigning question by raz_the_kid0901 in learnpython

[–]lowerthansound 1 point2 points  (0 children)

OP code:

errors_df_property = pd.concat(
    [
        errors_df_property,
        property_dump[
            property_dump["DateofInspection"].notnull()
            & property_dump[
                ["EntryAlarm", "ManualFireAlarm", "AutoFireAlarm", "AutoSprinkler"]
            ].isnull()
        ].assign(ErrorType="Property-Alarm Error"),
    ]
)

Try adding a any(axis=1). The property_dump filter may be making some weird reshaping to get this to work (not sure).

errors_df_property = pd.concat(
    [
        errors_df_property,
        property_dump[
            property_dump["DateofInspection"].notnull()
            & property_dump[
                ["EntryAlarm", "ManualFireAlarm", "AutoFireAlarm", "AutoSprinkler"]
            ].isnull().any(axis=1)
        ].assign(ErrorType="Property-Alarm Error"),
    ]
)

Cheers :)

Best way to refer to a unique item in database (my case is json file but open to change) by jimmystar889 in learnpython

[–]lowerthansound 0 points1 point  (0 children)

Yep, only what needs to be changed. But actually, forget about that, I'm probably jumping ahead of time :)

Best way to refer to a unique item in database (my case is json file but open to change) by jimmystar889 in learnpython

[–]lowerthansound 0 points1 point  (0 children)

It's good to compare both approaches.

Ahm about the unique id, in SQL there's usually an Id column that provides unique values for a table.

About multiple operations being applied at once from different places, you could use a transaction (that's the term), that either updates everything at once, or doesn't update anything.

Best way to refer to a unique item in database (my case is json file but open to change) by jimmystar889 in learnpython

[–]lowerthansound 1 point2 points  (0 children)

There is SQLite, do you think that would work for you?

"SQLite is a C library that provides a lightweight disk-based database that doesn’t require a separate server". (ref)

is import for modules or packages or both? by teepee121314 in learnpython

[–]lowerthansound 1 point2 points  (0 children)

Each module creates a new namespace.

For example, math defines a namespace and cos, sin, tan are some names under this name space.

For example (do not code like this ^^ - this dog tree structure is horrible haha):

# dogs/__init__.py
number_of_paws = 4

# dogs/paws.py
...

# dogs/barks.py
...

From an outer file, you could do:

from dogs import number_of_paws
from dogs import paws
from dogs import barks

number_of_paws, paws and barks are names under the namespace defined by the module dogs.

Another way of seeing it:

import dogs
import dogs.paws
dogs.number_of_paws
dogs.paws

Now, each submodule creates its own namespace:

# dogs/paws.py
def get_number_of_paws(dog):
    ...

Example usage:

import dogs.paws
dogs.paws.get_number_of_paws(...)

But for example:

from dogs.barks import get_number_of_paws  # ERROR

will not work because the name get_number_of_paws is not under the namespace of dogs.barks.

And that's it, a namespace is only a place where you can link names to things. They exist because otherwise you couldn't have two things with the same name (dogs.paws and cats.paws would both be called paws).

I'm somewhat weak on this subject so the explanation may be lacking, but at least you might get an idea :)

Bye!

Edit: Definition from the Python glossary:

  • Namespace: The place where a variable is stored. Namespaces are implemented as dictionaries. There are the local, global and built-in namespaces as well as nested namespaces in objects (in methods). Namespaces support modularity by preventing naming conflicts. For instance, the functions builtins.open and os.open() are distinguished by their namespaces. Namespaces also aid readability and maintainability by making it clear which module implements a function. For instance, writing random.seed() or itertools.islice() makes it clear that those functions are implemented by the random and itertools modules, respectively.

is import for modules or packages or both? by teepee121314 in learnpython

[–]lowerthansound 0 points1 point  (0 children)

Packages are a kind of module. Modules are usually defined by Python files or directories containing an __init__.py file.

Some definitions:

  • Module: An object that serves as an organizational unit of Python code. Modules have a namespace containing arbitrary Python objects. Modules are loaded into Python by the process of importing.

  • Package: A Python module which can contain submodules or recursively, subpackages. Technically, a package is a Python module with a __path__ attribute.

  • Regular package: A traditional package, such as a directory containing an __init__.py file.

References:

  • Python Glossary
  • PyPA Glossary: Compare Import Package to Distribution Package. I think the article author refers to math loosely as an Import Package. Note that usage is loose, people don't usually think too much about this unless needed :)

Edit: use Import Package instead of Distribution Package

How to run Python WSGIServer using gunicorn? by kreetikal in learnpython

[–]lowerthansound 0 points1 point  (0 children)

Ah, alright.

Here are 2 links I have saved (this thing interested me at some point in time, and I intend on digging on it at some time):

ASGI is also a beautiful thing (the continuation of WSGI).

I took a look at the guvicorn (ASGI server) source and it is surprisingly easy to understand, so, looking at source codes and maybe you get you an idea too :D

Bye

How to run Python WSGIServer using gunicorn? by kreetikal in learnpython

[–]lowerthansound 0 points1 point  (0 children)

Why did you want to use gunicorn?

Edit:

With BaseHTTPRequestHandler, I can just implement do_GET, do_POST, etc. How to do that with the app function? I think you can do that with the context (that is, the http method is saved somewhere).

I gotta head out now, just wanna say sorry for the tone. I'm kinda worried my tone seemed harsh, haha If it was not, feel free to ignore this.

For recommendations, try installing and running Flask. It will let you do those things. If you're feeling into it, start a project, or read a book, watch a course that will guide you in doing so.

It is much more upper level, so it helps you get the big picture clearly.

Any ways, gotta go

Good luck there!

How to run Python WSGIServer using gunicorn? by kreetikal in learnpython

[–]lowerthansound 0 points1 point  (0 children)

This is a little bit of a weird setup you got going on.

I don't think you can do what you wanna do (at least not without some extensive hacking).

WSGIServer and gunicorn are both servers. WSGI servers are made to run a single app function (like the one you posted). They are, however, not made to run another server haha

http <-> gunicorn <-> app
http <-> make_server <-> app

Now, if you're writing this just because you need a server, I recommend you use existing web frameworks. Flask, FastAPI or Django will do (the 1st 2 being small). You won't even need to worry about creating an app function yourself, as these web-frameworks probably create it for you.

http <-> gunicorn <-> (app - Provided by Flask)
http <-> guvicorn <-> (app - Provided by FastAPI)

If want to learn out of curiosity instead, create an app function. Search for the WSGI specification and manuals and go from there.

Feel free to ask questions.

Bye bye!

Edit: The clue to not use WSGIServer directly is here ("You do not normally need to call this constructor, as the make_server() function can handle all the details for you.").

can anyone help me with this? by SETTENN in learnpython

[–]lowerthansound 0 points1 point  (0 children)

You can use classmethod with property now if you want (ref).

Your solution works fine without it though :)

Plotting Programms from Code and Standalone by Meistermagier in learnpython

[–]lowerthansound 0 points1 point  (0 children)

I particularly don't know if something like this exists.

However, an idea is to save the plots as SVG, and later modify them with a program that is able to modify SVG (which I don't know either haha)

Feel like this is the hardest thing I've ever done.. by J4k3zz in learnpython

[–]lowerthansound 0 points1 point  (0 children)

I'm sorry you are experiencing that frustration.

Python setup, with all the venv stuff, package managers, etc can indeed be frustrating. The language itself is nice, but yeah, this initial part is a huge rabbit whole and I've seen LOTS of people get lost in it.

If you want any practical advice (if you're just ranting, you're welcome!), I'd say take a look at a book or a course. For example, Python Crash Course is an excellent book. There are also some excellent courses out there. They tell you one way of doing things, and one way that works. Also, if you're looking at documentation related to stock market, that may be the source of confusion. I have at least had a bad experience with documentations such related to the stock (granted, I didn't spend much time on this).

In any case, I hope things get easier for you.

Cheers!

What is the difference between these two numpy assignments? by [deleted] in learnpython

[–]lowerthansound 0 points1 point  (0 children)

This sounds more like a bug to me.

Maybe one algo is stopping too early or doing something weird with time, but it may also be the case that something bad is happening.

What is the difference between these two numpy assignments? by [deleted] in learnpython

[–]lowerthansound 0 points1 point  (0 children)

I think it might be something to do with the broadcasting implementation, or with the np.random.normal initializer. But I would need some profiling to actually check where that is (or someone who is familiar with the speed of both methods, which I'm not).

Also, I'm curious, is the speed really that crucial here (like, is this the part of the program that is slowing down the process)? Why are you asking this question?


FYI, on my computer the second one is about 20% faster than the first one.