« first day (1959 days earlier)      last day (3213 days later) » 
02:00 - 18:0018:00 - 00:00

02:27
Has anyone had experience with API requests and dealing with separate requests based on the initial one? Like you request something, get JSON back and then while looping through that JSON you make another request during each loop? Suggestions on alternative, or maybe more efficient structure.
 
2 hours later…
04:36
I am very confused by that codeover site ...
how do i use argparse when no options and no arguments are given, so i dont get "error: too few arguments"? is there a way to set a default option when nothing exists?
yes, all i find are default values for options
@JoranBeasley how did your docker experiment go? Any progress on that front?
maybe I'm just not getting what I'm reading, I could just check if argv==0 and not do anything with argparse, but that just seems wrong.
04:57
75
Q: Display help message with python argparse when script is called without any arguments

musashiXXXThis might be a simple one. Assume I have a program that uses argparse to process command line arguments/options. The following will print the 'help' message: ./myprogram -h or: ./myprogram --help But, if I run the script without any arguments whatsoever, it doesn't do anything. What I want...

@L3v3L ^^
thanks @idjaw, that seems like it will work, stupid as hell in my opinion, but yeah :P
there might be other solutions, but that was the first thing that came up in my search. So just sharing it.
meh it went fine ... it was pretty straightforward using docker compose ... Im still not sure I totally get docker. .. but it was cool and I learned a bit
@idjaw sorry if i sounded like I'm beating on the messenger, really appreciate the share ;)
np. :) good luck
05:48
CBG all.
 
1 hour later…
06:50
cbg all...
07:49
Cabbage!
@HenkHolterman, please see my updated question. Thank you for your precious comment. — Kay Lee 2 mins ago
My… precious… gollum.
@poke help me with this...
I created one python package and it's placed in site-packages..
ok
And I wanted to store some values like user entered values
I tried to save this values into json file in packages directory but it not gonna save in that directory ... why ?
is there any other way to save user entered values ?
You can’t really save anything in the site-packages folder. It’s usually in a location where a normal user does not have access. You need root access on Linux or elevated priviledges on Windows to write there. So it’s not a useful location to store any user data since the user has no access there.
You should store user-related things in the user’s home folder, or in some user-specific configuration folder.
Oh... Okay... I'll think about other options ..
08:41
hovalin.com – 3D printed violins.
I don’t even.
Technology is amazing.
And sometimes a bit scary.
09:25
As a fiddle playing techie, that ticks a few boxes...
cbg
Cabbage, all
Re-CBG.
hi
anyone work with intel galileo before?
09:55
@poke This is amazing.
 
1 hour later…
11:14
11:30
I think that server's taking strain
 
1 hour later…
12:55
Thank you all 2 gentlemen. I accepted Mr. Poke's answer as per Mr. Henk Holterman's kindness. — Kay Lee 1 hour ago
13:07
Well done Mr. Poke, much politeness all round :)
Cbg @programmer
Cabbage :-)
13:29
cbg all
13:49
Is there a convention for naming modules with a "_" at the start?
You mean apart from “don’t”? ;)
ha! :)
Maybe for internal modules that are not supposed to be consumed publicly
it's pretty much a good idea to try to avoid that type of design approach in Python. But if you really have to, make sure you test it implicitly (if you are taking a test driven approach).
If you don't want code to be publicly accessible, maybe you shouldn't be making it a module :-P
13:51
It's usually when you don't want other people to use them. For example, one of the gtk submodules is called _gtk because they don't want anyone else to use them.
I'm trying to debug something and it's trying to load a module with an underscore, so I wasn't sure where to find it
Man, pickle is being really slow in saving/loading this 200,000 item dictionary I made.
that's a huge jar of cornichons man
Maybe I should use a different approach...? What's good for Big Data of this magnitude?
redis?
first key/value storage that came to mind
13:55
pickle just raised a MemoryError so I guess I can't tough it out.
a quick googleweb search provided some suggestions to pickle to multiple files
as well
"Redis is an open source (BSD licensed), in-memory data structure store, used as database, cache and message broker." in-memory sounds like the opposite of what I want. I want this data to continue existing after my program ends, so I can read it the next time my program starts.
Or am I misinterpreting "in-memory"?
yes. Here is info about its persistence: redis.io/topics/persistence
Ok that looks a million times fancier than what I need. I'm going to take a look at shelve first.
I have a default config of redis. I set a few keys, shut down my server, restarted and was able to retrieve my keys. So you should be good with the default install even.
14:02
The fact that an installation process is required at all is a strike against it, frankly. My patience for third party libraries is very thin when I'm working on a Dumb Friday Project that I'll probably delete within the week.
oh
yeah...screw that :P
But shelve uses pickle?
guys :| I am so bad at managing event listeners
Having said that, Redis apparently only saves string values untrustworthy reference
I don't know what shelve uses, but apparently I don't have it. anydbm.error: db type could not be determined
14:10
it might be just as performant, but there is a pickle extension called dill: pypi.python.org/pypi/dill
Morning cabbage.
Oops, the file I was saving to already had data in it. Ok, now it's working for my 100-item test dict.
morning Morgan
Let's try it on my 200,000 item dict, which will take five minutes to generate.
*starts Jeopardy music
Yo Dawg, I heard you love RAMS....
@Kevin just reading the docs it seems to talk a lot about pickling.
Yeah, I know. I thought it would, I dunno, flush I/O more frequently than regular pickle does.
if this is a project you are going to throw away and you just want this to work, there is no harm in installing redis, then uninstalling. Let the redis flow through you
dooo it
Redis the new black
14:17
Well I really only wanted serialization because the program algorithm has three steps and the first step takes forever to run so that makes it hard to debug the second two steps.
The final product wouldn't require serialization at all.
Considering I'm in like minute 40 of trying to get serialization to work, I could have been done my project already, assuming each test only takes five minutes and assuming I could hammer out all bugs in fewer than eight run-crash-debug cycles.
So maybe I'll cut my losses and do that instead.
how long does it take to stop typing "true" instead of "True" in Python... :( haha
Took me a while
I once wrote several javascript methods inside a Python class when I was heavily working in both. My brain didn't click for a while....
There should be a way to tell vim to correct that.
There probably is, actually, but I don't know it.
14:25
import the "fix my brain" extension to vim? :)
dumb python question but is there a better way to do a loop like this in Python?
        start_time = time.time()
        loop = True

        while loop:
            if time.time() - start_time > timeout:
                raise RuntimeError("fail")

            try:
                self._trystuff
                loop = False

            except MyException as e:
                if time.time() - start_time > timeout:
                    print e, 'p =' + str(p) + ' cmd= ' + cmd
                    raise
I usually prefer to have a break statement rather than creating an explicit "should continue looping" flag.
does a break just immediately exit the while ?
that'd be cool
yes
ahh, then just while True for the loop. that's cleaner
It immediately* exits the closest enclosing loop. Not necessarily a while.
This has bitten me a couple times, ex. When I do
14:30
yeah. in my case it's just a single loop so easier. but good to know :)
while True:
    for item in x:
        if some_condition: break
    more_code_goes_here()
Is there an easy way to break out of 2 loops at once? That is, from an inner loop break out of the outer loop?
... Mistakenly thinking that the break kills the while loop, when it doesn't actually.
does it break an if statement too?
You can't break an if statement.
14:30
ah, nevermind. you had a for too :)
@zondo, not really. @enderland, nope
There are some languages that let you break out of multiple loops, but it really ends up being a GOTO statement.
You'd basically have to do
should_break_A = False
while A:
    while B:
        while C:
            if condition:
                should_break_A = True
                break
        if should_break_A: break
        some_code_goes_here()
    if should_break_A: break
    some_code_goes_here()
reasons not to nest too many loops... :)
Or just refactor the inner loops into functions.
14:33
Yeah, when I need to jump out of multiple loops, I refactor everything so that return puts me exactly where I need to be.
Python is definitely something I'm enjoying
Cabagge all
If I find myself with nested loops, I think long and hard about how I should not have that and I refactor the crap out of it.
@idjaw you would cry if you saw my code lol
I'm too much of a perfectionist right now
14:38
My flask view has 2 nested loops inside a main loop, and then AFTER rendering, the template has 3 loops nested inside another loop. LOL I'm a super coder apparently
I usually only get real loopy when I'm writing something with a tricky algorithm. Path finding or minmax or something like that.
does python bubble exceptions? like if a sub method throws an exception, will it make it to the caller method? I'm assuming yes..
This is the same stupid json api crap I've been dealing with all week. I think it's more just my lack of understanding json/dictionaries/nested information. I've basically given up on actually making use of the json and just feel like dumping the entire request into a DB and just talking to it instead lol.
@enderland Yeah.
but it can't if you code things wrong. lol. doh
14:43
@enderland make a pastebin for your exception code that isn't working.
In my experience, when I code things wrong that's when the most exceptions bubble up :-P
@idjaw no it wasn't working because I was an idiot, I fixed the symptom but not sure about the cause :P
I generally find that fixing the cause of bugs involves hiring someone to replace me
my current work is a dev tool, so bubbling exceptions to kill the app is much better than a customer facing app :)
14:49
cabbage all
just want to say thank you to everyone here
landed my first job yesterday....yayy!!!
i've really gained a lot from the discussions here and SO in general
Congrats
Sometimes you can refactor out this test-break-test-break business in nested loops using next(generator_expression):
SE is a trap...
    # cube = 3-d nested lists representing cells in a cubic structure
    # look for the first cell that satisifed predicate function
    found_cell = None
for grid in cube:
    for row in grid:
        for cell in row:
            if pred(cell):
                found_cell = cell
                break
        if found_cell:
            break
    if found_cell:
        break
found_cell = next((cell
    for grid in cube
        for row in grid
            for cell in row if pred(cell)), None)
I've only ever used it for for-loops, tho - while loops won't go in the generator expr too well.
morning everyone
14:56
I'd probably just do
def find_cell(cube, pred):
    for grid in cube:
        for row in grid:
            for cell in row:
                if pred(cell):
                    return cell
    return None
Anyone familiar with heroku Procfile syntax?
is there a way when patching or doing tests to basically make a method do nothing? I don't really like nesting patches like 5 lines deep :(
like:
self.foo.my_bar_func = 1
or something like that?
Define it as (lambda: None)?
Here is a decorator for enabling/disabling functions: wiki.python.org/moin/…
The main part:
def unchanged(func):
    "This decorator doesn't add any behavior"
    return func

def disabled(func):
    "This decorator disables the provided function, and does nothing"
    def empty_func(*args,**kargs):
        pass
    return empty_func

# define this as equivalent to unchanged, for nice symmetry with disabled
enabled = unchanged
Then put @disabled above the function defn to turn it off
oh woah lambda functions are legit
15:09
If I get three more up-votes, I reach the reputation cap. Anybody?...
@SudoGaron I've done it once or twice, usually you can just steal someone else's, what're you trying to do?
@PaulMcGuire is there an advantage to doing this over just a lamdba: None approach?
I'd say a matter of taste and visibility more than anything - where would you put your lambda?
I'm using it in tests - to mock out functions
The decorator might be clearer, easier to grep for
15:11
and by "mock out" I mean removing them from doing anything
I previously was doing a nested with patch('foo.bar') as foobar_mock: thing
that is unwieldy if I just want the function to basically do nothing
@corvid I've used it with running an app in the root. but I've restructured my app int a sub folder. so TestApp/main/__init__.py has my "app" initialization. I tried doing "web: gunicorn main.__init__:app" but that failes. wasn't sure if it doesn't like subfolder?
@idjaw decorators being the @patch approach?
correct
I feel like that's harder to read than nested patches
not at all
15:13
because order matters
my feelings might be wrong :P
give me a minute I'll show you an example....have some work things to do....pfffttt work
hah. no worries :)
@idjaw the specific code I'm working with is like this:
Good. I'll re-write that
err, sorry. I probably deleted it too early :P
Uk afternoon cabbage. Here's hoping for POETS.
15:26
@enderland Take a look at two solutions I recently wrote using decoratores to mock, it really makes the code cleaner: here and here
@idjaw hmm. I think the thing I dislike is that it then requires you to organize them much more significantly than I want - though I guess you could do all the arguments in the decorator right?
If my program has no bugs, then I've made an AI player for titanic tic tac toe that is unbeatable if it goes first.
Too bad it takes a couple minutes to explore the entire tree of possible game states at the start of every game.
@enderland I just find nested code really hard to follow. I like to limit the amount of indentations that go in to my code, so when I saw that I can use decorators for my mocking instead of the context manager, I was sold.
Now to pit my meaty human brain against it to see if I can work out a pattern to his moves. Then I can turn it in for rep.
@idjaw do you have to pass all the mock objects into the testcase if you don't plan on using them?
eeerr, I can figure that out myself. lol
> takes exactly 1 argument (3 given)
15:30
Whatever method you are calling that uses any other external method should be mocked.
you want to control the behaviour based on the different inputs to your method.
@SudoGaron just checked out my old project that used one but alas it would not be of much help :\ my manage.py is in my base directory
so something like this instead:
    @patch('socket.inet_aton', side_effect=socket.error)
    @patch('subprocess.check_output', return_value='foo')
    @patch.object(DockerRunner, '_cleanup_docker_container', side_effect=None)
    @patch.object(DockerRunner, '_start_docker_container', side_effect=None)
    def test_assign_ip_timeout_period_raises_runtime_exception_decorated(self, s_mock, co_mock, dr1_mock, dr2_mock):

        self.dr._docker_start_timeout = 0.01

        with self.assertRaises(RuntimeError):
            self.dr.start_docker_container(self.dc)
I guess that is easier to read. :P
now that I understand the mock paradigm at least
Understandably you have all this stacked @patch junk on top of your def
but look at how clean that implementation is inside your method. :P
@idjaw yeah. I think it's still a bit better? idk
tbh it's all preference. Don't let me push you in to something that you don't like. ;)
15:37
I guess I need to pass those patches into the method and that's the part I dislike
like it could be, for practical purposes:
def testname(self, a, b, c, d):
@corvid it's ok :D TY for looking at least. I appreciate it
trying to get this thing up in the world for some coworkers to test, etc.
and the arguments are passed backwards
which is screwy
like, my arg order is backwards in the example
I went through the pains of really understanding how decorators work and why it's all structured the way it is. It did give me a headache...but I don't regret it.
yeah. I think initially it was super confusing but now that I "get" the paradigm more doing it with decorators makes complete sense
enderland is rewriting all tests to use decorators :P
YES! CONVERTED ANOTHER!! HUZZAH!!
15:41
can you declare the mock name in the @patch statement? like:
@patch('foo', return_value='bar') = foo_patch
so when you declare your test you can know you put arguments in it correctly?
no
hello
given that I store an exception in an object, do I have a way to later print its stack trace?
oh, the trace
15:43
traceback.print_exc means that I have to be at the point where the exception is
@enderland yeah, I have the error itself, but not the trace
@FlorianMargaine are you looking for something like this: stackoverflow.com/questions/8238360/…
because that way, as long as you store it somewhere, you'll always have that stack trace for that particular exception.
@idjaw no, it's in the context of gevent which stores the exception itself gevent.org/gevent.html#gevent.Greenlet.exception
@SudoGaron if you wanna do it fast you can probably put a manage script in your base directory, flasky has a good pretty quick example
@idjaw it definitely makes things look nicer if you understand the mock paradigm
15:49
I just reached the reputation cap. I think I'll be gone for a while.
Okay, what do you guys think of this answer to the question "What will happen if Google decides to fork Python 2.8?"?
this one here yet?
HAHAHA
I had to upvote that answer
15:55
I wrote a comment there :P
haha just saw it
I've written device drivers in python
@AnttiHaapala Very good.
python is very different than JavaScript though
but javascript with its floats and lack of proper binary types is like pfft :d
16:00
@FlorianMargaine - be careful with storing exceptions. I did this in older versions of pyparsing, and users on Py3 started reporting many memory issues.
@PaulMcGuire well, right now it's only storing str(exception), which is totally fine for prod usage, but unusable for debugging
and I have no way to store exception... because gevent prevents that.
I don't want to hack gevent ._.
The core issue is the storing of the traceback - which is unfortunately the very part that you want when debugging
Try using the traceback module to persist the last 'n' levels of the stack trace as simple tuples along with the exception string.
@PaulMcGuire gevent itself doesn't store the full exception, which is the core issue
@FlorianMargaine you could use the traceback module to get the traceback as a string
Oooo, just got my first recruiter spam. They want me to join them in creating "Dark Web Intelligence".
16:08
@AnttiHaapala no, the traceback must be used where the exception is thrown
late morning cabbages, all
how goes the battle against all that is eval?
I now see the exc_info property...
@MorganThrapp do it...dark web it up. VB GUI...trace IP...do it.
@idjaw I'm tempted to reply to them and tell them that I'm more interested in the Dim Web.
16:16
tell them you are only paid in energy drinks and cheetos
like the real pros
I'll accept mountain dew and doritos in an emergency.
For my interview, I'll just spend the whole time on hackertyper.
instant-CTO hire.
Having said that, I can't tell if they actually did their research or if it was a lucky guess, because I did spend a lot of time in my teen years reading everything I could get my hands on about The TOR Project. Though, I don't know that there would be any record of that.
I ran an exit node for a bit, and even had Tails on a laptop.
Back when I was convinced I was going to be a hacker, but before I decided that it seemed too hard. :P
The CIA has been on to you ever since, and that recruiter was a CIA code letter
psssst
you're being recruited
you're fighting freedom now Morgan. God speed.
It seems that the logging module is still mired down in old-style string interpolation, full of %(this)s and %(that)s. Feels weird when I'm trying to lift myself up to Py3.
and would like to use "lskdjf {this} and {that}" instead
16:23
I would think it would be more NSA, but I have always thought working in intelligence would be cool.
The pieces just keep fitting betterer and betterer
DSM
DSM
Almost-noon cabbage for all.
cbg, DSM
DSM
DSM
I never know what to do with questions like this when I'm pretty sure the answer is simply "No."
Usually I just leave a comment saying "No, there's nothing in stdlib, look at x instead"
16:31
I don't say anything because answering "No, there's absolutely no way to do X anywhere in the built-in libs at all" is a good way to get a "well actually..." reply.
I believe there's a sizable population of SO users that have little interest in answering questions, but absolutely love proving other people wrong. No reason to create the perfect scenario for them.
DSM
DSM
I'm 99% sure there's no public built-in function which does this. I can't rule out that there's an unintentionally exposed function in some module which does.
(For example, there's a flatten in compiler.ast in 2.7.. which isn't great code, and used to be broken because they shadowed a name.. one of the few patches I've gotten into core. :-)
^^That's pretty cool
gj :)
<dm> I discovered that you'd never get an answer to a problem from Linux Gurus by asking. You have to troll in order for someone to help you with a Linux problem.
<dm> For example, I didn't know how to find files by contents and the man pages were way too confusing. What did I do? I knew from experience that if I just asked, I'd be told to read the man pages even though it was too hard for me.
<dm> Instead, I did what works. Trolling. By stating that Linux sucked because it was so hard to find a file compared to Windows, I got every self-described Linux Guru around the world coming to my ai
I've got that one bookmarked :-)
DSM
DSM
Depressing, but not entirely inaccurate.
16:37
you mean "but entirely accurate"
I've tried the "Python sucks because I can't do [thing]" tactic here and I only have about a 20% success rate.
DSM
DSM
@Florian: It doesn't match my experience. I'm good with algorithms but not much good with system-level stuff, and so I often find myself in need of assistance.
It's because that's too obvious of trolling. Python is too good for anyone to believe you.
I choose to believe it's because the problems I can't solve on my own are truly difficult and nobody responds because they don't know of any solution.
(Which isn't to say I've never asked an easy question. This is just for questions that I ask in the "Python sucks because I can't do thing" format)
DSM
DSM
The standard Python response to "I can't do thing", after some flailing around, is "well, so don't hold your arm like that," which is usually justified..
16:47
Python sucks because I can't pickle a ten megabyte dictionary.
you're still on that?
You need to import vinigar first.
I gave up on that, but after about 20 design-run-redesign cycles, each one five minutes long, I'm thinking about ungiving up.
DSM
DSM
? If I scroll up, will I find this explained?
I'm trying to write an unbeatable AI for titanic tic tac toe. Or rather, I'm trying to write one that doesn't require a five minute trip through the entire solution space every game.
There are 9*9 * 3^9 possible game states (not all of which are reachable from an empty starting board, granted), so it takes a while to grind through 'em all.
In practice it's more like 200,000 states.
But actually, if I only include game states that are reachable when the first player plays perfectly optimally and always chooses the first move leading to the fastest win, the decision tree is an order of magnitude smaller or more.
So I may just serialize that instead. the AI won't be able to play any arbitrary game state, but it will be able to win from an empty board.
16:55
Is "Is there a quick function I don't know of" grammatical?
I suspect it isn't
Looks grammatical to me but it's not quite idiomatic to my ear.
I'd go with "I don't know about" or "I'm not aware of"
Thanks, it was in a post I was editing
DSM
DSM
"My coffee cup is missing and you swear you didn't touch it. I thought there were only the two of us here. Is there someone I don't know of?" sounds fine, though casual, to my ear.
Funny, my reaction is opposite: I find it a bit stiff and/or archaic.
(emphasis on "a bit". If I heard it employed in ordinary conversation by a native speaker, I wouldn't think about it for more than half a second)
DSM
DSM
Yeah, but you say "baahg" instead of "bayg", so I can't take your opinion seriously. ;-)
17:01
:-P
DSM
DSM
It's true though that I think most people would say 'about' there.
Ok, got the optimal decision tree down to 18 kb. Now to jsonify it and write a jsfiddle to demo it.
I'd say the trailing "I don't know of" is contextually redundant, since, if the OP knew of it, he wouldn't have posted in the first place.
Should only take, oh, the rest of the day... Here's hoping nobody answers the question by then.
I didn't see any obvious overarching pattern to the AI's moves, so I think I'm really only competing against other brute-forcers like myself.
Of which there are 2-3 on Puzzling that Kevin me with some regularity.
well, I guess you could make the case for an alpha-beta pruning to trim your brute force
DSM
DSM
17:10
I'm going to be very happy when my current project is over and I can allow myself to be sniped by puzzles.
on the puzzle note ... this is fun(ish) ... tbf one or two tricked me slideshare.net/NandanSawant/python-puzzlers-2016-edition
DSM
DSM
@PaulMcGuire: if a function doesn't call itself, I really think "recursive" is a stretch.. I grant (having just checked) that the common definitions do actually seem to cover this case, but still..
has anyone messed around with this? github.com/anishathalye/neural-style
I'm new to programming/command line, trying to figure out the arguments for this
@DSM - I think this uses "recursion" in the mathematical sense vs. the programming sense. I remember learning in middle school about creating a recursive expression, which was of the form "X(sub i+1) = some expression of X(sub i), X(sub i-1), X(sub i-2)...".
(Is there a subscripting markdown?) Maybe something LaTeX-ey, like x_i?
DSM
DSM
No, nothing convenient like that. But we have Teams!
17:22
But I need "x-sub-i", and there is no "i" in Teams... :(
DSM
DSM
I can't deny that the more mathy definition applies here, but I think it causes more confusion. Since both you and the OP use it, I'm probably in the minority.
Maybe we need a new term for this, some combination of recursion and iteration - recurteration? itercursion?
17:55
Argh gosh darned binding callbacks in a loop! throws hat to ground, stomps it
DSM
DSM
JS?
Yeah.
for(var move in responses){
    var button = create_button(
        repr(move),
        (function(x){
            return function(){player_moved(x);}
        })(move)
    );
It will have to do.
02:00 - 18:0018:00 - 00:00

« first day (1959 days earlier)      last day (3213 days later) »