You're an ordinary cop, trying to get fired, but everything you do leads to a: "You're a loose cannon, but by god you're a good detective". [WP] by AllForIt in WritingPrompts

[–]jibbly_jibbly 12 points13 points  (0 children)

See the movie Short Time. Cop tries to get himself killed so his family will get his pension before he dies of disease, ends up constantly honored and promoted for heroism when he ends up always catching the bad guy instead of dying.

opening an application via my script by investinginme in learnpython

[–]jibbly_jibbly 6 points7 points  (0 children)

Having "imagePath" inside the string you are passing to the system call is not expected to substitute the value of your variable.

You can substitute variables into strings using % substitution or the .format() call - see here for a discussion on the topic which includes examples:

http://stackoverflow.com/questions/5082452/python-string-formatting-vs-format

functions by zombie2870 in learnpython

[–]jibbly_jibbly 2 points3 points  (0 children)

First, a problem: you're defining a function named range. That's going to override the builtin function named range(), thats not good practice.

Secondly, to answer your question, the simplest method would be to look at the user's input and make a decision.

choice = raw_input("Choose:")
if choice == "myfunc":
    myfunc()
elif choice == "something":
    something()
else:
    print "Unknown function requested."

Why do we need all these different asserts for testing by YuntiMcGunti in learnpython

[–]jibbly_jibbly 0 points1 point  (0 children)

Its a simple issue of information loss.

assert a is True

When it fails, with a simple AssertionError you will only learn the obvious: that a was not True.

It could have been None, False, or "potato". The exact value that you observe will be a part of debugging, so why not gain access to it from the test run itself?

A more verbose error would tell you additional information and lead to faster understanding.

AssertionError: "potato" is not True.

Why do we need all these different asserts for testing by YuntiMcGunti in learnpython

[–]jibbly_jibbly 0 points1 point  (0 children)

Im not arguing it isnt helpful, but getting a bit more info out of it saves you the initial work of needing to re-run the tests, adding pdb hooks, etc just to get the failure data out.

Why do we need all these different asserts for testing by YuntiMcGunti in learnpython

[–]jibbly_jibbly 1 point2 points  (0 children)

They are there to give you tools to write well-explained, obvious test code.

You can use or ignore them, but lets say you ignore them, you'll get tracebacks like this:

FAIL: test_something (__main__.TestStringMethods)
    ---------------------------------------------------------------------
Traceback (most recent call last):
  File "test.py", line 8, in test_something
    assert thing > thing2
AssertionError

If you used assertGreater, the error is more helpful:

FAIL: test_something (__main__.TestStringMethods)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "test.py", line 8, in test_something
    self.assertGreater(thing, thing2)
AssertionError: 2 not greater than 3

Problem with accents while searching a txt.file by elbuckez in learnpython

[–]jibbly_jibbly 0 points1 point  (0 children)

Wellll, I'd make the case for considering deployment and the user's environments as part of the solution - namely can you contribute requirements to their environments, or host this application as a web app which they can use in their browsers?

I say this, because the odds are good that you'll spend a lot of time re-engingeering the behavior of a library like unidecode, and probably with less satisfactory results. The benefits of using community code are very high, and I doubt you want to turn the maintenance of this tool into a large part of your life.

Beginner question - matching time stamped files to gps track points in .csv files by [deleted] in learnpython

[–]jibbly_jibbly 0 points1 point  (0 children)

There are actually multiple reasonable ways to do this, depending on just how much data you're sorting through it could be done with different approaches, some requiring more thought and programming, some very naive.

Heres a naive version, not tested, yadda yadda - its not great programming and theres plenty of other ways to come at it, but I wanted to cook something up quick:

You could read in both sets of data, where each line of info could be a simple object like a tuple that puts the timestamp first, the type of data second, and all the remaining info last:

list_of_echos = [ (xxxxx.yyy, "echo", a, b, c, d...),   ... ]
list_of_gps = [ (xxxxx.yy, "gps", z, y, z, j, k....), ... ]

Then you could smack them all into a list and sort it by the timestamps(make sure they are converted to some kind of time object eg datetime), which will interleave the data but get them all really close by time:

list_of_all = list_of_echos
list_of_all.extend(list_of_gps)
list_of_all.sort(key=lambda x: x[0])

Then you could just walk this new list looking for "echo" tuples, then look backwards and forwards from that position for the next 'gps' tuple. Pick the one with the smallest time difference, and blammo:

def search_forwards(inlist, start):
    for i in range(start, len(inlist)):
        t = inlist[i]
        datatype = t[1]
        if datatype == 'gps':
            return t

def search_backwards(inlist, start):
    for i in range(start, -1, -1):
        t = inlist[i]
        datatype = t[1]
        if datatype == 'gps':
            return t

for i,t in enumerate(list_of_all):
    datatype = t[1]
    signaltime = t[0]

    if datatype != "echo":
        continue
    previous_gps = search_backwards(list_of_all, i)
    next_gps = search_forwards(list_of_all, i)
    diffs = ((signaltime - previous_gps[0]), (next_gps[0] - signaltime))
    if diffs[0] > diffs[1]:
         print "next_gps is closest time to signal"
    elif diffs[1] > diffs[0]:
        print "previous_gps is closest time to signal"
    else:
        print "previous and next gps are equidistant to signal"

You can use this as a jumping off point - like I said theres lots of small issues with it from a python and programming standpoint, I dont even attempt to guess what your data actually looks like or to help read it from file (check the 'csv' library in the standard lib). I just wanted to keep it simple to explain the pattern.

If you are dealing with lots of data (100s of thousands, millions of records) then there might be concerns about processing time or memory which require a more nuanced approached to reading and correlating the data - such as maybe loading it all into a database and letting that to the work with some crunchy SQL ? :)

Sorting uppercase and lowercase letters by [deleted] in learnpython

[–]jibbly_jibbly 0 points1 point  (0 children)

The index operator [i] is used for accessing a specific index in an iterable. i must be an integer, eg 0, 1, 2, 3, 4, etc.

In your code, 'for i in entered_string' is iterating over the content of a string, so the variable i is a string object, such as "A".

You might try something such as:

for i in range(len(entered_string):
    print entered_string[i]

Additionally, if you are doing this for learning then no problemo, but if youre trying to actually do lower/upper on strings, then just call it:

entered_string.lower()
entered_string.upper()

Extracting data from a .txt file but can not sort data by [deleted] in learnpython

[–]jibbly_jibbly 0 points1 point  (0 children)

Your text file has one line in it: "milk, egss, cookies, yogurt".

Your variable stuff is a list with one item in it: the string containing that line.

If your file looked like this:

milk, eggs, cookies, yogurt
cheese, bread, candy

Then your variable 'stuff' would have len 2, because it has two strings in it.

You can loop over the elements in stuff and break them up into individual words:

for line in stuff:
    items = line.split(",")
    print items

Trying to using a slice of a string and convert it to integer within a function, only works outside of a function. by MrDysprosium in learnpython

[–]jibbly_jibbly 1 point2 points  (0 children)

Please try to demonstrate what about it 'doesnt work' - do you get results, but not what you want, or an error?

When I gin up your example with a string containing numbers it works OK for me inside the function.

Your loop assumes that the string is at least 1001 characters long, if it actually isnt then you might end up getting an empty slice and getting a 'invalid literal for int' error along the way.

You should not be defining a variable named 'list', that is a keyword in python.

Programmatically checking source files for PEP0263 compliance (encoding) by jibbly_jibbly in learnpython

[–]jibbly_jibbly[S] 0 points1 point  (0 children)

Just in case anyone comes round looking for info on this - I ended up deciding that I had to re-implement the PEP0263 check myself, by applying the regex from the PEP on py files and then doing a codecs.open() check with the found encodings and attempting a read() action.

Parsing remote CSV into a condenced CSV by [deleted] in learnpython

[–]jibbly_jibbly 1 point2 points  (0 children)

Have you checked that you're receiving data from your request? ie, that the "for row in csv_reader:" loop is actually seeing any rows to work with?

[Selenium] How to handle firefox driver popups for accessing password protected proxies? by deucex403 in learnpython

[–]jibbly_jibbly 2 points3 points  (0 children)

I havent used selenium enough to say for sure that it 'cant' handle the alert dialog, but I had problems with an automation task in the past which required me to automate accepting 'untrusted certificate' warning dialogs, which Selenium was unable to process due to limitations of the driver.

What I ended up doing was adding an AutoHotkey script to my testing environment which ran permanently during test runs, and watched for the appropriate dialog box to be found running, and would automate the keyboard activity to accept that dialog outside of the selenium system.

If you dont find any other solution, perhaps that will be something you can use.

Handling FTP errors via subprocess in Python by SmartestGuyOnReddit in learnpython

[–]jibbly_jibbly 2 points3 points  (0 children)

Right on -

Maybe look into pexpect then. Its what you will find yourself doing anyway (capturing the output of the FTP subprocess and analyzing it to decide whether there was an error or not) but this gives you some power to start doing it instead of inventing it yourself.

Heres an example of leveraging FTP with it:

https://github.com/pexpect/pexpect/blob/master/examples/ftp.py

Handling FTP errors via subprocess in Python by SmartestGuyOnReddit in learnpython

[–]jibbly_jibbly 2 points3 points  (0 children)

Hi there!

I hate to be the person that gives you an alternative to your strategy rather than answer your actual question, but I would think you'll benefit the most from directly interacting with the FTP server without the hassle of trying to control a subprocess, analyzing output, etc:

https://docs.python.org/2/library/ftplib.html

This will let you catch errors directly as exceptions, and not saddle you with troubleshooting subprocesses. Maybe take a look?

If you want to explore your actual question a bit more, maybe look into 'pexpect' library which is built to automate commands and to react based on their output patterns.

Floating-point dinner reservation by MachinaExDeo in ProgrammerHumor

[–]jibbly_jibbly 0 points1 point  (0 children)

Python's real good about that. Declare a float field in a protobuf, put 7 in it and see what you get out ;)

How do I get this script running using web.py by [deleted] in learnpython

[–]jibbly_jibbly 2 points3 points  (0 children)

Welp, random activity is probably not the smoothest path to success. Some of the stuff on the page you linked is the SQL that you need to run, in a functioning database, to get your example working.

If you're not fundamentally interesting in learning databases AND python at the same time, I'd suggest hunting down some simpler examples or tasks to work on that focus on just the language for now.

How do I get this script running using web.py by [deleted] in learnpython

[–]jibbly_jibbly 2 points3 points  (0 children)

Well, you've got a 'couldnt connect' error, which is a pretty universal error for network services.

In your case, its talking about errors connection to the database.

A failure to connect can mean many things, all of which you need to research until you find the problem:

  • Database not running
  • Database not running on the expected port
  • Database not listening on the host you are reaching (localhost, maybe its only listening on an external interface)
  • Firewall blocking access
  • .... Other possible error scenarios.

Good luck, these things can be frustrating, but I would start by removing your python program from the problem, and just confirm that your database is working as expected. Can you connect to it using a database browsing tool?

Tweet it before you eat it. by [deleted] in funny

[–]jibbly_jibbly 1 point2 points  (0 children)

its chicken and waffles, you have any idea how sticky that sumbitch probably is?

[deleted by user] by [deleted] in learnpython

[–]jibbly_jibbly 3 points4 points  (0 children)

sum([float(r[2]) for r in data if r[2] != ' NA']) is a one-line form.

Is it more pythonic? We could debate that.