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: Anonymous class inheritance I am building a python automation API around a device configuration that looks like this... root@EX4200-24T# show interfaces ge-0/0/6 mtu 9216; unit 0 { family ethernet-switching { port-mode trunk; vlan { members [ v100 v101 v102 ]; } } } ro...
Anonymous class inheritance
I am building a python automation API around a device configuration that looks like this... root@EX4200-24T# show interfaces ge-0/0/6 mtu 9216; unit 0 { family ethernet-switching { port-mode trunk; vlan { members [ v100 v101 v102 ]; } } } root@EX4200-24T# I am defining pyt...
[ "Does something like this help you?\nfrom functools import partial\nS=partial(SET, Family='ethernet-switching', PortMode='trunk')\nS(Interface='ge-0/0/6.0', Vlan=['v100', 'v101', 'v102'])\nS(Interface='ge-0/0/7.0', Vlan=['v100', 'v101', 'v102'])\nS(Interface='ge-0/0/8.0', Vlan=['v100', 'v101', 'v102'])\n\n", "gni...
[ 10, 2, 1 ]
[]
[]
[ "inheritance", "python" ]
stackoverflow_0005737728_inheritance_python.txt
Q: Detect File Change Without Polling I'm trying to use a method within a Python program to detect whether a file on the file system has been modified. I know that I could have something run on an every-5-seconds to check the last modification date off of the system, but I was curious as to whether there's an easier...
Detect File Change Without Polling
I'm trying to use a method within a Python program to detect whether a file on the file system has been modified. I know that I could have something run on an every-5-seconds to check the last modification date off of the system, but I was curious as to whether there's an easier method for doing this, without needing ...
[ "watchdog \nExcellent cross platform library for watching directories.\nFrom the website\n\nSupported Platforms\n\nLinux 2.6 (inotify)\nMac OS X (FSEvents, kqueue)\nFreeBSD/BSD (kqueue)\nWindows (ReadDirectoryChangesW with I/O completion ports; ReadDirectoryChangesW worker threads)\nOS-independent (polling the disk...
[ 80, 45, 7, 5 ]
[]
[]
[ "python" ]
stackoverflow_0005738442_python.txt
Q: Python editor that can connect to remote environment? I set up an interactive python environment in an application. I can input commands and they will execute inside it, having access to the variables that live there. The problem is that I coded a half-assed editor that allows only that. It doesn't have command hi...
Python editor that can connect to remote environment?
I set up an interactive python environment in an application. I can input commands and they will execute inside it, having access to the variables that live there. The problem is that I coded a half-assed editor that allows only that. It doesn't have command history, code completion etc, because I didn't code a full ID...
[ "Did you try integrating PyCrust into your application? See this SO question\nEmbedding a Python shell inside a Python program\nrpyc sounds like something which could be useful to you. rpyc added support for IronPython in their latest release. PyScripter supports rpyc. Maybe this is the combo you are looking for?\n...
[ 0 ]
[]
[]
[ "editor", "ide", "python" ]
stackoverflow_0005736216_editor_ide_python.txt
Q: css files in django hosted on webfaction I'm running django on webfaction, and am having trouble implementing my css files. A sample html file I have is: <html> <head> </head> <h1> Poll </h1> <body> <link rel="stylesheet" type="text/css" href="/home/shop/webapps/django/shop/static/index.css" /> <form name="Search ...
css files in django hosted on webfaction
I'm running django on webfaction, and am having trouble implementing my css files. A sample html file I have is: <html> <head> </head> <h1> Poll </h1> <body> <link rel="stylesheet" type="text/css" href="/home/shop/webapps/django/shop/static/index.css" /> <form name="Search bar" action="/search/results/p=1/" method="pos...
[ "Why are you referencing this stylesheet absolutely?\n<link rel=\"stylesheet\" type=\"text/css\" href=\"/home/shop/webapps/django/shop/static/index.css\" />\n\nJust refer to the static directory, as it takes care of static file loading for you:\n<link rel=\"stylesheet\" type=\"text/css\" href=\"/static/index.css\"...
[ 3, 1 ]
[]
[]
[ "django", "python", "webfaction" ]
stackoverflow_0005739638_django_python_webfaction.txt
Q: How to redirect the url after logging into Facebook? I have created a django application with a Facebook connect to the application. Now when i click on the Facebook login button, the oauth page pop ups. When i give the username n password, it gets closed without actually redirecting the page to any page. But when...
How to redirect the url after logging into Facebook?
I have created a django application with a Facebook connect to the application. Now when i click on the Facebook login button, the oauth page pop ups. When i give the username n password, it gets closed without actually redirecting the page to any page. But when i took FB page in a new tab, i could see the FB logged in...
[ "I suppose you are using the JS Facebook library if you say that the oauth just pop ups. I would go the simpler oauth redirect way, using a the following :\ndef build_authentication_redirect(self):\n args = {}\n args[\"client_id\"]=self.app_id\n args[\"redirect_uri\"]=self.redirect_...
[ 5, 2 ]
[]
[]
[ "django", "facebook", "facebook_graph_api", "python" ]
stackoverflow_0005730545_django_facebook_facebook_graph_api_python.txt
Q: Find and copy files to existing Folders with corresponding names in python i have a large number of files that i need to move to a specific existing folder. the problem is that the number code that relates the file and the folder has text on either side of it as shown below the number code is a071137 in the file n...
Find and copy files to existing Folders with corresponding names in python
i have a large number of files that i need to move to a specific existing folder. the problem is that the number code that relates the file and the folder has text on either side of it as shown below the number code is a071137 in the file name and A071137 in the folder name. for example, i need to move file: "a071137_g...
[ "Your question is rather vague, but hopefully I can at least point you in the right direction here. Sounds like you will want to be able to list all of the files in a directory, which can be done with os.listdir(directory) as described in the api. You will likely then iterate through these files, and extract the re...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0005739060_python.txt
Q: How to create e-mail reminders in Django I am looking to send e-mail reminders to users X amount of time before a scheduled even. I've been reading through the documentation for django-mailer, which seems to support such scheduled mailing, but am unable to find such functionality in the code. My thought is to hav...
How to create e-mail reminders in Django
I am looking to send e-mail reminders to users X amount of time before a scheduled even. I've been reading through the documentation for django-mailer, which seems to support such scheduled mailing, but am unable to find such functionality in the code. My thought is to have a script in my project that gets called by c...
[ "Roll your own.\nSending an email is trivial enough already. The coding required to complete the task will be application specific. What more can a pre-built package offer you? What features did you have in mind? All I can think of is a queryset which returns objects based on an arbitrary timestamp but it would add...
[ 1 ]
[]
[]
[ "cron", "django", "email", "python" ]
stackoverflow_0005738741_cron_django_email_python.txt
Q: Why does my code work in python shell but not when I double click the py file Why does my python file run perfectly in the IDLE but doesn't work when I double click it. Let me rephrase, My if/else statements never seem to be true even tho they work correctly in the IDLE. I even broke down ALL my code to the most s...
Why does my code work in python shell but not when I double click the py file
Why does my python file run perfectly in the IDLE but doesn't work when I double click it. Let me rephrase, My if/else statements never seem to be true even tho they work correctly in the IDLE. I even broke down ALL my code to the most simple if/else statement to test and make sure I wasn't missing something. Here is t...
[ "try adding\nchoice = choice.strip()\n\nthis works for me\nchoice = input('letter: ')\nchoice = choice.strip()\nif choice == 'a':\n print ('that is an a')\n input('press any key to exit...')\nelse:\n print('that letter is not an a')\n input('press any key to exit')\n\notherwise your input gives you the ...
[ 3, 1 ]
[]
[]
[ "python" ]
stackoverflow_0005739969_python.txt
Q: Efficient insert of multiple rows with SQLAlchemy/SQLite3 when duplicate entries exist I'm inserting multiple rows into an SQLite3 table using SQLAlchemy, and frequently the entries are already in the table. It is very slow to insert the rows one at a time, and catch the exception and continue if the row already ...
Efficient insert of multiple rows with SQLAlchemy/SQLite3 when duplicate entries exist
I'm inserting multiple rows into an SQLite3 table using SQLAlchemy, and frequently the entries are already in the table. It is very slow to insert the rows one at a time, and catch the exception and continue if the row already exists. Is there an efficient way to do this? If the row already exists, I'd like to do not...
[ "You can use an SQL statement\nINSERT OR IGNORE INTO ... etc. ...\n\nto simply ignore the insert if it is a duplicate. Learn about the IGNORE conflict clause here \nPerhaps you can use OR IGNORE as a prefix in your SQLAlchemy Insert -- the documentation for how to place OR IGNORE between INSERT and INTO in your SQL...
[ 5, 1 ]
[]
[]
[ "python", "sqlalchemy", "sqlite" ]
stackoverflow_0005737586_python_sqlalchemy_sqlite.txt
Q: SwigPyObject and JSON communication inside python code Intro. I have a C++ application, I use SWIG to launch GetObjects and PutObjects methods which are defined in python code. GetObjects method opens JSON formated file, takes objects from there and returns back them to C++ application. While the PutObjects method...
SwigPyObject and JSON communication inside python code
Intro. I have a C++ application, I use SWIG to launch GetObjects and PutObjects methods which are defined in python code. GetObjects method opens JSON formated file, takes objects from there and returns back them to C++ application. While the PutObjects method gets objects from C++ application, opens JSON formated file...
[ "You should be able to use the \"dir\" function to get a list of attributes of an object.\nHere is example which grabs all non function user created attributes (called \"properties\"):\nimport inspect\n\nclass MyObject(object):\n def __init__(self):\n self.b = 1\n self.c = 'a'\n def func(self):\...
[ 1 ]
[]
[]
[ "c++", "json", "python", "swig" ]
stackoverflow_0005740590_c++_json_python_swig.txt
Q: Python script to read the database tables and relation to create dot file Hi I am new to dot file concept, I am looking create ERD diagram with Primary keys and relationships. The approach is to whip up a Python script to read the database tables and to create a "dot" file which can then be used to generate the gr...
Python script to read the database tables and relation to create dot file
Hi I am new to dot file concept, I am looking create ERD diagram with Primary keys and relationships. The approach is to whip up a Python script to read the database tables and to create a "dot" file which can then be used to generate the graphic using graphviz. I found the way to generate graph using dot file on graph...
[ "for graphviz modules you can check this\nfor database manipulation, it depends on the size and complexity of your data, but you can start with the sqlite3 python module\n", "I wrote a crude script to do exactly this. It works only for mySQL for an engine that understands foreign keys (myISAM doesn't work). It do...
[ 2, 2 ]
[]
[]
[ "dot", "python" ]
stackoverflow_0005740676_dot_python.txt
Q: Checking a lot of URLs to see if they return 200. What's the cleverest way? I need to check a lot (~10 million) of URLs to see if they exist (return 200). I've written the following code to do this per-URL, but to do all of the URLs will take approximately forever. def is_200(url): try: pa...
Checking a lot of URLs to see if they return 200. What's the cleverest way?
I need to check a lot (~10 million) of URLs to see if they exist (return 200). I've written the following code to do this per-URL, but to do all of the URLs will take approximately forever. def is_200(url): try: parsed = urlparse(url) conn = httplib.HTTPConnection(parsed.netloc) ...
[ "Have a look at urllib3. It supports per-host connection re-using.\nAdditionally using multiple processes/threads or async I/O would be a good idea.\n", "All of this is in Python, version 3.x.\nI would create worker threads that check for 200. I'll give an example. The threadpool (put in threadpool.py):\n# http:/...
[ 2, 2 ]
[]
[]
[ "curl", "head", "http", "python" ]
stackoverflow_0005741220_curl_head_http_python.txt
Q: how to plot a x-y grid of e.g. squares with colours read from an array I have separate arrays of x and y coordinates, and a z-array of corresponding values. I wish to make a plot that has squares at each x and y coordinate that have colours set from the z array - something similar to this. I have searched quite ha...
how to plot a x-y grid of e.g. squares with colours read from an array
I have separate arrays of x and y coordinates, and a z-array of corresponding values. I wish to make a plot that has squares at each x and y coordinate that have colours set from the z array - something similar to this. I have searched quite hard on google to find how I can do this, but to no avail. The matplotlib.pypl...
[ "Thanks Andrew. I see how that works now. The thing is my z-array is just one column of numbers. Since they are not in any sensible order, it would be difficult to just re-shape the array into 2D to use pcolor.\nI have come up with a much better solution using a for loop to append rectangle patches to a patch colle...
[ 2, 1, 1 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0005715886_matplotlib_python.txt
Q: Dictionary-like object in Python that allows setting arbitrary attributes What I want to do in my code: myobj = <SomeBuiltinClass>() myobj.randomattr = 1 print myobj.randomattr ... I can implement a custom SomeClass that implements __setattr__ __getattr__. But I wonder if there is already a built-in Python class ...
Dictionary-like object in Python that allows setting arbitrary attributes
What I want to do in my code: myobj = <SomeBuiltinClass>() myobj.randomattr = 1 print myobj.randomattr ... I can implement a custom SomeClass that implements __setattr__ __getattr__. But I wonder if there is already a built-in Python class or simple way to do this?
[ "You can just use an empty class:\nclass A(object): pass\n\na = A()\na.randomattr = 1\n\n", "I like using the Bunch idiom for this. There are list of variations and some discussion here.\n", "One solution is to use mock's:\nfrom mock import Mock\nmyobj = Mock()\nmyobj.randomattr = 1\nprint myobj.randomattr\n\nS...
[ 8, 2, 0 ]
[]
[]
[ "attributes", "dictionary", "python" ]
stackoverflow_0002350817_attributes_dictionary_python.txt
Q: Pygame's Message-multiple lines? I am using pygame and livewires (though I don't think that part is relevant here) to create a game. I've got the game working, but I'm trying to make something akin to a title screen before the game starts. However, it doesn't recognize when I try to make a new line appear. Here is...
Pygame's Message-multiple lines?
I am using pygame and livewires (though I don't think that part is relevant here) to create a game. I've got the game working, but I'm trying to make something akin to a title screen before the game starts. However, it doesn't recognize when I try to make a new line appear. Here is what I have: begin_message=games....
[ "The livewires games.Message class cannot do this.\nGoing through the source code for games.Message shows that it inherits from games.Text, which has a method _create_surface(). Finally, this calls pygame.font.Font.render() to draw the text to a surface. If you look at the documentation for render(), it states \n\n...
[ 3, 0 ]
[]
[]
[ "pygame", "python" ]
stackoverflow_0002770886_pygame_python.txt
Q: Numpy array - duplicating rows and centering columns in a larger array I have a large number of arrays with dimension 72, x where x is less than 144. I'd like to take these arrays and do two things to them: Duplicate each row in the original so that there are 144 of them. Center the arrays horizontally inside a l...
Numpy array - duplicating rows and centering columns in a larger array
I have a large number of arrays with dimension 72, x where x is less than 144. I'd like to take these arrays and do two things to them: Duplicate each row in the original so that there are 144 of them. Center the arrays horizontally inside a larger 144 The end result is a 144x144 array. I'd like to use numpy and to t...
[ "Let's take a smaller example:\nimport numpy as np\na = np.array([[1, 2],\n [3, 4]])\n\nb = np.zeros((4,4))\n\nb[:,1:-1] = np.repeat(a, 2, axis=0)\n\n# returns:\n\narray([[ 0., 1., 2., 0.],\n [ 0., 1., 2., 0.],\n [ 0., 3., 4., 0.],\n [ 0., 3., 4., 0.]])\n\nSo for your case...
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0005741567_python.txt
Q: Send email when user creates a directory I have an filemanager application and I want some specific admin users to be notified when "baseusers" create directories. Mails are sent to users defined in admin pages. The optimal solution would be to have a checkbox in my profile pages for getting notifications but I wo...
Send email when user creates a directory
I have an filemanager application and I want some specific admin users to be notified when "baseusers" create directories. Mails are sent to users defined in admin pages. The optimal solution would be to have a checkbox in my profile pages for getting notifications but I would like to get this to work first. Here is my...
[ "To send and process the mails in the background you should use a mail queue.\nSeveral options are discussed in this thread: Advice on Python/Django and message queues\nFor your use case django-mailer seems like a good choice.\n" ]
[ 2 ]
[]
[]
[ "django", "django_models", "django_views", "python" ]
stackoverflow_0005741885_django_django_models_django_views_python.txt
Q: convert xml/html string to image using python or c++ I have following xml/html string and want to convert it to jpg can any one know how could I achieve this? <Text index="1" text="Hello Rizwan Ullah&#xD;" rotation="0" offsetX="182.7" offsetY="96.75" backgroundColor="10066329" backgroundAlpha="0.4" margin="0"> <![...
convert xml/html string to image using python or c++
I have following xml/html string and want to convert it to jpg can any one know how could I achieve this? <Text index="1" text="Hello Rizwan Ullah&#xD;" rotation="0" offsetX="182.7" offsetY="96.75" backgroundColor="10066329" backgroundAlpha="0.4" margin="0"> <![CDATA[<TEXTFORMAT LEADING="2"> <P ALIGN="LEFT"> <FONT FACE...
[ "Python Imaging Library (PIL) can render text to an image:\nExample from a pre-existing question:\nfrom PIL import Image\nimport ImageFont, ImageDraw\n\nimage = Image.new(\"RGBA\", (288,432), (255,255,255))\nusr_font = ImageFont.truetype(\"resources/HelveticaNeueLight.ttf\", 25)\nd_usr = ImageDraw.Draw(image)\nd_us...
[ 1 ]
[]
[]
[ "c++", "html", "image", "python" ]
stackoverflow_0005741803_c++_html_image_python.txt
Q: Menu problem with PyGame MOUSEBUTTONDOWN event Yes, that title wasn't worded very properly at all. Ok, here's what we've got - a Python program using the pyGame library, and we're making a game. We start in a menu environment main.py. When the user clicks on one of the menu buttons, an action is performed. The pro...
Menu problem with PyGame MOUSEBUTTONDOWN event
Yes, that title wasn't worded very properly at all. Ok, here's what we've got - a Python program using the pyGame library, and we're making a game. We start in a menu environment main.py. When the user clicks on one of the menu buttons, an action is performed. The program checks for clicks on menu items using the follo...
[ "You could use MOUSEBUTTONUP instead of MOUSBUTTONDOWN in the menu.\n", "Does adding pygame.event.clear() to the top of Play fix it?\n" ]
[ 2, 1 ]
[]
[]
[ "pygame", "python" ]
stackoverflow_0005740970_pygame_python.txt
Q: Python: convenient way to initialize lots of class members If I have lots of class variables to initialize, any way to shorten the use of "self." ? That is, instead of doing: self.variable1 = 1 self.variable2 = 10 self.variable3 = "hello" etc. is it possible to do some shortcut like: with self: variable1 = ...
Python: convenient way to initialize lots of class members
If I have lots of class variables to initialize, any way to shorten the use of "self." ? That is, instead of doing: self.variable1 = 1 self.variable2 = 10 self.variable3 = "hello" etc. is it possible to do some shortcut like: with self: variable1 = 1 variable2 = 2 variable3 = 'hello' Just thought I coul...
[ "There are ways to do this, but I wouldn't suggest them. It hampers readability.\n", "If you really want to do this, here's a way:\nself.__dict__.update(\n variable1 = 1,\n variable2 = 2,\n variable3 = 'hello')\n\nI'd usually just type self or use copy&paste in my editor.\n", "Another alternative, just...
[ 3, 2, 0 ]
[]
[]
[ "initialization", "python", "self", "shortcut", "variables" ]
stackoverflow_0005741506_initialization_python_self_shortcut_variables.txt
Q: python's print function not exactly an ordinary function? Environment: python 2.x If print is a built-in function, why does it not behave like other functions ? What is so special about print ? -----------start session-------------- >>> ord 'a' Exception : invalid syntax >>> ord('a') 97 >>> print 'a' a >>> print('...
python's print function not exactly an ordinary function?
Environment: python 2.x If print is a built-in function, why does it not behave like other functions ? What is so special about print ? -----------start session-------------- >>> ord 'a' Exception : invalid syntax >>> ord('a') 97 >>> print 'a' a >>> print('a') a >>> ord <built-in function ord> >>> print -----------fi...
[ "print in Python versions below 3, is not a function. There's a separate print statement which is part of the language grammar. print is not an identifier. It's a keyword. \n", "The short answer is that in Python 2, print is not a function but a statement.\nIn all versions of Python, almost everything is an objec...
[ 5, 5, 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0005741598_python.txt
Q: CodeIgniter-like Routes in CherryPy I'm coming from PHP frameworks, and one thing I like about them is that routing is sort of taken care of for me: I can drop all of my controllers in the directory controllers and it will automatically call Posts::delete(12) when a user visits http://www.example.com/posts/delete/...
CodeIgniter-like Routes in CherryPy
I'm coming from PHP frameworks, and one thing I like about them is that routing is sort of taken care of for me: I can drop all of my controllers in the directory controllers and it will automatically call Posts::delete(12) when a user visits http://www.example.com/posts/delete/12. I realize that I can use Routes with ...
[ "Simple way is to use cherrypy.tree.mount to mount a controller object. The structure of the controller will give you your basic routes.\nFor example:\nimport cherrypy\n\nclass AppRoot:\n def index(self):\n return \"App root's index\"\n index.exposed = True\n\n controller1 = Controller1Class()\n ...
[ 2 ]
[]
[]
[ "cherrypy", "python", "routes" ]
stackoverflow_0005630639_cherrypy_python_routes.txt
Q: Feedback on Python RSYNC script wanted This script appears to work great, but I'm sure this could be optimised by some of you gurus! Purpose of script: "watch" a directory for new files with particular file extension ensure file is not still being copied rsync the file to remote server rsync deletes the file scri...
Feedback on Python RSYNC script wanted
This script appears to work great, but I'm sure this could be optimised by some of you gurus! Purpose of script: "watch" a directory for new files with particular file extension ensure file is not still being copied rsync the file to remote server rsync deletes the file script loops continuously forever survives inter...
[ "first, eliminate useless statement\n# check if correct file extension\ndef checkExt(path):\n return path.endswith(FILE_EXT)\n\nthen be a little more pythonic\n# rsync subprocess\ndef rsyncFile(path):\n printLog(\"Syncing file '%s'\" % os.path.basename(path))\n try:\n p = subprocess.Popen(['rsync', ...
[ 2 ]
[]
[]
[ "python", "rsync" ]
stackoverflow_0005740783_python_rsync.txt
Q: How to plot a set of points in python? I have a set of points created through a python program which belongs to different clusters. I would like to plot it on a graph so that points in different clusters should be plotted with different colours. UPDATE In my case I have a univariate data ( marks of a test). Lookin...
How to plot a set of points in python?
I have a set of points created through a python program which belongs to different clusters. I would like to plot it on a graph so that points in different clusters should be plotted with different colours. UPDATE In my case I have a univariate data ( marks of a test). Looking for a way to plot it. I have two clusters...
[ "you can use matplotlib. I'm not sure to understand exactly your need, but it could be something like this :\nfrom pylab import *\nfor (x, y) in clusters:\n plot(x, y, '+')\nshow() # or savefig(<filename>)\n\n", "matplotlib is an easy to use plotting library. Should do what you want. Assuming your problem isn'...
[ 8, 0, 0 ]
[]
[]
[ "numpy", "python", "scipy" ]
stackoverflow_0005742241_numpy_python_scipy.txt
Q: Problem with GFF parser by BCBio I am trying to parse a GFF file using the BCBio GFF parser and I get the following error. Can anybody help me in resolving this problem? Traceback (most recent call last): File "gff_parse.py", line 6, in <module> for rec in GFF.parse(in_handle): File "build/bdist.linux-x86_6...
Problem with GFF parser by BCBio
I am trying to parse a GFF file using the BCBio GFF parser and I get the following error. Can anybody help me in resolving this problem? Traceback (most recent call last): File "gff_parse.py", line 6, in <module> for rec in GFF.parse(in_handle): File "build/bdist.linux-x86_64/egg/BCBio/GFF/GFFParser.py", line 70...
[ "How did you generate the GFF file? It appears to contain at least one invalid line. The fourth column should contain integers for the start coordinate of a feature; the error message indicates it contains the value 'New Start' instead.\nThe GFF3 specification page has some examples of valid GFF, and the online val...
[ 2 ]
[]
[]
[ "biopython", "python" ]
stackoverflow_0005742379_biopython_python.txt
Q: Python Indentation I thought every line in pythton is a statment, but have a look below: class Report(p.Report): def create(self): self.set(background=sp.LightYellow) self.add(p.Row(p.Text("Trip Name", valign=p.CENTER, font=p.font(weight=p.BOLD)), p.Column(p.T...
Python Indentation
I thought every line in pythton is a statment, but have a look below: class Report(p.Report): def create(self): self.set(background=sp.LightYellow) self.add(p.Row(p.Text("Trip Name", valign=p.CENTER, font=p.font(weight=p.BOLD)), p.Column(p.Text("Costs", ...
[ "Put simply, a statement can continue on to the next line as long as there is an open parenthesis or bracket or brace. \nValid:\nprint (\"hello \" \n \"world\"\n \"!\")\n\nInvalid:\nprint \"hello \" \n \"world\"\n \"!\"\n\n", "The second you open a bracket (either round or square) all id...
[ 5, 2, 0, 0, 0 ]
[]
[]
[ "indentation", "line", "python" ]
stackoverflow_0005742828_indentation_line_python.txt
Q: Creating templates in Django / Python I am learning Django and I tried to create a template like this: >>> weekend = True >>> from django.template import Template, Context >>> template_string = """ {% if weekend %} <p> This is a weekend </p> {% endif %} """ >>> t = Template(template_string) I get this followi...
Creating templates in Django / Python
I am learning Django and I tried to create a template like this: >>> weekend = True >>> from django.template import Template, Context >>> template_string = """ {% if weekend %} <p> This is a weekend </p> {% endif %} """ >>> t = Template(template_string) I get this following error. Am I missing something? Traceback...
[ "This has nothing to do with templates.\nStart your shell by doing python manage.py shell from the directory containing manage.py and settings.py.\n", "If you've started a django project try running the same code inside a django shell.\npython manage.py shell\n\nAlternatively set DJANGO_SETTINGS_MODULE to the nam...
[ 2, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0005743207_django_python.txt
Q: Ways to parse docs and normalize rows I feel as if I oversimplify/overcomplexify doc parsing at times, here is what I often do: data = open('data.txt', 'rb').read() for line in data.split('\n'): if not line.strip(): continue and this: import csv filenames=['first_name', 'last_name', 'email', 'postco...
Ways to parse docs and normalize rows
I feel as if I oversimplify/overcomplexify doc parsing at times, here is what I often do: data = open('data.txt', 'rb').read() for line in data.split('\n'): if not line.strip(): continue and this: import csv filenames=['first_name', 'last_name', 'email', 'postcode', 'telephone_no', ] reader = csv.DictRea...
[ "You could make the the list of non-empty lines a one-liner\nlines = filter(None, (line.strip() for line in open('data.txt', 'rb').readlines()))\n\nFastest way to remove everything except certain characters\nUse __contains__ method of a string constant with filter (filter returns string if used with string). So you...
[ 2, 1 ]
[]
[]
[ "normalization", "python", "string" ]
stackoverflow_0005743322_normalization_python_string.txt
Q: python click event scope issue in pygame I've created a GameObject class, using the python pygame library, which draws a rectangle on the screen. I would like to integrate an event handler which would allow me to draw the rectangle around, however the click events for the GameObject are not registering. Here a...
python click event scope issue in pygame
I've created a GameObject class, using the python pygame library, which draws a rectangle on the screen. I would like to integrate an event handler which would allow me to draw the rectangle around, however the click events for the GameObject are not registering. Here are a couple snippets of code from the class: ...
[ "\n\nDo I need to make the rect into an image for the mouse events to register, or is there some other way I can drag this box around?\n\n\nNo image required. Solution:\nNote: \n\nYou already use event to get MOUSEMOTION, so use event's data: .pos, and .button from the event. \nuse Color class to store as a singl...
[ 1 ]
[]
[]
[ "mouseevent", "pygame", "python", "scope" ]
stackoverflow_0005037080_mouseevent_pygame_python_scope.txt
Q: Setting up a Relational Table I want to add a relational data without dealing id's. Let me explain. For example, Nokta1 and Nokta2 is related to Cihaz1. Nokta3 is related to Cihaz2. So this is a one-to-many relation. Immediately after adding Cihaz1 and Cihaz2 rows to cihaz table, how can I insert Nokta1, Nokta2 an...
Setting up a Relational Table
I want to add a relational data without dealing id's. Let me explain. For example, Nokta1 and Nokta2 is related to Cihaz1. Nokta3 is related to Cihaz2. So this is a one-to-many relation. Immediately after adding Cihaz1 and Cihaz2 rows to cihaz table, how can I insert Nokta1, Nokta2 and Nokta3 rows to nokta table with t...
[ "The link table should be defined as:\n create table link ( \n nokta_id integer, \n cihaz_id integer,\n FOREIGN KEY(nokta_id) REFERENCES nokta(id),\n FOREIGN KEY(cihaz_id) REFERENCES cihaz(id)\n ) \n\nbut you really don't need this table at all. It is just a projection of the ...
[ 0, 0 ]
[]
[]
[ "database", "python", "sqlite" ]
stackoverflow_0005743300_database_python_sqlite.txt
Q: How to know the filetype through python In the very beginning,I tried to do like this(hoped to get some useful information in the head): >>content=open("fileurl","rb").read() I found that PNG (png)'s Header is lik this: 89504E47 (I don't know wheather it's true or not) But when I did in this way,the result is: ...
How to know the filetype through python
In the very beginning,I tried to do like this(hoped to get some useful information in the head): >>content=open("fileurl","rb").read() I found that PNG (png)'s Header is lik this: 89504E47 (I don't know wheather it's true or not) But when I did in this way,the result is: >>> content[:20] '\x89PNG\r\n\x1a\n\x00\x00\...
[ "'\\x89' is a representation of non-printable byte with value 0x89 (that's 137).\nAs for finding file types in Python, there is already mimetypes module for that. \nimport mimetypes\ntype, subtype = mimetypes.guess_type(filename_or_url)\n\nIn action:\n>>> mimetypes.guess_type('http://upload.wikimedia.org/wikipedia/...
[ 4, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005743548_python.txt
Q: Python create an event to an ObjectListView check box How would I create an event for when a box is checked/unchecked? For this example I just want it to print the data about the object that was checked NOTE: This code was modified from http://www.blog.pythonlibrary.org/2009/12/23/wxpython-using-objectlistview-in...
Python create an event to an ObjectListView check box
How would I create an event for when a box is checked/unchecked? For this example I just want it to print the data about the object that was checked NOTE: This code was modified from http://www.blog.pythonlibrary.org/2009/12/23/wxpython-using-objectlistview-instead-of-a-listctrl/ as a learning exercise import wx from ...
[ "The class ObjectListView does not seem to contain that functionality. After digging in the code for a while I have decided to extend it.\nYou can derive your own class from ObjectListView and force the event in. You have to override _HandleLeftDownOnImage and SetCheckState methods. Or you can just change the Objec...
[ 4, 0 ]
[]
[]
[ "events", "objectlistview", "python", "wxpython" ]
stackoverflow_0005704212_events_objectlistview_python_wxpython.txt
Q: which language will be suitable for an web Interface I am planning to write a webcrawler in c++ and i need to manage the crawler settings in a web interface ...so i am planning to use some languages like perl or python to use as web interface and c++ as language..which will be the best language for c++ to interac...
which language will be suitable for an web Interface
I am planning to write a webcrawler in c++ and i need to manage the crawler settings in a web interface ...so i am planning to use some languages like perl or python to use as web interface and c++ as language..which will be the best language for c++ to interact with python or perl ..etc..
[ "If your web UI needs are simple, there's no reason you can't build the web interface in C++ as well. I have built a server using the mongoose embeddable http server library, adding support for web configuration pages is simple enough. If all you need is to render some input forms and process the input fields when ...
[ 1, 0, -1 ]
[]
[]
[ "c++", "perl", "python" ]
stackoverflow_0005743742_c++_perl_python.txt
Q: How to extend pyWavelets to work with N-dimensional data? This may be a question for a different forum, if so please let me know. I noticed that only 14 people follow the wavelet tag. I've here an elegant way of extending the wavelet decomposition in pywt (pyWavelets package) to multiple dimensions. This should ru...
How to extend pyWavelets to work with N-dimensional data?
This may be a question for a different forum, if so please let me know. I noticed that only 14 people follow the wavelet tag. I've here an elegant way of extending the wavelet decomposition in pywt (pyWavelets package) to multiple dimensions. This should run out of the box if pywt is installed. Test 1 shows the decompo...
[ "First of all, I would like to point you to the function that already implements Single-level Multi-dimensional Transform (Source). It returns a dictionary of n-dimensional coefficients arrays. Coefficients are addressed by keys that describe type of the transform (approximation/details) applied to each of the dime...
[ 5 ]
[]
[]
[ "multidimensional_array", "python", "signal_processing", "wavelet" ]
stackoverflow_0005707353_multidimensional_array_python_signal_processing_wavelet.txt
Q: Sharing a value using decorators I'm trying get to know decorators, and I have a problem with sharing value, because I can't change it: def my_decorator(func1,func2) : def wrapper() : a=0 func1() func2() print(a) return wrapper def first_lazy_function() : a=1 prin...
Sharing a value using decorators
I'm trying get to know decorators, and I have a problem with sharing value, because I can't change it: def my_decorator(func1,func2) : def wrapper() : a=0 func1() func2() print(a) return wrapper def first_lazy_function() : a=1 print(a) def second_lazy_function() : ...
[ "Your problem is that you are using three local variables called a, not a global variable called a\nTry first line in the script a=0 and then in every function do global a and then a=1 or a=2 \n" ]
[ 3 ]
[]
[]
[ "decorator", "python" ]
stackoverflow_0005744095_decorator_python.txt
Q: numpy: query a data from masked record? I have mask record like this In [41]: x Out[41]: masked_records( CHR : [12 12 12 ..., 12 12 12] SNP : [rs4980929 rs4980929 rs4980929 ..., rs7975069 rs7975069 rs7975069] A1 : [C C C ..., T T T] A2 : [T T T ..., C C C] TEST : [GENO TREND ALLELIC...
numpy: query a data from masked record?
I have mask record like this In [41]: x Out[41]: masked_records( CHR : [12 12 12 ..., 12 12 12] SNP : [rs4980929 rs4980929 rs4980929 ..., rs7975069 rs7975069 rs7975069] A1 : [C C C ..., T T T] A2 : [T T T ..., C C C] TEST : [GENO TREND ALLELIC ..., ALLELIC DOM REC] AFF : [51/126/92...
[ "It should be as simple a x['P'][x['TEST'] == 'GENO']\ne.g.\nimport numpy as np\n\n# Make some fake data:\nx = np.zeros(10, dtype={'names':['P', 'TEST'], 'formats':[np.int, '|S5']})\nx['P'] = np.arange(10)\nx['TEST'] = ['GENO', 'TREND', 'ALLEL', 'DOM', 'REC', \n 'GENO', 'TREND', 'DOM', 'ALLEL', 'REC']\n...
[ 2 ]
[]
[]
[ "ipython", "numpy", "python", "recarray" ]
stackoverflow_0005739521_ipython_numpy_python_recarray.txt
Q: Numpy append: Automatically cast an array of the wrong dimension is there a way to do the following without an if clause? I'm reading a set of netcdf files with pupynere and want to build an array with numpy append. Sometimes the input data is multi-dimensional (see variable "a" below), sometimes one dimensional (...
Numpy append: Automatically cast an array of the wrong dimension
is there a way to do the following without an if clause? I'm reading a set of netcdf files with pupynere and want to build an array with numpy append. Sometimes the input data is multi-dimensional (see variable "a" below), sometimes one dimensional ("b"), but the number of elements in the first dimension is always the ...
[ "You can use numpy.atleast_2d():\nresult = np.append(result, np.atleast_2d(i), axis=0)\n\nThat said, note that the repeated use of numpy.append() is a very inefficient way to build a NumPy array -- it has to be reallocated in every step. If at all possible, preallocate the array with the desired final size and pop...
[ 3, 2, 1, 0 ]
[]
[]
[ "append", "list", "numpy", "performance", "python" ]
stackoverflow_0005729850_append_list_numpy_performance_python.txt
Q: Passing data into django forms class Test(forms.Form): def set_choices(self, choices): self.choices = choices def get_choices(self): return self.choices options = forms.ChoiceField(choices=get_choices()) f = Test() f.set_choices(...) Why isn't this possible? How else can I achieve...
Passing data into django forms
class Test(forms.Form): def set_choices(self, choices): self.choices = choices def get_choices(self): return self.choices options = forms.ChoiceField(choices=get_choices()) f = Test() f.set_choices(...) Why isn't this possible? How else can I achieve the goal of passing data into class...
[ "This is a basic Python issue. You need to think about the order these commands are executed in, and their scope.\nFirst, you define a form class called Test. That class has three attributes: a set_choices method, a get_choices method, and an options field. These definitions are evaluated when the class itself is d...
[ 9, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0005744327_django_python.txt
Q: Auto-generate a interface implementation for a dbus interface in Python? Are there any tools that can read a set of DBus XML files and create a set of representative Python classes? Any embedded code generated for catching related events & initialising the interface would also be a benefit. Currently the project ...
Auto-generate a interface implementation for a dbus interface in Python?
Are there any tools that can read a set of DBus XML files and create a set of representative Python classes? Any embedded code generated for catching related events & initialising the interface would also be a benefit. Currently the project I am working on is duplicating loads of lines of code from a large exported ap...
[ "Take a look at the code generation tools in telepathy-python. Telepathy's spec XML format is a superset of the standard D-Bus introspection format; you should be able to feed plain-ish introspection XML, possibly with a few extra annotations, to those tools.\n" ]
[ 0 ]
[]
[]
[ "code_generation", "dbus", "python" ]
stackoverflow_0005098279_code_generation_dbus_python.txt
Q: Template export troubles I can't understand the right way for exporting some function into python with boost.python. I have exported this class CL_Rectf. It inherits CL_Rectx<float>. Now I want to export function bounding_rect: # In CL_Rectf class exporting .def("BoundingRect", &CL_Rectf::bounding_rect, PYPOLICY_R...
Template export troubles
I can't understand the right way for exporting some function into python with boost.python. I have exported this class CL_Rectf. It inherits CL_Rectx<float>. Now I want to export function bounding_rect: # In CL_Rectf class exporting .def("BoundingRect", &CL_Rectf::bounding_rect, PYPOLICY_REFERENCE_EXISTING) It compile...
[ "Without knowing Boost.Python in particular, it seems to me that you exported CL_Rectf, but not CL_Rectx<float>. So when asked to convert a python object into a CL_Rectx<float>, Boost.Python doesn't know how, and raises the exception you see.\nMy advice would be be to forget about CL_Floatf and export the CL_Rectx<...
[ 1 ]
[]
[]
[ "boost", "boost_python", "c++", "python" ]
stackoverflow_0005736023_boost_boost_python_c++_python.txt
Q: Getting Host field from HTTP request in BaseHTTPRequestHandler I'm writing a script using BaseHTTPRequestHandler class. And in do_GET(self) method I need to get the content of the Host field from the HTTP request. I can do it by regexping the str(self.headers) like proposed here: Determine site domain in BaseHTTPS...
Getting Host field from HTTP request in BaseHTTPRequestHandler
I'm writing a script using BaseHTTPRequestHandler class. And in do_GET(self) method I need to get the content of the Host field from the HTTP request. I can do it by regexping the str(self.headers) like proposed here: Determine site domain in BaseHTTPServer, but it's kinda ugly and I wonder if there's cleaner way to do...
[ "The attribute self.headers is a dictionary-like structure, so you can do this:\ndef do_GET(self):\n host = self.headers.get('Host')\n\nWhen the header does not exist, None is returned.\n" ]
[ 21 ]
[]
[]
[ "basehttpserver", "python" ]
stackoverflow_0005744511_basehttpserver_python.txt
Q: Taking the results of a bash command and using it in python I am trying to write a code in python that will take some information from top and put it into a file. I want to just write the name of the application and generate the file. The problem i am having is that i can't get the output of the pidof command so i...
Taking the results of a bash command and using it in python
I am trying to write a code in python that will take some information from top and put it into a file. I want to just write the name of the application and generate the file. The problem i am having is that i can't get the output of the pidof command so i can use it in python. My code looks like this : import os a = i...
[ "First up, the use of input() is discouraged as it expects the user to type in valid Python expressions. Use raw_input() instead:\napp = raw_input('Name of the application: ')\n\nNext up, the return value from system('pidof') isn't the PID, it's the exit code from the pidof command, i.e. zero on success, non-zero o...
[ 8, 2 ]
[]
[]
[ "bash", "command", "operating_system", "python" ]
stackoverflow_0005744980_bash_command_operating_system_python.txt
Q: Copy_from command to copy values of dictionary in a table I want to insert values that are stored in a dictionary into a table. This dictionary contains 1000000 values. The sample of my dictionary is : mydictationary: {"a":1; "b":2; "c":3; "d":4} I am looking forward to use copy_from command (psycopg2) to copy...
Copy_from command to copy values of dictionary in a table
I want to insert values that are stored in a dictionary into a table. This dictionary contains 1000000 values. The sample of my dictionary is : mydictationary: {"a":1; "b":2; "c":3; "d":4} I am looking forward to use copy_from command (psycopg2) to copy these values into a table. Something like: cur.copy_from (mydi...
[ "Normal way to do it:\ncur.executemany('INSERT INTO myTable (key, value) VALUES (%s, %s)', mydictionary.items())\n\nIf you insist on using StringIO\nimport StringIO\ndictFile = StringIO.StringIO()\nfor item in dictionary.iteritems():\n dictFile.write(\"%s\\t%s\\n\"%item)\ncur.copy_from(dictFile, 'myTable')\n\n" ...
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0005745052_python.txt
Q: how to assign a list object to cvmat using python interface in OpenCV? I want to fill a cvMat object using cv.SetData() using python interface in OpenCV 2.1. In C, it can be done using the code below. double a[] = {1,2,3,4,5,6,7,8,9,10,11,12}; cvMat Ma; cvInitMatHeader(&Ma,3,4,CV_64FC1,a,CV_AUTOSTEP); but in pyth...
how to assign a list object to cvmat using python interface in OpenCV?
I want to fill a cvMat object using cv.SetData() using python interface in OpenCV 2.1. In C, it can be done using the code below. double a[] = {1,2,3,4,5,6,7,8,9,10,11,12}; cvMat Ma; cvInitMatHeader(&Ma,3,4,CV_64FC1,a,CV_AUTOSTEP); but in python interface, there is no InitMatHeader function, so I try to code like this...
[ "Try passing an array.array('d', vals) or a numpy.array(vals, numpy.float64):\nimport array\nimport cv\nimport numpy\n\nar = array.array('d', range(1, 13))\nna = numpy.array(range(1, 13), numpy.float64)\nfor vals in (ar, na):\n m = cv.CreateMatHeader(3, 4, cv.CV_64FC1)\n cv.SetData(m, vals, cv.CV_AUTOSTEP)\n ...
[ 4 ]
[]
[]
[ "opencv", "python" ]
stackoverflow_0005744328_opencv_python.txt
Q: Transparency is considered as black in windows and in program I'm using the PIL python library to do some batch copy-pasting from image to image. I had it working yesterday, but suddenly when I restarted my computer, the program considers transparency as black, and also, the image pasted in uses the palette of the...
Transparency is considered as black in windows and in program
I'm using the PIL python library to do some batch copy-pasting from image to image. I had it working yesterday, but suddenly when I restarted my computer, the program considers transparency as black, and also, the image pasted in uses the palette of the image being pasted into. Hope that's not too confusing.. Here's my...
[ "To be sure your pasted region is blended with the template image using the region's alpha layer, use the mask keyword argument and use the region image as the mask. It will automatically use the alpha layer to blend.\nHere's the code:\nimport Image\nimagein = Image.open(\"png-transparency.png\")\nx, y, w, h = (0,...
[ 0 ]
[]
[]
[ "palette", "python", "python_imaging_library", "transparency" ]
stackoverflow_0005737194_palette_python_python_imaging_library_transparency.txt
Q: SQLAlchemy - INSERT OR REPLACE equivalent does anybody know what is the equivalent to SQL "INSERT OR REPLACE" clause in SQLAlchemy and its SQL expression language? Many thanks -- honzas A: What about Session.merge? Session.merge(instance, load=True, **kw) Copy the state an instance onto the persistent instance ...
SQLAlchemy - INSERT OR REPLACE equivalent
does anybody know what is the equivalent to SQL "INSERT OR REPLACE" clause in SQLAlchemy and its SQL expression language? Many thanks -- honzas
[ "What about Session.merge?\nSession.merge(instance, load=True, **kw)\n\nCopy the state an instance onto the persistent instance with the same identifier.\nIf there is no persistent instance currently associated with the session, it will be loaded. Return the persistent instance. If the given instance is unsaved, sa...
[ 9, 6, 5, 1 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0000708762_python_sqlalchemy.txt
Q: Conversion of Unicode to List type in python The below one is working properly, >>> a = 1,2 >>> a = u'[1,2]' >>> print a [1,2] >>> type(a) <type 'unicode'> >>> n = [e.encode('utf-8') for e in a.strip('[]').split(',')] >>> n ['1', '2'] >>> type(n) <type 'list'> # But when include it in the program. Instead of cha...
Conversion of Unicode to List type in python
The below one is working properly, >>> a = 1,2 >>> a = u'[1,2]' >>> print a [1,2] >>> type(a) <type 'unicode'> >>> n = [e.encode('utf-8') for e in a.strip('[]').split(',')] >>> n ['1', '2'] >>> type(n) <type 'list'> # But when include it in the program. Instead of changing the value from unicode to list, its just ch...
[ "when you make a = u'[a]' you are not using the initial variable a put inside a list but the characters '[a]' \n>> a = 1,2\n>> a = u'[what?]'\n>> print a\n[what?]\n\n", "I think, what you are looking for is unicode function\n>>> a = 1,2\n>>> a\n(1, 2)\n>>> unicode(a)\nu'(1, 2)'\n>>> a = [1,2]\n>>> unicode(a)\nu'[...
[ 2, 1, 0 ]
[]
[]
[ "mod_python", "python" ]
stackoverflow_0005743627_mod_python_python.txt
Q: Python atexit for cleaning up server running in different process -- port still in use I have some integration testing code that spawns a HTTP server in a different process for calling against. This server could potentially get polluted by activity so I'd like the ability to start and stop new instances of it on d...
Python atexit for cleaning up server running in different process -- port still in use
I have some integration testing code that spawns a HTTP server in a different process for calling against. This server could potentially get polluted by activity so I'd like the ability to start and stop new instances of it on demand. This unfortunately isn't working... I am running into a situation where the port my s...
[ "Python atexit doesn't run when you terminate a process.\n>>>import atexit\n>>> def hook():\n... print \"hook ran\"\n... \n>>> atexit.register(hook)\n<function hook at 0x100414aa0>\n>>> \n# in another terminal: kill <python process id>\n>>> Terminated\n\n", "I wound up taking a slightly different approach inspi...
[ 1, 0 ]
[]
[]
[ "multiprocessing", "python" ]
stackoverflow_0005720499_multiprocessing_python.txt
Q: can I change fixed bug from a bzr post/pre-commit hook? I would like to use a post/pre-commit hook to fill the fixed bug field of a commit. I would like to do that because we use redmine and in redmine if you put fixed #132 in your commit message, it will mark bug #132 as fixed. So to make the developer doesnt for...
can I change fixed bug from a bzr post/pre-commit hook?
I would like to use a post/pre-commit hook to fill the fixed bug field of a commit. I would like to do that because we use redmine and in redmine if you put fixed #132 in your commit message, it will mark bug #132 as fixed. So to make the developer doesnt forget to fill the fixed bug field, i would like to do it for hi...
[ "Fixed bug property saved as part of the revision metadata, so you can update this change only before actual commit. That said post-commit hook won't work for you. Pre-commit hook according to the documentation invoked \"after a commit is calculated but before it is completed\". Actually at this stage new revision ...
[ 1 ]
[]
[]
[ "bazaar", "hook", "python" ]
stackoverflow_0005743936_bazaar_hook_python.txt
Q: python, saving changes made to an imported module I have a situation where users can pick another method from another clases and use it in thier own class using the .im_func. i give an example below import foo1 import foo2 foo1.ClassX.methodX = foo2.ClassX.methodX.im_func Where methodX could be implemented diffe...
python, saving changes made to an imported module
I have a situation where users can pick another method from another clases and use it in thier own class using the .im_func. i give an example below import foo1 import foo2 foo1.ClassX.methodX = foo2.ClassX.methodX.im_func Where methodX could be implemented differently in both modules. When i instantiate the object s...
[ "saving it as new py could be a problem but you can easily use serialization for it (pickle module) \nsee: http://docs.python.org/library/pickle.html\n", "The source code can be retrieved with inspect module. However, the problem with that is, that it's the original source code, not source code of dynamically mod...
[ 0, 0, 0 ]
[]
[]
[ "python", "savechanges" ]
stackoverflow_0005744816_python_savechanges.txt
Q: sqlalchemy self referential relationship not including 'self' I have a simple data structure, where a film table has a foreign key to country table. In order to retrieve all the films that are from the same country, I have this property 'same_country_films', a self-referential relationship. It almost does the job ...
sqlalchemy self referential relationship not including 'self'
I have a simple data structure, where a film table has a foreign key to country table. In order to retrieve all the films that are from the same country, I have this property 'same_country_films', a self-referential relationship. It almost does the job correctly, however, it also includes the film itself in the list. H...
[ "The simplest solution is to code this property yourself instead of relation:\nclass Film(object):\n @property\n def same_country_films(self):\n return [f for f in self.country.films if f!=self]\n\nThis solution won't do separate query for this property when both film.same_country_films and country.fil...
[ 3, 0 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0005666732_python_sqlalchemy.txt
Q: Replace tag with another in Python Django I have working with Python and I have some questions: I am using BeautifulSoup I want to replace an HTML tag with another one. Here is code example: html = BeautifulSoup(p) x = html.find('a', attrs={'href':'/slideshow'}) while x: ...
Replace tag with another in Python Django
I have working with Python and I have some questions: I am using BeautifulSoup I want to replace an HTML tag with another one. Here is code example: html = BeautifulSoup(p) x = html.find('a', attrs={'href':'/slideshow'}) while x: print 'x unchanged - ', x x=x...
[ "here is a solution to your problem:\nhtml = BeautifulSoup(p)\nanchors = html.findAll('a', href='/slideshow')\n\nfor anchor in anchors:\n anchor['href'] = '/slideshow_v2'\n\nprint html.findAll('a', href='/slideshow_v2')\n\nTake into acount please that this is not a Django related question.\nGood luck!\n" ]
[ 1 ]
[]
[]
[ "beautifulsoup", "python", "replace" ]
stackoverflow_0005744608_beautifulsoup_python_replace.txt
Q: What are the rules about default parameters in Python? I came across something today that I considered very odd. >>> import StringIO >>> def test(thing=StringIO.StringIO()): ... thing.write("test") ... print thing.getvalue() ... >>> test() test >>> test() testtest >>> test() testtesttest >>> test() testtestte...
What are the rules about default parameters in Python?
I came across something today that I considered very odd. >>> import StringIO >>> def test(thing=StringIO.StringIO()): ... thing.write("test") ... print thing.getvalue() ... >>> test() test >>> test() testtest >>> test() testtesttest >>> test() testtesttesttest >>> test() testtesttesttesttest Before today I would...
[ "Your second definition is perfectly correct. This behavior will happen with any mutable object. The common idiom is to use None as a guard.\ndef test(thing=None):\n if thing is None:\n thing = StringIO.StringIO()\n thing.write(\"test\")\n print thing.getvalue()\n\nSee this answer on Python 2.x gotc...
[ 4, 2 ]
[]
[]
[ "programming_languages", "python" ]
stackoverflow_0005746152_programming_languages_python.txt
Q: Python Resources Is there anyway to incorporate a "resources" folder with .exe's inside of it, with my python program?? I basically want to bundle .exe's with my .py file... My python program depends on these executables... If this isn't possible, would it be possible to convert .exe to .py??? A: For the first o...
Python Resources
Is there anyway to incorporate a "resources" folder with .exe's inside of it, with my python program?? I basically want to bundle .exe's with my .py file... My python program depends on these executables... If this isn't possible, would it be possible to convert .exe to .py???
[ "For the first one, yes. Just put it in a known subdirectory and manipulate __file__ with os.path to get the path to pass to subprocess.\nFor the second... no. Just no.\n" ]
[ 1 ]
[]
[]
[ "python", "resources" ]
stackoverflow_0005746621_python_resources.txt
Q: How are listproperty fields ordered in App Engine? I am planning to store some data in a listproperty and want to be sure that the order of the items in the list remains the same when I query my entity back out. Is there such a guarantee when putting and getting data from the datastore? To be clear, I am not tryi...
How are listproperty fields ordered in App Engine?
I am planning to store some data in a listproperty and want to be sure that the order of the items in the list remains the same when I query my entity back out. Is there such a guarantee when putting and getting data from the datastore? To be clear, I am not trying to order a set of results by anything in the listprop...
[ "The statement from the documentation is:\n\nOrder is generally preserved, so when entities are returned by queries and get(), the list properties values are in the same order as when they were stored. There's one exception to this: Blob and Text values are moved to the end of the list; however, they retain their o...
[ 4, 1 ]
[]
[]
[ "google_app_engine", "google_cloud_datastore", "python" ]
stackoverflow_0005745178_google_app_engine_google_cloud_datastore_python.txt
Q: calling python script from ajax got: malformed header from script. Bad header I am writting a application using jquery(ajax) and python. When I send the request using ajax to call a php script, everything works. But when I tried to call a python script, I got this error. malformed header from script. Bad header=A...
calling python script from ajax got: malformed header from script. Bad header
I am writting a application using jquery(ajax) and python. When I send the request using ajax to call a php script, everything works. But when I tried to call a python script, I got this error. malformed header from script. Bad header=AAAAAA I am not sure what I am missing. The only difference is the type of script aj...
[ "PHP was designed for web programming so it automatically attaches Content-type to HTTP headers but Python doesn't. Prepend this to main():\nprint \"Content-Type: text/html\\n\"\n\n" ]
[ 17 ]
[]
[]
[ "jquery", "python" ]
stackoverflow_0005746745_jquery_python.txt
Q: Python subprocess reading Having this code p = subprocess.Popen('tail -f /var/log/syslog', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) for line in p.stdout.readlines(): print line, time.sleep(1) The script hangs and does not write any lines even if I add something to syslog. Why? A: ...
Python subprocess reading
Having this code p = subprocess.Popen('tail -f /var/log/syslog', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) for line in p.stdout.readlines(): print line, time.sleep(1) The script hangs and does not write any lines even if I add something to syslog. Why?
[ "readlines() will not return until there is an eof on the process, which there won't be as tail never finishes without an interrupt.\nYou could change your loop to:\nwhile True:\n print(p.stdout.readline())\n\nUnless you want an additional 1s gap between each line., there is no need for a sleep as readline will ...
[ 5, 2 ]
[]
[]
[ "python", "subprocess" ]
stackoverflow_0005745471_python_subprocess.txt
Q: BeautifulSoup findall with class attribute- unicode encode error I am using BeautifulSoup to extract news stories(just the titles) from Hacker News and have this much up till now- import urllib2 from BeautifulSoup import BeautifulSoup HN_url = "http://news.ycombinator.com" def get_page(): page_html = urllib...
BeautifulSoup findall with class attribute- unicode encode error
I am using BeautifulSoup to extract news stories(just the titles) from Hacker News and have this much up till now- import urllib2 from BeautifulSoup import BeautifulSoup HN_url = "http://news.ycombinator.com" def get_page(): page_html = urllib2.urlopen(HN_url) return page_html def get_stories(content): ...
[ "Because BeautifulSoup works internally with unicode strings. Printing unicode strings to the console will cause Python to try the conversion of unicode to the default encoding of Python which is usually ascii. This will in general fail for non-ascii web-site. You may learn the basics about Python and Unicode by go...
[ 6, 1, 0 ]
[]
[]
[ "beautifulsoup", "python" ]
stackoverflow_0005746888_beautifulsoup_python.txt
Q: Optimal group selection from a dictionary Python So I have a dictionary with key:value(tuple). Something like this. {"name":(4,5),....} where (4,5) represents two categories (cat1, cat2). Given a maximum number for the second category, I would like to find the optimal combination of dictionary entries such that th...
Optimal group selection from a dictionary Python
So I have a dictionary with key:value(tuple). Something like this. {"name":(4,5),....} where (4,5) represents two categories (cat1, cat2). Given a maximum number for the second category, I would like to find the optimal combination of dictionary entries such that the 1st category is maximized or minimized. For example,...
[ "As Jochen Ritzel pointed out, this can be seen as an instance of the knapsack problem.\nTypically, you have a set of objects that have both \"weight\" (the \"second category\", in your example) and \"value\" (or \"cost\", if it is a minimization problem).\nThe problem consists in picking a subset of the objects su...
[ 1 ]
[]
[]
[ "algorithm", "python" ]
stackoverflow_0005746689_algorithm_python.txt
Q: Tkinter Frame adding itself to main window I have a program that is suppose to create a new Toplevel widget and then add a frame to it. Both the toplevel and frame classes are already created separately so when they are called my window fills automatically. But when the button is clicked the Toplevel window pops u...
Tkinter Frame adding itself to main window
I have a program that is suppose to create a new Toplevel widget and then add a frame to it. Both the toplevel and frame classes are already created separately so when they are called my window fills automatically. But when the button is clicked the Toplevel window pops up but the frame adds itself to the main window a...
[ "The bottom line is, your frame must be created as a descendant of a specific toplevel. You can't reparent a frame from one toplevel to another. So, for your code to work you must create the toplevel first, and then create your frame and tell it which toplevel to be created in.\n" ]
[ 1 ]
[]
[]
[ "frame", "python", "tkinter" ]
stackoverflow_0005747152_frame_python_tkinter.txt
Q: Python package structure I have a Python package with several subpackages. myproject/ __init__.py models/ __init__.py ... controllers/ __init__.py .. scripts/ __init__.py myscript.py Within myproject.scripts.myscript, how can I access myproject.models? I've tried from myproject im...
Python package structure
I have a Python package with several subpackages. myproject/ __init__.py models/ __init__.py ... controllers/ __init__.py .. scripts/ __init__.py myscript.py Within myproject.scripts.myscript, how can I access myproject.models? I've tried from myproject import models # No module named ...
[ "This is the correct version:\nfrom myproject import models\n\nIf it fails with ImportError: No module named foo it is because you haven't set PYTHONPATH to include the directory which contains myproject/.\nI'm afraid other people will suggest tricks to let you avoid setting PYTHONPATH. I urge you to disregard the...
[ 20, 2 ]
[]
[]
[ "package", "python" ]
stackoverflow_0005747598_package_python.txt
Q: terminal input not appearing import subprocess import threading import time class terminal(threading.Thread): def run(self): self.prompt() def prompt(self): x = True while x: command = raw_input() x = self.interpret(command) def interpret(self,command)...
terminal input not appearing
import subprocess import threading import time class terminal(threading.Thread): def run(self): self.prompt() def prompt(self): x = True while x: command = raw_input() x = self.interpret(command) def interpret(self,command): if command == 'exit': ...
[ "raw_input takes the prompt text as a parameter, and defaults to an empty string. Try changing it to raw_input(\"input: \") or something like that.\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0005747682_python.txt
Q: Showing Django Admin actions on template I'm currently building a dashboard for my project and I would like the admin or super user to be able to see all the actions that have been down so far, sort of like an activity log. For example: User A has created a new project object Is there any way to pull the django a...
Showing Django Admin actions on template
I'm currently building a dashboard for my project and I would like the admin or super user to be able to see all the actions that have been down so far, sort of like an activity log. For example: User A has created a new project object Is there any way to pull the django admin actions and place them on a template (my ...
[ "URLs:\n(r'^dashboard$', 'dashboard_view'),\n\nView:\nfrom django.contrib.admin.models import LogEntry\ndef dashboard_view(request):\n log = LogEntry.objects.select_related().all().order_by(\"id\")\n return render_to_response(\"app_name/dashboard.html\", {'log': log},)\n\nTemplate:\n{% for l in log %}\n<p>\n ...
[ 3 ]
[]
[]
[ "django", "django_admin", "django_templates", "python" ]
stackoverflow_0005746624_django_django_admin_django_templates_python.txt
Q: Is there a problem with inheriting from threading.Thread without actually starting the thread? I've created a Python class which inherits from threading.Thread, instances of which may not actually be run as a new thread (because the start() method is never invoked). The code has been written such that it works whe...
Is there a problem with inheriting from threading.Thread without actually starting the thread?
I've created a Python class which inherits from threading.Thread, instances of which may not actually be run as a new thread (because the start() method is never invoked). The code has been written such that it works whether start() has been invoked or not (just in a slightly different way). This is entirely intentiona...
[ "In my view a slightly cleaner design would be to not inherit your class from threading.Thread, but keep its run method as-is.\nNow:\n\nif you don't need threading, you can continue to use your class as you do currently;\nif you do need threading, create a new Thread object, setting the target= constructor argument...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0005747643_python.txt
Q: Converting text containing COMBINING DIAERESIS to utf-8 We hav some text containing german umlauts represented using e.g. 'a' + COMBINING DIAERESIS ($cc $88). Any idea how to convert such text properly to utf8? A: First, if it's not already a unicode then decode it. Second, unicodedata.normalize(). Third, encode...
Converting text containing COMBINING DIAERESIS to utf-8
We hav some text containing german umlauts represented using e.g. 'a' + COMBINING DIAERESIS ($cc $88). Any idea how to convert such text properly to utf8?
[ "First, if it's not already a unicode then decode it. Second, unicodedata.normalize(). Third, encode.\n" ]
[ 5 ]
[]
[]
[ "python", "unicode", "utf_8" ]
stackoverflow_0005748010_python_unicode_utf_8.txt
Q: Python iterations Has anybody any idea why this code fails to run smooth? It seems not to like iterations with the yield keyword: I am trying to mine all the numbers from any level of lists or dicts ( especially interested in lists ). At the second iteration it finds [2,3] but fails to print 2 and 3 one after othe...
Python iterations
Has anybody any idea why this code fails to run smooth? It seems not to like iterations with the yield keyword: I am trying to mine all the numbers from any level of lists or dicts ( especially interested in lists ). At the second iteration it finds [2,3] but fails to print 2 and 3 one after other...Imagine also that I...
[ "You should 're-yield' the generator to iterate through all list elements recursively.\nif isDict(each) or isList(each):\n for elem in digIn(each):\n yield elem\nelse:\n yield each\n\n", "digIn(each) is incorrect. You must iterate over it, and yield each value in turn.\n", "When you recursively ...
[ 1, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0005748094_python.txt
Q: Python matplotlib contour plot logarithmic color scale I have problems with a contour-plot using logarithmic color scaling. I want to specify the levels by hand. Matplotlib, however, draws the color bar in a strange fashion -- the labels are not placed well and only one color appears. The idea is based on http://a...
Python matplotlib contour plot logarithmic color scale
I have problems with a contour-plot using logarithmic color scaling. I want to specify the levels by hand. Matplotlib, however, draws the color bar in a strange fashion -- the labels are not placed well and only one color appears. The idea is based on http://adversus.110mb.com/?cat=8 Is there anybody out there, who can...
[ "So it's easily fixed; your order of levels means that the lowest level gets drawn last and therefore covered everything! \nTry:\naxim = ax.contourf(X,Y,Z,levels=[1e-3, 1e-2, 1e-1, 1e0],cmap=plt.cm.jet,norm = LogNorm())\n\ninstead and you should get the desired result.\n", "It looks like levels expects increas...
[ 14, 2 ]
[]
[]
[ "contour", "logging", "matplotlib", "plot", "python" ]
stackoverflow_0005748076_contour_logging_matplotlib_plot_python.txt
Q: How to retrieve all local variables of another module? I am receiving a module as a parameter and I would like to retrieve all of it's local variables (nothing that relates to XXX or a function or a class). How can that be done? I have tried: def _get_settings(self, module): return [setting for setting...
How to retrieve all local variables of another module?
I am receiving a module as a parameter and I would like to retrieve all of it's local variables (nothing that relates to XXX or a function or a class). How can that be done? I have tried: def _get_settings(self, module): return [setting for setting in dir(module) if not inspect.ismodule(setting) and not ins...
[ "dir() returns a list of strings. Use setting.startswith() directly.\n", "You can access all of the local variables with dir(). This returns a list of strings, where each string is the name of the attribute. This returns all of the variables as well as the methods. If you are looking specifically for just the in...
[ 2, 2 ]
[]
[]
[ "python" ]
stackoverflow_0005748448_python.txt
Q: What is the standard Python module for SQL queries? I am wondering what is the standard Python module for SQL queries? I am writing queries for an Oracle database in particular. I am looking to write quick, easy, and direct queries, in the context of both scripts and small programs. A: Each SQL database has the...
What is the standard Python module for SQL queries?
I am wondering what is the standard Python module for SQL queries? I am writing queries for an Oracle database in particular. I am looking to write quick, easy, and direct queries, in the context of both scripts and small programs.
[ "Each SQL database has their own module which implements DB-API 2.0. Oracle uses cx_Oracle.\n", "DB-API is the standard API for accessing SQL databases from Python.\nThe following page provides further information: http://wiki.python.org/moin/DatabaseProgramming/\n" ]
[ 10, 0 ]
[]
[]
[ "oracle", "python", "sql" ]
stackoverflow_0005748610_oracle_python_sql.txt
Q: Object has no attribute 'prepare' In my django project, I have 4 models that are all tied together in a chain. Model_D > Model_C > Model_B > Model_A So Model_C has a foreign key field that points to Model_B, and Model_B has a foreign key field that points to Model_A When I do a lookup like below, I get the followi...
Object has no attribute 'prepare'
In my django project, I have 4 models that are all tied together in a chain. Model_D > Model_C > Model_B > Model_A So Model_C has a foreign key field that points to Model_B, and Model_B has a foreign key field that points to Model_A When I do a lookup like below, I get the following error Model_D.objects.filter(model_c...
[ "http://code.djangoproject.com/ticket/13640\nThis error arises when you define a method on a model with the name 'evaluate'. Renaming the method solves the problem.\n" ]
[ 2 ]
[]
[]
[ "django", "django_models", "prepare", "python" ]
stackoverflow_0005734111_django_django_models_prepare_python.txt
Q: tail multiple logfiles in python This is probably a bit of a silly excercise for me, but it raises a bunch of interesting questions. I have a directory of logfiles from my chat client, and I want to be notified using notify-osd every time one of them changes. The script that I wrote basically uses os.popen to run...
tail multiple logfiles in python
This is probably a bit of a silly excercise for me, but it raises a bunch of interesting questions. I have a directory of logfiles from my chat client, and I want to be notified using notify-osd every time one of them changes. The script that I wrote basically uses os.popen to run the linux tail command on every one o...
[ "Not even looking at your source code, there are two ways you could easily do this more efficiently and handle multiple files.\n\nDon't bother running tail unless you have to. Simply os.stat all of the files and record the last modified time. If the last modified time is different, then raise a notification. \nUse...
[ 9, 4, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005725051_python.txt
Q: Getting Fabric Python Library to Work I installed Fabric via Pip, which was installed via Homebrew (OS X 10.6.6). The Fabric library is where pip says it should be, however I cannot get a basic fabfile going. I've tried the simple hello world example found here: http://docs.fabfile.org/en/1.0.1/tutorial.html Bash ...
Getting Fabric Python Library to Work
I installed Fabric via Pip, which was installed via Homebrew (OS X 10.6.6). The Fabric library is where pip says it should be, however I cannot get a basic fabfile going. I've tried the simple hello world example found here: http://docs.fabfile.org/en/1.0.1/tutorial.html Bash gives me the following error when I try fab...
[ "When you install Fabric with Homebrew and Pip, fab gets put at /usr/local/Cellar/python/2.7.1/bin/fab. Make sure /usr/local/Cellar/python/2.7.1/bin is on your PATH.\n" ]
[ 6 ]
[]
[]
[ "fabric", "homebrew", "pip", "python" ]
stackoverflow_0005749596_fabric_homebrew_pip_python.txt
Q: A Django question about redirect I've a page at / that displays a form for signup new users. When a new user registers, it will redirect to /dashboard. But when an authenticated user go to /, it should see the /dashboard page. The question is: should I put something like this in the home() view: if request.user.is...
A Django question about redirect
I've a page at / that displays a form for signup new users. When a new user registers, it will redirect to /dashboard. But when an authenticated user go to /, it should see the /dashboard page. The question is: should I put something like this in the home() view: if request.user.is_authenticated(): return HttpRespo...
[ "The redirect method is absolutely fine. Not sure what you mean by ugly. The redirect should take care of your URL issue as well. \n", "If I understand you correctly, you have a \"dashboard\" which is available only for authenticated users, so if not logged in user tries to enter it, he should be redirected to th...
[ 1, 0 ]
[]
[]
[ "django", "django_authentication", "python" ]
stackoverflow_0005749563_django_django_authentication_python.txt
Q: Looping through Login Credentials - Python Dictionaries Pretty new to Python and programming in general. At the moment I am trying to use a dictionary nested within a dictionary to loop through login Credentials. My Dictionary looks like this: loginCredentials = {'Company1':{'User':'UserName', 'Password':'UserPass...
Looping through Login Credentials - Python Dictionaries
Pretty new to Python and programming in general. At the moment I am trying to use a dictionary nested within a dictionary to loop through login Credentials. My Dictionary looks like this: loginCredentials = {'Company1':{'User':'UserName', 'Password':'UserPassword', 'StoreID':'StoreNum'}, 'Company2...
[ ">>> loginCredentials = {'Company1':{'User':'UserName', 'Password':'UserPassword', 'StoreID':'StoreNum'}, 'Company2':{'User':'UserName', 'Password':'UserPassword', 'StoreID':'StoreNum'}}\n>>> for company, credentials in loginCredentials.iteritems():\n... store_id = credentials[\"StoreID\"]\n... password = c...
[ 0, 0 ]
[]
[]
[ "dictionary", "for_loop", "loops", "python" ]
stackoverflow_0005749977_dictionary_for_loop_loops_python.txt
Q: Django Admin: Can I create a field that can only be used if a specific choice has been picked in a previous field on the same model? I would like to be able to set access to one field based on what was chosen in a previous field on the same model. Ideally so it can be used in the admin interface. My model looks li...
Django Admin: Can I create a field that can only be used if a specific choice has been picked in a previous field on the same model?
I would like to be able to set access to one field based on what was chosen in a previous field on the same model. Ideally so it can be used in the admin interface. My model looks like so: GENDER_CHOICES = ( ('f', 'Female'), ('m', 'Male'), ) class Animal(models.Model): name = models.CharField(max_length=25...
[ "Sounds like your going to need some javascript.\nYou can do this by adding a bit to your admin.py file.\nCheck out this:\n\nModelAdmin Media Defniitions - \n There are times where you would like\n add a bit of CSS and/or JavaScript to\n the add/change views. This can be\n accomplished by using a Media inner\n ...
[ 5 ]
[]
[]
[ "django", "python" ]
stackoverflow_0005749932_django_python.txt
Q: How to make a subclassed, custom Django form field non-required? The Django docs (http://docs.djangoproject.com/en/dev/ref/forms/fields/) say that you can create a subclass of django.forms.Field as long as it implements a clean() method and its init() method accepts the core arguments (required, label, initial, wi...
How to make a subclassed, custom Django form field non-required?
The Django docs (http://docs.djangoproject.com/en/dev/ref/forms/fields/) say that you can create a subclass of django.forms.Field as long as it implements a clean() method and its init() method accepts the core arguments (required, label, initial, widget, help_text). I was trying to use the code in the following Django...
[ "This should work, by modifying the clean method in CreditCardField (first 2 lines of method):\ndef clean(self, value):\n if not value and not self.required:\n return value\n \"\"\"Check if given CC number is valid and one of the\n card types we accept\"\"\"\n if value and (len(value) < 13 or ...
[ 1 ]
[]
[]
[ "django", "forms", "python", "required", "subclass" ]
stackoverflow_0005749966_django_forms_python_required_subclass.txt
Q: Python: Printing a list without the brackets and single quotes? I have a list full of IP addresses. I would like to iterate through the list and print each IP address. When I try doing this: def printList(theList): for item in theList: print item And the output looks like this: ['8.0.226.5'] ['8.0.2...
Python: Printing a list without the brackets and single quotes?
I have a list full of IP addresses. I would like to iterate through the list and print each IP address. When I try doing this: def printList(theList): for item in theList: print item And the output looks like this: ['8.0.226.5'] ['8.0.247.5'] ['8.0.247.71'] ['8.0.249.28'] ['8.0.249.29'] I have tried eve...
[ "Each item in the list is itself a singleton list. There's propably no reason for this - if you can't name one, go and remove them (by using re.find over re.findall or returning a single item from the list returned by re.findall), they're just redundant and cause trouble like in this case.\nRegardless, print item[0...
[ 6, 0 ]
[]
[]
[ "list", "loops", "printing", "python" ]
stackoverflow_0005750042_list_loops_printing_python.txt
Q: What is the fastest way to detect when two timestamps produce the same local time in Python? The UNIX timestamps 1289106000 and 1289109600 both represent 2010-11-07T01:00:00 in the US-East EST/EDT timezone, as a result of daylight savings time. I'm creating a dictionary-like object, keyed on timestamp, that needs...
What is the fastest way to detect when two timestamps produce the same local time in Python?
The UNIX timestamps 1289106000 and 1289109600 both represent 2010-11-07T01:00:00 in the US-East EST/EDT timezone, as a result of daylight savings time. I'm creating a dictionary-like object, keyed on timestamp, that needs to map any such pairs to the same value. Additionally, as much as we want to avoid premature opti...
[ "You could build a table, stretching as far into the past or future as you wish, with the overlapping hour for each year. It's easy to convert the timestamp to an approximate year with a simple division. Look up the tuple (start_leap_hour,end_leap_hour) from the year; if the timestamp is between them, subtract an h...
[ 2, 1 ]
[]
[]
[ "datetime", "dst", "optimization", "python" ]
stackoverflow_0005749694_datetime_dst_optimization_python.txt
Q: Invalid Django TIME_ZONE Doing a recent build, I ran Django's syncdb, and I'm getting the error: Traceback (most recent call last): File "manage.py", line 11, in <module> execute_manager(settings) File "/usr/lib/python2.6/site-packages/Django-1.3-py2.6.egg/django/core/management/__init__.py", line 438, in ...
Invalid Django TIME_ZONE
Doing a recent build, I ran Django's syncdb, and I'm getting the error: Traceback (most recent call last): File "manage.py", line 11, in <module> execute_manager(settings) File "/usr/lib/python2.6/site-packages/Django-1.3-py2.6.egg/django/core/management/__init__.py", line 438, in execute_manager utility.ex...
[ "According to the error message:\n\nValueError: Incorrect timezone\n setting: America/New_York EST5EDT\n SystemV/EST5EDT US/Eastern\n\nit seems that TIME_ZONE, in settings.py, is equal to : America/New_York EST5EDT SystemV/EST5EDT US/Eastern\nYou must write only America/New_York.\nIf it's not the case, check for ...
[ 32 ]
[]
[]
[ "django", "python" ]
stackoverflow_0005750150_django_python.txt
Q: Python import module (xlwt) from archive Let's say Tight Ars & Co. is a company with incredibly tight security policies, and lets assume I work for this company. Assume they've one task that requires a python script to write to excel files, and I find this incredibly wonderful library called xlwt. Now my script i...
Python import module (xlwt) from archive
Let's say Tight Ars & Co. is a company with incredibly tight security policies, and lets assume I work for this company. Assume they've one task that requires a python script to write to excel files, and I find this incredibly wonderful library called xlwt. Now my script is able to write to excel files, everything is ...
[ "Unless I am misunderstanding the question you should be able to obtain the source archive and simply copy the \"xlwt\" directory to the same directory as your script and it should be importable from the local directory.\n", "All setup.py typically does with any pure-Python package is copy files into a standard p...
[ 2, 2 ]
[]
[]
[ "archive", "module", "package", "python", "xlwt" ]
stackoverflow_0005749326_archive_module_package_python_xlwt.txt
Q: Capturing/Logging image related data using Django/Python I come from a ASP.Net background and taking baby steps in open source world. I have an image based application and for every image click I want to log data on server. I'm using Django/Python to host this application. My understanding is that I need to proce...
Capturing/Logging image related data using Django/Python
I come from a ASP.Net background and taking baby steps in open source world. I have an image based application and for every image click I want to log data on server. I'm using Django/Python to host this application. My understanding is that I need to process this data on client side and send to server using Ajax call...
[ "Your understanding of needing to use AJAX calls is one correct answer. \nYou could also register onclick JavaScript events for all images and have the JavaScript call a function that submits a form with the needed values for the view to process. That's sort of how ASP.net's PostBack works. The only difference is y...
[ 1 ]
[]
[]
[ "asp.net", "c#", "django", "python", "runatserver" ]
stackoverflow_0005742794_asp.net_c#_django_python_runatserver.txt
Q: Pygame image dimensions? How would I find the dimensions of an image I loaded into PyGame? I haven't found this in the sprite or surface classes. Thanks. A: Images are loaded as Surface objects, so you should be able to use Surface.get_size().
Pygame image dimensions?
How would I find the dimensions of an image I loaded into PyGame? I haven't found this in the sprite or surface classes. Thanks.
[ "Images are loaded as Surface objects, so you should be able to use Surface.get_size().\n" ]
[ 6 ]
[]
[]
[ "image", "pygame", "python" ]
stackoverflow_0005750258_image_pygame_python.txt
Q: How do I screen capture a URL with PIL? I'm trying to write a server process that will allow you to enter a URL, then every 30 min ping that URL and capture it as an image. Is this possible with a combination of something like CURL, urllib2 and PIL? A: Curl, urllib2, etc., grab the HTML code for a web page. But ...
How do I screen capture a URL with PIL?
I'm trying to write a server process that will allow you to enter a URL, then every 30 min ping that URL and capture it as an image. Is this possible with a combination of something like CURL, urllib2 and PIL?
[ "Curl, urllib2, etc., grab the HTML code for a web page. But a page doesn't look like anything on its own. Instead, a browser uses that code and renders a web page according to its own internal rules of how that code should be used. And, of course, each browser renders the page slightly differently.\nIn other words...
[ 1, 0 ]
[]
[]
[ "django", "python", "python_imaging_library" ]
stackoverflow_0005750314_django_python_python_imaging_library.txt
Q: Nested List and For Loop Consider this: list = 2*[2*[0]] for y in range(0,2): for x in range(0,2): if x ==0: list[x][y]=1 else: list[x][y]=2 print list Result: [[2,2],[2,2]] Why doesn't the result be [[1,1],[2,2]]? A: Because you are creating a list that is two references to the same subl...
Nested List and For Loop
Consider this: list = 2*[2*[0]] for y in range(0,2): for x in range(0,2): if x ==0: list[x][y]=1 else: list[x][y]=2 print list Result: [[2,2],[2,2]] Why doesn't the result be [[1,1],[2,2]]?
[ "Because you are creating a list that is two references to the same sublist\n>>> L = 2*[2*[0]]\n>>> id(L[0])\n3078300332L\n>>> id(L[1])\n3078300332L\n\nso changes to L[0] will affect L[1] because they are the same list\nThe usual way to do what you want would be\n>>> L = [[0]*2 for x in range(2)]\n>>> id(L[0])\n307...
[ 12, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005740232_python.txt
Q: Render HTML in django template (not unicode but ASCII) I understand that this is a little perverse, but I have a legacy database with some entries as formatted html. I'd like to just push this into my django templates as ASCII and let the browser display it. Django kindly converts my fields to unicode, and so th...
Render HTML in django template (not unicode but ASCII)
I understand that this is a little perverse, but I have a legacy database with some entries as formatted html. I'd like to just push this into my django templates as ASCII and let the browser display it. Django kindly converts my fields to unicode, and so the browser displays the entire text <p> </p> etc. intact. I wa...
[ "From http://docs.djangoproject.com/en/dev/ref/templates/builtins/ what you want is:\n{{ obj.text|safe }}\n\n" ]
[ 8 ]
[]
[]
[ "django", "python", "templates" ]
stackoverflow_0005750383_django_python_templates.txt
Q: PIL Check pixel that it's on with eval function Is there any way using the eval function in PIL to run through all pixels, while checking to see what each value is? The program runs through an image to see if each pixel is a certain rgb, and if it is, then it will turn that pixel into transparency. the eval functi...
PIL Check pixel that it's on with eval function
Is there any way using the eval function in PIL to run through all pixels, while checking to see what each value is? The program runs through an image to see if each pixel is a certain rgb, and if it is, then it will turn that pixel into transparency. the eval function in PIL seems it would do the job, but can my funct...
[ "Updated: Ahh, I see what you want to do. Here is an example using only PIL. It converts all white pixels to red with 50% alpha:\nimport Image\n\nimg = Image.open('stack.png').convert('RGBA')\nwidth, _ = img.size\nfor i, px in enumerate(img.getdata()):\n if px[:3] == (255, 255, 255):\n y = i / width\n ...
[ 11, 2 ]
[]
[]
[ "pixel", "python", "python_imaging_library", "rgb", "transparency" ]
stackoverflow_0005749794_pixel_python_python_imaging_library_rgb_transparency.txt
Q: display new message to new user App Engine I'm using Google App engine to allow a user to log in to the site. Once they log in, I create a token for them and use this to check whether the user is logged in. I want to be able to display a different message to first time users and a different one for returning users...
display new message to new user App Engine
I'm using Google App engine to allow a user to log in to the site. Once they log in, I create a token for them and use this to check whether the user is logged in. I want to be able to display a different message to first time users and a different one for returning users. {% ifequal cookie None %} <a href=...
[ "Assuming your user profile entity looks something like this:\nclass UserProfile(db.Model):\n UserID = db.UserProperty()\n FirstSession = db.DateTimeProperty(auto_now_add=True)\n\nTry this: \nfrom google.appengine.api import users\n\nuser = users.get_current_user()\n\nis_existing_user = UserProfile.all().fil...
[ 2, 0 ]
[]
[]
[ "django_templates", "google_app_engine", "python" ]
stackoverflow_0005747093_django_templates_google_app_engine_python.txt
Q: Python: Iterating through a dictionary gives me "int object not iterable" Here's my function: def printSubnetCountList(countList): print type(countList) for k, v in countList: if value: print "Subnet %d: %d" % key, value Here's the output when the function is called with the dictionary...
Python: Iterating through a dictionary gives me "int object not iterable"
Here's my function: def printSubnetCountList(countList): print type(countList) for k, v in countList: if value: print "Subnet %d: %d" % key, value Here's the output when the function is called with the dictionary passed to it: <type 'dict'> Traceback (most recent call last): File "compare...
[ "Try this\nfor k in countList:\n v = countList[k]\n\nOr this\nfor k, v in countList.items():\n\nRead this, please: Mapping Types — dict — Python documentation\n", "The for k, v syntax is a short form of the tuple unpacking notation, and could be written as for (k, v). This means that every element of the itera...
[ 52, 20, 2 ]
[]
[]
[ "dictionary", "loops", "python" ]
stackoverflow_0005750664_dictionary_loops_python.txt
Q: Eclipse XLRD, XLWT Import Error I downloaded the latest Enthought EPD python distribution (academic), which comes with python 2.7. I am using Eclipse as my IDE. Eclipse is set up to use this instance of Python. I ran the "images.py" example file under XLWT. "images.py": from xlwt import Workbook w = Workbook() ...
Eclipse XLRD, XLWT Import Error
I downloaded the latest Enthought EPD python distribution (academic), which comes with python 2.7. I am using Eclipse as my IDE. Eclipse is set up to use this instance of Python. I ran the "images.py" example file under XLWT. "images.py": from xlwt import Workbook w = Workbook() ws = w.add_sheet('Image') ws.insert_b...
[ "Yes, indeed, \"someone\" helped you with the answer.\nIt's nothing to do with xlrd, xlwt, xlutils, or Eclipse. \nIn general, if you put a script that does import foo into a directory named foo, Python is likely to try to import foo from that directory, and fail. \nSolution: Don't do that. Rename your script direct...
[ 1 ]
[]
[]
[ "eclipse", "python", "xlrd", "xlwt" ]
stackoverflow_0005666272_eclipse_python_xlrd_xlwt.txt
Q: Find comma space year but ignore comma year without space I am trying to read in a file and every time , year is found it prints it out. For example if it finds , 2003 it will print that out, but if it finds ,2003 it will ignore it. I originally used a split and was able to get the year to match up, but when I a...
Find comma space year but ignore comma year without space
I am trying to read in a file and every time , year is found it prints it out. For example if it finds , 2003 it will print that out, but if it finds ,2003 it will ignore it. I originally used a split and was able to get the year to match up, but when I added the , I realized that it looked at it like two different w...
[ "\nIf you want to search the file for the regex rather than match the entire file contents, remove ^ and $ from the regex.\nIf you want more than one match per file, use finditer or findall instead of search.\nUse raw string when specifying the regex: p=re.compile(r',\\s(19|20)\\d\\d')\n\nExample:\nfor m in re.find...
[ 1, 1, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0005750729_python_regex.txt
Q: Python 3.2 extremely slow when compare to Python 3.1.x I read through Python 3.2 changes and understand that it has made many improvement over 3.1. However, my exact same code with zero modification running on 3.2 is more than 10 times slower than when I run my code on 3.1.3 It took Python 3.2 six minutes to trans...
Python 3.2 extremely slow when compare to Python 3.1.x
I read through Python 3.2 changes and understand that it has made many improvement over 3.1. However, my exact same code with zero modification running on 3.2 is more than 10 times slower than when I run my code on 3.1.3 It took Python 3.2 six minutes to transfer binary content of a file to a physical device then recei...
[ "There is no obvious reason why this should be. You'll need to profile the app to see exactly what takes this additional time.\n" ]
[ 2 ]
[]
[]
[ "ctypes", "multithreading", "python", "python_3.1", "python_3.2" ]
stackoverflow_0005750494_ctypes_multithreading_python_python_3.1_python_3.2.txt
Q: Python decryption I am currently working on a homework assignment, and we have to build a function where we make a three step encryption/decryption program. One of the ciphers we have to build is a transposition/rail fence that takes a variable (n) as a number of "rails" that you'd like to have the message encrypt...
Python decryption
I am currently working on a homework assignment, and we have to build a function where we make a three step encryption/decryption program. One of the ciphers we have to build is a transposition/rail fence that takes a variable (n) as a number of "rails" that you'd like to have the message encrypted in. I've built the e...
[ "If your encryption method is correct, (someone commented that this isn't a rail cypher), the following is true:\nYou can do your encrypt like so:\n>>> def trans_encrypt(message,n):\n... return \"\".join([message[i::n] for i in range(n)])\n... \n>>> trans_encrypt(a,3)\n'adgbecf'\n\nI'll give you a hint about yo...
[ 3, 1 ]
[]
[]
[ "encryption", "python" ]
stackoverflow_0005750324_encryption_python.txt
Q: How to make Python use a path that contains colons in it? I have a program that includes an embedded Python 2.6 interpreter. When I invoke the interpreter, I call PySys_SetPath() to set the interpreter's import-path to the subdirectories installed next to my executable that contain my Python script files... like ...
How to make Python use a path that contains colons in it?
I have a program that includes an embedded Python 2.6 interpreter. When I invoke the interpreter, I call PySys_SetPath() to set the interpreter's import-path to the subdirectories installed next to my executable that contain my Python script files... like this: PySys_SetPath("/path/to/my/program/scripts/type1:/path/to...
[ "The problem you're running into is the PySys_SetPath function parses the string you pass using a colon as the delimiter. That parser sees each : character as delimiting a path, and there isn't a way around this (can't be escaped).\nHowever, you can bypass this by creating a list of the individual paths (each of w...
[ 6, 2 ]
[]
[]
[ "colon", "escaping", "path", "python" ]
stackoverflow_0005750982_colon_escaping_path_python.txt
Q: Passing a set as a parameter in Python I am trying to create a method in python (and utilizing numpy) to take a matrix A and reduce it to reduced row echelon form using the Gaussian Elimination Method. I've run into my first problem which is trying to pass a set as a parameter. For example:def gauss([A]): gets m...
Passing a set as a parameter in Python
I am trying to create a method in python (and utilizing numpy) to take a matrix A and reduce it to reduced row echelon form using the Gaussian Elimination Method. I've run into my first problem which is trying to pass a set as a parameter. For example:def gauss([A]): gets me an error which was surprising to me. Why i...
[ "JoshAdel is right (in the now dearly departed comment) that it's normally impossible to tell what's going on without some code and sample output, but in this case I think I know:\ndef gauss([A]):\n\nis not valid Python syntax. When you're declaring a function, you can't surround the parameter names with brackets. ...
[ 6, 4, 2 ]
[]
[]
[ "arrays", "matrix", "python" ]
stackoverflow_0005751418_arrays_matrix_python.txt
Q: Open Source Text Localization Library Is there an open source project that handles the process of localizing tokenized string text to other languages, and has complex handling for grammar, spelling (definite, indefinite, plural, singular), also for languages like german handling of masculine, feminine, neuter. Mos...
Open Source Text Localization Library
Is there an open source project that handles the process of localizing tokenized string text to other languages, and has complex handling for grammar, spelling (definite, indefinite, plural, singular), also for languages like german handling of masculine, feminine, neuter. Most localization frameworks do wholesale repl...
[ "To answer your question, I've not heard of any such a framework.\nFrom the limited amount that I understand and have heard about this topic, I'd say that this is beyond the state of the art ... certainly if you are trying to do this across multiple languages.\nHere are some relevant resources:\n\n\"Open-Source Sof...
[ 0 ]
[]
[]
[ "java", "javascript", "localization", "python" ]
stackoverflow_0005750281_java_javascript_localization_python.txt
Q: How to mount a network directory using python? I need to mount a directory "dir" on a network machine "data" using python on a linux machine I know that I can send the command via command line: mkdir ~/mnt/data_dir mount -t data:/dir/ ~/mnt/data_dir but how would I send those commands from a python script? A: I...
How to mount a network directory using python?
I need to mount a directory "dir" on a network machine "data" using python on a linux machine I know that I can send the command via command line: mkdir ~/mnt/data_dir mount -t data:/dir/ ~/mnt/data_dir but how would I send those commands from a python script?
[ "I'd recommend you use subprocess.checkcall.\nfrom subprocess import *\n\n#most simply\ncheck_call( 'mkdir ~/mnt/data_dir', shell=True )\ncheck_call( 'mount -t whatever data:/dir/ ~/mnt/data_dir', shell=True )\n\n\n#more securely\nfrom os.path import expanduser\ncheck_call( [ 'mkdir', expanduser( '~/mnt/data_dir' )...
[ 10, 7, 2, 1 ]
[]
[]
[ "linux", "mount", "python", "scripting" ]
stackoverflow_0002232420_linux_mount_python_scripting.txt
Q: In Python, how do I take a list and reduce it to a list of duplicates? I have a list of strings that should be unique. I want to be able to check for duplicates quickly. Specifically, I'd like to be able to take the original list and produce a new list containing any repeated items. I don't care how many times the...
In Python, how do I take a list and reduce it to a list of duplicates?
I have a list of strings that should be unique. I want to be able to check for duplicates quickly. Specifically, I'd like to be able to take the original list and produce a new list containing any repeated items. I don't care how many times the items are repeated so it doesn't have to have a word twice if there are two...
[ "This code should work:\nduplicates = set()\nfound = set()\nfor item in source:\n if item in found:\n duplicates.add(item)\n else:\n found.add(item)\n\n", "groupby from itertools will probably be useful here:\n\nfrom itertools import groupby\nduplicated=[k for (k,g) in groupby(sorted(l)) if le...
[ 20, 6, 4, 3, 2, 1, 0, 0 ]
[ "EDIT : Ok, doesn't work since you want duplicates only.\nWhith python > 2.4 :\nYou have set, just do :\nmy_filtered_list = list(set(mylist))\n\nSet is a data structure that doesn't have duplicate by nature.\nWith older Python versions :\nmy_filtered_list = list(dict.fromkeys(mylist).keys())\n\nDictionary map a uni...
[ -1 ]
[ "python" ]
stackoverflow_0000685671_python.txt
Q: can't get dbus signal listener to work in C with gnome multimedia keys I'm trying to make my own application that will listen to the media-keys in gnome using dbus. I have found a script that works in python and I'm trying to make it work by converting it to C. My c-code builds and runs correctly but it doesn't re...
can't get dbus signal listener to work in C with gnome multimedia keys
I'm trying to make my own application that will listen to the media-keys in gnome using dbus. I have found a script that works in python and I'm trying to make it work by converting it to C. My c-code builds and runs correctly but it doesn't respond to the dbus signal. this python code works: #!/usr/bin/env python """P...
[ "I solved the problem! Must call dbus_g_proxy_call with the name \"GrabMediaPlayerKeys\" (which you also can see in the python code)\nMust also register a marshaller which is done by first running this command:\nglib-genmarshal --header --body mediaplayerkeypressed.list > marshal.h\n\nand then use it in the dbus_g_...
[ 3 ]
[]
[]
[ "c", "dbus", "glib", "python", "signals" ]
stackoverflow_0005744041_c_dbus_glib_python_signals.txt
Q: Can I use a session token instead of a session? I've got a usecase called edit that seems to require a session since registration and keeping an OpenID / OAuth account isn't required. So I rolled my own authentication system med SHA1 that can check a password and now I want to know if I can implement the function ...
Can I use a session token instead of a session?
I've got a usecase called edit that seems to require a session since registration and keeping an OpenID / OAuth account isn't required. So I rolled my own authentication system med SHA1 that can check a password and now I want to know if I can implement the function to edit an article without bringing an own session ob...
[ "What you want is called a \"cookie-based session\" by libraries such as Beaker. Ideally, you should simply use Beaker or another library that provides such functionality, but in any case here's a lowdown on how they work:\nThe session data (which could just be a user identifier, or a flag indicating they have perm...
[ 1 ]
[]
[]
[ "google_app_engine", "python", "session" ]
stackoverflow_0005750653_google_app_engine_python_session.txt
Q: TypeError when using GAE Datastore and namespaces - can't retrieve entity I'm trying to retreive some OAuth information that I've stored using Datastore, but I'm getting this error when I'm instantiating my OAuthConsumer class: TypeError: __init__() got an unexpected keyword argument 'consumer_secret' This is als...
TypeError when using GAE Datastore and namespaces - can't retrieve entity
I'm trying to retreive some OAuth information that I've stored using Datastore, but I'm getting this error when I'm instantiating my OAuthConsumer class: TypeError: __init__() got an unexpected keyword argument 'consumer_secret' This is also my first time experimenting with Namespace, and I'm wondering if that has som...
[ "You're overriding the __init__ method on a Datastore Model class, and you're not passing the keyword arguments through to the parent constructor (or calling it at all!).\nAs a general rule, you shouldn't override the constructor of a Datastore Model class. It's possible to do it right, but it's tricky, and it's fa...
[ 3 ]
[]
[]
[ "google_app_engine", "namespaces", "python" ]
stackoverflow_0005751199_google_app_engine_namespaces_python.txt