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:
Read version info from .ABR file (Photoshop brush set)
Is it possible to detect which Photoshop version a brush set (.abr) file is compatible with from its binary data?
There is a open source C# programm called ABRViewer but it doesn't read version info.
Sample brushes:
http://mark-s.deviantart.com/art/Fractal-Bru... | Read version info from .ABR file (Photoshop brush set) | Is it possible to detect which Photoshop version a brush set (.abr) file is compatible with from its binary data?
There is a open source C# programm called ABRViewer but it doesn't read version info.
Sample brushes:
http://mark-s.deviantart.com/art/Fractal-Brushes-Set-20484978
http://redheadstock.deviantart.com/art/Arc... | [
"If you are on Windows, you may have some luck using Python's win32com to interact with Photoshop programatically (a nice example). Perhaps you could try to load in an ABR file via this API.\nBased upon this forum post, it appears that there is a document \"Photoshop File Formats,\" which is included in the Advanc... | [
4
] | [] | [] | [
"binary",
"hex",
"photoshop",
"python"
] | stackoverflow_0001736396_binary_hex_photoshop_python.txt |
Q:
Python: data vs. text?
Guido van Rossum's presentation about Python 3000 mentions several things to make a transition from Python 2 to Python 3 easier eventually. He is specifically talking about text handling since the move to Unicode as the only representation of strings in Python 3 is one of the major changes.
... | Python: data vs. text? | Guido van Rossum's presentation about Python 3000 mentions several things to make a transition from Python 2 to Python 3 easier eventually. He is specifically talking about text handling since the move to Unicode as the only representation of strings in Python 3 is one of the major changes.
As far as text handling goes... | [
"In a nutshell, the way text and data is handled in Py3k may arguably be the most \"breaking\" change in the language. By knowing and avoiding,when possible, the situations where some Python 2.6 logic will work differently than in 3.x, we can facilitate the migration when it happens. Yet we should expect that some... | [
20,
2
] | [] | [] | [
"python",
"python_3.x",
"unicode"
] | stackoverflow_0001736228_python_python_3.x_unicode.txt |
Q:
Quitting matplotlib.pyplot animation gracefully
I have a script that plots data of some photometry apertures, and I want to plot them in an xy plot. I am using matplotlib.pyplot with python 2.5.
The input data is stored in around 500 files and read. I am aware that this is not the most efficient way of inputting t... | Quitting matplotlib.pyplot animation gracefully | I have a script that plots data of some photometry apertures, and I want to plot them in an xy plot. I am using matplotlib.pyplot with python 2.5.
The input data is stored in around 500 files and read. I am aware that this is not the most efficient way of inputting the data but that's another issue...
Example code:
imp... | [
"If you update the data and do the draw in a loop, you should be able to interrupt it. Here's an example (that draws a stationary circle and then moves a line around the perimeter):\nfrom pylab import *\nimport time\n\ndata = [] # make the data\nfor i in range(1000):\n a = .01*pi*i+.0007\n m = -1./tan(a)\n... | [
2
] | [] | [] | [
"animation",
"matplotlib",
"python",
"quit"
] | stackoverflow_0001735370_animation_matplotlib_python_quit.txt |
Q:
Python binary diff
I'm trying to use bsdiff (or any binary diff implementation you come up with) to compute and apply diff onto random binary data. I would like to use it on data from a database, so it would be better not to have to write those onto disk and pass them to bsdiff.exe.
Is there any wrapper library or... | Python binary diff | I'm trying to use bsdiff (or any binary diff implementation you come up with) to compute and apply diff onto random binary data. I would like to use it on data from a database, so it would be better not to have to write those onto disk and pass them to bsdiff.exe.
Is there any wrapper library or way in python to do tha... | [
"From the bsdiff website:\n\nIt has also been made into a Python extension module, and there is a Windows port available.\n\nFollowing the link brings you to the module's page.\n",
"You can use difflib that is part of Python standard library. You can send any arbitrary data into a difflib.SequenceMatcher.\n",
"... | [
5,
2,
1
] | [] | [] | [
"diff",
"python"
] | stackoverflow_0001736348_diff_python.txt |
Q:
Cannot run appengine-admin on dev_server
I've decided to try out this project:
http://code.google.com/p/appengine-admin/wiki/QuickStart
For the sake of the experiment, I took the demo guest-book shipped with App Engine. The import park look like this:
import cgi
import datetime
import wsgiref.handlers
from googl... | Cannot run appengine-admin on dev_server | I've decided to try out this project:
http://code.google.com/p/appengine-admin/wiki/QuickStart
For the sake of the experiment, I took the demo guest-book shipped with App Engine. The import park look like this:
import cgi
import datetime
import wsgiref.handlers
from google.appengine.ext import db
from google.appengin... | [
"You appear to be using Python 2.6 (given that some of the messages are from files in /usr/lib/python2.6 ...!), but Google App Engine needs Python 2.5 (any 2.5.x will do for any versions of x), so you should install and use that to run the App Engine SDK.\n",
"Google App Engine only supports Python 2.5, and you'r... | [
4,
3,
3,
2,
1,
1,
0,
0
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0000790001_google_app_engine_python.txt |
Q:
How to bundle tkinter?
I am distributing an app that uses the Python/C API. I have all standard python modules in python31.zip which is basically an archive of the Lib folder in the python install directory. Here is the problem - most common modules like sys and io work fine. BUT tkinter does not. I get an error "... | How to bundle tkinter? | I am distributing an app that uses the Python/C API. I have all standard python modules in python31.zip which is basically an archive of the Lib folder in the python install directory. Here is the problem - most common modules like sys and io work fine. BUT tkinter does not. I get an error "cannot find module _tkinter"... | [
"why don't you use py2exe to bundle your application as an executable? It should take care of all the dependencies, and will include whatever you need.\n",
"I don't the best way to bundle tkinter with your app, but I do know why you're getting the error you are. The relevant section of the zipimport module docume... | [
1,
1
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0001736742_python_tkinter.txt |
Q:
Programatically saving an image to a Django ImageField is creating an infinite loop of images
I've got a save method on a model that looks like so:
def save(self, force_insert=False, force_update=False):
img_url = "http://example.com/%s.jpg" % (self.title)
name = urlparse(img_url).path.split('/')[-1]
c... | Programatically saving an image to a Django ImageField is creating an infinite loop of images | I've got a save method on a model that looks like so:
def save(self, force_insert=False, force_update=False):
img_url = "http://example.com/%s.jpg" % (self.title)
name = urlparse(img_url).path.split('/')[-1]
content = urllib.urlretrieve(img_url)
self.image.save(name, File(open(content[0])), save=True)
... | [
"I think from a browse through the source code that calling ImageFileField.save() (actually FileField.save() due to inheritance) causes the instance (namely the db row) that the file name is stored in to be updated.\nThis means that in your save method you call ImageFileField.save() which in turn calls your save me... | [
5,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0001736550_django_python.txt |
Q:
How Can I Make This Python Code More Usable And Readable?
Beginner in python, but been programming for about 5 years now. I suspect I have a lot to learn about doing things the object oriented way, but I know the basics. I planned on programming a calculator that shows it's work for the challenge and knowledge i'l... | How Can I Make This Python Code More Usable And Readable? | Beginner in python, but been programming for about 5 years now. I suspect I have a lot to learn about doing things the object oriented way, but I know the basics. I planned on programming a calculator that shows it's work for the challenge and knowledge i'll gain from it. I just started and this is what i've got, and i... | [
"Some problems:\ncontents = re.match(\"(\\(.*\\))\", problem)\n\nWhen it's given the input (1+2)/(3+4), it's going to try to evaluate 1+2)/(3+4.\nIt also doesn't go all the way into nested parentheses, for this you would need to use recursion.\nI think you should make another attempt at this before you \"look at th... | [
5,
2,
2,
0
] | [] | [] | [
"oop",
"python",
"readability",
"usability"
] | stackoverflow_0001737013_oop_python_readability_usability.txt |
Q:
Tree view GUI widget/gui library that can do multiple icons?
Screenshot
I'm looking to recreate this in Python; I can't find a library that seems to have what I need. Are there any GUI libraries that might possibly have this? - I have scoured wxWidgets (which is my preferred gui library) but they have nothing sim... | Tree view GUI widget/gui library that can do multiple icons? | Screenshot
I'm looking to recreate this in Python; I can't find a library that seems to have what I need. Are there any GUI libraries that might possibly have this? - I have scoured wxWidgets (which is my preferred gui library) but they have nothing similar.
I have a script already that uses a standard wxTreeCtrl but ... | [
"you have few options\n\nUse wx.lib.customtreectrl.CustomTreeCtrl\nAppendItem of CustomTreeCtrl can take any wx widget, which is shown at end, so you can use that to affect e.g. tree.AppendItem(root, \"item1\", wnd=yourImageControl)\nUse wx.gizmos.TreeListCtrl, you can have icons in separate columns and tree in fir... | [
2,
0
] | [] | [] | [
"python",
"user_interface",
"wxpython"
] | stackoverflow_0001736917_python_user_interface_wxpython.txt |
Q:
Why is wx.SingleChoiceDialog not subclassing properly
I'm trying to subclass the wxpython SingleChoiceDialog class. I have a TableChoiceDialog class that inherits from SingleChoiceDialog adding generic functionality, and I have 2 sub classes for that add more refined functionality. Basically I'm O.O.P'ing
In my ... | Why is wx.SingleChoiceDialog not subclassing properly | I'm trying to subclass the wxpython SingleChoiceDialog class. I have a TableChoiceDialog class that inherits from SingleChoiceDialog adding generic functionality, and I have 2 sub classes for that add more refined functionality. Basically I'm O.O.P'ing
In my TableChoiceDialog class I have a line which calls the super... | [
"\nThe call to __init__ seems alright (the first argument to __init__ is always self).\nYou might have a wrong build of wx. The swig's warning message indicates that there is no desctructor was generated for wxSingleChoiceDialog, see this memory leak discussion.\n\nThe message may be unrelated to the __init__ call.... | [
0,
0
] | [] | [] | [
"oop",
"python",
"subclass",
"wxpython"
] | stackoverflow_0000655662_oop_python_subclass_wxpython.txt |
Q:
SQLAlchemy 0.5.5 - defining table schema
I used sqlautocode to generate a model.py for an existing MySQL database and here's a table example:
fusion_articles = Table('fusion_articles', metadata,
Column(u'article_id', Integer(), primary_key=True, nullable=False),
Column(u'article_cat', Integer(), p... | SQLAlchemy 0.5.5 - defining table schema | I used sqlautocode to generate a model.py for an existing MySQL database and here's a table example:
fusion_articles = Table('fusion_articles', metadata,
Column(u'article_id', Integer(), primary_key=True, nullable=False),
Column(u'article_cat', Integer(), primary_key=False, nullable=False),
... | [
"It's largely a style preference, but also depends on how complex your code is.\nIf you're writing a short, isolated script that will likely not be imported elsewhere, bringing lots of names into your namespace (i.e. Table, Column) isn't a problem and makes the code easier to read.\nIf, on the other hand, you expec... | [
1
] | [] | [] | [
"python",
"sqlalchemy"
] | stackoverflow_0001737351_python_sqlalchemy.txt |
Q:
File open error by using codec utf-8 in python
I execute following code on windows xp and python 2.6.4
But it show IOError.
How to open file whose name has utf-8 codec.
>>> open( unicode('한글.txt', 'euc-kr').encode('utf-8') )
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
open( un... | File open error by using codec utf-8 in python | I execute following code on windows xp and python 2.6.4
But it show IOError.
How to open file whose name has utf-8 codec.
>>> open( unicode('한글.txt', 'euc-kr').encode('utf-8') )
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
open( unicode('한글.txt', 'euc-kr').encode('utf-8') )
IOError:... | [
"The C runtime interface that Windows exposes to Python uses the system code page to encode filenames. Unlike on OS X and modern Linux versions, on Windows the system code page is never UTF-8. So the UTF-8 byte string won't be any good.\nYou could encode the filename to the current code page using .encode('mbcs'), ... | [
17
] | [] | [] | [
"python",
"unicode",
"utf_8"
] | stackoverflow_0001737410_python_unicode_utf_8.txt |
Q:
How do I make powerpoint play presentations/load up ppts automatically?
I was wondering how I can make a script load powerpoint file, advance slides automatically and put it on full screen. Is there a way to make windows do that? Can I just load powerpoint.exe and maybe use some sort of API/Pipe to give commands f... | How do I make powerpoint play presentations/load up ppts automatically? | I was wondering how I can make a script load powerpoint file, advance slides automatically and put it on full screen. Is there a way to make windows do that? Can I just load powerpoint.exe and maybe use some sort of API/Pipe to give commands from another script.
To make a case: I'm making a script that automatically sc... | [
"One solution for you would be to use the PowerPoint Viewer program instead. PPT Viewer is set to open a PowerPoint file straight away in Presentation mode.\nAlternatively, you can use the argument /s to start Powerpoint.\n\"powerpoint.exe /s <filename>.ppt\"\n\nThis will be equivalent to telling PowerPoint to stra... | [
3,
1,
1,
0
] | [] | [] | [
"powerpoint",
"python"
] | stackoverflow_0001635565_powerpoint_python.txt |
Q:
Manipulate screen buffer in python
I know this is a long shot, but I was wondering if Python had a way to manipulate the screen buffer. Specifically, I want to be able to gray-out my desktop and highlight my windows when I press a key combination. Is this in the realm of possibility?
A:
From your question and th... | Manipulate screen buffer in python | I know this is a long shot, but I was wondering if Python had a way to manipulate the screen buffer. Specifically, I want to be able to gray-out my desktop and highlight my windows when I press a key combination. Is this in the realm of possibility?
| [
"From your question and the comments that followed, PyQt would be a good choice, you would have a common code for the three platforms.\nYou have to develop it as a GUI though, using the library functions, it also means you will have to rethink what you exactly want in terms of GUI possibilities, and in a way that r... | [
2,
2
] | [] | [] | [
"buffer",
"python",
"screen"
] | stackoverflow_0001734575_buffer_python_screen.txt |
Q:
What is this construct called in python: ( x, y )
What is this called in python:
[('/', MainPage)]
Is that an array .. of ... erhm one dictionary?
Is that
()
A tuple? ( or whatever they call it? )
A:
Its a list with a single tuple.
A:
Since no one has answered this bit yet:
A tuple? ( or whatever they cal... | What is this construct called in python: ( x, y ) | What is this called in python:
[('/', MainPage)]
Is that an array .. of ... erhm one dictionary?
Is that
()
A tuple? ( or whatever they call it? )
| [
"Its a list with a single tuple.\n",
"Since no one has answered this bit yet:\n\nA tuple? ( or whatever they call it? ) \n\nThe word \"tuple\" comes from maths. In maths, we might talk about (ordered) pairs, if we're doing 2d geometry. Moving to three dimensions means we need triples. In higher dimensions, we ... | [
13,
6,
3,
2,
1,
1,
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0001313805_python.txt |
Q:
Set Django model field with a method
I'm trying to set title_for_url but it shows up in my database as "<property object at 0x027427E0>". What am I doing wrong?
from django.db import models
class Entry(models.Model):
def _get_title_for_url(self):
title = "%s" % self.get_title_in_url_format()
... | Set Django model field with a method | I'm trying to set title_for_url but it shows up in my database as "<property object at 0x027427E0>". What am I doing wrong?
from django.db import models
class Entry(models.Model):
def _get_title_for_url(self):
title = "%s" % self.get_title_in_url_format()
return title
AUTHOR_CHOICES = (('001'... | [
"title_for_url = models.CharField(max_length=100, editable=False, default=property(_get_title_for_url)\n\nYou couldn't do that way.. 'default' should be a value or a calable(with no args)... (property is not calable)\nIn your case you need to update a save method:\nclass Entry(models.Model):\n def save(self, *ar... | [
3,
0,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0001735240_django_python.txt |
Q:
Loading a simple Qt Designer form in to Pyside
I create a simple form in Qt designer and am trying to load it in to a Qt application I'm creating with PySide but without much luck.
Here's the generated code from `pyside-uic':
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'clientEdit... | Loading a simple Qt Designer form in to Pyside | I create a simple form in Qt designer and am trying to load it in to a Qt application I'm creating with PySide but without much luck.
Here's the generated code from `pyside-uic':
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'clientEditorForm.ui'
#
# Created: Tue Nov 3 23:46:41 2009
# ... | [
"Turns out there is a bug in PySide with the QSpacerItem class. Commenting out the QSpacerItem instances in the code above makes it work just fine. There's a bug report on the PySide bugzilla.\n",
"Firstly you are using PySide(Nokia) not PyQt4(Riverbank Computing), although their API's are nearly identical they a... | [
5,
4
] | [] | [] | [
"pyside",
"python",
"qt4"
] | stackoverflow_0001672271_pyside_python_qt4.txt |
Q:
Boost::Python Windows 7 64 Bit
I can't seem to build boost::python correctly on my Windows 7 64Bit machine. It's vanilla 32bit python 2.6.4 in the c:\Python26 directory.
Pastebin is here of the debug build output : http://pastebin.com/m7d70f13e
Cheers,
Al
A:
On IRC, we have found the following procedure fixes ... | Boost::Python Windows 7 64 Bit | I can't seem to build boost::python correctly on my Windows 7 64Bit machine. It's vanilla 32bit python 2.6.4 in the c:\Python26 directory.
Pastebin is here of the debug build output : http://pastebin.com/m7d70f13e
Cheers,
Al
| [
"On IRC, we have found the following procedure fixes the problem:\n\nOpen tools/build/v2/tools/python.jam\nThere, locate the following code:\nif [ version.check-jam-version 3 1 17 ] || ( [ os.name ] != NT )\n{\n # Prior to version 3.1.17 Boost Jam's SHELL command did not support\n # quoted commands correctly ... | [
6
] | [] | [] | [
"64_bit",
"boost",
"python",
"windows_7"
] | stackoverflow_0001704046_64_bit_boost_python_windows_7.txt |
Q:
How should I create a web interface for my application?
First, a little background: I have written a little application in python with SQLAlchemy, which is roughly an improved RSS reader: it selects links that should interest the user, and shows them to him. I already have a very simple command-line interface, and... | How should I create a web interface for my application? | First, a little background: I have written a little application in python with SQLAlchemy, which is roughly an improved RSS reader: it selects links that should interest the user, and shows them to him. I already have a very simple command-line interface, and I envision a variety of interfaces: web, instant-messaging, ... | [
"I recommend that you use some kind of web framework, it will make things a lot easier. Since you already know Python you should look into Django framework. It seems that you can use SQLAlchemy with Django, see djange-sqlalchemy project.\nI recommend using JQuery framework/library for Javascript stuff. It greatly s... | [
6,
5,
3,
1,
1,
1,
1
] | [] | [] | [
"css",
"javascript",
"python"
] | stackoverflow_0001737514_css_javascript_python.txt |
Q:
Dict has key from list
How can I determine if any of the list elements are a key to a dict?
The straight forward way is,
for i in myList:
if i in myDict:
return True
return False
but is there a faster / more concise way?
A:
#!python
any(x in MyDict for x in MyList)
set(MyList).intersection(MyDict)
A:
... | Dict has key from list | How can I determine if any of the list elements are a key to a dict?
The straight forward way is,
for i in myList:
if i in myDict:
return True
return False
but is there a faster / more concise way?
| [
"#!python\nany(x in MyDict for x in MyList)\nset(MyList).intersection(MyDict)\n\n",
"In addition to any(item in my_dict for item in my_list) from @Ronny's answer:\nany(map(my_dict.__contains__, my_list)) # Python 3.x\n\nOr:\nfrom itertools import imap\nany(imap(my_dict.__contains__, my_list)) # Python 2.x\n\nMeas... | [
20,
6,
2,
1,
1
] | [] | [] | [
"dictionary",
"list",
"python"
] | stackoverflow_0001737778_dictionary_list_python.txt |
Q:
What's wrong with this program?
def short_distance(origins,(x,y),gap):
for (i,j) in origins.spilt(“ ”):
h=[]
h.append(float(math.sqrt ((i-x)*(i-x)+(j-y)*(j-y))))
for n in h:
if not gap < n:
print 0
if gap < n :
print n
A:
I would write the code more like this. If you run the code, it will report any faili... | What's wrong with this program? | def short_distance(origins,(x,y),gap):
for (i,j) in origins.spilt(“ ”):
h=[]
h.append(float(math.sqrt ((i-x)*(i-x)+(j-y)*(j-y))))
for n in h:
if not gap < n:
print 0
if gap < n :
print n
| [
"I would write the code more like this. If you run the code, it will report any failing tests (of which there are none).\nimport math\n\ndef short_distance(origins, point, gap):\n \"\"\"\n Describe origins, point, and gap are and what the \n expected outcome is.\n\n Then provide an example that tests th... | [
4,
2,
2,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0001737072_python.txt |
Q:
Django: debugging entries just disapearing
So, I'm pulling my hair out here, and maybe someone has an insight.
I have a cronjob that loops over all my Link objects, does some stuff, might change properties on the object and does a save(). That's it.
Every so often (around once an hour), one of my rows just disappe... | Django: debugging entries just disapearing | So, I'm pulling my hair out here, and maybe someone has an insight.
I have a cronjob that loops over all my Link objects, does some stuff, might change properties on the object and does a save(). That's it.
Every so often (around once an hour), one of my rows just disappears. Poof. Nothing in the logs.
So, I'm trying ... | [
"You could override the delete method on your Link class and dump a stack trace or log a message to see if it's indeed happening from within your Django application.\nimport sys, traceback\n\ndef delete(self):\n super(Link, self).delete()\n\n try:\n assert False\n except AssertionError, e\n tracebac... | [
2,
1
] | [] | [] | [
"debugging",
"django",
"python"
] | stackoverflow_0001737424_debugging_django_python.txt |
Q:
Including package data with Distribute
I'm trying to use Distribute for my project's setup.py. I want it to include all the files in the package folder, which are text and image files, but not .pyc files of course. I read that the files should either be tracked by CVS and SVN, or there should be a MAINFEST.in.
So:... | Including package data with Distribute | I'm trying to use Distribute for my project's setup.py. I want it to include all the files in the package folder, which are text and image files, but not .pyc files of course. I read that the files should either be tracked by CVS and SVN, or there should be a MAINFEST.in.
So:
I use neither CVS nor SVN, I use git. I kn... | [
"I've change that behavior in Distutils (in Python trunk (2.7/3.2) ) \nNow all files mentioned in package_data will be included by default without having to \nwrite a MANIFEST.in file, and without having to use the magic behavior based on DVCS.\nUntil then, I would recommend using an explicit MANIFEST.in and stick ... | [
5,
0
] | [] | [] | [
"distribute",
"distribution",
"python",
"setuptools"
] | stackoverflow_0001734373_distribute_distribution_python_setuptools.txt |
Q:
Using pyparsing to parse a word escape-split over multiple lines
I'm trying to parse words which can be broken up over multiple lines with a backslash-newline combination ("\\n") using pyparsing. Here's what I have done:
from pyparsing import *
continued_ending = Literal('\\') + lineEnd
word = Word(alphas)
split_... | Using pyparsing to parse a word escape-split over multiple lines | I'm trying to parse words which can be broken up over multiple lines with a backslash-newline combination ("\\n") using pyparsing. Here's what I have done:
from pyparsing import *
continued_ending = Literal('\\') + lineEnd
word = Word(alphas)
split_word = word + Suppress(continued_ending)
multi_line_word = Forward()
m... | [
"After poking around for a bit more, I came upon this help thread where there was this notable bit\n\nI often see inefficient grammars when\n someone implements a pyparsing grammar\n directly from a BNF definition. BNF\n does not have a concept of \"one or\n more\" or \"zero or more\" or\n \"optional\"...\n\nW... | [
6,
5
] | [] | [] | [
"parsing",
"pyparsing",
"python"
] | stackoverflow_0001735722_parsing_pyparsing_python.txt |
Q:
How do I enforce a UTF8 encoding on a generated CSV report?
How do I enforce a UTF8 encoding on a generated CSV report in web2py?
A:
Use the str.encode function together with the csv module, there is a complete example that will show you that in the Python documentation (or in the link given in comment to your q... | How do I enforce a UTF8 encoding on a generated CSV report? | How do I enforce a UTF8 encoding on a generated CSV report in web2py?
| [
"Use the str.encode function together with the csv module, there is a complete example that will show you that in the Python documentation (or in the link given in comment to your question). Quick example:\nrow = [\"one\", \"two\", \"three\"]\n\nimport csv\nwith open(\"report.csv\", \"wb\") as f:\n writer = csv.... | [
2
] | [] | [] | [
"python",
"web2py"
] | stackoverflow_0001737178_python_web2py.txt |
Q:
wxPython: How should I organize per-widget data in the controller?
I have a widget that displays a filesystem hierarchy for convenient browsing (basically a tree control and some associated toolbar buttons, such as "refresh"). Each of these widgets has a set of base directories for it to display (recursively). Ass... | wxPython: How should I organize per-widget data in the controller? | I have a widget that displays a filesystem hierarchy for convenient browsing (basically a tree control and some associated toolbar buttons, such as "refresh"). Each of these widgets has a set of base directories for it to display (recursively). Assume that the user may instantiate as many of these widgets as they find ... | [
"The anomaly (from the MVC viewpoint) that makes this design difficult to make MVC-conformant is that you want to display information that, by your conceptualization, \"does not live in a model\". There is no such thing as \"information that does not live in a model\" in MVC: its conceptual root is \"the models ho... | [
2,
1,
0
] | [] | [] | [
"model_view_controller",
"python",
"user_interface"
] | stackoverflow_0001686235_model_view_controller_python_user_interface.txt |
Q:
change 2 byte in a string
I'd like to change 2 byte in a string like this:
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
Let's imagine I want to replace 'RS' by 11, I know how to do it with one byte like [:], but for 2 or more in the middle of the string ?
Thanks !
A:
Strings are immutable, you can't change them. You have to ma... | change 2 byte in a string | I'd like to change 2 byte in a string like this:
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
Let's imagine I want to replace 'RS' by 11, I know how to do it with one byte like [:], but for 2 or more in the middle of the string ?
Thanks !
| [
"Strings are immutable, you can't change them. You have to make a new string from parts of the old one:\n>>> az= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'\n>>> az= az[:17]+'11'+az[19:]\n>>> az\n'ABCDEFGHIJKLMNOPQ11TUVWXYZ'\n\nalthough depending one what you're doing there may be a more appropriate way of handling it than relyin... | [
4,
1,
0
] | [] | [] | [
"python",
"string"
] | stackoverflow_0001737782_python_string.txt |
Q:
Count the number of occurences of letters in a Python string
So I got a DNA sequence.
ACCAGAGCGGCACAGCAGCGACATCAGCACTAGCACTAGCATCAGCATCAGCATCAGC
CTACATCATCACAGCAGCATCAGCATCGACATCAGCATCAGCATCAGCATCGACGACT
ACACCCCCCCCGGTGTGTGTGGGGGGTTAAAAATGATGAGTGATGAGTGAGTTGTGTG
CTACATCATCACAGCAGCATCAGCATCGACATCAGCATCAGCATCAGCATCG... | Count the number of occurences of letters in a Python string | So I got a DNA sequence.
ACCAGAGCGGCACAGCAGCGACATCAGCACTAGCACTAGCATCAGCATCAGCATCAGC
CTACATCATCACAGCAGCATCAGCATCGACATCAGCATCAGCATCAGCATCGACGACT
ACACCCCCCCCGGTGTGTGTGGGGGGTTAAAAATGATGAGTGATGAGTGAGTTGTGTG
CTACATCATCACAGCAGCATCAGCATCGACATCAGCATCAGCATCAGCATCGACGACT
TTCTATCATCATTCGGCGGGGGGATATATTATAGCGCGCGATTATTGCGCAGTCTACG
... | [
"for base in 'ACGT':\n print base, thesequence.count(base) + thesequence.count(base.lower())\n\n"
] | [
7
] | [] | [] | [
"python",
"string"
] | stackoverflow_0001738452_python_string.txt |
Q:
Python: how to make two lists from a dictionary
I have a dictionary.
{1 : [1.2, 2.3, 4.9, 2.0], 2 : [4.1, 5.1, 6.3], 3 : [4.9, 6.8, 9.5, 1.1, 7.1]}
I want to pass each key:value pair to an instance of matplotlib.pyplot as two lists: x values and y values.
Each key is an x value associated with each item in its ... | Python: how to make two lists from a dictionary | I have a dictionary.
{1 : [1.2, 2.3, 4.9, 2.0], 2 : [4.1, 5.1, 6.3], 3 : [4.9, 6.8, 9.5, 1.1, 7.1]}
I want to pass each key:value pair to an instance of matplotlib.pyplot as two lists: x values and y values.
Each key is an x value associated with each item in its value.
So I want two lists for each key:
[1,1,1,1] [1... | [
"for k, v in dictionary.iteritems():\n x = [k] * len(v)\n y = v\n pyplot.plot(x, y)\n\n",
"d = {1 : [1.2, 2.3, 4.9, 2.0], 2 : [4.1, 5.1, 6.3], 3 : [4.9, 6.8, 9.5, 1.1, 7.1]}\n\nres = [([x]*len(y), y) for x, y in d.iteritems()]\n\nres will be a list of tuples, where the first element in the tuple is your ... | [
13,
3,
2,
2,
2,
1,
0
] | [
"the map function in python will allow this\nx = [1,2,4]\ny = [1,24,2]\nc = zip(x,y)\nprint c\nd = map(None,x,y)\nprint d\n\ncheck it out. This will give you\n[(1, 1), (2, 24), (4, 2)]\n\nIn the case of zip(), if one of the lists are smaller then the others, values will be truncated:\nx = [1,2,4]\na = [1,2,3,4,5]\n... | [
-1
] | [
"python"
] | stackoverflow_0001738392_python.txt |
Q:
help!for function
I have post the similar question before,but this time the problem is different,I got stuck with the following code..can anyone help with it?thanks in advance
I have fixed mu code as suggested,thanks
from numpy import *
#vs,fs,rs are all m*n matrixs,got initial values in,i.e vs[0],fs[0],rs[0] are ... | help!for function | I have post the similar question before,but this time the problem is different,I got stuck with the following code..can anyone help with it?thanks in advance
I have fixed mu code as suggested,thanks
from numpy import *
#vs,fs,rs are all m*n matrixs,got initial values in,i.e vs[0],fs[0],rs[0] are known
#want use this fo... | [
"Put your inizialization outside the loop! Right now, you're resetting the arrays to all zeros each time through the loop, over and over, which is absurd. You also appear to have a typo -- you set vs twice and rs never -- so I've tried to guess what you meant.\nfrom numpy import *\n\n#vs,fs,rs are all m*n matrixs... | [
2,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0001738362_python.txt |
Q:
How to read this file using Python?
I have a DNA file in the following format:
>gi|5524211|gb|AAD44166.1| cytochrome
ACCAGAGCGGCACAGCAGCGACATCAGCACTAGCACTAGCATCAGCATCAGCATCAGC
CTACATCATCACAGCAGCATCAGCATCGACATCAGCATCAGCATCAGCATCGACGACT
ACACCCCCCCCGGTGTGTGTGGGGGGTTAAAAATGATGAGTGATGAGTGAGTTGTGTG
CTACATCATCACAGCAGCATC... | How to read this file using Python? | I have a DNA file in the following format:
>gi|5524211|gb|AAD44166.1| cytochrome
ACCAGAGCGGCACAGCAGCGACATCAGCACTAGCACTAGCATCAGCATCAGCATCAGC
CTACATCATCACAGCAGCATCAGCATCGACATCAGCATCAGCATCAGCATCGACGACT
ACACCCCCCCCGGTGTGTGTGGGGGGTTAAAAATGATGAGTGATGAGTGAGTTGTGTG
CTACATCATCACAGCAGCATCAGCATCGACATCAGCATCAGCATCAGCATCGACGACT
TTC... | [
"If there's always only one line of header :\ndnalines = text.split('\\n')[1:]\ndna = ''.join(dnalines)\n\nWith text = the contents of your file (for example, text = open('yourfile').read())\n",
"I did some tests, and it appears that the following is more efficient than delroth's answer:\ntext.split('\\n', 1)[1].... | [
8,
3
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0001738524_python_regex.txt |
Q:
Algorithm to Divide a list of numbers into 2 equal sum lists
There is a list of numbers.
The list is to be divided into 2 equal sized lists, with a minimal difference in sum. The sums have to be printed.
#Example:
>>>que = [2,3,10,5,8,9,7,3,5,2]
>>>make_teams(que)
27 27
Is there an error in the following code alg... | Algorithm to Divide a list of numbers into 2 equal sum lists |
There is a list of numbers.
The list is to be divided into 2 equal sized lists, with a minimal difference in sum. The sums have to be printed.
#Example:
>>>que = [2,3,10,5,8,9,7,3,5,2]
>>>make_teams(que)
27 27
Is there an error in the following code algorithm for some case?
How do I optimize and/or pythonize this?
d... | [
"Dynamic programming is the solution you're looking for.\nExample with [4, 3, 10, 3, 2, 5]:\n\nX-Axis: Reachable sum of group. max = sum(all numbers) / 2 (rounded up)\nY-Axis: Count elements in group. max = count numbers / 2 (rounded up)\n\n 1 2 3 4 5 6 7 8 9 10 11 12 13 14\n 1 |... | [
35,
6,
4,
2,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0
] | [] | [] | [
"algorithm",
"dynamic_programming",
"knapsack_problem",
"np_complete",
"python"
] | stackoverflow_0000890171_algorithm_dynamic_programming_knapsack_problem_np_complete_python.txt |
Q:
How does the Python's range function work?
If I write
for i in range(5):
print i
Then it gives 0, 1, 2, 3, 4
Does that mean Python assigned 0, 1, 2, 3, 4 to i at the same time?
However if I wrote:
for i in range(5):
a=i+1
Then I call a, it only gives 5
But if I add ''print a'' it gives 1, 2, 3, 4, 5
... | How does the Python's range function work? | If I write
for i in range(5):
print i
Then it gives 0, 1, 2, 3, 4
Does that mean Python assigned 0, 1, 2, 3, 4 to i at the same time?
However if I wrote:
for i in range(5):
a=i+1
Then I call a, it only gives 5
But if I add ''print a'' it gives 1, 2, 3, 4, 5
So my question is what is the difference here?
I... | [
"A \"for loop\" in most, if not all, programming languages is a mechanism to run a piece of code more than once.\nThis code:\nfor i in range(5):\n print i\n\ncan be thought of working like this:\ni = 0\nprint i\ni = 1\nprint i\ni = 2\nprint i\ni = 3\nprint i\ni = 4\nprint i\n\nSo you see, what happens is not tha... | [
52,
22,
7,
6,
0,
0
] | [] | [] | [
"for_loop",
"python",
"range"
] | stackoverflow_0001738109_for_loop_python_range.txt |
Q:
Python and iPhone development on Mac - minimum/recommended hardware?
What is the minimum configuration to do some Python and iPhone development on Mac ?
Platform wise: Mac Mini, Mac Pro, Mac Book, Mac Book Pro ?
Memory requirement
CPU speed
Thanks for your advice.
Laurent
A:
Any of those platforms are going to... | Python and iPhone development on Mac - minimum/recommended hardware? | What is the minimum configuration to do some Python and iPhone development on Mac ?
Platform wise: Mac Mini, Mac Pro, Mac Book, Mac Book Pro ?
Memory requirement
CPU speed
Thanks for your advice.
Laurent
| [
"Any of those platforms are going to be more than adequate for iPhone development, but since Apple is not allowing anything that requires a VM or an interpreted environment, there is no way to do iPhone development using Python at this time.\nEDIT: Looks like I misread that as doing Python development on an iPhone,... | [
4,
4,
1,
1
] | [] | [] | [
"iphone",
"macos",
"python"
] | stackoverflow_0001738845_iphone_macos_python.txt |
Q:
How to tell whether a file is executable on Windows in Python?
I'm writing grepath utility that finds executables in %PATH% that match a pattern.
I need to define whether given filename in the path is executable (emphasis is on command line scripts).
Based on "Tell if a file is executable" I've got:
import os
from... | How to tell whether a file is executable on Windows in Python? | I'm writing grepath utility that finds executables in %PATH% that match a pattern.
I need to define whether given filename in the path is executable (emphasis is on command line scripts).
Based on "Tell if a file is executable" I've got:
import os
from pywintypes import error
from win32api import FindExecutable, GetL... | [
"shoosh beat me to it :)\nIf I remember correctly, you should try to read the first 2 characters in the file. If you get back \"MZ\", you have an exe.\n\nhnd = open(file,\"rb\")\nif hnd.read(2) == \"MZ\":\n print \"exe\"\n\n",
"I think, that this should be sufficient:\n\ncheck file extension in PATHEXT - whether... | [
3,
3,
2,
1,
0
] | [
"Your question can't be answered. Windows can't tell the difference between a file which is associated with a scripting language vs. some other arbitrary program. As Windows is concerned, a .PY file is simply a document which is opened by python.exe.\n"
] | [
-1
] | [
"c++",
"python",
"winapi",
"windows"
] | stackoverflow_0000646955_c++_python_winapi_windows.txt |
Q:
Python: Architecture for url polling and posting
I have a simple problem. I have to fetch a url (about once a minute), check if there is any new content, and if there is, post it to another url.
I have a working system with a cronjob every minute that basically:
for link in models.Link.objects.filter(enabled=True)... | Python: Architecture for url polling and posting | I have a simple problem. I have to fetch a url (about once a minute), check if there is any new content, and if there is, post it to another url.
I have a working system with a cronjob every minute that basically:
for link in models.Link.objects.filter(enabled=True).select_related():
# do it in two phases in case t... | [
"Simplest: use a long-running process with sched (on its own thread) to handle the scheduling -- by posting requests to a Queue; have a fixed-size pool of threads (you can find a pre-made thread pool here, but it's easy to tweak it or roll your own) taking requests from the Queue (and returning results via a separa... | [
2
] | [] | [] | [
"architecture",
"concurrency",
"python"
] | stackoverflow_0001739185_architecture_concurrency_python.txt |
Q:
What is a good option for a Non-Blocking "Database" (Using a TCP Socket Server)
In short I'm creating a socket server so I can add multiplayer support to my Flash game (Using Actionscript 3.0 Binary Socket on the Client-End).
I decided to go with Python since I'm the sole developer of the game/server and this will... | What is a good option for a Non-Blocking "Database" (Using a TCP Socket Server) | In short I'm creating a socket server so I can add multiplayer support to my Flash game (Using Actionscript 3.0 Binary Socket on the Client-End).
I decided to go with Python since I'm the sole developer of the game/server and this will be my first non-blocking socket server. I was going to use Twisted but I deiced tha... | [
"I suggest you use any DB you like (sqlite comes with Python and will probably serve you well!): just have a dedicated thread that accesses said DB, taking requests from a Queue (and using another Queue, passed in as part of the request, to return results if needed). Threads aren't so bad if you have a small number... | [
6,
1
] | [] | [] | [
"database",
"python",
"sockets"
] | stackoverflow_0001739100_database_python_sockets.txt |
Q:
Allow / in django url
I want to make a wiki, and i must assign for each url a view. Each url can contain letters (A-Z, a-z), digits and punctuation ('.', ',', '/', '-', '_'). How can I make the expression ?
I want something like this :
(r'^(?P<wiki_page>\w+)/$', 'www.wiki.views.page')
but this works only for lett... | Allow / in django url | I want to make a wiki, and i must assign for each url a view. Each url can contain letters (A-Z, a-z), digits and punctuation ('.', ',', '/', '-', '_'). How can I make the expression ?
I want something like this :
(r'^(?P<wiki_page>\w+)/$', 'www.wiki.views.page')
but this works only for letters, digits and '_'.
| [
"Try this regexp:\nr'^(?P<wiki_page>[\\w.,/_\\-]+)/$'\n\n",
"You could replace \\w in the regex with a regex to match what you're looking for. Perhaps\n(r'^(?P<wiki_page>[A-Za-z_/,\\.-]+)$, 'www.wiki.views.page')\n\nor similar.\n",
"I think it's more of a regex question\nr'^(?P<wiki_page>[\\w\\.,_/\\-]+)/$'\n\... | [
4,
1,
0
] | [] | [] | [
"django",
"python",
"regex",
"url"
] | stackoverflow_0001739431_django_python_regex_url.txt |
Q:
Underscore _ as variable name in Python
Peter Norvig has an essay describing a program to solve sudoku puzzles, even the hardest ones, by combining deterministic logical operations and smart traversal of the possible solutions. The latter is done recursively; here's that function (source):
def search(values):
... | Underscore _ as variable name in Python | Peter Norvig has an essay describing a program to solve sudoku puzzles, even the hardest ones, by combining deterministic logical operations and smart traversal of the possible solutions. The latter is done recursively; here's that function (source):
def search(values):
"Using depth-first search and propagation, t... | [
"Yep, _ is a traditional name for \"don't care\" (which unfortunately clashes with its use in I18N, but that's a separate issue;-). BTW, in today's Python, instead of:\n_,s = min( (len( values[s]), s) \n for s in squares \n if len(values[s]) > 1\n )\n\nyou might code\ns = min((s for s ... | [
76,
13,
9
] | [] | [] | [
"metasyntactic_variable",
"naming_conventions",
"python",
"variables"
] | stackoverflow_0001739514_metasyntactic_variable_naming_conventions_python_variables.txt |
Q:
How to translate python tuple unpacking to Matlab?
I am translating some python code to Matlab, and want to figure out what the best way to translate the python tuple unpacking to Matlab is.
For the purposes of this example, a Body is a class whose constructor takes as input two functionals.
I have the following p... | How to translate python tuple unpacking to Matlab? | I am translating some python code to Matlab, and want to figure out what the best way to translate the python tuple unpacking to Matlab is.
For the purposes of this example, a Body is a class whose constructor takes as input two functionals.
I have the following python code:
X1 = lambda t: cos(t)
Y1 = lambda t: sin(t)
... | [
"Without knowing what Body is, this is my solution:\nbodies = cellfun(@(tuple)Body(tuple{1},tuple{2}), coords);\n\nor, if the output has to encapsulated in a cell array:\nbodies = cellfun(@(tuple)Body(tuple{1},tuple{2}), coords, 'UniformOutput',false);\n\nAnd just for testing, I tried it with the following:\nX1 = @... | [
2,
0
] | [] | [] | [
"iterable_unpacking",
"matlab",
"python"
] | stackoverflow_0001739566_iterable_unpacking_matlab_python.txt |
Q:
oneliner scramble program
It's that time of year again that programmers want to shuffle a list such that no element resides on its original position (at least in the Netherlands, we celebrate Sinterklaas and pick straws for deciding who writes who a poem). Does anyone have a nice Python single statement for that?
... | oneliner scramble program | It's that time of year again that programmers want to shuffle a list such that no element resides on its original position (at least in the Netherlands, we celebrate Sinterklaas and pick straws for deciding who writes who a poem). Does anyone have a nice Python single statement for that?
So, input example: range(10)
Ou... | [
"I found shuffle can be abused into solving this\nfrom random import shuffle\nL = [\"Anne\", \"Beth\", \"Cath\", \"Dave\", \"Emma\"]\nshuffle(L, int=lambda n: int(n - 1))\nprint L\n\nThe distribution is not uniform however this was not a requirement.\n#For 100,000 samples\n\n(('Beth', 'Cath', 'Dave', 'Emma', 'Anne'... | [
6,
5,
3,
1,
1,
1,
1,
0,
0,
0,
0
] | [] | [] | [
"code_golf",
"python",
"shuffle"
] | stackoverflow_0001735561_code_golf_python_shuffle.txt |
Q:
Elixir not creating my tables with default values
class MyObject(Entity):
name = Field(Unicode(256), default=u'default name', nullable=False)
using_options(shortnames=True)
using_mapper_options(save_on_init=False)
def __init__(self):
self.name = None
I am using MySQL in this case, but ... | Elixir not creating my tables with default values | class MyObject(Entity):
name = Field(Unicode(256), default=u'default name', nullable=False)
using_options(shortnames=True)
using_mapper_options(save_on_init=False)
def __init__(self):
self.name = None
I am using MySQL in this case, but have also checked against SQLite and I get the same res... | [
"default keyword argument in SQLAlchemy is for Python runtime default value, it's used for INSERT statements. Use PassiveDefault() object as positional argument when you really need database level default. \n"
] | [
2
] | [] | [] | [
"python",
"python_elixir",
"sqlalchemy"
] | stackoverflow_0001740040_python_python_elixir_sqlalchemy.txt |
Q:
Problem with pexpect and 'chained' function calls
The class below is designed to manipulate a cisco-like device interface, for the purpose of executing commands and updating configuration elements.
As is currently stands, I can instantiate the class, make a call to the ssh_to_aos_expsh function and get back valid ... | Problem with pexpect and 'chained' function calls | The class below is designed to manipulate a cisco-like device interface, for the purpose of executing commands and updating configuration elements.
As is currently stands, I can instantiate the class, make a call to the ssh_to_aos_expsh function and get back valid output (e.g. get the config when the command is 'show r... | [
"It turns out that there were two problems, both easy to fix once I knew what the issues were. First, the __init__ method contains no self.aos_config_prompt - something which the pexpect exception stated pretty clearly when I commented out my exception handling code. Second, given a self.aos_config_prompt that lo... | [
1,
0,
0
] | [] | [] | [
"pexpect",
"python"
] | stackoverflow_0001727591_pexpect_python.txt |
Q:
Can i integrate Blender with Phanthom Omni
I have some project about game programming, which have to use blender with phanthom ,Don't know possible to do it
A:
If you mean Phantom Omni, the haptic feedback device, and you mean Blender, the rendering program, then I don't see any reason why you can't use the API ... | Can i integrate Blender with Phanthom Omni | I have some project about game programming, which have to use blender with phanthom ,Don't know possible to do it
| [
"If you mean Phantom Omni, the haptic feedback device, and you mean Blender, the rendering program, then I don't see any reason why you can't use the API for both of them in a program, together to make a game.\nIn short, if your questions means what I think it does, of course. \n"
] | [
0
] | [] | [] | [
"blender",
"python"
] | stackoverflow_0001740299_blender_python.txt |
Q:
Integrating a simple web server into a custom main loop in python?
I have an application in python with a custom main loop (I don't believe the details are important). I'd like to integrate a simple non-blocking web server into the application which can introspect the application objects and possibly provide an in... | Integrating a simple web server into a custom main loop in python? | I have an application in python with a custom main loop (I don't believe the details are important). I'd like to integrate a simple non-blocking web server into the application which can introspect the application objects and possibly provide an interface to manipulate them. What's the best way to do this?
I'd like to ... | [
"Twisted is designed to make stuff like that fairly simple\nimport time\n\nfrom twisted.web import server, resource\nfrom twisted.internet import reactor\n\nclass Simple(resource.Resource):\n isLeaf = True\n def render_GET(self, request):\n return \"<html>%s Iterations!</html>\"%n\n\ndef main():\n g... | [
7
] | [
"I'd suggest creating a new thread and running a web server (such as Python's built-in SimpleHTTPServer or BaseHTTPServer). Threads really aren't that scary when it comes down to it.\nfrom threading import Event, Thread\nimport BaseHTTPServer\n\nshut_down = Event()\n\ndef http_server():\n server_address = ('', ... | [
-1
] | [
"loops",
"python"
] | stackoverflow_0001740235_loops_python.txt |
Q:
Python threading strange behaviour
from threading import *
from time import *
class MyThread(Thread):
def __init__(self,x):
self.x = x
Thread.__init__(self)
def run(self):
sleep(2)
print(self.x)
if __name__=='__main__':
threads = []
for i in range(5):
t... | Python threading strange behaviour | from threading import *
from time import *
class MyThread(Thread):
def __init__(self,x):
self.x = x
Thread.__init__(self)
def run(self):
sleep(2)
print(self.x)
if __name__=='__main__':
threads = []
for i in range(5):
threads.append(MyThread('Hello'))
fo... | [
"It looks like you've run into the problem documented in Python bug tracker issue 6750. Fixes for the problem are checked in and will appear in the next maintenance release of Python 3.1, if there is one, or in Python 3.2.\n$ python3.1 test_thread.py \nHello\nHello\nHello\nHello\nHello\nHello\nHello\n$ python3.2 t... | [
2,
0
] | [] | [] | [
"multithreading",
"python"
] | stackoverflow_0001740485_multithreading_python.txt |
Q:
XML attributes get sorted
When I create a document using the minidom, attributes get sorted alphabetically in the element. Take this example from here:
from xml.dom import minidom
# New document
xml = minidom.Document()
# Creates user element
userElem = xml.createElement("user")
# Set attributes to user element... | XML attributes get sorted | When I create a document using the minidom, attributes get sorted alphabetically in the element. Take this example from here:
from xml.dom import minidom
# New document
xml = minidom.Document()
# Creates user element
userElem = xml.createElement("user")
# Set attributes to user element
userElem.setAttribute("name", ... | [
"According to the documentation, the order of attributes is arbitrary but consistent for the life of the DOM. This is common across DOM implementations. Sorry.\n"
] | [
5
] | [] | [] | [
"minidom",
"python",
"xml"
] | stackoverflow_0001740731_minidom_python_xml.txt |
Q:
Python: Behavior of the garbage collector
I have a Django application that exhibits some strange garbage collection behavior. There is one view in particular that will just keep growing the VM size significantly every time it is called - up to a certain limit, at which point usage drops back again. The problem is ... | Python: Behavior of the garbage collector | I have a Django application that exhibits some strange garbage collection behavior. There is one view in particular that will just keep growing the VM size significantly every time it is called - up to a certain limit, at which point usage drops back again. The problem is that it's taking considerable time until that p... | [
"\nDoes the above even make sense, or do I have to look for the problem elsewhere? Is it just an unfortunate accident that significant data is kept around for so long in this particular use case?\n\nYes, it does make sense. And yes, there are other issues worth to consider. Django uses threading.local as base for D... | [
3,
2
] | [] | [] | [
"django",
"garbage_collection",
"memory",
"python"
] | stackoverflow_0001740394_django_garbage_collection_memory_python.txt |
Q:
Approaches to resize an uploaded image of unknown format with Python
PIL is great for resizing an image 99% of time. But as there are some formats which PIL cannot handle, e.g. interlaced PNG images, I wonder is there any other libraries to work with as a supplement to PIL when we encounter a unsupported image.
Be... | Approaches to resize an uploaded image of unknown format with Python | PIL is great for resizing an image 99% of time. But as there are some formats which PIL cannot handle, e.g. interlaced PNG images, I wonder is there any other libraries to work with as a supplement to PIL when we encounter a unsupported image.
Besides interlaced PNG images, what other formats are not currently supporte... | [
"You can use the binding python of imagemagick maybe : MagickWand\nYou might also be interested in PythonMagickWand\n"
] | [
1
] | [] | [] | [
"image",
"python",
"python_imaging_library"
] | stackoverflow_0001740682_image_python_python_imaging_library.txt |
Q:
translate python method to ruby
What would be the correct translation of the following Python method to Ruby?
def uniqueCombinations(self, items, n):
"""
items: list of elements
n: number in a group
"""
if n == 0:
yield []
else:
for i in range(len(items)-n+1):
f... | translate python method to ruby | What would be the correct translation of the following Python method to Ruby?
def uniqueCombinations(self, items, n):
"""
items: list of elements
n: number in a group
"""
if n == 0:
yield []
else:
for i in range(len(items)-n+1):
for cc in uniqueCombinations(items[i+1... | [
"yield [items[i]] + cc\n\nYou are attempting to concatenate an array ([items[i]]) and a Fixnum (cc). You could instead turn both into an array or use the << method to push cc onto [items[i]].\nyield [items[i]] << cc\n\n",
"From Ruby 1.8.7 onwards, class Array provides a method to return combinations:\nirb> ['01... | [
2,
2,
0
] | [] | [] | [
"python",
"ruby"
] | stackoverflow_0001740960_python_ruby.txt |
Q:
Google Eclipse Plugin - Work with Python
Does the Google Eclipse Plugin work at all with Pydev or is it only useful if I am developing in Java?
A:
The App Engine eclipse plugin is for Java development. As Casebash points out, though Pydev now has App Engine integration.
A:
You can, indeed, use Eclipse (and PyD... | Google Eclipse Plugin - Work with Python | Does the Google Eclipse Plugin work at all with Pydev or is it only useful if I am developing in Java?
| [
"The App Engine eclipse plugin is for Java development. As Casebash points out, though Pydev now has App Engine integration.\n",
"You can, indeed, use Eclipse (and PyDev) for Python development for App Engine -- see here for more, for example!\n"
] | [
3,
1
] | [] | [] | [
"eclipse",
"google_app_engine",
"python"
] | stackoverflow_0001739969_eclipse_google_app_engine_python.txt |
Q:
Google Wave Python Tutorial - Nothing happens
For the Google Wave Python Robot Tutorial, my capabilities.xml is visible and I can add it to a Wave, but the robot isn't actually responding to the events. I checked the logs, but I've fixed it so I'm not getting any more errors. Any suggestions?
A:
There's known is... | Google Wave Python Tutorial - Nothing happens | For the Google Wave Python Robot Tutorial, my capabilities.xml is visible and I can add it to a Wave, but the robot isn't actually responding to the events. I checked the logs, but I've fixed it so I'm not getting any more errors. Any suggestions?
| [
"There's known issue with Wave API: Issue 158 Fix is ready and is expected to be deployed in \"coming days\".\n"
] | [
3
] | [] | [] | [
"google_app_engine",
"google_wave",
"python"
] | stackoverflow_0001741773_google_app_engine_google_wave_python.txt |
Q:
Cron job (sending email) in Google App Engine
Possible Duplicate:
cron jobs on google appengine
I have created a Google App Engine app using Python for weekly project and assessment reporting.
I want to check on Fridays who has submitted the report so that I can send a notification email on Monday to those who h... | Cron job (sending email) in Google App Engine |
Possible Duplicate:
cron jobs on google appengine
I have created a Google App Engine app using Python for weekly project and assessment reporting.
I want to check on Fridays who has submitted the report so that I can send a notification email on Monday to those who haven't submitted the report.
Any suggestions on ho... | [
"You can schedule the task using the App Engine Scheduled Tasks feature.\nYou'll need to add an entry to the cron.yaml file for your application. Something like:\ncron:\n- description: friday mailout\n url: /mail/weekly\n schedule: every friday 09:00\n\nYou can send email using the App Engine Mail API.\n"
] | [
2
] | [] | [] | [
"cron",
"google_app_engine",
"python"
] | stackoverflow_0001741897_cron_google_app_engine_python.txt |
Q:
Can SQLAlchemy update the table structure?
I am working on my first pylons + SQLAlchemy app (I'm new to both).
As I change my mind on the table structure, I wish there was a similar function to metadata.create_all(), that checks if there are new columns definitions and create them in the database.
Does such a func... | Can SQLAlchemy update the table structure? | I am working on my first pylons + SQLAlchemy app (I'm new to both).
As I change my mind on the table structure, I wish there was a similar function to metadata.create_all(), that checks if there are new columns definitions and create them in the database.
Does such a function exist ?
| [
"I'm not (yet) a SQLAlchemy user, but I've heard good things about sqlalchemy-migrate. The general term of the problem you have is \"schema migration\", I'm sure a google search containing these terms will help you further.\n"
] | [
5
] | [] | [] | [
"mysql",
"pylons",
"python",
"sqlalchemy"
] | stackoverflow_0001742157_mysql_pylons_python_sqlalchemy.txt |
Q:
Python and factories
I cant seem to grasp the proper concepts of a factory.
Can anyone help me code a simple test? I read some texts over the internet and cant code it the same way. Actually i cant understand the process. Copying code is easy, but i need to learn why this wont work.
class Factory:
def __init_... | Python and factories | I cant seem to grasp the proper concepts of a factory.
Can anyone help me code a simple test? I read some texts over the internet and cant code it the same way. Actually i cant understand the process. Copying code is easy, but i need to learn why this wont work.
class Factory:
def __init__(self):
self.msg ... | [
"Your code is counter-productive (sorry, I must say it).\nThe sense of a factory is, that you don't have to know the class of your constructed object at the position where you create it.\nThe reason is, that object creation creates a gap in object oriented abstraction. You must be concrete in creating the object. B... | [
13,
5,
1,
0
] | [] | [] | [
"factory",
"oop",
"python"
] | stackoverflow_0001651593_factory_oop_python.txt |
Q:
Calling Method from Different Python File
As I'm currently learning Django / Python, I've not really been using the concept of Classes, yet. As far as I'm aware the method isn't static.. it's just a standard definition.
So let's say I have this Package called Example1 with a views.py that contains this method:
def... | Calling Method from Different Python File | As I'm currently learning Django / Python, I've not really been using the concept of Classes, yet. As far as I'm aware the method isn't static.. it's just a standard definition.
So let's say I have this Package called Example1 with a views.py that contains this method:
def adder(x,y):
return x + y
Then I have an Exa... | [
"Python has module level and class level methods. In this concept a \"module\" is a very special class that you get by using import instead of Name(). Try\nfrom Example1.views import adder as otherAdder\n\nto get access to the module level method. Now you can call otherAdder() and it will execute the code in the ot... | [
7,
6,
3
] | [] | [] | [
"django",
"methods",
"python"
] | stackoverflow_0001742430_django_methods_python.txt |
Q:
How do I get the selected text in desktop application using python-dbus?
For example, I open a pdf file or a web page in gnome, use mouse double click some text, so a word is selected, how can I get this word in a background running daemon written with python-dbus?
Some simple but working piece of script is apprec... | How do I get the selected text in desktop application using python-dbus? | For example, I open a pdf file or a web page in gnome, use mouse double click some text, so a word is selected, how can I get this word in a background running daemon written with python-dbus?
Some simple but working piece of script is appreciated greatly.
Thanks!
| [
"You don't need D-Bus, simply listen to changes for the middle-click (Selection) clipboard with for example Gtk:\nimport gtk\n\ndef _clipboard_changed(clipboard, event):\n text = clipboard.wait_for_text()\n\nclip = gtk.clipboard_get(gtk.gdk.SELECTION_PRIMARY)\nclip.connect(\"owner-change\", _clipboard_changed)\n... | [
7,
0
] | [] | [] | [
"dbus",
"gtk",
"python",
"selection",
"text"
] | stackoverflow_0001742264_dbus_gtk_python_selection_text.txt |
Q:
I am getting this sort of CSV data while making Http request to the CSV file. Very malformed string
I am getting this sort of CSV data while making Http request to the CSV file. Very malformed string.
response = '"Subject";"Start Date";"Start Time";"End Date";"End Time";"All day event";"Description""Play football... | I am getting this sort of CSV data while making Http request to the CSV file. Very malformed string | I am getting this sort of CSV data while making Http request to the CSV file. Very malformed string.
response = '"Subject";"Start Date";"Start Time";"End Date";"End Time";"All day event";"Description""Play football";"16/11/2009";"10:00 PM";"16/11/2009";"11:00 PM";"false";"""Watch 2012";"20/11/2009";"07:00 PM";"20/11/2... | [
"Here's a pyparsing solution:\nfrom pyparsing import QuotedString, Group, delimitedList, OneOrMore\n\n# a row of headings or data is a list of quoted strings, delimited by ';'s\nqs = QuotedString('\"')\ndatarow = Group(delimitedList(qs, ';'))\n\n# an entire data set is a single data row containing the headings, fol... | [
8,
3,
2,
1
] | [] | [] | [
"csv",
"python"
] | stackoverflow_0001742236_csv_python.txt |
Q:
Lightweight python wiki engine with pluggable auth system
I need to add wiki to my Tornado webapp. i'm new to python so i would like it not too intimidating to be learned and integrated and can use my existing authentication system, hence the lightweight. it would be better if can use mongodb backend.
I already ta... | Lightweight python wiki engine with pluggable auth system | I need to add wiki to my Tornado webapp. i'm new to python so i would like it not too intimidating to be learned and integrated and can use my existing authentication system, hence the lightweight. it would be better if can use mongodb backend.
I already take a look at moin-moin and it seems too complex(?). any other a... | [
"Have a look at Hatta. Overwrite WikiRequest.get_author() method to plug your authentication system. But it uses mercurial repository to store the data.\n",
"Skeletonz is a very nice lightweight Python cms that might be worth a look...\n"
] | [
4,
0
] | [] | [] | [
"python",
"wiki_engine"
] | stackoverflow_0001740957_python_wiki_engine.txt |
Q:
How to generate a list of 150 cases initialised with a dict in Python?
I would like to create a list like this
list = []
for i in range(150):
list.append({'open': False, 'serve': False})
But is there a better way in Python to do it ?
A:
With a list comprehension (don't use list as a variable name, as it s... | How to generate a list of 150 cases initialised with a dict in Python? | I would like to create a list like this
list = []
for i in range(150):
list.append({'open': False, 'serve': False})
But is there a better way in Python to do it ?
| [
"With a list comprehension (don't use list as a variable name, as it shadows the python built-in):\n# use range() in Python 3\nl = [{'open': False, 'serve': False} for i in xrange(150)]\n\n",
"Whatever you do, don't try list = [{'open':False,'serve':False}]*150, as you will have the same dictionary 150 times. :D\... | [
5,
1,
0
] | [] | [] | [
"dictionary",
"initialization",
"list",
"python"
] | stackoverflow_0001553145_dictionary_initialization_list_python.txt |
Q:
sorting function in python
I'm trying to sort a list of objects according to my criteria.
Here is my sorting function:
def sort_pots(self, pot1, pot2):
coeff1 = ((pot1.movable + pot1.convertible) / pot1.total)
coeff2 = ((pot2.movable + pot2.convertible) / pot2.total)
if coeff1 > coeff2:
return... | sorting function in python | I'm trying to sort a list of objects according to my criteria.
Here is my sorting function:
def sort_pots(self, pot1, pot2):
coeff1 = ((pot1.movable + pot1.convertible) / pot1.total)
coeff2 = ((pot2.movable + pot2.convertible) / pot2.total)
if coeff1 > coeff2:
return 1
elif coeff1 == coeff2:
... | [
"Does the following work?\ndef coef(pot):\n return (pot.movable + pot.convertible) / float(pot.total)\n\nl.sort(key=lambda x: (coef(x), x.total), reverse=True)\n\nIt should even be faster (key is better than cmp).\n",
"Just as a final note, you could override the __cmp__ method as follows:\nclass Potential(obj... | [
9,
2,
1
] | [] | [] | [
"python",
"sorting"
] | stackoverflow_0001742656_python_sorting.txt |
Q:
How is a union different from a struct? Do other languages have similar constructs?
Possible Duplicate:
Difference between a Structure and a Union in C
I see this code for a union in C:
union time
{
long simpleDate;
double perciseDate;
} mytime;
What is the difference between a union and... | How is a union different from a struct? Do other languages have similar constructs? |
Possible Duplicate:
Difference between a Structure and a Union in C
I see this code for a union in C:
union time
{
long simpleDate;
double perciseDate;
} mytime;
What is the difference between a union and a structure in C? Where would you use a union, what are its benefits? Is there a simila... | [
"A union behaves as if all its members are in the same location in memory, overlapping.\nThis is useful when you want to represent some kind of \"generic\" value, or a value that can be of any of a set of types. Because the fields overlap, you can only legally access a field if you know it's been previously initial... | [
14,
11,
2,
2,
1,
1,
1
] | [] | [] | [
"c",
"c++",
"java",
"programming_languages",
"python"
] | stackoverflow_0001742750_c_c++_java_programming_languages_python.txt |
Q:
How to sort model by values in a dictionary?
In Django, I have a model, and I will have a dictionary having the id's of objects in this model as keys, and a weight as values. I would like to use these weights in an order_by:
MyModel.objects.filter(title__icontains=query).order_by( 'value_from_the_dictionary' )
Ho... | How to sort model by values in a dictionary? | In Django, I have a model, and I will have a dictionary having the id's of objects in this model as keys, and a weight as values. I would like to use these weights in an order_by:
MyModel.objects.filter(title__icontains=query).order_by( 'value_from_the_dictionary' )
How to make this work?
I can't put the weights in th... | [
"Sorting in order_by is done by the database, so if those elements aren't in the database you can't order by them. You will have to get the queryset and then do the ordering in Python.\nqs = MyModel.objects.filter(title__icontains=query)\nqs.sort(key=lambda x: mydict[x])\n\n"
] | [
5
] | [] | [] | [
"django",
"python",
"sorting",
"sql_order_by"
] | stackoverflow_0001743288_django_python_sorting_sql_order_by.txt |
Q:
Convert flat data into a hierarchical python list
I have a data model from my database. This is a flat python list sorted by left values.
> id name left right
> 1 Beginning 1 6
> 2 FOO 2 5
> 3 BAR 3 4
> 4 Programming 6 13
> 5 Python 7 8
> 7 C# ... | Convert flat data into a hierarchical python list | I have a data model from my database. This is a flat python list sorted by left values.
> id name left right
> 1 Beginning 1 6
> 2 FOO 2 5
> 3 BAR 3 4
> 4 Programming 6 13
> 5 Python 7 8
> 7 C# 9 12
> 8 XNA 10 11
> 6 About 14 1... | [
"This is a modified pre-order tree traversal.\nhttp://www.sitepoint.com/print/hierarchical-data-database/\nSo the input looks like this, a list of dictionaries.\ndbrows = [\n {'title': 'Food', 'lft': 1, 'rgt': 18},\n {'title': 'Fruit', 'lft': 2, 'rgt': 11},\n #etc... etc... from the linked article.\n]\n\nUsin... | [
0
] | [] | [] | [
"hierarchical",
"python"
] | stackoverflow_0001740107_hierarchical_python.txt |
Q:
Conflicting Python Packages How can it be Resolved?
So we went to implement something today, and discovered that there already is several applications relying on the old implementation of our inhouse python library. Called cis_py. Now all applications for our implementation currently sit in a folder called, bin. T... | Conflicting Python Packages How can it be Resolved? | So we went to implement something today, and discovered that there already is several applications relying on the old implementation of our inhouse python library. Called cis_py. Now all applications for our implementation currently sit in a folder called, bin. This is where cis_py currently resides.
Now we went to dep... | [
"Try import sys; sys.path.insert(0, \"cis\") as the very start of your main Python file.\n",
"It looks like Alex Martelli's solution solved the emergency for you. Here's another solution, one I think better for the long term.\nIn source files, replace the line\nimport cis_py\n\nwith the line\nimport cis.cis_py a... | [
5,
1,
0,
0
] | [] | [] | [
"package",
"python"
] | stackoverflow_0001743596_package_python.txt |
Q:
Does Django cache templates automatically?
I'm new to Django and trying to implement a voting system between two images. However, it looks like the page is being cached or something because when I refresh it, some values are wrong. I have no cache setup in my Settings.
Here is the View:
def rate(request, type):
... | Does Django cache templates automatically? | I'm new to Django and trying to implement a voting system between two images. However, it looks like the page is being cached or something because when I refresh it, some values are wrong. I have no cache setup in my Settings.
Here is the View:
def rate(request, type):
photos = Photo.objects.order_by('?')[:2]
... | [
"Taking a look at this in some of my code, I have this in my template:\n{{ mytable.0.pk }}\n{{ mytable.1.pk }}\n{{ mytable.0.pk }}\n{{ mytable.3.pk }}\n\nAnd I get this output:\n91596\n54774\n156800\n23593\n\nOdd, until you consider that django executes database queries very lazily. This is what shows up in my mys... | [
8,
1,
1
] | [] | [] | [
"caching",
"django",
"django_templates",
"python"
] | stackoverflow_0001744339_caching_django_django_templates_python.txt |
Q:
ubuntu9.10 : how to use python's lib-dynload and site-packages directories?
In ubuntu 9.10, in usr/lib/ there are the directories python2.4, python2.5, python2.6 and python3.0
Only python 2.6 is actually working.
python2.4 has only a lib-dynload directory,
python2.5 has only lib-dynload and site-packages,
python3... | ubuntu9.10 : how to use python's lib-dynload and site-packages directories? | In ubuntu 9.10, in usr/lib/ there are the directories python2.4, python2.5, python2.6 and python3.0
Only python 2.6 is actually working.
python2.4 has only a lib-dynload directory,
python2.5 has only lib-dynload and site-packages,
python3.0 has only a dist-packages directory.
Now i'm wondering what is the idea behin... | [
"j3ll3, in Ubuntu (or any DPKG-based Linux OS) you can ask the question \"What package provides XYZ\" by typing\ndpkg -S /path/to/XYZ\n\nSo, for example, in Ubuntu 9.10,\ndpkg -S /usr/lib/python2.5/lib-dynload/gdbm.so\n\nreturns\npython-gdbm: /usr/lib/python2.5/lib-dynload/gdbm.so\n\nYou can find out more about the... | [
2,
1,
0,
0
] | [] | [] | [
"installation",
"python",
"ubuntu"
] | stackoverflow_0001733364_installation_python_ubuntu.txt |
Q:
A multithreaded queue in Python
I need to perform time consuming tasks in an webapplication.
Because the tasks can be so heavy that they run for minutes they have to run on multiple threads so the user won't have to look at a loading page for minutes.
So I thought a multithreaded queue would be a good solution.
Ea... | A multithreaded queue in Python | I need to perform time consuming tasks in an webapplication.
Because the tasks can be so heavy that they run for minutes they have to run on multiple threads so the user won't have to look at a loading page for minutes.
So I thought a multithreaded queue would be a good solution.
Each instance of a object that you add ... | [
"The Python standard library Queue module is already thread-safe and aware and should work for your requirements.\nHere's a nice paper Task Queue Implementation Pattern that discusses how to use Queue for task queues.\n",
"You just need your elements to extend threading.Thread and use Conditions() to implement th... | [
6,
2,
2,
1,
0,
0
] | [] | [] | [
"multithreading",
"python",
"queue"
] | stackoverflow_0001666441_multithreading_python_queue.txt |
Q:
What's the most Pythonic XHTML/HTML parser/generator/template module that supports DOM like access?
It should be able to create, modify and read X/HTML in a highly object oriented way that still feels DOM like but is not obese, and is really Pythonic.
Preferably it would deal with malformed HTML too, but we can sk... | What's the most Pythonic XHTML/HTML parser/generator/template module that supports DOM like access? | It should be able to create, modify and read X/HTML in a highly object oriented way that still feels DOM like but is not obese, and is really Pythonic.
Preferably it would deal with malformed HTML too, but we can skip this for templates.
For example, I'd like to do this:
>> from someAmazingTemplate import *
>> html = T... | [
"The first part can for the most part be done by ElementTree, but it takes a few more steps:\n>>> import xml.etree.ElementTree as ET\n>>> html = ET.XML('<html><head><title>Hi</title></head><body></body></html>')\n>>> html.head = html.find('head')\n>>> html.head.append(ET.XML('<link type=\"text/css\" href=\"main.css... | [
5,
1
] | [] | [] | [
"dom",
"parsing",
"python",
"template_engine",
"xhtml"
] | stackoverflow_0001745524_dom_parsing_python_template_engine_xhtml.txt |
Q:
How to allow a many-to-many relationship to be configured in Python
I have a simple app which requires a many-to-many relationship to be configured as part of its set-up. For example, the app requires a list of repository URLs, a list of users and for each user, a subset of the repository URLs.
I first thought of... | How to allow a many-to-many relationship to be configured in Python | I have a simple app which requires a many-to-many relationship to be configured as part of its set-up. For example, the app requires a list of repository URLs, a list of users and for each user, a subset of the repository URLs.
I first thought of using a config.py file similar to the following:
repositories = {
'r... | [
"I would store the config in JSON format. For example:\ncfg = \"\"\"\n{\n \"repositories\": {\n \"repo1\": \"http://svn.example.com/repo1/\",\n \"repo2\": \"http://svn.example.com/repo2/\",\n \"repo3\": \"http://svn.example.com/repo3/\"\n },\n \"user_repository_mapping\": {\n \... | [
2,
1
] | [
"The tactic I use is to put the whole application in a class, and then instead of having an importable config file, allow the user to pass in configuration to the constructor. Or, in more complicated cases they could even subclass the application class to add members or change behaviours. Although this does require... | [
-1
] | [
"configuration",
"python"
] | stackoverflow_0001745479_configuration_python.txt |
Q:
Connecting to APNS for iPhone Using Python
I'm trying to send push notifications to an iPhone using Python. I've exported my certificate and private key into a p12 file from keychain access and then converted it into pem file using the following command:
openssl pkcs12 -in cred.p12 -out cert.pem -nodes -clcerts
I... | Connecting to APNS for iPhone Using Python | I'm trying to send push notifications to an iPhone using Python. I've exported my certificate and private key into a p12 file from keychain access and then converted it into pem file using the following command:
openssl pkcs12 -in cred.p12 -out cert.pem -nodes -clcerts
I'm using APNSWrapper in Python for the connectio... | [
"I recently did this using Django - http://leecutsco.de/2009/07/14/push-on-the-iphone/\nMay be useful? It's making use of no extra libraries other than those included with Python already. Wouldn't take much to extract the send_message() method out.\n",
"Have you considered the Twisted package? The below code is ... | [
8,
2,
2,
1,
0
] | [] | [] | [
"iphone",
"push_notification",
"python",
"ssl"
] | stackoverflow_0001172769_iphone_push_notification_python_ssl.txt |
Q:
how can I filter on the second element in a tuple of tuples?
In my model I have a field:
country = models.CharField(_('Country'), max_length=2, choices=COUNTRIES)
Where COUNTRIES is a tuple of tuples like this:
COUNTRIES = (
('AF', _('Afghanistan')),
... and so on
Now I want to filter an instance of that ... | how can I filter on the second element in a tuple of tuples? | In my model I have a field:
country = models.CharField(_('Country'), max_length=2, choices=COUNTRIES)
Where COUNTRIES is a tuple of tuples like this:
COUNTRIES = (
('AF', _('Afghanistan')),
... and so on
Now I want to filter an instance of that model, by the country name.
This:
i = MyModel.objects.filter(co... | [
"You cannot filter directly by the country name (the choices are only used in the UI, not in the database).\nIf you get the full name as an input, lookup the code in the COUNTRIES tuple-of-tuples. For example:\n# ... initialize a lookup dictionary\ncountry_to_id_dict = dict((t[1], t[0]) for t in COUNTRIES)\n\n# ...... | [
4
] | [] | [] | [
"country",
"django",
"filter",
"python"
] | stackoverflow_0001745919_country_django_filter_python.txt |
Q:
Embedding a control in a QTableView?
I'm working a small qt app (using PyQt4) and I've come up with an idea but I'm unsure as to how to implement it. I have a QTableView that represents some data and I'd like to add another column to the QTableView that contains a checkbox control that could be wired up to some pi... | Embedding a control in a QTableView? | I'm working a small qt app (using PyQt4) and I've come up with an idea but I'm unsure as to how to implement it. I have a QTableView that represents some data and I'd like to add another column to the QTableView that contains a checkbox control that could be wired up to some piece of the model. For example, something l... | [
"Implementing your own table model is more work than using QStandardItemModel (as @Andy recommends), but it does give you a fine control over what you want to do, so I'll try to give you a summary of what to do. I assume you know all about Qt's documentation and PyQt's class documentation and can look up whatever ... | [
8,
4,
1
] | [] | [] | [
"pyqt4",
"python",
"qt",
"tableview"
] | stackoverflow_0001744348_pyqt4_python_qt_tableview.txt |
Q:
QtPython Qtreewidget Problem
I trying to do a Qtreewidget to attend a customer design suggestion. I am coding it on QtPython. I did a first try using Qt Designer, then generated the code. But when I try to run it, an error comes out:
self.centralwidget.setSortingEnabled(__sortingEnabled)
AttributeError: setSortin... | QtPython Qtreewidget Problem | I trying to do a Qtreewidget to attend a customer design suggestion. I am coding it on QtPython. I did a first try using Qt Designer, then generated the code. But when I try to run it, an error comes out:
self.centralwidget.setSortingEnabled(__sortingEnabled)
AttributeError: setSortingEnabled
I googled around, but di... | [
"I'm assuming the code you posted is what you got when you ran your UI file through pyuic4. I found the PyQt UI compiler to be buggy sometimes. All you can do is fix the output manually and complain to the vendor.\nIn your case, the line\nself.centralwidget.setSortingEnabled(__sortingEnabled) \n\nshould read\nself.... | [
2,
0
] | [] | [] | [
"pyqt",
"pyqt4",
"python",
"qt",
"qt4"
] | stackoverflow_0001745661_pyqt_pyqt4_python_qt_qt4.txt |
Q:
python csv headers
I have a set of csv headers that I am trying to match with uploads. It's not really working. Not all headers are required -- I just have to match what's in the file.
reader = csv.DictReader(open(PathFile))
headers = reader.fieldnames
for header in sorted(set(headers)):
if (header == 'ip') o... | python csv headers | I have a set of csv headers that I am trying to match with uploads. It's not really working. Not all headers are required -- I just have to match what's in the file.
reader = csv.DictReader(open(PathFile))
headers = reader.fieldnames
for header in sorted(set(headers)):
if (header == 'ip') or (header == 'IP'):
... | [
"Based on your edit, you need to skip the initial space after the comma.\nThis should do it:\n>>> reader = csv.DictReader(open(PathFile),skipinitialspace=True)\n\n",
"I am not exactly sure what you want to achieve but if you simply want to know if some columns is in CSV, and you are sure that all rows have same c... | [
12,
9
] | [] | [] | [
"csv",
"python"
] | stackoverflow_0001746489_csv_python.txt |
Q:
Minimal Python Installation
Various software installations on my laptop each require their own particular version of Python. ViewVC requires Python 2.5 and Blender requires Python 2.6. Mercurial (thankfully) comes with its Python interpreter packaged in a DLL in the Mercurial installation itself.
How do I get by w... | Minimal Python Installation | Various software installations on my laptop each require their own particular version of Python. ViewVC requires Python 2.5 and Blender requires Python 2.6. Mercurial (thankfully) comes with its Python interpreter packaged in a DLL in the Mercurial installation itself.
How do I get by without having to install the enti... | [
"It's hard to know which \"bare minimum\" the Blender scripts you'll want to use in the future may be counting on (short of the full Python standard library, which isn't all that large in term of disk space after all). Why not install both Python 2.5 and 2.6? They can coexist nicely (if your scriptable apps use h... | [
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0001746818_python.txt |
Q:
Finding the highest key
I'm just confused about why my code would not work, here's the question and the code I have so far (the test run says my answer is wrong).
Given the dictionary d, find the largest key in the dictionary and associate the corresponding value with the variable val_of_max. For example, given th... | Finding the highest key | I'm just confused about why my code would not work, here's the question and the code I have so far (the test run says my answer is wrong).
Given the dictionary d, find the largest key in the dictionary and associate the corresponding value with the variable val_of_max. For example, given the dictionary {5:3, 4:1, 12:2}... | [
"your code prints the key with the maximum value. What you want is:\nd = {5:3, 4:1, 12:2, 14:9}\nval_of_max = d[max(d.keys())]\nprint val_of_max\n\nThat is, you have to dereference the key to return the value.\n",
"this will do:\n>>> d = {5:3, 4:1, 12:2, 14:9}\n>>> d[max(d)]\n9\n>>> max(d) # just in case ... | [
12,
5,
1,
0
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0001661621_dictionary_python.txt |
Q:
Sum and Division example (Python)
>>> sum((1, 2, 3, 4, 5, 6, 7))
28
>>> 28/7
4.0
>>> sum((1,2,3,4,5,6,7,8,9,10,11,12,13,14))
105
>>> 105/7
15.0
>>>
How do I automate this sum and division using a loop maybe?
Edit: Maybe I wasn't clear - I want a loop to keep doing the sum (of multiples of 7, eg 1-7, 1-14, 1-21 et... | Sum and Division example (Python) | >>> sum((1, 2, 3, 4, 5, 6, 7))
28
>>> 28/7
4.0
>>> sum((1,2,3,4,5,6,7,8,9,10,11,12,13,14))
105
>>> 105/7
15.0
>>>
How do I automate this sum and division using a loop maybe?
Edit: Maybe I wasn't clear - I want a loop to keep doing the sum (of multiples of 7, eg 1-7, 1-14, 1-21 etc..) until it reaches x (x is the user ... | [
"The direct answer:\ndef sum_to_number_divided_by_seven(i):\n return sum(range(i+1)) / 7\n\nThe more efficient answer:\ndef sum_to_number_divided_by_seven(i):\n return (i*(i+1))/14\n\n",
"def sumdiv7(limit):\n for i in range(limit):\n result = sum(range(i*7)) / 7\n print \"For\", i, \", sumdiv ... | [
5,
1,
0,
0,
0
] | [] | [] | [
"division",
"python",
"sum"
] | stackoverflow_0001747130_division_python_sum.txt |
Q:
python reduce error?
The following is my python code:
>>> item = 1
>>> a = []
>>> a.append((1,2,3))
>>> a.append((7,2,4))
>>> sums=reduce(lambda x:abs(item-x[1]),a)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: <lambda>() takes exactly 1 argument (2 given)
>>>
How can I fix ... | python reduce error? | The following is my python code:
>>> item = 1
>>> a = []
>>> a.append((1,2,3))
>>> a.append((7,2,4))
>>> sums=reduce(lambda x:abs(item-x[1]),a)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: <lambda>() takes exactly 1 argument (2 given)
>>>
How can I fix it?
Thanks!
| [
"Your lambda takes only one argument, but reduce requires a function that takes two arguments. Make your lambda take two arguments.\nSince you didn't say what you want this code to do, I'll just guess:\nthe_sum=reduce(lambda x,y:abs(y[1]-x[1]),a)\n\n",
"Your problem itself is a bit unclear. Anyway, i have taken j... | [
8,
3,
2
] | [] | [] | [
"arguments",
"lambda",
"python",
"reduce"
] | stackoverflow_0001746999_arguments_lambda_python_reduce.txt |
Q:
How to use doctest on a Client script?
I am playing with Google Calendar API, creating some useful function.
I another hand, I want to do it right puting some useful doctest and starting agile development.
How to write doctest since the result of each function is not really predictible (Depending of what is new o... | How to use doctest on a Client script? | I am playing with Google Calendar API, creating some useful function.
I another hand, I want to do it right puting some useful doctest and starting agile development.
How to write doctest since the result of each function is not really predictible (Depending of what is new on the server) :
>>> calendar = GoogleCalenda... | [
"If you do decide to test an external service, you can use a test fixture:\n\nWrite a make_test_server() function, which will return a new server connection to simplify your tests.\nMake it a test fixture (dummy of the server) make_dummy_test_server() with predictable output.\nTest it, and make sure that all cases ... | [
1
] | [] | [] | [
"doctest",
"google_api",
"password_protection",
"python"
] | stackoverflow_0001747371_doctest_google_api_password_protection_python.txt |
Q:
Is Java or Python better for writing a web-page-source-checking web service on Google App Engines?
I hope you all have a nice day.
I want to write a web service that would check some web page HTML code every 20 minutes and e-mail it to my mail box. Here I was given a suggestion to use Google App Engine for this ta... | Is Java or Python better for writing a web-page-source-checking web service on Google App Engines? | I hope you all have a nice day.
I want to write a web service that would check some web page HTML code every 20 minutes and e-mail it to my mail box. Here I was given a suggestion to use Google App Engine for this task. Having briefly read through that site I learned that two languages could be used there: Java and Pyt... | [
"Both the languages and their App Engine implementations are pretty solid and mature. As a language, Python is faster to learn, but Java comes with richer tools such as Eclipse that may partly compensate. A lot depends on what other languages you have background in -- for example, coming from C#, Java would be si... | [
5,
3,
2
] | [] | [] | [
"google_app_engine",
"html",
"java",
"python",
"web_services"
] | stackoverflow_0001746867_google_app_engine_html_java_python_web_services.txt |
Q:
How to define the help of the CLI program in the __doc__?
I would like to do something like this :
def main():
"""
Display Information about a Google Calendar
-u --user login Google Login
-p --pass password Google Password
-d --debug Set DEBUG = True
-h --help D... | How to define the help of the CLI program in the __doc__? | I would like to do something like this :
def main():
"""
Display Information about a Google Calendar
-u --user login Google Login
-p --pass password Google Password
-d --debug Set DEBUG = True
-h --help Display this help
"""
print(__doc__)
if __name__ == "_... | [
"Because __doc__ is an attribute of the function, not a local variable. You need to refer to it as main.__doc__ like this:\ndef main():\n \"\"\"Display Information about a Google Calendar\n\n ...\"\"\"\n print(main.__doc__)\n\nif __name__ == \"__main__\":\n main()\n\n",
"If the help that you want to p... | [
4,
2
] | [] | [] | [
"command_line_interface",
"documentation_generation",
"python"
] | stackoverflow_0001747261_command_line_interface_documentation_generation_python.txt |
Q:
Weird Time Issue in Python
Problem with using times in Python.
Terminal > Python
>>> calendar.timegm(datetime.datetime.now().utctimetuple())
1258449380
This time indicates GMT: Tue, 17 Nov 2009 09:16:20 GMT
Eclipse via Django Server
>>> calendar.timegm(datetime.datetime.now().utctimetuple())
1258427784
This time... | Weird Time Issue in Python | Problem with using times in Python.
Terminal > Python
>>> calendar.timegm(datetime.datetime.now().utctimetuple())
1258449380
This time indicates GMT: Tue, 17 Nov 2009 09:16:20 GMT
Eclipse via Django Server
>>> calendar.timegm(datetime.datetime.now().utctimetuple())
1258427784
This time indicates GMT: Tue, 17 Nov 2009... | [
"Django is set to Chicago time. You to change it, edit (or add in) TIME_ZONE flag in settings.py.\nIf you are running on Windows, then Django might mess things up if you don't set it to your local zone - http://docs.djangoproject.com/en/dev/ref/settings/\n",
"You can check if it's the same version of python by ru... | [
7,
2,
0
] | [] | [] | [
"datetime",
"django",
"eclipse",
"python"
] | stackoverflow_0001747559_datetime_django_eclipse_python.txt |
Q:
Google Wave - Adding a participant to a Wave with the Python API
How do I add a participant to a Wave using the Python API given their email address?
A:
The method to add a participant given a user id (AddParticipant) to waves is in the waveapi.model.OpBasedWavelet subclass, rather than just waveapi.model.Wavele... | Google Wave - Adding a participant to a Wave with the Python API | How do I add a participant to a Wave using the Python API given their email address?
| [
"The method to add a participant given a user id (AddParticipant) to waves is in the waveapi.model.OpBasedWavelet subclass, rather than just waveapi.model.Wavelet. This user id is an email address. Look at this sample.\n"
] | [
0
] | [] | [] | [
"google_wave",
"python"
] | stackoverflow_0001747685_google_wave_python.txt |
Q:
More efficient method for this calculation?
a = 218500000000
s = 6
f = 2
k = 49
d = k + f + s
r = a
i = 0
while (r >= d):
r = r - d
#print ('r = ',r)
i = i+1
#print ('i = ',i)
print (i)
I think it does what I expect it to, but its way too slow to calculate such a large number, I waited 5 mins for i to... | More efficient method for this calculation? | a = 218500000000
s = 6
f = 2
k = 49
d = k + f + s
r = a
i = 0
while (r >= d):
r = r - d
#print ('r = ',r)
i = i+1
#print ('i = ',i)
print (i)
I think it does what I expect it to, but its way too slow to calculate such a large number, I waited 5 mins for i to print (while python used 100% cpu to calculate..... | [
"You can use i = a/d. :D\n",
"r = (a % d)\ni = (a / d)\n\nUse the modulo and division operators.\nThere is also a divmod function to calculate both together:\ni, r = divmod(a,d)\n\n",
"Isn't a division what you're looking for?\n",
"try 3833333333.3333333333333333333333. AKA r / d.\n",
"Looks like you are do... | [
4,
4,
2,
0,
0
] | [] | [] | [
"iteration",
"largenumber",
"long_integer",
"python"
] | stackoverflow_0001747713_iteration_largenumber_long_integer_python.txt |
Q:
Scheduling Filter on Database with Time Interval
Let's you have a science experiment called Weather and it records general information about the weather, one of which is recording the humidity every minute. After say 10 hours, you'll have 600 database values stored.
Weather.objects.filter().exclude(time__lt = comm... | Scheduling Filter on Database with Time Interval | Let's you have a science experiment called Weather and it records general information about the weather, one of which is recording the humidity every minute. After say 10 hours, you'll have 600 database values stored.
Weather.objects.filter().exclude(time__lt = commence).exclude(time__gt = cease)
This would create a f... | [
"SQL doesn't have a way to ask for every tenth, so ORMs won't typically give you a way to express that need. You could do that work in Python:\nsamples = list(Weather.objects.filter().exclude(time__lt=commence).exclude(time__gt=cease))\nfor s10 in samples[::10]:\n # do something with every tenth...\n\nThis will... | [
2
] | [] | [] | [
"django",
"filter",
"python"
] | stackoverflow_0001748130_django_filter_python.txt |
Q:
Is there a speed difference between WSGI and FCGI?
From the web I've gleaned that WSGI is a CGI for python web development/frameworks. FCGI seems to be a more generalised gateway for a variety of languages. Don't know the performance difference between the two in reference to the languages python and C/++.
A:
Co... | Is there a speed difference between WSGI and FCGI? | From the web I've gleaned that WSGI is a CGI for python web development/frameworks. FCGI seems to be a more generalised gateway for a variety of languages. Don't know the performance difference between the two in reference to the languages python and C/++.
| [
"Correct, WSGI is a Python programmatic API definition and FASTCGI is a language agnostic socket wire protocol definition. Effectively they are at different layers with WSGI being a higher layer. In other words, one can implement WSGI on top of something that so happened to use FASTCGI to communicate with a web ser... | [
81,
29
] | [] | [] | [
"fastcgi",
"python",
"wsgi"
] | stackoverflow_0001747266_fastcgi_python_wsgi.txt |
Q:
Multiprocessing Pool inside Process time out
When ever I use the following code the pool result always returns a timeout, is there something logically incorrect I am doing?
from multiprocessing import Pool, Process, cpu_count
def add(num):
return num+1
def add_wrap(num):
new_num = ppool.apply_async(add, [num... | Multiprocessing Pool inside Process time out | When ever I use the following code the pool result always returns a timeout, is there something logically incorrect I am doing?
from multiprocessing import Pool, Process, cpu_count
def add(num):
return num+1
def add_wrap(num):
new_num = ppool.apply_async(add, [num])
print new_num.get(timeout=3)
ppool = Pool(pr... | [
"You can't pass Pool objects between processes.\nIf you try this code, Python will raise a exception : 'NotImplementedError: pool objects cannot be passed between processes or pickled'.\nfrom multiprocessing import Queue, Pool\n\nq = Queue()\nppool = Pool(processes=2) ... | [
2
] | [] | [] | [
"multiprocessing",
"pool",
"process",
"python",
"timeout"
] | stackoverflow_0001747963_multiprocessing_pool_process_python_timeout.txt |
Q:
Automating old DOS application using Python
Is there a way to automate an old DOS application (16-bit, probably needs an emulator such as DOSBox) from Python (on Windows)? I would like to send keys and strings to the application, detect updates to the DOS "screen" and get the application output.
It would be even b... | Automating old DOS application using Python | Is there a way to automate an old DOS application (16-bit, probably needs an emulator such as DOSBox) from Python (on Windows)? I would like to send keys and strings to the application, detect updates to the DOS "screen" and get the application output.
It would be even better if the DOS application could run "hidden", ... | [
"I'm not familiar with DosBOX or whether it has an external API. However, for Sun VirtualBox there is a python API, so if it is OK to run DOS on a VM, you could easily use the VirtualBox Python API to control & automate the application you run on the DOS.\nYou can download the VirtualBox SDK here\n"
] | [
1
] | [] | [] | [
"automation",
"dos",
"dosbox",
"python",
"sendkeys"
] | stackoverflow_0001744796_automation_dos_dosbox_python_sendkeys.txt |
Q:
How do you write a program that interacts with others like banlist for warcraft 3?
As in title, what is banlist written in, or can be written in? I have a basic knowledge of Python but I don't see a way to get information from a running program.
A:
To my knowledge, banlist uses winpcap, an open source library fo... | How do you write a program that interacts with others like banlist for warcraft 3? | As in title, what is banlist written in, or can be written in? I have a basic knowledge of Python but I don't see a way to get information from a running program.
| [
"To my knowledge, banlist uses winpcap, an open source library for packet capture and network analysis for the Win32 platforms and \"understands\" (at least partially) the network traffic between the game running on your computer and Battle.net servers. Regarding Battle.net protocol, there is unofficial documentati... | [
3
] | [] | [] | [
"api",
"python",
"security"
] | stackoverflow_0001706158_api_python_security.txt |
Q:
How make Qt Designers autosize layouts work with Pyqt4?
I'm trying a simple example with Qt Designer and Pyqt4, when I preview the UI in Qt Designer (control+R) it looks good, but when I try to execute the generated UI code, layouts don't work properly and instead of autosizing widgets to the max they are so small... | How make Qt Designers autosize layouts work with Pyqt4? | I'm trying a simple example with Qt Designer and Pyqt4, when I preview the UI in Qt Designer (control+R) it looks good, but when I try to execute the generated UI code, layouts don't work properly and instead of autosizing widgets to the max they are so small that they can't be used.
If I use fixed sizes it works well.... | [
"This is a long shot, but isn't the code using QMainWindow and the XML ui-descripting defines a QWidget. I'm not sure if that is the problem, but it does not look 100% correct to me.\n"
] | [
0
] | [] | [] | [
"designer",
"pyqt",
"pyqt4",
"python",
"qt"
] | stackoverflow_0001747475_designer_pyqt_pyqt4_python_qt.txt |
Q:
Unable to unpickle a file on Mac that was pickled on Windows
I've got a simple class that I am pickling(dumping) to a file. On OS X this works fine, and on Windows this works fine.
However, while on windows I can load/unpickle the object fine - when windows then pickles this file and saves it back to disk, it beco... | Unable to unpickle a file on Mac that was pickled on Windows | I've got a simple class that I am pickling(dumping) to a file. On OS X this works fine, and on Windows this works fine.
However, while on windows I can load/unpickle the object fine - when windows then pickles this file and saves it back to disk, it becomes unreadable on OS X (although in Windows it still behaves as no... | [
"Pickle with the newest protocol version and open the files in binary mode in all cases. That should solve the problem.\n",
"It will be line endings - if you are using ASCII pickle open file in ascii mode 'r' or 'w' - if you are using a binary pickle open in binary mode 'rb' 'wb'. From the docstring:\n\nThe defau... | [
5,
3
] | [] | [] | [
"macos",
"pickle",
"python",
"windows"
] | stackoverflow_0001748958_macos_pickle_python_windows.txt |
Q:
How to implement restful webservice with python/django
i try to setup a ubuntu server with web service that create by django/python , anyone have an resource/tutorial/example code
A:
There is also piston, which is a Django framework for creating RESTful APIs. It has a slight learning curve, but nicely fits into... | How to implement restful webservice with python/django | i try to setup a ubuntu server with web service that create by django/python , anyone have an resource/tutorial/example code
| [
"There is also piston, which is a Django framework for creating RESTful APIs. It has a slight learning curve, but nicely fits into Django. \nIf you want something more lightweight, Simon Willison has very nice snippet that I have used previously that nicely models the HTTP methods:\nclass ArticleView(RestView):\n... | [
6,
1
] | [] | [] | [
"django",
"python",
"web_services"
] | stackoverflow_0001749005_django_python_web_services.txt |
Q:
Naming Conventions for Methods / Classes / Packages
What naming conventions do you use for everyday code? I'm pondering this because I currently have a project in Python that contains 3 packages, each with a unique purpose. Now, I've been putting general-purpose, 'utility' methods into the first package I created ... | Naming Conventions for Methods / Classes / Packages | What naming conventions do you use for everyday code? I'm pondering this because I currently have a project in Python that contains 3 packages, each with a unique purpose. Now, I've been putting general-purpose, 'utility' methods into the first package I created for the project, however I'm contemplating moving these m... | [
"In general, you should follow the naming convention of the language you're using. It doesn't matter if you like or prefer the standards of another language. Consistency within the context of the language helps make your code more readable, maintainable, and usable by others. In Python, that means you use PEP 8.\nU... | [
1,
0
] | [] | [] | [
"naming_conventions",
"python"
] | stackoverflow_0001749232_naming_conventions_python.txt |
Q:
How to detect whether two files are identical in Python
Is making system call to "md5sum file1" and "md5sum file2" and compare two return values enough in this case?
A:
If you want to do more than just detect if they differ, or don't trust the hashing solution, there are modules in the standard library called di... | How to detect whether two files are identical in Python | Is making system call to "md5sum file1" and "md5sum file2" and compare two return values enough in this case?
| [
"If you want to do more than just detect if they differ, or don't trust the hashing solution, there are modules in the standard library called difflib and filecmp that doesn't rely on external programs.\n",
"Well, that will tell you whether they're definitely different or probably the same. It's possible for two ... | [
15,
13,
13,
7,
3,
0,
0
] | [
"yes, it is enough\n"
] | [
-2
] | [
"compare",
"file",
"md5",
"python"
] | stackoverflow_0001748923_compare_file_md5_python.txt |
Q:
Remove one char from a string
I'd like to remove one char from a string like this:
string = "ASDFVGHFJHRSFDZFDJKUYTRDSEADFDHDS"
print len(string)
(33)
So i would like to remove one random char in this string, and then have a len = 32
What's the best way to do so ?
EDIT: thanks for your answers, but i forgot some... | Remove one char from a string | I'd like to remove one char from a string like this:
string = "ASDFVGHFJHRSFDZFDJKUYTRDSEADFDHDS"
print len(string)
(33)
So i would like to remove one random char in this string, and then have a len = 32
What's the best way to do so ?
EDIT: thanks for your answers, but i forgot something:
i'd like to print the char r... | [
">>> s=\"ASDFVGHFJHRSFDZFDJKUYTRDSEADFDHDS\"\n>>> r=random.randrange(len(string))\n>>> print s[:r]+s[r+1:]\nASDFVGHJHRSFDZFDJKUYTRDSEADFDHDS\n\n",
">>> import random\n>>> s = \"ASDFVGHFJHRSFDZFDJKUYTRDSEADFDHDS\"\n>>> i = random.randint(0, len(s)-1)\n>>> print s[:i] + s[i+1:]\nASDFVGHFJHRSFDZFDJKUYRDSEADFDHDS\n>>... | [
7,
5,
3
] | [] | [] | [
"python",
"string"
] | stackoverflow_0001749283_python_string.txt |
Q:
JavaScript equivalent of Python's __setitem__
var obj = {}
obj.__setitem__ = function(key, value){
this[key] = value * value
}
obj.x = 2 // 4
obj.y = 3 // 9
JavaScript doesn't have __setitem__ and this example obviously doesn't work.
In python __setitem__ works like:
class CustomDict(dict):
def __setitem__(... | JavaScript equivalent of Python's __setitem__ | var obj = {}
obj.__setitem__ = function(key, value){
this[key] = value * value
}
obj.x = 2 // 4
obj.y = 3 // 9
JavaScript doesn't have __setitem__ and this example obviously doesn't work.
In python __setitem__ works like:
class CustomDict(dict):
def __setitem__(self, key, value):
super(CustomDict, self).__se... | [
"\nIs it possible to implement __setitem__ behavior in JavaScript? \n\nNo. There is no getter/setter for arbitrary properties in JavaScript.\nIn Firefox you can use JavaScript 1.5+'s getters and setters to define x and y properties that square their values on assignment, eg.:\nvar obj= {\n _x: 0,\n get x() { ... | [
10,
7,
5,
5,
1
] | [] | [] | [
"javascript",
"python",
"syntactic_sugar"
] | stackoverflow_0001712074_javascript_python_syntactic_sugar.txt |
Q:
Cron in Google App Engine
I have made an app using Google App Engine in python of weekly Project and assessment report submitting.
I want to check that on Friday who have submitted the report and who don't just send the scheduled notification mail that he haven't submitted the report in last week.
but i don't wan... | Cron in Google App Engine | I have made an app using Google App Engine in python of weekly Project and assessment report submitting.
I want to check that on Friday who have submitted the report and who don't just send the scheduled notification mail that he haven't submitted the report in last week.
but i don't want to send the notification mail... | [
"Hard to fathom what you want (your English is very hard to parse), but anyway, besides Task Queues which are much more flexible and powerful (and may be harder to use for simple jobs that cron functionality covers perfectly), you can use cron to schedule App Engine tasks in Python by following the instructions her... | [
2,
0
] | [] | [] | [
"cron",
"google_app_engine",
"python"
] | stackoverflow_0001748074_cron_google_app_engine_python.txt |
Q:
Python, C: redirected stdout fires [Errno 9]
I try to log all the output of a program written in Python and C. However, printing from Python causes IOError: [Errno 9] Bad file descriptor
Please, does anyone know what the problem is and how to fix it?
PS: It's on Windows XP, Python 2.6 and MinGW GCC
#include <windo... | Python, C: redirected stdout fires [Errno 9] | I try to log all the output of a program written in Python and C. However, printing from Python causes IOError: [Errno 9] Bad file descriptor
Please, does anyone know what the problem is and how to fix it?
PS: It's on Windows XP, Python 2.6 and MinGW GCC
#include <windows.h>
#include <fcntl.h>
#include "Python.h"
int ... | [
"I think it could be to do with different C runtimes. I know you can't pass file descriptors between different C runtimes - Python is built with MSVC (you will need to check which version) - so you could try to make MinGW build against the same C runtime - I think there is options to do this in MinGW like -lmsvcrt8... | [
2
] | [] | [] | [
"c",
"python",
"stdout",
"windows"
] | stackoverflow_0001749762_c_python_stdout_windows.txt |
Q:
Python - Create html page with hyperlinks from os.listdir
I have a script that creates a folder called "videos" on a USB drive, moves 6,500 WMV files over to the "videos" folder. Then it's suppose to create an HTML page with hyperlinks to each file. Here is my current example that's broken. I'm trying to have it c... | Python - Create html page with hyperlinks from os.listdir | I have a script that creates a folder called "videos" on a USB drive, moves 6,500 WMV files over to the "videos" folder. Then it's suppose to create an HTML page with hyperlinks to each file. Here is my current example that's broken. I'm trying to have it crawl the videos directory and create an HTML page with hyperlin... | [
"import cgi\n\ndef is_video_file(filename):\n return filename.endswith(\".wmv\") # customize however you like\n\ndef createHTML():\n videoDirectory = os.listdir(\"videos\")\n with open(\"videos.html\", \"w\") as f:\n f.write(\"<html><body><ul>\\n\")\n for filename in videoDirectory:\n if is_video_file... | [
9,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0001749769_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.