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:
Converting integer hex format into strings
I am programming an application to send data using UDP sockets with Python 3.1.
The command socket.send requires data in bytes format.
The problem I am having is that the package I have to send has three different fields, the first one contains a 16 bits integer variable ... | Converting integer hex format into strings | I am programming an application to send data using UDP sockets with Python 3.1.
The command socket.send requires data in bytes format.
The problem I am having is that the package I have to send has three different fields, the first one contains a 16 bits integer variable (c_ushort) and so does the second field whereas ... | [
"You need to serialize your class, use pickle.\nclass Blah:\n def __init__(self,mynum, mystr):\n self.mynum = mynum\n self.mystr = mystr\n\na = Blah(3,\"blahblah\")\n#bytes(a) # this will fail with \"TypeError: 'Blah' object is not iterable\"\n\nimport pickle\nb = pickle.dumps(a) # turn it into a b... | [
1
] | [] | [] | [
"python",
"sockets"
] | stackoverflow_0003609156_python_sockets.txt |
Q:
Trac Using Database Authentication
Is it possible to use a database for authentication with Trac?
.htpasswd auth is not desired in this install.
Using Trac .11 and MySQL as the database. Trac is currently using the database, but provides no authentication.
A:
Out of the box, Trac doesn't actually do its own auth... | Trac Using Database Authentication | Is it possible to use a database for authentication with Trac?
.htpasswd auth is not desired in this install.
Using Trac .11 and MySQL as the database. Trac is currently using the database, but provides no authentication.
| [
"Out of the box, Trac doesn't actually do its own authentication, it leaves it up to the web server. So, you've got a wealth of Apache-related options available to you. You could maybe look at something like auth_mysql to let you keep user credentials in a database.\nAlternatively, take a look at the AccountManager... | [
5,
1,
0
] | [] | [] | [
"apache",
"mysql",
"python",
"trac"
] | stackoverflow_0000982226_apache_mysql_python_trac.txt |
Q:
Ways for combining Adobe AIR and Python - Python
I need to use Python because: I have implemented many scripts and libraries using Python in order to solve a certain problem.
I would like to use AIR because: I really love the flexibility of building UIs using HTML and Javascript, also implementing beautiful UI des... | Ways for combining Adobe AIR and Python - Python | I need to use Python because: I have implemented many scripts and libraries using Python in order to solve a certain problem.
I would like to use AIR because: I really love the flexibility of building UIs using HTML and Javascript, also implementing beautiful UI designs is actually very easy.
Any ideas if I can integra... | [
"I've been thinking about the same combo as well. PyAMF might be worth a look - I've been thinking of PyAMF + web2py + AIR myself, possibly with py2exe thrown in for good measure.\n"
] | [
2
] | [] | [] | [
"air",
"desktop_application",
"python"
] | stackoverflow_0003610084_air_desktop_application_python.txt |
Q:
Create a new array from numpy array based on the conditions from a list
Suppose that I have an array defined by:
data = np.array([('a1v1', 'a2v1', 'a3v1', 'a4v1', 'a5v1'),
('a1v1', 'a2v1', 'a3v1', 'a4v2', 'a5v1'),
('a1v3', 'a2v1', 'a3v1', 'a4v1', 'a5v2'),
('a1v2', 'a2v2', 'a3v1', 'a4v1', 'a5v2... | Create a new array from numpy array based on the conditions from a list | Suppose that I have an array defined by:
data = np.array([('a1v1', 'a2v1', 'a3v1', 'a4v1', 'a5v1'),
('a1v1', 'a2v1', 'a3v1', 'a4v2', 'a5v1'),
('a1v3', 'a2v1', 'a3v1', 'a4v1', 'a5v2'),
('a1v2', 'a2v2', 'a3v1', 'a4v1', 'a5v2'),
('a1v2', 'a2v3', 'a3v2', 'a4v1', 'a5v2'),
('a1v2', 'a2v3', ... | [
"If I'm understanding you correctly, you want to list the entire row, where a given tuple of columns is equal to some value. In that case, this should be what you want, though it's a bit verbose and obscure:\ntest_cols = data[['a1', 'a4']]\ntest_vals = np.array(('a1v1', 'a4v1'), test_cols.dtype)\ndata[test_cols ==... | [
1
] | [] | [] | [
"arrays",
"numpy",
"python",
"recarray"
] | stackoverflow_0003607001_arrays_numpy_python_recarray.txt |
Q:
Django: Advice on designing a model with varying fields
I'm looking for some advice/opinions on the best way to approach creating a sort-of-dynamic model in django.
The structure needs to describe data for Products. There are about 60 different possible data points that could be relevant, with each Product choosi... | Django: Advice on designing a model with varying fields | I'm looking for some advice/opinions on the best way to approach creating a sort-of-dynamic model in django.
The structure needs to describe data for Products. There are about 60 different possible data points that could be relevant, with each Product choosing about 20 of those points (with much overlapping) depending... | [
"If you are looking for implementations of dynamic attributes for models in django in some kind of eav style, have a look at eav-django, or at django-expando.\n",
"This is ordinary relational database design. Don't over-optimize it with OO and inheritance techniques. \nYou have a Product Category table with (pr... | [
2,
1
] | [] | [] | [
"django",
"models",
"orm",
"python"
] | stackoverflow_0003610327_django_models_orm_python.txt |
Q:
How come this way of ending a thread is not working?
I just came out with my noob way of ending a thread, but I don't know why it's not working. Would somebody please help me out?
Here's my sample code:
import wx
import thread
import time
import threading
class TestFrame(wx.Frame):
def __init__(self):
... | How come this way of ending a thread is not working? | I just came out with my noob way of ending a thread, but I don't know why it's not working. Would somebody please help me out?
Here's my sample code:
import wx
import thread
import time
import threading
class TestFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, parent = None, id = -1, title = "... | [
"Try using a thread safe method such as wx.CallAfter when updating your multiline.\n def LongRunning(self):\n Counter = 1\n\n while True:\n time.sleep(2)\n print \"Hello, \", Counter\n\n wx.CallAfter(self.updateMultiLine, \"hello, \" + str(Counter) + \"\\n\")\n Counter = Coun... | [
2,
1
] | [] | [] | [
"python",
"wx.textctrl",
"wxpython"
] | stackoverflow_0003609627_python_wx.textctrl_wxpython.txt |
Q:
doesPythonLikeCamels
Are Java style camelCase names good practice in Python. I know Capilized names should be reserved by convention for Class names. Methods should be small letters according to good style, or actually I am not so sure. Is there PEP about naming?
COMMENTS:
Sorry for camels :) , I learned from answ... | doesPythonLikeCamels | Are Java style camelCase names good practice in Python. I know Capilized names should be reserved by convention for Class names. Methods should be small letters according to good style, or actually I am not so sure. Is there PEP about naming?
COMMENTS:
Sorry for camels :) , I learned from answer PEP8, that my title is ... | [
"PEP 8 contains all the answers.\n",
"It's best to match whatever your organization uses or is comfortable with. Preaching \"the One True Python style\" doesn't exactly build harmony if everyone else already uses some other uniform manner. If it's some random hodgepodge of styles, then go ahead and advocate for... | [
10,
2,
1
] | [] | [] | [
"case",
"convention",
"naming",
"pep",
"python"
] | stackoverflow_0003610071_case_convention_naming_pep_python.txt |
Q:
How to read a musical file using python and identify the various frequency levels of the notes?
please help me with the python...this is my project topic...
A:
Fourier transforms. Learn some basics about music and signals before even considering code.
Basic Outline:
Audio Import
See http://wiki.python.org/moin/... | How to read a musical file using python and identify the various frequency levels of the notes? | please help me with the python...this is my project topic...
| [
"Fourier transforms. Learn some basics about music and signals before even considering code.\nBasic Outline:\nAudio Import\nSee http://wiki.python.org/moin/Audio/ and find one that will import your (unspecified) file.\nAnalysis\nGet numpy.\n>>> from numpy.fft import fft\n>>> a = abs(fft([1,2,3,2]*4))\n>>> a\narray... | [
2
] | [] | [] | [
"python"
] | stackoverflow_0003610847_python.txt |
Q:
Is it possible to memcache a json result in App Engine?
I think my question is already clear enough, but to make it even more clear i will illustrate it with my example.
I'm currently returning many json every request, which I would like to cache in some way. I thought memcache would be great, but I only see that ... | Is it possible to memcache a json result in App Engine? | I think my question is already clear enough, but to make it even more clear i will illustrate it with my example.
I'm currently returning many json every request, which I would like to cache in some way. I thought memcache would be great, but I only see that they use memcache for caching queries.
| [
"JSON is just text, so yes, you can store it in memcache.\n"
] | [
7
] | [] | [] | [
"google_app_engine",
"json",
"python"
] | stackoverflow_0003610854_google_app_engine_json_python.txt |
Q:
python and ruby equivalent of perls Template::Declare?
CPAN has the Template::Declare package. A declarative way to create HTML templates in Perl without any HTML directly written.
I would love to use similar packages in python and ruby. Are there equivalent packages for those languages?
A:
In Ruby there is Mark... | python and ruby equivalent of perls Template::Declare? | CPAN has the Template::Declare package. A declarative way to create HTML templates in Perl without any HTML directly written.
I would love to use similar packages in python and ruby. Are there equivalent packages for those languages?
| [
"In Ruby there is Markaby. The closest I know if in Python is Brevé.\nAlso there are a few more in Perl and other languages as well.\n/I3az/\n",
"If you like the look of Markaby, also see Erector which is inspired by it but said to be somewhat cleaner\n",
"Are you looking for something like Haml in Ruby ?\nExa... | [
6,
1,
0
] | [] | [] | [
"perl",
"python",
"ruby"
] | stackoverflow_0003607491_perl_python_ruby.txt |
Q:
How to empty a Python list without doing list = []?
If the my_list variable is global, you can't do:
my_list = []
that just create a new reference in the local scope.
Also, I found disgusting using the global keyword, so how can I empty a list using its methods?
A:
del a[:]
or
a[:] = []
A:
How about the foll... | How to empty a Python list without doing list = []? | If the my_list variable is global, you can't do:
my_list = []
that just create a new reference in the local scope.
Also, I found disgusting using the global keyword, so how can I empty a list using its methods?
| [
"del a[:]\n\nor\na[:] = []\n\n",
"How about the following to delete all list items:\ndef emptyit():\n del l[:]\n\n"
] | [
11,
1
] | [] | [] | [
"python",
"types"
] | stackoverflow_0003611203_python_types.txt |
Q:
special character at the begin who match with the end from every word [only regex]
what's best solution using regex, to remove special characters from the begin and the end of every word.
"as-df-- as-df- as-df (as-df) 'as-df' asdf-asdf) (asd-f asdf' asd-f' -asdf- %asdf%s asdf& $asdf$ +asdf+ asdf++ asdf''"
the ou... | special character at the begin who match with the end from every word [only regex] | what's best solution using regex, to remove special characters from the begin and the end of every word.
"as-df-- as-df- as-df (as-df) 'as-df' asdf-asdf) (asd-f asdf' asd-f' -asdf- %asdf%s asdf& $asdf$ +asdf+ asdf++ asdf''"
the output should be:
"as-df-- as-df- as-df (as-df) as-df asdf-asdf) (asd-f asdf' asd-f' a... | [
"For Perl, how about /\\b([^\\s\\w])\\w+\\1\\b/g? Note things like \\b don't work in all regex languages.\nOops, as @Nick pointed out, this doesn't work for non-identical pairs, like () [] etc.\nInstead you could do:\n s/\\b([^\\s\\w([\\]){}])\\w+\\1\\b/\\2/g\n s/\\b\\((\\w+)\\)\\b/\\1/g\n s/\\b\\[(\\w+)\\]\\b/\\1/... | [
1,
1
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0003611139_python_regex.txt |
Q:
python: confusion with local class name
I have the following code:
def f():
class XYZ:
# ...
cls = type('XXX', (XYZ, ), {})
# ...
return cls
I am now using it as follows:
C1 = f()
C2 = f()
and it seems to work fine: C1 is C2 returns False, there's no conflict between the class attributes ... | python: confusion with local class name | I have the following code:
def f():
class XYZ:
# ...
cls = type('XXX', (XYZ, ), {})
# ...
return cls
I am now using it as follows:
C1 = f()
C2 = f()
and it seems to work fine: C1 is C2 returns False, there's no conflict between the class attributes of the two classes, etc.
Question 1
Why is th... | [
"Question 3\nTo have cls.__name__ be anything you want, (with a nod to delnan's suggestion)\ndef f(clsname):\n class XYZ:\n # ...\n XYZ.__name__ = XYZ\n # ...\n return XYZ\n\nQuestion 1\nThe reason that c1 is not c2 is that they are two different objects stored at two different locations in memor... | [
2,
2
] | [] | [] | [
"class",
"namespaces",
"python"
] | stackoverflow_0003611432_class_namespaces_python.txt |
Q:
Storing and escaping Django tags and filters in Django models
I am outputting content from my models to my templates, however some model fields call data stored in other models. This happens only in a few fields. I am wondering whether using an if tag to evaluate this would be more efficient compared to storing th... | Storing and escaping Django tags and filters in Django models | I am outputting content from my models to my templates, however some model fields call data stored in other models. This happens only in a few fields. I am wondering whether using an if tag to evaluate this would be more efficient compared to storing the django tags inside the models.
Answers to this question say that... | [
"Thanks Ned, I tried implementing that but I found it to be quite complex and its also disadvantageous in terms of portability. \nHowever, I found exactly what I needed at Django Snippets (dont know why I didn't look there first). Its a quite useful utility known as render_as_template. \nAfter setting it up as a cu... | [
1,
0,
0
] | [] | [] | [
"django",
"django_templates",
"python"
] | stackoverflow_0003594909_django_django_templates_python.txt |
Q:
List query with, facebook friends in list?
In a python based facebook application on GAE, i want to check which friends of current user have "marked" a web page or not.
For this i have to run as many DB queries as the number of friends (say 100)
I fear this may run into "timeout" because of large no of queries.
Go... | List query with, facebook friends in list? | In a python based facebook application on GAE, i want to check which friends of current user have "marked" a web page or not.
For this i have to run as many DB queries as the number of friends (say 100)
I fear this may run into "timeout" because of large no of queries.
Google DOCs suggest that "list" queries run in par... | [
"I would suggest the following:\n\nMake 'marked' entities child entities of the users who have marked them.\nUse a key name for the 'marked' entity that is based on the URL of the page marked\nTo find friends who have marked a page, retrieve a list of friends, then generate the list of entity keys from the list of ... | [
1,
1
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0003606669_google_app_engine_python.txt |
Q:
in python; convert list of files to file like object
Er, so im juggling parsers and such, and I'm going from one thing which processes files to another.
The output from the first part of my code is a list of strings; I'm thinking of each string as a line from a text file.
The second part of the code needs a file t... | in python; convert list of files to file like object | Er, so im juggling parsers and such, and I'm going from one thing which processes files to another.
The output from the first part of my code is a list of strings; I'm thinking of each string as a line from a text file.
The second part of the code needs a file type as an input.
So my question is, is there a proper, pyt... | [
"StringIO implements (nearly) all stdio methods. Example:\n>>> import StringIO\n>>> StringIO.StringIO(\"hello\").read()\n'hello'\n\ncStringIO is a faster counterpart.\nTo convert your list of string, just join them:\n>>> list_of_strings = [\"hello\", \"line two\"]\n>>> handle = StringIO.StringIO('\\n'.join(list_of_... | [
12
] | [] | [] | [
"python",
"text"
] | stackoverflow_0003611972_python_text.txt |
Q:
How to fix broken relative links in offline webpages?
I wrote a simple Python script to download a web page for offline viewing. The problem is that the relative links are broken. So the offline file "c:\temp\webpage.html" has a href="index.aspx" but when opened in a browser it resolves to "file:///C:/temp/index... | How to fix broken relative links in offline webpages? | I wrote a simple Python script to download a web page for offline viewing. The problem is that the relative links are broken. So the offline file "c:\temp\webpage.html" has a href="index.aspx" but when opened in a browser it resolves to "file:///C:/temp/index.aspx" instead of "http://myorginalwebsite.com/index.aspx".... | [
"If you just want your relative links to refer to the website, just add a base tag in the head:\n<base href=\"http://myoriginalwebsite.com/\" />\n\n",
"lxml makes this braindead simple!\n>>> import lxml.html, urllib\n>>> url = 'http://www.google.com/'\n>>> e = lxml.html.parse(urllib.urlopen(url))\n>>> e.xpath('//... | [
5,
1,
0
] | [] | [] | [
"html",
"hyperlink",
"offline_browsing",
"python"
] | stackoverflow_0003611961_html_hyperlink_offline_browsing_python.txt |
Q:
Python ElementTree Check the node / element type
I am using ElementTree and cannot figure out if the childnode is text or not. childelement.text does not seem to work as it gives false positive even on nodes which are not text nodes.
Any suggestions?
Example
<tr>
<td><a href="sdas3">something for link</a></td>
... | Python ElementTree Check the node / element type | I am using ElementTree and cannot figure out if the childnode is text or not. childelement.text does not seem to work as it gives false positive even on nodes which are not text nodes.
Any suggestions?
Example
<tr>
<td><a href="sdas3">something for link</a></td>
<td>tttttk</td>
<td><a href="tyty">tyt for link</a>... | [
"How about using the getiterator method to iterate through the all the descendant nodes:\nimport xml.etree.ElementTree as xee\n\ncontent='''\n<tr>\n <td><a href=\"sdas3\">something for link</a></td>\n <td>tttttk</td>\n <td><a href=\"tyty\">tyt for link</a></td>\n</tr>\n'''\n\ndef text_content(node):\n result=... | [
1,
1
] | [] | [] | [
"elementtree",
"python"
] | stackoverflow_0003611513_elementtree_python.txt |
Q:
Does django with mongodb make migrations a thing of the past?
Since mongo doesn't have a schema, does that mean that we won't have to do migrations when we change the models?
What does the migration process look like with a non-relational db?
A:
I think this is a really good question, but the answers are going t... | Does django with mongodb make migrations a thing of the past? | Since mongo doesn't have a schema, does that mean that we won't have to do migrations when we change the models?
What does the migration process look like with a non-relational db?
| [
"I think this is a really good question, but the answers are going to be a little scattered based on the libs you're using and your expectations for a \"migration\".\nLet's take a look at some common migration actions:\n\nAdd a field: Mongo makes this very easy. Just add a field and you're done.\nDelete a field: In... | [
16,
2,
1
] | [] | [] | [
"django",
"mongodb",
"python"
] | stackoverflow_0003604565_django_mongodb_python.txt |
Q:
Output Django Object into XML-RPC response
I'm trying to return a django object in a XML-RPC response. Is it possible to serialize a model as XML-RPC methodResponse?
A:
I did figure out how serialize with xmlrpclib.dumps
def get_model(uuid):
o = MyModel.objects.get(uuid=uuid)
return xmlrpclib.dumps((o, )... | Output Django Object into XML-RPC response | I'm trying to return a django object in a XML-RPC response. Is it possible to serialize a model as XML-RPC methodResponse?
| [
"I did figure out how serialize with xmlrpclib.dumps\ndef get_model(uuid):\n o = MyModel.objects.get(uuid=uuid)\n return xmlrpclib.dumps((o, ), allow_none=True, methodresponse=1)\n\nThis will result in a XML-RPC methodResponse.\nThen on the client end I just need to use xmlrpclib.loads to convert to a python ... | [
1
] | [] | [] | [
"django",
"python",
"serialization",
"xml_rpc"
] | stackoverflow_0003611827_django_python_serialization_xml_rpc.txt |
Q:
can't multiply sequence by non-int of type 'float'
Why do I get an error of "can't multiply sequence by non-int of type 'float'"? from the following code:
def nestEgVariable(salary, save, growthRates):
SavingsRecord = []
fund = 0
depositPerYear = salary * save * 0.01
for i in growthRates:
... | can't multiply sequence by non-int of type 'float' | Why do I get an error of "can't multiply sequence by non-int of type 'float'"? from the following code:
def nestEgVariable(salary, save, growthRates):
SavingsRecord = []
fund = 0
depositPerYear = salary * save * 0.01
for i in growthRates:
fund = fund * (1 + 0.01 * growthRates) + depositPerYear... | [
"for i in growthRates: \n fund = fund * (1 + 0.01 * growthRates) + depositPerYear\n\nshould be:\nfor i in growthRates: \n fund = fund * (1 + 0.01 * i) + depositPerYear\n\nYou are multiplying 0.01 with the growthRates list object. Multiplying a list by an integer is valid (it's overloaded syntactic sugar th... | [
26,
20,
3,
2,
1,
0
] | [] | [] | [
"floating_point",
"python",
"sequence"
] | stackoverflow_0003612378_floating_point_python_sequence.txt |
Q:
Better way to zip files in Python (zip a whole directory with a single command)?
Possible Duplicate:
How do I zip the contents of a folder using python (version 2.5)?
Suppose I have a directory: /home/user/files/. This dir has a bunch of files:
/home/user/files/
-- test.py
-- config.py
I want to zip this di... | Better way to zip files in Python (zip a whole directory with a single command)? |
Possible Duplicate:
How do I zip the contents of a folder using python (version 2.5)?
Suppose I have a directory: /home/user/files/. This dir has a bunch of files:
/home/user/files/
-- test.py
-- config.py
I want to zip this directory using ZipFile in python. Do I need to loop through the directory and add thes... | [
"Note that this doesn't include empty directories. If those are required there are workarounds available on the web; probably best to get the ZipInfo record for empty directories in our favorite archiving programs to see what's in them.\nHardcoding file/path to get rid of specifics of my code...\ntarget_dir = '/tm... | [
24,
6,
2,
1
] | [] | [] | [
"python",
"zip"
] | stackoverflow_0003612094_python_zip.txt |
Q:
Why Python gets installed in Frameworks directory?
I've been wondering why python gets installed in directory named Frameworks? (though it's not Framework)
$ which python
/Library/Frameworks/Python.framework/Versions/2.7/bin/python... | Why Python gets installed in Frameworks directory? | I've been wondering why python gets installed in directory named Frameworks? (though it's not Framework)
$ which python
/Library/Frameworks/Python.framework/Versions/2.7/bin/python
Somebody please explain! Thanks!
| [
"That's the way it is in OS X.\nThe Mac/README file in the Python source tree goes into some more details of the advantages of a framework build versus a traditional UNIX shared-library build, which will also work on OS X. The main points:\n\n\"The main reason is because you want\nto create GUI programs in Python.... | [
5
] | [] | [] | [
"macos",
"python"
] | stackoverflow_0003612273_macos_python.txt |
Q:
Python 3 string slice behavior inconsistent
Wanted an easy way to extract year month and day from a string.
Using Python 3.1.2
Tried this:
processdate = "20100818"
print(processdate[0:4])
print(processdate[4:2])
print(processdate[6:2])
Results in:
...2010
...
...
Reread all the string docs, did some searching, c... | Python 3 string slice behavior inconsistent | Wanted an easy way to extract year month and day from a string.
Using Python 3.1.2
Tried this:
processdate = "20100818"
print(processdate[0:4])
print(processdate[4:2])
print(processdate[6:2])
Results in:
...2010
...
...
Reread all the string docs, did some searching, can't figure out why it'd be doing this.
I'm sure ... | [
"With a slice of [4:2], you're telling Python to start at character index 4 and stop at character index 2. Since 4 > 2, you are already past where you should stop when you start, so the slice is empty.\nDid you want the fourth and fifth characters? Then you want [4:6] instead.\n",
"The best way to do this is with... | [
6,
6,
2
] | [] | [] | [
"python",
"slice"
] | stackoverflow_0003612217_python_slice.txt |
Q:
Adjust Python Regex to not include a single digit in the findall results
I am trying to capture / extract numeric values from some strings.
Here is a sample string:
s='The shipping company had 93,999,888.5685 gallons of fuel on hand'
I want to pull the 93,999,888.5685 value
I have gotten my regex to this
> mine... | Adjust Python Regex to not include a single digit in the findall results | I am trying to capture / extract numeric values from some strings.
Here is a sample string:
s='The shipping company had 93,999,888.5685 gallons of fuel on hand'
I want to pull the 93,999,888.5685 value
I have gotten my regex to this
> mine=re.compile("(\d{1,3}([,\d{3}])*[.\d+]*)")
However, when I do a findall I get... | [
"The reason the 8 is being captured is because you have 2 capturing groups. Mark the 2nd group as a non-capturing group using ?: with this pattern: (\\d{1,3}(?:[,\\d{3}])*[.\\d+]*)\nYour second group, ([,\\d{3}]) is responsible for the additional match.\n",
"Your string broken up:\n(\n\\d{1,3} This will mat... | [
4,
1,
0
] | [
"Why not wrap it in \\D ? mine=re.compile(\"\\D(\\d{1,3}([,\\d{3}])[.\\d+])\\D\").\n"
] | [
-1
] | [
"numbers",
"python",
"regex"
] | stackoverflow_0003612693_numbers_python_regex.txt |
Q:
Best practices to make an Installer - Can I use Yum
I am new to installers and up until now have just been manually executing a line by line list of items to install. Clearly this is not a scaleable approach, especially when new servers need to be installed regularly, and not by the same person.
Currently I need t... | Best practices to make an Installer - Can I use Yum | I am new to installers and up until now have just been manually executing a line by line list of items to install. Clearly this is not a scaleable approach, especially when new servers need to be installed regularly, and not by the same person.
Currently I need to install about 30 packages via Yum (from large ones like... | [
"You're asking a few questions at once, so I'm just going to touch on packaging and installing Python libraries...\nUsing setup.py you can turn Python packages into RPMs for installation on any Red Hat/CentOS \nbox using yum. This is how I install all my packages internally at my job. Assuming the foundation rpmbui... | [
4,
2
] | [] | [] | [
"installation",
"python",
"yum"
] | stackoverflow_0003612785_installation_python_yum.txt |
Q:
Passing class instantiations (layering)
Program design:
Class A, which implements lower level data handling
Classes B-E, which provide a higher level interface to A to perform various functions
Class F, which is a UI object that interacts with B-E according to user input
There can only be one instantiation of ... | Passing class instantiations (layering) | Program design:
Class A, which implements lower level data handling
Classes B-E, which provide a higher level interface to A to perform various functions
Class F, which is a UI object that interacts with B-E according to user input
There can only be one instantiation of A at any given time, to avoid race condit... | [
"Use a Borg instead of a Singleton.\n>>> class Borg( object ):\n... __ss = {}\n... def __init__( self ):\n... self.__dict__ = self.__ss\n...\n>>> foo = Borg()\n>>> foo.x = 1\n>>> bar = Borg()\n>>> bar.x\n1\n\n",
"How about using the module technique, this is much simpler.\nin module \"A.py\"\n... | [
4,
0
] | [] | [] | [
"database",
"oop",
"python",
"python_3.x"
] | stackoverflow_0003612535_database_oop_python_python_3.x.txt |
Q:
Python can't import module named wsgi_soap from the soaplib
This code works on Debian under Python 2.5 but doesn't on Ubuntu under Python 2.6:
from soaplib.wsgi_soap import SimpleWSGISoapApp
On ubuntu under python 2.6 I get the error:
from soaplib.wsgi_soap import SimpleWSGISoapApp
ImportError: No module named w... | Python can't import module named wsgi_soap from the soaplib | This code works on Debian under Python 2.5 but doesn't on Ubuntu under Python 2.6:
from soaplib.wsgi_soap import SimpleWSGISoapApp
On ubuntu under python 2.6 I get the error:
from soaplib.wsgi_soap import SimpleWSGISoapApp
ImportError: No module named wsgi_soap
| [
"Don't call your own file soaplib.py. Rename it to something else. Also, remove the soaplib.pyc file that was generated.\n",
"I have used the latest version of the soaplib which is incompatible with the version 0.8.\n"
] | [
2,
0
] | [] | [] | [
"python",
"soap"
] | stackoverflow_0003422354_python_soap.txt |
Q:
Placing a Button in UltimateListCtrl using wxPython
I'm new to Pythong and I have been trying to get a button within UltimateListCtrl. I still can't figure out what I'm doing wrong. Here is my code:
try:
from agw import ultimatelistctrl as ULC
except ImportError: # if it's not there locally, try the wxPython l... | Placing a Button in UltimateListCtrl using wxPython | I'm new to Pythong and I have been trying to get a button within UltimateListCtrl. I still can't figure out what I'm doing wrong. Here is my code:
try:
from agw import ultimatelistctrl as ULC
except ImportError: # if it's not there locally, try the wxPython lib.
from wx.lib.agw import ultimatelistctrl as ULC
... | [
"button's parent should be your ULC i.e self.table\nSo change this line:\nbutton = wx.Button(self, id=wx.ID_ANY, label=\"Download\")\n\nto this:\nbutton = wx.Button(self.table, id=wx.ID_ANY, label=\"Download\")\n\nUpdate in response to comment:\nFor some reason it doesn't seem to be possible to delete all items in ... | [
3
] | [] | [] | [
"python",
"user_interface",
"wxpython"
] | stackoverflow_0003612934_python_user_interface_wxpython.txt |
Q:
writing large CSV files - dictionary based CSV writer seems to be the problem
I have a big bag of words array (words, and their counts) that I need to write to large flat csv file.
In testing with around 1000 or so words, this works just fine - I use the dictwriter as follows:
self.csv_out = csv.DictWriter(open(se... | writing large CSV files - dictionary based CSV writer seems to be the problem | I have a big bag of words array (words, and their counts) that I need to write to large flat csv file.
In testing with around 1000 or so words, this works just fine - I use the dictwriter as follows:
self.csv_out = csv.DictWriter(open(self.loc+'.csv','w'), quoting=csv.QUOTE_ALL, fieldnames=fields)
where fields is list... | [
"Ok, this is by no means the answer but i looked up the source-code for the csv module and noticed that there is a very expensive if not check in the module (§ 136-141 in python 2.6). \nif self.extrasaction == \"raise\":\n wrong_fields = [k for k in rowdict if k not in self.fieldnames]\n if wrong_fields:\n ... | [
2,
1
] | [] | [] | [
"csv",
"python"
] | stackoverflow_0003613457_csv_python.txt |
Q:
django middleware redirect infinite loop
I have a middleware that checks a session value and redirects depending that value. My problem is, it is creating an infinite redirect loop and I'm not sure why.
So, what I want to do is check to see if the value of the session visible is yes and if not redirect the user ... | django middleware redirect infinite loop | I have a middleware that checks a session value and redirects depending that value. My problem is, it is creating an infinite redirect loop and I'm not sure why.
So, what I want to do is check to see if the value of the session visible is yes and if not redirect the user to my test view.
Here is my middleware:
clas... | [
"You should at least avoid having it run when serving some media files:\nfrom django.conf import settings\n\nclass CheckStatus(object): \n\n def process_request(self, request): \n if request.user.is_authenticated(): \n if not request.path.startswith(settings.MEDIA_URL):\n ... | [
3
] | [] | [] | [
"django",
"django_middleware",
"python"
] | stackoverflow_0003613385_django_django_middleware_python.txt |
Q:
Wrappers around lambda expressions
I have functions in python that take two inputs, do some manipulations, and return two outputs. I would like to rearrange the output arguments, so I wrote a wrapper function around the original function that creates a new function with the new output order
def rotate(f):
h = ... | Wrappers around lambda expressions | I have functions in python that take two inputs, do some manipulations, and return two outputs. I would like to rearrange the output arguments, so I wrote a wrapper function around the original function that creates a new function with the new output order
def rotate(f):
h = lambda x,y: -f(x,y)[1], f(x,y)[0]
re... | [
"You need to add parentheses around the lambda expression:\nh = lambda x,y: (-f(x,y)[1], f(x,y)[0])\n\nOtherwise, Python interprets the code as:\nh = (lambda x,y: -f(x,y)[1]), f(x,y)[0]\n\nand h is a 2-tuple.\n",
"There is problem with precedence. Just use additional parentheses:\ndef rotate(f):\n h = lambda x... | [
7,
5
] | [] | [] | [
"lambda",
"python"
] | stackoverflow_0003613981_lambda_python.txt |
Q:
Google Appengine: objects passed to a template changes their addresses in memory
I query an array of objects from DB, then compare addresses of the objects in Model and in View. They differs! Why? I want access the same objects as from template as from business logics code.
I wouldn't ask for it but it really both... | Google Appengine: objects passed to a template changes their addresses in memory | I query an array of objects from DB, then compare addresses of the objects in Model and in View. They differs! Why? I want access the same objects as from template as from business logics code.
I wouldn't ask for it but it really bother me because function calls are disallowed in Django-styled templates and I even can'... | [
"When you use the query iterator, you in fact do several fetches in sequence, each one will result in a new model instance.\nInstead of doing:\ncats = db.GqlQuery(\"SELECT * FROM Cats\")\nfor cat in cats:\n ...\n\n...do this instead:\ncats = db.GqlQuery(\"SELECT * FROM Cats\").fetch(50)\nfor cat in cats:\n ..... | [
4
] | [] | [] | [
"google_app_engine",
"python",
"templates"
] | stackoverflow_0003613573_google_app_engine_python_templates.txt |
Q:
AttributeError when unpickling an object
I'm trying to pickle an instance of a class in one module, and unpickle it in another.
Here's where I pickle:
import cPickle
def pickleObject():
object = Foo()
savefile = open('path/to/file', 'w')
cPickle.dump(object, savefile, cPickle.HIGHEST_PROTOCOL)
class ... | AttributeError when unpickling an object | I'm trying to pickle an instance of a class in one module, and unpickle it in another.
Here's where I pickle:
import cPickle
def pickleObject():
object = Foo()
savefile = open('path/to/file', 'w')
cPickle.dump(object, savefile, cPickle.HIGHEST_PROTOCOL)
class Foo(object):
(...)
and here's where I tr... | [
"class Foo must be importable via the same path in the unpickling environment so that the pickled object can be reinstantiated. \nI think your issue is that you define Foo in the module that you are executing as main (__name__ == \"__main__\"). Pickle will serialize the path (not the class object/definition!!!) t... | [
25,
3
] | [] | [] | [
"pickle",
"python"
] | stackoverflow_0003614379_pickle_python.txt |
Q:
import django settings in app-engine-patch
I have a problem with Django settings.
My app runs with app-engine-patch.
I added a script that runs without django, and is reached directly via the app.yaml handlers.
I then get this error:
File "/base/python_runtime/python_lib/versions/third_party/django-0.96/django/con... | import django settings in app-engine-patch | I have a problem with Django settings.
My app runs with app-engine-patch.
I added a script that runs without django, and is reached directly via the app.yaml handlers.
I then get this error:
File "/base/python_runtime/python_lib/versions/third_party/django-0.96/django/conf/__init__.py", line 53, in _import_settings
rai... | [
"Change\nos.environ['DJANGO_SETTINGS_MODULE'] = 'settings.py' \n\nto\nos.environ['DJANGO_SETTINGS_MODULE'] = 'settings'\n\nThe value of the DJANGO_SETTINGS_MODULE is the name of the module (ie, as you would write it in an import statement in a Python script), not the path to the module.\n",
"Thanks to another que... | [
3,
0
] | [] | [] | [
"app_engine_patch",
"django",
"google_app_engine",
"python"
] | stackoverflow_0003579544_app_engine_patch_django_google_app_engine_python.txt |
Q:
How to check if key exists in datastore without returning the object
I want to be able to check if a key_name for my model exists in the datastore.
My code goes:
t=MyModel.get_by_key_name(c)
if t==None:
#key_name does not exist
I don't need the object, so is there a way (which would be faster and cost... | How to check if key exists in datastore without returning the object | I want to be able to check if a key_name for my model exists in the datastore.
My code goes:
t=MyModel.get_by_key_name(c)
if t==None:
#key_name does not exist
I don't need the object, so is there a way (which would be faster and cost less resource) to check if the object exist without returning it? I only ... | [
"You can't avoid get_by_key_name() or key-related equivalents to check if a key exists. Your code is fine.\n",
"The API talks about Model.all(keys_only=False) returning all the key names when keys_only is set to True\nLook at the query that is fired for this, and then you can write a query similar to this but j... | [
4,
1
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0003614521_google_app_engine_python.txt |
Q:
Django failing to route url (simple question)
I'm doing something stupid, and I'm not sure what it is. I have a the following urls.py in the root of my django project:
from django.conf.urls.defaults import *
from django.conf import settings
urlpatterns = patterns('',
(r'^$', include('preview_signup.urls')),
... | Django failing to route url (simple question) | I'm doing something stupid, and I'm not sure what it is. I have a the following urls.py in the root of my django project:
from django.conf.urls.defaults import *
from django.conf import settings
urlpatterns = patterns('',
(r'^$', include('preview_signup.urls')),
)
In my preview_signup module (django app) I have ... | [
"This code should work:\nurlpatterns = patterns('',\n (r'^', include('preview_signup.urls')),\n)\n\n$ (end of line) just removed.\n",
"When something goes wrong (or even if it doesn't), thoroughly read the django docs. Here's an excerpt from the aforementioned link:\nfrom django.conf.urls.defaults import *\n\... | [
4,
1
] | [] | [] | [
"django",
"django_urls",
"python"
] | stackoverflow_0003614594_django_django_urls_python.txt |
Q:
Python: open a file *with* script?
I have a python script bundled into a application (I'm on a mac) and have the application set to be able to open .zip files. But when I say "open foo.zip with bar.py" how do I access the file that I have passed to it?
Additional info:
Using tkinter.
What's a good way to debug th... | Python: open a file *with* script? | I have a python script bundled into a application (I'm on a mac) and have the application set to be able to open .zip files. But when I say "open foo.zip with bar.py" how do I access the file that I have passed to it?
Additional info:
Using tkinter.
What's a good way to debug this, as there is no terminal to pass info... | [
"You should be using sys.argv[1]\ntask = sys.argv[1].decode('utf-8')\nif task == u'uppercase':\n pass\nelif task == u'openitems':\n item_paths = sys.argv[2:]\n for itempath in item_paths:\n itempath = itempath.decode('utf-8')\n\n",
"If I'm not greatly mistaken, it should pass the name of the file ... | [
1,
0
] | [] | [] | [
"macos",
"python",
"tkinter"
] | stackoverflow_0003614609_macos_python_tkinter.txt |
Q:
How do I serve and log my current directory with a python web server?
I need to create a webserver that will respond to GET requests by serving pages from a specified folder, as well as log the pages the user is GETting, and the IP of the user.
The main trouble comes from me not knowing how to serve the directory ... | How do I serve and log my current directory with a python web server? | I need to create a webserver that will respond to GET requests by serving pages from a specified folder, as well as log the pages the user is GETting, and the IP of the user.
The main trouble comes from me not knowing how to serve the directory listing to the user when overriding the do_GET method. Here is my code so ... | [
"You need to use dir_listing() to list directories.\nRather than writing it here, I would suggest you look at the python cookbook/ recipes for detailed directions and understanding.\n\nhttp://code.activestate.com/recipes/392879-my-first-application-server/\n\n"
] | [
1
] | [] | [] | [
"get",
"logging",
"python",
"webserver"
] | stackoverflow_0003614729_get_logging_python_webserver.txt |
Q:
How to apply a "mixin" class to an old-style base class
I've written a mixin class that's designed to be layered on top of a new-style class, for example via
class MixedClass(MixinClass, BaseClass):
pass
What's the smoothest way to apply this mixin to an old-style class? It is using a call to super in its __... | How to apply a "mixin" class to an old-style base class | I've written a mixin class that's designed to be layered on top of a new-style class, for example via
class MixedClass(MixinClass, BaseClass):
pass
What's the smoothest way to apply this mixin to an old-style class? It is using a call to super in its __init__ method, so this will presumably (?) have to change, bu... | [
"\nThis class variable would be set by\n old_style_mix as part of the mixing\n process.\n\n...I assume you mean: \"...on the class it's decorating...\" as opposed to \"on the class that is its argument\" (the latter would be a disaster).\n\nold_style_mix would just update the\n class dictionary of e.g.\n MixedW... | [
1
] | [] | [] | [
"inheritance",
"mixins",
"python"
] | stackoverflow_0003614792_inheritance_mixins_python.txt |
Q:
Switch between version of Python?
I just installed Python 2.7, but IDLE is currently broken on OS X 10.6.4. Is there anyway I can revert to the earlier, Apple installed, version? A simple PATH adjustment, perhaps?
Right now $PATH looks like this for me:
/Library/Frameworks/Python.framework/Versions/2.7/bin:/usr/bi... | Switch between version of Python? | I just installed Python 2.7, but IDLE is currently broken on OS X 10.6.4. Is there anyway I can revert to the earlier, Apple installed, version? A simple PATH adjustment, perhaps?
Right now $PATH looks like this for me:
/Library/Frameworks/Python.framework/Versions/2.7/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/... | [
"/usr/bin/python is where Apple puts (the symlink to) the system version of Python -- so, just remove that first item from the PATH, and you should be fine.\n",
"The default version is in /usr/bin, so just do a\nexport PATH=/usr/bin:$PATH\n\n(Adjust the command according to your choice of shell)\nIt is simply a m... | [
2,
2,
0
] | [] | [] | [
"macos",
"path",
"python"
] | stackoverflow_0003614898_macos_path_python.txt |
Q:
Python raw_input("") error
I am writing a simple commandline script that uses raw_input, but it doesn't seem to work.
This code:
print "Hello!"
raw_input("")
Produces this error:
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
raw_input("")
TypeError: 'str' object is not callable
I ha... | Python raw_input("") error | I am writing a simple commandline script that uses raw_input, but it doesn't seem to work.
This code:
print "Hello!"
raw_input("")
Produces this error:
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
raw_input("")
TypeError: 'str' object is not callable
I have never encountered this error ... | [
"Works fine as presented, e.g. in an interpreter prompt in any Python 2 version:\n>>> print \"Hello!\"\nHello!\n>>> raw_input(\"\")\nbah\n'bah'\n>>> \n\nwhere bah is what I typed after the code you gave in response to the empty-prompt;-).\nThe only explanation for the error you mention is that you've performed othe... | [
2,
2
] | [] | [] | [
"python",
"python_2.6",
"raw_input",
"windows"
] | stackoverflow_0003615228_python_python_2.6_raw_input_windows.txt |
Q:
python: return value from __new__
EDIT
I actually called object.__new__(cls), and I didn't realize that by this I built an object of class cls! Thanks for pointing this out to me.
ORIGINAL QUESTION
The documentation says
If new() does not return an
instance of cls, then the new
instance’s init() method will ... | python: return value from __new__ | EDIT
I actually called object.__new__(cls), and I didn't realize that by this I built an object of class cls! Thanks for pointing this out to me.
ORIGINAL QUESTION
The documentation says
If new() does not return an
instance of cls, then the new
instance’s init() method will not
be invoked.
However, when I retu... | [
"Cannot reproduce your observation:\n>>> class cls(object):\n... def __new__(cls):\n... return object.__new__(object)\n... def __init__(self):\n... print 'in __init__'\n... \n>>> x = cls()\n>>> \n\nAs you see, cls.__init__ isn't executing.\nHow are you calling object.__new__ (and, btw, why are you?-).\n... | [
4
] | [] | [] | [
"constructor",
"python"
] | stackoverflow_0003615299_constructor_python.txt |
Q:
Python 2.7, ValueError when dealing with HTMLParser
First time working with the HTMLParser module. Trying to use standard string formatting on the ouput, but it's giving me an error. The following code:
import urllib2
from HTMLParser import HTMLParser
class LinksParser(HTMLParser):
def __init__(self, url):
... | Python 2.7, ValueError when dealing with HTMLParser | First time working with the HTMLParser module. Trying to use standard string formatting on the ouput, but it's giving me an error. The following code:
import urllib2
from HTMLParser import HTMLParser
class LinksParser(HTMLParser):
def __init__(self, url):
HTMLParser.__init__(self)
req = urllib2.url... | [
"print(\"Found Link --> {]\".format(value)) \n\nShould instead be:\nprint(\"Found Link --> {}\".format(value))\n\nYou used a square bracket instead of a brace.\n",
"This format string looks broken: print(\"Found Link --> {]\".format(value)). You need to change this to print(\"Found Link --> {key}\".format(key = v... | [
2,
0,
0
] | [] | [] | [
"html_parsing",
"python"
] | stackoverflow_0003615447_html_parsing_python.txt |
Q:
Is there a way to serve up a Python dictionary to a compatible type in Visual Basic 6 using win32com?
Is there a way to serve up a Python dictionary to a compatible type in Visual Basic 6 using win32com?
A:
I shudder to think of the requirements for this project. I feel sorry for you already.
Since there is no ... | Is there a way to serve up a Python dictionary to a compatible type in Visual Basic 6 using win32com? | Is there a way to serve up a Python dictionary to a compatible type in Visual Basic 6 using win32com?
| [
"I shudder to think of the requirements for this project. I feel sorry for you already.\nSince there is no dictionary type in COM, my guess is that you'll have to pass it out as two SAFEARRAYS and join it back together inside VB. That's the approach I would take.\nI found this helpful, especially the second half:... | [
0
] | [] | [] | [
"python",
"vb6",
"win32com"
] | stackoverflow_0003613403_python_vb6_win32com.txt |
Q:
Why is there so many Pythons installed in /usr/bin for my Snow Leopard? What decides which one is the System Python?
Why is there so many Pythons installed in /usr/bin for my Snow Leopard? What decides which one is the System Python?
When I simply type "python" it is 2.6.1 ~ but this doesn't seem to be the "System... | Why is there so many Pythons installed in /usr/bin for my Snow Leopard? What decides which one is the System Python? | Why is there so many Pythons installed in /usr/bin for my Snow Leopard? What decides which one is the System Python?
When I simply type "python" it is 2.6.1 ~ but this doesn't seem to be the "System Python", why not? How does one change system Python and what are the drawbacks?
| [
"My snow leopard only has python 2.5 and 2.6 installed, so it's not that many. You may have additional pythons installed (i.e. python3.0), either system wide (in /usr/bin/) or through macports (/opt/local). \nThe default system python is defined through a setting,\ndefaults write com.apple.versioner.python Version ... | [
3
] | [] | [] | [
"macos",
"osx_snow_leopard",
"python",
"system"
] | stackoverflow_0003615630_macos_osx_snow_leopard_python_system.txt |
Q:
Would someone explain to me why type(foo)(bar) is so heavily discouraged?
I have a dict of configuration variables that looks something like this:
self.config = {
"foo": "abcdef",
"bar": 42,
"xyz": True
}
I want to be able to update these variables from user input (which, in this case, will always be ... | Would someone explain to me why type(foo)(bar) is so heavily discouraged? | I have a dict of configuration variables that looks something like this:
self.config = {
"foo": "abcdef",
"bar": 42,
"xyz": True
}
I want to be able to update these variables from user input (which, in this case, will always be in the form of a string). The problem I'm facing is obvious, and my first solut... | [
"Not all types support the idiom \"call the type with a string to make a new instance of that type\". However, if you ensure you only have such types in your config dict (with a sanity check at init time maybe), and put suitable try/except protection around your conversion attempt (to deal with user errors such as... | [
5,
0
] | [] | [] | [
"python",
"types",
"user_input"
] | stackoverflow_0003614246_python_types_user_input.txt |
Q:
How do you make a choices field in django with an editable "other" option?
(
('one', 'One'),
('two', 'Two'),
('other', EDITABLE_HUMAN_READABLE_CHOICE),
)
So what I would like is a choices field with some common choices that are used frequently, but still be able to have the option of filling in a cus... | How do you make a choices field in django with an editable "other" option? | (
('one', 'One'),
('two', 'Two'),
('other', EDITABLE_HUMAN_READABLE_CHOICE),
)
So what I would like is a choices field with some common choices that are used frequently, but still be able to have the option of filling in a custom human readable value.
Is this possible or is there some better way of doing ... | [
"One way to do this would be to use a custom ModelForm for admin. This form can have two fields - one that accepts a set of predefined choices and another one that accepts arbitrary values. In the clean() method you can ensure that only one of these has been selected. \nIf you are particular about how the UI should... | [
7,
3
] | [] | [] | [
"django",
"python"
] | stackoverflow_0003614237_django_python.txt |
Q:
How to assure that filehandle.write() does not fail due to str/bytes conversions issues?
I need to detect if a filehandle is using binary mode or text mode - this is required in order to be able to encode/decode str/bytes. How can I do that?
When using binary mode myfile.write(bytes) works, and when in text mode m... | How to assure that filehandle.write() does not fail due to str/bytes conversions issues? | I need to detect if a filehandle is using binary mode or text mode - this is required in order to be able to encode/decode str/bytes. How can I do that?
When using binary mode myfile.write(bytes) works, and when in text mode myfile.write(str) works.
The idea is that I need to know this in order to be able to encode/dec... | [
"http://docs.python.org/library/stdtypes.html#file.mode\n>>> f = open(\"blah.txt\", \"wb\")\n>>> f\n<open file 'blah.txt', mode 'wb' at 0x0000000001E44E00>\n>>> f.mode\n'wb'\n>>> \"b\" in f.mode\nTrue\n\nWith this caveat:\n\nfile.mode\nThe I/O mode for the file. If the file was created using the open()\nbuilt-in fu... | [
4,
1
] | [] | [] | [
"file_io",
"filehandle",
"python",
"python_3.x"
] | stackoverflow_0003611102_file_io_filehandle_python_python_3.x.txt |
Q:
How to select questions which have no answers, in sqlalchemy
I've two classes: Question and Answer. A question may have 0 or many answers.
class Question(Base):
__tablename__ = "questions"
answers = relationship('Answer', backref='question',
primaryjoin="Question.id==Answer.ques... | How to select questions which have no answers, in sqlalchemy | I've two classes: Question and Answer. A question may have 0 or many answers.
class Question(Base):
__tablename__ = "questions"
answers = relationship('Answer', backref='question',
primaryjoin="Question.id==Answer.question_id")
class Answer(Base):
__tablename__ = "answers"
Now ... | [
"Just use\nsession.query(Question).filter(Question.answers == None).all()\n\nwhich basically is a NULL check (common filter operators).\nHere's a gist example: http://gist.github.com/560473\nThe query generates the following SQL:\nSELECT questions.id AS questions_id \nFROM questions \nWHERE NOT (EXISTS (SELECT 1 \n... | [
3,
0
] | [] | [] | [
"python",
"sqlalchemy"
] | stackoverflow_0003616530_python_sqlalchemy.txt |
Q:
Have I organised my django app correctly?
I'm in a situation where I need to merge two Django apps into a single, re-usable app. Neither are particularly large, but they are certainly not trivial apps and to preserve readability / sanity I'm trying to keep the two apps separated to some extent.
I could set up eac... | Have I organised my django app correctly? | I'm in a situation where I need to merge two Django apps into a single, re-usable app. Neither are particularly large, but they are certainly not trivial apps and to preserve readability / sanity I'm trying to keep the two apps separated to some extent.
I could set up each app as a sub-package (which would be a python... | [
"Flat is better than nested.\nA \"composite\" application, built from two peer applications is fine. It works well.\nAnd it promotes reuse by allowing the two components to be \"plug-and-play\" options in the larger application. \nDon't nest things unless you're forced to. The number one reason forcing you to ne... | [
2,
1,
1
] | [] | [] | [
"django",
"package",
"python",
"structure"
] | stackoverflow_0003611631_django_package_python_structure.txt |
Q:
How to create an in-memory zip file with directories without touching the disk?
In a python web application, I'm packaging up some stuff in a zip-file. I want to do this completely on the fly, in memory, without touching the disk. This goes fine using ZipFile.writestr as long as I'm creating a flat directory struc... | How to create an in-memory zip file with directories without touching the disk? | In a python web application, I'm packaging up some stuff in a zip-file. I want to do this completely on the fly, in memory, without touching the disk. This goes fine using ZipFile.writestr as long as I'm creating a flat directory structure, but how do I create directories inside the zip?
I'm using python2.4.
http://doc... | [
"What 'theomega' said in the comment to my original post, adding a '/' in the filename does the trick. Thanks!\nfrom zipfile import ZipFile\nfrom StringIO import StringIO\n\ninMemoryOutputFile = StringIO()\n\nzipFile = ZipFile(inMemoryOutputFile, 'w') \nzipFile.writestr('OEBPS/content.xhtml', 'hello world')\nzipFil... | [
33,
1
] | [] | [] | [
"python"
] | stackoverflow_0003610221_python.txt |
Q:
A better way to assign list into a var
Was coding something in Python. Have a piece of code, wanted to know if it can be done more elegantly...
# Statistics format is - done|remaining|200's|404's|size
statf = open(STATS_FILE, 'r').read()
starf = statf.strip().split('|')
done = int(starf[0])
rema = int(starf[1])
... | A better way to assign list into a var | Was coding something in Python. Have a piece of code, wanted to know if it can be done more elegantly...
# Statistics format is - done|remaining|200's|404's|size
statf = open(STATS_FILE, 'r').read()
starf = statf.strip().split('|')
done = int(starf[0])
rema = int(starf[1])
succ = int(starf[2])
fails = int(starf[3])
... | [
"done, rema, succ, fails, size, ... = [int(x) for x in starf]\n\nBetter:\nlabels = (\"done\", \"rema\", \"succ\", \"fails\", \"size\")\n\ndata = dict(zip(labels, [int(x) for x in starf]))\n\nprint data['done']\n\n",
"What I don't like about the answers so far is that they stick everything in one expression. You ... | [
6,
5,
4,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0003613073_python.txt |
Q:
opening file: Writing is invalid mode
When executing:
path=os.path.dirname(__file__)+'/log.txt'
log=open(path,"w",encoding='utf-8')
I get:
log=open(path,'w',encoding='utf-8')
File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 1203, in __init__
raise IOError('invalid mode... | opening file: Writing is invalid mode | When executing:
path=os.path.dirname(__file__)+'/log.txt'
log=open(path,"w",encoding='utf-8')
I get:
log=open(path,'w',encoding='utf-8')
File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 1203, in __init__
raise IOError('invalid mode: %s' % mode)
IOError: invalid mode: w
I'm... | [
"\nApp Engine's Python runtime supports Python 2.5 – newer versions of Python, including Python 2.6, are not currently supported. For security reasons, some Python modules written in C won't run in App Engine's sandbox. Because App Engine doesn't support writing to disk or opening direct network connections, other ... | [
3,
3
] | [] | [] | [
"app_engine_patch",
"google_app_engine",
"python"
] | stackoverflow_0003616964_app_engine_patch_google_app_engine_python.txt |
Q:
Iterating over dictionary items(), values(), keys() in Python 3
If I understand correctly, in Python 2, iter(d.keys()) was the same as d.iterkeys(). But now, d.keys() is a view, which is in between the list and the iterator. What's the difference between a view and an iterator?
In other words, in Python 3, what's ... | Iterating over dictionary items(), values(), keys() in Python 3 | If I understand correctly, in Python 2, iter(d.keys()) was the same as d.iterkeys(). But now, d.keys() is a view, which is in between the list and the iterator. What's the difference between a view and an iterator?
In other words, in Python 3, what's the difference between
for k in d.keys()
f(k)
and
for k in iter(... | [
"I'm not sure if this is quite an answer to your questions but hopefully it explains a bit about the difference between Python 2 and 3 in this regard.\nIn Python 2, iter(d.keys()) and d.iterkeys() are not quite equivalent, although they will behave the same. In the first, keys() will return a copy of the dictionary... | [
71
] | [] | [] | [
"dictionary",
"iterator",
"python",
"python_3.x"
] | stackoverflow_0003616721_dictionary_iterator_python_python_3.x.txt |
Q:
part of GtkLabel clickable
How to do, that just a part of GtkLabel has a clicked event and calls a function.
I make a twitter client, witch shows tweets and i would like to, when in the tweet is a # hashtag and I click it, the application shows a new window with search of this #hashtag. and I dont know how to do t... | part of GtkLabel clickable | How to do, that just a part of GtkLabel has a clicked event and calls a function.
I make a twitter client, witch shows tweets and i would like to, when in the tweet is a # hashtag and I click it, the application shows a new window with search of this #hashtag. and I dont know how to do that just the #hashtag would invo... | [
"You can surround the clickable part in <a> tags and connect to the activate-link signal. \nHere is an example:\nimport gtk\n\ndef hashtag_handler(label, uri):\n print('You clicked on the tag #%s' % uri)\n return True # to indicate that we handled the link request\n\nwindow = gtk.Window()\nlabel = gtk.Label()... | [
3
] | [] | [] | [
"gtk",
"pygtk",
"python"
] | stackoverflow_0003608207_gtk_pygtk_python.txt |
Q:
returning matches from an unknown number of python lists
I have a list which contains 1-5 lists within it. I want to return only the values which appear in all the lists. I can easily create an exception for it there is only one list, but I can't think of a way round it when there are an multiple (unknown number o... | returning matches from an unknown number of python lists | I have a list which contains 1-5 lists within it. I want to return only the values which appear in all the lists. I can easily create an exception for it there is only one list, but I can't think of a way round it when there are an multiple (unknown number of) lists. For example:
[[1,2,3,4],[2,3,7,8],[2,3,6,9],[1,2,5,7... | [
"reduce(set.intersection, (set(x) for x in [[1,2,3,4],[2,3,7,8],[2,3,6,9],[1,2,5,7]]))\n\n",
"You can use frozenset.intersection (or set.intersection if you prefer):\n>>> l = [[1,2,3,4],[2,3,7,8],[2,3,6,9],[1,2,5,7]]\n>>> frozenset.intersection(*(frozenset(x) for x in l))\nfrozenset({2})\n\nAdd a call to list if ... | [
4,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0003617179_python.txt |
Q:
Python socket module: http proxy
Hello I'm trying to use protected http socks server with socket module as in the code shown below
>>> import socket
>>> s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
>>> host = 'http://user:pass@server.com'
>>> port = 8888
>>> s.bind((host, port))
It gives me error:
soc... | Python socket module: http proxy | Hello I'm trying to use protected http socks server with socket module as in the code shown below
>>> import socket
>>> s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
>>> host = 'http://user:pass@server.com'
>>> port = 8888
>>> s.bind((host, port))
It gives me error:
socket.gaierror: [Errno -2] Name or servi... | [
"I believe your problem is because your host is malformed. The Socket host is just a name not a protocol. Your host should be something like:\nhost = 'server.com'\n\nThe authentication should be done after you connect, i.e., the first message you send is the authentication.\nI can't give you the specifics of how to... | [
1
] | [] | [] | [
"proxy",
"python",
"sockets"
] | stackoverflow_0003617376_proxy_python_sockets.txt |
Q:
Representing an immutable hierarchy using tuples
I am trying to represent a hierarchy using namedtuple. Essentially, every node has three attributes relevant to the hierarchy: parent, leftChild and rightChild (they also have some attributes that carry the actual information, but that is not important for the quest... | Representing an immutable hierarchy using tuples | I am trying to represent a hierarchy using namedtuple. Essentially, every node has three attributes relevant to the hierarchy: parent, leftChild and rightChild (they also have some attributes that carry the actual information, but that is not important for the question). The problem is the circular reference between pa... | [
"No, there is not.\n",
"Remove parent field. You can still implement any tree-manipulation operations efficient without keeping reference to parent node.\n",
"One trick is not to use an object reference, but instead, a symbolic ID that you maintain in a hash table.\n"
] | [
2,
0,
0
] | [] | [] | [
"hierarchy",
"python",
"tuples"
] | stackoverflow_0003616822_hierarchy_python_tuples.txt |
Q:
Does Python's urllib2 have a gethostbyname function?
I need to get a requested host's ip address using urllib2 like:
import urllib2
req = urllib2.Request('http://www.example.com/')
r = urllib2.urlopen(req)
Are there any functions like ip = urllib2.gethostbyname(req)?
A:
You can use:
import socket
socket.getho... | Does Python's urllib2 have a gethostbyname function? | I need to get a requested host's ip address using urllib2 like:
import urllib2
req = urllib2.Request('http://www.example.com/')
r = urllib2.urlopen(req)
Are there any functions like ip = urllib2.gethostbyname(req)?
| [
"You can use:\nimport socket\nsocket.gethostbyname('www.google.com')\n\nthis will return the IP address for the host. Don't pass 'http://www.google.com'. That will not work.\n",
"There's a socket.gethostbyname function which will resolve the host names if that's what you mean.\nAlthough if you already have a conn... | [
2,
1
] | [] | [] | [
"gethostbyname",
"python",
"urllib2"
] | stackoverflow_0003617616_gethostbyname_python_urllib2.txt |
Q:
Execute a python command within vim and getting the output
When Vim is compiled with Python support, you can script Vim with Python using the :python command. How would I go about using this to execute the command and insert the result under the cursor? For example, if I were to execute :python import os; os.listd... | Execute a python command within vim and getting the output | When Vim is compiled with Python support, you can script Vim with Python using the :python command. How would I go about using this to execute the command and insert the result under the cursor? For example, if I were to execute :python import os; os.listdir('aDirectory')[0], I would want the first filename returned to... | [
":,!python -c \"import os; print os.listdir('aDirectory')[0]\"\n\n",
"The following works fine for me:\nwrite the python code you want to execute in the line you want.\nimport os\nprint(os.listdir('.'))\n\nafter that visually select the lines you want to execute in python \n:'<,'>!python\n\nand after that the pyt... | [
5,
3,
2,
0
] | [] | [] | [
"python",
"vim"
] | stackoverflow_0003608742_python_vim.txt |
Q:
Getting python exceptions printed the normal way with PyObjC
I'm getting errors like this:
2010-07-13 20:43:15.131
Python[1527:60f] main: Caught
OC_PythonException: :
LoginMenuSet instance has no attribute
'play_sound'
That's with this code:
@try {
[section loop]; //Loop through section
} @catch (NSE... | Getting python exceptions printed the normal way with PyObjC | I'm getting errors like this:
2010-07-13 20:43:15.131
Python[1527:60f] main: Caught
OC_PythonException: :
LoginMenuSet instance has no attribute
'play_sound'
That's with this code:
@try {
[section loop]; //Loop through section
} @catch (NSException *exception) {
NSLog(@"Caught %@: %@", [exception name... | [
"One trick to see Python exceptions is to call objc.setVerbose(1). This makes PyObjC slightly more verbose and causes it to print Python stack traces when converting exceptions from Python to Objective-C.\n",
"Here's my own solution:\nIn Objective-C class:\n@try {\n [section loop]; //Loop through section\n... | [
9,
0
] | [] | [] | [
"exception",
"exception_handling",
"objective_c",
"pyobjc",
"python"
] | stackoverflow_0003240867_exception_exception_handling_objective_c_pyobjc_python.txt |
Q:
How similar are Python, jQuery, C syntax wise?
I'm trying to get a sense of the similarities between languages in syntax. How similar are Python, jQuery and C? I started programming in Actionscript 3 and then moved on to Javascript , then went on and learned Prototype, and then I started using jQuery and found tha... | How similar are Python, jQuery, C syntax wise? | I'm trying to get a sense of the similarities between languages in syntax. How similar are Python, jQuery and C? I started programming in Actionscript 3 and then moved on to Javascript , then went on and learned Prototype, and then I started using jQuery and found that the syntax is very different. So is jQuery more li... | [
"C is much different from the languages you've asked about. Remember that C isn't an interpreted language and will not be treated as such in your code. In short, you're up for a lot more material to learn --while dealing with C-- in terms of things like memory management and semantics than the other languages.\nI... | [
8,
3,
3
] | [] | [] | [
"c",
"javascript",
"jquery",
"python",
"syntax"
] | stackoverflow_0003615122_c_javascript_jquery_python_syntax.txt |
Q:
Django QuerySet .defer() problem - bug or feature?
An example is better than a thousand words:
In [3]: User.objects.filter(id=19)[0] == User.objects.filter(id=19)[0]
Out[3]: True
In [4]: User.objects.filter(id=19)[0] == User.objects.filter(id=19).defer('email')[0]
Out[4]: False
Does it work like this... | Django QuerySet .defer() problem - bug or feature? | An example is better than a thousand words:
In [3]: User.objects.filter(id=19)[0] == User.objects.filter(id=19)[0]
Out[3]: True
In [4]: User.objects.filter(id=19)[0] == User.objects.filter(id=19).defer('email')[0]
Out[4]: False
Does it work like this on purpose ?
Subquestion: is there any simple way to ge... | [
"Deferred queries return a different class, provided by the deferred_class_factory:\n# in db/models/query_utils.py\n\ndef deferred_class_factory(model, attrs):\n \"\"\"\n Returns a class object that is a copy of \"model\" with the specified \"attrs\"\n being replaced with DeferredAttribute objects. The \"p... | [
4,
0
] | [] | [] | [
"django",
"django_models",
"orm",
"python"
] | stackoverflow_0003617886_django_django_models_orm_python.txt |
Q:
Python - Regular Expression Wildcards from Socket data?
I have a question regarding regular expressions in Python. The expressions are composed of data that would be read from a server, connected via socket. I'm trying to use and read wildcards in these expressions. Example: Let's say I run a chat server. When a m... | Python - Regular Expression Wildcards from Socket data? | I have a question regarding regular expressions in Python. The expressions are composed of data that would be read from a server, connected via socket. I'm trying to use and read wildcards in these expressions. Example: Let's say I run a chat server. When a message is recieved, the server sends to all clients (JSmith s... | [
"If the data is always that simple, you do not need to use regular expresssions at all:\nline = 'JSmith sends \"Hello everyone!\"'\nuser, data = line.split(' sends ', 1)\n# remove the quotes\ndata = data[1:-1]\nprint \"%s: %s\" % (user, data)\n\nWith regular expressions (using named expressions):\nimport re\nline =... | [
1
] | [] | [] | [
"chat",
"python",
"regex",
"wildcard"
] | stackoverflow_0003611573_chat_python_regex_wildcard.txt |
Q:
How to insert bulk data in Google App Engine Datastore?
I have some CSV files for cities,state and countries with their ids, names etc. I want to put all this data into Google app engine datastore.
Can someone please suggest an efficient way of doing this on development server as well as on the production server?... | How to insert bulk data in Google App Engine Datastore? | I have some CSV files for cities,state and countries with their ids, names etc. I want to put all this data into Google app engine datastore.
Can someone please suggest an efficient way of doing this on development server as well as on the production server?
Thanks in advance.
| [
"You're in luck. The functionality you described is baked into appcfg.py:\nhttp://code.google.com/appengine/docs/python/tools/uploadingdata.html\n"
] | [
3
] | [] | [] | [
"google_app_engine",
"google_cloud_datastore",
"python"
] | stackoverflow_0003618147_google_app_engine_google_cloud_datastore_python.txt |
Q:
How to empty a Python dict without doing my_dict = {}?
If the my_dict variable is global, you can't do:
my_dict = {}
that just create a new reference in the local scope.
Also, I found disgusting using the global keyword, so how can I empty a dict using its methods?
A:
Use the clear() method?
Documentation - (do... | How to empty a Python dict without doing my_dict = {}? | If the my_dict variable is global, you can't do:
my_dict = {}
that just create a new reference in the local scope.
Also, I found disgusting using the global keyword, so how can I empty a dict using its methods?
| [
"Use the clear() method?\nDocumentation - (docs.python.org)\n",
"you mean like .clear() ?\n",
"my_dict.clear()\n\n",
"my_dict.clear()\n"
] | [
8,
3,
1,
1
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0003618612_dictionary_python.txt |
Q:
python: defining registry in base class
I'm implementing enumeration using a base class that defines a variety of methods. The actual enumerations are subclasses of that, with no additional methods or attributes. (Each subclass is populated with its own values using the constructor defined in the base class).
I us... | python: defining registry in base class | I'm implementing enumeration using a base class that defines a variety of methods. The actual enumerations are subclasses of that, with no additional methods or attributes. (Each subclass is populated with its own values using the constructor defined in the base class).
I use a registry (a class attribute that stores a... | [
"As you already have a metaclass you might as well use it to put a add a separate _registry attribute to each subclass automatically.\nclass IterRegistry(type):\n def __new__(cls, name, bases, attr):\n attr['_registry'] = {} # now every class has it's own _registry\n return type.__new__(cls, name, ... | [
3,
1,
0
] | [] | [] | [
"attributes",
"class",
"python"
] | stackoverflow_0003617996_attributes_class_python.txt |
Q:
Python & MySQL: Matching element from list of with a record from database
I have a list of objects which I built with a class, and one of the properties of this class is the variable "tag". (below called tagList)
I am trying to match this variable from a record that is bought in using MySQLdb. (below called record... | Python & MySQL: Matching element from list of with a record from database | I have a list of objects which I built with a class, and one of the properties of this class is the variable "tag". (below called tagList)
I am trying to match this variable from a record that is bought in using MySQLdb. (below called record)
I can output both to the screen, and see them identically by eye, although ca... | [
"You should use == instead of is.\n>>> 'abcdefgh'[2:6] is 'cdef'\nFalse\n>>> 'abcdefgh'[2:6] == 'cdef'\nTrue\n\nRelated Question\n\nPython '==' vs 'is' comparing strings, 'is' fails sometimes, why?\n\n"
] | [
1
] | [] | [] | [
"mysql",
"python"
] | stackoverflow_0003619048_mysql_python.txt |
Q:
oauth on appengine: access issue
I am having some difficulty accessing resources through OAuth on AppEngine.
My client application (on Linux using python-oauth) is able to retrieve a valid "access token" but when I try to access a protected resource (e.g. user = oauth.get_current_user()) , I get a oauth.OAuthRequ... | oauth on appengine: access issue | I am having some difficulty accessing resources through OAuth on AppEngine.
My client application (on Linux using python-oauth) is able to retrieve a valid "access token" but when I try to access a protected resource (e.g. user = oauth.get_current_user()) , I get a oauth.OAuthRequestError exception thrown.
headers: {'... | [
"I had a similar problem. Although i can't be more specific (I don't have the code with me) I can tell you that the problem is probably related to the request. Google App Engine is very picky with the request you make.\nTry sending the request body empty. For example, this is the usual call:\nimport httplib\nconnec... | [
0
] | [] | [] | [
"google_app_engine",
"oauth",
"python"
] | stackoverflow_0003586555_google_app_engine_oauth_python.txt |
Q:
Pygame - calling surface.convert() on animated sprite causes transparent background to become white
Everyone says to use .convert() on surfaces to speed up animations (which will be an issue with my game because it will be an MMO to some extent, so it might have a dozen or a couple dozen characters moving at the s... | Pygame - calling surface.convert() on animated sprite causes transparent background to become white | Everyone says to use .convert() on surfaces to speed up animations (which will be an issue with my game because it will be an MMO to some extent, so it might have a dozen or a couple dozen characters moving at the same time), the problem is that my transparent PNG images work great without convert but as soon as I use ... | [
"convert_alpha should do the trick \nhttp://www.pygame.org/docs/ref/surface.html#Surface.convert_alpha\n"
] | [
3
] | [] | [] | [
"geometry_surface",
"pygame",
"python",
"sprite",
"transparent"
] | stackoverflow_0003616903_geometry_surface_pygame_python_sprite_transparent.txt |
Q:
How do I embed a python library in a C++ app?
I've embedded python on a mobile device successfully, but now how do I include a python library such as urllib?
Additionally, how can I include my own python scripts without a PYTHONPATH?
(please note: python is not installed on this system)
A:
The easiest way is to ... | How do I embed a python library in a C++ app? | I've embedded python on a mobile device successfully, but now how do I include a python library such as urllib?
Additionally, how can I include my own python scripts without a PYTHONPATH?
(please note: python is not installed on this system)
| [
"The easiest way is to create a .zip file containing all the python code you need and add this to your process's PYTHONPATH environment variable (via setenv()) prior to initializing the embedded Python interpreter. Usage of .pyd libraries can be done similarly by adding them to the same directory as the .zip and in... | [
1
] | [] | [] | [
"embed",
"python"
] | stackoverflow_0003618281_embed_python.txt |
Q:
How to calculate timedelta until next execution for scheduled events
I have three lists that define when a task should be executed:
minute: A list of integers from 0-59 that represent the minutes of an hour of when execution should occur;
hour: A list of integers from 0-23 that represent the hours of a day of whe... | How to calculate timedelta until next execution for scheduled events | I have three lists that define when a task should be executed:
minute: A list of integers from 0-59 that represent the minutes of an hour of when execution should occur;
hour: A list of integers from 0-23 that represent the hours of a day of when execution should occur
day_of_week: A list of integers from 0-6, where S... | [
"Using dateutil (edited to address the OP's updated question):\nimport datetime\nimport random\nimport dateutil.relativedelta as dr\nimport itertools\n\nday_of_week = [1,3,5,6]\nhour = [1,10,15,17,20]\nminute = [4,34,51,58]\n\nnow=datetime.datetime.now()\ndeltas=[]\n\nfor min,hr,dow in itertools.product(minute,hour... | [
1,
0
] | [] | [] | [
"datetime",
"python"
] | stackoverflow_0003618538_datetime_python.txt |
Q:
PyQt application crashes after closing QMessagebox window
Here is the code of my simple tray application. It crashes with segfault when i call information window from context menu of application and then close it.
I've tryed different variants to find a reason of segfault, this is my last try.
#!/usr/bin/env pytho... | PyQt application crashes after closing QMessagebox window | Here is the code of my simple tray application. It crashes with segfault when i call information window from context menu of application and then close it.
I've tryed different variants to find a reason of segfault, this is my last try.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
from PyQt4 import QtCore
... | [
"I don't know Python but in your appExit(), you should be calling quit() or exit() on the application object which will cause your call to sys.exit(app.exec_()) in main to return. Again, not knowing the Python specifics, you can do this by using the Qt macro qApp and call qApp->quit() or QCoreApplication::instance(... | [
3
] | [] | [] | [
"contextmenu",
"pyqt",
"python",
"tray",
"trayicon"
] | stackoverflow_0003619514_contextmenu_pyqt_python_tray_trayicon.txt |
Q:
ctypes.windll.user32.GetCursorInfo() - how can I manage this to work? [Python]
I have to get the information about the current mouse cursor from windows but I'm not managing to work this command...
what should I do?
Can someone post one example?
A:
What information are you trying to get out of the GetCursorInfo... | ctypes.windll.user32.GetCursorInfo() - how can I manage this to work? [Python] | I have to get the information about the current mouse cursor from windows but I'm not managing to work this command...
what should I do?
Can someone post one example?
| [
"What information are you trying to get out of the GetCursorInfo() call? It would be easier to use the win32 extensions (especially if you just want cursor position).\n>>> import win32gui\n>>> win32gui.GetCursorInfo()\n(1, 65555, (717, 412))\n\n"
] | [
1
] | [] | [] | [
"ctypes",
"python",
"windows"
] | stackoverflow_0003619690_ctypes_python_windows.txt |
Q:
Python Directory Display in Finder, Explorer, Dolphin, etc... (Cross-Platform)
I would like to find some way of Viewing a Directory in the default file system viewer (Windows Explorer, Finder, Dolphin, etc...) that will work on all major platforms.
I do not have the detailed knowledge of Linux, nor of OSX in order... | Python Directory Display in Finder, Explorer, Dolphin, etc... (Cross-Platform) | I would like to find some way of Viewing a Directory in the default file system viewer (Windows Explorer, Finder, Dolphin, etc...) that will work on all major platforms.
I do not have the detailed knowledge of Linux, nor of OSX in order to write this. Is there some script out there that will do what I want?
| [
"OSX:\nos.system('open \"%s\"' % foldername)\n\nWindows:\nos.startfile(foldername)\n\nUnix:\nos.system('xdg-open \"%s\"' % foldername)\n\nCombined:\nimport os\n\nsystems = {\n 'nt': os.startfile,\n 'posix': lambda foldername: os.system('xdg-open \"%s\"' % foldername)\n 'os2': lambda foldername: os.system('... | [
4
] | [] | [] | [
"cross_platform",
"directory",
"python"
] | stackoverflow_0003619908_cross_platform_directory_python.txt |
Q:
simple twisted receiver for orbited comet server
I have an unusual request.
I've just moved to a new apartment and I won't have my internet hooked up for over a week. I'm trying to develop my application using my phone for online documentation. Before I moved I found this video (vodpod.com/watch/4071950-building-r... | simple twisted receiver for orbited comet server | I have an unusual request.
I've just moved to a new apartment and I won't have my internet hooked up for over a week. I'm trying to develop my application using my phone for online documentation. Before I moved I found this video (vodpod.com/watch/4071950-building-real-time-network-applications-for-the-web-with-twisted... | [
"You can watch the video on Android/Symbian/WinMobile using SkyFire.\n",
"The URL to the code examples used in that video:\nhttp://orbited.org/blog/files/tutorial/examples.tgz\n"
] | [
1,
1
] | [] | [] | [
"orbited",
"python",
"twisted"
] | stackoverflow_0003619836_orbited_python_twisted.txt |
Q:
python: regular expressions, how to match a string of undefind length which has a structure and finishes with a specific group
I need to create a regexp to match strings like this 999-123-222-...-22
The string can be finished by &Ns=(any number) or without this... So valid strings for me are
999-123-222-...-22
99... | python: regular expressions, how to match a string of undefind length which has a structure and finishes with a specific group | I need to create a regexp to match strings like this 999-123-222-...-22
The string can be finished by &Ns=(any number) or without this... So valid strings for me are
999-123-222-...-22
999-123-222-...-22&Ns=12
999-123-222-...-22&Ns=12
And following are not valid:
999-123-222-...-22&N=1
I have tried testing it several... | [
"Not sure if you want to literally match 999-123-22-...-22 or if that can be any sequence of numbers/dashes. Here are two different regexes:\n/^[\\d-]+(&Ns=\\d+)?$/\n\n/^999-123-222-\\.\\.\\.-22(&Ns=\\d+)?$/\n\nThe key idea is the (&Ns=\\d+)?$ part, which matches an optional &Ns=<digits>, and is anchored to the end... | [
1,
0,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0003618193_python_regex.txt |
Q:
Database Wrapper Class for Python
I am a PHP developer and recently migrated to Python. In PHP, there are many classes available at for example phpclasses.org which saves a lot of developer's time. I am looking for similar kind of repository for python. I need a database wrapper class for accessing the database wi... | Database Wrapper Class for Python | I am a PHP developer and recently migrated to Python. In PHP, there are many classes available at for example phpclasses.org which saves a lot of developer's time. I am looking for similar kind of repository for python. I need a database wrapper class for accessing the database with python. One of the class i found was... | [
"Following Skurmedel's advice, I remembered reading about SQLAlchemy before. It's pretty well documented and maintained. Here's a good start point: SQLAlchemy 1.4 / 2.0 Tutorial\n",
"Most databases you choose to use will have a module available that conforms to the DBAPI. That gives you access that is quite easy ... | [
3,
1
] | [] | [] | [
"database",
"python"
] | stackoverflow_0003618995_database_python.txt |
Q:
Release a lock temporarily if it is held, in python
I have a bunch of different methods that are not supposed to run concurrently, so I use a single lock to synchronize them. Looks something like this:
selected_method = choose_method()
with lock:
selected_method()
In some of these methods, I sometimes call a ... | Release a lock temporarily if it is held, in python | I have a bunch of different methods that are not supposed to run concurrently, so I use a single lock to synchronize them. Looks something like this:
selected_method = choose_method()
with lock:
selected_method()
In some of these methods, I sometimes call a helper function that does some slow network IO. (Let's c... | [
"\nI would much prefer to rewrite network_method() so that it checks to see whether the lock is held, and if so release it before starting and acquire it again at the end.\nNote that network_method() sometimes gets called from other places, so it shouldn't release the lock if it's not on the thread that holds it.\n... | [
3,
0
] | [] | [] | [
"locking",
"multithreading",
"python"
] | stackoverflow_0003618515_locking_multithreading_python.txt |
Q:
tkinter in python. .pack works, but .grid produces nothing
This code works fine and produces checkbuttons in a long long list.
def createbutton(self,name):
var = IntVar()
account = name[0]
chk = Checkbutton(self.root, text=account, variable=var)
chk.pack(side = BOTTOM)
self.states.append((name,... | tkinter in python. .pack works, but .grid produces nothing | This code works fine and produces checkbuttons in a long long list.
def createbutton(self,name):
var = IntVar()
account = name[0]
chk = Checkbutton(self.root, text=account, variable=var)
chk.pack(side = BOTTOM)
self.states.append((name,var))
The problem is that the list of buttons is so long, that ... | [
"Is it possible that you have other widgets that are in the root window, and they are put there using pack? If you try to use pack and grid in the same container your app can go into an infinite loop as each manager struggles for control of the container.\n"
] | [
0
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0003619671_python_tkinter.txt |
Q:
Who stops my threads?
I have some threads fishing into a queue for jobs, something like this:
class Worker(Thread):
[...]
def run(self):
while not self.terminated:
job = myQueue.get_nowait()
job.dosomething()
sleep(0.5)
Now, self.terminated is just a bool value ... | Who stops my threads? | I have some threads fishing into a queue for jobs, something like this:
class Worker(Thread):
[...]
def run(self):
while not self.terminated:
job = myQueue.get_nowait()
job.dosomething()
sleep(0.5)
Now, self.terminated is just a bool value I use to exit the loop but,... | [
"If that is the actual code it's pretty obvious: myQueue.get_nowait() raises an Exception (Empty) when the queue is empty!\n",
"stackoverflow? :)\n",
"As example, an exception inside the loop will stop the thread.\nWhy do you use get_nowait() and not get()? What if the Queue is empty?\n",
"I have two suggesti... | [
3,
2,
2,
1,
0
] | [] | [] | [
"multithreading",
"python"
] | stackoverflow_0003620185_multithreading_python.txt |
Q:
Modeling Hierarchical Data - GAE
I'm new in google-app-engine and google datastore (bigtable) and I've some doubts in order of which could be the best approach to design the required data model.
I need to create a hierarchy model, something like a product catalog, each domain has some subdomains in deep. For the m... | Modeling Hierarchical Data - GAE | I'm new in google-app-engine and google datastore (bigtable) and I've some doubts in order of which could be the best approach to design the required data model.
I need to create a hierarchy model, something like a product catalog, each domain has some subdomains in deep. For the moment the structure for the products c... | [
"I'm not sure what kinds of queries you'll need to do in addition to those mentioned in the question, but storing the data in an explicit ancestor hierarchy would make the ones you asked about fall out pretty easily.\nFor example, to get all wines from a particular origin:\norigin_key = db.Key.from_path('Origin', 1... | [
1
] | [] | [] | [
"bigtable",
"google_app_engine",
"python"
] | stackoverflow_0003620147_bigtable_google_app_engine_python.txt |
Q:
Tagging similar sentences with lower time complexity than n^2
This is my first post, have been a lurker for a long time, so will try my best to explain myself here.
I have been using lowest common substring method along with basic word match and substring match(regexp) for clustering similar stories on the net.
Bu... | Tagging similar sentences with lower time complexity than n^2 | This is my first post, have been a lurker for a long time, so will try my best to explain myself here.
I have been using lowest common substring method along with basic word match and substring match(regexp) for clustering similar stories on the net.
But the problem is its time complexity is n^2 (I compare each title t... | [
"Use an inverted index: for each word, store a list of pairs (docId, numOccurences).\nThen, to find all strings which might be similar to a given string, go through its words and look up strings containing that word in the inverted index. This way you'll get a table \"(docId, wordMatchScore)\" that automatically co... | [
4,
3
] | [] | [] | [
"algorithm",
"python",
"string"
] | stackoverflow_0003620318_algorithm_python_string.txt |
Q:
How do you generate the non-convex hull from a series of points?
I am currently trying to construct the area covered by a device over an operating period.
The first step in this process appears to be constructing a polygon of the covered area.
Since the pattern is not a standard shape, convex hulls overstate the... | How do you generate the non-convex hull from a series of points? | I am currently trying to construct the area covered by a device over an operating period.
The first step in this process appears to be constructing a polygon of the covered area.
Since the pattern is not a standard shape, convex hulls overstate the covered area by jumping to the largest coverage area possible.
I hav... | [
"You might try looking into Alpha Shapes. The CGAL library can compute them.\nEdit: I see that the paper you linked references alpha shapes, and also has an algorithm listing. Is that not high level enough for you? Since you listed python as a tag, I'm sure there are Delaunay triangulation libraries in Python, whic... | [
4
] | [] | [] | [
"computational_geometry",
"geometry",
"gis",
"math",
"python"
] | stackoverflow_0003620446_computational_geometry_geometry_gis_math_python.txt |
Q:
Why is my code stopping?
Hey I've encountered an issue where my program stops iterating through the file at the 57802 record for some reason I cannot figure out. I put a heartbeat section in so I would be able to see which line it is on and it helped but now I am stuck as to why it stops here. I thought it was a... | Why is my code stopping? | Hey I've encountered an issue where my program stops iterating through the file at the 57802 record for some reason I cannot figure out. I put a heartbeat section in so I would be able to see which line it is on and it helped but now I am stuck as to why it stops here. I thought it was a memory issue but I just ran i... | [
"What does the input line that gives you trouble look like? I'd try printing that out. I suspect your CPU is pegged while this is running. \nNested regexps, like you have can have VERY bad performance when they don't match quickly.\n((\\w+).?)+:\n\nImagine a string that doesn't have the : in it but is fairly long. ... | [
7,
2,
1,
1,
0,
0
] | [] | [] | [
"python",
"regex",
"string_matching"
] | stackoverflow_0003614075_python_regex_string_matching.txt |
Q:
How to remove leading and trailing spaces from strings in a Python list
i have a list:
row=['hi', 'there', 'how', ...........'some stuff is here are ','you']
as you can see row[8]='some stuff is here are '
if the last character is a space i would like to get everything except for the last character like this:
if ... | How to remove leading and trailing spaces from strings in a Python list | i have a list:
row=['hi', 'there', 'how', ...........'some stuff is here are ','you']
as you can see row[8]='some stuff is here are '
if the last character is a space i would like to get everything except for the last character like this:
if row[8][len(row[8])-1]==' ':
row[8]=row[8][0:len(row[8])-2]
this method is ... | [
"row = [x.strip() for x in row]\n\n(if you just want to get spaces at the end, use rstrip)\n",
"Negative indexes count from the end. And slices are anchored before the index given.\nif row[8][-1]==' ':\n row[8]=row[8][:-1]\n\n",
"So you want it without trailing spaces? Can you just use row[8].rstrip?\n"
] | [
10,
4,
4
] | [] | [] | [
"python"
] | stackoverflow_0003621008_python.txt |
Q:
Appengine - Reportlab PDF
I'm using Google appengine and want to generate a PDF with reportlab.
The application works well and can generate PDF's like 'Hello World' and little else.
But what I want is to fetch data from a form with the data that the user entered and generate PDF dynamically.
Anyone can share a pie... | Appengine - Reportlab PDF | I'm using Google appengine and want to generate a PDF with reportlab.
The application works well and can generate PDF's like 'Hello World' and little else.
But what I want is to fetch data from a form with the data that the user entered and generate PDF dynamically.
Anyone can share a piece of code? I would be grateful... | [
"I assume you use the webapp framework.\nimport cgi\n\nfrom google.appengine.api import users\nfrom google.appengine.ext import webapp\nfrom google.appengine.ext.webapp.util import run_wsgi_app\n\nclass MainPage(webapp.RequestHandler):\n def get(self):\n self.response.out.write(\"\"\"\n <html>\n ... | [
2
] | [] | [] | [
"google_app_engine",
"python",
"reportlab"
] | stackoverflow_0003621010_google_app_engine_python_reportlab.txt |
Q:
Accessing the content of a variable array with ctypes
I use ctypes to access a file reading C function in python. As the read data is huge and unknown in size I use **float in C .
int read_file(const char *file,int *n_,int *m_,float **data_) {...}
The functions mallocs an 2d array, called data, of the appropriate... | Accessing the content of a variable array with ctypes | I use ctypes to access a file reading C function in python. As the read data is huge and unknown in size I use **float in C .
int read_file(const char *file,int *n_,int *m_,float **data_) {...}
The functions mallocs an 2d array, called data, of the appropriate size, here n and m, and copies the values to the reference... | [
"might be simpler to do the whole thing in python with the struct library. but if you're sold on ctypes (and I don't blame you, it's pretty cool):\n#include <malloc.h>\nvoid floatarr(int* n, float** f)\n{\n int i;\n float* f2 = malloc(sizeof(float)*10);\n n[0] = 10;\n for (i=0;i<10;i++)\n { f2[i] = (... | [
3
] | [] | [] | [
"ctypes",
"multidimensional_array",
"pointers",
"python"
] | stackoverflow_0003620348_ctypes_multidimensional_array_pointers_python.txt |
Q:
Is there a way to write a command so that it aborts a running function call?
I have a widget that measures elapsed time, then after a certain duration it does a command. However, if the widget is left I want I want it to abort this function call and not do the command.
How do I go about this?
A:
Use the thread... | Is there a way to write a command so that it aborts a running function call? | I have a widget that measures elapsed time, then after a certain duration it does a command. However, if the widget is left I want I want it to abort this function call and not do the command.
How do I go about this?
| [
"Use the threading module and start a new thread that will run the function.\nJust abort the function is a bad idea as you don't know if you interrupt the thread in a critical situation. You should extend your function like this:\nimport threading\n\nclass WidgetThread(threading.Thread):\n def __init__(self):\n... | [
3,
0,
0
] | [] | [] | [
"abort",
"python",
"tkinter"
] | stackoverflow_0003621111_abort_python_tkinter.txt |
Q:
Is there a way to package a python extension written in C into a binary so I don't have to python-install it?
I wrote a Python extension in C, and my python program uses that extension. In order for it to work, I would have to install the extension on the user's system before my program can run. Is there a way to ... | Is there a way to package a python extension written in C into a binary so I don't have to python-install it? | I wrote a Python extension in C, and my python program uses that extension. In order for it to work, I would have to install the extension on the user's system before my program can run. Is there a way to bypass that installation step and somehow just have the extension in my python package? The only compiled part obvi... | [
"You can avoid having some one to install it independently but you can not avoid installation completely. If his computing platform differs from yours, he will have to build the extension.\nWhat can be done is that you setup a package distribution using distutils. This way the package could be installed or built. Y... | [
2,
1
] | [] | [] | [
"c",
"installation",
"python"
] | stackoverflow_0003619990_c_installation_python.txt |
Q:
python: cleaning up a string
i have a string like this
somestring='in this/ string / i have many. interesting.occurrences of {different chars} that need to .be removed '
here is the result i want:
somestring='in this string i have many interesting occurrences of different chars that need to be removed'
i st... | python: cleaning up a string | i have a string like this
somestring='in this/ string / i have many. interesting.occurrences of {different chars} that need to .be removed '
here is the result i want:
somestring='in this string i have many interesting occurrences of different chars that need to be removed'
i started to manually do all kinds of ... | [
"I would use regular expression to replace all non-alphanumerics to spaces:\n>>> import re\n>>> somestring='in this/ string / i have many. interesting.occurrences of {different chars} that need to .be removed '\n>>> rx = re.compile('\\W+')\n>>> res = rx.sub(' ', somestring).strip()\n>>> res\n'in this string i ... | [
17,
2,
1
] | [] | [] | [
"python",
"string"
] | stackoverflow_0003621296_python_string.txt |
Q:
python round problem
I am facing the problem while dividing
my max_sum = 14
total_no=4
so when i do
print "x :", (total_sum/total_no)
, I get 3 and not 3.5
I tried many ways for printing but failed, can somebody let me know what way I get in 3.5 format?
Thank you
A:
In Python 2.x, dividing two integers by... | python round problem | I am facing the problem while dividing
my max_sum = 14
total_no=4
so when i do
print "x :", (total_sum/total_no)
, I get 3 and not 3.5
I tried many ways for printing but failed, can somebody let me know what way I get in 3.5 format?
Thank you
| [
"In Python 2.x, dividing two integers by default dives you another integer. This is often confusing, and has been fixed in Python 3.x. You can bypass it by casting one of the numbers to a float, which will automatically cast the other:\nfloat( 14 ) / 4 == 3.5\nThe relevant PEP is number 238:\n\nThe current division... | [
9,
2,
1,
0,
0
] | [] | [] | [
"division",
"integer_division",
"python",
"python_2.x",
"rounding"
] | stackoverflow_0003621717_division_integer_division_python_python_2.x_rounding.txt |
Q:
Python - Minimum of a List of Instance Variables
I'm new to Python and I really love the min function.
>>>min([1,3,15])
0
But what if I have a list of instances, and they all have a variable named number?
class Instance():
def __init__(self, number):
self.number = number
i1 = Instance(1)
i2 = Instanc... | Python - Minimum of a List of Instance Variables | I'm new to Python and I really love the min function.
>>>min([1,3,15])
0
But what if I have a list of instances, and they all have a variable named number?
class Instance():
def __init__(self, number):
self.number = number
i1 = Instance(1)
i2 = Instance(3)
i3 = Instance(15)
iList = [i1,i2,i3]
Do I really... | [
"The OOP way would be to implement __lt__:\nclass Instance():\n def __init__(self, number):\n self.number = number\n\n def __lt__(self, other):\n return self.number < other.number\n # now min(iList) just works\n\nAnother way is\nimin = min(iList, key=lambda x:x.number)\nFunctions like sor... | [
14,
10,
5,
1
] | [] | [] | [
"list",
"min",
"python"
] | stackoverflow_0003621826_list_min_python.txt |
Q:
How to deal with Python ~ static typing?
I am from Java world and I wonder what is so great about dynamic typing in Python besides missing errors while compiling the code?
Do you like Python's typing? Do you have an example where it helped in a big project? Isn't it a bit error prone?
A:
Static type checking is ... | How to deal with Python ~ static typing? | I am from Java world and I wonder what is so great about dynamic typing in Python besides missing errors while compiling the code?
Do you like Python's typing? Do you have an example where it helped in a big project? Isn't it a bit error prone?
| [
"Static type checking is undecidable in the general case. This means that there are programs which are statically type-safe but for which the type-checker cannot prove that they are statically type-safe, and thus the type-checker must reject those programs.\nIn other words: there are type-safe programs that the typ... | [
17,
13,
5,
2,
0,
0,
0
] | [] | [] | [
"dynamic_typing",
"java",
"python",
"static_typing"
] | stackoverflow_0003621297_dynamic_typing_java_python_static_typing.txt |
Q:
I have to make mouse move until cursor change, but, how?
I want to make a little script that make the mouse moves until the icon changes, but I'm not having success with it...
Here it's what I'm trying
def enterLink():
mouseMove(*position[4])
for win32gui.GetCursorInfo()[1] == 65567:
mouseMove(*pos... | I have to make mouse move until cursor change, but, how? | I want to make a little script that make the mouse moves until the icon changes, but I'm not having success with it...
Here it's what I'm trying
def enterLink():
mouseMove(*position[4])
for win32gui.GetCursorInfo()[1] == 65567:
mouseMove(*position[5])
mouseMove(*position[4])
How I have to do th... | [
"\nThe commands are correct =/\n\nIf they were correct, it would work...\nfor win32gui.GetCursorInfo()[1] == 65567:\n\nI suggest if.\n"
] | [
1
] | [] | [] | [
"python",
"windows"
] | stackoverflow_0003622019_python_windows.txt |
Q:
Using Twill from Python to open a link: " 'module' object has no attribute 'Popen' " What is it?
I have downloaded and installed Python 2.5.4 on my computer (my OS is Windows XP), downloaded “Goggle App Engine Software Development Kit” and created my first application in Python, which was a directory named hellowo... | Using Twill from Python to open a link: " 'module' object has no attribute 'Popen' " What is it? | I have downloaded and installed Python 2.5.4 on my computer (my OS is Windows XP), downloaded “Goggle App Engine Software Development Kit” and created my first application in Python, which was a directory named helloworld that contained a small python file with the same name (helloworld.py). Here are the contents of th... | [
"I think you should use mechanize directly. Twill communicates with the system in a way that's not supported by Google App Engine.\nimport mechanize\n\nbrowser = mechanize.Browser()\n\nbrowser.open('http://www.python.org')\n\nfor f in browser.forms():\n print f # you'll have to extend it\n\n",
"you can't use a... | [
2,
2,
2
] | [] | [] | [
"google_app_engine",
"popen",
"python",
"twill"
] | stackoverflow_0003621432_google_app_engine_popen_python_twill.txt |
Q:
How to include PDF in Sphinx documentation?
I have a PDF that has some in depth explanation for an example in the Sphinx documentation for a package I have. Is there a way to easily include the PDF in my project (and have it copy over when I build the docs)? I tried linking to it with :doc: but this did not copy i... | How to include PDF in Sphinx documentation? | I have a PDF that has some in depth explanation for an example in the Sphinx documentation for a package I have. Is there a way to easily include the PDF in my project (and have it copy over when I build the docs)? I tried linking to it with :doc: but this did not copy it over.
| [
"Use the :download: text role to bring in an arbitrary additional file. So in your case you might do something like this:\nFor an in-depth explanation, please see :download:`A Detailed Example <some_extra_file.pdf>`.\n\n"
] | [
24
] | [] | [] | [
"pdf",
"python",
"python_sphinx"
] | stackoverflow_0003615142_pdf_python_python_sphinx.txt |
Q:
Deploying cx_Oracle onto various versions of Oracle Client
I have some small python apps that use cx_Oracle to connect to an Oracle database. I deploy these apps by compiling them with py2exe, which works fine in many cases.
The problem is, there is no standard Oracle Client version (9i and 10g for example) across... | Deploying cx_Oracle onto various versions of Oracle Client | I have some small python apps that use cx_Oracle to connect to an Oracle database. I deploy these apps by compiling them with py2exe, which works fine in many cases.
The problem is, there is no standard Oracle Client version (9i and 10g for example) across the many people who need to install this, and it would be very ... | [
"If you want to build multiple cx_Oracle versions (eg: cx_Oracle10g, cx_Oracle11g, etc.) then you'll need to modify the cx_Oracle setup.py script. The last step in the script is a call to setup(); the first parameter is the name of the module to build. All you need to do is to change \"cx_Oracle\" to \"cx_Oracle\... | [
3
] | [] | [] | [
"cx_oracle",
"instantclient",
"oracle",
"py2exe",
"python"
] | stackoverflow_0003348894_cx_oracle_instantclient_oracle_py2exe_python.txt |
Q:
Break from for loop
Here is my code:
def detLoser(frag, a):
word = frag + a
if word in wordlist:
lost = True
else:
for words in wordlist:
if words[:len(word) == word:
return #I want this to break out.
else:
lost = True
Where ... | Break from for loop | Here is my code:
def detLoser(frag, a):
word = frag + a
if word in wordlist:
lost = True
else:
for words in wordlist:
if words[:len(word) == word:
return #I want this to break out.
else:
lost = True
Where I have a return, I've tri... | [
"You've omitted the ] from the list slice. But what is the code trying to achieve, anyway? \nfoo[ : len( foo ) ] == foo\n\nalways! \nI assume this isn't the complete code -- if so, where is wordlist defined? (is it a list? -- it's much faster to test containment for a set.)\n",
"def detLoser(frag, a):\n\n word... | [
6,
2
] | [] | [] | [
"breakpoints",
"python"
] | stackoverflow_0003622135_breakpoints_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.