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: Problem writing unicode UTF-16 data to file in python I'm working on Windows with Python 2.6.1. I have a Unicode UTF-16 text file containing the single string Hello, if I look at it in a binary editor I see: FF FE 48 00 65 00 6C 00 6C 00 6F 00 0D 00 0A 00 BOM H e l l o CR LF What I want t...
Problem writing unicode UTF-16 data to file in python
I'm working on Windows with Python 2.6.1. I have a Unicode UTF-16 text file containing the single string Hello, if I look at it in a binary editor I see: FF FE 48 00 65 00 6C 00 6C 00 6F 00 0D 00 0A 00 BOM H e l l o CR LF What I want to do is read in this file, run it through Google Translate ...
[ "I believe the output from Google is UTF-8, not UTF-16. Try this fix:\nret = unicode(b.strip('\"'), encoding='utf-8', errors='ignore') \n\n", "Those E3 bytes are not \"escape characters\". If one had no access to documentation, and was forced to make a guess, the most likely suspect for the response encoding wou...
[ 5, 2 ]
[]
[]
[ "python", "unicode" ]
stackoverflow_0005411757_python_unicode.txt
Q: MySQL AB, MySQL Server 5.5 Folder in HKEY_LOCAL_MACHINE not present I am trying to MySQL for Python (MySQLdb package) in Windows so that I can use it in the Django web frame. I have just installed MySQL Community Server 5.5.9 and I have managed to run it and test it using the testing procedures suggested in the My...
MySQL AB, MySQL Server 5.5 Folder in HKEY_LOCAL_MACHINE not present
I am trying to MySQL for Python (MySQLdb package) in Windows so that I can use it in the Django web frame. I have just installed MySQL Community Server 5.5.9 and I have managed to run it and test it using the testing procedures suggested in the MySQL 5.5 Reference Manual. However, I discovered that I still don't have t...
[ "I found that the key was actually generated under HKEY_CURRENT_USER instead of HKEY_LOCAL_MACHINE. Thanks.\n" ]
[ 2 ]
[]
[]
[ "django", "mysql", "python" ]
stackoverflow_0005059883_django_mysql_python.txt
Q: Access a variable in a method under a class in python class user_management(wx.Panel): def login(self): # Login Function can be later integrated to allow users access to your program username = self.txt_Username.GetValue() self.frame.SetStatusText("Welcome "+username+" to the system!!")...
Access a variable in a method under a class in python
class user_management(wx.Panel): def login(self): # Login Function can be later integrated to allow users access to your program username = self.txt_Username.GetValue() self.frame.SetStatusText("Welcome "+username+" to the system!!") test = MyApp(0) test.MainLoop() How can i acc...
[ "Currently username is a local variable and can't be accessed outside of the method. You could make it a member variable by doing something like self.username instead. It would probably be a good idea to initialize it in an __init__ method.\nEDIT: katrielalex has the right idea. You probably want to store the usern...
[ 4, 1 ]
[]
[]
[ "class", "global", "methods", "python", "static" ]
stackoverflow_0005412479_class_global_methods_python_static.txt
Q: Python - BeautifulSoup - HTML Parsing Here is fragment of the site code <td class='vcard' id='results100212571'> <h2 class="custom_seeMore"> <a class="fn openPreview" href="link.html">Hotel Name<span class="seeMore">See More...</span></a> </h2> <div class='clearer'></div> <div class='adr'> <span class...
Python - BeautifulSoup - HTML Parsing
Here is fragment of the site code <td class='vcard' id='results100212571'> <h2 class="custom_seeMore"> <a class="fn openPreview" href="link.html">Hotel Name<span class="seeMore">See More...</span></a> </h2> <div class='clearer'></div> <div class='adr'> <span class='postal-code'>00000</span> <span class=...
[ "According to the BeautifulSoup documentation, element.string will be None if element has multiple children.\nIn your case,\nprint element.find('a', {'class' : 'fn openPreview'}).contents[0].string\n\nwill print \"Hotel Name\".\n" ]
[ 8 ]
[]
[]
[ "beautifulsoup", "html_parsing", "python" ]
stackoverflow_0005412558_beautifulsoup_html_parsing_python.txt
Q: Asynchronous URLfetch when we don't care about the result? [Python] In some code I'm writing for GAE I need to periodically perform a GET on a URL on another system, in essence 'pinging' it and I'm not terribly concerned if the request fails, times out or succeeds. As I basically want to 'fire and forget' and not ...
Asynchronous URLfetch when we don't care about the result? [Python]
In some code I'm writing for GAE I need to periodically perform a GET on a URL on another system, in essence 'pinging' it and I'm not terribly concerned if the request fails, times out or succeeds. As I basically want to 'fire and forget' and not slow down my own code by waiting for the request, I'm using an asynchrono...
[ "A task queue task is your best option here. The message you're seeing in the log indicates that the request is waiting for your URLFetch to complete before returning, so this doesn't help. You say a task is 'overkill', but really, they're very lightweight, and definitely the best way to do this. Deferred will even...
[ 7, 2 ]
[]
[]
[ "asynchronous", "google_app_engine", "python", "urlfetch" ]
stackoverflow_0005411291_asynchronous_google_app_engine_python_urlfetch.txt
Q: Django - Inception style transaction handling I'm no transaction / database expert, so pardon my ignorance in the wording here: When you use Django's transaction.commit_on_success(func), any error that's propagated to the control of commit_on_success will roll back the transaction which is really helpful of course...
Django - Inception style transaction handling
I'm no transaction / database expert, so pardon my ignorance in the wording here: When you use Django's transaction.commit_on_success(func), any error that's propagated to the control of commit_on_success will roll back the transaction which is really helpful of course in case you need some all-or-nothing action in a m...
[ "not a final solution but an idea based on this snippet (which is good idea per se)\nthis plus savepoints can create nice solution: a decorator, which will be aware if transaction is inside other transaction (and if it is, is using savepoints instead of transactions).\n" ]
[ 2 ]
[]
[]
[ "database", "django", "python", "transactions" ]
stackoverflow_0005411232_database_django_python_transactions.txt
Q: How to keep a windows service running Below is the framework for the windows service that I am running. In the event of an error, the error is logged and can be viewed in the event viewer. The problem is that the script just quits and does not restart again even though I have the recovery set to restart the servic...
How to keep a windows service running
Below is the framework for the windows service that I am running. In the event of an error, the error is logged and can be viewed in the event viewer. The problem is that the script just quits and does not restart again even though I have the recovery set to restart the service on the first, second and subsequent failu...
[ "Below is a service that just divides by zero to raise an error. If there is an error, an event is sent and the service exits using os._exit(-1). The value has to be anything but 0 so that the windows knows that the service didn't exit nicely.\nfrom win32api import CloseHandle, GetLastError, SetConsoleCtrlHandler\n...
[ 8, 0, 0 ]
[]
[]
[ "python", "windows_services" ]
stackoverflow_0005315193_python_windows_services.txt
Q: django & jython I'm new to django and jython. So, I have a very basic question. Is it possible to run java applications using jython in django framework? I've got jython installed and django running on my machine, and I'm trying to write an applet. Many thanks in advance. A: The latest development documentation ...
django & jython
I'm new to django and jython. So, I have a very basic question. Is it possible to run java applications using jython in django framework? I've got jython installed and django running on my machine, and I'm trying to write an applet. Many thanks in advance.
[ "The latest development documentation has a complete chapter covering Django and Jython:\nhttp://docs.djangoproject.com/en/dev/howto/jython/\nAnd you can also check the python wiki on jython:\nhttp://wiki.python.org/jython/DjangoOnJython\n" ]
[ 2 ]
[]
[]
[ "django", "jython", "python" ]
stackoverflow_0005413009_django_jython_python.txt
Q: Overcoming 1mb file restriction in GAE Datastore As if for now, we are using datastore blob to store profile images of our site. And there is restriction in Datastore for storing more than 1mb file as a blob in datastore. Is there any work around for this. A: You could use the Blobstore. Google App Engine inclu...
Overcoming 1mb file restriction in GAE Datastore
As if for now, we are using datastore blob to store profile images of our site. And there is restriction in Datastore for storing more than 1mb file as a blob in datastore. Is there any work around for this.
[ "You could use the Blobstore.\n\nGoogle App Engine includes the Blobstore service, which allows apps to serve data objects that can be up to 2 gigabytes in size. These objects are called Blobstore values, or blobs. Blobstore values are served as responses from request handlers and are created as uploads via web for...
[ 5, 0 ]
[]
[]
[ "google_app_engine", "google_cloud_datastore", "python" ]
stackoverflow_0005401070_google_app_engine_google_cloud_datastore_python.txt
Q: Naming practice for optional argument in python function Is it OK to give the optional argument in a python function the same name as an outside variable? It seems to work fine as functions f and g defined below give the same output. However, is this considered bad practice and does it fail in some cases? a = 1 de...
Naming practice for optional argument in python function
Is it OK to give the optional argument in a python function the same name as an outside variable? It seems to work fine as functions f and g defined below give the same output. However, is this considered bad practice and does it fail in some cases? a = 1 def f(x,A=a): return x*A def g(x,a=a): return x*a print g(2) >>...
[ "It will work, although it can easily be a bit confusing, it is perfectly valid. This is due to the fact that the function and the call to the function happen in different namespaces. So if you write:\ndef some_function(var1,var2=somevalue): #var1 & var2 of functions namespace\n some things happening here\n\nva...
[ 2, 1 ]
[ "Stop to use the word \"variable\" in Python !\nThere are no variables in the sense of \"chunk of memory whose value can change\"\nAnd the use of \"variable\" as synonym of \"identifier\" or \"name\" is confusing;\nPleaaaase !\n", "it fails if you want to pass the variable to it.\nBut the best naming practice is ...
[ -1, -2 ]
[ "function", "optional_arguments", "python", "variables" ]
stackoverflow_0005369576_function_optional_arguments_python_variables.txt
Q: Replacing reoccuring characters in strings in Python 3.1 Is it possible to replace a single character inside a string that occurs many times? Input: Sentence=("This is an Example. Thxs code is not what I'm having problems with.") #Example input ^ Sentence=("This is an Example. Thi...
Replacing reoccuring characters in strings in Python 3.1
Is it possible to replace a single character inside a string that occurs many times? Input: Sentence=("This is an Example. Thxs code is not what I'm having problems with.") #Example input ^ Sentence=("This is an Example. This code is not what I'm having problems with.") #Desired output...
[ "You can do it by including some context:\ns = s.replace(\"Thxs\", \"This\")\n\n\nAlternatively you can keep a list of words that you don't wish to replace:\nwhitelist = ['example', 'explanation']\n\ndef replace_except_whitelist(m):\n s = m.group()\n if s in whitelist: return s\n else: return s.replace('x'...
[ 4, 0, 0 ]
[]
[]
[ "python", "replace", "string", "variables" ]
stackoverflow_0005412282_python_replace_string_variables.txt
Q: What characters are in my python identation sections in vim? I have this in my vimrc. set listchars=trail:.,tab:>-,eol:$ set nolist noremap <leader>i :set list!<CR> " Toggle invisible chars When I'm programming in Python and I run <leader>i, my identation doesn't show any characters, since it isn't trailing white...
What characters are in my python identation sections in vim?
I have this in my vimrc. set listchars=trail:.,tab:>-,eol:$ set nolist noremap <leader>i :set list!<CR> " Toggle invisible chars When I'm programming in Python and I run <leader>i, my identation doesn't show any characters, since it isn't trailing whitespace, neither tabs. Now, I'm wondering: what character exactly ar...
[ "The indentation is spaces. Trailing whitespace is whitespace with nothing but a newline after it. Indentation obviously has code after it, thus no list char.\nIn regards to your edit, you have a few options.\n\nDon't make vimdiff ignore whitespace for python files by setting diffopt with an autocmd FileType pyth...
[ 2, 1 ]
[]
[]
[ "indentation", "python", "vim" ]
stackoverflow_0005411604_indentation_python_vim.txt
Q: Writing to a stream on a PostgreSQL trigger using Python I would like to write a trigger for a PostgreSQL database which, on insertions, would notify a node.js server which would send some data to connected clients. Currently, my thought is to write a Python row insert trigger for the database which would write d...
Writing to a stream on a PostgreSQL trigger using Python
I would like to write a trigger for a PostgreSQL database which, on insertions, would notify a node.js server which would send some data to connected clients. Currently, my thought is to write a Python row insert trigger for the database which would write data to some file which would then be read by the node.js serve...
[ "Have you looked at Listen Notify functionality?\nhttp://www.postgresql.org/docs/9.0/interactive/sql-notify.html\nAlso you will want to test out different options against your needs, instead of assuming one is not fast enough for what you need. Maybe your python approach will work just fine.\n" ]
[ 1 ]
[]
[]
[ "node.js", "postgresql", "python", "triggers" ]
stackoverflow_0005413441_node.js_postgresql_python_triggers.txt
Q: How to scale an image in Python? def scaleImage(image): """ A function that takes an image and makes each pixel grayscale: the red, blue, green components are the average of the respective components in each original pixel. """ pix = image.getPixels() # How can I condense the followin...
How to scale an image in Python?
def scaleImage(image): """ A function that takes an image and makes each pixel grayscale: the red, blue, green components are the average of the respective components in each original pixel. """ pix = image.getPixels() # How can I condense the following loop? newimage = Image() fo...
[ "if you are using PIL \ngreyscaleIm = Image.open(filename).convert(\"L\")\nhttp://effbot.org/imagingbook/introduction.htm\n", "although it may be overkill depending on what your ultimate goal is. It is also possible to do it with opencv.\nimg = cv.LoadImage(image)\ngray = cv.cvCreateImage ((img.width, img.height)...
[ 3, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005413451_python.txt
Q: How do I import a COM object namespace/enumeration in Python? I'm relatively new to programming/python, so I'd appreciate any help I can get. I want to save an excel file as a specific format using Excel through COM. Here is the code: import win32com.client as win32 def excel(): app = 'Excel' x1 = win...
How do I import a COM object namespace/enumeration in Python?
I'm relatively new to programming/python, so I'd appreciate any help I can get. I want to save an excel file as a specific format using Excel through COM. Here is the code: import win32com.client as win32 def excel(): app = 'Excel' x1 = win32.gencache.EnsureDispatch('%s.Application' % app) ss = x1.Work...
[ "This question is a bit stale, but for those reaching this page from Google (as I did) my solution was accessing the constants via the win32com.client.constants object instead of on the application object itself as suggested by Eric. This lets you use enum constants just like in the VBE:\n>>> import win32com.client...
[ 9, 2, 1, 1 ]
[]
[]
[ "com", "enumeration", "excel", "namespaces", "python" ]
stackoverflow_0001646230_com_enumeration_excel_namespaces_python.txt
Q: Python Run a daemon sub-process & read stdout I need to run a program and gather its output to stdout. This program (socat) needs to run in the background for the duration of the python script. Socat sits in dameon mode once it's run, but first it outputs some lines to stdout that I need for the rest of my script....
Python Run a daemon sub-process & read stdout
I need to run a program and gather its output to stdout. This program (socat) needs to run in the background for the duration of the python script. Socat sits in dameon mode once it's run, but first it outputs some lines to stdout that I need for the rest of my script. Command: socat -d -d PTY: PTY: Output: 2011/03/23 ...
[ "#!/usr/bin/python\nfrom subprocess import Popen, PIPE, STDOUT\nimport pty\nimport os\n\ncmd = 'socat -d -d PTY: PTY:'\n\nmaster, slave = pty.openpty()\n\np = Popen(cmd, shell=True, stdin=PIPE, stdout=slave, stderr=slave, close_fds=True)\nstdout = os.fdopen(master)\nprint stdout.readline()\nprint stdout.readline()\...
[ 28, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005411780_python.txt
Q: Design help: Configurable behavior based on input I am working in Python, but this is a general design question so general answers are welcome. I will explain the context not as part of the question, but to serve as an example: I have a script which receives a CSV file, it uses the fields in this file to make aut...
Design help: Configurable behavior based on input
I am working in Python, but this is a general design question so general answers are welcome. I will explain the context not as part of the question, but to serve as an example: I have a script which receives a CSV file, it uses the fields in this file to make automated phone calls. The fields represent names to be s...
[ "I'm solving a related but not identical problem currently. \nMy solution is to create a control list of the same length as the target csv lines, where each element in the control list is the name of a useMethod. In my case the useMethod is an editor widget; in your case, it would be a function that defines how ...
[ 1 ]
[]
[]
[ "configuration", "design_patterns", "input", "python" ]
stackoverflow_0005413229_configuration_design_patterns_input_python.txt
Q: how to get a part of file path? for example I have string: test = "/var/tmp/test.log" I want to get a path of this file. A: Use os.path.dirname(): >>> import os >>> os.path.dirname('/var/tmp/test.log') '/var/tmp' A: >>> import os >>> os.path.dirname("/var/tmp/test.log") '/var/tmp' A: Which part are you ...
how to get a part of file path?
for example I have string: test = "/var/tmp/test.log" I want to get a path of this file.
[ "Use os.path.dirname():\n>>> import os\n>>> os.path.dirname('/var/tmp/test.log')\n'/var/tmp'\n\n", " >>> import os\n >>> os.path.dirname(\"/var/tmp/test.log\")\n '/var/tmp'\n\n", "Which part are you interested in? The os.path module has a lot of useful functions. If that fails, a .split(\"/\") would do the tric...
[ 5, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005406622_python.txt
Q: Python formatting large values Below is the code for formatting an x value that I have been using. Examples of what does it do: It formats 7,500,000 into 7.5 M It formats 800,000 into 800 K It def Formatting(self, x, pos): formats = ((1e-12,'%d%s T','%1.1f T'), (1e-9, '%d%s B','%1.1f B'), ...
Python formatting large values
Below is the code for formatting an x value that I have been using. Examples of what does it do: It formats 7,500,000 into 7.5 M It formats 800,000 into 800 K It def Formatting(self, x, pos): formats = ((1e-12,'%d%s T','%1.1f T'), (1e-9, '%d%s B','%1.1f B'), (1e-6, '%d%s M','%1.1f ...
[ "There's probably a shorter way to generate the format strings; but they're easy enough to just map to each magnitude. I don't fully understand the behavior you want w/r/t decimal point length, but the logic for that should be easy. \nSince what you had was a method, I incorporated this into a class. (This also avo...
[ 4, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005413985_python.txt
Q: Whats the pythonic way to convert a heterogenous list of scalars into a string I have a list which contains strings integers and floats. I want to convert it into a string and save it to file (CSV format) - I dont want to convert every field manually - but I would also prefer not to use the CSV parsing module as i...
Whats the pythonic way to convert a heterogenous list of scalars into a string
I have a list which contains strings integers and floats. I want to convert it into a string and save it to file (CSV format) - I dont want to convert every field manually - but I would also prefer not to use the CSV parsing module as it is too heavyweight for a quick and dirty script which has a format that never chan...
[ "\nI would also prefer not to use the CSV parsing module as it is too heavyweight for a quick and dirty script\n\nReally, what's the cost? A few milliseconds of runtime, or a few minutes of development time?\n\nwhich has a format that never changes\n\nThat's irrelevant. You have data that requires escaping, quoting...
[ 6, 4, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005413856_python.txt
Q: Why does this PIL call crash python? import Image from numpy import zeros, asarray YUV = zeros((240, 320, 3), dtype='uint8') im = Image.fromarray(YUV, mode="YCbCr") blah = asarray(im) When I run this (IPython 0.10.1 on Py 2.7.1) it seems to make python read some memory which it shouldn't be reading. Sometimes it...
Why does this PIL call crash python?
import Image from numpy import zeros, asarray YUV = zeros((240, 320, 3), dtype='uint8') im = Image.fromarray(YUV, mode="YCbCr") blah = asarray(im) When I run this (IPython 0.10.1 on Py 2.7.1) it seems to make python read some memory which it shouldn't be reading. Sometimes it crashes, sometimes it doesn't but I can s...
[ "I noticed that your image is YCbCr 3-channel, but you're displaying 4 channels. Turns out the \"junk data\" problem is caused by a bug in PIL's array interface, and a fix was committed in Nov 2010. PIL's array interface is returning a 4th channel. \nI ran your test case under PIL 1.1.7 and see the noise. I comment...
[ 4 ]
[]
[]
[ "arrays", "numpy", "python", "python_imaging_library" ]
stackoverflow_0005413323_arrays_numpy_python_python_imaging_library.txt
Q: What alarm/access hardware can I control from *NIX? Okay, so not strictly a programming question BUT the point is I want to integrate my new building's business access/alarm system into the rest of my *NIX setup at my business. I do NOT want to use some cruddy windows GUI program written for Windows XP SP1 that m...
What alarm/access hardware can I control from *NIX?
Okay, so not strictly a programming question BUT the point is I want to integrate my new building's business access/alarm system into the rest of my *NIX setup at my business. I do NOT want to use some cruddy windows GUI program written for Windows XP SP1 that manages a bare circuit-board via a serial connection and p...
[ "What is you physical location? If europe you could have a look at EIB-Technologies. Just google for EIB and you'll see many answers for your question. EIB stands for European Installation Bus. It is a technology used for controlling almost everything in buildings (light, alarms, aircon, etc...) using a bus and cen...
[ 1, 1, 0, 0 ]
[]
[]
[ "api", "hardware", "python" ]
stackoverflow_0004703978_api_hardware_python.txt
Q: customize select in django admin I have a model, one field of it is a ForeignKey, so i see select in django admin, is it possiable to customize labels of this select? class Model(models.Model): name = models.CharField() def __unicode__(self): return self.name class Part(models.Model): name ...
customize select in django admin
I have a model, one field of it is a ForeignKey, so i see select in django admin, is it possiable to customize labels of this select? class Model(models.Model): name = models.CharField() def __unicode__(self): return self.name class Part(models.Model): name = models.CharField() parent = mo...
[ "If you mean the field label:\nusing code from:\nDjango Admin - Overriding the widget of a custom form field\n# forms.py\n\nfrom django import forms\nfrom django.contrib import admin\n\nclass ProductAdminForm(forms.ModelForm):\n def __init__(self, *args, **kwargs):\n super(ProductAdminForm, self).__init__...
[ 12 ]
[]
[]
[ "customization", "django", "django_admin", "python" ]
stackoverflow_0005414853_customization_django_django_admin_python.txt
Q: How to strip unicode "punctuation" from Python string Here's the problem, I have a unicode string as input to a python sqlite query. The query failed ('like'). It turns out the string, 'FRANCE' doesn't have 6 characters, it has seven. And the seventh is . . . unicode U+FEFF, a zero-width no-break space. How on ear...
How to strip unicode "punctuation" from Python string
Here's the problem, I have a unicode string as input to a python sqlite query. The query failed ('like'). It turns out the string, 'FRANCE' doesn't have 6 characters, it has seven. And the seventh is . . . unicode U+FEFF, a zero-width no-break space. How on earth do I trap a class of such things before the query?
[ "You may use the unicodedata categories as part of the unicode data table in Python:\n>>> unicodedata.category(u'a')\n'Ll'\n>>> unicodedata.category(u'.')\n'Po'\n>>> unicodedata.category(u',')\n'Po'\n\nThe categories for punctation characters start with 'P' as you can see.\nSo you need to filter you out char by cha...
[ 11, 1, 0 ]
[]
[]
[ "punctuation", "python", "unicode" ]
stackoverflow_0005414818_punctuation_python_unicode.txt
Q: How to use python re module to filter the int number by digital I want to use python re module to filter the int number by the number digital. 1 700 76093 71365 35837 75671 ^^ ||--------------------- this position should not be 6,7,8,9,0 |---------------------- this position should not b...
How to use python re module to filter the int number by digital
I want to use python re module to filter the int number by the number digital. 1 700 76093 71365 35837 75671 ^^ ||--------------------- this position should not be 6,7,8,9,0 |---------------------- this position should not be 5,6,7 Code: int_list=[1,700,76093,71365,35837,75671] str_list = [s...
[ "Are you sure you want to be using the re module? You can get at what you're trying to do with some simple math operations.\ndef valid_number(n):\n return 0 < n%1000/100 < 6 and not 5 >= n%10000/1000 >= 7\n\nint_list = [1,700,76093,71365,35837,75671,]\nresult = [x for x in int_list if valid_number(x)]\n\nor alte...
[ 4, 1 ]
[]
[]
[ "digital", "filter", "int", "python", "regex" ]
stackoverflow_0005414705_digital_filter_int_python_regex.txt
Q: How to check contents of incoming HTTP header request I'm playing around with some APIs and I'm trying to figure this out. I am making a basic HTTP authenticated request to my server via the API. As part of this request, the authenticated key is stored in the HTTP header as username. So my question is, how do I ...
How to check contents of incoming HTTP header request
I'm playing around with some APIs and I'm trying to figure this out. I am making a basic HTTP authenticated request to my server via the API. As part of this request, the authenticated key is stored in the HTTP header as username. So my question is, how do I get the contents of the incoming request such that I can pe...
[ "http://docs.djangoproject.com/en/dev/ref/request-response/\nHttpRequest.META\nA standard Python dictionary containing all available HTTP headers. \nAvailable headers depend on the client and server, but here are some examples:\n\n CONTENT_LENGTH\n CONTENT_TYPE\n HTTP_ACCEPT_ENCODING\n H...
[ 6, 2 ]
[]
[]
[ "basic_authentication", "django", "http_headers", "python" ]
stackoverflow_0005414687_basic_authentication_django_http_headers_python.txt
Q: Splitting a string? Possible Duplicate: Splitting a string into a list in python I'd like to take user input and break it apart character by character. Basically I have this string = raw_input("String: ") print string Now I want to split each of these letters and put them into a list. So lets say I input hello...
Splitting a string?
Possible Duplicate: Splitting a string into a list in python I'd like to take user input and break it apart character by character. Basically I have this string = raw_input("String: ") print string Now I want to split each of these letters and put them into a list. So lets say I input hello, I get a list like ['h'...
[ "Just convert this string to a list. It is already an iterable sequence of individual characters so the conversion is automatic.\nstring = raw_input(\"String: \")\nprint(list(string))\n\n", "You usually don't need to, since strings are iterable regardless. But:\nprint list('hello')\n\n", "s = [c for c in strin...
[ 3, 2, 0 ]
[]
[]
[ "list", "python", "split", "string" ]
stackoverflow_0005413764_list_python_split_string.txt
Q: Virtual Machine implemented in assembly on an x86 I was just wondering if anybody here has written or knows where I can find a simple virtual machine written in x86 assembly, preferably Fasm, but anything would serve as an example as long as it is simple or at least well commented. Thank you in advance. A: A VM ...
Virtual Machine implemented in assembly on an x86
I was just wondering if anybody here has written or knows where I can find a simple virtual machine written in x86 assembly, preferably Fasm, but anything would serve as an example as long as it is simple or at least well commented. Thank you in advance.
[ "A VM written in FASM? Hmm, the closest project that I can think of is RevaForth, an implementation of Forth originally written in FASM. The author has since switched to NASM, but that is not much different from FASM.\n", "I did something like that in the past for a software protection. A great resource is defini...
[ 4, 1 ]
[]
[]
[ "assembly", "fasm", "python", "vm_implementation" ]
stackoverflow_0005414884_assembly_fasm_python_vm_implementation.txt
Q: Python - How to group variables separated by or/and operators I am trying to find a way to make the following (sample) code more elegant: if answer == "yes" or "Yes" or "Y" or "y" or "why not": print("yeah") In the same manner there in english you would not say: The possible answers are yes or Yes or Y or wh...
Python - How to group variables separated by or/and operators
I am trying to find a way to make the following (sample) code more elegant: if answer == "yes" or "Yes" or "Y" or "y" or "why not": print("yeah") In the same manner there in english you would not say: The possible answers are yes or Yes or Y or why not. and you would rather say: The possible answers are yes, Ye...
[ "Option 1: answer in [\"yes\", \"Yes\", \"Y\", \"y\", \"why not\"] ... not a good idea, builds a list each time you run it.\nOption 2: answer in (\"yes\", \"Yes\", \"Y\", \"y\", \"why not\") ... better idea, the (constant, immutable) tuple is built at compile time.\nOption 3: do this once: \nallowables = set([\"yes...
[ 6, 3, 1 ]
[]
[]
[ "operators", "python" ]
stackoverflow_0005415212_operators_python.txt
Q: I upgraded Python 2.5 to 2.6 but now get "ImportError: No module named tagging.views" THE ISSUE The problem: it seems like the tagging module which I have in my /srv/python-environments/saltycrane/lib/python2.5/site-packages/tagging is not being included because I upgraded the system to 2.6, despite my assumption ...
I upgraded Python 2.5 to 2.6 but now get "ImportError: No module named tagging.views"
THE ISSUE The problem: it seems like the tagging module which I have in my /srv/python-environments/saltycrane/lib/python2.5/site-packages/tagging is not being included because I upgraded the system to 2.6, despite my assumption of relying on 2.5 in virtualenv mode. Here's the error in /var/log/apache2/error.log: [Thu ...
[ "I think if you changed this it might work:\nALLDIRS = [os.path.join(virtualenv, 'lib', 'python%s' % sys.version[:3], 'site-packages')]\nto\nALLDIRS = [os.path.join(virtualenv, 'lib', 'python2.5', 'site-packages')]\nSetting your WSGIPythonHome is what is suggested when using virtualenv with modwsgi:\nvirtualenv --n...
[ 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0005415269_django_python.txt
Q: How can I modify a file while other threads read from it? I'm multithreading data (both reading and writing) into/from a single text file. I need to be able to replace or remove text from this file without replacing the actual file. I cannot simply .read() into a string, then .write() a new file with the same name...
How can I modify a file while other threads read from it?
I'm multithreading data (both reading and writing) into/from a single text file. I need to be able to replace or remove text from this file without replacing the actual file. I cannot simply .read() into a string, then .write() a new file with the same name, because other threads are still using that file. I cannot .wr...
[ "Bad idea. Use another thread which is sole responsible for writing/reading into the file. Or read the file into memory if it is not too big.\n", "Sure it's possible, but probably only useful if you were reading/writing into the file in a uniform way. When I say uniform, you should treat the file as blocks of da...
[ 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0005415720_python.txt
Q: google app engine form validation with css in python I have been looking at form validation in python using Django as this seems to be the default way to do it, other than checking each field, performing some validation and kicking out a specific message for each field that is badly formed. Ideally I want the bene...
google app engine form validation with css in python
I have been looking at form validation in python using Django as this seems to be the default way to do it, other than checking each field, performing some validation and kicking out a specific message for each field that is badly formed. Ideally I want the benefits of form validation, but I do not know how to couple t...
[ "\"Customizing Form Design\" section of http://www.djangobook.com/en/2.0/chapter07/ explains how to style forms to go with your HTML and CSS.\n", "Looking at those references etc http://www.djangobook.com/en/2.0/chapter07/, I have been unable to come up with a good way to couple everything together. The problem r...
[ 1, 0 ]
[]
[]
[ "google_app_engine", "python", "validation" ]
stackoverflow_0005403104_google_app_engine_python_validation.txt
Q: encoding problem in Python when urlopen() a gbk page My code here: # coding:utf-8 if __name__ == '__main__': from urllib2 import urlopen url = 'http://iccna.blog.sohu.com/164572951.html' data = urlopen(url).read() soup = BeautifulSoup(data,fromEncoding='gb18030') print WebExtractor(soup) but ...
encoding problem in Python when urlopen() a gbk page
My code here: # coding:utf-8 if __name__ == '__main__': from urllib2 import urlopen url = 'http://iccna.blog.sohu.com/164572951.html' data = urlopen(url).read() soup = BeautifulSoup(data,fromEncoding='gb18030') print WebExtractor(soup) but when debugging, the data like this: ��5h�,��4�H�5��VM��\ ...
[ "The problem is that the server returns the data compressed by Gzip. Try this:\n#-*- coding: utf-8 -*-\nfrom __future__ import print_function\n\nimport gzip\nimport StringIO\nimport urllib2\nfrom BeautifulSoup import BeautifulSoup\n\nurl = 'http://iccna.blog.sohu.com/164572951.html'\nresponse = urllib2.urlopen(url)...
[ 1 ]
[]
[]
[ "encoding", "python" ]
stackoverflow_0005415503_encoding_python.txt
Q: xml.dom.minidom getting elements by tagname How can I retrieve the value of code with this (below) xml string and when using xml.dom.minidom? <data> <element1> <name>myname</name> </element1> <element2> <code>3</code> <name>another name</name> </element2> </data> Because mu...
xml.dom.minidom getting elements by tagname
How can I retrieve the value of code with this (below) xml string and when using xml.dom.minidom? <data> <element1> <name>myname</name> </element1> <element2> <code>3</code> <name>another name</name> </element2> </data> Because multiple 'name' tags can appear I would like to do ...
[ "The below code worked fine for me. I think you had multiple tags and you want to get the name from the second tag.\nmyxml = \"\"\"\\\n<data>\n <element>\n <name>myname</name>\n </element>\n <element>\n <code>3</code>\n <name>another name</name>\n </element>\n</data>\n\"\"\"\n\ndom...
[ 2 ]
[]
[]
[ "minidom", "python", "xml" ]
stackoverflow_0005416348_minidom_python_xml.txt
Q: Django extending user onetoone I have a model which extends User model and have form for it class Dealer(models.Model): account =models.CharField(max_length=8,blank=True) addresses = generic.GenericRelation( Addres, null=True, blank=True ) email =models.EmailField(blank=T...
Django extending user onetoone
I have a model which extends User model and have form for it class Dealer(models.Model): account =models.CharField(max_length=8,blank=True) addresses = generic.GenericRelation( Addres, null=True, blank=True ) email =models.EmailField(blank=True) name ...
[ "Assuming the id you are passing in is the id of the Dealer:\nviews.py:\nfrom django.shortcuts import get_object_or_404\n\ndef dealer_form(request, id_):\n if id_:\n dealer = get_object_or_404(Dealer, pk=id_)\n\n form=DealerForm(instance=dealer)\n return render_to_response('dealer_form.html', {'form...
[ 1 ]
[]
[]
[ "django", "django_forms", "python" ]
stackoverflow_0005415199_django_django_forms_python.txt
Q: Optimizing join query performance in google app engine Scenario Entity1 (id,itmname) Entity2 (id,itmname,price) Entity3 (id,itmname,profit) profit and price are both IntegerProperty I want to count all the item with price more then 500 and profit more then 10. I know its join operation and is not supported by go...
Optimizing join query performance in google app engine
Scenario Entity1 (id,itmname) Entity2 (id,itmname,price) Entity3 (id,itmname,profit) profit and price are both IntegerProperty I want to count all the item with price more then 500 and profit more then 10. I know its join operation and is not supported by google. I tried my best to find out the way other then executi...
[ "Google App Engine developers have always focused on read optimization and that is one thing where denormalization pops in. Before you design your data structure, you should work on possible cases in which the data could be retrieved. Designing of models comes later. A closer look at I/O session about \nBuilding Sc...
[ 1, 0 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0005415342_google_app_engine_python.txt
Q: Why must I restart fastcgi process for Django? Possible Duplicate: Django, Nginx, FastCGI caching problem when I change code Currently I use Nginx + fastcgi to run Django applications. After I change the source code of a Python file in a web application, I always see the old version of application from browser. ...
Why must I restart fastcgi process for Django?
Possible Duplicate: Django, Nginx, FastCGI caching problem when I change code Currently I use Nginx + fastcgi to run Django applications. After I change the source code of a Python file in a web application, I always see the old version of application from browser. It seems that it doesn't include my changes. Only a...
[ "New changes aren't reflected until after restart because your code is loaded into memory when the server is started. The only reason why the django development environment doesn't suffer this is because it is constantly watching the filesystem for changes and auto-reloads when it detects a change.\nThere are some...
[ 2 ]
[]
[]
[ "django", "nginx", "python" ]
stackoverflow_0005416993_django_nginx_python.txt
Q: No handlers could be found for logger "myapp.lib" I just upgraded to Django 1.3 which brings it's own logging module. I did set up logging and it is working when the modules are accessed by Apache/mod_wsgi. But when I am working with the django shell, Logging does not work - I always get the infamous error "No han...
No handlers could be found for logger "myapp.lib"
I just upgraded to Django 1.3 which brings it's own logging module. I did set up logging and it is working when the modules are accessed by Apache/mod_wsgi. But when I am working with the django shell, Logging does not work - I always get the infamous error "No handlers could be found for logger 'myapp.lib'" when worki...
[ "To log from the django shell you would need to run:\nimport logging\nl=logging.getLogger('myapp.lib')\nl.warn(\"foo\")\n\n__name__ is __main__ at the shell.\n" ]
[ 1 ]
[]
[]
[ "django", "logging", "python" ]
stackoverflow_0005417350_django_logging_python.txt
Q: Task queue works from view, but UnknownQueueError when run from unit tests Updated: Originally I didn't realize this only fails when run from unit tests. I have a working task queue in AppEngine with Python. - When calling a view manually, the task is added to the queue and runs - When called from unit tests, add...
Task queue works from view, but UnknownQueueError when run from unit tests
Updated: Originally I didn't realize this only fails when run from unit tests. I have a working task queue in AppEngine with Python. - When calling a view manually, the task is added to the queue and runs - When called from unit tests, adding the task to the queue fails with an UnknownQueueError. When reading about o...
[ "Edit: working answer. My problem was adding the stub fix in an individual unit test: moving it to setUp() fixed things.\nIn tests.py\nfrom google.appengine.api import apiproxy_stub_map\nimport os\n\nclass BlahTest(MyAppTestCase)\n def setUp(self):\n '''Ensure dev appserver task queue knows where to find ...
[ 12 ]
[]
[]
[ "google_app_engine", "python", "unit_testing" ]
stackoverflow_0005324515_google_app_engine_python_unit_testing.txt
Q: Django (w PyCharm) & PYTHON PATH issue I have purchased PyCharm and am trying to get things to work however I am encountering this issue.. Once I start a project everything works great... Now if I want a standalone app.. let's say at /users/me/djangoApps I understand I have to add this directory to the python pat...
Django (w PyCharm) & PYTHON PATH issue
I have purchased PyCharm and am trying to get things to work however I am encountering this issue.. Once I start a project everything works great... Now if I want a standalone app.. let's say at /users/me/djangoApps I understand I have to add this directory to the python path.. I am trying to do so by creating a file ...
[ "In pycharm open the settings \"cmd\" + \",\" and then to \"Project Structure\" click on \"Sources\" to include any modules.\n", "Don't add that file to your python site-packages, then your django project is gonna be included for all future projects down the road.\nIf you wanna debug, within PyCharm, click the Ru...
[ 10, 2 ]
[]
[]
[ "django", "pycharm", "python", "pythonpath" ]
stackoverflow_0004878661_django_pycharm_python_pythonpath.txt
Q: uploading file contents in python takes a long time I'm trying to upload files with the following code: url = "/folder/sub/interface?" connection = httplib.HTTPConnection('www.mydomain.com') def sendUpload(self): fields = [] file1 = ['file1', '/home/me/Desktop/sometextfile.txt'] f = open(file1[1], 'r'...
uploading file contents in python takes a long time
I'm trying to upload files with the following code: url = "/folder/sub/interface?" connection = httplib.HTTPConnection('www.mydomain.com') def sendUpload(self): fields = [] file1 = ['file1', '/home/me/Desktop/sometextfile.txt'] f = open(file1[1], 'r') file1.append(f.read()) files = [file1] cont...
[ "You don't seem to be sending the body of your request to the server, so it's probably stuck waiting for content-length bytes to arrive, which they never do.\nAre you sure that\nself.connection.request(\"POST\", self.url + upload_data, {}, myheaders)\n\nshouldn't read\nself.connection.request(\"POST\", self.url + u...
[ 1 ]
[]
[]
[ "httplib", "multipart", "python", "upload" ]
stackoverflow_0005418053_httplib_multipart_python_upload.txt
Q: How to wrap multithreaded C++ library using Python C/API? This is a somewhat long question, but I hope I can express it clearly. I am trying to wrap a C++ library using Python/C API. The main library, say, mylib, has its own object system (it is something like an interpreter for another language ) and uniquely ide...
How to wrap multithreaded C++ library using Python C/API?
This is a somewhat long question, but I hope I can express it clearly. I am trying to wrap a C++ library using Python/C API. The main library, say, mylib, has its own object system (it is something like an interpreter for another language ) and uniquely identifies each object in its environment by an Id. It creates mul...
[ "From your description it doesn't really sound like a threading issue at all: you claim you define the Dummy class without using the Python API, but that would mean Dummy instances are not PyObjects, so the reinterpret_cast will do the wrong thing. You can't create PyObjects by just instantiating a C++ class; you n...
[ 4, 0 ]
[]
[]
[ "c++", "pthreads", "python" ]
stackoverflow_0005416368_c++_pthreads_python.txt
Q: How to order choices based on their name instead of their index? This is my first post on stackoverflow, I'm going to try to follow the basic rules but be gentle with me. I have to make a few changes (which appeared superficial at first glance) to a django app. The client wants all the dropdown menus of the forms ...
How to order choices based on their name instead of their index?
This is my first post on stackoverflow, I'm going to try to follow the basic rules but be gentle with me. I have to make a few changes (which appeared superficial at first glance) to a django app. The client wants all the dropdown menus of the forms in the admin part of the site to be sorted alphabetically. The problem...
[ "changing the choices attribute of the form field to the sorted choices should fix your problem.\nforms.py \nclass YourAdminForm(forms.Form):\n def __init__(self, *args, **kwargs):\n super(YourAdminForm, self).__init__(*args, **kwargs)\n sorted_choices = sorted(YourModel.STATE, key=lambda x: x[1])\...
[ 4, 3 ]
[]
[]
[ "django", "django_admin", "python" ]
stackoverflow_0005418042_django_django_admin_python.txt
Q: How to make a non-square contourf-plot I'm using contourf in pyplot to plot some scalar data, but when my domain is non-square i feel like the data is misrepresented because it always plots it in a square (though the axis values will increase faster on one side.) How can i force the axis scaling to be equal, such ...
How to make a non-square contourf-plot
I'm using contourf in pyplot to plot some scalar data, but when my domain is non-square i feel like the data is misrepresented because it always plots it in a square (though the axis values will increase faster on one side.) How can i force the axis scaling to be equal, such that if my domain is twice as long in the x-...
[ "Using ax.set_aspect:\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nfig = plt.figure()\nax = fig.add_subplot(111)\nx=np.r_[-10:10:100j]\ny=np.r_[-20:20:100j]\nz= np.add.outer(x*x, y*y)\ncontour=ax.contour(x,y,z)\nfig.colorbar(contour)\nax.set_aspect('equal')\n# ax.axis('equal')\nplt.show()\n\nyields\n\nwh...
[ 5, 4, 0 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0005418712_matplotlib_python.txt
Q: Getting a Windows Transparency wxPython I'm trying to get a windows transparency in wxPython. I tried self.GetTransparent(), however that apparently doesn't exist. So, how do I go about getting a windows transparency? A: You have to derive your own class, which will be aware of its own transparency: import wx ...
Getting a Windows Transparency wxPython
I'm trying to get a windows transparency in wxPython. I tried self.GetTransparent(), however that apparently doesn't exist. So, how do I go about getting a windows transparency?
[ "You have to derive your own class, which will be aware of its own transparency:\nimport wx\n\nclass TransparentAwareFrame(wx.Frame):\n def __init__(self, *args, **kwargs):\n wx.Frame.__init__(self, *args, **kwargs)\n self.transparency = 255\n\n def SetTransparent(self, value):\n self.tra...
[ 2 ]
[]
[]
[ "alpha", "python", "transparency", "wxpython" ]
stackoverflow_0005255325_alpha_python_transparency_wxpython.txt
Q: How to call functions using ctypes with no input parameters? I am trying to call the C++ function add_two_U from Python using ctypes. The function add_two_U is defined in the C++ header file as: extern ExternalInputs_add_two add_two_U; The structure ExternalInputs_add_two is defined in the header file as: typede...
How to call functions using ctypes with no input parameters?
I am trying to call the C++ function add_two_U from Python using ctypes. The function add_two_U is defined in the C++ header file as: extern ExternalInputs_add_two add_two_U; The structure ExternalInputs_add_two is defined in the header file as: typedef struct { int32_T Input; /* '<Root>/Input...
[ "add_two_U is not a function, it's an exported value. You need to use in_dll.\nSee Accessing values exported from dlls.\n", "David,\nThank you for answering my first question. I changed my Python code to this:\n#Comment out this line. add_two_U is not a function\n#U_Model = cdll.add_two_win32.add_two_U\n\n#Get ...
[ 1, 0 ]
[]
[]
[ "ctypes", "python" ]
stackoverflow_0005407666_ctypes_python.txt
Q: Debugging visually using >>, >, >|, ||, |<, <, << Debugging performance problems using a standard debugger is almost hopeless since the level of detail is too high. Other ways are using a profiler, but they seldom give me good information, especially when there is GUI and background threads involved, as I never kn...
Debugging visually using >>, >, >|, ||, |<, <, <<
Debugging performance problems using a standard debugger is almost hopeless since the level of detail is too high. Other ways are using a profiler, but they seldom give me good information, especially when there is GUI and background threads involved, as I never know whether the user was actually waiting for the comput...
[ "The \"Fast Forward to critical spot\" function already exists in any debugger, it's called a \"breakpoint\". There are indeed debuggers that can slow down execution, but that will not help you debug performance problems, because it doesn't slow down the computer. The processor and disk and memory is still exactly ...
[ 4, 1, 1 ]
[]
[]
[ "debuggervisualizer", "debugging", "java", "performance", "python" ]
stackoverflow_0005416987_debuggervisualizer_debugging_java_performance_python.txt
Q: Web.py: Can't get multithreaded behavior with multiple browser tabs I heard Web.py is a multithreaded webserver by default. So created a simple application that sleeps for a minute before returning "Hello World". Now if I call this application (i.e., http://localhost:8080/) from two different browsers almost simu...
Web.py: Can't get multithreaded behavior with multiple browser tabs
I heard Web.py is a multithreaded webserver by default. So created a simple application that sleeps for a minute before returning "Hello World". Now if I call this application (i.e., http://localhost:8080/) from two different browsers almost simultaneously, I get the 'Hello World' almost simultaneously in both browse...
[ "The behaviour you describe seems to be specific to certain browsers. After taking the time to recreate your situation, i.e. creating a simple web.py application that sleeps for a while before answering a request, I was able to recreate the issue - in Firefox. Trying the same in IE8 using two tabs actually produced...
[ 5 ]
[]
[]
[ "multithreading", "python", "web.py", "webserver" ]
stackoverflow_0005419285_multithreading_python_web.py_webserver.txt
Q: How to suppress a Qt GUI application? I need to run a Qt application in Batch mode, so basically I need to run it without GUI. I've already tried using QCoreApplication but my application relies on the existence of X11 window. So I need the GUI to open regularly, but I need to "hide" it from the user. I know that...
How to suppress a Qt GUI application?
I need to run a Qt application in Batch mode, so basically I need to run it without GUI. I've already tried using QCoreApplication but my application relies on the existence of X11 window. So I need the GUI to open regularly, but I need to "hide" it from the user. I know that I have the ability to create a virtual VNC...
[ "As @utdmr suggested, that solved the problem.\nI've thought that show() was also responsible for the signal/slot mechanism and other Qt and X11 functions. But apparently, the application works normally, just doesn't show the GUI. \nAnd that was exactly what I needed since it is a fully developed application and th...
[ 1 ]
[]
[]
[ "linux", "python", "qt", "user_interface", "x11" ]
stackoverflow_0005369290_linux_python_qt_user_interface_x11.txt
Q: Python: Unexpected ordering in lists I've encountering a weird behavior while working with lists in Python. I've implemented a method that returns a list of lists of Integers; in particular, those are cycles within a graph each including three nodes: simple_cycles = compute_cycles(graph) That returns me something...
Python: Unexpected ordering in lists
I've encountering a weird behavior while working with lists in Python. I've implemented a method that returns a list of lists of Integers; in particular, those are cycles within a graph each including three nodes: simple_cycles = compute_cycles(graph) That returns me something like this: [[40000,20000,30000],[700,500,...
[ "I don't understand why you're using dict.\nprint sorted(set(tuple(sorted(x)) for x in L))\n\n", "Dictionaries do not necessarily keep the order. They are allowed to change it. Put this in the interpreter: {'a': 1, 'b': 2, 'c': 3}. I got {'a': 1, 'c': 3, 'b': 2}.\n", "My problem is finally solved. Because I put...
[ 3, 1, 0 ]
[]
[]
[ "list", "no_duplicates", "python" ]
stackoverflow_0005417533_list_no_duplicates_python.txt
Q: The influence of ? in the regex string Consider the following Python code: >>> re.search(r'.*(99)', 'aa99bb').groups() ('99',) >>> re.search(r'.*(99)?', 'aa99bb').groups() (None,) I don't understand why I don't catch 99 in the second example. A: This is because the .* first matches the entire string. At that po...
The influence of ? in the regex string
Consider the following Python code: >>> re.search(r'.*(99)', 'aa99bb').groups() ('99',) >>> re.search(r'.*(99)?', 'aa99bb').groups() (None,) I don't understand why I don't catch 99 in the second example.
[ "This is because the .* first matches the entire string. At that point, it's not possible to match 99 any more, and since the group is optional, the regex engine stops because it has found a successful match.\nIf on the other hand the group is mandatory, the regex engine has to backtrack into the .*.\nCompare the f...
[ 11, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0005361205_python_regex.txt
Q: Google App Engine ( GAE ) and static files best practices I'm trying to create kind of instagram application, and I'm learning GAE so I would like to create the whole application with it. The problem I see is that serving images to the client will consume a lot of traffic and I don't want that since Google bills y...
Google App Engine ( GAE ) and static files best practices
I'm trying to create kind of instagram application, and I'm learning GAE so I would like to create the whole application with it. The problem I see is that serving images to the client will consume a lot of traffic and I don't want that since Google bills you for that. My question is: which are the best practices worki...
[ "Someone is going to charge you to deliver your content, be it Google through AppEngine or Amazon through S3 or CloudFront or something else. You'll want to put together a spreadsheet into which you can plug numbers to see how the various alternatives work at different volumes.\nAmazon CloudFront is a good choice f...
[ 3, 2 ]
[]
[]
[ "google_app_engine", "optimization", "python", "static" ]
stackoverflow_0005418599_google_app_engine_optimization_python_static.txt
Q: How to interfere some text in a html link string in python In the company I am working they use the above command to construct a link from a list of data we are holding on a map link=a % firstUpper(b) which produces something like <a href="path/tomyhtml/foo.html">foo</a> I would like to alter the link string and...
How to interfere some text in a html link string in python
In the company I am working they use the above command to construct a link from a list of data we are holding on a map link=a % firstUpper(b) which produces something like <a href="path/tomyhtml/foo.html">foo</a> I would like to alter the link string and add a title attribute to it so it becomes like <a href="path/t...
[ "Using BeautifulSoup:\nfrom BeautifulSoup import BeautifulSoup\nsoup = BeautifulSoup('<a href=\"path/tomyhtml/foo.html\">foo</a>')\nsoup.a[\"title\"] = \"Some cool title\"\n\n", "s = '<a href=\"%s\" title=\"%s\">foo</a>'\n\nprint s % (href_string, title_string)\n\n" ]
[ 4, 2 ]
[]
[]
[ "html", "python", "string" ]
stackoverflow_0005420560_html_python_string.txt
Q: Python string manipulation using xrange What is faster way to manipulate myInput string in order to have myOutput string? myInput = "1,3-5,7" myOutput = "1,3,4,5,7" A: i remember a question on SO that turned [1,3,4,5,7] into "1,3-5,7" but i don't remember which this is the opposite problem: def expand(s): ...
Python string manipulation using xrange
What is faster way to manipulate myInput string in order to have myOutput string? myInput = "1,3-5,7" myOutput = "1,3,4,5,7"
[ "i remember a question on SO that turned [1,3,4,5,7] into \"1,3-5,7\" but i don't remember which\nthis is the opposite problem:\ndef expand(s): \n return ','.join(sum([v if len(v)==1 else map(str, apply(lambda a,b: range(a,b+1), map(int, v))) for v in [p.split('-') for p in s.split(',')]],[]))\n\nprint expand(\"...
[ 1, 1, 1 ]
[]
[]
[ "python", "string" ]
stackoverflow_0005420535_python_string.txt
Q: Accessing Django custom models through Manager returns empty set From all I've read, it appears this should Just Work, but it doesn't. I have a custom model: from django.db import models from django.contrib.auth.models import * class Feed(models.Model): user = models.ForeignKey(User, blank=True, null=True) ...
Accessing Django custom models through Manager returns empty set
From all I've read, it appears this should Just Work, but it doesn't. I have a custom model: from django.db import models from django.contrib.auth.models import * class Feed(models.Model): user = models.ForeignKey(User, blank=True, null=True) link = models.CharField(max_length=200) startDate = models.CharF...
[ "Whoa.\nWhy are you overriding your model's __init__? There are very few good reasons to do this, and if you do, you must absolutely keep the interface the same- because that __init__ is called every time django pulls one of your models from the db (which is why you get the error when you call .get())\nWhat are yo...
[ 2, 0 ]
[]
[]
[ "django", "django_models", "python", "sqlite" ]
stackoverflow_0005420594_django_django_models_python_sqlite.txt
Q: Javascript validation with Django I have a filtering option in my Django application. The filtering is done by the choice (Name, location, designation EmployeeID, ..etc) selected on a drop down and the value entered in a text field. Now I wanted to validate when the user chooses EmployeeID from the drop down choic...
Javascript validation with Django
I have a filtering option in my Django application. The filtering is done by the choice (Name, location, designation EmployeeID, ..etc) selected on a drop down and the value entered in a text field. Now I wanted to validate when the user chooses EmployeeID from the drop down choice. If no value is entered in text box w...
[ "Checked your code and if I understand your problem correctly, you want do that:\n<form name=\"myform\" id=\"myformid\" method=\"POST\" action=\"http://10.1.0.90:8080/filter/\" onSubmit=\"javascript:return isEmpty();\" >\n\nFilter By: \n<select name=\"choices\" id =\"choicesId\" style=\"color: black; background-c...
[ 3 ]
[]
[]
[ "django", "dom_events", "javascript", "python" ]
stackoverflow_0005417018_django_dom_events_javascript_python.txt
Q: installing Django 1.3 to Python 2.5 on Mac OS X Using Mac OS X v 10.6.7 Django 1.3 Python 2.5 I am trying to run setup.py and install Django to the /Library/Python/2.5 version of Python. By default it installs in the 2.6 folder. Need to re-direct. Thanks, Harry A: I see that you are trying to change the default...
installing Django 1.3 to Python 2.5 on Mac OS X
Using Mac OS X v 10.6.7 Django 1.3 Python 2.5 I am trying to run setup.py and install Django to the /Library/Python/2.5 version of Python. By default it installs in the 2.6 folder. Need to re-direct. Thanks, Harry
[ "I see that you are trying to change the default install path from system python to a different python version. In that case, have you considered virtualenv? \nYou can install virtualenv by running \npip install virtualenv\n\nIt is much cleaner and much easier to manage as the number of projects and their dependenc...
[ 1, 1 ]
[]
[]
[ "django", "macos", "operating_system", "python" ]
stackoverflow_0005420650_django_macos_operating_system_python.txt
Q: Calling recv hangs after handle is called I've got a Python class I'm using to emulate an IMAP server for a unit test. When the handle() callback happens, I try to use recv() to get the data that just arrived but I'm blocking on the recv() call. I thought recv() would return with the data that was received but ins...
Calling recv hangs after handle is called
I've got a Python class I'm using to emulate an IMAP server for a unit test. When the handle() callback happens, I try to use recv() to get the data that just arrived but I'm blocking on the recv() call. I thought recv() would return with the data that was received but instead, it just sits there. In case it matters, I...
[ "(Posted as an answer this time) Per the IMAP protocol, servers speak first, sending an OK greeting to the client. Both your server and client seem to be trying to recv() from each other at the same time:\natlas% telnet chaos 143\nTrying 192.168.1.5...\nConnected to chaos\nEscape character is '^]'.\n* OK chaos Cyru...
[ 2 ]
[]
[]
[ "imap", "python", "sockets" ]
stackoverflow_0005412265_imap_python_sockets.txt
Q: Feedback on different backends for GWT I have to re-design an existing application which uses Pylons (Python) on the backend and GWT on the frontend. In the course of this re-design I can also change the backend system. I tried to read up on the advantages and disadvantages of various backend systems (Java, Python...
Feedback on different backends for GWT
I have to re-design an existing application which uses Pylons (Python) on the backend and GWT on the frontend. In the course of this re-design I can also change the backend system. I tried to read up on the advantages and disadvantages of various backend systems (Java, Python, etc) but I would be thankful for some feed...
[ "We had the same dilemma in the past. \nI was involved in designing and building a system that had a GWT frontend and Java (Spring, Hibernate) backend. Some of our other (related) systems were built in Python and Ruby, so the expertise was there, and a question just like yours came up.\nWe decided on Java mainly so...
[ 1 ]
[]
[]
[ "architecture", "gwt", "java", "python", "web_frameworks" ]
stackoverflow_0005417372_architecture_gwt_java_python_web_frameworks.txt
Q: Why is this django template not working? This was working 2 weeks ago. I can't figure what is causing this error now. I am getting the error Caught TypeError while rendering: 'int' object is not iterable on the line in my template where the FOR loop starts. views.py @csrf_exempt def my_status(request): impor...
Why is this django template not working?
This was working 2 weeks ago. I can't figure what is causing this error now. I am getting the error Caught TypeError while rendering: 'int' object is not iterable on the line in my template where the FOR loop starts. views.py @csrf_exempt def my_status(request): import twitter client = twitter.Api() #get...
[ "In your data:\n{'PAP': 10, 'btw': 10, 'via': 20, 'crowd': 10, 'is': 10, 'half': 10, 'anyway': 10, \"#fb'\": 10, 'items': 10, '[@leynaaaa': 10, 'are': 10}\n\nThere's a key called items. Can you pass in a test dictionary without the items key to the template to see if it works?\nWorkaround:\nAssuming you can't rena...
[ 2, 0 ]
[]
[]
[ "django", "for_loop", "python" ]
stackoverflow_0005421252_django_for_loop_python.txt
Q: Shell script calls Python from terminal but fails from Cron I have a shell script, thus: export PYTHONPATH=/usr/local/lib/python cd /home/skip/workspace/UAM for file in *.txt do echo $file >>log.fil /usr/bin/python push.py -s $file done return 0 It runs properly from command line. prints each filename t...
Shell script calls Python from terminal but fails from Cron
I have a shell script, thus: export PYTHONPATH=/usr/local/lib/python cd /home/skip/workspace/UAM for file in *.txt do echo $file >>log.fil /usr/bin/python push.py -s $file done return 0 It runs properly from command line. prints each filename to the log file and runs the python push.py command as expected. (...
[ "Check that push.py doesn't need any environment variables that may not be set in crontab context. If it is a user crontab (not a root cron) then it will be executed as if the same user executed that line, but not necessarily into the same environment (like aliases and Path set on initialization files).\n", "Got ...
[ 3, 1 ]
[]
[]
[ "bash", "cron", "python" ]
stackoverflow_0005421423_bash_cron_python.txt
Q: Python - Optimal code to find preceding and following five words from a given point in a line I'm trying to write code to find the 5 words on either side of a particular phrase. Easy enough, but I have to do this on a massive volume of data, thus the code needs to be optimal! for file in listing: file2 = open(...
Python - Optimal code to find preceding and following five words from a given point in a line
I'm trying to write code to find the 5 words on either side of a particular phrase. Easy enough, but I have to do this on a massive volume of data, thus the code needs to be optimal! for file in listing: file2 = open('//home/user/Documents/Corpus/Files/'+file,'r') for line in file2: linetrigrams = trigr...
[ "Several significant factors to consider when weighing various approaches:\n\nMultiline vs single line\nLength of the lines\nLength of the search pattern\nRate of the search matching\nWhat to do if there are fewer than 5 words before/after\nHow to handle non-word, non-space characters (newlines and punctuation)\nCa...
[ 3, 2, 1, 1, 0 ]
[]
[]
[ "python", "search", "string" ]
stackoverflow_0005421517_python_search_string.txt
Q: Python getattr, howto address the constructor of a django model In the code below I render the person model. Instead of person() I want to use a getattr to make use of a variable model name. Something like getattr('person', ????) The code below is a simplified verdion of my app engine code. class person(djangofor...
Python getattr, howto address the constructor of a django model
In the code below I render the person model. Instead of person() I want to use a getattr to make use of a variable model name. Something like getattr('person', ????) The code below is a simplified verdion of my app engine code. class person(djangoforms.ModelForm): name = djangoforms.forms.CharField(max_length=24,...
[ "The constructor of a python class is named __init__, so use getattr(YourClass, '__init__').\nHowever, this is probably not what you want. See Does python have an equivalent to Java Class.forName()? - this might be the solution for your question.\n", "I used\nget_class('main.person')()\n\ninstead of \nget_class('...
[ 0, 0, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0005420586_django_python.txt
Q: How can I make Django use the correct current time for my system locale? From Python interpreter in the Gnome terminal on Ubuntu, I enter and get the following: >>> import datetime >>> now = datetime.datetime.now() >>> print now 2011-03-24 12:27:32.527229 With Django, the output to the web browser is an hour behi...
How can I make Django use the correct current time for my system locale?
From Python interpreter in the Gnome terminal on Ubuntu, I enter and get the following: >>> import datetime >>> now = datetime.datetime.now() >>> print now 2011-03-24 12:27:32.527229 With Django, the output to the web browser is an hour behind: It is now 2011-03-24 11:27:38.864572. The Django code (running on the sa...
[ "The TIME_ZONE setting in your project is incorrect.\n" ]
[ 1 ]
[]
[]
[ "datetime", "django", "python" ]
stackoverflow_0005422464_datetime_django_python.txt
Q: numpy: efficient execution of a complex reshape of an array I am reading a vendor-provided large binary array into a 2D numpy array tempfid(M, N) # load data data=numpy.fromfile(file=dirname+'/fid', dtype=numpy.dtype('i4')) # convert to complex data fid=data[::2]+1j*data[1::2] tempfid=fid.reshape(I*J*K, N) and...
numpy: efficient execution of a complex reshape of an array
I am reading a vendor-provided large binary array into a 2D numpy array tempfid(M, N) # load data data=numpy.fromfile(file=dirname+'/fid', dtype=numpy.dtype('i4')) # convert to complex data fid=data[::2]+1j*data[1::2] tempfid=fid.reshape(I*J*K, N) and then I need to reshape it into a 4D array useful4d(N,I,J,K) usin...
[ "How about this. Set us your indicies using the vectorized versions of f1,f2,f3 (not necessarily using np.vectorize, but perhaps just writing a function that takes an array and returns an array), then use np.ix_: \nhttp://docs.scipy.org/doc/numpy/reference/generated/numpy.ix_.html\nto get the index arrays. Then res...
[ 2, 2 ]
[]
[]
[ "multidimensional_array", "numpy", "python", "slice" ]
stackoverflow_0005422184_multidimensional_array_numpy_python_slice.txt
Q: Python: Is there a way I can run mainloop() in the background? Is there a way I can run mainloop() in the background? I don't want to add the complexity of threads. Thanks in advance. A: No. The main loop of a GUI framework must always run in the foreground. A: No, you can't do this. The message loop runs in i...
Python: Is there a way I can run mainloop() in the background?
Is there a way I can run mainloop() in the background? I don't want to add the complexity of threads. Thanks in advance.
[ "No. The main loop of a GUI framework must always run in the foreground.\n", "No, you can't do this. The message loop runs in its thread and processes your message queue. \nThere isn't really any official distinction between background and foreground threads. The thread that processes your message is typically c...
[ 3, 2, 0 ]
[]
[]
[ "program_entry_point", "python", "tkinter" ]
stackoverflow_0005420885_program_entry_point_python_tkinter.txt
Q: Counting entries with Python dictionary datatype I'm learning Python and writing a program that keeps track of the total number of various types of file extensions. I think a dictionary would be the perfect data type to track this information, something like: .txt 14 .c 27 .java 12 I have some code written th...
Counting entries with Python dictionary datatype
I'm learning Python and writing a program that keeps track of the total number of various types of file extensions. I think a dictionary would be the perfect data type to track this information, something like: .txt 14 .c 27 .java 12 I have some code written that builds a set, which eliminates duplicate file exten...
[ "In Python 2.7 or above, you can use collections.Counter:\nfrom collections import Counter\nc = Counter(i.extension for i in file_list)\nprint(c)\n\nCounter is a class derived from the standard Python dict.\nIf you prefer to use a plain dict, you can take advantage of its setdefault() method:\ncounts = {}\nfor i in...
[ 7, 3 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0005422911_dictionary_python.txt
Q: OpenERP cache features I want to cache some results in my OpenERP module, so I dug around a bit and found the cache decorator. Unfortunately, the most documentation I've been able to find is in the class declaration: Use it as a decorator of the function you plan to cache Timeout: 0 = no timeout, otherwise in sec...
OpenERP cache features
I want to cache some results in my OpenERP module, so I dug around a bit and found the cache decorator. Unfortunately, the most documentation I've been able to find is in the class declaration: Use it as a decorator of the function you plan to cache Timeout: 0 = no timeout, otherwise in seconds Can anybody recommend ...
[ "After digging around some more, the simplest example I've found is the ir_model_data._get_id() method:\n@tools.cache()\ndef _get_id(self, cr, uid, module, xml_id):\n ids = self.search(cr, uid, [('module','=',module),('name','=', xml_id)])\n if not ids:\n raise ValueError('No references to %s.%s' % (mo...
[ 5, 3 ]
[]
[]
[ "caching", "openerp", "python" ]
stackoverflow_0003182153_caching_openerp_python.txt
Q: How does garbage collection and scoping work in C#? I'm learning C# coming from python and wish to know how the C# garbage collector works - I found that I understood a lot more about python once I figured out what it was doing behind the scenes, and wish to avoid making the sort of noob errors I made at first whe...
How does garbage collection and scoping work in C#?
I'm learning C# coming from python and wish to know how the C# garbage collector works - I found that I understood a lot more about python once I figured out what it was doing behind the scenes, and wish to avoid making the sort of noob errors I made at first when learning python. I've not been able to find any good c...
[ "The dotnet GC engine is a mark-and-sweep engine rather than a reference-counter engine like you're used to in python. The system doesn't maintain a count of references to a variable, but rather runs a \"collection\" when it needs to reclaim RAM, marking all of the currently-reachable pointers, and removing all the...
[ 25, 6, 5, 3 ]
[]
[]
[ ".net", "c#", "garbage_collection", "python" ]
stackoverflow_0005422918_.net_c#_garbage_collection_python.txt
Q: I'm getting an error when trying to open a website url with Python 3.1, urllib & json: operation was attempted on something that is not a socket I'm getting an error when trying to open a website url with Python 3.1, urllib & json urllib.error.URLError: Here's the code. The first website loads fine. The second ...
I'm getting an error when trying to open a website url with Python 3.1, urllib & json: operation was attempted on something that is not a socket
I'm getting an error when trying to open a website url with Python 3.1, urllib & json urllib.error.URLError: Here's the code. The first website loads fine. The second one import json import urllib.request import urllib.parse import util # This one works fine response = urllib.request.urlopen('http://python.org/') ...
[ "Please edit the title and tags and maybe even the question body:\nThis has nothing to do with JSON and everything to do with Windows. It's also at a lower level than urllib. (Probably in the SSL code.) Distilled:\nBoth of the following approaches fail on Python 3.1.2 for Vista, but work fine on Linux (Python 3.1.3...
[ 1, 1 ]
[]
[]
[ "json", "python", "urllib" ]
stackoverflow_0002977850_json_python_urllib.txt
Q: Converting G Force data to rotation? I've been playing around with an accelerometer with 3 axis: X, Y and Z. It says on the supplier's site that it measures gravitational force. I'm sending this data to the blender games engine where I am rotating a cube in real time depending on the data values coming from the ac...
Converting G Force data to rotation?
I've been playing around with an accelerometer with 3 axis: X, Y and Z. It says on the supplier's site that it measures gravitational force. I'm sending this data to the blender games engine where I am rotating a cube in real time depending on the data values coming from the accelerometer. However the values coming th...
[ "I guess you are using the measured acceleration to find the direction of gravitational pull (ie, down). If you are moving the accelerometer, apart from just turning it, there will be some additional force; think of the accelerometer having a pendulum weight handing from it, as you move it the pendulum sways (altho...
[ 1, 1 ]
[]
[]
[ "3d", "accelerometer", "blender", "math", "python" ]
stackoverflow_0005420986_3d_accelerometer_blender_math_python.txt
Q: How do I fill text-boxes in a gui application through command line? I'm designing an NLP (Natural Language Processing) application in python and I want to use the following UNL (Universal Networking Language) EnConverter that is an executable gui - 3rd party - application and only works on windows (I don't have it...
How do I fill text-boxes in a gui application through command line?
I'm designing an NLP (Natural Language Processing) application in python and I want to use the following UNL (Universal Networking Language) EnConverter that is an executable gui - 3rd party - application and only works on windows (I don't have its source-code) : So, what I want to know is how can I program a console...
[ "You can use Win32::GuiTest. It can detect widgets, click buttons, write text to GUI etc.\n", "You can use PyWinAuto. It can detect widgets, click buttons, write text to GUI etc.\n", "The Windows Sendkey package looks like it should be ideal this kind of thing.\nFrom the page:\nIn this example, SendKeys is used...
[ 4, 3, 1 ]
[]
[]
[ "console", "perl", "python", "ui_automation", "windows" ]
stackoverflow_0005418255_console_perl_python_ui_automation_windows.txt
Q: Python: _socket.so Greetings! So I'm creating a Python script that will when finished be compiled with Shedskin. Currently we do a little FTP work in this script so we import the ftplib module. When I attempt to compile it with Shedskin we get the error back saying that there is no '_socket' file in our Python2.6 ...
Python: _socket.so
Greetings! So I'm creating a Python script that will when finished be compiled with Shedskin. Currently we do a little FTP work in this script so we import the ftplib module. When I attempt to compile it with Shedskin we get the error back saying that there is no '_socket' file in our Python2.6 installation on Ubuntu. ...
[ "Look for shdeskin supported library modules in\n/usr/lib/python2.6/site-packages/shedskin/lib/.\nMy Fedora installation of shdeskin 0.7 does not include ftplib.\n" ]
[ 0 ]
[]
[]
[ "ftp", "python", "sockets" ]
stackoverflow_0005422714_ftp_python_sockets.txt
Q: Which OS recommended for Programmers? My stack for web developing includes Django/Python and Qt/C++ for non-web developing. What is most comfortable OS for a developer with such a stack ? A: Once you go linux, you'll never go back (though you might go crazy and move onto bsd). Ubuntu is probably the easiest OS ...
Which OS recommended for Programmers?
My stack for web developing includes Django/Python and Qt/C++ for non-web developing. What is most comfortable OS for a developer with such a stack ?
[ "Once you go linux, you'll never go back (though you might go crazy and move onto bsd). Ubuntu is probably the easiest OS to start with, if only because of the truckloads of documentation, forum assistance, etc. Good luck!\n", "If you don't want to use an language that has special requirements (like .net), the ...
[ 1, 1, 1 ]
[]
[]
[ "linux", "python", "qt" ]
stackoverflow_0005423404_linux_python_qt.txt
Q: Django directory plugin Is there any Django plugin or reusable app available that we can use to add online directory feature to our Django based website? A: You will not find something like that, because using django means you can do that with just a few lines of code by yourself. Django is not a CMS, but a fram...
Django directory plugin
Is there any Django plugin or reusable app available that we can use to add online directory feature to our Django based website?
[ "You will not find something like that, because using django means you can do that with just a few lines of code by yourself. Django is not a CMS, but a framework, which means you are one level deeper. A lot of the things where you would use a plugin in a CMS are common tasks for django programmers, so there really...
[ 1 ]
[]
[]
[ "directory", "django", "plugins", "python", "web" ]
stackoverflow_0005399853_directory_django_plugins_python_web.txt
Q: How to install Python Virtualenv? I'm new to Python. I need to install "Virtualenv" but I don't can't figure out how it works and how to install it. I have downloaded and uncompress virtualenv-1.5.2. What sould be my next step? Best Regards, A: Inside the uncompressed virtualenv directory run python setup.py i...
How to install Python Virtualenv?
I'm new to Python. I need to install "Virtualenv" but I don't can't figure out how it works and how to install it. I have downloaded and uncompress virtualenv-1.5.2. What sould be my next step? Best Regards,
[ "Inside the uncompressed virtualenv directory run \n\npython setup.py install\n\nYou should also learn about easy_install and pip for Python package installation. \n", "Just install ActivePython, it already includes virtualenv, easy_install, pip and PyPM.\n" ]
[ 2, 0 ]
[]
[]
[ "installation", "python", "virtualenv" ]
stackoverflow_0005418947_installation_python_virtualenv.txt
Q: Split names separated with commas when surnames are also separated with commas I have a following database field: AUX: Smith, J., Jones, M. & Ford, S. There can names from one up to 15 and others are separated by comma and last one separated by & How can I split this into list, where list[1]=Smith, J, list[2]=Jone...
Split names separated with commas when surnames are also separated with commas
I have a following database field: AUX: Smith, J., Jones, M. & Ford, S. There can names from one up to 15 and others are separated by comma and last one separated by & How can I split this into list, where list[1]=Smith, J, list[2]=Jones, M. and so forth?
[ "def parseNames(namestr):\n namestr = namestr.replace('&', ',')\n nameparts = [namepart.strip() for namepart in namestr.split(',')]\n it = iter(nameparts)\n return zip(it,it) # return list of part-pairs\n\ndef nameStr(name, fmt=\"{lastname}, {firstname}\"):\n return fmt.format(lastname=name[0], ...
[ 3 ]
[]
[]
[ "list", "python", "split" ]
stackoverflow_0005423949_list_python_split.txt
Q: Obtaining a unique top-down list of folders in python Given these folders s:\test\zoneA\UnitA s:\test\zoneB\UnitA s:\test\zoneB\UnitB\Item_1 I would like to pass to a function 's:\test' and get unique bottom list of folders Resulting in what you see above... 3 entries. Instead, when I use my function import os fo...
Obtaining a unique top-down list of folders in python
Given these folders s:\test\zoneA\UnitA s:\test\zoneB\UnitA s:\test\zoneB\UnitB\Item_1 I would like to pass to a function 's:\test' and get unique bottom list of folders Resulting in what you see above... 3 entries. Instead, when I use my function import os for top, dirs, files in os.walk('S:\\\test'): for nm in d...
[ "I guess what you want are folders without subfolders?\nimport os\nfor path, dirs, files in os.walk('S:\\\\\\test'):\n if not dirs:\n print path\n\n" ]
[ 0 ]
[]
[]
[ "directory", "os.walk", "python", "unique" ]
stackoverflow_0005423978_directory_os.walk_python_unique.txt
Q: Pass python variable from object to parent I'm writing a python program that wants to keep track of a status flag from several different places. I've done some reading to discover that a Python variable passed into a function can't necessarily be modified by that function (in my case it can't). As an example: de...
Pass python variable from object to parent
I'm writing a python program that wants to keep track of a status flag from several different places. I've done some reading to discover that a Python variable passed into a function can't necessarily be modified by that function (in my case it can't). As an example: def testfunc(self, inVariable): inVariable = 4 ...
[ "\nGlobal variables, perhaps?\n\nGlobal variables are almost always a bad idea.\nA variable in Python is just binding a name to a value, in testFunc all you're doing is changing the value bound to inVariable rather than changing the variable itself.\nYou'll need to pass an object to your function and modify its att...
[ 1, 1, 1 ]
[]
[]
[ "python", "variables" ]
stackoverflow_0005398183_python_variables.txt
Q: newline and spaces in database column I cannot find the records using the WHERE CLAUSE : SELECT sensor FROM table WHERE type = 'FEET' There are records in the table whose 'type' column values are 'FEET', so I suppose it's something wrong about the format. the result would be something more than 'FEET' so that it ...
newline and spaces in database column
I cannot find the records using the WHERE CLAUSE : SELECT sensor FROM table WHERE type = 'FEET' There are records in the table whose 'type' column values are 'FEET', so I suppose it's something wrong about the format. the result would be something more than 'FEET' so that it simply can not find those equal to 'FEET'. ...
[ "You say \"\"\"Since in the statement: WHERE a = value.. a should be a column name\"\"\". Not so, a can be any expression.\nYou say \"\"\"the resultTem turns out something like: ('FEET\\n ',) while resultTem[0] turns out like: FEET, which should be 'FEET\\n'\"\". Instead of print resultTem[0], use print repr(result...
[ 2, 1, 1, 0 ]
[]
[]
[ "postgresql", "python", "where_clause", "whitespace" ]
stackoverflow_0005423712_postgresql_python_where_clause_whitespace.txt
Q: Replacing all but specific elements using regex in Python Using regular expressions in Python, I am trying to remove all XML-type elements in a string, except those containing QUOTE, eg <QUOTE>, </QUOTE> or <QUOTE A="B"> should remain, but others such as <EXAMPLE> or <TEST A="B"> should be removed. I've created th...
Replacing all but specific elements using regex in Python
Using regular expressions in Python, I am trying to remove all XML-type elements in a string, except those containing QUOTE, eg <QUOTE>, </QUOTE> or <QUOTE A="B"> should remain, but others such as <EXAMPLE> or <TEST A="B"> should be removed. I've created this, which replaces all elements but can't work out the not part...
[ "I believe a negative lookahead assertion will do what you want:\nimport re\n\nregex = r'<(?!/?QUOTE\\b)[^>]+>'\n\ntests = [\n 'a plain old string',\n 'a string with <SOME> <XML TAGS=\"stuff\">',\n 'a string with <QUOTE>, </QUOTE>, and <QUOTE with=\"data\">',\n 'a string that has <QUOTEA> tags </QUOTEB>...
[ 5, 1, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0005423811_python_regex.txt
Q: Returning a PDF response in Django I'm asking a very similar question to this one. I'm creating a pdf using wkhtmltopdf on an Ubuntu server in Django. from tempfile import * from subprocess import Popen, PIPE tempfile = gettempdir()+"/results.pdf" papersize = 'Tabloid' orientation = 'Landscape' command_args = "wk...
Returning a PDF response in Django
I'm asking a very similar question to this one. I'm creating a pdf using wkhtmltopdf on an Ubuntu server in Django. from tempfile import * from subprocess import Popen, PIPE tempfile = gettempdir()+"/results.pdf" papersize = 'Tabloid' orientation = 'Landscape' command_args = "wkhtmltopdf -O %s -s %s -T 0 -R 0 -B 0 -L ...
[ "wkhtmltopdf is not outputting the contents of the PDF for Popen to read it. pdf_contents correctly contains the output of the command (nothing). You will need to read the contents of the output file if you want to return it to the client (see below), or skip the output file and make wkhtmltopdf output the conten...
[ 3, 2, 1, 0 ]
[]
[]
[ "django", "pdf", "popen", "python", "wkhtmltopdf" ]
stackoverflow_0005423995_django_pdf_popen_python_wkhtmltopdf.txt
Q: Receiving email with .csv attachment with google app engine I have been able to read emails, and I can see the attachments, but they don't come in as .csv data. I guess it is an 'EncodedPayload' type? The following code: for filename, content in attachments: logging.info("filename: " + filename) fileReade...
Receiving email with .csv attachment with google app engine
I have been able to read emails, and I can see the attachments, but they don't come in as .csv data. I guess it is an 'EncodedPayload' type? The following code: for filename, content in attachments: logging.info("filename: " + filename) fileReader = csv.reader(content.split("\n")) gave me this error: 'Encoded...
[ "call decode() on your content:\nfileReader = csv.reader(content.decode())\n\n" ]
[ 1 ]
[]
[]
[ "email", "google_app_engine", "python" ]
stackoverflow_0005424822_email_google_app_engine_python.txt
Q: DJango How to build a formset for a Quiz? I'm working on a quiz application that needs to display a quiz to be taken My models .py looks like this from django.db import models from django.contrib.auth.models import User from django.contrib import admin ####################### #Quiz Structure Models# #############...
DJango How to build a formset for a Quiz?
I'm working on a quiz application that needs to display a quiz to be taken My models .py looks like this from django.db import models from django.contrib.auth.models import User from django.contrib import admin ####################### #Quiz Structure Models# ####################### class Quiz(models.Model): name ...
[ "If I am understanding your question correctly, you'll probably want to create a custom Form at execute time, and many custom Fields. I would expect something along the lines of:\nclass QuizForm(forms.Form):\n def __init__(self, data, questions, *args, **kwargs):\n self.questions = questions\n for...
[ 4, 1 ]
[]
[]
[ "django", "django_forms", "python" ]
stackoverflow_0005423590_django_django_forms_python.txt
Q: How can I make an indeterminate progress bar in a Python console app? I'm rewritting a C# Console application in Python, and I'd like to port an indeterminate console-based progress bar class I wrote. I have examples of creating determinate progress bars using text, but I'm not sure how I would do an indeterminat...
How can I make an indeterminate progress bar in a Python console app?
I'm rewritting a C# Console application in Python, and I'd like to port an indeterminate console-based progress bar class I wrote. I have examples of creating determinate progress bars using text, but I'm not sure how I would do an indeterminate one. I'm assuming I would need threading of some sort. Thanks for your he...
[ "import sys, time\nwhile True:\n for i in range( 4 ):\n sys.stdout.write( '\\r' + ( '.' * i ) + ' ' )\n sys.stdout.flush()\n time.sleep( 0.5 )\n\nThat does the animation on the command line. There should be enough examples on threading in Python here.\nedit:\nPossible solution with threadi...
[ 4, 1 ]
[]
[]
[ "c#", "progress_bar", "python" ]
stackoverflow_0005424951_c#_progress_bar_python.txt
Q: Evaluating result of expression in if-statement in python Possible Duplicate: How to assign a variable in IF, and then return it. (Python) In Python is there a better way to do this?: myVal = getVal() if not myVal: continue I'd like to do something like this: if not (myVal = getVal()): continue But th...
Evaluating result of expression in if-statement in python
Possible Duplicate: How to assign a variable in IF, and then return it. (Python) In Python is there a better way to do this?: myVal = getVal() if not myVal: continue I'd like to do something like this: if not (myVal = getVal()): continue But that is not valid syntax. Are there any other ways to do this o...
[ "Its not pythonic to have return value for assignment. In python, assignment means binding object to a name, not putting value in memory location.\n", "No, you can't do this.\nI'd say that's because it's too easy to confuse with if not (myVal == getVal()):.\n", "No you can't do this.\nHowever, almost all situat...
[ 3, 1, 0, 0 ]
[]
[]
[ "python", "syntax" ]
stackoverflow_0005424611_python_syntax.txt
Q: How do we handle Python xmlrpclib Connection Refused? I don't know what the heck I'm doing wrong here, I wrote have an RPC client trying to connect to a non-existent server, and I'm trying to handle the exception that is thrown, but no matter what I try I can't figure out how I'm supposed to handle this: def _get_...
How do we handle Python xmlrpclib Connection Refused?
I don't know what the heck I'm doing wrong here, I wrote have an RPC client trying to connect to a non-existent server, and I'm trying to handle the exception that is thrown, but no matter what I try I can't figure out how I'm supposed to handle this: def _get_rpc(): try: a = ServerProxy('http://dd:LNXFhcZn...
[ "_get_rpc returns a reference to unconnected ServerProxy's supervisor method. The exception isn't happening in the call to _get_rpc where you handle it; it's happening when you try to evaluate this supervisor method (in \"if not rpc\"). Try from the interactive prompt:\nPython 2.6.5 (r265:79063, Apr 16 2010, 13:57:...
[ 4 ]
[]
[]
[ "exception_handling", "python", "xml_rpc", "xmlrpclib" ]
stackoverflow_0004696642_exception_handling_python_xml_rpc_xmlrpclib.txt
Q: python+postgresql: Convert string literal to regex I want to execute a query where I match a column name using a regex to my variable, s. s is a string literal and may contain things like ?, *, ., etc. I want to convert s so that ? turns into .{0,3}, so that all of its remaining regex symbols remain literals, and ...
python+postgresql: Convert string literal to regex
I want to execute a query where I match a column name using a regex to my variable, s. s is a string literal and may contain things like ?, *, ., etc. I want to convert s so that ? turns into .{0,3}, so that all of its remaining regex symbols remain literals, and then add .* to the end. examples: Hi -> Hi.* Fo?ar -> Fo...
[ "print '.{0,3}'.join(re.escape(part) for part in s.split('?')) + '.*'\n\n", "Use the re.escape(string) method.\nWhich states:\n\nReturn string with all\n non-alphanumerics backslashed; this is\n useful if you want to match an\n arbitrary literal string that may have\n regular expression metacharacters in\n i...
[ 4, 1 ]
[]
[]
[ "postgresql", "python", "regex", "string" ]
stackoverflow_0005425260_postgresql_python_regex_string.txt
Q: Is there any library which provides similar functions as twill and mechanized but has better quality I am trying to write some test script for a web application. So I tried use twill, which turns out to be using mechanized to parse html. But it really lets me down. For example, somehow, it couldn't correctly rec...
Is there any library which provides similar functions as twill and mechanized but has better quality
I am trying to write some test script for a web application. So I tried use twill, which turns out to be using mechanized to parse html. But it really lets me down. For example, somehow, it couldn't correctly recognize a form on web page requires method "POST", not "GET". So, is there any better alternatives other th...
[ "Well, that's not true.\nmechanize can recognize whether the method of the form is POST or GET just fine. It looks the \"method\" attribute of the <form> tag to do so.\nSo, if it didn't work for your particular case, you'd have to look what's wrong. Can you provide the HTML source code for the page you're trying to...
[ 3 ]
[]
[]
[ "python" ]
stackoverflow_0005425364_python.txt
Q: Simple UI to capture data I know that this is a vague question, but I was hoping to get some help. I know VBA pretty well, and have been able to accomplish some simple tasks in python as well as the statistical programming language in R. What I am looking to do is create a simple application that lets me capture ...
Simple UI to capture data
I know that this is a vague question, but I was hoping to get some help. I know VBA pretty well, and have been able to accomplish some simple tasks in python as well as the statistical programming language in R. What I am looking to do is create a simple application that lets me capture data, some of which is captured...
[ "If you choose to program in Python:\nYou could use the pygame package to easily capture keyboard events. The library was built to write games, but would probably give you the functionality that you are looking for with keydown/keyup events. It also handles mouse events and (since it is intended for games) has the ...
[ 1, 0, 0 ]
[]
[]
[ "python", "r", "user_interface", "vba" ]
stackoverflow_0005410244_python_r_user_interface_vba.txt
Q: Python / Django - Class Dictionary Persistent in View? I have a class in Django that is stored in the utils directory. I use this class almost like a model for my views.py. I am experiencing the weirdest behavior. I instantiate the class and have a dictionary belonging to it; however, the dictionary seems to be...
Python / Django - Class Dictionary Persistent in View?
I have a class in Django that is stored in the utils directory. I use this class almost like a model for my views.py. I am experiencing the weirdest behavior. I instantiate the class and have a dictionary belonging to it; however, the dictionary seems to be saved / cached / remembered on the next page load. class my...
[ "Field my_class.id is a class field not an instance member, so there is only one copy of my_class.id for every my_class instance.\nIf you want id to be unique for every instance, you need to initialize it in __init__:\ndef __init(self, request):\n ...\n self.id = { ... }\n\n" ]
[ 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0005425486_django_python.txt
Q: Problem upgrading a tool using easy_install On Ubuntu server : # easy_install mercurial Searching for mercurial Best match: mercurial 1.8.1 Adding mercurial 1.8.1 to easy-install.pth file Using /usr/local/lib/python2.6/dist-packages Processing dependencies for mercurial Finished processing dependencies for mercur...
Problem upgrading a tool using easy_install
On Ubuntu server : # easy_install mercurial Searching for mercurial Best match: mercurial 1.8.1 Adding mercurial 1.8.1 to easy-install.pth file Using /usr/local/lib/python2.6/dist-packages Processing dependencies for mercurial Finished processing dependencies for mercurial Now, if I do hg version it says I'm using th...
[ "I fixed the problem by uninstalling the package following this :\nHow do I remove packages installed with Python's easy_install?\nthen reinstalling.\nNow, easy_install don't install the very last version I wanted, so I'll install it manually certainly.\n", "You can install mercurial using aptitude. I'm not sure ...
[ 1, 0, 0 ]
[]
[]
[ "easy_install", "python" ]
stackoverflow_0005424537_easy_install_python.txt
Q: Django: How can I tell if a certain quality of all objects in a RelatedManager is the same? Let's say I have a ManyToManyField, from Swallow -=> Coconut. Also, let's say that Coconut has a boolean field called "Young." For a given swallow, how can I tell if all its coconuts are young? (What I'm really looking for ...
Django: How can I tell if a certain quality of all objects in a RelatedManager is the same?
Let's say I have a ManyToManyField, from Swallow -=> Coconut. Also, let's say that Coconut has a boolean field called "Young." For a given swallow, how can I tell if all its coconuts are young? (What I'm really looking for is not so much the ability to tell whether the swallow's coconuts are young, but a way to tell wh...
[ "OK, I figured it out. I need:\nswallow.coconuts.aggregate(test=Variance('young'))\n\nIf that is 0, I know that they are all the same.\n", "if there is no `coconut` for a `swallow` that is `not young`\nthen all `coconuts` are `young`\n\nEDIT:\nas far as I know, there is no queryset method that can do that, but y...
[ 3, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0005425582_django_python.txt
Q: How to make a object create another object As in the title how do I go about creating a object which creates another object? The object is simply supposed to replicate itself so like I call on this class to replicate itself the objects don't have to be different just that it creates another one of itself in like a...
How to make a object create another object
As in the title how do I go about creating a object which creates another object? The object is simply supposed to replicate itself so like I call on this class to replicate itself the objects don't have to be different just that it creates another one of itself in like a endless loop. The grey goo example is basically...
[ "class foo(object):\n def make_object(self):\n return []\n\nf = foo()\nmyobject = f.make_object()\n\nThis object creates another object (an empty list) and returns it.\nBut I have a feeling this is not what you intended. You need to specify more in your question and explain what specifically you are havin...
[ 3 ]
[]
[]
[ "python" ]
stackoverflow_0005426450_python.txt
Q: reducing I/O on application and database Is there a way to reduce the I/O's associated with either mysql or a python script? I am thinking of using EC2 and the costs seem okay except I can't really predict my I/O usage and I am worried it might blindside me with costs. I basically develop a python script to par...
reducing I/O on application and database
Is there a way to reduce the I/O's associated with either mysql or a python script? I am thinking of using EC2 and the costs seem okay except I can't really predict my I/O usage and I am worried it might blindside me with costs. I basically develop a python script to parse data and upload it into mysql. Once its in...
[ "By IO I assume you mean disk IO... and assuming you can fit everything into memory comfortably. You could:\n\nDisable swap on your box†\nUse mysql MEMORY tables while you are processing, (or perhaps consider using an Sqlite3 in memory store if you are only using the database for the convenience of SQL queries)\n\n...
[ 0, 0 ]
[]
[]
[ "amazon_ec2", "mysql", "mysql_management", "python" ]
stackoverflow_0005425289_amazon_ec2_mysql_mysql_management_python.txt
Q: Python 2.5 subprocess.Popen problem I'm trying to run the following little Python script: #!/usr/local/bin/python2.5 import sys, subprocess child = subprocess.Popen("muscle -stable -FASTA", stdin=sys.stdin, stdout=subprocess.PIPE, stderr=su...
Python 2.5 subprocess.Popen problem
I'm trying to run the following little Python script: #!/usr/local/bin/python2.5 import sys, subprocess child = subprocess.Popen("muscle -stable -FASTA", stdin=sys.stdin, stdout=subprocess.PIPE, stderr=subprocess.PIPE, s...
[ "Use child.communicate(someinput) to get the full output; see the 'warning' boxes in the documentation also. If you really need to read stdin interactively while writing to stdout, then (at least on Windows) you may be out of luck with Python + pipes. \n", "Your process is blocked on a full pipe, waiting for you ...
[ 3, 3 ]
[]
[]
[ "python", "subprocess" ]
stackoverflow_0005426487_python_subprocess.txt
Q: python django: convert the postgresql timestamp to datetime I have a postgresql table with a timestamp field, among other fields. How can I convert this timestamp field to a standard datetime python object and get the date like this: "Apr 23" I know how to do it in the django template (with the 'date' template ta...
python django: convert the postgresql timestamp to datetime
I have a postgresql table with a timestamp field, among other fields. How can I convert this timestamp field to a standard datetime python object and get the date like this: "Apr 23" I know how to do it in the django template (with the 'date' template tag), I need to do in views.py so I can create an array with these ...
[ "Something like this:\nTIME_FORMAT = \"%b %d\"\nf_str = obj.date.strftime(TIME_FORMAT)\n\nor\nTIME_FORMAT = \"%b %d\"\narr = [d.strftime(TIME_FORMAT) for d in dates]\n\nstrftime formatting\n" ]
[ 3 ]
[]
[]
[ "django", "postgresql", "python" ]
stackoverflow_0005425701_django_postgresql_python.txt
Q: How to remove new line and linefeed from title tags of a page? (Google App Engine - Python) I have this code to extract title: soup = BeautifulSoup.BeautifulSoup(urllib.urlopen(url)) title = str(soup.html.head.title.string).lstrip("\r\n").rstrip("\r\n") Some sites add return or newline before and after title tags...
How to remove new line and linefeed from title tags of a page? (Google App Engine - Python)
I have this code to extract title: soup = BeautifulSoup.BeautifulSoup(urllib.urlopen(url)) title = str(soup.html.head.title.string).lstrip("\r\n").rstrip("\r\n") Some sites add return or newline before and after title tags (why?) and to remove them I added .lstrip("\r\n").rstrip("\r\n") This works for instance with ...
[ "Try using str(title).strip() which will trim all whitespace from the start and end of the string.\n", "On poundwire, there's a tab character inside the <title> tag. There are also some spaces (the indenting that you'll probably see if you \"view source\") which you probably want removed too.\nLike samplebias say...
[ 4, 1 ]
[]
[]
[ "beautifulsoup", "google_app_engine", "python", "urllib" ]
stackoverflow_0005426523_beautifulsoup_google_app_engine_python_urllib.txt
Q: Use matplotlib.contour with complex data I'm trying to show a contour plot using matplotlib from a complex array. The array is a 2x2 complex matrix, generated by the (C like) method: for i in max_y: for j in max_x: pos_x = pos_x + step z = complex(pos_x,pos_y) c_arr[i][j] = complex_function...
Use matplotlib.contour with complex data
I'm trying to show a contour plot using matplotlib from a complex array. The array is a 2x2 complex matrix, generated by the (C like) method: for i in max_y: for j in max_x: pos_x = pos_x + step z = complex(pos_x,pos_y) c_arr[i][j] = complex_function(z) pos_y = pos_y + step I would like to p...
[ "matplotlib.pyplot.contour() allows complex-valued input arrays. It extracts real values from the array implicitly:\n#!/usr/bin/env python\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\n# generate data\nx = np.r_[0:100:30j]\ny = np.r_[0:1:20j]\nX, Y = np.meshgrid(x, y)\nZ = X*np.exp(1j*Y) # some arbit...
[ 3 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0005426200_matplotlib_python.txt
Q: Python attribute access error I am trying to customize attribute access in a class (python2.7). Say I define the following class: class testAttrAccess(object): def __init__(self): self.data = {"attr1":"value1","attr2":"value2"} def __getattr__(self,name): try: return self.data...
Python attribute access error
I am trying to customize attribute access in a class (python2.7). Say I define the following class: class testAttrAccess(object): def __init__(self): self.data = {"attr1":"value1","attr2":"value2"} def __getattr__(self,name): try: return self.data[name] except KeyError: ...
[ "__getattribute__() is still default, so it is reaching for self.attr2 instead of self.data['attr2']\n", "So if __getattribute__() is raising an AttributeError, then why isn't __getattr__() being called and returning the proper value?\n\nThat only applies if python is calling __getattribute__ for you as a part of...
[ 1, 1, 0, 0 ]
[]
[]
[ "attributes", "oop", "python" ]
stackoverflow_0005424595_attributes_oop_python.txt