« first day (3343 days earlier)      last day (1598 days later) » 
00:00 - 17:0017:00 - 00:00

wim
12:00 AM
he would also rail on physicists for their sloppy math
 
To be fair to the physicists, approximations are good enough for most purposes.
 
wim
it was not about approximations, more about carelessly using theorems from analysis without checking if they're satisfying the Antecedent in the first place
 
God knows what he'd say about engineers there
 
wim
I feel like engineers are a bit more rigorous in many cases. Perhaps because they are held accountable when they screw up
 
Things like the Ergun Equation put fuel into cars, but it's only an approximation
 
wim
12:06 AM
And they test the heck out of everything
ack, much of fluid dynamics is built up on heuristics and magic numbers from what I saw ... yuck
 
Yeah, it's just fitting things to empirical data
 
@wim can't argue with that
 
You'll love Reynolds Number, I'm sure. Between 2000 and 2200, stuff happens. Below that it's laminar, above that it's turbulent flow. Don't design something in-between, then you don't have to care too much :P
 
Dimensionless constants are pretty cool
 
It's also used all the time in Chem Eng :)
Those parts I kinda miss. But you go further into it all in study then get dumped on an oil rig with equipment from the 80s and, then it's just a number-crunching game rather than innovation
"This oil well has a slightly different composition; how do we recalibrate Ol' Faithful to distill it?". Of course it's not all like that, but an awful lot of jobs are
 
 
1 hour later…
 
1 hour later…
wim
2:59 AM
Anyone got a beautiful solution for day 10 to show off? Numpy, maybe? I have a slow and ugly pure python solution (brute force) and would like to get inspired by something better/faster...
 
3:16 AM
anyone here amazing with python
 
3:52 AM
@ChristianMatthew I'm amazing even without python
 
i need help with a jupyter notebook wiki data dump issue
 
If you can break down your problem to its simplest bits then I'm sure people can help
 
import requests

# Parsing HTML
from bs4 import BeautifulSoup

# File system management
import os
base_url = 'https://dumps.wikimedia.org/enwiki/'
index = requests.get(base_url).text
soup_index = BeautifulSoup(index, 'html.parser')

# Find the links that are dates of dumps
dumps = [a['href'] for a in soup_index.find_all('a') if
         a.has_attr('href')]
dumps
dump_url = base_url + '20191101/'

# Retrieve the html
dump_html = requests.get(dump_url).text
dump_html[:10]
# Convert to a soup
soup_dump = BeautifulSoup(dump_html, 'html.parser')

# Find li elements with the class file
soup_dump.find_all('li', {'class': 'file'}, limit = 10)[:4]
# Convert to a soup
soup_dump = BeautifulSoup(dump_html, 'html.parser')

# Find li elements with the class file
soup_dump.find_all('li', {'class': 'file'}, limit = 10)[:4]
files = []

# Search through all files
for file in soup_dump.find_all('li', {'class': 'file'}):
    text = file.text
    # Select the relevant files
    if 'pages-articles' in text:
        files.append((text.split()[0], text.split()[1:]))

files[:5]
files_to_download = [file[0] for file in files if '.xml-p' in file[0]]
files_to_download[-5:]
import sys
from keras.utils import get_file

keras_home = '/Users/Christian/.keras/datasets/'
ok this part here is spinning
so does that mean the data is downloading
The default download directory for keras is ~/.keras/datasets. I already had the dataset downloaded, but the download will take around 150 minutes and requires at least 15 GB of disk space.
well i guess so
here is my second question
can machine learning be accomplished for smaller data sets
but more input
 
@wim Nothing particularly good here. I did solve part 2 by sorting a list of points, but the key function was ugly
 
4:21 AM
hi, quick question, how heavy of a dependency is flask for communication with a chrome extension?
is it worth it? I have 3 PRs to review and one implementation uses flask (swaglyrics.dev/SwSpotify)
 
@aadibajpai pretty heavy, can you just use HTTP with the requests package?
 
I think the implementations set up a server to which the chrome extension then sends data. One of them (github.com/SwagLyrics/SwSpotify/pull/13) adds custom classes for the server implementation
I'm pretty confused which way to go
 
@smci gooey and wooey wasn't that helpful. It might be due to lack of my understanding. But instead i was able to make an exe file for the script which basically shows all the headers and the workflow while executing the script using pyinstaller.
 
wim
@aadibajpai The code looks bad. Random commented out bits and dead code. Redirecting stderr to devnull and then not restoring it in a finally block. starts a thread then just joins it immediately. tests don't look to be testing anything.
 
4:40 AM
@wim haven't got to actually reviewing them yet, just need to sort out implementations first
 
wim
4:53 AM
@JoelHarmon my part2 is fine, runs in a fraction of a second. it's the part1 that's slow.
 
How slow is slow?
 
wim
O(n**2)
I am comparing pairwise and have ~350 asteroids
so it's ~60k comparisons
 
If you make backreferences, you only need to compare the rest of your row to the right, plus anything down from you.
"If I can see you, you can see me" and all that.
 
wim
I already am
that's still O(n**2)
it's just halving the coefficient
 
(n**2)/2 is still n**2, but it is also twice as fast.
 
wim
4:57 AM
I get it, but I am doing already (it only saved 3 seconds btw)
 
My implementation is around a second.
 
Basically, just use the current point and some step parameters to define some range()'s of interest; any second ones will go into a set of blocked items to be ignored later.
Gotta run, as I am sure you do.
 
wim
hmm
>>> t0 = time.time(); a, b = part_ab(data); print(time.time()-t0)
3.3623299598693848
oh shoot, we're starting!
thanks!
more intcode lol
 
5:13 AM
I have a concept question
about a prediction model that I want to build
say I want to sell cars.
there are only 1000 cars in the lot so that is not a lot of data
but I go through the process of asking the person about what kind of car they want
in this case with enough questions I can generally recommend a car to that person.
how could I use deep learning over a period of time to help this process in any way from any perspective
the only data set that grows is the question asked and car buying outcome
lastly is this good to do in combination with a graph db
 
5:31 AM
@RahulMoharir You want to deploy it as a (Windows) EXE rather than as web service endpoints?
...or just that you wanted the latter but ended up having to do the former?
 
5:53 AM
I have no idea how to debug day 11 part 2 view spoiler
 
user10984358
6:13 AM
@ChristianMatthew if dataset is a problem, I once had to do a process called "data augmentation" I was dealing with numpy arrays of audio files and there was not much audio files so I had to augment data, I added in white noise, increased the pitch ended up with 3x more data than with what I started with, if you dont know data augmentation you might wanna look into that, ofc there is a chance you can overfit your model
 
user10984358
I was using a basic CNN so I dont really know how well this affected mine
 
awful mistake, took me way too long to realize why nothing looked right view spoiler
 
6:40 AM
cbg guys o/
 
7:08 AM
It's been more than 3-4 days and I am still struggling to come up with a "design" to add one more id field(In case user collection user_id) which will take ObjectId hex string(Auto generated one) as its value whenever we are inserting a new record to mongodb collection.
Now I feel like I shouldn't have gone with MongoDB, with MySQL it was much easier, because you can always add auto incremented primary key field. And you would never have to deal with this ObjectId and it's hex string?
 
7:37 AM
How up-to-date is Aaron's answer to "What is the best way to implement nested dictionaries in Python?"? cc: @AaronHall. And even if the objection to defaultdict is that it doesn't pretty-print, I suggest that approach should still be shown first, because that's what everyone uses.
 
7:58 AM
Am I right about this. I think the OP really wants a 2-level nested-dict that provides a multikey lookup: dist_dict.get(key1, key2, ...) Did anyone ever implement that sort of thing?
 
wim
@smci Looks alright to me, mostly. The last one shown (one called vivdict) has a bug that he's overlooked. The approach shown first is the best one IMO, and should stay first.
 
Hello.. one question, I’m new to uwsgi and when I run the code pastebin.com/raw/ZagmAMkc using the command uwsgi --http :9090 --wsgi-file wsgi.py --enable-threads --processes 2, I get two processes, but the thread that I’m creating is running only in the main process.. I was expecting the thread also to be part of the fork, but that is not the case. How is it working internally?
 
wim
I don't much like the way he brags and puts down the other answerers, but that's just his style.
 
> This output is quite inelegant, and the results are quite unreadable. The solution typically given is to recursively convert back to a dict for manual inspection. This non-trivial solution is left as an exercise for the reader.
you weren't kidding
 
8:17 AM
you have to rise to the top 4 years late somehow
 
wim
8:33 AM
my robot is bugged for 2 of my 5 tokens and I can't for the life of me figure out why
 
I'm happy to say today's code worked without bugs the first time. Well there was one bug but view spoiler
@wim 5 tokens?
 
wim
auth tokens
 
Oooh, right
 
wim
 
Already part 1? Weird
 
wim
8:41 AM
yeah
this is the input data, would you mind to check?
 
Sure, on mobile though till a bit.
 
wim
thx
 
I get your last line...
Server-side bug?
What are the odds that both of our straightforward solutions bug out surprisingly on the same input?
part1 is very trivial
not to mention that view spoiler
Any chance that your submitter script pairs the answer with the wrong token?
 
wim
no chance, I've been using it all this year
 
There were buggy challenges in earlier years. Have you checked his twitter yet?
 
wim
8:56 AM
hmm I'll check now
 
can't see anything
 
wim
just to clarify, you got 1565 too?
 
9:25 AM
@wim perhaps your reddit commenter is on to something. What if our solutions are wrong and you shouldn't count the initial square, but the other tokens cross the input square anyway? Maybe worth looking at the paths...
You could check by setting a flag that checks if the input square was revisited. If the "good" answers stay and the "bad" answer shifts one: you'll know.
Hmm, but no, first step is always a paint...
 
I have a dictionary containing key value pairs
{'XXX ': 'ABC', 'XXY' : 'ABB'}

I need the dictionary value for a string even if there is a partial match with a key in the dictionary.
Example the key:
string 'XXX LOL' should be 'ABC LOL'

I have tried iterating over the dictionary but that's too long especially when the dictionary is huge and I have millions of string to transform.
 
9:42 AM
Fast, easy, general: pick one
 
Will the keys in the string always be surrounded by space or would a key like 'XXXLOL' also turn into 'ABCLOL'?
 
wim
@AndrasDeak Nice idea. I will check it ...
 
Need it fast @AndrasDeak and not always be surrounded by space so 'XXXLOL' will turn into 'ABCLOL' @Aran-Fey
I have also tried having a pre-processed second dictionary with key lengths and keys and then in the loop compare with keys that have the same length or more
but even that is quite slow, faster than checking every single key still
 
Then all I can think of is to replace your dict with a prefix tree. Like {'X': {'X': {'X': 'ABC', 'Y': 'ABB'}}}. Then loop over the input string and see which substrings exist in that tree
 
wim
@AndrasDeak humm, nope - in all 5 of the datasets the zero position was revisited more than once.
 
9:53 AM
Bah.
 
Hi guys! How do I remove the \ from the strings but still keep the different numbers as strings i.e. '2342342','23423423', '3342324'
https://pastebin.com/igARuk43
 
print(lista_join)?
 
Well, what i actually want is to have a simple web interface with a button which when clicked will execute the python script and display the output in the same page.
The exe file is actually of no use to me but works better for people who dont need to see the code.
 
@Aran-Fey I guess that is an alternate solution but checking each nested dictionary wouldn't that take forever too?
 
Yes, but I can't think of a way to do it faster
 
10:07 AM
:48081138 Yes, that's the output I need but I need to save it as a variable, and a =print(lista_join) is None
 
You already have it as a variable though
namely, lista_join
 
10:27 AM
@AnttiHaapala I certainly can change it, but I still don't see a better solution. — chuwy 1 hour ago
@wim ^
 
yay, active asker after 7 years
 
10:47 AM
@Aran-Fey yes, but then it contains backslashes and I dont know how to eliminate those
 
Nope, it doesn't contain backslashes
I'm guessing you looked at repr(lista_join), but a MCVE would've been nice
*sigh* For the millionth time I wish SO actually had useful Q/A pairs, like this one
>>> text = '"' + "'"
>>> text
'"\''
>>> print(text)
"'
There's no backslash there. But if you repr it, then python displays it as a valid string literal, which requires one of the quotes to be escaped with a backslash.
>>> text == '"\''
True
 
11:07 AM
I see, thks!!
 
11:34 AM
I have a flask app and I need to do some web scraping every 6 hours and put that data into the database, what would I use to achieve this? Celery? Redis Queue?
 
why not use scrapy and run it via cron?
 
because I've never heard of scrapy, I'll give it a go, thanks
well actually it's not really scraping, but accessing an ftp interface
 
then Python's ftplib ?
 
I'll try that, thanks
so should this data gathering part of my app be completely separate from the web app itself?
 
11:56 AM
I'd keep them separate... there's no reason for them to be coupled
 
12:11 PM
Morning all
 
morning... looking forward to Friday? :p
 
Hmm? Something in the circus?
 
No. I'm going to have to tactically vote for the first time in my life and I feel dirty
 
Ah, on Thursday (weird day). Not Friday 13th :P
 
Et tois?
 
12:15 PM
@OldTinfoil in Latin it should be "et tu, puppe?"
 
@OldTinfoil whatever the outcome - I think I'm going to have to make sure I've got a bottle of something strong to consume :)
 
@AndrasDeak bwahaha
@JonClements Definitely.
I've got an unopened bottle of Absinthe from Prague
 
Nice
 
Either way, I suspect it'll be getting opened
 
AAB
12:21 PM
Hi All.
have a question regarding JSON
say I have object as follows
{ "host": { "file1" : "filepath", "file2": "filepath" } }
say this object held by "host" needs 2 values to be added
I just create the property and add them
is this usage fine?
or should I make an array
 
I would use the json library
 
AAB
{"host":[{}]} ??
@OldTinfoil hi
 
AAB
Yes I am using the json library I am asking about the choice
as in {"host " : {}} or {"host":[]}
 
Depends on your requirements. Do you want a list or a dictionary?
 
AAB
12:25 PM
Dictionary
I am new json object
 
Then use {"host " : {}}
 
AAB
so when I add something a property with its value is created am I correct?
This is the way json object was intended to be used rite
I keep confusing this with normal class objects
:P
@OldTinfoil thanks!
 
It's not a case of "it was intended to be used this way" - it's just a way of representing data. If you need to just have a list of items, then you would use []. If you need a dictionary, you would use {}
 
AAB
Got it thanks!
:)
 
Good luck
 
1:02 PM
I realise that this is an open ended question - but why does SQLAlchemy often fail to use an existing index on the database? (I'm using hint(), so I'm not stuck)
Or is it just OldTinfoil related?
 
I wouldn't have thought SQLA had anything to do with that - surely it's just whatever the query planner in the DB is saying?
 
Well, that's what I would have reckoned too. I've got a slow Flask page, so when I installed the debug toolbar to try to profile what was going on
I saw from the explain that the query is resorting to using filesort and thus starting my investigation
 
Umm... maybe a sanity check would be to explain the query that sqla produces directly to the DB? Or just check the query it's generating is sane...
 
1:48 PM
Well that'll be it then. The order by is causing the filesort, as you would expect. I thought that my clustered index would be better than scanning & sorting 3.5 million entries, but clearly sql disagrees with me.
I'm not a DB guy, so it's probably right.
 
@OldTinfoil generally, if the optimiser can work out it's going to have to access most of the table anyway - it won't use an index
 
Well, in this specific case, there's around 150k results
Would it be more sensible to use the index to grab the results, then order it in a subquery?
 
what DBMS is it?
(and what's your query that sqla ends up generating look like?)
 
Not sure what you're looking for. I'm using mariadb / innodb if that's what you mean?
SELECT reading.metric_id AS metric_id, reading.sensor_id AS sensor_id, reading.timestamp AS timestamp, reading.value AS value
FROM reading
WHERE %(param_1)s = reading.metric_id ORDER BY reading.timestamp
 
yup... and what's the index definition?
 
2:00 PM
CREATE INDEX idx_metric_reading_1_ordered ON reading(metric_id, sensor_id, timestamp, value);
 
Umm... so it should be able to use that index if it wanted... just out of curiosity - what happens if you just create a simple index?
 
Well, it uses the index if I omit the order by
So the back-end manager thinks that it might as well do an full filesort rather than using the index to help with the order by.
 
Fair 'nough
 
import csv


list_of_search = []
full_list = []
check_list = []
with open('Report.csv', 'r') as csv_file:
    reader = csv.reader(csv_file, delimiter=',')
    for row in reader:
      list_of_search.append(row[1])
      search_list_lenght = len(list_of_search)
      for index in range(search_list_lenght):
        list_by_word = list_of_search[index].split(',')
        list_by_word_length = len(list_by_word)
        for counter in range(list_by_word_length):
          full_list = list_by_word[counter].split(',')
any Idea how to make it more efficent?
efficient*
 
2:18 PM
Define efficient
Ie - "it's taking too long" -> How long is it taking now, how long does it need to take?
 
it takes too much time, still running and repeating it self
 
@Pooya what is that code trying to do? It looks a little convoluted...
 
second column of csv file include string like that => alternative,key,accounts,channel,sales
I have to grab each string and check how many time it repeats
grab each word from the row and check how many times it repeats
 
eg: why are you looping over everything in list_to_search more than once...?
 
because each row contain multiple string and that's the only way I knew to distinct them from each other
 
2:29 PM
why do you search through all rows in list_of_search instead of just the current row?
 
I''m guessing you're after something like:
 
you keep reprocessing each line again for each following line. Your algorithm is at least O(n^2).
 
import csv
from collections import Counter

with open('Report.csv') as fin:
    csvin = csv.reader(fin)
    rows = (row[1].split(',') for row in csvin)
    counts = Counter(word for row in rows for word in row)
 
@JonClements May I ask you please explain the last line for me
 
Counter or the generator expression?
 
2:34 PM
would be great if you can tell me both because I do not get it
 
... for x in y for z in x is equivalent to for x in y: for z in x: ...
 
@JonClements Now I get it, thanks a lot Jon
@Aran-Fey Thank you so much
 
@Pooya did that give the result you were after?
 
morning cbg
o/
 
2:43 PM
o/
 
@JonClements There is a thing, it shows how many time each string is repeated
 
@wim "has a bug that he's overlooked" - can you back up that assertion?
 
@PooyaPanahandeh ?
 
@smci I don't really like the question, "What is the best way to implement nested dictionaries?" to be honest, it's the sort of construct that's likely to give you more problems than it solves.
 
I mean it shows like blow :
'Powerful': 1, 'PR25': 1, 'preise': 1,
and as I checked with the document you sent and also the excel file it means Powerful repeated once.
 
2:47 PM
yeah... is that not what you're after?
 
@AaronHall smc's question, or the question in the post?
 
it's what I want exactly
 
@Arne has to be the latter
 
let me clarify.
 
ah, and "construct" is the autovividict, I got it.
 
2:49 PM
mod power display :P
 
I only ever use the .setdefault method.
 
I don't think I've ever needed a nested dict outside SO
then again my problems are usually more of a 4d-array-of-doubles (or double complexes) kind
 
^^same
 
I haven't used it in a long time.
 
I'm suddenly reminded of that "classes are pointless, just use dicts instead" reddit post I read a while ago... that was one heck of a read
 
2:54 PM
In a crackpot sort of way or not?
 
The usage is when you're recursing something and creating a recursive data structure that isn't the final result (maybe you have redundant keys or something and need to merge the values from the keys). There's probably better ways to represent the control flow or semantics...
 
getting the right information out of an arbitrarily deep nested dict is probably about as hard as the initial problem, so I'd agree
 
it does help with the cursing
 
@AndrasDeak they were serious about it, if that's what you mean
 
for these kinds of problems, I find myself using NamedTuple a lot lately. Always hated them, but annotations made them really pleasant to use.
 
3:00 PM
@Aran-Fey crackpots are always serious. The question was whether it made sense :)
 
grammatically? Yes. Otherwise? No :P
 
I was reading something (a twitter post?) recently about how "being right is the currency of IT" - how we'd rather work with a jerk (to an extent) who is always right than a nice guy who's always wrong.
 
sounds dubious to me
 
It rang quite true with me. I think it's interesting to talk about. I want to be the always right nice guy, myself.
 
it sounds more like justification for smart jerks to keep being jerks, "because I'm always right"
the two don't have to go hand in hand
If you're a psychopath it might make sense, but otherwise one can be right and strive to handle people well. So not sure how it's the "currency of IT".
 
3:04 PM
It's also why we don't like being wrong.
If we're wrong, we lose face becauses we look less reliable.
And we're worried that people might not want to work with us after realizing we're wrong.
 
hmm, I might be in the minority, but I don't mind much being wrong as long as it doesn't lead to being a nuisance for my peers
at least, that's how I perceive myself. I might be wrong in that, too =D
I only lose face if my jokes fall flat. can't stomach that at all
 
I was very sensitive to this in grade school even. Even then it was more important to me that my classmates could get correct information from me than that they liked me. And it hurt me when they didn't like me.
 
@AaronHall I don't agree at all. Most people don't like being wrong because it sucks thanks to cognitive dissonance. Your implicit assumption is that you are smart and infallible. Any proof of the contrary causes you mental distress. I think it's an unhealthy thing to fear being wrong for what it might make others think about you. Intelligent people are aware that to err is human, so being wrong is fine if you own them and try to do better.
My bottom line is always that you shouldn't position yourself in the world with respect to other people. Especially not by trying to justify your self-esteem based on the opinion of others, nor to position yourself somewhere by pushing others down.
 
I have to be ok with being wrong - so that I can correct it. I hope all my answers have correct information, and if you see anything incorrect, please let me know. I'll probably fix it within the day.
 
(general "you" all the way, of course)
 
3:12 PM
Worrying that people might not want to work with you if you're wrong sounds... exhausting
 
I imagine it's only a problem if you're an extreme narcissist or a psychopath :) Healthy self-esteem should balance such urges. "Keep in check" is probably better phrasing.
 
Guys I have one more question, I tried to write in csv file and get this error, already google it but the solution wasn't work
error is: a bytes-like object is required, not 'str'
 
Sounds like you opened the file in binary mode for some reason
 
@PooyaPanahandeh how did you open the file?
 
with open('output.csv','wb') as result_file:
        wr = csv.writer(result_file, dialect='excel')
        wr.writerow(counts)
That's how I tried to open file and write on it
 
3:21 PM
Do open('output.csv', 'w', newline='') instead
 
if I print the counts, I will get result like 'Speed': 1,
 
But now getting just word like spead
 
@PooyaPanahandeh please also take a look at the csv manual, which tells you how to do this, amongst other things.
 
And how do you want the csv file to look?
 
3:24 PM
Today's AoC seems fairly straightforward, what's hurting my brain a little is managing the direction changes. Hmm.
 
@PooyaPanahandeh you need a dict writer to write a dict
 
I got it now, let me check, Thank you so much for your help
 
or you should explicitly write the dict items (the default is just the keys)
with open('output.csv', 'w', newline='') as result_file:
    wr = csv.writer(result_file, dialect='excel')
    wr.writrerows(counts.items())
 
    :48085588 sorry for taking your time, but it's what I want to write into csv file :
    {('Wwwxxx': 1, 'Xxl': 1, 'MF112': 1, '•Ecosystm': 1})
and with your solution get The following error:
Traceback (most recent call last):
  File "main.py", line 13, in <module>
    wr.writrerows(counts.items())
AttributeError: '_csv.writer' object has no attribute 'writrerows'
 
typo. You have an extra "r" in "writRerows"
 
3:37 PM
@Aran-Fey yes, you right, thanks a lot
Thank you so much guys, for sending me the doc link and answering my question, thank you so much
 
I want to do a direction switch using a dict, why can't I just write lambdas instead of functions?
 
direction switch? You mean new_dict = {v: k for k, v in old_dict.items()} ?
 
@JonClements no I mean slight spoiler?
 
@AndrasDeak If such a person is making no apparent effort to improve and consistently giving wrong information, everyone will eventually lose patience with that person, stop using them, and when it becomes apparent that they are expensive and creating no value, they'll be fired.
 
@toonarmycaptain ahhh okay
 
3:50 PM
@toonarmycaptain because you wrote lamda, not lambda
that's also why you get a SyntaxError
 
that's only 50% of the reason though
 
true that...
 
@MisterMiyagi smh
 
lambda does not allow statements, including augmented assignment statements
with 3.8, you should be able to write 0: lambda: self.x := self.x + 1 etc.
though I'd recommend working with numerical coordinates.
 
@MisterMiyagi What do you mean?
 
3:56 PM
complex numbers can be nicely abused to represent 2D coordinates
 
@toonarmycaptain use a two-dimensional list/tuple as coordinates so that you have 0,1 instead of x, y
then you can do self[axis] += distance for e.g. axis, distance = 0, -1
or as @Aran-Fey suggested, use a single complex coordinate, so that e.g. self.y += 1 becomes self += 1j.
 
4:11 PM
@MisterMiyagi Ah. But apparently it has to be lambda: (assigment:=expression) But also, unless I'm doing it wrong, it's not going to let you because the lambda doesn't have access to the scope where self is defined?
@Aran-Fey I've thought about this. It's been so long since I've used complex numbers though. I'll try it :)
 
4:24 PM
@toonarmycaptain I don't have 3.8, so I can't verify whether := needs parentheses or not. In any case, the lambda does not assign to self, only to one of its attributes, which is fine.
self is available as a closure of the lambda
plus, := works in the containing scope, so it should be possible to re-assign regular targets (including self). Feel free to try. It's not going to be useful in your case, though.
 
I'm pretty sure assexps can only assign to simple identifiers, so (self.x := y) is out
>>> (x.y:=1)
  File "<stdin>", line 1
SyntaxError: cannot use named assignment with attribute
python.org/dev/peps/pep-0572/#syntax-and-semantics indicates that the syntax is NAME := expr
 
that's mildly disappointing
 
@MisterMiyagi It works outside a class, but within it says unresolved reference x_position for class dict. I guess the lambda presumes the self. in self.x_position refers to the dict?
 
It's not that it can't figure out what self refers to. It knows what it refers to, but refuses to perform a setattr on it.
... Unless you're getting an error other than SyntaxError: cannot use named assignment with attribute, in which case I'd be quite interested in an MCVE
 
4:39 PM
"unresolved reference x_position for class dict" doesn't make any sense for the case. It should be a SyntaxError (as per what Kevin said), no chance to execute it.
 
@MisterMiyagi Well that's what pycharm says. When I tried it in the interpreter it did say SyntaxError.
 
@MisterMiyagi I'm conflicted, because on one hand, I'm an adult and should be able to do named assignment with attribute if I want. On the other hand, assexps are potentially very good at shooting people in the foot so maybe we should curtail their power just a little bit.
 
I solved Day 6 this morning in the shower!
well, part 1
 
But it says Invalid Syntax, without further explanation.
 
If you're still playing around with your previous code, self.move: dict = { is probably a syntax error for the same reason that {1: foo = 23} is a syntax error
 
4:47 PM
@Kevin I haven't bought into the "asspressions are just sometimes confusing" wagon from the start. There is no way to objectively separate these cases (see PEP 572, even). So for me it's either all in or withdraw. The current asspressions being neither here nor there is just another reason for me to avoid them out of principle.
 
@Kevin Isn't that a valid type hint by any chance? I'm more worried by the lack of b in lambda
 
yeah, it's a type annotation
 
I notice that in the language grammar, the ":=" token is always preceded by test, not NAME, so as far as the ast parser is concerned, an assexp's left hand side can have anything that may appear on a regular assignement statement's left hand side. So the code must be going out of its way to forbid non-name targets. Perhaps this is an indication that assexps were implemented in a way that would make it easy to remove this restriction
 
Can someone help me write a function for sorted() ? I have an list with objects and need to sort that list based on the distance between the element's object.id's. The first element of the list needs to be fixed at it's position and cannot move anywhere else.
 
@RandoHinn side note: if it looks like [1, 2, 3] it's a list, not an array
 
4:50 PM
In other words, maybe the language devs are taking a "wait and see" approach. First determine how frequently the average user shoots themselves in the foot with name-only assexps. If there are few injuries, then permit arbitrary targets.
 
I don't know why the date is saved locally to csv as symbol of "#" but if i uploaded the csv online to view it. it's shown normally. here's my code pastebin.com/uMs3ancj and here's when i uploaded it online. sharecsv.com/s/a25ee87f972d5aa8e9f33458239166a6/output.csv
 
@AndrasDeak dangit, noted..
 
@Kevin Ah. When I do lambda: (self.xy := self.xy - 1) instead of lambda self.xy: (self.xy := self.xy - 1 it gives exactly the error you indicated
 
@RandoHinn So, something like sorted(stuff, key=lambda x: abs(id(x)-id(stuff[0])))?
 
4:51 PM
@RandoHinn and you should write something like def dist_from_first(obj): return distance(obj.id, fixed_first_obj.id), where fixed_first_obj is in the enclosing scope
 
@RandoHinn do you mean pairwise distances or the distance to the first element?
 
@MisterMiyagi pairwise
 
@RandoHinn then the question is unclear to me
 
But ok. I'm going to use the complex method instead and see how quickly that bites me due to ignorance ;)
 
@toonarmycaptain that's because in your second case, self.xy is used as a parameter name. These must be regular names.
 
4:52 PM
Hmm, I think I have misunderstood what "id" means in this context
 
def foo(self.xy, b): ... isn't valid either
@RandoHinn then sorting them doesn't really make any sense. sorted is meant to establish some total or partial order of a collection. pairwise distances are not an order of a collection.
 
In other words, pairwise distance has "two legs": distance of "this" from "that". For sorting a list you need something with "one leg": the value of "this".
 
Let me rephrase this then
 
@αԋɱҽԃαмєяιcαη this looks relevant: help.turbolaw.com/hc/en-us/articles/…. TLDR: it's a problem with excel
 
Alright got it.
thanks @Kevin
 
4:57 PM
Q: is there some efficient way to "peek" at the return type of a callable that I'm going to call often? I'd like to remember the result and use an optimised path for further calls.
my problem is that I have a Union[Callable[..., T], Callable[..., Awaitable[T]]] (i.e. I may need to use await foo() instead of foo())
 
@MisterMiyagi sounds like JIT compilation which needs a call or prior info
Or is this just some weird caching?
 
"Don't worry, type annotations won't have runtime significance", they told me...
 
@AndrasDeak is there a difference? :D
 
not sure
 
@Kevin actually, if I could trust annotations I would not have that problem :/
but as it stands, I only find out the type after the first call
 
00:00 - 17:0017:00 - 00:00

« first day (3343 days earlier)      last day (1598 days later) »