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:
Parmiko SFTP File - Calling .next() causes StopIteration immediately, even with lines remaining
I'm attempting to use Paramiko (Python SSH library) to read a remote file, and iterate through the lines.
My file looks something like this:
# Instance Name VERSION COMMENT
Bob 1.5 ... | Parmiko SFTP File - Calling .next() causes StopIteration immediately, even with lines remaining | I'm attempting to use Paramiko (Python SSH library) to read a remote file, and iterate through the lines.
My file looks something like this:
# Instance Name VERSION COMMENT
Bob 1.5 Bob the Builder
Sam 1.7 Play it again, Sam
My Par... | [
"The the next() function is simply calling readline() internally. The only thing that can cause a StopIteration is if readline returned an empty string (look at the code, it's 4 lines). \nLook at what the return of readline() is for your file. If it's returning an empty string, there has to be a bug in the line-buf... | [
0
] | [] | [] | [
"paramiko",
"python",
"sftp"
] | stackoverflow_0008130037_paramiko_python_sftp.txt |
Q:
Is it still not enough to simply use threads to update GUI?
For example:
class DemoFrame(wx.Frame):
def __init__(self):
Initializing
...
self.TextA = wx.StaticText(MainPanel, id = -1, label = "TextAOrWhatever")
self.TextB = wx.StaticText(MainPanel, id = -1, label = "TextBOrWhat... | Is it still not enough to simply use threads to update GUI? | For example:
class DemoFrame(wx.Frame):
def __init__(self):
Initializing
...
self.TextA = wx.StaticText(MainPanel, id = -1, label = "TextAOrWhatever")
self.TextB = wx.StaticText(MainPanel, id = -1, label = "TextBOrWhatever")
...
def StaticTextUpdating(self, ObjectName, ... | [
"Most wx methods are not thread-safe. Use wx.CallAfter if you want to invoke a wx method from another thread; replace\nObjectName.SetLabel(Message)\n\nwith:\nwx.CallAfter(ObjectName.SetLabel, Message)\n\nEdit: Some Background Information\nIn wx (And in most other UI platforms) all the UI updates get executed in a s... | [
4,
2
] | [] | [] | [
"multithreading",
"python",
"thread_safety",
"wxpython"
] | stackoverflow_0008313169_multithreading_python_thread_safety_wxpython.txt |
Q:
List returns more values than expected
I have a list of say two values, I'm then supposed to multiply each value by an integer until both elements in become integers and append these new values to a new list. Say I have a list [0.5,1], what's supposed to happen is that I'm gonna multiply each by 2 and get 1 and 2 ... | List returns more values than expected | I have a list of say two values, I'm then supposed to multiply each value by an integer until both elements in become integers and append these new values to a new list. Say I have a list [0.5,1], what's supposed to happen is that I'm gonna multiply each by 2 and get 1 and 2 and append these to a new list [1,2]. For th... | [
"It looks like you should be clearing alist inside of the while loop, otherwise each run through the for loop will append len(newlist) items to alist without removing previous elements of alist.\nu = 1 \nnewlist = [1, 0.5]\nwhile True:\n alist = []\n cont = True\n for value in newlist:\n w = value*u... | [
2,
1,
0,
0
] | [] | [] | [
"list",
"python"
] | stackoverflow_0008316205_list_python.txt |
Q:
How to stop loop when user enters "quit", "end", etc?
This is my code
#!/usr/bin/python3.1$
#Break Statement$
while True:$ ... | How to stop loop when user enters "quit", "end", etc? | This is my code
#!/usr/bin/python3.1$
#Break Statement$
while True:$
s=(... | [
"You should not have $ at the end of every line.\nAlso, instead of this:\nif s=='Quit,quit,End,end':\n\nyou want to use in and a list:\nif s in ['Quit','quit','End','end']:\n\nYou can also handle other inputs such as QUIT and QUit by using str.lower:\nif s.lower() in ['quit', 'end']:\n\n"
] | [
7
] | [] | [] | [
"python"
] | stackoverflow_0008316936_python.txt |
Q:
Login to website using python
I am trying to login to this page using Python.
I tried using the steps described on this other Stack Overflow post, and got the following code:
import urllib, urllib2, cookielib
username = 'username'
password = 'password'
cj = cookielib.CookieJar()
opener = urllib2.build_opener(url... | Login to website using python | I am trying to login to this page using Python.
I tried using the steps described on this other Stack Overflow post, and got the following code:
import urllib, urllib2, cookielib
username = 'username'
password = 'password'
cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
login... | [
"I would recommend using the wonderful requests module.\nThe code below will get you logged into the site and persist the cookies for the duration of the session.\nimport requests\nimport sys\n\nEMAIL = ''\nPASSWORD = ''\n\nURL = 'http://friends.cisv.org'\n\ndef main():\n # Start a session so we can have persist... | [
36,
3
] | [] | [] | [
"authentication",
"cookies",
"python"
] | stackoverflow_0008316818_authentication_cookies_python.txt |
Q:
Standard 401 response when using HTTP auth in flask
In flask, I'm using the following snippet to enable HTTP auth:
def authenticate():
return Response('<Why access is denied string goes here...>', 401, {'WWW-Authenticate':'Basic realm="Login Required"'})
Now, in my past experience with Flask, if someone's cre... | Standard 401 response when using HTTP auth in flask | In flask, I'm using the following snippet to enable HTTP auth:
def authenticate():
return Response('<Why access is denied string goes here...>', 401, {'WWW-Authenticate':'Basic realm="Login Required"'})
Now, in my past experience with Flask, if someone's credentials are incorrect and I want to let them know I can ... | [
"Custom error responses are really quite easy in Flask. Create a function whose only argument is the HTTP error status code, make it return a flask.Response instance, and decorate it with @app.errorhandler.\n@app.errorhandler(401)\ndef custom_401(error):\n return Response('<Why access is denied string goes here... | [
40,
17
] | [] | [] | [
"abort",
"apache2",
"flask",
"http_authentication",
"python"
] | stackoverflow_0007877230_abort_apache2_flask_http_authentication_python.txt |
Q:
Load and modify a tkinter gui from a pickle file
I have some trouble loading a GUI interface from a pickle file.
I was able to do what I want but it doesn't work exactly as I expected and I'm not sure it is the correct way.
This is a reduced example of the basic gui (you don't really have to read it and understand... | Load and modify a tkinter gui from a pickle file | I have some trouble loading a GUI interface from a pickle file.
I was able to do what I want but it doesn't work exactly as I expected and I'm not sure it is the correct way.
This is a reduced example of the basic gui (you don't really have to read it and understand it depth, it is not the main question):
tableRel = {}... | [
"The mainloop is where your root widget listens and responds to input and other events, like mouse clicks, keypresses, and signals from the OS. By using after, you are taking advantage of mainloop to call your update procedure every n seconds.\nWhat you could do in addition is keep track of how long the interface ... | [
3
] | [] | [] | [
"pickle",
"python",
"tkinter",
"user_interface"
] | stackoverflow_0008315113_pickle_python_tkinter_user_interface.txt |
Q:
Sending http headers with python
I've set up a little script that should feed a client with html.
import socket
sock = socket.socket()
sock.bind(('', 8080))
sock.listen(5)
client, adress = sock.accept()
print "Incoming:", adress
print client.recv(1024)
print
client.send("Content-Type: text/html\n\n")
client.sen... | Sending http headers with python | I've set up a little script that should feed a client with html.
import socket
sock = socket.socket()
sock.bind(('', 8080))
sock.listen(5)
client, adress = sock.accept()
print "Incoming:", adress
print client.recv(1024)
print
client.send("Content-Type: text/html\n\n")
client.send('<html><body></body></html>')
prin... | [
"The response header should include a response code indicating success.\nBefore the Content-Type line, add:\nclient.send('HTTP/1.0 200 OK\\r\\n')\n\nAlso, to make the test more visible, put some content in the page:\nclient.send('<html><body><h1>Hello World</body></html>')\n\nAfter the response is sent, close the c... | [
18,
0
] | [] | [] | [
"client",
"html",
"python",
"sockets"
] | stackoverflow_0008315209_client_html_python_sockets.txt |
Q:
How to write Regex for extracting tags?
I want to extract all tags in a xml file. However, I cannot write proper regular expression to extract the content I want.
The tags format in the file is like :
Tags=<"tracffic""apple""sample">
And I want to return a list contained all the tags: [traffic, apple, sample]
I... | How to write Regex for extracting tags? | I want to extract all tags in a xml file. However, I cannot write proper regular expression to extract the content I want.
The tags format in the file is like :
Tags=<"tracffic""apple""sample">
And I want to return a list contained all the tags: [traffic, apple, sample]
I tried this:
Tags=<("[\w]+")+
which onl... | [
"Try this:\nm = re.search('<(\".+\")>', 'Tags=<\"traffic\"\"apple\"\"sample\">')\ntags = [x for x in m.group(1).split('\"') if x]\n\nNow tags contains:\n['traffic', 'apple', 'sample']\n\n"
] | [
1
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0008317073_python_regex.txt |
Q:
How do I specify slugifying code in this South migration?
I have a model like:
class Thing(models.Model):
title = models.CharField(_('Title'), max_length=255)
I want to add this NOT NULL field:
slug = models.SlugField(_('Slug'), max_length=255)
When I run "python manage.py schemamigration things --auto", I g... | How do I specify slugifying code in this South migration? | I have a model like:
class Thing(models.Model):
title = models.CharField(_('Title'), max_length=255)
I want to add this NOT NULL field:
slug = models.SlugField(_('Slug'), max_length=255)
When I run "python manage.py schemamigration things --auto", I get prompted to enter Python code for my one-off default value. ... | [
"i'd probably leave it blank in the migration, and instead follow it with a data migration creating the slugs there with some code\n"
] | [
6
] | [] | [] | [
"django",
"django_south",
"python"
] | stackoverflow_0008317194_django_django_south_python.txt |
Q:
Why does this python implementation of an "operable function" fail?
I wanted to demonstrate the usefulness of decorators in python to some people and failed at a simple example: Consider two functions (for sake of simplicity without arguments) f and g.
One can define their sum f+g as the function that returns f() ... | Why does this python implementation of an "operable function" fail? | I wanted to demonstrate the usefulness of decorators in python to some people and failed at a simple example: Consider two functions (for sake of simplicity without arguments) f and g.
One can define their sum f+g as the function that returns f() + g(). Of course adding, subtracting etc. of functions is not defined in ... | [
"For the first issue, I didn't see any problems when changing binary_op_names from a list to a tuple, not sure why you were seeing that.\nAs for the second issue, all operations will perform an XOR because __xor__ was the last item that op was set to. Because op is not passed into the lambda when it is created, ea... | [
2
] | [] | [] | [
"decorator",
"python"
] | stackoverflow_0008317201_decorator_python.txt |
Q:
Function argument having value that is neither passed in by caller nor default value
I have a decorator like this:
def region_required(view_func):
def new_view(request, ctx = {}, *args, **kw):
import pdb; pdb.set_trace()
ctx['regions'] = Region.objects.all()
return view_func(request, co... | Function argument having value that is neither passed in by caller nor default value | I have a decorator like this:
def region_required(view_func):
def new_view(request, ctx = {}, *args, **kw):
import pdb; pdb.set_trace()
ctx['regions'] = Region.objects.all()
return view_func(request, context=ctx, *args, **kw)
return new_view
I uses it to decorate view functions.
Today I... | [
"You're using a mutable argument as a default parameter. Every time it's called without that argument, it will include the one you provided, including prior modifications. Use None as the default value instead, check for it, and if it is None, assign the empty dict in the body of the function.\ndef region_required(... | [
5,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0008317532_django_python.txt |
Q:
adding to a string without commas
I want to add things to a string without any commas.
I have a string URL: http://gdata.youtube.com/feeds/api/standardfeeds/feed_str?max-results=max_result&time=
feed_str = top_rated
max_result = 5
time_str = today
web_str = "http://gdata.youtube.com/feeds/api/standardfeeds/",feed_... | adding to a string without commas | I want to add things to a string without any commas.
I have a string URL: http://gdata.youtube.com/feeds/api/standardfeeds/feed_str?max-results=max_result&time=
feed_str = top_rated
max_result = 5
time_str = today
web_str = "http://gdata.youtube.com/feeds/api/standardfeeds/",feed_str, "?max-results=" ,max_result,"&time... | [
"Here's a hint ; you are looking for a way to concatenate strings.\n",
"String concatenation is what you are looking for and SO has many threads on this topic ( String concatenation vs. string substitution in Python , Concatenation Operator + or , ,...)\n",
"Simply remove the commas on the web_str and put the s... | [
3,
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0008315370_python.txt |
Q:
Efficient structure for element wise access to very large sparse matrix (Python/Cython)
I'm looking for an efficient data structure to represent a very large matrix of integers in Python/Cython with focus on element-wise operations.
I'm currently building a model that requires a lot of element-wise operations on a... | Efficient structure for element wise access to very large sparse matrix (Python/Cython) | I'm looking for an efficient data structure to represent a very large matrix of integers in Python/Cython with focus on element-wise operations.
I'm currently building a model that requires a lot of element-wise operations on a large, highly sparse matrix (ca. 50bn read/writes on a 2MMx500k matrix). Previously I've run... | [
"If you aren't doing row- or column-based accesses, you can use a dict with a tuple key like A[(i,j)].\n"
] | [
3
] | [] | [] | [
"cython",
"python",
"scipy",
"sparse_matrix"
] | stackoverflow_0008317830_cython_python_scipy_sparse_matrix.txt |
Q:
Does M2Crypto's public_decrypt(block, padarg) perform decryption or verfication?
I got some Python code that seems to use a public key for decrypting data. The data is probably encrypted using the corresponding private key. (I am not sure about it, because encryption with private key is normally called signing).... | Does M2Crypto's public_decrypt(block, padarg) perform decryption or verfication? | I got some Python code that seems to use a public key for decrypting data. The data is probably encrypted using the corresponding private key. (I am not sure about it, because encryption with private key is normally called signing).
The Python code given below works fine if we have an appropriate public key file:
def... | [
"Without knowing the M2Crypto library (but knowing a bit of cryptography), it looks like the public_decrypt function is just a wrapper around OpenSSL's RSA_public_decrypt function, a low-level RSA operation.\nThis is seldom useful per se, but it internally used in the signature verification operation.\nAs the decry... | [
0
] | [] | [] | [
"c#",
"cryptography",
"m2crypto",
"python",
"rsa"
] | stackoverflow_0008306832_c#_cryptography_m2crypto_python_rsa.txt |
Q:
Coordinating distributed Python processes using queuing or REST web service
Server A has a process that exports n database tables as flat files. Server B contains a utility that loads the flat files into a DW appliance database.
A process runs on server A that exports and compresses about 50-75 tables. Each time ... | Coordinating distributed Python processes using queuing or REST web service | Server A has a process that exports n database tables as flat files. Server B contains a utility that loads the flat files into a DW appliance database.
A process runs on server A that exports and compresses about 50-75 tables. Each time a table is exported and a file produced, a .flag file is also generated.
Server B... | [
"Message brokers such as Rabbit contain practical solutions for a number of problems:\n\nmultiple producers and consumers are supported without risk of duplication of messages\natomicity and unit-of-work logic provide transactional integrity, preventing duplication and loss of messages in the event of failure\nhori... | [
3,
2
] | [] | [] | [
"concurrency",
"data_warehouse",
"message_queue",
"python",
"rest"
] | stackoverflow_0008298571_concurrency_data_warehouse_message_queue_python_rest.txt |
Q:
Parse email and get number from body
I want to extract the first number found in an e-mail body. With the help with email library I extracted just the body from the mail to a string. But the problem is that before the real plain-text body begins there is some info about encoding and such (those contains digits). H... | Parse email and get number from body | I want to extract the first number found in an e-mail body. With the help with email library I extracted just the body from the mail to a string. But the problem is that before the real plain-text body begins there is some info about encoding and such (those contains digits). How can I skip those on a reliable way that... | [
"You may want to use the iterators to skip over the subpart headers.\nhttp://docs.python.org/library/email.iterators.html#module-email.iterators\nThis example will print the body of each message subpart that is text/plain:\nfor part in email.iterators.typed_subpart_iterator(msg, 'text', 'plain'):\n for body_line ... | [
6,
0
] | [] | [] | [
"email",
"python",
"regex"
] | stackoverflow_0008317951_email_python_regex.txt |
Q:
Python: Is it possible to have a list of lists? and how do I call a particular list?
Here is what I am thinking:
MSILISTS = [
AC_LIST = [
'somename.msi',
'someothername.msi',
]
]
i am not sure if this is right...
but the problem is how do I set it up with lots of these individual lists an... | Python: Is it possible to have a list of lists? and how do I call a particular list? | Here is what I am thinking:
MSILISTS = [
AC_LIST = [
'somename.msi',
'someothername.msi',
]
]
i am not sure if this is right...
but the problem is how do I set it up with lots of these individual lists and then call them?
| [
"You either want to use nested lists:\nMSILISTS = [\n [\n 'somename.msi',\n 'someothername.msi',\n ],\n]\n\nprint MSILISTS[0]\n\nOr use a dictionary:\nMSILISTS = {\n 'AC_LIST': [\n 'somename.msi',\n 'someothername.msi',\n ]\n}\n\nprint MSILISTS['AC_LIST']\n\n",
"If you want... | [
3,
2,
2,
1,
1,
0,
0
] | [] | [] | [
"list",
"python"
] | stackoverflow_0008318167_list_python.txt |
Q:
What are the steps to convert from using libglade to GtkBuilder? (Python)
I have a small project that uses libglade and use the following to load the xml file:
self.gladefile = "sdm.glade"
self.wTree = gtk.glade.XML(self.gladefile)
self.window = self.wTree.get_widget("MainWindow")
if (self.window):
self.wind... | What are the steps to convert from using libglade to GtkBuilder? (Python) | I have a small project that uses libglade and use the following to load the xml file:
self.gladefile = "sdm.glade"
self.wTree = gtk.glade.XML(self.gladefile)
self.window = self.wTree.get_widget("MainWindow")
if (self.window):
self.window.connect("destroy", gtk.main_quit)
dic = { "on_button1_clicked" : self.button... | [
"You need to use gtk.Builder instead. This class can load any number of UI files, so you need to add them manually, either as files or as strings:\nself.uifile = \"sdm.ui\"\nself.wTree = gtk.Builder()\nself.wTree.add_from_file(self.uifile)\n\nInstead of get_widget, just use get_object on the builder class:\nself.wi... | [
11,
5
] | [] | [] | [
"glade",
"gtkbuilder",
"pygtk",
"python"
] | stackoverflow_0000748872_glade_gtkbuilder_pygtk_python.txt |
Q:
Trouble during building step of MPI for python
I am a bit stuck during the building process of the MPI python v 1.2.2 installation. Specifically, I get the following error message:
i686-apple-darwin10-gcc-4.2.1: /Library/Frameworks/Python.framework/Versions/7.1/Python/Versions/7.1/Python: Not a directory
warning: ... | Trouble during building step of MPI for python | I am a bit stuck during the building process of the MPI python v 1.2.2 installation. Specifically, I get the following error message:
i686-apple-darwin10-gcc-4.2.1: /Library/Frameworks/Python.framework/Versions/7.1/Python/Versions/7.1/Python: Not a directory
warning: build_exe: building extension "python2.7-mpi" failed... | [
"Any one of them should work, the one which seems the easiest is:\n$ python setup.py build --mpicc=/where/you/have/mpicc\n\nSo you would simply run\n$ python setup.py build --mpicc=/Library/Frameworks/Python.framework/Versions/7.1\n\nAssuming that is where mpicc is located.\nDoes this help?\n"
] | [
1
] | [] | [] | [
"python"
] | stackoverflow_0008318278_python.txt |
Q:
Force eclipse to reload Python modules
I have started a Eclipse PyDev project, and found out that BeautifulSoup was missing.
I installed it using easy_install, and now the scripts runs fine from the command line. Eclipse, however, still thinks that BeautifulSoup isn't installed, displaying an annoying error messag... | Force eclipse to reload Python modules | I have started a Eclipse PyDev project, and found out that BeautifulSoup was missing.
I installed it using easy_install, and now the scripts runs fine from the command line. Eclipse, however, still thinks that BeautifulSoup isn't installed, displaying an annoying error message and not supplying any introspection or aut... | [
"You have to reconfigure the python interpreters. Normally the automatic configuration utility should discover everything by itself, but otherwise you can manually add/remove packages. Here's a screenshot of where the settings are located:\n\nIn the only occasion in which I can recall I needed to do that, all I did... | [
2
] | [] | [] | [
"eclipse",
"pydev",
"python",
"setuptools"
] | stackoverflow_0008318103_eclipse_pydev_python_setuptools.txt |
Q:
Creating Dynamic Text Using the blit method
I'm creating a basic game where a black square moves around the screen. There are two other squares, a green square and a red square. When the black square collides with the red square it quits the program, when it collides with the green square it adds to your points co... | Creating Dynamic Text Using the blit method | I'm creating a basic game where a black square moves around the screen. There are two other squares, a green square and a red square. When the black square collides with the red square it quits the program, when it collides with the green square it adds to your points counter. I've got the red square part down but I'm ... | [
"Honestly, I don't think you really need a separate class for the score, you can just have an add score method which is called whenever the rects for the big and little squares collide:\ndef addScore():\n global score\n score += 1 #just increasing thescore\n if pygame.font: #checking if the font loading... | [
0
] | [] | [] | [
"pygame",
"python"
] | stackoverflow_0008306288_pygame_python.txt |
Q:
Installing Thrift with Python bindings on Windows 7 32-bit
I am trying to install pycassa, a Cassandra client in Python, on Windows 7.
Running pip install pycassa I got this error message:
error: unable to find vcvarsall.bat
Digging deeper, I found that Python failed to install the thrift library and Python bindi... | Installing Thrift with Python bindings on Windows 7 32-bit | I am trying to install pycassa, a Cassandra client in Python, on Windows 7.
Running pip install pycassa I got this error message:
error: unable to find vcvarsall.bat
Digging deeper, I found that Python failed to install the thrift library and Python bindings. One way people suggest is to install a C++ compiler, such a... | [
"Thrift really has two (kinds of) components: there's the Thrift compiler, which generates code given an interface, and then there are the per-language libraries, which implement the low-level thrift protocols and transports for each language.\nYou almost certainly don't need the Thrift compiler, which is what you ... | [
3
] | [] | [] | [
"cassandra",
"pycassa",
"python",
"thrift",
"windows_7"
] | stackoverflow_0008310966_cassandra_pycassa_python_thrift_windows_7.txt |
Q:
Iteration through lists of different length
I have to use a backwards loop:
for i in range(len(my_ls))[::-1]:
print i
But some of the lists have length = 1 (as in ['one']).
As a result the interpreter prints nothing at all.
Nevertheless, in python's own shell it works all right and 0 is printed, as was planne... | Iteration through lists of different length | I have to use a backwards loop:
for i in range(len(my_ls))[::-1]:
print i
But some of the lists have length = 1 (as in ['one']).
As a result the interpreter prints nothing at all.
Nevertheless, in python's own shell it works all right and 0 is printed, as was planned.
Any ideas how to overcome this problem?
I run ... | [
"Could you not just pass the list to reversed()[docs] and then iterate over the resulting reverse iterator?\nfor x in reversed(lst):\n print x\n\n",
"Is this what you are trying to achieve?\n>>> li = ['one']\n>>> for i in range(len(li)-1, -1, -1):\n... print li[i]\n... \none\n\nEDIT: The difference between... | [
4,
1,
0
] | [] | [] | [
"loops",
"python"
] | stackoverflow_0008318590_loops_python.txt |
Q:
What multinlingual database support for Django 1.3?
I am using Django for quite a while but each time I ask myself the same question again and again.
Which multilingual database backend should I use ?
I used django-multilingual on Django 1.1, django-multilingual-ng on Django 1.2
I add a look at django-nani for Dj... | What multinlingual database support for Django 1.3? | I am using Django for quite a while but each time I ask myself the same question again and again.
Which multilingual database backend should I use ?
I used django-multilingual on Django 1.1, django-multilingual-ng on Django 1.2
I add a look at django-nani for Django 1.3 but there quite few problems :
No ModelAdmin AP... | [
"Take a look a these ressource pages:\n\nDjango Packages Model translation\nDjango Packages Internationalization\nDjango Wiki Model Internationalization\n\n",
"one solution is to use this projet that is made by the creator of django-multilingual-ng (\ndjango-hvad )\nbut the probleme is that it's in alpha state.\n... | [
2,
1,
0
] | [] | [] | [
"django",
"django_multilingual",
"multilingual",
"orm",
"python"
] | stackoverflow_0007401573_django_django_multilingual_multilingual_orm_python.txt |
Q:
vim autocomplete for pymongo
How can I setup vim & pymongo autocomplete for the code below:
import pymongo
connection = pymongo.Connection()
collection = connection["msg"].posts
result = collection.<tab>
Autocomplete in general works but it doesn't seem to be contextual, it just shows everything.
A:
Check out ... | vim autocomplete for pymongo | How can I setup vim & pymongo autocomplete for the code below:
import pymongo
connection = pymongo.Connection()
collection = connection["msg"].posts
result = collection.<tab>
Autocomplete in general works but it doesn't seem to be contextual, it just shows everything.
| [
"Check out Pydiction for vim. Although I have not tried it with third party modules, the documentation says it should work:\n'Pydiction can complete Python's keywords, built-in functions, and string literals, as well as standard, custom and third-party package and module names and their attributes and methods. It c... | [
1
] | [] | [] | [
"autocomplete",
"pymongo",
"python",
"vim"
] | stackoverflow_0006707960_autocomplete_pymongo_python_vim.txt |
Q:
Map actors and their movie onto a dictionary
def parse_actor_data(actor_data):
while 1:
line = actor_data.readline().strip()
if line.count('-') > 5:
break
actor_movie = {}
values = []
actor_name = ''
running_list = []
movie = []
for line in actor_data:
... | Map actors and their movie onto a dictionary | def parse_actor_data(actor_data):
while 1:
line = actor_data.readline().strip()
if line.count('-') > 5:
break
actor_movie = {}
values = []
actor_name = ''
running_list = []
movie = []
for line in actor_data:
position = line.find(')')
running = line... | [
"Every time you run:\nactor_movie[actor_name] = movie\n\nyou're overwriting the last movie that was associated with that actor. Try something like this instead where you're storing a list of movies, not just a single value:\ntry:\n actor_movie[actor_name].append(movie)\nexcept KeyError:\n actor_movie[actor_na... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0008318925_python.txt |
Q:
django manage.py settings default
I have a settings.py file and a dev_settings.py file that I use to override some values for dev purposes. Everytime I run the ./manage.py command, I have to specify --settings=whatever.local_settings. This becomes very tedious to do every time and I am trying to find a way to fo... | django manage.py settings default | I have a settings.py file and a dev_settings.py file that I use to override some values for dev purposes. Everytime I run the ./manage.py command, I have to specify --settings=whatever.local_settings. This becomes very tedious to do every time and I am trying to find a way to force manage.py to load my dev_settings.p... | [
"manage.py sets path to settings for you, that's why it's ignoring DJANGO_SETTINGS_MODULE (it's basically just script that wraps around django-admin.py).\nThere are 2 easy ways to fix your problem:\n\nset DJANGO_SETTINGS_MODULE and use django-admin.py to run all commands instead of manage.py. This is even better if... | [
16,
3,
2,
1,
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0008318688_django_python.txt |
Q:
How to copy files from a directory based on items in a list of filenames in Python
I'm new to Python and I have created following function to copy files from the directory(livepromptDir) based on the item in the list(promptList). So far, it only copy the first item in the list to the destination directory. Please ... | How to copy files from a directory based on items in a list of filenames in Python | I'm new to Python and I have created following function to copy files from the directory(livepromptDir) based on the item in the list(promptList). So far, it only copy the first item in the list to the destination directory. Please help! Thanks in advance.
def copyItemToPrompt():
#This function will copy all of the... | [
"You want to move the return outside of the for loop, otherwise your function returns after the first iteration. Actually, you don't even need the return:\ndef copyItemToPrompt():\n \"\"\"This function will copy all of the appropriate Voice Prompt files from LivePrompts directory to promptDir based on promptLis... | [
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0008318848_python.txt |
Q:
Strange behavior of QProgressBar with PyQt4
I have this sample of code:
import sys
import time
from PyQt4.QtGui import *
from PyQt4.QtCore import *
class Bar(QDialog):
def __init__(self, parent=None):
super(Bar, self).__init__()
self.pbar = QProgressBar(self)
self.pbar.setV... | Strange behavior of QProgressBar with PyQt4 | I have this sample of code:
import sys
import time
from PyQt4.QtGui import *
from PyQt4.QtCore import *
class Bar(QDialog):
def __init__(self, parent=None):
super(Bar, self).__init__()
self.pbar = QProgressBar(self)
self.pbar.setValue(0)
layout = QHBoxLayout()
la... | [
"Try adding a\nQApplication.processEvents()\n\njust after print value (this should force the UI to update).\n"
] | [
1
] | [] | [] | [
"linux",
"progress",
"pyqt",
"python",
"qt"
] | stackoverflow_0008318977_linux_progress_pyqt_python_qt.txt |
Q:
Specify that packages should be automatically unzipped
I just ran into a weird issue where Django is unable to look inside of zipped egg files when searching for fixtures. I've noticed that in my project's eggs folder, some projects are unzipped to directories and some are left in their zip files. Is there a way f... | Specify that packages should be automatically unzipped | I just ran into a weird issue where Django is unable to look inside of zipped egg files when searching for fixtures. I've noticed that in my project's eggs folder, some projects are unzipped to directories and some are left in their zip files. Is there a way for me to specify in setup.py that my project must be unzippe... | [
"Yes, TK, there is. Use the zip_safe parameter to the setup() method to tell setup that your file needs to be unzipped:\nsetup(\n ...\n zip_safe = False,\n ...\n)\n\n"
] | [
1
] | [] | [] | [
"buildout",
"python",
"setuptools"
] | stackoverflow_0008319255_buildout_python_setuptools.txt |
Q:
developer tools used in programming
I am a pretty recent developer..
but I have a single monitor (big enough) but it is so annoying that every now and then I first use the text editor to write the code and then go to terminal to execute and debug
I was wondering if there is any developer tools where I can like use... | developer tools used in programming | I am a pretty recent developer..
but I have a single monitor (big enough) but it is so annoying that every now and then I first use the text editor to write the code and then go to terminal to execute and debug
I was wondering if there is any developer tools where I can like use half screen for that note pad and the ot... | [
"Use ViM in split window mode, edit your script on the left side and start ConqueTerm (use :ConqueTerm bash) on the right side. Now you can code and execute Python code in the same terminal window at the same time using a superior text editor ;-)\nDisclaimer: Of course this only helps if you are familiar with ViM a... | [
3,
2,
2,
1,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0008319090_python.txt |
Q:
try except and programming etiquette
I'm making a GUI and I'm finding myself to be using a lot of try except statements. My question is, should I be redesigning my program to use less try except statements or is try except a good practice to be using in python programs? I like them because they're informative an... | try except and programming etiquette | I'm making a GUI and I'm finding myself to be using a lot of try except statements. My question is, should I be redesigning my program to use less try except statements or is try except a good practice to be using in python programs? I like them because they're informative and make debugging, for me, easier. Just wo... | [
"One of Python's idioms is: It's easier to ask for forgiveness than for permission. (Python Glossary, have a look at EAFP).\nSo it's perfectly acceptable to structure program flow with exception handling (and reasonably fast too, compared to other languages). It fits Python's dynamic nature nicely imho.\n",
"One ... | [
7,
4,
2
] | [] | [] | [
"python"
] | stackoverflow_0008319401_python.txt |
Q:
Scipy - Inverse Sampling Method from custom probability density function
I am trying to perform an inverse sampling from a custom probability density function (PDF). I am just wondering if this even possible, i.e. integrating the PDF, inverting the result and then solving it for a given uniform number. The PDF has... | Scipy - Inverse Sampling Method from custom probability density function | I am trying to perform an inverse sampling from a custom probability density function (PDF). I am just wondering if this even possible, i.e. integrating the PDF, inverting the result and then solving it for a given uniform number. The PDF has the shape f(x, alpha, mean(x))=(1/Gamma(alpha+1)(x))((x*(alpha+1)/mean(x))^(... | [
"Assuming you mean that you're trying to randomly choose values which will be distributed according to your PDF, then yes, it is possible. This is described on Wikipedia as inverse transform sampling. Basically, it's just what you said: integrate the PDF to produce the cumulative distribution (CDF), invert it (whic... | [
4
] | [] | [] | [
"numpy",
"python",
"scipy"
] | stackoverflow_0008319498_numpy_python_scipy.txt |
Q:
Communication between PHP and Python with XML-RPC
I want communicate between php and python with XML-RPC.
Is it possible to run XML-RPC on different server similar to what is depicted in the diagram below?
(source: picofile.com)
A:
Yes. XML-RPC is language agnostic. PHP has xml-rpc libraries, and so does Pyth... | Communication between PHP and Python with XML-RPC | I want communicate between php and python with XML-RPC.
Is it possible to run XML-RPC on different server similar to what is depicted in the diagram below?
(source: picofile.com)
| [
"Yes. XML-RPC is language agnostic. PHP has xml-rpc libraries, and so does Python.\n"
] | [
1
] | [] | [] | [
"php",
"python",
"rpc",
"xml_rpc"
] | stackoverflow_0007703283_php_python_rpc_xml_rpc.txt |
Q:
Python string issue
This is to take text from a file and combine with a string to print to a new file for a combined result
file = open('/home/user/facts', 'r')
result = open('/home/user/result.txt', 'a')
i = 1
for line in file:
print >>result, "fact_text[%d] = \"%s\";"% (i, line)
i += 1
For some reason t... | Python string issue | This is to take text from a file and combine with a string to print to a new file for a combined result
file = open('/home/user/facts', 'r')
result = open('/home/user/result.txt', 'a')
i = 1
for line in file:
print >>result, "fact_text[%d] = \"%s\";"% (i, line)
i += 1
For some reason the "; is showing up on a ... | [
"When reading lines from a file using for line in file the resulting string contains a newline character. You can strip it off using line.strip(). So your print statement becomes:\nprint >>result, \"fact_text[%d] = \\\"%s\\\";\" % (i, line.strip())\n\n",
"Because line contains a newline character at the end. You... | [
6,
1
] | [] | [] | [
"python",
"string"
] | stackoverflow_0008320106_python_string.txt |
Q:
Indexing chat logs and searching them in Django
My Django application needs to be able to search large volumes of chat logs that are stored on another Postgres DB i.e. a different one that my Django's DB. Initially users on the site would be using simple full-text search the logs but later we intend to parse these... | Indexing chat logs and searching them in Django | My Django application needs to be able to search large volumes of chat logs that are stored on another Postgres DB i.e. a different one that my Django's DB. Initially users on the site would be using simple full-text search the logs but later we intend to parse these logs using NLP.
What would be a better indexing opti... | [
"Also check out Haystack\n",
"It won't be completely painless to implement, but I think if you want to do full text search the clear answer is Solr/Lucene as far as open source implementations go. Caveat: I don't use Solr with Python, and I've never used Sphinx.\nThe pipeline would be something like read the logs... | [
1,
0
] | [] | [] | [
"django",
"full_text_search",
"nlp",
"python",
"search"
] | stackoverflow_0008309056_django_full_text_search_nlp_python_search.txt |
Q:
comparing two files and writing the missing values to a file
I have a problem when I try to compare two large files. What I am trying to do is take a line from one file, search all the lines of another file for a match and if there isn't one, write that line to another file. I was able to recreate the problem wi... | comparing two files and writing the missing values to a file | I have a problem when I try to compare two large files. What I am trying to do is take a line from one file, search all the lines of another file for a match and if there isn't one, write that line to another file. I was able to recreate the problem with the simple example below:
file1.txt (contents)
apple
banana
pea... | [
"srgerg's answer will work.\nHowever, reading through files multiple times will have a very large runtime complexity. Therefore, if the files (though large) are small enough to fit into memory, then you might consider putting all the lines in file_old into a data structure for comparison:\nold_lines = set((line.str... | [
4,
2,
1,
1,
1,
0
] | [] | [] | [
"compare",
"file",
"loops",
"python"
] | stackoverflow_0008319970_compare_file_loops_python.txt |
Q:
Redis add element value to a set in a transaction
I'm very new to redis and I'm trying to do the following inside a tranaction:
increment key
add incremented value from before to a set
using redis commands it would be something like
multi
i = incr "value"
sadd "set" i
exec
Is there any redis command that would do... | Redis add element value to a set in a transaction | I'm very new to redis and I'm trying to do the following inside a tranaction:
increment key
add incremented value from before to a set
using redis commands it would be something like
multi
i = incr "value"
sadd "set" i
exec
Is there any redis command that would do that in one step with out needing two transactions and... | [
"Unfortunately you can't do that directly. You can use a MULTI/EXEC block to guarantee atomicity of the query in the following way:\ndo {\n WATCH value\n i = 1 + GET value\n MULTI\n set value i\n SADD set i\n result = EXEC\n} while (result == nil)\n\n",
"There is a GETSET (http://redis.io/comman... | [
3,
0
] | [] | [] | [
"python",
"redis",
"transactions"
] | stackoverflow_0008317093_python_redis_transactions.txt |
Q:
Emulate Keystrokes with Python in Linux
I am writing a script in Python using Selenium that auto fills out a web form (a helpdesk ticketing system)
A factor in this is the body of the ticket does not have an element id that Selenium recognizes, so in order to type in the body I have to find the title element, pre... | Emulate Keystrokes with Python in Linux | I am writing a script in Python using Selenium that auto fills out a web form (a helpdesk ticketing system)
A factor in this is the body of the ticket does not have an element id that Selenium recognizes, so in order to type in the body I have to find the title element, press the tab key, then start typing in to the b... | [
"You have a bug in your code. Change this:\nbody = open(email.txt)\n\nto:\nbody = open(\"email.txt\").read()\n\n"
] | [
2
] | [] | [] | [
"python",
"selenium_webdriver"
] | stackoverflow_0008316118_python_selenium_webdriver.txt |
Q:
How to make sure a script only runs after another script
I have two python scripts running as cronjobs.
ScriptA processes log files and insert records to a table, ScriptB uses the records to generate a report.
I have arranged ScriptA to run one hour before ScriptB, but sometimes ScriptB run before ScriptA finish i... | How to make sure a script only runs after another script | I have two python scripts running as cronjobs.
ScriptA processes log files and insert records to a table, ScriptB uses the records to generate a report.
I have arranged ScriptA to run one hour before ScriptB, but sometimes ScriptB run before ScriptA finish inserting, thus generating a incorrect report.
How do I make su... | [
"Wouldn't it be better to make a single cron job that runs ScriptA and then ScriptB? That way you can be sure that ScriptB doesn't run until ScriptA finishes, and you don't need to modify either script.\nThe cronjob could run a simple shell script like:\n#!/bin/sh\n\npython ScriptA.py\npython ScriptB.py\n\nEdit: If... | [
9,
2,
0,
0
] | [] | [] | [
"bash",
"cron",
"crontab",
"python"
] | stackoverflow_0008320304_bash_cron_crontab_python.txt |
Q:
How to load user CSS in a WebKit WebView using PyObjC?
I'd like to have a small browser that uses my own CSS.
The problem is that CSS is not loaded or, I guess, it loads but without any effect.
Here is the full code (I don't use an Interface Builder):
import Foundation
import WebKit
import AppKit
import objc
def ... | How to load user CSS in a WebKit WebView using PyObjC? | I'd like to have a small browser that uses my own CSS.
The problem is that CSS is not loaded or, I guess, it loads but without any effect.
Here is the full code (I don't use an Interface Builder):
import Foundation
import WebKit
import AppKit
import objc
def main():
app = AppKit.NSApplication.sharedApplication()
... | [
"Apple doesn't properly document that setUserStyleSheetLocation can only be a local path or data: URL. Qt does explain this in their documentation of the corresponding setting in QtWebKit:\nhttp://doc.qt.nokia.com/latest/qwebsettings.html#setUserStyleSheetUrl\n\nSpecifies the location of a user stylesheet to load w... | [
3
] | [] | [] | [
"css",
"objective_c",
"pyobjc",
"python",
"webkit"
] | stackoverflow_0007221699_css_objective_c_pyobjc_python_webkit.txt |
Q:
How do I install SQLObject for use with Python?
I need to use SQLObject with Python and I downloaded SQLObject-1.0.0-py2.6.egg but I have no idea what to do next.
A:
For unix-type machines you should use easy_install (or better yet pip):
easy_install sqlobject
or
pip install sqlobject
(you might have to do th... | How do I install SQLObject for use with Python? | I need to use SQLObject with Python and I downloaded SQLObject-1.0.0-py2.6.egg but I have no idea what to do next.
| [
"For unix-type machines you should use easy_install (or better yet pip):\neasy_install sqlobject\n\nor \npip install sqlobject\n\n(you might have to do this as root).\nIf you're using Windows you'll need to install either easy_install or pip.\nYou can get details on this at this question.\nThis will install SQLObje... | [
2
] | [] | [] | [
"python",
"python_3.x",
"sqlobject"
] | stackoverflow_0005492780_python_python_3.x_sqlobject.txt |
Q:
Block and hide QDialog: Alternative to exec_()?
In my Qt-based application (built using PyQt 4.8.6), I have a class that is a subclass of QtGui.QDialog:
class ModelDialog(QtGui.QDialog):
...
When I run the application's user interface, I can display the QDialog like so:
def main():
app = QtGui.QApplicatio... | Block and hide QDialog: Alternative to exec_()? | In my Qt-based application (built using PyQt 4.8.6), I have a class that is a subclass of QtGui.QDialog:
class ModelDialog(QtGui.QDialog):
...
When I run the application's user interface, I can display the QDialog like so:
def main():
app = QtGui.QApplication(sys.argv)
dialog = ModelDialog()
dialog.exe... | [
"Use app.exec_() instead of dialog.exec_().\n"
] | [
2
] | [] | [] | [
"exec",
"pyqt",
"pyqt4",
"python",
"qt"
] | stackoverflow_0008319687_exec_pyqt_pyqt4_python_qt.txt |
Q:
sh: -c: line 1: syntax error near unexpected token `;'
I'm testing on my python script:
#!/usr/bin/python
import os,sys
import glob
import commands
import gzip
from itertools import islice
f1=gzip.open("/home/xug/scratch/test_trim.fastq","w")
LIST=[]
N = 4
with open("/home/xug/scratch/test.fastq", "r") as f:
... | sh: -c: line 1: syntax error near unexpected token `;' | I'm testing on my python script:
#!/usr/bin/python
import os,sys
import glob
import commands
import gzip
from itertools import islice
f1=gzip.open("/home/xug/scratch/test_trim.fastq","w")
LIST=[]
N = 4
with open("/home/xug/scratch/test.fastq", "r") as f:
while True:
line_group = list(islice(f, N))
... | [
"(continuing from the comments above)\nTo remove trailing B from a string using Python's built-in re module, try:\nimport re\n\nl3_trim = re.sub(r\"B*$\", \"\", l3)\n\n"
] | [
2
] | [] | [] | [
"python"
] | stackoverflow_0008320111_python.txt |
Q:
Read .daq (Data Acquisition Toolbox for Matlab) file format in python
Anyone know of a way to read in .daq files generated with the Matlab Data Acquisition Toolbox in python? Alternatively, a simple way (using only open-source software) to convert the files to csv or .mat files which can be read by python would b... | Read .daq (Data Acquisition Toolbox for Matlab) file format in python | Anyone know of a way to read in .daq files generated with the Matlab Data Acquisition Toolbox in python? Alternatively, a simple way (using only open-source software) to convert the files to csv or .mat files which can be read by python would be ok.
| [
"I am not sure if you have solved this by now or not, but you can generate .mat files from the .daq files easily in matlab using daqread. In the command window:\nData = daqread(mydata.daq);\ncd(saveDir)\nsave('Data','Data')\n\nThe Data variable is a .mat file. This can easily be added to a file directory scanning f... | [
2
] | [] | [] | [
"file_io",
"matlab",
"python"
] | stackoverflow_0007692354_file_io_matlab_python.txt |
Q:
django-piston: How do I make an emitter return a downloadable file?
I have the following emitter:
class iCalEmitter(Emitter):
def render(self, request):
data = self.construct()
cal = Calendar()
cal.add('prodid', 'iCalendar Feed')
cal.add('version', '2.0')
for event in d... | django-piston: How do I make an emitter return a downloadable file? | I have the following emitter:
class iCalEmitter(Emitter):
def render(self, request):
data = self.construct()
cal = Calendar()
cal.add('prodid', 'iCalendar Feed')
cal.add('version', '2.0')
for event in data:
if event.get('start'):
event['start_time... | [
"Modifying response headers through an emitter is not an easy task, so I took a different route. I added a URL pattern to my app to match /events/calendar.ics and passed the emitter_format parameter through the URL pattern. Ugly, but it works.\n"
] | [
0
] | [] | [] | [
"django",
"django_piston",
"python"
] | stackoverflow_0008314847_django_django_piston_python.txt |
Q:
Data truncated for column 'cur_url' at row 1
Using django-socialregistration, got error messages:
Data truncated for column 'cur_url' at row 1
What went wrong here?
A:
You have tried to insert a larger value than field accepts, so it was literally "cut to fit".
| Data truncated for column 'cur_url' at row 1 | Using django-socialregistration, got error messages:
Data truncated for column 'cur_url' at row 1
What went wrong here?
| [
"You have tried to insert a larger value than field accepts, so it was literally \"cut to fit\".\n"
] | [
25
] | [] | [] | [
"django",
"python"
] | stackoverflow_0008321078_django_python.txt |
Q:
python dictionary creation
I have a class called Polynomial, and it stores information to the polynomial in a dictionary. The keys are the exponents and the values are the coefficients. To create an instance of the Polynomial class, you type the following:
P1 = Polynomial((2, 14), (2, 11), (-12, 3), (42, 0))
The ... | python dictionary creation | I have a class called Polynomial, and it stores information to the polynomial in a dictionary. The keys are the exponents and the values are the coefficients. To create an instance of the Polynomial class, you type the following:
P1 = Polynomial((2, 14), (2, 11), (-12, 3), (42, 0))
The first item in the pairing is the... | [
"A dictionary has one value per key. What would self.termdict[11] return otherwise?\n",
"The problem is here:\ntermdict = dict(termpairs)\n\nYou are \"converting\" your termpairs to a dict, so you will get something like:\n((2, 14), (2, 11), (-12, 3), (42, 0)) => {2: 14, 2: 11, -12: 3, 42: 0}\n\nIn a dict there c... | [
2,
2,
2,
1,
0,
0
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0008321525_dictionary_python.txt |
Q:
Conditional redirecting in Pyramid
I am looking for a way to redirect users to different routes/templates that is compatible with using @view_config.
I have a function that reads in an uploaded file and attempts to create a new model based on the file content. I was wondering if there was a clean way that I can re... | Conditional redirecting in Pyramid | I am looking for a way to redirect users to different routes/templates that is compatible with using @view_config.
I have a function that reads in an uploaded file and attempts to create a new model based on the file content. I was wondering if there was a clean way that I can redirect the user to one of two urls, base... | [
"What you are asking is not \"How to redirect\" but \"How to change renderer in the view function\". To answer quickly, I think you could use:\nrequest.override_renderer = 'other-renderer.mak'\n\nBut I don't think it's a good idea. Here's the usual pattern that is used most of the time to handle form submission:\nf... | [
5,
2
] | [] | [] | [
"pyramid",
"python",
"redirect",
"view"
] | stackoverflow_0008320089_pyramid_python_redirect_view.txt |
Q:
Does using an '_' for typename in a namedtuple do anything special?
I'm looking at code that does uses an _ for typename in a namedtuple. I was wondering what the purpose of this is.
example = namedtuple('_', ['NameOfClass1', 'NameOfClass2'])
Why not just use String?
A:
That is a somewhat odd example of a name... | Does using an '_' for typename in a namedtuple do anything special? | I'm looking at code that does uses an _ for typename in a namedtuple. I was wondering what the purpose of this is.
example = namedtuple('_', ['NameOfClass1', 'NameOfClass2'])
Why not just use String?
| [
"That is a somewhat odd example of a namedtuple. The whole point is to give meaningful names to the class and its attributes. Some of the features such as the __repr__ and the class docstring derive most of their benefit from meaningful names.\nFWIW, the namedtuple factory includes a verbose option which makes it... | [
4,
1
] | [] | [] | [
"collections",
"namedtuple",
"python",
"tuples"
] | stackoverflow_0007923493_collections_namedtuple_python_tuples.txt |
Q:
How to send list from server to client in twisted python?
I am doing a multiclient chat server program in twisted python. In my program, if we send 'list' from one client, server has to send the list of connected clients to that client. Also, when we send 'talk clientname message' from one client, server has to se... | How to send list from server to client in twisted python? | I am doing a multiclient chat server program in twisted python. In my program, if we send 'list' from one client, server has to send the list of connected clients to that client. Also, when we send 'talk clientname message' from one client, server has to send that message to the destination client specified in the 'cli... | [
"\nyou can't rely how much data dataReceived() receives. You might need to subclass from LineReceiver and use lineReceived() to process input line by line.\ntransport.write() accepts a string, not a list.\n\nYou need to define clientname for a client e.g., a factory should be able to find a client given its name. ... | [
1
] | [] | [] | [
"factory",
"python",
"tcp",
"twisted"
] | stackoverflow_0008321815_factory_python_tcp_twisted.txt |
Q:
Non SMTP email with Python
I want to send emails with custom 'FROM' field, like *noreply@example_company.com*, it's easy to do in PHP, but I don't know how to do that in python and can't find any good documentation.
in other words, what is the python equivalent of the following php code?
$to = "user@gmail.com";
$... | Non SMTP email with Python | I want to send emails with custom 'FROM' field, like *noreply@example_company.com*, it's easy to do in PHP, but I don't know how to do that in python and can't find any good documentation.
in other words, what is the python equivalent of the following php code?
$to = "user@gmail.com";
$subject = "Weekly news";
$messag... | [
"You will always have to send it to some smtp server, this is in fact what php also does, it uses the settings from php.ini on windows and the local mail delivery system on unix.\nhttp://php.net/manual/en/function.mail.php\nfrom the python documentation:\nhttp://docs.python.org/py3k/library/email-examples.html\nmai... | [
2
] | [] | [] | [
"python"
] | stackoverflow_0008322026_python.txt |
Q:
Modifying a namedtuple's constructor arguments via subclassing?
I want to create a namedtuple which represents the individual flags in a short bitfield. I'm trying to subclass it so that I can unpack the bitfield before the tuple is created. However, my current attempt isn't working:
class Status(collections.nam... | Modifying a namedtuple's constructor arguments via subclassing? | I want to create a namedtuple which represents the individual flags in a short bitfield. I'm trying to subclass it so that I can unpack the bitfield before the tuple is created. However, my current attempt isn't working:
class Status(collections.namedtuple("Status", "started checking start_after_check checked error p... | [
"You almost had it :-) There are just two little corrections:\n\nThe new method needs a return statement\nThe super call should have two arguments, cls and Status\n\nThe resulting code looks like this:\nimport collections\n\nclass Status(collections.namedtuple(\"Status\", \"started checking start_after_check check... | [
20,
10
] | [] | [] | [
"namedtuple",
"new_operator",
"python",
"super"
] | stackoverflow_0003474118_namedtuple_new_operator_python_super.txt |
Q:
MySQL syntax error?
I have searched on forums for the error I keep getting when running my code but it seems to be situation specific.
My program connects to a database, and takes a line from a text file, extracts the name from the line, and uses that name to do a search query in the database. The following is the... | MySQL syntax error? | I have searched on forums for the error I keep getting when running my code but it seems to be situation specific.
My program connects to a database, and takes a line from a text file, extracts the name from the line, and uses that name to do a search query in the database. The following is the relevant code:
while lin... | [
"If your language is Python, your SQL statement should look like:\ncur.execute(\"\"\"SELECT Date, Contrib, Amount, Street, City, State, Zip FROM indiv_contribs WHERE Contrib = %s, %s\"\"\", (last, first))\nrows = cur.fetchall()\n\n"
] | [
3
] | [] | [] | [
"database",
"mysql",
"python"
] | stackoverflow_0008320965_database_mysql_python.txt |
Q:
Creating a list from an existing list if a condition is true in Python
I'm trying to remove some items from a list,
list1 = ["CCC-C", "CCC-P", "CCC-A-P", "CCC-A-H", "CCC-J", "CCC-S-X"]
new_list = [i for i in list1 if (len(i) == 5 or len(i) == 7 or i[6] != "H")]
Unless any item in list1 has length 5 or 7, or its 7... | Creating a list from an existing list if a condition is true in Python | I'm trying to remove some items from a list,
list1 = ["CCC-C", "CCC-P", "CCC-A-P", "CCC-A-H", "CCC-J", "CCC-S-X"]
new_list = [i for i in list1 if (len(i) == 5 or len(i) == 7 or i[6] != "H")]
Unless any item in list1 has length 5 or 7, or its 7th character is "H", it shouldn't be in new_list.
But the code above include... | [
"Boolean expression in Python is executed in following order:\n>>> A() or B()\n\nIf A() returns True, there is no need to check B()\n>>> A() and B()\n\nIf A() return False, there is no need to check B()\nI hope it gives you some idea.\n",
"Do this:\nnew_list = [i for i in list1 if len(i)==5 or (len(i)==7 and i[6]... | [
2,
2,
0,
0
] | [] | [] | [
"conditional_statements",
"list",
"python"
] | stackoverflow_0008322239_conditional_statements_list_python.txt |
Q:
Save each column of an Excel file in a separate text file
I would like to save each column of an excel file in a separate text file.
For example..
ID, contents
1, aaa is bla bla bla
2, ccc is bla bla bla
I would like to save 1 aaa is bla bla bla in a.txt
and save 2 ccc is blablabla in b.txt.
How can I do this in ... | Save each column of an Excel file in a separate text file | I would like to save each column of an excel file in a separate text file.
For example..
ID, contents
1, aaa is bla bla bla
2, ccc is bla bla bla
I would like to save 1 aaa is bla bla bla in a.txt
and save 2 ccc is blablabla in b.txt.
How can I do this in Python?
| [
"If there is a Python question in here, the answer is likely to use csv module :-)\nIf it is an Excel question, there is a SaveAs option for \"Tab Delimited Text (.txt)\" and another for \"Comma Separated Values (*.csv)\". Here is a step-by-step tutorial: http://www.howtogeek.com/79991/convert-an-excel-spreadshee... | [
1,
0
] | [] | [] | [
"excel",
"python"
] | stackoverflow_0008322656_excel_python.txt |
Q:
Unable to truly background an SSH tunnel using Fabric and nohup
I can't seem to get Fabric to play nice with backgrounding a process that I've used nohup on. . . It should be possible, given various pieces of information, including here and here.
def test():
h = 'xxxxx.compute-1.amazonaws.com'
ports = [16646, ... | Unable to truly background an SSH tunnel using Fabric and nohup | I can't seem to get Fabric to play nice with backgrounding a process that I've used nohup on. . . It should be possible, given various pieces of information, including here and here.
def test():
h = 'xxxxx.compute-1.amazonaws.com'
ports = [16646, 9090, 6666]
with settings(host_string = h):
tun_s = "ssh -o Str... | [
"So, it seems after much wrangling that this is not possible for whatever reason with my setup (default Ubuntu installs on EC2 instances). I have no idea why and as it seems possible according to various sources.\nI fixed my particular problem by using Paramiko in place of Fabric, for calls that need to be left run... | [
0
] | [] | [] | [
"bash",
"fabric",
"nohup",
"python",
"ssh"
] | stackoverflow_0008318407_bash_fabric_nohup_python_ssh.txt |
Q:
python parallel Popen
I've been puzzling this for whole night now...
makeflags = ['--prefix=/usr','--libdir=/usr/lib']
rootdir='/tmp/project'
ps = set()
def configModule(m):
print m
return Popen(["./autogen.sh"] + makeflags, cwd=rootdir+"/"+m)
for module in ['mod1','mod2','mod3' ... 'mod10']:
ps.add... | python parallel Popen | I've been puzzling this for whole night now...
makeflags = ['--prefix=/usr','--libdir=/usr/lib']
rootdir='/tmp/project'
ps = set()
def configModule(m):
print m
return Popen(["./autogen.sh"] + makeflags, cwd=rootdir+"/"+m)
for module in ['mod1','mod2','mod3' ... 'mod10']:
ps.add(configModule(module))
os.... | [
"Your code works for me, and should start all the processes. You're not giving us much to work with: what behavior differs?\nYou're not redirecting output in the code you pasted, so you're probably seeing the childs' stderr streams. One thing though is that:\nos.wait()\n\n…will only wait for 1 process. You might wa... | [
1,
1
] | [] | [] | [
"multiprocessing",
"parallel_processing",
"python",
"subprocess"
] | stackoverflow_0008322841_multiprocessing_parallel_processing_python_subprocess.txt |
Q:
dynamic FileField path
I'm trying to use get_file_path function to generate dynamic path. Can I use Album slug field instead of this str(instance.id) in get_file_path? thanks
Here is models
def get_file_path(instance, filename):
return os.path.join('files', str(instance.id), filename)
class Album(models.Mod... | dynamic FileField path | I'm trying to use get_file_path function to generate dynamic path. Can I use Album slug field instead of this str(instance.id) in get_file_path? thanks
Here is models
def get_file_path(instance, filename):
return os.path.join('files', str(instance.id), filename)
class Album(models.Model):
name = models.CharF... | [
"Quite straightforward: str(instance.album.slug)\n",
"Yes, just use instance.slug instead of instance.id\nAnother example you can find in the answer of post Change filename before save file in Django\nUpdate: If not all instances have a slug field than you could be interested in a solution like this:\ndef get_fil... | [
2,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0008322413_django_python.txt |
Q:
Mechanize not being installed by easy_install?
I am in the process of migrating from an old Win2K machine to a new and much more powerful Vista 64 bit PC. Most of the migration has gone fairly smoothly - but I did find that I needed to reinstall ALL of my Python related tools.
I've downloaded the mechanize-0.1.11.... | Mechanize not being installed by easy_install? | I am in the process of migrating from an old Win2K machine to a new and much more powerful Vista 64 bit PC. Most of the migration has gone fairly smoothly - but I did find that I needed to reinstall ALL of my Python related tools.
I've downloaded the mechanize-0.1.11.tar.gz file and ran easy_install to install it. This... | [
"There is a note on the py2exe site that it does not work if the source is in egg format:\n\npy2exe does not currently (as of\n 0.6.5) work out of the box if some of your program's dependencies are in\n .egg form.\nIf your program does not itself use\n setuptools facilities (eg,\n pkg_resources), then all you n... | [
2,
0
] | [] | [] | [
"easy_install",
"mechanize",
"python"
] | stackoverflow_0001151256_easy_install_mechanize_python.txt |
Q:
Are classless methods in Python useful for anything?
I just noticed that you can do this in Python:
def f(self):
print self.name
class A:
z=f
name="A"
class B:
z=f
name = "B"
…
print a.z()
>>> A
In other words, f() behaves like a method that is not defined on any class, but can be attached... | Are classless methods in Python useful for anything? | I just noticed that you can do this in Python:
def f(self):
print self.name
class A:
z=f
name="A"
class B:
z=f
name = "B"
…
print a.z()
>>> A
In other words, f() behaves like a method that is not defined on any class, but can be attached to one. And of course it will produce a runtime error if ... | [
"Yes, it is useful and it does serve a purpose, but it is also quite rare to have to do this. If you think you need to patch classes after they've been defined you should always stop and consider whether it really is the best way.\nOne situation is monkey-patching. I've done this in a large Plone system where some ... | [
7,
3,
2
] | [] | [] | [
"class",
"methods",
"python"
] | stackoverflow_0008322261_class_methods_python.txt |
Q:
Is Sentry compatible with Mongodb?
Is Sentry (python/django) compatible with Mongodb?
If not, is there an easy solution to make it compatible?
Thanks guys.
A:
Sentry is built on a relational DB, and thus will require such for the foreseeable future. It's possible to implement most things in many NoSQL solutions,... | Is Sentry compatible with Mongodb? | Is Sentry (python/django) compatible with Mongodb?
If not, is there an easy solution to make it compatible?
Thanks guys.
| [
"Sentry is built on a relational DB, and thus will require such for the foreseeable future. It's possible to implement most things in many NoSQL solutions, but the various types of indexes, and some of the (newer) advanced SQL would be a lot more work.\nAs an example, Sentry 2.0 includes a \"Trending\" option, whic... | [
3,
0
] | [] | [] | [
"django",
"mongodb",
"python",
"sentry"
] | stackoverflow_0008175353_django_mongodb_python_sentry.txt |
Q:
Import subclass from a base class in Python
I have a base class that has a method that creates an instance of a subclass that is called the same as the input string.
This worked before by putting the subclasses and the base class in the same file, and doing something like globals()[name].
Now, however, I've split ... | Import subclass from a base class in Python | I have a base class that has a method that creates an instance of a subclass that is called the same as the input string.
This worked before by putting the subclasses and the base class in the same file, and doing something like globals()[name].
Now, however, I've split up the subclasses into other files. They each ha... | [
"You can move the import statement that is failing to the method that creates the subclass object.\n",
"From what I'm understanding, you have:\n\nA base class\nA series of derived classes from the base class\nA factory method in the base class that instantiates the correct type of derived class\nThe derived class... | [
7,
7,
0
] | [] | [] | [
"base",
"import",
"inheritance",
"python",
"subclass"
] | stackoverflow_0008323872_base_import_inheritance_python_subclass.txt |
Q:
How to pass command-line parameters to a Perl script executed from Python
I have written this code to run a Perl script from my Python script:
#!/usr/bin/python
import subprocess
var = "/some/file/path/"
pipe = subprocess.Popen(["perl", "./SignalPktSender.pl ", var], stdin=subprocess.PIPE)
But my perl script ne... | How to pass command-line parameters to a Perl script executed from Python | I have written this code to run a Perl script from my Python script:
#!/usr/bin/python
import subprocess
var = "/some/file/path/"
pipe = subprocess.Popen(["perl", "./SignalPktSender.pl ", var], stdin=subprocess.PIPE)
But my perl script needs command line arguments. How can I pass command arguments to the Perl script... | [
"From the Python docs on the subprocess module:\n\nclass subprocess.Popen(args, bufsize=0, executable=None, stdin=None, stdout=None, stderr=None, preexec_fn=None, close_fds=False, shell=False, cwd=None, env=None, universal_newlines=False, startupinfo=None, creationflags=0)\nArguments are:\nargs should be a string, ... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0008324015_python.txt |
Q:
Scraping dynamic content in a website
I need to scrape news announcements from this website, Link.
The announcements seem to be generated dynamically. They dont appear in the source. I usually use mechanize but I assume it wouldnt work. What can I do for this? I'm ok with python or perl.
A:
If the content is gen... | Scraping dynamic content in a website | I need to scrape news announcements from this website, Link.
The announcements seem to be generated dynamically. They dont appear in the source. I usually use mechanize but I assume it wouldnt work. What can I do for this? I'm ok with python or perl.
| [
"If the content is generated dynamically, you can use Windmill or Seleninum to drive the browser and get the data once it's been rendered.\nYou can find an example here.\n",
"The polite option would be to ask the owners of the site if they have an API which allows you access to their news stories.\nThe less polit... | [
11,
4,
0
] | [
"In python you can use urllib and urllib2 to connect to a website and collect data. For example:\nfrom urllib2 import urlopen\nmyUrl = \"http://www.marketvectorsindices.com/#!News/List\"\ninStream = urlopen(myUrl)\ninstream.read(1024) # etc, in a while loop\n# all your fun page parsing code (perhaps: import from x... | [
-8
] | [
"perl",
"python",
"web_scraping"
] | stackoverflow_0008323728_perl_python_web_scraping.txt |
Q:
Python: String replacement (replace hyphens with underscores) in all tag names inside an XML
I have a not-so-well formed XML with hyphens inside the tag names, which I want to replace with underscores (to be able to work with lxml.objectify). I want to replace ALL tag names, including nested childs.
A sample XML:... | Python: String replacement (replace hyphens with underscores) in all tag names inside an XML | I have a not-so-well formed XML with hyphens inside the tag names, which I want to replace with underscores (to be able to work with lxml.objectify). I want to replace ALL tag names, including nested childs.
A sample XML:
<job>
<server>
<cpu-set>
</cpu-set>
</server>
<ip-routings>
</ip-routings>
</job>... | [
"Use xpath to find the elements with hyphens and re-write tags:\nfrom lxml import etree\ndata = \"\"\"<job>\n <server>\n <cpu-set>\n </cpu-set>\n </server>\n <ip-routings>\n </ip-routings>\n</job>\"\"\"\ndoc = etree.XML(data)\nfor e in doc.xpath('//*[contains(local-name(),\"-\")]'):\n e.tag = e.tag.repla... | [
4,
1
] | [] | [] | [
"lxml",
"python"
] | stackoverflow_0008324018_lxml_python.txt |
Q:
I came across a tricky trouble about django Queryset
Tricky code:
user = User.objects.filter(id=123)
user[0].last_name = 'foo'
user[0].save() # Cannot be saved.
id(user[0]) # 32131
id(user[0]) # 44232 ( different )
user cannot be saved in this way.
Normal code:
user = User.objects.filter(id=123)
if user:... | I came across a tricky trouble about django Queryset | Tricky code:
user = User.objects.filter(id=123)
user[0].last_name = 'foo'
user[0].save() # Cannot be saved.
id(user[0]) # 32131
id(user[0]) # 44232 ( different )
user cannot be saved in this way.
Normal code:
user = User.objects.filter(id=123)
if user:
user[0].last_name = 'foo'
user[0].save() # Saved suc... | [
"In first variant your user queryset isn't evaluated yet. So every time you write user[0] ORM makes independent query to DB. In second variation queryset is evalutaed and acts like normal Python list.\nAnd BTW if you want just one row, use get:\nuser = User.objects.get(id=123)\n\n",
"when you index into a queryse... | [
5,
2,
1
] | [] | [] | [
"django",
"django_queryset",
"python"
] | stackoverflow_0008324341_django_django_queryset_python.txt |
Q:
json.loads(jsonstring) in Python fails if string has a "\r" i.e. carriage return character
I am getting a JSON string which has a "\r" character somewhere e.g. "{"data":"foo \r\n bar"}" when I try to parse it throws ValueError.
>>> j="""{"data":"foo \r\n bar"}"""
>>> import json
>>> f=json.loads(j)
Traceback (mos... | json.loads(jsonstring) in Python fails if string has a "\r" i.e. carriage return character | I am getting a JSON string which has a "\r" character somewhere e.g. "{"data":"foo \r\n bar"}" when I try to parse it throws ValueError.
>>> j="""{"data":"foo \r\n bar"}"""
>>> import json
>>> f=json.loads(j)
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
f=json.loads(j)
File "C:\Py... | [
"You should escape slashes in JSON:\nj=\"\"\"{\"data\":\"foo \\\\r\\\\n bar\"}\"\"\"\n\nIf you are not escaping them, your JSON is invalid (being valid Python string).\n",
"Logically python is doing what should have been done !\nIts the same old CRLF (inspired from typewriters)\nCR = Carraige Return\nLF = Line Fe... | [
5,
1
] | [] | [] | [
"json",
"parsing",
"python"
] | stackoverflow_0008324169_json_parsing_python.txt |
Q:
Why C++ can't be made as Python in terms of convenience
This question may seem to be naive.
But I think it'll be much worse if I don't ask it at all.
When a discussion begins about the features of Python that the developers love the most, they usually mention list comprehension, syntax relying on indentation (thus... | Why C++ can't be made as Python in terms of convenience | This question may seem to be naive.
But I think it'll be much worse if I don't ask it at all.
When a discussion begins about the features of Python that the developers love the most, they usually mention list comprehension, syntax relying on indentation (thus avoiding brackets, etc.) and some other.
At such moments I a... | [
"Google as created a language called Golang ( or Go). It is a compiled language with python like syntaxe. There are alot of video and documenttation that will answer your question there.\n"
] | [
0
] | [] | [] | [
"c++",
"python"
] | stackoverflow_0008325334_c++_python.txt |
Q:
Extract items from array: between given values/conditions
I have a number of timeseries data in arrays and wish to extract values between given dates in the simplest way possible avoiding loops.
Here's an example:
from numpy import *
from datetime import *
# datetime array
date_a=array([
datetime(2000,1,1),
datet... | Extract items from array: between given values/conditions | I have a number of timeseries data in arrays and wish to extract values between given dates in the simplest way possible avoiding loops.
Here's an example:
from numpy import *
from datetime import *
# datetime array
date_a=array([
datetime(2000,1,1),
datetime(2000,1,2),
datetime(2000,1,3),
datetime(2000,1,4),
datetime... | [
"If you want one-liner, then you can use \nitem_c=item_a[(date_a >= (datetime(2000,1,3))) * (date_a <= (datetime(2000,1,4)))]\n\n",
"It's not clear to me why you are using the item_a variable. But to isolate the entries you want you can simply do:\n>>> np.where(np.logical_and(date_a >= datetime(2000,1,3), date_a ... | [
4,
3,
1
] | [] | [] | [
"indexing",
"numpy",
"python",
"slice"
] | stackoverflow_0008325089_indexing_numpy_python_slice.txt |
Q:
simple passing of variables to classes
Why doesn't this work ?
class spin(threading.Thread):
def __init__(self):
super(spin,self).__init__()
self._stop = False
def run (self,var):
self.var=var
print self.var
def echo (self,va... | simple passing of variables to classes | Why doesn't this work ?
class spin(threading.Thread):
def __init__(self):
super(spin,self).__init__()
self._stop = False
def run (self,var):
self.var=var
print self.var
def echo (self,var):
self.var=var
... | [
"The reason s.start('hello') does not work is that the inherited Threadin.start() method takes no arguments other than self.\nCalling s.echo('hello') does appear to work, but it calls the function in the context of the main thread instead of spawning a new thread.\nOne way to fix your code is by supplying var to th... | [
2
] | [] | [] | [
"class",
"python",
"variables"
] | stackoverflow_0008325471_class_python_variables.txt |
Q:
string splitting in python with ignoring \r \n cases
I am having this problem which is really weird I am trying to solve it and i can't find the best way.
I am passing this string as an argv[] "copy c:\root c:\noot" in python.
and i want to gave c:\root and c:\noot all together as one piece when splitting
examp... | string splitting in python with ignoring \r \n cases | I am having this problem which is really weird I am trying to solve it and i can't find the best way.
I am passing this string as an argv[] "copy c:\root c:\noot" in python.
and i want to gave c:\root and c:\noot all together as one piece when splitting
example:
commandLineOptions = "copy c:\root c:\noot" # this is... | [
"str.split accepts second parameter - maximum number of 'splits': \n>>> commandLineOptions = \"copy c:\\root c:\\noot\"\n>>> commandLineOptions.split(' ', 1)\n['copy', 'c:\\root c:\\noot']\n\n"
] | [
3
] | [] | [] | [
"command_line_arguments",
"filenames",
"python",
"split"
] | stackoverflow_0008325688_command_line_arguments_filenames_python_split.txt |
Q:
Using Custom Property in Google App Engine
I'm using google app engine/python. And I have created a custom datatype and property. But I have problem using it. This is my definition
from datetime import datetime
class MyDateTime(datetime):
def __str__(self):
return self.strftime("%Y-%m-%d %H:%M")
clas... | Using Custom Property in Google App Engine | I'm using google app engine/python. And I have created a custom datatype and property. But I have problem using it. This is my definition
from datetime import datetime
class MyDateTime(datetime):
def __str__(self):
return self.strftime("%Y-%m-%d %H:%M")
class MyDateTimeProperty(db.Property):
# specify... | [
"Your Property subclass needs to define a validate() method if its datatype isn't one of the defined datastore data types that the default validator knows about. There's an example validator method in this article.\n"
] | [
3
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0008323907_google_app_engine_python.txt |
Q:
Python newline constant like C++ std::endl
I am formatting a string (in magic method __str__) and I don't want to use a raw "\n" or "\r\n".
Does python have a cross-platform newline identifier like std::endl in C++?
I tried to Google it, but couldn't find an answer.
A:
How about using os.linesep? It contains the... | Python newline constant like C++ std::endl | I am formatting a string (in magic method __str__) and I don't want to use a raw "\n" or "\r\n".
Does python have a cross-platform newline identifier like std::endl in C++?
I tried to Google it, but couldn't find an answer.
| [
"How about using os.linesep? It contains the appropriate line separator for your OS:\n>>> import os\n>>> os.linesep\n'\\n'\n>>> print \"line one\" + os.linesep + \"line two\"\nline one\nline two\n\n",
"No. Use \\n. And in C++, std::endl is nothing other than \"\\n\" << std::flush, and it is not more cross-platfor... | [
17,
8,
6
] | [] | [] | [
"newline",
"python",
"string_formatting"
] | stackoverflow_0008325840_newline_python_string_formatting.txt |
Q:
How can I get parent class' self?
class Test1:
def __init__(self):
self.x = 1
class Test2(Test1):
# how can I get parent class's self.x ??
# exactly here not def __init__(self) or other methods in Test2..
Please... I spent hours figuring out how to get parent class' self! and failed..
I nee... | How can I get parent class' self? | class Test1:
def __init__(self):
self.x = 1
class Test2(Test1):
# how can I get parent class's self.x ??
# exactly here not def __init__(self) or other methods in Test2..
Please... I spent hours figuring out how to get parent class' self! and failed..
I need a python expert!
| [
"This is not possible. self.x is an instance variable. Instance variables can only be accessed from within instance-methods. Outside methods you are in a static context.\nYou can do this (pure class-variables (not instance)):\nclass Test1:\n x = 1\n\nclass Test2:\n y = Test1.x\n\n",
"At the point of class-d... | [
2,
2,
2
] | [] | [] | [
"python"
] | stackoverflow_0008325905_python.txt |
Q:
Proper layout of python packages for a Graphical User Interface (GUI)
On the project I'm currently working on (a GUI for a testing system) I'm required to write base classes for all graphical objects and inherit these objects into the class which utilises the graphical object. The actual working code is then writ... | Proper layout of python packages for a Graphical User Interface (GUI) | On the project I'm currently working on (a GUI for a testing system) I'm required to write base classes for all graphical objects and inherit these objects into the class which utilises the graphical object. The actual working code is then written there. This seems like standard procedure for these sort of GUI relate... | [
"I like to keep things modular, so would go with\n/mainfolder --> __init__.py\n launcher.py\n /MainPackage --> __init__.py\n /Mainframe --> __init__.py\n Mainframe.py\n ... | [
1
] | [] | [] | [
"file_organization",
"filesystems",
"layout",
"package",
"python"
] | stackoverflow_0008326065_file_organization_filesystems_layout_package_python.txt |
Q:
Django infer a field from other fields
I am currently having a model:
class Current(models.Model):
field1 = models.IntegerField()
field2 = models.IntegerField()
field3 = models.IntegerField()
I need to have field3 to be set directly equal to field1 + field2 without actually sending it.
What's th... | Django infer a field from other fields | I am currently having a model:
class Current(models.Model):
field1 = models.IntegerField()
field2 = models.IntegerField()
field3 = models.IntegerField()
I need to have field3 to be set directly equal to field1 + field2 without actually sending it.
What's the standard way in django to do this?
PS: Yes... | [
"Something like this? But not sure why this would need to be saved in the database.\nclass Current(models.Model): \n field1 = models.IntegerField() \n field2 = models.IntegerField()\n field3 = models.IntegerField() \n\n def save(self, *args, **kwargs):\n self.field3 = self.field1 + self.field2... | [
2,
0
] | [] | [] | [
"class",
"django",
"django_models",
"python"
] | stackoverflow_0008326109_class_django_django_models_python.txt |
Q:
Flask + Jinja2: how to measure performances
I need to compare the performances of a Flask application that uses jinja2.Template.render against jinja2.Template.stream to be sure that there is no loss of performances using the streaming of templates.
My (very simple) idea was to print the timestamp before and after ... | Flask + Jinja2: how to measure performances | I need to compare the performances of a Flask application that uses jinja2.Template.render against jinja2.Template.stream to be sure that there is no loss of performances using the streaming of templates.
My (very simple) idea was to print the timestamp before and after the rendering of the template, but since the webp... | [
"You need to look at the system clock before and after the call.\nIt's easier to do this if you don't immediately return the response from template.render or template.stream.\nIE:\nfrom time import time\n\ndef index():\n # THE REST OF YOUR CODE GOES HERE\n start = time.time()\n resp = template.render(messa... | [
2
] | [] | [] | [
"flask",
"jinja2",
"performance",
"python"
] | stackoverflow_0008324284_flask_jinja2_performance_python.txt |
Q:
API front-end architecture
I want to build a web site that is a front-end for an API. Basically, the front-end takes some user input and uses that to query the API and retrieve results. When the results are retrieved, they are displayed. This is all done asynchronously.
My questions are:
Do I use something like C... | API front-end architecture | I want to build a web site that is a front-end for an API. Basically, the front-end takes some user input and uses that to query the API and retrieve results. When the results are retrieved, they are displayed. This is all done asynchronously.
My questions are:
Do I use something like Celery to handle the API querying... | [
"You're missing some points here. By your requirements I assume that you want to build a frontend (html + javascript) that queries a (RESTful) API, which will simply be a server that \"speaks\" HTTP.\nSo, your API querying has to do with your server, that is, with Django on Apache or with Tornado or.. Celery cannot... | [
2
] | [] | [] | [
"architecture",
"celery",
"django",
"python"
] | stackoverflow_0008325123_architecture_celery_django_python.txt |
Q:
python and ip range?
For example, I have a file ( city and ip addresses ):
....
City1 31.25.87.0 - 31.25.87.15
.... ....
City2 31.47.224.0 - 31.47.255.255
....
How to know by ip adress city name ?
A:
http://www.icir.org/robin/pysubnettree/
you may need to convert ip ranges in cidr, so this library can h... | python and ip range? | For example, I have a file ( city and ip addresses ):
....
City1 31.25.87.0 - 31.25.87.15
.... ....
City2 31.47.224.0 - 31.47.255.255
....
How to know by ip adress city name ?
| [
"http://www.icir.org/robin/pysubnettree/\nyou may need to convert ip ranges in cidr, so this library can help you\nhttp://code.google.com/p/python-iptools/\nPlease consider that converting ip ranges to cidrs you may have multiple cidr blocks so you have to repeat the city in the tree\n"
] | [
1
] | [] | [] | [
"python"
] | stackoverflow_0008326655_python.txt |
Q:
How do I get my output in column format?
I'm very new to Python and have a question. Currently I'm using this to calculate the times between a message goes out and the message comes in. The resulting starting time, time delta, and the Unique ID are then presented in file. How could I do I generate an output in col... | How do I get my output in column format? | I'm very new to Python and have a question. Currently I'm using this to calculate the times between a message goes out and the message comes in. The resulting starting time, time delta, and the Unique ID are then presented in file. How could I do I generate an output in column format with these three qualities?
def ti... | [
"To write it into a CSV file you can use this:\nimport csv\n\nwith open('output_file.csv', 'w') as f:\n csv_w = csv.writer(f)\n for rec in time_deltas(infile): \n csv_w.writerow(rec)\n\nor even shorter:\nimport csv\n\nwith open('output_file.csv', 'w') as f:\n csv.writer(f).writerows(time_deltas(infi... | [
3,
0
] | [] | [] | [
"python",
"string"
] | stackoverflow_0008326588_python_string.txt |
Q:
Can't use a function call inside the format method, when formatting a string
I've got some code:
def secret_formula(started):
jelly_beans = started * 500
jars = jelly_beans / 1000
crates = jars / 100
return jelly_beans, jars, crates
start_point = 10000
#print ('We\'d have {0} beans, {1} jars, and... | Can't use a function call inside the format method, when formatting a string | I've got some code:
def secret_formula(started):
jelly_beans = started * 500
jars = jelly_beans / 1000
crates = jars / 100
return jelly_beans, jars, crates
start_point = 10000
#print ('We\'d have {0} beans, {1} jars, and {2} crates.'
.format(secret_formula(start_point)))
print ('We\'d have %d... | [
"The commented out line should be\nprint ('We\\'d have {0} beans, {1} jars, and {2} crates.'\n .format(*secret_formula(start_point)))\n\nNotice the * before secret_formula(...) -- it tells Python to unpack the result when passing the values to format().\n"
] | [
3
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0008326192_python_python_3.x.txt |
Q:
using key as value in Mongoengine
I use mongoengine for mongodb in django.
but.. mongoengine fields (like StringField) makes me build up schema toward the way that I don't want. I mean, it strictly insists that I pre-write key name before I do know what it will be. for example...
in case that I do not know what ke... | using key as value in Mongoengine | I use mongoengine for mongodb in django.
but.. mongoengine fields (like StringField) makes me build up schema toward the way that I don't want. I mean, it strictly insists that I pre-write key name before I do know what it will be. for example...
in case that I do not know what key name will be put into database...
> f... | [
"Have you considered using PyMongo directly instead of using Mongoengine? Mongoengine is designed to declare and validate a schema for your documents, and provides many tools and conveniences around that. If your documents are going to vary, I'm not sure Mongoengine is the right choice for you.\nIf, however, you ha... | [
2
] | [] | [] | [
"django",
"mongodb",
"mongoengine",
"python"
] | stackoverflow_0008326361_django_mongodb_mongoengine_python.txt |
Q:
Can python regex negate a list of words?
I have to match all the alphanumeric words from a text.
>>> import re
>>> text = "hello world!! how are you?"
>>> final_list = re.findall(r"[a-zA-Z0-9]+", text)
>>> final_list
['hello', 'world', 'how', 'are', 'you']
>>>
This is fine, but further I have few words to negate ... | Can python regex negate a list of words? | I have to match all the alphanumeric words from a text.
>>> import re
>>> text = "hello world!! how are you?"
>>> final_list = re.findall(r"[a-zA-Z0-9]+", text)
>>> final_list
['hello', 'world', 'how', 'are', 'you']
>>>
This is fine, but further I have few words to negate i.e. the words that shouldn't be in my final l... | [
"I don't think there is a clean way to do this using regular expressions. The closest I could find was bit ugly and not exactly what you wanted:\n>>> re.findall(r\"\\b(?:world|other|words)|([a-zA-Z0-9]+)\\b\", text)\n['hello', '', 'how', 'are', 'you']\n\nWhy not use Python's sets instead. They are very fast:\n>>>... | [
6,
1
] | [
"Don't ask uselessly too much to regex.\nInstead, think to generators.\nimport re\n\nunwanted = ('world', 'other', 'words')\n\ntext = \"hello world!! how are you?\"\n\ngen = (m.group() for m in re.finditer(\"[a-zA-Z0-9]+\",text))\nli = [ w for w in gen if w not in unwanted ]\n\nAnd a generator can be created instea... | [
-1
] | [
"python",
"regex",
"regex_negation"
] | stackoverflow_0008323369_python_regex_regex_negation.txt |
Q:
Changing data type (dtype) of tabular.tabarray or numpy.recarray
I want to represent data as a spreadsheet would in Python. Thinking "well, someone's certainly written such a module!" I went to PyPI, where I found Tabular, which wraps NumPy's recarrays with powerful data manipulations functions. Great! Sadly, it d... | Changing data type (dtype) of tabular.tabarray or numpy.recarray | I want to represent data as a spreadsheet would in Python. Thinking "well, someone's certainly written such a module!" I went to PyPI, where I found Tabular, which wraps NumPy's recarrays with powerful data manipulations functions. Great! Sadly, it doesn't seem to act like a spreadsheet at all when it comes to strings.... | [
"As one of the designers of tabular ... I have to say that I largely think the first answerer sort of hits the nail on the head.\nOP, the \"truncation\" behavior that you deplore is a fundamental issue with NumPy, on which Tabular is based. But it's not really accurate to say that it's a \"bug\" that should fixed,... | [
6,
2
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0008315642_numpy_python.txt |
Q:
Python - Trying to get a different timezone
Totally new to python, I'm actually working on an ex-colleague's script. in looking at it it seems fairly straight-forward. Here's the situation:
The script looks at current localtime (UTC) and renders a time-based table that scrolls/changes throughout the day as the hou... | Python - Trying to get a different timezone | Totally new to python, I'm actually working on an ex-colleague's script. in looking at it it seems fairly straight-forward. Here's the situation:
The script looks at current localtime (UTC) and renders a time-based table that scrolls/changes throughout the day as the hours pass so there's always a rolling 8 hour table.... | [
"Yes, try to install pytz, it will help you a lot when working with different timezones (and UTC).\nThe current UTC time (independent from the timezone of your computer) can be obtained with:\nimport pytz\nfrom datetime import datetime\n\nnow = datetime.now(pytz.utc)\n\nnow is now datetime.datetime(2011, 11, 30, 14... | [
3,
0
] | [] | [] | [
"python",
"timezone"
] | stackoverflow_0008327365_python_timezone.txt |
Q:
Is the routes Dispatcher broken in CherryPy for Mac?
Is CherryPy broken? I just set it up and tried to use the routes dispatcher but it has an import error, my code is as follows:
import cherrypy
mapper = cherrypy.dispatch.RoutesDispatcher()
The error is:
Traceback (most recent call last):
File "<stdin>", line... | Is the routes Dispatcher broken in CherryPy for Mac? | Is CherryPy broken? I just set it up and tried to use the routes dispatcher but it has an import error, my code is as follows:
import cherrypy
mapper = cherrypy.dispatch.RoutesDispatcher()
The error is:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/jwesonga/environments/cherr... | [
"I have successfully used CherryPy with the routes dispatcher under OS X.\nThe error you've shown is:\nImportError: No module named routes\n\nThis is pretty clear -- Python can't find the routes modules. Have you installed it? This is not part of CherryPy, it's a separate module that you will need to install. If... | [
6
] | [] | [] | [
"cherrypy",
"python"
] | stackoverflow_0008326480_cherrypy_python.txt |
Q:
Access array of c-structs using Python ctypes
I have a C-function that allocates memory at the address passed to and is accessed via Python. The pointer contents does contain an array of structs in the C code, but I am unable to get ctypes to access the array properly beyond the 0th element. How can I get the prop... | Access array of c-structs using Python ctypes | I have a C-function that allocates memory at the address passed to and is accessed via Python. The pointer contents does contain an array of structs in the C code, but I am unable to get ctypes to access the array properly beyond the 0th element. How can I get the proper memory offset to be able to access the non-zero ... | [
"D Hess put me in the right direction; The solution was:\nGroupArray = POINTER(Group * count)\ngroup_array = GroupArray.from_address(addressof(myGroups))\nfor x in range(0,count):\n print \"~~~~~~~~~~\" + group_array.contents[x].groupname\n\n",
"First create a new type which is an array of Group:\nGroupArray =... | [
4,
3
] | [] | [] | [
"c",
"ctypes",
"pointers",
"python"
] | stackoverflow_0008318196_c_ctypes_pointers_python.txt |
Q:
how to extract nested lists?
Duplicates:
Flattening a shallow list in Python
Comprehension for flattening a sequence of sequences?
Lets say I have a list with nested lists:
[["a","b","c"], ["d","e","f"], ["g","h","i","j"]...]
what is the best way to convert it to a single list like that
["a", "b", "c", "d", "e... | how to extract nested lists? |
Duplicates:
Flattening a shallow list in Python
Comprehension for flattening a sequence of sequences?
Lets say I have a list with nested lists:
[["a","b","c"], ["d","e","f"], ["g","h","i","j"]...]
what is the best way to convert it to a single list like that
["a", "b", "c", "d", "e"....]
| [
"Use itertools.chain:\nfrom itertools import chain\n\nlist(chain.from_iterable(list_of_lists))\n\n",
"There's a straight forward example of this in the itertools documentation (see http://docs.python.org/library/itertools.html#recipes look for flatten()), but it's as simple as:\n>>> from itertools import chain\n>... | [
41,
25,
3
] | [] | [] | [
"list",
"python"
] | stackoverflow_0008327856_list_python.txt |
Q:
Python gettext: convert Unicode literals into text
I work in Windows. Python 2.7.2
I have a module in which i have to translate a few messages with gettext.
So i create UTF-8 no BOM *.po file, make *.mo out of it and use code like this:
t = gettext.translation('index','./locale', languages=['ru'])
_= t.ugettext
... | Python gettext: convert Unicode literals into text | I work in Windows. Python 2.7.2
I have a module in which i have to translate a few messages with gettext.
So i create UTF-8 no BOM *.po file, make *.mo out of it and use code like this:
t = gettext.translation('index','./locale', languages=['ru'])
_= t.ugettext
t.install()
As a result i have something like this:
(u'... | [
"\nHow to covert it into common UTF-8 text?\n\nThis is the wrong question. :) It is already UTF-8 text... What you are trying to understand is how to display it as alphabetical characters. This should be automatic in anything that uses strings as visual output. The easiest case, the print function (or statement).\n... | [
1
] | [] | [] | [
"gettext",
"internationalization",
"python",
"unicode",
"windows"
] | stackoverflow_0008327994_gettext_internationalization_python_unicode_windows.txt |
Q:
Strange pygame image error
I have a small problem in my code. I have the following code:
import os,pygame
class npc:
ntype = 0
image = None
x = 0
y = 0
text = ""
name = ""
def Draw(self,screen):
screen.blit(self.image, [self.x*32,self.y*32])
def __init__(self,name,nx,ny):
... | Strange pygame image error | I have a small problem in my code. I have the following code:
import os,pygame
class npc:
ntype = 0
image = None
x = 0
y = 0
text = ""
name = ""
def Draw(self,screen):
screen.blit(self.image, [self.x*32,self.y*32])
def __init__(self,name,nx,ny):
f = open(name)
z =... | [
"You might have a trailing newline character. Try stripping the line:\nself.image = pygame.image.load(os.path.join('img', line.strip()))\n\nBetter yet, load your file differently. Instead of the loop, you could do something like this (assuming every file is formatted identically, and has at least the same number of... | [
2
] | [] | [] | [
"image",
"pygame",
"python"
] | stackoverflow_0008328290_image_pygame_python.txt |
Q:
how to delete lowercase words from a string in python
I'm new in python and I'm having some issues doing a simple thing.
I've an array (or list as it's said in python) like this:
list = [ 'NICE dog' , 'blue FLOWER' , 'GOOD cat' , 'YELLOW caw']
As you see each element of this array contains some words. These word... | how to delete lowercase words from a string in python | I'm new in python and I'm having some issues doing a simple thing.
I've an array (or list as it's said in python) like this:
list = [ 'NICE dog' , 'blue FLOWER' , 'GOOD cat' , 'YELLOW caw']
As you see each element of this array contains some words. These words is both lowercase and uppercase.
How I can delete from th... | [
"l = [ 'NICE dog' , 'blue FLOWER' , 'GOOD cat' , 'YELLOW caw']\n\noutput = [' '.join(w for w in a.split() if w.isupper()) for a in l]\n# or: \noutput = [' '.join(filter(str.isupper, a.split())) for a in l]\n\nreturns:\n['NICE', 'FLOWER', 'GOOD', 'YELLOW']\n\n(Don't use list as variable name.)\n",
"The followi... | [
9,
3,
2,
1,
0,
0
] | [] | [] | [
"list",
"python"
] | stackoverflow_0008326839_list_python.txt |
Q:
Django - Deserialize an object conserving ManyToMany field
I have a model called Goal and another one called Action. Here I highlight the important parts:
class Goal(models.Model):
leaders = models.ManyToManyField(User, null=True)
class Action(models.Model):
before = models.TextField(null=True)
after ... | Django - Deserialize an object conserving ManyToMany field | I have a model called Goal and another one called Action. Here I highlight the important parts:
class Goal(models.Model):
leaders = models.ManyToManyField(User, null=True)
class Action(models.Model):
before = models.TextField(null=True)
after = models.TextField(null=True)
When a user edits a Goal I save a... | [
"The issue here is, as soon as you call: before_object.object.leaders you are getting a ModelManager which will make new DB queries when you call the method all() ! thats the default behaviour of the ModelManager.\nSo, to solve your problem you will have to write a new manager within your Model object. and this Man... | [
0
] | [] | [] | [
"django",
"python",
"xml_deserialization"
] | stackoverflow_0008327791_django_python_xml_deserialization.txt |
Q:
replacing special characters in between the multiple substring in a string
Consider a string:
str1="abcd<aaa>some thing <#^&*some more!#$@ </aaa>
abcdefgasf <aaa>asfaf %^&*$saf asf %$^ </aaa>
<another tag> some text </another tag>
... | replacing special characters in between the multiple substring in a string | Consider a string:
str1="abcd<aaa>some thing <#^&*some more!#$@ </aaa>
abcdefgasf <aaa>asfaf %^&*$saf asf %$^ </aaa>
<another tag> some text </another tag>
<aaa>sfafaff#%%%^^</aaa> "
Now in the above string how to replace the special... | [
"Here is a possible solution, is a little bit complex, so I'll explain it step by step.\nWe are going to use a module called re, for regular expressions:\nimport re\n\nOK, here is our string:\ns = 'abcd<aaa>some thing <#^&*some more!#$@ </aaa> abcdefgasf <aaa>asfaf %^&*$saf asf %$^ </aaa> <another tag> some text <... | [
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0008328264_python.txt |
Q:
Multidimensional List/Dict/whatever?
I'd like to create a multidimensional array in Python to parse it later on. I'm a switcher from PHP so I'm a little bit confused of how to create a dict or list or anything else to get that data out this way. Anyone an idea?
for group, value in data:
print '%s = %s' % (grou... | Multidimensional List/Dict/whatever? | I'd like to create a multidimensional array in Python to parse it later on. I'm a switcher from PHP so I'm a little bit confused of how to create a dict or list or anything else to get that data out this way. Anyone an idea?
for group, value in data:
print '%s = %s' % (group, value)
for member, value in group:
... | [
"You can create a recursive list or dict to achieve it, I would prefer dict as you can name the variables e.g.\nmydata = [\n {\n 'name': 'Windows',\n 'value': '12%',\n 'members': [\n {\n 'name': 'pc1',\n 'value': 123,\n 'members': []\... | [
5,
0
] | [] | [] | [
"arraylist",
"dictionary",
"list",
"multidimensional_array",
"python"
] | stackoverflow_0008328045_arraylist_dictionary_list_multidimensional_array_python.txt |
Q:
Pythonic way to assign default values
Consider this line:
some_value = lst.attr[idx]
There are two possible errors here, the attr might not exist, and the idx might be out of range.
Is there any elegant way to reduce this statement? Ideally, to something like this:
some_value = lst.attr[idx] or default_value
(Do... | Pythonic way to assign default values | Consider this line:
some_value = lst.attr[idx]
There are two possible errors here, the attr might not exist, and the idx might be out of range.
Is there any elegant way to reduce this statement? Ideally, to something like this:
some_value = lst.attr[idx] or default_value
(Don't try that at home. That only works for p... | [
"You need to decide what you are trying achieve here. The use of the word \"error\" is probably misleading.\nIf you are actually trying to handle the case where the wrong type of object is passed to your function then you don't want to handle that and should raise an exception.\nIf you are trying to allow your func... | [
6,
4,
3,
2,
2,
0
] | [] | [] | [
"error_handling",
"python"
] | stackoverflow_0008324620_error_handling_python.txt |
Q:
More functional os.walk
Since I need to do many traversals of directories, which some complex filtering, I thought to create a wrapper around os.walk.
Which is something like this:
def fwalk(root, pred_dir, pred_files, walk_function=walk):
"""Wrapper function around the standard os.walk, that filter out
th... | More functional os.walk | Since I need to do many traversals of directories, which some complex filtering, I thought to create a wrapper around os.walk.
Which is something like this:
def fwalk(root, pred_dir, pred_files, walk_function=walk):
"""Wrapper function around the standard os.walk, that filter out
the directories visited using a... | [
"you need to modify dirs in place in order to avoid recursive traversal of the removed directories. Use:\ndirs[:] = [d for d in dirs if pred_dir(path.join(base, d))]\n\nthis will remove the need to check _ignore_dirs_predicate(base) (and remove the NameError caused by the use of _ignore_dirs_predicate instead of pr... | [
1,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0008324840_python.txt |
Q:
How to extract filenames from cmd input in python
I'm running a python program compiled on windows which receives files as input but have problems when I'm passing file names.
foo.py:
def main():
args = sys.argv[1:]
for i in args:
print i
But when I compile and call it from the command line
\python foo.py... | How to extract filenames from cmd input in python | I'm running a python program compiled on windows which receives files as input but have problems when I'm passing file names.
foo.py:
def main():
args = sys.argv[1:]
for i in args:
print i
But when I compile and call it from the command line
\python foo.py *.html
It directly gives me the result of *.html whic... | [
"You need to use something called glob. For a single filename what you are doing is fine. But if you want to loop through a file pattern, then use glob. It's basically a regex for files\nimport glob\n\nglob.glob('*.html') #return all html files in curr dir\nglob.glob('*') # lists all files in the current direct... | [
4,
0
] | [] | [] | [
"python"
] | stackoverflow_0008329183_python.txt |
Q:
Mixins, multi-inheritance, constructors, and data
I have a class:
class A(object):
def __init__(self, *args):
# impl
Also a "mixin", basically another class with some data and methods:
class Mixin(object):
def __init__(self):
self.data = []
def a_method(self):
# do something
... | Mixins, multi-inheritance, constructors, and data | I have a class:
class A(object):
def __init__(self, *args):
# impl
Also a "mixin", basically another class with some data and methods:
class Mixin(object):
def __init__(self):
self.data = []
def a_method(self):
# do something
Now I create a subclass of A with the mixin:
class AWit... | [
"class A_1(object):\n def __init__(self, *args, **kwargs):\n print 'A_1 constructor'\n super(A_1, self).__init__(*args, **kwargs)\n\nclass A_2(object):\n def __init__(self, *args, **kwargs):\n print 'A_2 constructor'\n super(A_2, self).__init__(*args, **kwargs)\n\nclass B(A_1, A_2)... | [
10,
9
] | [] | [] | [
"mixins",
"multiple_inheritance",
"python"
] | stackoverflow_0006294867_mixins_multiple_inheritance_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.