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:
How to find the location of a python package installed via egg-link?
I'm working on a plugin architecture and need to convert a package name like "foo.bar" to the absolute path where the code resides. imp.find_module seems to do what I want, except when the code in question is installed via an egg-link (installed ... | How to find the location of a python package installed via egg-link? | I'm working on a plugin architecture and need to convert a package name like "foo.bar" to the absolute path where the code resides. imp.find_module seems to do what I want, except when the code in question is installed via an egg-link (installed via 'pip install develop').
If there are two modules foo.bar and foo.bar2 ... | [
"The easiest way would be to just import the module and inspect its __file__ attribute:\nimport os\nimport foo.bar\n\nprint(os.path.abspath(foo.bar.__file__))\n\nFor dynamic imports:\nimport os\nimport sys\n\nmodule_name = 'foo.bar'\n__import__(module_name)\nprint(os.path.abspath(sys.modules[module_name].__file__))... | [
5
] | [] | [] | [
"pip",
"python",
"setuptools"
] | stackoverflow_0008395868_pip_python_setuptools.txt |
Q:
Putting command in the background with Fabric does not work on some hosts
For testing purposes, I am running the following command, with plain ssh command line tool:
ssh user@host "nohup sleep 100 >> /tmp/xxx 2>&1 < /dev/null &"
This is working as expected, in all my hosts: a sleep process is created in the backg... | Putting command in the background with Fabric does not work on some hosts | For testing purposes, I am running the following command, with plain ssh command line tool:
ssh user@host "nohup sleep 100 >> /tmp/xxx 2>&1 < /dev/null &"
This is working as expected, in all my hosts: a sleep process is created in the background, and the ssh finishes immediately.
I am trying to implement this function... | [
"You are probably bumping into the infamous Fabric issue #395. The easiet workaround for these problems is to run your task with pty=False.\n"
] | [
25
] | [] | [] | [
"fabric",
"python",
"ssh"
] | stackoverflow_0008396987_fabric_python_ssh.txt |
Q:
Threading with PyGTK
To begin, I must say that I have searched for quite a long time on this subject and I probably know of most basic resources. I am attempting to use this: https://github.com/woodenbrick/gtkPopupNotify to add a system of notifications to a previously all command line program. Sadly, this usually... | Threading with PyGTK | To begin, I must say that I have searched for quite a long time on this subject and I probably know of most basic resources. I am attempting to use this: https://github.com/woodenbrick/gtkPopupNotify to add a system of notifications to a previously all command line program. Sadly, this usually will hang due to the fact... | [
"With PyGTK, I highly recommend avoiding threads altogether. The GTK libraries aren't fully thread-safe and, under Win-32, they don't support threads at all. So, trying to work with them ends up being a pain. You can get some really nice results by \"faking it\" using Python generators and the gobject.idle_add() me... | [
1
] | [] | [] | [
"pygtk",
"python"
] | stackoverflow_0008396825_pygtk_python.txt |
Q:
PYTHON and mouse clicks and entering phrases into pop ups
I am trying to get python to emulatue mouse clicks, and then type a phrase into the pop up window that the mouse clicks into or the text box.
1) click a security box "run" link with mouse
2) move inside a pop up and enter different phrases with python
What ... | PYTHON and mouse clicks and entering phrases into pop ups | I am trying to get python to emulatue mouse clicks, and then type a phrase into the pop up window that the mouse clicks into or the text box.
1) click a security box "run" link with mouse
2) move inside a pop up and enter different phrases with python
What would be the best way to control the mouse and keyboard in this... | [
"Have a look at Pywinauto.\nIt should be straightforward to use, and you will be looking for functions such as TypeKeys and Click.\n",
"Use a Python GUI library to interact with keyboard and mouse events. I prefer wxPython which is a very popular library. Take a look at wxPython key events API.\nhttp://www.wxpyth... | [
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0008397617_python.txt |
Q:
How to add a progress bar in a Python command-line URL downloader?
I have made a simple command-line URL downloader in Python. When the user supplies a URL it reads the file from web and saves it in a string, then saves the string in a file on the computer.
I want to add a progress bar. How should I go about it?
... | How to add a progress bar in a Python command-line URL downloader? | I have made a simple command-line URL downloader in Python. When the user supplies a URL it reads the file from web and saves it in a string, then saves the string in a file on the computer.
I want to add a progress bar. How should I go about it?
| [
"This is a very basic implementation of a progress bar on the command line:\n>>> def progress_bar(percentage, length):\n... filled = int(length / 100.0 * percentage)\n... return '#' * filled + '_' * (length - filled)\n... \n>>> progress_bar(100, 80)\n'########################################################... | [
3,
2
] | [] | [] | [
"command_line",
"download",
"progress_bar",
"python"
] | stackoverflow_0008397667_command_line_download_progress_bar_python.txt |
Q:
Eager loading of non-singleton collections
I'd like to load collections of repeated objects. My model looks like this:
Item -> Identifier
I'd like to load (eagerly) collections of Items that share the same Identifier, but ignore the vast majority of collections that contain one item or less. The ORM relationship ... | Eager loading of non-singleton collections | I'd like to load collections of repeated objects. My model looks like this:
Item -> Identifier
I'd like to load (eagerly) collections of Items that share the same Identifier, but ignore the vast majority of collections that contain one item or less. The ORM relationship is set up in both directions (Identifier.items a... | [
"Using a sub-query, this can be achieved as following:\nq = (select([Item.identifier_id, func.count(Item.id).label(\"cnt\")]).\n group_by(Item.identifier_id).having(func.count(Item.id)>1)).alias(\"subq\")\nqry = (session.query(Item).join(q, Item.identifier_id==q.c.identifier_id))\nprint qry # prints SQL statem... | [
2,
0
] | [] | [] | [
"group_by",
"orm",
"python",
"sqlalchemy"
] | stackoverflow_0008392653_group_by_orm_python_sqlalchemy.txt |
Q:
How to improve performance of this counting program?
Given a file looks like this:
1440927 1
1727557 3
1440927 2
9917156 4
The first field is an ID which is in range(0, 200000000). The second field represents a type , which is in range(1, 5). And type 1 and type 2 belong to a common category S1, while type 3 and ... | How to improve performance of this counting program? | Given a file looks like this:
1440927 1
1727557 3
1440927 2
9917156 4
The first field is an ID which is in range(0, 200000000). The second field represents a type , which is in range(1, 5). And type 1 and type 2 belong to a common category S1, while type 3 and type 4 belong to S2. One single ID may have several record... | [
"You're using a iterator over the file, this means that you only buffer a few lines at the time. Every time the buffer is empty the disk needs to seek and your program has to wait. \n200MB easily fits into your memory, so getting all lines will speed things up:\ndef gen(path):\n # load all the lines, \n lines... | [
3,
2,
2
] | [] | [] | [
"bitarray",
"performance",
"python"
] | stackoverflow_0008397766_bitarray_performance_python.txt |
Q:
Get new e-mails mail folder multiple times
So I have this class that starts like this:
class emailreader():
def __init__(self, server, port, username, password):
self.imap_server = imaplib.IMAP4_SSL(server, int(port))
self.imap_server.login(username, password)
self.imap_server.select('I... | Get new e-mails mail folder multiple times | So I have this class that starts like this:
class emailreader():
def __init__(self, server, port, username, password):
self.imap_server = imaplib.IMAP4_SSL(server, int(port))
self.imap_server.login(username, password)
self.imap_server.select('INBOX')
def _get_raw_emails(self):
m... | [
"I found the solution. I had to execute a method that's called check() from my imap object whenever new mails may have arrived. This is my \"new\" _get_raw_emails() method:\n def _get_raw_emails(self):\n messages = []\n self.imap_server.check() # Fetch new mails since object is created.\n ty... | [
0
] | [] | [] | [
"imap",
"python"
] | stackoverflow_0008391831_imap_python.txt |
Q:
Importing layout position for a graph using networkx
I am very new to Networkx. I am trying to import layout position generated by random_layout() function. I dont know how to do proceed with it.
Code to generate layout position:
G = nx.random_geometric_graph(10, 0.5)
pos = nx.random_layout(G)
nx.set_node_attribut... | Importing layout position for a graph using networkx | I am very new to Networkx. I am trying to import layout position generated by random_layout() function. I dont know how to do proceed with it.
Code to generate layout position:
G = nx.random_geometric_graph(10, 0.5)
pos = nx.random_layout(G)
nx.set_node_attributes(G, 'pos', pos)
f = open("graphLayout.txt", 'wb')
f.writ... | [
"The nx.random_layout function returns a dictionary mapping nodes to positions. As pos is a Python object, you don't want to just store the printed string version of it to a file, as you did in f.write(\"%s\" % pos). This gives you a file containing your dictionary, but reading it back in isn't as easy. \nInstead,... | [
0
] | [] | [] | [
"networkx",
"python"
] | stackoverflow_0008395420_networkx_python.txt |
Q:
Python Mechanize won't properly handle a redirect
I'm working on a scraper using Mechanize and Beautiful Soup in Python and for some reason redirects aren't working. Here's my code (I apologize for naming my variables "thing" and "stuff"; I don't normally do that, trust me):
stuff = soup.find('div', attrs={'class'... | Python Mechanize won't properly handle a redirect | I'm working on a scraper using Mechanize and Beautiful Soup in Python and for some reason redirects aren't working. Here's my code (I apologize for naming my variables "thing" and "stuff"; I don't normally do that, trust me):
stuff = soup.find('div', attrs={'class' : 'paging'}).ul.findAll('a', href=True)
for thing ... | [
"Both urllib2 and mechanize openers include a handler for redirect responses by default (you can check looking at the handlers attribute), so I don't think the problem is that a redirect response isn't being correctly followed.\nTo troubleshoot the problem, you should capture the traffic in your web browser (in fir... | [
2
] | [] | [] | [
"mechanize",
"python"
] | stackoverflow_0008397452_mechanize_python.txt |
Q:
ZeroDivisionError: float division` in python
querytimes = "SELECT video_id, COUNT(src_ip) FROM video GROUP BY video_id ORDER BY COUNT(src_ip) DESC"
cur.execute (querytimes)
dltimes = cur.fetchall()
for row in dltimes:
videoid = str(row [0])
downloadtimes = int(str(row [1]))
x.append(rank)
rank = r... | ZeroDivisionError: float division` in python | querytimes = "SELECT video_id, COUNT(src_ip) FROM video GROUP BY video_id ORDER BY COUNT(src_ip) DESC"
cur.execute (querytimes)
dltimes = cur.fetchall()
for row in dltimes:
videoid = str(row [0])
downloadtimes = int(str(row [1]))
x.append(rank)
rank = rank + 1
y.append(downloadtimes)
v.append(... | [
"Have you checked that your counter dictionary has at least one value that matches the nb == n condition? To me it seems like either your sum or your len return 0 as a result...\nCheck this out:\n>>> n = 3\n>>> counter = {'a': 1}\n>>> 100. / sum(1 for nb in counter.itervalues() if nb == n) / len(counter) \nTracebac... | [
3,
0
] | [] | [] | [
"python"
] | stackoverflow_0008398828_python.txt |
Q:
Python: wxPython: Help on GridBagSizer Layout Management
I got an problem trying to resize the controls, could someone point out where needs correction for a tidy controls stack up?
i.e. the TextCtrl boxes should be standard default sizes.
and The Read & Set buttons to be stacked just right below the TextCtrl boxe... | Python: wxPython: Help on GridBagSizer Layout Management | I got an problem trying to resize the controls, could someone point out where needs correction for a tidy controls stack up?
i.e. the TextCtrl boxes should be standard default sizes.
and The Read & Set buttons to be stacked just right below the TextCtrl boxes.
Here's my code:
class AVMCPanel(wx.Panel):
def __init_... | [
"In the following code:\nself.rtext = wx.TextCtrl(self, 1, \"\", size=(80, -1), style=wx.ALL)\nself.stext = wx.TextCtrl(self, 1, \"\", size=(80, -1), style=wx.ALL)\n\nYou are using a Sizer flag on a TextCtrl. Remove this to prevent the TextCtrl from being vertically taller.\nYour buttons are going down because the ... | [
1
] | [] | [] | [
"layout",
"python",
"wxpython"
] | stackoverflow_0008397955_layout_python_wxpython.txt |
Q:
Caching large html fragments in Django and passing them to the template when they contain smart quotes
I'm using urllib2 to open and read two external web pages and then saving them to django's internal cache, like so:
header = urllib2.urlopen( "http://www.mysite.com/pageheader.html" ).read()
footer = urllib2.urlo... | Caching large html fragments in Django and passing them to the template when they contain smart quotes | I'm using urllib2 to open and read two external web pages and then saving them to django's internal cache, like so:
header = urllib2.urlopen( "http://www.mysite.com/pageheader.html" ).read()
footer = urllib2.urlopen( "http://www.mysite.com/pagefooter.html" ).read()
cache.add( 'header', header )
cache.add( 'footer', fo... | [
"Check if urllib2 can properly encode retrieved page, more here:\nurllib2 read to Unicode\n"
] | [
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0007663510_django_python.txt |
Q:
Access variables defined in Mako namespace
Normally, "importing" a namespace in Mako appears to only allow access to defs.
## base.mako
<%
somevar = ["one", "two", "three"]
%>
<%def name="foo()">Bar</%def>
And an importing template:
## child.mako
<%namespace name="base" file="base.mako" />
${base.foo()} # wor... | Access variables defined in Mako namespace | Normally, "importing" a namespace in Mako appears to only allow access to defs.
## base.mako
<%
somevar = ["one", "two", "three"]
%>
<%def name="foo()">Bar</%def>
And an importing template:
## child.mako
<%namespace name="base" file="base.mako" />
${base.foo()} # works
${base.somevar} # fails: no soup for you
In ... | [
"I've had the same problem - the answer is in the documentation on inheritance:\n\nThe attr accessor of the Namespace object allows access to module level variables declared in a template. By accessing self.attr, you can access regular attributes from the inheritance chain as declared in <%! %> sections.\n\nThus yo... | [
4,
2
] | [] | [] | [
"mako",
"python"
] | stackoverflow_0006696918_mako_python.txt |
Q:
Can I create object names from a text file in Python 2.7?
I'm working on a game project.
I've created an object, Star(Object).
I want to assign the name of the variables, dynamically, from a text file.
If I have a text file with:
Sol
Centauri
Vega
I want the program to create the Star(Object) with variable names ... | Can I create object names from a text file in Python 2.7? | I'm working on a game project.
I've created an object, Star(Object).
I want to assign the name of the variables, dynamically, from a text file.
If I have a text file with:
Sol
Centauri
Vega
I want the program to create the Star(Object) with variable names from the text file. I want the process automated, because I'm ... | [
"The name of a star should not be the name of the variable. Variable names should reflect the context in which the variable is used, e.g. destinationStar or homeStar.\nA star's name should be a property of the Star object, accessed via Star.name:\nclass Star(object):\n \"\"\"Keeps track of a star.\"\"\"\n\n ... | [
4,
1,
1,
0,
0,
0
] | [
"You can use the types module to create class objects at the run time:\nimport types\n\ndef make_class(name):\n cls = types.ClassType(name, (), {})\n return cls\n\ncls = make_class(\"Star\")\nobj = cls()\n\nIn the above example, cls becomes your class Star\n"
] | [
-1
] | [
"object",
"python",
"python_2.x"
] | stackoverflow_0004576987_object_python_python_2.x.txt |
Q:
renaming default python-unittest function names
python's unittest testrunner looks for setUpModule() defined in a file to perform before running any test specified in the module. is there a way to use a decorator or some other tool inorder to rename the function name?
for example:
@somedecorator
def globalSetUp():... | renaming default python-unittest function names | python's unittest testrunner looks for setUpModule() defined in a file to perform before running any test specified in the module. is there a way to use a decorator or some other tool inorder to rename the function name?
for example:
@somedecorator
def globalSetUp():...
will enable unittest's loader to recognize this ... | [
"Why not just rename/alias the function?\ndef globalSetUp():\n ...\n\nsetUpModule = globalSetUp\n\nIt's just a single additional line, just like a decorator would be.\n",
"Derive from TestCase, and in your subclass call your own setup function in the setUp method. Then create your classes from this new subclas... | [
2,
1
] | [] | [] | [
"python",
"python_2.6",
"unittest2"
] | stackoverflow_0008397690_python_python_2.6_unittest2.txt |
Q:
Can I statically link Cython modules into an executable which embeds python?
I currently have an executable compiled from C++ that embeds python. The embedded executable runs a python script which load several Cython modules. Both the Cython modules and the executable are linked against a shared library.
I want ... | Can I statically link Cython modules into an executable which embeds python? | I currently have an executable compiled from C++ that embeds python. The embedded executable runs a python script which load several Cython modules. Both the Cython modules and the executable are linked against a shared library.
I want to move the shared library into the executable by statically linking the shared li... | [
"Yes it's possible, but if you have an hand on the python interpreter. What i'm going to describe have been done for python on IOS platform. You need to check more how to let python known about your module if you don't want to touch on the original python interpreter (Replace TEST everywhere with your own tag/libna... | [
8
] | [] | [] | [
"cython",
"python",
"static_libraries"
] | stackoverflow_0008366544_cython_python_static_libraries.txt |
Q:
C2DM Python framework
I need to implement client notification for android and I thought to use c2dm.
Is there any framework for c2dm in python ? Does anybody have experience with server side c2dm in python ?
A:
I don't know of an existing library, but I also recently searched how to send notifications to my dro... | C2DM Python framework | I need to implement client notification for android and I thought to use c2dm.
Is there any framework for c2dm in python ? Does anybody have experience with server side c2dm in python ?
| [
"I don't know of an existing library, but I also recently searched how to send notifications to my droid using Python, and I came throuht this blog post which explains how C2DM works and gives a sample Python implementation. I didn't test it yet, but I believe it could be useful as a base at least.\nEDIT:\nThere is... | [
2
] | [] | [] | [
"python"
] | stackoverflow_0008398460_python.txt |
Q:
how to import / add module named web in python
import web
ImportError: No module named web
in below code:
import web
urls = (
'/(.*)', 'hello'
)
app = web.application(urls, globals())
class hello:
def GET(self, name):
if not name:
name = 'world'
return 'Hello, ' + n... | how to import / add module named web in python | import web
ImportError: No module named web
in below code:
import web
urls = (
'/(.*)', 'hello'
)
app = web.application(urls, globals())
class hello:
def GET(self, name):
if not name:
name = 'world'
return 'Hello, ' + name + '!'
if __name__ == "__main__":
app.run()
... | [
"Is Webpy installed in a directory on your Python path? Have a look at what directories are included by...\nimport sys\n\nprint sys.path\n\nIt is better to install third-party packages using something like pip or easy_install - this usually avoids path issues. \nsudo easy_install web.py\n\nBut if you absolutely can... | [
3,
0
] | [] | [] | [
"eclipse",
"python",
"web.py",
"web_services"
] | stackoverflow_0008398877_eclipse_python_web.py_web_services.txt |
Q:
Can't get htmltmpl working on Windows Vista
I am trying to install the Python library htmltmpl as it is a dependency of the Venus feed reader.
I tried to install htmltmpl from here
When I ran the test suite I got the following output:
C:\htmltmpl-1.22>python test.py
This is not UNIX.
Converting newline separators ... | Can't get htmltmpl working on Windows Vista | I am trying to install the Python library htmltmpl as it is a dependency of the Venus feed reader.
I tried to install htmltmpl from here
When I ran the test suite I got the following output:
C:\htmltmpl-1.22>python test.py
This is not UNIX.
Converting newline separators in .tmpl and .res files.
1 ... cached ... FAILED
... | [
"From the docs:\n\nThe module should work on all platforms supported by Python. The\n module is supported by its author only on the UNIX platform using\n Python versions 2.1 or newer.\n\n"
] | [
1
] | [] | [] | [
"python"
] | stackoverflow_0005798390_python.txt |
Q:
Logging access to elements in data members of python objects
I want to be able to tell wheter a data field in my Python object was modified since some event. I thought I would implement this
using properties like the following:
class C(object):
def get_scores(self):
print 'getter'
return self.... | Logging access to elements in data members of python objects | I want to be able to tell wheter a data field in my Python object was modified since some event. I thought I would implement this
using properties like the following:
class C(object):
def get_scores(self):
print 'getter'
return self.__scores
def set_scores(self, value):
print 'setter'
... | [
"I'd say there isn't any easy solution for that.\nIf you plan to use lists, as in your example, then you'll need to subclass list and, at least, provide your own implementation of the __setitem__ method to allow the list changes to be monitored. For a complete example in which other methods are also overwritten, pl... | [
3,
2
] | [] | [] | [
"encapsulation",
"python"
] | stackoverflow_0008397861_encapsulation_python.txt |
Q:
How to detect an infinite loop in a monitored process
I'm using Python (winappdbg) to monitor a process (the main feature is to catch the exceptions).
But I would like also to detect infinite loops.
Do you know a way to do that with Python?
With or without winappdbg ...
A:
The only way to detect an infinite loop... | How to detect an infinite loop in a monitored process | I'm using Python (winappdbg) to monitor a process (the main feature is to catch the exceptions).
But I would like also to detect infinite loops.
Do you know a way to do that with Python?
With or without winappdbg ...
| [
"The only way to detect an infinite loop is to include in the loop itself a test for those conditions that would bring it to never end.\nFor example: if your loop is supposed to make a variable decrease until it reaches zero (var == 0 would be the exit condition), you should include a test for what I would call \"p... | [
3,
2,
1
] | [] | [] | [
"infinite_loop",
"monitoring",
"python"
] | stackoverflow_0008398444_infinite_loop_monitoring_python.txt |
Q:
how to best ignore free domain emails for sending a pdf via email(python)
I need to send a certain pdf to corporate users who fill out a form and not to users to use public domain email addresses like gmail. This is not spam email, users are filling out a form to get the pdf in email. Form mentions to use company ... | how to best ignore free domain emails for sending a pdf via email(python) | I need to send a certain pdf to corporate users who fill out a form and not to users to use public domain email addresses like gmail. This is not spam email, users are filling out a form to get the pdf in email. Form mentions to use company email id, but some people still register using their personal email address.
Qu... | [
"You can use in in conjunction with a list, this is an example, don't use this in production, it might break.\nlist = ['gmail', 'aol', 'hotmail', 'yahoo']\nmyemail = 'foo@aol.com'\nif mystring.split('@')[1].split('.')[0] in list:\n print 'I`m public'\n\n",
"To parse e-mail addresses, I'd look at some regex tha... | [
1,
0
] | [] | [] | [
"email",
"python"
] | stackoverflow_0008399008_email_python.txt |
Q:
Nested Lists and List Comprehensions
I am fairly new to Python and I'm having trouble figuring out how to apply a list comprehension to part of a nested list (specifically at the index level).
For instance, if I have the following:
my_list = [[1,2], [3,7], [6,9], [4,3]]
new_list = [[i*2 for i in sublist] for subl... | Nested Lists and List Comprehensions | I am fairly new to Python and I'm having trouble figuring out how to apply a list comprehension to part of a nested list (specifically at the index level).
For instance, if I have the following:
my_list = [[1,2], [3,7], [6,9], [4,3]]
new_list = [[i*2 for i in sublist] for sublist in my_list]
How would I alter my list... | [
"A more general version of mac's:\n>>> my_list = [[1,2], [3,7], [6,9], [4,3]]\n>>> new_list = [[v*2 if i==0 else v for i,v in enumerate(sublist)] for sublist in my_list]\n>>> new_list\n[[2, 2], [6, 7], [12, 9], [8, 3]]\n\n",
"Are you looking for this?\n>>> my_list = [[1,2], [3,7], [6,9], [4,3]]\n>>> [[sublist[0] ... | [
2,
1,
0
] | [] | [] | [
"list_comprehension",
"nested_lists",
"python"
] | stackoverflow_0008399386_list_comprehension_nested_lists_python.txt |
Q:
lock creation in python
When I read the documentation, it seems the lock object is mentioned in both threading and
thread library, so I found there are 2 ways to create a lock: threading.Lock() and thread.allocate_lock(), and the return values are both of type thread.lock.
>>> a = thread.allocate_lock()
>>> b = ... | lock creation in python | When I read the documentation, it seems the lock object is mentioned in both threading and
thread library, so I found there are 2 ways to create a lock: threading.Lock() and thread.allocate_lock(), and the return values are both of type thread.lock.
>>> a = thread.allocate_lock()
>>> b = threading.Lock()
>>> a
<threa... | [
"Python Docs itself recommends the threading module.\n\nNote\n The thread module has been renamed to _thread in Python 3.0. The 2to3 tool will\n automatically adapt imports when converting your sources to 3.0; however, you \n should consider using the high-level threading module instead.\n\nThe threading module ... | [
2
] | [] | [] | [
"locking",
"multithreading",
"python"
] | stackoverflow_0008399634_locking_multithreading_python.txt |
Q:
Security around user uploaded files
I have a client's python website which runs a dropbox-like feature that allows uploading of files.
I want to make sure that uploading files does not open up the server to vulnerabilities.
So, I store all uploaded files as blobs in a postgres database and do not trust the file ... | Security around user uploaded files | I have a client's python website which runs a dropbox-like feature that allows uploading of files.
I want to make sure that uploading files does not open up the server to vulnerabilities.
So, I store all uploaded files as blobs in a postgres database and do not trust the file name and extension of the file, I let the... | [
"The referenced \"bug\" question (which chains to this)doesn't refer to a bug, it says that some MS Office file types are, like Java jars, packaged and compressed as zipfiles. If you rename a .xlsx file to .zip, you can view the contents - I found 13 .xml files and a .bin printer settings file in a simple example.... | [
0
] | [] | [] | [
"file",
"python",
"upload",
"web_applications"
] | stackoverflow_0008399248_file_python_upload_web_applications.txt |
Q:
Triggering Python (from PHP) via MySQL
Background
I am considering various architecture options. While I have used SQL over the years as a query language, I have limited experience with triggers and stored procedures.
The Problem: Integrating PHP and Python via MySQL
In the red corner of the boxing ring, I have so... | Triggering Python (from PHP) via MySQL | Background
I am considering various architecture options. While I have used SQL over the years as a query language, I have limited experience with triggers and stored procedures.
The Problem: Integrating PHP and Python via MySQL
In the red corner of the boxing ring, I have some off-the-shelf PHP which processes some XM... | [
"Solution 4: Let Python publish a webservice (XMLRPC or SOAP) containing a webmethod that can be called by PHP to tell Python that new data is available. \n(Python XMLRPC is very ease to use)\n"
] | [
2
] | [] | [] | [
"mysql",
"python",
"triggers"
] | stackoverflow_0008399677_mysql_python_triggers.txt |
Q:
simple calculation in python
I have a list of integers ordered from maximum to minimum, like this: [2345,67,24,24,11,11,6,6,6,6,6,3,3,3,3,3,1,1,1,1,1,1]
I just simply want to calculate the portion of each value in this list, like 5% is '1', 4% is '3' ,1% is 2345 and print out this result
What's an easy way to do ... | simple calculation in python | I have a list of integers ordered from maximum to minimum, like this: [2345,67,24,24,11,11,6,6,6,6,6,3,3,3,3,3,1,1,1,1,1,1]
I just simply want to calculate the portion of each value in this list, like 5% is '1', 4% is '3' ,1% is 2345 and print out this result
What's an easy way to do this?
| [
"One way. I'm sure there will be better ways to do it. \n import collections\n d = collections.defaultdict(float)\n\n ip = [2345,67,24,24,11,11,6,6,6,6,6,3,3,3,3,3,1,1,1,1,1,1]\n length = len(ip)\n\n for i in ip:\n d[i] += 1\n\n for i in d:\n print \"%5d : %.2f%%\" % (i, (d[i]/length) * 100)... | [
3,
2,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0008399599_python.txt |
Q:
Redis data explorer
Is there any tool to explore the redis data?
I am using redis module with Python
I see a blog with showing stats and thought if there is some people already using
Thank you
A:
You can use redis-cli it does the job, I am not sure what a data exploration tool for redis would looks like anyway,... | Redis data explorer | Is there any tool to explore the redis data?
I am using redis module with Python
I see a blog with showing stats and thought if there is some people already using
Thank you
| [
"You can use redis-cli it does the job, I am not sure what a data exploration tool for redis would looks like anyway, a big list with all the keys ?\nHere is an example of how you can explore your data:\n# list all the keys\n keys *\n# list all the keys starting with zz\n keys zz*\n# check the data type\n type m... | [
1
] | [] | [] | [
"python",
"redis"
] | stackoverflow_0008393378_python_redis.txt |
Q:
Should a webserver ignore the request body when request method is not POST or PUT?
I was working on a simple API server using tornado and all requests require the parameter access_token. I was playing with curl, and was surprised to find that DELETE and GET requests will not extract this value from the request bod... | Should a webserver ignore the request body when request method is not POST or PUT? | I was working on a simple API server using tornado and all requests require the parameter access_token. I was playing with curl, and was surprised to find that DELETE and GET requests will not extract this value from the request body--they only allow this param to be passed via the query string.
ie, when I do
curl -i ... | [
"This is correct per the HTTP/1.1 protocol specification.\nDELETE and GET requests do not accept entity data enclosed in the request.\nAccording to the definition, get requests retrieve their entity data from the request URI.\nHEAD requests are defined as identical to GET requests except that the server should not ... | [
2,
0
] | [] | [] | [
"curl",
"http",
"python",
"tornado"
] | stackoverflow_0008394414_curl_http_python_tornado.txt |
Q:
Automating PDF generation
What would be a solid tool to use for generating PDF reports? Particularly, we are interested in creating interactive PDFs that have video, like the example found here.
Right now we are using Python and reportlab to generate PDFs, but have not explored the library completely (mostly beca... | Automating PDF generation | What would be a solid tool to use for generating PDF reports? Particularly, we are interested in creating interactive PDFs that have video, like the example found here.
Right now we are using Python and reportlab to generate PDFs, but have not explored the library completely (mostly because the license pricing is a li... | [
"Recently, I needed to create PDF reports for a Django application; a ReportLab license was available, but I ended up choosing LaTeX. The benefit of this approach is that we could use Django templates to generate the LaTeX source, and not get over encumbered writing lots of code for the many reports we needed to c... | [
5,
0
] | [] | [] | [
"acrobat",
"adobe",
"pdf",
"python",
"report"
] | stackoverflow_0008394343_acrobat_adobe_pdf_python_report.txt |
Q:
Can we execute multiple commands in the same command prompt launched by python
There is an excel file which contains the paths of multiple scenarios. I am using os.system(command) in a for loop. In each iteration, a path is read from excel file and executes the scenario for that path.
My problem is that every tim... | Can we execute multiple commands in the same command prompt launched by python | There is an excel file which contains the paths of multiple scenarios. I am using os.system(command) in a for loop. In each iteration, a path is read from excel file and executes the scenario for that path.
My problem is that every time, by using os.system(), a CMD opens, execute one command and close. In next iterati... | [
"If you want to use the subprocess module, try something like this : \nfrom subprocess import call\nimport os.path\n\ndef call_scenario(path, config_file):\n retcode = call([\"path/of/exe\", os.path.join(path,config_file)])\n if retcode != 0:\n print \"Something bad happened : %s\"%retcode \n\nWhen usin... | [
2,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0008398558_python.txt |
Q:
bigram of a adjacent sentence in python
Let's say I have three sentences:
hello world
hello python
today is tuesday
If I generate bigrams of each string it would generate something like this:
[('hello', 'world')]
[('this', 'is'), ('is', 'python')]
[('today', 'is'), ('is', 'tuesday')]
Is there a difference betwe... | bigram of a adjacent sentence in python | Let's say I have three sentences:
hello world
hello python
today is tuesday
If I generate bigrams of each string it would generate something like this:
[('hello', 'world')]
[('this', 'is'), ('is', 'python')]
[('today', 'is'), ('is', 'tuesday')]
Is there a difference between bigrams for a sentence and bigrams for two... | [
"\nbut if i want to generate bigrams for the adjacent sentences will it give the same result as the above output. if not what would the output look like?\n\nIt depends what you want. If you define the items of your bigrams to be a whole sentence, it would look like this: \n[('hello world', 'this is python'),('this ... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0008400178_python.txt |
Q:
ZMQ pub/sub reliable/scalable design
I'm designin a pub/sub architecture using ZMQ. I need maximum reliability and scalability and am kind of lost in the hell of possibilities provided.
At the moment, I got a set a publishers and subscribers, linked by a broker. The broker is a simple forwarder device exposing a f... | ZMQ pub/sub reliable/scalable design | I'm designin a pub/sub architecture using ZMQ. I need maximum reliability and scalability and am kind of lost in the hell of possibilities provided.
At the moment, I got a set a publishers and subscribers, linked by a broker. The broker is a simple forwarder device exposing a frontend for publishers, and a backend for ... | [
"It's not possible to answer your question directly because it's predicated on so many assumptions, many of which are probably wrong.\nYou're getting lost because you're using the wrong approach. Consider 0MQ as a language, one that you don't know very well yet. If you start by trying to write \"maximum reliability... | [
7,
4
] | [] | [] | [
"messagebroker",
"publish_subscribe",
"python",
"zeromq"
] | stackoverflow_0008394076_messagebroker_publish_subscribe_python_zeromq.txt |
Q:
How to get data from jQuery script (web.py)?
I can't find any tutorial for jQuery + web.py.
So I've got basic question on POST method.
I've got jQuery script:
<script>
jQuery('#continue').click(function() {
var command = jQuery('#continue').attr('value');
jQuery.ajax({
type: "P... | How to get data from jQuery script (web.py)? | I can't find any tutorial for jQuery + web.py.
So I've got basic question on POST method.
I've got jQuery script:
<script>
jQuery('#continue').click(function() {
var command = jQuery('#continue').attr('value');
jQuery.ajax({
type: "POST",
data: {signal : command},
... | [
"you need to use web.input in web.py to access POST variables\nlook at the docs: http://webpy.org/docs/0.3/api (search for \"function input\")\ndef POST(self):\n s = web.input().signal\n print s\n return\n\n",
"<script>\n jQuery('#continue').click(function() {\n var command = jQuery('#continu... | [
4,
0
] | [] | [] | [
"ajax",
"jquery",
"python",
"web.py"
] | stackoverflow_0008399341_ajax_jquery_python_web.py.txt |
Q:
How do I filter the thick edges of an image?
I am using the Python image library for some basic image operations. I wish to do detect edges of an image, but only the thick ones.
How can I do this?
A:
I think I would start by eroding the image in order to remove the thinner edges, leaving the thicker ones, and t... | How do I filter the thick edges of an image? | I am using the Python image library for some basic image operations. I wish to do detect edges of an image, but only the thick ones.
How can I do this?
| [
"I think I would start by eroding the image in order to remove the thinner edges, leaving the thicker ones, and then edge detect. See erosion and dilation - may help.\n",
"I have a feeling thick edges will get detected as 2 edges - in which case you would have to do non-maximum suppression. Have you tried using a... | [
2,
0,
0
] | [] | [] | [
"image_processing",
"python",
"python_imaging_library"
] | stackoverflow_0008383452_image_processing_python_python_imaging_library.txt |
Q:
generating events in Unix/c/Python
I want to write up a Program either in C / Python - Unix(Open SUSE) for the following:-
1) Report / alarm mechanism : wherin if some updatation has been done in particular folder, or anything else changed at OS level, then it would raise an alarm or a signal should be sent to al... | generating events in Unix/c/Python | I want to write up a Program either in C / Python - Unix(Open SUSE) for the following:-
1) Report / alarm mechanism : wherin if some updatation has been done in particular folder, or anything else changed at OS level, then it would raise an alarm or a signal should be sent to already executing program and would then d... | [
"Use libev, its easy to embed it into your application,, Using either C or Python.\nhttp://software.schmorp.de/pkg/libev.html\nand this is a refrence,, http://pod.tst.eu/http://cvs.schmorp.de/libev/ev.pod\n",
"Looks like the right tool for your job is \nPyinotify --\nProject overview page is here: \nhttps://githu... | [
1,
0
] | [] | [] | [
"c",
"python",
"unix"
] | stackoverflow_0008378020_c_python_unix.txt |
Q:
python networking: asynchat handshake
I am using python asynchat to implement a network protocol.
At connection time I need to send a command and the server answer with a session.
My main problem is that I need to wait until I get the session response. but not sure how to implement this. should I use socket.recv f... | python networking: asynchat handshake | I am using python asynchat to implement a network protocol.
At connection time I need to send a command and the server answer with a session.
My main problem is that I need to wait until I get the session response. but not sure how to implement this. should I use socket.recv for the connection setup? is a good idea?
| [
"When writing a network application using asynchronous techniques, you wait by recording your state somewhere and then letting the main loop continue. At some future time, the data you're waiting for will become available, the main loop will notify you of that fact, and you can combine the new data with the record... | [
3
] | [] | [] | [
"asynchronous",
"asyncore",
"networking",
"python"
] | stackoverflow_0008394790_asynchronous_asyncore_networking_python.txt |
Q:
How to convert timestamp string to datetime object?
Possible Duplicate:
Converting unix timestamp string to readable date in Python
I have a timestamp:
t = 1322745926.123
How to convert timestamp to datetime object ?
datetime.strptime(t,date_format)
What should date_format be in the above function call?
A:
d... | How to convert timestamp string to datetime object? |
Possible Duplicate:
Converting unix timestamp string to readable date in Python
I have a timestamp:
t = 1322745926.123
How to convert timestamp to datetime object ?
datetime.strptime(t,date_format)
What should date_format be in the above function call?
| [
"datetime.strptime() is not the right function for your problem. It convertes a string like \"30 Nov 00\" to a struct_time object.\nYou propably want\nfrom datetime import datetime\nt = 1322745926.123\ndatetime.fromtimestamp(t).isoformat()\n\nThe result from this code is\n'2011-12-01T14:25:26.123000'\n\nif your tim... | [
10,
3,
2
] | [] | [] | [
"python",
"time"
] | stackoverflow_0008400687_python_time.txt |
Q:
mod_rewrite's RewriteMap prg works just for first request
I'm creating a simple IP blacklist. Each request is evaluated against list of IPs and throws 403 if necessary. I decided to deal with it on Apache side with mod_rewrite, its RewriteMap and simple python script.
In VirtualHost:
<VirtualHost *:80>
...
... | mod_rewrite's RewriteMap prg works just for first request | I'm creating a simple IP blacklist. Each request is evaluated against list of IPs and throws 403 if necessary. I decided to deal with it on Apache side with mod_rewrite, its RewriteMap and simple python script.
In VirtualHost:
<VirtualHost *:80>
...
RewriteEngine On
RewriteMap banip prg:/path/to/script.py... | [
"I think you may want to take a close look at the RewriteMap documentation. In particular:\n\nThis program is started once, when the Apache server is started, and\n then communicates with the rewriting engine via its stdin and stdout\n file-handles. For each map-function lookup it will receive the key to\n look... | [
4
] | [] | [] | [
"apache",
"mod_rewrite",
"python"
] | stackoverflow_0008392159_apache_mod_rewrite_python.txt |
Q:
python: plotting a line defining the color by a function
I would like to draw a vector in python defining its color according to the value of a function (something like y=f(x)). For instance if the line has a unit length, at the beginning (x=0) I want to fill it with blue and at the end (x=1) with red, using the f... | python: plotting a line defining the color by a function | I would like to draw a vector in python defining its color according to the value of a function (something like y=f(x)). For instance if the line has a unit length, at the beginning (x=0) I want to fill it with blue and at the end (x=1) with red, using the function to define the palette of colors.
I have tried to look ... | [
"You might need to use Python PIL for that: http://effbot.org/imagingbook/pil-index.htm\nHere is a simple example that could get you started, once you have PIL installed:\nimport Image, ImageDraw\nimport math\n\n# Create image, giving size and background color\nim = Image.new(\"RGB\", (400,400), (0, 128, 128) )\n\... | [
0
] | [] | [] | [
"plot",
"python"
] | stackoverflow_0008370092_plot_python.txt |
Q:
Python asyncore: "filedescriptor out of range in select()"
I have some python script with more than 3k outgoing socket connections, based on asyncore lib.
I can't use select(..) due to connections limit (1024), but poll(..) not working properly too:
asyncore.loop(use_poll=True)
With this invocation my app ignores... | Python asyncore: "filedescriptor out of range in select()" | I have some python script with more than 3k outgoing socket connections, based on asyncore lib.
I can't use select(..) due to connections limit (1024), but poll(..) not working properly too:
asyncore.loop(use_poll=True)
With this invocation my app ignores any socket events. Note that select() on less than 1024 sockets... | [
"First, a minor correction. use_poll=True does not cause asyncore to use epoll(2). It causes it to use poll(2) (moreover, the way asyncore works, there is little reason to try to use epoll(2), because the Python-level overhead of asyncore overwhelms any cost of the socket event notification API being used).\nSeco... | [
0
] | [] | [] | [
"asynchronous",
"asyncore",
"linux",
"python",
"sockets"
] | stackoverflow_0007997012_asynchronous_asyncore_linux_python_sockets.txt |
Q:
Use sched module to run at a given time
I'm working on a python script that needs to run between two given times. I'm required to use the build in sched module as this script needs to be able to run directly on any machine that has python 2.7 as to reduce configuration time. (SO CRON IS NOT AN OPTION)
A few varia... | Use sched module to run at a given time | I'm working on a python script that needs to run between two given times. I'm required to use the build in sched module as this script needs to be able to run directly on any machine that has python 2.7 as to reduce configuration time. (SO CRON IS NOT AN OPTION)
A few variables define the settings for the time to run,... | [
"If I got your requirements right, what you need is probably a loop, that will re-enter a task in the queue every time it will be executed. Something along the lines of:\n# This code assumes you have created a function called \"func\" \n# that returns the time at which the next execution should happen.\ns = sched.s... | [
12
] | [] | [] | [
"python",
"scheduled_tasks"
] | stackoverflow_0008401042_python_scheduled_tasks.txt |
Q:
Match trigrams, bigrams, and unigrams to a text; if unigram or bigram a substring of already matched trigram, pass; python
main_text is a list of lists containing sentences that've been part-of-speech tagged:
main_text = [[('the', 'DT'), ('mad', 'JJ'), ('hatter', 'NN'), ('likes','VB'),
('tea','N... | Match trigrams, bigrams, and unigrams to a text; if unigram or bigram a substring of already matched trigram, pass; python | main_text is a list of lists containing sentences that've been part-of-speech tagged:
main_text = [[('the', 'DT'), ('mad', 'JJ'), ('hatter', 'NN'), ('likes','VB'),
('tea','NN'), ('and','CC'), ('hats', 'NN')], [('the', 'DT'), ('red','JJ')
('queen', 'NN'), ('hates','VB... | [
"I've had a stab at implementing this using a generator. I found some gaps in your spec, so I've made assumptions.\nIf the unigram or bigram forms a substring of an already matched trigram, don't return anything. - Is a bit ambiguous about which gram is referring to the search elements or the matched elements. Make... | [
1
] | [] | [] | [
"nlp",
"python",
"text_processing"
] | stackoverflow_0008304305_nlp_python_text_processing.txt |
Q:
Does the latest version of blender work with python 2.7?
Does blender 2.60a work with python 2.7?
when i launch blender it shows me
found bundled python 2.7 in program file...something like this...
but on the blender site it says that i must have python 3.2, so how did that happen?
A:
Newer versions of Blende... | Does the latest version of blender work with python 2.7? | Does blender 2.60a work with python 2.7?
when i launch blender it shows me
found bundled python 2.7 in program file...something like this...
but on the blender site it says that i must have python 3.2, so how did that happen?
| [
"Newer versions of Blender only work with Python 3. For this reason they give you a full copy of a Python version that they know will work. If you wanted to run Blender with a 2.x version of Python you would have to convert the source and modules to 2.x compatible code and then recompile.\nYour system may have a ... | [
3
] | [] | [] | [
"blender",
"python"
] | stackoverflow_0008400841_blender_python.txt |
Q:
Django 1.3 get_absolute_url and localeurl
I am using Django 1.3 in my project and switching away from the javascript i18n function to localeurl.
Really handy although I am stuck with my get_absolute_url().
Everytime I try and call up a page it defaults to the default language, even if I have selected another one.
... | Django 1.3 get_absolute_url and localeurl | I am using Django 1.3 in my project and switching away from the javascript i18n function to localeurl.
Really handy although I am stuck with my get_absolute_url().
Everytime I try and call up a page it defaults to the default language, even if I have selected another one.
is there a workaround for get_absolute_url() to... | [
"Try whith this:\nfrom django.utils.translation import get_language\nget_language()\n\n"
] | [
1
] | [] | [] | [
"django",
"django_localeurl",
"internationalization",
"python"
] | stackoverflow_0008400826_django_django_localeurl_internationalization_python.txt |
Q:
Avoiding or recovering a locked-up serial port in Python
I'm working on a simple serial transfer program with python 2.7 serial on win7. On my first effort it locked up and I had to terminate it manually. This resulted in the port being inaccessible and needing a re-boot to recover.
I'll be more careful, of cour... | Avoiding or recovering a locked-up serial port in Python | I'm working on a simple serial transfer program with python 2.7 serial on win7. On my first effort it locked up and I had to terminate it manually. This resulted in the port being inaccessible and needing a re-boot to recover.
I'll be more careful, of course, but is there any way to be bullet-proof sure that the port... | [
"When invoking your serial device, you might want to use timeout= argument in the invocation.\nI've been in trouble with the same case, and ended to use timeout + a construction to ensure the port is closed:\nserial = Serial(...)\ntry:\n # do your stuff here\nfinally:\n serial.close()\n\nCheck also the atexit... | [
1
] | [] | [] | [
"python",
"serial_port"
] | stackoverflow_0008402176_python_serial_port.txt |
Q:
Why there's no thread suspension support in Python?
In Python doc, it says
The design of this module is loosely based on Java’s threading model, ... threads cannot be destroyed, stopped, suspended, resumed, or interrupted.
I could understand that the underlying mechanisms of Java and Python are different. But a... | Why there's no thread suspension support in Python? | In Python doc, it says
The design of this module is loosely based on Java’s threading model, ... threads cannot be destroyed, stopped, suspended, resumed, or interrupted.
I could understand that the underlying mechanisms of Java and Python are different. But as there are individual solutions for both UNIX and Window... | [
"thread is not a unit for resource allocation, so before thread is closed, the thread should close all the resource it acquired (including file, socket, and other user-defined resources)\nit you destroy the thread, all these resources will leak.\nso you should not destroy a thread\nfor more information, check http:... | [
3,
2
] | [] | [] | [
"multithreading",
"python"
] | stackoverflow_0008401699_multithreading_python.txt |
Q:
Best setup to develop cross-platform GUI-based apps using Python
I have been using REALbasic for a number of years to develop cross-platform apps. I have become frustrated developing with a proprietary language and so have decided to change languages and have settled on Python and QT.
Since I know no Python, woul... | Best setup to develop cross-platform GUI-based apps using Python | I have been using REALbasic for a number of years to develop cross-platform apps. I have become frustrated developing with a proprietary language and so have decided to change languages and have settled on Python and QT.
Since I know no Python, would people recommend Python 2 or 3?
I think I will be using PyQt or PySi... | [
"PySide and PyQt4 are almost identical. In fact, you can often replace PyQt4 with PySide (and vice versa) in your code's import declarations.\nPython2 and Python3 are almost identical as well, with a few minor changes that a beginner won't notice for a while (aside from print being made a function).\nPython2 has mo... | [
1,
0,
0
] | [] | [] | [
"pyqt",
"pyside",
"python",
"qt",
"user_interface"
] | stackoverflow_0008396569_pyqt_pyside_python_qt_user_interface.txt |
Q:
winappdbg: using a kernel32 function
I try to use the function GetProcessTimes(hprocess).
I use this code :
p = debug.excel(argv,bFollow=True)
win32.kernel32.GetProcessTimes(p)
But that does not work ...
this function takes 4 arguments (5 given)
Someone could help ? What do I forget ?
Thanks
A:
Can i suggest ... | winappdbg: using a kernel32 function | I try to use the function GetProcessTimes(hprocess).
I use this code :
p = debug.excel(argv,bFollow=True)
win32.kernel32.GetProcessTimes(p)
But that does not work ...
this function takes 4 arguments (5 given)
Someone could help ? What do I forget ?
Thanks
| [
"Can i suggest to do your own call ? (Taken from python pybench itself):\n# if you have win32 process\nimport win32process\ndef getprocesstimes_systimes():\n d = win32process.GetProcessTimes(win32process.GetCurrentProcess())\n return (d['UserTime'] / WIN32_PROCESS_TIMES_TICKS_PER_SECOND,\n d['KernelTim... | [
0
] | [] | [] | [
"python",
"windows"
] | stackoverflow_0008401753_python_windows.txt |
Q:
adding elements to different sets from a list in python
Let's say I have a list named
mylist = []
This list contains sentences from a file. My question is:
Is there a way I can add each element of mylist into separate sets?
If it can be done, then how to add to different set?
My code:
mylist = []
wordlist = o... | adding elements to different sets from a list in python | Let's say I have a list named
mylist = []
This list contains sentences from a file. My question is:
Is there a way I can add each element of mylist into separate sets?
If it can be done, then how to add to different set?
My code:
mylist = []
wordlist = open('data.txt', 'r').read().split()
ngrams = [wordlist[i:i+5]... | [
"with open('data.txt', 'r') as f:\n for line in f:\n words = line.split()\n mylist = zip(words, words[1:])\n print mylist\n\n",
"words = input.split() \nzip(words, words[1:])\n\n",
"I might be just misunderstanding your question, yet... are you trying any of these two?\nCreating new s... | [
2,
0,
0
] | [] | [] | [
"list",
"python",
"set"
] | stackoverflow_0008402253_list_python_set.txt |
Q:
matplotlib 3D scatter plot colors of dots very light
I used the command below to create a 3D scatter plot:
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
sizeseq = 2
colorseq = "k"
fig = plt.figure(1, (5,5), dpi=300)
ax = Axes3D(fig)
ax.view_init(20, -45)
x, y, z = [1,2,3,4,5,6,7,8,9,10... | matplotlib 3D scatter plot colors of dots very light | I used the command below to create a 3D scatter plot:
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
sizeseq = 2
colorseq = "k"
fig = plt.figure(1, (5,5), dpi=300)
ax = Axes3D(fig)
ax.view_init(20, -45)
x, y, z = [1,2,3,4,5,6,7,8,9,10], [1,2,3,4,5,6,7,8,9,10], [1,2,3,4,5,6,7,8,9,10]
ax.scatt... | [
"This appears to be scatter using a fancy 3d effect so you can distinguish between dots in the foreground and dots in the background. You might have to hack mplot3d to get it to stop doing that.\nAlternatively, you may be able to use plot3D which doesn't show this behaviour.\nax.plot3D(x, y, z, 'k.', alpha=.8)\n\n"... | [
3,
2
] | [] | [] | [
"matplotlib",
"python",
"scatter_plot"
] | stackoverflow_0008401986_matplotlib_python_scatter_plot.txt |
Q:
Remove bias in yticklabel in matplotlib
My problem is that when I plot y-values that are very close, matplotlib uses a bias for the yticklabel as seen in the picture below (+1.2 in the top left corner).
I don't want the bias as it does not reduce the length of the yticklabels. How can I remove the bias, so that i... | Remove bias in yticklabel in matplotlib | My problem is that when I plot y-values that are very close, matplotlib uses a bias for the yticklabel as seen in the picture below (+1.2 in the top left corner).
I don't want the bias as it does not reduce the length of the yticklabels. How can I remove the bias, so that it shows 1.2000010, 1.2000012...
Here is the c... | [
"The easiest (and probably preferred) way of achieving this using the pyplot interface is using the supplied function pyplot.ticklabel_format in a way analogous to\nfrom pylab import *\n\nplot((0,1),(1.200001,1.200002))\nticklabel_format(useOffset=False)\nshow()\n\nThe other proposed solutions give you more direct ... | [
4,
2,
0
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0008391886_matplotlib_python.txt |
Q:
Python twisted error : "Request.write called on a request after Request.finish was called"
I am new to Twisted and I can't understand why do I get this error while running my script.\
Basically, the script is composed of 2 pages, the first one is a HTML form that calls itself execute a blocking method and display ... | Python twisted error : "Request.write called on a request after Request.finish was called" | I am new to Twisted and I can't understand why do I get this error while running my script.\
Basically, the script is composed of 2 pages, the first one is a HTML form that calls itself execute a blocking method and display the results. When requests are sent to the server simultaneously I got this error:
exceptions.Ru... | [
"I finally found the solution. The code has to be modified as follow.\\\nThe line with the second addCallback needs to be changed to addErrback.\nclass FormPage(Resource): \n def render_GET(self, request):\n return\n <html>\n <body>\n <form method=\"POST\"... | [
1
] | [] | [] | [
"python",
"twisted.web"
] | stackoverflow_0008384648_python_twisted.web.txt |
Q:
FormAlchemy drop down list not setting values
All Im trying to do is set the values of a drop down list using a dictionary using formalchemy 1.3.5.
The documentation reads:
Methods taking an options parameter will accept several ways of specifying those options:
an iterable of SQLAlchemy objects; str() of each o... | FormAlchemy drop down list not setting values | All Im trying to do is set the values of a drop down list using a dictionary using formalchemy 1.3.5.
The documentation reads:
Methods taking an options parameter will accept several ways of specifying those options:
an iterable of SQLAlchemy objects; str() of each object will be the description, and the primary key ... | [
"I guess the doc is out of date. Try with a list\n"
] | [
0
] | [] | [] | [
"formalchemy",
"python",
"sqlalchemy"
] | stackoverflow_0008400471_formalchemy_python_sqlalchemy.txt |
Q:
How can I write a generic Python 2.2 function that returns a list of unset parameters?
I have a function with many input parameters, and I need a function that will return a list of parameter names (not values) for each parameter whose value is '' or None
Normally I'd throw an exception in such a method. If anyon... | How can I write a generic Python 2.2 function that returns a list of unset parameters? | I have a function with many input parameters, and I need a function that will return a list of parameter names (not values) for each parameter whose value is '' or None
Normally I'd throw an exception in such a method. If anyone wants to crack the problem by throwing an exception, that is fine. I still have the requi... | [
"I'm pretty sure I don't understand the question or how what you posted as your 'best solution' meets the requirements, but working just from:\n\nI have a function with many input parameters, and I need a function\n that will return a list of parameter names (not values) for each\n parameter whose value is '' or ... | [
2,
1,
0,
0,
0,
0,
0
] | [] | [] | [
"jython",
"python"
] | stackoverflow_0008360710_jython_python.txt |
Q:
Preferable way to automatically update SSH config file using Python?
I'm using Fabric to automate some of my workflow, most of which involves manipulating EC2 instances.
I'm looking for a way to keep my .ssh/config file up-to-date, as I regularly spin up and shutdown EC2 instances, and it's very helpful to me if I... | Preferable way to automatically update SSH config file using Python? | I'm using Fabric to automate some of my workflow, most of which involves manipulating EC2 instances.
I'm looking for a way to keep my .ssh/config file up-to-date, as I regularly spin up and shutdown EC2 instances, and it's very helpful to me if I can ssh into them easily for debugging and so on.
Entries within my SSH c... | [
"What we do for this sort of configuration is maintain a directory of configuration fragments, which can be added/removed as necessary, and then doing something along the lines of:\ncat .ssh/config.d/* > .ssh/config\n\nThis will append things in lexical order, which means the ordering depends on how you elect to na... | [
8,
0
] | [] | [] | [
"amazon_ec2",
"configuration",
"fabric",
"python",
"ssh"
] | stackoverflow_0008402780_amazon_ec2_configuration_fabric_python_ssh.txt |
Q:
Django plural translation of days and hours not working
Here's my function, which I use to display delays. Delays can be positive (if there's delay) or negative. This function takes timedelta as argument.
def delta_string(delta):
days = delta.days
hours = delta.seconds/3600
if days < 0 and ... | Django plural translation of days and hours not working | Here's my function, which I use to display delays. Delays can be positive (if there's delay) or negative. This function takes timedelta as argument.
def delta_string(delta):
days = delta.days
hours = delta.seconds/3600
if days < 0 and hours > 0:
days = days + 1
hours = 2... | [
"Instead of rolling out your own solution, use Django's built-in timesince template filter (if you need this functionality within a template) or timesince function in django.utils.timesince. These will handle translation for you.\n"
] | [
2
] | [] | [] | [
"django",
"localization",
"python",
"translation"
] | stackoverflow_0008401379_django_localization_python_translation.txt |
Q:
Several issues with capturing a screen video with python
i have already asked a similar question on stackoverflow, but its not the same :-)
I have three problems with my code:
The framerate is not steady. When i execute the code without the screengrab, i still get low framerates, and whats worse, the framerate va... | Several issues with capturing a screen video with python | i have already asked a similar question on stackoverflow, but its not the same :-)
I have three problems with my code:
The framerate is not steady. When i execute the code without the screengrab, i still get low framerates, and whats worse, the framerate varies. I post output below. Any tips to fix this?
Its very slow... | [
"The documentation for time.sleep\n\ntime.sleep(secs)¶\nSuspend execution for the given number of seconds. The argument may be a floating point number to indicate a more precise sleep time.\n The actual suspension time may be less than that requested because any\n caught signal will terminate the sleep() followin... | [
0,
0
] | [] | [] | [
"optimization",
"python"
] | stackoverflow_0008402542_optimization_python.txt |
Q:
Linker Error Lunatic Python lua.require('socket') -> undefined symbol: lua_getmetatable
I have a python project that relies on some lua files, one of which requires 'socket'. I get an error loading socket.core "undefined symbol: lua_getmetatable" when I try to require that lua file from python 2.7.
Simple reprodu... | Linker Error Lunatic Python lua.require('socket') -> undefined symbol: lua_getmetatable | I have a python project that relies on some lua files, one of which requires 'socket'. I get an error loading socket.core "undefined symbol: lua_getmetatable" when I try to require that lua file from python 2.7.
Simple reproducer:
$ python
Python 2.7.1+ (r271:86832, Apr 11 2011, 18:13:53)
[GCC 4.5.2] on linux2
Type "... | [
"The problem is not in luasocket, but in the way symbols from shared libraries are handled.\nThe problem is that the while the lua.so (Python module) links to liblua5.1.so, shared modules loaded by require do not have access to the symbols from liblua5.1.so. On Mac OS X this works, because symbols from dlopen are l... | [
6
] | [] | [] | [
"c",
"lua",
"python",
"ubuntu"
] | stackoverflow_0008361437_c_lua_python_ubuntu.txt |
Q:
How to find how many Ethernet cards are in my computer?
I want to write code to find how many Ethernet cards my computer has. Any ideas?
A:
There is no protable way to do so unless you have any specific OS in mind.
As for Win32/Win64 you can parse the o/p from ipconfig /all
As for linux you can parse the o/p f... | How to find how many Ethernet cards are in my computer? | I want to write code to find how many Ethernet cards my computer has. Any ideas?
| [
"There is no protable way to do so unless you have any specific OS in mind. \n\nAs for Win32/Win64 you can parse the o/p from ipconfig /all\nAs for linux you can parse the o/p from lshw -class network\nAs for other systems similar things should be here\n\nYou can extend the below code, by adding more system, comman... | [
2,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0008402755_python.txt |
Q:
BoxSizer issue: Not expanding to fit contents of StaticText
I'm creating a StaticText element with multiple child StaticText elements that aren't quite sizing correctly. I'm sure it's a BoxSizer issue, but maybe not? Here's a screenshot of what's happening: http://cloud.smallparade.com/CMxC
That should read:
Wilco... | BoxSizer issue: Not expanding to fit contents of StaticText | I'm creating a StaticText element with multiple child StaticText elements that aren't quite sizing correctly. I'm sure it's a BoxSizer issue, but maybe not? Here's a screenshot of what's happening: http://cloud.smallparade.com/CMxC
That should read:
Wilco
One Sunday Morning (Song
For Jane Smiley's Boyfriend)
The Whole ... | [
"I've never seen anyone create a sizer like that. Normally you do this:\nmySizer = wx.BoxSizer(wx.VERTICAL)\n\nThen you add each element. I suspect that since you're doing it in a weird way, you're getting weird results. Don't use the StaticText's sizer method for this. They are not container objects. Instead, do t... | [
1
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0008403632_python_wxpython.txt |
Q:
how to intercept CRUD in sqlalchemy based app?
I am running an app that using sqlalchemy to access db layer. now I need to get all the insert, update, delete operation, I wrote db operation in two many places and seems it will be very risky to change those code. Is there anyway that I could just change sqlalche... | how to intercept CRUD in sqlalchemy based app? | I am running an app that using sqlalchemy to access db layer. now I need to get all the insert, update, delete operation, I wrote db operation in two many places and seems it will be very risky to change those code. Is there anyway that I could just change sqlalchemy's code and capture all "insert, update, delete" o... | [
"See before_execute and other events documented in Connection Events. Sample from documentation verbatim:\nfrom sqlalchemy import event, create_engine\n\ndef before_execute(conn, clauseelement, multiparams, params):\n log.info(\"Received statement: %s\" % clauseelement)\n\nengine = create_engine('postgresql://sc... | [
1
] | [] | [] | [
"crud",
"database",
"orm",
"python",
"sqlalchemy"
] | stackoverflow_0008403121_crud_database_orm_python_sqlalchemy.txt |
Q:
Why does searching for YouTube videos using the Python API in Google App Engine go slowly and give me this warning?
My application is a modification of the "Getting Started Guide" for the YouTube Data Python API found here. Here is my code:
def initialize():
yt_service = gdata.youtube.service.YouTubeService()... | Why does searching for YouTube videos using the Python API in Google App Engine go slowly and give me this warning? | My application is a modification of the "Getting Started Guide" for the YouTube Data Python API found here. Here is my code:
def initialize():
yt_service = gdata.youtube.service.YouTubeService()
# Turn on HTTPS/SSL access.
# Note: SSL is not available at this time for uploads.
yt_service.ssl = True
... | [
"Looks like this is a security \"feature\" in app engine:\nhttp://code.google.com/appengine/docs/python/urlfetch/overview.html#Request_Headers\nHere's the actual code that does the stripping on line 238:\nhttp://code.google.com/p/googleappengine/source/browse/trunk/python/google/appengine/api/urlfetch_stub.py?r=56\... | [
1
] | [] | [] | [
"gdata",
"google_app_engine",
"python",
"youtube",
"youtube_api"
] | stackoverflow_0008395013_gdata_google_app_engine_python_youtube_youtube_api.txt |
Q:
Python: fastest list.index() operation USING 'is', not '==' (i.e. by reference)
Question:
In python, list.index(a) will return any index for which a == list[index] is true. But I need to find the index for which a is list[index], and do so as quickly as possible (speed is vital). How would I go about doing so?
Bac... | Python: fastest list.index() operation USING 'is', not '==' (i.e. by reference) | Question:
In python, list.index(a) will return any index for which a == list[index] is true. But I need to find the index for which a is list[index], and do so as quickly as possible (speed is vital). How would I go about doing so?
Background:
Maybe I am going about programming the wrong way. Just in case, here is the ... | [
"\nIn python, list.index(a) will return any index for which a == list[index] is true. But I need to find the index for which a is list[index], and do so as quickly as possible (speed is vital).\n\nEven if list.index() worked that way, you wouldn't get much benefit from that. Since there is no character type in Pyt... | [
2,
1,
0
] | [] | [] | [
"list",
"python"
] | stackoverflow_0008403460_list_python.txt |
Q:
want to parse paragraph using regex
I have paragraph like below. I just Want to ignore text [[drama film|film]].Output should be film.
ANother example [[Scotland|Scottish]] output should be Scottish
If there no Pipe [[Eva Birthistle]] then output should be only Eva Birthistle
Ae Fond Kiss... (also known as ''Jus... | want to parse paragraph using regex | I have paragraph like below. I just Want to ignore text [[drama film|film]].Output should be film.
ANother example [[Scotland|Scottish]] output should be Scottish
If there no Pipe [[Eva Birthistle]] then output should be only Eva Birthistle
Ae Fond Kiss... (also known as ''Just a Kiss'') is a 2004 romantic [[drama fi... | [
"The other solution's didn't work because your question was unclear. Here is the solution to this question\n>>> x=\"Ae Fond Kiss... (also known as ''Just a Kiss'') is a 2004 romantic [[drama film|film]]\\ndirected by [[Ken Loach]], and starring [[Atta Yaqub]] and [[Eva Birthistle]]. The \\ntitle is taken from a [[S... | [
0,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0008403856_python_regex.txt |
Q:
Parallelism in python isn't working right
I was developing an app on gae using python 2.7, an ajax call requests some data from an API, a single request could take ~200 ms, however when I open two browsers and make two requests at a very close time they take more than the double of that, I've tried putting everyth... | Parallelism in python isn't working right | I was developing an app on gae using python 2.7, an ajax call requests some data from an API, a single request could take ~200 ms, however when I open two browsers and make two requests at a very close time they take more than the double of that, I've tried putting everything in threads but it didn't work.. (this happe... | [
"David Beazley gave a talk about this issue at PyCon 2010.\nAs others have already stated, for some tasks, using threading especially with multiple cores can lead to slower performance than the same task performed by a single thread. The problem, Beazley found, had to do with multiple cores having a \"GIL battle\":... | [
9,
4,
1
] | [] | [] | [
"google_app_engine",
"multithreading",
"python",
"python_2.7",
"python_multithreading"
] | stackoverflow_0008403768_google_app_engine_multithreading_python_python_2.7_python_multithreading.txt |
Q:
Can I call a jython script from java -jar myjar.jar?
I have a python script that I believe I can convert to jython. I want to call java -jar myjar.jar to launch my application. Is it possible to call that command, and have the main class call that script (does it have to be converted to jython)? The script launche... | Can I call a jython script from java -jar myjar.jar? | I have a python script that I believe I can convert to jython. I want to call java -jar myjar.jar to launch my application. Is it possible to call that command, and have the main class call that script (does it have to be converted to jython)? The script launches my program. Let me know, it might sound a little roundab... | [
"You can create a jar base on you Jython \nhttp://wiki.python.org/jython/JythonFaq/DistributingJythonScripts\n"
] | [
2
] | [] | [] | [
"jar",
"java",
"jython",
"launch",
"python"
] | stackoverflow_0008402059_jar_java_jython_launch_python.txt |
Q:
Which web frameworks support Python3 (PEP3333 - WSGI 1.0.1 compliance)
I had recently started learning Python, and with all the research I decided it was good to start with Python3 (that's what even Guido advised at Google IO'11). But lack of support for Python3 by major (web)frameworks has really bugged me. I kno... | Which web frameworks support Python3 (PEP3333 - WSGI 1.0.1 compliance) | I had recently started learning Python, and with all the research I decided it was good to start with Python3 (that's what even Guido advised at Google IO'11). But lack of support for Python3 by major (web)frameworks has really bugged me. I know this same question has been asked all over the Internet and even on StackO... | [
"There was earlier little incentive for web frameworks to move to Python 3, as there was no usable WSGI standard for Python 3. Now we have PEP 3333, but it is still very new, so few frameworks had yet had time to port to Python 3.\nBesides CherryPy there is only two other Python 3 web frameworks I'm aware of, and t... | [
6,
3
] | [] | [] | [
"python",
"python_3.x",
"web_frameworks",
"wsgi"
] | stackoverflow_0006258706_python_python_3.x_web_frameworks_wsgi.txt |
Q:
Appending a new line to file
I am wondering how to append a newline every time the list reaches the size of the checker board (8). Heres my code so far. It works but I want to put a newline every 8 characters.
saveFile=input("Please enter the name of the file you want to save in: ")
outputFile=open(saveFile,"w"... | Appending a new line to file | I am wondering how to append a newline every time the list reaches the size of the checker board (8). Heres my code so far. It works but I want to put a newline every 8 characters.
saveFile=input("Please enter the name of the file you want to save in: ")
outputFile=open(saveFile,"w")
pieceList=[]
for row_index i... | [
"Use \nif row_index % 8 == 0:\n # put newline\n\n",
"saveFile=input(\"Please enter the name of the file you want to save in: \")\n outputFile=open(saveFile,\"w\")\n pieceList=[]\n characterCounter =0\n for row_index in range (self.SIZE):\n for column_index in range(self.SIZE):\n pieceRow=[]\n ... | [
2,
1,
0,
0,
0
] | [] | [] | [
"file_io",
"python"
] | stackoverflow_0008404152_file_io_python.txt |
Q:
Python logging from multiple processes
I have a possibly long running program that currently has 4 processes, but could be configured to have more. I have researched logging from multiple processes using python's logging and am using the SocketHandler approach discussed here. I never had any problems having a si... | Python logging from multiple processes | I have a possibly long running program that currently has 4 processes, but could be configured to have more. I have researched logging from multiple processes using python's logging and am using the SocketHandler approach discussed here. I never had any problems having a single logger (no sockets), but from what I re... | [
"\nDo I need to create a new log object after each os.fork()? What happens to the existing global log object?\n\nAFAIK the global log object remains pointing to the same logger in parent and child processes. So you shouldn't need to create a new one. However, I think you should create and add the SocketHandler afte... | [
2
] | [] | [] | [
"file_io",
"multiprocessing",
"python",
"sockets"
] | stackoverflow_0008403839_file_io_multiprocessing_python_sockets.txt |
Q:
Return a django user that is in two models' many-to-many fields
I have the models:
class Project(models.Model):
project_collaborators = models.ManyToManyField(User)
class Node(models.Model):
collaborators = models.ManyToManyField(User)
project = models.ForeignKey(Project)
I would like to get all user... | Return a django user that is in two models' many-to-many fields | I have the models:
class Project(models.Model):
project_collaborators = models.ManyToManyField(User)
class Node(models.Model):
collaborators = models.ManyToManyField(User)
project = models.ForeignKey(Project)
I would like to get all users that are node collaborators and also a project collaborator, assumi... | [
"from django.db.models import F\nUser.objects.filter(node__pk=node.pk, project=F('node__project'))\n\nThat should work. Haven't tested it. If not, you can try this one as well:\nUser.objects.filter(node__pk=node.pk, project__node__pk=node.pk)\n\nAssuming they both work, you might want to try both in something like ... | [
1
] | [] | [] | [
"django",
"django_forms",
"django_models",
"python"
] | stackoverflow_0008404512_django_django_forms_django_models_python.txt |
Q:
pythonic module organization - how to refer to files in root directory?
I have my python code in a folder called "project", so my code files are in project/*.py. I want to have submodules within it, e.g.
project/code.py # where code lives
project/mymodule1 # where more code lives
project/mymodule2
each module d... | pythonic module organization - how to refer to files in root directory? | I have my python code in a folder called "project", so my code files are in project/*.py. I want to have submodules within it, e.g.
project/code.py # where code lives
project/mymodule1 # where more code lives
project/mymodule2
each module directory has its own init.py file, e.g.
project/mymodule1/__init__.py
suppos... | [
"This is possible in Python 2.5 and above. See the docs on Intra-Package References.\nA couple of things to note:\nIf you intend for your users to install your package somewhere, for example using distutils or setuptools, then project will likely already be in the search path, and you can change the relative impor... | [
4,
1
] | [] | [] | [
"module",
"python",
"pythonpath",
"unix"
] | stackoverflow_0008404296_module_python_pythonpath_unix.txt |
Q:
Override f[k] += v for a class
I'm implementing a Fenwick tree class in python.
Basically I have an internal list and two methods, get(key) and increase(key, inc), to handle reading and updating this list.
Mapping f[5] to f.get(5) is easy with __getitem__, but is there any way to make f[5] += 2 mean f.increase(5, ... | Override f[k] += v for a class | I'm implementing a Fenwick tree class in python.
Basically I have an internal list and two methods, get(key) and increase(key, inc), to handle reading and updating this list.
Mapping f[5] to f.get(5) is easy with __getitem__, but is there any way to make f[5] += 2 mean f.increase(5, 2)?
I found a relevant mailing list ... | [
"No, the approach you described is pretty much the only option. There may be minor variations, but there's no (sane, at least) way around the fact that f[5] += 2 will call __getitem__, then __setitem__, and do the + part only on the object retrieved, without considering the container.\n",
"I think it depends on w... | [
3,
0,
0
] | [] | [] | [
"python",
"python_3.2"
] | stackoverflow_0008404414_python_python_3.2.txt |
Q:
how to emit (fire) axes_leave_event
This is my first question of stackoverflow! I've got a PyQT gui that's displaying an mpl figure canvas. I've set the margins around my main axes to 0 so the plot will completely fill the figure canvas and the widget that contains it. The problem is that when I do this I no lo... | how to emit (fire) axes_leave_event | This is my first question of stackoverflow! I've got a PyQT gui that's displaying an mpl figure canvas. I've set the margins around my main axes to 0 so the plot will completely fill the figure canvas and the widget that contains it. The problem is that when I do this I no longer get the axes_leave_event when I leav... | [
"This is somewhat based on guesswork, since I can't test it with matplotlib, but something along these lines might work:\nclass MyDiagram(FigureCanvas):\n def __init__(self, fig):\n FigureCanvas.__init__(self, fig)\n self._cursor = None\n\n def enterEvent(self, event):\n if (self._cursor ... | [
0
] | [] | [] | [
"matplotlib",
"pyqt",
"python"
] | stackoverflow_0008361848_matplotlib_pyqt_python.txt |
Q:
What's the pythonic way of conditional variable initialization?
Due to the scoping rules of Python, all variables once initialized within a scope are available thereafter. Since conditionals do not introduce new scope, constructs in other languages (such as initializing a variable before that condition) aren't ne... | What's the pythonic way of conditional variable initialization? | Due to the scoping rules of Python, all variables once initialized within a scope are available thereafter. Since conditionals do not introduce new scope, constructs in other languages (such as initializing a variable before that condition) aren't necessarily needed. For example, we might have:
def foo(optionalvar = ... | [
"Python also has a very useful if syntax pattern which you can use here\n message = get_other_message() if optional_var else get_message()\n\nOr if you want to compare strictly with None\n message = get_other_message() if optional_var is not None else get_message()\n\nUnlike with example 1) you posted this doesn'... | [
13,
4,
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0008404856_python.txt |
Q:
Jumping to end of python output buffer in emacs
When using python-mode, py-execute-buffer puts the output in a Python Output buffer. I'm nearly always interested in seeing the end of that output, not the beginning. How can I configure emacs so that it automatically jumps to the bottom of the buffer, instead of sta... | Jumping to end of python output buffer in emacs | When using python-mode, py-execute-buffer puts the output in a Python Output buffer. I'm nearly always interested in seeing the end of that output, not the beginning. How can I configure emacs so that it automatically jumps to the bottom of the buffer, instead of starting at the top, when it first appears?
| [
"I don't see any hooks for that, but it can be done with some advising. This code attaches and idle timer with 0 timeout to py-postprocess-output-buffer, so that is executed after output postprocessing is done and control is given back to the user:\n(defadvice py-postprocess-output-buffer (after my-py-postprocess-o... | [
1
] | [] | [] | [
"emacs",
"python"
] | stackoverflow_0008402838_emacs_python.txt |
Q:
Natural Language parser for parsing sports play-by-play data
I'm trying to come up with a parser for football plays. I use the term "natural language" here very loosely so please bear with me as I know little to nothing about this field.
Here are some examples of what I'm working with
(Format: TIME|DOWN&DIST|OFF_... | Natural Language parser for parsing sports play-by-play data | I'm trying to come up with a parser for football plays. I use the term "natural language" here very loosely so please bear with me as I know little to nothing about this field.
Here are some examples of what I'm working with
(Format: TIME|DOWN&DIST|OFF_TEAM|DESCRIPTION):
04:39|4th and 20@NYJ46|Dal|Mat McBriar punts fo... | [
"I think pyparsing would be very useful here.\nYour input text looks very regular (unlike real natural language), and pyparsing is great at this stuff. you should have a look at it.\nFor example to parse the following sentences:\nMat McBriar punts for 32 yards to NYJ14.\nMark Sanchez rush to the right for 3 yards t... | [
4,
0
] | [] | [] | [
"nlp",
"parsing",
"python"
] | stackoverflow_0008198923_nlp_parsing_python.txt |
Q:
Google App Engine and win32 DDE
I'm trying to set up a little server through the App Engine Python development server:
GOAL:
On Windows I've got a DDE application.
I need to read data from this application and serve it over the Internet.
SITUATION:
The development server is working correctly on port 80, enabling m... | Google App Engine and win32 DDE | I'm trying to set up a little server through the App Engine Python development server:
GOAL:
On Windows I've got a DDE application.
I need to read data from this application and serve it over the Internet.
SITUATION:
The development server is working correctly on port 80, enabling me to store data and make it available... | [
"The problem was not on the GAE development server: I managed to uninstall the win32 python build 216 library and install a previous version. The problem was indeed with the manifest of the build 216 and not with the GAE development server. Now it works fine with build 214.\n"
] | [
1
] | [] | [] | [
"dde",
"google_app_engine",
"python",
"pywin32"
] | stackoverflow_0008384052_dde_google_app_engine_python_pywin32.txt |
Q:
Function not writing to .xls correctly . Python 2.7.1
When I check my Excel file it only writes one line of data which is the last input.
def Table(fn,fe):
for fseq in fn:
count=0
for k in fseq:
if k=='G' or k=='C':
count=count+1
... | Function not writing to .xls correctly . Python 2.7.1 | When I check my Excel file it only writes one line of data which is the last input.
def Table(fn,fe):
for fseq in fn:
count=0
for k in fseq:
if k=='G' or k=='C':
count=count+1
percentage=(float(count)/len(fseq))*100
... | [
"Your for loop is looping over the strings, not the characters of each string. Try this:\n for k in fn:\n for c in k:\n if c=='G' or c=='C':\n count=count+1\n\n(The else: is not necessary.)\nYou will also need to move your file writing code inside of the outer loop in order to get y... | [
1,
0,
0
] | [] | [] | [
"export_to_excel",
"function",
"python",
"string"
] | stackoverflow_0008380516_export_to_excel_function_python_string.txt |
Q:
How to ask the DB if a file exists from a .js in Google App Engine
what I'm trying to do is have a upload button to upload files to our storage system. I'm using Google App Engine with Python. Also HTML and Javascript for views.
For that, we have a HTML, and a.js that asks the user if he's sure that he wants to ov... | How to ask the DB if a file exists from a .js in Google App Engine | what I'm trying to do is have a upload button to upload files to our storage system. I'm using Google App Engine with Python. Also HTML and Javascript for views.
For that, we have a HTML, and a.js that asks the user if he's sure that he wants to overwrite a file. For that overwriting question, I need to ask the Databas... | [
"Here's a possibility:\nImplement a servlet that can answer the question given a filename; it could return a '0' or '1' (or whatever you choose) as its HTTP response depending on whether the file exists. Then make an XmlHttpRequest POST to that servlet from your javascript with the filename as a POST parameter. Dep... | [
1,
1
] | [] | [] | [
"google_app_engine",
"gql",
"html",
"javascript",
"python"
] | stackoverflow_0008404589_google_app_engine_gql_html_javascript_python.txt |
Q:
Where does the initial sys.path come from
I'm trying to figure out where does the initial sys.path value come from. One ubuntu system suddenly (by which I mean probably manually by someone doing something weird) lost entries at the end of the array.
All other hosts: ['', '/usr/lib/python2.7', '/usr/lib/python2.7/p... | Where does the initial sys.path come from | I'm trying to figure out where does the initial sys.path value come from. One ubuntu system suddenly (by which I mean probably manually by someone doing something weird) lost entries at the end of the array.
All other hosts: ['', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-linux2', '/usr/lib/python2.7/lib-tk', '/usr... | [
"It comes from the python-support package, specifically from the /usr/lib/python2.7/dist-packages/python-support.pth file that is installed.\nThere shouldn't be any modules installed to that directory manually and any package installing modules to that directory should have a dependency on the python-support packag... | [
4
] | [] | [] | [
"import",
"path",
"python"
] | stackoverflow_0008405855_import_path_python.txt |
Q:
Using jsonpickle in python to parse multiple child attributes
I'm parsing JSON that looks like this:
{
"attr1": true,
"attr2": "foo",
"attr3": 7,
"attr4": [
{
"someattr1": "foo",
"someattr2": "bar"
},
{
"someattr1": "foo",
"someattr2": "bar"
... | Using jsonpickle in python to parse multiple child attributes | I'm parsing JSON that looks like this:
{
"attr1": true,
"attr2": "foo",
"attr3": 7,
"attr4": [
{
"someattr1": "foo",
"someattr2": "bar"
},
{
"someattr1": "foo",
"someattr2": "bar"
},
],
"attr6": false
}
How would I go about get... | [
"\nHow would I go about getting the 2nd attr4's someattr1 using jsonpickle?\n\nPlease note that your json object has an extra comma before the closing square bracket that will make the parser fail. Once removed that, you can:\nimport jsonpickle as jp\n\njson = '''\n{\n \"attr1\": true,\n \"attr2\": \"fooA\",\... | [
0
] | [] | [] | [
"json",
"parsing",
"python"
] | stackoverflow_0008405666_json_parsing_python.txt |
Q:
My class cannot find a python file in the jar
I have a jar file that launches a python script. It works if my jar file is at the root of the working directory. If I move it out of the working directory, it cannot find the python script anymore. Why does my call to find the script file not look inside the jar? I us... | My class cannot find a python file in the jar | I have a jar file that launches a python script. It works if my jar file is at the root of the working directory. If I move it out of the working directory, it cannot find the python script anymore. Why does my call to find the script file not look inside the jar? I use ./(the path). Why does it automatically look in t... | [
"Reposting my guess as an answer:\nAre you looking for the python script as a file? or as a resource? You might want to share more information about your problem because right now all anyone can do is guess. My guess is that you're trying to read the Python script as a file, and files don't exist inside of jars. To... | [
1
] | [] | [] | [
"jar",
"java",
"launch",
"path",
"python"
] | stackoverflow_0008405987_jar_java_launch_path_python.txt |
Q:
Remove all but certain words from a list (like a white list)
Imagine a list that has random words:
words = ['elephant', 'dog', 'blue', 'sam', 'white', 'red', 'sun', 'moon']
And I want to remove all but the following words (like a whitelist):
colors = ['red', 'green', 'blue', 'orange', 'white']
And I want to prod... | Remove all but certain words from a list (like a white list) | Imagine a list that has random words:
words = ['elephant', 'dog', 'blue', 'sam', 'white', 'red', 'sun', 'moon']
And I want to remove all but the following words (like a whitelist):
colors = ['red', 'green', 'blue', 'orange', 'white']
And I want to produce the following list (order matters):
filtered = ['blue', 'white... | [
"If you want to keep order and efficiently filter out non-colors, create a set of colors, so that in checking is faster and then you can just go thru all words and filter out non-colors\nwords = ['elephant', 'dog', 'blue', 'sam', 'white', 'red', 'sun', 'moon']\ncolors = set(['red', 'green', 'blue', 'orange', 'white... | [
4,
2,
1,
1,
1
] | [] | [] | [
"list",
"python"
] | stackoverflow_0008404848_list_python.txt |
Q:
Python scoping mutable vs immutable
First I'm going to start like everyone else. I'm new to python. My teacher gave me the problem:
def f(a, b, c):
a = 1
c = b
c[0] = 2
a = 10
b = [11, 12, 13]
c = [13, 14, 15]
f(a, b, c)
print a, b, c
It prints:
10 [2, 12, 13] [13, 14, 15]
I understand... | Python scoping mutable vs immutable | First I'm going to start like everyone else. I'm new to python. My teacher gave me the problem:
def f(a, b, c):
a = 1
c = b
c[0] = 2
a = 10
b = [11, 12, 13]
c = [13, 14, 15]
f(a, b, c)
print a, b, c
It prints:
10 [2, 12, 13] [13, 14, 15]
I understand that a stays at 10 because integers are ... | [
"c = b \nc[0] = 2\n\nSince you're setting c to point to b, You could just as easily do this:\ndef f(a, b, unused): # notice c isn't in the parameter list \n a = 1\n c = b # c is declared here\n c[0] = 2 # c points to b, so c[0] is b[0]\n\nNow it's obvious that c is always the same as b, so why not just... | [
4,
2,
1
] | [] | [] | [
"immutability",
"mutable",
"python",
"scoping"
] | stackoverflow_0008407035_immutability_mutable_python_scoping.txt |
Q:
Fastest way to solve long polynomial with lots of different powers
I'm looking for the fastest solution, x, to this polynomial equation:
Let m be an element in set M.
sum over all m {a_m * x^(b_m) - c_m * x^(b_m - 1)} = 0, where a_m, b_m, c_m are all different for each m. The set M has ~15-20 elements.
If the solu... | Fastest way to solve long polynomial with lots of different powers | I'm looking for the fastest solution, x, to this polynomial equation:
Let m be an element in set M.
sum over all m {a_m * x^(b_m) - c_m * x^(b_m - 1)} = 0, where a_m, b_m, c_m are all different for each m. The set M has ~15-20 elements.
If the solution is > 4, it will return 4. If the solution is < 0, it will return 0.... | [
"If you're only looking for one root and not all roots, you can use Newton's Method, which I expect is reasonably fast for the polynomials you've described.\nlet f(x) = sum over all m {a*x^(b) - c*x^(b-1)}\nthen f'(x), the derivative of f(x), is the sum over all m {(a*b)*x^(b-1) - (c*(b-1))*x^(b-2)}.\ndef newton(f,... | [
2
] | [] | [] | [
"math",
"optimization",
"package",
"performance",
"python"
] | stackoverflow_0008406745_math_optimization_package_performance_python.txt |
Q:
finding element of numpy array that satisfies condition
One can use numpy's extract function to match an element in an array. The following code matches an element 'a.' exactly in an array. Suppose I want
to match all elements containing '.', how would I do that? Note that in this case, there would be two matches.... | finding element of numpy array that satisfies condition | One can use numpy's extract function to match an element in an array. The following code matches an element 'a.' exactly in an array. Suppose I want
to match all elements containing '.', how would I do that? Note that in this case, there would be two matches. I'd also like to get the row and column number of the matche... | [
"You can use the string operations:\n>>> import numpy as np\n>>> x = np.array([['a.','cd'],['ef','g.']])\n>>> x[np.char.find(x, '.') > -1]\narray(['a.', 'g.'], \n dtype='|S2')\n\nEDIT: As per request in the comments... If you want to find out the indexes of where the target condition is true, use numpy.where:\... | [
9,
3
] | [] | [] | [
"numpy",
"python",
"search"
] | stackoverflow_0008407090_numpy_python_search.txt |
Q:
Custom HTML for ManyToMany Field in ModelForm
I am currently working on a form that displays information about a specific product on my website. Each price is represented by a Price object, and each Item has several Price objects associated with it. I have created a ModelForm to display the data in my Item, which ... | Custom HTML for ManyToMany Field in ModelForm | I am currently working on a form that displays information about a specific product on my website. Each price is represented by a Price object, and each Item has several Price objects associated with it. I have created a ModelForm to display the data in my Item, which works. However, when I try to display the ManyToMan... | [
"One approach is to use an inline_modelformset to edit your prices. This will probably require you to change your Item model to not have a M2M to Price, but rather have Item as an FK to Price.\nThis way, you can use a custom form for Price, and have one or more instances of a PriceForm that will be automatically re... | [
0
] | [] | [] | [
"django",
"django_forms",
"django_templates",
"python"
] | stackoverflow_0008379860_django_django_forms_django_templates_python.txt |
Q:
How to call a cmd file within python script
This is the python script will do. The question is how to call the external cmd file within the function?
Read a CSV file in the directory.
If the content in 6th column is equal to 'approved', then calls an
external windows script 'TransferProd.cmd'
.
def readCSV(x)... | How to call a cmd file within python script | This is the python script will do. The question is how to call the external cmd file within the function?
Read a CSV file in the directory.
If the content in 6th column is equal to 'approved', then calls an
external windows script 'TransferProd.cmd'
.
def readCSV(x):
#csvContents is a list in the global scope ... | [
"Take a look at the subprocess module.\nimport subprocess\np = subprocess.Popen(['TransferProd.cmd'])\n\nYou can specify where you want output/errors to go (directly to a file or to a file-like object), pipe in input, etc.\n",
"import os\nos.system('TransferProd.cmd')\n\nThis works in both unix/windows flavors as... | [
4,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0008407279_python.txt |
Q:
TypeError while working with a Python list
In the following code fragment:
def func_5_2(datei, num):
import linecache
i = 0
number = num + 1
l = []
while True:
l[i] = linecache.getline(datei, number)
if (l[i] == ''):
break
Is it possible to fix the problem I get on ... | TypeError while working with a Python list | In the following code fragment:
def func_5_2(datei, num):
import linecache
i = 0
number = num + 1
l = []
while True:
l[i] = linecache.getline(datei, number)
if (l[i] == ''):
break
Is it possible to fix the problem I get on this line?
list[i] = linecache.getline(datei, nu... | [
"You get this exception because the object list is never defined. Initialize list before using it. \nFor example like this:\nlist = []\n\nYour code is trying to assign an item to the builtin sequence type list.\nIt is not a good practice to name variables like existing types...\nGive the variable another name like ... | [
1
] | [] | [] | [
"getline",
"linecache",
"list",
"python"
] | stackoverflow_0008407475_getline_linecache_list_python.txt |
Q:
How to render tags in Flask/GAE?
I am new to all these and trying to figure out how to make a simple blog post with tags.
Here are the relevant parts:
Model:
class Post(db.Model):
title = db.StringProperty(required = True)
content = db.TextProperty(required = True)
when = db.DateTimeProperty(auto_now_a... | How to render tags in Flask/GAE? | I am new to all these and trying to figure out how to make a simple blog post with tags.
Here are the relevant parts:
Model:
class Post(db.Model):
title = db.StringProperty(required = True)
content = db.TextProperty(required = True)
when = db.DateTimeProperty(auto_now_add = True)
author = db.UserPropert... | [
"I think you need to customize your own WTForm field instead of using TextField.\nThere are some sample code on wtforms document.\nhttp://wtforms.simplecodes.com/docs/0.6.1/fields.html#custom-fields\nclass TagListField(Field):\n widget = TextInput()\n\n def _value(self):\n if self.data:\n re... | [
3
] | [] | [] | [
"flask",
"google_app_engine",
"python",
"tags",
"wtforms"
] | stackoverflow_0008405093_flask_google_app_engine_python_tags_wtforms.txt |
Q:
Python: how to make a recursive generator function
I have been working on generating all possible submodels for a biological problem. I have a working recursion for generating a big list of all the submodels I want. However, the lists get unmanageably large pretty fast (N=12 is just possible in the example below, ... | Python: how to make a recursive generator function | I have been working on generating all possible submodels for a biological problem. I have a working recursion for generating a big list of all the submodels I want. However, the lists get unmanageably large pretty fast (N=12 is just possible in the example below, N>12 uses too much memory). So I wanted to convert it to... | [
"You should change this:\nsubmodel_generator(newpat, current+1, maxn)\n\nto this:\nfor b in submodel_generator(newpat, current+1, maxn):\n yield b\n\nThis will recursively yield the value from successive calls to the function.\n[Update]: Note that as of Python 3.3, you can use the new yield from syntax:\nyield f... | [
26
] | [] | [] | [
"generator",
"python",
"recursion"
] | stackoverflow_0008407760_generator_python_recursion.txt |
Q:
How to insert and format values cell by cell in an XLSX file using openpyxl
I am trying to write an XLSX file using the openpyxl module. I am using the append() method to insert the values row by row. But I want to insert the values cell by cell instead. I would also like to format the cell (font, colour, alignmen... | How to insert and format values cell by cell in an XLSX file using openpyxl | I am trying to write an XLSX file using the openpyxl module. I am using the append() method to insert the values row by row. But I want to insert the values cell by cell instead. I would also like to format the cell (font, colour, alignment etc). Please help me.
| [
"You can set all that cell by cell (if that is what you need) using openpyxl. Here is a small example which sets the value, name (named_range) and some style of cells in a workbook:\nfrom openpyxl.workbook import Workbook\nwb = Workbook()\ndest_filename = r'empty_book.xlsx'\nws = wb.worksheets[0] \n\nname = 'nam... | [
6
] | [] | [] | [
"excel",
"openpyxl",
"python",
"xlsx"
] | stackoverflow_0005829219_excel_openpyxl_python_xlsx.txt |
Q:
sqlalchemy mapper event issue
Ii defined the following classes in sqlalchemy:
class User(Base):
__tablename__ = 'user'
userId = Column(Integer, primary_key=True)
email = Column(String(60), unique=True,nullable=False)
userName = Column(Unicode(16),unique=True)
_password = Column('password', Unic... | sqlalchemy mapper event issue | Ii defined the following classes in sqlalchemy:
class User(Base):
__tablename__ = 'user'
userId = Column(Integer, primary_key=True)
email = Column(String(60), unique=True,nullable=False)
userName = Column(Unicode(16),unique=True)
_password = Column('password', Unicode(60))
groups = relationship(... | [
"As the extract from the before_insert documentation suggests:\n\nColumn-based attributes can be modified within this method which will\n result in the new value being inserted. However no changes to the\n overall flush plan can be made, and manipulation of the Session will\n not have the desired effect. To mani... | [
1
] | [] | [] | [
"python",
"sqlalchemy"
] | stackoverflow_0008401524_python_sqlalchemy.txt |
Q:
Fast performance array processing in Numpy/Python
I am trying to find out the optimal way (fastest performance) to process coordinate and measurement data stored in several numpy arrays.
I need to calculate the distance from each grid point (lot, lon, alt value in green in the attached image) to each measurement l... | Fast performance array processing in Numpy/Python | I am trying to find out the optimal way (fastest performance) to process coordinate and measurement data stored in several numpy arrays.
I need to calculate the distance from each grid point (lot, lon, alt value in green in the attached image) to each measurement location (lat, lon, alt, range from target in gray in th... | [
"I think the scipy.spatial.distance module will help you out with this problem: http://docs.scipy.org/doc/scipy/reference/spatial.distance.html\nYou should store your points as 2-d numpy arrays with 2 columns and N rows, where N is the number of points in the array. To convert your grid_lon and grid_lat to this for... | [
3
] | [] | [] | [
"arrays",
"grid",
"numpy",
"python"
] | stackoverflow_0008406107_arrays_grid_numpy_python.txt |
Q:
python natural comparison between strings?
Does Python have a fast function for doing a natural sort between two strings? Not sorting necessarily, just a comparison function that returns 0, -1 or 1 depending on which is ahead in natural order or same.
EDIT: the proposed function is correct but it is far too slo... | python natural comparison between strings? | Does Python have a fast function for doing a natural sort between two strings? Not sorting necessarily, just a comparison function that returns 0, -1 or 1 depending on which is ahead in natural order or same.
EDIT: the proposed function is correct but it is far too slow. How can this be done quickly in Python?
NOTE ... | [
"cmp is the built-in function to do just that.\n>>> a = 'hello'\n>>> b = 'world'\n>>> cmp(a, b)\n-1\n\nEDIT: with \"natural sort\" do you refer to sorting numbers as humans would do? If this is the case, than this is a possible recipe.\n",
"Adapted from the answer to this question: Does Python have a built in fun... | [
5,
5,
2
] | [] | [] | [
"python",
"sorting",
"unix"
] | stackoverflow_0008408125_python_sorting_unix.txt |
Q:
I don't understand tests in Django, Can you help me please?
I am having a hard time with tests in Django and Python, for my final project I am making a forums website, but I don't really have any idea how or what my tests should be. Here is the views page from mysite file. Could someone please walk me through wha... | I don't understand tests in Django, Can you help me please? | I am having a hard time with tests in Django and Python, for my final project I am making a forums website, but I don't really have any idea how or what my tests should be. Here is the views page from mysite file. Could someone please walk me through what I should test for besides if a user is logged in.
from django.c... | [
"First read the Django testing documentation. You might also want to read this book. It's dated in some areas, but testing is still pretty much the same now as it was in 1.1.\nIt's a bit much of a topic to cover in an SO answer.\n",
"Well, you could test:\n\nIf you have the right number of pages for the objects y... | [
3,
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0008408231_django_python.txt |
Q:
Getting the Tasks in a Google App Engine TaskQueue
I know you can view the currently queued and running tasks in the Dashboard or development server console. However, is there any way to get that list programmatically? The docs only describe how to add tasks to the queue, but not how to list and/or cancel them.
In... | Getting the Tasks in a Google App Engine TaskQueue | I know you can view the currently queued and running tasks in the Dashboard or development server console. However, is there any way to get that list programmatically? The docs only describe how to add tasks to the queue, but not how to list and/or cancel them.
In python please.
| [
"It sure doesn't look that way. Instead of removing the task, how about altering the task handler, whatever it is that handles the task url invokes, to check to see if the work specified still needs to be done, and just return 200 OK immediately if the task would be deleted.\nThis issue on google-code appears to r... | [
2,
1,
0
] | [] | [] | [
"dashboard",
"google_app_engine",
"python",
"task",
"task_queue"
] | stackoverflow_0004002514_dashboard_google_app_engine_python_task_task_queue.txt |
Q:
Is there a way to find an item in a tuple without using a for loop in Python?
I have a tuple of Control values and I want to find the one with a matching name. Right now I use this:
listView
for control in controls:
if control.name == "ListView":
listView = control
Can I do it simpler than this? Perha... | Is there a way to find an item in a tuple without using a for loop in Python? | I have a tuple of Control values and I want to find the one with a matching name. Right now I use this:
listView
for control in controls:
if control.name == "ListView":
listView = control
Can I do it simpler than this? Perhaps something like:
listView = controls.FirstOrDefault(c => c.name == "ListView")
| [
"Here is one option:\nlistView = next(c for c in controls if c.name == \"ListView\")\n\nNote that this will raise a StopIteration if no matching item exists, so you will need to put this in a try/except and replace it with a default if you get a StopIteration.\nAlternatively you can add your default value to the it... | [
6,
2,
1
] | [] | [] | [
"loops",
"python",
"tuples"
] | stackoverflow_0008408347_loops_python_tuples.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.