content stringlengths 85 101k | title stringlengths 0 150 | question stringlengths 15 48k | answers list | answers_scores list | non_answers list | non_answers_scores list | tags list | name stringlengths 35 137 |
|---|---|---|---|---|---|---|---|---|
Q:
In Python, why won't something print without a newline?
import time
import sys
sys.stdout.write("1")
time.sleep(5)
print("2")
will print "12" after 5 seconds
import time
import sys
sys.stdout.write("1\n")
time.sleep(5)
print("2")
will print "1\n" right away, then "2" after 5 seconds
Why is this?
A:
If you add ... | In Python, why won't something print without a newline? | import time
import sys
sys.stdout.write("1")
time.sleep(5)
print("2")
will print "12" after 5 seconds
import time
import sys
sys.stdout.write("1\n")
time.sleep(5)
print("2")
will print "1\n" right away, then "2" after 5 seconds
Why is this?
| [
"If you add \"\\n\" then stream is flushed automaticaly, and it is not without new line at the end.\nYou can flush output with: sys.stdout.flush()\n",
"Because stdout is buffered. You may be able to force the output sooner with a sys.stdout.flush() call.\n",
"The sys.stdout.write command from the sys module pur... | [
29,
9,
5,
4,
4,
1
] | [] | [] | [
"posix",
"python"
] | stackoverflow_0005917537_posix_python.txt |
Q:
Reinventing the Counter class from collections module
Just for fun, I tried reinventing the Counter class from the collections module.
My intent was simple. Given a list, map the element to frequency in which it occurs.
Here is what I wrote:
>>> l
['a', 'a', 'b', 'c']
>>> d = {}
>>> for a in l:
d[a] = l.count... | Reinventing the Counter class from collections module | Just for fun, I tried reinventing the Counter class from the collections module.
My intent was simple. Given a list, map the element to frequency in which it occurs.
Here is what I wrote:
>>> l
['a', 'a', 'b', 'c']
>>> d = {}
>>> for a in l:
d[a] = l.count(a)
>>> d
{'a': 2, 'c': 1, 'b': 1}
Just wondering, how goo... | [
"Let's concentrate on the only relevant part:\nfor a in l:\n d[a] = l.count(a)\n\nThis is pretty bad, it calls .count() for EVERY member and .count() goes over every member itself so this complexity is O(n^2).\nThis is O(n):\nl = ['a', 'a', 'b', 'c']\nd = {}\nfor a in l:\n if a in d: # we saw a before\n ... | [
3,
0
] | [] | [] | [
"counter",
"dictionary",
"python"
] | stackoverflow_0005917628_counter_dictionary_python.txt |
Q:
Find all decorated functions in a module
Is it possible to find out if a function is decorated at runtime? For example could I find all functions in a module that are decorated by "example"?
@example
def test1():
print "test1"
A:
Since you have indicated that you have the control over the wrapper code, here ... | Find all decorated functions in a module | Is it possible to find out if a function is decorated at runtime? For example could I find all functions in a module that are decorated by "example"?
@example
def test1():
print "test1"
| [
"Since you have indicated that you have the control over the wrapper code, here is an example:\ndef example(f):\n f.wrapped = True\n return f\n\n@example\ndef test1():\n print \"test1\"\n\ndef test2():\n print \"test2\"\n\n\nprint test1.wrapped\nprint hasattr(test2, 'wrapped')\n\n",
"In the general ca... | [
13,
9,
3,
2
] | [
"If you can, monkeypatch the decorator at runtime to catch which functions are being passed to it:\ndecfuncs = []\n\ndef decpatch(dec):\n def catchdec(func, *args, **kwargs):\n decfuncs.append(func)\n return dec(func, *args, **kwargs)\n return catchdec\n\nsomemodule.somedecorator = decpatch(somemodule.somed... | [
-1
] | [
"python"
] | stackoverflow_0002144109_python.txt |
Q:
basics to create a MML console in Python
I am looking to have a MML (man machine language) console written in Python as the only entry point to control and monitor a back-end process. Basically will be able to:
attach to an existing back-end process
if back-end process is not running, still open console and be ab... | basics to create a MML console in Python | I am looking to have a MML (man machine language) console written in Python as the only entry point to control and monitor a back-end process. Basically will be able to:
attach to an existing back-end process
if back-end process is not running, still open console and be able to spawn back-end process (by introducing t... | [
"Maybe this is a start: http://code.google.com/p/squires/wiki/SquiresHowto\nYou could use a Socket to do the communication between Front- and Backend.\n",
"High on my list would be twisted. It's fairly easy to build a an interactive console with and it's Perspective Broker system would probably work well for you.... | [
1,
1
] | [] | [] | [
"console",
"inter_process_communicat",
"ipc",
"linux",
"python"
] | stackoverflow_0005917834_console_inter_process_communicat_ipc_linux_python.txt |
Q:
Loading a cookie in google app engine
What's the best way to load a facebook cookie in google app engine (python)?
The cookies attribute (in the request class) is a dictionary of cookies. Once I get mine I have a string with & sign separating the attributes. How can I turn this easily into a dictionary?
This is th... | Loading a cookie in google app engine | What's the best way to load a facebook cookie in google app engine (python)?
The cookies attribute (in the request class) is a dictionary of cookies. Once I get mine I have a string with & sign separating the attributes. How can I turn this easily into a dictionary?
This is the string: "access_token=value&expires=value... | [
"cgi.parse_qs\n"
] | [
3
] | [] | [] | [
"cookies",
"dictionary",
"facebook",
"google_app_engine",
"python"
] | stackoverflow_0005918126_cookies_dictionary_facebook_google_app_engine_python.txt |
Q:
Python: override __str__ in an exception instance
I'm trying to override the printed output from an Exception subclass in Python after the exception has been raised and I'm having no luck getting my override to actually be called.
def str_override(self):
"""
Override the output with a fixed string
"""
... | Python: override __str__ in an exception instance | I'm trying to override the printed output from an Exception subclass in Python after the exception has been raised and I'm having no luck getting my override to actually be called.
def str_override(self):
"""
Override the output with a fixed string
"""
return "Override!"
def reraise(exception):
""... | [
"The problem is not that __str__() doesn't get overriden (just like you've already said, it does), but rather that str(e) (which invisibly gets called by print) is not always equivalent to e.__str__(). More specifically, if I get it right, str() (and other special methods, such as repr()), won't look for str in the... | [
13,
2
] | [] | [] | [
"exception",
"python",
"string"
] | stackoverflow_0005918003_exception_python_string.txt |
Q:
Tell a raw string (r'') from a regular string ('')?
I'm currently building a tool that will have to match filenames against a pattern. For convenience, I intend to provide both lazy matching (in a glob-like fashion) and regexp matching. For example, the following two snippets would eventually have the same effects... | Tell a raw string (r'') from a regular string ('')? | I'm currently building a tool that will have to match filenames against a pattern. For convenience, I intend to provide both lazy matching (in a glob-like fashion) and regexp matching. For example, the following two snippets would eventually have the same effects:
@mylib.rule('static/*.html')
def myfunc():
pass
@m... | [
"You can't tell them apart. Every raw string literal could also be written as a standard string literal (possibly requiring more quoting) and vice versa. Apart from this, I'd definitely give different names to the two decorators. They don't do the same things, they do different things.\nExample (CPython):\n>>> a... | [
15,
11,
3
] | [] | [] | [
"python",
"regex",
"string"
] | stackoverflow_0005915940_python_regex_string.txt |
Q:
Exploits in Python - manipulating hex strings
I'm quite new to python and trying to port a simple exploit I've written for a stack overflow (just a nop sled, shell code and return address). This isn't for nefarious purposes but rather for a security lecture at a university.
Given a hex string (deadbeef), what are ... | Exploits in Python - manipulating hex strings | I'm quite new to python and trying to port a simple exploit I've written for a stack overflow (just a nop sled, shell code and return address). This isn't for nefarious purposes but rather for a security lecture at a university.
Given a hex string (deadbeef), what are the best ways to:
represent it as a series of byte... | [
"In Python 2.6 and above, you can use the built-in bytearray class.\nTo create your bytearray object:\nb = bytearray.fromhex('deadbeef')\n\nTo alter a byte, you can reference it using array notation:\nb[2] += 7\n\nTo reverse the bytearray in place, use b.reverse(). To create an iterator that iterates over it in rev... | [
4,
0,
0
] | [] | [] | [
"exploit",
"hex",
"python",
"security"
] | stackoverflow_0005918353_exploit_hex_python_security.txt |
Q:
problem with django forms
i have the following django form . which has a choice field. im trying to get the value selected in the radioSelect widget . im using (cleaned_data) method for this task.
but it cant access the method cleaned_data for some reason.
Exception Value :'AnswersForm' object has no attribute 'cl... | problem with django forms | i have the following django form . which has a choice field. im trying to get the value selected in the radioSelect widget . im using (cleaned_data) method for this task.
but it cant access the method cleaned_data for some reason.
Exception Value :'AnswersForm' object has no attribute 'cleaned_data'
forms.py:
class ... | [
"You don't show any code where you pass data to the form or check if it is valid. Normal practice is something like:\nif request.method == 'POST':\n form = Forms.AnswersForm(request.POST)\n if form.is_valid():\n do_something_with(form.cleaned_data['answers'])\n\nYou cannot access cleaned_data until you... | [
4,
0
] | [] | [] | [
"django",
"django_forms",
"python"
] | stackoverflow_0005918356_django_django_forms_python.txt |
Q:
How do I specify which version of python I want to use with make?
How do I specify which version of python I want to use with make?
A:
Typically python is the name of the system's default Python version, but all installed versions are also available with names like python2.7 or python3.2. You can use those name... | How do I specify which version of python I want to use with make? | How do I specify which version of python I want to use with make?
| [
"Typically python is the name of the system's default Python version, but all installed versions are also available with names like python2.7 or python3.2. You can use those names in a command in a Makefile, or you can put them on the #! line of a Python script if you want to invoke it that way.\n",
"A makefile ... | [
1,
1
] | [] | [] | [
"makefile",
"path",
"python",
"unix"
] | stackoverflow_0005918532_makefile_path_python_unix.txt |
Q:
a for loop that won't pass beyond the first item in python
I have this simple average function and when its run with a test data, will show the length of the data, but when calculating the actual average just won't go beyond the first item in the sequence. I need help in finding what I am doing wrong here. Thank... | a for loop that won't pass beyond the first item in python | I have this simple average function and when its run with a test data, will show the length of the data, but when calculating the actual average just won't go beyond the first item in the sequence. I need help in finding what I am doing wrong here. Thanks in advance for taking the time to answer if you do.
def avg(s... | [
"This is wrong:\ndef avg(seq):\n total = 0\n for i in seq:\n total+=i\n average = total/len(seq)\n return (float(average))\n\nThis is right:\ndef avg(seq):\n total = 0\n for i in seq:\n total += i\n average = total / len(seq)\n return average\n\nOr, if you haven't upgra... | [
6,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0005917582_python.txt |
Q:
pystackexchange polling issue
So, I'm fairly new to python and I had an idea today to make a script that polls stackoverflow for my rep, and when it changes, it sends an email, which gets sent to my phone as a text.
The emailing part works, but for some reason I can't get the polling right, so I decided I'd see i... | pystackexchange polling issue | So, I'm fairly new to python and I had an idea today to make a script that polls stackoverflow for my rep, and when it changes, it sends an email, which gets sent to my phone as a text.
The emailing part works, but for some reason I can't get the polling right, so I decided I'd see if maybe you guys wanted to take a s... | [
"This is a simplified example that will loop properly:\nimport time\nfrom stackauth import StackAuth\nfrom stackexchange import Site, StackOverflow\n\nrep = None\nwhile True:\n stack_auth = StackAuth()\n so = Site(StackOverflow)\n accounts = stack_auth.associated(so, 641766) # using my id\n so_acct = fi... | [
1
] | [] | [] | [
"python",
"stackexchange"
] | stackoverflow_0005918627_python_stackexchange.txt |
Q:
Recursive Function Call in OOP Python
So I've recently started doing Object Oriented Programming with Python, and for a specific problem I have to write a class that deals with fractions. Everything seems to be coming along fine with writing methods of common math operators such as subtraction and addition; howev... | Recursive Function Call in OOP Python | So I've recently started doing Object Oriented Programming with Python, and for a specific problem I have to write a class that deals with fractions. Everything seems to be coming along fine with writing methods of common math operators such as subtraction and addition; however, I am stuck with a recursive method.
cl... | [
"This line is where the NameError occurs:\nreturn GreatestCommonDivisor(self, denominator, numerator%denominator)\n\nIt should read:\nreturn self.GreatestCommonDivisor(denominator, numerator % denominator)\n\n",
"GreatestCommonDivisor is an instance method, not a global method. You need to do\nreturn self.Greates... | [
10,
2
] | [] | [] | [
"oop",
"python",
"recursion"
] | stackoverflow_0005918688_oop_python_recursion.txt |
Q:
Spawn Process/Run Executable on Web Server
I am looking to run a process (for example an instance of python) on a web server. How do I initiate this via http request? For example, a user arrives on my page, I want to initiate a python instance on the web server that can be accessed via ajax requests. For now, I ju... | Spawn Process/Run Executable on Web Server | I am looking to run a process (for example an instance of python) on a web server. How do I initiate this via http request? For example, a user arrives on my page, I want to initiate a python instance on the web server that can be accessed via ajax requests. For now, I just want to focus on the initiation of the proces... | [
"Use mod_python on Apache. Stick a Python file in your DocumentRoot. Blammo.. You have Python executing on your web server.\n"
] | [
3
] | [] | [] | [
"http",
"php",
"process",
"python",
"webserver"
] | stackoverflow_0005918826_http_php_process_python_webserver.txt |
Q:
GUI Progress Indicator using command line tools
I would like to know a good way to make a GUI progress bar. I'm using python, Glade/GTK. An example of a program I'd like to get more than just a pulse bar. Something that could give the user a more accurate way to know the progress. The program I'm trying to capture... | GUI Progress Indicator using command line tools | I would like to know a good way to make a GUI progress bar. I'm using python, Glade/GTK. An example of a program I'd like to get more than just a pulse bar. Something that could give the user a more accurate way to know the progress. The program I'm trying to capture this for is cdparanoia, but would like to know how t... | [
"gtk.ProgressBar? (Note the .set_fraction() method.)\nHere's some info about doing non-blocking reads from a subprocess. The suggestion of polling with timeout seems appropriate. Also, this answer.\nMy dim memory of cdparanoia's progress indicator is that it is very idiosyncratic. But I'm guessing it's just some si... | [
0
] | [] | [] | [
"glade",
"progress_bar",
"pygtk",
"python",
"shell"
] | stackoverflow_0005918827_glade_progress_bar_pygtk_python_shell.txt |
Q:
How to interact with a webpage with python?
Basically, I want to be able to mimic the functions of an internet browser, but without having to actually graphically render it. My ideal scenario would be, for example, a script which opens a connection with a webpage, makes all the necessary calls and interactions, an... | How to interact with a webpage with python? | Basically, I want to be able to mimic the functions of an internet browser, but without having to actually graphically render it. My ideal scenario would be, for example, a script which opens a connection with a webpage, makes all the necessary calls and interactions, and can list what javascript went off (this is a tr... | [
"You should check out twill. It works on the command line but also has a python api.\n",
"You might want to check out PhantomJS. You script it in JavaScript rather than Python, but it seems to be a nice headless browser based on WebKit.\nAnother option might be to use Selenium, which has a Python binding availabl... | [
3,
3
] | [] | [] | [
"python"
] | stackoverflow_0005916636_python.txt |
Q:
In Django, Can I `defer()` fields in an object that's being queried by `select_related()`
In my Django app I want to use select_related() on a QuerySet to "follow" a ForeignKey field, but I only need to access a few of the fields on the "followed" model instance. Can I use the defer() method somehow with my "follo... | In Django, Can I `defer()` fields in an object that's being queried by `select_related()` | In my Django app I want to use select_related() on a QuerySet to "follow" a ForeignKey field, but I only need to access a few of the fields on the "followed" model instance. Can I use the defer() method somehow with my "followed" field.
e.g., if I have...
class BarModel(models.Model):
...
blah = models.TextFiel... | [
"Using Django's double-underscore notation as shown here.\nFooModel.objects.all().select_related('bar').defer('bar__blah', ...)\n\n"
] | [
12
] | [] | [] | [
"django",
"django_queryset",
"django_select_related",
"python"
] | stackoverflow_0005919031_django_django_queryset_django_select_related_python.txt |
Q:
Python calling both Java and C modules, howto?
Jython calls Java modules, and C-language modules callable from Python. What if a Python/Jython program needs to call some modules in Java and some in C, any solution?
A:
Jython partially supports ctypes in last builds, so you should check whether current support is... | Python calling both Java and C modules, howto? | Jython calls Java modules, and C-language modules callable from Python. What if a Python/Jython program needs to call some modules in Java and some in C, any solution?
| [
"Jython partially supports ctypes in last builds, so you should check whether current support is enough for your needs. \nIf not, you can go with JNA, http://www.flester.com/blog/2009/02/21/java-jna-jythonjruby-the-sweet-spot\n"
] | [
0
] | [] | [] | [
"jython",
"python"
] | stackoverflow_0005919060_jython_python.txt |
Q:
Scrape Facebook in Python
I'm interested in getting the number of friends each of my friends on Facebook has. Apparently the official Facebook API does not allow getting the friends of friends, so I need to get around this (somehwhat sensible) limitation somehow. I tried the following:
import sys
import urllib, ur... | Scrape Facebook in Python | I'm interested in getting the number of friends each of my friends on Facebook has. Apparently the official Facebook API does not allow getting the friends of friends, so I need to get around this (somehwhat sensible) limitation somehow. I tried the following:
import sys
import urllib, urllib2, cookielib
username = 'm... | [
"Have you tried tracing and comparing HTTP transactions with Fiddler2 or Wireshark? Fiddler can even trace https, as long as your client code can be made to work with bogus certs.\n",
"I did try a lot of ways to scrape facebook and the only way that worked for me is :\nTo install selenium , the firefox plugin, th... | [
3,
0
] | [] | [] | [
"captcha",
"facebook",
"python"
] | stackoverflow_0004297380_captcha_facebook_python.txt |
Q:
Not install all files in site_packages using setup.py
When i install software(XYZ) using setup.py file using command "python setup.py install" it copy only files present in parent directory to the folder present in site_packages/XYZ .in setup file i define all packages and data_files which i want to use. Software ... | Not install all files in site_packages using setup.py | When i install software(XYZ) using setup.py file using command "python setup.py install" it copy only files present in parent directory to the folder present in site_packages/XYZ .in setup file i define all packages and data_files which i want to use. Software package structure
XYZ
__init__.py
main.py
test1... | [
"It sounds like your setup.py needs to have:\npackages=['vector', 'exlib'],\n\n"
] | [
1
] | [] | [] | [
"python",
"setup.py",
"setuptools"
] | stackoverflow_0005919185_python_setup.py_setuptools.txt |
Q:
PyCUDA+Threading = Invalid Handles on kernel invocations
I'll try and make this clear;
I've got two classes; GPU(Object), for general access to GPU functionality, and multifunc(threading.Thread) for a particular function I'm trying to multi-device-ify. GPU contains most of the 'first time' processing needed for a... | PyCUDA+Threading = Invalid Handles on kernel invocations | I'll try and make this clear;
I've got two classes; GPU(Object), for general access to GPU functionality, and multifunc(threading.Thread) for a particular function I'm trying to multi-device-ify. GPU contains most of the 'first time' processing needed for all subsequent usecases, so multifunc gets called from GPU with... | [
"The reason is context affinity. Every CUDA function instance is tied to a context, and they are not portable (the same applies to memory allocations and texture references). So each context must load the function instance separately, and then use the function handle returned by that load operation.\nIf you are not... | [
5,
1
] | [] | [] | [
"cuda",
"gpgpu",
"multithreading",
"pycuda",
"python"
] | stackoverflow_0005918937_cuda_gpgpu_multithreading_pycuda_python.txt |
Q:
wrapping a scripted command line interface
I want to call an external program from within python, but this external program tries to interact with the user by using an internal script (in the telemarketer sense) to ask questions and change questions based on answers given. The creators of this program are also kn... | wrapping a scripted command line interface | I want to call an external program from within python, but this external program tries to interact with the user by using an internal script (in the telemarketer sense) to ask questions and change questions based on answers given. The creators of this program are also known for occasionally changing the text of some o... | [
"Are you looking for something like pexpect?\n"
] | [
3
] | [] | [] | [
"command_line_interface",
"python"
] | stackoverflow_0005918184_command_line_interface_python.txt |
Q:
Python how to find the number of characters in the user input
im creating a sort of quiz game on python and one of the questions is 'type a word that has 5 letters in them'.
so basicaly what i want is for the user to type anything that has 5 letters or characters in them.and then python checks if it has 5 letters ... | Python how to find the number of characters in the user input | im creating a sort of quiz game on python and one of the questions is 'type a word that has 5 letters in them'.
so basicaly what i want is for the user to type anything that has 5 letters or characters in them.and then python checks if it has 5 letters and if it is correct it sends them to the next question.
| [
"For your game, i assume you have some while loop that keeps things rolling.\nDo this:\nword = input(\"Give me a 5 letter word: \")\n\nThe line above will ask the user for the 5 letter word and their input will be stored in the variable word. Then check\nif len(word) != 5:\n print \"that's not 5 letters...\"\n\n... | [
3,
1,
1
] | [] | [] | [
"python",
"variables"
] | stackoverflow_0005919828_python_variables.txt |
Q:
reading words from a file into a set, maintaining order
here is an array of Unicode words used in the python script.
texts =[u"abc", u"pqr", u"mnp"]
The script is working as expected with the above 3 words example. The issue is that there are thousands of words in a text file.
How do I read from the text file?
U... | reading words from a file into a set, maintaining order | here is an array of Unicode words used in the python script.
texts =[u"abc", u"pqr", u"mnp"]
The script is working as expected with the above 3 words example. The issue is that there are thousands of words in a text file.
How do I read from the text file?
Update:
I have 2 issues. The sequence of words from the text f... | [
"This is because how sets work. They don't maintain the order of the items stored in the set.\nFrom the documentation:\n\nA set object is an unordered collection of distinct hashable objects\n\n",
"I see no problem with your file reading code. Given that the words appear in the file separated by whitespace, and t... | [
2,
2
] | [] | [] | [
"python"
] | stackoverflow_0005919631_python.txt |
Q:
Django Toggling MultiDB and Installed Apps in settings.py
I have a set of apps and multiple databases that are only needed during initial setup. I want to toggle this as needed so I setup a constant IMPORT_MODE in settings.py.
To make this work, I changed INSTALLED_APPS from a tuple to a list. That way I can add... | Django Toggling MultiDB and Installed Apps in settings.py | I have a set of apps and multiple databases that are only needed during initial setup. I want to toggle this as needed so I setup a constant IMPORT_MODE in settings.py.
To make this work, I changed INSTALLED_APPS from a tuple to a list. That way I can add the list of apps I need when doing setup as needed. There did... | [
"It shouldn't matter no. You might want to consider doing something like this though, which is a Django idiom I've seen (and use). Define your alternate settings in another module (say import_mode.py) and import them, overriding the default settings but only when the module containing your alternate settings is imp... | [
0
] | [] | [] | [
"django",
"list",
"python",
"tuples"
] | stackoverflow_0005919787_django_list_python_tuples.txt |
Q:
having 2 groups of users to view 2 different views in django
i have a django project that has 2 types of users ( teachers and students in my case )
i want each group of them to view a different page when they login.
how is that possible ?
or how to know what group a certain user belong to ?
thanks in advance
A... | having 2 groups of users to view 2 different views in django | i have a django project that has 2 types of users ( teachers and students in my case )
i want each group of them to view a different page when they login.
how is that possible ?
or how to know what group a certain user belong to ?
thanks in advance
| [
"To get the groups of a user check the docs on authentication.\n\nUser objects have two many-to-many\n fields: models.User. groups and\n user_permissions. User objects can\n access their related objects in the\n same way as any other Django model:\n\nmyuser.groups = [group_list]\n\nSo if you want to check if a ... | [
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0005920407_django_python.txt |
Q:
QooXDoo example for config.json from manual produce error pretty-print
I take the example from the doc 1.4 for "pretty-print" job key in my config.json.
"jobs" : {
"pretty-print" : {
"general" : { ..... },
"comments" : { ...... },
"blocks" : { ....... }
},
python... | QooXDoo example for config.json from manual produce error pretty-print | I take the example from the doc 1.4 for "pretty-print" job key in my config.json.
"jobs" : {
"pretty-print" : {
"general" : { ..... },
"comments" : { ...... },
"blocks" : { ....... }
},
python Generate.py produce this:
Warning: ! Unknown job config key "blocks" - ig... | [
"You got it nearly right, you just missed one level of nesting.\nThe overall structure of the jobs map is as follows (which is also documented here):\n\"jobs\" : {\n \"job-name\" : {\n \"pretty-print\" : { ... }\n ...\n }\n ...\n}\n\nSo you just need to insert a job name between \"jobs... | [
2
] | [] | [] | [
"python",
"qooxdoo"
] | stackoverflow_0005919837_python_qooxdoo.txt |
Q:
QTabWidget with CheckBox in title
I was wondering how to create (using PyQt4) a derived QTabWidget with a check box next to each tab title? Like this:
A:
Actually I chose to only subclass QTabWidget.
The checkBox is added at the creation of a new tab and saved to a list in order to get its index back.
setCheckSt... | QTabWidget with CheckBox in title | I was wondering how to create (using PyQt4) a derived QTabWidget with a check box next to each tab title? Like this:
| [
"Actually I chose to only subclass QTabWidget.\nThe checkBox is added at the creation of a new tab and saved to a list in order to get its index back.\nsetCheckState/isChecked methods are intended to control the state of each checkBox specified by its tab index.\nFinally, the \"stateChanged(int)\" signal is capture... | [
9,
2
] | [] | [] | [
"checkbox",
"pyqt4",
"python",
"qt4",
"qtabwidget"
] | stackoverflow_0005818387_checkbox_pyqt4_python_qt4_qtabwidget.txt |
Q:
Finding repeats in multiple lists read from CSV File (Python)
Title seems confusing, but let's say I'm working with the following CSV file ('names.csv').
name1,name2,name3
Bob,Jane,Joe
Megan,Tom,Jane
Jane,Joe,Rob
My question is, how would I go about making code that returns the string that occurs ... | Finding repeats in multiple lists read from CSV File (Python) | Title seems confusing, but let's say I'm working with the following CSV file ('names.csv').
name1,name2,name3
Bob,Jane,Joe
Megan,Tom,Jane
Jane,Joe,Rob
My question is, how would I go about making code that returns the string that occurs at least 3 times. So the output should be 'Jane', because that occu... | [
"I'd do it like this: \n>>> from collections import defaultdict\n>>> d = defaultdict(int)\n>>> rows = [['Bob', 'Jane', 'Joe'],\n... ['Megan', 'Tom', 'Jane'],\n... ['Jane', 'Joe', 'Rob']]\n...\n>>> for row in rows:\n... for name in row:\n... d[name] += 1\n... \n>>> filter(lambda x: x[1] >= 3, d.iteritems... | [
0,
0
] | [] | [] | [
"csv",
"python"
] | stackoverflow_0005919930_csv_python.txt |
Q:
pymysql issue 'NoneType' object has no attribute 'encode'
Hi i'm trying to use pymysql. Here is the simpliest code
import pymysql
conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd=None,
db='newbase')
and i'm getting error:
'NoneType' object has no attribute 'encode'.
i... | pymysql issue 'NoneType' object has no attribute 'encode' | Hi i'm trying to use pymysql. Here is the simpliest code
import pymysql
conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd=None,
db='newbase')
and i'm getting error:
'NoneType' object has no attribute 'encode'.
i'm using easyphp5.3.6.0
What should i do ?
| [
"Looks like there is a problem with passwd=None parameter. Try to specify password as some string or do not pass this parameter.\n"
] | [
1
] | [] | [] | [
"mysql",
"python"
] | stackoverflow_0005920762_mysql_python.txt |
Q:
Get Path of Uploaded File using Python
Is it possible to get the full path of the file on the user's computer being uploaded to my site?
Using os.path.abspath(fileitem.filename) simply gets me the address of where my script is executing from on my shared hosting server.
FYI: fileitem = form['file'] and form = cgi... | Get Path of Uploaded File using Python | Is it possible to get the full path of the file on the user's computer being uploaded to my site?
Using os.path.abspath(fileitem.filename) simply gets me the address of where my script is executing from on my shared hosting server.
FYI: fileitem = form['file'] and form = cgi.FieldStorage()
| [
"No, that information isn't sent by the user, so it's not available on your end\n",
"To complete the answer - IE <= 7 used to send full file path instead of filename only, but IE 8 changed the default setting and sends only file names for privacy reasons.\nEven if client did send the full file path, many web-base... | [
5,
0
] | [] | [] | [
"python",
"upload"
] | stackoverflow_0002918010_python_upload.txt |
Q:
PyGTK how to click button and open file in pop-up window
I editted the code so that the 3 buttons now show up .Can someone please tell me how to make it so that when I click the button that says Helloworld and application called Helloworld.py will pop-up in another window.Same for the other 2 buttons
!/usr/bin/env... | PyGTK how to click button and open file in pop-up window | I editted the code so that the 3 buttons now show up .Can someone please tell me how to make it so that when I click the button that says Helloworld and application called Helloworld.py will pop-up in another window.Same for the other 2 buttons
!/usr/bin/env python
# menu.py
import pygtk
pygtk.require('2.0')
import ... | [
"You could do something like this. I'm assuming you just want to execute your .py files, e.g. helloworld.py etc. I'm using Popen from subprocess to execute python (not assuming the py files are executable) scripts. Note that I've edited the script to only have one button, this is just to show you the idea.\nimport ... | [
2
] | [] | [] | [
"menu",
"pygtk",
"python"
] | stackoverflow_0005914652_menu_pygtk_python.txt |
Q:
Getting data from a chart that is displayed on a website
I was asked to draw a graph like this one
using Latex (more precisely, tikz and/or pgf). This would not be a problem if I had the data, but I don't. All I have is the website from where graphs can be displayed, but I don't know how to get the data from the... | Getting data from a chart that is displayed on a website | I was asked to draw a graph like this one
using Latex (more precisely, tikz and/or pgf). This would not be a problem if I had the data, but I don't. All I have is the website from where graphs can be displayed, but I don't know how to get the data from there.
I spent the day today trying to get this data, including w... | [
"Well, it'd be great if Google provided an API for this data! That said, you can still scrape some data out of the site. Here's how to go about it...\nInstall Firebug\nI prefer Firebug for Firefox, but Chrome's developer tools should also work. \nInvestigate\nFirst things first, let's visit the url in question and ... | [
25
] | [] | [] | [
"latex",
"python",
"tikz"
] | stackoverflow_0005919981_latex_python_tikz.txt |
Q:
Can we only get the web page header information and not the body? (Mechanize)
What if I only need to download the page if it has not changed since the last download?
What is the best way? can I get the size of the page first, then compare the decide if it has changed, if so, I ask for download else skip?
I plan to... | Can we only get the web page header information and not the body? (Mechanize) | What if I only need to download the page if it has not changed since the last download?
What is the best way? can I get the size of the page first, then compare the decide if it has changed, if so, I ask for download else skip?
I plan to use (python) mechanize.
| [
"the request should be a HEAD, not a GET:\n\n9.4 HEAD\nThe HEAD method is identical to GET\nexcept that the server MUST NOT return\na message-body in the response. The\nmetainformation contained in the HTTP\nheaders in response to a HEAD request\nSHOULD be identical to the information\nsent in response to a GET re... | [
5,
0
] | [] | [] | [
"mechanize",
"python",
"screen_scraping"
] | stackoverflow_0002730997_mechanize_python_screen_scraping.txt |
Q:
Python/Mechanize - Can not select form - ParseError(exc)
i am getting this error:
>>> br = Browser()
>>> br.open("http://www.bestforumz.com/forum/")
<response_seek_wrapper at 0x21f9fd0
whose wrapped object =
<closeable_response at 0x21f9558 whose
fp = <socket._fileobject object at
0x021F5F30>>>
>>> br.select_form(... | Python/Mechanize - Can not select form - ParseError(exc) | i am getting this error:
>>> br = Browser()
>>> br.open("http://www.bestforumz.com/forum/")
<response_seek_wrapper at 0x21f9fd0
whose wrapped object =
<closeable_response at 0x21f9558 whose
fp = <socket._fileobject object at
0x021F5F30>>>
>>> br.select_form(nr=0)
Traceback (most recent call last):
File "<pyshell#3>"... | [
"I tell you this is some secret i've been used for parse html (the goal is make a force parsing html by mechanize)\nbr = mechanize.Browser(factory=mechanize.DefaultFactory(i_want_broken_xhtml_support=True))\n\n",
"mechanize isn't guaranteed to parse all HTML. You might have to do this by hand (which isn't too har... | [
3,
1
] | [] | [] | [
"mechanize",
"python"
] | stackoverflow_0004062250_mechanize_python.txt |
Q:
How to make mechanize not fail with forms on this page?
import mechanize
url = 'http://steamcommunity.com'
br=mechanize.Browser(factory=mechanize.RobustFactory())
br.open(url)
print br.request
print br.form
for each in br.forms():
print each
print
The above code results in:
Traceback (most recent call ... | How to make mechanize not fail with forms on this page? | import mechanize
url = 'http://steamcommunity.com'
br=mechanize.Browser(factory=mechanize.RobustFactory())
br.open(url)
print br.request
print br.form
for each in br.forms():
print each
print
The above code results in:
Traceback (most recent call last):
File "./mech_test.py", line 12, in <module>
for ... | [
"Did you mention that the website is redirecting to an https (ssl) server ?\nWell, try to set a new HTTPS handler like this:\nmechanize.HTTPSHandler()\n\n",
"Use this secret, i'm sure this is work for you ;)\nbr = mechanize.Browser(factory=mechanize.DefaultFactory(i_want_broken_xhtml_support=True))\n\n"
] | [
2,
2
] | [] | [] | [
"automation",
"mechanize",
"python",
"screen_scraping"
] | stackoverflow_0000922148_automation_mechanize_python_screen_scraping.txt |
Q:
Optimize this python log-parsing code
The runtime of this code on my laptop for a 4.2 GB input file is 48 seconds. The input file is tab-delimited, with each value appearing in quotes. Each record ends with a newline, e.g. '"val1"\t"val2"\t"val3"\t..."valn"\n'
I've tried using multiprocessing with 10 threads: One ... | Optimize this python log-parsing code | The runtime of this code on my laptop for a 4.2 GB input file is 48 seconds. The input file is tab-delimited, with each value appearing in quotes. Each record ends with a newline, e.g. '"val1"\t"val2"\t"val3"\t..."valn"\n'
I've tried using multiprocessing with 10 threads: One to queue up the lines, 8 to parse individua... | [
"Use regular expressions.\nA test determines that the expensive part of the process is the call to str.split(). Probably having to construct a list and a bunch of string objects for every line is expensive.\nFirstly, you need to construct a regular expression to match against the line. Something like:\nexpression =... | [
4,
2,
1,
1,
0,
0,
0
] | [] | [] | [
"logfiles",
"multiprocessing",
"multithreading",
"optimization",
"python"
] | stackoverflow_0005902653_logfiles_multiprocessing_multithreading_optimization_python.txt |
Q:
Django file upload input validation and security
I'm creating a very simple django upload application but I want to make it as secure as possible. This is app is going to be completely one way, IE. anybody who uploads a file will never have to retrieve it. So far I've done the following:
Disallow certain file e... | Django file upload input validation and security | I'm creating a very simple django upload application but I want to make it as secure as possible. This is app is going to be completely one way, IE. anybody who uploads a file will never have to retrieve it. So far I've done the following:
Disallow certain file extensions (.php, .html, .py, .rb, .pl, .cgi, .htaccess... | [
"Disallowing a file extension is -- potentially -- a waste of time. A unix server doesn't use the extension -- it uses ownership and permissions. \nWhen accepting an upload, you will often rename the file to prevent it being misused. Uploaded files should be simply named \"upload_xxx\" with the \"xxx\" being a k... | [
7,
2
] | [] | [] | [
"django",
"file_upload",
"python",
"security"
] | stackoverflow_0001095250_django_file_upload_python_security.txt |
Q:
How to account for column-contiguous array when extending numpy with C
I have a C-function to normalize the rows of an array in log-space (this prevents numerical underflow).
The prototype of my C-function is as follows:
void normalize_logspace_matrix(size_t nrow, size_t ncol, double* mat);
You can see that it ta... | How to account for column-contiguous array when extending numpy with C | I have a C-function to normalize the rows of an array in log-space (this prevents numerical underflow).
The prototype of my C-function is as follows:
void normalize_logspace_matrix(size_t nrow, size_t ncol, double* mat);
You can see that it takes a pointer to an array and modifies it in place. The C-code of course ass... | [
"If you want to support arrays in C and Fortran order without ever copying, your C function needs to be flexible enough to support both orderings. This can be achieved by passing the strides of the NumPy array to the C function: Change the prototype to\nvoid normalize_logspace_matrix(size_t nrow, size_t ncol, \n ... | [
8,
3,
0
] | [] | [] | [
"c",
"cython",
"numpy",
"python"
] | stackoverflow_0004420622_c_cython_numpy_python.txt |
Q:
making a single script wrapping 3 python codes
I have 3 python codes which I want to call one after another automatically so that they result in the final in s single call.
How do I wrap these codes into single script? codes are model-multiple.py, align2d.py, model-single.py.
model-multiple.py is
from modelle... | making a single script wrapping 3 python codes | I have 3 python codes which I want to call one after another automatically so that they result in the final in s single call.
How do I wrap these codes into single script? codes are model-multiple.py, align2d.py, model-single.py.
model-multiple.py is
from modeller import * # Load standard Modeller cla... | [
"You have two options:\n\nThe quick-and-dirty way: just call them one after another in a shell script or in a Python script (using system or subprocess.Popen)\nMake them do their work in some function, import them into a single script and invoke each module's \"do work\" function\n\n",
"If all three scripts are s... | [
2,
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0005921168_python.txt |
Q:
How to call a Python function like in Javascript
if i do this , it will be ok :
def a():
b = [1,2,3]
def d():
print b
d()
a()
but i have many method need function d , so i have to defined it out of the function a , but it show error :
def d():
print b
def a():
b = [1,2,3]
d()
a(... | How to call a Python function like in Javascript | if i do this , it will be ok :
def a():
b = [1,2,3]
def d():
print b
d()
a()
but i have many method need function d , so i have to defined it out of the function a , but it show error :
def d():
print b
def a():
b = [1,2,3]
d()
a()
error:
File "c.py", line 21, in <module>
a()
... | [
"You are probably getting confused by javascript's scoping which is the opposite of python's. Read what the official Python tutorial has to say about scopes and namespaces before you go any further! You might also find this talk by Ian Bicking useful: Javascript for People Who Know Python. He does a great job cover... | [
4,
3,
1,
0,
0
] | [] | [] | [
"javascript",
"python",
"variables"
] | stackoverflow_0005919642_javascript_python_variables.txt |
Q:
Python Routes, giving request method
I have something like using python routes, How to map request method like post, get, delete here...
mapper.connect("/user", controller=user_controller, action="user")
A:
Add a condition, specify the HTTP method required and map to the appropriate controller action. For exampl... | Python Routes, giving request method | I have something like using python routes, How to map request method like post, get, delete here...
mapper.connect("/user", controller=user_controller, action="user")
| [
"Add a condition, specify the HTTP method required and map to the appropriate controller action. For example, your snippet could be rewritten as:\nmapper.connect(\"/user\", controller=user_controller, action=\"get_user\", conditions=dict(method=[\"GET\"]))\nmapper.connect(\"/user\", controller=user_controller, acti... | [
4
] | [] | [] | [
"python",
"routes"
] | stackoverflow_0005921061_python_routes.txt |
Q:
string/char comparison vs. bitwise comparison in python
I have a large data set of nucleotide sequences (long strings simply put) which converts into a 104*13440 matrix full of characters. My project forces me to do degenerate string matching while exploring all possible states/oppertunities (i-e no fancy heuristi... | string/char comparison vs. bitwise comparison in python | I have a large data set of nucleotide sequences (long strings simply put) which converts into a 104*13440 matrix full of characters. My project forces me to do degenerate string matching while exploring all possible states/oppertunities (i-e no fancy heuristics and/or screening). Since the data set is so large, manuall... | [
"\nWill converting characters to\n respective binary, and implementing\n minor neural networks using bitwise\n comparisons save processing time and\n memory consumption, as compared to\n simple character comparison?\n\nNo. Introducing something as complex as a neural network to solve string comparison is going... | [
0
] | [] | [] | [
"bit_manipulation",
"comparison",
"neural_network",
"python",
"string"
] | stackoverflow_0005921603_bit_manipulation_comparison_neural_network_python_string.txt |
Q:
How to parse a HTML file with table using Python
I have got a html file with table ( its a large one, so only sample code is given ). I want to retrieve the values in tables. I tried the HTMLParser library from python.
I started coding like below. Then I found that the attribute "class" is same as system defined ... | How to parse a HTML file with table using Python | I have got a html file with table ( its a large one, so only sample code is given ). I want to retrieve the values in tables. I tried the HTMLParser library from python.
I started coding like below. Then I found that the attribute "class" is same as system defined keyword. So its giving me error.
class MyHTMLParser(HT... | [
"Note that the documentation of the handle_starttag method states:\n\nThe tag argument is the name of the\n tag converted to lower case. The attrs\n argument is a list of (name, value)\n pairs containing the attributes found\n inside the tag’s <> brackets.\n\nSo, you're probably looking for something like:\nfro... | [
4,
2,
1
] | [] | [] | [
"html",
"html_parsing",
"parsing",
"python"
] | stackoverflow_0005920623_html_html_parsing_parsing_python.txt |
Q:
How do you find the index of an element in an Array on Python while in loop
Sorry but I'm fairly new to programming and cannot seem to find anything that relates to what I need...
while i<size(Array):
for index, k in enumerate(Array1):
if (k==Array[i]):
print index
... | How do you find the index of an element in an Array on Python while in loop | Sorry but I'm fairly new to programming and cannot seem to find anything that relates to what I need...
while i<size(Array):
for index, k in enumerate(Array1):
if (k==Array[i]):
print index
i=i+1
The above code presents an output that has the index out of bound... | [
"i is an index and you are updating it too often. Move the indentation of i = i+1 to get rid of the index out of bounds.\nwhile i<size(Array):\n for index, k in enumerate(Array1):\n if (k==Array[i]):\n print index\n i=i+1\n\n",
"If you only want the first index (or there wi... | [
1,
1,
1,
0,
0
] | [] | [] | [
"for_loop",
"indexing",
"python",
"while_loop"
] | stackoverflow_0005920938_for_loop_indexing_python_while_loop.txt |
Q:
Python - Debug running application
I'm trying to fix bugs from gedit plugins. Gedit uses C but some of its plugins are in Python. My computer is old and I cannot run an IDE. I've read about PDB (Python Debugger), but i cannot call the plugin directly with PDB. Is it possible set breakpoints in a gedit plugin, run ... | Python - Debug running application | I'm trying to fix bugs from gedit plugins. Gedit uses C but some of its plugins are in Python. My computer is old and I cannot run an IDE. I've read about PDB (Python Debugger), but i cannot call the plugin directly with PDB. Is it possible set breakpoints in a gedit plugin, run gedit and then use PDB to debug?
| [
"You could try editing the gedit plugins that you want to debug and putting\nimport pdb; pdb.set_trace()\n\nin there and that should break into the debugger. You might need to launch gedit from a command prompt instead of the GUI so that it has a terminal for pdb to run in.\n",
"AFAIK you can't really use gedit f... | [
4,
0
] | [] | [] | [
"gedit",
"pdb",
"python"
] | stackoverflow_0005921855_gedit_pdb_python.txt |
Q:
Views error in Django
I have used forms of Django in this manner and have got an error:
Error:invalid literal for int() with base 10: 'check'
#this is forms.py
from django import forms
class PersonalInfo(forms.Form):
Name = forms.CharField(max_length=20)
Email_ID = forms.EmailField(require... | Views error in Django | I have used forms of Django in this manner and have got an error:
Error:invalid literal for int() with base 10: 'check'
#this is forms.py
from django import forms
class PersonalInfo(forms.Form):
Name = forms.CharField(max_length=20)
Email_ID = forms.EmailField(required=False)
Address = ... | [
"I think the problem is in line\nper_job = Personal(cd['Name'], cd['Email_ID'], cd['Address'], cd['Contact_Phone'], cd['Image'])\n\nI don't know if it's possible to create a model instance with only positional parameters, but it's not mentioned in the docs. You should be using keyword parameters:\nper_job = Persona... | [
2
] | [] | [] | [
"django",
"django_forms",
"django_views",
"python"
] | stackoverflow_0005921743_django_django_forms_django_views_python.txt |
Q:
using dict vs class __dict__ method to format strings
I have been using dict to format strings
s = '%(name1)s %(name2)s'
d = {}
d['name1'] = 'asdf'
d['name2'] = 'whatever'
result = s % d
I just realized that I can do this with a class and using the dict method
instead:
s = '%(name1)s %(name2)s'
class D : pass
d =... | using dict vs class __dict__ method to format strings | I have been using dict to format strings
s = '%(name1)s %(name2)s'
d = {}
d['name1'] = 'asdf'
d['name2'] = 'whatever'
result = s % d
I just realized that I can do this with a class and using the dict method
instead:
s = '%(name1)s %(name2)s'
class D : pass
d = D()
d.name1 = 'asdf'
d.name2 = 'whatever'
result = s % d._... | [
"You can use new-style formatting, which allows getattr and getitem operators in format string:\n>>> class X(object):\n... pass\n... \n>>> x = X()\n>>> x.x = 1\n>>> d = {'a':1, 'b':2}\n>>> \"{0[a]} {0[b]} {1.x}\".format(d, x)\n'1 2 1'\n\nRegarding disadvantages of your approach - object's __dict__ is limited to... | [
8,
2
] | [] | [] | [
"python"
] | stackoverflow_0005921901_python.txt |
Q:
Load form data in JavaScript and run something client side
The original framework of my app (using Python) is below:
user key in keywords in forms.
App use the data in forms as parameter to get some results from third-party website.
The result which is from third-party website will be analyzed in my app.
Then sho... | Load form data in JavaScript and run something client side | The original framework of my app (using Python) is below:
user key in keywords in forms.
App use the data in forms as parameter to get some results from third-party website.
The result which is from third-party website will be analyzed in my app.
Then show the result of analyze to user.
But there are some problems be... | [
"It's very unclear what you are looking for. If the question is about server push keywords are WebSockets,Socket.io,Ajax,Comet,Bayeux to start with\n"
] | [
0
] | [] | [] | [
"javascript",
"python"
] | stackoverflow_0005922032_javascript_python.txt |
Q:
How to uninstall wxpython 2.8 on Mac OSX 10.6
Some details of my machine and installed packages before proceeding further:
Mac OSX version: 10.6.6
Python version: Activestate Python 2.7.1
wxpython version: wxpython 2.8 (uses Carbon API hence limited to 32-bit mode arch only)
I installed wxPython2.8-osx-unicode-py2... | How to uninstall wxpython 2.8 on Mac OSX 10.6 | Some details of my machine and installed packages before proceeding further:
Mac OSX version: 10.6.6
Python version: Activestate Python 2.7.1
wxpython version: wxpython 2.8 (uses Carbon API hence limited to 32-bit mode arch only)
I installed wxPython2.8-osx-unicode-py2.7 from wxpython website using their .dmg installer... | [
"If you look in the .dmg for wxPython, there is an uninstall_wxPython.py unininstall script. Just drag it to your desktop and run python ~/Desktop/uninstall_wxPython.py in a terminal.\n"
] | [
8
] | [] | [] | [
"macos",
"python",
"uninstallation",
"wxpython"
] | stackoverflow_0005920764_macos_python_uninstallation_wxpython.txt |
Q:
Finding/Replacing substrings with annotations in an ASCII file in Python
I'm having a little coding issue in a bioinformatics project I'm working on. Basically, my task is to extract motif sequences from a database and use the information to annotate a sequence alignment file. The alignment file is plain text, so ... | Finding/Replacing substrings with annotations in an ASCII file in Python | I'm having a little coding issue in a bioinformatics project I'm working on. Basically, my task is to extract motif sequences from a database and use the information to annotate a sequence alignment file. The alignment file is plain text, so the annotation will not be anything elaborate, at best simply replacing the ex... | [
"Something like the following should do the trick. I've made assumptions about your input data as you've not posted samples and that you're running python 2.7.\nmotifs = [ x.strip() for x in open('final motifs_11SGLOBULIN','r') ]\nredact = '*****'\n\nwith open('11sglobulin.seqs','r') as data_in, open('11sglobulin.s... | [
2,
2,
1,
0
] | [] | [] | [
"bioinformatics",
"biopython",
"python",
"text_processing"
] | stackoverflow_0005870012_bioinformatics_biopython_python_text_processing.txt |
Q:
python: need help to implement strptime() the right way
I am trying to find the difference in days between the current date and the date that I extract from the database (postgresql)
This is my code:
cur.execute('select id, city_id, event_id, duration, DATE(startdate) from main_cityevent where DATE(startdate) ... | python: need help to implement strptime() the right way | I am trying to find the difference in days between the current date and the date that I extract from the database (postgresql)
This is my code:
cur.execute('select id, city_id, event_id, duration, DATE(startdate) from main_cityevent where DATE(startdate) <= DATE(NOW())')
rows = cur.fetchall()
for city_event... | [
"You are probably importing datetime.datetime (the class) instead of datetime (the module).\nBy always importing the datetime module, you can use both datetime.datetime and datetime.date, which is more appropriate in your case, and has a nice .today() method.\nAnd you don't need the whole str() -> strptime() trip, ... | [
3,
1
] | [] | [] | [
"date",
"datetime",
"python",
"time"
] | stackoverflow_0005921936_date_datetime_python_time.txt |
Q:
Python summing frequencies in a file
I have a large file (950MB) that conains words and frequencies as follows, one per line:
word1 54
word2 1
word3 12
word4 3
word1 99
word4 147
word1 4
word2 6
etc...
I need to sum the frequencies for the words, e.g word1 = 54 + 99 + 4 = 157, and output this to a list/file.
Wha... | Python summing frequencies in a file | I have a large file (950MB) that conains words and frequencies as follows, one per line:
word1 54
word2 1
word3 12
word4 3
word1 99
word4 147
word1 4
word2 6
etc...
I need to sum the frequencies for the words, e.g word1 = 54 + 99 + 4 = 157, and output this to a list/file.
What is the most efficient way of doing this ... | [
"Try next:\nfrom collections import defaultdict\n\nd = defaultdict(int)\n\nwith open('file') as fh:\n for line in fh:\n word, count = line.split()\n d[word] += count\n\n",
"You don't have to read the whole file into memory. You could also split the file into multiple smaller files, process each f... | [
5,
0,
0
] | [] | [] | [
"file",
"frequency",
"python",
"sum",
"word"
] | stackoverflow_0005921832_file_frequency_python_sum_word.txt |
Q:
Writing output of a python script to HTML with CGI
I have a Python script that extracts some text from a file and annotates another file, writing the results to a new file. Because the files I am annotating are ASCII, I am very restricted as to how I can annotate the text, and I would like to instead write the res... | Writing output of a python script to HTML with CGI | I have a Python script that extracts some text from a file and annotates another file, writing the results to a new file. Because the files I am annotating are ASCII, I am very restricted as to how I can annotate the text, and I would like to instead write the results to HTML so that I can annotate by changing text col... | [
"I think you want\nline = line.replace(item, \"<span style=\\\"color:skyBlue\\\">\"+item+\"</span>\")\n\nThis will just add a <span> and set the color in CSS.\n"
] | [
2
] | [] | [] | [
"cgi",
"html",
"python"
] | stackoverflow_0005922774_cgi_html_python.txt |
Q:
'WSGIRequest' object is not subscriptable
I'm getting this error in this function in my views.py file. It's confusing because I don't know what 'WSGIRequest' is or why it's giving me problems. I know I have a variable called "newUser" because when I take out that one line the print(request.POST) line prints it out... | 'WSGIRequest' object is not subscriptable | I'm getting this error in this function in my views.py file. It's confusing because I don't know what 'WSGIRequest' is or why it's giving me problems. I know I have a variable called "newUser" because when I take out that one line the print(request.POST) line prints it out.
def AddNewUser(request):
a=AMI()
if(request.... | [
"It means that WSGIRequest does not implement __getitem__. You are trying to treat the HttpRequest object like a dictionary but it's not. If you want to access this newUser variable use the POST object, which implements a dictionary-like interface:\nrequest.POST['newUser']\n\nYou'd do well to peruse the Django docs... | [
23
] | [] | [] | [
"django",
"html",
"python"
] | stackoverflow_0005922958_django_html_python.txt |
Q:
fabric run fork
I want to use Fabric.api.run to directly start an application in a remote box. Since the application takes really a long to finish, I wish to be able to fork a child process, such that I don't need to wait for a long time.
The code is like:
from fabric.api import run
....
run("python ./myApp.py --... | fabric run fork | I want to use Fabric.api.run to directly start an application in a remote box. Since the application takes really a long to finish, I wish to be able to fork a child process, such that I don't need to wait for a long time.
The code is like:
from fabric.api import run
....
run("python ./myApp.py --fork=True >myApp.log ... | [
"Talking of forks, there is a fork of Fabric that enables parallel execution, apart from lots of other improvements.\nhttp://tav.espians.com/fabric-python-with-cleaner-api-and-parallel-deployment-support.html\nDepending on what you are doing, you may want to consider that.\n\nApart from that, I think you want to us... | [
3
] | [] | [] | [
"fabric",
"fork",
"python"
] | stackoverflow_0005922855_fabric_fork_python.txt |
Q:
How come CPython is faster than PyPy on the two tests "slowspitfire" and "waf"?
Judging from the benchmarks posted on the PyPy Speed Center it appears as if PyPy is faster than CPython for all but two of the tests presented.
CPython is faster than PyPy on the two tests "slowspitfire" and "waf". Why is that? What k... | How come CPython is faster than PyPy on the two tests "slowspitfire" and "waf"? | Judging from the benchmarks posted on the PyPy Speed Center it appears as if PyPy is faster than CPython for all but two of the tests presented.
CPython is faster than PyPy on the two tests "slowspitfire" and "waf". Why is that? What kind of operations do those two tests test? What makes CPython faster for those operat... | [
"As Tobu said, there's a message on the mailing list that sketches an explanation for slowspitfire: long lists with GC objects in them, among other factors.\nThe waf benchmark has less of a pronounced difference in performance, and I'd guess that the answer would be more complicated: some factors PyPy does better, ... | [
8
] | [] | [] | [
"benchmarking",
"cpython",
"pypy",
"python"
] | stackoverflow_0005843950_benchmarking_cpython_pypy_python.txt |
Q:
Why is standard output from subprocess (redirected to unbuffered file) being buffered?
From http://docs.python.org/library/functions.html#open
The optional bufsize argument
specifies the file’s desired buffer
size: 0 means unbuffered, 1 means line
buffered, any other positive value
means use a buffer of (... | Why is standard output from subprocess (redirected to unbuffered file) being buffered? | From http://docs.python.org/library/functions.html#open
The optional bufsize argument
specifies the file’s desired buffer
size: 0 means unbuffered, 1 means line
buffered, any other positive value
means use a buffer of (approximately)
that size. A negative bufsize means to
use the system default, which is
... | [
"Use python with the -u flag, e.g.:\nif __name__ == '__main__':\n p = subprocess.Popen(\n ['python', '-u', 'sub_process.py'],\n stdout=open('std-output', 'w'))\n time.sleep(3)\n p.terminate()\n\n",
"Extending Magnus Skog solution (+1 by the way :) ):\nWell basically what happen is that when... | [
8,
5
] | [] | [] | [
"buffering",
"popen",
"python",
"stdout",
"subprocess"
] | stackoverflow_0005922554_buffering_popen_python_stdout_subprocess.txt |
Q:
Calculating similarity -> python code to php code - Whats wrong?
I am trying to convert the following python code to a PHP code. Can you please explain me what is wrong in my PHP code, because I do not get the same results. If you need example data please let me know.
# Returns a distance-based similarity score fo... | Calculating similarity -> python code to php code - Whats wrong? | I am trying to convert the following python code to a PHP code. Can you please explain me what is wrong in my PHP code, because I do not get the same results. If you need example data please let me know.
# Returns a distance-based similarity score for person1 and person2
def sim_distance(prefs,person1,person2):
# ... | [
"The main difference is that you've added sqrt to the PHP code. The PHP also doesn't handle the special case of no prefs in common, which gives 0 in the python version and 1 in the PHP version.\nI tested both versions and those are the only differences I found.\n",
"this is close as i could make a direct translat... | [
1,
0
] | [] | [] | [
"php",
"python",
"similarity"
] | stackoverflow_0005923275_php_python_similarity.txt |
Q:
Problems importing GDK
I am trying to import GDK to my program however I continue to get an error
No module named GDK
Do you know how I can fix this? Since it was working before I already tried import gtk.GDK
and import GDK.
I have installed PyGTK and PyGDK is part of of it pyGTK.
A:
Try:
import gtk.gdk
(note:... | Problems importing GDK | I am trying to import GDK to my program however I continue to get an error
No module named GDK
Do you know how I can fix this? Since it was working before I already tried import gtk.GDK
and import GDK.
I have installed PyGTK and PyGDK is part of of it pyGTK.
| [
"Try:\nimport gtk.gdk\n\n(note: small letters)\n"
] | [
8
] | [] | [] | [
"gdk",
"gtk",
"import",
"python",
"user_interface"
] | stackoverflow_0005923746_gdk_gtk_import_python_user_interface.txt |
Q:
Python sorting a file by frequency
I have a file that contains a list of words like:
word1 34
word2 12
word3 6
word4 498
word5 50
I want to sort the file by the numerical value. My code:
sortedfreqlist = sorted(freqlist, key=operator.itemgetter(1), reverse=True)
Doesn't quite work because it sorts the numbers as ... | Python sorting a file by frequency | I have a file that contains a list of words like:
word1 34
word2 12
word3 6
word4 498
word5 50
I want to sort the file by the numerical value. My code:
sortedfreqlist = sorted(freqlist, key=operator.itemgetter(1), reverse=True)
Doesn't quite work because it sorts the numbers as words i.e 12 comes before 6 etc.
Any ide... | [
"The sorting is not working because your values are not of a numeric type, thus lexicographic sorting is applied. Be sure to convert your sort key to to a number, for example like this:\nsortedfreqlist = sorted(freqlist, key=lambda item: int(item[1]), reverse=True)\n\n",
"Search \"natural sort python\" in your fa... | [
3,
0
] | [] | [] | [
"file",
"int",
"python",
"sorting",
"string"
] | stackoverflow_0005923792_file_int_python_sorting_string.txt |
Q:
Stumped by relative imports
I don't know what's going on:
$ ls
__init__.py main.py module.py
$ cat main.py
from . import module
$ python3 main.py
Traceback (most recent call last):
File "main.py", line 1, in <module>
from . import module
ValueError: Attempted relative import in non-package
A:
From PEP 32... | Stumped by relative imports | I don't know what's going on:
$ ls
__init__.py main.py module.py
$ cat main.py
from . import module
$ python3 main.py
Traceback (most recent call last):
File "main.py", line 1, in <module>
from . import module
ValueError: Attempted relative import in non-package
| [
"From PEP 328:\n\nRelative imports use a module's __name__ attribute to determine that module's position in the package hierarchy. If the module's name does not contain any package information (e.g. it is set to '__main__') then relative imports are resolved as if the module were a top level module, regardless of w... | [
4,
0
] | [] | [] | [
"python"
] | stackoverflow_0005923775_python.txt |
Q:
Google App Engine get and post on the same model
I am new to google app engine/webapp and trying to get a simple app running. The app will be for a demo car rental service. I would like to have a request handler for adding new cars that handles both a get and a post for the add car page.
The get should return a f... | Google App Engine get and post on the same model | I am new to google app engine/webapp and trying to get a simple app running. The app will be for a demo car rental service. I would like to have a request handler for adding new cars that handles both a get and a post for the add car page.
The get should return a form to be filled and submitted. The post should add th... | [
"I've tested your code and is correct, my guess is that the original post method in your code has some indentation error.\n"
] | [
3
] | [] | [] | [
"google_app_engine",
"python",
"web_applications"
] | stackoverflow_0005923921_google_app_engine_python_web_applications.txt |
Q:
Python EIG matrix
I have
k=linalg.eig(Ki)
where Ki for example is :
[[ 1.84026465 -0.463138 ]
[-0.463138 3.83931947]]
and result k is:
(array([ 1.73817877, 3.94140535]), array([[-0.97655787, 0.21525501],
[-0.21525501, -0.97655787]]))
how can I display just biggest value from k (I don't know why ar... | Python EIG matrix | I have
k=linalg.eig(Ki)
where Ki for example is :
[[ 1.84026465 -0.463138 ]
[-0.463138 3.83931947]]
and result k is:
(array([ 1.73817877, 3.94140535]), array([[-0.97655787, 0.21525501],
[-0.21525501, -0.97655787]]))
how can I display just biggest value from k (I don't know why are there 2 array, if I c... | [
"linalg.eig returns two arrays, first the eigenvalues, then the eigenvectors.\nIf you want the maximimum eigenvalue, then\nvals,vecs=linalg.eig(Ki)\nmax_eigenvalue = vals.max()\n\n",
"Here are the eigenvalues: \nhttp://www.wolframalpha.com/input/?i=eigenvalues{{1.84026465%2C-0.463138}%2C%20{-0.21525501%2C%20-0.97... | [
5,
1
] | [] | [] | [
"matrix",
"python"
] | stackoverflow_0005923969_matrix_python.txt |
Q:
python script to send commands to vim (mvim)
I wrote a very simple vim plugin and python script trying to test some communication between the two. My vim-script looks like this:
function! HelloWorld()
silent :!python helloworld.py
endf
nmap <C-P> :call HelloWorld()<CR>
then my python script looks like this:
... | python script to send commands to vim (mvim) | I wrote a very simple vim plugin and python script trying to test some communication between the two. My vim-script looks like this:
function! HelloWorld()
silent :!python helloworld.py
endf
nmap <C-P> :call HelloWorld()<CR>
then my python script looks like this:
import os;
os.system( 'mvim --servername VIM -u N... | [
"Try replacing\nsilent :!python helloworld.py\n\nwith\nsilent :!(sleep 0.5s && python helloworld.py) &\nredraw!\n\n(the point is in returning to vim before remote command arrives). If it works, then the problem is in processing remote commands while receiving shell output. You can also try another workarounds:\ncal... | [
3
] | [] | [] | [
"macvim",
"python",
"vim"
] | stackoverflow_0005923721_macvim_python_vim.txt |
Q:
avoid duplicate key names by adding suffix
I need to have my title as the keyname the problem is this could cause problems with duplicate keynames, how can i check if it exists and add -1 to the end if it does, or add -2 to the end if -1 exists.
keyName = "hello"
duplicates = Entry.get_by_key_name(keyName)
... | avoid duplicate key names by adding suffix | I need to have my title as the keyname the problem is this could cause problems with duplicate keynames, how can i check if it exists and add -1 to the end if it does, or add -2 to the end if -1 exists.
keyName = "hello"
duplicates = Entry.get_by_key_name(keyName)
if duplicates:
keyName = ke... | [
"keyName = \"hello\"\n\ntestName = keyName\nsuffix = 0\nwhile Entry.get_by_key_name(testName):\n suffix += 1\n testName = \"%s-%d\" % (keyName, suffix)\n\nkeyName = testName\n\n",
"A different way to think about the problem:\nfrom itertools import imap, dropwhile, count\n\ndef make_name(i):\n stem = \"foo\"\... | [
3,
2
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0005924097_google_app_engine_python.txt |
Q:
Passing a numpy array to Delphi dll
I am trying to implement an image classification algorithm in Python. The problem is that python takes very long with looping through the array. That's why I decided to write a Delphi dll which performs the array-processing. My problem is that I don't know how to pass the multid... | Passing a numpy array to Delphi dll | I am trying to implement an image classification algorithm in Python. The problem is that python takes very long with looping through the array. That's why I decided to write a Delphi dll which performs the array-processing. My problem is that I don't know how to pass the multidimensional python-array to my dll-functio... | [
"What you're doing won't work, and is likely to corrupt memory too.\nA Delphi dynamic array is implemented under the hood as a data structure that holds some metadata about the array, including the length. But what you're passing to it is a C-style pointer-as-array, which is a pointer, not a Delphi dynamic array d... | [
1,
1
] | [] | [] | [
"delphi",
"dll",
"multidimensional_array",
"python"
] | stackoverflow_0005913129_delphi_dll_multidimensional_array_python.txt |
Q:
Global variable in Python
I've been reading a Python textbook, and I see the following code:
class Database:
# the database implementation
pass
database = None
def initialize_database():
global database
database = Database()
Now, why is there a global declaration inside initialize_database function?... | Global variable in Python | I've been reading a Python textbook, and I see the following code:
class Database:
# the database implementation
pass
database = None
def initialize_database():
global database
database = Database()
Now, why is there a global declaration inside initialize_database function? We had defined database outsid... | [
"You can reference a global when it's not declared global in a function, but you can only read it; writing it will create a new local variable hiding the global variable. The global declaration makes it able to write to the global.\n",
"'global x' doesn't make x global, it should be read as \"from now on in this ... | [
9,
1
] | [] | [] | [
"declaration",
"function",
"global_variables",
"python"
] | stackoverflow_0005924636_declaration_function_global_variables_python.txt |
Q:
Having trouble understanding some class code in python
I'm pretty new to programming and am having some trouble understanding the output of this code.
#testclass.py
class TestCount:
count = 0
def __init__(self):
self.attr1 = TestCount.count
self.attr2 = TestCount.count + 1
TestCoun... | Having trouble understanding some class code in python | I'm pretty new to programming and am having some trouble understanding the output of this code.
#testclass.py
class TestCount:
count = 0
def __init__(self):
self.attr1 = TestCount.count
self.attr2 = TestCount.count + 1
TestCount.count += 2
x = TestCount()
y = TestCount()
print(x.attr1... | [
"count is a property of the class, not the instance. That means this value is shared by all instances.\nYou are initializing attr1 with TestCount.count and later increasing it by 2. So the second instance will start with attr1 being set to 2, for the third instance 4, etc.\nIf you want both properties (attr1 and a... | [
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0005925017_python.txt |
Q:
Why does wsgiref.simple_server report content-type of request as 'text/plain' while none was sent?
Output from client.py is text/plain although no content-type header was sent to the server.
Why?
# ---------------------------------------------- server.py
from wsgiref.simple_server import make_server
def simple_ap... | Why does wsgiref.simple_server report content-type of request as 'text/plain' while none was sent? | Output from client.py is text/plain although no content-type header was sent to the server.
Why?
# ---------------------------------------------- server.py
from wsgiref.simple_server import make_server
def simple_app(environ, start_response):
print environ.get('CONTENT_TYPE')
start_response('200 OK', [])
r... | [
"The type text/plain is the default for MIME, in section 5.2 Content Type Defaults.\nThe WSGI simple_server uses BaseHTTPRequestHandler which in turn uses a mimetools.Message class to parse the headers sent by the client -- here is where it sets the default:\n# mimetools.py\n\nclass Message(rfc822.Message):\n\n ... | [
1
] | [] | [] | [
"content_type",
"python",
"wsgi",
"wsgiref"
] | stackoverflow_0005924166_content_type_python_wsgi_wsgiref.txt |
Q:
Sorting data and generating table outputs from CSV file in Python
Let's say I've got the following CSV file (subjects.csv)
subjects,name1,name2,name3
Chemistry,Tom,Will,Rob
Biology,Megan,Sam,Tim
Physics,Tim,Will,Bob
Maths,Will,Tim,Joe
I want to find which pairs of students share the same class, focusing only on T... | Sorting data and generating table outputs from CSV file in Python | Let's say I've got the following CSV file (subjects.csv)
subjects,name1,name2,name3
Chemistry,Tom,Will,Rob
Biology,Megan,Sam,Tim
Physics,Tim,Will,Bob
Maths,Will,Tim,Joe
I want to find which pairs of students share the same class, focusing only on Tim, Tom and Will. How would I go about pairing these in Python?
i.e.
Ti... | [
"You can create a dictionary with what class each student is taking:\n>>> import csv\n>>> import collections\n>>> D = collections.defaultdict(set)\n>>> with open('subjects.csv','rb') as f:\n... subject_reader = csv.reader(f)\n... header = subject_reader.next()\n... for row in subject_reader:\n... ... | [
4
] | [] | [] | [
"csv",
"python"
] | stackoverflow_0005925011_csv_python.txt |
Q:
Is there anyway to bind an event handler to a Tkinter window being moved?
I'm trying to make it so that if a Tkinter window is dragged or moved in any way, a function is called. Is there any way to do this?
This is in Windows 7.
A:
Possibly the configure event.
http://effbot.org/tkinterbook/tkinter-events-and-... | Is there anyway to bind an event handler to a Tkinter window being moved? | I'm trying to make it so that if a Tkinter window is dragged or moved in any way, a function is called. Is there any way to do this?
This is in Windows 7.
| [
"Possibly the configure event. \nhttp://effbot.org/tkinterbook/tkinter-events-and-bindings.htm\nsearch for:\n<Configure>\nThe widget changed size (or location, on some platforms). The new size is \nprovided in the width and height attributes of the event object passed to the callback.\n\n"
] | [
3
] | [] | [] | [
"drag",
"python",
"tkinter",
"window",
"windows_7"
] | stackoverflow_0005925130_drag_python_tkinter_window_windows_7.txt |
Q:
Python inside GNU Screen eventually becomes idle if Screen is dettached
I have a python script which uses multiprocessing and subprocess to launch multiple external commands in parallel with different arguments. The code can be found here.
For convenience I launch this script inside a GNU Screen session. The machi... | Python inside GNU Screen eventually becomes idle if Screen is dettached | I have a python script which uses multiprocessing and subprocess to launch multiple external commands in parallel with different arguments. The code can be found here.
For convenience I launch this script inside a GNU Screen session. The machine where this script is running has 12 processors which are idle until proces... | [
"I can't explain the reason for what you are seeing. However, I do have an idea of what you can try next.\n\nTry piping the output of the script to: | tee out.txt\nIf that has no effect, try...\nRun screen on another [hop] host. From there SSH into your worker host. Run your script in the non-emulated shell. Then ... | [
4
] | [] | [] | [
"gnu_screen",
"idle_processing",
"multiprocessing",
"python",
"subprocess"
] | stackoverflow_0005925170_gnu_screen_idle_processing_multiprocessing_python_subprocess.txt |
Q:
gql error: BadQueryError: Parse Error: Invalid ORDER BY Property at symbol :3
I'm getting this error:
Parse Error: Invalid ORDER BY Property at symbol :3
Can't see what is causing it, if I remove the substitution and add "date" it works.
order = "date"
playlists_data = db.GqlQuery('SELECT * FROM Playlist WHERE
... | gql error: BadQueryError: Parse Error: Invalid ORDER BY Property at symbol :3 | I'm getting this error:
Parse Error: Invalid ORDER BY Property at symbol :3
Can't see what is causing it, if I remove the substitution and add "date" it works.
order = "date"
playlists_data = db.GqlQuery('SELECT * FROM Playlist WHERE
client = :1 AND
catego... | [
"ORDER BY doesn't support bound parameters.\nThey can only be used in a WHERE clause, and only to replace property values, not property names.\n"
] | [
4
] | [] | [] | [
"google_app_engine",
"gql",
"python"
] | stackoverflow_0005925139_google_app_engine_gql_python.txt |
Q:
PyQt4 create windows that are unresizable
For some reason, any widget I create using PyQt4 cannot be resized. When i try and resize the window with the mouse nothing happens. The following simple program reproduces this behavior on my machine:
from PyQt4.QtGui import QMainWindow, QApplication
from sys import argv
... | PyQt4 create windows that are unresizable | For some reason, any widget I create using PyQt4 cannot be resized. When i try and resize the window with the mouse nothing happens. The following simple program reproduces this behavior on my machine:
from PyQt4.QtGui import QMainWindow, QApplication
from sys import argv
app = QApplication(argv)
mw = QMainWindow()
ap... | [
"mw.setGeometry(0, 0, 640, 480) before exec.\n\nit locates window on screen (firs two parametrs), resizes it (3 and 4 parametr) and enables resizing.\n",
"I have found the solution - it turns out I had broken my compiz settings in a rather... unique manner, which caused Qt apps to not resize correctly. Thanks to ... | [
0,
0
] | [] | [] | [
"c++",
"pyqt",
"python",
"qt",
"qt4"
] | stackoverflow_0005924702_c++_pyqt_python_qt_qt4.txt |
Q:
Python string trimming
I have a string in python, which is in this format:
[NUMBER][OPERATOR][NUMBER][UNNEEDED JUNK]
e.g.:
5+5.[)]1
How could I trim that down to just 5+5?
EDIT
I forgot to mention, basically, you just need to look for the first non-numeric character after the operator, and crop everything (start... | Python string trimming | I have a string in python, which is in this format:
[NUMBER][OPERATOR][NUMBER][UNNEEDED JUNK]
e.g.:
5+5.[)]1
How could I trim that down to just 5+5?
EDIT
I forgot to mention, basically, you just need to look for the first non-numeric character after the operator, and crop everything (starting at that point) off.
| [
"This is a simple regular expression:\nimport re\n\ns = \"5+5.[)]1\"\ns = re.search(\"\\d+\\+\\d+\", s).group()\nprint(s) # 5+5\n\n",
"re.search(r'\\d+.\\d+','123+55.[)]1').group()\n\nThis should work.\n"
] | [
6,
3
] | [] | [] | [
"python",
"regex",
"string",
"trim"
] | stackoverflow_0005925297_python_regex_string_trim.txt |
Q:
python loop through imports & check for variable
I've successfully imported a bunch of modules in a folder using
from assets import *
Now i want to loop through those imported modules and check for a specific variable or function. I tried to use dir() function to get a list of imported modules and look through t... | python loop through imports & check for variable | I've successfully imported a bunch of modules in a folder using
from assets import *
Now i want to loop through those imported modules and check for a specific variable or function. I tried to use dir() function to get a list of imported modules and look through them, but because i'm looping through an array of strin... | [
"I think what you're doing could be done much more simply:\nimport assets\nfor aModule in vars(assets).values():\n if hasattr(aModule, 'alt') and word in aModule.alt:\n print \"found it!\"\n print aModule.__name__\n\n"
] | [
3
] | [] | [] | [
"dir",
"for_loop",
"import",
"python"
] | stackoverflow_0005924836_dir_for_loop_import_python.txt |
Q:
Extensions and libraries for Django
Where can find all the extensions and libraries for Django in one place. http://planetdjango.org/ seemed have all the news but not all of the libraries.
Something like http://wordpress.org/extend/plugins/ with ratings and comments by the community
A:
The best place by far is... | Extensions and libraries for Django | Where can find all the extensions and libraries for Django in one place. http://planetdjango.org/ seemed have all the news but not all of the libraries.
Something like http://wordpress.org/extend/plugins/ with ratings and comments by the community
| [
"The best place by far is http://djangopackages.com/. It has a very novel approach to organizing apps, it's a great resource. It has a grid system which makes it easy to compare apps with similar features. It's built on an opensource django project, and it seems they will be launching a pythonpackages.com soon as w... | [
6,
1
] | [] | [] | [
"django",
"libraries",
"plugins",
"python"
] | stackoverflow_0005925613_django_libraries_plugins_python.txt |
Q:
I'm trying to learn SQLite for Python...Best method?
I've read a few books that touch on SQLite but nothing concrete enough to help me learn it within Python, Question is, is there any book or source you could recommend to help me with this...
Secondly is learning MySQL the same as learning SQLite because I see th... | I'm trying to learn SQLite for Python...Best method? | I've read a few books that touch on SQLite but nothing concrete enough to help me learn it within Python, Question is, is there any book or source you could recommend to help me with this...
Secondly is learning MySQL the same as learning SQLite because I see those resources everywhere...
| [
"You probably want to learn about SQL, variants of which are used by a number of different relational databases, including MySQL and SQLite (which as several comments have pointed out you are mixing together) using the python standard library's sqlite3 module. You can't go wrong with Doug Hellmann's PyMOTW introduc... | [
8,
1
] | [] | [] | [
"python",
"sqlite"
] | stackoverflow_0005925167_python_sqlite.txt |
Q:
Extracting paragraph breaks from OCR text?
I'm trying to recreate the paragraphs and indentations from the output of OCR'd image text, like so:
Input (imagine that this is an image, not typed):
Output (with a few mistakes):
As you can see, no paragraph breaks or indentations are preserved.
Using Python, I tried ... | Extracting paragraph breaks from OCR text? | I'm trying to recreate the paragraphs and indentations from the output of OCR'd image text, like so:
Input (imagine that this is an image, not typed):
Output (with a few mistakes):
As you can see, no paragraph breaks or indentations are preserved.
Using Python, I tried an approach like this, but it doesn't work (fail... | [
"You can break up the image into multiple paragraphs by looking at the entropy of each 5-10 pixel horizontal slice. Although this is usually used to create \"interesting\" thumbnails from larger images or videos, you can also use it to identify the presence or absence of text. Here's how.\nYou divide the image into... | [
5,
1
] | [] | [] | [
"latex",
"ocr",
"python",
"tesseract"
] | stackoverflow_0005925561_latex_ocr_python_tesseract.txt |
Q:
UPDATE:Sorting a list from a for output from highest to lowest in python
for x in letters:
frequency[x]+=1
for x in frequency:
print x,frequency[x],frequency[x]/float(n)
Sorry but I'm fairly new to programming and everything and I'm trying to get the output to be sorted from highest v... | UPDATE:Sorting a list from a for output from highest to lowest in python | for x in letters:
frequency[x]+=1
for x in frequency:
print x,frequency[x],frequency[x]/float(n)
Sorry but I'm fairly new to programming and everything and I'm trying to get the output to be sorted from highest value of frequency[x]/float(n) to lowest value. Is there any method of being a... | [
"For the keys:\nsorted(frequency, key=lambda x: frequency[x], reverse=True)\n\n",
"This should do the trick:\nfreqs = sorted([frequency[x]/float(n) for x in frequency], reverse=True)\n\nIf you want it more like the print statement you have above, try this:\nfor (fxn, fx, x) in sorted([(frequency[x]/float(n), freq... | [
3,
1,
1,
1
] | [] | [] | [
"frequency",
"histogram",
"python"
] | stackoverflow_0005925703_frequency_histogram_python.txt |
Q:
Frequency Analysis in Python -Print letters with frequency rather than numbers with frequency
s=array1 #user inputs an array with text in it
n=len(s)
f=arange(0,26,1)
import collections
dict = collections.defaultdict(int)
for c in s:
dict[c] += 1
for c in f:
print c,dict[c]/float(n)
In the output, c is ... | Frequency Analysis in Python -Print letters with frequency rather than numbers with frequency | s=array1 #user inputs an array with text in it
n=len(s)
f=arange(0,26,1)
import collections
dict = collections.defaultdict(int)
for c in s:
dict[c] += 1
for c in f:
print c,dict[c]/float(n)
In the output, c is in numbers rather then letters and I'm not sure how to convert it back to letters.
Also, is there ... | [
"It should be pointed out that you aren't calling map with the right type of arguments (thus the TypeError). It takes a single function and one or more iterables, to which the function is applied to. Your second argument is toChar[i] which would be a string. All iterables implement __iter__. To illustrate:\n>>> l, ... | [
4,
3,
1,
1,
0
] | [] | [] | [
"frequency_analysis",
"histogram",
"numbers",
"python"
] | stackoverflow_0005925442_frequency_analysis_histogram_numbers_python.txt |
Q:
Facebook Python SDK
How do you post to Facebook using the Facebook Python SDK? I tried to do it using:
self.Facebook = facebooksdk.GraphAPI(oauth_token)
self.Facebook.put_object("me", "feed", message="Hello World.")
And here's my traceback:
Traceback (most recent call last):
File "epistle.py", line 559, in send
s... | Facebook Python SDK | How do you post to Facebook using the Facebook Python SDK? I tried to do it using:
self.Facebook = facebooksdk.GraphAPI(oauth_token)
self.Facebook.put_object("me", "feed", message="Hello World.")
And here's my traceback:
Traceback (most recent call last):
File "epistle.py", line 559, in send
self.Facebook.put_object("... | [
"Are you correctly obtaining the oauth_token value? Bad signature indicates the the SDK signed the request to Facebook but the token didn't match what Facebook's API servers were expecting. I would check that you are using the correct Facebook application key and secret when you extract the oauth_token from the Fac... | [
1
] | [] | [] | [
"facebook",
"facebook_graph_api",
"python"
] | stackoverflow_0005925099_facebook_facebook_graph_api_python.txt |
Q:
Getting a set of values from a dictionary of sets
What is the preferred method to get the set of values from a dictionary of sets?
I came up with using reduce and itervalues() was wondering if there is a better method.
>>> m_dict = { 'a': set([1,2]),
... 'b': set([1,4,5]),
... 'c': set([2,8,9]) }
>>> print m_dict
... | Getting a set of values from a dictionary of sets | What is the preferred method to get the set of values from a dictionary of sets?
I came up with using reduce and itervalues() was wondering if there is a better method.
>>> m_dict = { 'a': set([1,2]),
... 'b': set([1,4,5]),
... 'c': set([2,8,9]) }
>>> print m_dict
{'a': set([1, 2]), 'c': set([8, 9, 2]), 'b': set([1, 4,... | [
"set.union can accept multiple sets so, set.union(*m_dict.values())\n"
] | [
4
] | [] | [] | [
"dictionary",
"python",
"set"
] | stackoverflow_0005926011_dictionary_python_set.txt |
Q:
Plot Histogram in Python
I have two lists, x and y.
x contains the alphabet A-Z and Y contains the frequency of them in a file.
I've tried researching how to plot these values in a histogram but has had no success with understanding how to plot it.
n, bins, patches = plt.hist(x, 26, normed=1, facecolor='blue', alp... | Plot Histogram in Python | I have two lists, x and y.
x contains the alphabet A-Z and Y contains the frequency of them in a file.
I've tried researching how to plot these values in a histogram but has had no success with understanding how to plot it.
n, bins, patches = plt.hist(x, 26, normed=1, facecolor='blue', alpha=0.75)
Would x be list x in... | [
"hist works on a collection of values and computes and draws the histogram from them.\nIn your case you already precalculated the frequency of each group (letter). To represent your data in an histogram form use better matplotlib bar:\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nalphab = ['A', 'B', 'C', ... | [
50
] | [] | [] | [
"frequency",
"histogram",
"python"
] | stackoverflow_0005926061_frequency_histogram_python.txt |
Q:
Python server problems
I created a simple server and client using Python. When i run it on my computer i works fine. But if i run the server on my comupter and try to open client on the other computer, it cant find my server.
Thanks for helping.
A:
Do you know the IP for your server computer? Just making sure y... | Python server problems | I created a simple server and client using Python. When i run it on my computer i works fine. But if i run the server on my comupter and try to open client on the other computer, it cant find my server.
Thanks for helping.
| [
"Do you know the IP for your server computer? Just making sure you know that 127.0.0.1 (or localhost) no longer works in this setup.\nAre your computers behind a NAT?\nCan you ping from one computer to another?\nDo you have a firewall?\n",
"For BaseHTTPServer http://docs.python.org/library/basehttpserver.html you... | [
2,
0
] | [] | [] | [
"network_programming",
"networking",
"python"
] | stackoverflow_0005926773_network_programming_networking_python.txt |
Q:
python sockets, request.recv and signals
i have a question because i am fairly new to python, socket programming and signals. i have written a python socket server that forks a new process to handle requests for every client that connects to a certain port. I have caught the ctrl+c signal and closed my database co... | python sockets, request.recv and signals | i have a question because i am fairly new to python, socket programming and signals. i have written a python socket server that forks a new process to handle requests for every client that connects to a certain port. I have caught the ctrl+c signal and closed my database connections should the the server get such signa... | [
"Signals exist in their own process: a signal raised in a client process won't be known about by the server process and vice versa. Your options are either to have one process tell the other that it is being terminated, or just wait for the other side to notice that the connection has been dropped (which, if you're... | [
2
] | [] | [] | [
"linux",
"python",
"signals",
"sockets"
] | stackoverflow_0005926908_linux_python_signals_sockets.txt |
Q:
GTK MenuItem with counter bubble on right
I want to ask if there's a simple way to do MenuItem like this http://dl.dropbox.com/u/865508/menuitem.png in PyGtk (or maybe some other language rather than python). I think it would be helpful for a lot of people)
Thank you.
A:
Yes; a MenuItem is also a Container, so y... | GTK MenuItem with counter bubble on right | I want to ask if there's a simple way to do MenuItem like this http://dl.dropbox.com/u/865508/menuitem.png in PyGtk (or maybe some other language rather than python). I think it would be helpful for a lot of people)
Thank you.
| [
"Yes; a MenuItem is also a Container, so you can add any widgets you like to it. Just create an empty one with gtk.MenuItem(label=None) and add an HBox with a label on the left and an icon (for the counter bubble) on the right.\n"
] | [
1
] | [] | [] | [
"gnome",
"gtk",
"python",
"ubuntu"
] | stackoverflow_0005924292_gnome_gtk_python_ubuntu.txt |
Q:
Can't import matplotlib
I installed matplotlib using the Mac disk image installer for MacOS 10.5 and Python 2.5. I installed numpy then tried to import matplotlib but got this error: ImportError: numpy 1.1 or later is required; you have 2.0.0.dev8462. It seems to that version 2.0.0.dev8462 would be later than vers... | Can't import matplotlib | I installed matplotlib using the Mac disk image installer for MacOS 10.5 and Python 2.5. I installed numpy then tried to import matplotlib but got this error: ImportError: numpy 1.1 or later is required; you have 2.0.0.dev8462. It seems to that version 2.0.0.dev8462 would be later than version 1.1 but I am guessing tha... | [
"Here is the troublesome code located in Lib/site-packages/matplotlib/__init__.py in my python distribution on Windows\nnn = numpy.__version__.split('.')\nif not (int(nn[0]) >= 1 and int(nn[1]) >= 1):\n raise ImportError(\n 'numpy 1.1 or later is required; you have %s' % numpy.__version__)\n\nThe prob... | [
1,
0
] | [] | [] | [
"installation",
"matplotlib",
"numpy",
"python"
] | stackoverflow_0003035028_installation_matplotlib_numpy_python.txt |
Q:
Separating code from for function while using values within for function in python
Sorry for the confusing title :s
for x in frequency:
alphab = [x]
frequencies = [frequency[x]]
print alphab, frequencies
How would I be able to separate the below code from the above code whilst still using ... | Separating code from for function while using values within for function in python | Sorry for the confusing title :s
for x in frequency:
alphab = [x]
frequencies = [frequency[x]]
print alphab, frequencies
How would I be able to separate the below code from the above code whilst still using the output from for x in frequency: If I run what's here, the histogram is opened for ea... | [
"def plotfreq(frequency, alphab):\n\n pos = np.arange(len(alphab))\n width = 1.0 \n\n ax = plt.axes()\n ax.set_xticks(pos + (width / 2))\n ax.set_xticklabels(alphab)\n plt.xlabel('Letter')\n plt.ylabel('Absolute Frequency')\n plt.title(\"Absolute Frequency of letters in text\")\n plt.... | [
0,
0
] | [] | [] | [
"for_loop",
"python"
] | stackoverflow_0005926821_for_loop_python.txt |
Q:
How to get the bar heights of histogram P(x) corresponding to a given x?
I am relatively new to python. I have plotted a histogram (say P(r)) of Gaussian random numbers (r) using the code given below where I have used the numpy.hist command. How can I now get the value of P(r) corresponding to a given value of r? ... | How to get the bar heights of histogram P(x) corresponding to a given x? | I am relatively new to python. I have plotted a histogram (say P(r)) of Gaussian random numbers (r) using the code given below where I have used the numpy.hist command. How can I now get the value of P(r) corresponding to a given value of r? I mean I need the bar height corresponding to a given value on the x-axis of t... | [
"The hist() function returns the information you are looking for:\nn, bins, patches = pl.hist(R, nbins, normed=True)\n\nn is an array of the bar heights, and bins is the array of bin boundaries. In the given example, len(n) would be 100 and len(bins) would be 101.\nGiven some x value, you can use numpy.searchsorte... | [
8
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0005926937_numpy_python.txt |
Q:
Python GUI - padding colour
So i've created a frame here..
frame=Frame(master, bg="grey")
frame.pack(side=TOP, fill=BOTH, padx=15, expand=1)
self.canvas = Canvas(frame, height = 500, width = 7000, bg="white")
self.canvas.pack()
It has got some padding, however, i want the padding to have some color like blue. I ... | Python GUI - padding colour | So i've created a frame here..
frame=Frame(master, bg="grey")
frame.pack(side=TOP, fill=BOTH, padx=15, expand=1)
self.canvas = Canvas(frame, height = 500, width = 7000, bg="white")
self.canvas.pack()
It has got some padding, however, i want the padding to have some color like blue. I don't know how to do that. I thin... | [
"The padding color is just the color of the container it is in. You can use another frame with whatever color that you want. \nYour other option is to use the highlightbackground and highlightthickness options if you dont need them to serve their normal purpose (which is to show which widget has keyboard focus)\n"
... | [
1
] | [] | [] | [
"python",
"tkinter",
"user_interface"
] | stackoverflow_0005927085_python_tkinter_user_interface.txt |
Q:
Multiple text inputs in django form via Google App Engine
Goal: to create a question where a user creates a poll question that is "mad-libs" style (i.e. "Would you fool around with _(text)__ if she wasnt dating _(text)_?").
Code: This file creates a django form corresponding to an appengine entity.
from django im... | Multiple text inputs in django form via Google App Engine | Goal: to create a question where a user creates a poll question that is "mad-libs" style (i.e. "Would you fool around with _(text)__ if she wasnt dating _(text)_?").
Code: This file creates a django form corresponding to an appengine entity.
from django import newforms as forms
import models
from google.appengine.ext.... | [
"I still don't totally understand your question. If you post your full source and an example of the result you are trying to get, then you will get a better response. \nHere's an example of constructing a form for someone to answer the question. I hard coded the question, but you could easily retrieve that dynam... | [
0
] | [] | [] | [
"django",
"django_forms",
"django_models",
"google_app_engine",
"python"
] | stackoverflow_0005905645_django_django_forms_django_models_google_app_engine_python.txt |
Q:
Pytesser inaccurate
Simple question. When I run this image through pytesser, i get $+s. How can I fix that?
EDIT
So... my code generates images similar to the image linked above, just with different numbers, and is supposed to solve the simple math problem, which is obviously impossible if all I can get out of the... | Pytesser inaccurate | Simple question. When I run this image through pytesser, i get $+s. How can I fix that?
EDIT
So... my code generates images similar to the image linked above, just with different numbers, and is supposed to solve the simple math problem, which is obviously impossible if all I can get out of the picture is $+s
Here's th... | [
"Try my little function. I'm running tesseract from the svn repo, so my results might be more accurate.\nI'm on Linux, so on Windows, I'd imagine that you'll have to replace tesseract with tesseract.exe to make it work.\nimport tempfile, subprocess\n\ndef ocr(image):\n tempFile = tempfile.NamedTemporaryFile(delete... | [
2,
1
] | [] | [] | [
"ocr",
"python"
] | stackoverflow_0005925344_ocr_python.txt |
Q:
xml.dom.minidom.parse() failing when XML attribute contains unicode
I'm querying a web service using urllib2.request and receiving XML. If I violate the web service's rate limit (1 call/second), I receive HTML back saying I've violated the rate limit.
Even though I can time.sleep() for 2-3 seconds after each call,... | xml.dom.minidom.parse() failing when XML attribute contains unicode | I'm querying a web service using urllib2.request and receiving XML. If I violate the web service's rate limit (1 call/second), I receive HTML back saying I've violated the rate limit.
Even though I can time.sleep() for 2-3 seconds after each call, I still, for whatever reason, violate the rate limit.
To test that my re... | [
"I think that 	 is a tab. You should try http://docs.python.org/library/htmllib.html#module-htmlentitydefs to convert special html entities back to whatever they are. (That may have the problem of < etc). Or you could do a string substitution that substitute 	 with a space.\nJust as a suggestion, when you'... | [
0,
0
] | [] | [] | [
"minidom",
"parsing",
"python",
"web_services",
"xml"
] | stackoverflow_0005922221_minidom_parsing_python_web_services_xml.txt |
Q:
Is this boolean test pythonic for limiting a list's members to a set of legal values?
I have a list of legal words:
legal = ['osama','bin','laden']
A function accepts a list that must contain words in the legal list & returns true if every member of the list is a legal word.
def is_legal( list ):
return not an... | Is this boolean test pythonic for limiting a list's members to a set of legal values? | I have a list of legal words:
legal = ['osama','bin','laden']
A function accepts a list that must contain words in the legal list & returns true if every member of the list is a legal word.
def is_legal( list ):
return not any( [tok not in legal for tok in list ] )
| [
"It's easier to read if you use all() instead of any():\nlegal = set(['osama','bin','laden'])\n\ndef is_legal(seq):\n return all(tok in legal for tok in seq)\n\n",
"You don't want the square brackets (since they force creation of a list), and you don't want to shadow builtins, but yes.\ndef is_legal(seq):\n ... | [
4,
1,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0005927081_python.txt |
Q:
Referencing/manipulating SQL fields in Python code
I am trying to code a website similar to reddit where people can post stories and then vote on them
So right now, I have some Python code to create a time score (PostDate) and a general rating score (VoteStatus), however I need to know how to reference/manipulate... | Referencing/manipulating SQL fields in Python code | I am trying to code a website similar to reddit where people can post stories and then vote on them
So right now, I have some Python code to create a time score (PostDate) and a general rating score (VoteStatus), however I need to know how to reference/manipulate fields in an SQL table with Python.
Any help?
impor... | [
"For MySQL, see this question: Python MySQL module\nThere is also an sqlite3 module that you can use on a flat sqlite file, like so:\nimport sqlite3\nconn = sqlite3.connect('mydb.db')\nrows = list(conn.execute(\"SELECT * FROM Database ORDER BY VoteStatus\"))\n\n"
] | [
0
] | [] | [] | [
"python",
"sql"
] | stackoverflow_0005928213_python_sql.txt |
Q:
celery memory management
I have a 3 celery nodes running between 6 and 8 workers each and my tasks tend to use a lot of memory. It seems that when the tasks finish, they aren't releasing the memory. Is there a way to either tell the worker process to die and restart after execution completes, or improve celery's g... | celery memory management | I have a 3 celery nodes running between 6 and 8 workers each and my tasks tend to use a lot of memory. It seems that when the tasks finish, they aren't releasing the memory. Is there a way to either tell the worker process to die and restart after execution completes, or improve celery's garbage collection?
| [
"For those workers you could set max-tasks-per-child-setting to one.\n"
] | [
6
] | [] | [] | [
"celery",
"python"
] | stackoverflow_0005928370_celery_python.txt |
Q:
pickle.load Not Working
I got a file that contains a data structure with test results from a Windows user. He created this file using the pickle.dump command. On Ubuntu, I tried to load this test results with the following program:
import pickle
import my_module
f = open('results', 'r')
print pickle.load(f)
f.clo... | pickle.load Not Working | I got a file that contains a data structure with test results from a Windows user. He created this file using the pickle.dump command. On Ubuntu, I tried to load this test results with the following program:
import pickle
import my_module
f = open('results', 'r')
print pickle.load(f)
f.close()
But I get an error insi... | [
"The problem lies in pickle's way of handling newline characters. Some of the line feed characters cripple module names in dumped / loaded data.\nStoring and loading files in binary mode may help, but I was having trouble with them too. After a long time reading docs and searching I found that pickle handles severa... | [
4,
2
] | [] | [] | [
"pickle",
"python"
] | stackoverflow_0005927606_pickle_python.txt |
Q:
formatting a string with multiple float values in python
I am trying to truncate some float values contained in the same string but I'm not quite sure how to proceed.
Currently I am using the Python xml.dom.minidom to write out some xml using Node.toxml(). I have something like:
1.471392 0.740274 0.659904 -0.56... | formatting a string with multiple float values in python | I am trying to truncate some float values contained in the same string but I'm not quite sure how to proceed.
Currently I am using the Python xml.dom.minidom to write out some xml using Node.toxml(). I have something like:
1.471392 0.740274 0.659904 -0.560021 1.312128 -0.697930 1.557193 5.156295 2.279541 -0.760170 -... | [
"Here is an one-liner:\n\" \".join([str(round(float(i),2)) for i in data.split(' ')])\n\nwhere data contains your string of floats. Might not be the most efficient, but it does the job.\n",
">>> '%.2f' % (1.471392,)\n'1.47'\n\n",
"def round_2(f):\n return round(f, 2)\n\n>>> map(round_2, [1.3234254, 2.3352145... | [
1,
1,
0
] | [] | [] | [
"formatting",
"python",
"string",
"xml"
] | stackoverflow_0005928926_formatting_python_string_xml.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.