« first day (2777 days earlier)      last day (2396 days later) » 

 
1 hour later…
user8177336
01:29
hey guys, when I make a thread and run a function that uses the matplotlib module, I get the following error message....I have no clue why. I searched multiple times on google and could find no solution. please help
user8177336
2018-05-23 20:28:01.161 Python[915:64414] WARNING: nextEventMatchingMask should only be called from the Main Thread! This will throw an exception in the future.
2018-05-23 20:28:01.161 Python[915:64414] *** Assertion failure in +[NSUndoManager _endTopLevelGroupings], /BuildRoot/Library/Caches/com.apple.xbs/Sources/Foundation/Foundation-1452.23/Foundation/Misc.subproj/NSUndoManager.m:361
2018-05-23 20:28:01.166 Python[915:64414] *** Assertion failure in +[NSUndoManager _endTopLevelGroupings], /BuildRoot/Library/Caches/com.apple.xbs/Sources/Foundation/Foundation-1452.23/Foundation/Misc.subpro
user8177336
just to clarify, i ran the functio through the thread
wim
wim
02:06
@coldspeed blast from the past. I actually had an upvote sitting on it.
02:16
Does anyone have a bit of experience with Scala?
How exactly does the => operator translate to Python?
user8177336
do u mean >= ?
user8177336
@Annabelle
user8177336
oh sorry
For example I have this:
  def makeIndex(langs: List[String], rdd: RDD[WikipediaArticle]): RDD[(String, Iterable[WikipediaArticle])] =
  rdd.flatMap(article => {
    findLanguages(langs, article)
      .map(lang => (lang, article))
  }).groupByKey
Was wondering what the => meant.
user8177336
02:19
=> is syntactic sugar for creating instances of functions. Recall that every function in scala is an instance of a class.
Yes, I saw that. But I don't seem to understand it properly. :(
Thank you though!
user8177336
@Annabelle it means that if i have Int => String into a function, then i will input a integer into a function and get a string as the output
user8177336
does that make sense
Hmm okay. So..
I get the concept, but now I don't get how it works in the example I have.
user8177336
02:27
Hey guys can somone help me with the python error up there that i posted please ^^^? I realy need help and i cant find anything that helps on google
@BOi did you see this (not sure if it will help): stackoverflow.com/questions/30997347/…
user8177336
yeah im not on fullscreen. it still doesn't work
user8177336
python launcher keeps quitting on me for some reason so the code doesn't finish executing @W.Dodge
Maybe a question on the main board is in order. Might get a few down votes (not sure it would really) but it will be worth it for the answer
user8177336
02:43
@W.Dodge good idea. ill just wait for like half an hour and post it cause im working on something else and i'll need to post a really well asked question to not get downvotes :)
@BOi Good Luck! found one more: stackoverflow.com/questions/32019556/…
user8177336
@W.Dodge Thanks for the help mate. I already saw that and i tried it. python launcher does nothing this time. i have no clue what in the world is happening. anyway, thats no problem. thanks again for trying to help me out
How is numpy.ufunc.reduceat used?
Why is the indice-rules such defined?
Is there any post that visualize it?
e.g.
In [65]:
np.add.reduceat([0,1,2,3,4,5,6,7],[4,1])
Out[65]:
array([ 4, 28])
03:03
Did you read the description in the docs? numpy.ufunc.reduceat
So for your example, since 4 > 1, the first slice that is summed over is just the element at index 4, which is 4. Then the second slice is from index 1 to the end of the array.
I did, but still confused...
I need to understand an answer people gave me, and he used this function,
but the array of concern is of higher dimension (>=3)
In [87]: np.add.reduceat(arr, arr) # single element slices
Out[87]: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

In [88]: np.add.reduceat(arr, [5]) # one slice - index 5 to the end of array
Out[88]: array([35])

In [89]: np.add.reduceat(arr, [3, 9, 6]) # - arr[3:9], arr[9], arr[6:arr.shape[0]]
Out[89]: array([33,  9, 30])
Ah sorry, that's with arr = np.arange(10).
@miradulo Oh only the first one is reasonable for me... Is that always a [-1] appended to the end?
I meant your saying # one slice - index 5 to the end of array
03:16
From the docs: when i = len(indices) - 1 (so for the last index), indices[i+1] = a.shape[axis].
I don't understand that part of the docs...
So the last reduction is always from the last index passed to the end of the array, along whatever axis the reduction is being applied.
Is that axis always a fixed value?
And I have another question, is that the indices in the docs means numpy.indices?
Yes. Defaulted to 0.
ohhhhhhhhhhhhhh
I got it
so a.shape[axis] is the length of that dimension?
03:21
The indices parameter is anything array-like, so you can pass a list as I was doing, or a NumPy array or what have you.
and yes! Construct some higher dimensional arrays and inspect the .shapes if you're not totally comfortable with it.
thank you so much I think I'm approaching it...
but I still hate high dimension arrays
Yeah, they take some getting used to. If you want to read some interesting NumPy answers Divakar has taught me a lot through theirs.
@miradulo appreciate your time, if you want to listen: my mood now
Ok I'll read it
Ha, no worries :)
I think only genius use numpy... but I'm stupid
03:31
@Niing I use Numpy... theory disproven!
The one know more are (probably) always modest. (but i have met some are not, lol)
03:52
lol, I just found that I should first read about numpy.ufunc.reduce then go on to .reduceat...
04:50
Morning cbg
 
1 hour later…
06:15
Oh the joy of SfB telcos. Apparently there should be a presentation going on, but all we're getting is a black screen.
cbg
@IljaEverilä I don't think I can recall a single instance where telcos just worked and were an enjoyable experience
You'd think that problem should be solved by now, but they are like printers
except that not even big corporations have good ones =/
The bigger the corp, the more horrid the telcos.
Not having them any more was one of the benefits of leaving BigCorp I didn't even know I was getting :D
Cabbage
This seems off-topic to me, maybe "too broad". I guess it's pretty harmless, though. stackoverflow.com/questions/50502103/…
06:53
stackoverflow.com/questions/50498337/… too broad, lacks minimal understanding, and half of the question is a dupe
what's going on here? Hours and not a single decent answerable question?
I know, right? Are all the school kids on break or something? Where are the easy questions that attract unreadable one-liner answers?
Oi I said decent
this was nice... I liked this
Oh, right. I guess my standards are pretty low nowadays ¯\_(ツ)_/¯
I shouldn't complain... you have a hammer and you're actually more active answering... should count my blessings ;)
07:06
I got used to the hammer pretty quickly. Wouldn't want to live without it anymore
It's a bit sad that your blessings can be counted with a 2-bit integer though :^)
meh, could be worse :p
There've been a lot of questions where the answer is just "use a dict". Do these people not learn the basic data structures? This guy is struggling to do an O(n) operation in O(n log n).
> This question has never been asked here.
:I Right. You're the first person to ever need a dict, buddy.
cbg
07:25
heh. In all fairness, the sorting step for that initial L1 and L2 remains
The time complexity of the code generating the input doesn't count :p
Btw, you should consider putting some empty lines in your block of code and comments. It looks a bit overwhelming the way it is right now
question
@coldspeed why do you favor itemgetter over key=lambda ...? Is it faster?
sure, is that better now?
:thumbs_up:
07:30
@Arne yes, avoid lambdas where possible. Always try to pass named function callables, they do the same thing, but better
TMYK 🌈🌟
Thanks both, for the comments
hey guys (coldspeed, what happened to your avatar)?
it is no longer that black and white squarey thing
I'm trying to import a file lib
it's callled
ssh-rev3.py
So I'm doing this
import ssh-rev3
but it does not take the hyphen
did you try import ssh_rev3?
hyphen is a disallowed character in many naming schemes, and some packaging tools will silently change them to underscore
07:38
@Arne that what I was thinking
very simple stuff but until you do it yourself, you don't know it
@Mulliganaceous you know, you can change it
Is your last one the default one? Yours look kinda black and white
I also changed mines. It is so green and light
Found something bizarre
In [266]: Counter({'both1':1, 'both2': -200, 'only_y':203 }) + Counter( {'both1':5, 'both2': 400, 'only_y':13 }) + Counter({'both1':0, 'both2':2,
     ...:  'only_x': 100 })
Out[266]: Counter({'both1': 6, 'both2': 202, 'only_x': 100, 'only_y': 216})
This works
But not this
In [267]: x
Out[267]: {'both1': 0, 'both2': 2, 'only_x': 100}

In [268]: y
Out[268]: {'both1': 1, 'both2': -200, 'only_y': 203}

In [269]: z
Out[269]: {'both1': 5, 'both2': 400, 'only_y': 13}

In [270]: sum(map(Counter, (x, y, z)), Counter())
Out[270]: Counter({'both1': 6, 'both2': 400, 'only_x': 100, 'only_y': 216})
"both2" should not be 400 (it should be 202)
It's because adding two counters removes elements with a count <= 0
wtf that is so unintuitive
why does it work the first time though?
07:49
wild guess: addition is evaluated right to left, so it never drops below 0
oh, so it is. The order is different across the two methods
good catch
>>> Counter(a=-2) + Counter(a=5) + Counter(a=1)
Counter({'a': 4})
>>> Counter(a=1) + Counter(a=-2) + Counter(a=5)
Counter({'a': 5})
^ MCVE :P
...Had I known the order matters
oftentimes coming up with the best MCVE means knowing why your problem occurs... which implies you know why/how the problem is caused and needn't have asked anyway XD
Although Counter does support negative counts, it's mostly designed to handle non-negative counts, and you often have to do convoluted stuff to make it do what you want with negative values.
honestly, if it does implicit things like dropping keys, it should not allow negative ones at all. But I guess backwards compatibility forces it
07:55
So if you combine Counters using - you lose negative results, you have to use the explicit .subtract method.
08:06
@Arne Definitely! itemgetter is quite efficient, and it's a C function call, which is always faster than a Python function call, since Python function calls have more overhead than C calls.
Another common "avoid lambdas" situation is writing a lambda just so you can use it with map, instead of using a simple expression in a gen exp or list comp. Eg,
map(lambda x: x*x + 1, range(5))
# instead of
(x*x + 1 for x in range(5))
Of course, if the expression is complicated, and you already have a function defined for it, you might as well pass it to map, rather than calling that function in a gen exp. The point being that we want to avoid unnecessary Python function calls.
08:28
I am bad at hitting the repcap
180 yesterday again
in pandas I can do df.amount but not df."t time". Can you use names with spaces this way?
Yes, but you need to use dictionary syntax. df['t time']
@roganjosh oh ok. So it's just not possible to use it as an attribute. Thanks
And, for the sake of sanity, I really dislike df.amount syntax because it's possible to chain a lot of operations in Pandas so I find it helps with understanding to use df['amount'] but that's personal opinion :)
:)
08:37
@Anush it is not possible to use 'foo bar' in python as an attribute
except you could have success with getattr(df, 'foo bar') in general case :P
@AnttiHaapala thanks
Hey guys, just a question. Why are processes tend to be used for heavy workloads? Why aren't threads used for heavy workloads?
I've been trying to search for an answer around the web but can't.
@SeanFrancisN.Ballais it is because CPython does allow threads to run concurrently but not in parallel
08:44
Primarily because of the global interpreter lock
but even then there is a bad gotcha, the default setup of multiprocessing is very dangerous in Linux/Unix :P
I get that since it's a CPython limitation, but what about in a general case? Outside Python, why would one use processes over threads?
@AnttiHaapala, it is??? How come?
@SeanFrancisN.Ballais It's not just about how heavy the workload is, but how it's distributed. If it's CPU-intensive, then you pretty much need multiprocessing. However, if a lot of the workload involves waiting on IO, then threads may be fine, since throwing more cores at the work isn't going to make the IO happen faster.
@SeanFrancisN.Ballais multiprocessing in default settings will use fork to launch the new processes, and continue executing a copy of the python process in there...
however the problem is that fork is inherently unsafe in programs that use threads.
and in Mac for example there are system libraries that use threads without you knowing :P
for example to resolve DNS queries... so if you use multiprocessing in a program that also uses DNS you're open to all sorts of deadlocks
the solution is to force the use of the same kind of launch that is used in Windows, on Linux, Mac too
Ohh
@PM2Ring, why would a CPU-intensive task multiprocessing? Couldn't just we give it more threads? This is assuming that we are outside of Python.
08:52
why does my smtp email code in python not show to address ?
@SeanFrancisN.Ballais 1) more control over where each process is run 2) if there is no need to share resources, processes are a cleaner cut and avoid all bugs that may arise in a shared memory space
    from email.mime.text import MIMEText
    username = "[email protected]"
    password = "*******"
    fromaddr = "[email protected]"
    toaddrs = ['[email protected]']
    server = smtplib.SMTP ("smtp.gmail.com",587)
    server.ehlo()
    server.starttls()
    server.login (username,password)
    emailBody = msg
    msg = MIMEText(emailBody)
    import socket
    ip=socket.gethostname()
    msg['Subject'] = "My subject %s" % (ip)
    msg["From"] = fromaddr
    #msg["To"] = toaddrs
    server.sendmail (fromaddr, toaddrs, msg.as_string())
@Arne, "more control over where each process is run" is pretty interesting. Can you elaborate more on that?
@SeanFrancisN.Ballais Sorry, I was just talking about Python, where all threads run on a single core. And if each thread needs lots of CPU power then creating more threads isn't going to speed up the task, and in fact the extra overhead of thread handling gives the CPU even more work to do.
@SeanFrancisN.Ballais I am not 100% on this, but as far as I understood threads vs processes, starting a new process will ask the os scheduler which core is available for work, and put it there. The same is not necessarily true for threads, because [my knowledge fails me here, but if it is true it has probably to do with the constraint of sharing resources]
09:00
@Arne I see. Since threads share the same memory space, it would prolly be harder if they were run in different cores?
@PM2Ring, I don't quite understand why creating more threads isn't going to speed things up.
618
A: What is the difference between a process and a thread?

Scott LanghamProcess Each process provides the resources needed to execute a program. A process has a virtual address space, executable code, open handles to system objects, a security context, a unique process identifier, environment variables, a priority class, minimum and maximum working set sizes, and at ...

@SeanFrancisN.Ballais If a thread is CPU bound then any time spent running other threads is lost to it. If you had (say) four CPU-bound threads running in a single process there could not be any overall speedup.
@SeanFrancisN.Ballais Can I link you to a conference that explains this perfectly ? It's Robert Hettinger that explains it, it should motivate you just for this.
@IMCoins, that'll be helpful, especially in preparation for my exam tomorrow.
09:05
@holdenweb I'm not sure that holds outside of Python. And within numpy it's possible to specify the number of threads for MKL
@holdenweb, that would relate to how a process is scheduled? I was looking for something outside Python.
@IMCoins, not sure if that will hold outside Python but I'll take a look into it.
This conference is priceless in my opinion. But a bit boring after 45 minutes. I nearly fell asleep at that time. ;D
@roganjosh It holds for any process where all threads are run on the same CPU. Numpy takes special measures to break out of this restriction to run compiled code that is known to be thread-safe, I believe.
@holdenweb any process within python. Sean is talking more generally. And yes, numpy releases the GIL
@SeanFrancisN.Ballais It relates to how the threads are scheduled within the process, I believe, and is specific to the implementation. I don't think either Iron Python or Jython use a GIL.
09:08
@holdenweb, then I guess that's Python-specific. Was looking for something more general but thanks though.
Outside Python (dreadful thought!) the advantages of multiple processes are in address space separation - it's impossible for processes to interfere with each others' memory, while threads, being all part of the same process, share a virtual address space and thus can accidentally (i.e. when not programmed carefully enough) overwrite each others' memory.
Also, multiple threads all contribute towards their process's resource limits.
So if each thread (say) wanted to open thirty network sockets, and you had 20 threads, you 'd need to be able to have 600 files running at the same time. Some systems have per-process limits on such things.
@holdenweb, "dreadful thought!" Haha. Are processes terminated if they reach the resource limit?
How about in CPU-intensive cases, can you provide an example?
From what I have read and understood, Threads are useful to convert synchronous code into async code in a fast way.
But if you code from scratch, the best is to use async functionality and not threads. Because it's faster, and less dangerous as you explained with the overwrite of each others' memory.
Correct me if im wrong. ;d
how do you invert a regex? Say we have cliffordpat = r'CLIFFORD'
df[df.Transaction_Description.str.contains(cliffordpat)]
But I want to extract all the rows that don't contain cliffordpat
How do you do that?
I had a vehicle routing server that I used to hammer with requests to build distance/time matrices. At first I didn't use a Session and the code would crash out with a systemerror because I ran out of ephemeral ports
So I don't see why threaded code would be any different if you exhausted some system resource
09:19
@Anush There is no simple operator to invert an arbitrary regex
Then I switched to a routing engine build in C++ that allowed single calls for a matrix and spent an entire day trying to disprove that it gave the correct answers because there was no way on Earth it could be running so fast :P
@Arne hmm..
in this case it's an exact match
I mean grep can do it :)
grep -v
@roganjosh, interesting but I'm still trying to understand.
Well, yeah, the last comment wasn't relevant :)
23
Q: Reversal of string.contains In python, pandas

Xodarap777I have something like this in my code: df2 = df[df['A'].str.contains("Hello|World")] However, I want all the rows that don't contain either of Hello or World. How do I most efficiently reverse this?

Your question is a dupe. In your case, it seems that using the ~ operator is enough using pandas and str.contains
jpp
jpp
09:35
cbg all
@IMCoins Thanks! So much easier than I realised
jpp
jpp
How do you handle a question such as "how can I optimize list.append(0, something) by using a single list comprehension?" I feel an answer which uses a list comprehension is ultimately a bad answer.
I just read an odd comment. Is his confusion possibly due to Pandas syntax?
Another thing: Shouldn't the max be inside: key=max(os.path.getmtime)Anton vBR 1 hour ago
@jpp Huh? That looks like a TypeError: append() takes exactly one argument to me.
@jpp He probably meant insert().
jpp
jpp
sorry list.insert(0, something).
But still the same question.. I mean this question has upvotes, the list comprehension has 7 upvotes, but ultimately I have this feeling inside it's a bad Q&A
I'd hate someone learning list comprehension to come upon this as a valid use.
09:40
I don't get what the use of a list comprehension is. Is there a %timeit?
Well, wouldn't iterating in reverse through the list and appending be faster than inserting all the element as first item ?
jpp
jpp
The questioner doesn't mention performance in the question, but he does in the comments.
Ah, rightio. Yes, a list comp is probably a dumb solution. And generally you don't want to insert at the start of a list if you can avoid it. And you especially don't want to do that in a loop.
jpp
jpp
This is the last thing I'd want to show anyone learning Python
Forget about last, probably hide and never mention its existence
09:42
Do we have a canonical dup for "replacing a slice of a list with another list", i.e. slice assignment?
@SeanFrancisN.Ballais Don't think the process is terminated - attempts to use an unavailable resource will simply fail.
@jpp Ok. I haven't looked at the answers yet, but the OP's solution #1 is better than solution #2. #1 temporarily uses a little more RAM, but it's faster.
@holdenweb, I see. But wouldn't that behaviour be OS-dependent?
@roganjosh Conciseness of expression, though it's often a judgement call.
@SeanFrancisN.Ballais Naturally it will be - each environment is different.
jpp
jpp
@PM2Ring, Yeh I think the question is valid (but not great) because many green beans come upon the magic of list comprehensions and look to use it everywhere. But any answer should at least mention this isn't a good use of list comprehensions.
09:45
@holdenweb oops, you've read it out of context, I should have made it clearer. jpp was talking about a user asking a question about using a list comprehension instead of .insert()
@jpp Yeah. People think that just because list has an .insert method it must be ok to use it. ;)
jpp
jpp
@PM2Ring, Haha, fair enough. I think a lot of the time they read somewhere "list comprehensions are efficient" and take this to mean "list comprehensions are always efficient for any imaginable task and can overcome any inbuilt time complexity constraints to give you O(1)".
@jpp Interesting. I'm surprised that the OP's solution 2 is slightly faster. L3viathan's code isn't evil, but it's a little slow due to the gen exp overhead.
@jpp Indeed. Several of my answers / comments contain the phrase "list comprehensions aren't magic". :) OTOH, they do use a special LIST_APPEND bytecode, which is faster than calling the .append method in a loop.
@roganjosh Right - in that case the OP is an inexperienced programmer with a shiny new toy!
"List comprehensions are good, so I must use them for everything." When you only have a hammer ...
@jpp What are the timing like with a smaller list, say a = ['orange', 'apple', 'banana']*100 ?
09:56
Well they do facilitate cramming more code on a single line and everyone knows that the more you can get in a single line, the faster it will run :)
Every time I see some overly complex list comprehension employing itertools I do a quick local test with %timeit. In almost every case it's demonstrably slower than the less "fancy" solution.
jpp
jpp
@PM2Ring, %timeit l3v(a) # 81.9 µs
%timeit jpp(a) # 68.3 µs
%timeit original(a) # 64.7 µs
%timeit original2(a) # 64.2 µs
@roganjosh Yup. People worry too much about execution speed, when most of the time it simply doesn't factor. It's much easier to speed up a correct, slow program than it is to fix up an incorrect, fast one.
@jpp Yep. That gen exp has a lot of overhead. And your solution is a bit slow due to copying back & forth with that deque.
jpp
jpp
@PM2Ring, Yep - of course. It's only useful if you're repeatedly appending to the left (which I tried to explain).
@PM2Ring, and if you're not repeatedly appending to the left, it's unlikely to be your bottleneck.
True. You did explain it, but of course the test doesn't demonstrate that feature of deque. FWIW, deque is also faster than list when you're using it as a stack, appending (and popping) on the right, which surprised me when I learned about it.
jpp
jpp
10:07
I thought the benefit was much smaller to the right
since list usually keeps some spare space at the end for additional elements
BTW, Knuth actually said: "We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil. Yet we should not pass up our opportunities in that critical 3%."
OTOH, it's good to have a general feel for which stuff is fast and which is slow, so you use the appropriate constructions for the job at hand. Eg, build a list from left to right by appending rather than right to left by inserting.
but you need to be Knuth to know that 3%
cabbage
Or you follow holdenweb's advice, and write a clear, correct program. Then when you're almost done, profile it with realistic data and see if there are any spots in the program that are worth trying to optimize.
jpp
jpp
@PM2Ring, Yes, let's call that mature optimization
10:14
it's just "optimization"
jpp
jpp
Ha, but adding the epithet also allows to provide a snarky reference against doing things prematurely ;)
10:27
@pythonRcpp you seem to be creating just a MIME part, not a message
if there is just a single part, you don't need to create a separate MIME structure anyway
do you specifically need to use server.sendmail(), I recall it's only there for legacy reasons?
Is this new? I just saw a page where the highest voted answer is above the accepted answer! stackoverflow.com/questions/31917595/…
5 messages moved from #!/bin/bash
It's a few months new, I think :p
@Aran-Fey Thanks. It must have happened while I was absent.
DSM
DSM
@tripleee: eh?
10:34
@DSM not a Bash question by any stretch; pythonRcpp is fairly regular in this room too so it felt sensible to move the discussion here
am I not supposed to do that?
FWIW we've done similar before (and got bashed for it;)
DSM
DSM
It's fine to move a conversation here in the general sense, i.e. "hey, take this to the Python room, this is #!/bin/bash", but in the literal sense I think it's only a good idea if what you're moving is self-contained. For my part I can't figure out what the question is from what you copied, so I'd probably have deleted it and asked the OP to repost.
the main problem is that moved messages retain their original time-based position in the transcript
2 hours ago, by pythonRcpp
why does my smtp email code in python not show to address ?
I guess it make sense, but the first message in the series is hiding up there ^
DSM
DSM
Ah, so I have to read way up in the history to find the question? That explains my confusion.
10:39
yup
my reply is linked to the question, but yeah, that's a bit fugly
So I also suggest a softer solution next time
sure, okay, thanks for the feedback
DSM
DSM
SO's chat implementation is a little lacking. :-/
Slack does a better job of code formatting, too..
at least we have formatted links here... \o/
10:43
I'd be happy if inline (backticked) code in chat was a little more visible, eg with a slightly different background color.
DSM
DSM
But isn't that backwards? SO should be good at code and bad at links, and Slack the reverse.
I want to be able to mix and match text and code without having to check Kevin's guide to remind myself of what's arbitrarily forbidden..
rule of thumb: nothing works
5
10:59
I've even considered patching my browser to use a more obviously code font.
11:14
Cabbage
11:35
@jpp I hope the OP doesn't want to run the generator for too long. Your solution is going to chew up a fair bit of RAM doing the de-duping. ;)
@PM2Ring Could you add a bit of an explanation to your answer? I've been staring at it for 10 minutes and still haven't figured it out
FWIW, there are other interesting ways to generate compositions, eg stackoverflow.com/a/40220262/4014959
Please help close-as-duplicate yet another pivoting question stackoverflow.com/questions/50507735/…
jpp
jpp
11:51
@PM2Ring, Yeh you're right.. I should put my disclaimer in bold
I was half-expecting a downvote. it's still good (in my opinion) to see valid, but inferior solutions.
@smci, done. But how on earth does the canonical not come up as the first SO google result for "pandas how to pivot"
@PM2Ring I just got it and I'm now convinced that you're a genius.
How to access parameter values with name in decorator?
@Aran-Fey Thanks. :) I couldn't be bothered trying to explain it. And Wikipedia does a pretty good job, so I linked to that.
@jpp Why do you assume that people correctly ask questions to Google ? :P
If I ask "pandas pivot" to Google, the first SO answer is a dup, leading to the main SO pandas pivot Q/A.
jpp
jpp
@IMCoins, Yeh not complaining. Guess votes don't count to google (but they should!)
the older posts tend to get more traction perhaps, the canonical is only ~6m old
12:00
@jpp Google probably does look at votes, but it's probably more interested in page hits and the number of previous searches.
@Akshay Your question is rather cryptic. Do you have a small piece of example code you can show us?
yes
You believe that Google indexing algorithms look at specific criteria of specific sites ? I don't see how that could be possible. Except if they'd do an exception for each major site (e.g : SO). But that would take a huge amount of time, right.
@PM2Ring sending short snippet
@IMCoins SO is pretty popular. Google can afford to use a slightly specialized algorithm. Their search results are pretty good, but they tend to be focused more on questions than on answers. Trying to find answers via keywords (for dupe target hunting) can be a bit frustrating, since the overwhelming majority of hits are for questions that use the keyword in the title, which is a pain when you're trying to find answers that use that keyword.
12:06
You can use Sandbox for testing @Akshay.
Thanks Guys. checking on sandbox
def ArgValidator():

    def decorator(f):
        def decorate(*args, **kwargs):
            print args
            print kwargs
            f(*args)
        return decorate

    return decorator

@ArgValidator()
def sayHello(a1, a2, a3, a4):
    print 'Hello arguments:', a1, a2, a3, a4


sayHello(1,2,3,4)
This is the code
intention is to read arguments with param name since params are of same data type
You wish to print all the arguments of the function you decorate ? Is that it ?
currently just printing for testing, but I wont to perform some checks on those params in decorator
12:12
shouldn't decorate return the return value from f in general?
Yes. That return line should be return f(*args, **kwargs)
I think that is not a hard rule. Just went through these examples, python.org/dev/peps/pep-0318/#id79
Nothing's a hard rule, but you can only gain something from implementing it correctly
def my_decorator(func):
	def my_wrapper(*args, **kwargs):
		for arg in args:
			print ('I have an arg that is {}'.format(arg))
		return func(*args, **kwargs)
	return my_wrapper

@my_decorator
def my_func(a1, a2):
	pass

if __name__ == '__main__':
	my_func(1, 2)
This prints :
I have an arg that is 1
I have an arg that is 2
If you want to check using **kwargs, you must say
my_func(a1=1, a2=2)
that helps
12:17
I still don't understand the question, but my gut tells me that you're after Signature.bind
@Akshay If you want to decorate a function that returns something apart from None, then decorate should have an explicit return.
@jpp Do not expect that new-users will know terms like 'pivot', 'long-form', 'wide-form', 'stack'/unstack, 'melt', 'reshape'. That question was originally called "Python Pandas CSV rearrange DataFrame" stackoverflow.com/posts/50507735/revisions . Any thoughts on how to improve findability, other than closing tons of questions with related-wording names into the canonical?
@Aran-Fey He wants to perform a check on a function's arguments, using a decorator.
def my_decorator(func):
    sig = inspect.signature(func)
    def my_wrapper(*args, **kwargs):
        bound_args = sig.bind(*args, **kwargs)
        print(bound_args)
        return func(*args, **kwargs)
    return my_wrapper

@my_decorator
def my_func(a1, a2):
    pass

my_func(1, 3) # output: <BoundArguments (a1=1, a2=3)>
Thanks for closing, now we have a bridge from "Pandas rearrange DataFrame from long-form to wide-form" to How to pivot a dataframe
12:20
Also, while we're at it, you should really use functools.wraps on your decorators
I got error when I tried doing that.
return f(**kwargs)
NameError: global name 'kwargs' is not defined
functools.wraps is exactly what I was looking for
Thanks @Aran
Thanks Guys for checking on this
@jpp Oh right, the canonical with 110 votes shows up second in relevance behind How to pivot categorical variable in pandas? with 1 vote. That's a good point, I'll ask a Meta question about how that could be fixed.
@Akshay That's odd. I modified your code to use return f(*args, **kwargs) and it ran fine for me on Python 2.6.6.
@PM2Ring Why Python 2.6.6 ? :o :o :o :o
@PM2Ring, my bad, I did not return from innermost function
12:25
Obviously we are having a Python 2 day :/
@IMCoins That's the most recent version of Python 2 that I have.
jpp
jpp
12:48
@smci, I don't understand Hans' point, google is equally bad :p
(in this particular instance)
If you've ever wanted a Myst linking book along with all 7 Myst games you have 4 hours left: kickstarter.com/projects/1252280491/…
They raised over $2.5 million, it's crazy.
Whoaah
10x but still
Math!
Looks like an incomprehensible amount of money
I've actually backed 5 Kickstarters recently. We used to post cool ones all the time, but it dropped off at some point.
13:14
@Simon :slap: for answering a really common dupe. stackoverflow.com/questions/50510272/is-a-number-an-integer
Ouch.
guilt Couldn't resist.
13:29
I've turned to the dark side (scrappy non-working code and sloppy answers - plz help*/*give codez)
cbg \o
we should bring back shiny kick starters. I missed out on a switch projector kick starter and I'm kicking myself for it :(
Now I have to hook up my switch to the hotel room tomorrow like a normal person :( Point being, if someone posted that kick starter here I would have saw it :(
13:44
Could anyone explain why there is a +1 in the numerator? tensorflow docs - Notes_on_SAME_Convolution_Padding
Line 7
did you look at a few edge cases to see if it makes sense?
the only way reasonable for me is floor(n_i+p_i-k/s) + 1 = n_0
But that has ceil, not floor. Could that be it?
This is from another book I've read, but I'm not sure about whether they're equivalent
I guess you should 1. look at an integer and its floor/ceil with the two kinds of +1, and 2. look at a half-integer and do the same
if the two left-hand-sides give you the same number in both cases (integer and half-integer), you're safe
I think :D
uh maybe not, 1/s might mess with my naive approach
13:48
Yes I'm also thinking about the 1/s term...
Since it's on the numerator it's not very clear for me.
this will probably matter when the rest of the numerator is m*s for an integer m
so your edge cases are n_i+p_i-k == m*s or m*s+-1 to be sure
I'm sure there's a good and logical argument to be made here but number theory has never been my strong suit
@AndrasDeak I'm appreciate your time, I'm also not familiar with that...
unlike me most guys here have either formal or informal CS backgrounds, so hopefully someone else will be able to help
What's your background ?

« first day (2777 days earlier)      last day (2396 days later) »