content
stringlengths
85
101k
title
stringlengths
0
150
question
stringlengths
15
48k
answers
list
answers_scores
list
non_answers
list
non_answers_scores
list
tags
list
name
stringlengths
35
137
Q: python - Read file from and to specific lines of text I'm not talking about specific line numbers because i'm reading multiple files with the same format but vary in length. Say i have this text file: Something here... ... ... ... Start #I want this block of text a b c d e f g h i j ...
python - Read file from and to specific lines of text
I'm not talking about specific line numbers because i'm reading multiple files with the same format but vary in length. Say i have this text file: Something here... ... ... ... Start #I want this block of text a b c d e f g h i j k l m n End #until this line of th...
[ "If you simply want the block of text between Start and End, you can do something simple like:\nwith open('test.txt') as input_data:\n # Skips text before the beginning of the interesting block:\n for line in input_data:\n if line.strip() == 'Start': # Or whatever test is needed\n break\n ...
[ 37, 5, 3, 1 ]
[]
[]
[ "file", "linecache", "python" ]
stackoverflow_0007559397_file_linecache_python.txt
Q: Python Script to List Local Users using Win32net I'm using this script on a LAN to get each of the machines to list out their local administrators and users. There has been a security breach in our network where a couple students have created local admins off directory, and we need to find out where. The list it ...
Python Script to List Local Users using Win32net
I'm using this script on a LAN to get each of the machines to list out their local administrators and users. There has been a security breach in our network where a couple students have created local admins off directory, and we need to find out where. The list it imports just has the IP addresses of the entire networ...
[ "As you have it here, the file is closed after the first call to GetUsers() - you should dedent the F.close().\nMy guess is that the real problem is extraneous newline characters on the line, so try:\nfor CurrentIP in F.readlines():\n GetUsers( CurrentIP.strip() );\n\nF.close()\n\nAs a matter of Python style, fo...
[ 1 ]
[]
[]
[ "administration", "python", "winapi", "windows" ]
stackoverflow_0007560827_administration_python_winapi_windows.txt
Q: Handling hardware resources when testing with Jenkins I want to setup Jenkins to 1) pull our source code from our repository, 2) compile and build it 3) run the tests on an embedded device step 1 & 2 are quite easy and straight forward with Jenkins as for step 3, we have hundreds of those devices in various ver...
Handling hardware resources when testing with Jenkins
I want to setup Jenkins to 1) pull our source code from our repository, 2) compile and build it 3) run the tests on an embedded device step 1 & 2 are quite easy and straight forward with Jenkins as for step 3, we have hundreds of those devices in various versions of them, and I'm looking for a utility (preferable in...
[ "What I have found, is that the best thing to do, is have something like jenkins, or if you're using enterprise, electric commander, manage a resource 'pool' the pool is essentially virtual devices, but they have a property, such that you can call into a python script w/ either an ip-address or serial port and comm...
[ 1 ]
[]
[]
[ "embedded", "jenkins", "python" ]
stackoverflow_0007559224_embedded_jenkins_python.txt
Q: python read files from hard disk and return result depending on the pattern found what i wanna do is this; - read files from hard drive and find a pattern like the see if the file contains this string if it does return true or return false. In the function call it should print out nicely saying `the found in file...
python read files from hard disk and return result depending on the pattern found
what i wanna do is this; - read files from hard drive and find a pattern like the see if the file contains this string if it does return true or return false. In the function call it should print out nicely saying `the found in file.txt etc. this is what i have came up with so far import os path = '../' folder = os.li...
[ "import re\nm1 = re.compile(r'.*?\\.txt$')\npattern = 'yourpattern'\nm2 = re.compile(r'%s' % (pattern))\n\nfor file in filter(m1.search, os.listdir(somedir)):\n if m2.search(open(file,'r').read()):\n print file, 'contains', pattern\n else:\n print file, 'does not contain', pattern\n\nmodify outp...
[ 1 ]
[]
[]
[ "design_patterns", "file", "python" ]
stackoverflow_0007561019_design_patterns_file_python.txt
Q: Get the column names of a python numpy ndarray Let's say I have a data file called data.txt that looks like: TIME FX FY FZ 0 10 5 6 1 2 4 7 2 5 2 6 ... In Python run: import numpy as np myData = np.genfromtxt("data.txt", names=True) >>> print myData["TIME"] [0, 1, 2] The names at the top of my da...
Get the column names of a python numpy ndarray
Let's say I have a data file called data.txt that looks like: TIME FX FY FZ 0 10 5 6 1 2 4 7 2 5 2 6 ... In Python run: import numpy as np myData = np.genfromtxt("data.txt", names=True) >>> print myData["TIME"] [0, 1, 2] The names at the top of my data file will vary, so what I would like to do is fin...
[ "Try:\nmyData.dtype.names\n\nThis will return a tuple of the field names.\nIn [10]: myData.dtype.names\nOut[10]: ('TIME', 'FX', 'FY', 'FZ')\n\n" ]
[ 78 ]
[]
[]
[ "arrays", "names", "numpy", "python" ]
stackoverflow_0007561017_arrays_names_numpy_python.txt
Q: How to sum all the numbers of one column in python? I need to know how to sum all the numbers of a column in a CSV file. For example. My data looks like this: column count min max sum mean 80 29573061 2 40 855179253 28.92 81 28861459 2 40 802912711 27.82 82 28165830 2 40 778234605 27....
How to sum all the numbers of one column in python?
I need to know how to sum all the numbers of a column in a CSV file. For example. My data looks like this: column count min max sum mean 80 29573061 2 40 855179253 28.92 81 28861459 2 40 802912711 27.82 82 28165830 2 40 778234605 27.63 83 27479902 2 40 754170015 27.44 84 26800815...
[ "You could keep a running total using an \"augmented assignment\" +=:\ntotal=0\nfor row in reader:\n PxCount = 10**(-float(row[5])/10)*float(row[1])\n total+=PxCount\n\n\nTo skip the first line (header) in the csv file:\nwith open(file) as f:\n next(f) # read and throw away first line in f\n re...
[ 2, 2, 1 ]
[]
[]
[ "arrays", "python" ]
stackoverflow_0007561136_arrays_python.txt
Q: Django: What's the best way to create different "kinds" of users and use them interchangeably? I'm building a site similar to eBay. I have two kind of users: Sellers and Buyers. I've read this https://docs.djangoproject.com/en/1.3/topics/auth/#storing-additional-information-about-users and i've created a UserProfi...
Django: What's the best way to create different "kinds" of users and use them interchangeably?
I'm building a site similar to eBay. I have two kind of users: Sellers and Buyers. I've read this https://docs.djangoproject.com/en/1.3/topics/auth/#storing-additional-information-about-users and i've created a UserProfile(abstract) model and two other models: Seller and Buyer. Now, i've other model: Comment. Comment c...
[ "Groups. It's already part of Django authentication. \nhttps://docs.djangoproject.com/en/1.3/topics/auth/#groups\n\nHow should [I] relate them?\n\nRelate to the User. You get the profile from the User. You get the groups from the User.\nRelate to the primary, central, important entity. Think of a Profile as a...
[ 1 ]
[]
[]
[ "authentication", "django", "python" ]
stackoverflow_0007561318_authentication_django_python.txt
Q: Regex matching? I have the below regular expression in Python, ^1?$|^(11+?)\1+$ Since there is a pipe '|', I will split it into 2 regex, ^1?$ For this, it should validate 1 or empty value. Am I correct? ^(11+?)\1+$ For the above regex, it would validate value of 1111. The first pair of 11 is based on (11+?) and...
Regex matching?
I have the below regular expression in Python, ^1?$|^(11+?)\1+$ Since there is a pipe '|', I will split it into 2 regex, ^1?$ For this, it should validate 1 or empty value. Am I correct? ^(11+?)\1+$ For the above regex, it would validate value of 1111. The first pair of 11 is based on (11+?) and the second pair of 1...
[ "\nTed wrote:\nFor this, it should validate 1 or empty value. Am I correct?\n\nYes, that is correct.\n\nTed wrote:\nWhen I attempt to execute it in Python, it returns true only for 1111 but not 11 or empty value. Am I wrong somewhere?\n\nThe empty string does get matched. The following snippet:\n#!/usr/bin/env pyth...
[ 2, 0, 0, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0007561232_python_regex.txt
Q: From a .py file converted to an .exe (using py2exe), how do you import data from a written file? My program saves data to an external .py file for use later on. This works fine normally, however once converted to an executable, it saves a file externally, but only draws from the internal data. This is what the cod...
From a .py file converted to an .exe (using py2exe), how do you import data from a written file?
My program saves data to an external .py file for use later on. This works fine normally, however once converted to an executable, it saves a file externally, but only draws from the internal data. This is what the code looks like: def save_game(): with open("save.py") as _save: _save.write("""variables to ...
[ "Use the official method and use pickle instead.\n" ]
[ 2 ]
[]
[]
[ "py2exe", "python" ]
stackoverflow_0007561313_py2exe_python.txt
Q: What's the fastest implementation for bignum? (Java's bigInteger / Cython's int / gmpy / etc...) Are there any benchmark on this??? (I tried googling for some results but found none... and I couldn't test gmpy because gmplib wouldn't be installed on my laptop) thank you! A: First of all, I'm probably biased sinc...
What's the fastest implementation for bignum? (Java's bigInteger / Cython's int / gmpy / etc...)
Are there any benchmark on this??? (I tried googling for some results but found none... and I couldn't test gmpy because gmplib wouldn't be installed on my laptop) thank you!
[ "First of all, I'm probably biased since I'm the maintainer of gmpy.\ngmpy uses the GMP multiple-precision library and GMP is usually considered the fastest general purpose multiple-precision library. But when it's \"fastest\" depends on on the operation and the size of the values. When I compare the performance be...
[ 2 ]
[]
[]
[ "bignum", "cython", "java", "performance", "python" ]
stackoverflow_0007560850_bignum_cython_java_performance_python.txt
Q: Emacs: python-shell doesn't respond to RET When I start python-shell (or even just start python from M-x shell), Emacs gives the expected prompt: bash-3.2$ python Python 2.7.1 (r271:86832, Jun 16 2011, 16:59:05) [GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2335.15.00)] on darwin Type "help", "copyrigh...
Emacs: python-shell doesn't respond to RET
When I start python-shell (or even just start python from M-x shell), Emacs gives the expected prompt: bash-3.2$ python Python 2.7.1 (r271:86832, Jun 16 2011, 16:59:05) [GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2335.15.00)] on darwin Type "help", "copyright", "credits" or "license" for more information....
[ "After you do \"M-x shell\" and then \"python RET\", do \"C-h k RET\" and then what is displayed? the Help buffer should say that \"comint-send-input\" is the command that is executed for RET. If it isn't showing \"comint-send-input\" as the command executed by \"RET\" then there is probably something in one of you...
[ 3 ]
[]
[]
[ "aquamacs", "emacs", "python" ]
stackoverflow_0007558095_aquamacs_emacs_python.txt
Q: Graphing data, website views what platform to use I have been tasked with producing a analytic tool for some of the data which we get in about the activities the company i work for has with its clients. Last week i made a mock up view of one possible graph using some PHP and the Flot Jquery graphing tool. Unfortu...
Graphing data, website views what platform to use
I have been tasked with producing a analytic tool for some of the data which we get in about the activities the company i work for has with its clients. Last week i made a mock up view of one possible graph using some PHP and the Flot Jquery graphing tool. Unfortunatly I dont think I am going to be able to use flot fo...
[ "Have a look at Google Charts Tools http://code.google.com/apis/chart/\n", "Also have a look at jqPlot http://www.jqplot.com/ - it uses jQuery - a javascript library.\nI usually pass all my data down into the template, and the charts/graphs are rendered in the client's browser.\n", "Also check out d3.js. Beaut...
[ 3, 2, 0 ]
[]
[]
[ "django", "graph", "matplotlib", "python", "reportlab" ]
stackoverflow_0007517055_django_graph_matplotlib_python_reportlab.txt
Q: What's the difference in: Import module & From module import module? Here is my program that takes a list a words and sorts them from longest to shortest and breaks ties with the random module. import random def sort_by_length1(words): t = [] for word in words: t.append((len(word), random(), word...
What's the difference in: Import module & From module import module?
Here is my program that takes a list a words and sorts them from longest to shortest and breaks ties with the random module. import random def sort_by_length1(words): t = [] for word in words: t.append((len(word), random(), word)) t.sort(reverse = True) res = [] for length, randomm, wor...
[ "from random import random \n\nis equivalent to\nimport random as _random\nrandom = _random.random\n\nso if you only do\nimport random\n\nyou have to use \nrandom.random()\n\ninstead of\nrandom()\n\n", "random module has a random function. When you do import random you get the module, which obviously is not calla...
[ 3, 2, 1, 0 ]
[]
[]
[ "module", "python", "random" ]
stackoverflow_0007561371_module_python_random.txt
Q: How to find relatedness in Wordnet using Python I would like to find the relatedness (not similarity) between two words using Python. The hso (Hirst and St-Onge,1998), lesk (Banerjee and Pedersen, 2003), and vector (Patwardhan, 2003) algorithms are implemented in Perl here but i cant seem to find the same for Pyth...
How to find relatedness in Wordnet using Python
I would like to find the relatedness (not similarity) between two words using Python. The hso (Hirst and St-Onge,1998), lesk (Banerjee and Pedersen, 2003), and vector (Patwardhan, 2003) algorithms are implemented in Perl here but i cant seem to find the same for Python in the nltk lib. I need to use Python as it is par...
[ "There is also a web interface you could access - you could presumably write a python client to query the web interface to get the lesk or vector values.\nYou can find those web interfaces here...\nhttp://marimba.d.umn.edu\nhttp://talisker.d.umn.edu\nGood luck,\nTed\n", "I used NLTK to load WordNet into the Neo4j...
[ 5, 4, 2 ]
[]
[]
[ "nltk", "python", "similarity", "wordnet" ]
stackoverflow_0007335740_nltk_python_similarity_wordnet.txt
Q: Define Self as multiple attributes in Django I'm new to Django and building my first app. I want locations in my Admin section to be displayed by a combination of different attributes from the model. Currently they are shown by the icon by using the following code. def __unicode__(self): return self.icon ...
Define Self as multiple attributes in Django
I'm new to Django and building my first app. I want locations in my Admin section to be displayed by a combination of different attributes from the model. Currently they are shown by the icon by using the following code. def __unicode__(self): return self.icon I want to be able to add my other two attributes t...
[ "If I have understood you correctly then the following should produce the result that you are looking for (but you'll need to edit the attribute names):\ndef __unicode__(self):\n return u\"{0} ({1}, {2})\".format(self.icon, self.attrib1, self.attrib2)\n\n" ]
[ 2 ]
[]
[]
[ "django", "django_admin", "django_models", "python" ]
stackoverflow_0007561600_django_django_admin_django_models_python.txt
Q: How do I run twisted trial on all tests in a directory? How do I run trial so that it executes all tests within a directory? All my unit tests pass if I run trial on each file individually, but if I try something like... trial test/ on the test directory, it gives me one "PASSED", and the following message... Us...
How do I run twisted trial on all tests in a directory?
How do I run trial so that it executes all tests within a directory? All my unit tests pass if I run trial on each file individually, but if I try something like... trial test/ on the test directory, it gives me one "PASSED", and the following message... UserWarning: (for module __init__) not in path importer cache ...
[ "First of all: you can't call your top-level unit test package test. That's the name of Python's unit tests, so you will never be able to run your tests in an installed configuration, and depending on how your python is set up, you may end up importing python's own tests instead of your own.\nSecond: sys.path is a...
[ 5 ]
[]
[]
[ "python", "trial", "twisted" ]
stackoverflow_0007561073_python_trial_twisted.txt
Q: ParseException: Expected end of text I am trying to parse text using pyparsing. My function is shown below. Firstly, I construct a list containing all the terms in my dictionary (a dictionary of commonly used terms in my website). Then I set my grammar to be this list of commonly used words. Then I construct the Z...
ParseException: Expected end of text
I am trying to parse text using pyparsing. My function is shown below. Firstly, I construct a list containing all the terms in my dictionary (a dictionary of commonly used terms in my website). Then I set my grammar to be this list of commonly used words. Then I construct the ZeroOrMore object with the grammar. Finally...
[ "Instead of parseString, you may be more interested in using scanString or searchString. Unlike parseString, these functions skim through the input looking for matches, instead of requiring a complete match of all the content in the input string. scanString returns a generator, so for large input text, will give y...
[ 6, 4 ]
[]
[]
[ "parsing", "pyparsing", "python" ]
stackoverflow_0007560583_parsing_pyparsing_python.txt
Q: How to detect type of Form Field in Template in Django Hi guys i have simple Django Form , but I need to get type of this field elements and I made some special operations according to this. Is there an easy way to get type of Form Field in Django Template? Any help will be appreciated. A: For your ...
How to detect type of Form Field in Template in Django
Hi guys i have simple Django Form , but I need to get type of this field elements and I made some special operations according to this. Is there an easy way to get type of Form Field in Django Template? Any help will be appreciated.
[ "For your actual use case the image widget from the django-form-utils package should be a good match.\nOn more general level: If you simply want to modify the html generated by a standard widget you should subclass the widget and tweak the render-method. \nTake a look at this blog post to get the basic idea.\n" ]
[ 1 ]
[]
[]
[ "django", "django_forms", "django_templates", "python" ]
stackoverflow_0007560574_django_django_forms_django_templates_python.txt
Q: SQLAlchemy, sqlite and fork() What is the best way to use fork() in a SQLAlchemy + sqlite project? The SQLAlchemy documentation mentions that one should call create_engine() in the child but doesn't mention any other caveats, of which I am sure there are plenty (write locks, busy_timeout, dispose/connection-issues...
SQLAlchemy, sqlite and fork()
What is the best way to use fork() in a SQLAlchemy + sqlite project? The SQLAlchemy documentation mentions that one should call create_engine() in the child but doesn't mention any other caveats, of which I am sure there are plenty (write locks, busy_timeout, dispose/connection-issues, etc). Would the design issue of w...
[ "SQLite does not support write concurrency so only one client can write to a single database at any point in time. With that constraint in place, the only gain you will get from using transactions is the ability to roll them back. If you plan to use multiple databases, make sure you don't drag yourself into a deadl...
[ 1, 0 ]
[]
[]
[ "fork", "python", "sqlalchemy", "sqlite" ]
stackoverflow_0007561733_fork_python_sqlalchemy_sqlite.txt
Q: Why am I getting an AttributeError when trying to print out I am learning about urllib2 by following this tutorial http://docs.python.org/howto/urllib2.html#urlerror Running the code below yields a different outcome from the tutorial import urllib2 req = urllib2.Request('http://www.pretend-o-server.org') try: ...
Why am I getting an AttributeError when trying to print out
I am learning about urllib2 by following this tutorial http://docs.python.org/howto/urllib2.html#urlerror Running the code below yields a different outcome from the tutorial import urllib2 req = urllib2.Request('http://www.pretend-o-server.org') try: urllib2.urlopen(req) except urllib2.URLError, e: print e.rea...
[ "Depending on the error type, the object e may or may not carry that attribute.\nIn the link you provided there is a more complete example:\n\nNumber 2\n\nfrom urllib2 import Request, urlopen, URLError\nreq = Request(someurl)\ntry:\n response = urlopen(req)\nexcept URLError, e:\n if hasattr(e, 'reason'): # <-...
[ 8, 4, 1 ]
[]
[]
[ "attributes", "python", "urllib", "urllib2" ]
stackoverflow_0007554846_attributes_python_urllib_urllib2.txt
Q: Python 3 gives wrong output when dividing two large numbers? a = 15511210043330985984000000 # (25!) b = 479001600 # (12!) c = 6227020800 # (13!) On dividing ans = int(a/(b*c)) or ans = int((a/b)/c) we get ans equal to 5200299 instead of 5200300 A: In Python 3.x / means floati...
Python 3 gives wrong output when dividing two large numbers?
a = 15511210043330985984000000 # (25!) b = 479001600 # (12!) c = 6227020800 # (13!) On dividing ans = int(a/(b*c)) or ans = int((a/b)/c) we get ans equal to 5200299 instead of 5200300
[ "In Python 3.x / means floating point division and can give small rounding errors. Use // for integer division.\n\nans = a // (b*c)\n\n", "Try using integer division instead of float division.\n>>> 15511210043330985984000000 / (479001600 * 6227020800)\n5200299.999999999\n>>> 15511210043330985984000000 // (4790016...
[ 10, 4, 3 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0007561498_python_python_3.x.txt
Q: wxPython: SplitterWindow and SetMaxSize for one Subwindow I am quiet new to wxPython, so I hope there is nothing basic I am overlooking: I want to use a SplitterWindow to split up my Frame's content in two resizable subwindows (A and B), but I want one of the windows (B) to have a MaxSize set. Unfortunately, this ...
wxPython: SplitterWindow and SetMaxSize for one Subwindow
I am quiet new to wxPython, so I hope there is nothing basic I am overlooking: I want to use a SplitterWindow to split up my Frame's content in two resizable subwindows (A and B), but I want one of the windows (B) to have a MaxSize set. Unfortunately, this poses a problem: When I resize (enlarge), the whole frame (I a...
[ "I no longer actively work with wx so cannot test a solution. However I believe what you are looking for is\nSetSashGravity(0.5)\n\nThe default behaviour of a SplitterWindow is that upon a Resize event, only the Right or Bottom window will be resized. And in your case you have imposed a maximum size upon that win...
[ 4 ]
[]
[]
[ "python", "sizer", "splitter", "wxpython" ]
stackoverflow_0007561513_python_sizer_splitter_wxpython.txt
Q: Python how to join list of lists using join function I am new to Python. Have a question regarding join function. masterlist = [ ('ap172', ['33', '212-583-1173', '19 Boxer Rd.', 'New York', 'NY', '10005']), ('axe99', ['42', '212-582-5959', '315 W. 115th Street, Apt. 11B', 'New York', 'NY', '10027']) ] I w...
Python how to join list of lists using join function
I am new to Python. Have a question regarding join function. masterlist = [ ('ap172', ['33', '212-583-1173', '19 Boxer Rd.', 'New York', 'NY', '10005']), ('axe99', ['42', '212-582-5959', '315 W. 115th Street, Apt. 11B', 'New York', 'NY', '10027']) ] I want to print each element of list delimited by pipe. If I ...
[ "I think splitting up the tuples in the for loop would be cleaner.\nfor identifier, data in masterlist:\n print \"%s%s\" %(identifier, '|'.join(data))\n\n", "from itertools import chain\nfor symbol, items in masterlist:\n print \"|\".join(chain( [symbol], items))\n\n", "To get what you got you can try\nf...
[ 3, 2, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0007561650_python.txt
Q: Workaround Way To Install Numpy? Right now I have a script which uses numpy that I want to run automatically on a server. When I ssh in and run it manually, it works fine. However, when I set it to run as a cron job, it can't find numpy. Apparently due to the shared server environment, the cron demon for whatev...
Workaround Way To Install Numpy?
Right now I have a script which uses numpy that I want to run automatically on a server. When I ssh in and run it manually, it works fine. However, when I set it to run as a cron job, it can't find numpy. Apparently due to the shared server environment, the cron demon for whatever reason can't find numpy. I contact...
[ "If you have numpy installed somewhere on the server, you can add it into the import path for python; at the beginning of your script, do something like this:\nimport sys\nsys.path.append(\"/path/to/numpy\")\nimport numpy\n\n", "The cronjob runs with an empty environment. As such, it's either not using the same p...
[ 2, 2, 1, 1 ]
[]
[]
[ "cron", "installation", "numpy", "python" ]
stackoverflow_0007561969_cron_installation_numpy_python.txt
Q: Creating a loop to print html lists I need to create a html list similar in form to the following: <ul class="treeView"> <li> Root Item <ul class="collapsibleList"> <li> Sub-Folder 1 <ul> <li> Sub-Sub-Folder 1 ...
Creating a loop to print html lists
I need to create a html list similar in form to the following: <ul class="treeView"> <li> Root Item <ul class="collapsibleList"> <li> Sub-Folder 1 <ul> <li> Sub-Sub-Folder 1 <ul> <li>Item ...
[ "This might help to get you started on a simpler solution that uses a nested dictionary to represent your files instead of lists:\ndir = {}\nstart = rootdir.rfind('/')+1\nfor path, dirs, files in os.walk(rootdir):\n folders = path[start:].split('/')\n subdir = dict.fromkeys(files)\n parent = reduce(dict.ge...
[ 0 ]
[]
[]
[ "html", "loops", "python" ]
stackoverflow_0007561445_html_loops_python.txt
Q: Referencing files located in another directory in program I am currently working on a server. I've created my own directory but need access to files located in a different directory on the server. Basically, I have code that needs access to the files located in another directory on the server but I do not know how...
Referencing files located in another directory in program
I am currently working on a server. I've created my own directory but need access to files located in a different directory on the server. Basically, I have code that needs access to the files located in another directory on the server but I do not know how to go about doing this. Is there a command in my code that I c...
[ "os.chdir(\"/ruths/data/fec/efr\")\n", "You can specify the whole path when you enter a file name. For example, say you want to open a file \"foo.txt\" in the directory \"/home/docs\". You could run the command:\nf = open(\"/home/docs/foo.txt\")\n\nwhere f is now a handle for your file. Alternatively, the command...
[ 1, 1 ]
[]
[]
[ "directory", "file", "python" ]
stackoverflow_0007562313_directory_file_python.txt
Q: Use Python Framework or Build Own I am an experienced PHP developer (10 years) who has built 3 different custom frameworks for extreme high traffic sites. I have recently started to get into programming a lot of python, usually just for fun (algorithms). I am starting to develop a new site as my side project and w...
Use Python Framework or Build Own
I am an experienced PHP developer (10 years) who has built 3 different custom frameworks for extreme high traffic sites. I have recently started to get into programming a lot of python, usually just for fun (algorithms). I am starting to develop a new site as my side project and wanted to know if I should use a pre-exi...
[ "Learn from existing frameworks, I think. The Python web stack (wsgi, sqlalchemy, template engines, full stack frameworks, microframeworks) has spent a lot of time maturing. You'll have the opportunity to develop fast and learn from existing design.\n" ]
[ 1 ]
[]
[]
[ "frameworks", "python" ]
stackoverflow_0007562454_frameworks_python.txt
Q: How to return keys in original order in a dict I'm reading in a file and storing the info in a dict as it reads from top to bottom. I don't want to print out in a wrong order compared to the original file. Also, a very small question: I remember seeing it somewhere a short form of the if and else statement: if a ...
How to return keys in original order in a dict
I'm reading in a file and storing the info in a dict as it reads from top to bottom. I don't want to print out in a wrong order compared to the original file. Also, a very small question: I remember seeing it somewhere a short form of the if and else statement: if a == 'a': a = 'b' ? a = 'c' Do you know the exa...
[ "\nUse an OrderedDict.\na = 'b' if a == 'a' else 'c'\n\n", "You can use OrderedDict, or you can store the data in a list and index it with a dict, or store it in a dict and save the keys in a list as you go.\n", "I don't know about the dict but the short form you're looking for is the Does Python have a ternary...
[ 8, 1, 0, 0, 0 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0007562337_dictionary_python.txt
Q: PEP 354-like implementation of enums At one point enums were considered by the Python developers to add to the language, but they dropped the feature. Is there some implementation of the PEP 354? — the specification seems pretty robust. A: http://pypi.python.org/pypi/enum/ is the implementation of this PEP. A: ...
PEP 354-like implementation of enums
At one point enums were considered by the Python developers to add to the language, but they dropped the feature. Is there some implementation of the PEP 354? — the specification seems pretty robust.
[ "http://pypi.python.org/pypi/enum/ is the implementation of this PEP.\n", "The PyPI package enum provides a Python implementation of the data types described in this PEP.\nAlso, an implementation by Barry Warsaw.\nFinally, PEP 435 has been accepted for Python 3.4, the backport is enum34, and the advanced version ...
[ 1, 0 ]
[]
[]
[ "enums", "pep", "python" ]
stackoverflow_0007562671_enums_pep_python.txt
Q: Django using wrong foreign key for joins I have two relationships between models in Django, a many-to-many between Foo and Bar and a foreign key on Foo pointed towards Bar. When I do a query that involves both Foo and Bar, django insists on using the Foreign Key instead of the M2M to do the join. (The M2M is the r...
Django using wrong foreign key for joins
I have two relationships between models in Django, a many-to-many between Foo and Bar and a foreign key on Foo pointed towards Bar. When I do a query that involves both Foo and Bar, django insists on using the Foreign Key instead of the M2M to do the join. (The M2M is the real data here, the Foreign Key is just a bit o...
[ "I figured it out, and it was definitely an instance of 'should have used real code for the example'.\nI had the many-to-many relation on the Bar table called 'foos' (lets say). The foreign key was automatically creating a related_name on the Bar table called 'foo'. I was not actually calling:\nBar.objects.filter...
[ 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0007562406_django_python.txt
Q: Flushing python GAE datastore when unit testing I am following the recommendations on the app engine site for unit testing coding with GAE. I have set the PseudoRandomHRConsistencyPolicy probability to 0% to force the code to account for cases where the data is not yet consistent. The problem is that in my test ...
Flushing python GAE datastore when unit testing
I am following the recommendations on the app engine site for unit testing coding with GAE. I have set the PseudoRandomHRConsistencyPolicy probability to 0% to force the code to account for cases where the data is not yet consistent. The problem is that in my test suite I want to do some data setup (creating and addi...
[ "The key to doing this is noted near the end of the section on HRD testing:\n\nIn the local environment, performing a get() of an Entity that\n belongs to an entity group with an unapplied write will always make\n the results of the unapplied write visible to subsequent global\n queries. In production this is no...
[ 6 ]
[]
[]
[ "google_app_engine", "google_cloud_datastore", "python", "unit_testing" ]
stackoverflow_0007560666_google_app_engine_google_cloud_datastore_python_unit_testing.txt
Q: Deriving a class from TestCase throws two errors I have some basic setup/teardown code that I want to reuse in a whole bunch of unit tests. So I got the bright idea of creating some derived classes to avoid repeating code in every test class. In so doing, I received two strange errors. One, I cannot solve. Here...
Deriving a class from TestCase throws two errors
I have some basic setup/teardown code that I want to reuse in a whole bunch of unit tests. So I got the bright idea of creating some derived classes to avoid repeating code in every test class. In so doing, I received two strange errors. One, I cannot solve. Here is the unsolvable one: AttributeError: 'TestDesktopRo...
[ "It's because you're overriding __init__() incorrectly. Almost certainly, you don't want to override __init__() at all; you should do everything in setUp(). I've been using unittest for >10 years and I don't think I've ever overridden __init__().\nHowever, if you really do need to override __init__(), remember that...
[ 64, 1 ]
[]
[]
[ "python", "unit_testing" ]
stackoverflow_0007562775_python_unit_testing.txt
Q: Python inserting backslashes during regular expression I'm trying to do a regex to substitute in a backslash, but Python seems to be inserting a double-backslash, and I can't make it stop! >>> re.sub('a', '\\ b', 'a') '\\ b' Double backslash is supposed to be backslash (escape + backslash = backslash), but it end...
Python inserting backslashes during regular expression
I'm trying to do a regex to substitute in a backslash, but Python seems to be inserting a double-backslash, and I can't make it stop! >>> re.sub('a', '\\ b', 'a') '\\ b' Double backslash is supposed to be backslash (escape + backslash = backslash), but it ends up being literal. If I remove the double slash, it doesn't...
[ "It's not inserting a double backslash. That is simply the interactive interpreter showing the string as a string literal. Use print to see the actual string:\n>>> \"\\\\n\"\n'\\\\n'\n>>> print \"\\\\n\"\n\\n\n\n", "I suppose this isn't an answer (I second Liquid_Fire), but a suggestion:\n\"\\\\b\" -> \\b\nr\"\\b...
[ 6, 4, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0007562832_python_regex.txt
Q: String vs. Enum for checking type of object in Python Say I have an object called Tag, and I have three types of tags as indicated by an instance variable in the following way, class Tag(object): def __init__(self, name, type): self.name = name self.type = type t1 = Tag("blue", "cold") t2 = Ta...
String vs. Enum for checking type of object in Python
Say I have an object called Tag, and I have three types of tags as indicated by an instance variable in the following way, class Tag(object): def __init__(self, name, type): self.name = name self.type = type t1 = Tag("blue", "cold") t2 = Tag("red", "warm") t3 = Tag("black", "hot") Let's say I only...
[ "It's possible the performance difference may not be significant enough for you to worry about it. You should make a simple test if you're concerned about performance. Use Python's timeit module to test the performance of both cases.\n", "I wouldn't be worried about the performance of this unless profiling shows ...
[ 2, 2, 1, 0 ]
[]
[]
[ "enums", "performance", "python", "string", "types" ]
stackoverflow_0007561199_enums_performance_python_string_types.txt
Q: Matching 2 regular expressions in Python Is it possible to match 2 regular expressions in Python? For instance, I have a use-case wherein I need to compare 2 expressions like this: re.match('google\.com\/maps', 'google\.com\/maps2', re.IGNORECASE) I would expect to be returned a RE object. But obviously, Python e...
Matching 2 regular expressions in Python
Is it possible to match 2 regular expressions in Python? For instance, I have a use-case wherein I need to compare 2 expressions like this: re.match('google\.com\/maps', 'google\.com\/maps2', re.IGNORECASE) I would expect to be returned a RE object. But obviously, Python expects a string as the second parameter. Is th...
[ "Outside of the syntax clarification on re.match, I think I am understanding that you are struggling with taking two or more unknown (user input) regex expressions and classifying which is a more 'specific' match against a string. \nRecall for a moment that a Python regex really is a type of computer program. Most ...
[ 16, 2, 1, 1, 1, 1, 1, 1 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0007463233_python_regex.txt
Q: Does Wikipedia allow URL fetching via Google App Engine? I am writing a Python web app and in it I plan to leverage Wikipedia. When trying out some URL Fetching code I was able to fetch both Google and Facebook (via Google App Engine services), but when I attempted to fetch wikipedia.org, I received an exception. ...
Does Wikipedia allow URL fetching via Google App Engine?
I am writing a Python web app and in it I plan to leverage Wikipedia. When trying out some URL Fetching code I was able to fetch both Google and Facebook (via Google App Engine services), but when I attempted to fetch wikipedia.org, I received an exception. Can anyone confirm that Wikipedia does not accept these types ...
[ "urllib2 default user-agent is banned from wikipedia and it results in a 403 HTTP response.\nYou should modify your application user-agent with something like this:\n#Option 1\nimport urllib2\nopener = urllib2.build_opener()\nopener.addheaders = [('User-agent', 'MyUserAgent')]\nres= opener.open('http://whatsmyusera...
[ 5, 1 ]
[]
[]
[ "google_app_engine", "http", "python", "url", "web_applications" ]
stackoverflow_0007543571_google_app_engine_http_python_url_web_applications.txt
Q: Best way to handle Unicode in Python Anyone has a link or best practices for handling Unicode characters across python applications? or we need to convert the strings all over the place? [EDIT] Currently we are converting everything we post in urlencode to utf-8 but im wondering if there is a better way to handle ...
Best way to handle Unicode in Python
Anyone has a link or best practices for handling Unicode characters across python applications? or we need to convert the strings all over the place? [EDIT] Currently we are converting everything we post in urlencode to utf-8 but im wondering if there is a better way to handle that instead of calling encode('UTF-8')
[ "The main thing you need to do is understand unicode. Realise that a str in Python stores bytes, while a unicode object stores characters; they are distinct things, and shouldn't be treated as interchangeable. All your text strings should always be unicode objects; everything else is binary data.\nFor more, check o...
[ 2, 1 ]
[]
[]
[ "google_app_engine", "python", "unicode" ]
stackoverflow_0007560133_google_app_engine_python_unicode.txt
Q: Django get all related Choices where Event=Event.id I'm trying to create my first application using Django. I'm using the following code to create a list of events. {% for Event in location_list %} {{ Event.lat }}, {{ Event.long }}, html: "{{ Event.id }}", }] {% endfor %} I need to edit t...
Django get all related Choices where Event=Event.id
I'm trying to create my first application using Django. I'm using the following code to create a list of events. {% for Event in location_list %} {{ Event.lat }}, {{ Event.long }}, html: "{{ Event.id }}", }] {% endfor %} I need to edit the code so that {{ Event.id }} Becomes something like ...
[ "It looks like you're trying to follow relationships backward. \n# In the shell\n# fetch events from the db\n>>> events = Event.objects.all()\n>>> for event in events:\n... # fetch all the choices for this event\n... event_choices = event.choice_set.all() \n... print event_choices\n\nIn the template, yo...
[ 2 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0007562885_django_django_models_python.txt
Q: Django (nonrel), App engine and asynchronous database calls When using Google App Engine with Django-nonrel, is there any way to take advantage of the Async Datastore API when I declare my model classes with the Django API? A: Ok, I've investigated a bit more and found an alternative way to deal with having a D...
Django (nonrel), App engine and asynchronous database calls
When using Google App Engine with Django-nonrel, is there any way to take advantage of the Async Datastore API when I declare my model classes with the Django API?
[ "Ok, I've investigated a bit more and found an alternative way to deal with having a Django Model (i.e.: all Django features there) and still having access to the async API...\nMainly, using the datastore directly: \nfrom google.appengine.api import datastore\n\nand I already had methods to convert all my models to...
[ 3, 1 ]
[]
[]
[ "django", "django_nonrel", "google_app_engine", "google_cloud_datastore", "python" ]
stackoverflow_0007550083_django_django_nonrel_google_app_engine_google_cloud_datastore_python.txt
Q: Why does the xml.sax parser in Jython 2.5.2 turn two-character attributes in to tuples? When ever I encounter a 2-character attribute in my XML stream when parsing with xml.sax under Jython 2.5.2 it converts the attribute name to a tuple. No amount of coercion of that name allows me to extract the value for the at...
Why does the xml.sax parser in Jython 2.5.2 turn two-character attributes in to tuples?
When ever I encounter a 2-character attribute in my XML stream when parsing with xml.sax under Jython 2.5.2 it converts the attribute name to a tuple. No amount of coercion of that name allows me to extract the value for the attribute. I tried passing the tuple or converting it to a string and passing that. Both cases ...
[ "So, this is a reported bug in Jython. It took some digging but I found it in their bug archive:\nhttp://bugs.jython.org/issue1768\nThe second comment on the bug provides a work-around for the issue: use the _attrs.getValue() method to retrieve values off the attributes list. Like so:\nattrs._attrs.getValue('id')\n...
[ 0 ]
[]
[]
[ "jython", "python", "sax", "xml" ]
stackoverflow_0007562272_jython_python_sax_xml.txt
Q: Python: preventing caching from slowing me down I'm working on a web app with very aggressive caching. Virtually every component of the web app: views, partial views, controller output, disk loads, REST-API calls, Database queries. Everything that can be cached, at any level, is cached, all using decorators. Natur...
Python: preventing caching from slowing me down
I'm working on a web app with very aggressive caching. Virtually every component of the web app: views, partial views, controller output, disk loads, REST-API calls, Database queries. Everything that can be cached, at any level, is cached, all using decorators. Naturally, this is blazing fast, since the vast majority o...
[ "If you are serializing Python objects and not simple datatypes, and have to use pickle, try cPickle.HIGHEST_PROTOCOL:\nmy_serialized_object = cPickle.dumps(my_object, cPickle.HIGHEST_PROTOCOL)\n\nThe default protocol is compatible with older versions of Python, but you likely don't care about that.\nI just did a s...
[ 3 ]
[]
[]
[ "performance", "pickle", "python", "serialization" ]
stackoverflow_0007563141_performance_pickle_python_serialization.txt
Q: Should I merge images in memory (.py) or in view (HTML)? My facebook app lets the user upload an image, select what the image is (eyes, nose, mouth or other body part) and then can combine by selecting three random images by category and that's works fine and the code looks ok and readable though not very advanced...
Should I merge images in memory (.py) or in view (HTML)?
My facebook app lets the user upload an image, select what the image is (eyes, nose, mouth or other body part) and then can combine by selecting three random images by category and that's works fine and the code looks ok and readable though not very advanced: class CyberFazeHandler(BaseHandler): def get_random_ima...
[ "Which is more efficient depends on how it'll be used. If the user will be loading a lot of these mashups, it makes more sense to send them as separate images, because there will be fewer images for the browser to cache (a+b+c images instead of a*b*c).\nYour code has a much more egregious performance issue, however...
[ 1 ]
[]
[]
[ "facebook", "google_app_engine", "image_processing", "python", "random" ]
stackoverflow_0007552604_facebook_google_app_engine_image_processing_python_random.txt
Q: Fit simulated and experimental data points with Python I have written some code which performs a Monte Carlo simulation and produces curves of signal intensity versus time. The shape of such a curve depends on various parameters, two of which my collaborator wants to determine by the 'real life version' of the exp...
Fit simulated and experimental data points with Python
I have written some code which performs a Monte Carlo simulation and produces curves of signal intensity versus time. The shape of such a curve depends on various parameters, two of which my collaborator wants to determine by the 'real life version' of the experiment I am simulating. We are ready to compare her experi...
[ "For fitting your data with an arbitrary function you usually want the Levenberg–Marquardt algorithm, and that is what scipy.optimize.leastsq uses, so you are most likely using the correct function.\nHave a look at the tutorial in section 5.4 of this page and see if it helps.\nIt is also possible your underlying fu...
[ 3, 2, 2, 1 ]
[]
[]
[ "curve_fitting", "least_squares", "python", "scientific_computing", "scipy" ]
stackoverflow_0007445070_curve_fitting_least_squares_python_scientific_computing_scipy.txt
Q: Force Content-Type or expose request.data in Flask for known content-type I am recreating a service in Python/Flask and am running into an issue with the way the existing clients authenticate. I have to match the existing clients scheme for compatibility reasons. The existing clients take the username, password an...
Force Content-Type or expose request.data in Flask for known content-type
I am recreating a service in Python/Flask and am running into an issue with the way the existing clients authenticate. I have to match the existing clients scheme for compatibility reasons. The existing clients take the username, password and base64 encode it. This is not HTTP Basic Authentication, despite sounding sim...
[ "You want to look at the request.form object when dealing with urlencoded posts with normal mimetypes. In this case you have an unusual form, but here is a way to do it:\n# mkreq.py\nfrom urllib import urlencode\nimport urllib2\nfrom base64 import b64encode\n\ncredentials = {\n 'username': 'test@example....
[ 2, 1 ]
[]
[]
[ "base64", "content_type", "flask", "python" ]
stackoverflow_0007086448_base64_content_type_flask_python.txt
Q: How do i pass a generator yield statement to another function. -Python i've been reading on this site and can't seem to find the specific answer i want. i've tried reading david beasly's slides on iteration and generators but still can't quite get the answer i'm looking for though the question seems simple. i'm ru...
How do i pass a generator yield statement to another function. -Python
i've been reading on this site and can't seem to find the specific answer i want. i've tried reading david beasly's slides on iteration and generators but still can't quite get the answer i'm looking for though the question seems simple. i'm running a clock-based simulation (Brian for neural networking) and i have a ge...
[ "\"more specifically unsupported operand type '-' for int and generator\" Take the hint.\nYou can't use a generator in a trivial formula. You have to \"expand\" it with a generator expression.\nron= (d/(1-b))\n\nHas a generator b, right? b is not a \"value\". It's some kind of sequence of values.\nSo, you have t...
[ 2 ]
[]
[]
[ "generator", "python", "yield" ]
stackoverflow_0007563541_generator_python_yield.txt
Q: How do I serialize a Java object such that it can be deserialized by pickle (Python)? I'm using a Python service that uses pickled messages as part of its protocol. I'd like to query this service from Java, but to do so, I need to pickle my message on the client (Java). Are there any implementations of pickle th...
How do I serialize a Java object such that it can be deserialized by pickle (Python)?
I'm using a Python service that uses pickled messages as part of its protocol. I'd like to query this service from Java, but to do so, I need to pickle my message on the client (Java). Are there any implementations of pickle that run on the JVM (ideally with minimal dependencies)? Clarification: Modifying the server ...
[ "Some additional investigation yielded pyrolite, an MIT-licensed library that allows Java and .NET programs to interface with the Python world. In addition to remote object functionality, it (more importantly) includes a pickle serializer and de-serializer.\n", "You can use a Java JSON serializer like GSON or Ja...
[ 6, 1 ]
[]
[]
[ "java", "python", "serialization" ]
stackoverflow_0007558389_java_python_serialization.txt
Q: What is the best way to send messages to Socket.IO clients from various back-ends My Setup: I have an existing python script that is using Tweepy to access the Twitter Streaming API. I also have a website that shows aggregate real-time information from other sources from various back-ends. My Ideal Scenario: I wa...
What is the best way to send messages to Socket.IO clients from various back-ends
My Setup: I have an existing python script that is using Tweepy to access the Twitter Streaming API. I also have a website that shows aggregate real-time information from other sources from various back-ends. My Ideal Scenario: I want to publish real-time tweets as well as real-time updates of my other information to ...
[ "The best way I've found for this sort of thing is using a message broker. Personally, I've used RabbitMQ for this, which seems to meet the requirements mentioned in your comment on the other answer (socket.io 0.7 and scalable). If you use RabbitMQ, I'd recommend the amqp module for node, available through npm, and...
[ 2, 1 ]
[]
[]
[ "node.js", "python", "socket.io" ]
stackoverflow_0007564052_node.js_python_socket.io.txt
Q: how does the compile() work in python? I have two code which really confused me. def get_context(): __gc = globals() __lc = locals() def precompiler(code): exec code in __lc def compiler(script, scope): return compile(script, scope, 'eval') def executor(expr): return ...
how does the compile() work in python?
I have two code which really confused me. def get_context(): __gc = globals() __lc = locals() def precompiler(code): exec code in __lc def compiler(script, scope): return compile(script, scope, 'eval') def executor(expr): return eval(expr, __gc, __lc) return precompil...
[ "In your first example, you are executing 'abc=123' in your first context, and 'abc=345' in your second context. So 'test_var==123' is true in your first context and false in your second context.\nIn your second example, you have caught an interesting situation where the interpreter has removed test_var from the c...
[ 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0007564005_python.txt
Q: Debugging a Python Extension in Eclipse I have a Python extension that I have successfully built and used on Windows, OSX, and linux. I now need to be able to debug this Python extension. I am averse to the use of gdb at the command line, so I would really like to get this to work in Eclipse. To begin with, I ...
Debugging a Python Extension in Eclipse
I have a Python extension that I have successfully built and used on Windows, OSX, and linux. I now need to be able to debug this Python extension. I am averse to the use of gdb at the command line, so I would really like to get this to work in Eclipse. To begin with, I did my best to follow the instructions in htt...
[ "Which compiler are you using, MSVC or GCC? For MSVC, you can start python first, and attach the python_d.exe (windbg or visual studio), then you can load your module, setup the breakpoint, you can verify whether your module's symbol got loaded in the debug->module windows (MSVC).\n" ]
[ 1 ]
[]
[]
[ "c", "eclipse", "eclipse_cdt", "python" ]
stackoverflow_0006183294_c_eclipse_eclipse_cdt_python.txt
Q: What is the best way to encode string by public-key in python Is there any way to encode string by public-key? I found two packages, pycrypto and m2crypto. But I can not find how to use them. A: To encode a string using public key: #!/usr/bin/env python from M2Crypto import RSA, X509 x509 = X509.load_cert("rec...
What is the best way to encode string by public-key in python
Is there any way to encode string by public-key? I found two packages, pycrypto and m2crypto. But I can not find how to use them.
[ "To encode a string using public key:\n#!/usr/bin/env python \nfrom M2Crypto import RSA, X509\n\nx509 = X509.load_cert(\"recipient_cert.pem\")\nrsa = x509.get_pubkey().get_rsa()\nprint rsa.public_encrypt(\"your string to encrypt\", RSA.pkcs1_oaep_padding)\n\n" ]
[ 1 ]
[]
[]
[ "private_key", "public_key_encryption", "pycrypto", "python" ]
stackoverflow_0007563732_private_key_public_key_encryption_pycrypto_python.txt
Q: django foreign key admin interface and models structure (All code is some kind of pseudocode, just for better reading I have an Invoice model: class Invoice(models.Model): // many fields here I need to attach some products (with price for unit, and quantity fields) to this invoice, so I made additional ...
django foreign key admin interface and models structure
(All code is some kind of pseudocode, just for better reading I have an Invoice model: class Invoice(models.Model): // many fields here I need to attach some products (with price for unit, and quantity fields) to this invoice, so I made additional table: class InvoiceProduct(models.Model): product = mode...
[ "My suggestion for your customer's request\n\nHe wants one button (Add product) then pop-up windows appears, with fields: product, quantity, unit price. He fills them, press OK.\n\nDo NOT use the django admin for this. Only use it for people who want to access the data almost directly. In my head I see it just one ...
[ 0 ]
[]
[]
[ "admin", "django", "foreign_keys", "inline", "python" ]
stackoverflow_0007557341_admin_django_foreign_keys_inline_python.txt
Q: How to loop over histogram to get the color of the picture? In this answer about detecting the color of an image olooney said that "loop over the histogram and take the average of pixel color weighed by the pixel count". I ran the histogram like this: class ImageResize(webapp.RequestHandler): def get(self): ...
How to loop over histogram to get the color of the picture?
In this answer about detecting the color of an image olooney said that "loop over the histogram and take the average of pixel color weighed by the pixel count". I ran the histogram like this: class ImageResize(webapp.RequestHandler): def get(self): q = HomePage.all() q.filter("firm_name", "noise") ...
[ "Assuming hist2[0] is the histogram of the red pixels, then it is a histogram of pixel counts indexed by the red component. That means that sum(hist2[0]) is always going to be the number of pixels in the image, and len(hist2[0]) is always going to be 256. This will always give you the same answer, for all three of ...
[ 3 ]
[]
[]
[ "google_app_engine", "histogram", "python" ]
stackoverflow_0007563315_google_app_engine_histogram_python.txt
Q: Python Client/Server to stream logfile updates in realtime? We have applications on Solaris 10 servers that generate text logfiles. We need to stream these logfiles in realtime to a central server for monitoring of new events. Ideally we'd have a NFS-mount, and all our system would write their logs to there, and t...
Python Client/Server to stream logfile updates in realtime?
We have applications on Solaris 10 servers that generate text logfiles. We need to stream these logfiles in realtime to a central server for monitoring of new events. Ideally we'd have a NFS-mount, and all our system would write their logs to there, and the monitoring server could just pull them up from there. Unfortun...
[ "Check out Python's logging module. http://docs.python.org/library/logging.html\nIt contains the capability to log to files, streams, syslog, networked servers, and more. The cookbook contains examples or logging over the network. http://docs.python.org/howto/logging-cookbook.html#logging-cookbook\nThe module is fa...
[ 0, 0 ]
[]
[]
[ "logfiles", "python", "solaris_10", "streaming", "twisted" ]
stackoverflow_0007563560_logfiles_python_solaris_10_streaming_twisted.txt
Q: Passing a dictionary as a function parameter and calling the function in Python In the following code, how do I pass the dictionary to func2. How should func2 be called? def func2(a,**c): if len(c) > 0: print len(c) print c u={'a':1,'b':2} func2(1,u) A: Just as it accepts them: func2(1,**u) A: This won...
Passing a dictionary as a function parameter and calling the function in Python
In the following code, how do I pass the dictionary to func2. How should func2 be called? def func2(a,**c): if len(c) > 0: print len(c) print c u={'a':1,'b':2} func2(1,u)
[ "Just as it accepts them:\nfunc2(1,**u)\n\n", "This won't run, because there are multiple parameters for the name a.\nBut if you change it to:\ndef func2(x,**c):\n if len(c) > 0:\n print len(c)\n print c\n\nThen you call it as:\nfunc2(1, a=1, b=2)\n\nor\nu={'a':1,'b':2}\nfunc2(1, **u)\n\n", "This m...
[ 2, 1, 0 ]
[]
[]
[ "dictionary", "keyword_argument", "python" ]
stackoverflow_0007564883_dictionary_keyword_argument_python.txt
Q: Django many to many relation on generic models I have some models which will need to have many to many relation with some images. Instead of creating each relation individually, I want to have some generic model relations that I can use for all my models. So I've created Image and ImageItem models (I'm not sure if...
Django many to many relation on generic models
I have some models which will need to have many to many relation with some images. Instead of creating each relation individually, I want to have some generic model relations that I can use for all my models. So I've created Image and ImageItem models (I'm not sure if I'm on the right track..): from django.contrib.cont...
[ "Take a look at the docs explaining the GenericInlineModelAdmin.\nIf i get you right, the example does exactly what you want:\nclass Image(models.Model):\n image = models.ImageField(upload_to=\"images\")\n content_type = models.ForeignKey(ContentType)\n object_id = models.PositiveIntegerField()\n conten...
[ 1 ]
[]
[]
[ "django", "django_admin", "python" ]
stackoverflow_0007565277_django_django_admin_python.txt
Q: OOP concepts in Python Can any one suggest any links where Python object oriented concepts are clearly explained with example.. Data Abstraction Encapsulation Class Object Datahiding Inheritance Polymorphism A: Here is a good starting point: Introduction to OOP with Python.
OOP concepts in Python
Can any one suggest any links where Python object oriented concepts are clearly explained with example.. Data Abstraction Encapsulation Class Object Datahiding Inheritance Polymorphism
[ "Here is a good starting point: Introduction to OOP with Python.\n" ]
[ 4 ]
[]
[]
[ "oop", "python" ]
stackoverflow_0007565439_oop_python.txt
Q: Is there a way to override the "key" function for list.max() and list.sort() in the class of the list items? I have multiple subclasses of a superclass that store something in a instance_of_a_class.value and I override __cmp__() to provide reasonable ==, <, > etc. comparisons. However, I have multiple places in my...
Is there a way to override the "key" function for list.max() and list.sort() in the class of the list items?
I have multiple subclasses of a superclass that store something in a instance_of_a_class.value and I override __cmp__() to provide reasonable ==, <, > etc. comparisons. However, I have multiple places in my code where I do min(list_of_instances_of_class, key=lambda _: _.value) or max(list_of_instances_of_class, key=lam...
[ "Just implement __lt__:\nclass Obj(object):\n def __init__(self, value):\n self.value = value\n def __lt__(self, other):\n return self.value < other.value\n def __repr__(self):\n return 'Obj(%r)' % self.value\n\nobj_list = [Obj(2), Obj(1), Obj(4), Obj(3)]\n\nprint max(obj_list)\nprint ...
[ 6, 1 ]
[]
[]
[ "python" ]
stackoverflow_0007565630_python.txt
Q: enumerating all possible strings of length K from an alphabet in Python Possible Duplicate: is there any best way to generate all possible three letters keywords how can I enumerate all strings of length K from an alphabet L, where L is simply a list of characters? E.g. if L = ['A', 'B', 'C'] and K = 2, I'd like...
enumerating all possible strings of length K from an alphabet in Python
Possible Duplicate: is there any best way to generate all possible three letters keywords how can I enumerate all strings of length K from an alphabet L, where L is simply a list of characters? E.g. if L = ['A', 'B', 'C'] and K = 2, I'd like to enumerate all possible strings of length 2 that can be made up with the ...
[ "this is part of the Python Documentation\nEDIT2: of course the right answer is the product, thanks for the comment\nprint [''.join(x) for x in product('ABC', repeat=3)]\n\nprints 27 elements\n['AAA', 'AAB', 'AAC', 'ABA', 'ABB', 'ABC', 'ACA', 'ACB', 'ACC', 'BAA', 'BAB', \n'BAC', 'BBA', 'BBB', 'BBC', 'BCA', 'BCB', ...
[ 1, 0 ]
[]
[]
[ "combinatorics", "python" ]
stackoverflow_0007565675_combinatorics_python.txt
Q: python dictionary- two keys to each value Hi I am fairly sure you can't do this but I was wondering if you could have a dictionary where each of the values can be accessed via two keys without duplicating the dictionary. The reason I want to do this is that the two keys will represent the same thing but one will b...
python dictionary- two keys to each value
Hi I am fairly sure you can't do this but I was wondering if you could have a dictionary where each of the values can be accessed via two keys without duplicating the dictionary. The reason I want to do this is that the two keys will represent the same thing but one will be a shortened version eg. 'TYR' and 'Y' will bo...
[ "Just place same (mutable) object in two places. If you change the object it will change in both places in the dictionary. Only donwside is that you have to add and delete both explicitly (you could create some helper method though).\nIn [4]: d = {}\nIn [5]: c = [1,2]\nIn [7]: d[1] = c\nIn [8]: d[2] = c\nIn [9]: d\...
[ 5 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0007565957_dictionary_python.txt
Q: Stty getting insane on using Python subprocess I am facing a weird problem. Every time I call a particular command cmd via subprocess.Popen(cmd).wait(), the stty gets bad (does not echo my further commands on the shell, newline does not work, etc.) when the command is over. I have to run stty sane to get the stty...
Stty getting insane on using Python subprocess
I am facing a weird problem. Every time I call a particular command cmd via subprocess.Popen(cmd).wait(), the stty gets bad (does not echo my further commands on the shell, newline does not work, etc.) when the command is over. I have to run stty sane to get the stty fine again. What could be the reason for this? Upda...
[ "It's possible that the command you're running is emitting some escape sequences into your terminal that are changing its mode or other settings. Programs that need the full terminal capability do that (e.g. text based editors).\nCapturing the standard output of the program you're executing and preventing it from g...
[ 0 ]
[]
[]
[ "debugging", "linux", "python", "stty", "subprocess" ]
stackoverflow_0007565753_debugging_linux_python_stty_subprocess.txt
Q: nginx+uwsgi+python2.7 come up with a bottleneck that can not pass 20000x40000 benchmarking i'm coming up with a bottleneck that my server can't pass a 20000x40000 benchmark test no matter what adjustments i made. the server have 128G Ram and with an Xeon 6 core cpu, centos5.6-64bit, in a good shape. i try combinat...
nginx+uwsgi+python2.7 come up with a bottleneck that can not pass 20000x40000 benchmarking
i'm coming up with a bottleneck that my server can't pass a 20000x40000 benchmark test no matter what adjustments i made. the server have 128G Ram and with an Xeon 6 core cpu, centos5.6-64bit, in a good shape. i try combinations including: nginx + uwsgi + python2.7 nginx + apache + mod_wsgi + python2.7 apache + mod_wsg...
[ "Allowing such amount of concurrent connections on a single system requires a huge list of kernel tuning and probably you will never be able to manage such load in production.\nFirst of all you have to increase the number of ephemeral port, the socket backlog queue, the number of allowed file descriptor per process...
[ 2 ]
[]
[]
[ "apache", "benchmarking", "nginx", "python", "uwsgi" ]
stackoverflow_0007565742_apache_benchmarking_nginx_python_uwsgi.txt
Q: find optional middle of string surrounded by lazy, regex I'm using python and regex to try to extract the optional middle of a string. >>> re.search(r'(.*?)(HELLO|BYE)?(.*?END)', r'qweHELLOsdfsEND').groups() ('', None, 'qweHELLOsdfsEND') #what I want is ('qwe', 'HELLO', 'sdfsEND') >>> re.search(r'(.*?)(HELLO|BYE)...
find optional middle of string surrounded by lazy, regex
I'm using python and regex to try to extract the optional middle of a string. >>> re.search(r'(.*?)(HELLO|BYE)?(.*?END)', r'qweHELLOsdfsEND').groups() ('', None, 'qweHELLOsdfsEND') #what I want is ('qwe', 'HELLO', 'sdfsEND') >>> re.search(r'(.*?)(HELLO|BYE)?(.*?END)', r'qweBLAHsdfsEND').groups() ('', None, 'qweBLAHsdf...
[ "Your regex fails because the first part is happy with matching the empty string, the second part fails (which is OK since it's optional), so the third part captures all. Solution: Make the first part match anything up to HELLO or END:\n>>> re.search(r'((?:(?!HELLO|BYE).)*)(HELLO|BYE)?(.*?END)', r'qweHELLOsdfsEND')...
[ 2, 1 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0007566067_python_regex.txt
Q: How do I filter on composite keys? I need filter this view: function (doc) { if (doc.doc_type == 'asd'){ emit([doc.date, doc.string_key_0, doc.string_key_1], doc.list_field); }; } I do: key_filter_0 = ['START_TIME', 'STRING0', 'STRING1'] key_filter_1 = ['END_TIME', 'STRING0', 'STRING1'] VIEW[key_f...
How do I filter on composite keys?
I need filter this view: function (doc) { if (doc.doc_type == 'asd'){ emit([doc.date, doc.string_key_0, doc.string_key_1], doc.list_field); }; } I do: key_filter_0 = ['START_TIME', 'STRING0', 'STRING1'] key_filter_1 = ['END_TIME', 'STRING0', 'STRING1'] VIEW[key_filter_0:key_filter_1] but the view only...
[ "There's no such thing as 'key filters' in CouchDB.\nEvery item you emit into your view will be sorted by its key, and you can then find all items between a given startkey and endkey. In your case, items are first sorted by date then string_key_0 then string_key_1.\nIt sounds like you were expecting to only see ite...
[ 1 ]
[]
[]
[ "couchdb", "python" ]
stackoverflow_0007563918_couchdb_python.txt
Q: DRY version of a list What would be the most efficient way to do the following: genres = [value_from_key(wb, 'Genre (1)', n), value_from_key(wb, 'Genre (2)', n), value_from_key(wb, 'Genre (3)', n), value_from_key(wb, 'Genre (4)', n),] I tried doing it with a list comprehension -- gen...
DRY version of a list
What would be the most efficient way to do the following: genres = [value_from_key(wb, 'Genre (1)', n), value_from_key(wb, 'Genre (2)', n), value_from_key(wb, 'Genre (3)', n), value_from_key(wb, 'Genre (4)', n),] I tried doing it with a list comprehension -- genres = [value_from_key(wb, '...
[ "Replace the square brackets [1,4] with round braces (1,4) in your call to range:\ngenres = [value_from_key(wb, 'Genre (%s)'%(i), n) for i in range(1,4)]\n\n", "\nbut it kept raising a TypeError saying object is unsubscriptable.\n\nBecause range[1,4] means \"use the tuple (1, 4) as a subscript for range\". Since ...
[ 5, 2 ]
[]
[]
[ "python" ]
stackoverflow_0007565883_python.txt
Q: PyGTK nonblocking Is there a way to not block PyGTK while performing some expensive operation? I know threading would work but it would take a lot of code and setup. Thanks, A: Setting up a background thread in PyGTK is not all that difficult. A: Threading is not really a good choice in pygtk. Just check the m...
PyGTK nonblocking
Is there a way to not block PyGTK while performing some expensive operation? I know threading would work but it would take a lot of code and setup. Thanks,
[ "Setting up a background thread in PyGTK is not all that difficult.\n", "Threading is not really a good choice in pygtk. Just check the main loop for events in your expensive loop by doing, and let it do its thing:\nwhile my_operation_running:\n\n <my code>\n\n while gtk.events_pending():\n gtk.main_...
[ 3, 1, 0 ]
[]
[]
[ "pygtk", "python" ]
stackoverflow_0007435419_pygtk_python.txt
Q: Two basic ANTLR questions I'm trying to use ANTLR to take a simple grammar and produce assembly output. My language of choice in ANTLR is Python. Many tutorials seem very complicated or elaborate on things that aren't relevant to me; I only really need some very simple functionality. So I have two questions: 'Retu...
Two basic ANTLR questions
I'm trying to use ANTLR to take a simple grammar and produce assembly output. My language of choice in ANTLR is Python. Many tutorials seem very complicated or elaborate on things that aren't relevant to me; I only really need some very simple functionality. So I have two questions: 'Returning' values from one rule to ...
[ "\n\nReturning values from one rule to another\nLet's say you want to parse simple expressions and provide a map of variables at runtime that can be used in these expressions. A simple grammar including the custom Python code, returns statements from the rules, and the parameter vars to the entry point of your gram...
[ 10 ]
[]
[]
[ "antlr", "assembly", "python" ]
stackoverflow_0007565974_antlr_assembly_python.txt
Q: PyGTK: upon profiling, gtk.main() takes more time than expected, how do I know if this is reasonable? My program is a visualizer that is constantly updating the display. I am trying to optimize it to increase the framerate, and my largest cost is gtk._gtk.main: ncalls tottime percall cumtime percall filenam...
PyGTK: upon profiling, gtk.main() takes more time than expected, how do I know if this is reasonable?
My program is a visualizer that is constantly updating the display. I am trying to optimize it to increase the framerate, and my largest cost is gtk._gtk.main: ncalls tottime percall cumtime percall filename:lineno(function) 1 9.159 9.159 45.476 45.476 {gtk._gtk.main} 868 8.146 0.00...
[ "You're interpreting the profiling data wrong.\ngtk.main() is really just running your program as the user interacts with it. What you're seeing is that it takes time to run your program, not gtk.main() itself.\n" ]
[ 1 ]
[]
[]
[ "gtk", "profiling", "pygtk", "python" ]
stackoverflow_0006564004_gtk_profiling_pygtk_python.txt
Q: Regular expression to match only two numbers I have such string: something: 20 kg/ something: 120 kg I have this regex ("[0-9]{1,2} kg", string), but it returns 20kg both times. I need to return 20kg only in first case. A: Try this: (?<!\d)\d{1,2}\s+kg The (?<!...) is a negative look behind. So it matches one...
Regular expression to match only two numbers
I have such string: something: 20 kg/ something: 120 kg I have this regex ("[0-9]{1,2} kg", string), but it returns 20kg both times. I need to return 20kg only in first case.
[ "Try this:\n(?<!\\d)\\d{1,2}\\s+kg\n\nThe (?<!...) is a negative look behind. So it matches one or two digits not preceded by a digit. I also changed the literal space with one or more space chars.\nSeeing you've asked Python questions, here's a demo in Python:\n#!/usr/bin/env python\nimport re\nstring = 'something...
[ 3 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0007566749_python_regex.txt
Q: Facebook permissions for viewing photos I'm writing a Facebook application that accesses the user's friends' photos. For some reason, I can only access certain photos. I have narrowed it down to only being able to access photos with the 'Friends of Friends' privacy setting turned ON. The pictures I can't access s...
Facebook permissions for viewing photos
I'm writing a Facebook application that accesses the user's friends' photos. For some reason, I can only access certain photos. I have narrowed it down to only being able to access photos with the 'Friends of Friends' privacy setting turned ON. The pictures I can't access still have the 'Friends' privacy settings turn...
[ "There's a privacy setting which can override this, check the settings on the friends' account to see what their options for 'How people bring your info to apps they use' setting is - it's on https://www.facebook.com/settings/?tab=privacy and allows users to stop apps their friends use from accessing any data about...
[ 1 ]
[]
[]
[ "facebook", "facebook_graph_api", "json", "python" ]
stackoverflow_0007565795_facebook_facebook_graph_api_json_python.txt
Q: Python: parsing binary stl file I'm having some difficulties while parsing a binary STL file with Python (2.7.1 32-bit and Windows 7 64). The file is a about 450k in size, but my parser suddenly stops working after parsing 244 triangles out of ~8600 with en exception of struct.unpack: Exception unpack requires a...
Python: parsing binary stl file
I'm having some difficulties while parsing a binary STL file with Python (2.7.1 32-bit and Windows 7 64). The file is a about 450k in size, but my parser suddenly stops working after parsing 244 triangles out of ~8600 with en exception of struct.unpack: Exception unpack requires a string argument of length 12 The cu...
[ "Your unpack function calls f.read twice. I suspect you've walked off the end of the file.\nYou'll also have trouble with reading the file in text mode on Windows. Any incidental occurrences of \\r\\n will be read in as \\n. Make the following change to avoid this problem.\nf = open(infilename, \"rb\")\n\n" ]
[ 10 ]
[]
[]
[ "binaryfiles", "python" ]
stackoverflow_0007566825_binaryfiles_python.txt
Q: south & mysql problem can somebody help me out on this: I have installed recently south to use it updating changes in my django-based project on the production server (Appache 2.0, MySql 5.0, python 2.5, Mysqldb for python, django 1.3, and south 0.7.3). After converting my app named signature to south, which was ...
south & mysql problem
can somebody help me out on this: I have installed recently south to use it updating changes in my django-based project on the production server (Appache 2.0, MySql 5.0, python 2.5, Mysqldb for python, django 1.3, and south 0.7.3). After converting my app named signature to south, which was done successfully, the comm...
[ "The error is saying that there is a missing table in your database called \"chold.signupsetup\".\nYou should check that that this table exists, and if not create it. The usual way of creating tables for django apps is to run syncdb:\n$ python manage.py syncdb\n\nThen try running the migration again.\n" ]
[ 0 ]
[]
[]
[ "django", "django_south", "mysql", "python" ]
stackoverflow_0007553306_django_django_south_mysql_python.txt
Q: How to restrict users from creating a python object? I have a domain object User. I am looking for some way to restrict other python classes form creating any objects of `user' type. A: You can use closures to hide the object away from the code but please accept that doing it in Python is considered very unpytho...
How to restrict users from creating a python object?
I have a domain object User. I am looking for some way to restrict other python classes form creating any objects of `user' type.
[ "You can use closures to hide the object away from the code but please accept that doing it in Python is considered very unpythonic and is pretty much against the philosophy of the language. You are supposed to document proper behavior, not guard against your users.\nclass KittenFactory(object):\n def __create_t...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0007566849_python.txt
Q: Session variable fetched into a local var changes when operating on the local one i noticed a strange behaviour when interacting with session variables in Django. In one of my app i created a middleware.py file containing a function that copy a session variable that stores an object into a local one and then i cha...
Session variable fetched into a local var changes when operating on the local one
i noticed a strange behaviour when interacting with session variables in Django. In one of my app i created a middleware.py file containing a function that copy a session variable that stores an object into a local one and then i change an attribute of the object from the local var. It happens that the changes i make t...
[ "user is a mutable object, so it's passed by reference. Anything is correct.\n", "This is nothing to do with sessions, but a simple consequence of how Python mutable objects work. When you do user = request.session['user'] you are getting a reference to the object, exactly as you would with any other mutable obje...
[ 1, 1 ]
[]
[]
[ "django", "python", "session" ]
stackoverflow_0007567112_django_python_session.txt
Q: Using Python, how do I close a file in use by another user over a network? I have a program that creates a bunch of movie files. I runs as a cron job and every time it runs the movies from the previous iteration are moved to a 'previous' folder so that there is always a previous version to look at. These movie fil...
Using Python, how do I close a file in use by another user over a network?
I have a program that creates a bunch of movie files. I runs as a cron job and every time it runs the movies from the previous iteration are moved to a 'previous' folder so that there is always a previous version to look at. These movie files are accessed across a network by various users and that's where I'm running i...
[ "This question has nothing to do with Python, and everything to do with the particular operating system and file system you're using. Could you please provide these details?\nAt least in Windows you can use Sysinternals Handle to force a particular handle to a file to be closed. Especially as this file is opened b...
[ 3, 0, 0 ]
[]
[]
[ "file_io", "python" ]
stackoverflow_0007567029_file_io_python.txt
Q: Python: right way to build a string by joining a smaller substring N times What is the right "pythonic" way to do the following operation? s = "" for i in xrange(0, N): s += "0101" E.g. in Perl it would be: $s = "0101" x $N A: Nearly the same as Perl: "0101" * N A: The most Pythonic way would be s = "0101...
Python: right way to build a string by joining a smaller substring N times
What is the right "pythonic" way to do the following operation? s = "" for i in xrange(0, N): s += "0101" E.g. in Perl it would be: $s = "0101" x $N
[ "Nearly the same as Perl:\n\"0101\" * N\n\n", "The most Pythonic way would be\ns = \"0101\" * N\n\nOther methods include:\n\nuse StringIO, which is a file-like object for building strings:\nfrom StringIO import StringIO\n\nuse \"\".join; that is\n`\"\".join(\"0101\" for i in xrange(N)`\n\nuse your algorithm. In a...
[ 9, 2 ]
[]
[]
[ "python", "string" ]
stackoverflow_0007567275_python_string.txt
Q: Weird stuff happening while importing modules I hate to give the question this heading but I actually don't know whats happening so here it goes. I was doing another project in which I wanted to use logging module. The code is distributed among few files & instead of creating separate logger objects for seperate f...
Weird stuff happening while importing modules
I hate to give the question this heading but I actually don't know whats happening so here it goes. I was doing another project in which I wanted to use logging module. The code is distributed among few files & instead of creating separate logger objects for seperate files, I thought of creating a logs.py with contents...
[ "logging.getLogger('') will return exactly the same object each time you call it. So each time you instantiate a Logger (why use old-style classes here?) you are attaching one more handler resulting in printing to one more target. As all your targets pointing to the same thing, the last call to .debug() will print ...
[ 2, 2, 1 ]
[]
[]
[ "python", "python_2.7", "python_module" ]
stackoverflow_0007566942_python_python_2.7_python_module.txt
Q: Recommendation for Optimum Template Engine for Python Web Dev in a Particular Use Case For Python Web Development, there is a large selection of template engines. My work is limited to a fairly narrow/specific set of use cases. A description of these might suggest to someone who has a working knowledge with many/m...
Recommendation for Optimum Template Engine for Python Web Dev in a Particular Use Case
For Python Web Development, there is a large selection of template engines. My work is limited to a fairly narrow/specific set of use cases. A description of these might suggest to someone who has a working knowledge with many/most of them, that one of them is better suited for my particular use cases. In other words, ...
[ "If your templating requirements are really simple, then I suggest you to use Python's builtin String Formatting engine...\n", "You may want to take a look at Jinja2. It offers precompilation of templates, allows familiar Python syntax and is framework-agnostic.\n", "Mako, Jinja2, Cheetah and the Django templat...
[ 1, 1, 0 ]
[]
[]
[ "jquery", "python", "template_engine" ]
stackoverflow_0007567108_jquery_python_template_engine.txt
Q: How to control Apache via Django to connect to mongoose(another HTTP server)? I have been doing lots of searching and reading to solve this. The main goal is let a Django-based web management system connecting to a device which runs a http server as well. Django will handle user request and ask device for the real...
How to control Apache via Django to connect to mongoose(another HTTP server)?
I have been doing lots of searching and reading to solve this. The main goal is let a Django-based web management system connecting to a device which runs a http server as well. Django will handle user request and ask device for the real data, then feedback to user. Now I have a "kinda-work-in-concept" solution: Brows...
[ "You could use httplib or urllib2 (both supplied in the Python standard library) in your Django view to send HTTP requests to the device running mongoose.\nAlternatively you could use the Requests library which provides a less verbose API for generating HTTP requests - see also this blog post.\n(Also, I would stron...
[ 0, 0 ]
[]
[]
[ "apache", "django", "mod_python", "mod_wsgi", "python" ]
stackoverflow_0007565812_apache_django_mod_python_mod_wsgi_python.txt
Q: Help parsing text file in python Really been struggling with this one for some time now, i have many text files with a specific format from which i need to extract all the data and file into different fields of a database. The struggle is tweaking the parameters for parsing, ensuring i get all the info correctly. ...
Help parsing text file in python
Really been struggling with this one for some time now, i have many text files with a specific format from which i need to extract all the data and file into different fields of a database. The struggle is tweaking the parameters for parsing, ensuring i get all the info correctly. the format is shown below: WHITESPACE ...
[ "\nYou are splitting the whole line into words. You need to split into first word, second word and the rest. Like line.split(None, 2).\nIt would probably use regular expressions. And use the oposite logic, that is if it starts with number 1 through 5, use it, otherwise pass. Like:\npattern = re.compile(r'([12345])\...
[ 2, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007566551_python.txt
Q: Relative redirect in Django The url config of my app currently looks like this: from django.conf.urls.defaults import patterns from django.views.generic.simple import redirect_to urlpatterns = patterns("myapp.views", (r"^$", redirect_to, {"url": "main/"}), (r"^(?P<title>.+)/$", "article"), ... ) This...
Relative redirect in Django
The url config of my app currently looks like this: from django.conf.urls.defaults import patterns from django.views.generic.simple import redirect_to urlpatterns = patterns("myapp.views", (r"^$", redirect_to, {"url": "main/"}), (r"^(?P<title>.+)/$", "article"), ... ) This works fine when the app’s urls a...
[ "In django 1.4 you will be able to use the function reverse_lazy():\nfrom django.core.urlresolvers import reverse_lazy\nurlpatterns = patterns(\"myapp.views\",\n (r\"^$\", redirect_to, {\"url\": reverse_lazy(\"myapp_title\")}),\n (r\"^(?P<title>.+)/$\", \"article\", name=\"myapp_title\"),\n ...\n)\n\nrever...
[ 2 ]
[]
[]
[ "django", "http", "python", "redirect" ]
stackoverflow_0007568000_django_http_python_redirect.txt
Q: Decrypt in Python an encrypted message in Java I'm trying to decrypt in Python (with M2Crypto) an encrypted message generated in Java with this library My code (which I actually found here) works decrypting messages encrypted by itself, but not from Java's library, I get the following error: EVPError: 'wrong final...
Decrypt in Python an encrypted message in Java
I'm trying to decrypt in Python (with M2Crypto) an encrypted message generated in Java with this library My code (which I actually found here) works decrypting messages encrypted by itself, but not from Java's library, I get the following error: EVPError: 'wrong final block length' I have tried both *aes_128_cbc* and ...
[ "What does \"ascii encoded\" mean? As you know, my code expected base64 input and produced base64 output. Removing the calls to b64decode and b64encode in the encrypt and decrypt functions will let you pass in raw data, then it'll be up to you to decode the input from Java into raw bytes.\n" ]
[ 1 ]
[]
[]
[ "aes", "java", "m2crypto", "python" ]
stackoverflow_0007567520_aes_java_m2crypto_python.txt
Q: Unknown syntax error on creating a simple widget in Tkinter I was following this tutorial (http://sebsauvage.net/python/gui/#add_button) on making widgets with Tkinter. I have been making sure to follow it very carefully but, when I run it now in step 10, I get an "Invalid Syntax" Error. Here the code: import tki...
Unknown syntax error on creating a simple widget in Tkinter
I was following this tutorial (http://sebsauvage.net/python/gui/#add_button) on making widgets with Tkinter. I have been making sure to follow it very carefully but, when I run it now in step 10, I get an "Invalid Syntax" Error. Here the code: import tkinter class simpleapp_tk(tkinter.Tk): def __init__(self,paren...
[ "Replace u\"Click me !**\" with \"Click me !**\"\nThe u indicates a Unicode string (type unicode instead of str) in Python 2, but in Python 3, the distinction between the str and unicode types is gone and the u is scrapped.\n", "There is no u prefix for unicode strings in Python 3.\n" ]
[ 4, 2 ]
[]
[]
[ "python", "python_3.x", "syntax_error", "tkinter" ]
stackoverflow_0007568139_python_python_3.x_syntax_error_tkinter.txt
Q: Error: "can only concatenate tuple (not "list") to tuple" in urls, Django I've got an error in my urls: TypeError at / can only concatenate tuple (not "list") to tuple Can't get what I did wrong. Where is the list in there? from django.conf import settings from django.conf.urls.defaults import patterns, includ...
Error: "can only concatenate tuple (not "list") to tuple" in urls, Django
I've got an error in my urls: TypeError at / can only concatenate tuple (not "list") to tuple Can't get what I did wrong. Where is the list in there? from django.conf import settings from django.conf.urls.defaults import patterns, include, url # Uncomment the next two lines to enable the admin: from django.contrib...
[ "The error pretty much describes your problem. You're missing a call to patterns() in your first definition of urlpatterns.\n", "\nTypeError at / can only concatenate tuple (not \"list\") to tuple\n\nIt means exactly what it says. It is complaining about urlpatterns += patterns(...). The += attempts to concatenat...
[ 4, 1 ]
[]
[]
[ "django", "django_urls", "python" ]
stackoverflow_0007568304_django_django_urls_python.txt
Q: Scalable clipping mask I need to to clip variablesized images into puzzle shaped pices like this(not squares): http://www.fernando.com.ar/jquery-puzzle/ I have considered the posibility of doing this with a php library like Cairo or GD, but have little to no experience with these librays, and see no immidiate soul...
Scalable clipping mask
I need to to clip variablesized images into puzzle shaped pices like this(not squares): http://www.fernando.com.ar/jquery-puzzle/ I have considered the posibility of doing this with a php library like Cairo or GD, but have little to no experience with these librays, and see no immidiate soulution for creating a clippin...
[ "GD is quite complicated, I've heard very good things about Image Magick for which there is a PHP version and lots of documentation on php.net. However, not all web servers would have this installed by default. \nhttp://www.php.net/manual/en/book.imagick.php\n", "If you choose to do it using PHP with GD then the ...
[ 0, 0, 0 ]
[]
[]
[ "java", "php", "python", "scripting" ]
stackoverflow_0006958826_java_php_python_scripting.txt
Q: Trouble with imaplib fetch formats: RFC822 unequel utf8? I want to read an email messege which is in utf8 format. And this is not working with the following code: I guess i have to take a different format, but which and how? The output gives sth. like "=C3=96sterreich" for "Österreich". So far I have this...Thanx ...
Trouble with imaplib fetch formats: RFC822 unequel utf8?
I want to read an email messege which is in utf8 format. And this is not working with the following code: I guess i have to take a different format, but which and how? The output gives sth. like "=C3=96sterreich" for "Österreich". So far I have this...Thanx import imaplib import email imap4 = imaplib.IMAP4(SERVER) ima...
[ "Data in MIME containers is usually encoded using “quoted-printable” codec. I don't know the internals of imaplib but I believe what you're looking for is quopri.decodestring().\n" ]
[ 3 ]
[]
[]
[ "formatting", "imaplib", "python", "rfc822" ]
stackoverflow_0007567704_formatting_imaplib_python_rfc822.txt
Q: Why is environ['QUERY_STRING'] returning a zero length string? I found the solution to my (dumb) problem and listed it below. I'm using Python 2.7.1+ on Ubuntu 11.04. The client/server are on the same computer. From the Wing debugger, I know the server code is being called and I can walk through the code one line ...
Why is environ['QUERY_STRING'] returning a zero length string?
I found the solution to my (dumb) problem and listed it below. I'm using Python 2.7.1+ on Ubuntu 11.04. The client/server are on the same computer. From the Wing debugger, I know the server code is being called and I can walk through the code one line at a time. In this instance, I know 22 bytes were transferred. In F...
[ "You're doing a POST query so the QUERY_STRING is indeed going to be empty as it represents the query string of a GET request (it can also appear in other request types but it's unrelated to the problem at hand). You are supposed to parse POST data by consuming the wsgi.input stream.\n" ]
[ 3 ]
[]
[]
[ "ajax", "apache", "client_server", "python" ]
stackoverflow_0007568381_ajax_apache_client_server_python.txt
Q: Check if Twisted Server launched with twistd was started successfully I need a reliable way to check if a Twisted-based server, started via twistd (and a TAC-file), was started successfully. It may fail because some network options are setup wrong. Since I cannot access the twistd log (as it is logged to /dev/null...
Check if Twisted Server launched with twistd was started successfully
I need a reliable way to check if a Twisted-based server, started via twistd (and a TAC-file), was started successfully. It may fail because some network options are setup wrong. Since I cannot access the twistd log (as it is logged to /dev/null, because I don't need the log-clutter twistd produces), I need to find out...
[ "You're explicitly specifying a PID file. twistd will write its PID into that file. You can check the system to see if there is a process with that PID.\nYou could also re-enable logging with a custom log observer which only logs your startup event and discards all other log messages. Then you can watch the log ...
[ 5 ]
[]
[]
[ "python", "twistd", "twisted" ]
stackoverflow_0007568309_python_twistd_twisted.txt
Q: Rendering common session information in every view I'd like to output some information that depends on session data in Django. Let's take a "Login" / "Logged in as | Logout" fragment for example. It depends on my request.session['user']. Of course I can put a user object in the context every time I render a page ...
Rendering common session information in every view
I'd like to output some information that depends on session data in Django. Let's take a "Login" / "Logged in as | Logout" fragment for example. It depends on my request.session['user']. Of course I can put a user object in the context every time I render a page and then switch on {% if user %}, but that seems to brea...
[ "Use template inheritance to derive all of your templates from a common base that suitably uses the common parts of the context, and make all your contexts with a factory function that ensures the insertion in them of those common parts.\n", "Are you trying to make certain areas of your site only accessible when ...
[ 5, 0, 0 ]
[]
[]
[ "django", "python", "session", "templates" ]
stackoverflow_0001148854_django_python_session_templates.txt
Q: Regex to extract paragraph I am attempting to write a regex in Python to extract part of a paragraph. In the below paragraph, the part I wish to extract is bolded. Proposal will boost bailout fund, inject cash into banks and cut Greek debt says reports. My regex and output as follows, >>> text = 'Proposal wil...
Regex to extract paragraph
I am attempting to write a regex in Python to extract part of a paragraph. In the below paragraph, the part I wish to extract is bolded. Proposal will boost bailout fund, inject cash into banks and cut Greek debt says reports. My regex and output as follows, >>> text = 'Proposal will boost bailout fund, inject cas...
[ "use \nre.search(reg, text).group(0)\n\nor (your case):\npattern.search(text).group(0)\n\n", "From the documentation:\n\nIf one or more groups are present in the pattern, return a list of groups; this will be a list of tuples if the pattern has more than one group. Empty matches are included in the result unless...
[ 1, 1, 0, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0007569069_python_regex.txt
Q: decorators in python I am trying to understand the functioning of decorators. What am i doing wrong in the following code. Please do correct it As I have understood when aFunction() is called it in turn calls myDecorator() which also makes a call to afunction(). Right? Also how to pass parameters into afunction() ...
decorators in python
I am trying to understand the functioning of decorators. What am i doing wrong in the following code. Please do correct it As I have understood when aFunction() is called it in turn calls myDecorator() which also makes a call to afunction(). Right? Also how to pass parameters into afunction() class myDecorator(object):...
[ "class myDecorator(object):\n\n def __init__(self, f):\n print \"inside myDecorator.__init__()\"\n # save a reference to the real function, so it can be called later\n self.f = f\n\n def __call__(self, *args, **kwargs):\n print \"inside myDecorator.__call__()\"\n # call the ...
[ 4, 2, 1 ]
[]
[]
[ "decorator", "python" ]
stackoverflow_0007569584_decorator_python.txt
Q: Python script that notifies me when a update is made to a website. I need to make a script that will notify me when a change is made to a website. I am not sure about the best way to go about this and I don't know what python has that will be useful. Any push in the right direction would be helpful. A: You may ...
Python script that notifies me when a update is made to a website.
I need to make a script that will notify me when a change is made to a website. I am not sure about the best way to go about this and I don't know what python has that will be useful. Any push in the right direction would be helpful.
[ "You may use the last-modified date of the remote page :\nimport urllib\nu = urllib.urlopen(\"http://www.google.com\")\nu.info().get(\"last-modified\")\n\n", "It all depends on what you define as an update to a website.\nThe simplest solution would be to use urllib2 to get the contents of the given website, stori...
[ 4, 1 ]
[]
[]
[ "data_retrieval", "python" ]
stackoverflow_0007569424_data_retrieval_python.txt
Q: Python List Parsing Probably a simple question, but I am new to Python. I have a file containing email addresses, one per line. I want to read the file and append them together separated by a comma. Is there a more pythonic way of doing this? def getEmailList(file_name): f = open(file_name, 'r') emailstr...
Python List Parsing
Probably a simple question, but I am new to Python. I have a file containing email addresses, one per line. I want to read the file and append them together separated by a comma. Is there a more pythonic way of doing this? def getEmailList(file_name): f = open(file_name, 'r') emailstr = '' for line in f: ...
[ "You could do the following:\ndef getEmailList(file_name):\n with open(file_name) as f:\n return \",\".join(x.rstrip() for x in f)\n\nThe key features of that version are:\n\nUsing the with statement so that the file is automatically closed when control leaves that block.\nUsing the list comprehension gen...
[ 7, 2, 0, 0, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007569748_python.txt
Q: Subtract SQL DATETIME from datetime.now() in Python I have a DATETIME field in SQL. Its content is: 2012-08-26 13:00:00 I want to know how much time has passed from that date until now. In Python 2.7, it's easy: import time,datetime start = datetime.datetime.strptime('2012-08-26 13:00:00', '%Y-%m-%d %H:%M:%S') en...
Subtract SQL DATETIME from datetime.now() in Python
I have a DATETIME field in SQL. Its content is: 2012-08-26 13:00:00 I want to know how much time has passed from that date until now. In Python 2.7, it's easy: import time,datetime start = datetime.datetime.strptime('2012-08-26 13:00:00', '%Y-%m-%d %H:%M:%S') end = datetime.datetime.now() delta = start - end print del...
[ "time.strptime is in Python 2.4. It returns a time tuple, which can be then converted to a datetime as shown below.\nstart = time.strptime('2012-08-26 13:00:00', '%Y-%m-%d %H:%M:%S')\nstart = datetime.datetime(*start[:6])\n\n", "in python 2.4, the strptime() function is located in the time module.\n" ]
[ 11, 0 ]
[]
[]
[ "datetime", "python", "strptime", "time" ]
stackoverflow_0007570015_datetime_python_strptime_time.txt
Q: In Django, can I exclude a field in ModelForm sub-subclass? I have a “generic” InternForm that inherits from ModelForm and defines common messages, widgets, etc. I defined a subclass called ApplyInternForm for application form that is accessible to everyone and I want to hide some of the “advanced” fields. How c...
In Django, can I exclude a field in ModelForm sub-subclass?
I have a “generic” InternForm that inherits from ModelForm and defines common messages, widgets, etc. I defined a subclass called ApplyInternForm for application form that is accessible to everyone and I want to hide some of the “advanced” fields. How can I override exclude setting in the form's subclass? class Inter...
[ "Defining a Meta class in the subclass worked for me:\nclass InternForm(ModelForm):\n\n # ...\n\n class Meta:\n model = Intern\n\nclass ApplyInternForm(InternForm):\n\n class Meta:\n model = Intern\n exclude = ('is_active',)\n\n", "Not in this way, no. When you subclass a form the fi...
[ 3, 1 ]
[ "You can change widget to hidden:\nclass ApplyInternForm(InternForm):\n class Meta:\n widgets = {\n 'is_active': forms.HiddenInput(required=False),\n }\n\n" ]
[ -1 ]
[ "django", "django_1.3", "django_forms", "modelform", "python" ]
stackoverflow_0007568618_django_django_1.3_django_forms_modelform_python.txt
Q: Starting a process as a subprocess in Python I am writing a program that uses multiple worker processes (a pre-forking model) with the following code. from multiprocessing import Process for i in range(0,3): Process(target=worker, args=(i,)).start() I use Windows. I notice that they are run as separate proce...
Starting a process as a subprocess in Python
I am writing a program that uses multiple worker processes (a pre-forking model) with the following code. from multiprocessing import Process for i in range(0,3): Process(target=worker, args=(i,)).start() I use Windows. I notice that they are run as separate processes when I wanted them to start as subprocesses i...
[ "You seem to be confusing terminology here. A subprocess is a separate process. The processes that are created will be children of the main process of your program, and in that sense are subprocesses. If you want threads, then use multithreading instead of multiprocessing, but note that Python won't use multiple co...
[ 3, 3, 1 ]
[]
[]
[ "python" ]
stackoverflow_0007570906_python.txt
Q: Python: return output of ksh function On Unix, how can Iretrieve the output of a ksh function as a Python variable? The function is called sset and is defined in my ".kshrc". I tried using the subparser module according to comment recommendations. Here's what I came up with: import shlex import subprocess comma...
Python: return output of ksh function
On Unix, how can Iretrieve the output of a ksh function as a Python variable? The function is called sset and is defined in my ".kshrc". I tried using the subparser module according to comment recommendations. Here's what I came up with: import shlex import subprocess command_line = "/bin/ksh -c \". /Home/user/.khsr...
[ "shlex is not doing what you want:\n>>> list(shlex.shlex(\"/bin/ksh -c \\\". /Home/user/.khsrc\\\"\"))\n['/', 'bin', '/', 'ksh', '-', 'c', '\". /Home/user/.khsrc\"']\n\nYou're trying to execute the root directory, and that is not allowed, since, well, it's a directory and not an executable.\nInstead, just give subp...
[ 3 ]
[]
[]
[ "exec", "ksh", "python", "unix" ]
stackoverflow_0007567377_exec_ksh_python_unix.txt
Q: Realtime Socket.IO scaling problem - python I'm trying to do something like the stream on Facebook, with socket.io 0.6 and tornadio. Each user has is own comet channel/group in his wall. I'm sending a comet message to the wall of all my friends (even if they aren't online). The problem is about scaling: what if i ...
Realtime Socket.IO scaling problem - python
I'm trying to do something like the stream on Facebook, with socket.io 0.6 and tornadio. Each user has is own comet channel/group in his wall. I'm sending a comet message to the wall of all my friends (even if they aren't online). The problem is about scaling: what if i have 1 million friends? It would take a long time...
[ "This is a difficult problem in the social space. There is a trade-off between two approaches:\n\npush: When a user produces an event (e.g. a status update), you push that status update out to the stream of each of the user's friends. When a user loads his or her stream, you only have to read a record from a single...
[ 2 ]
[]
[]
[ "python", "real_time", "socket.io", "tornado" ]
stackoverflow_0007571068_python_real_time_socket.io_tornado.txt
Q: How to quickly insert huge datas into datastore while running on GAE development server? Background: While coding on GAE's local Development Web Server, user need to upload Mega-level datas and store (not straight forward store, but need many format check and translate) them into Datastore using deferred library. ...
How to quickly insert huge datas into datastore while running on GAE development server?
Background: While coding on GAE's local Development Web Server, user need to upload Mega-level datas and store (not straight forward store, but need many format check and translate) them into Datastore using deferred library. Usually about 50,000 entities, CSV File size is about 5MB, and I tried to insert 200 entities ...
[ "appengine-mapreduce is definitely an option for loading CSV files. Use blobstore to upload CSV file and then setup BlobstoreLineInputReader mapper type to load data into datastore.\nSome more links: Python Guide to mapreduce reader types is here. The one of interest is BlobstoreLineInputReader. The only input it r...
[ 1 ]
[]
[]
[ "google_app_engine", "google_cloud_datastore", "python" ]
stackoverflow_0007562034_google_app_engine_google_cloud_datastore_python.txt
Q: Creating a nested JSON request with Python A user needs to pass a json object as a part of the request. It would look something like this: {"token" :"ayaljltja", "addresses": [ {'name':'Home','address':'20 Main Street', 'city':'new-york'}, {'name':'work', 'address':'x Street', 'city':'o...
Creating a nested JSON request with Python
A user needs to pass a json object as a part of the request. It would look something like this: {"token" :"ayaljltja", "addresses": [ {'name':'Home','address':'20 Main Street', 'city':'new-york'}, {'name':'work', 'address':'x Street', 'city':'ohio'} ]} I have two problems right now. Firs...
[ "With command line curl, save your JSON to a file, say data.json. Then try: curl -X POST -d @data.json http://your.service.url\nIt's also possible to enter the JSON directly to the -d parameter but (as it sounds like you know already) you have to get your quoting and escaping exactly correct. \n", "First make sur...
[ 2, 2 ]
[]
[]
[ "curl", "deserialization", "json", "python", "serialization" ]
stackoverflow_0007570156_curl_deserialization_json_python_serialization.txt
Q: In great need of help on finishing python program The "Component" argument for addCompnent() method is an instance of the component class. In short, Component has 2 arguments; "Component(self,name,methodCount)" As you see in my code, I added each Component to a list. What I need to do in validCount() is return the...
In great need of help on finishing python program
The "Component" argument for addCompnent() method is an instance of the component class. In short, Component has 2 arguments; "Component(self,name,methodCount)" As you see in my code, I added each Component to a list. What I need to do in validCount() is return the number of components where the methodCount != 0. From ...
[ "A few comments.\n\nComment your code. Especially when you have mistakes, discerning what your code is supposed to do can be difficult for outsiders.\nIt's bad form to capitalize the \"Component\" argument to addComponent. Use capital letters for class names, lower case for parameter names. This code reads like you...
[ 4 ]
[]
[]
[ "python" ]
stackoverflow_0007564888_python.txt