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:
Django: separate template dir for model
What's the point of using template structure like this:
templates/
app/
article_view.html # or view_article.html
category_view.html
vs
templates/
app/
article/
view.html
category/
view.html
It's easier to find... | Django: separate template dir for model | What's the point of using template structure like this:
templates/
app/
article_view.html # or view_article.html
category_view.html
vs
templates/
app/
article/
view.html
category/
view.html
It's easier to find particular template with second approach, bu... | [
"This depends on the scale of the project; a small-scale thingie could be more easy to handle with the first approach, while a project with several hundred template files could use a better folder structure, i.e. the second approach\n",
"Generally speaking, templates are associated with views rather than models. ... | [
1,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0003945233_django_python.txt |
Q:
The dateutil.parser.parse() of distance strings?
Anyone know a python package that's the dateutil of distance strings? It would be great if something was out there that worked something like the following:
>>> from awesome_dist_module import Distance
>>> d = Distance("100 ft")
>>> d.meters
30.48
>>> d = Distance(... | The dateutil.parser.parse() of distance strings? | Anyone know a python package that's the dateutil of distance strings? It would be great if something was out there that worked something like the following:
>>> from awesome_dist_module import Distance
>>> d = Distance("100 ft")
>>> d.meters
30.48
>>> d = Distance("100 feet")
>>> d.meters
30.48
>>> d.miles
0.018939393... | [
"I wrote this for you, but you can expand it as you like:\nclass Distance(object):\n\n METER = 1\n FOOT = 0.3048\n MILE = 1609.344\n INCH = 0.0254\n UNITS = {'meters': METER,\n 'mts': METER,\n 'mt': METER,\n 'feet': FOOT,\n 'foot': FOOT,\n 'ft': FOOT,\n ... | [
3,
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0003943752_python.txt |
Q:
Reading and interpreting data from a binary file in Python
I want to read a file byte by byte and check if the last bit of each byte is set:
#!/usr/bin/python
def main():
fh = open('/tmp/test.txt', 'rb')
try:
byte = fh.read(1)
while byte != "":
if (int(byte,16) & 0x01) is 0x01:... | Reading and interpreting data from a binary file in Python | I want to read a file byte by byte and check if the last bit of each byte is set:
#!/usr/bin/python
def main():
fh = open('/tmp/test.txt', 'rb')
try:
byte = fh.read(1)
while byte != "":
if (int(byte,16) & 0x01) is 0x01:
print 1
else:
print... | [
"Try using the bytearray type (Python 2.6 and later), it's much better suited to dealing with byte data. Your try block would be just:\nba = bytearray(fh.read())\nfor byte in ba:\n print byte & 1\n\nor to create a list of results:\nlow_bit_list = [byte & 1 for byte in bytearray(fh.read())]\n\nThis works because ... | [
51,
9,
4
] | [] | [] | [
"binary",
"bitwise_operators",
"python"
] | stackoverflow_0003943149_binary_bitwise_operators_python.txt |
Q:
Undefined variable from import when using wxPython in pydev
I just downloaded wxPython, and was running some of the sample programs from here. However, on every line that uses a variable from wx.*, I get a "Undefined variable from import error"
For example, the following program generates five errors on lines 1,4,... | Undefined variable from import when using wxPython in pydev | I just downloaded wxPython, and was running some of the sample programs from here. However, on every line that uses a variable from wx.*, I get a "Undefined variable from import error"
For example, the following program generates five errors on lines 1,4,8, and two on line 5:
import wx
class MyFrame(wx.Frame):
""" ... | [
"This happened to me. I had installed PyDev and configured it and went on my merry way. A few months later, I installed wxPython and had this same problem. An easy way to fix is in eclipse:\nWindow -> Preferences -> Pydev -> Interpreter - Python\nJust remove the default interpreter and add a new one (it can be t... | [
40,
7,
3,
3,
3,
3
] | [] | [] | [
"eclipse",
"pydev",
"python",
"wxpython"
] | stackoverflow_0002143549_eclipse_pydev_python_wxpython.txt |
Q:
Can't scroll to the end of TreeView PyGTK / GTK
When I try to scroll down to the end of my TreeView, which is inside a ScrolledWindow, it doesn't scroll where it should but one or two lines before.
I tried several methods and they all provide the same behavior :
self.wTree.get_widget("tree_last_log").scroll_to_cel... | Can't scroll to the end of TreeView PyGTK / GTK | When I try to scroll down to the end of my TreeView, which is inside a ScrolledWindow, it doesn't scroll where it should but one or two lines before.
I tried several methods and they all provide the same behavior :
self.wTree.get_widget("tree_last_log").scroll_to_cell((self.number_results-1,))
# or
self.wTree.get_widg... | [
"The C API docs may be helpful:\nhttp://library.gnome.org/devel/gtk/stable/GtkTreeView.html#gtk-tree-view-scroll-to-cell\nYou can see there are arguments there that would mess things up, depending on how pygtk defaults them. You might try specifying explicitly all the args.\nOne trick to TreeView and TextView is th... | [
1
] | [] | [] | [
"gtk",
"gtk2",
"pygtk",
"python"
] | stackoverflow_0003510705_gtk_gtk2_pygtk_python.txt |
Q:
What does this code do in Python?
I'm learning Python and ran into some code that has this line...
self.clear()
I am curious as to what it would do and why would someone need to do this?
A:
That line calls the clear method on the current object. What the clear method actually does depends on what class this cod... | What does this code do in Python? | I'm learning Python and ran into some code that has this line...
self.clear()
I am curious as to what it would do and why would someone need to do this?
| [
"That line calls the clear method on the current object. What the clear method actually does depends on what class this code is inside.\n",
"If you found it inside the function, that looked like:\ndef __parse(self,filename):\n\nthen you will probably find something similar to this:\ndef clear(self):\n\nIf you fin... | [
5,
1
] | [
"sorry if it wasnt clear but i just found the code for clear() ... all it did was clear the UserDict object before assigning new values to it....i misunderstood the code and thought the writer was actually deleting the current object....anyway answer found....thanks for the help guys....i will be more careful in th... | [
-1
] | [
"python"
] | stackoverflow_0003945554_python.txt |
Q:
Python - Iterate through 2 lists at the same time
Possible Duplicate:
How to iterate through two lists in parallel?
I have 2 lists:
l = ["a", "b", "c"]
m = ["x", "y", "z"]
And I want to iterate through both at the same time, something like this:
for e, f in l, m:
print e, f
Must show:
a x
b y
c z
The thin... | Python - Iterate through 2 lists at the same time |
Possible Duplicate:
How to iterate through two lists in parallel?
I have 2 lists:
l = ["a", "b", "c"]
m = ["x", "y", "z"]
And I want to iterate through both at the same time, something like this:
for e, f in l, m:
print e, f
Must show:
a x
b y
c z
The thing is that is totally illegal. How can I do something l... | [
"Look at itertools izip. It'll look like this\nfor i,j in izip( mylistA, mylistB ):\n print i + j\n\nThe zip function will also work but izip creates an iterator which does not force the creation of a third list.\n"
] | [
6
] | [] | [] | [
"list",
"loops",
"python"
] | stackoverflow_0003945809_list_loops_python.txt |
Q:
Searching a normal query in an inverted index
I have a full inverted index in form of nested python dictionary. Its structure is :
{word : { doc_name : [location_list] } }
For example let the dictionary be called index, then for a word " spam ", entry would look like :
{ spam : { doc1.txt : [102,300,399], ... | Searching a normal query in an inverted index | I have a full inverted index in form of nested python dictionary. Its structure is :
{word : { doc_name : [location_list] } }
For example let the dictionary be called index, then for a word " spam ", entry would look like :
{ spam : { doc1.txt : [102,300,399], doc5.txt : [200,587] } }
so that, the documents con... | [
"Here's a start:\ndoc_has_word = [ (index[word].keys(),word) for word in wordlist ]\n\nThis will build an list of (word,document) pairs. You can't easily make a dictionary out of that, since each document occurs many times.\nBut\nfrom collections import defaultdict\ndoc_words = defaultdict(list)\nfor d, w in doc_h... | [
3,
0,
0
] | [] | [] | [
"information_retrieval",
"inverted_index",
"python"
] | stackoverflow_0003944910_information_retrieval_inverted_index_python.txt |
Q:
Passing self into a constructor in python
I recently was working on a little python project and came to a situation where I wanted to pass self into the constructor of another object. I'm not sure why, but I had to look up whether this was legal in python. I've done this many times in C++ and Java but I don't reme... | Passing self into a constructor in python | I recently was working on a little python project and came to a situation where I wanted to pass self into the constructor of another object. I'm not sure why, but I had to look up whether this was legal in python. I've done this many times in C++ and Java but I don't remember ever having to do this with python.
Is pas... | [
"Yes it is legal, and yes it is pythonic.\nI find myself using this pattern when you have an object and a container object where the contained objects need to know about their parent.\n",
"Just pass it like a parameter. Of course, it won't be called self in the other initializer...\nclass A:\n def __init__(se... | [
18,
4
] | [] | [] | [
"python",
"self",
"this"
] | stackoverflow_0003945924_python_self_this.txt |
Q:
Encoding JSON in Mako?
Im having trouble with json in mako. I do this:
${ to_json( dict( a = 1, b = 2 ) ) }
where to_json is:
<%!
import simplejson as json
def to_json( d ):
return json.dumps( d )
%>
however, instead of giving me
{"a": "1", "b": "2"}
its giving me
{"a": 1, "b&qu... | Encoding JSON in Mako? | Im having trouble with json in mako. I do this:
${ to_json( dict( a = 1, b = 2 ) ) }
where to_json is:
<%!
import simplejson as json
def to_json( d ):
return json.dumps( d )
%>
however, instead of giving me
{"a": "1", "b": "2"}
its giving me
{"a": 1, "b": 2}
so mako changes the... | [
"seems like theres an auto filter somewhere, so when i changed \n${ to_json( dict( a = 1, b = 2 ) ) }\n\nto\n${ to_json( dict( a = 1, b = 2 ) ) | n }\n\nto turn off filters, it is okay, thanks\n"
] | [
2
] | [] | [] | [
"json",
"mako",
"python"
] | stackoverflow_0003945820_json_mako_python.txt |
Q:
Converting string to tuple and adding to tuple
I have a config file like this.
[rects]
rect1=(2,2,10,10)
rect2=(12,8,2,10)
I need to loop through the values and convert them to tuples.
I then need to make a tuple of the tuples like
((2,2,10,10), (12,8,2,10))
A:
Instead of using a regex or int/string functions, ... | Converting string to tuple and adding to tuple | I have a config file like this.
[rects]
rect1=(2,2,10,10)
rect2=(12,8,2,10)
I need to loop through the values and convert them to tuples.
I then need to make a tuple of the tuples like
((2,2,10,10), (12,8,2,10))
| [
"Instead of using a regex or int/string functions, you could also use the ast module's literal_eval function, which only evaluates strings that are valid Python literals. This function is safe (according to the docs).\nhttp://docs.python.org/library/ast.html#ast.literal_eval\nimport ast\nast.literal_eval(\"(1,2,3,4... | [
11,
9,
3,
2,
2
] | [] | [] | [
"python",
"string",
"tuples"
] | stackoverflow_0003945856_python_string_tuples.txt |
Q:
How do I update an instance of a Django Model with request.POST if POST is a nested array?
I have a form that submits the following data:
question[priority] = "3"
question[effort] = "5"
question[question] = "A question"
That data is submitted to the URL /questions/1/save where 1 is the question.id. What I'd love ... | How do I update an instance of a Django Model with request.POST if POST is a nested array? | I have a form that submits the following data:
question[priority] = "3"
question[effort] = "5"
question[question] = "A question"
That data is submitted to the URL /questions/1/save where 1 is the question.id. What I'd love to do is get question #1 and update it based on the POST data. I've got some of it working, but ... | [
"You can use a ModelForm to accomplish this. First define the ModelForm:\nfrom django import forms\n\nclass QuestionForm(forms.ModelForm):\n class Meta:\n model = Question\n\nThen, in your view:\nquestion = Question.objects.get(pk=id)\nif request.method == 'POST':\n form = QuestionForm(request.POST, i... | [
43
] | [] | [] | [
"django",
"django_models",
"post",
"python",
"request"
] | stackoverflow_0003946036_django_django_models_post_python_request.txt |
Q:
What are the implications of using mutable types as default arguments in Python?
Possible Duplicates:
Why the “mutable default argument fix” syntax is so ugly, asks python newbie
least astonishment in python: the mutable default argument
Here is an example.
def list_as_default(arg = []):
pass
A:
From: http... | What are the implications of using mutable types as default arguments in Python? |
Possible Duplicates:
Why the “mutable default argument fix” syntax is so ugly, asks python newbie
least astonishment in python: the mutable default argument
Here is an example.
def list_as_default(arg = []):
pass
| [
"From: http://www.network-theory.co.uk/docs/pytut/DefaultArgumentValues.html\nThe default value is evaluated only once. This makes a difference when the default is a mutable object such as a list, dictionary, or instances of most classes. For example, the following function accumulates the arguments passed to it on... | [
2
] | [] | [] | [
"least_astonishment",
"python"
] | stackoverflow_0003946235_least_astonishment_python.txt |
Q:
A little help needed in code translation (Python to C#)
Good night everyone,
This question leaves me a little embarassed because, of couse, I know I should be able to get the answer alone. However, my knowledge about Python is just a little bit more than nothing, so I need help from someone more experienced with i... | A little help needed in code translation (Python to C#) | Good night everyone,
This question leaves me a little embarassed because, of couse, I know I should be able to get the answer alone. However, my knowledge about Python is just a little bit more than nothing, so I need help from someone more experienced with it than me...
The following code comes from Norvig's "Natural ... | [
"Let's tackle the first function first:\ndef segment(text): \n \"Return a list of words that is the best segmentation of text.\" \n if not text: return [] \n candidates = ([first]+segment(rem) for first,rem in splits(text)) \n return max(candidates, key=Pwords) \n\nIt takes a word and returns the most l... | [
2,
1
] | [] | [] | [
"c#",
"python"
] | stackoverflow_0003946265_c#_python.txt |
Q:
Matplotlib how to draw on figure on PIL image
I've got a new problem here, I wish to inputs a PIL image object, and then draw the figure that generated from matplotlib, and then return the PIL image object. How could I achieve this?
A:
Why don't you create the image in matplotlib, save it and then import it into... | Matplotlib how to draw on figure on PIL image | I've got a new problem here, I wish to inputs a PIL image object, and then draw the figure that generated from matplotlib, and then return the PIL image object. How could I achieve this?
| [
"Why don't you create the image in matplotlib, save it and then import it into pil?\nxdata = pylab.arange(1961, 2031, 1)\npylab.figure(num=None, figsize=(20.48, 10.24), dpi=100, facecolor='w', edgecolor='k')\npylab.plot(xdata, ydata, linewidth=3.0)\npylab.xlabel(xlabel)\npylab.ylabel(ylabel)\npylab.title(title)\npy... | [
3
] | [] | [] | [
"matplotlib",
"python",
"python_imaging_library"
] | stackoverflow_0003939217_matplotlib_python_python_imaging_library.txt |
Q:
Appengine - Can a user import Yaml or Json file to update datastore with new values?
Imagine this scenario:
I made a small application in Python for Google App Engine for general use.
Users can login to my app, update their profile, change address and change the picture among many other things.
A user can expor... | Appengine - Can a user import Yaml or Json file to update datastore with new values? | Imagine this scenario:
I made a small application in Python for Google App Engine for general use.
Users can login to my app, update their profile, change address and change the picture among many other things.
A user can export the models to PDF, YAML and JSON, save the file on his computer.
You can download any ... | [
"Yes. Your users will be able to upload data in any file type your application can process. You will, of course, need to write handlers to process the files and perform the updates.\nThere are also some size restrictions with uploading, downloading, and processing data. You will want to keep those in mind.\n"
] | [
1
] | [] | [] | [
"google_app_engine",
"google_cloud_datastore",
"python"
] | stackoverflow_0003946401_google_app_engine_google_cloud_datastore_python.txt |
Q:
Function declaration in python to have a readable and clean code?
Is it possible to declare functions in python and define them later or in a separate file?
I have some code like:
class tata:
def method1(self):
def func1():
# This local function will be only used in method1, so there is no use t... | Function declaration in python to have a readable and clean code? | Is it possible to declare functions in python and define them later or in a separate file?
I have some code like:
class tata:
def method1(self):
def func1():
# This local function will be only used in method1, so there is no use to
# define it outside.
# Some code for func1.
... | [
"Sure, no problem:\nfoo.py:\ndef func1():\n pass\n\nscript.py:\nimport foo\nclass tata:\n def method1(self):\n func1=foo.func1\n\n",
"I think what you want is to import the function within method1, e.g.\ndef method1(...):\n from module_where_func1_is_defined import func1\n # do stuff\n somethin... | [
6,
3,
2,
2,
0
] | [] | [] | [
"declaration",
"python",
"syntax"
] | stackoverflow_0003946628_declaration_python_syntax.txt |
Q:
Randomise order of if-else execution in Python
This might sound like a strange question, but bear with me...
I have a dictionary in Python with values like so:
'B': 23.6
'D': 0.6
'F': 35.9
'H': 35.9
I need to do an if-else with these values to do different things depending which one is > 30. The code I have at th... | Randomise order of if-else execution in Python | This might sound like a strange question, but bear with me...
I have a dictionary in Python with values like so:
'B': 23.6
'D': 0.6
'F': 35.9
'H': 35.9
I need to do an if-else with these values to do different things depending which one is > 30. The code I have at the moment is along the lines of:
if angles['B'] > 30:... | [
"You can make a sequence of key/value pairs:\npairs = angles.iteritems()\n\nFilter it to remove elements <= 30:\nfiltered = [(name, value) for name, value in pairs if value > 30]\n\ncheck to see if there are any options\nif filtered:\n\nand then pick one:\n from random import choice\n name, value = choice(fil... | [
11,
2,
1,
1
] | [] | [] | [
"python",
"random"
] | stackoverflow_0003946488_python_random.txt |
Q:
What to consider before subclassing list?
I was recently going over a coding problem I was having and someone looking at the code said that subclassing list was bad (my problem was unrelated to that class). He said that you shouldn't do it and that it came with a bunch of bad side effects. Is this true?
I'm asking... | What to consider before subclassing list? | I was recently going over a coding problem I was having and someone looking at the code said that subclassing list was bad (my problem was unrelated to that class). He said that you shouldn't do it and that it came with a bunch of bad side effects. Is this true?
I'm asking if list is generally bad to subclass and if so... | [
"The abstract base classes provided in the collections module, particularly MutableSequence, can be useful when implementing list-like classes. These are available in Python 2.6 and later.\nWith ABCs you can implement the \"core\" functionality of your class and it will provide the methods which logically depend o... | [
18,
15,
11,
6
] | [] | [] | [
"list",
"python",
"subclassing"
] | stackoverflow_0003945940_list_python_subclassing.txt |
Q:
Append element with SAX in python
I know how to parse xml with sax in python, but how would I go about inserting elements into the document i'm parsing? Do I have to create a separate file?
Could someone provide a simple example or alter the one I've put below. Thanks.
from xml.sax.handler import ContentHandler
... | Append element with SAX in python | I know how to parse xml with sax in python, but how would I go about inserting elements into the document i'm parsing? Do I have to create a separate file?
Could someone provide a simple example or alter the one I've put below. Thanks.
from xml.sax.handler import ContentHandler
from xml.sax import make_parser
import ... | [
"With DOM, you have the entire xml structure in memory.\nWith SAX, you don't have a DOM available, so you don't have anything to append an element to.\nThe main reason for using SAX is if the xml structure is really, really huge-- if it would be a serious performance hit to place the DOM in memory. If that isn't th... | [
0
] | [] | [] | [
"python",
"sax",
"xml"
] | stackoverflow_0003946743_python_sax_xml.txt |
Q:
Running a Python program on a web server
I have a Python script which accepts a XML file as input and then processes it and creates another file.
Now the way I have to run this program in terminal (mac) is:
ttx myfile.xml
And it does the job.
Now I am trying to install this program on a web server.
I have all th... | Running a Python program on a web server | I have a Python script which accepts a XML file as input and then processes it and creates another file.
Now the way I have to run this program in terminal (mac) is:
ttx myfile.xml
And it does the job.
Now I am trying to install this program on a web server.
I have all the necessary files installed as Modules und... | [
"Passing the data would be easiest with HTTP POST. As to integrating Python script w/ Apache, the way I know would be to create a simple Django app to wrap the main Python function in your script, but I believe there must be some more direct way.\n",
"There is a \"minimal http-upload cgi-script\"-recipe, which ca... | [
0,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0003247591_python.txt |
Q:
How to make NSLog work with Python's logging module when using PyObjC?
I'm writing a Django-based webapp that imports a Cocoa framework via PyObjC. The Cocoa framework has NSLog() littered all through it and while I can see them when running the Django server in non-daemon mode, as soon as I go to daemon I simply... | How to make NSLog work with Python's logging module when using PyObjC? | I'm writing a Django-based webapp that imports a Cocoa framework via PyObjC. The Cocoa framework has NSLog() littered all through it and while I can see them when running the Django server in non-daemon mode, as soon as I go to daemon I simply lose all this useful NSLog() output.
Is there any easy way to get NSLog stu... | [
"According to this page, NSLog basically works like\nfprintf(stderr, format_string, args ...);\n\nso you do need to capture / redirect the standard error output. I wrote a post some time ago which might help for Python-only programs, but I would guess that the Cocoa code accesses the process-level file descriptor 2... | [
3
] | [] | [] | [
"django",
"logging",
"nslog",
"pyobjc",
"python"
] | stackoverflow_0003910541_django_logging_nslog_pyobjc_python.txt |
Q:
Setting up a python screen scraper that could work on Google App engine
I am looking to setup a automated screen scraper that will run on Google app engine using python. I want it to scrape the site and put the specified results into a Entity in app engine. I am looking for some directions on what to use. I have s... | Setting up a python screen scraper that could work on Google App engine | I am looking to setup a automated screen scraper that will run on Google app engine using python. I want it to scrape the site and put the specified results into a Entity in app engine. I am looking for some directions on what to use. I have seen beautifulsoup but wonder if people could recommend anything else that cou... | [
"Beautifulsoup runs fine on App Engine (just make sure to use 3.0.8, not the iffy 3.1.0). The main alternative, I think, would be html5lib -- I haven't tries it on App Engine but I believe it does run there (quite slowly -- if that's a problem I think you need to stick with BeautifulSoup), e.g. this service runs on... | [
4,
1,
0,
0
] | [] | [] | [
"google_app_engine",
"python",
"screen_scraping"
] | stackoverflow_0002406082_google_app_engine_python_screen_scraping.txt |
Q:
Getting the entire output from subprocess.Popen
I'm getting a slightly weird result from calling subprocess.Popen that I suspect has a lot to do with me being brand-new to Python.
args = [ 'cscript', '%USERPROFILE%\\tools\\jslint.js','%USERPROFILE%\\tools\\jslint.js' ]
p = Popen(args, stdout=PIPE, shell=True).comm... | Getting the entire output from subprocess.Popen | I'm getting a slightly weird result from calling subprocess.Popen that I suspect has a lot to do with me being brand-new to Python.
args = [ 'cscript', '%USERPROFILE%\\tools\\jslint.js','%USERPROFILE%\\tools\\jslint.js' ]
p = Popen(args, stdout=PIPE, shell=True).communicate()[0]
Results in output like the following (t... | [
"Is it going to stderr? Try redirecting:\np = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True).communicate()[0]\n\n",
"It's probably going to stderr, as SimonJ suggested.\nAlso, the docs say not to use shell=True in Windows for your case:\n\nThe executable argument specifies th... | [
7,
3
] | [] | [] | [
"python",
"stdout",
"subprocess"
] | stackoverflow_0003947191_python_stdout_subprocess.txt |
Q:
List of substrings
I have big string, it can have a few thousands lines. I would like to to get all sub-strings like: [tag] here can be everything [/tag] in a list.
How can I do this? My regex is not working (or I'm doing something wrong).
A:
The function find_all_tags returns a list of all occurences of tag t... | List of substrings | I have big string, it can have a few thousands lines. I would like to to get all sub-strings like: [tag] here can be everything [/tag] in a list.
How can I do this? My regex is not working (or I'm doing something wrong).
| [
"The function find_all_tags returns a list of all occurences of tag tag in text:\nimport re\ndef find_all_tags(text, tag):\n return re.findall(r\"(?s)\\[\" + tag + r\"\\].*?\\[/\" + tag + r\"\\]\", text)\n\n>>> text=\"\"\"this is [b]bold text[/b] and some[b]\nthat spans a line[/b] some [i]italics[/i] and some\n[... | [
0,
0
] | [] | [] | [
"list",
"python",
"regex",
"string",
"tags"
] | stackoverflow_0003944856_list_python_regex_string_tags.txt |
Q:
Call a function in a module after setup.py installation
I've got a program/joke that needs a reasonably large data structure to operate, (a dictionary that takes a few seconds to construct) and I would like to create and pickle it into the installation dir when running python setup.py install.
setup() in distutils... | Call a function in a module after setup.py installation | I've got a program/joke that needs a reasonably large data structure to operate, (a dictionary that takes a few seconds to construct) and I would like to create and pickle it into the installation dir when running python setup.py install.
setup() in distutils.core looks like it shouldn't exit, so I thought that I could... | [
"I created a dummy setup.py as:\nfrom distutils.core import setup\nsetup()\nprint 'after'\n\nand my print statement prints just fine after running python setup.py install.\nI tried an invalid command like python setup.py xx, and the after print didn't get called.\nAre you sure it didn't raise an Exception or System... | [
1
] | [] | [] | [
"distutils",
"python",
"setup.py"
] | stackoverflow_0003947041_distutils_python_setup.py.txt |
Q:
First Python Tkinter window works, but the rest are blank
I think I'm missing something basic about Tkinter.
What would be the correct way to create several windows with the same hidden root window? I can get one window to open, but once it's closed subsequent ones show up blank, without any widgets in them. I've ... | First Python Tkinter window works, but the rest are blank | I think I'm missing something basic about Tkinter.
What would be the correct way to create several windows with the same hidden root window? I can get one window to open, but once it's closed subsequent ones show up blank, without any widgets in them. I've also noticed if I leave the root window visible, it disappears ... | [
"Your question is too vague to know for certain what the problem is. Rest assured, when you use it right it's quite easy to create multiple windows, and to hide and show them at will.\nYou ask what the correct way to create multiple windows is; the answer to that is to call Toplevel() for each window, nothing more,... | [
3
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0003945585_python_tkinter.txt |
Q:
Recursive directory list/analyze function doesn't seem to recurse right
I wrote what I thought was a straightforward Python script to traverse a given directory and tabulate all the file suffixes it finds. The output looks like this:
OTUS-ASIO:face fish$ sufs
>>> /Users/fish/Dropbox/ost2/face (total 194)
... | Recursive directory list/analyze function doesn't seem to recurse right | I wrote what I thought was a straightforward Python script to traverse a given directory and tabulate all the file suffixes it finds. The output looks like this:
OTUS-ASIO:face fish$ sufs
>>> /Users/fish/Dropbox/ost2/face (total 194)
=== 1 1 -
=== css 16 ... | [
"Yeah, Won't you be better off if you used os.walk\nfor root, dirs, files in os.walk(basedir):\n ... do you stuff ..\n\nSee the example at \n\nhttp://docs.python.org/library/os.html\n\nAlso look at os.path.splitext(path), a finer way to find the type of your file.\n>>> os.path.splitext('/d/c/as.jpeg')\n('/d/c/as... | [
3,
1
] | [] | [] | [
"command_line",
"directory_structure",
"filesystems",
"python",
"recursion"
] | stackoverflow_0003946439_command_line_directory_structure_filesystems_python_recursion.txt |
Q:
Sorting csv columns in bash, reading bash output into python variables
Hi I have a ton of data in multiple csv files and filter out a data set using grep:
user@machine:~/$ cat data.csv | grep -a "63[789]\...;"
637.05;1450.2
637.32;1448.7
637.60;1447.7
637.87;1451.5
638.14;1454.2
638.41;1448.6
638.69;1445.8
638.96;... | Sorting csv columns in bash, reading bash output into python variables | Hi I have a ton of data in multiple csv files and filter out a data set using grep:
user@machine:~/$ cat data.csv | grep -a "63[789]\...;"
637.05;1450.2
637.32;1448.7
637.60;1447.7
637.87;1451.5
638.14;1454.2
638.41;1448.6
638.69;1445.8
638.96;1440.0
639.23;1431.9
639.50;1428.8
639.77;1427.3
I want to figure out the d... | [
"A quick one-liner would be:\ngrep -a \"63[789]\\...;\" data.csv | sort -n -r -t ';' -k 2 | head --lines=1\n\nThis simply sorts the file numerically based on the second column and then prints out the first row. Hope that helps.\n",
"If you are going to use Python, then use Python. Why are you intermixing bash com... | [
6,
3,
1,
1,
1,
0,
0
] | [] | [] | [
"bash",
"python",
"shell"
] | stackoverflow_0003946898_bash_python_shell.txt |
Q:
Change Form Validation for Admin Login in Django
I use a custom auth backend in my django application that allows users to login with ther emails.
But when I try to login in the admin I get the message: "usernames cant contain the '@' char"
I suppose this error is raised before it reaches the auth backend, so its... | Change Form Validation for Admin Login in Django | I use a custom auth backend in my django application that allows users to login with ther emails.
But when I try to login in the admin I get the message: "usernames cant contain the '@' char"
I suppose this error is raised before it reaches the auth backend, so its a form issue, right ?
| [
"Unfortunately no, this error is raised just if the authentication fails and there is no User with the given email. The bad thing is that this validation is hard-coded [1].\nThere is an open ticket for this [2].\nSince version 1.2 django allows emails as User.username, if you're using this version maybe you won't e... | [
1
] | [] | [] | [
"django",
"django_admin",
"django_forms",
"python"
] | stackoverflow_0003947102_django_django_admin_django_forms_python.txt |
Q:
Splitting a long tuple into smaller tuples
I have a long tuple like
(2, 2, 10, 10, 344, 344, 45, 43, 2, 2, 10, 10, 12, 8, 2, 10)
and i am trying to split it into a tuple of tuples like
((2, 2, 10, 10), (344, 344, 45, 43), (2, 2, 10, 10), (12, 8, 2, 10))
I am new to python and am not very good with tuples o(2, 2,... | Splitting a long tuple into smaller tuples | I have a long tuple like
(2, 2, 10, 10, 344, 344, 45, 43, 2, 2, 10, 10, 12, 8, 2, 10)
and i am trying to split it into a tuple of tuples like
((2, 2, 10, 10), (344, 344, 45, 43), (2, 2, 10, 10), (12, 8, 2, 10))
I am new to python and am not very good with tuples o(2, 2, 10, 10, 344, 344, 45, 43, 2, 2, 10, 10, 12, 8, ... | [
"Well there is a certain idiom for that:\ndef grouper(n, iterable):\n args = [iter(iterable)] * n\n return zip(*args)\n\nt = (2, 2, 10, 10, 344, 344, 45, 43, 2, 2, 10, 10, 12, 8, 2, 10)\nprint grouper(4, t)\n\nBut its kind of complicated to explain. A slightly more general version of this is listed in the ite... | [
10,
4,
0,
0
] | [] | [] | [
"list",
"python",
"split",
"tuples"
] | stackoverflow_0003947337_list_python_split_tuples.txt |
Q:
How to develop and then parse a data structure
I'm designing a weather program where I need to keep track of certain things and allow the user to add data which will be saved and subsequently read later. My fields are
City
State
Zip
Metar
I might have more I want to do with this configuration file later, so I woul... | How to develop and then parse a data structure | I'm designing a weather program where I need to keep track of certain things and allow the user to add data which will be saved and subsequently read later. My fields are
City
State
Zip
Metar
I might have more I want to do with this configuration file later, so I would like it to have something like this:
[LOCATIONS]
P... | [
"To store data, you may use XML. Then read it off using any XML parser, SAX or DOM which are included with python. \nSince the size of data is very less (only around 20-25 entries per user), you can take the approach of first knowing about the search term, whether its state name or whether its pin code etc. (Ask us... | [
2,
1,
0,
0,
0
] | [] | [] | [
"data_structures",
"file_io",
"parsing",
"python"
] | stackoverflow_0003920681_data_structures_file_io_parsing_python.txt |
Q:
Python - removing items from lists
# I have 3 lists:
L1 = [1, 2, 3, 4, 5, 6, 7, 8, 9]
L2 = [4, 7, 8]
L3 = [5, 2, 9]
# I want to create another that is L1 minus L2's memebers and L3's memebers, so:
L4 = (L1 - L2) - L3 # Of course this isn't going to work
I'm wondering, what is the "correct" way to do this. I can ... | Python - removing items from lists | # I have 3 lists:
L1 = [1, 2, 3, 4, 5, 6, 7, 8, 9]
L2 = [4, 7, 8]
L3 = [5, 2, 9]
# I want to create another that is L1 minus L2's memebers and L3's memebers, so:
L4 = (L1 - L2) - L3 # Of course this isn't going to work
I'm wondering, what is the "correct" way to do this. I can do it many different ways, but Python's ... | [
"Here are some tries:\nL4 = [ n for n in L1 if (n not in L2) and (n not in L3) ] # parens for clarity\n\ntmpset = set( L2 + L3 )\nL4 = [ n for n in L1 if n not in tmpset ]\n\nNow that I have had a moment to think, I realize that the L2 + L3 thing creates a temporary list that immediately gets thrown away. So an e... | [
10,
6,
0,
0,
0,
0
] | [] | [] | [
"list_comprehension",
"python"
] | stackoverflow_0003947654_list_comprehension_python.txt |
Q:
How to parse e.g. 2010-04-24T07:47:00.007+02:00 with Python strptime
Does anyone know how to parse the format as described in the title using Pythons strptime method?
I have something similar to this:
import datetime
date = datetime.datetime.strptime(entry.published.text, '%Y-%m-%dT%H:%M:%S.Z')
I can't seem t... | How to parse e.g. 2010-04-24T07:47:00.007+02:00 with Python strptime | Does anyone know how to parse the format as described in the title using Pythons strptime method?
I have something similar to this:
import datetime
date = datetime.datetime.strptime(entry.published.text, '%Y-%m-%dT%H:%M:%S.Z')
I can't seem to figure out what kind of timeformat this is. By the way, I'm a newbie at ... | [
"That date is in ISO 8601, or more specifically RFC 3339, format.\nSuch dates can't be parsed with strptime. There's a Python issue that discusses this.\ndateutil.parser.parse can handle a wide variety of dates, including the one in your example.\nIf you're using an external module for XML or RSS parsing, there is... | [
5,
0,
0
] | [
"That's the standard XML datetime format, ISO 8601. If you're already using an XML library, most of them have datetime parsers built in. xml.utils.iso8601 works reasonably well.\nimport xml.utils.iso8601\ndate = xml.utils.iso8601.parse(entry.published.text)\n\nYou can look at a bunch of other ways to deal with that... | [
-1
] | [
"date",
"python",
"rfc3339",
"strptime"
] | stackoverflow_0003946689_date_python_rfc3339_strptime.txt |
Q:
how to find out whether website is using cookies or http based authentication
I am trying to automate files download via a webserver. I plan on using wget or curl or python urllib / urllib2.
Most solutions use wget and urllib and urllib2. They all talk of HHTP based authentication and cookie based authentication.... | how to find out whether website is using cookies or http based authentication | I am trying to automate files download via a webserver. I plan on using wget or curl or python urllib / urllib2.
Most solutions use wget and urllib and urllib2. They all talk of HHTP based authentication and cookie based authentication. My problem is I dont know which one is used in the website that stores my data.
He... | [
"If you log in using a Web page, the site is probably using cookie-based authentication. (It could technically use HTTP basic auth, by embedding your credentials in the URI, but this would be a dumb thing to do in most cases.) If you get a separate, smallish dialog with a user name and password field (like this one... | [
2,
1,
0
] | [] | [] | [
"cgi",
"python",
"session_cookies",
"urllib2",
"wget"
] | stackoverflow_0003944624_cgi_python_session_cookies_urllib2_wget.txt |
Q:
Get the coords and height/width of a svg group into python
Hi I want to load the groups of a svg-file into several gtk pixbuffs/subpixbufs
therefore I need the coordinates and width and height of them
I'm currently just using rsvg and gtk
is it possible to get those information with that modules ? Or do I need an... | Get the coords and height/width of a svg group into python | Hi I want to load the groups of a svg-file into several gtk pixbuffs/subpixbufs
therefore I need the coordinates and width and height of them
I'm currently just using rsvg and gtk
is it possible to get those information with that modules ? Or do I need another module to read out that data from the svg-file?
thanks alo... | [
"I found out to simply use RSVG::Handle::get_dimensions_sub(id)\n"
] | [
1
] | [] | [] | [
"gtk",
"python",
"rsvg",
"svg"
] | stackoverflow_0003268600_gtk_python_rsvg_svg.txt |
Q:
What is the correct way to form MySQL queries in python?
I am new to python, I come here from the land of PHP. I constructed a SQL query like this in python based on my PHP knowledge and I get warnings and errors
cursor_.execute("update posts set comment_count = comment_count + "+str(cursor_.rowcount)+" where ID =... | What is the correct way to form MySQL queries in python? | I am new to python, I come here from the land of PHP. I constructed a SQL query like this in python based on my PHP knowledge and I get warnings and errors
cursor_.execute("update posts set comment_count = comment_count + "+str(cursor_.rowcount)+" where ID = " + str(postid))
# rowcount here is int
What is the right wa... | [
"First of all, it's high time to learn to pass variables to the queries safely, using the method Matus expressed. Clearer,\ntuple = (foovar, barvar)\ncursor.execute(\"QUERY WHERE foo = ? AND bar = ?\", tuple)\n\nIf you only need to pass one variable, you must still make it a tuple: insert comma at the end to tell P... | [
3,
2
] | [] | [] | [
"mysql",
"python",
"sql"
] | stackoverflow_0003948309_mysql_python_sql.txt |
Q:
Pythonic equivalent of ./foo.py < bar.png
I've got a Python program that reads from sys.stdin, so I can call it with ./foo.py < bar.png. How do I test this code from within another Python module? That is, how do I set stdin to point to the contents of a file while running the test script? I don't want to do someth... | Pythonic equivalent of ./foo.py < bar.png | I've got a Python program that reads from sys.stdin, so I can call it with ./foo.py < bar.png. How do I test this code from within another Python module? That is, how do I set stdin to point to the contents of a file while running the test script? I don't want to do something like ./test.py < test.png. I don't think I ... | [
"You should generalise your script so that it can be invoked from the test script, in addition to being used as a standalone program. Here's an example script that does this:\n#! /usr/bin/python\n\nimport sys\n\ndef read_input_from(file):\n print file.read(),\n\nif __name__ == \"__main__\":\n if len(sys.argv)... | [
3,
2,
1,
0
] | [] | [] | [
"python",
"unit_testing"
] | stackoverflow_0003948247_python_unit_testing.txt |
Q:
Python. Transform str('+') to mathematical operation
How transform str('+') to mathematical operation?
For example:
a = [0,1,2] # or a = ['0','1','2']
b = ['+','-','*']
c = int(a[0]+b[0]+a[1])
In other words, how transform str('-1*2') to int(), without for i in c: if i == '+': ...
Thanks.
A:
You can also use th... | Python. Transform str('+') to mathematical operation | How transform str('+') to mathematical operation?
For example:
a = [0,1,2] # or a = ['0','1','2']
b = ['+','-','*']
c = int(a[0]+b[0]+a[1])
In other words, how transform str('-1*2') to int(), without for i in c: if i == '+': ...
Thanks.
| [
"You can also use the operator module:\nimport operator as op\n#Create a mapping between the string and the operator:\nops = {'+': op.add, '-': op.sub, '*': op.mul}\n\na = [0,1,2]\nb = ['+','-','*']\n\n#use the mapping\nc = ops[b[0]](a[0], a[1])\n\n",
"i thin you're looking for eval(), but i advice to use somethi... | [
4,
2,
2,
1,
1,
0,
0
] | [] | [] | [
"eval",
"python"
] | stackoverflow_0003948244_eval_python.txt |
Q:
Python unittests almost never check types
I was going through a few tests written in Java using JUnit and I could'nt help noticing the emphasis which is laid on checking the "type" of objects. This is something I have never seen in Python test-suites.
Java being statically-typed and Python being dynamically-typed,... | Python unittests almost never check types | I was going through a few tests written in Java using JUnit and I could'nt help noticing the emphasis which is laid on checking the "type" of objects. This is something I have never seen in Python test-suites.
Java being statically-typed and Python being dynamically-typed, should'nt the reverse be the case?
| [
"In dynamically-typed languages, developers often follow the duck typing principle -- \"if it looks like a duck and walks like a duck, it is a duck\". As long as the object does what all the tests require, does it really matter what kind of object it is? Duck typing says no.\n",
"Python unit tests do check type... | [
15,
5,
0
] | [] | [] | [
"java",
"python",
"unit_testing"
] | stackoverflow_0003943808_java_python_unit_testing.txt |
Q:
How do libraries in different programming languages handle Date & Time, Timestamps & Durations, Leapseconds & -years, DSTs & Timezones, ...?
Is there a standard body or a specific normative way how time-related things should be implemented in practice (like ICU for Unicode-related tasks) or is this currently a "be... | How do libraries in different programming languages handle Date & Time, Timestamps & Durations, Leapseconds & -years, DSTs & Timezones, ...? | Is there a standard body or a specific normative way how time-related things should be implemented in practice (like ICU for Unicode-related tasks) or is this currently a "best-effort", depending on how much effort, time and money language and library implementers want to spend?
Is there a specific and complete impleme... | [
"I'll try to give an answer to the second and third question using the Java library which might become part of Java 7.\njavax.time.* (JSR 310)\nThese classes are a complete rewrite of JodaTime trying to fix the design flaws of util.Date/util.Time as well as JodaTime.\nJSR 310 tries to provide a comprehensive model ... | [
17,
11,
11,
7,
4,
4
] | [] | [] | [
"c#",
"date",
"language_agnostic",
"python",
"time"
] | stackoverflow_0003709870_c#_date_language_agnostic_python_time.txt |
Q:
Python replacement for PHP's header
How to send a raw http header in python just like header() in PHP ?
A:
Pass a list of two-tuples containing the header name and header value to the start_response() function.
A:
In Django, you'd be like:
def someview(request):
# ... etc ...
out = HttpResponse(outputs... | Python replacement for PHP's header | How to send a raw http header in python just like header() in PHP ?
| [
"Pass a list of two-tuples containing the header name and header value to the start_response() function.\n",
"In Django, you'd be like:\ndef someview(request):\n # ... etc ...\n out = HttpResponse(outputstring,\n mimetype=\"text/html\",\n status_code=\"302\",\n )\n out['Content-Dispo... | [
1,
1
] | [] | [] | [
"header",
"php",
"python"
] | stackoverflow_0003948690_header_php_python.txt |
Q:
twisted on centos missing mail.smtp?
I'm trying to get buildbot running on centos5, and getting the following error:
File "/usr/lib/python2.4/site-packages/buildbot/status/mail.py", line 14, in ?
from twisted.mail.smtp import sendmail, ESMTPSenderFactory
ImportError: No module named mail.smtp
I have the fol... | twisted on centos missing mail.smtp? | I'm trying to get buildbot running on centos5, and getting the following error:
File "/usr/lib/python2.4/site-packages/buildbot/status/mail.py", line 14, in ?
from twisted.mail.smtp import sendmail, ESMTPSenderFactory
ImportError: No module named mail.smtp
I have the following twisted packages installed (and don... | [
"The equivalent of apt-file in redhat is \"yum whatprovides\". But I did try this for the smtp package you are looking for and it did return any matching package :(\n[vc@vc ~]$ yum whatprovides */twisted/mail/smtp.py \nLoaded plugins: downloadonly, fastestmirror \nExcluding Packages in global exclude list \nFinishe... | [
1
] | [] | [] | [
"centos",
"python",
"rpm",
"twisted"
] | stackoverflow_0003937164_centos_python_rpm_twisted.txt |
Q:
Python indentation when adding looping statements to existing code
In Python, what do you do when you write 100 lines of code and forget to add a bunch of loop statements somewhere?
I mean, if you add a while statement somewhere, you've to now indent all the lines below it. It's not like you can just put braces an... | Python indentation when adding looping statements to existing code | In Python, what do you do when you write 100 lines of code and forget to add a bunch of loop statements somewhere?
I mean, if you add a while statement somewhere, you've to now indent all the lines below it. It's not like you can just put braces and be done with it. Go to every single line and add tabs/spaces. What if... | [
"I think every serious editor or IDE supports the option to select multiple lines and press tab to indent or Shift-Tab to unindent all that lines.\n",
"in IDLE, the standard python IDE, select the code, go on 'format' and you can chooose indent region, dedent region and so on\n",
"You have to use an editor comm... | [
11,
3,
1,
1,
0
] | [] | [] | [
"indentation",
"python",
"python_idle"
] | stackoverflow_0003948257_indentation_python_python_idle.txt |
Q:
Copying a list of paths/files to a directory
I'm just doing an exercise where I have a list of files (given as absolute paths), which should be copied to a given directory if some sort of flag is set. This is my function to copy the files:
def copy_to(paths, dst):
if not os.path.exists(dst):
os.makedirs(dst)... | Copying a list of paths/files to a directory | I'm just doing an exercise where I have a list of files (given as absolute paths), which should be copied to a given directory if some sort of flag is set. This is my function to copy the files:
def copy_to(paths, dst):
if not os.path.exists(dst):
os.makedirs(dst)
for path in paths:
shutil.copy(path, dst)
... | [
"As per the current manual, it is not needed:\n\nshutil.copy(src, dst) Copy the file\n src to the file or directory dst. If\n dst is a directory, a file with the\n same basename as src is created (or\n overwritten) in the directory\n specified. Permission bits are copied.\n src and dst are path names given as... | [
3,
1,
1
] | [] | [] | [
"file_io",
"python"
] | stackoverflow_0003948805_file_io_python.txt |
Q:
How can I put a wx.ScrolledWindow inside a wx.SplitterWindow?
I wouldn't have thought this would be so tricky. I'm trying to get something like this:
X | X
Where both Xs are ScrolledWindows that will ultimately contain lots of text and '|' is a "splitter" dividing the two. I want something about like most visual ... | How can I put a wx.ScrolledWindow inside a wx.SplitterWindow? | I wouldn't have thought this would be so tricky. I'm trying to get something like this:
X | X
Where both Xs are ScrolledWindows that will ultimately contain lots of text and '|' is a "splitter" dividing the two. I want something about like most visual diffs give you. I can't seem to get this to work, though. My big ... | [
"What's wrong with the example? For me it works as expected.\n"
] | [
0
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0003861148_python_wxpython.txt |
Q:
In Python, how can I prohibit class inheritance?
Possible Duplicate:
Final classes in Python 3.x- something Guido isn't telling me?
I was watching a talk (How to design a good API and why it matters) in which it was said, literally, "design and document for inheritance, else prohibit it". The talk was using Java... | In Python, how can I prohibit class inheritance? |
Possible Duplicate:
Final classes in Python 3.x- something Guido isn't telling me?
I was watching a talk (How to design a good API and why it matters) in which it was said, literally, "design and document for inheritance, else prohibit it". The talk was using Java as an example, where there's the 'final' keyword for... | [
"There is no Python keyword for this - it is not Pythonic.\nWhether a class can be subclassed is determined by a flag called Py_TPFLAGS_BASETYPE which can be set via the C API.\n\nThis bit is set when the type can be used as the base type of another type. If this bit is clear, the type cannot be subtyped (similar t... | [
18,
12
] | [] | [] | [
"python"
] | stackoverflow_0003948964_python.txt |
Q:
Override reversed(...) in Python 2.5
I need a custom __reverse__ function for my class that I am deploying on App Engine, so it needs to work with Python 2.5. Is there a __future__ import or a workaround I could use?
Subclassing list won't work, as I need my class to be a subclass of dict.
EDIT:
Using OrderedDict ... | Override reversed(...) in Python 2.5 | I need a custom __reverse__ function for my class that I am deploying on App Engine, so it needs to work with Python 2.5. Is there a __future__ import or a workaround I could use?
Subclassing list won't work, as I need my class to be a subclass of dict.
EDIT:
Using OrderedDict will not solve the problems, because the d... | [
"__reversed__ isn't supported in 2.5, so your only option if you really need to customize the reversed order of your collection, is to modify the places that you call reversed to use something else.\nBut I'm curious: if you are subclassing dict, then the order of items is arbitrary anyway, so what does reversed mea... | [
2,
1
] | [] | [] | [
"python",
"python_2.5"
] | stackoverflow_0003949172_python_python_2.5.txt |
Q:
Turn a hex string into a percent encoded string in Python
I have a string. It looks like s = 'e6b693e6a0abe699ab'.
I want to put a percent sign in front of every pair of characters, so percentEncode(s) == '%e6%b6%93%e6%a0%ab%e6%99%ab'.
What's a good way of writing percentEncode(s)?
(Note, I don't care that unreser... | Turn a hex string into a percent encoded string in Python | I have a string. It looks like s = 'e6b693e6a0abe699ab'.
I want to put a percent sign in front of every pair of characters, so percentEncode(s) == '%e6%b6%93%e6%a0%ab%e6%99%ab'.
What's a good way of writing percentEncode(s)?
(Note, I don't care that unreserved characters aren't converted into ASCII.)
I can think of big... | [
">>> ''.join( \"%\"+i+s[n+1] for n,i in enumerate(s) if n%2==0 )\n'%e6%b6%93%e6%a0%ab%e6%99%ab'\n\nOr using re\n>>> import re\n>>> re.sub(\"(..)\",\"%\\\\1\",s)\n'%e6%b6%93%e6%a0%ab%e6%99%ab'\n\n",
"Oh, you mean:\n''.join([\"%%%s\" % pair for pair in [s[i:i+2] for i in range(0,len(s),2)]])\n\nThough probably if ... | [
3,
2,
2,
1,
1,
1
] | [] | [] | [
"percent_encoding",
"python"
] | stackoverflow_0003938801_percent_encoding_python.txt |
Q:
How can you manually render a form field with its initial value set?
I'm trying to render a form's fields manually so that my designer colleagues could manipulate the input elements within the HTML instead of struggling in Python source.
ie. Instead of declaring form fields like this...
{{ form.first_n... | How can you manually render a form field with its initial value set? | I'm trying to render a form's fields manually so that my designer colleagues could manipulate the input elements within the HTML instead of struggling in Python source.
ie. Instead of declaring form fields like this...
{{ form.first_name }}
.. I actually do ...
<label for="id_first_name">You... | [
"There is an interesting long standing ticket about this very issue. There is sample code to implement a template filter in the comments that should do what you need:\nhttp://code.djangoproject.com/ticket/10427\n",
"<input value=\"{{form.name.data|default_if_none:'my_defaut_value'}}\" ... />\n\nYou will have to u... | [
4,
0
] | [] | [] | [
"django",
"django_forms",
"form_fields",
"python"
] | stackoverflow_0003929903_django_django_forms_form_fields_python.txt |
Q:
Python save as/open
hello there
i am making a text editor in Tkinter (python)
and so i made a menu and wanted to know how i can call a function that will display the windows Save-as or open boxes that every program uses.
For example in notepad you can click file-save and then it opens the windows save box.
I alrea... | Python save as/open | hello there
i am making a text editor in Tkinter (python)
and so i made a menu and wanted to know how i can call a function that will display the windows Save-as or open boxes that every program uses.
For example in notepad you can click file-save and then it opens the windows save box.
I already have the menu but how ... | [
"Here is an example from http://www.daniweb.com/forums/thread39327.html:\n\n\nimport tkFileDialog\n\ndef open_it():\n filename = tkFileDialog.askopenfilename()\n print filename # test\n\ndef save_it():\n filename = tkFileDialog.askopenfilename()\n print filename # test\n\ndef save_as():\n filename ... | [
2
] | [] | [] | [
"python",
"tkinter",
"windows"
] | stackoverflow_0003950034_python_tkinter_windows.txt |
Q:
Generate RGB colors as different as possible
I have been using the random function to generate color values xi = [a, b, c] where a, b, and c can be any number from 0 to 255.
I need ideas to write a function that generate x values as different as possible for the human eye. One of the problems I am having is that I... | Generate RGB colors as different as possible | I have been using the random function to generate color values xi = [a, b, c] where a, b, and c can be any number from 0 to 255.
I need ideas to write a function that generate x values as different as possible for the human eye. One of the problems I am having is that I don't know the number of x elements that will be ... | [
"Using a different colour model can help here - for example, you could use HSV, and then cycle through the hue while maintaining a consistent saturation and value.\nHSV also makes it easier to generate colours which complement each other, for example, you could take 2 colours with hues 120 or 180 degrees apart.\nSe... | [
6
] | [] | [] | [
"colors",
"python",
"rgb"
] | stackoverflow_0003950024_colors_python_rgb.txt |
Q:
Paging python lists in slices of 4 items
Possible Duplicate:
How do you split a list into evenly sized chunks in Python?
mylist = [1, 2, 3, 4, 5, 6, 7, 8, 9]
I need to pass blocks of these to a third party API that can only deal with 4 items at a time. I could do one at a time but it's a HTTP request and proces... | Paging python lists in slices of 4 items |
Possible Duplicate:
How do you split a list into evenly sized chunks in Python?
mylist = [1, 2, 3, 4, 5, 6, 7, 8, 9]
I need to pass blocks of these to a third party API that can only deal with 4 items at a time. I could do one at a time but it's a HTTP request and process for each go so I'd prefer to do it in the l... | [
"mylist = [1, 2, 3, 4, 5, 6, 7, 8, 9] \nprint [mylist[i:i+4] for i in range(0, len(mylist), 4)]\n# Prints [[1, 2, 3, 4], [5, 6, 7, 8], [9]]\n\n"
] | [
76
] | [] | [] | [
"chunks",
"python"
] | stackoverflow_0003950079_chunks_python.txt |
Q:
Automatically add a variable into context on per-application basis in Django?
I want to add a context variable in Django, so that I could define its value on per-application basis, or leave it empty.
Example:
apps/someapp/views.py:
def_context_var('app_name', 'Calendar')
templates/base.html:
{% if app_name %}You... | Automatically add a variable into context on per-application basis in Django? | I want to add a context variable in Django, so that I could define its value on per-application basis, or leave it empty.
Example:
apps/someapp/views.py:
def_context_var('app_name', 'Calendar')
templates/base.html:
{% if app_name %}You are in {{ app_name }} app.{% endif %}
....
{% if app_name %}Subsections of {{ app_... | [
"You can call resolve(request.path) in a context processor to resolve the current url. See the django documentation on resolve for its return values, especially app_name. \n"
] | [
2
] | [] | [] | [
"django",
"django_urls",
"python"
] | stackoverflow_0003950082_django_django_urls_python.txt |
Q:
Min heap is, but is a max heap module defined in python?
Possible Duplicate:
What do I use for a max-heap implementation in Python?
Python has a min heap implemented in the heapq module. However, if one would want a max heap, would one have to build from scratch?
A:
You could multiply your numbers by -1 and u... | Min heap is, but is a max heap module defined in python? |
Possible Duplicate:
What do I use for a max-heap implementation in Python?
Python has a min heap implemented in the heapq module. However, if one would want a max heap, would one have to build from scratch?
| [
"You could multiply your numbers by -1 and use the min heap. \n",
"No need to implement a max heap from scratch. You can easily employ a bit of math to turn your min heap into a max heap!\nSee this and this - but really this SO answer. \n"
] | [
2,
0
] | [] | [] | [
"data_structures",
"heap",
"python"
] | stackoverflow_0003950368_data_structures_heap_python.txt |
Q:
How to see the error and still keep the program on in the Python shell?
I know try/except can handle errors in my program.
But, is there a way of making the error be displayed in the program execution, be ignored and let the execution go on?
A:
In VBScript and other VB-derived languages, you can get this sort of... | How to see the error and still keep the program on in the Python shell? | I know try/except can handle errors in my program.
But, is there a way of making the error be displayed in the program execution, be ignored and let the execution go on?
| [
"In VBScript and other VB-derived languages, you can get this sort of behavior with \"ON ERROR GOTO NEXT\".\nNo such behavior exists in Python. Even if you wrap each top-level statement like:\ntry:\n do_something()\nexcept Exception as e:\n print e\n\ntry:\n do_something_else()\nexcept Exception as e:\n print e... | [
3,
2
] | [] | [] | [
"error_handling",
"exception",
"exception_handling",
"python"
] | stackoverflow_0003950505_error_handling_exception_exception_handling_python.txt |
Q:
What threading module should I use to prevent disk IO from blocking network IO?
I have a Python application that, to be brief, receives data from a remote server, processes it, responds to the server, and occasionally saves the processed data to disk. The problem I've encountered is that there is a lot of data to ... | What threading module should I use to prevent disk IO from blocking network IO? | I have a Python application that, to be brief, receives data from a remote server, processes it, responds to the server, and occasionally saves the processed data to disk. The problem I've encountered is that there is a lot of data to write, and the save process can take upwards of half a minute. This is apparently a b... | [
"Since you're I/O bound, then use the threading module. \nYou should almost never need to use thread, it's a low-level interface; the threading module is a high-level interface wrapper for thread.\nThe multiprocessing module is different from the threading module, multiprocessing uses multiple subprocesses to exec... | [
7
] | [] | [] | [
"blocking",
"io",
"multithreading",
"nonblocking",
"python"
] | stackoverflow_0003950607_blocking_io_multithreading_nonblocking_python.txt |
Q:
trying to POST to w3c validator with python script
I'm trying to use this python script to upload a file to the w3c validator.
~/Desktop/urllib2_file$ python test-upload.py -u http://validator.w3.org/ -f ../index.php -n uploaded_file -p Content-Type=text/html > ../results.html && firefox ../results.html
Any help ... | trying to POST to w3c validator with python script | I'm trying to use this python script to upload a file to the w3c validator.
~/Desktop/urllib2_file$ python test-upload.py -u http://validator.w3.org/ -f ../index.php -n uploaded_file -p Content-Type=text/html > ../results.html && firefox ../results.html
Any help will be greatly appreciated!
EDIT:
cyraxjoe pointed out ... | [
"You are uploading a php-script which is a server-side script, you need to upload the resulting html after the php procesing. Perhaps with php-cli then store in a file the resulting text and upload that file.\n"
] | [
1
] | [] | [] | [
"curl",
"post",
"python"
] | stackoverflow_0003950591_curl_post_python.txt |
Q:
Python Implementation of PageRank
I am attempting to understand the concepts behind Google PageRank, and am attempting to implement a similar (though rudimentary) version in Python. I have spent the last few hours familiarizing myself with the algorithm, however it's still not all that clear.
I've located a parti... | Python Implementation of PageRank | I am attempting to understand the concepts behind Google PageRank, and am attempting to implement a similar (though rudimentary) version in Python. I have spent the last few hours familiarizing myself with the algorithm, however it's still not all that clear.
I've located a particularly interesting website that outlin... | [
"I'll try to give a simple explanation (definition) of the PageRank algorithm from my personal notes.\nLet us say that pages T1, T2, ... Tn are pointing to page A, then\nPR(A) = (1-d) + d * (PR(T1) / C(T1) + ... + PR(Tn) / C(Tn))\n\nwhere\n\nPR(Ti) is the PageRank of Ti\nC(Ti) is the number of outgoing links from p... | [
8
] | [] | [] | [
"linear_algebra",
"pagerank",
"python"
] | stackoverflow_0003950627_linear_algebra_pagerank_python.txt |
Q:
Minimax: how can I implement it in Python?
As long as I've been a programmer I still have a very elementary level education in algorithms (because I'm self-taught). Perhaps there is a good beginner book on them that you could suggest in your answer.
A:
As a general note, Introduction to Algorithms. That book wi... | Minimax: how can I implement it in Python? | As long as I've been a programmer I still have a very elementary level education in algorithms (because I'm self-taught). Perhaps there is a good beginner book on them that you could suggest in your answer.
| [
"As a general note, Introduction to Algorithms. That book will get you through pretty much everything you need to know about general algorithms.\nEdit:\nAs AndrewF mentioned, it doesn't actually contain minimax specifically, but it's still a very good resource for learning to understand and implement algorithms.\n"... | [
3,
1,
1
] | [] | [] | [
"algorithm",
"minimax",
"python"
] | stackoverflow_0003950728_algorithm_minimax_python.txt |
Q:
Python IDLE will not open
After fumbling with some keys on my keyboard while trying to get a script to run by clicking on Run in python IDLE I must of did something, because now python will not open. It opens from the command prompt fine, but the normal way it will not open whatsoever. I tried repairing and reinst... | Python IDLE will not open | After fumbling with some keys on my keyboard while trying to get a script to run by clicking on Run in python IDLE I must of did something, because now python will not open. It opens from the command prompt fine, but the normal way it will not open whatsoever. I tried repairing and reinstalling. Still no luck. I am on ... | [
"try executing C:\\path\\to\\python.exe -m idlelib.idle in command prompt, is there any error message?\n"
] | [
3
] | [] | [] | [
"python",
"python_idle",
"startup"
] | stackoverflow_0003950973_python_python_idle_startup.txt |
Q:
Python: Fetching and parsing text from html files
I'm trying to work on a project about page ranking.
I want to make an index (dictionary) which looks like this:
file1.html -> [[cat, ate, food, drank, milk], [file2.html, file3.html]]
file2.html -> [[dog, barked, ran, away], [file1.html, file4.html]]
Fetching lin... | Python: Fetching and parsing text from html files | I'm trying to work on a project about page ranking.
I want to make an index (dictionary) which looks like this:
file1.html -> [[cat, ate, food, drank, milk], [file2.html, file3.html]]
file2.html -> [[dog, barked, ran, away], [file1.html, file4.html]]
Fetching links is easy - look for anchor tags.
My question is - how... | [
"Use an HTML parser - something like BeautifulSoup.\n",
"If the text isn't enclosed in tags is it really HTML?\nAs Amber says, you'll have an easier job of this using some HTML parser like BeautifulSoup. \nThe example below demonstrates a simple method for returning text within tags.\nThis method works for any t... | [
1,
0
] | [] | [] | [
"html",
"parsing",
"python"
] | stackoverflow_0003950741_html_parsing_python.txt |
Q:
Safe way to uninstall old version of python
I want to update my Python framework on Mac and delete the old versions
but I am not sure if is safe to
rm -fr /Library/Frameworks/Python.framework/Versions/2.4 - 2.5 - 2.6 -3.0 etc.
Any suggestion?
A:
Yes, it's safe.
The Mac's system python's are in /System/Library/... | Safe way to uninstall old version of python | I want to update my Python framework on Mac and delete the old versions
but I am not sure if is safe to
rm -fr /Library/Frameworks/Python.framework/Versions/2.4 - 2.5 - 2.6 -3.0 etc.
Any suggestion?
| [
"Yes, it's safe.\nThe Mac's system python's are in /System/Library/....\n.dmg's downloaded and installed from python.org are placed in /Library/....\nDon't delete the /System ones, but the /Library ones are user installed, so they should be safe to delete.\n"
] | [
30
] | [
"No, it's not safe. Generally, don't mess with the Python that comes with your OS, many system tools depends on having a specific version of Python.\n"
] | [
-1
] | [
"installation",
"macos",
"python"
] | stackoverflow_0003950819_installation_macos_python.txt |
Q:
Twisted UDP Server - daemonize?
I have the following UDP server using Twisted:
# init the thread capability
threadable.init(1)
# set the thread pool size
reactor.suggestThreadPoolSize(32)
class BaseThreadedUDPServer(DatagramProtocol):
def datagramReceived(self, datagram, (host, port)):
#do some stuff... | Twisted UDP Server - daemonize? | I have the following UDP server using Twisted:
# init the thread capability
threadable.init(1)
# set the thread pool size
reactor.suggestThreadPoolSize(32)
class BaseThreadedUDPServer(DatagramProtocol):
def datagramReceived(self, datagram, (host, port)):
#do some stuff here...
def main():
reactor.lis... | [
"The daemonization code in twistd doesn't care if you're serving up UDP or TCP. The way you daemonize a UDP server is identical to the way you daemonize a TCP server. You should be able to use the TCP echo server as an example to write a .tac file for your UDP server.\n",
"Try this:\nimport twisted.application\... | [
3,
3
] | [] | [] | [
"daemon",
"python",
"twisted"
] | stackoverflow_0003931346_daemon_python_twisted.txt |
Q:
How can I extend an embedded python interpreter with C++ functions?
How can I extend an embedded interpreter with C++ code? I have embedded the interpreter and I can use boost.python to make a loadable module (as in a shared library) but I don't want the library floating around because I want to directly interface... | How can I extend an embedded python interpreter with C++ functions? | How can I extend an embedded interpreter with C++ code? I have embedded the interpreter and I can use boost.python to make a loadable module (as in a shared library) but I don't want the library floating around because I want to directly interface with my C++ application. Sorry if my writing is a bit incoherent.
| [
"At least for the 2.x interpreters: you write your methods as C-style code with PyObject* return values. They all basically look like:\nPyObject* foo(PyObject *self, PyObject *args);\n\nThen, you collect these methods in a static array of PyMethodDef:\nstatic PyMethodDef MyMethods[] =\n{\n {\"mymethod\", foo, M... | [
2
] | [] | [] | [
"boost",
"boost_python",
"embed",
"extend",
"python"
] | stackoverflow_0003951407_boost_boost_python_embed_extend_python.txt |
Q:
fetching and parsing text not enclosed within tags
I'm trying to work on a project about page ranking. I want to make an index (dictionary) which looks like this:
file1.html -> [[cat, ate, food, drank, milk], [file2.html, file3.html]]
file2.html -> [[dog, barked, ran, away], [file1.html, file4.html]]
Fetching lin... | fetching and parsing text not enclosed within tags | I'm trying to work on a project about page ranking. I want to make an index (dictionary) which looks like this:
file1.html -> [[cat, ate, food, drank, milk], [file2.html, file3.html]]
file2.html -> [[dog, barked, ran, away], [file1.html, file4.html]]
Fetching links is easy - look for anchor tags. My question is - how ... | [
"One way to go about this is to simply ignore all the tags and what you've got left is assumed to be text. It will make the regex large though.\n",
"I wouldn't use regex, I would use something like lxml, that way you can get the tags, the text and also the structure of the document as needed.\n",
"You say the t... | [
1,
0,
0,
0
] | [] | [] | [
"html",
"html_parsing",
"python"
] | stackoverflow_0003951280_html_html_parsing_python.txt |
Q:
How to revert compiled Python 2.6.4 to system default on Snow Leopard?
So earlier this year I manually built 2.6.4 for Snow Leopard because I wanted a slightly more updated version of Python than what Apple released. This has caused all kinds of problems when installing some eggs like PIL and running other 3rd par... | How to revert compiled Python 2.6.4 to system default on Snow Leopard? | So earlier this year I manually built 2.6.4 for Snow Leopard because I wanted a slightly more updated version of Python than what Apple released. This has caused all kinds of problems when installing some eggs like PIL and running other 3rd party python apps. Now I just want to revert everything back to what Snow Leopa... | [
"Set the PATH environment variable so that /usr/bin is ahead of wherever you put your custom compiled Python binary.\n"
] | [
1
] | [] | [] | [
"osx_snow_leopard",
"python"
] | stackoverflow_0003951608_osx_snow_leopard_python.txt |
Q:
How to abort python fabric run command?
run("if [ -d data.bak ];then mv data.bak data;fi;")
sudo('....')
sudo('')
I am using fabric deploy for my web project. I want to find a way that will stop the rest of the execution of the command, if it doesn't find the data.bak directory. Any way to achieve this in fabric?... | How to abort python fabric run command? | run("if [ -d data.bak ];then mv data.bak data;fi;")
sudo('....')
sudo('')
I am using fabric deploy for my web project. I want to find a way that will stop the rest of the execution of the command, if it doesn't find the data.bak directory. Any way to achieve this in fabric?
| [
"There is a contribute api in fabric.contrib.files import.\n"
] | [
1
] | [] | [] | [
"fabric",
"python",
"sudo"
] | stackoverflow_0003947827_fabric_python_sudo.txt |
Q:
How to replace the first occurrence of a regular expression in Python?
I want to replace just the first occurrence of a regular expression in a string. Is there a convenient way to do this?
A:
re.sub() has a count parameter that indicates how many substitutions to perform. You can just set that to 1:
>>> s = "fo... | How to replace the first occurrence of a regular expression in Python? | I want to replace just the first occurrence of a regular expression in a string. Is there a convenient way to do this?
| [
"re.sub() has a count parameter that indicates how many substitutions to perform. You can just set that to 1:\n>>> s = \"foo foo foofoo foo\"\n>>> re.sub(\"foo\", \"bar\", s, 1)\n'bar foo foofoo foo'\n>>> s = \"baz baz foo baz foo baz\"\n>>> re.sub(\"foo\", \"bar\", s, 1)\n'baz baz bar baz foo baz'\n\nEdit: And a v... | [
74,
17
] | [] | [] | [
"python",
"regex",
"replace",
"search"
] | stackoverflow_0003951660_python_regex_replace_search.txt |
Q:
How to invoke a function on an object dynamically by name?
In Python, say I have a string that contains the name of a class function that I know a particular object will have, how can I invoke it?
That is:
obj = MyClass() # this class has a method doStuff()
func = "doStuff"
# how to call obj.doStuff() using the fu... | How to invoke a function on an object dynamically by name? | In Python, say I have a string that contains the name of a class function that I know a particular object will have, how can I invoke it?
That is:
obj = MyClass() # this class has a method doStuff()
func = "doStuff"
# how to call obj.doStuff() using the func variable?
| [
"Use the getattr built-in function. See the documentation\nobj = MyClass()\ntry:\n func = getattr(obj, \"dostuff\")\n func()\nexcept AttributeError:\n print(\"dostuff not found\")\n\n"
] | [
99
] | [] | [] | [
"python"
] | stackoverflow_0003951840_python.txt |
Q:
how to launch an exe with a variable path, special characters and arguements
I want to copy an installer file from a location where one of the folder names changes as per the build number
This works for defining the path where the last folder name changes
import glob
import os
dirname = "z:\\zzinstall\\*.insta... | how to launch an exe with a variable path, special characters and arguements | I want to copy an installer file from a location where one of the folder names changes as per the build number
This works for defining the path where the last folder name changes
import glob
import os
dirname = "z:\\zzinstall\\*.install"
filespec = "setup.exe"
print glob.glob (os.path.join (dirname, filespec))
#... | [
"The related question you linked to does contain a relatively clear answer to your problem:\nimport subprocess\nsubprocess.call(['z:/zzinstall/35115.install/setup.exe', '/S', '/z', ''])\n\nSo you don't need to concatenate the path of setup.exe and its arguments. The arguments you specify in the list are passed dire... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0003950338_python.txt |
Q:
How do you embed album art into an MP3 using Python?
I've been using mutagen for reading and writing MP3 tags, but I want to be able to embed album art directly into the file.
A:
Here is how to add example.png as album cover into example.mp3 with mutagen:
from mutagen.mp3 import MP3
from mutagen.id3 import ID3, ... | How do you embed album art into an MP3 using Python? | I've been using mutagen for reading and writing MP3 tags, but I want to be able to embed album art directly into the file.
| [
"Here is how to add example.png as album cover into example.mp3 with mutagen:\nfrom mutagen.mp3 import MP3\nfrom mutagen.id3 import ID3, APIC, error\n\naudio = MP3('example.mp3', ID3=ID3)\n\n# add ID3 tag if it doesn't exist\ntry:\n audio.add_tags()\nexcept error:\n pass\n\naudio.tags.add(\n APIC(\n ... | [
38,
13,
3,
1,
0
] | [] | [] | [
"albumart",
"id3",
"metadata",
"mp3",
"python"
] | stackoverflow_0000409949_albumart_id3_metadata_mp3_python.txt |
Q:
Trouble with easy_install cheetah on WIndows Xp
I have installed PyQT from this URL:
http://www.riverbankcomputing.co.uk/static/Downloads/PyQt4/PyQt-Py2.6-gpl-4.7.7-1.exe
I have Python 2.6 installed.
My OS is Windows XP SP3.
I entered this into cmd.exe:
easy_install cheetah
This is the output:
C:\Documents and Se... | Trouble with easy_install cheetah on WIndows Xp | I have installed PyQT from this URL:
http://www.riverbankcomputing.co.uk/static/Downloads/PyQt4/PyQt-Py2.6-gpl-4.7.7-1.exe
I have Python 2.6 installed.
My OS is Windows XP SP3.
I entered this into cmd.exe:
easy_install cheetah
This is the output:
C:\Documents and Settings\All Users>easy_install cheetah
Searching for c... | [
"The error you're getting on 'awtoum' is probably for the Autumn-ORM, which you can probably install with the command easy_install autumn. Once you have that prerequisite working, you can give the Cheetah installation another try, and it should skip right on past the error if the Autumn-ORM is already installed.\nA... | [
2
] | [] | [] | [
"cheetah",
"python"
] | stackoverflow_0003949532_cheetah_python.txt |
Q:
Simple python regex groups can't parse date
I'm trying to parse dates with regex, using groups, but python is returning empty lists. I'm not doing anything fancy, just 12/25/10 sort of stuff. I want it to reject 12/25-10 though.
date = re.compile("\d{1,2}([/.-])\d{1,2}\1\d{2}")
I've tried online regex libraries... | Simple python regex groups can't parse date | I'm trying to parse dates with regex, using groups, but python is returning empty lists. I'm not doing anything fancy, just 12/25/10 sort of stuff. I want it to reject 12/25-10 though.
date = re.compile("\d{1,2}([/.-])\d{1,2}\1\d{2}")
I've tried online regex libraries, but their solutions don't seem to run either. ... | [
"Use a raw string:\ndate = re.compile(r\"\\d{1,2}([/.-])\\d{1,2}\\1\\d{2}\")\n\nOtherwise, the \\1 in the string literal is interpreted as the character 1 (Start of Heading).\nEDIT: To add groups for the date components, use:\nre.compile(r\"(\\d{1,2})([/.-])(\\d{1,2})\\2(\\d{2})\")\n\n",
"You should use Python's ... | [
5,
5,
2
] | [] | [] | [
"python",
"python_2.x",
"regex",
"regex_group"
] | stackoverflow_0003951971_python_python_2.x_regex_regex_group.txt |
Q:
Is there a more Pythonic approach to this?
This is my first python script, be ye warned.
I pieced this together from Dive Into Python, and it works great. However since it is my first Python script I would appreciate any tips on how it can be made better or approaches that may better embrace the Python way of pro... | Is there a more Pythonic approach to this? | This is my first python script, be ye warned.
I pieced this together from Dive Into Python, and it works great. However since it is my first Python script I would appreciate any tips on how it can be made better or approaches that may better embrace the Python way of programming.
import os
import shutil
def getSource... | [
"As others mentioned, you probably want to use walk from the built-in os module. Also, consider using PEP 8 compatible style (no camel-case but this_stye_of_function_naming()). Wrapping directly executable code (i.e. no library/module) into a if __name__ == '__main__': ... block is also a good practice.\n",
"Th... | [
6,
4,
3,
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0003951780_python.txt |
Q:
Python Range Class/Subclass
I have code for a Range class like this:
class Range:
def __init__(self, start, end):
self.setStart(start)
self.setEnd(end)
def getStart(self):
return self.start
def setStart(self, s):
self.start = s
def getEnd(self):
return self.end
def setE... | Python Range Class/Subclass | I have code for a Range class like this:
class Range:
def __init__(self, start, end):
self.setStart(start)
self.setEnd(end)
def getStart(self):
return self.start
def setStart(self, s):
self.start = s
def getEnd(self):
return self.end
def setEnd(self, e):
self.end = e
... | [
"In general it is much easier to answer questions if you provide a specific error message or thing that is going wrong. Here's what happened when I tried to run the above:\n\nFirst up:\n`SyntaxError: invalid syntax` \n\non if seq == POSITIVE. What's wrong here? Oh yes, you're missing a colon after the conditional. ... | [
4,
0
] | [] | [] | [
"python",
"subclass"
] | stackoverflow_0003909733_python_subclass.txt |
Q:
How do I use ReverseProxyProtocol
I have the following:
My webserver running on twisted
My comet server, aka orbited
Note that 1 and 2 are different processes.
Basically, I want 1 and 2 to share the same port. Request that are http://mysite.com/a/b/c should go to the webserver and anything starting with http://m... | How do I use ReverseProxyProtocol | I have the following:
My webserver running on twisted
My comet server, aka orbited
Note that 1 and 2 are different processes.
Basically, I want 1 and 2 to share the same port. Request that are http://mysite.com/a/b/c should go to the webserver and anything starting with http://mysite.com/orbited/ should go to the orb... | [
"The cleanest way is to put something like nginx in front of both servers.\n"
] | [
0
] | [] | [] | [
"python",
"twisted"
] | stackoverflow_0003952487_python_twisted.txt |
Q:
python and sqlite - escape input
Using python with a sqlite DB - whats the method used for escaping the data going out and pulling the data coming out?
Using pysqlite2
Google has conflicting suggestions.
A:
Use the second parameter args to pass arguments; don't do the escaping yourself. Not only is this easier, ... | python and sqlite - escape input | Using python with a sqlite DB - whats the method used for escaping the data going out and pulling the data coming out?
Using pysqlite2
Google has conflicting suggestions.
| [
"Use the second parameter args to pass arguments; don't do the escaping yourself. Not only is this easier, it also helps prevent SQL injection attacks.\ncursor.execute(sql,args)\n\nfor example,\ncursor.execute('INSERT INTO foo VALUES (?, ?)', (\"It's okay\", \"No escaping necessary\") )\n\n"
] | [
23
] | [] | [] | [
"pysqlite",
"python",
"sqlite"
] | stackoverflow_0003952543_pysqlite_python_sqlite.txt |
Q:
PyQt4: AttributeError: 'QLineEdit' object has no attribute 'setPlaceholderText'
I have a QLineEdit, and I want to set a placeholder text. When I call setPlaceholderText(string) I get an AttributeError, but:
>>> from PyQt4 import QtCore
>>> QtCore.PYQT_VERSION_STR
'4.7.4'
>>> QtCore.QT_VERSION_STR
'4.7.0'
and from... | PyQt4: AttributeError: 'QLineEdit' object has no attribute 'setPlaceholderText' | I have a QLineEdit, and I want to set a placeholder text. When I call setPlaceholderText(string) I get an AttributeError, but:
>>> from PyQt4 import QtCore
>>> QtCore.PYQT_VERSION_STR
'4.7.4'
>>> QtCore.QT_VERSION_STR
'4.7.0'
and from the QAssistant:
This property holds the line edit's
placeholder text.
...
Thi... | [
"I would guess that although the libraries are very recent, the bindings are simply not that up to date.\nYou might want to check out PySide - a Nokia project with (IMO) fewer license issues than PyQt.\n"
] | [
3
] | [] | [] | [
"pyqt4",
"python",
"qlineedit"
] | stackoverflow_0003952850_pyqt4_python_qlineedit.txt |
Q:
Issues with implementing a network server with SocketServer
I am beginner in socket programming and need your help. I have implemented simple echo server using ThreadedTCPServer example from the Python documentation. It works fine, but I have the following problems:
Server hangs (in socket.recv) when Client tries... | Issues with implementing a network server with SocketServer | I am beginner in socket programming and need your help. I have implemented simple echo server using ThreadedTCPServer example from the Python documentation. It works fine, but I have the following problems:
Server hangs (in socket.recv) when Client tries to send zero-length data.
Server hangs (in socket.recv) when the... | [
"I don't know python but I will try and answer based on my socket programming knowledge.\nA zero byte message will NOT cause \"sock.recv\" to come out. Refer here for an explanation. If sock.recv returns with length 0, it is an indication that the other side has disconnected the TCP connection.\nif len (buf) < BUF_... | [
2,
0
] | [] | [] | [
"python",
"sockets",
"socketserver"
] | stackoverflow_0003845885_python_sockets_socketserver.txt |
Q:
Regular expression match from right direction
Normally, we use regular expression match from left to right direction. I want to know whether there is some switch that can be used to match from the right to left in python?
Or is this feature embedded in any other language?
e.g.
abcd1_abcd2
If given regular express... | Regular expression match from right direction | Normally, we use regular expression match from left to right direction. I want to know whether there is some switch that can be used to match from the right to left in python?
Or is this feature embedded in any other language?
e.g.
abcd1_abcd2
If given regular expression abcd, it will match two abcd strings. What I wa... | [
"You can reverse the list as proposed by @SilentGhost:\nimport re\n\nfor s in reversed(re.findall('abcd.', 'abcd1_abcd2')):\n print s\n\n"
] | [
3
] | [] | [] | [
"python",
"regex",
"reverse"
] | stackoverflow_0003953142_python_regex_reverse.txt |
Q:
Extra output none while printing an command line argument
It's my day 1 of learning python. so it's a noob question for many of you. See the following code:
#!/usr/bin/env python
import sys
def hello(name):
name = name + '!!!!'
print 'hello', name
def main():
print hello(sys.argv[1])
if __name__ ==... | Extra output none while printing an command line argument | It's my day 1 of learning python. so it's a noob question for many of you. See the following code:
#!/usr/bin/env python
import sys
def hello(name):
name = name + '!!!!'
print 'hello', name
def main():
print hello(sys.argv[1])
if __name__ == '__main__':
main()
when I run it
$ ./Python-1.py alice
h... | [
"Count the number of print statements in your code. You'll see that you're printing \"hello alice!!!\" in the hello function, and printing the result of the hello function. Because the hello function doesn't return a value (which you'd do with the return statement), it ends up returning the object None. Your print ... | [
26,
6
] | [] | [] | [
"function",
"python"
] | stackoverflow_0003953233_function_python.txt |
Q:
pymongo: a more efficient update
I am trying to push some big files (around 4 million records) into a mongo instance. What I am basically trying to achieve is to update the existent data with the one from the files. The algorithm would look something like:
rowHeaders = ('orderId', 'manufacturer', 'itemWeight')
for... | pymongo: a more efficient update | I am trying to push some big files (around 4 million records) into a mongo instance. What I am basically trying to achieve is to update the existent data with the one from the files. The algorithm would look something like:
rowHeaders = ('orderId', 'manufacturer', 'itemWeight')
for row in dataFile:
row = row.strip(... | [
"Combine an unique index on orderId with an update query where you also check for a change in itemWeight. The unique index prevents an insert with only a modified timestamp if the orderId is already present and itemWeight is the same.\nmongoCollection.ensure_index('orderId', unique=True)\nmongoCollection.update({'o... | [
6
] | [] | [] | [
"mongodb",
"pymongo",
"python"
] | stackoverflow_0003815633_mongodb_pymongo_python.txt |
Q:
PyMongo: group with 2d geospatial index in conditions returns an error
The error returned is:
exception: manual matcher config not allowed
Here's my code:
cond = {'id': id, 'date': {'$gte': start_date}, 'date': {'$lte': end_date}, 'location': {'$within': {'$box': box }}}
reduce = 'function(obj, prev) { prev.count+... | PyMongo: group with 2d geospatial index in conditions returns an error | The error returned is:
exception: manual matcher config not allowed
Here's my code:
cond = {'id': id, 'date': {'$gte': start_date}, 'date': {'$lte': end_date}, 'location': {'$within': {'$box': box }}}
reduce = 'function(obj, prev) { prev.count++; }'
rows = collection.group({'location': True}, cond, {'count': 0}, reduce... | [
"MongoDB currently (version 1.6.2) doesn't support geo queries for mapreduce and group functions. See http://jira.mongodb.org/browse/SERVER-1742 for the issue ticket (and consider voting it up).\n"
] | [
1
] | [] | [] | [
"mongodb",
"pymongo",
"python"
] | stackoverflow_0003841208_mongodb_pymongo_python.txt |
Q:
Cooperative multitasking using TPL
We are porting modeling application, which uses IronPython scripts for custom actions in modeling process. The existing application executes each Python script in separate thread and uses cooperative model for this. Now we want to port it to TPL, but first we want to measure cont... | Cooperative multitasking using TPL | We are porting modeling application, which uses IronPython scripts for custom actions in modeling process. The existing application executes each Python script in separate thread and uses cooperative model for this. Now we want to port it to TPL, but first we want to measure context switching
.
Basically, what we have... | [
"It sounds like you'd be well served to use the producer/consumer pattern .NET 4 has built in to a few collections.\nCheck out page 55 in this free PDF from Microsoft, Patterns of Parallel Programming\n"
] | [
2
] | [] | [] | [
"c#",
"multithreading",
"python",
"scheduled_tasks",
"task"
] | stackoverflow_0003921930_c#_multithreading_python_scheduled_tasks_task.txt |
Q:
Programming books in ePub format
I purchased an iPad hoping to read books on it that've been aging on my desk for months, but it turned out that there're NO programming books available on iBookstore.
Are there any (Python, PHP, jQuery) books available in ePub format? Conversion from pdf to epub is not an option b... | Programming books in ePub format | I purchased an iPad hoping to read books on it that've been aging on my desk for months, but it turned out that there're NO programming books available on iBookstore.
Are there any (Python, PHP, jQuery) books available in ePub format? Conversion from pdf to epub is not an option because the formatting is lost in the p... | [
"You can buy all O'Reilly books straight off their website in ePub and many other formats. Should work fine on the iPad (don't have one myself).\n",
"I found two free and good ePub programming books so far\n\nStructure and Interpretation of Computer Programs (SICP)\nProGIT\n\n",
"Manning has some programming bo... | [
13,
8,
5,
3,
0
] | [] | [] | [
"epub",
"jquery",
"php",
"python"
] | stackoverflow_0003278477_epub_jquery_php_python.txt |
Q:
What is PyObjC?
I understand the concept of PyObjC, but can nowhere find any information on what exactly it is or how to get started with it.
Is it like a converter, where youinput python files and get an objective c one?
Or is it a library you can import to your objective c files which let's you write python in t... | What is PyObjC? | I understand the concept of PyObjC, but can nowhere find any information on what exactly it is or how to get started with it.
Is it like a converter, where youinput python files and get an objective c one?
Or is it a library you can import to your objective c files which let's you write python in them?
Or is it somethi... | [
"It's a language binding, meaning it allows you to call ObjC code from Python and vice versa. You write wrapper modules in ObjC that can be linked into the Python interpreter (which is written in C) to give it access to ObjC functions (tutorial for this use case). Apparently, the entire Cocoa framework is already w... | [
6
] | [] | [] | [
"language_binding",
"objective_c",
"pyobjc",
"python"
] | stackoverflow_0003953679_language_binding_objective_c_pyobjc_python.txt |
Q:
How to write a port scanner listening for 'ACK' in python?
please can anyone help me with the port scanner program to scan ports on the IP address provided,for ACK. i want to know the technique used to scan for ACK & use multi-threading so please help me in that perspective.
Thank you
A:
Just a heads-up - Windo... | How to write a port scanner listening for 'ACK' in python? | please can anyone help me with the port scanner program to scan ports on the IP address provided,for ACK. i want to know the technique used to scan for ACK & use multi-threading so please help me in that perspective.
Thank you
| [
"Just a heads-up - Windows XP SP2 and later disable raw sockets, so you won't be able to scan for TCP ACK messages specifically on Windows. Since an ACK message is the last message in establishing a TCP connection, you can implicitly detect the ACK message by attempting to establish a connection with a simple socke... | [
3,
1
] | [] | [] | [
"multithreading",
"port_scanning",
"python",
"sockets"
] | stackoverflow_0003952978_multithreading_port_scanning_python_sockets.txt |
Q:
Is XML parsing in PHP as fast as Python or other alternatives?
So I have 16 GB worth of XML files to process (about 700 files total), and I already have a functional PHP script to do that (With XMLReader) but it's taking forever. I was wondering if parsing in Python would be faster (Python being the only other lan... | Is XML parsing in PHP as fast as Python or other alternatives? | So I have 16 GB worth of XML files to process (about 700 files total), and I already have a functional PHP script to do that (With XMLReader) but it's taking forever. I was wondering if parsing in Python would be faster (Python being the only other language I'm proficient in, I'm sure something in C would be faster).
| [
"I think that both of them can rely over wrappers for fast C libraries (mostly libxml2) so there's shouldn't be too much difference in parsing per se.\nYou could try if there are differences caused by overhead, then it depends what are you gonna do over that XML. Parsing it for what?\n",
"There's actually three d... | [
2,
2,
1
] | [] | [] | [
"php",
"python",
"xml"
] | stackoverflow_0003953563_php_python_xml.txt |
Q:
recursively downloading files from webpage
http://examples.oreilly.com/9780735615366/
I actually want to be able to have all these files in my disk.
as u can see there are many folders each with different type of files.
and u cannot download "the-folder" directly...only individual files
~
is there any way to autom... | recursively downloading files from webpage | http://examples.oreilly.com/9780735615366/
I actually want to be able to have all these files in my disk.
as u can see there are many folders each with different type of files.
and u cannot download "the-folder" directly...only individual files
~
is there any way to automate process..?
I will need regular expressions o... | [
"Take a look at wget tool. It can do exactly what you want.\n",
"wget (GNU command line tool) will do this for you.\nThe documentation for what you want to do is here:\nhttp://www.gnu.org/software/wget/manual/html_node/Recursive-Retrieval-Options.html\n",
"Try Wget. it's a simple command line utility able to do... | [
4,
1,
0,
0
] | [] | [] | [
"python",
"recursion",
"regex",
"scripting"
] | stackoverflow_0003953853_python_recursion_regex_scripting.txt |
Q:
python: how to slice/store iter pointed data in a fixed buffer class?
All,
As you know, by python iter we can use iter.next() to get the next item of data.
take a list for example:
l = [x for x in range(100)]
itl = iter(l)
itl.next() # 0
itl.next() # 1
Now I want a buffer can store *general... | python: how to slice/store iter pointed data in a fixed buffer class? | All,
As you know, by python iter we can use iter.next() to get the next item of data.
take a list for example:
l = [x for x in range(100)]
itl = iter(l)
itl.next() # 0
itl.next() # 1
Now I want a buffer can store *general iter pointed data * slice in fixed size, use above list iter to demo my qu... | [
"Since you asked about design, I'll write a bit about what you want - it's not a iterator. \nThe defining property of a iterator is that it only supports iteration, not random access. But methods like .first and .last do random access, so what you ask for is not a iterator. \nThere are of course containers that all... | [
4,
3
] | [] | [] | [
"buffer",
"iterator",
"python"
] | stackoverflow_0003953282_buffer_iterator_python.txt |
Q:
Getting local variables of function
I'm trying to get a local variable from a decorator. An example:
def needs_privilege(privilege, project=None):
"""Check whether the logged-in user is authorised based on the
given privilege
@type privilege: Privilege object, id, or str
@param privilege: The requ... | Getting local variables of function | I'm trying to get a local variable from a decorator. An example:
def needs_privilege(privilege, project=None):
"""Check whether the logged-in user is authorised based on the
given privilege
@type privilege: Privilege object, id, or str
@param privilege: The requested privilege"""
def validate(func... | [
"Your decorator basically check if a user have the permission to execute a given function, i don't actually understand why you want to retrieve (to attach) the privilege to the function that was being wrapped but you can do this without adding another argument to all your functions.\ndef needs_privilege(privilege, ... | [
3,
2,
1,
0
] | [] | [] | [
"decorator",
"locals",
"python",
"unix"
] | stackoverflow_0003953216_decorator_locals_python_unix.txt |
Q:
Python vs Flash
Can python be used as a language to develop browser based games? Like we do in flash. If yes then what frameworks are available to get my hands dirty? If no then what are the reasons?
A:
Give it a try to Panda3D. I have successfully used it before to create and deploy 3D game environments that ru... | Python vs Flash | Can python be used as a language to develop browser based games? Like we do in flash. If yes then what frameworks are available to get my hands dirty? If no then what are the reasons?
| [
"Give it a try to Panda3D. I have successfully used it before to create and deploy 3D game environments that run in a browser (runtime is required). Works for Mac. Linux and Windows.\nExamples here: http://www.panda3d.org/gallery/\nTheir manual is very clear and has a bunch of examples. http://www.panda3d.org/manua... | [
3,
1,
1,
0
] | [] | [] | [
"actionscript",
"flash",
"python"
] | stackoverflow_0003953999_actionscript_flash_python.txt |
Q:
calculate IP checksum in python
I need to calculate the checksum of an IP packet as described in http://www.faqs.org/rfcs/rfc1071.html.
I have already the following code:
#!/usr/bin/python
import struct
data = "45 00 00 47 73 88 40 00 40 06 a2 c4 83 9f 0e 85 83 9f 0e a1"
# a test for the checksum calculation
de... | calculate IP checksum in python | I need to calculate the checksum of an IP packet as described in http://www.faqs.org/rfcs/rfc1071.html.
I have already the following code:
#!/usr/bin/python
import struct
data = "45 00 00 47 73 88 40 00 40 06 a2 c4 83 9f 0e 85 83 9f 0e a1"
# a test for the checksum calculation
def _checksum(data):
#calculate the... | [
"You can use the solution directly from checksum udp calculation python, which results in the expected checksum value of zero.\nimport struct\n\ndata = \"45 00 00 47 73 88 40 00 40 06 a2 c4 83 9f 0e 85 83 9f 0e a1\"\n\ndef carry_around_add(a, b):\n c = a + b\n return (c & 0xffff) + (c >> 16)\n\ndef checksum(m... | [
9,
6
] | [] | [] | [
"checksum",
"network_protocols",
"python"
] | stackoverflow_0003949726_checksum_network_protocols_python.txt |
Q:
Is it possible to make a cross browser extension linked to a Python web app backend?
Current Situation
I am in the early phases of designing a web app that the user will interact with via a browser extension that will be in the form of a horizontal nav bar. I wanted to use Pylons and Python on this project but am ... | Is it possible to make a cross browser extension linked to a Python web app backend? | Current Situation
I am in the early phases of designing a web app that the user will interact with via a browser extension that will be in the form of a horizontal nav bar. I wanted to use Pylons and Python on this project but am unsure how it fits in. As I understand it a browser extension is "just bundled HTML, CSS, ... | [
"As long as the extension uses HTTP to communicate, you can use whatever server-side technology you like to generate the data passed back to the client.\n"
] | [
2
] | [] | [] | [
"browser",
"cross_browser",
"javascript",
"python"
] | stackoverflow_0003954243_browser_cross_browser_javascript_python.txt |
Q:
When would we need a javascript client template engine?
Recently, I found out that jQuery has an official template engine which was contributed by the Microsoft team.
Also I had heard about jTemplate from my friends, but I'm still confused:
When & where might I need to use these plugins?
How should I choose betw... | When would we need a javascript client template engine? | Recently, I found out that jQuery has an official template engine which was contributed by the Microsoft team.
Also I had heard about jTemplate from my friends, but I'm still confused:
When & where might I need to use these plugins?
How should I choose between the many client side template engines?
| [
"The reason for a jQuery template engine is this: developers write Javascript code to create new chunks of HTML to inject into the page. This usually is done by concatenating many strings with variables for values, and it becomes difficult to maintain.\nWith a jQuery template engine, the process of creating HTML ... | [
1,
0,
0
] | [] | [] | [
"client_side",
"javascript",
"python",
"template_engine"
] | stackoverflow_0003954099_client_side_javascript_python_template_engine.txt |
Q:
Shuffle position of elements in a list
Possible Duplicate:
Shuffling a list of objects in python
IF I have a list:
a = ["a", "b", "c", ..., "zzz"]
how can I randomly shuffle its elements in order to obtain a list:
b = ["c", "zh", ...]
without consuming a lot of the system's resources?
A:
import random
b ... | Shuffle position of elements in a list |
Possible Duplicate:
Shuffling a list of objects in python
IF I have a list:
a = ["a", "b", "c", ..., "zzz"]
how can I randomly shuffle its elements in order to obtain a list:
b = ["c", "zh", ...]
without consuming a lot of the system's resources?
| [
"import random\nb = list(a)\nrandom.shuffle(b)\n\n",
"random.shuffle() shuffles a sequence in-place.\n",
"Not sure how much resources it consumes, but shuffle in the random module does exactly like this.\nimport random\na = [1,2,3,4,5]\nrandom.shuffle(a)\n\n"
] | [
9,
5,
2
] | [] | [] | [
"python"
] | stackoverflow_0003954321_python.txt |
Q:
How to serve up dynamic content via django and php on same domain?
I just finished rewriting a significant portion of my web site using python's django, but I also have some legacy code in php that I haven't finished migrating over yet. Is it possible to get these two working on the same domain and if so, how do I... | How to serve up dynamic content via django and php on same domain? | I just finished rewriting a significant portion of my web site using python's django, but I also have some legacy code in php that I haven't finished migrating over yet. Is it possible to get these two working on the same domain and if so, how do I go about doing it?
I'm running this site on a virtual Ubuntu instance a... | [
"Basically you have to configure apache to use the default handler for the path hosting your legacy code, usually adding a <directory> or <location> section to your apache site config.\nSomething like:\n<Location \"/legacy\">\n SetHandler None\n</Location>\n\n"
] | [
2
] | [] | [] | [
"apache",
"django",
"php",
"python"
] | stackoverflow_0003954467_apache_django_php_python.txt |
Q:
TkInter: how can I pass a numeric value to specify the color?
how can I assign a numeric value instead of a string to specify the color of my button ? What the exact syntax ?
button = tk.Button(itemFrame, text="", bg="red", width=10, command=callback)
i.e bg = #FF0000
thanks
A:
There are two general ways to s... | TkInter: how can I pass a numeric value to specify the color? | how can I assign a numeric value instead of a string to specify the color of my button ? What the exact syntax ?
button = tk.Button(itemFrame, text="", bg="red", width=10, command=callback)
i.e bg = #FF0000
thanks
| [
"There are two general ways to specify colors in Tkinter.\n\nYou can use a string specifying the proportion of red, green, and blue in hexadecimal digits.\nYou can also use any locally defined standard color name\n\n\n#rgb Four bits per color\n#rrggbb Eight bits per color\n#rrrgggbbb Twelve bits per color\n\nThe... | [
2
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0003954524_python_tkinter.txt |
Q:
Left hand side of assignment with infinite generators
Sorry to double my earlier question, but I thought to ask specific data which would solve the problem. I want this result
tuple_of_vars = (item for _, item for zip(tuple_of_vars, new_vals_generator))
as this is not possible
a, b, c, d = (val for val in infite_... | Left hand side of assignment with infinite generators | Sorry to double my earlier question, but I thought to ask specific data which would solve the problem. I want this result
tuple_of_vars = (item for _, item for zip(tuple_of_vars, new_vals_generator))
as this is not possible
a, b, c, d = (val for val in infite_generator)
actually then I want to do in single line
for v... | [
"When you know the var_list's length, you could use itertools.islice to cut off the infinite generator:\n>>> import itertools\n>>> infgen = itertools.cycle([1,4,9])\n>>> a,b,c,d = itertools.islice(infgen, 4)\n>>> a,b,c,d\n(1, 4, 9, 1)\n\nIt works for assignment to a slice of list too.\n>>> lst = [0]*20\n>>> lst[2:1... | [
1
] | [] | [] | [
"generator",
"infinite",
"lazy_evaluation",
"python"
] | stackoverflow_0003954564_generator_infinite_lazy_evaluation_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.