« first day (3144 days earlier)      last day (1809 days later) » 

12:41 AM
Hey, is the usual convention lat/lon or lon/lat, when dealing with geo points in Google Maps, Baidu Maps, geopandas, shapely? I see all sorts of different styles in code. In particular I'm writing/looking for a basic Point class which is a bit more geo-aware than a shapely.geometry.Point, e.g. instances can compute their distances dist(self, other, method='straight'/'manhattan'), in the proximity of Beijing (116.39E 39.93N). Am I reinventing the wheel? There must be a similar class out there.
('GeoPoint'?)
(i.e. a GeoPoint which knows how to calculate Manhattan distances in the local vicinity of a reference point (e.g. center of Beijing) from lon_scale_factor*difference_in_longitude + lat_scale_factor*difference_in_latitude; no need for Great-Circle or haversine). Also, I'll be writing a less sucky __str__() representation than shapely.geometry.Point's default
 
12:56 AM
@smci I would assume that for anything in Google Maps the convention is lat/lon. I have personal site that uses a Google Maps layer and the JS code that drives the map uses that format.
 
@Dodge Sure, but I'm also talking about geopandas and shapely.geometry, where Point is unitless and people seem to do all sorts of whatever; it's a real Tower of Babel. I think I will subclass Point as GeoPoint, declare a dist_km() function, and store LAT_SCALE_FACTOR, LON_SCALE_FACTOR as class variables on GeoPoint. Then I can use the plotting functions on Point. Sound good? But I still don't know whether in client code using those libraries people tend to write lon/lat or lat/lon...
 
Yeah, I figured you'd be fully aware of the convention I described and also realized while typing that the issue was likely much more complex than loading a map layer with a couple dozen markers. You sound like you have a firm grasp on your implementation so, if I were you, I might be inclined to not care too much about what others are doing.
Unless, of course, there is an accepted standard involved which appears not to be the case hence your initial question
 
1:20 AM
@Dodge Uhuh, I mean I just need a fast-and-dirty geo-aware GeoPoint class, that can also easily be plotted - so if I can use someone's existing code, better. Since the convention in geomapping-land seems to be lon/lat, and to easily thunk to/from Google Maps from my code and data, I guess I override Point such that Point.x = longitude, Point.y = latitude. And man that Point thing needs a custom __str__ method override...
It doesn't need to be a very smart GeoPoint, just know how to compute straight-line and Manhattan distances in km. I calculated my delta_lon/lat scaling factors in the vicinity of Beijing, China (116.39E:39.93N) to be LAT_SCALE_FACTOR ~= 111.0 , LON_SCALE_FACTOR ~= 85 . They're nice clean round numbers, that'll do fine. I'm not trying to guide a missile.
 
Sounds fun! And now that you mention it, the lon/lat format is more in sync with x y plotting on a Cartesian plane.
 
1:36 AM
@Dodge Yay! `>>> tq.iloc[0].o
(116.29E:39.97N)`
Hey does anyone know the exact syntax for forming an URL query to Google Maps for (116.29E:39.97N)? Because if you type it into the query box it flips lon<->lat and massages the coords into DMS: https://www.google.com/maps/place/39°58'12.0"N+116°17'24.0"E/
 
 
4 hours later…
6:01 AM
@Dodge After I had solved it myself manually, I found this excellent question Simple calculations for working with lat/lon and km distance?. Or if you want the coefficients in miles GIS.SE: Calculating longitude length in miles?
 
 
2 hours later…
8:24 AM
How can i run flask that used blueprint in it with systemd service ?
How can i run flask that used blueprint in it with systemd service ?
app.run() not work ! when i not use blueprint this way work but when i using blueprint this way not work ?
 
@alireza maybe this can help blog.miguelgrinberg.com/post/…
 
Good morning all!
 
Sup
 
8:40 AM
@shad0w_wa1k3r is a right way to use gunicorn ?
 
@alireza by just a glance at the article, it seems okay to good
 
I want to learn how to build a simple Point of sales with PyQt.Can anyone point me to the right direction?
 
@shad0w_wa1k3r I use init.py in my directory that make my app packaged and not work with this article
i'm using this method
http://flask.pocoo.org/docs/1.0/tutorial/factory/
 
9:35 AM
@Dodge: argh, shapely.geometry.Point is unhashable (it must contain a mutable structure like a list), hence pandas.Series.nunique blows up with TypeError: unhashable type: 'Point' ... sigh... will have to use clunky groupby-aggregations just to count the number of unique coords, etc...
 
9:46 AM
@DeveshKumarSingh closed
 
@smci subclass it with a __hash__ based on the coordinate tuple? Exactly checking float coords would be fragile anyway
 
@smci umm... doesn't pandas actually have a geo extension?
Oh... there's geopandas.org ... or is that what you're already using?
 
10:06 AM
I already kludged it, just hacked on a ghetto hash function, seems to be working ok to me:
def __hash__(self):
"""Kludge __hash__ method so this works with groupby, aggregations etc."""
return hash(self.x) ^ hash(self.y)
 
for some reason... a bitwise-op of two hashes looks scary to me :)
Hope the __eq__ method is sensible :)
 
@JonClements I could also do hash((self.x, self.y)), does it really matter? The only issue is __eq__ should work. (I suppose there could be a theoretical issue with floating-point exactness, but my lat/lon are guaranteed to be rounded to 2dp so we sidestep that)
@JonClements What should my __eq__ do? I inherited a Point.__eq__ but not a __hash__ from Point which I subclass with GeoPoint. Is this courting disaster?
I mean shapely.geometry.Point does not define __hash__ which seems like an oversight, means you can't do pandas things like groupby, aggregate, nunique etc.
@JonClements I'm using both shapely.geometry, geopandas. From my very brief due diligence today that seems to be what people use; shapely.geometry is nice for plotting.
 
I'm not sure... I have no experience in this area... just saying that return hash(self.x) ^ hash(self.y) makes me nervous...
 
Next, in order to make sort_values work and avoid TypeError: '<' not supported between instances of 'GeoPoint' and 'GeoPoint', a GeoPoint.__lt__ method needs to impose some arbitrary "well-defined" order on (x,y) ...
 
(kind of looks to me like it's making something hashable just to make it hashable and it's not going to have a huge amount of unique hash space)
@smci maybe consider if you're already over-riding a hash method of using functools.total_ordering
must be a reason why the author(s) of that library didn't implement such things though... are there definitely not other methods/ways of doing it? Find it a little bit hard to believe that people able to write a geolibrary would deliberately choose to not implement such a thing if it made any sense on how to do so...
 
10:31 AM
@JonClements Well I hacked on a __lt__ method and it all seems to be working correctly for sorting, nuniques, groupby, aggregation
 
heck... sorting two coordinates - which one is considered first and why... and all that...
 
>>> xpts = x[['o','d']].melt(var_name='isOrig', value_name='coord').coord
>>> xpts[7] < xpts[13]
False
>>> xpts.sort_values()
6 (116.11E:39.86N)
1 (116.11E:39.87N)
17 (116.12E:39.85N)
13 (116.12E:39.87N)
18 (116.19E:39.91N)
2 (116.27E:39.90N)
12 (116.27E:39.91N)
4 (116.30E:39.91N)
8 (116.30E:39.92N)
7 (116.30E:39.95N)
15 (116.30E:39.95N)
19 (116.30E:39.95N)
11 (116.32E:39.89N)
14 (116.32E:40.01N)
16 (116.32E:40.01N)
5 (116.33E:40.00N)
3 (116.33E:40.00N)
def __lt__(self, other):
    """Kludge arbitrary __lt__ method so this works with sort_values etc."""
    if self.x == other.x:
        return self.y < other.y
    else:
        return self.x < other.x
 
kludge?
is that just a word you've made up
@smci I kinda like that word
gonna use it in my python projects now
 
@JonClements And in fact __lt__ is not so arbitrary because everywhere in the world except near the equator, delta_longitude is further distance than delta_latitude (and in my case it's in Beijing, 40N). And it also has the useful and pleasing property that (long, then lat) sort order is roughly the same as command-line or ASCIIbetical sort order (well except when coords go negative, my __str__ is hardwired to assume North and East, cos it's Beijing).
 
@smci I'd go with hash((self.x,self.y))
oh, you said as much in your next message
 
10:37 AM
@AndrasDeak Yes I had already changed to that earlier.
 
yeah, that's the best in this scenario I think, also semantically
the tuples would also work for sorting
(Though you'd have to be specific in what sorting means, it's not obvious. You could also sort by distance for instance)
 
@connectyourcharger Oh no, 'kludge' is a time-honoured word in science and engineering, it was first taught to me by a Canadian electronic engineer I worked with (although she pronounced it 'klooge', so at first I had no idea what she was on about). Equivalently stated, It Gets The Job Done (tm)
 
@connectyourcharger reference
 
the more duck tape the better
 
10:41 AM
duct tape solves everything
 
now you know the philosophy of kludging
 
kludgology
 
@AndrasDeak Right, but I just mean the default pandas pd.Series.sort_values method, as used in value_counts, pd.crosstab and so on. I just want well-defined ordering when paging through seas of these crappy little coords so I don't go stark staring maaaad...
 
the study of kludging
 
@smci OK
 
10:42 AM
@smci you mean you haven't gone mad already!? Join us... it's liberating :p
 
@JonClements The center literally cannot hold, in this coord system :P
 
@JonClements oh no, I'm seeing a talking dog again
 
but this isn't the dog you're looking for... waves hand...
saw a question yesterday I thought I might fancy having a go at and made a note of it... can't bloomin' find it now... sighs
 
our new logo
 
10:46 AM
@JonClements Hmm, thanks for the tip, but all the builtins seem to work as long as we define __lt__ and __eq__, which is the minimal set. (Obviously xpts[7] <= xpts[13] blows up with TypeError: '<=' not supported between instances of 'GeoPoint' and 'GeoPoint', but I don't need the rich comparison operators for my use-case)
 
@connectyourcharger madness is liberating... duct tape serves the opposite purpose or something...
 
oh so we have to change the logo then?
 
"The Kludgeons" sounds like it should be a punk band or something :o
 
let it be so
a theology and a punk band: the kludgeons
 
FYI, this PyCon 2017 talk Sofia Heisler: No More Sad Pandas: Optimizing Pandas Code for Speed and Efficiency and YouTube video are excellent. Invoking df.iterrows really should cause with a (suppressable) warning on performance and bad habits.
 
10:52 AM
is anyone here even remotely familiar with the unofficial chat api?
like, at all?
I've managed to authenticate with the /ws-auth endpoint but any request I send to try and send a message gives me a 500 (internal server error).
aha! never mind
 
@connectyourcharger there's plenty of APIs out there that have something related to chat... we experimented with it ages ago at github.com/sopython/rabbit - but fairly sure someone's written Python libraries for it anyway... look at stackapps?
 
well I'm trying to figure out how it works so I can implement it in my own app later
 
Ah. From [blog by Hynek](https://hynek.me/articles/hashes-and-equality/) *"You shouldn’t compare by value but hash by identity. This approach fails to take the second assumption into account. That said, it usually works perfectly fine because it takes a rather unlikely hash collision to become a problem.*

*However it’s still a violation of the contract with the Python runtime and may lead to problems; albeit only possibly in the future. Python feels so strongly about this that as of Python 3, it automatically makes classes unhashable if you implement `__eq__` but not `__hash__`. Python 2 l
 
maybe I need to collect new cookies...
 
@JonClements In fact hash(self._a) ^ hash(self._b) ^ ... is undesirable as, if only the order of the contents changes, you get identical hashes. See discussion here. So use hash((self.a, self.b, ...)). Also, __eq__ should also check the typie is identical as well as the hash-value.
 
11:13 AM
are you planning making something go "ping" futher or? :p
 
and FYI if you want the expert answer from Cryptography.SE: How to hash a list of multiple items?
 
thanks for keeping me posted with info. For now though, I need to step afk and get Sunday lunch going... will no doubt see you around and good luck :)
 
11:28 AM
Hello guys , kindly need some help
How can uniy test a method with a non return
0
Q: Unit test a non returnable function which randomly generates numbers

Idris StackAm new in unit testing, I have a function which doesn't return anything and generates numbers randomly from a certain number to another, I read about the mocking library but it's still confusing to me, how can I unit test this function. What I want to test Testing if numbers are generated be...

 
@IdrisStack You're not allowed to post questions within 48 hours of their posting
 
yikes sorry
 
it's ok just make sure to read the rules
 
11:48 AM
use the sandbox for testing
 
12:06 PM
@smci That answer makes good points, but it is looking from a crypto perspective, and some of that stuff is irrelevant when you just want decent hashing for a hash table (a dict or set). The built-in hash in Python is quite fast, though its avalanching behaviour isn't fantastic. But that's not a big deal, due to the way dict & set implement their hash tables.
@smci But yeah, hashing the tuple is much better than hash(self.x) ^ hash(self.y). And it's slightly faster, too, since you're only calling hash once per point.
FWIW, here is a link to some info & diagrams I posted here a while ago about hashing & the avalanche effect.
 
12:25 PM
ok this is extremely cool
I figured out how to connect to the websocket for any chat room and stream the messages
 
1:12 PM
now I just have to figure out how to send messages
 
1:22 PM
hi there !
 
1:33 PM
hey
 
@connectyourcharger last warning
 
@AndrasDeak that one was a pure accident
I have two chat rooms open and I thought I was in my testing room
sorry about that
 
2:06 PM
How can I check which date format is more common
I already expect the ambiguous dates to be default to '%m/%d/%y'
what I really need is the following scenario :
I have a list of different format patterns
patterns: ['%d/%m/%y', ‘%m/%d/%y’…..]


Apply patterns[0]
1/3/18 # ‘%d/%m/%y’
1/4/18 # ‘d%/%m/%y’
22/5/18 # ‘d%m/%y’

but if we apply :
Apply patterns[1]
1/3/18 # ‘%m/%d/%y’
1/4/18 # ‘%m/%d/%y’
22/5/18 # ‘%d/%m/%y’

So in this case format ‘%m/%d/%y’ came less than format ‘d%m/%y’ therefor ‘d%m/%y’ should be applied
please help
 
Still on the same problem...
Haven't you gotten any useful insights here already?
 
here is my code so far :
i have thanks to your help all , i could now perfectly guess almost any date format by now
but my problem now is how to apply each found format on the whole list and see which one covers the most , and null values are acceptable
i have a a few lines of codes and i can't find where my mistake is , i'm getting what i need sometimes and sometimes the try/except gives a Null
 
come up with an algorithm, then implement it
Or if you're debugging post your code with an MCVE
It will have to be self-contained and clear
If it's more than a few lines link it from a code paste service
"Check each format, count compatible items, take max" seems straightforward enough. Error-prone as well, of course.
You should still try fixing the data source
 
2:32 PM
sorry trying to format it with paster
 from datetime import datetime
 all_formats: ['1/2/18','1/3/18','5/22/18','15/2/18','15/2/18','15/2/18','15/2/18','15/2/18','15/2/18']


 format_patterns = ['%m/%d/%y', '%m/%d/%y', '%m/%d/%y', '%d/%m/%y', '%d/%m/%y', '%d/%m/%y', '%d/%m/%y', '%d/%m/%y']
 patterns = list(set(format_patterns)) # after no duplicates ['%d/%m/%y', '%m/%d/%y']

 for f in all_formats:
            try:

            conv = datetime.strptime(s,patterns[0])
            formatted = conv.strftime(patterns[0])
            print(formatted ,patterns[0])
 
You need to loop over all the patterns, then for each pattern count the formats that convert correctly. If you have a new maximum, keep the pattern, and maybe the converted dates as well. Don't use bare excepts, only catch what you expect to be raised.
 
this is what i'm trying to do but i keep failing
 
Your code tries to do very little from what I said.
To debug it, print both the format and the pattern in the except to see which one breaks and understand why.
 
2:49 PM
"for each pattern count the formats that convert correctly." i will start with that
thanks
seems like i need multi try/except
 
Probably not. Two loops.
 
one loop for the patterns and one for the formats
yes thank you
for p in patterns:
    for s in all_formats:
        # print('#####',str(patterns[0]))
        try:
            conv = datetime.strptime(s,p)
            formatted = conv.strftime(p)
            print(formatted ,p)
        except:
            print('Null')
output is:
01/02/18 %m/%d/%y
01/03/18 %m/%d/%y
Null
01/02/18 %d/%m/%y
01/03/18 %d/%m/%y
15/02/18 %d/%m/%y
 
initialize best count to 0
for every possible pattern:
    initialize counts for this pattern to 0
    for every possible date string:
        see if the given pattern can convert the given date string
        increment counter if it can
    check counter, if it's a new maximum remember this pattern
^ the naive algorithm
@HarvesterHaidar I'm not helping further if you ignore my suggestions
 
i just need the counter please !
 
good luck
 
3:01 PM
i'm applying them sorry just slow with python , i didn't mean to ignore , i just got your lat suggestion
 
3:11 PM
i don't know how to apply what you suggested , i couldn't agree more with the logic , but it's really complicated for me
thanks for your help anyway , i'll try to apply your suggestion
 
3:38 PM
@AndrasDeak i keep failing
this part is the only thing left " check counter, if it's a new maximum remember this pattern"
i didn't know how to implement it
 
I've started streaming again. Just working more on my baseball card app today. Feel free to come say hi: twitch.tv/codeguru42
 
4:15 PM
Sorry, this is completely unrelated, but I just discovered chatrooms, and this is so cool!
 
Welcome :)
 
4:52 PM
can anybody please simplify the last line for me , there's something i'm not getting

initialize best count to 0
for every possible pattern:
    initialize counts for this pattern to 0
    for every possible date string:
        see if the given pattern can convert the given date string
        increment counter if it can
    check counter, if it's a new maximum remember this pattern
 
Post your existing code for the rest first. Use pastebin or something similar.
I want to make sure you've made use of earlier suggestions
 
best_count = 0

    for p in patterns:
        pattern_counter = 0
        for s in expire_date:
            try:
                conv = datetime.strptime(s,p)
                formatted = conv.strftime(p)
                pattern_counter += 1
                # best_count +=1
                # best_count +=1
                print(formatted ,p)
            except:
                print('Null')
sorry didn't format well
 
0/3, nice
Sorry, I don't want anyone to waste their time helping you.
 
i really couldn't do much with your suggestion , applying them i mean
 
Max
Hey guys, need some help with opencv, when drawing... cv2.convexHull(contour[i]), it looks like it draws points(??) and not the outline...?
 
4:59 PM
that's why i entered this room , i don't know how to do it
please
 
Max
 
@Max it doesn't draw anything, does it?
 
Max
I.E. the above happens, when there should be an outline joining the 'points' together
I'd post a full on question however I feel like I'm doing something stupid instead
 
Aren't you plotting with a different call...?
 
Max
```for i in contours:
cv2.drawContours(img, contours[i], -1, (0,0,255), 2)```
 
5:01 PM
What is contours?
 
Max
cv2.findContours....
 
if it's the return value from convexhull, it's a single contour, and looping over it will give you a point each
 
Max
more specifically.. opencv is version 4, so contours,_ = cv2.findContours(...)
 
Plot a point, get a point.
 
Max
but it shouldn't plot points
Every example shown has it plotted as an outline of said points from the contour
as shown there
bruh i fixed it
 
5:04 PM
for i in range(len(contours)):
        hull = cv.convexHull(contours[i])
        hull_list.append(hull)
OK.
 
Max
yeah, that was the problem lmao
thanks
 
No problem
 
i don't understand how mu code is far from your suggestion
thanks for your time anyways
i'll keep trying
with your suggestions
 
3 hours ago, by Andras Deak
You need to loop over all the patterns, then for each pattern count the formats that convert correctly. If you have a new maximum, keep the pattern, and maybe the converted dates as well. Don't use bare excepts, only catch what you expect to be raised.
2 hours ago, by Andras Deak
To debug it, print both the format and the pattern in the except to see which one breaks and understand why.
13 mins ago, by Andras Deak
Post your existing code for the rest first. Use pastebin or something similar.
Three hard instructions ignored
 
sorry i didn't see the first one
my bad
i'll try again thanks
 
user10648668
5:48 PM
Say I have a list of numbers like {(1.57079632679490, 1.57079632679490, 1.57079632679490), (4.71238898038469, 4.71238898038469, 10.9955742875643), (1.57079632679490, 4.71238898038469, 1.57079632679490), (1.57079632679490, 4.71238898038469, 10.9955742875643), (4.71238898038469, 4.71238898038469, 1.57079632679490), (1.57079632679490, 1.57079632679490, 10.9955742875643), (4.71238898038469, 1.57079632679490, 1.57079632679490), (4.71238898038469, 1.57079632679490, 10.9955742875643)})
 
user10648668
Most of these (I believe) are multiples of Pi or e (standard mathematical constants) and is returned by a SymPy computation. Is there anything similar to FullSimplify in Mathematica, that'll show me the numbers in terms of multiples of mathematical constants or will tell me if they're multiples of square roots of 2 or 3, etc. ?
 
@Blue there's no list in there
 
user10648668
@AndrasDeak Well, it's not exactly a list...
 
I think there is a function that you can give functions/expressions to use
 
user10648668
Anyway, let's consider a list for now...if that simplifies things...
 
user10648668
5:54 PM
@AndrasDeak Remember which?
 
@Blue no, I just prefer to be exact in technical matters :P
vague notions can seed larger confusions down the road
@Blue no, otherwise I'd have told you. It's been a while since I've used sympy (and in any case don't bet on a sure result), I'll try to figure it out
@Blue Actually, if they were exact pi or e-related expressions then sympy would leave them like that. Where are those numbers coming from? Not something like numerical integration or zero finding, I hope.
 
user10648668
Well, that's the context ^
 
user10648668
Basically solving a set of equations. The solutions should be exact multiples of Pi (at least in the cases I'm dealing with).
 
is the formula in the last line based on visual estimation?
 
user10648668
6:00 PM
@AndrasDeak Which formula?
 
the end of the answer you linked
ah, no, that's for the Pauli, sorry
Have you checked solveset? The docs suggests to use that instead of solve docs.sympy.org/latest/tutorial/solvers.html
I have the strong feeling that this is an XY problem and you should force sympy to give you exact results in the first place
if solveset doesn't give saner results I'd try working a bit on paper. For instance the determinant of the matrix seems to be exp(i*(lambda+theta)) which might be much easier on a symbolic solver
Actually, it might be even simpler: the (1,1) matrix element defines theta for you. Then (1,2) and (2,1) define lambda and phi for you. Am I missing something?
 
user10648668
@AndrasDeak Trying, but it seems the arguments vary a bit from solve (reading the docs)
 
(you can use an assertion to check that the three parameters reproduce the final (2,2) matrix element)
 
user10648668
@AndrasDeak Well, that's true. I could try solving for the parameters one-by-one. But even then I'm thinking that solve would still give an approximated decimal result. Could try solveset there maybe
 
or use 2*arccos(1/sqrt(5)) exactly :P
No need for a program
 
user10648668
6:12 PM
Heh, that should actually work :P
 
user10648668
I was trying to be more generalistic...but in this specific case the form of the matrix is nice with not many cross-terms
 
user10648668
Would arccos be able to give me the solutions in terms of Pi or square roots of natural numbers?
 
If one exists, yes
Most real numbers are not nice cosines
 
user10648668
@AndrasDeak Ah, sounds useful
 
user10648668
Trying
 
6:18 PM
You can also use arccos(M[0,0]) etc. for generality...
 
user10648668
> numpy.arccos(1/math.sqrt(2))
0.7853981633974484
 
user10648668
Erm...doesn't seem to work
 
user10648668
This should be Pi/4
 
Sympy...
the num in numpy stands for numerical
Sympy's arccos and sympy's sqrt
1/math.sqrt(2) or 1/np.sqrt(2) or 2**(-0.5) are all double-precision (non-exact) numbers and sympy has no chance to give you an exact result
 
user10648668
>>> from mpmath import *
>>> mp.dps = 25; mp.pretty = True
>>> acos(-1)
3.141592653589793238462643
>>> acos(0)
1.570796326794896619231322
>>> acos(1)
0.0
>>> nprint(chop(taylor(acos, 0, 6)))
[1.5708, -1.0, 0.0, -0.166667, 0.0, -0.075, 0.0]
 
user10648668
6:23 PM
@AndrasDeak I see it's acos()
 
You keep insisting on numerical tools and seem to be surprised that you get a numerical result
@Blue that's possible
 
user10648668
@AndrasDeak Well, I initially wasn't expecting otherwise, but then I came across Mathematica's FullSimplify
 
user10648668
I don't know how it works in the background, but it gives exact results for these stuff
 
you gave it exact inputs
Z = {{-1/Sqrt[2], I/Sqrt[2]}, {I/Sqrt[2], -1/Sqrt[2]}};
the equivalent is -1/sympy.sqrt(2) or something
 
user10648668
@AndrasDeak So you're saying sympy's exact but numpy isn't?
 
user10648668
6:26 PM
Didn't know that
 
of course
5 mins ago, by Andras Deak
the num in numpy stands for numerical
the sym in sympy stands for symbolical
numpy is exact to double precision, which means it's not exact at all
 
user10648668
> acos(1/sympy.sqrt(2))
 
user10648668
> TypeError: cannot create mpf from sqrt(2)/2
 
wrong acos
 
user10648668
@AndrasDeak This is the mpmath one?
 
6:30 PM
indeed
 
user10648668
So what should I use instead?
 
hold on
OK, I thought I was going mad
>>> import sympy as sym
>>> sym.acos(1/sym.sqrt(2))
pi/4
 
user10648668
OK lol, where is sympy.acos() and sympy.sqrt() defined? I couldn't find it in their documentation
 
you're looking at the mpmath docs, not the sympy core docs
"core" not in the official sense I think
 
user10648668
6:33 PM
@AndrasDeak Link?
 
user10648668
Ah, thanks!
 
oddly enough I can't seem to be able to create a symbolic number to show the same thing for sympy:
>>> import numpy as np
>>> 0.1*3 == 0.3
False
>>> np.float64(0.1)*3 == np.float64(0.3)
False
>>> sym.S('1/10') * 3 == sym.S('0.3')
True
gotcha
 
user10648668
Hehe
 
'0.1' even as a string is always parsed as a double :/
the way this works is that once something becomes a double (python float) you've lost
Only strings or symbolic types are exact
This goes everywhere, not just sympy. But mathematica sort of defaults to symbolic numbers.
 
6:50 PM
@Blue FWIW, mpmath can find simple formulas for constants, but for best results you should use at least 50 digits of precision. See mpmath.org/doc/current/identification.html#constant-recognition But as Andras said, you really should be doing all of this symbolically, with Sympy.
 
user10648668
Yup, I didn't really know much about symbolic computations before this. Cool stuff!
 
Just expect a bumpy ride with sympy, it's much less powerful than maple or Mathematica. But it's also 100% cheaper than both.
 
user10648668
Incidentally, the SymPy Online Shell can produce LaTeX output...which is amazing.
 
user10648668
@AndrasDeak Indeed. And for me Mathematica is installed on a Windows OS...which I hate to use.
 
user10648668
Wouldn't be able to buy another Linux version...in the near future.
 
6:54 PM
But if something doesn't seem to make any sense also consider the possibility of a bug. Two years ago we've run into a bug with a student which ended up being known and fixed (in master, not in the latest release). Essentially A*cos(phi)^2 + A*sin(phi)^2 came out as something other than A...
@Blue is it tied to that specific install, or just windows? You can use it on a virtualbox install of windows (the only sane way to have windows anyway ;)
 
user10648668
@AndrasDeak Tied to that specific install...most probably. Otherwise people could buy once and install it on all their PCs. :P
 
Yeah, I guess. Although it could be tied to hardware or something...
 
 
2 hours later…
8:39 PM
recbg
 
cbg
 
ecstatic about Finland winning world championship in ice hockey:D
with a team of nobodies :F
 
not anymore
And what happened to the non-nobodies?
 
they were like "meh"
basically "meh, Finland is not going to win anyhoo"
 
9:03 PM
@AnttiHaapala 🇫🇮
 
9:55 PM
@JonClements CORRECTION to what I wrote on __lt__ : everywhere in the world except near the equator, delta_latitude is further distance than delta_longitude. Duh. One degree of latitude is always ~110.574 km
@connectyourcharger A sidebar on the etymology of 'kludge': I always assumed it was Yiddish or German. origin Turns out most likely Germanic origin
 
10:18 PM
Apr 1 at 13:31, by PM 2Ring
For really accurate ellipsoid work, see Kearney's geographiclib, written in C++, but with bindings available in many languages, including Python. Kearney's algorithms always converge (unlike Vincenty's), and whereas Vincenty can often give errors of a metre or more, the error from Kearney's algorithms are on the order of a nanometre, when used on the WGS84 ellipsoid (the standard ellipsoid used by GPS).
Of course, for the problem you were talking about, the simple spherical model is fine, and calculating a few cosines is a lot faster than computing ellipsoid geodesics. ;)
 
10:35 PM
@AndrasDeak i tried my best to implement your suggestion but i don't know anymore of how to proceed , here's my code on pasetbin pastebin.com/7RqZSsD9
 
the indentation is inconsistent, and you have to tell me how it works and how it doesn't
you should also add example inputs that show when it doesn't give the right (partial) answers, assuming that's still a problem
 
it should work when the counter which saved the "most successful " pattern is a higher value
 
that sentence is too ambiguous, I'm not sure what you're trying to say
 
here's a an example and the output using this approach pastebin.com/UmdvF5q
 
wrong link?
 
10:40 PM
i still can't get it to decide which date format pattern came more
it's just an output line , shall post it here instead of pastebin ?
 
first fix the pastebin link, I can't view it
 
...why not add the input and the code into a single complete runnable pastebin?
 
doing it right now
heres
https://pastebin.com/md12FNt0
i want to end up with only the most successful format pattern
 
OK, so slap on top from datetime import datetime and it's complete. Next time someone asks for an MCVE, show them something like this. It has input, it has output, it's runnable, doesn't have much needless fluff, and you can go on telling them what's wrong with it. This is important.
Before we go on, are you comfortably aware of what the code is doing as it is right now?
 
10:51 PM
all i understand from the code is that it counts the fail and success of applying each format pattern but i expect it to give me just the most common pattern
it's not that clear to me i understand your suggestion from earlier but applying it to the code is suffering for me , all the pythonic rules and indentations
 
Yeah, it only counts fail and success. It's not what you need. For that you need to keep track of the overall "best" (across every pattern). You don't really need the fail counter, because you can always know that fail_count = len(dates) - success_count
@HarvesterHaidar the "pythonic rules" and indentation are just basic syntax, you first have to lay out the algorithm which is pretty much language-agnostic
In this case, you need another counter that is the "best so far". You only set it to 0 once, before the first loop.
 
i will initialise best counter before the 2 loops and where do i need to increment it >
?
 
The success counter is fine as it is. What you have to do after the inner loop (but inside the outer loop) is check the success counter's state against the "best so far" counter, and if it's greater then set the "best so far counter" to this new value. And of course assign the winning pattern to a name.
 
@PM2Ring Dude, it's just Baidu Maps routing users around urban Beijing: longitudes 115.47-117.29º E, latitudes 39.46-40.97º N ... don't light this BBQ with a bucket of liquid oxygen... engineering overkill... I'm not computing polar orbit launch coords either...
 
where should the best so far" counter take the increment from so i can compare it against the success counter ?
 
11:02 PM
@AndrasDeak you're spending huge amount of effort with Harvester, why not encourage him/her to post it as a SO question so you can get recognition for your work?
 
> after the inner loop (but inside the outer loop)
@smci because if I'd see the corresponding question I'd have to downvote and close-vote it
 
@AndrasDeak Yeah I guessed that... teaching person how to fish...
 
i'm learning from him please
 
I'm also >< this close to sending them away so this is sort of a last chance to see if they can use help
@HarvesterHaidar unfortunately if the basic algorithmic part eludes you that's not something we can teach you
 
@HarvesterHaidar Yeah that code's much improved from earlier... try to pay closer attention to all Andras's good suggestions, you should almost be paying him an hourly rate by now ;-)
 
11:04 PM
if the python syntax or idioms elude you we can help, though I'd prefer reading a good tutorial first
 
i can't pay him enough and thank him enough
 
@smci did you kludge together that origin fact
 
@HarvesterHaidar we're all here as volunteers (hence my pushback against wasting people's time here), and you can thank me by doing all you can to improve and learn and by paying attention
 
i'm sorry if i sounded ignorant to your suggestion i just didn't know how to implement them , i'm trying my best and i won't let you waste more time
 
Andras and Harvester why don't we just use a Counter (collections.Counter) keyed directly on the string pattern? Then to increment it (for a given pattern), we just do counters[pattern] += 1. I think thats' cleaner. And Counter has a nice sort method we can use at the end.
 
11:07 PM
So going back to your problem: the inner loop computes for a given pattern how many dates can be converted with it. What you need is to compare that number for a given pattern to the "best so far" (which is initially 0, and has to be checked for each pattern, updated when a new best is found)
@smci there are many ways to do this better, but if Harvester can't put together the fundamental algorithm there's no amount of elegant python that can help them solve this going forward
 
Ah I see you're trying to count successes and fails. But we only need to count (say) successes, we know for a fixed list length L=len(all_dates), that fails = L - successes. So my my first comment is "only have one counter, and count successes, ignore fails"
 
I would expect that the naive, barebones "check the numbers against best numbers so far" is easiest to comprehend
@smci yup
 
...in which case we can simply have a clause except ValueError: pass to trap and silently ignore fails
 
which is pretty much what they originally had
 
I solved it in 11 lines using `collections.Counter`. Here's a sneapk peak at the result:

>>> counter.most_common()
[('%d/%m/%y', 3), ('%m/%d/%y', 2)]
@AndrasDeak Err, I can't seem to reply to his posts now
 
11:21 PM
that's not possible
 
i'm here still trying i managed to increment the best count
sorry i was on the IDE
 
@smci I don't think you're helping at all. You can do it, great, you get a cookie.
 
@AndrasDeak I'm hinting to him/her to use collections.Counter. But, a dict of {'pattern':count} is fine too. Either way, directly increment into counter[pattern] += 1 , no need for temporaries pattern_counter, fail_counter
 
a cookie?
 
I'm certain bringing dicts into the picture will only confuse them more.
Also trying to prod them along two different paths will confuse them too.
let's get a naive solution working in a way that they see what's going on and then we can talk about how to make it better
 
11:24 PM
Guys, don't mean to interrupt this conversation, but the conversation that is going on right now seems like it's going nowhere
Has the user asked a question on SO?
 
I'm having déja vu
 
of what?
 
i asked before on the topic of guessing the format and i managed it
 
Should you not ask a separate question if you are having different issues?
 
11:26 PM
oh lol
Yeah, honestly friends, just break up this conversation, it honestly doesn't seem like it's benefitting anybody at this point
@HarvesterHaidar If you are having new issues, I'd encourage you to post as a question on the main site. That is what it's there for.
 
i'm almost there but i will do as you whish
you've been all helpful thank you for your time
 
@connectyourcharger it really isn't
 
Stack Overflow wasn't made to help people or to teach people. It was intended as a knowledge repository. It's just that with most on-topic questions having been answered in the last 10 years most things asked today are either off-topic, duplicates or helpdesk questions.
5
 
While I don't know enough about the situation to comment, I'd encourage the user to post a question anyway. If they're an intelligent enough person and they can safely assume that their question cannot be answered by another one, then they will post the question. If they can find an answer, they should be intelligent enough to know when not to post a question.
And judging from the user's post history, I think it's OK to assume they are intelligent enough to be self-sufficient on the site.
Tell me if I am wrong in my judgement.
 
11:35 PM
you're totally right
i'll try my best with Andras approach and if i don't come through i will post the question
again thank you all for your time
 
good luck
 
thanks !
 
also, is anyone available to help me test my bot in a separate room?
if not, that's fine
 
If you can explain what you want to do you will definitely get ready-made answers, I'm not sure how much you'll learn from them though based on previous discussions. You'll see anyway.
 
just curious
 

« first day (3144 days earlier)      last day (1809 days later) »