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:
Python : How to ignore a delimited part of a sentence?
I have the following line :
CommonSettingsMandatory = #<Import Project="[\\.]*Shared(\\vc10\\|\\)CommonSettings\.targets," />#,true
and i want the following output:
['commonsettingsmandatory', '<Import Project="[\\\\.]*Shared(\\\\vc10\\\\|\\\\)CommonSettings\... | Python : How to ignore a delimited part of a sentence? | I have the following line :
CommonSettingsMandatory = #<Import Project="[\\.]*Shared(\\vc10\\|\\)CommonSettings\.targets," />#,true
and i want the following output:
['commonsettingsmandatory', '<Import Project="[\\\\.]*Shared(\\\\vc10\\\\|\\\\)CommonSettings\\.targets," />', 'true'
If i do a simple regex with the com... | [
"While you might be able to use split with a lookbehind, I would use the groups captured by this expression.\n(\\S+)\\s*=\\s*##([^#]+)##,\\s*(.*)\n\nm = re.Search(expression, myString). use m.group(1) for the first string, m.group(2) for the second, etc.\n",
"http://docs.python.org/library/re.html#re.split\nimpo... | [
0,
0,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0006442466_python_regex.txt |
Q:
Spawn a new non-blocking process using Python on Mac OS X
I found some articles and even stack|overflow questions addressing this subject, but I still can't do it..
What I want to do is open an instance of firefox from python. then the python application should keep minding its own business and ignore the firefox ... | Spawn a new non-blocking process using Python on Mac OS X | I found some articles and even stack|overflow questions addressing this subject, but I still can't do it..
What I want to do is open an instance of firefox from python. then the python application should keep minding its own business and ignore the firefox process.
I was able to achive this goal on Windows-7 and XP usi... | [
"To show what I meant:\nimport os\nif not os.fork():\n os.system('firefox')\nos._exit(0)\n\nVersion that doesn't quit the main Python process:\nimport os\nif not os.fork():\n os.system('firefox')\n os._exit(0)\n\n",
"You'll need to detach the process somehow. I snatched this from spawning process from py... | [
3,
2
] | [] | [] | [
"macos",
"nonblocking",
"python",
"subprocess"
] | stackoverflow_0006441807_macos_nonblocking_python_subprocess.txt |
Q:
Python - How to import functions?
models.py
def operation(argument):
#Operation
return variable
class X(models.Model)
a = models ...
b = models ...
I am trying to import operation in my views.py .. When I try using
from project.models import operation
But then I get the fo... | Python - How to import functions? | models.py
def operation(argument):
#Operation
return variable
class X(models.Model)
a = models ...
b = models ...
I am trying to import operation in my views.py .. When I try using
from project.models import operation
But then I get the following error
ImportError: cannot im... | [
"You would have to import the class to get access to the instance method you've defined on the class.\n",
"/* */ aren't valid comment characters in python, which is causes a parse error, so the import fails. Use # instead.\nAlso, you'll want to get an instance of X then call the operation method on that. Like:\... | [
0,
0
] | [] | [] | [
"import",
"python",
"syntax"
] | stackoverflow_0006442959_import_python_syntax.txt |
Q:
Correct path to run python script with php from cgi-bin folder
I want to run python script 'test.py' from my cgi-bin directory on my webserver. the cgi-bin directory is at 'www/cgi-bin/'. The python scrip is in that directory. The php code I'm executing is at 'www/html/website/index.php'.
what is the correct pat... | Correct path to run python script with php from cgi-bin folder | I want to run python script 'test.py' from my cgi-bin directory on my webserver. the cgi-bin directory is at 'www/cgi-bin/'. The python scrip is in that directory. The php code I'm executing is at 'www/html/website/index.php'.
what is the correct path that goes here ------> exec('path');
TYVM
edit:
My python script ... | [
"Assuming the PHP script is in the same directory as the \"www\" directory.\n<?\n exec('./www/cgi-bin/test.py'); \n?>\n\nor without chmoding, you can run it through Python\n<?\n exec('python ./www/cgi-bin/test.py'); \n?>\n\n",
"Your PHP code is executing in the www/html/website/ directory then. You need to ... | [
0,
0
] | [] | [] | [
"cgi_bin",
"php",
"python"
] | stackoverflow_0006442870_cgi_bin_php_python.txt |
Q:
Google AppEngine startup times
I've already read how to avoid slow ("cold") startup times on AppEngine, and implemented the solution from the cookbook using 10 second polls, but it doesn't seem to help a lot.
I use the Python runtime, and have installed several handlers to handle my requests, none of them doing so... | Google AppEngine startup times | I've already read how to avoid slow ("cold") startup times on AppEngine, and implemented the solution from the cookbook using 10 second polls, but it doesn't seem to help a lot.
I use the Python runtime, and have installed several handlers to handle my requests, none of them doing something particularly time consuming ... | [
"The \"appropriate\" way of avoiding slow too many slow startup times is to use the \"always on\" option. Of course, this is not a free option ($0.30 per day).\n"
] | [
5
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0006443268_google_app_engine_python.txt |
Q:
Debugging Python pygame being run through livewires
Python seems to completely ignore one of my objects - the games.Text object. Can't seem to understand why, syntax seems correct. Here's the code.
from livewires import games
#Creating and validating the pygame screen.
myscreen = games.Screen ()
#Loading an image... | Debugging Python pygame being run through livewires | Python seems to completely ignore one of my objects - the games.Text object. Can't seem to understand why, syntax seems correct. Here's the code.
from livewires import games
#Creating and validating the pygame screen.
myscreen = games.Screen ()
#Loading an image into memory to create an image object
wall_image = games... | [
"Your problem seems to be some combination of misspelling \"colour\" in a few places (this package is from the UK), forgetting\nfrom livewires import colour\n\nand failing to notice an error message:\nNameError: name 'color' is not defined\n\nAt least I assume that's your problem, because after those changes it run... | [
1
] | [] | [] | [
"debugging",
"livewires",
"pygame",
"python"
] | stackoverflow_0006443145_debugging_livewires_pygame_python.txt |
Q:
Python how to grab certain number of lines after match
Let's say I have an input text file of the following format:
Section1 Heading Number of lines: n1
Line 1
Line 2
...
Line n1
Maybe some irrelevant lines
Section2 Heading Number of lines: n2
Line 1
Line 2
...
Line n2
where certain sections of the file st... | Python how to grab certain number of lines after match | Let's say I have an input text file of the following format:
Section1 Heading Number of lines: n1
Line 1
Line 2
...
Line n1
Maybe some irrelevant lines
Section2 Heading Number of lines: n2
Line 1
Line 2
...
Line n2
where certain sections of the file start with a header line that specifies how many lines are in ... | [
"# f is a file object\n# n1 is how many lines to read\nlines = [f.readline() for i in range(n1)]\n\n",
"You can put logic like this in a generator:\ndef take(seq, n):\n \"\"\" gets n items from a sequence \"\"\"\n return [next(seq) for i in range(n)]\n\ndef getblocks(lines):\n # `it` is a iterator and kn... | [
2,
0
] | [] | [] | [
"lines",
"printing",
"python",
"text_files"
] | stackoverflow_0006443392_lines_printing_python_text_files.txt |
Q:
Notepad++ Scripting: How to remove Newline?
I'm currently writing a very simple script in PythonScript for a basic ASCII checkbox support in a text file.
The plan is that when I hit Alt+F2 the editor toggles [ ] to [x] and [x] to [ ] if the line starts with the checkboxes or otherwise to just insert a [ ] at the c... | Notepad++ Scripting: How to remove Newline? | I'm currently writing a very simple script in PythonScript for a basic ASCII checkbox support in a text file.
The plan is that when I hit Alt+F2 the editor toggles [ ] to [x] and [x] to [ ] if the line starts with the checkboxes or otherwise to just insert a [ ] at the current position.
I've written a script which work... | [
"Use the editor.replaceWholeLine method with the editor.replaceLine method. \nThe script above works now\n"
] | [
2
] | [] | [] | [
"notepad++",
"python",
"scripting"
] | stackoverflow_0006443484_notepad++_python_scripting.txt |
Q:
Fabian Gallina's python.el: imenu support
Can someone share instructions how can I get working imenu support with Fabian Gallina's python.el?
This is the commit that introduced imenu support, but my understanding of elisp is very low:
https://github.com/fgallina/python.el/commit/938e03cf6cdfcc30de84a4ec428aef9ff3c... | Fabian Gallina's python.el: imenu support | Can someone share instructions how can I get working imenu support with Fabian Gallina's python.el?
This is the commit that introduced imenu support, but my understanding of elisp is very low:
https://github.com/fgallina/python.el/commit/938e03cf6cdfcc30de84a4ec428aef9ff3c0c852
Currently I opened python file (major mod... | [
"I have resolved it like this:\n(add-hook 'python-mode-hook\n (lambda ()\n (setq imenu-create-index-function 'python-imenu-create-index)))\n\n"
] | [
4
] | [] | [] | [
"emacs",
"python"
] | stackoverflow_0006317667_emacs_python.txt |
Q:
Returning a file in uploads directory with web2py - strings issue
I have users upload files into a fake directory structure using a database. I have fields for the parent path & the filename & the file (file is of type "upload") that I set using my controller. I can see that files are properly being stored in th... | Returning a file in uploads directory with web2py - strings issue | I have users upload files into a fake directory structure using a database. I have fields for the parent path & the filename & the file (file is of type "upload") that I set using my controller. I can see that files are properly being stored in the uploads directory so that is working. Just for reference I store the... | [
"You're almost right. Try:\nos.path.join(request.folder,'uploads',file.file)\n\n",
"Python strings are sequence types, and therefore iterable. When you submit a single string as an argument to the join method, it iterates over each character in the string. So, for example:\n>>> '/'.join('hello')\n'h/e/l/l/o'\n\n... | [
4,
1
] | [] | [] | [
"python",
"web2py"
] | stackoverflow_0006439252_python_web2py.txt |
Q:
Debugging Python pygame program
from livewires import games, color
#Creating and validating the pygame screen.
scrwidth = 640
scrheight = 480
fps = 50
myscr = games.Screen(scrwidth, scrheight)
#Loading an image into memory to create an image object
wall_image = games.load_image("wall.jpg", transparent = False)
my... | Debugging Python pygame program | from livewires import games, color
#Creating and validating the pygame screen.
scrwidth = 640
scrheight = 480
fps = 50
myscr = games.Screen(scrwidth, scrheight)
#Loading an image into memory to create an image object
wall_image = games.load_image("wall.jpg", transparent = False)
myscr.set_background (wall_image)
#Prin... | [
"I think i know whats happening, if i am not wrong you could be assuming that \ngames.init(screen_width = 640, screen_height = 480, \n fps = 50)\nis the same thing as \nscrwidth = 640\nscrheight = 480\nfps = 50\ngames.init(scrwidth, scrheight)\n\nBut that may not the case, the arguments int Screen look fo... | [
2
] | [] | [] | [
"debugging",
"pygame",
"python"
] | stackoverflow_0006443869_debugging_pygame_python.txt |
Q:
Authorization in social networking website
I need to accomplish the following related to privileges:
I have 3 users:
- User A
- User B
- User C
Each of the users has the following documents with associated access settings:
- User A
- Document A1, only allow contacts to view
- Document A2, allow everyone t... | Authorization in social networking website | I need to accomplish the following related to privileges:
I have 3 users:
- User A
- User B
- User C
Each of the users has the following documents with associated access settings:
- User A
- Document A1, only allow contacts to view
- Document A2, allow everyone to view
- Document A3, allow no one to view e... | [
"Unfortunately Django's authorization system does not allow you to assign permissions per object, only per class. Here I assume that each of your \"Document\" is an instance of a model class.\nThere are, however, reusable apps that greatly simplify this task. Have a look at django-guardian or other packages that wo... | [
7,
5,
3,
3,
0
] | [] | [] | [
"authorization",
"django",
"python",
"social_networking"
] | stackoverflow_0006328590_authorization_django_python_social_networking.txt |
Q:
How to structure a python cmd application which has separate command modules
I'm writing a python command-line tool using the cmd2 module which is an enhanced version of cmd. The tool is an administration application and is used to administer a number of sub-modules.
I'd like to structure the code so that each sub... | How to structure a python cmd application which has separate command modules | I'm writing a python command-line tool using the cmd2 module which is an enhanced version of cmd. The tool is an administration application and is used to administer a number of sub-modules.
I'd like to structure the code so that each sub-module has its own class responsible for providing the commands that can be execu... | [
"You may have some luck structuring your SubModules as Plugins to the main ConsoleApp. You'd need a couple of new methods on ConsoleApp. Something like add_command_module(self, klass) which would just append the klass (SubModuleA for example) to some list inside ConsoleApp.\nThen in ConsoleApp, override the onecmd ... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0006341039_python.txt |
Q:
What gui elements to be used?
I'm trying to create a journal entry interface, similar to those well known accounting softwares using wxpython for the gui and psycopg2 as backend. I tried doing it with a listctrl, but its use is not for that particular interaction. My question, is there a built-in widgets closely r... | What gui elements to be used? | I'm trying to create a journal entry interface, similar to those well known accounting softwares using wxpython for the gui and psycopg2 as backend. I tried doing it with a listctrl, but its use is not for that particular interaction. My question, is there a built-in widgets closely related to those elements?.
| [
"Download the wxPython Docs and Demos from http://wxpython.org/download.php. The demo allows you to \"shop\" for widgets easier since you get to see them in action and can view the code used to create them. I suggest checking out the UltimateListCtrl.\n"
] | [
1
] | [] | [] | [
"psycopg2",
"python",
"wxpython",
"wxwidgets"
] | stackoverflow_0006362373_psycopg2_python_wxpython_wxwidgets.txt |
Q:
Tornado 'Hello World' Error
I am trying to run the following HelloWorld Script at Command Line
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
from tornado.options import define, options
define("port", default=8888, help="run on the given port", type=int)
class MainHand... | Tornado 'Hello World' Error | I am trying to run the following HelloWorld Script at Command Line
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
from tornado.options import define, options
define("port", default=8888, help="run on the given port", type=int)
class MainHandler(tornado.web.RequestHandler):... | [
"As you've found out yourself, the problem is that python 2.4 does not support the conditional expression operator.\nHow you can switch to another Python version depends on your system. On debian and Ubuntu, you can edit /usr/share/python/debian_defaults. On all Linux systems, you can remove /usr/bin/python and lin... | [
2,
1
] | [] | [] | [
"python",
"tornado"
] | stackoverflow_0006443643_python_tornado.txt |
Q:
Install Python extension to specific location
My project mix pure Python code, and Cython extensions for optimization and for linking with C libraries. I have one source tree for my Python project, and one for Cython and C code. My Cython extensions each have a setup.py file to build them. Actually, for each exten... | Install Python extension to specific location | My project mix pure Python code, and Cython extensions for optimization and for linking with C libraries. I have one source tree for my Python project, and one for Cython and C code. My Cython extensions each have a setup.py file to build them. Actually, for each extension, I do the following:
python setup.py build_ext... | [
"I finally found the answer! The option is -b (or --build_lib)\npython setup.py build_ext -b ../some/specific/place/\n\n",
"Maybe you could use the alternate installation functionnality of distutils which will allow you to remove the useless hierarchy folders.\nTry something like this :\npython setup.py install -... | [
9,
0
] | [] | [] | [
"distutils",
"python"
] | stackoverflow_0006362466_distutils_python.txt |
Q:
Confused by which XML processing option to use
I'm fairly new to Python, and I've just started working with XML parsing. I am getting a bit overwhelmed by all the options for working with XML, and I'm hoping an experienced person can give me some advice (and perhaps a code sample??) for the simple problem I'm wor... | Confused by which XML processing option to use | I'm fairly new to Python, and I've just started working with XML parsing. I am getting a bit overwhelmed by all the options for working with XML, and I'm hoping an experienced person can give me some advice (and perhaps a code sample??) for the simple problem I'm working on.
I am working on a simple Python contact man... | [
"The best solution is to use ElementTree and parse this into a set of classes and manipulate the classes and then serialize them back to XML. You can do this by hand if the XML is really as simple as your example or you can use some tool or library to generate the bindings. \nWorking directly with XML in most cases... | [
2,
2
] | [] | [] | [
"dom",
"elementtree",
"minidom",
"python",
"xml"
] | stackoverflow_0006443839_dom_elementtree_minidom_python_xml.txt |
Q:
Using a Python Script in Java (Eclipse)
I've been looking to incorporate a Python Script a friend made for me into a Java application that I am trying to develop. After some trial and error I finally found out about 'Jython' and used the PythonInterpreter to try and run the script.
However, upon trying to run it,... | Using a Python Script in Java (Eclipse) | I've been looking to incorporate a Python Script a friend made for me into a Java application that I am trying to develop. After some trial and error I finally found out about 'Jython' and used the PythonInterpreter to try and run the script.
However, upon trying to run it, I am getting an error within the Python Scri... | [
"My guess is that you don't get command line arguments if the interpreter is called (well not that surprisingly, where should it get the correct values? [or what would be the correct value?]). \n\nos.getcwd()\nReturn a string representing the current working directory.\n\n\nWould return the working dir, but presuma... | [
2
] | [] | [] | [
"eclipse",
"interpreter",
"java",
"jython",
"python"
] | stackoverflow_0006444131_eclipse_interpreter_java_jython_python.txt |
Q:
Problem with forms and Photologue
I'm using Pinax to create a new project. For this project I needed to create a new app 'Business' which is much like Profiles but they wanted to keep everything seperate for Businesses.
I'm trying to have the admin be able to change the logo or "avatar" for the business profile. ... | Problem with forms and Photologue | I'm using Pinax to create a new project. For this project I needed to create a new app 'Business' which is much like Profiles but they wanted to keep everything seperate for Businesses.
I'm trying to have the admin be able to change the logo or "avatar" for the business profile. Im using the ImageModel class from Pho... | [
"The ChangeLogoForm's model is BusinessLogo, but when calling it's constructor you pass it a Business instance:\nb = get_object_or_404(Business, pk = bus_id)\n...\nform = ChangeLogoForm(request.POST, request.FILES, instance = b)\n\n(And you should probably use a OneToOneField field instead of ForeignKey)\n"
] | [
0
] | [] | [] | [
"django",
"django_models",
"django_views",
"pinax",
"python"
] | stackoverflow_0006441171_django_django_models_django_views_pinax_python.txt |
Q:
Python function return to jQuery var
I've a python script that returns something. In a html page, I use jQuery to send a GET request to this script (with $.get()). I want the "return" of python script in a jQuery/javascript var. Is it possible with jQuery function? Without use JSON or other.
A:
$.get("url", func... | Python function return to jQuery var | I've a python script that returns something. In a html page, I use jQuery to send a GET request to this script (with $.get()). I want the "return" of python script in a jQuery/javascript var. Is it possible with jQuery function? Without use JSON or other.
| [
"$.get(\"url\", function (response) { \n var myVar = response;\n // Do stuff with variable here\n});\n\nIf the response contains HTML, you can use $(response) to get a jquery object to do operations on, but the response object itself is already a string.\n",
"Try setting the dataType parameter to HTML. So in t... | [
1,
1,
0
] | [
"Why would you say \"without using JSON\"? That's exactly what JSON is for.\n"
] | [
-2
] | [
"jquery",
"python"
] | stackoverflow_0006444458_jquery_python.txt |
Q:
How to tweak my tooltips in wxpython?
I was trying to add a tooltip to show the full content of a truncated ObjectListView, until it turned out it had such a feature built-in:
I tried making my own tool tips using wx.TipWindow, wx.PopupWindow and SuperToolTip, but none of them looked as 'native' as this one.
Wh... | How to tweak my tooltips in wxpython? | I was trying to add a tooltip to show the full content of a truncated ObjectListView, until it turned out it had such a feature built-in:
I tried making my own tool tips using wx.TipWindow, wx.PopupWindow and SuperToolTip, but none of them looked as 'native' as this one.
While I'm aware of this wiki article that sup... | [
"I'm not sure if we have a way to create a native Win7 tooltip yet, as you've seen wx.TipWindow looks like the tooltips from older versions of Windows, so there are probably some newer APIs that we should be using instead. Please create a ticket at trac.wxwidgets.org to find out for sure or to request the change i... | [
4,
1
] | [] | [] | [
"python",
"tooltip",
"wxpython"
] | stackoverflow_0006415104_python_tooltip_wxpython.txt |
Q:
Setting up Cx_Oracle
I am running ...
SQL*Plus: Release 9.2.X.X.X - Production on Wed Jun 22 13:02:14 2011
Copyright (c) 1982, 2002, Oracle Corporation. All rights reserved.
Connected to:
Oracle Database 10g Enterprise Edition Release 10.2.X.X.X - 64bit Production
With the Partitioning, OLAP and Data Mining opt... | Setting up Cx_Oracle | I am running ...
SQL*Plus: Release 9.2.X.X.X - Production on Wed Jun 22 13:02:14 2011
Copyright (c) 1982, 2002, Oracle Corporation. All rights reserved.
Connected to:
Oracle Database 10g Enterprise Edition Release 10.2.X.X.X - 64bit Production
With the Partitioning, OLAP and Data Mining options
with Python version... | [
"Your Oracle client should match the cx_Oracle version. Any reason for using the Oracle 9 client? You should be able to just download and install the version 10 (or even 11 client), and matching cx_Oracle version. They will both work with Oracle 10g.\nWe use Oracle 10g at work, and I use the 11g client (and corr... | [
1
] | [] | [] | [
"cx_oracle",
"database",
"python"
] | stackoverflow_0006444251_cx_oracle_database_python.txt |
Q:
how to save image using python?
I want to save a .jsp image from a web page in to my computer using python.
I have tried many methods including
retrieve function in mechanize and
urllib.urlretrieve('http://example.com/img.jsp', 'img.jsp')
but the problem is when I try to open the image using the image library it t... | how to save image using python? | I want to save a .jsp image from a web page in to my computer using python.
I have tried many methods including
retrieve function in mechanize and
urllib.urlretrieve('http://example.com/img.jsp', 'img.jsp')
but the problem is when I try to open the image using the image library it throws the following error
File "c... | [
"You haven't provided enough information, but my guess is that the web server isn't responding the way you think it is -- did you peek the HTTP traffic with Fiddler or Firebug or look at what's in the file?\nCan you get a copy of the image some other way -- if so, compare that to what you downloaded programmaticall... | [
0
] | [] | [] | [
"image",
"image_manipulation",
"jsp",
"mechanize",
"python"
] | stackoverflow_0006437095_image_image_manipulation_jsp_mechanize_python.txt |
Q:
Downloading Javascript File from Website using Python
I am trying to use python to download the results from the following website:
http://david.abcc.ncifcrf.gov/api.jsp?type=GENBANK_ACCESSION&ids=CP000010,CP000125,CP000124,CP000124,CP000124,CP000124&tool=chartReport&annot=KEGG_PATHWAY
I was attempting to use me... | Downloading Javascript File from Website using Python | I am trying to use python to download the results from the following website:
http://david.abcc.ncifcrf.gov/api.jsp?type=GENBANK_ACCESSION&ids=CP000010,CP000125,CP000124,CP000124,CP000124,CP000124&tool=chartReport&annot=KEGG_PATHWAY
I was attempting to use mechanize before I realized that the Download File is written... | [
"After some more research on that link, I came up with this. You can definitely use mechanize to do it.\nimport mechanize\n\ndef getJSVariableValue(content, variable):\n value_start_index = content.find(variable)\n value_start_index = content.find('\"', value_start_index) + 1\n\n value_end_index = content.... | [
2
] | [] | [] | [
"bioinformatics",
"download",
"javascript",
"python"
] | stackoverflow_0006444824_bioinformatics_download_javascript_python.txt |
Q:
Using repoze.what with declarative syntax in pylons
I'm writing an application in Pylons and I want to add an authorization scheme. I've chosen repoze.what. I followed the tutorial from Pylons cookbook:
http://wiki.pylonshq.com/display/pylonscookbook/Authorization+with+repoze.what
The problem is that in lib/auth.p... | Using repoze.what with declarative syntax in pylons | I'm writing an application in Pylons and I want to add an authorization scheme. I've chosen repoze.what. I followed the tutorial from Pylons cookbook:
http://wiki.pylonshq.com/display/pylonscookbook/Authorization+with+repoze.what
The problem is that in lib/auth.py I need to include models for User, Group and Permission... | [
"In the model __init__.py you need to bind the engine to the session.\ndef init_model(engine):\n \"\"\"Call me before using any of the tables or classes in the model\"\"\"\n ## Reflected tables must be defined and mapped here\n #global reflected_table\n #reflected_table = sa.Table(\"Reflected\", meta.me... | [
0,
0
] | [] | [] | [
"pylons",
"python",
"sqlalchemy"
] | stackoverflow_0006397318_pylons_python_sqlalchemy.txt |
Q:
Insert Data to multiple MySQL database tables from .csv file
I have a database with tables: person, player, coach, and team. All the tables have an auto-increment id field as the primary key. Person has id, firstname, lastname. Player and coach both have the id field, as well as person_id and team_id as foreign ke... | Insert Data to multiple MySQL database tables from .csv file | I have a database with tables: person, player, coach, and team. All the tables have an auto-increment id field as the primary key. Person has id, firstname, lastname. Player and coach both have the id field, as well as person_id and team_id as foreign keys to tie them to a team.id or person.id field in the other tables... | [
"Using an ORM might be an overkill for your purpose, but it makes your life easy if you need to do real work with data. It will require you to install some software, but if you are willing to learn some new stuff, you will probably gain a lot down the road. Luckily, it is not very hard to start using it, for exam... | [
1,
1
] | [] | [] | [
"bash",
"csv",
"mysql",
"python"
] | stackoverflow_0006444885_bash_csv_mysql_python.txt |
Q:
Concatenation in Python, concatenating lists and strings
i'm not sure if this is the correct syntax to do this, but i want to print out a specific element in a list.
user,activity,data=readfile('data.txt')
kclust,clusters=kcluster(data,k=3)
for i in range(len(kclust)):
print "Cluster %d: ??" % (i+1,clusters[... | Concatenation in Python, concatenating lists and strings | i'm not sure if this is the correct syntax to do this, but i want to print out a specific element in a list.
user,activity,data=readfile('data.txt')
kclust,clusters=kcluster(data,k=3)
for i in range(len(kclust)):
print "Cluster %d: ??" % (i+1,clusters[i])
print [[userobjectIds[r] for r in kclust[i]][:3]]
... | [
"You can use %r:\n\n'r': String (converts any Python object using repr()).\n\nprint \"Cluster %d: %r\" % (i+1,clusters[i])\n\n",
"I don't know about kcluster function, but it seems it returns a list, not a number. Alternatively, you could try:\nprint \"Cluster %d:\"%(i+1), clusters[i]\n\n"
] | [
5,
0
] | [] | [] | [
"concatenation",
"list",
"python",
"string"
] | stackoverflow_0006445590_concatenation_list_python_string.txt |
Q:
Regex to return all characters until "/" searching backwards
I'm having trouble with this regex and I think I'm almost there.
m =re.findall('[a-z]{6}\.[a-z]{3}\.[a-z]{2} (?=\" target)', 'http://domain.com.uy " target')
This gives me the "exact" output that I want. that is domain.com.uy but obviously this is just ... | Regex to return all characters until "/" searching backwards | I'm having trouble with this regex and I think I'm almost there.
m =re.findall('[a-z]{6}\.[a-z]{3}\.[a-z]{2} (?=\" target)', 'http://domain.com.uy " target')
This gives me the "exact" output that I want. that is domain.com.uy but obviously this is just an example since [a-z]{6} just matches the previous 6 characters a... | [
"try this (maybe you need to escape / in Python):\n/([^/]*)$\n\n",
"Another option is to use a positive lookbehind such as (?<=//):\n>>> re.search(r'(?<=//).+(?= \\\" target)', \n... 'http://domain.com.uy \" target').group(0)\n'domain.com.uy'\n\nNote that this will match slashes within the url itself, i... | [
1,
1,
1,
0
] | [] | [] | [
"findall",
"python",
"regex"
] | stackoverflow_0006445436_findall_python_regex.txt |
Q:
Python 2.6 Django MYSQLDB error
Getting started with Django 1.3.1 and Upon running
python manage.py syncdb
with Python 2.6. I keep getting an error loading mysqldb module: No module named mysqldb message. I have tried doing sudo yum install python-mysql and sudo yum install python-mysqldb
on a CentOS 5 system bu... | Python 2.6 Django MYSQLDB error | Getting started with Django 1.3.1 and Upon running
python manage.py syncdb
with Python 2.6. I keep getting an error loading mysqldb module: No module named mysqldb message. I have tried doing sudo yum install python-mysql and sudo yum install python-mysqldb
on a CentOS 5 system but I get a "no package found" message ... | [
"There's no point using the system packaging tools if you're using a different Python version to the one provided by the system. You'll have to use the Python packaging tools instead - eg easy_install mysqldb.\n",
"If you are just getting started with Django you should really take a look at virtualenv and pip. \n... | [
0,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0006445327_django_python.txt |
Q:
Using an Excel table format in python
I have an Excel table saved as a CSV that looks something like (when it's in Excel) this just longer:
Monday Tuesday Wednesday Thursday Friday
marsbar 9 8 0 6 5
reeses 0 0 0 9 0
twix 2 3 0 5 6
snickers 9 8 0 6 5
(The format... | Using an Excel table format in python | I have an Excel table saved as a CSV that looks something like (when it's in Excel) this just longer:
Monday Tuesday Wednesday Thursday Friday
marsbar 9 8 0 6 5
reeses 0 0 0 9 0
twix 2 3 0 5 6
snickers 9 8 0 6 5
(The format isnt perfect, but you get the gist--candy ... | [
"We can help you write such a program, yes.\nWe will not write the program for you (that's not what StackOverflow is about).\nPython comes with a CSV module, which will read in an Excel-saved CSV file. \nYou can store your data in a dictionary, which will make it easier to retrieve.\nGood luck!\n",
"Maybe with th... | [
3,
2,
2,
1,
0
] | [] | [] | [
"python",
"tabular"
] | stackoverflow_0006444632_python_tabular.txt |
Q:
Strip javascript code before rendering in django templates
{% if posts %}
{% for p in posts %}
{{p|safe}}
{% endfor %}
{% endif %}
I want this to render html but not javascript, what should I do?
A:
There is no filter in django that can do what ou want: strip javascript and leave html.
You can c... | Strip javascript code before rendering in django templates | {% if posts %}
{% for p in posts %}
{{p|safe}}
{% endfor %}
{% endif %}
I want this to render html but not javascript, what should I do?
| [
"There is no filter in django that can do what ou want: strip javascript and leave html.\nYou can create a custom template filter to do that:\nfrom django import template\nfrom django.template.defaultfilters import stringfilter\nfrom django.utils.safestring import mark_safe\nfrom django.utils.encoding import force_... | [
4
] | [] | [] | [
"django",
"javascript",
"python"
] | stackoverflow_0006444893_django_javascript_python.txt |
Q:
MySQLdb AND Python 2.6
How does one get the MySQLdb module for Python 2.6?
I am on a CentOS 5 distribution and easy_install MySQLdb does not work for me. (cant find MySQLdb at pypy.python.org/simple/)
Thanks!
A:
Have you tried it manually?
download the source
untar the file
cd into the MySQL-python-1.2.3 folder... | MySQLdb AND Python 2.6 | How does one get the MySQLdb module for Python 2.6?
I am on a CentOS 5 distribution and easy_install MySQLdb does not work for me. (cant find MySQLdb at pypy.python.org/simple/)
Thanks!
| [
"Have you tried it manually?\n\ndownload the source\nuntar the file\ncd into the MySQL-python-1.2.3 folder\npython setup.py install\n\n"
] | [
1
] | [] | [] | [
"easy_install",
"mysql",
"python"
] | stackoverflow_0006445898_easy_install_mysql_python.txt |
Q:
Calling methods from a dynamic list of modules
I'm trying to do two things here, dynamically import all modules in a directory (the amount/names are unknown) and then for each of those modules found call a function called checkMe(). checkMe() is guaranteed to be in each module, so there is no need to check. This i... | Calling methods from a dynamic list of modules | I'm trying to do two things here, dynamically import all modules in a directory (the amount/names are unknown) and then for each of those modules found call a function called checkMe(). checkMe() is guaranteed to be in each module, so there is no need to check. This is what I have so far:
Import
import sys
import os
im... | [
"__import__ has some tricky semantics regarding packages (directories containing an __init__.py) vs modules. You would need to use the fromlist argument to make it work. As it is, running a module by path is easiest with runpy (from the comments: run_path needs Python 2.7 or newer):\nimport runpy\nrunpy.run_path('p... | [
0
] | [] | [] | [
"module",
"python"
] | stackoverflow_0006445901_module_python.txt |
Q:
How to detect and mask missing data on imported csv files in Python?
I am very new to Python and I have been trying to detect missing data in lists created from data in imported csv files so that I can plot the series using matplotlib without getting an error.
I show you what I have:
import numpy as np
# import ma... | How to detect and mask missing data on imported csv files in Python? | I am very new to Python and I have been trying to detect missing data in lists created from data in imported csv files so that I can plot the series using matplotlib without getting an error.
I show you what I have:
import numpy as np
# import matplotlib.pyplot as plt
import csv
from pylab import *
res = csv.reader(op... | [
"What do you mean by mask? Remove? If so, try the following:\nmasked_data = [point for point in data if point != '']\n\nEdit:\nI'm not used to numpy, but maybe this is what you are searching for:\n>>> data = numpy.array(['0', '', '1', '', '2'])\n>>> numpy.ma.masked_where(data == '', data)\nmasked_array(data = [0 --... | [
1,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0006445493_python.txt |
Q:
Adding to the dir() of instance
I have a class (named "A") with some instance variables. I want to add the dir() of this variables to the dir() of instances of class A.
For example:
class A(object):
def __init__(self, x, y):
self.x = x
self.y = y
class X(object):
def f_x(self):
pass... | Adding to the dir() of instance | I have a class (named "A") with some instance variables. I want to add the dir() of this variables to the dir() of instances of class A.
For example:
class A(object):
def __init__(self, x, y):
self.x = x
self.y = y
class X(object):
def f_x(self):
pass
class Y(object):
def f_y(self):
... | [
"Why don't you simply inherit from both classes?\nclass B(A, X):\n pass\n\na = B()\ndir(a)\n\n",
"A should really be a subclass of X and Y in this case. (Just be sure to read Michele Simionato's article on super and diamond inheritence before you get too deep into it.)\nclass X(object):\n def f_x(self):\n ... | [
2,
2
] | [] | [] | [
"python"
] | stackoverflow_0006446094_python.txt |
Q:
Exact semantics of Matplotlib's "interactive mode" (ion(), ioff())?
The documentation for the "interactive mode" in Matplotlib's pyplot reads:
The interactive property of the pyplot interface controls whether a figure canvas is drawn on every pyplot command. If interactive is False, then the figure state is updat... | Exact semantics of Matplotlib's "interactive mode" (ion(), ioff())? | The documentation for the "interactive mode" in Matplotlib's pyplot reads:
The interactive property of the pyplot interface controls whether a figure canvas is drawn on every pyplot command. If interactive is False, then the figure state is updated on every plot command, but will only be drawn on explicit calls to dra... | [
"Here is the summary of an interesting discussion on this subject in the Matplotlib mailing list. The executive summary is:\n\nThe interactive mode (activated with ion()) automates many things. In particular, pyplot.* commands automatically update on the screen the relevant axes. However, method calls on Matplot... | [
16,
4
] | [] | [] | [
"interactive_mode",
"matplotlib",
"python"
] | stackoverflow_0006130341_interactive_mode_matplotlib_python.txt |
Q:
how to couple 'reasons' with return values, elegantly
What often happens in code I'm writing is I'll have a function that checks a condition dependent on many other conditions, e.g.:
def is_foo(bar):
if X: return True
if Y: return False
if Z: return True
return False
Then, I'll want to debug my co... | how to couple 'reasons' with return values, elegantly | What often happens in code I'm writing is I'll have a function that checks a condition dependent on many other conditions, e.g.:
def is_foo(bar):
if X: return True
if Y: return False
if Z: return True
return False
Then, I'll want to debug my code or log it, so I'll change the above to:
def is_foo_reaso... | [
"This is a perfectly good way to do it. Only thing I might change is nest is_foo_reason in is_foo (so that there's only one, simple interface) and add a default argument to is_foo(), e.g.\n#for backwards compatibility:\ndef is_foo(bar, reason=False): \n def is_foo_reason(bar):\n if X: return True, \"cause... | [
8,
4,
1
] | [] | [] | [
"python"
] | stackoverflow_0006446603_python.txt |
Q:
Get easy_install to work with more recent version of Python
Python 2.4 was the default on my CentOS5 system. I now have Python 2.6 running and I am trying to do an easy_install.
I installed the setuptools egg file for Python 2.6. py26 is on username.sitename.com while python 2.4 is installed system wide so I curr... | Get easy_install to work with more recent version of Python | Python 2.4 was the default on my CentOS5 system. I now have Python 2.6 running and I am trying to do an easy_install.
I installed the setuptools egg file for Python 2.6. py26 is on username.sitename.com while python 2.4 is installed system wide so I currently just get a permission denied error when i run
easy_install... | [
"Actually easy_install has the option of specifying the Python version to use a la:\neasy_install-N.N \n\nSo in this case I just do easy_install-2.6\nShould have looked it up more closely before posting!\nusing easy-install\n",
"You can also force Python interpreter to run easy_install.\n python2.6 /usr/bin/easy_... | [
2,
1,
0
] | [] | [] | [
"easy_install",
"python",
"setuptools"
] | stackoverflow_0006445580_easy_install_python_setuptools.txt |
Q:
What is the significance of the 'P' in LAMP? Why is it PHP, Perl, or Python?
I'm a Java web developer that knows a bit of Python (but haven't done any Python web development), and I am curious what exactly is meant by a LAMP stack.
I understand this to be Linux-Apache-MySQL-(PHP, Perl, or Python), but I don't unde... | What is the significance of the 'P' in LAMP? Why is it PHP, Perl, or Python? | I'm a Java web developer that knows a bit of Python (but haven't done any Python web development), and I am curious what exactly is meant by a LAMP stack.
I understand this to be Linux-Apache-MySQL-(PHP, Perl, or Python), but I don't understand what unites these three languages other than the letter P.
Is a LAMP stack ... | [
"It's just so happens that the most commonly used components in that part of the stack all happened to begin with a P. It's nothing more than a coincidence. The LAMP acronym was coined before Ruby gained its current popularity levels and there's no reason why you couldn't stick Ruby in the P slot.\n",
"I believe... | [
8,
7,
2,
1
] | [] | [] | [
"java",
"lamp",
"python",
"ruby"
] | stackoverflow_0006446385_java_lamp_python_ruby.txt |
Q:
Is anybody aware of a mature Java library which will help me query a Hudson / Jenkins server
I'm primarily a Python developer working in an environment where just about every important batch is run by a Hudson or Jenkins server. I've written a python library which uses Hudson's python API which allows me trivially... | Is anybody aware of a mature Java library which will help me query a Hudson / Jenkins server | I'm primarily a Python developer working in an environment where just about every important batch is run by a Hudson or Jenkins server. I've written a python library which uses Hudson's python API which allows me trivially write Hudson clients in Python.
I'm looking for a Java class which will help me do the same kind... | [
"jenkins cli\nis that what you need?\n"
] | [
2
] | [] | [] | [
"ant",
"hudson",
"java",
"jenkins",
"python"
] | stackoverflow_0006412439_ant_hudson_java_jenkins_python.txt |
Q:
Should command line option processing logic and logging logic be a separate function or part of the main loop in a Python program
I am an intermediate level Python Programmer and I have written a Python program that scrapes Mutual Fun NAV data from a web site and inserts those into a database.
The code is around 1... | Should command line option processing logic and logging logic be a separate function or part of the main loop in a Python program | I am an intermediate level Python Programmer and I have written a Python program that scrapes Mutual Fun NAV data from a web site and inserts those into a database.
The code is around 176 lines long and has logic related to command line option processing using the argparse module and logging logic using the logger modu... | [
"My favorite template to separating logging, argument parsing and the essential work of a script or application.\ndef the_real_work( option, option, *files ):\n etc.\n\ndef build_parser( ):\n parser = argparse.ArgumentParser()\n ...\n return parser\n\nif __name__ == \"__main__\":\n logging.basicConfi... | [
3,
2,
2
] | [] | [] | [
"python"
] | stackoverflow_0006447048_python.txt |
Q:
Python not returning all data when reading file chunk by chunk
I'm encrypting some files using python, but I'm having problems with reading the file chunk by chunk.
It's sometimes not returning all data of the last chunk.
When the file is 307200 bytes long, I have no problems.
When it's 279363 bytes long, I do.
I... | Python not returning all data when reading file chunk by chunk | I'm encrypting some files using python, but I'm having problems with reading the file chunk by chunk.
It's sometimes not returning all data of the last chunk.
When the file is 307200 bytes long, I have no problems.
When it's 279363 bytes long, I do.
I ran this piece of code over 2 files (respectively 307200 & 279363 b... | [
"Are you running on Windows? If so you may need to open your files in binary mode:\ninfile = open('somefile','rb')\n\n",
"I feel very stupid now, but I'm kind of glad nobody else noticed the same problem.\nI was calling w.close, not w.close()\n",
"That's odd. \nDid you create the second file as the first one, ... | [
4,
1,
0
] | [] | [] | [
"chunking",
"file_io",
"python"
] | stackoverflow_0005651425_chunking_file_io_python.txt |
Q:
How to implement a search engine using python mysql?
I have a MySQL database created using a custom Python script. I need to implement full-text search on a table in the database. I can use SELECT * FROM myTable WHERE (title LIKE '%hello%' OR title LIKE '%world%'), however I don't think that is a very efficient wa... | How to implement a search engine using python mysql? | I have a MySQL database created using a custom Python script. I need to implement full-text search on a table in the database. I can use SELECT * FROM myTable WHERE (title LIKE '%hello%' OR title LIKE '%world%'), however I don't think that is a very efficient way of implementing search since the data in the table has n... | [
"If your data is content like you could use some full-text search specific engine like Lucene:\nhttp://lucene.apache.org/pylucene/\nIf you are doing Django you have Haystack:\nhttp://haystacksearch.org/\nSolr is also a full-text search related technology you might read about:\nhttp://wiki.apache.org/solr/SolPython\... | [
4,
0,
0
] | [] | [] | [
"full_text_search",
"mysql",
"python",
"search_engine"
] | stackoverflow_0006447262_full_text_search_mysql_python_search_engine.txt |
Q:
Explicit code generation from WSDL file for autocomplete?
I'm using the suds library as a SOAP client in some project.
I would like to know if there was a way to generate Python code according to the WSDL file.
For example, consider the following line to be from the WSDL file:
<operation name="GetLastTradePrice">
... | Explicit code generation from WSDL file for autocomplete? | I'm using the suds library as a SOAP client in some project.
I would like to know if there was a way to generate Python code according to the WSDL file.
For example, consider the following line to be from the WSDL file:
<operation name="GetLastTradePrice">
Then, I want to get in some .py file the auto-generated functi... | [
"Ye olde ZSI library can generate Python code from a WSDL definition but, compared to suds, it's quite painful to use and requires another really old module called PyXML. I'd stick to suds, auto-completion isn't worth all that.\n",
"There are many SOAP server implementations for python, some more usable than othe... | [
0,
0
] | [] | [] | [
"autocomplete",
"python",
"soap",
"suds",
"wsdl"
] | stackoverflow_0006431443_autocomplete_python_soap_suds_wsdl.txt |
Q:
Grabbing pixels through Selenium / Python
I am doing some automation on the sever side. I'd like to somehow interact with the HTML page through Python code and access the pixel data. What kind of options Selenium offers for his kind of approaches?
Possible considerations
Raw pixel data access in in-process mem... | Grabbing pixels through Selenium / Python | I am doing some automation on the sever side. I'd like to somehow interact with the HTML page through Python code and access the pixel data. What kind of options Selenium offers for his kind of approaches?
Possible considerations
Raw pixel data access in in-process memory
Get pixels by saving them to a local image f... | [
"Using Selenium you can query the canvas for its image data using Selenium's getEval method (ref) with some smartly designed js code.\nYou can do it pixel by pixel if that's what you want, or just grab the entire canvas using the toDataURL method.\n"
] | [
2
] | [] | [] | [
"canvas",
"html",
"html5_canvas",
"python",
"selenium"
] | stackoverflow_0006447165_canvas_html_html5_canvas_python_selenium.txt |
Q:
Convert Any Iterable to Array in Python
This just has to be a dupe, but I just didn't find any existing instance of this question...
What is the easiest way to convert any iterable to an array in Python (ideally, without importing anything)?
Note: Ideally, if the input is an array then it shouldn't duplicate it (b... | Convert Any Iterable to Array in Python | This just has to be a dupe, but I just didn't find any existing instance of this question...
What is the easiest way to convert any iterable to an array in Python (ideally, without importing anything)?
Note: Ideally, if the input is an array then it shouldn't duplicate it (but this isn't required).
| [
"It depends on what you mean by array. If you really mean array and not list or the like, then you should be aware that arrays are containers of elements of the same (basic) type (see http://docs.python.org/library/array.html), i.e. not all iterables can be converted into an array. If you mean list, try the followi... | [
18,
4,
2,
2,
0
] | [] | [] | [
"arrays",
"iterable",
"list",
"python"
] | stackoverflow_0006447388_arrays_iterable_list_python.txt |
Q:
Python lose Mysql Server connection
i'm connecting python to mySqL Databases and sending things from android two Double values to be store in Mysql then i get this error
enter code here
Exception in thread :
Traceback (most recent call last):
File "C:\Python27\lib\threading.py", line 530, in __bootstrap_inner... | Python lose Mysql Server connection | i'm connecting python to mySqL Databases and sending things from android two Double values to be store in Mysql then i get this error
enter code here
Exception in thread :
Traceback (most recent call last):
File "C:\Python27\lib\threading.py", line 530, in __bootstrap_inner
self.run()
File "C:\Users\ingy\Desktop... | [
"This is what I do, in our case it only goes away once in the worst case and throws a different error, so we don't get infinite recurision.\ndef query(self, sql, parameters=None):\n cursor = self.db.cursor()\n try:\n cursor.execute(sql, parameters)\n return cursor\n except mysql.connector.Err... | [
3,
1
] | [] | [] | [
"android",
"mysql",
"python"
] | stackoverflow_0006447174_android_mysql_python.txt |
Q:
replace names with lists from file
I have a file like divided in sections like that:
[main]
a
b
< sectionA
c
[sectionA]
x
< sectionB
y
z
[sectionB]
q
w
e
I want to replace the "< sectionA" with contents from sectionA and so on. The final result should be a list with only the elements in the right order, like t... | replace names with lists from file | I have a file like divided in sections like that:
[main]
a
b
< sectionA
c
[sectionA]
x
< sectionB
y
z
[sectionB]
q
w
e
I want to replace the "< sectionA" with contents from sectionA and so on. The final result should be a list with only the elements in the right order, like that:
['a', 'b', 'x', 'q', 'w', 'e', 'y',... | [
"It's not that hard. This is the algorithm:\n1. Find all indexes in main starting with <.\n2. If none are found, go to 5.\n3. Replace every index with the according section (inserted unpacked).\n4. Go to 1.\n5. Done.\n\n",
"I solved your problem with two functions. The first for rendering the input file (renderfi... | [
0,
0,
0
] | [] | [] | [
"dictionary",
"file",
"list",
"python"
] | stackoverflow_0006446887_dictionary_file_list_python.txt |
Q:
Python reading of a file stops before it should in Windows 7
I am using Python to open the physical disk in the computer to read the first sector.
disk = r"\\.\PhysicalDrive0"
with open(disk, 'r') as f:
f.seek(0)
partdata = f.read(512)
len(partdata)
In windows XP len(partdata) will return 512 and ... | Python reading of a file stops before it should in Windows 7 | I am using Python to open the physical disk in the computer to read the first sector.
disk = r"\\.\PhysicalDrive0"
with open(disk, 'r') as f:
f.seek(0)
partdata = f.read(512)
len(partdata)
In windows XP len(partdata) will return 512 and have the correct content. In windows 7 len(partdata) returns 230 a... | [
"Try opening in binary mode\nwith open(disk, 'rb') as f:\n\n"
] | [
7
] | [] | [] | [
"disk",
"python",
"readfile",
"windows_7"
] | stackoverflow_0006447760_disk_python_readfile_windows_7.txt |
Q:
How to queryset all user that are in a foreign table?
I have a model called book and in that model there is a foreignkey field (called author) to the user model.
I need in one of my views to returm a list of all the authors(not all users, just users that appear in the book model(just the authors).
I don't know w... | How to queryset all user that are in a foreign table? | I have a model called book and in that model there is a foreignkey field (called author) to the user model.
I need in one of my views to returm a list of all the authors(not all users, just users that appear in the book model(just the authors).
I don't know why, but i'm having a hard time getting that.
Can any one pl... | [
"Try this:\nUser.objects.filter(book__isnull=False).distinct()\n\nI'm assuming there is only one foreign key from the Book model to the User model. \n\nisnull filters for all users which are in the which are linked to the Book model.\ndistinct ensures that each author only appears once in the results.\n\n"
] | [
2
] | [] | [] | [
"django",
"django_views",
"python"
] | stackoverflow_0006447605_django_django_views_python.txt |
Q:
What is wrong with this module?
I have triple checked the syntax on this python module statement, and it is NOT working...
correct = 0
ahtriggercount = 0
def IsCorrect():
#Increase correct count.
correct = correct + 1
#Lower autohelp trigger count.
if ahtriggercount > 0:
ahtriggercount = a... | What is wrong with this module? | I have triple checked the syntax on this python module statement, and it is NOT working...
correct = 0
ahtriggercount = 0
def IsCorrect():
#Increase correct count.
correct = correct + 1
#Lower autohelp trigger count.
if ahtriggercount > 0:
ahtriggercount = ahtriggercount - 1
The general "synta... | [
"You need to tell python that you're accessing a global variable. Like this:\ncorrect = 0\nahtriggercount = 0\n\ndef IsCorrect():\n global correct, ahtriggercount\n #Increase correct count.\n correct = correct + 1\n #Lower autohelp trigger count.\n if ahtriggercount > 0:\n ahtriggercount = aht... | [
3,
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0006447667_python.txt |
Q:
Python/Django: What mode for mod_wsgi
I am new to Python and plan to learn Python/Django. I am in the middle of installing Apache and mod_wsgi right now, I have read on the website that there are two modes: embedded mode (favoring performance) and deamon mode (favoring security). I am wondering what would be a bet... | Python/Django: What mode for mod_wsgi | I am new to Python and plan to learn Python/Django. I am in the middle of installing Apache and mod_wsgi right now, I have read on the website that there are two modes: embedded mode (favoring performance) and deamon mode (favoring security). I am wondering what would be a better option in this case, and what is the re... | [
"The modwsgi documenation explains the differences. Embedded mode will run the application within the Apache process itself, deamon mode will not. The summary of the first seven paragraphs of the docs:\n\nThus, unless you are adept at configuring Apache, always use daemon mode when available.\n\n"
] | [
2
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0006447723_django_django_models_python.txt |
Q:
Running Python script as root (with sudo) - what is the username of the effective user?
I've recently began using ConfigParser() for my python scripts to add some functionality to them for config files. I know how to use it but I have a problem. My script needs to run as the root user, using sudo. The config files... | Running Python script as root (with sudo) - what is the username of the effective user? | I've recently began using ConfigParser() for my python scripts to add some functionality to them for config files. I know how to use it but I have a problem. My script needs to run as the root user, using sudo. The config files are in ~/.config/scriptconfig/ but when you run a script as sudo it temporarily changes user... | [
"If you run your script with sudo (sudo myscript.py) then the environment variable $USER will be root and the environment variable $SUDO_USER will be the name of the user who executed the command sudo myscript.py. This following is simply a clarification of the previous post by Cédric Julien. Consider the followi... | [
30,
7,
4
] | [] | [] | [
"configuration",
"python",
"root",
"sudo"
] | stackoverflow_0005721529_configuration_python_root_sudo.txt |
Q:
why am I getting one line of numbers?
num = int(input('Enter a number:'))
for i in range(0, num, 1):
for j in range(0, i):
print(num, end =" ")
for i in range(num, 0, -1):
for j in range(0, i):
print(num, end=" ")
A:
Because end=" " overrides the default behaviour which is to print a ne... | why am I getting one line of numbers? | num = int(input('Enter a number:'))
for i in range(0, num, 1):
for j in range(0, i):
print(num, end =" ")
for i in range(num, 0, -1):
for j in range(0, i):
print(num, end=" ")
| [
"Because end=\" \" overrides the default behaviour which is to print a newline \\n.\nThe effect of this is to separate each number by a space rather than a newline \\n.\n",
"This line print(num, end=\" \") will only print the initial number num. Are you perhaps wanting one of your iterating numbers (i or j)?\nAl... | [
9,
1
] | [] | [] | [
"python"
] | stackoverflow_0006447941_python.txt |
Q:
Web interface for a twisted application
I have a application written in Twisted and I want to add a web interface to control and monitor it. I'll need plenty of dynamic pages that show the current status and configuration, so I hoped for a framework that offers at least a templating language with inheritance and s... | Web interface for a twisted application | I have a application written in Twisted and I want to add a web interface to control and monitor it. I'll need plenty of dynamic pages that show the current status and configuration, so I hoped for a framework that offers at least a templating language with inheritance and some basic routing.
Since I am using Twisted a... | [
"Since Nevow is still down and I didn't want to write routing and support for a templating lib myself, I ended up using Flask. It turned out to be quite easy:\n# make a Flask app\nfrom flask import Flask, render_template, g\napp = Flask(__name__)\n@app.route(\"/\")\ndef index():\n return render_template(\"index.... | [
14,
6,
3
] | [] | [] | [
"python",
"twisted",
"twisted.web",
"web_frameworks"
] | stackoverflow_0005248825_python_twisted_twisted.web_web_frameworks.txt |
Q:
Hijacking, redirecting, display output with Python 2.7
I am a new programmer with little experience but I am in the process of learning Python 2.7. I use Python(x,y) or Spydar as the programs are called on Windows 7.
The main packages I'm using are numpy, pil and potentially win32gui.
I am currently trying to wr... | Hijacking, redirecting, display output with Python 2.7 | I am a new programmer with little experience but I am in the process of learning Python 2.7. I use Python(x,y) or Spydar as the programs are called on Windows 7.
The main packages I'm using are numpy, pil and potentially win32gui.
I am currently trying to write a program to mine information from a 3rd-party software.... | [
"One approach that might work would be to do something like so:\n\nget the window handle (FindWindow() or something similar, there are a few ways to do this)\nget the window dimensions (GetClientRect() or GetWindowRect())\nget the device context for the window (GetWindowDC())\nget the image data from the window (Bi... | [
0
] | [] | [] | [
"python",
"python_2.7",
"winapi"
] | stackoverflow_0006445620_python_python_2.7_winapi.txt |
Q:
Difference between raise Exception, "foo" and raise Exception("foo")?
The title is pretty self explanatory -- what's the difference between:
raise Exception, "foo"
and
raise Exception("foo")
Does it do exactly the same thing, just different syntax?
I'm using Python 2.x, but I'd like to hear of any differences in... | Difference between raise Exception, "foo" and raise Exception("foo")? | The title is pretty self explanatory -- what's the difference between:
raise Exception, "foo"
and
raise Exception("foo")
Does it do exactly the same thing, just different syntax?
I'm using Python 2.x, but I'd like to hear of any differences in Python 3.x
| [
"both amount to the same thing in Python2. in Python3, the raise Exception, \"foo\" syntax is no longer supported.\n"
] | [
24
] | [] | [] | [
"python"
] | stackoverflow_0006448229_python.txt |
Q:
Script/utility to rewrite all svn:externals in repository trunk
Say that one wishes to convert all absolute svn:externals URLS to relative URLS throughout their repository.
Alternatively, if heeding the tip in the svn:externals docs ("You should seriously consider using explicit revision numbers..."), one might fi... | Script/utility to rewrite all svn:externals in repository trunk | Say that one wishes to convert all absolute svn:externals URLS to relative URLS throughout their repository.
Alternatively, if heeding the tip in the svn:externals docs ("You should seriously consider using explicit revision numbers..."), one might find themselves needing to periodically pull new revisions for external... | [
"Here's my class to extract parts from a single line of an svn:externals property:\nfrom urlparse import urlparse\nimport re\nclass SvnExternalsLine:\n '''Consult https://subversion.apache.org/docs/release-notes/1.5.html#externals for parsing algorithm.\n The old svn:externals format consists of:\n <lo... | [
4
] | [] | [] | [
"python",
"scripting",
"svn_externals"
] | stackoverflow_0006448240_python_scripting_svn_externals.txt |
Q:
Dynamically create subpackage
Is it possible to create a package dynamically, something like:
subpackage = create_subpackage(package_name, package_path)
The package should be associated with a physical path so that modules from that path can be imported through it.
The purpose is to be able to have subpackages th... | Dynamically create subpackage | Is it possible to create a package dynamically, something like:
subpackage = create_subpackage(package_name, package_path)
The package should be associated with a physical path so that modules from that path can be imported through it.
The purpose is to be able to have subpackages that are not subdirectories of their ... | [
"While this won't give you exactly the layout you're asking for, this might help: http://docs.python.org/tutorial/modules.html#packages-in-multiple-directories\nBasically, each package has a __path__ attribute that contains a list of places to search for submodules. And you can modify it to your liking.\ne.g.\nmain... | [
3
] | [] | [] | [
"package",
"python"
] | stackoverflow_0006447961_package_python.txt |
Q:
Boost Python signature mismatch problem
I'm getting a signature mismatch with a method I'm exposing to python. Here's the code below
class StatusEffect
{
public:
//Virtual functions and non related ommitted
void AddCancellation(std::string &effect)
{
CancelsEffects.insert(effect);
}
}
There are... | Boost Python signature mismatch problem | I'm getting a signature mismatch with a method I'm exposing to python. Here's the code below
class StatusEffect
{
public:
//Virtual functions and non related ommitted
void AddCancellation(std::string &effect)
{
CancelsEffects.insert(effect);
}
}
There are some virtual methods in StatusEffect that I ... | [
"Turns out I need to have \nvoid AddCancellation(std::string &effect)\n{\n CancelsEffects.insert(effect);\n}\n\nas\nvoid AddCancellation(const std::string &effect)\n{\n CancelsEffects.insert(effect);\n}\n\n",
"I think the problem might be that Boost.Python doesn't entirely understand that StatusEffectWrapper ... | [
2,
1
] | [] | [] | [
"boost_python",
"c++",
"python"
] | stackoverflow_0006258485_boost_python_c++_python.txt |
Q:
Relink python object (i.e. pass by reference)
I have a function that I want to use to manipulate an input parameter, however, in the process I must copy the input parameter. I do not want to return the modified object (because multiprocessing may or may not be involved). How can I reassign the input parameter to t... | Relink python object (i.e. pass by reference) | I have a function that I want to use to manipulate an input parameter, however, in the process I must copy the input parameter. I do not want to return the modified object (because multiprocessing may or may not be involved). How can I reassign the input parameter to the copied value? Here's a representation of the fun... | [
"Update: Ok, now that I understand more about the problem, I would suggest a combination of options 1 and 4: create public update() and dictify() methods. These could be wrappers around option 4 or some variation like myObj.__dict__.update(modObj.__dict__) -- both of which are somewhat hackish. \nOr, they could be ... | [
1
] | [] | [] | [
"pass_by_reference",
"python",
"reference"
] | stackoverflow_0006448823_pass_by_reference_python_reference.txt |
Q:
PyCUDA/CUDA: Causes of non-deterministic launch failures?
Anyone following CUDA will probably have seen a few of my queries regarding a project I'm involved in, but for those who haven't I'll summarize. (Sorry for the long question in advance)
Three Kernels, One Generates a data set based on some input variables (... | PyCUDA/CUDA: Causes of non-deterministic launch failures? | Anyone following CUDA will probably have seen a few of my queries regarding a project I'm involved in, but for those who haven't I'll summarize. (Sorry for the long question in advance)
Three Kernels, One Generates a data set based on some input variables (deals with bit-combinations so can grow exponentially), another... | [
"Have you tried:\ncuda-memcheck python yourapp.py\n\nYou likely have an out of bounds memory access.\n"
] | [
4
] | [
"You can use nVidia CUDA Profiler and see what gets executed before the failure.\n"
] | [
-1
] | [
"cuda",
"gpgpu",
"pycuda",
"python"
] | stackoverflow_0005827219_cuda_gpgpu_pycuda_python.txt |
Q:
python -- measuring pixel brightness
How can I get a measure for a pixels brightness for a specific pixel in an image? I'm looking for an absolute scale for comparing different pixels' brightness. Thanks
A:
To get the pixel's RGB value you can use PIL:
from PIL import Image
from math import sqrt
imag = Image.ope... | python -- measuring pixel brightness | How can I get a measure for a pixels brightness for a specific pixel in an image? I'm looking for an absolute scale for comparing different pixels' brightness. Thanks
| [
"To get the pixel's RGB value you can use PIL:\nfrom PIL import Image\nfrom math import sqrt\nimag = Image.open(\"yourimage.yourextension\")\n#Convert the image te RGB if it is a .gif for example\nimag = imag.convert ('RGB')\n#coordinates of the pixel\nX,Y = 0,0\n#Get RGB\npixelRGB = imag.getpixel((X,Y))\nR,G,B = p... | [
27
] | [] | [] | [
"brightness",
"image",
"pixel",
"python"
] | stackoverflow_0006442118_brightness_image_pixel_python.txt |
Q:
Does garbage collection make python slower?
OK, so we are developing an network related application where the user can upload their own python scripts to decide for an algorithm. Our code contains c and cython and python modules.
Since avoiding latency, memory footprint and minimal processing is critical for us, ... | Does garbage collection make python slower? | OK, so we are developing an network related application where the user can upload their own python scripts to decide for an algorithm. Our code contains c and cython and python modules.
Since avoiding latency, memory footprint and minimal processing is critical for us, we were wondering if it's a wise and effective (p... | [
"Just let the language do what it wants to do, and if you find you have an actual problem, come on back and post about it. Otherwise it's premature optimization.\n",
"gc.disable only turns off the cyclic garbage collector. Objects will still be collected when the refcount drops to zero anyway. So unless you have... | [
18,
11,
5,
4,
2,
1
] | [] | [] | [
"cython",
"garbage_collection",
"memory_leaks",
"memory_management",
"python"
] | stackoverflow_0006448742_cython_garbage_collection_memory_leaks_memory_management_python.txt |
Q:
Problem writing to a text input in python's mechanize module
First and foremost, I am writing a python script to automate purchasing of certain domains from dreamhost.com. I first go to the website's panel where users can do pretty much anything the site has to offer. Here is the code:
br = mechanize.Browser()
b... | Problem writing to a text input in python's mechanize module | First and foremost, I am writing a python script to automate purchasing of certain domains from dreamhost.com. I first go to the website's panel where users can do pretty much anything the site has to offer. Here is the code:
br = mechanize.Browser()
br.open("https://panel.dreamhost.com/index.cgi?tree=domain.registra... | [
"I haven't looked at the site but I strongly suspect that some javascript is doing something that you're not doing with mechanize. The standard answer in these cases is to use Selenium Webdriver to automate a browser (it has a Python API).\nEdit:\nSelenium Webdriver has HtmlUnit headless browser that supports javas... | [
1
] | [] | [] | [
"mechanize",
"python",
"submit",
"textinput"
] | stackoverflow_0006449602_mechanize_python_submit_textinput.txt |
Q:
No module named os found -- Django, mod_wsgi, Apache 2.2
I'm trying to set up apache, mod_wsgi, and django. I'm getting an internal server error with this in my apache error log:
[Wed Jun 22 21:31:55 2011] [error] [client ::1] mod_wsgi (pid=2893): Target WSGI script '/django/internal/django-development.wsgi' canno... | No module named os found -- Django, mod_wsgi, Apache 2.2 | I'm trying to set up apache, mod_wsgi, and django. I'm getting an internal server error with this in my apache error log:
[Wed Jun 22 21:31:55 2011] [error] [client ::1] mod_wsgi (pid=2893): Target WSGI script '/django/internal/django-development.wsgi' cannot be loaded as Python module.
[Wed Jun 22 21:31:55 2011] [erro... | [
"mod_wsgi for some reason cannot see your Py2.5 library. I would suggest checking the value of WSGIPythonPath and make sure it points to something like /usr/lib/python2.5\n"
] | [
1
] | [] | [] | [
"apache",
"django",
"mod_wsgi",
"python"
] | stackoverflow_0006449400_apache_django_mod_wsgi_python.txt |
Q:
Implement lookahead iterator for strings in Python
I'm doing some parsing that requires one token of lookahead. What I'd like is a fast function (or class?) that would take an iterator and turn it into a list of tuples in the form (token, lookahead), such that:
>>> a = ['a', 'b', 'c', 'd']
>>> list(lookahead(a))
... | Implement lookahead iterator for strings in Python | I'm doing some parsing that requires one token of lookahead. What I'd like is a fast function (or class?) that would take an iterator and turn it into a list of tuples in the form (token, lookahead), such that:
>>> a = ['a', 'b', 'c', 'd']
>>> list(lookahead(a))
[('a', 'b'), ('b', 'c'), ('c', 'd'), ('d', None)]
basic... | [
"There are easier ways if you are just using lists - see Sven's answer. Here is one way to do it for general iterators\n>>> from itertools import tee, izip_longest\n>>> a = ['a', 'b', 'c', 'd']\n>>> it1, it2 = tee(iter(a))\n>>> next(it2) # discard this first value\n'a'\n>>> [(x,y) for x,y in izip_longest(it1, it2)... | [
11,
8,
6,
2,
1
] | [] | [] | [
"algorithm",
"python"
] | stackoverflow_0006448117_algorithm_python.txt |
Q:
sharing variables between two wxpython tabs
I have asked this question but it was not very well formulated.
persistence of objects in python
As a newbie to both python, and GUI programming
I have a large project which contains a number of python files. File a.py defines a class called fobject I am using python 2.... | sharing variables between two wxpython tabs | I have asked this question but it was not very well formulated.
persistence of objects in python
As a newbie to both python, and GUI programming
I have a large project which contains a number of python files. File a.py defines a class called fobject I am using python 2.5
File b.py and c.py have classes called BProject... | [
"I'm not following this very well, but normally you need to pass the data in when you instantiate the class. Otherwise, you can use PubSub to pass the information between classes or you could create a simple local web server that each tab checks periodically for new data and updates itself.\n",
"If your fObject m... | [
1,
0
] | [] | [] | [
"oop",
"python",
"wxpython"
] | stackoverflow_0006438085_oop_python_wxpython.txt |
Q:
What is the most performant way to implement zoom to a cairo-drawn canvas?
I have a wx.ScrolledWindow where is drawn on using cairo. I have implemented a zoom-functionality which right now redraws the whole content.
But as there will be up to 200 curves to draw I should consider a more performant solution.
I have ... | What is the most performant way to implement zoom to a cairo-drawn canvas? | I have a wx.ScrolledWindow where is drawn on using cairo. I have implemented a zoom-functionality which right now redraws the whole content.
But as there will be up to 200 curves to draw I should consider a more performant solution.
I have thought of these:
Buffering images for the zoom factors -1/+1 (Memory consuming... | [
"Not really a concrete answer to your question, but I was faced with the same problem and just switched to matplotlib where a zoom and pan function is already implemented. I am not sure though if it is super performant. I have the feeling my program was running more smoothly before.\nI also tried out floatcanvas an... | [
1,
1
] | [] | [] | [
"cairo",
"python",
"wxpython"
] | stackoverflow_0006049208_cairo_python_wxpython.txt |
Q:
Can I import as only for a function, and have the rest imported as they are?
Let's say I have a function named "hello" in a module named a, and various other functions. Is it possible to import hello as goodbye, along with the other symbols? I am thinking of something like this, however it's not valid:
from a impo... | Can I import as only for a function, and have the rest imported as they are? | Let's say I have a function named "hello" in a module named a, and various other functions. Is it possible to import hello as goodbye, along with the other symbols? I am thinking of something like this, however it's not valid:
from a import hello as goodbye,*
| [
"You can import from a, then bind the new name that you want and delete the previous. Something like\nfrom a import *\ngoodbye = hello\ndel hello\n\nStar imports are usually not so good exactly because of namespace pollution.\n",
"from a import *\nfrom a import hello as goodbye\n\n",
"Next two lines work fine f... | [
7,
2,
1,
1
] | [] | [] | [
"import",
"python"
] | stackoverflow_0006450228_import_python.txt |
Q:
Google App Engine Python simplejson escaping?
The version of django.utils.simplejson on GAE is for example escaping "/" characters, but not "\n" when doing js = json.dumps(my_dict_w_strings_w_newline_and_slash) which is causing problems when I try to json.loads(js) in my client someplace else.
Any suggestions on h... | Google App Engine Python simplejson escaping? | The version of django.utils.simplejson on GAE is for example escaping "/" characters, but not "\n" when doing js = json.dumps(my_dict_w_strings_w_newline_and_slash) which is causing problems when I try to json.loads(js) in my client someplace else.
Any suggestions on how to sort out a solution? The strings are base64 e... | [
"I tried the simplejson version shipped with the SDK (Django 0.96 and 1.2) and both escape '\\n':\n>>> simplejson.dumps({'foo': '\\n'})\n'{\"foo\": \"\\\\n\"}'\n\nAnd on http://shell.appspot.com/:\nGoogle App Engine/1.5.1\nPython 2.5.2 (r252:60911, Mar 17 2011, 15:16:30) \n[GCC 4.3.1]\n\n>>> from django.utils impor... | [
3,
0
] | [] | [] | [
"google_app_engine",
"python",
"simplejson"
] | stackoverflow_0006445108_google_app_engine_python_simplejson.txt |
Q:
google app engine with django retrieve item by key from a template to a view
i have this small problem with google app engine i want to retrieve images from datastore , my function is 100 percent working if i enter the key inside the code on the other hand if i get as a parameter it would give me BadKeyError
here... | google app engine with django retrieve item by key from a template to a view | i have this small problem with google app engine i want to retrieve images from datastore , my function is 100 percent working if i enter the key inside the code on the other hand if i get as a parameter it would give me BadKeyError
here is the form
{% for image in image.all %}
<li>{{ image.title ... | [
"I created something simliar to what you want to achieve.. Hope this helps\nimage.py\nimport os\nfrom google.appengine.ext import db\nfrom google.appengine.ext import webapp\nfrom google.appengine.ext.webapp import template\nfrom google.appengine.ext.webapp.util import run_wsgi_app\nclass Profile(db.Model):\n ... | [
0
] | [] | [] | [
"django",
"google_app_engine",
"python",
"templates"
] | stackoverflow_0006445950_django_google_app_engine_python_templates.txt |
Q:
Need help getting authentication to work in all apps in a Django project
I'm starting up on Django, and am just a novice when it comes to server-side code. All of my web coding experience is in the front-end and is limited to CSS, HTML, and basic javascript. But I thought it was time to take it up a notch and lea... | Need help getting authentication to work in all apps in a Django project | I'm starting up on Django, and am just a novice when it comes to server-side code. All of my web coding experience is in the front-end and is limited to CSS, HTML, and basic javascript. But I thought it was time to take it up a notch and learn more about the back-end of things and decided to start here. I went throug... | [
"try request.user.is_authenticatedinstead. \n",
"If you use RequestContext(request) and you have django.contrib.auth.context_processors.auth in your TEMPLATE_CONTEXT_PROCESSORS the user variable will be accessible on your template.\nhttps://docs.djangoproject.com/en/dev/ref/templates/api/#django-contrib-auth-cont... | [
1,
1,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0006448356_django_python.txt |
Q:
Libxml Cleaner adds unwanted tag to HTML fragments
I'm trying to sanitize user input to prevent XSS injection using libxml's HTML cleaner. When I input a string like this:
Normal text <b>Bold text</b>
I get this instead:
<p>Normal text <b>Bold text</b></p>
I want to get rid of the <p> tag that surrounds all of ... | Libxml Cleaner adds unwanted tag to HTML fragments | I'm trying to sanitize user input to prevent XSS injection using libxml's HTML cleaner. When I input a string like this:
Normal text <b>Bold text</b>
I get this instead:
<p>Normal text <b>Bold text</b></p>
I want to get rid of the <p> tag that surrounds all of my input.
Here is the function that currently does the c... | [
"All TEXT fragments/nodes must be enclosed in some kind of an element. libxml will attempt to fix this as best as it can.\ndef sanitize_html(html):\n cleaned_html = cleaner.clean_html(html)\n return re.sub(r'</p>$', '', re.sub(r'^<p>', '', cleaned_html))\n\nCaching the compiled regular expressions or finding ... | [
3
] | [] | [] | [
"libxml2",
"parsing",
"python"
] | stackoverflow_0006448802_libxml2_parsing_python.txt |
Q:
encoding problem with pgsql/python?
I retrieved a bunch of text records from my postgresql database and intend to preprocess these text documents before analyzing them.
I want to tokenize the documents but ran into some problem during tokenizing
#some other bunch of regex replacements
#toToken is the text... | encoding problem with pgsql/python? | I retrieved a bunch of text records from my postgresql database and intend to preprocess these text documents before analyzing them.
I want to tokenize the documents but ran into some problem during tokenizing
#some other bunch of regex replacements
#toToken is the text string
toTokens = self.regexClit... | [
"Why don't you use toTokens.strip(). No need of str module.\nThere are 2 string types in Python, str and unicode. Look at this for an explanation.\n"
] | [
4
] | [] | [] | [
"encoding",
"postgresql",
"python"
] | stackoverflow_0006450413_encoding_postgresql_python.txt |
Q:
Problem with django urls which have a hyphen in them
I have a simple set of urls in a Django url conf file which points to some object detail generic views.
urlpatterns = patterns('',
url(r'^projects/(?P<slug>[\w-]+)/$', ProjectDetailView.as_view(), name='view_project'),
url(r'^roles/(?P<slug>[\w-]+)/$', RoleDet... | Problem with django urls which have a hyphen in them | I have a simple set of urls in a Django url conf file which points to some object detail generic views.
urlpatterns = patterns('',
url(r'^projects/(?P<slug>[\w-]+)/$', ProjectDetailView.as_view(), name='view_project'),
url(r'^roles/(?P<slug>[\w-]+)/$', RoleDetailView.as_view(), name='view_role'),
)
The problem is wh... | [
"Change [\\w-]+ to [-\\w]+. For me [\\w-]+ never works with python regexp's.\n",
"My guess is that you wrote a custom template tag, but it's broken. You're using it in base.html :P\n"
] | [
5,
1
] | [] | [] | [
"django",
"python",
"url_routing"
] | stackoverflow_0006449950_django_python_url_routing.txt |
Q:
Migrating Small App to High Replication Datastore
The current recommendation from google is that all apps start migrating to the high replication datastore. My app is small and still in development. My understanding is that the more data my app accumulates the more involved the transition process will be. So I've ... | Migrating Small App to High Replication Datastore | The current recommendation from google is that all apps start migrating to the high replication datastore. My app is small and still in development. My understanding is that the more data my app accumulates the more involved the transition process will be. So I've decided to migrate ASAP (while I still only have 56k of... | [
"I believe that the fix is to specify the full app id for your high replication app in the --application flag. In your case the full app id is: s~essayhost. App Engine tries to hide the s~ prefix, but doesn't always succeed.\n",
"I ran into the same issue as you. This is how I fixed it:\nappcfg.py upload_data --c... | [
5,
3
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0006239400_google_app_engine_python.txt |
Q:
What is the usage of else: after a try/except clause
Possible Duplicates:
when is it necessary to add an else clause to a try..except in Python?
Python try-else
for arg in sys.argv[1:]:
try:
f = open(arg, 'r')
except IOError:
print 'cannot open', arg
else:
print arg, 'has', le... | What is the usage of else: after a try/except clause |
Possible Duplicates:
when is it necessary to add an else clause to a try..except in Python?
Python try-else
for arg in sys.argv[1:]:
try:
f = open(arg, 'r')
except IOError:
print 'cannot open', arg
else:
print arg, 'has', len(f.readlines()), 'lines'
f.close()
What is usag... | [
"The try...except...else statement mean something like this : \ntry:\n # execute some code\nexcept:\n # if code raises an error, execute this code\nelse:\n # if the \"try\" code did not raise an error, execute this code\n\n",
"From the Python documentation:\n\nThe optional else clause is executed if and ... | [
3,
3
] | [] | [] | [
"python"
] | stackoverflow_0006450740_python.txt |
Q:
Python paradigm for "derived fields"/"class attributes from calculations"
I have a class that, let's say, computes a person's insurance risk, and a few other variables are computed during computation. I will need access to the risk and the other variables later.
class InsuranceRiskModel:
self.risk = None
... | Python paradigm for "derived fields"/"class attributes from calculations" | I have a class that, let's say, computes a person's insurance risk, and a few other variables are computed during computation. I will need access to the risk and the other variables later.
class InsuranceRiskModel:
self.risk = None
self.other_var = None
...
def get_risk():
# do a bunch of calc... | [
"No, it is not a legitimate thing to raise a NotYetCalculatedError ever, in any program (unless the calculation would take hours of work).\nget_other_var() should automatically calculate the risk\nWhat you actually want to do is run all the calculations when you initialize the class, or if you can't do that, you'll... | [
6,
1
] | [] | [] | [
"attributes",
"class_attributes",
"oop",
"properties",
"python"
] | stackoverflow_0006451034_attributes_class_attributes_oop_properties_python.txt |
Q:
How to change offsets of matplotlib LineCollection after creation
I would like to create a stack of line plots using a LineCollection. The following code draws two identical sine curves offset from one another by (0, 0.2):
import matplotlib.pyplot as plt
import matplotlib.collections
import numpy as np
x=np.arang... | How to change offsets of matplotlib LineCollection after creation | I would like to create a stack of line plots using a LineCollection. The following code draws two identical sine curves offset from one another by (0, 0.2):
import matplotlib.pyplot as plt
import matplotlib.collections
import numpy as np
x=np.arange(1000)
y=np.sin(x/50.)
l=zip(x,y)
f=plt.figure()
a=f.add_subplot(111)... | [
"I think you found a bug in matplotlib, but I have a couple work arounds. It looks like lines._paths gets generated in LineCollection().__init__ using the offsets you provide. lines._paths is not property updated when you call lines.set_offsets(). In your simple example, you can re-generate the paths since you s... | [
1,
0
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0006418166_matplotlib_python.txt |
Q:
Matplotlib - changing plot size within rectangular grid
I have 4 subplots (created by using add_subplot) organised in a 2x2 rectangular grid. The two in the second row do not need to take up as much space and I wish to change it such that the top row takes up two thirds of the space and the bottom row takes up the... | Matplotlib - changing plot size within rectangular grid | I have 4 subplots (created by using add_subplot) organised in a 2x2 rectangular grid. The two in the second row do not need to take up as much space and I wish to change it such that the top row takes up two thirds of the space and the bottom row takes up the remaining third.
I've found that you can arbitrarily place s... | [
"Maybe AxisGrid toolkit will help. It seems to offer more control than subplot()\n",
"Use subplot2grid, where you specify a 3x3 grid but make subplots in the first row have rowspan=2.\n"
] | [
1,
1
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0003423776_matplotlib_python.txt |
Q:
Error compiling the io programming language
I'm trying to compile io but it's failing and I can't understand why. Here's what I did to compile it:
mkdir build && cd build
cmake ..
make
Here's a gist of output from cmake
Which seems fine but when I run make (gist of the output)
it fails with something to do with p... | Error compiling the io programming language | I'm trying to compile io but it's failing and I can't understand why. Here's what I did to compile it:
mkdir build && cd build
cmake ..
make
Here's a gist of output from cmake
Which seems fine but when I run make (gist of the output)
it fails with something to do with python: error: #error "LONG_BIT definition appears... | [
"Looking at your make log then this line could the the cause:\n\nIn file included from /Library/Frameworks/Python.framework/Headers/Python.h:57\n\nI don't have that file here (or in my ~/Library/Frameworks/ and Io compiles successfully for me. \nSo perhaps you are using a different version of Xcode (I'm using 3.2.... | [
1
] | [] | [] | [
"compilation",
"iolanguage",
"python"
] | stackoverflow_0006449166_compilation_iolanguage_python.txt |
Q:
Need a regex for phrase including spaces in between, but not spaces to the right?
I have a logfile, where we parse each line using regex in Python.
Part of each line contains a phrase, which is one or more words.
For example, in the below, the phrase is "SOME PHRASE".
12-09-95 10:37:46,082 [3] INFO Foobar <> - 199... | Need a regex for phrase including spaces in between, but not spaces to the right? | I have a logfile, where we parse each line using regex in Python.
Part of each line contains a phrase, which is one or more words.
For example, in the below, the phrase is "SOME PHRASE".
12-09-95 10:37:46,082 [3] INFO Foobar <> - 1995-Dec-09 10:37:47.189025 --- [5571467078570868736::TYPE ::SOME PHRASE ::1995-Dec-09 ... | [
"You could not match trailing whitespace like so..\n::(?P<phrase>[\\w\\s]+?)\\s*::\n\n",
"why to use regex?\n>>> line = \"12-09-95 10:37:46,082 [3] INFO Foobar <> - 1995-Dec-09 10:37:47.189025 --- [5571467078570868736::TYPE ::SOME PHRASE ::1995-Dec-09 10:37:47.165672::1995-Dec-09 10:37:47.188790::00:00:00.0231... | [
2,
0,
0
] | [] | [] | [
"parsing",
"python",
"regex"
] | stackoverflow_0006450543_parsing_python_regex.txt |
Q:
Is there an easy way to capture all Frame/Window keystrokes in Python or wxPython
I tried EVT_KEY_DOWN but doesn't work. Is there a way to capture any keystroke such as F1, F2 , ENTER, and others. I am using a Frame and Panel.
A:
I used EVT_KEY_DOWN in a dialog subclass. In the __init__ method of your dialog cla... | Is there an easy way to capture all Frame/Window keystrokes in Python or wxPython | I tried EVT_KEY_DOWN but doesn't work. Is there a way to capture any keystroke such as F1, F2 , ENTER, and others. I am using a Frame and Panel.
| [
"I used EVT_KEY_DOWN in a dialog subclass. In the __init__ method of your dialog class, bind to EVT_KEY_DOWN:\ndef __init__(self, ....):\n # ...other init code...\n self.Bind(wx.wx.EVT_KEY_UP, self.handle_key_up)\n\nThen provide a method on your dialog like:\ndef handle_key_up(self, event):\n keycode = eve... | [
3,
3,
1
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0006420573_python_wxpython.txt |
Q:
Total "CPU hours" in Python
In order to run a python script on a large deployment, I need to find out the "total CPU hours" that my script uses. The script executes a separate program (a simulation that, notably, uses MPI), which needs to be included in the count. What is the best, and most precise, way of doing t... | Total "CPU hours" in Python | In order to run a python script on a large deployment, I need to find out the "total CPU hours" that my script uses. The script executes a separate program (a simulation that, notably, uses MPI), which needs to be included in the count. What is the best, and most precise, way of doing this?
To be more specific, the tot... | [
"Run time your-command, which includes a cpu time column and accounts for children.\n",
"Start here: http://manpages.ubuntu.com/manpages/dapper/man8/sa.8.html\n"
] | [
1,
0
] | [] | [] | [
"cluster_computing",
"cpu",
"cpu_usage",
"mpi",
"python"
] | stackoverflow_0006447015_cluster_computing_cpu_cpu_usage_mpi_python.txt |
Q:
H-Geometry in Python
Is there any Python module for H-Geometry trigonometric functions? It would be pretty easy to write them, but I'd prefer to avoid it, especially if there is an existing better implementation out there.
I looked through the Python math library, but it doesn't have these functions.
A:
I wrote ... | H-Geometry in Python | Is there any Python module for H-Geometry trigonometric functions? It would be pretty easy to write them, but I'd prefer to avoid it, especially if there is an existing better implementation out there.
I looked through the Python math library, but it doesn't have these functions.
| [
"I wrote incomplete library for H-Geometry, but decided to push it only now. It can be found at https://github.com/simukis/H-Geometry\n",
"Look into numpy, if you're doing numerical calculations of any sort. E.g. numpy.sinh, numpy.tanh, np.cosh, etc.\n"
] | [
1,
0
] | [] | [] | [
"geometry",
"module",
"python",
"trigonometry"
] | stackoverflow_0006049902_geometry_module_python_trigonometry.txt |
Q:
soaplib with mod_wsgi without django, cherypy or other framework
I checked soaplib for python on net and i get the example
import soaplib
from soaplib.core.service import rpc, DefinitionBase
from soaplib.core.model.primitive import String, Integer
from soaplib.core.server import wsgi
from soaplib.core.model.clazz... | soaplib with mod_wsgi without django, cherypy or other framework | I checked soaplib for python on net and i get the example
import soaplib
from soaplib.core.service import rpc, DefinitionBase
from soaplib.core.model.primitive import String, Integer
from soaplib.core.server import wsgi
from soaplib.core.model.clazz import Array
class HelloWorldService(DefinitionBase):
@soap(Str... | [
"Like every other \"Integration With\" document in the wiki, except with application = wsgi.Application(soap_application).\n"
] | [
3
] | [] | [] | [
"mod_wsgi",
"python",
"soaplib"
] | stackoverflow_0006452480_mod_wsgi_python_soaplib.txt |
Q:
How to run Python code using less than 1% of CPU?
I am developing some Python code for Windows. A criteria is that it will use less than 1% of CPU. I understand that it is impossible to guarantee this all the time due to things like garbage collection, but what would be the best practice to get as close as possibl... | How to run Python code using less than 1% of CPU? | I am developing some Python code for Windows. A criteria is that it will use less than 1% of CPU. I understand that it is impossible to guarantee this all the time due to things like garbage collection, but what would be the best practice to get as close as possible. My current solution is to spread a lot of time.sleep... | [
"It is the job of the operating system to schedule CPU time. Use your operating system's built-in process-limits mechanisms (hopefully they exist on Windows) to restrict your process to <1% CPU.\nThis style of sprinkling unnecessary sleeps every few lines in the code will make the code terrible to create and extend... | [
11,
11,
3
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0006451692_python_python_3.x.txt |
Q:
How to properly use mysqldb in python
I'm trying to figure out how to use python's mysqldb. I can do my job with my current knownledge, but I want to use the best practices.
Should I close properly my cursor? Exiting the program isn't close it autmatically? (Shouldn't I expect the object destructor to do it anyway... | How to properly use mysqldb in python | I'm trying to figure out how to use python's mysqldb. I can do my job with my current knownledge, but I want to use the best practices.
Should I close properly my cursor? Exiting the program isn't close it autmatically? (Shouldn't I expect the object destructor to do it anyway?)
Should I create new cursors for every qu... | [
"\nShould I close properly my cursor?\n\nYes, you should. Explicit is better than implicit.\n\nShould I create new cursors for every\n query, or one cursor is enough for\n multiple different queries in the same\n DB?\n\nThis depends on how you use this cursor. For simple tasks it is enough to use one cursor. ... | [
2
] | [] | [] | [
"cursor",
"mysql_python",
"python"
] | stackoverflow_0006453067_cursor_mysql_python_python.txt |
Q:
Django class based views - threading issue?
I think I'm experiencing a threadding issue with the Django class-based views I have written.
After launching the application, the UpdateView functions fine until CreateView is called/visited. Then subsequent UpdateViews populate the 'code' field with the value generated... | Django class based views - threading issue? | I think I'm experiencing a threadding issue with the Django class-based views I have written.
After launching the application, the UpdateView functions fine until CreateView is called/visited. Then subsequent UpdateViews populate the 'code' field with the value generated in the get_initial method of CreateView.
The pro... | [
"Try removing the call to super's get_initial. It's seems to use a class property instead of an instance property, causing you trouble. Try this:\ndef get_initial(self):\n myobject = MyObject.objects.order_by('-code')[0]\n code = int(myobject.code) + 1\n initial={'code': str(code)}\n return initial\n\... | [
1
] | [] | [] | [
"django",
"multithreading",
"python"
] | stackoverflow_0006451229_django_multithreading_python.txt |
Q:
DeadlineExceededError: ApplicationError: 5 in using urllib2.urlopen() function
In my application I am using the urllib2.urlopen() function to call an api and get the result from that api.But this is not working fine.Sometimes it shows the result but sometimes it gives the following error:
Traceback (most recent ca... | DeadlineExceededError: ApplicationError: 5 in using urllib2.urlopen() function | In my application I am using the urllib2.urlopen() function to call an api and get the result from that api.But this is not working fine.Sometimes it shows the result but sometimes it gives the following error:
Traceback (most recent call last):
File "/base/python_runtime/python_lib/versions/1/google/appengine/ext/we... | [
"The default timeout for URL Fetch requests is just 5 seconds so you might want to increase it by using the urlfetch directly:\nfrom google.appengine.api import urlfetch\n\ntry:\n resp = urlfetch.fetch('http://whoapi.com/api-v1/?domain=%s&rtype=serverip&apikey=xyzxyz'% domain, method=urlfetch.GET, deadline=10)\n... | [
12,
0
] | [] | [] | [
"google_app_engine",
"python",
"try_catch",
"urllib2",
"urlopen"
] | stackoverflow_0006453003_google_app_engine_python_try_catch_urllib2_urlopen.txt |
Q:
One-liner possible?
I know that in Python this is possible:
'\n'.join(alist)
Assuming the 'alist' is a list of urls, can I output an HTML string which will produce a list of href tags, something like this
'<a href="'.join(alist)
I know the above is wrong, but I was wondering if there was a smarter way to do this... | One-liner possible? | I know that in Python this is possible:
'\n'.join(alist)
Assuming the 'alist' is a list of urls, can I output an HTML string which will produce a list of href tags, something like this
'<a href="'.join(alist)
I know the above is wrong, but I was wondering if there was a smarter way to do this. I have done the followi... | [
"You're looking for a generator expression:\n''.join('<a href=\"' + u + '\">' + u + '</a><br/>' for u in adict[alist])\n\nIf you don't want a <br/> after the last item, move the <br/> into the string to join with.\nAlso, I'm assuming here adict[alist] contains HTML code. If it contains text, you must wrap u with ht... | [
6,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0006454179_python.txt |
Q:
Shutil.copy and Glob
I am trying to copy all the files containing 'BNALP' to another directory called 'source'...I tried using the glob and shutil function to do this but an error message always arises stating "TypeError: coercing to Unicode: need string or buffer, list found". I was wondering if anyone could hel... | Shutil.copy and Glob | I am trying to copy all the files containing 'BNALP' to another directory called 'source'...I tried using the glob and shutil function to do this but an error message always arises stating "TypeError: coercing to Unicode: need string or buffer, list found". I was wondering if anyone could help me in the right directio... | [
"Have you tried the solutions provided on How do I copy a file in python? Based on half-remembered python and your error message, are you trying to copy a list of files to a destination? If so, you'd need to iterate through them calling the copy each time.\nSee also\n\ncopy multiple files in python\nPython Windows... | [
2
] | [] | [] | [
"python",
"shutil"
] | stackoverflow_0006455127_python_shutil.txt |
Q:
python:extract certain part of string
I have a string from which I would like to extract certain part. The string looks like :
E:/test/my_code/content/dir/disp_temp_2.hgx
This is a path on a machine for a specific file with extension hgx
I would exactly like to capture "disp_temp_2". The problem is that I used s... | python:extract certain part of string | I have a string from which I would like to extract certain part. The string looks like :
E:/test/my_code/content/dir/disp_temp_2.hgx
This is a path on a machine for a specific file with extension hgx
I would exactly like to capture "disp_temp_2". The problem is that I used strip function, does not work for me correct... | [
"Use the os.path module:\nimport os.path\nfilename = \"E:/test/my_code/content/dir/disp_temp_2.hgx\"\nname = os.path.basename(filename).split('.')[0]\n\n",
"Python comes with the os.path module, which gives you much better tools for handling paths and filenames:\n>>> import os.path\n>>> p = \"E:/test/my_code/cont... | [
6,
3,
1,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0006455145_python.txt |
Q:
importing protobuf generated modules within packages
This is my directory structure.
.
|-- A
| |-- B
| | `-- b.proto
| `-- C
| `-- c.proto
`-- py_gen
I compile the test.proto like this
protoc --python_out=py_gen/ --proto_path ${ROOT}/A ${ROOT}/A/B/b.proto \
${ROOT}/A/C/c.proto
and this is ... | importing protobuf generated modules within packages | This is my directory structure.
.
|-- A
| |-- B
| | `-- b.proto
| `-- C
| `-- c.proto
`-- py_gen
I compile the test.proto like this
protoc --python_out=py_gen/ --proto_path ${ROOT}/A ${ROOT}/A/B/b.proto \
${ROOT}/A/C/c.proto
and this is the results that I get.
.
`-- py_gen
|-- B
... | [
"Just:\nimport B.b_pb2\n\nWithout the .py ending. Also, for this to work, the B directory must have an __init__.py file in it, which can be empty. This tells Python this is a package directory. AFAIK protobuf won't put the __init__.py in there for your - but neither should it, since its goal is to just generate a s... | [
3
] | [] | [] | [
"protocol_buffers",
"python"
] | stackoverflow_0006455244_protocol_buffers_python.txt |
Q:
How can I parallelize method calls on an array of objects?
I have a simulation that consists of a list of objects. I'd like to call a method on all of those objects in parallel, since none of them depends on the other, using a thread pool. You can't pickle a method, so I was thinking of using a wrapper function ... | How can I parallelize method calls on an array of objects? | I have a simulation that consists of a list of objects. I'd like to call a method on all of those objects in parallel, since none of them depends on the other, using a thread pool. You can't pickle a method, so I was thinking of using a wrapper function with a side effect to do something like the following:
from mult... | [
"The main source of confusion is that multiprocessing uses separate processes and not threads. This means that any changes to object state made by the children aren't automatically visible to the parent.\nThe easiest way to handle this in your example is to have wrapper return the new value, and then use the return... | [
1
] | [] | [] | [
"multiprocessing",
"python"
] | stackoverflow_0006455465_multiprocessing_python.txt |
Q:
Python Regex that adds space after dot
How can I use re to write a regex in Python that finds the pattern:
dot "." followed directly by any char [a-zA-Z] (not space or digit)
and then add a space between the dot and the char?
i.e.
str="Thanks.Bob"
newsttr="Thanks. Bob"
Thanks in advance,
Zvi
A:
re.sub(r'\.... | Python Regex that adds space after dot | How can I use re to write a regex in Python that finds the pattern:
dot "." followed directly by any char [a-zA-Z] (not space or digit)
and then add a space between the dot and the char?
i.e.
str="Thanks.Bob"
newsttr="Thanks. Bob"
Thanks in advance,
Zvi
| [
"re.sub(r'\\.([a-zA-Z])', r'. \\1', oldstr)\n",
"re.sub('(?<=\\.)(?=[a-zA-Z])', ' ', str)\n\n",
"Try\nre.sub(r\"\\.([a-zA-Z])\", \". \\\\1\", \"Thanks.Bob\")\n\n"
] | [
15,
6,
2
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0006455557_python_regex.txt |
Q:
Extracting line after new line
I have a text file with something like
Country1
city1
city2
Country2
city3
city4
I want to separate country and cities. Is there any quick way of doing it? I am thinking of some file handling and then extracting to different files, is it best way or can be done with some regex etc ... | Extracting line after new line | I have a text file with something like
Country1
city1
city2
Country2
city3
city4
I want to separate country and cities. Is there any quick way of doing it? I am thinking of some file handling and then extracting to different files, is it best way or can be done with some regex etc quickly?
| [
"countries=[]\ncities=[]\nwith open(\"countries.txt\") as f:\n gap=True\n for line in f:\n line=line.strip()\n if gap:\n countries.append(line)\n gap=False\n elif line==\"\":\n gap=True\n else:\n cities.append(line)\nprint countries\nprin... | [
5,
2,
1,
1,
0,
0,
0,
0,
0
] | [] | [] | [
"parsing",
"php",
"python",
"regex",
"vim"
] | stackoverflow_0006436170_parsing_php_python_regex_vim.txt |
Q:
Python/Django - *args as list
I'm using the .order_by() method/function; however, I want to construct the order_by fields dynamically. The problem is .order_by() expects to receive a string or buffer. So, I can't build a list or tuple or object to send to the function. How can I achieve this goal?
I wanted to d... | Python/Django - *args as list | I'm using the .order_by() method/function; however, I want to construct the order_by fields dynamically. The problem is .order_by() expects to receive a string or buffer. So, I can't build a list or tuple or object to send to the function. How can I achieve this goal?
I wanted to do something like:
field_list = []
f... | [
"You can use model.objects.all().order_by(*field_list); this is due to the fact that order_by accepts multiple string arguments, not lists of multiple strings.\nSee This chapter in djangobook, search for order_by, and this for arguments unpacking.\n"
] | [
8
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0006456119_django_django_models_python.txt |
Q:
(Python) Set a specific palette in an image using PIL or PyPNG
I have a bunch of images that I am working on separately, that fit back together after being worked on. I'd like to compress them to a 8 bit image in order to save size. I'm currently doing this with PIL by calling:
image = image.convert('P', palette=I... | (Python) Set a specific palette in an image using PIL or PyPNG | I have a bunch of images that I am working on separately, that fit back together after being worked on. I'd like to compress them to a 8 bit image in order to save size. I'm currently doing this with PIL by calling:
image = image.convert('P', palette=Image.ADAPTIVE, colors=256)
The problem is though that the palettes ... | [
"Only way so far I have discovered to do this is using PythonMagick, which is unfortunate as PythonMagick is slow, undocumented, and difficult to install on Linux if you don't use the python-pythonmagick package. \ncolormap = PythonMagick.Image(\"colors256.png\")\noriginal.map(colormap)\n\n"
] | [
0
] | [] | [] | [
"image",
"imaging",
"palette",
"python",
"python_imaging_library"
] | stackoverflow_0006445865_image_imaging_palette_python_python_imaging_library.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.