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:
User defined Exception doubt
I have this exception class
class Value(Exception):
def __init__(self,val):
self.val = val
def __str__(self):
return repr(self.val)
raise Value('4')
and the exception comes as
Traceback (most recent call last):
File "<module1>", line 20, in <module>
Value: '... | User defined Exception doubt | I have this exception class
class Value(Exception):
def __init__(self,val):
self.val = val
def __str__(self):
return repr(self.val)
raise Value('4')
and the exception comes as
Traceback (most recent call last):
File "<module1>", line 20, in <module>
Value: '4'
------------------------------... | [
"I think you meant to write val instead of value here:\ndef __str__(self):\n return repr(self.val) # <--- not self.value\n\nTo display multiple values I'd recommend str.format (requires Python 2.6 or newer). Example:\ndef __str__(self):\n return \"Hello: {0}\".format(self.val)\n\nAnother example:\ndef __str__... | [
2,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0004490038_python.txt |
Q:
Is it possible to see the source code of the violating files in Hudson with Violations and Pylint?
I'm using Hudson CI with a Python project. I've installed the Violations plugin and configured it to run the code against pylint. This works, but I only see a list of violations without linking to the source code. Is... | Is it possible to see the source code of the violating files in Hudson with Violations and Pylint? | I'm using Hudson CI with a Python project. I've installed the Violations plugin and configured it to run the code against pylint. This works, but I only see a list of violations without linking to the source code. Is it possible to setup Violations and pylint to load and highlight the violating source files (something ... | [
"Well, after some more debugging, I realized that the pylint output file referenced the source code files relative to where pylint was being run, which wasn't the same path that Hudson needed. Basically, Violations needed the paths relative to the Hudson workspace.\n",
"I ran into a similar problem with pylint an... | [
2,
1,
0
] | [] | [] | [
"hudson",
"python"
] | stackoverflow_0002502345_hudson_python.txt |
Q:
Python - what is difference in os.popen and subprocess.Popen?
Python - what is difference in os.popen and subprocess.Popen?
A:
The os process functionality is considered obsolete. The subprocess module was introduced in Python 2.4 as a unified, more powerful replacement for several older modules and functions re... | Python - what is difference in os.popen and subprocess.Popen? | Python - what is difference in os.popen and subprocess.Popen?
| [
"The os process functionality is considered obsolete. The subprocess module was introduced in Python 2.4 as a unified, more powerful replacement for several older modules and functions related to subprocesses. They are listed here:\n\nos.system\nos.spawn*\nos.popen*\npopen2.*\ncommands.*\n\nos.popen was deprecated ... | [
6
] | [] | [] | [
"process",
"python"
] | stackoverflow_0004490686_process_python.txt |
Q:
Python home directory in Windows / Problem with multiple versions
I'm using Python 3 for developing and CollabNet Subversion Edge as versioning software. Subversion Edge comes with a little program called ViewVC which is written in Python 2, which is also directly bundled with it. There is a system environment var... | Python home directory in Windows / Problem with multiple versions | I'm using Python 3 for developing and CollabNet Subversion Edge as versioning software. Subversion Edge comes with a little program called ViewVC which is written in Python 2, which is also directly bundled with it. There is a system environment variable called PYTHONHOME.
If it is set to the Python 2 distribution fro... | [
"You shouldn't need to set PYTHONHOME at all. Python uses it (if set) to locate its installation. Typically, it should be able to locate it without this variable, as well: by looking at the path name of the python executable, and, failing that, by looking into the registry.\n",
"Write a .bat or cmd file that save... | [
3,
0,
0
] | [] | [] | [
"collabnet",
"python",
"windows"
] | stackoverflow_0004489683_collabnet_python_windows.txt |
Q:
Missing methods in Python class inheritance?
I am not very experienced with class inheritance. Please help me and have a look at the code below:
class Handle(STAFHandle):
def __init__(self, HandleName):
handle = STAFHandle.__init__(self, HandleName)
self.initLogger(handle)
def initLogger(... | Missing methods in Python class inheritance? | I am not very experienced with class inheritance. Please help me and have a look at the code below:
class Handle(STAFHandle):
def __init__(self, HandleName):
handle = STAFHandle.__init__(self, HandleName)
self.initLogger(handle)
def initLogger(self, handle):
self.logger = Logging(handl... | [
"STAFHandle.__init__ returns None. You probably want:\nclass Handle(STAFHandle):\n def __init__(self, handle_name):\n super(Handle, self).__init__(handle_name)\n self.initLogger()\n\n def initLogger(self):\n self.logger = Logging(self, 'Test')\n\nhandle = Handle('test')\n\nRemember that _... | [
4
] | [] | [] | [
"oop",
"python"
] | stackoverflow_0004491402_oop_python.txt |
Q:
Replace part of numpy 1D array with shorter array
I have a 1D numpy array containing some audio data. I'm doing some processing and want to replace certain parts of the data with white noise. The noise should, however, be shorter then the replaced part. Generating the noise is not a problem, but I'm wondering what... | Replace part of numpy 1D array with shorter array | I have a 1D numpy array containing some audio data. I'm doing some processing and want to replace certain parts of the data with white noise. The noise should, however, be shorter then the replaced part. Generating the noise is not a problem, but I'm wondering what the easiest way to replace the original data with the ... | [
"What advantage does a numpy array have over a python list for your application? I think one of the weaknesses of numpy arrays is that they are not easy to resize:\nhttp://mail.python.org/pipermail/python-list/2008-June/1181494.html\nDo you really need to reclaim the memory from the segments of the array you're sho... | [
5,
0
] | [] | [] | [
"arrays",
"numpy",
"python"
] | stackoverflow_0004490987_arrays_numpy_python.txt |
Q:
Math formula for first person 3d game
I want to make a first person 3d game but I can't set the camera formula right.
So I have a rotation: 0 to 359. Next the x,y coordinates, z remains the same.
Camera rotation : 0 - front, 90 - left, 180 - back, 270 - right but I can adapt it
What is the formula for the camera ... | Math formula for first person 3d game | I want to make a first person 3d game but I can't set the camera formula right.
So I have a rotation: 0 to 359. Next the x,y coordinates, z remains the same.
Camera rotation : 0 - front, 90 - left, 180 - back, 270 - right but I can adapt it
What is the formula for the camera ?
Platform: Panda3d, python, opengl
Thank y... | [
"OK, it looks like you need a Doom style camera movement, i.e., no up-down turns. Consider this:\n\nYou need to render the \"world\" as seen through the camera.\nAssuming positive x is to the right and positive y is to your front, when the camera moves to the right the world's image moves to the left.\nWhen the cam... | [
3,
0
] | [] | [] | [
"3d",
"math",
"panda3d",
"python"
] | stackoverflow_0004490570_3d_math_panda3d_python.txt |
Q:
Is python is a good choice as language used to implementing my first 3D model?
I am C/C /Java programmer, but lately I have started learn Python.
Moreover I have 3D Graphics on my studies. I have to create 3D model of my apartment, with dynamic camera. I am wondering if this is a good idea to merge this two issu... | Is python is a good choice as language used to implementing my first 3D model? | I am C/C /Java programmer, but lately I have started learn Python.
Moreover I have 3D Graphics on my studies. I have to create 3D model of my apartment, with dynamic camera. I am wondering if this is a good idea to merge this two issues, by writing this 3D model in python.
However as I said, I am a python beginner, ... | [
"You can also checkout Pyglet, which is a higher-level library for using with OpenGL.\n",
"IMHO C++ is a better option for 3D graphics, and you have experience in it.\nThough you can have a look at PyOpenGL, python bindings for OpenGl.\n\nhttp://pyopengl.sourceforge.net/\n\n",
"If you're solely trying to learn ... | [
4,
3,
2,
1
] | [] | [] | [
"3d",
"python"
] | stackoverflow_0004490991_3d_python.txt |
Q:
Where to place the call to a external API that has a dependency on a Model?
Suppose I have a Django app named "blog".
There's a model called Post and I have an external API call that returns the list of the most popular posts in a given time, e.g., the Google Analytics API.
My question is: Where is the expected pl... | Where to place the call to a external API that has a dependency on a Model? | Suppose I have a Django app named "blog".
There's a model called Post and I have an external API call that returns the list of the most popular posts in a given time, e.g., the Google Analytics API.
My question is: Where is the expected place that I should place the code that makes the call to the external API, parses ... | [
"It should be done in a view, or better, if your view code is getting cluttered, put it in a helper module.\nimport util\ndef view(request):\n util.process_post_rankings(request.user.id)\n # ... write additional logic and render to template\n\nHowever, be cautious with relying on external apis to render a pag... | [
4,
1
] | [] | [] | [
"django",
"python",
"web_services"
] | stackoverflow_0004491434_django_python_web_services.txt |
Q:
Cron Terminates Python Script?
I have a 'long' python script that takes roughly 45[min] to run. I use another (a 'scheduler' script) python script to run this long script. When I run the 'scheduler' script using the terminal, everything works perfectly (meaning, the 'long' script runs without any issues).
I had so... | Cron Terminates Python Script? | I have a 'long' python script that takes roughly 45[min] to run. I use another (a 'scheduler' script) python script to run this long script. When I run the 'scheduler' script using the terminal, everything works perfectly (meaning, the 'long' script runs without any issues).
I had some struggles, but eventually succeed... | [
"I have a hunch that it's due to the way cron handles stdout. How are you redirecting output?\nFrom http://aplawrence.com/BDD/bbcronbasics.html:\n\nOUTPUT\nNormally the output of any program is\n sent to STDOUT (standard out) and\n usually winds up on someone's display\n screen. For jobs started by cron,\n STD... | [
6
] | [] | [] | [
"cron",
"linux",
"popen",
"python",
"subprocess"
] | stackoverflow_0004491708_cron_linux_popen_python_subprocess.txt |
Q:
Python Parsing Framework
If I needed facilitate the extraction of data from various (non-API) internet sources, is there a framework-type solution that would streamline the process of having developers write reusable, yet source specific parsers on a large scale?
A:
Pyparsing is a Python library that I've found ... | Python Parsing Framework | If I needed facilitate the extraction of data from various (non-API) internet sources, is there a framework-type solution that would streamline the process of having developers write reusable, yet source specific parsers on a large scale?
| [
"Pyparsing is a Python library that I've found to be very useful for parsing custom domain specific languages.\n",
"For *ML screen scraping, look no further than Beautiful Soup.\n"
] | [
5,
0
] | [] | [] | [
"data_mining",
"python",
"text_parsing"
] | stackoverflow_0004491292_data_mining_python_text_parsing.txt |
Q:
Drawing fast lines in pygame
I'm trying to draw fast lines using pygame that aren't rendered directly to the screen. I've got a Python list as large as the number of pixels for the desired resolution, and store integer values corresponding to the number of times that pixel was hit by the line algorithm. Using th... | Drawing fast lines in pygame | I'm trying to draw fast lines using pygame that aren't rendered directly to the screen. I've got a Python list as large as the number of pixels for the desired resolution, and store integer values corresponding to the number of times that pixel was hit by the line algorithm. Using this, a 2D heat map is built up, so ... | [
"Try Cython or something similar. (If you do, I would be interested in knowing if/how much that helped)\n\nCython is a programming language to\n simplify writing C and C++ extension\n modules for the CPython Python\n runtime. Strictly speaking, Cython\n syntax is a superset of Python syntax\n additionally supp... | [
1
] | [] | [] | [
"bresenham",
"pygame",
"python"
] | stackoverflow_0004491892_bresenham_pygame_python.txt |
Q:
How to use python to invoke events on a desktop?
how to use python to invoke events , like a torrent application and also feeding it with a torrent file in linux ?
A:
Most bittorrent apps on Linux will accept a .torrent file as a command line parameter. With some (notable Azureus//Vuze) you may need to use a ful... | How to use python to invoke events on a desktop? | how to use python to invoke events , like a torrent application and also feeding it with a torrent file in linux ?
| [
"Most bittorrent apps on Linux will accept a .torrent file as a command line parameter. With some (notable Azureus//Vuze) you may need to use a fully qualified pathname, which you can get with os.path.abspath. Then just use your favorite method of running programs from Python like the subprocess module or even os.s... | [
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0004492001_python.txt |
Q:
Python readability through descriptive naming
I have been using Python for about a year now, coming from a mostly Java background. I found Python quite easy to learn because of its focus on readability and simple design. The thing I don't understand about python is why for a language that focuses so heavily on rea... | Python readability through descriptive naming | I have been using Python for about a year now, coming from a mostly Java background. I found Python quite easy to learn because of its focus on readability and simple design. The thing I don't understand about python is why for a language that focuses so heavily on readability, it often uses very non-descriptive names ... | [
"I guess there's a balance to be struck between being descriptive and concise, and Python's scripting background makes it somewhat more concise than Java (because us hobbyists are too lazy for all that typing ;-) ). At the risk of sounding like a fanboy, Python tries to walk the line between the descriptive-but-lon... | [
2,
0
] | [] | [] | [
"naming_conventions",
"python"
] | stackoverflow_0004491550_naming_conventions_python.txt |
Q:
CPython as a library for C (To execute Python code from C)
I'm not C expert so what I'm asking might be crazy.
Is it possible to compile CPython using an ARM c-compiler (like yagarto or arm-gcc)
and then call it from a C application to process lines of python code?
If so, what are the resources/documents I should... | CPython as a library for C (To execute Python code from C) | I'm not C expert so what I'm asking might be crazy.
Is it possible to compile CPython using an ARM c-compiler (like yagarto or arm-gcc)
and then call it from a C application to process lines of python code?
If so, what are the resources/documents I should be looking at?
| [
"Embedding Python in Another Application on Python.org\n"
] | [
3
] | [] | [] | [
"arm",
"c",
"compiler_construction",
"cpython",
"python"
] | stackoverflow_0004492174_arm_c_compiler_construction_cpython_python.txt |
Q:
Tool to detect non-dotted relative imports in Python?
It's considered bad Python to use imports like this:
import my_module
When you are doing a relative import and this would work:
from . import my_module
Is there a tool that can detect these non-dotted relative imports in my code and warn me so I could update ... | Tool to detect non-dotted relative imports in Python? | It's considered bad Python to use imports like this:
import my_module
When you are doing a relative import and this would work:
from . import my_module
Is there a tool that can detect these non-dotted relative imports in my code and warn me so I could update them to the dotted syntax? My project has hundreds of Pytho... | [
"[Reposted as an answer because it apparently did the trick]\n2to3 will automatically convert them, because it's compulsory in Python 3.\nHere's the relevant source code if you want to modify it for your purposes.\nAlternatively, you could just run 2to3 with only that fixer: 2to3 -w -f import myproject/\n",
"pyli... | [
5,
1
] | [] | [] | [
"import",
"python",
"relative_path"
] | stackoverflow_0004490564_import_python_relative_path.txt |
Q:
How to convert string to byte arrays?
How can I convert a string to its byte value? I have a string "hello" and I want to change is to something like "/x68...".
A:
Python 2.6 and later have a bytearray type which may be what you're looking for. Unlike strings, it is mutable, i.e., you can change individual bytes... | How to convert string to byte arrays? | How can I convert a string to its byte value? I have a string "hello" and I want to change is to something like "/x68...".
| [
"Python 2.6 and later have a bytearray type which may be what you're looking for. Unlike strings, it is mutable, i.e., you can change individual bytes \"in place\" rather than having to create a whole new string. It has a nice mix of the features of lists and strings. And it also makes your intent clear, that you a... | [
33,
28,
14
] | [] | [] | [
"python"
] | stackoverflow_0004490901_python.txt |
Q:
Validity of GUI design patterns under linux
I am investigating a switch from windows to linux and i struggle to find samples of design patterns applied in this world.
The application is a classic client server with detailed forms for each business entity.
It will be taking user input, do some validation checks, a ... | Validity of GUI design patterns under linux | I am investigating a switch from windows to linux and i struggle to find samples of design patterns applied in this world.
The application is a classic client server with detailed forms for each business entity.
It will be taking user input, do some validation checks, a few calculations, and save them to database.
It w... | [
"When you go Python, have a look at Qt (Python bindings to choose from: PyQt or PySide). Qt is a really nice / feature complete / mature cross-platform GUI library (which also does some other things). \nAs far as Python bindings are concerned, PyQt is GPL or commercial at the moment / PySide is LGPL (if licenses ma... | [
4,
2,
1,
0,
0
] | [] | [] | [
"design_patterns",
"linux",
"mvvm",
"python",
"ruby"
] | stackoverflow_0002751548_design_patterns_linux_mvvm_python_ruby.txt |
Q:
jQuery getJSON Output using Python/Django
So, I'm trying to make a simple call using jQuery .getJSON to my local web server using python/django to serve up its requests. The address being used is:
http://localhost:8000/api/0.1/tonight-mobile.json?callback=jsonp1290277462296
I'm trying to write a simple web view... | jQuery getJSON Output using Python/Django | So, I'm trying to make a simple call using jQuery .getJSON to my local web server using python/django to serve up its requests. The address being used is:
http://localhost:8000/api/0.1/tonight-mobile.json?callback=jsonp1290277462296
I'm trying to write a simple web view that can access this url and return a JSON pac... | [
"First, callback = request.GET.get('callback=?', '') won't get you the value of callback.\ncallback = request.GET.get( 'callback', None ) \n\nWorks much better.\nTo debug this kind of thing. You might want to include print statements in your Django view function so you can see what's going on. For example: print ... | [
0
] | [] | [] | [
"django_views",
"getjson",
"jsonp",
"python"
] | stackoverflow_0004492919_django_views_getjson_jsonp_python.txt |
Q:
How can I get an album URL from the Picasa API?
I really don't like the Picasa feed-oriented API. Why couldn't they create a REST interface?
Does anyone know how I can get the URL for a particular album? For example, say I have:
gd_client = gdata.photos.service.PhotosService()
albums = gd_client.GetUserFeed(user="... | How can I get an album URL from the Picasa API? | I really don't like the Picasa feed-oriented API. Why couldn't they create a REST interface?
Does anyone know how I can get the URL for a particular album? For example, say I have:
gd_client = gdata.photos.service.PhotosService()
albums = gd_client.GetUserFeed(user="user@gmail.com")
album = albums.entry[0]
How can I f... | [
"you can access an album's picasaweb url through calling .GetHtmlLink().href on an entry\nalbum_urls = [album.GetHtmlLink().href for album in albums.entry]\n\n"
] | [
6
] | [
"Get the album URL by going to http://picasaweb.google.com/[username]/[album title].\n"
] | [
-1
] | [
"picasa",
"python"
] | stackoverflow_0001760329_picasa_python.txt |
Q:
Is there a built-in function to sort and filter a python list in one step?
Given a directory of files all with numeric names, I currently sort and filter the directory list in two steps.
#files = os.listdir(path)
files = ["0", "1", "10", "5", "2", "11", "4", "15", "18", "14", "7", "8", "9"]
firstFile = 5
lastFil... | Is there a built-in function to sort and filter a python list in one step? | Given a directory of files all with numeric names, I currently sort and filter the directory list in two steps.
#files = os.listdir(path)
files = ["0", "1", "10", "5", "2", "11", "4", "15", "18", "14", "7", "8", "9"]
firstFile = 5
lastFile = 15
#filter out any files that are not in the desired range
files = filter(... | [
"Those are orthogonal tasks, I don't think they should be mixed. Besides, it's easy to filter and sort separately in one line with generator expressions\nfiles = sorted( (f for f in files if firstFile <= int(f) < lastFile), key=int)\n\n",
"The most straightforward way to do this is (in 2.6 at least) is to create ... | [
23,
1
] | [] | [] | [
"python"
] | stackoverflow_0004492254_python.txt |
Q:
Directing script output to a file using subprocess?
From within a python script ("main.py"), I am using the subprocess module to run another script ("sub_script.py").
Here's the code in the "main.py" script that 'runs' "sub_script.py":
subprocess.Popen([sys.executable, "sub_script.py"])
this works fine as long as... | Directing script output to a file using subprocess? | From within a python script ("main.py"), I am using the subprocess module to run another script ("sub_script.py").
Here's the code in the "main.py" script that 'runs' "sub_script.py":
subprocess.Popen([sys.executable, "sub_script.py"])
this works fine as long as "sub_script.py" does not have any "print" statements in ... | [
"subprocess.Popen([sys.executable, \"sub_script.py\"], stdout=open(\"log.txt\", \"a\"))\n\n"
] | [
2
] | [] | [] | [
"linux",
"python",
"subprocess"
] | stackoverflow_0004493067_linux_python_subprocess.txt |
Q:
Appropriate Data structure
I have to implement the value iteration algorithm for finding the optimal policy for each state of an MDP using Bellman's equation.
The input file is some thing like below:
s1 0 (a1 s1 0.5) (a1 s2 0.5) (a2 s1 1.0)
s2 0 (a1 s2 1.0) (a2 s1 0.5) (a2 s3 0.5)
s3 10 (a1 s2 1.0) (a2 s3 0.5) (a2... | Appropriate Data structure | I have to implement the value iteration algorithm for finding the optimal policy for each state of an MDP using Bellman's equation.
The input file is some thing like below:
s1 0 (a1 s1 0.5) (a1 s2 0.5) (a2 s1 1.0)
s2 0 (a1 s2 1.0) (a2 s1 0.5) (a2 s3 0.5)
s3 10 (a1 s2 1.0) (a2 s3 0.5) (a2 s4 0.5)
where s1 is the state 0... | [
"s1 0 (a1 s1 0.5) (a1 s2 0.5) (a2 s1 1.0)\ns2 0 (a1 s2 1.0) (a2 s1 0.5) (a2 s3 0.5)\ns3 10 (a1 s2 1.0) (a2 s3 0.5) (a2 s4 0.5)\n\nSomething like this?\ndata = { 's1': { 'reward': 0,\n 'action': { 'a1': { 's1': 0.5,\n 's2': 0.5 },\n 'a2'... | [
2,
0
] | [] | [] | [
"machine_learning",
"python"
] | stackoverflow_0003807531_machine_learning_python.txt |
Q:
Read-only Django object manager?
I am doing agressive caching and I'd like to make sure that nobody accidentally writes code that updates the database directly. I would imagine that the way to solve this would be to rename the normal object manager .rw_objects for the caches use, and replace .objects with a manage... | Read-only Django object manager? | I am doing agressive caching and I'd like to make sure that nobody accidentally writes code that updates the database directly. I would imagine that the way to solve this would be to rename the normal object manager .rw_objects for the caches use, and replace .objects with a manager that logs a warning on a non-updatin... | [
"I'm thinking about two approaches here.\n\nCreate a custom Manager, override _insert(), _update() to raise exception / log the query, and get_query_set() to return custom QuerySet that overrides create(), get_or_create(), and update().\nIf you're using django 1.2, Create another database connection in settings.py ... | [
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0004493385_django_python.txt |
Q:
Google App Engine, define a Preprocessing class
I am trying to define a base request handling class so that the webapp pages may inherit some basic methods and variable which otherwise would be required to be repeatedly be defined for each page of the application. A sort of similar functionality like django prepro... | Google App Engine, define a Preprocessing class |
I am trying to define a base request handling class so that the webapp pages may inherit some basic methods and variable which otherwise would be required to be repeatedly be defined for each page of the application. A sort of similar functionality like django preprocessors. This is my base class from which other pag... | [
"A much simpler solution than bgporter's is to do the common setup in the initialize method of webapp.RequestHandler. Here's an example from work, where we wanted to add a Django-like is_ajax method to the request object:\nclass BaseHandler(webapp.RequestHandler):\n def initialize(self, request, response):\n ... | [
5,
2
] | [] | [] | [
"django_templates",
"google_app_engine",
"preprocessor",
"python",
"web_applications"
] | stackoverflow_0004488015_django_templates_google_app_engine_preprocessor_python_web_applications.txt |
Q:
check if a number is present in a list, app engine templates
I am trying to generate a board (10X10) using the app engine templates and html table. So this means basically putting a break after 10 iterations of the loop. How can I acieve this using the app engine's inbuilt template engine (django 0.96)?
Update
Luk... | check if a number is present in a list, app engine templates | I am trying to generate a board (10X10) using the app engine templates and html table. So this means basically putting a break after 10 iterations of the loop. How can I acieve this using the app engine's inbuilt template engine (django 0.96)?
Update
Lukes answer solved my problem of automatically inserting the break.
... | [
"Does 0.96's templatetags have divisibleby? That seems like it'd do the trick:\n{% for end_number in end_numbers %}\n {% if forloop.counter|divisibleby:\"10\" %}\n </tr>\n {% endif %}\n{% endfor %}\n\n",
"At this point you might be better off writing your own templatetag, or using something like smarti... | [
5,
1,
1,
0
] | [] | [] | [
"conditional_statements",
"django_templates",
"google_app_engine",
"loops",
"python"
] | stackoverflow_0004493275_conditional_statements_django_templates_google_app_engine_loops_python.txt |
Q:
How can I extract only the email body with Python using IMAP?
I am relatively new to programming and to python, but I think I have done ok so far. This is the code I have, and it works fine, except it gets the entire message in MIME format. I only want the text body of unread emails, but I can't quite figure it ou... | How can I extract only the email body with Python using IMAP? | I am relatively new to programming and to python, but I think I have done ok so far. This is the code I have, and it works fine, except it gets the entire message in MIME format. I only want the text body of unread emails, but I can't quite figure it out how to strip out all of the formatting and header info. If I send... | [
"Sounds like you're looking for the email package:\n\nThe email package provides a standard parser that understands most email document structures, including MIME documents. You can pass the parser a string or a file object, and the parser will return to you the root Message instance of the object structure. For si... | [
1
] | [] | [] | [
"imap",
"printing",
"python"
] | stackoverflow_0004493573_imap_printing_python.txt |
Q:
How to override save() method of modelform class and added missing information?
I just started to learn Django and I had a question.
I'm trying to automatically add the missing information, when saving form data. I get to change/add the desired "cleaned_data" information by overriding save() method of modelform cl... | How to override save() method of modelform class and added missing information? | I just started to learn Django and I had a question.
I'm trying to automatically add the missing information, when saving form data. I get to change/add the desired "cleaned_data" information by overriding save() method of modelform class, but changes are not recorded in the database. Actually, how to write the modifie... | [
"Try setting the data on self.instance instead of in self.cleaned_data, and let me know if that works.\n"
] | [
2
] | [] | [] | [
"django",
"modelform",
"models",
"python",
"save"
] | stackoverflow_0004493822_django_modelform_models_python_save.txt |
Q:
Regex question about parsing method signature
I'm trying to parse a method signature that is in this format:
'function_name(foo=<str>, bar=<array>)'
From this, I want the name of the method, and each argument and it's type. Obviously I don't want the <, > characters, etc. The number of parameters will be variable... | Regex question about parsing method signature | I'm trying to parse a method signature that is in this format:
'function_name(foo=<str>, bar=<array>)'
From this, I want the name of the method, and each argument and it's type. Obviously I don't want the <, > characters, etc. The number of parameters will be variable.
My question is: How is it possible to get all the... | [
"You can't match a variable number of groups with Python regular expressions (see this). Instead you can use a combination of regex and split().\n>>> name, args = re.match(r'(\\w+)\\((.*)\\)', 'function_name(foo=<str>, bar=<array>, baz=<int>)').groups()\n>>> args = [re.match(r'(\\w+)=<(\\w+)>', arg).groups() for ar... | [
2
] | [] | [] | [
"method_signature",
"python",
"regex"
] | stackoverflow_0004493844_method_signature_python_regex.txt |
Q:
How to test for situation where a specific library is missing in Python
I have some packages that have soft dependencies on other packages with a fall back to a default (simple) implementation.
The problem is that this is very hard to test for using unit tests. I could set up separate virtual environments, but tha... | How to test for situation where a specific library is missing in Python | I have some packages that have soft dependencies on other packages with a fall back to a default (simple) implementation.
The problem is that this is very hard to test for using unit tests. I could set up separate virtual environments, but that is hard to manage.
Is there a package or a way to achieve the following: ha... | [
"One way is to edit sys.path, especially if your packages install into different directories/zipfiles (e.g. if you are using eggs). Before importing, drop the ones you don't want from sys.path.\nIf that's not feasible (because all components live in a single sys.path entry), you can hack suppression into the packag... | [
2,
2
] | [] | [] | [
"import",
"python",
"unit_testing"
] | stackoverflow_0004493750_import_python_unit_testing.txt |
Q:
Another question on negative regex
I have a python script that checks code for coding convention errors. It does this by matching a regex that represents a violation of the coding standard.
One of our standards is that 'if', 'while' and 'do-while' conditionals must contain a conditional operator.
So no
if (var1)... | Another question on negative regex | I have a python script that checks code for coding convention errors. It does this by matching a regex that represents a violation of the coding standard.
One of our standards is that 'if', 'while' and 'do-while' conditionals must contain a conditional operator.
So no
if (var1)
{
// blah
}
Instead I need
if (var... | [
"This could do it for the input you provided, but as mentioned in the comments, it's better using a parser (e.g. pyparsing).\n>>> s\n'if (var1)'\n>>> s2\n'if (var1 == TRUE)'\n>>> if re.search(r\"^if.+==|<=|>=|\\|\\||&&\", s): print \"found bad signs\"\n... \n>>> if re.search(r\"^if.+==|<=|>=|\\|\\||&&\", s2): prin... | [
1,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0004389255_python_regex.txt |
Q:
Django: standard location/conventions for data import scripts?
I'm working on a number of Django projects, and in most of them, I have initial data to import.
This data isn't neat JSON, as shown in the fixture examples in the Django docs - it tends to be messy Excel or CSV files. The scripts tend to look like the ... | Django: standard location/conventions for data import scripts? | I'm working on a number of Django projects, and in most of them, I have initial data to import.
This data isn't neat JSON, as shown in the fixture examples in the Django docs - it tends to be messy Excel or CSV files. The scripts tend to look like the following snippet, and I just run them as standalone Python, because... | [
"I like putting them in management commands - that way when someone else works on the project, the commands are where they're expected to be by someone who wasn't familiar with the choices being made during initial development.\n",
"Django supports pluggable serialization modules. If you can arrange your CSV form... | [
3,
1,
0,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0004494071_django_python.txt |
Q:
Best way to convert a Unicode URL to ASCII (UTF-8 percent-escaped) in Python?
I'm wondering what's the best way -- or if there's a simple way with the standard library -- to convert a URL with Unicode chars in the domain name and path to the equivalent ASCII URL, encoded with domain as IDNA and the path %-encoded,... | Best way to convert a Unicode URL to ASCII (UTF-8 percent-escaped) in Python? | I'm wondering what's the best way -- or if there's a simple way with the standard library -- to convert a URL with Unicode chars in the domain name and path to the equivalent ASCII URL, encoded with domain as IDNA and the path %-encoded, as per RFC 3986.
I get from the user a URL in UTF-8. So if they've typed in http:/... | [
"Code:\nimport urlparse, urllib\n\ndef fixurl(url):\n # turn string into unicode\n if not isinstance(url,unicode):\n url = url.decode('utf8')\n\n # parse it\n parsed = urlparse.urlsplit(url)\n\n # divide the netloc further\n userpass,at,hostport = parsed.netloc.rpartition('@')\n user,col... | [
46,
5,
2,
2,
0
] | [] | [] | [
"python",
"unicode",
"url",
"utf_8"
] | stackoverflow_0000804336_python_unicode_url_utf_8.txt |
Q:
Parsing and grouping text in a string using Python
I need to parse a series of short strings that are comprised of 3 parts: a question and 2 possible answers. The string will follow a consistent format:
This is the question "answer_option_1 is in quotes" "answer_option_2 is in quotes"
I need to identify the ques... | Parsing and grouping text in a string using Python | I need to parse a series of short strings that are comprised of 3 parts: a question and 2 possible answers. The string will follow a consistent format:
This is the question "answer_option_1 is in quotes" "answer_option_2 is in quotes"
I need to identify the question part and the two possible answer choices that are i... | [
">>> import re\n>>> s = \"Who will win the game 'Michigan' 'Ohio State'\"\n>>> re.match(r'(.+)\\s+([\\'\"])(.+?)\\2\\s+([\\'\"])(.+?)\\4', s).groups()\n('Who will win the game', \"'\", 'Michigan', \"'\", 'Ohio State')\n\n",
"If your format is a simple as you say (i.e. not as in your examples), you don't need rege... | [
1,
1,
0,
0
] | [] | [] | [
"parsing",
"pyparsing",
"python"
] | stackoverflow_0004156464_parsing_pyparsing_python.txt |
Q:
Python regex matching problem
I have been parsing a GraphViz file for a specific identifer using Regex. Here is the typical content from this file:
node10 [label="second-messenger-mediated signaling\nGO:0019932", fontname=Courier, ...];
node11 [label="inositol phosphate-mediated signaling\nGO:0048016", fontname=C... | Python regex matching problem | I have been parsing a GraphViz file for a specific identifer using Regex. Here is the typical content from this file:
node10 [label="second-messenger-mediated signaling\nGO:0019932", fontname=Courier, ...];
node11 [label="inositol phosphate-mediated signaling\nGO:0048016", fontname=Courier, ...];
node12 [label="activ... | [
"Don't reinvent the wheel.\npydot is a library which parses dot files using pyparsing.\n",
"if you match each line, then node 12 will be splitted in 2 lines...you should read the all file or iter between one node and one other...\n",
"Is the \\ after the first line of node12 escaping the line ending?\n"
] | [
3,
2,
1
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0004494532_python_regex.txt |
Q:
Java and Python Together in Single Google App Engine Project
I currently have a Java application running on Google App Engine, but I want to add the features that the Python module's SearchableModel provides (for search features of course). Is it possible to run python code in the same project as Java code, just ... | Java and Python Together in Single Google App Engine Project | I currently have a Java application running on Google App Engine, but I want to add the features that the Python module's SearchableModel provides (for search features of course). Is it possible to run python code in the same project as Java code, just under a different version? If not, could they be two separate app... | [
"It is possible to run Python and Java applications on different versions.\nFrom:\n\nLast but not least: remember that you can have different version of your app (using the same datastore) some of which are implemented with the Python runtime, some with the Java runtime, and you can access versions that differ from... | [
9,
3
] | [] | [] | [
"google_app_engine",
"google_cloud_datastore",
"java",
"python"
] | stackoverflow_0004494539_google_app_engine_google_cloud_datastore_java_python.txt |
Q:
How do I modify my simple Python code, to take into account HTTP headers?
def URLRequest(url, params, method="POST"):
r = urllib2.urlopen(url, data=urllib.urlencode(params))
return r
In this method, I send a POST request to a certain URL. What if I want to do headers as well? I want to send a dictionary... | How do I modify my simple Python code, to take into account HTTP headers? | def URLRequest(url, params, method="POST"):
r = urllib2.urlopen(url, data=urllib.urlencode(params))
return r
In this method, I send a POST request to a certain URL. What if I want to do headers as well? I want to send a dictionary of additional headers (in addition to standard headers).
| [
"def URLPost(url, params, method=\"POST\", headers = {}):\n req = urllib2.Request(url)\n for k, v in headers.items():\n req.add_header(k, v)\n r = urllib2.urlopen(req, data=urllib.urlencode(params))\n return r\n\n",
"With urllib2, you can easily use custom \"Handlers\" to send additional heade... | [
2,
0
] | [] | [] | [
"api",
"http",
"python",
"rest",
"url"
] | stackoverflow_0004494916_api_http_python_rest_url.txt |
Q:
BFS function not returning path right
Hey guys, what's up ya'll. For this, I have to create a BFS function that finds shortest path between a destination and source for the game called Quoridor, I'm sure some of ya'll played this before. When I run it, no errors were found but I want the shortest path function to ... | BFS function not returning path right | Hey guys, what's up ya'll. For this, I have to create a BFS function that finds shortest path between a destination and source for the game called Quoridor, I'm sure some of ya'll played this before. When I run it, no errors were found but I want the shortest path function to return the path as one I did in searchBFS f... | [
"stack = myStack.Stack()\nif dest in visited:\n temp = dest\n while tmp != source:\n myStack.push(tmp, stack)\n tmp = tmp.previous\n\nI think the tmp and temp variables here should be the same? Although I would expect an error since tmp isn't assigned before you use it.\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0004495156_python.txt |
Q:
"too many values to unpack error" when trying to create a batch in pyglet
I have been trying to get batches to work in pyglet, but I am completely confused by the error message "too many values to unpack" coming from the pyglet/graphics/__init__.py file. My guess is that that I am doing something wrong syntaxwise ... | "too many values to unpack error" when trying to create a batch in pyglet | I have been trying to get batches to work in pyglet, but I am completely confused by the error message "too many values to unpack" coming from the pyglet/graphics/__init__.py file. My guess is that that I am doing something wrong syntaxwise when adding the geometry to the batch.
I cut down my code to the essential par... | [
"Your problem is in this line:\nbatch.add(12, GL_TRIANGLES, TextureBindGroup(texture), (('t2f', (0, 0)), ('v3f', (64, 64, 0)), ('t2f', (1, 1)), ('v3f', (-64, -64, 205)), ('t2f', (0, 1)), ('v3f', (-64, 64, 205)), ('t2f', (1, 1)), ('v3f', (64, -64, 205)), ('t2f', (1, 0)), ('v3f', (64, 64, 0)), ('t2f', (0, 1)), ('v3f'... | [
1,
0,
0,
0
] | [] | [] | [
"opengl",
"pyglet",
"python"
] | stackoverflow_0004494705_opengl_pyglet_python.txt |
Q:
input time in web2py
I want to take input time to complete a task in format no. of days,hours in web2py. Is there any defined field,type for this in SQLField.
time module in python allows only max 24 hours time.
A:
Sorry Field(...'time') only allows 24 hours and there is no specific type for timeinterval. Yet yo... | input time in web2py | I want to take input time to complete a task in format no. of days,hours in web2py. Is there any defined field,type for this in SQLField.
time module in python allows only max 24 hours time.
| [
"Sorry Field(...'time') only allows 24 hours and there is no specific type for timeinterval. Yet you can make define one using:\n timeinterval = SQLCustomType(....)\n\nand use it as\n Field('name',type=timeinterval, widget=....)\n\nYou can also make your own widget to handle it.\nPlease ask on the web2py mailing li... | [
1
] | [] | [] | [
"database",
"python",
"time",
"web2py"
] | stackoverflow_0004495116_database_python_time_web2py.txt |
Q:
Foward declaration of classes in Python
The following program can run successfully:
class Simple(object):
def __init__(self, name):
self.name = name
def __add__(self, other):
c = Composite()
c._members.append(self)
c._members.append(other)
return c
def __repr__(self):
... | Foward declaration of classes in Python | The following program can run successfully:
class Simple(object):
def __init__(self, name):
self.name = name
def __add__(self, other):
c = Composite()
c._members.append(self)
c._members.append(other)
return c
def __repr__(self):
return "Simple('%s')" % self.name
class ... | [
"Since none of the references are needed until the methods are called, circular imports can work here. The trick is to use fully-qualified references.\nimport composite\n\nclass Simple(object):\n ...\n def __add__(self, other):\n c = composite.Composite()\n c._members.append(self)\n c._members.append(ot... | [
5,
2
] | [] | [] | [
"class_design",
"forward_declaration",
"method_resolution_order",
"python"
] | stackoverflow_0004495469_class_design_forward_declaration_method_resolution_order_python.txt |
Q:
DSA verification calculation
Am I missing something? from FIPS180-2, on page 25, it gives the values of u1, u2, g^u1 mod p, y^u2 mod p and v. i have calculated all the values except v. yet, when i do the math, my calculations refuse to be v = 0x8bac1ab66410435cb7181f95b16ab97c92b341c0. instead, i get v = 0xc5a5469... | DSA verification calculation | Am I missing something? from FIPS180-2, on page 25, it gives the values of u1, u2, g^u1 mod p, y^u2 mod p and v. i have calculated all the values except v. yet, when i do the math, my calculations refuse to be v = 0x8bac1ab66410435cb7181f95b16ab97c92b341c0. instead, i get v = 0xc5a54698ae8e5b94661134260594ff4e3f488e26,... | [
"You're skipping one mod p calculation. You should compute: \n(((pow(g, u1, p) * pow(y, u2, p))) % p ) % q\n"
] | [
5
] | [] | [] | [
"cryptography",
"dsa",
"math",
"python"
] | stackoverflow_0004493387_cryptography_dsa_math_python.txt |
Q:
Why is this except being called? - Python
I have a method that checks a JSON payload for JSON decoding errors, and KeyErrors. For some reason, the except statement with the KeyError is getting called, but then shows there was in fact, no KeyError as the object is None. Here is the code:
try:
test_data ... | Why is this except being called? - Python | I have a method that checks a JSON payload for JSON decoding errors, and KeyErrors. For some reason, the except statement with the KeyError is getting called, but then shows there was in fact, no KeyError as the object is None. Here is the code:
try:
test_data = simplejson.loads(self.raw_data) # Loads the d... | [
"The KeyError is probably raised by simplejson.loads and the offending key may really be None. Not enough context to say more. If you give the traceback as asked, it will help greatly.\n",
"Looking through the traceback should tell you what module the exception was raised in. You might also want to consider using... | [
1,
0
] | [] | [] | [
"except",
"exception",
"json",
"python"
] | stackoverflow_0004495446_except_exception_json_python.txt |
Q:
Python filter list to remove certain links from html source code
I have html source code which I want to filter out one or more links and keep the others.
I have set up my filter with "*" as the wildcard:
<a*>Link1</a>‚ <a*>Link2</a>‚ or <a*>Link3</a>
<a*>A bad link*</a>
some text* <a*>update*</a>
other text rig... | Python filter list to remove certain links from html source code | I have html source code which I want to filter out one or more links and keep the others.
I have set up my filter with "*" as the wildcard:
<a*>Link1</a>‚ <a*>Link2</a>‚ or <a*>Link3</a>
<a*>A bad link*</a>
some text* <a*>update*</a>
other text right before link <a*>click here</a>
I would like to filter out every in... | [
"To remove <a> tags and keep only the text not contained within those tags:\n>>> from BeautifulSoup import BeautifulSoup as bs\n>>> markup = \"\"\"<a*>Link1</a> <a*>Link2</a> or <a*>Link3</a>\n... <a*>A bad link*</a>\n... some text* <a*>update*</a>\n... other text right before link <a*>click here</a>\"\"\"\n>>> sou... | [
3,
0
] | [] | [] | [
"beautifulsoup",
"python",
"regex"
] | stackoverflow_0004495090_beautifulsoup_python_regex.txt |
Q:
Measuring bytecode usage
I'm looking for an absolute method to benchmark/measure computations performed in python. In Java, it's possible to calculate the bytecode usage for a given set of instructions. Is there a similar approach I could take in Python?
I'm open to alternative suggestions for measuring computatio... | Measuring bytecode usage | I'm looking for an absolute method to benchmark/measure computations performed in python. In Java, it's possible to calculate the bytecode usage for a given set of instructions. Is there a similar approach I could take in Python?
I'm open to alternative suggestions for measuring computation performed so long as the var... | [
"Check out the dis module.\n>>> import dis\n>>> def x(a,b):\n... return a+b\n... \n>>> dis.dis(x)\n 2 0 LOAD_FAST 0 (a)\n 3 LOAD_FAST 1 (b)\n 6 BINARY_ADD \n 7 RETURN_VALUE \n\n"
] | [
1
] | [] | [] | [
"bytecode",
"compiler_construction",
"interpreter",
"python"
] | stackoverflow_0004495593_bytecode_compiler_construction_interpreter_python.txt |
Q:
python command line programming examples, recipes
There has been a need for python command line utilities at work lately and I have no experience in writing cli's. Regardless, I must still pop them out.
My biggest hurdle is the structure of these programs. Also, the method in getting and verifying input from the ... | python command line programming examples, recipes | There has been a need for python command line utilities at work lately and I have no experience in writing cli's. Regardless, I must still pop them out.
My biggest hurdle is the structure of these programs. Also, the method in getting and verifying input from the user. I have been ending up with very looong while loop... | [
"I like baker. You use it like so:\n% cat my.py\nimport baker\n\n\n@baker.command\ndef cmd(start, end):\n print '%s %s' % (start, end)\n\n\nif __name__ == '__main__':\n baker.run()\n\n% python my.py cmd 2010-12-01 2010-12-31\n2010-12-01 2010-12-31\n\n",
"Random hints:\n\nthe optionparser module is good for ... | [
5,
4,
0,
0
] | [] | [] | [
"command_line_interface",
"python"
] | stackoverflow_0004494941_command_line_interface_python.txt |
Q:
Get python script to run on boot up in mac
How would I get a python script to run everytime the computer boots?
A:
How to run a shell script on startup (OSX)
And in that script just call your program
python path/to/yourScript.py
EDIT: Since 2010 the above link has gone sour. But also since 2010 have some answer... | Get python script to run on boot up in mac | How would I get a python script to run everytime the computer boots?
| [
"How to run a shell script on startup (OSX)\nAnd in that script just call your program\npython path/to/yourScript.py\n\nEDIT: Since 2010 the above link has gone sour. But also since 2010 have some answers popped up the describe similar methods, eg.\nRunning script upon login mac\nHow to get shell scripts to run on ... | [
3,
1
] | [] | [] | [
"boot",
"macos",
"python"
] | stackoverflow_0004495949_boot_macos_python.txt |
Q:
Nonlinear e^(-x) regression using scipy, python, numpy
The code below is giving me a flat line for the line of best fit rather than a nice curve along the model of e^(-x) that would fit the data. Can anyone show me how to fix the code below so that it fits my data?
import numpy as np
import matplotlib.pyplot as... | Nonlinear e^(-x) regression using scipy, python, numpy | The code below is giving me a flat line for the line of best fit rather than a nice curve along the model of e^(-x) that would fit the data. Can anyone show me how to fix the code below so that it fits my data?
import numpy as np
import matplotlib.pyplot as plt
import scipy.optimize
def _eNegX_(p,x):
x0,y0,c,k=... | [
"It looks like it's a problem with your initial guesses; something like (1, 1, 1, 1) works fine:\nYou have\np_guess=(np.median(x),np.min(y),np.max(y),.01)\n\nfor the function\ndef _eNegX_(p,x):\n x0,y0,c,k=p \n y = (c * np.exp(-k*(x-x0))) + y0\n return y\n\nSo that's test_data_maxe^( -.01(x - test_data_me... | [
11
] | [] | [] | [
"numpy",
"python",
"scientific_computing",
"scipy",
"statistics"
] | stackoverflow_0004495127_numpy_python_scientific_computing_scipy_statistics.txt |
Q:
How do I parse a website in python once I know its url?
If I know the url of a wiki site , How do I use python to parse the contents of it ?
A:
This is a very broad question, but the first things to reach for are urllib, which will handle the downloading part, and Beautiful Soup, which will do the parsing. Glui... | How do I parse a website in python once I know its url? | If I know the url of a wiki site , How do I use python to parse the contents of it ?
| [
"This is a very broad question, but the first things to reach for are urllib, which will handle the downloading part, and Beautiful Soup, which will do the parsing. Gluing them together and writing the code to actually extract information from the parse tree is up to you.\n",
"You might try Scrapy as well.\n"
] | [
10,
2
] | [] | [] | [
"python"
] | stackoverflow_0004496717_python.txt |
Q:
Python threads all executing on a single core
I have a Python program that spawns many threads, runs 4 at a time, and each performs an expensive operation. Pseudocode:
for object in list:
t = Thread(target=process, args=(object))
# if fewer than 4 threads are currently running, t.start(). Otherwise, add t ... | Python threads all executing on a single core | I have a Python program that spawns many threads, runs 4 at a time, and each performs an expensive operation. Pseudocode:
for object in list:
t = Thread(target=process, args=(object))
# if fewer than 4 threads are currently running, t.start(). Otherwise, add t to queue
But when the program is run, Activity Mon... | [
"Note that in many cases (and virtually all cases where your \"expensive operation\" is a calculation implemented in Python), multiple threads will not actually run concurrently due to Python's Global Interpreter Lock (GIL).\n\nThe GIL is an interpreter-level lock.\n This lock prevents execution of\n multiple thr... | [
84,
9,
6
] | [] | [] | [
"multithreading",
"performance",
"python"
] | stackoverflow_0004496680_multithreading_performance_python.txt |
Q:
Maintaining environment state between subprocess.Popen commands?
I'm writing a deployment engine for our system, where each project specifies his custom deployment instructions.
The nodes are running on EC2.
One of the projects depends on a from source version of a 3rd party application.
Specifically:
cd /tmp
wge... | Maintaining environment state between subprocess.Popen commands? | I'm writing a deployment engine for our system, where each project specifies his custom deployment instructions.
The nodes are running on EC2.
One of the projects depends on a from source version of a 3rd party application.
Specifically:
cd /tmp
wget s3://.../tools/x264_20_12_2010.zip
unzip x264_20_12_2010.zip
cd x264... | [
"\nThink of os.chdir(\"DIRECTORY\") instead of Popen(\"cd DIRECTORY\")\nMaybe it's best here not to execute a new shell for each command: Just write one multi-line shell skript\n\ndeploy_commands = \"\"\"apt-get foo\napt-get bar\ncd baz ; boo bat\"\"\"\nend execute via Popen(deploy_commands, shell=True).\nBut pleas... | [
0,
0
] | [] | [] | [
"amazon_ec2",
"command_line",
"python",
"shellexecute",
"subprocess"
] | stackoverflow_0004492727_amazon_ec2_command_line_python_shellexecute_subprocess.txt |
Q:
Multiple port scans using external tool, subprocess.Popen and threads
I am using a port scanner to scan my subnet. The port scanner unfortunately can scan one port of only one host at a time. Also the scanner has a 1 sec timeout for unreachable hosts. The scanner(being an outside program) has to be run from subpro... | Multiple port scans using external tool, subprocess.Popen and threads | I am using a port scanner to scan my subnet. The port scanner unfortunately can scan one port of only one host at a time. Also the scanner has a 1 sec timeout for unreachable hosts. The scanner(being an outside program) has to be run from subprocess.Popen() and to speed it up - so that I may send multiple probes while ... | [
"Why don't you try it?\n(Answer: No they will have their own pipe)\n",
"Use the shell\n for h in host1 host2 host3\n do\n scan $h >$h.scan &\n done\n cat *.scan >all.scan\n\nThis will scan the entire list of hosts all at the same time, each in a separate process. No threads.\nEach scan will produce a .scan f... | [
1,
1,
0
] | [] | [] | [
"python",
"python_2.4",
"subprocess"
] | stackoverflow_0004460109_python_python_2.4_subprocess.txt |
Q:
With regards to urllib AttributeError: 'module' object has no attribute 'urlopen'
import re
import string
import shutil
import os
import os.path
import time
import datetime
import math
import urllib
from array import array
import random
filehandle = urllib.urlopen('http://www.google.com/') #open webpage
s = fileh... | With regards to urllib AttributeError: 'module' object has no attribute 'urlopen' | import re
import string
import shutil
import os
import os.path
import time
import datetime
import math
import urllib
from array import array
import random
filehandle = urllib.urlopen('http://www.google.com/') #open webpage
s = filehandle.read() #read
print s #display
#what i plan to do with it once i get the first p... | [
"it appears that the urlopen method is available in the urllib.request module and not in the urllib module as you're expecting. \nrule of thumb - if you're getting an AttributeError, that field/operation is not present in the particular module. \nEDIT - Thanks to AndiDog for pointing out - this is a solution val... | [
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0004496980_python.txt |
Q:
How Google App Engine limit Python?
Does anybody know, how GAE limit Python interpreter? For example, how they block IO operations, or URL operations.
Shared hosting also do it in some way?
A:
From Google's site:
An application can only access other
computers on the Internet through the
provided URL fetch and ... | How Google App Engine limit Python? | Does anybody know, how GAE limit Python interpreter? For example, how they block IO operations, or URL operations.
Shared hosting also do it in some way?
| [
"From Google's site:\n\nAn application can only access other\ncomputers on the Internet through the\nprovided URL fetch and email\nservices. Other computers can only\nconnect to the application by making\nHTTP (or HTTPS) requests on the\nstandard ports.\nAn application cannot write to the\nfile system. An app can r... | [
1,
1,
0,
0
] | [] | [] | [
"hosting",
"python",
"shared_hosting"
] | stackoverflow_0004496914_hosting_python_shared_hosting.txt |
Q:
better way of handling nested list
my_list = [ [1,2,3,4,5,6], [1,3,4],[34,56,56,56]]
for item in my_list:
var1,var2,var3,var4,var5,var6 = None
if len(item) ==1:
var1 = item[0]
if len(item) == 2:
var1 = item[0]
var2 = item[1]
if len(item) == 3:
var1 = item[... | better way of handling nested list | my_list = [ [1,2,3,4,5,6], [1,3,4],[34,56,56,56]]
for item in my_list:
var1,var2,var3,var4,var5,var6 = None
if len(item) ==1:
var1 = item[0]
if len(item) == 2:
var1 = item[0]
var2 = item[1]
if len(item) == 3:
var1 = item[0]
var2 = item[1]
var3... | [
"See Calls and Function definitions in the Python documentation, specifically:\n\nIf the syntax *expression appears in\n the function call, expression must\n evaluate to a sequence. Elements from\n this sequence are treated as if they\n were additional positional\n arguments....\n\nIf the syntax **expression a... | [
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0004496712_python.txt |
Q:
Error while trying to parse a website url using python . how to debug it?
#!/usr/bin/python
import json
import urllib
from BeautifulSoup import BeautifulSoup
from BeautifulSoup import BeautifulStoneSoup
import BeautifulSoup
def showsome(searchfor):
query = urllib.urlencode({'q': searchfor})
url = 'http://aj... | Error while trying to parse a website url using python . how to debug it? | #!/usr/bin/python
import json
import urllib
from BeautifulSoup import BeautifulSoup
from BeautifulSoup import BeautifulStoneSoup
import BeautifulSoup
def showsome(searchfor):
query = urllib.urlencode({'q': searchfor})
url = 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&%s' % query
search_response... | [
"\nWhat is the wrong in this code ?\n\nYour indentation is all wonky in the for loop, and this line:\nimport BeautifulSoup \n\nshould be deleted, as it masks this earlier import:\nfrom BeautifulSoup import BeautifulSoup\n\n",
"It appears you're trying to access the Google ajax API in Python. You might consider ... | [
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0004496882_python.txt |
Q:
Python OpenWRT crontab
Im trying to run python script on OpenWrt box:
#!/root/system/usr/bin/python
import subprocess
p = subprocess.Popen([r"snmpget","-v","1","-c","public","-Oqv","-Ln", "192.168.1.1","1.3.6.1.2.1.2.2.1.10.7"], stdout=subprocess.PIPE).communicate()[0]
data = [r"curl","-d","iface_id=1&content="+ ... | Python OpenWRT crontab | Im trying to run python script on OpenWrt box:
#!/root/system/usr/bin/python
import subprocess
p = subprocess.Popen([r"snmpget","-v","1","-c","public","-Oqv","-Ln", "192.168.1.1","1.3.6.1.2.1.2.2.1.10.7"], stdout=subprocess.PIPE).communicate()[0]
data = [r"curl","-d","iface_id=1&content="+ str(p).rstrip() ,"http://192... | [
"Could it be that snmpget or curl are not in the path of cron?\n",
"I replace curl with python urllib request and now its working! :) \nurl = 'http://192.168.1.5:8080/stat/add_istat/\"' # write ur URL here\n\nvalues = {'iface_id' : '1', #write ur specific key/value pair\n 'content' : str(p).rstrip(),\n ... | [
1,
0
] | [] | [] | [
"cron",
"openwrt",
"python",
"snmp"
] | stackoverflow_0004494716_cron_openwrt_python_snmp.txt |
Q:
import webkit fails with an ImportError
When I import webkit on Ubuntu 10.04 I get the following error:
Traceback (most recent call last):
File "test.py", line 1, in <module>
import webkit
File "/usr/lib/pymodules/python2.6/webkit/__init__.py", line 19, in <module>
import webkit
ImportError: /usr/lib/p... | import webkit fails with an ImportError | When I import webkit on Ubuntu 10.04 I get the following error:
Traceback (most recent call last):
File "test.py", line 1, in <module>
import webkit
File "/usr/lib/pymodules/python2.6/webkit/__init__.py", line 19, in <module>
import webkit
ImportError: /usr/lib/pymodules/python2.6/webkit/webkit.so: undefine... | [
"Your /usr/lib/pymodules/python2.6/webkit/webkit.so is probably linked against an older version of libwebkit. In that case you'll need to install the correct versions of both software packages.\n"
] | [
1
] | [] | [] | [
"python",
"webkit"
] | stackoverflow_0004497587_python_webkit.txt |
Q:
Algorithm to sum/stack values from a time series graph where data points don't match on time
I have a graphing/analysis problem i can't quite get my head around. I can do a brute force, but its too slow, maybe someone has a better idea, or knows or a speedy library for python?
I have 2+ time series data sets (x,y)... | Algorithm to sum/stack values from a time series graph where data points don't match on time | I have a graphing/analysis problem i can't quite get my head around. I can do a brute force, but its too slow, maybe someone has a better idea, or knows or a speedy library for python?
I have 2+ time series data sets (x,y) that i want to aggregate (and subsequently plot). The issue is that the x values across the serie... | [
"Something like this:\ndef join_series(s1, s2):\n S1 = iter(s1)\n S2 = iter(s2)\n value1 = 0\n value2 = 0\n time1, next1 = next(S1)\n time2, next2 = next(S2)\n end1 = False\n end2 = False\n\n while True: \n time = min(time1, time2)\n if time == time1:\n value1 ... | [
1,
1,
1
] | [] | [] | [
"aggregate_functions",
"analysis",
"data_analysis",
"graph",
"python"
] | stackoverflow_0004497038_aggregate_functions_analysis_data_analysis_graph_python.txt |
Q:
Pyparsing: How can I parse data and then edit a specific value in a .txt file?
my data is located in a .txt file (no, I can't change it to a different format) and it looks like this:
varaiablename = value
something = thisvalue
youget = the_idea
Here is my code so far (taken from the examples in Pyparsing):
... | Pyparsing: How can I parse data and then edit a specific value in a .txt file? | my data is located in a .txt file (no, I can't change it to a different format) and it looks like this:
varaiablename = value
something = thisvalue
youget = the_idea
Here is my code so far (taken from the examples in Pyparsing):
from pyparsing import Word, alphas, alphanums, Literal, restOfLine, OneOrMore, \
emp... | [
"Even though you have already selected another answer, let me answer your original question, which was how to do this using pyparsing.\nIf you are trying to make selective changes in some body of text, then transformString is a better choice than scanString (although scanString or searchString are fine for validati... | [
6,
3,
1,
1
] | [] | [] | [
"pyparsing",
"python"
] | stackoverflow_0004494233_pyparsing_python.txt |
Q:
Has anybody been able to install PyWeka?
I need to install in python 2.6 or 2.7 for windows the library PyWeka0.3dev, It says it requires setuptools, which I installed but then they told me it was a deprecated instalation library and I installed distribute, then I downloaded the PyWeka compressed package and each ... | Has anybody been able to install PyWeka? | I need to install in python 2.6 or 2.7 for windows the library PyWeka0.3dev, It says it requires setuptools, which I installed but then they told me it was a deprecated instalation library and I installed distribute, then I downloaded the PyWeka compressed package and each time I try to install it neither with setup.py... | [
"As mentioned to you via Aardvark (yes, I am omnipresent), the module in question is broken. You can't easy_install it. It's a bug in PyWeka.\nYou can download the file from PyPI, http://pypi.python.org/pypi/PyWeka/0.3dev, and unpack it.\nIn the file setup.py, remove the following two lines:\nfrom ez_setup import u... | [
1,
0
] | [] | [] | [
"distribute",
"python",
"setuptools",
"windows"
] | stackoverflow_0004493871_distribute_python_setuptools_windows.txt |
Q:
Why does this code return a list index error?
Basically it's supposed to take a set of coordinates and return a list of coordinates of it's neighbors. However, when it hits here:
if result[i][0] < 0 or result[i][0] >= board.dimensions:
result.pop(i)
when i is 2, it gives me an out of index error. I can manage... | Why does this code return a list index error? | Basically it's supposed to take a set of coordinates and return a list of coordinates of it's neighbors. However, when it hits here:
if result[i][0] < 0 or result[i][0] >= board.dimensions:
result.pop(i)
when i is 2, it gives me an out of index error. I can manage to have it print result[2][0] but at the if statem... | [
"You get the indexes to iterate over from the list, and then you proceed to remove elements from the list. Eventually you're going to hit an index that no longer exists. Use a list comprehension to filter instead.\nresult = [entry for entry in result if entry[0] >= 0 and\n entry[0] < board.dimensions and entry[1] ... | [
4,
2,
2,
1,
1,
0,
0
] | [] | [] | [
"indexing",
"python"
] | stackoverflow_0004496424_indexing_python.txt |
Q:
Transparent 3D bar graphs
I would like to generate 3D bar graphs with transparent surfaces so that I can see what is going on behind tall bars.
The mplot3d API docs say that keywords are allowed for the bar3d function. I pass all the required parameters but can only output graphs with solid surfaces. These and th... | Transparent 3D bar graphs | I would like to generate 3D bar graphs with transparent surfaces so that I can see what is going on behind tall bars.
The mplot3d API docs say that keywords are allowed for the bar3d function. I pass all the required parameters but can only output graphs with solid surfaces. These and these bar graphs clearly show sem... | [
"My best guess is that you might find bar3d() Order of Coloring and Matlibplot Colors of some use.\nThat is to say, my understanding is that transparency should be handled in the alpha value of any given color used (as an RGBA argument used in the manner described in the first link).\nHaving said that, I can't expl... | [
0
] | [] | [] | [
"bar_chart",
"matplotlib",
"python"
] | stackoverflow_0004498143_bar_chart_matplotlib_python.txt |
Q:
Developing a RIA with Django - what technology stack?
I need to develop a web application with the following requirements:
Desktop like UI on the client side
Application deployment
Scalability (i.e. distributing the service on multiple servers)
What I thought of so far (as I love Python but haven't done much web... | Developing a RIA with Django - what technology stack? | I need to develop a web application with the following requirements:
Desktop like UI on the client side
Application deployment
Scalability (i.e. distributing the service on multiple servers)
What I thought of so far (as I love Python but haven't done much web development yet):
Django
Fabric (think I've read somewher... | [
"For RIA you need to use some client technology in your templates.\nSee at Dojo or ExtJs.\nExtJs docs have example of Web Desktop app, but this library is not free for commercial project. I like more Dojo, and it is free.\n",
"\nRich Internet Application: Javascript to do stuff asynchronously (AJAX). If you want ... | [
3,
3,
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0004498125_django_python.txt |
Q:
Building PortAudio and PyAudio on Mac running Snow Leopard (arch issues)
I'd like to tell you what I've tried and then I'd really welcome any comments you can provide on how I can get PortAudio and PyAudio setup correctly!
I've tried installing the stable and svn releases of PortAudio from their website for my Co... | Building PortAudio and PyAudio on Mac running Snow Leopard (arch issues) | I'd like to tell you what I've tried and then I'd really welcome any comments you can provide on how I can get PortAudio and PyAudio setup correctly!
I've tried installing the stable and svn releases of PortAudio from their website for my Core 2 Duo MacBook Pro running Snow Leopard. The stable release has a sizeof err... | [
"Thanks to PyAudio's author's speedy response to my inquiries, I now have a nicely installed copy. His directions are posted below for anyone who has similar issues.\n\nHi Michael,\nTry this:\n1) Make sure your directory layout is\n like:\n./foo/pyaudio/portaudio-v19/ ./foo/pyaudio/\n2) Build portaudio-v19 from so... | [
5,
1
] | [] | [] | [
"portaudio",
"pyaudio",
"python"
] | stackoverflow_0002893193_portaudio_pyaudio_python.txt |
Q:
Silent printing of a PDF in Python
I'm trying to print a PDF with Python, without opening the PDF viewer application (Adobe, Foxit etc.). I need also to know when printing has finished (to delete the file).
Here I found this implementation:
import win32ui, dde, os.path, time
from win32api import FindExecutable
fro... | Silent printing of a PDF in Python | I'm trying to print a PDF with Python, without opening the PDF viewer application (Adobe, Foxit etc.). I need also to know when printing has finished (to delete the file).
Here I found this implementation:
import win32ui, dde, os.path, time
from win32api import FindExecutable
from os import spawnl, P_NOWAIT
...
pd = "C... | [
"I suggest you install GSView and GSPrint and shell out to gsprint.exe to print the pdf.\np = subprocess.Popen([r\"p:\\ath\\to\\gsprint.exe\", \"test.pdf\"], \n stdout=subprocess.PIPE, stderr=subprocess.PIPE)\nstdout, stderr = p.communicate()\nprint stdout\nprint stderr\n\nI have used this in a ... | [
21
] | [] | [] | [
"pdf",
"printing",
"python",
"silent",
"windows"
] | stackoverflow_0004498099_pdf_printing_python_silent_windows.txt |
Q:
How to get binary post data in Django !nicely?
forgive me if this is a bit of a newbie question, I started to learn Django yesterday, and I'm trying not to get into bad habits, i.e. I am trying to do things "the django way" from the start.
I have a view that recieves binary data as a http post field. Now Django of... | How to get binary post data in Django !nicely? | forgive me if this is a bit of a newbie question, I started to learn Django yesterday, and I'm trying not to get into bad habits, i.e. I am trying to do things "the django way" from the start.
I have a view that recieves binary data as a http post field. Now Django of course autoconverts my binary data to a unicode str... | [
"Some might say that storing binary data in a standard form field is a bad habit in some way :)\nYou could use standard library methods of Python to convert your string back to a binary representation.\nTake a look at binascii — Convert between binary and ASCI\n\nPosting before edit:\nWhat about this piece of code ... | [
4
] | [] | [] | [
"django",
"django_views",
"python"
] | stackoverflow_0004499129_django_django_views_python.txt |
Q:
Python/Django excel to html
Okay, so what I want to do is upload an excel sheet and display it on my website, in html. What are my options here ? I've found this xlrd module that allows you to read the data from spreadsheets, but I don't really need that right now.
A:
Why don't you need xlrd? It sounds like exac... | Python/Django excel to html | Okay, so what I want to do is upload an excel sheet and display it on my website, in html. What are my options here ? I've found this xlrd module that allows you to read the data from spreadsheets, but I don't really need that right now.
| [
"Why don't you need xlrd? It sounds like exactly what you need. \nCreate a Django model with a FileField that holds the spreadsheet. Then your view uses xlrd to loop over the rows and columns and put them into an HTML table. Job done.\nPossible complications: multiple sheets in one Excel file; formulas; styles.\n",... | [
4,
0
] | [] | [] | [
"django",
"excel",
"html",
"python"
] | stackoverflow_0004498678_django_excel_html_python.txt |
Q:
Django Templates: Display a date only if it's in the future
How do I compare dates in a Django template? I thought of several possible avenues:
Send today's date in the context to be compared at the template
Create my own template tag
Have some logic in the view to only pass the date if it's in the future
Althou... | Django Templates: Display a date only if it's in the future | How do I compare dates in a Django template? I thought of several possible avenues:
Send today's date in the context to be compared at the template
Create my own template tag
Have some logic in the view to only pass the date if it's in the future
Although the last option seems easier, I rather leave the display logic... | [
"I'd go with a template filter:\nfrom datetime import date\n...\n@register.filter\ndef future_dates_only(the_date):\n if the_date > date.today():\n return the_date\n else:\n return None\n\nThen in your view do something like:\n{{specialdate|future_dates_only|date:\"d M Y\"}}\n\n",
"IMO it is clean... | [
6,
2
] | [] | [] | [
"datetime",
"django",
"django_templates",
"python"
] | stackoverflow_0004493761_datetime_django_django_templates_python.txt |
Q:
TypeError: Python thinks that I passed a function 2 arguments but I only passed it 1
I work on something in Seattle Repy which is a restricted subset of Python. Anyway, I wanted to implement my own Queue that derives from a list:
class Queue(list):
job_count = 0
def __init__(self):
list.__init... | TypeError: Python thinks that I passed a function 2 arguments but I only passed it 1 | I work on something in Seattle Repy which is a restricted subset of Python. Anyway, I wanted to implement my own Queue that derives from a list:
class Queue(list):
job_count = 0
def __init__(self):
list.__init__(self)
def appendleft(item):
item.creation_time = getruntime()
item... | [
"You must enter the self reference in each function definition:\ndef appendleft(self, item):\n\n",
"Python automatically passes SELF (ie the current object) as the first argument, so you'd need to change the function definition for appendleft to: \ndef appendleft(self, item):\n\nThis is also true for other funct... | [
7,
6,
3
] | [] | [] | [
"arguments",
"exception",
"parameters",
"python"
] | stackoverflow_0004499404_arguments_exception_parameters_python.txt |
Q:
Google App Engine - Production Only - Module Import Error
I am getting this error when running the app in production. It works fine in my local environment. But, after I upload to server, it throws this exception.
The test_handler module exists in test package (and it works fine in local). I believe that the entir... | Google App Engine - Production Only - Module Import Error | I am getting this error when running the app in production. It works fine in my local environment. But, after I upload to server, it throws this exception.
The test_handler module exists in test package (and it works fine in local). I believe that the entire folder structure will be uploaded to the server, when we uplo... | [
"You can now download the source if you were the developer who uploaded it.\nThis should give you a concrete understanding of what was uploaded.\nAppEngine Docs: Downloading Source Code\n",
"The issue was with the package name. I named the package as 'test', which might have stepped on the shoes of some other pac... | [
0,
0
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0004458281_google_app_engine_python.txt |
Q:
lxml objectify does not call constructors for custom element classes
lxml.objectify does not seem to call the constructors for my custom element classes:
from lxml import objectify, etree
class CustomLookup(etree.CustomElementClassLookup):
def lookup(self, node_type, document, namespace, name):
lookup... | lxml objectify does not call constructors for custom element classes | lxml.objectify does not seem to call the constructors for my custom element classes:
from lxml import objectify, etree
class CustomLookup(etree.CustomElementClassLookup):
def lookup(self, node_type, document, namespace, name):
lookupmap = { 'custom' : CustomElement }
try:
return lookupm... | [
"From the lxml docs:\n\nElement initialization\nThere is one thing to know up front.\n Element classes must not have an\n __init___ or __new__ method. There should not be any internal state\n either, except for the data stored in\n the underlying XML tree. Element\n instances are created and garbage\n collect... | [
2
] | [] | [] | [
"constructor",
"lxml",
"objectify",
"python"
] | stackoverflow_0004499496_constructor_lxml_objectify_python.txt |
Q:
Is there anything else to do Audio in 92khz to 192khz?
I spend lot of time researching/finding a best developer friendly framework or libraries for cross platform to deal with solid/accurate/lipsync sort of audio solution. Still could not find one which can be used for cross platform.
I tried GStreamer (was the be... | Is there anything else to do Audio in 92khz to 192khz? | I spend lot of time researching/finding a best developer friendly framework or libraries for cross platform to deal with solid/accurate/lipsync sort of audio solution. Still could not find one which can be used for cross platform.
I tried GStreamer (was the best one) but it is best for linux as it covers CELT/Vorbis/Sp... | [
"It's C++ and i don't know if it fully fits your bill, but RtAudio provides a nice and easy to use cross-platform wrapper for realtime audio output & input.\n",
"murgaLua comes with a binding to proteaAudio if you want to have something to be up and running quickly...\nIt's cross platform Windows-Mac-Linux ;)\n"
... | [
1,
1
] | [] | [] | [
"ada",
"c",
"java",
"lua",
"python"
] | stackoverflow_0004498849_ada_c_java_lua_python.txt |
Q:
XPath: Get node below another node
I'm new to XPath, and I need to get the table node after the following:
<p><b>Some unique string</b></p>
<center><table>
<tr>
<th>.....
I have been trying things such as:
"following-sibling::.//p//b[.='Some unique string']"
".//p//b[.='Some unique string']/following:://table"
... | XPath: Get node below another node | I'm new to XPath, and I need to get the table node after the following:
<p><b>Some unique string</b></p>
<center><table>
<tr>
<th>.....
I have been trying things such as:
"following-sibling::.//p//b[.='Some unique string']"
".//p//b[.='Some unique string']/following:://table"
So far I've managed to get rather stuc... | [
"This XPath 1.0 expression:\n//b[.='Some unique string']/following::table[1] \n\nMeaning: the first following table element of any b element in the whole document having 'Some unique string' as string value\n"
] | [
3
] | [] | [] | [
"lxml",
"python",
"xpath"
] | stackoverflow_0004499542_lxml_python_xpath.txt |
Q:
mmapping in Python C modules - any pitfalls to be aware of?
I'm writing a Python module in C and I intend to mmap largeish blocks of memory (perhaps 500 MB). Is there anything about working in the same process space as the Python interpreter that I should be careful of?
A:
No, you're fine.
On 32-bit systems, you... | mmapping in Python C modules - any pitfalls to be aware of? | I'm writing a Python module in C and I intend to mmap largeish blocks of memory (perhaps 500 MB). Is there anything about working in the same process space as the Python interpreter that I should be careful of?
| [
"No, you're fine.\nOn 32-bit systems, you could run out of virtual memory, or with virtual memory fragmentation not have a single chunk big enough to map as many huge files as you want. But that pitfall isn't particular to CPython.\n"
] | [
2
] | [] | [] | [
"c",
"cpython",
"memory_mapping",
"mmap",
"python"
] | stackoverflow_0004499483_c_cpython_memory_mapping_mmap_python.txt |
Q:
Testing a custom Django template filter
I have a custom template filter I created under project/app/templatetags.
I want to add some regression tests for some bugs I just found. How would I go about doing so?
A:
The easiest way to test a template filter is to test it as a regular function.
@register.filter deco... | Testing a custom Django template filter | I have a custom template filter I created under project/app/templatetags.
I want to add some regression tests for some bugs I just found. How would I go about doing so?
| [
"The easiest way to test a template filter is to test it as a regular function. \n@register.filter decorator doesn't harm the underlying function, you can import the filter and use just it like if it is not decorated. This approach is useful for testing filter logic. \nIf you want to write more integration-style te... | [
17,
16
] | [] | [] | [
"django",
"django_template_filters",
"python"
] | stackoverflow_0004496109_django_django_template_filters_python.txt |
Q:
Check if a file is available (not used by another process) in Python
I'm looking for some code to check if a file in the file system is available (not used by another process). How could I do it in Python? Thanks!
How I'll use it: cylically check if file is available and when it is (processes don't need it anymore... | Check if a file is available (not used by another process) in Python | I'm looking for some code to check if a file in the file system is available (not used by another process). How could I do it in Python? Thanks!
How I'll use it: cylically check if file is available and when it is (processes don't need it anymore) delete it.
| [
"while True:\n try:\n os.remove(yourfilename) # try to remove it directly\n except OSError as e:\n if e.errno == errno.ENOENT: # file doesn't exist\n break\n time.sleep(5)\n else:\n break\n\n",
"If the file other process has the file open and you delete it, it will ... | [
2,
0,
0
] | [] | [] | [
"file",
"python"
] | stackoverflow_0004498330_file_python.txt |
Q:
Print a PDF and delete the file when printing has finished
I have a Python application taht will be executed repeatedly. It saves a PDF as a file and then prints it. When printing ends it deletes the file.
My current solution (for the print and delete part) is this:
win32api.ShellExecute(0, "print", file_path, Non... | Print a PDF and delete the file when printing has finished | I have a Python application taht will be executed repeatedly. It saves a PDF as a file and then prints it. When printing ends it deletes the file.
My current solution (for the print and delete part) is this:
win32api.ShellExecute(0, "print", file_path, None, ".", 0)
time.sleep(10)
os.remove(self.options.dest_name)
t... | [
"At last I've found a good solution, thanks to this answer (and also @Lennart mentioned it on a comment):\ninstall Ghostscript\ninstall GSview (which includes gsprint.exe)\nwrite this code:\nfile_path = \"C:\\\\temp\\\\test.pdf\"\np = subprocess.Popen([\"C:\\\\Ghostgum\\\\gsview\\\\gsprint.exe\", \"-printer\", prin... | [
4,
2,
1,
0
] | [] | [] | [
"pdf",
"printing",
"python",
"windows"
] | stackoverflow_0004469629_pdf_printing_python_windows.txt |
Q:
how to display python list in django template
I am new to python and django. I want to know how can I dispaly python list in django template. The list is a list of days in weeks e.g day_list = ['sunday','monday','tuesday']
A:
Pass it to the template as a context and then simply iterate over it.
{% for day in day... | how to display python list in django template | I am new to python and django. I want to know how can I dispaly python list in django template. The list is a list of days in weeks e.g day_list = ['sunday','monday','tuesday']
| [
"Pass it to the template as a context and then simply iterate over it.\n{% for day in day_list %}\n {{ day }}\n{% endfor %}\n\nThis is the documentation for the for tag. I recommend you go through the Django tutorial, and in part 3 they go over passing stuff to your templates, including iterating over sequences... | [
15,
2
] | [] | [] | [
"django",
"python"
] | stackoverflow_0004500462_django_python.txt |
Q:
Directory Listing based on time
How to list the files in a directory based on timestamp?
os.listdir()
lists in arbitrary order.
Is there a build-in function to list based on timestamp? or by any order?
A:
You could call stat() on each of the files and sort by one of the timestamps, perhaps by using a key fun... | Directory Listing based on time | How to list the files in a directory based on timestamp?
os.listdir()
lists in arbitrary order.
Is there a build-in function to list based on timestamp? or by any order?
| [
"You could call stat() on each of the files and sort by one of the timestamps, perhaps by using a key function that returns a file's timestamp.\nimport os\n\ndef sorted_ls(path):\n mtime = lambda f: os.stat(os.path.join(path, f)).st_mtime\n return list(sorted(os.listdir(path), key=mtime))\n\nprint(sorted_ls('... | [
52,
0
] | [] | [] | [
"directory",
"python"
] | stackoverflow_0004500564_directory_python.txt |
Q:
Looking for a PHP and/or Python RAD
I am looking for RAD like environment for PHP and/or Python free or not does not matter.
It should have a visual environment where one can use a point and click interface so that it is possible to select objects with mouse and move them around.
I have looked at Delphi4PHP. The R... | Looking for a PHP and/or Python RAD | I am looking for RAD like environment for PHP and/or Python free or not does not matter.
It should have a visual environment where one can use a point and click interface so that it is possible to select objects with mouse and move them around.
I have looked at Delphi4PHP. The RAD part is fantastic, but I don't like th... | [
"Python and PHP both have a binding for GTK :\n\nPyGTK for Python;\nPHP GTK for PHP;\n\nYou can use Glade as a RADD to draw a GTK app.\nGTK runs on Windows, Linux and Mac OS.\nIf you are looking for something embedding everything, I can think of SPE for Python, but you really can run Glade as stand alone. \nSince a... | [
5,
2,
2,
2,
1,
1,
1,
1,
1,
0,
0,
0,
0
] | [
"The good news is that you won't miss it as soon as you familiarize yourself with a way of work when the responsibilities are shared.\nThink it over: really the programmer is the right person to assemble the user interface? I think not even in case of a desktop application.\nProgrammer should write good code, separ... | [
-5
] | [
"php",
"python",
"vcl4php"
] | stackoverflow_0000801090_php_python_vcl4php.txt |
Q:
os.fork() sem_wait: Permission denied
I am trying to compile python 2.5 on AIX 6.1, and the following occurs:
Python 2.6.5 (r265:79063, Jun 3 2010, 11:43:45)
[GCC 4.2.0] on aix6
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.fork()
0
sem_wait: Permission denied
741398
... | os.fork() sem_wait: Permission denied | I am trying to compile python 2.5 on AIX 6.1, and the following occurs:
Python 2.6.5 (r265:79063, Jun 3 2010, 11:43:45)
[GCC 4.2.0] on aix6
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.fork()
0
sem_wait: Permission denied
741398
I have found this bug, which sounds simila... | [
"The answer is my stupidity....\nFrom the above it is obvious... The version I am compiling is later in the command search path than another version that was already on the machine....\nRearranging the PATH shows that the HAVE_BROKEN_POSIX_SEMAPHORES flag fixes the problem ...\nDuhhh (Time to take a break)\n"
] | [
1
] | [] | [] | [
"aix",
"python"
] | stackoverflow_0004500987_aix_python.txt |
Q:
What can be used instead of ast module?
In my project I evaluate a json data to extract information. The code is as follows :
conn = httplib.HTTPConnection(host)
conn.request("GET", "/done_json.php")
r = conn.getresponse()
data = r.read()
tmp = ast.literal_eval(data)
list = []
for a in tmp.keys():
list.append(... | What can be used instead of ast module? | In my project I evaluate a json data to extract information. The code is as follows :
conn = httplib.HTTPConnection(host)
conn.request("GET", "/done_json.php")
r = conn.getresponse()
data = r.read()
tmp = ast.literal_eval(data)
list = []
for a in tmp.keys():
list.append(tmp[a])
How can I change this to be Python 2... | [
"Don't use ast.literal_eval, it's the wrong thing for the job anyway. Use simplejson.load(r) (or the standard json module instead of simplejson in newer versions).\nast.literal_eval is designed to evaluate Python literals. JSON is mostly the same, but not entirely (true/false/null instead of True/False/None).\n"
] | [
3
] | [] | [] | [
"abstract_syntax_tree",
"evaluate",
"json",
"python",
"python_2.4"
] | stackoverflow_0004500887_abstract_syntax_tree_evaluate_json_python_python_2.4.txt |
Q:
ChoiceField - choices based on boolean field
I am trying to have a choicefield that only displays the users with the ProjectManager boolean field checked as true. I am having some trouble figuring out the way to do it though.
A little background. When a user is created, there is a checkbox that they can select i... | ChoiceField - choices based on boolean field | I am trying to have a choicefield that only displays the users with the ProjectManager boolean field checked as true. I am having some trouble figuring out the way to do it though.
A little background. When a user is created, there is a checkbox that they can select if they are a project manager or not. If they chec... | [
"Does this help?\nclass TimeMaterialsForm(ModelForm):\n status = forms.ChoiceField(choices=STATUS_CHOICES)\n project_manager = forms.forms.ModelChoiceField(queryset=customUser.objects.filter(pm=True))\n ... \n\nhttp://docs.djangoproject.com/en/dev/ref/forms/fields/#modelchoicefield\n"
] | [
1
] | [] | [] | [
"django",
"django_forms",
"django_models",
"python"
] | stackoverflow_0004500921_django_django_forms_django_models_python.txt |
Q:
sequence/stack diagam for recursive function
for the code below:
def printList(L):
if L:
print L[0]
printList(L[1:])
I can have sequence diagram like this:
# NON PYTHON PSEUDO CODE
PrintList([1,2,3])
prints [1,2,3][0] => 1
runs printList([1,2,3][1:]) => printList([2,3])
=> we're now ... | sequence/stack diagam for recursive function | for the code below:
def printList(L):
if L:
print L[0]
printList(L[1:])
I can have sequence diagram like this:
# NON PYTHON PSEUDO CODE
PrintList([1,2,3])
prints [1,2,3][0] => 1
runs printList([1,2,3][1:]) => printList([2,3])
=> we're now in printList([2,3])
prints [2,3][0] => 2
... | [
"The print statement called after the recursive calls will all get hit \"on the way back up\". That is, each of your statements: \"it reaches the end of the function and returns None\" can be changed to \"it prints the current value of L[0], reaches the end of the function, and returns None\", which will be 3, 2, a... | [
1
] | [] | [] | [
"python",
"recursion",
"sequence_diagram",
"string"
] | stackoverflow_0004501309_python_recursion_sequence_diagram_string.txt |
Q:
Class as an input in a function
I have a file different_classes that contains three different classes. It is something like:
class first(object):
def __init__(x, y, z):
body of the first class
class second(first):
def __init__(x, y, z, a=2, b=3):
body of the second class
class third(object):
... | Class as an input in a function | I have a file different_classes that contains three different classes. It is something like:
class first(object):
def __init__(x, y, z):
body of the first class
class second(first):
def __init__(x, y, z, a=2, b=3):
body of the second class
class third(object):
def __init__(x, y, z):
body of th... | [
"Rather than passing the name of the class, why not just pass the class itself:\ndef create_blah(class_type = different_classes.first, x=x1, y=y1, z=z1):\n instance = class_type(x, y, z)\n\nRemember that a class is just an object like anything else in Python: you can assign them to variables and pass them around... | [
11,
0
] | [
"Sort of. Thare are fancier ways, but I suggest this one.\ndef create_blah(class_type = \"first\", x=x1, y=y1, z=z1):\n if class_type == \"first\":\n instance=different_classes.first(x,y,z)\n ...\n\n"
] | [
-2
] | [
"class",
"input",
"python"
] | stackoverflow_0004501403_class_input_python.txt |
Q:
Python: How can I merge these 2 overloaded constructors into 1 constructor
I have a class called Portfolio & right now I have 2 constructors (although as I just discovered u cant overload functions in python) so I have to merge these 2 constructors.
I am an experienced python programmer but this merging 2 construc... | Python: How can I merge these 2 overloaded constructors into 1 constructor | I have a class called Portfolio & right now I have 2 constructors (although as I just discovered u cant overload functions in python) so I have to merge these 2 constructors.
I am an experienced python programmer but this merging 2 constructors that are pretty contradictory is really doing my head in! :P
The first cons... | [
"Why does this all have to happen in constructors?\nYou could construct your object, then call separate methods on it for for importing the stock lists, or creating the database.\nWrapping that up in the Builder pattern may suit your existing design.\n",
"def __init__(self, _app_parent, _db_path, stock_list=None)... | [
2,
1,
1
] | [] | [] | [
"python",
"sql"
] | stackoverflow_0004495003_python_sql.txt |
Q:
Python: Pickle derived classes as if they were an instance of the base class
I want to define a base class so that when derived class instances are pickled, they are pickled as if they are instances of the base class. This is because the derived classes may exist on the client side of the pickling but not on the s... | Python: Pickle derived classes as if they were an instance of the base class | I want to define a base class so that when derived class instances are pickled, they are pickled as if they are instances of the base class. This is because the derived classes may exist on the client side of the pickling but not on the server side, but this is not important to the server since it only needs informatio... | [
"I believe you can do it by giving the object a __reduce__ method, returning a tuple, the first part of which should be BaseClass.__new__ (this will be called when loading the object in unpickling). See the pickle documentation (Python 2, Python 3) for the full details. I haven't attempted this.\nDepending on what ... | [
2,
1
] | [] | [] | [
"pickle",
"python",
"subclass"
] | stackoverflow_0004500740_pickle_python_subclass.txt |
Q:
How to get in python the key pressed without press enter?
I saw here a solution, but i don't want wait until the key is pressed. I want to get the last key pressed.
A:
The related question may help you, as @S.Lott mentioned: Detect in python which keys are pressed
I am writting in, though to give yu advice: don'... | How to get in python the key pressed without press enter? | I saw here a solution, but i don't want wait until the key is pressed. I want to get the last key pressed.
| [
"The related question may help you, as @S.Lott mentioned: Detect in python which keys are pressed\nI am writting in, though to give yu advice: don't worry about that. \nWhat kind of program are you trying to produce?\nProgramas running on a terminal usually don't have an interface in which getting \"live\" keystro... | [
4,
0
] | [] | [] | [
"keyboard_events",
"python",
"python_2.6"
] | stackoverflow_0004501700_keyboard_events_python_python_2.6.txt |
Q:
Python - extracting a list of sub strings
How to extract a list of sub strings based on some patterns in python?
for example,
str = 'this {{is}} a sample {{text}}'.
expected result : a python list which contains 'is' and 'text'
A:
>>> import re
>>> re.findall("{{(.*?)}}", "this {{is}} a sample {{text}}")
['is'... | Python - extracting a list of sub strings | How to extract a list of sub strings based on some patterns in python?
for example,
str = 'this {{is}} a sample {{text}}'.
expected result : a python list which contains 'is' and 'text'
| [
">>> import re\n>>> re.findall(\"{{(.*?)}}\", \"this {{is}} a sample {{text}}\")\n['is', 'text']\n\n",
"You can use the following:\nres = re.findall(\"{{([^{}]*)}}\", a)\nprint \"a python list which contains %s and %s\" % (res[0], res[1])\n\nCheers\n",
"Assuming \"some patterns\" means \"single words between do... | [
14,
2,
2,
1,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0004502314_python_regex.txt |
Q:
Can XML-RPC methods be called by name (as strings) in Python?
In python, calling XML-RPC methods involves invoking methods on a proxy object:
from xmlrpclib import ServerProxy
print ServerProxy('https://example.com/rpc').api.hello_there('John')
In some other languages, like perl, you pass your method name as a me... | Can XML-RPC methods be called by name (as strings) in Python? | In python, calling XML-RPC methods involves invoking methods on a proxy object:
from xmlrpclib import ServerProxy
print ServerProxy('https://example.com/rpc').api.hello_there('John')
In some other languages, like perl, you pass your method name as a method parameter.
use Frontier::Client;
$p = Frontier::Client->new(ur... | [
"Just use getattr, as with any Python object.\nfunc = getattr(ServerProxy('https://example.com/rpc'), \"api.hello_there\")\nprint func('John')\n\n"
] | [
3
] | [] | [] | [
"call",
"getattr",
"python",
"xml_rpc",
"xmlrpclib"
] | stackoverflow_0004502492_call_getattr_python_xml_rpc_xmlrpclib.txt |
Q:
fastest way to invoke a process from python?
What is the fastest/most efficient method to execute an executable from python? It seems to me that os.system is faster than subprocess.popen. I would like to be able to read the lines that come out of this other process, but far more important than anything else is ... | fastest way to invoke a process from python? | What is the fastest/most efficient method to execute an executable from python? It seems to me that os.system is faster than subprocess.popen. I would like to be able to read the lines that come out of this other process, but far more important than anything else is speed.
| [
"I would expect any speed difference between, say, os.system and os.execv and subprocess.Popen, to be swamped by the expense of starting a new process (and the context-switching needed to actually run it). Therefore I recommend using subprocess first and measuring the performance.\nOne possible performance consider... | [
4
] | [] | [] | [
"linux",
"python",
"subprocess"
] | stackoverflow_0004502469_linux_python_subprocess.txt |
Q:
Is a compiled python program a derivative of Python
Is a "compiled" python program (i.e. *.pyc file created by CPython) a derivative product of CPython? In other words, does one need to comply the Python license in all the programs he or she writes?
Disclaimer: I know that the answers here do not qualify as legal ... | Is a compiled python program a derivative of Python | Is a "compiled" python program (i.e. *.pyc file created by CPython) a derivative product of CPython? In other words, does one need to comply the Python license in all the programs he or she writes?
Disclaimer: I know that the answers here do not qualify as legal consultation.
| [
"No, from a licensing standpoint \"derivative\" applies to a modified version of the Python interpreter or its standard libraries, not to programs you write that run on the interpreter. It doesn't matter whether your programs are expressed as plain text or as compiled bytecode.\n",
"For comparison: bison is distr... | [
3,
0
] | [] | [] | [
"licensing",
"python"
] | stackoverflow_0004502237_licensing_python.txt |
Q:
Python multiprocessing and sockets not being closed
I'm experiencing an odd behaviour when using multiprocessing and socket on Python. I'm dealing with a piece of code similar that the one I'm posting below (I've simplified things a lot trying to be naive).
The code spawns three processes: one process does nothin... | Python multiprocessing and sockets not being closed | I'm experiencing an odd behaviour when using multiprocessing and socket on Python. I'm dealing with a piece of code similar that the one I'm posting below (I've simplified things a lot trying to be naive).
The code spawns three processes: one process does nothing, another process launches the third one, that will be l... | [
"To fix the immediate problem (of the socket not shutting down), add self.s.shutdown(socket.SHUT_RDWR) to the Server.stop method:\ndef stop(self):\n self.is_stop.set()\n self.s.shutdown(socket.SHUT_RDWR) \n self.s.close()\n\n",
"I am no expert on the multiprocessing package, but it would appear that the... | [
2,
1
] | [] | [] | [
"multiprocessing",
"multithreading",
"process",
"python",
"sockets"
] | stackoverflow_0004501877_multiprocessing_multithreading_process_python_sockets.txt |
Q:
How to pass self declared variables between different classes in python
I am trying to create a program that tracks bike intervals and creates a map of a course to use while biking. I want to be able to havbe a red line track the line while the stopwatch is counting. However, I am not able to pass the canvas betwe... | How to pass self declared variables between different classes in python | I am trying to create a program that tracks bike intervals and creates a map of a course to use while biking. I want to be able to havbe a red line track the line while the stopwatch is counting. However, I am not able to pass the canvas between the class for the main App and the Stopwatch.
from Tkinter import *
impor... | [
"Variables declared as part of self are instance variables - they're tied to a particular instance of the class, not the class itself - hence why you can't access them via App., since that's looking for them in the class, when c is actually a member of myapp.\nWhat you need to do is pass the App's self.c to the Sto... | [
3
] | [] | [] | [
"python",
"tkinter",
"variables"
] | stackoverflow_0004502885_python_tkinter_variables.txt |
Q:
variable can't be expression -- extending the user model in django
I realize that there are much more elegant ways to do this, and I will get there, but this is just hacking around trying to make it all work first. I've gotten this error:
SyntaxError at /accounts/profile/foobar/
keyword can't be an expression (... | variable can't be expression -- extending the user model in django | I realize that there are much more elegant ways to do this, and I will get there, but this is just hacking around trying to make it all work first. I've gotten this error:
SyntaxError at /accounts/profile/foobar/
keyword can't be an expression (views.py, line 104)
and here is the corresponding line. Note: keyword i... | [
"Easily duplicated:\n>>> def foo(**kwargs):\n... return None\n... \n>>> foo(a.b=1)\n File \"<stdin>\", line 1\nSyntaxError: keyword can't be an expression\n\nThe error message is a bit cryptic - where's the keyword? I suspect its to do with '.' being syntax for getattr.\n"
] | [
4
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0004503029_django_django_models_python.txt |
Q:
Getting a list of strings with character removed in permutation
I want to remove a character from a string in permutation....
Let us say that I have a function
def (string,char):
# remove char from string
Say I have aAabbAA as string and A as char then I want the strings [aabb,aAabb,aabbA,aabbA, aabbAA,aAabbA... | Getting a list of strings with character removed in permutation | I want to remove a character from a string in permutation....
Let us say that I have a function
def (string,char):
# remove char from string
Say I have aAabbAA as string and A as char then I want the strings [aabb,aAabb,aabbA,aabbA, aabbAA,aAabbA ,aAabbA ] as output that is A gets removed 3 times , 2 times , 1 tim... | [
"Here is one crazy idea using recursion:\ndef f(s, c, start):\n i = s.find(c, start)\n if i < 0:\n return [s]\n else:\n return f(s, c, i+1) + f(s[:i]+s[i+1:], c, i)\n\ns = 'aAabbAA'\nprint f(s, 'A', 0)\n# ['aAabbAA', 'aAabbA', 'aAabbA', 'aAabb', 'aabbAA', 'aabbA', 'aabbA', 'aabb']\n\nEdit: Us... | [
3,
1,
0
] | [] | [] | [
"permutation",
"python",
"string"
] | stackoverflow_0004502843_permutation_python_string.txt |
Q:
Need help with joins in sqlalchemy
I'm new to Python, as well as SQL Alchemy, but not the underlying development and database concepts. I know what I want to do and how I'd do it manually, but I'm trying to learn how an ORM works.
I have two tables, Images and Keywords. The Images table contains an id column tha... | Need help with joins in sqlalchemy | I'm new to Python, as well as SQL Alchemy, but not the underlying development and database concepts. I know what I want to do and how I'd do it manually, but I'm trying to learn how an ORM works.
I have two tables, Images and Keywords. The Images table contains an id column that is its primary key, as well as some ot... | [
"It appears that I was still getting the wrong version of join, even importing the one under sqlalchemy.orm. I did this to resolve the problem:\nfrom sqlalchemy.orm.util import join as join_\n\nimage = session.query(Image).select_from(join_(Image, Keyword)).\\\n filter(Keyword.keyword == 'boy')\n\nIs that reall... | [
1
] | [] | [] | [
"join",
"python",
"sqlalchemy"
] | stackoverflow_0004502573_join_python_sqlalchemy.txt |
Q:
how do i parse a wiki page without taking a dump of it in python?
Is it possible to parse a wiki without taking its dump , as the dump itself is way too much data to handle . Thus lets say I have the url of a certain wiki and once i call it through urllib , how do I parse it and get a certain type of data using py... | how do i parse a wiki page without taking a dump of it in python? | Is it possible to parse a wiki without taking its dump , as the dump itself is way too much data to handle . Thus lets say I have the url of a certain wiki and once i call it through urllib , how do I parse it and get a certain type of data using python .
here type means a certain data corresponding to a semantic matc... | [
"You need an HTML parser to get the useful data from the HTML.\nYou can use BeautifulSoup to help parse the HTML. I recommend that you read the documentation and have a look at the examples there. \n",
"I'd suggest an option such as Harvestman instead, since a semantic search is likely throw multiple pages, comp... | [
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0004503257_python.txt |
Q:
How to elementwise-multiply a scipy.sparse matrix by a broadcasted dense 1d array?
Suppose I have a 2d sparse array. In my real usecase both the number of rows and columns are much bigger (say 20000 and 50000) hence it cannot fit in memory when a dense representation is used:
>>> import numpy as np
>>> import scip... | How to elementwise-multiply a scipy.sparse matrix by a broadcasted dense 1d array? | Suppose I have a 2d sparse array. In my real usecase both the number of rows and columns are much bigger (say 20000 and 50000) hence it cannot fit in memory when a dense representation is used:
>>> import numpy as np
>>> import scipy.sparse as ssp
>>> a = ssp.lil_matrix((5, 3))
>>> a[1, 2] = -1
>>> a[4, 1] = 2
>>> a.t... | [
"I replied over at scipy.org as well, but I thought I should add an answer here, in case others find this page when searching.\nYou can turn the vector into a sparse diagonal matrix and then use matrix multiplication (with *) to do the same thing as broadcasting, but efficiently.\n>>> d = ssp.lil_matrix((3,3))\n>>>... | [
49,
27,
1
] | [] | [] | [
"numpy",
"python",
"scipy",
"sparse_matrix"
] | stackoverflow_0003247775_numpy_python_scipy_sparse_matrix.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.