« first day (3828 days earlier)      last day (1127 days later) » 

4:22 AM
cabbages
 
4:43 AM
making a coding classical playlist. Who are some good composers that aren't the typical names thrown around?
 
@piRSquared Wikipedia list of off-Broadway classical composers?
 
lol, k. I'll look (-:
 
with "typical" does that include Mussorgsky and Bartok?
en.wikipedia.org/wiki/List_of_Classical-era_composers has a lot of names I don't recognize
 
no... it does not. therefore good responses
 
Satie and Prokofiev are not "classical-era" but certainly "serious music"; are they too modern for you?
 
4:48 AM
no... not too modern. TIL new composers.
 
I would still regard those as household names
maybe my household is sophistiqué
 
no! no! I bet 1 in 1000 households know those names.
 
I don't even listen to classical music
 
Well, you payed attention at some point in your life
 
I guess (-: I have a friend who is a serious Prokofiev fan
 
4:57 AM
I love this video. It's hilarious and I like listening to it.
 
I have a CD by Ensemble Ambrosius with "classical" arrangements of some Zappa instrumentals; pretty good listening in its own right and occasionally hilarious if you have listened to the originals
ensembleambrosius.com/faq wonderful Finglish spelling
 
OK! They are interesting. I mean, I liked it but then it started jarring my senses.
 
5:13 AM
logger = logging.getLogger('UrlTracking')
logger.setLevel(logging.INFO)
formatter = logging.Formatter(
    '%(asctime)s - %(name)s - %(levelname)-5.5s - %(message)s')
file_handler = logging.FileHandler('urltracking.log', 'a', encoding='utf-8')
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)

logger.info("Success")  #--> This will go file only.
loggger.warning("Fail") #--> i want it to go to file and stdout as well
 
 
2 hours later…
@Arne Thanks Arne, it's much helpful. really appreciated .
 
it had a bug, I fixed it a second ago
just in case you copied anything already
also, that logging setup didn't explicitly define the default-(aka root-) logger, so any other_log = logging.getLogger(__name__) will use those settings (the formatter only forwards the log message, and the handler sends it to stderr, iirc). Don't know if that's something you want or need.
 
@PaulMcG kind words but I'm more often wrong... remember that "fools seldom differ"? :p
 
7:47 AM
@Arne that custom logging will be used for one script only.
 
ok
 
It's works fine except that log.exception got printed
 
log.exception is just log.error with exc_info=True
or log.critical?
 
except (httpx.RequestError) as e:
    log.exception(
        "Url: {:75}, Reason: {}".format(
            url, type(e).__name__), exc_info=False)
    continue
so I've t o changed it to log.error
 
that's a funny piece of code ^^
you don't need to, but log.exception with exc_info set to False is .. unidiomatic
 
7:53 AM
got it
Just changed it to log.error but still being printed
 
I'm not sure I understand. it's printing the stacktrace and you don't want that, or something else?
 
Nope, i meant that log.error got printed on stdout while i want it to be into file.
 
then you might need CRITICAL for the console handler. or change the log call to info
 
Can someone explain exceptions, in a way to me they look like an error message that is used to control the program flow.
 
@Arne I was mixing out log.error and log.exception :D now it's clear for me the point of exc_info
Thank you ^
 
8:14 AM
rooms a bit quiet, any Python rooms that have people chatting?
 
@Months_not_minutes we usually here due in day time. seems your time zone is different.
 
yes, EST Eastern Australia
 
And regarding your question. Exception is actually help you better to track your program.
Exception is a thing where you didn't Expected it to be but if it's happen then you've to catch it and then follow
 
@αԋɱҽԃαмєяιcαη thanks, yes, some programs seem written to catch the exception as it's expected, hence it's a part of the flow control
 
also you can catch what is not on account as well.
not just for specific one.
 
8:19 AM
@Months_not_minutes if you want lots of chatting, you'll enjoy the python dicsord more, this room tends to be on the calmer side
 
@Arne :D but a lot of wrong information given.
Personally, I like the current due to multiple reasons. it's well managed and a lot of Python experts is here. you ask a question and then you get a response from many of experts :D on the other side! the most famous libraries creators is even visiting the room
 
yeah, I also prefer this room, mostly for the same reasons
 
@Arne I don't really do chat rooms anymore, I just came in here to ask a quick question, I joined Stack Exchange just recently so thought I would drop in.
 
@Months_not_minutes almost welcome :P you would love to check the rules to better understand how things goes on here :P
 
@αԋɱҽԃαмєяιcαη Stack exchange is a bit stricter
 
8:27 AM
@Months_not_minutes Just to be managed well. and that's the main reason why it's been very popular. you need an info/help ! so you've it free of charge and well organized
 
@αԋɱҽԃαмєяιcαη some very good posters on the board.
 
 
4 hours later…
12:28 PM
I just ran import dev, and it seems to exist but doesn't do much more than that. Does anyone know what it's good for? It isn't listed in docs.python.org/3/library
doesn't exist in python2, btw
I'm an idiot, false alarm. I was running python3 from a folder that had an empty directory called dev in it.
 
1:22 PM
@JamesMcIntyre please see our code formatting guide for chat and practice in the sandbox if necessary
For a quick solution you'll have to define a default value for each of those parameters, but I suspect that's just a bandaid for your design problem.
Python can't fill in function parameters for you if you don't pass them or specify a default.
And I have a vague suspicion that your problem would benefit from dataclasses but I've never used them
 
Is there a way of passing them in a named way rather than just order for this cercomstance where there are many properties? e.g. Prop = Void(MeterType = 'standard')?
 
@JamesMcIntyre Have you read a python tutorial yet?
 
I was reading stuff on it but was struggling. I also watched a video on it but it just said how to do it in the order method
 
I meant python in general. How to write and call functions. What keyword parameters are.
In your case if you create an instance with Void(a=b) it will pass those arguments to __init__ as is.
This should be sufficient information if you know how python functions can be defined with various kinds of parameters. If you don't know that, read a basic python tutorial before trying to write classes.
 
I know how to write and call functions. keyword permaters is somthing I've never understood how to do. Ahh ok, so you're saying that what I'm saying would actually work but it's not possible to create a "bank" instance and then populate the properties later?
 
1:28 PM
No, I'm saying what I said. You have to define default values for those parameters if you don't always want to pass them. Just like with any other function. And passing a keyword argument during call will not use the corresponding default. Just like with any other function.
Do you see why I'm asking if you know how functions work in this regard?
@JamesMcIntyre Please read a good tutorial. The official one might suffice for now.
 
I'm dyselic so I do struggle with manuals. I'm not fully understanding what you're saying :/
 
I'm sorry to hear that, but you'll have to take your time and understand these anyway. Don't rush yourself.
Tutorials are at least different from "manuals" (documentation). They give you structured information which you can more easily absorb.
 
journey before destination, as they say.
 
I'm told that the Python Crash Course 2nd edition from our list at sopython.com/wiki/What_tutorial_should_I_read%3F is really good for newbies
the official python tutorial assumes more general programming knowledge, but it's free
@JamesMcIntyre I know this will take more time for you to get comfortable with. But you have to understand the basics of the language before you build more advanced things on top.
 
Unforantuly I'm also doing this for work and so can't spend too much time going into the theory. Can you point me in right direction in terms of how I can either create empty instances of a class or feed in permaters/properties by name rather than 1st, 2nd, 3rd property etc?

I have been using Python as a primary tool in my job for around 2 years so I do have a decnet grasp of how to achive things with Python
 
1:34 PM
I've given all the pointers I could at this point, sorry
 
Ahh well. Back to Youtube and Discord then. I do appricate your time. Thank you
 
good luck
 
1:49 PM
morning cabbages, folks
 
cbg
 
Cbg
@roganjosh Done!
 
Thanks
 
Can someone actually explain the concept behind why inside function assigning or changing a value of a list, existing outside the function, to a new one, does not require it to be global-ized
 
global is needed so that you can rebind the given name at the global scope
 
because the list itself is mutable, unlike an int, which is immutable
 
2:04 PM
My first guess what mutability, is it the correct reason?
@AndrasDeak So by rebind you mean, change the value to something else?
 
@CoolCloud that's such a vague statement that it can't be wrong
@CoolCloud no
 
Just an MRE here:
def foo():
    lst[0] = 10

def bar():
    print(lst)

lst = [0,1,2,3,4,5]
foo()
bar()
 
The global name 'x' refers to a box of shoes. You can take out shoes from the box: that is mutation. Rebinding the name 'x' means taking the label and putting it on a different box. Or a ball. Or a giraffe.
 
I beat an int with a baseball bat (intending to make it lose 1 -- effectively perform the `my_int -1`). What I get is a new int standing in its place, while the old int is rushed to the hospital

I beat a list with a baseball bat (with the intention of making it lose one -- effectively, `my_list.pop`). That list stands in front of me, weathered and bleeding, with broken teeth.

Moral of the story: lists are mutable (i.e. in-place), ints are not
 
@CoolCloud I bet we're already pointed you to it but please read and understand nedbatchelder.com/text/names.html
 
2:07 PM
@inspectorG4dget Lol gonna have hard time forgetting this ;)
@AndrasDeak Yea I understand better :D
 
someone once told me the difference between TypeError and ValueError in a similar way:
 
I just saw this question stackoverflow.com/q/67021416/13382000, just wanted to know what correct reason to give to it.
 
read what I linked anyway
 
ValueError: you come home and go to bed, and you find your neighbor's wife there instead of your partner. That's a ValueError

TypeError: you come home and go to bed, and you find a racoon there instead of your partner. That's the wrong type of entity to be in your bed - that's a TypeError
 
@CoolCloud correct reason is closing as dupe
 
2:10 PM
@inspectorG4dget Damn, that hits
 
Lotta misinformation in the comments of that post
 
@CoolCloud yup. I've adopted that style of story-telling ever since I saw that comment. Same with print vs return: I give you a cookie, vs I write "cookie" on a whiteboard somewhere
 
@Kevin I just found a whole Q&A where multiple upvoted answers claim you need the global keyword to "modify" values stackoverflow.com/questions/10588317/…
 
"global variables have to be declared with global at the beginning of a function" -- wrong, you only need the global statement to assign to a global, not to read from it (or mutate it, although OP never actually asks about that)
"If a variable isn't defined in a function, it automatically becomes global" -- wrong, it searches the containing scopes for a matching name, so it could easily find a nonlocal (yet nonglobal) variable
 
decided not to use that as a dupe target
 
2:12 PM
@Kevin My idea was tkinter widgets store information as dict? So I used indexing on the dict to reassign and since dicts are mutable, it does not require global.
 
@CoolCloud dicts are not special, forget about dicts
they can be mutated, period
 
dicts, lists, sets are mutable. Their immutable counterparts are frozendict, tuple, frozenset. Meanwhile, ints, strs, floats, bools, are immutable
 
let's forget about frozendict, please
 
sure, but why?
 
obsolete third-party library
 
2:15 PM
ahh
 
23 hours ago, by Aran-Fey
The worst part is that frozendict is unmaintained and throws a DeprecationWarning, so you have to use immutabledict instead, which doesn't sound quite as catchy
 
widgets are like dicts in the sense that they implement __setitem__ -- in other words, doing x["foo"] = bar is a sensible operation. But this behavior is no more exclusive to dicts than addition is exclusive to integers
They may be the poster boys of the operation but they don't own it
 
To me a list is more token mutable than a dict. Sue me.
 
@Kevin If a variable is defined outside of functions, it is global by default right?
 
Yeah.
I'm tempted to drop "by default" there too. I don't know of a way to make it not be global in that case.
 
2:17 PM
I mean when you said "If a variable isn't defined in a function, it automatically becomes global" it comfused me
 
I'm not even sure "global" makes sense in this context
 
I didn't say it, I quoted it ;-)
 
@JamesMcIntyre Don't know whether these will be helpful or not ...
 
The term "global" is a bit misleading because once your program grows larger than one file, you can have multiple exclusive sets of "globals" and none of them are universally accessible everywhere with the same syntax
 
Ha I see
 
2:20 PM
There is, sadly, an error in the graphic. The call should be f(x, y) rather than f(a+b, y). I'm sure others have presented it better.
 
@CoolCloud Perhaps another way of phrasing that quote would be "if you reference a variable name in a function without using that name in an assignment statement, then Python knows the variable is global not local".
 
I think of global as a relationship between the point of reference and where the name resides. Global with respect to the point where you're trying to refer it.
might be a pointless distinction on my part
 
in def bar(): print(lst), Python notices that you reference lst without ever doing lst = [whatever] inside bar. So it searches outwards for other scopes where lst = does occur, and finds lst = [0,1,2,3,4,5] at the file-level scope. Now it knows what object you're referring to, and will happily print it for you
 
@Kevin Then would it do the same searching outside the function for other types of variables too?
 
Sure. It works for all objects, regardless of type.
 
2:28 PM
@CoolCloud other types? This is getting scary.
 
The name resolution system and the type hierarchy are more or less entirely independent
 
@AndrasDeak Lol, okay, im gonna leave this topic here before it gets any more scarier ;)
 
@CoolCloud please go read nedbat's article I linked
It should become obvious that there's no difference between mutable and immutable variables when it comes to name binding. It's just that it's physically* impossible to change the state of immutable variables.
As long as you think mutable objects are somehow special-cased, keep rereading it and then asking questions here. (Because they aren't.)
 
Arguably, the name resolution system can't care about types, because the vast majority of type information is only determined at runtime, and name resolution has to do half of its work at parse time, long before a single line of code has executed
 
Cool Cool, I understand better. I'll take it from here and build upon it :D
 
2:32 PM
build upon it by reading the article I linked
 
@AndrasDeak Lol yea sure man, I already started reading it long back when you sent.
 
PS. This topic is one where you can be 99.99% fine if you can understand it well enough to predict its behavior in your own code. The last 0.01%, acquirable only by understanding it well enough to explain it to your grandmother, is mostly only useful for bragging rights and educators
So don't feel bad if you can't diagram out the whole thing on a blackboard
 
@Kevin Sure, ill figure it out slowly :D Thanks
 
Yet another voronoi diagram of a koch curve, this one with degree 4. In my earlier diagrams there was a small yet noticeable difference between the regions southwest of the curve, vs the ones northeast of the curve. But as degree increases, the differences shrink. this may be ultimately useful for my infinity-degree nearest-point-on-curve finder.
 
2:47 PM
Initially I was hopeful that I wouldn't have to guard against maximum recursion depth for my finder. The parametric curve formula I was using didn't need one, because it provably terminated in ~40ish calls for any normal float. But my curve finder's arithmetic will likely incorporate square roots, so some inputs may never converge towards my base case.
 
@Kevin Plus parameters: they define the call namespace's initial contents, and are always local.
 
Yeah.
 
Hence SyntaxError: name 'a' is parameter and global, which I'd never seen until I just tried it!
 
Ooh, it's fun to find new SyntaxErrors
 
3:10 PM
Reminds me of the time I was browsing through the NetHack source code looking for easter eggs. The devs like to put in jokey messages for game scenarios that almost never occur. A well-known one is, if you shapeshift into a metal-eating monster and consume a trident, it says "your breath is fresher", a reference to Trident brand gum.
Anyway, while browsing I noticed a message I had never seen mentioned in any of the extensive fan documentation: "you hear the sounds of faint typing". I determined that I could get this message in the game if I shapeshifted into a monster that can pass through walls, move through the usually-impenetrable stone border around a level, and apply a stethoscope onto the truly impassable edge of the screen.
In this context, it's obvious that it's a "breaking the fourth wall" joke -- the player character is hearing the keystrokes of my real life self.
 
@Kevin I remember reading about that
 
Thus ends my tangential story of very rare messages
 
Perhaps here :P
 
Yes, it is likely
Sep 28 '16 at 18:22, by Kevin
Nethack's a fun game. One time I went source diving through it and found an easter egg that apparently nobody had ever discussed online before: if you polymorph into a xorn and travel to the very edge of the map and apply a stethoscope to the impenetrable wall, it says "you hear the sound of faint typing" implying that it's the fourth wall
 
Yeah, just checked
 
3:14 PM
Easier to search for if you know that only xorns can walk through walls
I have mentioned xorns only three times in here so it's easy pickings. Well, five times now.
 
"Faint typing" is surprisingly fruitful
 
Good thing I didn't misremember it as "you hear the faint sounds of typing" or any of the other plausible permutations
 
SO chat search doesn't respect adjacency anyway
 
A broken clock is right twice a day :-D
 
3:31 PM
Today's work related task is to parse a ten year old swf file and see how much of its object coordinate data can be salvaged from it. Sothink was once a well-recommended swf decompiler, but now it only runs on machines that haven't been sent the Flash self-destruct code from Adobe. Not very useful for data archaeologists like me.
The advanced age of the file may be to my advantage, because the only documentation for swf happens to be from the 2012ish era. I don't have to worry about revisions occurring after that.
I have already verified that my file has a valid 8 byte header, and its data payload is zlib-decompressable to a byte sequence of expected size. So far so good.
Next up, parse this bitfield with a variable number of bits, and which may or may not have filler bits to ensure the next record is byte aligned.
struct.unpack cannot save me now
I might actually use generator.send() for once
 
3:58 PM
so delving into the binary data?
 
Yeah
 
Just seen this @holdenweb

I found out that you can put "= None" into the perameters of the class which gives it the None starting artibute so it doens't complain at init and then you can assign the properties later
 
Sure. It's possible to write classes where instance attributes aren't given values during initialisation and acquire them later, but then you can find your logic being invaded by if hasattr( ... ) tests, a sure sign something smells a bit.
 
Yeah, where possible you should try to have all your important attributes ready to go during init
 
I much prefer objects with well-defined namespaces.
 
4:22 PM
I'm curious what "doesn't complain at init" entails here, since Python usually doesn't have a problem with late-created attributes. Maybe it's a linter or something that's giving a warning.
 
error on instantiation without passed arguments
 
Oh ok, I was thinking of something other than default args
class A:
    x = None
    y = None
    def __init__(self):
        pass

class B:
    def __init__(self):
        self.x = None
        self.y = None
Something like either of these
(Neither of which I condone)
 
4:43 PM
@JamesMcIntyre are you familiar with default values and keyword arguments?
 
@Code-Apprentice been there, done that
review recent history from around here chat.stackoverflow.com/transcript/6?m=51957592#51957592
 
Thanks for the input guys:

Yes, I've just been learning about default values and so this is how I found out to set all my atribues equal to None so they can be set later in the code. I didn't understand holdenweb's thing about hasattr( ... ) though
 
@JamesMcIntyre good luck. With default values, you won't have to worry about hasattr().
 
Thanks Code
 
5:16 PM
Hmm, my parser thinks this file has seven "end of file" tags. Somehow I think that's not right
The first one appears 10% of the way into the file. I guess the rest is just random bits!
 
 
1 hour later…
6:32 PM
file format spec: "FileAttributes tag: always one byte long."
My parser: "Located FileAttributes tag. Length in bytes: 4"
I hope those three additional bytes don't contain any super cool data, because I don't know what they represent
 
they are probably a tag from whoever created the file
 
6:55 PM
Hi!
I've been trying to apply a filter to images in python, consisting of adding randomly gray/transparent pixels to an image (not the whole image but randomly) to make it seem more opaque and transform solid colors into not uniform colors.
I've tried to get this by adding salt and pepper noise but it's not similar since it's pure black or white instead of the effect I wish that is gray/transparent pixels. Does someone has an advise or idea on how this could be possible?
 
Hello. What libraries are you using?
 
Dang, an image manipulation question appears just as I'm about to go into a meeting. I'll comment later if I have any thoughts
 
Kevin has to uphold his image manipulation
 
I've tried using Wand and Pillow getting a noise effect (but was not able to get the transparent/gray effect, got black and white random pixels instead)
 
Transparency needs the right kind of image format that supports it. Grayscale should be universal.
Kevin's a lot more image-y than me. I'm a numpy person, so I'd solve this by manipulating RGB arrays.
 
7:24 PM
I see! in the meantime as I haven't been able to address a more efficient way yet, I was just thinking how I could do that using numpy, is it possible to create gray semi transparent pixels (so you can actually see through them) so I could create kind of a mask and place it over an image? (Probably this is basic, I'm new at manipulating images/using numpy xD)
 
Perhaps you could use pillow.readthedocs.io/en/stable/reference/… or pillow.readthedocs.io/en/stable/reference/…, don't know off the top of my head what the arguments ought to look like
 
7:37 PM
from PIL import Image, ImageChops
import random

img = Image.open("test_image.png")
noise_mask = img.copy()
pix = noise_mask.load()
w,h = noise_mask.size
for x in range(w):
    for y in range(h):
        color = (random.randint(220, 255),)*3
        pix[x,y] = color

result = ImageChops.multiply(img, noise_mask)
result.save("output.png")
Here's a quick prototype I put together. The mask contains gray pixels ranging from pure white to mostly white. multiplying the original image with the mask will cause each pixel to become a little darker to a random degree, creating a mildly staticy texture.
Here are my input and output files. Click to view them at maximum size to compare their details.
 
7:53 PM
@lorelayb sorry, I distracted myself. As far as the numpy arrays are concerned, yes, if you have a (w, h, 4)-shaped RGBA array then you can set arbitrary pixels to arbitrary colours and transparency. Question is whether your image manipulation library will be able to render the array (usually yes).
@Kevin is pix a numpy array by any chance?
No, because it has .size instead of .shape.
and its shape is 2d even though its elements are 3-length tuples
 
Thank you so much guys!!! amazing, that makes sense, that is the kind of effect I was just trying to get @Kevin! Taking a look now to understand better the way it works, will reach out if any question to understand it better, thank you for the help!
 
So for the record the numpy version of what Kevin did would look something like this:
although this will also scale the transparency in the RGBA case which is probably not what you want
you seem happy with Kevin's version so I won't iterate this
(and I didn't run that to see if it works)
bah, it's still buggy
I'll trash it, let me know if you're interested in a working version
 
8:20 PM
@AndrasDeak of course, if possible I would like to see your solution as well, I'm glad about the help you both have provided me
 
from PIL import Image
import numpy as np

rng = np.random.default_rng()

img_pil = Image.open("test_image.png")
img = np.array(img_pil)

if img.ndim == 2 or img.shape[-1] == 3:
    # greyscale image or RGB without alpha
    # (shape (w, h) or (w, h, 3), respectively
    scale_shape = img.shape[:2]
else:
    # RGBA image of shape (w, h, 4)
    scale_shape = img.shape
scale = rng.uniform(220, 255, size=scale_shape) / 255
if scale.ndim == 3:
    # don't scale alpha channel
    scale[..., -1] = 1

img = (img * scale).astype(img.dtype)
I couldn't make it more elegant ensuring that it works for all kinds of images
 
@Kevin Is that retro-homage to the venerable BBC Test Card F (1967-1998), or just TV Test Cards in general?
 
8:39 PM
@AndrasDeak thank you!! taking a look at this approach
 
No problem. If you know the type of your image the logic gets a lot cleaner
actually, no, that's still buggy
argh
Don't drink and drive not sleep and code
So that works for an RGBA image which happened to be Kevin's example. But it has the same bug as the earlier version for RGB and greyscale images... *sigh*
if img.ndim == 2 or img.shape[-1] == 3:
    # greyscale image or RGB without alpha
    # (shape (w, h) or (w, h, 3), respectively
    #scale_shape = img.shape[:2]  # buggy
    scale_shape = img.shape[:2] + (1,)*(img.ndims - 2)  # correct?
Pfft, I mean img.ndim. I'll just stop here before I make it any worse. Let's rehash in a few days when I'll have slept.
 
I wasn't aware Python allowed this 3 > 2 > 1 > 0 I knew it could do 3 > 2 > 1. is 3 > 2 > 1 > 0 doing what I think it's doing?
 
If you think it's doing 3 > 2 and 2 > 1 and 1 > 0 then yes :P
 
that is really cool
This Python language might make it after all.
 
8:55 PM
@AndrasDeak Thank you! have some rest!
 
python's a tad overzealous with those implicit ands though
>>> 'fire' in 'firetruck' == True
False
 
obviously 'fire' isn't in False >.< I see what you're saying
 
Hmm, that could probably be a neat puzzle if you put it like "Where can adding parentheses change the result of an expression without altering the order of operations?"
Although that's probably too vague. Something like foo(1, 2) vs foo((1, 2)) would also be a valid answer to that
 
9:23 PM
@Aran-Fey or anything non-associative, like a series of ands/ors
 
@AndrasDeak What do you mean by "non associative"?
 
9:40 PM
@Code-Apprentice (a and b) or c != a and (b or c)
it's not strictly speaking associativity because it involves two different operators
other example: octonion multiplication :P
 
right, associativity applies when you use the same operator multiple times in the same expression.
 

« first day (3828 days earlier)      last day (1127 days later) »