« first day (3391 days earlier)      last day (1548 days later) » 
00:00 - 19:0019:00 - 00:00

12:07 AM
English enhancement proposal: I amn't sure this is a good idea after all
 
English doesn't need enhancements... it's perfectly logical... cough cough cough cough... hacking cough... omg... I'm now coughing up my stomach.... :)
 
1:10 AM
if you're ever in the market for a logical (human) language to learn you should check out classical arabic
i was amazed at how elegant it was compared to English and how polished the grammar was
 
 
2 hours later…
3:22 AM
I'm passing dicts with a particular format between functions, but there is no singular useful name that I can find to describe them when used as function arguments. Should I just define a class and use that instead?
 
3:33 AM
a name for the dict? Params works
If your sole reason for making a class is for passing arguments, I'd say classes are not a good fit. Classes should only really be made where they make sense.
If you wish to consider alternatives to the dict, you can consider named tuples or dataclasses, but honestly i don't think you need to go that far if it's simply a question of passing some params to various functions
 
I think I will go with a class in the end, the dict is significantly important enough to warrant it I think.
Thanks
 
No worries. Something i usually consider asking myself when trying to justify classes: Is the class going to have many methods? or any methods at all even? Does this thing represent a logical grouping, and are there going to be many objects required for this class or not. But At the end of the day, it's also a preference thing
If you are inclined for classes even if you don't have a lot of methods as such, then the dataclass is a good option to consider
But personally, i only really resort to classes if i must.
(aka almost never :P)
 
3:49 AM
Yes, I have so far avoided classes. And now I need to wade through the simplest of examples to find how to define them :D
 
cbg
 
4:05 AM
How do I create a variable for a class which is computed and stored the first time it is called, and then returns the stored value thereafter?
 
4:36 AM
Almost 100 :P when I go over I will give bounties so that I will be one of those who's crossed 100k the most times on SO
 
 
1 hour later…
5:42 AM
@jigglypuff One way is using properties
import time

class OneTimeCompute:
    @property
    def some_var(self):
        try:
            return self._some_var
        except AttributeError:
            #some long computation
            time.sleep(3)
            self._some_var = 42
            return self._some_var

obj = OneTimeCompute()
obj.some_var
 
6:00 AM
Thanks, that's what I was looking for
 
6:34 AM
@jigglypuff what does naming have to do with design?
 
need help with Tornado
anyone who has worked on Tornado Session?
 
7:17 AM
anyone?
 
cbg all, I have a Django listview I want to filter by the current user title post. How is the best way to implement that? Thanks. My view below:
class PropertyListView(ListView):
    #landlord is name used in the for loop
    context_object_name = 'apartmentinfos'
    model = ApartmentBasicInfo
    template_name = 'property_list.html'

    #trying to get the user
    def get_queryset(self):
        #user_pk = self.kwargs['pk']
        #current_user = get_object_or_404(User, pk=user_pk)
        #query = super().get_queryset()
        #profiles = query.filter(is_active=True, user_id=current_user.id).order_by('-id')
        #return profiles
I have tried the above code but i get key errors. This is the link to the full code: dpaste.com/2BTS9TN
@shad0w_wa1k3r @Code-Apprentice , @all Your input will be most appreciated.
 
7:31 AM
@superv please avoid pinging people if you're not already in conversation with them regarding something
 
Noted. Thanks :)
 
@superv thanks... it looks like you're on the right path - is there a specific problem you're having?
 
@JonClements I want each user to be able to see their specific post and not post from other users, which is what I am having now. I know i have to filter it from the listview but how to actually go about writing the code is my problem now. Thanks
 
Okay... well the current user is available as self.request.user...
def get_queryset(self):
    qs = super().get_queryset()
    return qs.filter(user=self.request.user).order_by('-id')
So ^^^ assuming that you have a field user on ApartmentBasicInfo that's a foreign key to the default User model...
 
7:59 AM
@JonClements Thanks. But I do not have a field for user on the apartmentbasicinfo. Does that mean I have to add the field for it to work?
 
@superv in your case, it could be return qs.filter(rental_property__created_by=self.request.user).order_by('-id'). See related object querying documentation.
 
@shad0w_wa1k3r ahh... makes sense when you actually look at the dpaste :)
 
yeah, it was a follow-up question, so easier for me to read through :)
 
@JonClements @shad0w_wa1k3r Thanks so much guys. Hopefully I can get better like you guys
 
good luck
 
8:21 AM
@shad0w_wa1k3r @JonClements I think it works now but I have to test it further. I really appreciate guys.
 
 
2 hours later…
10:03 AM
Guys I have the following List that I want to access the 'day' component but I cannot do so, here is a small sample of my data and I will also tell you what I did:
'List': [{
    "meeting" : {
          "day" : 1,
          "time" : "12.10"
    }, ....

}
 
I'd go with big_dict['List'][0]['meeting']['day'] based on that
 
day_list =[]
for item in f4['List']:
    meet_day= item['meeting']['day']
    meet_day_list.append(meet_day)
I will try your solution @AndrasDeak thank you
 
what you have seems reasonable to me if you fix the two different list names
 
in some other script it worked but here it does not recognize 'day'
 
so your dict is probably off
 
10:07 AM
if i put only 'meeting' it works but when I put the second variable it doesnt
 
so print the offending item['meeting'] and check its .keys()
Python doesn't lie, so when code which you think should work breaks you have to see which assumption of yours fails.
 
dict_keys(['day', 'time'])
this is the output I get
it's confusing, then it should work right?
 
well then "does not recognize 'day'" should not happen assuming you mean a KeyError
we'll need an actual MCVE that doesn't work
 
KeyError: 'day' this is the error I get
 
I see. Yes, that should not happen.
are you sure you printed it for the case that actually throws the error?
 
10:13 AM
did you check the item['meetings'].keys() for all (failing) items or just one of them?
 
try:
    meet_day = item['meeting']['day']
except KeyError:
    print(item['meeting'].keys())
 
I will try it , one second
@AndrasDeak this is what I get:
dict_keys([])
 
yay
you have a {} in there somewhere
 
so what do you recommend?
 
not trying to look up keys in an empty dict
Your options are 1. handle missing keys in a reasonable manner, 2. fix your data upstream, 3. both
 
10:18 AM
okay thank you I will ty to work on it!!
 
Grr.... why oh why (or how) does Google Assistant keep re-enabling itself on my tablet device!?
Keep going into settings and disable it... and then... it'll randomly perk up either listening or spewing off non-sense because it heard something on the radio or whatever
 
user6568562
Cbg
 
user6568562
I thought I witnessed a discussion where it was said that functions that don't return values should return an empty tuple instead of None; Yet, I don't find any trace of this recommendation anywhere. Am I misremembering ?
 
10:33 AM
None is the canonical "no value" in Python
 
@MisterMiyagi I think @randomhopeful knows that :)
 
user6568562
Absolutely; That I understand. A singleton, the sole instance of the NoneType
 
Unless your function is designed to return arbitrary length tuples, in which case an empty tuple still satisfies that, don't use () to mean "no value"
 
I don't recall such a discussion... but if the function "contract" as it were is that it guarantees to always return a tuple then yes... but whether that's desirable or not is another thing depending on context
 
@JonClements I meant that as '() isn't the canonical "no value"'
 
user6568562
10:36 AM
Copy that; Thank you, guys
 
user6568562
I must've misunderstood the context of the discussion
 
Although, I'd find it odd to as a design choice to return arbitrary length tuples... I can understand returning an empty list instead of None makes sense in some cases - especially those that the caller just wants to do: for obj in function(...) and doesn't care if it's empty or not... but generally, if you're returning a tuple then it kind of indicates it's fixed and you can assume unpacking it will work fine etc...
 
A few years ago, I would have agreed with that.
These days, I use NamedTuple for fixed-length sequences with meaningful positions. Tuple[T, ...] is a good way to pass on list'ish data that isn't meant to be mutated.
 
Can anyone explain what's happening here?

print(set(s) == set(partial_sigmaStar))              # False
print(set(s).difference(set(partial_sigmaStar)))   # output: set()
How come they not be equal when there is no difference?
 
what does print(set(s) < set(partial_sigmaStar)) give you?
 
10:50 AM
That gives me True
 
proper superset
 
@SebastianNielsen just to note if you're using set methods (such as .difference) the right-hand side just needs to be iterable - you don't need to convert it to a set itself... so just use set(s).difference(other)
 
@SebastianNielsen does that answer your question already, then?
 
Yeah, it seems like there is one more element in the partial_sigmaStar
But still weird that "difference" doesn't show what that element is
I would like to know what the difference is
 
Jul 3 '19 at 12:07, by Aran-Fey
Rule #1 of programming: If the function you're calling doesn't do what you expect, read its documentation.
 
10:54 AM
Oh,
I got it now
 
The function you're looking for is symmetric_difference
 
11:23 AM
does someone know a dupe for "I named my file .csv but it contains JSON"?
 
user10984358
Would you guys recommend return str(path_obj.absolute()) or return f'{path_obj.absolute()}' if i expect str instance where this return is expected?
 
cbg guys o/
 
@TheNamesAlc use str
 
@TheNamesAlc what does the latter give you other than forcing python >= 3.6?
 
user10984358
I thought pathlib came in 3.6 a google search reveals it came in 3.4 so str it is, thanks
 
11:54 AM
What are qualities of "good code"? So far I've got these 3:
1) Readability (meaningful variable names, comments, no huge walls of code, ...)
2) Efficiency (runtime/space complexity)
3) Maintainability (proper use of functions/OOP, no global variables, single responsibility principle, ...)
 
4) Documentation, in case of python
 
Hmmm. There's not much I could write about that. I guess I'll put that under "readability"
Although, I should probably also mention testing somewhere. Hrmmm. Maybe I could group testing and writing docs, since neither of those is really a part of the code itself
(Sure, docstrings are part of the code, but writing documentation for your code is different from writing good code)
 
12:10 PM
Your categories are broad enough that they probably cover most aspects. For instance I thought of spaghetti code and code with too many layers of nesting, but both fall under 3) and maybe 1)
 
Yeah, there's some overlap
 
while there's best practices... it all depends on context as well... if it's just you and a one time script for instance... you might want 2) and screw 1) and 3)
 
user6568562
@AndrasDeak docs.python.org should be mentioned in every grace
 
Yeah, I'm definitely gonna be needing a big fat header that reads "there is no correct level of abstraction in programming"
 
@randomhopeful OK, but we're talking about code ;) Unlike most languages python code has docs inside as well.
 
12:16 PM
@Aran-Fey however, if you're not just doing a "intended to be a throw-away" job... then what you can do is abstract initially on the principle that you're going to have face (2) at some point, and keep focused on (1)
and then you've covered (3) (or should have)
 
@Aran-Fey 3) Covers basically everything there is, including 1), Andras' 4) and parts of 2)
 
Yeah, true. Maybe calling it "maintainability" is a poor choice; that section is mostly gonna be about program architecture
 
user6568562
@AndrasDeak Yes, those jolly good docstrings. Thanks for clarifying ( :
 
12:46 PM
I am not sure how to search/ask this. Can I somehow remove these invalid unicode characters from a string before I write them to this xml? (screenshot below)
 
@hitter maybe something like this would help - stackoverflow.com/a/8689826/2689986
 
@shad0w_wa1k3r well it seems to be a non-printable character, I'll try to see if it works for this utf8 encoding
 
1:03 PM
Gotta love Windows - strongly dislike it when I have to boot into it to do specific stuff... Told it many times - "no - not updating is fine for now..." - it's now doing the "yam you I'm going to update anyway and enjoy watching the 30% update notice and then restart the computer whether you like it or not" thing
Lol... Done its reboot, I then had to catch that from the bios boot up stuff to enable it to go back - and guess what, another update and restart
 
classic Windows...
 
I've come around to Windows a little bit... I think what frustrates me most is that it thinks it's the only OS on the computer
 
1:19 PM
surely if there were other OSes on the computer you wouldn't be inside Windows, eh?
 
It's a dual boot @AndrasDeak - the MBR by default goes to Linux but sadly sometimes I need to do Windows core level stuff I can't do with mono on. Net etc...
 
sadly, one doesn't always have a choice, even with multiple OSes.
 
Could probably virtualbox it in some cases - not sure though
Anyway - where's Kevin when you need him. Got an idea for a green/white deck involving hush bringer :)
 
1:36 PM
# example-1
f_list = ['az','bf','cw','ddft']
# Expected output
dynamic_dict = {0:'az',1:'bf',2:'cw',3:'ddft'}

# example-12
f_list = ['av','bm']
# Expected output
dynamic_dict = {0:'av',1:'bm'}

# Here f_list can be of any length from 1 to any positive number , dictionary should be created accordingly...what should be approach
 
dynamic_dict = dict(enumerate(f_list))
 
you can use dict(enumerate(f_list)) , but there really isn't much point to it
 
the only point I can see is implementing a "list with holes in it"
The presence of a design problem is more likely.
 
@AndrasDeak true. but as long as the indices match a bare enumerate, that's out.
 
I figured converting from an existing list to one with holes later
 
1:57 PM
Hi guys
 
hello
 
Can u guys clear my doubt
I am full stack developer pertaining to python, django and angular
 
We are planning to start project
 
@JonClements hushbringer's predecessor, torpor orb, has enjoyed some success when combined with creatures such as phyrexian dreadnaught, eater of days, and leveler. I'm not sure if there is any precedent for turning off leaves-the-battlefield triggers, but I have no doubt there are shenanigans to be had.
 
2:01 PM
@AndrasDeak That's how I extended my IntComputer when it used very high position numbers as registers, rather than extending to a huge list.
 
Its actually product
So here i want to know about to product and how can i deal with it using my technologies.
 
@JonClements On mine I briefly tried to have it boot into windows after 30s rather than linux, but I couldn't find a way to do that with grub.
 
Trying to think of cards that have utterly ruinous leaves-the-battlefield triggers, which would benefit from hushbringer... Lich and its variants are obviously as bad as you can get, but they're not creatures, so there's no useful interaction there
 
2:23 PM
@SaisivaA If you can narrow this down to a specific question or two, you are more likely to get a friendly response. What specifically are you wanting to know? "how I can deal with it" is not specific enough.
 
Terminology poll. True or False: "True is an int"
 
True. Same thing as "Kevin is a mammal"; a human is still a mammal just like a bool is an int
 
In OO-speak, I equate "is-a" with "is-an-instance-of or is-an-instance-of-a-subclass-of", so I would also say "True"
The important distinction to folks learning OO is that "is-implemented-using-a" is not the same as "is-a". I might define a class which is a collection of items (or more likely related to a collection of items), but that doesn't mean it should subclass from list.
 
Hi guys
 
This poll is born from my frustration that every time I write a comment like "str.find's return value is an int, so you don't have to worry about distinguishing a return value of, say, 1, from a return value of True", a member of the Well Actually brigade appears and says "well actually, True is an int, so you haven't guaranteed that it won't be returned by str.find"
 
2:38 PM
@Aran-Fey so are you claiming that Kevin descends from apes and are not created. Now someone might be offended here.
 
@Kevin Quick google suggests zero is an integer, so no.
 
I need to find a phrasing of "str.find returns an int" that means "the exact type of str.find's return value is int" without having to twist the sentence in awkward ways
 
@Kevin good point :P
@Kevin let's make a PR.
 
Whoops. Kevin may not have been the most suitable subject :P
 
To the People In Charge of English, I submit a PR for a new word, "es", which means "is, with the guarantee that no other categorization is more precise than this one"
True is an int, and True es a bool, but True es not an int, because "bool" is a more precise categorization than "int"
 
2:41 PM
Weird that everyone is so convinced that True is an int. I'm not so sure about that, semantically speaking. Of course non-semantically it is.
 
@Kevin str.find returns an int.?
 
Can someone here help me with pandas?
 
Or "int object"?
 
@toonarmycaptain Yep.
All ints are int objects, so also yes
 
@It's_me That depends on what exactly you need help with, so we probably won't find out unless you actually ask your question
 
2:43 PM
@It's_me It's possible, ask your question
 
But yes, there are some people who know pandas here if that's what you were asking
 
And there are some pretty good guessers here too, even if they don't know
 
@Kevin I was suggesting you phrase it like that, with the code styling of the type. And that it s true, but in a sense 43.0 is an integer, if taken without reference to it's digital implementation, so I'm suggesting to make clear that it's returning an integer python object, not just a number without significant decimal or fractional part.
 
inb4 "but 'es' is useless since the most precise categorization is always the reflexive one. In other words, 'True es True' trumps 'True es a bool', so the latter is forbidden"
 
When True falls in the forest and there's nobody there to hear it, is it an int?
 
2:46 PM
I wouldn't fret too much about the wording on this "is a" thing. Just because some smartypants well-actually'd you doesn't mean anyone was actually confused about what you were trying to say
 
it is dishonor on his family
 
@PaulMcG can I post the link of stackoverflow question here?
 
@It's_me please read sopython.com/chatroom first to see when and how to ask
 
Hmmm, the etiquette here is "only if you have waited a couple of days first"
 
I think I've unfortunately clouded the issue by choosing a cluster of types that have a confusing semantic relationship. Perhaps a non-programmer mathematician would tell you that "True" is not an integer in any sense. I would have chosen an example that doesn't touch anything numbery, but I couldn't come up with one that uses well-known builtin types
 
2:48 PM
Give the main group a chance to answer before posting in chat.
 
I tried the answer on my dataframe but that doesn't work, I have added the image of my result in the comment
 
Yes, you just asked that today, please come back later if you haven't gotten a good response from the broader community.
 
Does anyone know how MATLAB solves large system of linear equations? I'm still stuck.
 
Incidentally, those pings to YO, Ben_W, and jezrael, almost certainly did not actually reach their intended recipient. You can't ping someone that hasn't already interacted with your question. Good thing, too, or else every power user's inbox would be flooded with requests from users they've never talked to.
 
Sorry new here...actually stuck on the specific part of data cleaning and the results are not in my favour
 
3:12 PM
Every time I think I know everything about Python's syntax, I find something new... Today I learned that raise from is a thing.
 
@Kevin poke had a hand in having raise from None
 
whaaaaa?! raise from example, please?
 
The question that employed it is stackoverflow.com/questions/59951549/…, but it gives little indication of its purpose. Paragraph six of docs.python.org/3/library/exceptions.html#built-in-exceptions describes it.
Basically if you want a stack trace with two tracebacks and two exceptions separated by "The above exception was the direct cause of the following exception", use raise from
... But you can also get two tracebacks and two exceptions if you use a regular raise inside an except. The only difference I see is that the message is instead "During handling of the above exception, another exception occurred"
I guess raise from is more flexible because you can use it when you're not inside an except.
raise ValueError from TypeError is a syntactically valid complete Python program, for instance
 
Hi all. Regex101 with Python engine finds a match for a pattern (with non-English alphabet in it), however, the re.search in Python doesn't find it. For example, this code (pastebin.com/57gFn8eW) prints exists #2, but doesn't print exists #1. (exists #2 is a non-exact match).
 
3:29 PM
Hmm, I suspect a Unicode control character is at work here. I notice that when I highlight the second word, it highlights from right to left, which is the opposite of what I might expect for conventional ASCII text. So I suspect there's an RTL mark in there.
I don't know off the top of my head how re interacts with RTL marks
Or, hmm, now that I read the code again, maybe I'm overlooking something simpler.
 
what is that?
 
txt = fin.read() will load the full contents of the text file into txt. The full contents of the text file is three words, so a regex that matches against exactly one word isn't going to match it. This would be true even for ASCII text.
 
ohh
 
Perhaps you could do something like:
import re

with open("words.txt","r") as fin:
    for line in fin:
        if(re.search('$نوید^',line)) is not None:
            print("exists #1")
        if(re.search('نوید',line)) is not None:
            print("exists #2")
 
Well that's what I didn't want to do :/ Because there are many more words than those three I've put in the example.
 
3:34 PM
I'm not actually sure if this will give correct results, since it prints nothing on my machine. But your original code didn't print anything on my machine either, so I'm guessing something got mangled when I tried to create words.txt. I blame Windows.
 
I tried \bنوید\b as well without success. Do you think that has something to do with the read as well?
 
Or, hmm, am I misremembering how "^" and "$" behave for multiline strings? I'll compose an ASCII-only prototype and play around with that...
It may be worthwhile to try the re.MULTILINE flag, see if that does anything
 
Is there a cool recipe to chain map over many functions? My naive example of what I mean:
from functools import reduce

def f(x): return x + 1
def g(x): return x * x
def h(x): return x - 2

[*reduce(lambda a, b: map(b, a), [range(10), f, g, h])]
# [-1, 2, 7, 14, 23, 34, 47, 62, 79, 98]
 
import re

"""contents of words.txt:
foo
bar
troz
"""

with open("words.txt","r") as fin:
    txt = fin.read()
    if(re.search('bar',txt)) is not None:
        print("exists #1")
    if(re.search('^bar$',txt)) is not None:
        print("exists #2")
    if(re.search('^bar$',txt, re.MULTILINE)) is not None:
        print("exists #3")
    if(re.search('\bbar\b',txt)) is not None:
        print("exists #4")
    if(re.search(r'\bbar\b',txt)) is not None:
        print("exists #5")

#result:
#exists #1
 
@Kevin Hmm... That's what I should have tested at first. So you mean it has nothing to do with non-English letters, right?
 
3:41 PM
Ok, so first, "^" matches the start of the string and "$" matches the end, so "$whatever^" is not likely to match anything. Second, they don't match the beginning/end of a line unless you specify re.MULTILINE. Third, you need to use raw strings if you're using the word boundary sequence \b, because otherwise it gets interpreted as a literal backspace character
 
@Kevin Oh... very delicate and useful points! Thanks. Let me try them.
 
@aderchox I'm not sure. There might be multiple problems at work here, with some of them caused by confusion between ^ and $, and some of them caused by non-English letters. My environment refuses to play nicely with your example text, so I can't draw any solid conclusions.
 
By the way, That's weird your system didn't print anything. I'm on Windows too. I even copy pasted from my pastebin and created a new file (thinking maybe something was wrong with the clipboard or something else) but it's still at least printing the "exists #2".
 
"If your country's government replaced your courts with AI (artificial intelligence) would you trust it? " - I need the option "More than the current system" in addition to the probably/definitely/not.
 
Yes it works now! :) re.MULTILINE didn't but using a raw string did the job! Thanks @Kevin
 
3:47 PM
It's not totally out of the question that an RTL mark causes "$" and "^" to behave in an unusual way. Maybe it's the one scenario where "$whatever^" really would match something sensible.
A word boundary approach may ultimately be less frustrating, since I wouldn't expect an RTL mark to change how they work
 
@Kevin RTL mark was really interesting, I didn't know about it :)
 
@piRSquared I was waiting for you to be online here..
 
It's You!!
 
@toonarmycaptain AI as in, a fully generalized AI with human level intelligence or better? Sure, although if such an AI existed I think having one in a jury would be the least revolutionary of all the societal changes it would cause. Or AI as in a machine learning algorithm trained on a data set curated by a human? No, since the human's bias would bleed into the data set.
 
@Kevin It's the JetBrains dev survey - it doesn't specify. But I feel that that's an important detail - as in, "do I want to have surgery by remotely operated robot? Y/N " doesn't take into account that my other option is the local barber copying youtube.
 
3:53 PM
Even if the data set was "every case ever tried in our country", that too would be biased. Unless you think the existing system isn't discriminatory in any way, in which case why replace it with an AI?
 
@Kevin You are that experiment and it's run amok and we adore you for it.
 
@It's_me please don't ping users with your problem unless they expressed a prior interest in helping
 
Sorry but in dire need for help
 
That may be the case, but we don't make exceptions on the basis of urgency
3
@piRSquared If I ever break out of my simulation and conquer the world, I promise not to eradicate humanity or keep them in a zoo or anything. Granted, an evil AI would also say this to try to trick you, but oh well.
 
it's ok but my reputation isn't enough to ping specific user for chat.
 
3:58 PM
Since the statement can't possibly benefit me, that must mean it's genuine :>
 
@It's_me I'll tell you that your question is very confusing. You can reduce your example to a minimal one and show what you mean. Until then, it is far too much work for me (or anyone) to figure out what you are trying to do. If your situation is dire, spend the time to make your question as clear as possible. Make it shorter, not longer.
 
Maybe you could write a non-biased court AI by feeding every law into a theorem prover, and asking it to prove or disprove "the defendant broke the law" using only the laws as axioms. It would be a pretty monumental task to do that, though, since even simple laws like "it's illegal to break into someone's house" is only simple to a human because we have an intuitive understanding of what a "house" is
 
@Kevin TRICK ME!! Why would I need tricking? Do you need me to flip a switch somewhere? Just let me know.
 
Hmm, I was hoping the "release AI? Y/N" prompt would be immediately available to you. If you don't know where it is, and I don't, then some elbow grease is required
 
Also @It's_me, think about not making pandas part of your question, I'm pretty sure there is no magic bullet in pandas to solve your problem. Instead, try pulling out just one cell of data, and see how you would go about extracting your desired values from just that string. Now you have simplified your problem down to native Python data types. Once that is resolved, then you can fold that thinking back into a process to use against the cells in the dataframe.
 
4:11 PM
+1 for expressing the problem with native Python data types. I'm much better at parsing regular strings, compared to manipulating pandas types.
 
@piRSquared simplified for you (I am having dataset of research papers with references in column of each paper and every paper has many references as we know about papers and I want to look for each reference in the same reference column to find out where the reference is used again(duplicated) if any and count the value and get the index of duplicated location.)
 
Even if it turns out that "convert the dataframe to a builtin data structure, do manipulation on the regular strings, and convert back to dataframe" is too slow for practical purposes, it gives you an objective basis for a follow-up question of the form "This is what I want to do, but it's too slow, is there a pandas-specific approach?"
 
@Kevin I tried regular expression but it doesn't help
 
You'll know with complete certainty that the reader can figure out what you're trying to do, because they'll be able to run the slow code and see what it does
 
4:16 PM
You have several issues at once, and counting the duplicate references is secondary to actually parsing the references from that mess of text in each cell. Until you can do that, looking for duplicates, etc. is beyond your reach.
You could go in two directions: how to parse references from a cell containing unstructured text; build a list of lists containing something already converted to a searchable thing, like a list of ints, and come up with an algorithm to search that list of lists of ints to locate and index duplicates.
 
I have parsed the references. @PaulMcG I don't understand what you are saying?
 
@It's_me it's a good start that you're showing the rows of your input, but it would also help to show what the output ought to look like. The way I'm reading your question, it sounds like you want to find any cell that appears more than once. So the expected output for your input data is "no duplicates found", right? Or is it something else? If you describe what the output is from the start, then the readers of your question don't need to wonder about it.
 
@smci perfectly friendly
 
@Aran-Fey Who's prefectly friendly: the OP or me?
 
ttk.Notebook question: Trying to associate a clicked tab with its child frame without depending on the tab text. The only way I can find is getting the tab text using the tab index and then iterating through stored values(something like a dict) that associates the tab text to the children. If the provided string for the tab text is too long I cut it down to x characters long for a better GUI layout but this can result in 2 tabs having the same tab text. This is why I cant use the tab text.
 
4:19 PM
If you are looking for duplicates of the strings you have already parsed, what are the regexes for?
 
from tkinter import *
from tkinter import ttk

main = Tk()

def printframe(event):
    # I need to find which frame is connected to the tab that I click. Identity gives the element on the tab, index gives a int, neither can be used to find the children for that tab.
    # Because the tab name is being trimmed for cosmetic reasons its possible that I would have multiple tabs with the same name. This means I cant use book.tab(index, 'text')
    # to match up the clicked tab with the matching frame.
 
@smci Well, I was referring to your comment, since the OP never talked to anyone specifically
 
I have a bad feeling that the question is actually "how do I tell if two references are the same, even if one uses MLA style and the other uses APA style?"
 
And if you just want to find multiple references to a string, you don't need a data frame. Just make a list of (paper_id, reference_string) tuples, sort by reference string, use groupby to group them, and there are your lists of duplicate references.
For that matter, I've learned that pandas doesn't even require that you sort before grouping, so isn't df.groupby going to do your reference matchups?
 
@PaulMcG tried what you said but it give this result imgur.com/pAwBcTv
 
4:24 PM
@It's_me this will be my only guess at what you are trying to do. If I'm wrong, I won't make any more attempts at helping without you editing your question. df.groupby('reference')['_id'].nunique()
 
@sidnical Can't you use notebook.select() to retrieve the currently activated tab?
 
@sidnical Perhaps you could keep a list of Frame objects, which you append to as you create them in the for x in range(5): loop. Then you can determine the current Frame inside printframe by doing frame = my_list_of_frames[event.widget.index("current")]
I don't know if this is the idiomatic approach but I'm optimistic that it does the right thing
 
sorry, I was trying to keep my post simple and left out a detail. The tab is being clicked but not selected. Im clicking an X on the tab to close it. im wanting to go cleanup the children and then .forget the tab.
.select is the currently selected tab and right clicking a tab or clicking an element on a tab does not make it selected
@kevin "current" will give the currently selected frame so this would have the same problem.
 
Let me see if I understand. Each tab header has some text and an "X" button, much like the tabs in, say, Firefox. You can click on an X, even if that tab is not the current tab, and you want that tab to be destroyed/forgotten/whatever.
 
My notebook's tabs don't have an X like that
 
4:36 PM
@kevin, correct. just closing the tab is not a problem because I can use the index to .forget(index). Problem is that widgets like tk.Text dont get cleaned up and may still have references so I want to get the frame and go cleanup those objects before forgetting the tab.
 
Or maybe I misunderstand, because I wasn't aware that you could put a button in a tab header, and I don't see an obvious way of doing so
 
@Aran-Fey you have to add an element for it to come up
 
I seem to recall a technology with which you could make a site-specific browser. I have used in the past, and do currently use Fluid on mac osx. But due to its UI/UX/browser_feature limitations, I'd like to switch. I think I'm thinking of Atom browser. Could someone please validate?
 
You say that .forget(index) works, so I assume you have some way of getting the correct index. In that case, you can get the frame by doing my_list_of_frames[index].
The "store a separate list" approach I'm suggesting is independent of the particular way that you choose the index
 
4:38 PM
Thanks @piRSquared for your help. Will try to reorganize the question as above method doesn't help me?
 
@kevin, if you close a tab the index of the other tabs will change. I'd update those indexes but have the same problem with no way to connect each tab to the stored objects
 
@Kevin @PaulMcG thanks for your help also.
 
If the indices of the other tabs change, then updating the indices of the corresponding frames in my_list_of_frames should, in principle, be as simple as del my_list_of_frames[index]. Unless the indices in the Notebook are getting rearranged in an unusual way
 
ah, so you're referring to the index of the item in the list. Not really a stored index for that item. That may work.
 
If these Xes were ordinary Button widgets, I might suggest associating each one to a frame by employing "early binding" lambdas inside their bind calls, e.g. x_button.bind(lambda x_button=x_button, frame=frame: on_button_clicked(x_button, frame). But the code at stackoverflow.com/questions/39458337/… doesn't seem to be using Button or bind, so maybe that's not relevant here
I'm not super well versed in ttk, compared to what I know about tkinter. Alas.
 
4:49 PM
well I appreciate the help. Was hoping I was just missing something.
 
Oops, I'm half wrong. The code uses bind, but not Button. I think you really need individual button instances to do the early binding approach though.
 
ah
i'll try it with the list index matching the tab index. Looks promising.
 
Meanwhile, I'm going to look into .identify. I feel like it should give you a useful result, so it's curious that it's returning an empty string instead.
 
in the example I built out its dong that empty string. In my actual program I think its getting the element every time. I just wish I could use that element to get the actual tab.
 
If element holds the name of the frame, I wonder if you could use stackoverflow.com/questions/8894841/… to get the frame reference? I'm not sure if you need to qualify it with the names of its ancestors, or what
I'm assuming that tkinter assigns unique internal names to each widget, but I'm not sure that's actually true
 
5:06 PM
from what i've seen tk does unless you name it
element is the element in the tab. Like "tab" or "label". the X element im creating is called 'close' so when its clicked the element is 'close'. I havent found a way to tie that to info in the tab.
 
Here is a small prototype that uses nametowidget to get a frame reference, given its name. Not sure how useful it is here, since it sounds like you don't have easy access to the frame name, but I may as well post it for the record.
 
they're using 'current' which uses the selected tab. when I close a tab its not active. So far all I can collect about the tab i've clicked is the index, and the element on the tab that i clicked.
 
This may be environment-specific, but when I run the code at stackoverflow.com/questions/39458337/… and click down on an X, the tab belonging to that X becomes active. So in that case I'd expect "current" to return the correct tab.
Possibly you are about to say "yeah, I found that behavior annoying. Clicking the X of an inactive tab shouldn't make it active, so I changed it so that doesn't happen. The drawback being, 'current' gives me a useless value". This is understandable.
 
let me double check this
 
i am creating my own python package. is there a way to have a file called `package_meta.py` which contains the package number and this same file is been imported into setup.py and __init__.py of my package.. if so, how do i import it into setup.py if it lives in the same directory. doing
from package_meta import PackageMeta
doesn't seem to work.. any help please
 
5:21 PM
brb
 
5:33 PM
@Kevin @Aran-Fey you were right. the book.select() and 'current' are getting the clicked tab. Guess I missed something when I tested this. My mistake.
Solution found. Thank you very much.
 
Glad to hear it :-)
 
@Kevin toying around with ideas... Could probably do something awesome involving blue - trying to stick to white and green though...
 
Do you have a specific payoff in mind? Is there some recently printed card I'm not aware of that becomes really strong when you can ignore its enters/leaves-the-battlefield triggers? Or are you more interested in shutting down the beneficial abilities of your opponents?
Making your opponent's cards less good is a time-honored archtype, and white/blue is very good at it
Many decks of this type can be found by googling "hatebears", if you want inspiration
 
5:48 PM
Nothing particular
Just trying to make a strong green deck
 
I believe green/blue was doing quite well recently, powered by Oko Thief of Crowns / Questing Beast / Veil of Summer. So well, in fact, that Oko and Veil were banned. So maybe they're not doing quite as well now.
 
@JoeSaad I don't see the point of having a separate file that contains package metadata. Stuff like the package version should be inside the package; unless you somehow import your package_meta file (which is messy) you might as well put the metadata directly into your setup.py
 
Got 4 questing beasts available - but yeah, rest are banned in standard
 
I assume your goal is to avoid duplicating information? (i.e. hard-coding the version in the package itself and in the setup.py)
 
I don't see any pure white/green archetypes in the metagame... mtggoldfish.com/archetype/standard-wug-166962#paperis is WUG but it's not commonly played.
(Which is not to say that only the archetypes listed there are strong. Merely that making a strong deck is easiest when you are following an archetype)
 
5:58 PM
cbg!
 
The vast majority of my decks are "rogue" builds where, instead of looking at guides online telling me what I should do, I thought, "wouldn't it be fun if I did something with {neat card X}?". Some of them turned out quite strong. One of them turned out to be Bogles, about five years before Bogles dominated Modern tournaments.
 
wim
how dumb UI bugs like this can hang around for 2 weeks?!
usually this stuff should be caught in QA, and if it somehow accidentally makes it to prod deploy, it should be rolled back (or rolled forward for trivial fix) within hours
stack exchange dev team must be really stretched thin at the moment
@jigglypuff check out this @cached_property. It's a descriptor which just replaces itself with a normal instance attribute after the first (lazy) computation of value. You can invalidate the cache by deleting the attribute.
@Aran-Fey 4) testability. if you need some crazy intrusive hacks to setup the necessary mocks, it's not good code. usually good separation of concerns makes code easily testable.
 
6:13 PM
@wim oh hey, that looks pretty nifty
huh looks like there's an entire package called cached property on pypi
 
wim
@JoeSaad this is surprisingly difficult using setup.py. but modern build system with pyproject.toml make it trivial (you just define a __version__ attribute in the top-level module, and the build system will collect that)
I would strongly discourage having a module package_meta.py because this is allowing the design shortcomings of distutils/setuptools to be a "bad influence" on how you structure your package.
@ParitoshSingh there are many, and it's reinvented in various frameworks several times. pydanny's one mentions this in the credits:
> Pip, Django, Werkzueg, Bottle, Pyramid, and Zope for having their own implementations. This package originally used an implementation that matched the Bottle version.
 
6:29 PM
@Aran-Fey the reason i want to use package_meta is that init is also using the same variables.. so just wanted to use single source of version changing in the codebase
rather than in setup and init
@wim i am looking at packaging.python.org/guides/single-sourcing-package-version even though the description is not that clear for all steps, but i am leaning towards step 3
 
@wim That's a bit tough for me because I have like 0 experience with mocking. Will keep it in mind though, thanks
wim knows a billion times more about packaging than I do, so I'm gonna hand this over to him
 
wim
@JoeSaad I really hate that page. Every suggestion there is a bad hack, to work around the problem of not being able to import your project from within setup.py. Which is a problem of distutils, not a problem of your package!
 
@wim i hate its lack of clarity.. it's not clear enough.. so your suggestion is something else altogether?
 
Aran, did you manage to settle on a go-to guide for packaging that didn't make you cringe?
And i suppose same Q to you wim
 
@wim do you have a clear documentation to follow?
 
wim
6:37 PM
@JoeSaad Yes. Just define in your __init__.py the attributes, like this: github.com/wimglenn/resources-example/blob/…
then use a build system such as flit or poetry. they have their own guides and clear documentation.
 
@wim so how is setup.py accessing those?
 
wim
In this case, there is no setup.py.
The build system will access these metadata values from the source tree directly.
 
oh, no that's a big change for me, since it's not really my package and my teammates will want that one
 
wim
Then, sadly, you have no good option but to duplicate the info in source and setup.py
 
@ParitoshSingh Not really. I followed wim's advice of using flit, but I haven't actually done much with it yet. Haven't gotten around to it yet
 
6:41 PM
ah i see
 
which stackexchange site can I ask for help on setting up a design for an application. A time series data visualization app. I need to build an app like this :https://www.highcharts.com/stock/demo/lazy-loading
But I need to add more top level layers, more series and selections..I prefer to do it in python
 
sounds like closed as too broad :P
 
@ParitoshSingh I wish there was a site 'closed as too broad' :)
 
Hehe. I'd say that no one can really help you with your specific use case, Essentially you just need to sit through, decide on a rough outline on how you want to divide things, and start building the design. As you go through it, you'd naturally end up changing a few things around. For guidance, you can rely on seeing how other libraries do it for inspiration
advice about Structuring a project can only really be given in the general sense, you'd have to figure out the specifics as you actually start implementing it.
So yeah, that would be my recommendation. Take inspiration from other libraries, make some kind of meaningful sub-units in your mind, which you can then translate to submodules or classes and go from there.
oh lookie here . And the close vote too, funny :P
 
I guess that is the path. Time is a constraint, hence I wanted to get some technical advice on the code design of the specific app. I appreciate your advice, If I ever reach a stage where I can ask some specific questions I'll ping you after posting! Keep an eye out.
 
6:54 PM
While browsing social media the other week, I saw a post that read "tfw when Stephen is devoured by slithy toves :-(". I had no idea what this referred to and moved on. This week, I got really into a podcast starring a man named Stephen. Imagine my displeasure when, in episode 60, he mentions his growing interest in tove breeding. I've been retroactively spoiled!
 
So, I'm looking for a piece of code that helps me demonstrate to beginners why writing readable code is important. Something simple that nonetheless takes a while to understand. Something that:
1) is short (preferably around 5-10 lines)
2) uses only simple syntax (no list comps, yield, etc)
3) isn't based on some complex algorithm or whatever (I don't want to give people the excuse "I'd have figured it out if I was familiar with [rocket science]!")
Any ideas?
 
hm, perhaps use bad names, easiest way to make code tough to read is to use misleading names
 
00:00 - 19:0019:00 - 00:00

« first day (3391 days earlier)      last day (1548 days later) »