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:
Equivalent from C# matchObject.Value in Python?
I am trying to parse some C# code to Python. There are several regular expression in that code. Everything worked fine so far, but now I've got the following problem:
C# Code:
Match m = regEx.Match( Expression );
while( m.Success )
{
Expression = Expression.Repla... | Equivalent from C# matchObject.Value in Python? | I am trying to parse some C# code to Python. There are several regular expression in that code. Everything worked fine so far, but now I've got the following problem:
C# Code:
Match m = regEx.Match( Expression );
while( m.Success )
{
Expression = Expression.Replace( m.Value, m.Groups[1].Value + this.Solve( m.Groups... | [
"I think this is what you are trying to do; match.group() (without a parameter) returns the match the whole regex matches:\nm = re.search( pattern, text )\nif m and len( m.group(3) ) > 3:\n text = text.replace( m.group(), m.group(1) + solve( m.group(2) ) )\n\nI’m not sure why you had a loop there, so I removed i... | [
1,
0
] | [] | [] | [
"c#",
"python",
"regex"
] | stackoverflow_0008112611_c#_python_regex.txt |
Q:
what is wrong with this python code - SyntaxError?
I keep getting an error whenever I enter this code (I'm a python noob so I'm probably missing something obvious)
def expadd(num, exp):
while ((num and exp) != (1001)):
return (num ^ exp) + expadd((num + 1), (exp + 1))
return 0
buffer = str(expadd(1... | what is wrong with this python code - SyntaxError? | I keep getting an error whenever I enter this code (I'm a python noob so I'm probably missing something obvious)
def expadd(num, exp):
while ((num and exp) != (1001)):
return (num ^ exp) + expadd((num + 1), (exp + 1))
return 0
buffer = str(expadd(1000, 1000)
total = 0 #error here "syntax error"
for i in... | [
"You are missing a closing parenthesis on the preceding line:\nbuffer = str(expadd(1000, 1000)\n\nYour code is also indented incorrectly (the body of the expadd function should be indented), but due to the location of the error I assume that's only due to copy/pasting it here.\n",
"Besides the syntax error, there... | [
3,
2
] | [] | [] | [
"python"
] | stackoverflow_0008113110_python.txt |
Q:
Try statement - multiple conditions - Python 2
I have little problem with try statement along with multiple conditions. When there is error at 2nd condition, it asks for 1st condition. What I want from it to do is to repeat the same condition, not the whole cycle. I hope you understand me, since my English isn't v... | Try statement - multiple conditions - Python 2 | I have little problem with try statement along with multiple conditions. When there is error at 2nd condition, it asks for 1st condition. What I want from it to do is to repeat the same condition, not the whole cycle. I hope you understand me, since my English isn't very good and also I'm newbie to Python so I also don... | [
"Write a function to query for a single float, and call it twice:\ndef input_float(msg):\n while True:\n try:\n return float(raw_input(msg))\n except ValueError:\n pass\nzacatek = input_float(\"Zacatek: \")\nkonec = input_float(\"Konec: \")\n\n",
"What's happening is that yo... | [
5,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0008113249_python.txt |
Q:
How to read a file with variable multi-row data in Python
I have a file that is about 100Mb that looks like this:
#meta data 1
skadjflaskdjfasljdfalskdjfl
sdkfjhasdlkgjhsdlkjghlaskdj
asdhfk
#meta data 2
jflaksdjflaksjdflkjasdlfjas
ldaksjflkdsajlkdfj
#meta data 3
alsdkjflasdjkfglalaskdjf
This file contains one... | How to read a file with variable multi-row data in Python | I have a file that is about 100Mb that looks like this:
#meta data 1
skadjflaskdjfasljdfalskdjfl
sdkfjhasdlkgjhsdlkjghlaskdj
asdhfk
#meta data 2
jflaksdjflaksjdflkjasdlfjas
ldaksjflkdsajlkdfj
#meta data 3
alsdkjflasdjkfglalaskdjf
This file contains one row of meta data that corresponds to several, variable length ... | [
"itertools.groupby provides an easy way to collect lines into groups:\nimport itertools\n\ndata=[]\nwith open('data.txt','r') as f:\n for key,group in itertools.groupby(f,lambda line: line.startswith('#meta')):\n if key:\n meta=next(group).strip()\n else:\n lines=''.join(group... | [
4,
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0008113359_python.txt |
Q:
select range of date's from a column with time stamp in python
I have a file with many columns along with few columns having 'dates'(say 20,27,53 are columns wth dates).
From a particular column(say 53), i want to select all the dates in a specific month(say may).
The problem is the format of date is "5/01/2011 12... | select range of date's from a column with time stamp in python | I have a file with many columns along with few columns having 'dates'(say 20,27,53 are columns wth dates).
From a particular column(say 53), i want to select all the dates in a specific month(say may).
The problem is the format of date is "5/01/2011 12:53". I mean the date includes time also.
I tried few ways but the p... | [
"It appears that you are trying to call your daterange() function with arguments that look like dates without quotes or anything. This is not how most programming languages work. Try saying something like datetime.strptime(\"5/01/2011 00:00\", \"%m/%d/%Y %H:%M\"), in other words specifying the input format you ex... | [
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0008113447_python.txt |
Q:
Profile GUI application bootstrap
I have some applications which suffer of very slow boot time.
In theory I just want to exit as soon as the gui fires up. Until now I've done it by hand, and it worked, but I wonder if there is a better way...
A solution of course would be to add a "sys.exit" where I want to make i... | Profile GUI application bootstrap | I have some applications which suffer of very slow boot time.
In theory I just want to exit as soon as the gui fires up. Until now I've done it by hand, and it worked, but I wonder if there is a better way...
A solution of course would be to add a "sys.exit" where I want to make it quit, but I should modify the code th... | [
"Alright then, to actually set an \"exit point\" exactly where I want without touching the code is not so trivial.\nIt can be done however, I think, playing around with sys.settrace, as shown here\nhttp://www.doughellmann.com/PyMOTW/sys/tracing.html\nSo the solution for me is to actually modify the code, simply add... | [
0
] | [] | [] | [
"profiling",
"python"
] | stackoverflow_0008092239_profiling_python.txt |
Q:
Python regex to match and remove a specific pattern
I have a file with the following grammar:
<whitespace_sequence><string><whitespace_sequence><--More--><whitespace_sequence><string_sequence><newline>
Using Python (2.4), I would like to remove the sequence:
"<whitespace_sequence><--More--><whitespace_sequence>"... | Python regex to match and remove a specific pattern | I have a file with the following grammar:
<whitespace_sequence><string><whitespace_sequence><--More--><whitespace_sequence><string_sequence><newline>
Using Python (2.4), I would like to remove the sequence:
"<whitespace_sequence><--More--><whitespace_sequence>" from the above grammar.
I am using the following regex... | [
"It looks like the problem with your regex is the double quotes. Without them, it works fine:\n>>> sample = ' string --More-- anotherstring \\n'\n>>> import re\n>>> re.search(r'(\\s+)(--More--)(\\s+)', sample).groups()\n(' ', '--More--', ' ')\n\nFWIW, here is a great resource for developing a rege... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0008112993_python.txt |
Q:
Django: How do I add data to a ModelForm subclass before validation?
As part of a form validation in Django, I want to check when a user last made a post.
I've had a look at this, and this question on stackoverflow, which appear to address this issue, and initially used the accepted answer here. Essentially the p... | Django: How do I add data to a ModelForm subclass before validation? | As part of a form validation in Django, I want to check when a user last made a post.
I've had a look at this, and this question on stackoverflow, which appear to address this issue, and initially used the accepted answer here. Essentially the process at the moment has been to add the request.user object during the
d... | [
"You can override get_form_kwargs method of the CreateView (ArticleCreateView in your case) to pass user to the form.\ndef get_form_kwargs(self):\n kwargs = super(ArticleCreateView, self).get_form_kwargs()\n kwargs['user'] = self.request.user\n return kwargs\n\nOverride your form's init method\n...\ndef __... | [
5,
4,
0
] | [] | [] | [
"django",
"django_forms",
"python"
] | stackoverflow_0008112859_django_django_forms_python.txt |
Q:
wxPython statusbar
How can I make the Statusbar show a specific text without having to hover one of the menubar's items? I want to make a MP3 player I'm building be able to output currently playing file in the statusbar.
A:
Use:
self.statusbar.SetStatusText('text', field_number)
| wxPython statusbar | How can I make the Statusbar show a specific text without having to hover one of the menubar's items? I want to make a MP3 player I'm building be able to output currently playing file in the statusbar.
| [
"Use:\nself.statusbar.SetStatusText('text', field_number)\n\n"
] | [
4
] | [] | [] | [
"python",
"statusbar",
"user_interface",
"wxpython"
] | stackoverflow_0008113448_python_statusbar_user_interface_wxpython.txt |
Q:
Downloading PDF files with Scrapy
I'm scraping pdf files from a site using Scrapy, a Python web-scraping framework.
The site requires to follow the same session in order to allow you to download the pdf.
It works great with Scrapy's because it's all automated but when I run the script after a couple of seconds it... | Downloading PDF files with Scrapy | I'm scraping pdf files from a site using Scrapy, a Python web-scraping framework.
The site requires to follow the same session in order to allow you to download the pdf.
It works great with Scrapy's because it's all automated but when I run the script after a couple of seconds it starts to give me fake pdf files like ... | [
"I think the site tracks your session. If it's a PHP site, pass PHPSESSID cookie to the request which downloads the PDF file.\n"
] | [
0
] | [] | [] | [
"cookies",
"python",
"scrapy",
"session"
] | stackoverflow_0008108477_cookies_python_scrapy_session.txt |
Q:
Loop until a specific user input
I am trying to write a number guessing program as follows:
def oracle():
n = ' '
print 'Start number = 50'
guess = 50 #Sets 50 as a starting number
n = raw_input("\n\nTrue, False or Correct?: ")
while True:
if n == 'True':
guess = guess + int... | Loop until a specific user input | I am trying to write a number guessing program as follows:
def oracle():
n = ' '
print 'Start number = 50'
guess = 50 #Sets 50 as a starting number
n = raw_input("\n\nTrue, False or Correct?: ")
while True:
if n == 'True':
guess = guess + int(guess/5)
print
... | [
"As an alternative to @Mark Byers' approach, you can use while True:\nguess = 50 # this should be outside the loop, I think\nwhile True: # infinite loop\n n = raw_input(\"\\n\\nTrue, False or Correct?: \")\n if n == \"Correct\":\n break # stops the loop\n elif n == \"True\":\n # etc.\... | [
18,
2
] | [] | [] | [
"loops",
"numbers",
"python"
] | stackoverflow_0008114355_loops_numbers_python.txt |
Q:
Parsing malformed string in python
Possible Duplicate:
Decode HTML entities in Python string?
I have a malformed string in Python:
Muhammad Ali's fight with Larry Holmes
where ' is a apostrophe.
Firstly what representation is this: '? Secondly, how can I parse the string in python so that it replace... | Parsing malformed string in python |
Possible Duplicate:
Decode HTML entities in Python string?
I have a malformed string in Python:
Muhammad Ali's fight with Larry Holmes
where ' is a apostrophe.
Firstly what representation is this: '? Secondly, how can I parse the string in python so that it replaces ' with '
| [
"The Python Standard Library's HTMLParser is able to decode HTML entities in strings.\n>>> import HTMLParser\n>>> h = HTMLParser.HTMLParser()\n>>> s = h.unescape('© 2010')\n>>> s\nu'\\xa9 2010'\n>>> print s\n© 2010\n>>> s = h.unescape('© 2010')\n>>> s\nu'\\xa9 2010'\n\nA range of solutions are described h... | [
5,
1
] | [] | [] | [
"python"
] | stackoverflow_0008114373_python.txt |
Q:
Cross platform build script that can call MSBuild or Xbuild depending on environment?
I have a simple .Net console app which has only framework dependencies. It can compile fine with either MSBuild on windows or Mono/XBuild on linux. It is part of a larger project, which has a python build script. Is there any sim... | Cross platform build script that can call MSBuild or Xbuild depending on environment? | I have a simple .Net console app which has only framework dependencies. It can compile fine with either MSBuild on windows or Mono/XBuild on linux. It is part of a larger project, which has a python build script. Is there any simple way to determine the most suitable build engine (msbuild/xbuild) and use that?
In other... | [
"Far easier would be to write a small shell script for Linux or OSX that ran xbuild but was called msbuild. The arguments are the same I think.\n"
] | [
0
] | [] | [] | [
"c#",
"mono",
"msbuild",
"python",
"scripting"
] | stackoverflow_0008114067_c#_mono_msbuild_python_scripting.txt |
Q:
How to pass flags to a distutils extension?
I'm trying to install a Python module that contains C modules. The C code relies on a library being available in the system's global install locations (/usr/include, /usr/lib), but in my case I only have a local installation of this lib available. Therefore, I would like... | How to pass flags to a distutils extension? | I'm trying to install a Python module that contains C modules. The C code relies on a library being available in the system's global install locations (/usr/include, /usr/lib), but in my case I only have a local installation of this lib available. Therefore, I would like to pass parameters (e.g., --incdir, --libdir) wh... | [
"I found out that prepending\nCFLAGS=\"-I<local include dir>\" LDFLAGS=\"-L<local lib dir>\"\n\nto the command line when calling setup.py did the trick.\n"
] | [
15
] | [] | [] | [
"distutils",
"python",
"setuptools"
] | stackoverflow_0008111754_distutils_python_setuptools.txt |
Q:
Django database reconnect
Django's backend (firebird) problem reconnecting to database was fixed as here by disabling request finishing signal. It works on the development server, but when the project was deployed with mod_wsgi connections it again started to reinitialize for each request. How can I fix it? Thanks... | Django database reconnect | Django's backend (firebird) problem reconnecting to database was fixed as here by disabling request finishing signal. It works on the development server, but when the project was deployed with mod_wsgi connections it again started to reinitialize for each request. How can I fix it? Thanks.
p.s my connection is very exp... | [
"Are you sure that the connections aren't being created from distinct processes. Depending on how you run mod_wsgi then multiple processes could be involved in accepting and handling requests. See:\nhttp://code.google.com/p/modwsgi/wiki/ProcessesAndThreading\nMake sure you are using mod_wsgi daemon mode with defaul... | [
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0003421731_django_python.txt |
Q:
How can I make python 2.6 my default in Mac OS X Lion?
I just upgraded to lion and with it came Python 2.7. I need to use 2.6 as my default python as the project I primarily work on uses 2.6.
A:
Apple has provided two very simple ways to change the default python on OS X 10.6 Snow Leopard and 10.7 Lion. It's a... | How can I make python 2.6 my default in Mac OS X Lion? | I just upgraded to lion and with it came Python 2.7. I need to use 2.6 as my default python as the project I primarily work on uses 2.6.
| [
"Apple has provided two very simple ways to change the default python on OS X 10.6 Snow Leopard and 10.7 Lion. It's all detailed in the Apple man page for python(1):\n$ man python\n$ which python\n/usr/bin/python\n$ python -V\nPython 2.7.1\n#\n# temporarily change version\n#\n$ export VERSIONER_PYTHON_VERSION=2.6\... | [
72,
4,
1
] | [] | [] | [
"macos",
"osx_lion",
"python"
] | stackoverflow_0006998545_macos_osx_lion_python.txt |
Q:
Python ISO-8859-1 encoding
I'm facing a huge encoding problem in Python when dealing with ISO-8859-1 / Latin-1 character set.
When using os.listdir to get the contents of a folder I'm getting the strings encoded in ISO-8859-1 (ex: ''Ol\xe1 Mundo''), however in the Python interpreter the same string is encoded to a... | Python ISO-8859-1 encoding | I'm facing a huge encoding problem in Python when dealing with ISO-8859-1 / Latin-1 character set.
When using os.listdir to get the contents of a folder I'm getting the strings encoded in ISO-8859-1 (ex: ''Ol\xe1 Mundo''), however in the Python interpreter the same string is encoded to a different charset:
In : 'Olá Mu... | [
"When you enter a non-unicode string literal in a python2 interactive session, the system default encoding will be assumed for it.\nIt appears that you are using windows, and that the default encoding is therefore probably \"cp850\" or \"cp437\":\nC:\\>python\nPython 2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.15... | [
3
] | [] | [] | [
"encoding",
"iso_8859_1",
"python",
"unicode"
] | stackoverflow_0008110496_encoding_iso_8859_1_python_unicode.txt |
Q:
Bi-dimensional arrays in Python
I have a vector with int values like:
v=[10,8,6]
and what I want is to create an m*m matrix that stores the distance between these elements, i.e. take each element of the vector and substract it from all the other ones, so at the end I will end up with:
m[3][3]=10-10 10-8 10-6... | Bi-dimensional arrays in Python | I have a vector with int values like:
v=[10,8,6]
and what I want is to create an m*m matrix that stores the distance between these elements, i.e. take each element of the vector and substract it from all the other ones, so at the end I will end up with:
m[3][3]=10-10 10-8 10-6
8-10 8-8 8-6
... | [
"v= [10,8,6] \nm = [[abs(y-x) for y in v] for x in v]\n\nEDIT:\nFor pretty printing you can use something like:\nfor i in m:\n print '%s '*len(i) % tuple(i)\n\n",
"You need to make a list for each row inside of the enveloping list. I used a double list comprehension to make m and then made the formatting a little... | [
4,
1,
1,
0
] | [] | [] | [
"arrays",
"python"
] | stackoverflow_0008114425_arrays_python.txt |
Q:
Python memcached set_multi storing issue
I have discovered an issue when trying to store a lot of keys using python-memcached.
Here is what I'm doing:
import memcache
# This dict has a 2270 entries that is generated on production server
v = eval(open("/home/dragoon/output").read())
a = memcache.Client(['unix:/tmp... | Python memcached set_multi storing issue | I have discovered an issue when trying to store a lot of keys using python-memcached.
Here is what I'm doing:
import memcache
# This dict has a 2270 entries that is generated on production server
v = eval(open("/home/dragoon/output").read())
a = memcache.Client(['unix:/tmp/memcached.sock'], debug=1)
Next I'm trying t... | [
"Try using pylibmc as your memcache driver, rather than using python-memcache\nI've seen this issue on Memcache 1.4.7 on Ubuntu 11 as well.\n",
"Ok. It seems that there is some bug in memcached 1.4.2 that is the last version in Ubuntu 10.04 LTS.\nMemcached 1.4.5 works fine.\n"
] | [
1,
0
] | [] | [] | [
"memcached",
"python",
"python_memcached"
] | stackoverflow_0007980844_memcached_python_python_memcached.txt |
Q:
How to make an exe file out of Python Scrapy script?
I have a Scrapy script, and it's working fine. To distribute it to my friends, I need it to be executable because they don't know much about Scrapy. Would someone tell me how to turn a Scrapy script into an exe file?
Is py2exe applicable in this regard?
A:
Yes... | How to make an exe file out of Python Scrapy script? | I have a Scrapy script, and it's working fine. To distribute it to my friends, I need it to be executable because they don't know much about Scrapy. Would someone tell me how to turn a Scrapy script into an exe file?
Is py2exe applicable in this regard?
| [
"Yes, use py2exe\nAsk questions about any specific problems you have.\n"
] | [
1
] | [] | [] | [
"exe",
"python",
"scrapy"
] | stackoverflow_0008114839_exe_python_scrapy.txt |
Q:
Algorithm implementation in python
I have certain algorithm need to implement. Basically the rules are:
The first whitespace-separated token on a line will be the word being defined.
The later tokens will be the definition. If the definition is “.”, that word is a primitive, i.e., a word with no definition.
The... | Algorithm implementation in python | I have certain algorithm need to implement. Basically the rules are:
The first whitespace-separated token on a line will be the word being defined.
The later tokens will be the definition. If the definition is “.”, that word is a primitive, i.e., a word with no definition.
The output is a single comma-separated line... | [
"def read_graph(lines):\n g = {}\n for line in lines:\n words = line.split()\n if words[1] == '.':\n words = words[:1]\n g[words[0]] = words[1:]\n return g\n\ndef dump_graph(g):\n out = []\n def dump(key):\n for k in g[key]:\n dump(k)\n if key ... | [
0
] | [] | [] | [
"graph_algorithm",
"python"
] | stackoverflow_0008114675_graph_algorithm_python.txt |
Q:
Writing a file with properties from the datastore
I want a comma-separated list of all the email addresses my application stores. It's too large for a regular request and writing it to the blobstore is also a too large request:
class CSVHandler(webapp2.RequestHandler):
def get(self):
entities = Entity.... | Writing a file with properties from the datastore | I want a comma-separated list of all the email addresses my application stores. It's too large for a regular request and writing it to the blobstore is also a too large request:
class CSVHandler(webapp2.RequestHandler):
def get(self):
entities = Entity.all().fetch(10000)
s = ''
for entity in... | [
"You should probably use the built-in bulkloader tool, which can download all objects via the remote API and save selected fields into CSV format. \n",
"Instead of trying to save the entire file in a single write operation, write it to the blobstore in chunks. Using the csv module will make this easier, allowing ... | [
1,
1
] | [] | [] | [
"csv",
"google_app_engine",
"google_cloud_datastore",
"python"
] | stackoverflow_0008114499_csv_google_app_engine_google_cloud_datastore_python.txt |
Q:
How do I set up SQLite with a Django project?
I have read the Django documentation (For reference, https://docs.djangoproject.com/en/1.3/intro/tutorial01/), but I'm still having issues setting up a Django project to work with a database. Because I'm new to web development, I figured I would start with SQLite for d... | How do I set up SQLite with a Django project? | I have read the Django documentation (For reference, https://docs.djangoproject.com/en/1.3/intro/tutorial01/), but I'm still having issues setting up a Django project to work with a database. Because I'm new to web development, I figured I would start with SQLite for development since I'm not putting anything into prod... | [
"Do a 'sudo apt-get install libsqlite3-dev' and then recompile Python 2.7.\nIn the long term, to reduce ambiguity of co-existing Python installations and packages, I highly recommend installing pip, virtualenv, and virtualenvwrapper.\n"
] | [
4
] | [] | [] | [
"django",
"python",
"sqlite"
] | stackoverflow_0008114946_django_python_sqlite.txt |
Q:
wxpython tree ctrl images
Ok I have an example here:
Runable Example
Example
Extract the zip files and then run otherwise it won't work at all
However when run the images won't be added to there tree ctrl and it will simply error.
Code (Note won't run without images, see zip file above)
import wx
class TestFrame(... | wxpython tree ctrl images | Ok I have an example here:
Runable Example
Example
Extract the zip files and then run otherwise it won't work at all
However when run the images won't be added to there tree ctrl and it will simply error.
Code (Note won't run without images, see zip file above)
import wx
class TestFrame(wx.Frame):
def __init__(se... | [
"There are 2 problems with you code.\n\nNot all of your images are 16px x 16px, but you are trying to add them to image list that should contain only 16 x 16 images. To solve this you should scale them to 16 x 16 before adding to a list.\nYou should assign image list to tree object before applying images to tree it... | [
2
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0008114005_python_wxpython.txt |
Q:
Python two lists finding index value
listEx = ['cat *(select: "Brown")*', 'dog', 'turtle', 'apple']
listEx2 = ['hampter',' bird', 'monkey', 'banana', 'cat']
for j in listEx2:
for i in listEx:
if j in i:
print listEx.index(j)
What I am trying to accomplish is search the items in listEx2 in... | Python two lists finding index value | listEx = ['cat *(select: "Brown")*', 'dog', 'turtle', 'apple']
listEx2 = ['hampter',' bird', 'monkey', 'banana', 'cat']
for j in listEx2:
for i in listEx:
if j in i:
print listEx.index(j)
What I am trying to accomplish is search the items in listEx2 in listEx. If the item from listEx2 is foun... | [
"Just use enumerate: \nlistEx = ['cat *(select: \"Brown\")*', 'dog', 'turtle', 'apple']\nlistEx2 = ['hampter',' bird', 'monkey', 'banana', 'cat']\n\nfor j in listEx2:\n for pos, i in enumerate(listEx):\n if j in i:\n print j, \"found in\", i, \"at position\", pos, \"of listEx\"\n\nThis will pri... | [
4,
3
] | [] | [] | [
"python"
] | stackoverflow_0008115015_python.txt |
Q:
Embed a stateful Python script into C++ program using boost::python
I have a C++ program that keeps generating data. I have a python class that process these data. I want to use this python class to process the data: when each time a data point is generated, I can use this python script to process the data. But th... | Embed a stateful Python script into C++ program using boost::python | I have a C++ program that keeps generating data. I have a python class that process these data. I want to use this python class to process the data: when each time a data point is generated, I can use this python script to process the data. But this python script must be "stateful", i.e. it should be able to remember w... | [
"For basic information about how to execute your python script:\nhttp://www.boost.org/doc/libs/1_47_0/libs/python/doc/tutorial/doc/html/python/embedding.html\nFor details on manipulating python objects in C++\nhttp://www.boost.org/doc/libs/1_47_0/libs/python/doc/tutorial/doc/html/python/object.html\nMuch of boost-p... | [
0
] | [] | [] | [
"boost",
"boost_python",
"c++",
"python"
] | stackoverflow_0008003916_boost_boost_python_c++_python.txt |
Q:
open source python projects
I'm very interested in studying (and maybe contributing to) a open source python project.
I have found Zope to be an interesting possibility. The only thing which draws me away from it is that I have absolutely no interest in web development.
When looking for a project for this purpo... | open source python projects | I'm very interested in studying (and maybe contributing to) a open source python project.
I have found Zope to be an interesting possibility. The only thing which draws me away from it is that I have absolutely no interest in web development.
When looking for a project for this purpose, I come across many; however, ... | [
"You could go to the Python Wall of Shame, find a project that needs porting to Python3... That would be an interesting way to familiarize yourself with a code base, Python3, and we will all love you for it!\n",
"I think that IPython would be a great place to start.\n",
"You can check Twisted. It's a huge proje... | [
3,
0,
0
] | [] | [] | [
"command_line",
"command_line_interface",
"open_source",
"python"
] | stackoverflow_0008115087_command_line_command_line_interface_open_source_python.txt |
Q:
Can I access a function internal dictionary externally in python
Say I have the following script:
file.py:
class A():
def a(self):
var={'a':1,'b':2...}
Can I access var externally (something like: import file; file.A.a.var['a'])?
Thanks!
A:
No, you can't access it. That dictionary is only created when the... | Can I access a function internal dictionary externally in python | Say I have the following script:
file.py:
class A():
def a(self):
var={'a':1,'b':2...}
Can I access var externally (something like: import file; file.A.a.var['a'])?
Thanks!
| [
"No, you can't access it. That dictionary is only created when the method is called.\nIf you can modify the source code you can:\n\nmove the construction of the dictionary to the class constructor or to the module level\nor return a reference to the dictionary from the method\n\n",
"you can't access a variable be... | [
3,
0
] | [] | [] | [
"python"
] | stackoverflow_0008115283_python.txt |
Q:
I need help understanding why the return value is different from what I expected. I am using the cmd module
I have two files that I am trying to work with. menu.py has the menus that program.py imports.
menu.py:
import cmd,sys
user = 'no one'
class loginMenu(cmd.Cmd):
def postloop(self):
user = 'lil... | I need help understanding why the return value is different from what I expected. I am using the cmd module | I have two files that I am trying to work with. menu.py has the menus that program.py imports.
menu.py:
import cmd,sys
user = 'no one'
class loginMenu(cmd.Cmd):
def postloop(self):
user = 'lilith'
return user
intro="""login menu"""
def do_smtoggle(self,person):
return True
de... | [
"That's because the assignment to user here:\ndef postloop(self):\n user = 'lilith'\n return user\n\nis acting on a local instance of the var. To affect the global var user, you would need to add a:\nglobal user\n\nto the top of that function. Though I wouldn't recommend it, as there are usually better ways... | [
2,
2
] | [] | [] | [
"cmd",
"python"
] | stackoverflow_0008115461_cmd_python.txt |
Q:
Python script pops up console when run by scheduler
Possible Duplicate:
Run python script without DOS shell appearing
I have a python script that Windows Scheduler runs every 5 minutes for me. The script works fine but every time it runs it's loading up the console really quick on my desktop before it automatic... | Python script pops up console when run by scheduler |
Possible Duplicate:
Run python script without DOS shell appearing
I have a python script that Windows Scheduler runs every 5 minutes for me. The script works fine but every time it runs it's loading up the console really quick on my desktop before it automatically closes. Does anyone know how to remove this behavi... | [
"Run it through pythonw instead of python (pyw if you're using the new launcher).\n"
] | [
9
] | [] | [] | [
"python",
"windows",
"windows_console",
"windows_task_scheduler"
] | stackoverflow_0008115492_python_windows_windows_console_windows_task_scheduler.txt |
Q:
Overusing sitecustomize.py: .bash_profile instead?
Maybe it's because I am more comfortable with python over the shell, but I chose to add to my sys.path list in /usr/lib/python[x.x]/sitecustomize.py in this manner:
base = '/home/droogans/py/'
locs = ['foo','django']
for loc in locs:
sys.path.insert(0, base ... | Overusing sitecustomize.py: .bash_profile instead? | Maybe it's because I am more comfortable with python over the shell, but I chose to add to my sys.path list in /usr/lib/python[x.x]/sitecustomize.py in this manner:
base = '/home/droogans/py/'
locs = ['foo','django']
for loc in locs:
sys.path.insert(0, base + loc)
And now I've added a try:except block below it, ... | [
"Sometimes you are not going to have superuser status on the machine you are using. In such cases you won't be able to modify /usr, so it would be necessary then to know how to set environment variables in your personal ~/.bashrc or ~/.profile or ~/.bash_profile. (The particular file to use depends on your system).... | [
1
] | [] | [] | [
"bash",
"django",
"python",
"shell"
] | stackoverflow_0008115399_bash_django_python_shell.txt |
Q:
Smoothing Data in Contour Plot with Matplotlib
I am working on creating a contour plot using Matplotlib. I have all of the data
in an array that is multidimensional. It is 12 long about 2000 wide. So it is
basically a list of 12 lists that are 2000 in length. I have the contour plot
working fine, but I need to smo... | Smoothing Data in Contour Plot with Matplotlib | I am working on creating a contour plot using Matplotlib. I have all of the data
in an array that is multidimensional. It is 12 long about 2000 wide. So it is
basically a list of 12 lists that are 2000 in length. I have the contour plot
working fine, but I need to smooth the data. I have read a lot of
examples. Unfortu... | [
"You could smooth your data with a gaussian_filter:\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport scipy.ndimage as ndimage\n\nX, Y = np.mgrid[-70:70, -70:70]\nZ = np.cos((X**2+Y**2)/200.)+ np.random.normal(size=X.shape)\n\n# Increase the value of sigma to increase the amount of blurring.\n# order=0 m... | [
12,
9
] | [] | [] | [
"contour",
"matplotlib",
"python",
"scipy",
"smoothing"
] | stackoverflow_0008055489_contour_matplotlib_python_scipy_smoothing.txt |
Q:
How to construct dynamic function invocation with variable arguments in Python
I'm attempting to wrap a call to an operation with a variable argument list into a generalized function with fixed arguments like this:
def vectorizeIt(args, op)
op is a function with a variable number of arguments and args is a list w... | How to construct dynamic function invocation with variable arguments in Python | I'm attempting to wrap a call to an operation with a variable argument list into a generalized function with fixed arguments like this:
def vectorizeIt(args, op)
op is a function with a variable number of arguments and args is a list with the arguments I'd like to pass to it. For example if len(args) == 3 then I'd li... | [
"Use the \"splat\" operator * to apply an arbitrary number of arguments to op:\ndef vectorizeIt(args, op):\n op(*args)\n\n\nReference:\n\nSalty Crane: How to use *args and **kwargs (also linked aboved)\nUnpacking argument lists (official docs)\n\n"
] | [
4
] | [] | [] | [
"argument_passing",
"python",
"variadic_functions"
] | stackoverflow_0008115528_argument_passing_python_variadic_functions.txt |
Q:
Yaml addressing and template with GAE is not working ? TemplateDoesNotExist just by simple change in yaml ?
I have problem with using template in Google App Engine by Python.
the thing is, when I address my static folder in Yaml, I can NOT access to my template and when I remove it, it is access able. look at the ... | Yaml addressing and template with GAE is not working ? TemplateDoesNotExist just by simple change in yaml ? | I have problem with using template in Google App Engine by Python.
the thing is, when I address my static folder in Yaml, I can NOT access to my template and when I remove it, it is access able. look at the files.
this is my file structure
-src\
----\calc.py
----\main.py
----\index.html
----templ\
---------\calc.html
-... | [
"Files designated as static in app.yaml are not available to application code in the python runtime. They are only served directly the the user's browser in response to requests matching the regular expression in app.yaml.\nDo not mark templates as static. Only files that should be served as-is to the user, such as... | [
3,
1
] | [] | [] | [
"django_templates",
"google_app_engine",
"python",
"templates",
"yaml"
] | stackoverflow_0008112722_django_templates_google_app_engine_python_templates_yaml.txt |
Q:
Populate object from request in GAE
I know that I can use django forms, but I'm looking for a native( gae api ) way to populate an object with request'data.
Something like that:
from google.appengine.ext import db
class MyModel(db.Model)
prop1 = db.StringProperty()
prop2 = db.StringProperty()
and in requ... | Populate object from request in GAE | I know that I can use django forms, but I'm looking for a native( gae api ) way to populate an object with request'data.
Something like that:
from google.appengine.ext import db
class MyModel(db.Model)
prop1 = db.StringProperty()
prop2 = db.StringProperty()
and in request handler
class Page(webapp.RequestHand... | [
"You could try this way that works for me:\nmymodel = MyModel(prop1=self.request.get('prop1'))\n\nif a have a form with a field like the following\n<input type=\"text\" name=\"prop1\" />\n\nI hope it works for you. \n",
"What you're generally looking for is a forms library with datastore integration. We used to ... | [
0,
0
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0008112459_google_app_engine_python.txt |
Q:
different types of line terminations(unix, windows, etc)
I'm note sure about conventions for different types of line termination in different programming languages. I know that there are 2 types, 1: line feed, 2: carriage-return, line feed. My question is: how does readline in different programming languages, like... | different types of line terminations(unix, windows, etc) | I'm note sure about conventions for different types of line termination in different programming languages. I know that there are 2 types, 1: line feed, 2: carriage-return, line feed. My question is: how does readline in different programming languages, like python: a = fd.readline();, c/c++: file.getline (buffer,100);... | [
"You mostly don't need to worry about it. If you come to a point when something doesn't work, come back and ask about that.\nNote however that what determines the line-ending convention is not which programming language you use, but the platform it runs on (*nix/Windows/Mac, all are different).\n"
] | [
1
] | [] | [] | [
"linefeed",
"python",
"termination"
] | stackoverflow_0008113895_linefeed_python_termination.txt |
Q:
GAE datastore fetch taking too long?
I have a query which looks like this:
userBase = UserEntry.all().filter('debug =', False).filter('disabled =', False).filter('first_message =', False).fetch(200)
And an index (built and serving)
- kind: UserEntry
properties:
- name: first_message
- name: disabled
... | GAE datastore fetch taking too long? | I have a query which looks like this:
userBase = UserEntry.all().filter('debug =', False).filter('disabled =', False).filter('first_message =', False).fetch(200)
And an index (built and serving)
- kind: UserEntry
properties:
- name: first_message
- name: disabled
- name: debug
There are around 1000 en... | [
"Your custom index appears to be in the wrong order; the query is most likely being done by a zigzag merge-join rather than using your custom index. Try filtering the properties in the same order they're in index.yaml.\n"
] | [
1
] | [
"The fetch number is too big, try fetch(200) and see how long it taken.\n"
] | [
-1
] | [
"google_app_engine",
"python"
] | stackoverflow_0008111028_google_app_engine_python.txt |
Q:
python find index of of item in list
Possible Duplicate:
Python two lists finding index value
listEx = ['cat *(Select: "Standard")*', 'dog', 'cow', 'turtle *(Select: "Standard")*', 'onion', 'carrot *(select: "Standard")*']
listEx2 = ['house', 'farm', 'cottage', 'cat', 'turtle', 'computer', 'carrot']
for i in li... | python find index of of item in list |
Possible Duplicate:
Python two lists finding index value
listEx = ['cat *(Select: "Standard")*', 'dog', 'cow', 'turtle *(Select: "Standard")*', 'onion', 'carrot *(select: "Standard")*']
listEx2 = ['house', 'farm', 'cottage', 'cat', 'turtle', 'computer', 'carrot']
for i in listEx2:
for j in ListEx:
if i ... | [
"I might need some further clarification on this!\nI think you're mixing things up a bit here.\nWhen you do for i in listEx2:, in each iteration, i is the value of the position in the list, NOT the index!\nIf you just need the index where elements occur, then why not something like:\nfor i in listEx2:\n if i in ... | [
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0008115909_python.txt |
Q:
Searching for strings and locating the line numbers that strings are located in [PYTHON]
How can I search for strings and locate the line numbers that strings are located in?
For example
>>> findlinenb('example.txt', ['desktop', 'connection', 'processor'])
desktop in 23
connection in 35, 38, 35
processor in 4, 5, ... | Searching for strings and locating the line numbers that strings are located in [PYTHON] | How can I search for strings and locate the line numbers that strings are located in?
For example
>>> findlinenb('example.txt', ['desktop', 'connection', 'processor'])
desktop in 23
connection in 35, 38, 35
processor in 4, 5, 6, 8
My code:
def findlinenb (filename, list):
file = open(filename, "r")
content = file.read... | [
"words = ['desktop', 'connection', 'processor']\noccurrences = dict((w, []) for w in words)\nwith open(\"example.txt\") as f:\n for i, line in enumerate(f, 1):\n for w in words:\n if w in line:\n occurrences[w].append(i)\nprint occurrences.items()\n\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0008115983_python.txt |
Q:
need to extract multiple line text from big chunk of text in python language
In python I have big text in multline.
I need to get the text between {{book and }}
I tired using regular expression
problem is text inside is in mutiline string
I tried {{book (.+) it gives me text only in first line
the I tried {{book... | need to extract multiple line text from big chunk of text in python language | In python I have big text in multline.
I need to get the text between {{book and }}
I tired using regular expression
problem is text inside is in mutiline string
I tried {{book (.+) it gives me text only in first line
the I tried {{book (.+) }} this gives error
re.search("{{book .*?}", pagetext).group()
I have tried... | [
"You need to use the re.DOTALL flag to allow . to capture newline characters. Also, you should escape the braces because they are special characters in Python regex syntax.\nre.search(r\"\\{\\{book .*?\\}\\}\", pagetext, re.DOTALL)\n\n",
"If there could be nested {{expr}} then regular expressions are not enough e... | [
1,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0008111703_python_regex.txt |
Q:
Working with a list, performing arithmetic logic in Python
Suppose I have made a large list of numbers, and I want to make another one which I will add, pairwise, with the first list.
Here's the first list, A:
[109, 77, 57, 34, 94, 68, 96, 72, 39, 67, 49, 71, 121, 89, 61, 84, 45, 40, 104, 68, 54, 60, 68, 62, 91, 4... | Working with a list, performing arithmetic logic in Python | Suppose I have made a large list of numbers, and I want to make another one which I will add, pairwise, with the first list.
Here's the first list, A:
[109, 77, 57, 34, 94, 68, 96, 72, 39, 67, 49, 71, 121, 89, 61, 84, 45, 40, 104, 68, 54, 60, 68, 62, 91, 45, 41, 118, 44, 35, 53, 86, 41, 63, 111, 112, 54, 34, 52, 72, 11... | [
"result = [(x + y) for x, y in itertools.izip(A, B)]\n\nOr:\nresult = map(operator.add, itertools.izip(A, B))\n\n",
"Here is two possible options:\n\nUse list comprehension.\nUse NumPy.\n\nI will be using shortened versions of your lists for convenience, and the element-wise sum will go into c.\nList comprehensio... | [
5,
2,
0
] | [] | [] | [
"list",
"python"
] | stackoverflow_0008116329_list_python.txt |
Q:
Getting the line above a search value in python
I have a text file that I want to search for a specific ip address, and the way the text file is set up is that the host name is above the ip add. ie
real HOSTNAME
address xx.xx.xx.xx
What is the best/simplest way to go about getting the hostname when I only got th... | Getting the line above a search value in python | I have a text file that I want to search for a specific ip address, and the way the text file is set up is that the host name is above the ip add. ie
real HOSTNAME
address xx.xx.xx.xx
What is the best/simplest way to go about getting the hostname when I only got the ip address to search on? Regular expressions? Is t... | [
"A regex is likely this simplest solution.\n>>> textdata = '''\nsomeline\nanother line\nreal HOSTNAME\n\naddress 127.0.0.1\npost 1\npost 2\n'''\n>>> re.findall('^(.*)$\\n^.*$\\naddress 127.0.0.1', textdata, re.MULTILINE)\n['real HOSTNAME']\n\nYou could also use the linecache module or simply read all the lines into... | [
3,
2,
2
] | [] | [] | [
"multiline",
"python",
"regex",
"sed"
] | stackoverflow_0008116395_multiline_python_regex_sed.txt |
Q:
access excel programmatically, run a ODBC query, save data, do vlookups
I am looking for a way to automate an entire process that uses Excel & ODBC queries. I know that Excel can use to a ODBC driver to run queries against a Mysql database. But I need this query to be triggered programmatically.
The individual ste... | access excel programmatically, run a ODBC query, save data, do vlookups | I am looking for a way to automate an entire process that uses Excel & ODBC queries. I know that Excel can use to a ODBC driver to run queries against a Mysql database. But I need this query to be triggered programmatically.
The individual steps the program or script should be able to do are:
1. Open Excel file
2. Run ... | [
"What you want to do is probably possible using COM (Python tutorial). It will be messy, hard to code and hard to debug. And no way it'll work on a mac.\nInstead, if I was you I would try and take the problem out of excel. For instance in Python, I would first directly access mysql. I would then parse my second... | [
1
] | [] | [] | [
"excel",
"odbc",
"php",
"python",
"vlookup"
] | stackoverflow_0008116614_excel_odbc_php_python_vlookup.txt |
Q:
correct class inheritance
I've written some code that allows the term 'job' to be used universally to perform a unique task. The specific jobs can be chosen through setting an initial variable "job_type". From that initial variable a particulay subclass is chosen to perform the appropriate job. Maybe the code will... | correct class inheritance | I've written some code that allows the term 'job' to be used universally to perform a unique task. The specific jobs can be chosen through setting an initial variable "job_type". From that initial variable a particulay subclass is chosen to perform the appropriate job. Maybe the code will make more sense :)
if __name__... | [
"I suspect that what you really want is to use the Factory Method Pattern here.\nYou could change your code to something like this:\nif __name__=='__main__':\n # these variables would normally be called in from a config file\n job_type = 'job1'\n uni_var = 10\n\n job_select = superClass.optionFactory(jo... | [
1,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0008116537_python.txt |
Q:
GAE: KindError when getting entities via ListProperty
I have a Contest entity which uses a ListProperty to store keys of Candidate entities. Here are some details:
class Contest(db.Model):
candidates = db.ListProperty(db.Key)
def create_candidate_objects(self):
put_list = []
for n, name i... | GAE: KindError when getting entities via ListProperty | I have a Contest entity which uses a ListProperty to store keys of Candidate entities. Here are some details:
class Contest(db.Model):
candidates = db.ListProperty(db.Key)
def create_candidate_objects(self):
put_list = []
for n, name in enumerate(self.tmp_candidates):
put_list.appe... | [
"Most likely you're defining Candidate in another module you haven't imported. Where is Candidate defined? Have you imported the module it's in when you call db.get? Calling Candidate.get(key_list) should work, since it forces you to have a valid Candidate when you call it.\n"
] | [
1
] | [
"Try this:\nc = db.get([str(i) for i in contest.candidates])\n\n"
] | [
-1
] | [
"google_app_engine",
"python"
] | stackoverflow_0008108130_google_app_engine_python.txt |
Q:
How do I get the value of a textarea?
This is a follow up to my other question. I am asking again because this seems more a javascript question than a Google App Engine question.
I have a form
<form name="choice_form" id="choice_form" method="post" action="/g/choicehandler" onsubmit="writeToStorage()">
<textarea... | How do I get the value of a textarea? | This is a follow up to my other question. I am asking again because this seems more a javascript question than a Google App Engine question.
I have a form
<form name="choice_form" id="choice_form" method="post" action="/g/choicehandler" onsubmit="writeToStorage()">
<textarea name="choice" rows="7" cols="50"></textare... | [
"choice_form is the <form>, not the <textarea>.\nYou need to give the <textarea> an ID and use that ID instead.\n",
"You can access the form formally using:\ndocument.forms['choice_form']\n\nor also:\ndocument.forms.choice_form\n\nEach form has an elements collection that is all the form controls. You can access ... | [
4,
3,
2,
1
] | [] | [] | [
"html",
"javascript",
"python",
"xmlhttprequest"
] | stackoverflow_0008116545_html_javascript_python_xmlhttprequest.txt |
Q:
Can python source code executed using PyRun_SimpleString be extracted?
I am developing a software based on embedded Python and C++. I want to secure some of my python code and prevent people from copying it.
For now I am using PyRun_SimpleString to execute the python code and the string is generated using my C++ ... | Can python source code executed using PyRun_SimpleString be extracted? | I am developing a software based on embedded Python and C++. I want to secure some of my python code and prevent people from copying it.
For now I am using PyRun_SimpleString to execute the python code and the string is generated using my C++ code.
If I use this method, will it secure the Python code from being copie... | [
"So, as I understand it the actual program will not exist in the executable, either in python source form, nor in 'marshalled' form (basically .pyc image) or compiled form, though I guess it will exist in some encrypted or obfuscated form which is converted into python source at run time.\nThis definitely makes it ... | [
0
] | [] | [] | [
"embed",
"python",
"security"
] | stackoverflow_0008116901_embed_python_security.txt |
Q:
Having trouble removing punctuation and upper case letters? (Beginner)
Awful programmer here. For a class assignment I have to take words from a text document, count them, and order them. I am having trouble erasing the punctuation and replacing the upper case letters with lower ones. Any guidance would be greatly... | Having trouble removing punctuation and upper case letters? (Beginner) | Awful programmer here. For a class assignment I have to take words from a text document, count them, and order them. I am having trouble erasing the punctuation and replacing the upper case letters with lower ones. Any guidance would be greatly appreciated.
docwords={}
doc=raw_input("Please enter the name of a text fil... | [
"To start, your main is not doing what you want. Notice what the for loops do: first, you read each line, one at a time, and assign a list of the words in each line to words. But you've just been overwriting words over and over again, so now words is the list of words in the last line. Now, you put those words i... | [
2,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0008116882_python.txt |
Q:
KeyErrors and how to raise a KeyError
For my homework assignment, I am told to raise a key error if the key(text) the user enters contains any non alphabetic characters and reprompt. So far I have this which seems to work but obviously doesn't use the expected try/except structure
key=input("Please enter the key w... | KeyErrors and how to raise a KeyError | For my homework assignment, I am told to raise a key error if the key(text) the user enters contains any non alphabetic characters and reprompt. So far I have this which seems to work but obviously doesn't use the expected try/except structure
key=input("Please enter the key word you want to use: ")
ok=key.isalpha()
wh... | [
"This is not appropriate usage of KeyError (it's supposed to be used for dict lookups, or similar situations), but if it is what you have been asked to do then try something like this :\ndef prompt_thing():\n s = raw_input(\"Please enter the key word you want to use: \")\n if s == '' or not s.isalnum():\n ... | [
19
] | [] | [] | [
"exception",
"python"
] | stackoverflow_0008117007_exception_python.txt |
Q:
Run python subprocess for x seconds every y seconds
I'd like to control a bash program from within Python. I'd like to run an external command every x seconds for y seconds, and then kill it after y seconds. I'm having a bit of trouble with threads and sleep and wait and etc. and am wondering if someone can post a... | Run python subprocess for x seconds every y seconds | I'd like to control a bash program from within Python. I'd like to run an external command every x seconds for y seconds, and then kill it after y seconds. I'm having a bit of trouble with threads and sleep and wait and etc. and am wondering if someone can post a simple example.
For example, from the CLI the usage migh... | [
"does this help?\nimport threading\nimport subprocess\nimport time\n\nclass IntervalRunner(threading.Thread):\n def __init__(self, seconds):\n self.seconds = seconds\n threading.Thread.__init__(self)\n\n def run(self):\n while True:\n p = subprocess.Popen('ls -la'.split(), shel... | [
6,
0
] | [] | [] | [
"python",
"sleep",
"subprocess",
"wait"
] | stackoverflow_0006970574_python_sleep_subprocess_wait.txt |
Q:
How to print text in color without the termcolor module in python
I would just like to know how could I print color text without the termcolor module.
I don't want the termcolor because if someone use my script and he don't have the termcolor module installed, it won't work! :(
I read somewhere that I could just u... | How to print text in color without the termcolor module in python | I would just like to know how could I print color text without the termcolor module.
I don't want the termcolor because if someone use my script and he don't have the termcolor module installed, it won't work! :(
I read somewhere that I could just use the code here: http://www.tux-planet.fr/les-codes-de-couleurs-en-bas... | [
"You need to print the escape sequences. For example, to print 'foo' in red, try out this one:\nprint '\\x1b[31mfoo\\x1b[0m'\nTo discover the escape sequences, you can use termcolor.colored function. \nBut, the \"normal\" way is to simply have a dependency on termcolor.. you can give them the module at the same t... | [
2
] | [] | [] | [
"python"
] | stackoverflow_0008117037_python.txt |
Q:
Validate Name Surname using regex in Python/Django
I'm wondering how I could validate a full email address with first name (optionally a last name or several last names as well) and an email address.
E.g. John Doe <john@doe.org> or Jane <jane@doe.org> should both validate correctly, where as missing name would no... | Validate Name Surname using regex in Python/Django | I'm wondering how I could validate a full email address with first name (optionally a last name or several last names as well) and an email address.
E.g. John Doe <john@doe.org> or Jane <jane@doe.org> should both validate correctly, where as missing name would not, e.g. <jane@doe.org>.
I'm using Django so a Python rege... | [
"I'm assuming the first/last name is not known ahead of time so I will not try to do a regex group match (Matching the name provided and the characters before the @ symbol in the email to be equal).\n>>> import re\n>>> name_email_matcher = re.compile('^(?P<name>[A-Za-z ]+)<(?P<email>[^ ]+@[^.]+\\.[\\w.]+)>$')\n>>> ... | [
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0008116441_django_python.txt |
Q:
Python program using too much memory
I got these results from Heapy, but it's unclear what exactly they mean.
Index Count % Size % Cumulative % Kind (class / dict of class)
0 262539 59 36961284 48 36961284 48 dict (no owner)
1 65536 15 34340864 45 71302148 93 dict of myobj.Container
... | Python program using too much memory | I got these results from Heapy, but it's unclear what exactly they mean.
Index Count % Size % Cumulative % Kind (class / dict of class)
0 262539 59 36961284 48 36961284 48 dict (no owner)
1 65536 15 34340864 45 71302148 93 dict of myobj.Container
2 65536 15 2097152 3 73399300 9... | [
"Python doesn't eliminate the overhead of structures like that. Sorry. Its dynamic nature makes \nsuch compiler optimizations difficult. But then I don't know any language that would eliminate the overhead introduced by keeping things in dictionaries.\ndict (no owner) probably includes all the dictionaries you are ... | [
6
] | [] | [] | [
"memory",
"optimization",
"profiling",
"python"
] | stackoverflow_0008117042_memory_optimization_profiling_python.txt |
Q:
Different Behavior while calling Attributes from Class and Instance Variables
I defined such simple class as below:
>>> class myclass(object):
name = "google"
And I am creating an instance to call name attribute
>>> a = myclass()
>>> a.name
'google'
and also calling it directly from the class itself.
>>> m... | Different Behavior while calling Attributes from Class and Instance Variables | I defined such simple class as below:
>>> class myclass(object):
name = "google"
And I am creating an instance to call name attribute
>>> a = myclass()
>>> a.name
'google'
and also calling it directly from the class itself.
>>> myclass.name
'google'
So far (as I am having background with C# and Java) I will ca... | [
"I took a look at Python Data Model documentation. If you skip ahead to \"Class instances\" section, you will see the crucial explanation:\n\nAttribute assignments and deletions update the instance’s dictionary,\n never a class’s dictionary.\n\nSo in your example, when you do a.name = ..., you introduce a new key ... | [
4
] | [] | [] | [
"python"
] | stackoverflow_0008117124_python.txt |
Q:
Use function to update calculations
I created a function which updates the single list by adding the interest rate.
def first(lst, rate):
for i in range(len(lst)):
lst[i] += lst[i] * rate[i]
My question is, how to use this function to update two dimensional list by adding the interest rate?
For exampl... | Use function to update calculations | I created a function which updates the single list by adding the interest rate.
def first(lst, rate):
for i in range(len(lst)):
lst[i] += lst[i] * rate[i]
My question is, how to use this function to update two dimensional list by adding the interest rate?
For example:
lst2 = [[25, 10, 300], [7, 30, 80], [7... | [
"This situation is kind of strange, because you're completely relying on the functions having side-effects instead of returning values. However, here's a solution:\ndef second(lst2, rate):\n for i in range(len(lst2)):\n first(lst2[i], rate)\n\n",
"Short answer: this is what numpy is for.\nimport numpy\nlst2 ... | [
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0008117136_python.txt |
Q:
How do I get the values of a parsed query string in python?
querystring = cgi.parse_qs(decrypted_qs)
self.response.out.write(querystring) #output: {'param2': ['v2'], 'param1': ['v1']}
self.response.out.write(querystring.param2) #AttributeError: 'dict' object has no attribute 'param2'
The original dict: {'param1... | How do I get the values of a parsed query string in python? | querystring = cgi.parse_qs(decrypted_qs)
self.response.out.write(querystring) #output: {'param2': ['v2'], 'param1': ['v1']}
self.response.out.write(querystring.param2) #AttributeError: 'dict' object has no attribute 'param2'
The original dict: {'param1': 'v1', 'param2': 'v2'}
So why isn't the second one working, wha... | [
"Python dicts don't work like JavaScript dicts. You need to use it the same way you access elements in a list:\nquerystring['param2']\n\n",
"Don't attempt to extract query string parameters yourself in the first place - use your framework. If you're using webapp, you can access query string parameters through th... | [
1,
0
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0008115712_google_app_engine_python.txt |
Q:
Twistar ORM refresh function
Maybe I did not understand, but I can not update the object. The procedure is as follows:
I do SELECT (find()), get the object.
Change some properties in the properties of this object
Run the refresh.
Then I get the following error:
exceptions.AttributeError: 'list' object has no att... | Twistar ORM refresh function | Maybe I did not understand, but I can not update the object. The procedure is as follows:
I do SELECT (find()), get the object.
Change some properties in the properties of this object
Run the refresh.
Then I get the following error:
exceptions.AttributeError: 'list' object has no attribute 'keys'
Even when I try to ... | [
"Without code, it's not likely anyone will provide a useful answer. The obvious response is that you're looking up the keys attribute on a list, and lists do not have that attribute. You should have learned that much by reading the exception, though. The traceback will tell you where the exception occurred (and ... | [
0
] | [] | [] | [
"orm",
"python",
"twisted"
] | stackoverflow_0007754566_orm_python_twisted.txt |
Q:
Can't encode cyrillic character in python 2.7.x
When I trying to encode cyrillic "Р" character I get errors. Here is my code and errors:
>>> "Р".encode('utf8')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xd0 in position 0: ordinal no... | Can't encode cyrillic character in python 2.7.x | When I trying to encode cyrillic "Р" character I get errors. Here is my code and errors:
>>> "Р".encode('utf8')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xd0 in position 0: ordinal not in range(128)
How to solve it. Please help me. I'm... | [
"Anything in \"\" (e.g. a str) in Python 2.x is already encoded. You need to decode it to a unicode before you can encode it as something else.\n\"Unicode In Python, Completely Demystified\"\n",
"Python's interpreter starts in an ascii-only mode so you can't input Cyrllic characters directly. Instead you can cre... | [
2,
0
] | [] | [] | [
"character_encoding",
"encoding",
"python"
] | stackoverflow_0008117027_character_encoding_encoding_python.txt |
Q:
process.communicate and getche() fails
I am attempting to automate the execution of an interactive command line tool written in C++.
When launched, the binary waits for the letter S, Q, or P (Status, Quit, or Pause). It uses a nonstandard msvcrt function "getche" to acquire the key stroke (instead of a gets() for... | process.communicate and getche() fails | I am attempting to automate the execution of an interactive command line tool written in C++.
When launched, the binary waits for the letter S, Q, or P (Status, Quit, or Pause). It uses a nonstandard msvcrt function "getche" to acquire the key stroke (instead of a gets() for example) without the user having to hit ent... | [
"Adam Rosenfield's answer is a sensible approach if you can modify the behavior of the called program. Otherwise, if you really need to write to the console input buffer, try PyWin32's win32console module. That said, I'm not sure how to get the character echo part working correctly when stdout is piped. It ends up ... | [
3,
2
] | [] | [] | [
"popen",
"python",
"subprocess",
"windows"
] | stackoverflow_0008117055_popen_python_subprocess_windows.txt |
Q:
Python subprocess?
I think I might be repeating the question but I didn't find any of the answers suited to my requirement.
Pardon my ignorance.
I have a program running which continuously spits out some binary data from a server.It never stops until it's killed.
I want to wrap it in a python script to read the ou... | Python subprocess? | I think I might be repeating the question but I didn't find any of the answers suited to my requirement.
Pardon my ignorance.
I have a program running which continuously spits out some binary data from a server.It never stops until it's killed.
I want to wrap it in a python script to read the output and process it as a... | [
"Read with a length limit:\nproc = subprocess.Popen(args, stdin=None, stdout=subprocess.PIPE, stderr=None)\nwhile True:\n chunk = proc.stdout.read(1024)\n # chunk is <= 1024 bytes\n\n\nThis is the code from your comment, slightly modified. It works for me:\nimport subprocess\n\nclass container(object):\n p... | [
3,
0,
0
] | [] | [] | [
"python",
"subprocess"
] | stackoverflow_0008117249_python_subprocess.txt |
Q:
Installing a Python module in Windows
I'm trying to install a Python module on my Windows computer. I installed the development version of the NetBeans IDE to use as my Python editor, and it seems that they install Jython 2.5 under their own program folder, and force you to use that installation for development.
I... | Installing a Python module in Windows | I'm trying to install a Python module on my Windows computer. I installed the development version of the NetBeans IDE to use as my Python editor, and it seems that they install Jython 2.5 under their own program folder, and force you to use that installation for development.
I've been trying to install the PyWhois modu... | [
"Jython is Python for Java - are you sure this is what you want? I have answered this for \"normal\" Python for Windows, I assume this is what you are after.\nTo use Python under Windows, you need to install the Windows binary installer, which you can download from the Python download page. Make sure you choose the... | [
5
] | [] | [] | [
"module",
"netbeans",
"python",
"pywhois",
"windows"
] | stackoverflow_0008116986_module_netbeans_python_pywhois_windows.txt |
Q:
Referencing Current Django HttpRequest Instance
I'm new to python/django and wondering if there is a way to reference the current HttpRequest instance other than passing around the request instance.
For example, in .net I could reference the request instance from any function using:
HttpContext.Current.Request.
C... | Referencing Current Django HttpRequest Instance | I'm new to python/django and wondering if there is a way to reference the current HttpRequest instance other than passing around the request instance.
For example, in .net I could reference the request instance from any function using:
HttpContext.Current.Request.
Can this be done in django without having to keep putt... | [
"in short, no. since django's own session exists inside request any function or class not passed request will not have it in it's scope.\n"
] | [
0
] | [] | [] | [
"django",
"httprequest",
"python"
] | stackoverflow_0008116164_django_httprequest_python.txt |
Q:
How to write a function that takes a string and prints the letters in decreasing order of frequency?
I got this far:
def most_frequent(string):
d = dict()
for key in string:
if key not in d:
d[key] = 1
else:
d[key] += 1
return d
print most_frequent('aabbbc')
Re... | How to write a function that takes a string and prints the letters in decreasing order of frequency? | I got this far:
def most_frequent(string):
d = dict()
for key in string:
if key not in d:
d[key] = 1
else:
d[key] += 1
return d
print most_frequent('aabbbc')
Returning:
{'a': 2, 'c': 1, 'b': 3}
Now I need to:
reverse the pair
sort by number by decreasing order
onl... | [
"Here's a one line answer\nsortedLetters = sorted(d.iteritems(), key=lambda (k,v): (v,k))\n\n",
"This should do it nicely.\ndef frequency_analysis(string):\n d = dict()\n for key in string:\n d[key] = d.get(key, 0) + 1\n return d\n\ndef letters_in_order_of_frequency(string):\n frequencies = fre... | [
13,
5,
3,
3,
2,
2,
2,
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0000665942_python.txt |
Q:
Can I test XMLHttpRequest() in SDK with localhost?
The following code does not seem to work because when I try to get the "chooser" in Google App Engine (Python) it is undefined:
chooser = self.request.get("chooser")
self.response.out.write("chooser: %s " % chooser)
#returns "chooser:" without any value
Is this ... | Can I test XMLHttpRequest() in SDK with localhost? | The following code does not seem to work because when I try to get the "chooser" in Google App Engine (Python) it is undefined:
chooser = self.request.get("chooser")
self.response.out.write("chooser: %s " % chooser)
#returns "chooser:" without any value
Is this valid javascript?
var formData = new FormData();
for... | [
"Actually you're submitting the form twice. Once in writeToStorage via AJAX and also with the normal way with the the form. You will have to change two things.\n\nwriteToStorage has to return false as the last action\nChange your onsubmit to onsubmit=\"return writeToStorage()\"\n\nThis way you will prevent the defa... | [
1
] | [] | [] | [
"google_app_engine",
"javascript",
"python",
"xmlhttprequest"
] | stackoverflow_0008114926_google_app_engine_javascript_python_xmlhttprequest.txt |
Q:
Python tool to generate a unique temporary filename
To get a unique name for a temporary file you can use NamedTemporaryFile. But I want a fifo instead of a regular file, so something like:
name = generate_unique_name() # how?
try:
os.mkfifo(name)
# do stuff with the FIFO
finally:
os.remove(name)
Is ... | Python tool to generate a unique temporary filename | To get a unique name for a temporary file you can use NamedTemporaryFile. But I want a fifo instead of a regular file, so something like:
name = generate_unique_name() # how?
try:
os.mkfifo(name)
# do stuff with the FIFO
finally:
os.remove(name)
Is there a stdlib way to autogenerate a temporary filename w... | [
"Python has the tempfile module, which may have what you're looking for in it.\n"
] | [
11
] | [] | [] | [
"python",
"temp"
] | stackoverflow_0008118204_python_temp.txt |
Q:
How can I draw the value text for a slider widget from matplotlib?
I'm using a slider widget from matplotlib and I've been trying to update just the slider bar using blit for faster animation because if I use draw() for the whole canvas it is too slow. I got the bar to animate faster using this method (though it ... | How can I draw the value text for a slider widget from matplotlib? | I'm using a slider widget from matplotlib and I've been trying to update just the slider bar using blit for faster animation because if I use draw() for the whole canvas it is too slow. I got the bar to animate faster using this method (though it doesn't look perfect), but I can't figure out how to draw the slider val... | [
"It works perfectly (win7 64bit mpl 1.0.0 py2.6.5) with: \nIn [7]: f = figure()\nIn [8]: ax = f.add_subplot(111)\nIn [9]: sl = Slider (ax, 'Sigma',0.20, 18, valinit=0, dragging=True, fc='blue') \n\nit can be dragged manually very fast and without needing to make draw() or canvas.blit().\n"
] | [
0
] | [] | [] | [
"matplotlib",
"python",
"slider"
] | stackoverflow_0008117089_matplotlib_python_slider.txt |
Q:
django-uni-form helpers and CSRF tags over POST
I'm using django-uni-forms to display my fields, with a rather rudimentary example straight out of their book.
When I render the form fields using <form>{%csrf_tag%} {%form|as_uni_form%}</form>, everything works as expected.
However, django-uni-form Helpers allow you... | django-uni-form helpers and CSRF tags over POST | I'm using django-uni-forms to display my fields, with a rather rudimentary example straight out of their book.
When I render the form fields using <form>{%csrf_tag%} {%form|as_uni_form%}</form>, everything works as expected.
However, django-uni-form Helpers allow you to generate the form tag (and other helper-related c... | [
"Have you checked the source? It should already be there. The uni_form template tag should include it automatically.\n",
"I'm having the exact same problem with django-uni-form. The csrf token does not show up after the <form> tag if I use:\n{% load uni_form_tags %}\n{% uni_form form helper %}\n\nor:\n{% load uni... | [
3,
2,
1,
1
] | [] | [] | [
"django",
"python",
"uniform"
] | stackoverflow_0004771169_django_python_uniform.txt |
Q:
How to pass a raw pointer to Boost.Python?
I'm trying to use Boost.Python as a wrapper for a C++ function that receives a pointer, modifies the data (managed on Python side as numpy array for example) and returns. How do I get Python numpy and Boost.Python to collaborate and to give me the raw pointer inside the f... | How to pass a raw pointer to Boost.Python? | I'm trying to use Boost.Python as a wrapper for a C++ function that receives a pointer, modifies the data (managed on Python side as numpy array for example) and returns. How do I get Python numpy and Boost.Python to collaborate and to give me the raw pointer inside the function?
#include <boost/python.hpp>
namespace
{... | [
"One way that seems to work, suggested by Andreas Kloeckner, comments and alternatives are welcome. The greet() is modified as follows,\nchar const *greet(boost::python::object obj) {\n PyObject* pobj = obj.ptr();\n Py_buffer pybuf;\n if(PyObject_GetBuffer(pobj, &pybuf, PyBUF_SIMPLE)!=-1)\n {\n v... | [
3,
0
] | [] | [] | [
"boost_python",
"numpy",
"pointers",
"python"
] | stackoverflow_0008109336_boost_python_numpy_pointers_python.txt |
Q:
How to get SqlAlchemy Table to read "implicit" schema
Using table creation as normal:
t = Table(name, meta, [columns ...])
This is the first run where I create the table. In future executions I would like to use the table without having to indicate the [columns]. This seems redundant as it should already be speci... | How to get SqlAlchemy Table to read "implicit" schema | Using table creation as normal:
t = Table(name, meta, [columns ...])
This is the first run where I create the table. In future executions I would like to use the table without having to indicate the [columns]. This seems redundant as it should already be specified in the table schema. In other words, for future access... | [
"See Reflecting Database Objects of SA documentation:\nt = Table(name, meta, autoload=True)#, autoload_with=engine)\n\n"
] | [
1
] | [] | [] | [
"database",
"python",
"sqlalchemy"
] | stackoverflow_0008112845_database_python_sqlalchemy.txt |
Q:
How to use mock in django?
I tried to install a mock library for django from http://www.voidspace.org.uk/python/mock/
But when i type in
pip install -U mock
while in virtualenv, and then try to
import mock
from django project's shell i get:
ImportError: No module named mock
What can I do?
A:
Check to see if t... | How to use mock in django? | I tried to install a mock library for django from http://www.voidspace.org.uk/python/mock/
But when i type in
pip install -U mock
while in virtualenv, and then try to
import mock
from django project's shell i get:
ImportError: No module named mock
What can I do?
| [
"Check to see if the module is in the path. To do this, in the Python shell:\n>>> import sys\n>>> print sys.path\n\nIf it was installed correctly, you should see the mock directory in one of the directories printed out.\nIf you do not find the mock directory, I'm assuming that pip is not installing the module in th... | [
4,
2
] | [] | [] | [
"django",
"mocking",
"python",
"virtualenv"
] | stackoverflow_0008115618_django_mocking_python_virtualenv.txt |
Q:
Os.system not exiting
I am working on a python based tkinter script, where the flow is like this:
A csh script can be run by specifying the script name and arguments on unix terminal.
A python script is written to take the script name and argument input from user (in GUI).
The python script then needs to exec... | Os.system not exiting | I am working on a python based tkinter script, where the flow is like this:
A csh script can be run by specifying the script name and arguments on unix terminal.
A python script is written to take the script name and argument input from user (in GUI).
The python script then needs to execute the script on prompt fr... | [
"I think using subprocess would be better here, it will allow you to control stdin stdout and stderr as well as return with an exit code that can be captured in python again.\nhttp://docs.python.org/library/subprocess.html\n"
] | [
2
] | [] | [] | [
"os.system",
"python"
] | stackoverflow_0008118873_os.system_python.txt |
Q:
Program Calculating The Logs of Primes
Mathematical rule shows that my "program" gives a wrong answer.
I would be very grateful if you could check this small piece of code and tell me the problem with it. I know that the problem is somewhere after the line ll = []. I just can't pinpoint the exact cause of it. Bu... | Program Calculating The Logs of Primes | Mathematical rule shows that my "program" gives a wrong answer.
I would be very grateful if you could check this small piece of code and tell me the problem with it. I know that the problem is somewhere after the line ll = []. I just can't pinpoint the exact cause of it. But I do know that the sum of the logarithms o... | [
"Your second list doesn't only contain the logs of primes, it contains the logs of all integers between 2 and lp[500].\n",
"This is wrong:\nfor i in range(2, lp[500]): ## Gives all numbers from 2 to lp[500]\n if i < 3581:\n i = log(i, ) ## this changes i which is your loop variable!\n ll.append(i... | [
6,
1,
0,
0
] | [] | [] | [
"math",
"python"
] | stackoverflow_0008118606_math_python.txt |
Q:
Best way to fork multiple shell commands/processes in Python?
Most of the examples I've seen with os.fork and the subprocess/multiprocessing modules show how to fork a new instance of the calling python script or a chunk of python code. What would be the best way to spawn a set of arbitrary shell command concurre... | Best way to fork multiple shell commands/processes in Python? | Most of the examples I've seen with os.fork and the subprocess/multiprocessing modules show how to fork a new instance of the calling python script or a chunk of python code. What would be the best way to spawn a set of arbitrary shell command concurrently?
I suppose, I could just use subprocess.call or one of the Pop... | [
"All calls to subprocess.Popen return immediately to the caller. It's the calls to wait and communicate which block. So all you need to do is spin up a number of processes using subprocess.Popen (set stdin to /dev/null for safety), and then one by one call communicate until they're all complete.\nNaturally I'm assu... | [
4,
1,
1,
1,
0
] | [] | [] | [
"python",
"shell"
] | stackoverflow_0008090084_python_shell.txt |
Q:
PYTHONPATH error Linux Terminal v Console
I am having trouble getting PYTHONPATH set. I have added this line to ~/.bashrc
export PYTHONPATH=$PYTHONPATH:/home/sayth/My_Programs/Python
I ran source ~/.bashrc
Here is the issue though if I type python at the terminal and get a python REPL I can then import modules fr... | PYTHONPATH error Linux Terminal v Console | I am having trouble getting PYTHONPATH set. I have added this line to ~/.bashrc
export PYTHONPATH=$PYTHONPATH:/home/sayth/My_Programs/Python
I ran source ~/.bashrc
Here is the issue though if I type python at the terminal and get a python REPL I can then import modules from ~/My_Programs/Python without a problem.
Howe... | [
"I'm going to guess that you did not launch your ninja-ide from the same terminal that you source ~/.bashrc from -- the new environment variable only influences child processes of whichever shell process did the sourcing. Of course, logging out and in again may do it, but if you're living entirely in the GUI (e.g.,... | [
3
] | [] | [] | [
"environment_variables",
"path",
"python",
"terminal",
"ubuntu"
] | stackoverflow_0008119259_environment_variables_path_python_terminal_ubuntu.txt |
Q:
Python and Gtk+3 Entry problems
Greetings guys and girls!
I am new in programming Gtk+ and need a "decent" opensource twitter client and I can't find one, so I'm developing one that 'll be opensource. I'm using Gtk+3 and Python (PyGObject not PyGtk), and I'm having 2 problems with my Entry:
1 - can't connect a han... | Python and Gtk+3 Entry problems | Greetings guys and girls!
I am new in programming Gtk+ and need a "decent" opensource twitter client and I can't find one, so I'm developing one that 'll be opensource. I'm using Gtk+3 and Python (PyGObject not PyGtk), and I'm having 2 problems with my Entry:
1 - can't connect a handler to these signals : "deleted-tex... | [
"The problem here is that the inserted-text signal is emitted by Gtk.EntryBuffer objects, not by Gtk.Entry ones. To connect to that signal, you should use something like this:\nentry = Gtk.Entry()\nentry_buffer = entry.get_buffer()\nentry_buffer.connect('inserted-text', callback)\n\n"
] | [
2
] | [] | [] | [
"gtk3",
"open_source",
"pyobject",
"python",
"twitter"
] | stackoverflow_0008118999_gtk3_open_source_pyobject_python_twitter.txt |
Q:
Doctest for nested docstring
Suppose I have following code:
def foo(s):
"""A dummy function foo. For example:
>>> a = '''This is a test string line 1
This is a test string line 2
This is a test string line 3'''
>>> foo(a)
This is a test string line 1
This is a test string line 2
This is a test string line 3
>... | Doctest for nested docstring | Suppose I have following code:
def foo(s):
"""A dummy function foo. For example:
>>> a = '''This is a test string line 1
This is a test string line 2
This is a test string line 3'''
>>> foo(a)
This is a test string line 1
This is a test string line 2
This is a test string line 3
>>>
"""
print s
if __name_... | [
"I think you need to put some dots there\n>>> a = \"\"\"This is a test string line 1\n... This is a test string line 2\n... This is a test string line 3\"\"\"\n\n"
] | [
12
] | [] | [] | [
"docstring",
"doctest",
"python"
] | stackoverflow_0008119308_docstring_doctest_python.txt |
Q:
SQL Server (SQLCMD), Python and encoding issue when using non ascii chars
i'm facing an encoding issue with my python code, when asking data that are in SQL Server 2005.
(because i was unable to compile PyMSSQL-2.0.0b1) i'm using this piece of code and i am able to do some select but now i stick with the issue tha... | SQL Server (SQLCMD), Python and encoding issue when using non ascii chars | i'm facing an encoding issue with my python code, when asking data that are in SQL Server 2005.
(because i was unable to compile PyMSSQL-2.0.0b1) i'm using this piece of code and i am able to do some select but now i stick with the issue that i do not know what SQLCMD is output-ting to me :(
(i had to work with Europea... | [
"The problem might be that console works in ascii mode by default and output is converted\nvia current codepage setting. You can try the following, either write result\nto separate file with: -o <file> -u\nThen result file will have proper ucs2 encoding, which python gladly takes. Another\nis to setup utf8 console ... | [
0,
0
] | [] | [] | [
"encoding",
"python",
"sql_server_2005",
"sqlcmd",
"utf"
] | stackoverflow_0007993710_encoding_python_sql_server_2005_sqlcmd_utf.txt |
Q:
How to create simple python project using buildout?
I'm developing a Django application with buildout. I configured everything properly, it's working like a charm (at least during the development).
I want to create a companion project (module?), within the same buildout.cfg. How do you do that with buildout? I wan... | How to create simple python project using buildout? | I'm developing a Django application with buildout. I configured everything properly, it's working like a charm (at least during the development).
I want to create a companion project (module?), within the same buildout.cfg. How do you do that with buildout? I want my module to use tornado web server to serve deferred r... | [
"You have to add another part:\n[buildout]\nparts = django tornado\n\n[django]\nrecipe = z3c.recipe.scripts\neggs =\n Django\n # DjangoDevKit\n\n[tornado]\nrecipe = z3c.recipe.scripts\neggs = Tornado\n\n"
] | [
1
] | [] | [] | [
"buildout",
"django",
"python"
] | stackoverflow_0008113048_buildout_django_python.txt |
Q:
Can I redo/undo in ipython shell?
A feature in bpython called rewind.
Is there some similar key bindings?
A:
In short: no.
bpython's rewind works, behind the scenes, by rerunning everything you've entered minus the last bit. It's a neat feature, but it's not all that important when you can just delete or replace... | Can I redo/undo in ipython shell? | A feature in bpython called rewind.
Is there some similar key bindings?
| [
"In short: no.\nbpython's rewind works, behind the scenes, by rerunning everything you've entered minus the last bit. It's a neat feature, but it's not all that important when you can just delete or replace any variable at any time.\nIf you do want to rerun all but the last line, you can use %reset, then %rerun 1-1... | [
4
] | [] | [] | [
"ipython",
"python",
"shell"
] | stackoverflow_0008117522_ipython_python_shell.txt |
Q:
celery task does not terminate
I've created a task where the program uploads a file and the task acts as expected i.e it successfully uploads the file but even after the task does its work, the task does not "terminate", the state still remains PENDING. How can I fix this?
A:
From the celery docs:
PENDING: Task... | celery task does not terminate | I've created a task where the program uploads a file and the task acts as expected i.e it successfully uploads the file but even after the task does its work, the task does not "terminate", the state still remains PENDING. How can I fix this?
| [
"From the celery docs:\n\nPENDING: Task is waiting for execution or unknown. Any task id that is\n not know is implied to be in the pending state.\n\nAre you sure the task finishes what it does cleanly? Best to post code.\n"
] | [
0
] | [] | [] | [
"celery",
"python"
] | stackoverflow_0007631676_celery_python.txt |
Q:
Java and Python
I am trying to open a java link I have saved on my folder on my desktop. I can't get it to find the file. The java address is x:\green\Adam\FILEJAR.jar. This is an executable JAR file I want to open it and have it on my desktop, just open it and have it run as normal for the Java link. Want Python ... | Java and Python | I am trying to open a java link I have saved on my folder on my desktop. I can't get it to find the file. The java address is x:\green\Adam\FILEJAR.jar. This is an executable JAR file I want to open it and have it on my desktop, just open it and have it run as normal for the Java link. Want Python just to open it.
impo... | [
"The jar file itself is nothing but an archive with byte-compiled java code. \nTo execute it properly, try:\nimport subprocess\nrun = r\"java -jar x:\\green\\Adam\\FILEJAR.jar\"\nproc = subprocess.Popen(run)\n\n"
] | [
1
] | [] | [] | [
"java",
"python"
] | stackoverflow_0008120204_java_python.txt |
Q:
Python Tkinter program for Status Bar
from Tkinter import *
class StatusBar(Frame):
def __init__(self, master):
Frame.__init__(self, master)
self.label = Label(self, bd=1, relief=SUNKEN, anchor=W)
self.label.pack(fill=X)
def set(self, format, *args):
self.label.co... | Python Tkinter program for Status Bar | from Tkinter import *
class StatusBar(Frame):
def __init__(self, master):
Frame.__init__(self, master)
self.label = Label(self, bd=1, relief=SUNKEN, anchor=W)
self.label.pack(fill=X)
def set(self, format, *args):
self.label.config(text=format % args)
self.label... | [
"It's there; it's just very small because none of the widgets requested much space.\nIf you put some text in the Label, or gave root a geometry, it would be easier to see:\nimport Tkinter as tk\nclass StatusBar(tk.Frame): \n def __init__(self, master):\n tk.Frame.__init__(self, master)\n self.var... | [
9
] | [] | [] | [
"python"
] | stackoverflow_0008120246_python.txt |
Q:
how to use google user id in entities - python appengine
I create an entity like so:
company = dbDatafile(usOwner = user)
company.name = self.request.get("name")
company.put()
where user is the Google User account. Now when I try to search on that user like:
datafiles = dbDatafile.gql("WHERE usOwner = '%s'" % use... | how to use google user id in entities - python appengine | I create an entity like so:
company = dbDatafile(usOwner = user)
company.name = self.request.get("name")
company.put()
where user is the Google User account. Now when I try to search on that user like:
datafiles = dbDatafile.gql("WHERE usOwner = '%s'" % user.user_id())
assign to a jinja2 template var:
template_values... | [
"If usOwner is a UserProperty, you need to use USER() in GQL:\ndatafiles = dbDatafile.gql(\"WHERE usOwner = USER(:1)\", user.email())\n\nAlso remember always to use placeholders, not string interpolation - just because it's not SQL, doesn't mean it's not vulnerable to injection.\n",
"OK this isn't strictly answer... | [
5,
0
] | [] | [] | [
"google_app_engine",
"jinja2",
"python"
] | stackoverflow_0008119922_google_app_engine_jinja2_python.txt |
Q:
Python Float Division Not Exact
Possible Duplicate:
Python float - str - float weirdness
Python float division does not appear to have accurate results. Can someone explain why?
>>>3.0/5
0.59999999999999998
A:
Short answer: Floats use finite-precision binary encoding to represent numbers, so various operations... | Python Float Division Not Exact |
Possible Duplicate:
Python float - str - float weirdness
Python float division does not appear to have accurate results. Can someone explain why?
>>>3.0/5
0.59999999999999998
| [
"Short answer: Floats use finite-precision binary encoding to represent numbers, so various operations lose some precision.\nThe Wikipedia page has a lot of information (maybe too much).\nSee also: How do I use accurate float arithmetic in Python?\n",
"Floating point arithmetic is not exact; there are rounding er... | [
2,
1
] | [] | [] | [
"division",
"floating_point",
"python"
] | stackoverflow_0008120914_division_floating_point_python.txt |
Q:
Pgmagick resize image by width
I'm using graphicsmagick to do simple operations on images such as resizing, croppping etc, and i'm trying to use pgmagick via python instead.
For resizing, a script issues the following commands
gm convert image.jpg -resize 80x ...
resizing the mages according to width is my main ... | Pgmagick resize image by width | I'm using graphicsmagick to do simple operations on images such as resizing, croppping etc, and i'm trying to use pgmagick via python instead.
For resizing, a script issues the following commands
gm convert image.jpg -resize 80x ...
resizing the mages according to width is my main concern, and the command above works... | [
"Unfortunately could not find a way to implement \"resize\" in pgmagick for it uses the c++ api, which only has support for scale op for now. \nYet implemented it as ugly as: \ndef resize(new_size):\n g = pgmagick.Geometry(new_size) # distinguishes whether width, height or both given\n image = pgmagick.Imag... | [
1
] | [] | [] | [
"graphicsmagick",
"image_resizing",
"python"
] | stackoverflow_0008067802_graphicsmagick_image_resizing_python.txt |
Q:
Get the complete structure of a program?
I would have a quite simple question, but can't find any suitable automated solution for now.
I have developed an algorithm that performs a lot of stuff (image processing in fact) in Python.
What I want to do now is to optimize it. And for that, I would love to create a g... | Get the complete structure of a program? | I would have a quite simple question, but can't find any suitable automated solution for now.
I have developed an algorithm that performs a lot of stuff (image processing in fact) in Python.
What I want to do now is to optimize it. And for that, I would love to create a graph of my algorithm.
Kind of an UML chart or ... | [
"Take a look at this:\nhttp://blog.prashanthellina.com/2007/11/14/generating-call-graphs-for-understanding-and-refactoring-python-code/\n",
"UML generation is provided by pyreverse - it's part of pylint package\nIt generates UML in dot format - or png, etc.\nIt creates UML diagram, so you can easily see basic str... | [
1,
1
] | [] | [] | [
"coding_style",
"python"
] | stackoverflow_0008119900_coding_style_python.txt |
Q:
Mono Playback of Mp3s in Python OR C++
Im coding a music player in python using pyqt and I wanted it to feature mono playback of mp3 files.
I've accomplished that using pygame, as its mixer has a specific parameter channels that I can set to 1 to get mono playback.
However, pygame mp3 support is limited, so I'm se... | Mono Playback of Mp3s in Python OR C++ | Im coding a music player in python using pyqt and I wanted it to feature mono playback of mp3 files.
I've accomplished that using pygame, as its mixer has a specific parameter channels that I can set to 1 to get mono playback.
However, pygame mp3 support is limited, so I'm searching for a library that will be able to h... | [
"IF you want really good Windows support I suspect you might need or find it easier to use a different API for Windows... check these links:\n\nhttp://people.csail.mit.edu/hubert/pyaudio/ (cross-platform)\nhttp://ffmpeg.org/ffmpeg.html (cross-platform)\nhttp://www.codeproject.com/KB/audio-video/MP3Example.aspx (Win... | [
4,
1,
1,
0
] | [] | [] | [
"audio",
"c++",
"mp3",
"python"
] | stackoverflow_0008064784_audio_c++_mp3_python.txt |
Q:
How to update QStandartItemModel without freezing the main UI
I'm starting to learn PyQt4 and have been stuck on something for a long time now and can't figure it out myself:
Here is the concept: There is a TreeView with custom QStandartItemModel, which gets rebuild every couple of seconds, and can have a lot (hun... | How to update QStandartItemModel without freezing the main UI | I'm starting to learn PyQt4 and have been stuck on something for a long time now and can't figure it out myself:
Here is the concept: There is a TreeView with custom QStandartItemModel, which gets rebuild every couple of seconds, and can have a lot (hundreds at least) of entries, there also will be additional delegates... | [
"You have the right idea.\nYou need a separate worker thread to recompute the model for you (as often as you want, time based or signal based). Then you need to hook up a signal when the computation is done to notify the main thread.\nThere are a few gotchas you have to be aware of.\n\nQObjects live in threads. Sig... | [
1
] | [] | [] | [
"pyqt",
"python",
"qthread"
] | stackoverflow_0008110759_pyqt_python_qthread.txt |
Q:
Circular import in python+django?! how to make it work?
Hello I'm spliting my files because the model is getting bigger. So here we are again with problems:
My models;
If in my Category model I remove the "ArticleToCategory" and the many-to-many relationship it works well. But I need them!
How to fix it?
I deleted... | Circular import in python+django?! how to make it work? | Hello I'm spliting my files because the model is getting bigger. So here we are again with problems:
My models;
If in my Category model I remove the "ArticleToCategory" and the many-to-many relationship it works well. But I need them!
How to fix it?
I deleted the model.py in order to load files from the model package.
... | [
"You can define foreign keys using strings, to avoid exactly this problem.\nclass Art2C(..):\n art = m.ForeignKey('Article')\n from_other_app = m.ForeignKey('other_app.Article')\n\n"
] | [
7
] | [] | [] | [
"django",
"python"
] | stackoverflow_0008121656_django_python.txt |
Q:
How to wrap a c++ library for python?
I have a library and some head files, no c++ source code, I want to use it with python.
I tried py++, but gccxml report error.
I tried swig, but some many "undefined symbol" errors.
Are there some smart tools can do such things automatically?
A:
You could try using boost pyt... | How to wrap a c++ library for python? | I have a library and some head files, no c++ source code, I want to use it with python.
I tried py++, but gccxml report error.
I tried swig, but some many "undefined symbol" errors.
Are there some smart tools can do such things automatically?
| [
"You could try using boost python\nYou'd need to create a simple wrapper dll that links to your original library, containing code similar to this (assuming you wanted to export a class called LibraryClass with 2 functions, foo & bar)\n#include <librarytowrap.h>\n#include <boost/python.hpp>\nusing namespace boost::p... | [
2,
1,
0
] | [] | [] | [
"c++",
"python"
] | stackoverflow_0008119799_c++_python.txt |
Q:
Pattern Match a string for atleast two consecutive alphabets anywhere in the string
In my python code i want to pattern match a string for atleast two consecutive alphabets anywhere in the string.
I used, re.match(r'([a-zA-Z][a-zA-Z])+',str)
This matches a string for example 'abc', but does not match '1abc'. What ... | Pattern Match a string for atleast two consecutive alphabets anywhere in the string | In my python code i want to pattern match a string for atleast two consecutive alphabets anywhere in the string.
I used, re.match(r'([a-zA-Z][a-zA-Z])+',str)
This matches a string for example 'abc', but does not match '1abc'. What is the mistake in my regex ?
Please Help
Thank You
| [
"The method match looks from the beginning of the string only. You should use search instead.\nAlso your regex is built to match an even amount of characters.\nre.search(r'([a-zA-Z][a-zA-Z]+)',str)\n\n",
"I didn't quite understand what you want, but from the example provided one can see that you misinterpreted wh... | [
2,
2,
2
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0008121789_python_regex.txt |
Q:
Dynamically import and create class instance
With my python application, I have 40 modules (classes) which contain a parser for some text. In my function I only want to instanciate and use a particular module. These are all sorted in the database.
I am at the point now where I know my parser, and have both the pyt... | Dynamically import and create class instance | With my python application, I have 40 modules (classes) which contain a parser for some text. In my function I only want to instanciate and use a particular module. These are all sorted in the database.
I am at the point now where I know my parser, and have both the python file name and class I want to import and creat... | [
"Try this:\nfile_name = 'lex_parser'\nclass_name = 'LexParser'\n\nParser = getattr(__import__(file_name), class_name)\n\nNote that file_name must not contain .py.\nThis won't work if the module is within a package because __import__ would return the top level package. In that case you can do this:\nimport sys\n\nfi... | [
6,
3
] | [] | [] | [
"python"
] | stackoverflow_0008119897_python.txt |
Q:
Python: How to check a string for substrings from a list?
Possible Duplicate:
Check if multiple strings exist in another string
I can't seem to find an equivalent of code that functions like this anywhere for Python:
Basically, I'd like to check a string for substrings contained in a list.
A:
Try this test:
an... | Python: How to check a string for substrings from a list? |
Possible Duplicate:
Check if multiple strings exist in another string
I can't seem to find an equivalent of code that functions like this anywhere for Python:
Basically, I'd like to check a string for substrings contained in a list.
| [
"Try this test:\nany(substring in string for substring in substring_list)\n\nIt will return True if any of the substrings in substring_list is contained in string.\nNote that there is a Python analogue of Marc Gravell's answer in the linked question:\nfrom itertools import imap\nany(imap(string.__contains__, substr... | [
247
] | [] | [] | [
"list",
"python",
"string",
"substring"
] | stackoverflow_0008122079_list_python_string_substring.txt |
Q:
last five minutes Log4j log analysis using Python
I'm trying to analyze my java application logs ( using log4j ) logged within last five minutes. I'm planning to use Python to analyze last five minutes logs ans if there is any warnings, have to send a mail to me.
Can any one suggest me, what is the best method of... | last five minutes Log4j log analysis using Python | I'm trying to analyze my java application logs ( using log4j ) logged within last five minutes. I'm planning to use Python to analyze last five minutes logs ans if there is any warnings, have to send a mail to me.
Can any one suggest me, what is the best method of getting log lines for last five minutes?
I have to use... | [
"Since your log-file is sorted chronologically, you will have to parse it completely:\nfrom datetime import datetime, timedelta\nnow = datetime.now()\nlookback = timedelta(minutes=5)\noldest = (now - lookback).strftime('%Y-%m-%d %H:%M:%S')\n\nlines = []\n\nwith open('logfile.log', 'r') as f:\n for line in f:\n ... | [
2,
0
] | [] | [] | [
"log4j",
"python"
] | stackoverflow_0008121974_log4j_python.txt |
Q:
How do I change dynamically the text of a button in tkinter?
I have a dropdown menu and a button.I am trying to change the text on the button according to the choice in the dropdown menu.I used trace,but gives me this error :
TypeError: change_button_text() takes no arguments (3 given)
This is an example:
from Tk... | How do I change dynamically the text of a button in tkinter? | I have a dropdown menu and a button.I am trying to change the text on the button according to the choice in the dropdown menu.I used trace,but gives me this error :
TypeError: change_button_text() takes no arguments (3 given)
This is an example:
from Tkinter import*
import Tkinter as tk
import os
def change_button_t... | [
"Change your function definition of change_button_text to accept parameters. Callback functions called from the trace function will always receive three arguments: the name of the variable, the index and the mode. None of these are really interesting, but your function needs to match this signature for the callback... | [
1
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0008121592_python_tkinter.txt |
Q:
TypeError: 'float' object not iterable
I'm using python 3.2.2 on windows 7 and I'm trying to create a program which accepts 7 numbers and then tells the user how many are positive, how many are negative and how many are zero. this is what I have got so far:
count=7
for i in count:
num = float(input("Type a num... | TypeError: 'float' object not iterable | I'm using python 3.2.2 on windows 7 and I'm trying to create a program which accepts 7 numbers and then tells the user how many are positive, how many are negative and how many are zero. this is what I have got so far:
count=7
for i in count:
num = float(input("Type a number, any number:"))
if num == 0:
... | [
"for i in count: means for i in 7:, which won't work. The bit after the in should be of an iterable type, not a number. Try this:\nfor i in range(count):\n\n",
"use \n\nrange(count)\n\nint and float are not iterable\n"
] | [
34,
4
] | [] | [] | [
"floating_point",
"for_loop",
"python",
"python_3.x"
] | stackoverflow_0008120019_floating_point_for_loop_python_python_3.x.txt |
Q:
Retrieving media (images, videos etc.) from links in Perl
Similar to Reddit's r/pic sub-reddit, I want to aggregate media from various sources. Some sites use OEmbed specs to expose media on the page but not all sites do it. I was browsing through Reddit's source because essentially they 'scrape' links that users ... | Retrieving media (images, videos etc.) from links in Perl | Similar to Reddit's r/pic sub-reddit, I want to aggregate media from various sources. Some sites use OEmbed specs to expose media on the page but not all sites do it. I was browsing through Reddit's source because essentially they 'scrape' links that users submit, retrieve images, videos etc. They create thumbnails whi... | [
"Image::Size is the specialised module for determining image sizes from various format. It should be enough to read the first 1000 octets or so from a resource, enough for the diverse image headers, into a buffer and operating on that. I have not tested this.\nI do not know any general scraping module that has an A... | [
1,
0
] | [] | [] | [
"media",
"perl",
"python",
"reddit",
"web_scraping"
] | stackoverflow_0008107699_media_perl_python_reddit_web_scraping.txt |
Q:
Copied variable changes the original?
I have a simple problem in Python that is very very strange.
def estExt(matriz,erro):
# (1) Determinar o vector X das soluções
print ("Matrix after:");
print(matriz);
aux=matriz;
x=solucoes(aux); # IF aux is a copy of matrix, why the matrix is changed??
... | Copied variable changes the original? | I have a simple problem in Python that is very very strange.
def estExt(matriz,erro):
# (1) Determinar o vector X das soluções
print ("Matrix after:");
print(matriz);
aux=matriz;
x=solucoes(aux); # IF aux is a copy of matrix, why the matrix is changed??
print ("Matrix before: ");
print(mat... | [
"The line\naux=matriz;\n\nDoes not make a copy of matriz, it merely creates a new reference to matriz named aux. You probably want\naux=matriz[:]\n\nWhich will make a copy, assuming matriz is a simple data structure. If it is more complex, you should probably use copy.deepcopy\naux = copy.deepcopy(matriz)\n\nAs a... | [
121,
29,
7
] | [] | [] | [
"python",
"variables"
] | stackoverflow_0008122627_python_variables.txt |
Q:
Is it possible to profile a script run in WLST?
Is it possible to profile a script run in wlst? I need to profile a python script that migrates data from an XML file to an LDAP.
A:
So, I am answering my own question! Yes it is possible to profile. The JVM arguements needed for JProfiler/any other profiler needs ... | Is it possible to profile a script run in WLST? | Is it possible to profile a script run in wlst? I need to profile a python script that migrates data from an XML file to an LDAP.
| [
"So, I am answering my own question! Yes it is possible to profile. The JVM arguements needed for JProfiler/any other profiler needs to be added to wlst.sh and it works.\n"
] | [
0
] | [] | [] | [
"python",
"weblogic11g",
"wlst"
] | stackoverflow_0007709023_python_weblogic11g_wlst.txt |
Q:
Python's imp.reload() function is not working?
Here's a concise example:
x.py:
class x:
var = 'from x.py'
y.py:
class x:
var = 'from y.py'
test.py
import imp
def write_module(filename):
fp = open('z.py', 'w')
fp.write(open(filename).read())
fp.close()
write_module('x.py')
import z
print(z.x.var) # Pri... | Python's imp.reload() function is not working? | Here's a concise example:
x.py:
class x:
var = 'from x.py'
y.py:
class x:
var = 'from y.py'
test.py
import imp
def write_module(filename):
fp = open('z.py', 'w')
fp.write(open(filename).read())
fp.close()
write_module('x.py')
import z
print(z.x.var) # Prints 'from x.py'
write_module('y.py')
imp.reload(z)
p... | [
"This happens because the file creation dates (of z.py and its compiled counterpart z.pyc) are identical, so Python thinks that the file is unchanged and doesn't recompile it. \nActually, when I was trying and re-trying your code, it once worked as expected - probably because the two files happened to be created on... | [
9
] | [] | [] | [
"import",
"python"
] | stackoverflow_0008122734_import_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.