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: Operations for Long and Float in Python I'm trying to compute this: from scipy import * 3600**3400 * (exp(-3600)) / factorial(3400) the error: unsupported long and float A: Try using logarithms instead of working with the numbers directly. Since none of your operations are addition or subtraction, you could do ...
Operations for Long and Float in Python
I'm trying to compute this: from scipy import * 3600**3400 * (exp(-3600)) / factorial(3400) the error: unsupported long and float
[ "Try using logarithms instead of working with the numbers directly. Since none of your operations are addition or subtraction, you could do the whole thing in logarithm form and convert back at the end.\n", "Computing with numbers of such magnitude, you just can't use ordinary 64-bit-or-so floats, which is what P...
[ 3, 2, 1, 0, 0 ]
[]
[]
[ "floating_point", "long_integer", "python", "scipy" ]
stackoverflow_0001526142_floating_point_long_integer_python_scipy.txt
Q: Why can't I save an object in Django? thechan = Score.objects.filter(content=44)[0:1] thechan[0].custom_score = 2 thechan[0].save() I do print statements, and it shows everything fine. However, it's not SAVING! I go into my database, and I run a simple SELECT statement..and it's not changed! select custom_score F...
Why can't I save an object in Django?
thechan = Score.objects.filter(content=44)[0:1] thechan[0].custom_score = 2 thechan[0].save() I do print statements, and it shows everything fine. However, it's not SAVING! I go into my database, and I run a simple SELECT statement..and it's not changed! select custom_score FROM music_score where content_id = 44;
[ "What's going on here is that Score.objects.filter() doesn't return a regular list, but a QuerySet. QuerySets behave like lists in some ways, but every time you slice one you get a new QuerySet instance, and everytime you index into one, you get a new instance of your model class.\nThat means your original code do...
[ 13 ]
[ "Fixed.\nthechan = Score.objects.get(content=44)\nthechan.custom_score = 2\nthechan.save()\n\n" ]
[ -1 ]
[ "django", "frameworks", "python" ]
stackoverflow_0001528656_django_frameworks_python.txt
Q: reading lines 2 at a time Is there a better way to read lines two at a time from a file in python than: with open(fn) as f: for line in f: try: line2 = f.next() except StopIteration: line2 = '' print line, line2 # or something more interesting I'm in 2.5.4. Any...
reading lines 2 at a time
Is there a better way to read lines two at a time from a file in python than: with open(fn) as f: for line in f: try: line2 = f.next() except StopIteration: line2 = '' print line, line2 # or something more interesting I'm in 2.5.4. Anything different in newer versio...
[ "import itertools\n\nwith open(fn) as f:\n for line, line2 in itertools.izip_longest(f, f, fillvalue=''):\n print line, line2\n\nAlas, izip_longest requires Python 2.6 or better; 2.5 only has izip, which would truncate the last line if f has an odd number of lines. It's quite easy to supply the equivalent func...
[ 18, 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0001528711_python.txt
Q: Can a WIN32 program authenticate into Django authentication system, using MYSQL? I have a web service with Django Framework. My friend's project is a WIN32 program and also a MS-sql server. The Win32 program currently has a login system that talks to a MS-sql for authentication. However, we would like to INTEGRATE...
Can a WIN32 program authenticate into Django authentication system, using MYSQL?
I have a web service with Django Framework. My friend's project is a WIN32 program and also a MS-sql server. The Win32 program currently has a login system that talks to a MS-sql for authentication. However, we would like to INTEGRATE this login system as one. Please answer the 2 things: I want scrap the MS-SQL to use...
[ "Either provide a view where your win32 client can post to the django server and get a response that means \"good login\" or \"bad login\". This will require you to modify the win32 client and create a very simple django view.\nOr provide your own Django Authentication backend that authenticates your django logins ...
[ 2, 0 ]
[]
[]
[ "authentication", "django", "frameworks", "python", "windows" ]
stackoverflow_0001529128_authentication_django_frameworks_python_windows.txt
Q: why is urllib2 missing table fields which I can see in the Firefox source? the html that I am receiving from urllib2 is missing dozens of fields of data that I can see when I view the source of the URL in Firefox. Any advice would be much appreciated. Here is what it looks like: from FireFox view source: # ...<t...
why is urllib2 missing table fields which I can see in the Firefox source?
the html that I am receiving from urllib2 is missing dozens of fields of data that I can see when I view the source of the URL in Firefox. Any advice would be much appreciated. Here is what it looks like: from FireFox view source: # ...<td class=td6>as</td></tr></thead>|ManyFields|<br></div><div id="c1">... from url...
[ "It seems from a cursory check that the page you're getting has a lot of Javascript; perhaps that Javascript cooperates in building the information that you see at the end in Firefox (at least some of it is actively altering the page's contents). If you need to scrape JS-rich pages, your best bet is to automate an...
[ 2, 0 ]
[]
[]
[ "field", "html", "python", "urllib2" ]
stackoverflow_0001529234_field_html_python_urllib2.txt
Q: Help to solve my problems with python LIST? author_A = [['book_x',1,10],['book_y',2,20],['book_z',3,30]] author_B = [['book_s',5,10],['book_t',2,20],['book_z',3,30]] author_A AND author_B = ['book_z',3,30] author_A = [['book_x',1,10],['book_y',2,20]] author_B = [['book_s',5,10],['book_t'...
Help to solve my problems with python LIST?
author_A = [['book_x',1,10],['book_y',2,20],['book_z',3,30]] author_B = [['book_s',5,10],['book_t',2,20],['book_z',3,30]] author_A AND author_B = ['book_z',3,30] author_A = [['book_x',1,10],['book_y',2,20]] author_B = [['book_s',5,10],['book_t',2,20]] ----------------------------...
[ "author_A = [['book_x',1,10],['book_y',2,20],['book_z',3,30]]\nauthor_B = [['book_s',5,10],['book_t',2,20],['book_z',3,30]]\n\ndef present(A, B):\n Aset = set(tuple(x) for x in A)\n Bset = set(tuple(x) for x in B)\n both = Aset & Bset\n justA = Aset - both\n justB = Bset - both\n totals = [0, 0]\n print \"%-...
[ 6, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0001529307_python.txt
Q: Django Vote Up/Down method I am making a small app that lets users vote items either up or down. I'm using Django (and new to it!). I am just wondering, what is the best way to present the upvote link to the user. As a link, button or something else? I have already done something like this in php with a different ...
Django Vote Up/Down method
I am making a small app that lets users vote items either up or down. I'm using Django (and new to it!). I am just wondering, what is the best way to present the upvote link to the user. As a link, button or something else? I have already done something like this in php with a different framework but I'm not sure if I ...
[ "Here's the gist of my solution. I use images with jQuery/AJAX to handle clicks. Strongly influenced by this site. There's some stuff that could use some work (error handling in the client, for example -- and much of it could probably be refactored) but hopefully the code is useful to you.\nThe HTML:\n <div ...
[ 39, 14, 11, 8 ]
[]
[]
[ "django", "python", "voting" ]
stackoverflow_0001528583_django_python_voting.txt
Q: how to create new file using python how can i create new file in /var/log directory using python language in OSX leopard? i tried to do it using os.open function but i get "permission denied" thanks in advance A: Only root can write in /var/log/ on Mac OS X...: $ ls -ld /var/log drwxr-xr-x 60 root wheel 2040 ...
how to create new file using python
how can i create new file in /var/log directory using python language in OSX leopard? i tried to do it using os.open function but i get "permission denied" thanks in advance
[ "Only root can write in /var/log/ on Mac OS X...:\n$ ls -ld /var/log\ndrwxr-xr-x 60 root wheel 2040 Oct 6 17:00 /var/log\n\nMaybe consider using the syslog module in the standard library...\n", "It probably failed because /var/log has user set to root and group set to wheel. Try running your python code as ro...
[ 6, 1, 1 ]
[]
[]
[ "macos", "osx_leopard", "python" ]
stackoverflow_0001529584_macos_osx_leopard_python.txt
Q: Cannot shuffle list in Python This is my list: biglist = [ {'title':'U2','link':'u2.com'}, {'title':'beatles','link':'beatles.com'} ] print random.shuffle(biglist) that doesn't work! It returns none. A: random.shuffle shuffles the list, it does not return a new list. So check biglist, not the result of random....
Cannot shuffle list in Python
This is my list: biglist = [ {'title':'U2','link':'u2.com'}, {'title':'beatles','link':'beatles.com'} ] print random.shuffle(biglist) that doesn't work! It returns none.
[ "random.shuffle shuffles the list, it does not return a new list. So check biglist, not the result of random.shuffle.\nDocumentation for the random module: http://docs.python.org/library/random.html\n" ]
[ 16 ]
[]
[]
[ "list", "python", "random" ]
stackoverflow_0001530161_list_python_random.txt
Q: In Django, the HTML code is shown instead of the actual text & g t ; Welcome How do I show the actual symbol instead? Is it a template filter? Thanks. A: Bit hard to know without more details. If it's from data that you're passing in from the view, you might want to use mark_safe. from django.utils.safestring im...
In Django, the HTML code is shown instead of the actual text
& g t ; Welcome How do I show the actual symbol instead? Is it a template filter? Thanks.
[ "Bit hard to know without more details. If it's from data that you're passing in from the view, you might want to use mark_safe.\nfrom django.utils.safestring import mark_safe\n\ndef your_view(request):\n ...\n foo = '&gt;'\n mark_safe(foo)\n ...\n\nOtherwise, you want the safe filter:\n{{ myvar|safe }}...
[ 5 ]
[]
[]
[ "django", "python" ]
stackoverflow_0001530178_django_python.txt
Q: Close Python when Parent is closed I have a Python program (PP) that loads another Program(AP) via COM, gets its window handle and sets it to be the PP parent. This works pretty well except that I can't control that AP still has their [X] button available in the top left corner. Since this is a pretty obvious pla...
Close Python when Parent is closed
I have a Python program (PP) that loads another Program(AP) via COM, gets its window handle and sets it to be the PP parent. This works pretty well except that I can't control that AP still has their [X] button available in the top left corner. Since this is a pretty obvious place for the user to close when they are d...
[ "How's PP's control flow? If it's event-driven it could get appropriate events upon closure of that parent window or termination of that AP process; otherwise it could \"poll\" to check if the window or process are still around.\n", "As you said you get AP's handle and pass it to PP, so PP has that handle around...
[ 1, 0 ]
[]
[]
[ "com", "parent", "python", "wxpython" ]
stackoverflow_0001521670_com_parent_python_wxpython.txt
Q: Sharing widgets between PyQT and Boost.Python I was wondering if it was possible to share widgets between PyQt and Boost.Python. I will be embedding a Python interpreter into an application of mine that uses Qt. I would like users of my application to be able to embed their own UI widgets into UI widgets programm...
Sharing widgets between PyQT and Boost.Python
I was wondering if it was possible to share widgets between PyQt and Boost.Python. I will be embedding a Python interpreter into an application of mine that uses Qt. I would like users of my application to be able to embed their own UI widgets into UI widgets programmed in C++ and exposed via Boost.Python. Is this pos...
[ "I've tried to write some proxying for this, but I haven't succeeded completely. Here's a start that tries to solve this, but the dir() won't work. Calling functions directly works somewhat.\nThe idea was to create an additional python object wrapped in SIP and forward any calls/attributes to that object if the ori...
[ 2 ]
[]
[]
[ "boost_python", "pyqt", "python", "python_sip", "qt" ]
stackoverflow_0001436514_boost_python_pyqt_python_python_sip_qt.txt
Q: How do I change my float into a two decimal number with a comma as a decimal point separator in python? I have a float: 1.2333333 How do I change it into a two decimal number with a comma as a decimal point separator, eg 1,23? A: To get two decimals, use '%.2f' % 1.2333333 To get a comma, use replace(): ('%.2f'...
How do I change my float into a two decimal number with a comma as a decimal point separator in python?
I have a float: 1.2333333 How do I change it into a two decimal number with a comma as a decimal point separator, eg 1,23?
[ "To get two decimals, use\n'%.2f' % 1.2333333\n\nTo get a comma, use replace():\n('%.2f' % 1.2333333).replace('.', ',')\n\nA second option would be to change the locale to some place which uses a comma and then use locale.format():\nlocale.setlocale(locale.LC_ALL, 'FR')\nlocale.format('%.2f', 1.2333333)\n\n", "Th...
[ 16, 8, 2 ]
[]
[]
[ "decimal", "floating_point", "python" ]
stackoverflow_0001530430_decimal_floating_point_python.txt
Q: Ruby methods equivalent of "if a in list" in python? In python I can use this to check if the element in list a: >>> a = range(10) >>> 5 in a True >>> 16 in a False How this can be done in Ruby? A: Use the include?() method: (1..10).include?(5) #=>true (1..10).include?(16) #=>false EDIT: (1..10) is Range in Ru...
Ruby methods equivalent of "if a in list" in python?
In python I can use this to check if the element in list a: >>> a = range(10) >>> 5 in a True >>> 16 in a False How this can be done in Ruby?
[ "Use the include?() method:\n(1..10).include?(5) #=>true\n(1..10).include?(16) #=>false\n\nEDIT:\n(1..10) is Range in Ruby , in the case you want an Array(list) :\n(1..10).to_a #=> [1,2,3,4,5,6,7,8,9,10]\n\n", "Range has the === method, which checks whether the argument is part of the range.\nYou use it like this...
[ 27, 10 ]
[]
[]
[ "python", "ruby", "syntax" ]
stackoverflow_0001529986_python_ruby_syntax.txt
Q: flup/fastcgi cpu usage under no-load conditions I'm running Django as threaded fastcgi via flup, served by lighttpd, communicating via sockets. What is the expected CPU usage for each fastcgi thread under no load? On startup, each thread runs at 3-4% cpu usage for a while, and then backs off to around .5% over the...
flup/fastcgi cpu usage under no-load conditions
I'm running Django as threaded fastcgi via flup, served by lighttpd, communicating via sockets. What is the expected CPU usage for each fastcgi thread under no load? On startup, each thread runs at 3-4% cpu usage for a while, and then backs off to around .5% over the course of a couple of hours. It doesn't sink below t...
[ "I've looked at this on django running as fastcgi on both Slicehost (django 1.1, python 2.6) and Dreamhost (django 1.0, python 2.5), and I can say this:\nRunning the top command shows the processes use a large amount of CPU to start up for ~2-3 seconds, then drop down to 0 almost immediately.\nRunning the ps aux co...
[ 2, 0 ]
[]
[]
[ "django", "fastcgi", "flup", "lighttpd", "python" ]
stackoverflow_0001522844_django_fastcgi_flup_lighttpd_python.txt
Q: Using callback function in pyevent I want to detect pressing the "snapshot" button on the top of a webcam in linux. The button has this entry in /dev: /dev/input/by-id/usb-PixArt_Imaging_Inc._USB2.0_UVC_VGA-event-if00 I am using the "rel" wrapper, at the moment, because it handles exceptions better. Before the ...
Using callback function in pyevent
I want to detect pressing the "snapshot" button on the top of a webcam in linux. The button has this entry in /dev: /dev/input/by-id/usb-PixArt_Imaging_Inc._USB2.0_UVC_VGA-event-if00 I am using the "rel" wrapper, at the moment, because it handles exceptions better. Before the following code executes, self.s.cam_btn ...
[ "Never used pyevent, but would try rescheduling the event at the end of the handler:\ndef snap(self):\n # ... code ...\n rel.read(self.s.cam_btn, self.snap)\n return False\n\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0001528915_python.txt
Q: Coming from a Visual Studio background, what do you recommend I use to start my VERY FIRST Python project? I'm locked in using C# and I don't like it one bit. I have to start branching out to better myself as a professional and as a person, so I've decided to start making things in my own time using Python. The pr...
Coming from a Visual Studio background, what do you recommend I use to start my VERY FIRST Python project?
I'm locked in using C# and I don't like it one bit. I have to start branching out to better myself as a professional and as a person, so I've decided to start making things in my own time using Python. The problem is, I've basically programmed only in C#. What IDE should I use to make programs using Python? My goal is ...
[ "How about IronPython\nAs of VS 2010 it will become a first class .Net language\nOr currently in a VS2008 shell IronPythonStudio\nNot that I have used any of these\nIn hindsight this may not make for a very good cross platform solution, but it will allow you to leverage your VS experience\n", "You don't really ne...
[ 5, 3, 2, 1, 1, 1, 1, 0, 0, 0, 0 ]
[]
[]
[ "c#", "ide", "python", "vim" ]
stackoverflow_0001517428_c#_ide_python_vim.txt
Q: how do I sign data with pyme? I just installed pyme on my ubuntu system. it was easy (thanks apt-get) and I can reproduce the example code (encrypting using a public key in my keyring). now I would like to sign some data and I didn't manage to find any example code nor much documentation. this is what I've been ...
how do I sign data with pyme?
I just installed pyme on my ubuntu system. it was easy (thanks apt-get) and I can reproduce the example code (encrypting using a public key in my keyring). now I would like to sign some data and I didn't manage to find any example code nor much documentation. this is what I've been doing: >>> plain = pyme.core.Data('...
[ "You can follow example from pyme doc and modify it a bit:\nimport pyme.core\nimport pyme.pygpgme\n\nplaintext = pyme.core.Data('this is a test message')\nciphertext = pyme.core.Data()\nctx = pyme.core.Context()\nctx.set_armor(1)\nname = 'me@office.com'\nctx.op_keylist_start(name, 0)\nkey = ctx.op_keylist_next()\n#...
[ 0 ]
[]
[]
[ "encryption", "gnupg", "gpgme", "pyme", "python" ]
stackoverflow_0001530797_encryption_gnupg_gpgme_pyme_python.txt
Q: Python HTML Minimizer I have a cherrypy web server that uses larges amounts of HTML data. Is there anyway in Python to minimize the HTML so that all comments, spaces, ext, are removed? A: Not what you mean, but: Gzip. (Assuming you aren't already serving through a compressing front-end.) Compression will zip a...
Python HTML Minimizer
I have a cherrypy web server that uses larges amounts of HTML data. Is there anyway in Python to minimize the HTML so that all comments, spaces, ext, are removed?
[ "Not what you mean, but: Gzip. (Assuming you aren't already serving through a compressing front-end.) Compression will zip away whitespace to almost nothing; unless you have excessively large comments this will be more effective than minification.\n", "there are bindings to tidy for python, called mxTidy from eGe...
[ 4, 2, 0 ]
[]
[]
[ "html", "minimize", "python" ]
stackoverflow_0001437357_html_minimize_python.txt
Q: BioPython: Skipping over bad GIDs with Entrez.esummary/Entrez.read Sorry about the odd title. I am using eSearch & eSummary to go from Accession Number --> gID --> TaxID Assume that 'accessions' is a list of 20 accession numbers (I do 20 at a time because that's the maximum that NCBI will allow). I do: handle = E...
BioPython: Skipping over bad GIDs with Entrez.esummary/Entrez.read
Sorry about the odd title. I am using eSearch & eSummary to go from Accession Number --> gID --> TaxID Assume that 'accessions' is a list of 20 accession numbers (I do 20 at a time because that's the maximum that NCBI will allow). I do: handle = Entrez.esearch(db="nucleotide", rettype="xml", term=accessions) record = ...
[ "I sent a message out to the BioPython mailing list.Apparently it's a bug & they're working on it.\n", "I'd have a look at Parser.py and see what is being parsed. It looks like you are getting a result from the NCBI ok, but the format of one record is tripping up the parser.\nIt may be possible to subclass/monkey...
[ 3, 0 ]
[]
[]
[ "bioinformatics", "biopython", "python" ]
stackoverflow_0001523571_bioinformatics_biopython_python.txt
Q: Double import in grok This is a normal case of mutual import. Suppose you have the following layout ./test.py ./one ./one/__init__.py ./one/two ./one/two/__init__.py ./one/two/m.py ./one/two/three ./one/two/three/__init__.py ./one/two/three/four ./one/two/three/four/__init__.py ./one/two/three/four/e.py ./one/two/...
Double import in grok
This is a normal case of mutual import. Suppose you have the following layout ./test.py ./one ./one/__init__.py ./one/two ./one/two/__init__.py ./one/two/m.py ./one/two/three ./one/two/three/__init__.py ./one/two/three/four ./one/two/three/four/__init__.py ./one/two/three/four/e.py ./one/two/u.py And you have test.py ...
[ "This could possibly be a side-effect of the introspection Grok does, I'm not sure.\nTry to put a pdb.set_trace() in m, and check at the stack trace to see what is importing the modules.\n" ]
[ 0 ]
[]
[]
[ "grok", "python" ]
stackoverflow_0001531647_grok_python.txt
Q: Django: apply "same parent" constraint to ManyToManyField mapping to self I have a model where tasks are pieces of work that each may depend on some number of other tasks to complete before it can start. Tasks are grouped into jobs, and I want to disallow dependencies between jobs. This is the relevant subset of m...
Django: apply "same parent" constraint to ManyToManyField mapping to self
I have a model where tasks are pieces of work that each may depend on some number of other tasks to complete before it can start. Tasks are grouped into jobs, and I want to disallow dependencies between jobs. This is the relevant subset of my model: class Job(models.Model): name = models.CharField(max_length=60, un...
[ "There are two separate issues here.\nIf you want to enforce this constraint at the model level, you might have to define an explicit \"through\" model and override its save() method (you can't just override Task.save() as that isn't necessarily invoked for adding entries to an M2M). Django 1.2 will have a fuller m...
[ 3 ]
[]
[]
[ "constraints", "django", "orm", "python" ]
stackoverflow_0001531065_constraints_django_orm_python.txt
Q: I heard that Python has automated "garbage collection" , but C++ does not. What does that mean? I heard that Python has automated "garbage collection" , but C++ does not. What does that mean? A: Try reading up on it. A: That means that python user doesn't need to clean his dynamic created objects, like you're ...
I heard that Python has automated "garbage collection" , but C++ does not. What does that mean?
I heard that Python has automated "garbage collection" , but C++ does not. What does that mean?
[ "Try reading up on it.\n", "That means that python user doesn't need to clean his dynamic created objects, like you're obligated to do it in C/C++.\nExample in C++:\nchar *ch = new char[100];\nch[0]='a';\nch[1]='b';\n//....\n// somewhere else in your program you need to release the alocated memory.\ndelete [] ch;...
[ 12, 9, 4, 3, 2, 0 ]
[]
[]
[ "c++", "garbage_collection", "python" ]
stackoverflow_0001530245_c++_garbage_collection_python.txt
Q: How to read lines from a file into a multidimensional array (or an array of lists) in python I have a file with a format similar to this: a,3,4,2,1 3,2,1,a,2 I want to read the file and create an array of lists in a way that: array[0] = ['a','3','4','2','1'] array[1] = ['3','2','1','a','2'] How can I do that? So...
How to read lines from a file into a multidimensional array (or an array of lists) in python
I have a file with a format similar to this: a,3,4,2,1 3,2,1,a,2 I want to read the file and create an array of lists in a way that: array[0] = ['a','3','4','2','1'] array[1] = ['3','2','1','a','2'] How can I do that? So far I am stuck with: f = open('./urls-eu.csv', 'r') for line in f: arr = line.split(',') prin...
[ "Batteries included:\n>>> import csv\n>>> array = list( csv.reader( open( r'./urls-eu.csv' ) ) )\n>>> array[0]\n['a', '3', '4', '2', '1']\n>>> array[1]\n['3', '2', '1', 'a', '2']\n\n", "you're almost there, you just need to do:\narr = [line.split(',') for line in open('./urls-eu.csv')]\n\nit iteratively process f...
[ 16, 7 ]
[]
[]
[ "list", "multidimensional_array", "python" ]
stackoverflow_0001532810_list_multidimensional_array_python.txt
Q: Debugging a scripting language like ruby I am basically from the world of C language programming, now delving into the world of scripting languages like Ruby and Python. I am wondering how to do debugging. At present the steps I follow is, I complete a large script, Comment everything but the portion I want to c...
Debugging a scripting language like ruby
I am basically from the world of C language programming, now delving into the world of scripting languages like Ruby and Python. I am wondering how to do debugging. At present the steps I follow is, I complete a large script, Comment everything but the portion I want to check Execute the script Though it works, I am...
[ "Your sequence seems entirely backwards to me. Here's how I do it:\n\nI write a test for the functionality I want.\nI start writing the script, executing bits and verifying test results.\nI review what I'd done to document and publish.\n\nSpecifically, I execute before I complete. It's way too late by then.\nTher...
[ 10, 6, 4, 3, 2, 2, 2, 0, 0, 0, 0 ]
[]
[]
[ "python", "ruby", "scripting_language" ]
stackoverflow_0001529896_python_ruby_scripting_language.txt
Q: Access is Denied loading a dll with ctypes on Vista I'm having issues with using ctypes. I'm trying to get the following project running on Vista. http://sourceforge.net/projects/fractalfrost/ I've used the project before on Vista and had no problems. I don't see any think changed in svn that cause this I'm thin...
Access is Denied loading a dll with ctypes on Vista
I'm having issues with using ctypes. I'm trying to get the following project running on Vista. http://sourceforge.net/projects/fractalfrost/ I've used the project before on Vista and had no problems. I don't see any think changed in svn that cause this I'm thinking it's something local to this machine. In fact I'm n...
[ "I know it sounds like a silly thing, but since you didn't explicitly mention it:\nDid you check the permissions on the file you're trying to access? Perhaps you, you know, don't have read or execute access to the file.\n" ]
[ 2 ]
[]
[]
[ "ctypes", "python", "windows_vista" ]
stackoverflow_0001533466_ctypes_python_windows_vista.txt
Q: What is the best way to distribute a python program extended with custom c modules? I've explored python for several years, but now I'm slowly learning how to work with c. Using the python documentation, I learned how to extend my python programs with some c, since this seemed like the logical way to start playin...
What is the best way to distribute a python program extended with custom c modules?
I've explored python for several years, but now I'm slowly learning how to work with c. Using the python documentation, I learned how to extend my python programs with some c, since this seemed like the logical way to start playing with it. My question now is how to distribute a program like this. I suppose the heart...
[ "Please read up on distutils. Specifically, the section on Extension Modules.\nMaking assumptions about compilers is bad policy; your instinct may not have all the facts. You could do some marketplace survey -- ask what they can handle regarding source distribution of extension modules.\nIt's relatively easy to c...
[ 6, 1 ]
[]
[]
[ "c", "linux", "macos", "python", "software_distribution" ]
stackoverflow_0000294766_c_linux_macos_python_software_distribution.txt
Q: Why does my function "hangs" def retCursor(): host = "localhost" user = "disappearedng" db = "gupan_crawling3" conn = MySQLdb.connect( host=host, user=user, passwd=passwd, db=db) cursor = conn.cursor() return cursor singleCur = retCursor() def checkTemplateBuilt(netlocH): """Used by c...
Why does my function "hangs"
def retCursor(): host = "localhost" user = "disappearedng" db = "gupan_crawling3" conn = MySQLdb.connect( host=host, user=user, passwd=passwd, db=db) cursor = conn.cursor() return cursor singleCur = retCursor() def checkTemplateBuilt(netlocH): """Used by crawler specifically, this check d...
[ "There might be a lock on the table preventing the query from completing.\n", "Try logging the query string to a file right before you execute it.\nThen when you think it is hung, you can look at the query and see if it works manually\n", "According to your traceback, you interrupted the script during the execu...
[ 1, 1, 0 ]
[]
[]
[ "mysql", "python" ]
stackoverflow_0001532474_mysql_python.txt
Q: Good high-level python ftp/http lib? I'm looking for a good, high-level python ftp client/server library. I'm working on a project that has "evolved" a small http/ftp library on top of ftplib/urllib/urllib2 from what was originally one function, and almost none of it was designed to be built upon. So now it's time...
Good high-level python ftp/http lib?
I'm looking for a good, high-level python ftp client/server library. I'm working on a project that has "evolved" a small http/ftp library on top of ftplib/urllib/urllib2 from what was originally one function, and almost none of it was designed to be built upon. So now it's time to refactor kind of seriously, and I'd li...
[ "URLgrabber appears to be very mature, and since it's used by yum (and thus many Unix systems), I would expect it to be very stable. Python 2.x is largely backward compatible. You might encounter some warnings, but I would expect it to work suitably under Python 2.6.\n", "Depending on the sort of application you ...
[ 4, 0 ]
[]
[]
[ "ftp", "http", "python" ]
stackoverflow_0001532760_ftp_http_python.txt
Q: Python object initialization bug. Or am I misunderstanding how objects work? 1 import sys 2 3 class dummy(object): 4 def __init__(self, val): 5 self.val = val 6 7 class myobj(object): 8 def __init__(self, resources): 9 self._resources = resources 10 11 class ext(myobj...
Python object initialization bug. Or am I misunderstanding how objects work?
1 import sys 2 3 class dummy(object): 4 def __init__(self, val): 5 self.val = val 6 7 class myobj(object): 8 def __init__(self, resources): 9 self._resources = resources 10 11 class ext(myobj): 12 def __init__(self, resources=[]): 13 #myobj.__init__(self, res...
[ "You should change\ndef __init__(self, resources=[]):\n self._resources = resources\n\nto\ndef __init__(self, resources=None):\n if resources is None:\n resources = []\n self._resources = resources\n\nand all will be better. This is a detail in the way default arguments are handled if they're mutabl...
[ 8, 6, 2, 1, 0 ]
[]
[]
[ "arguments", "mutable", "python" ]
stackoverflow_0001534407_arguments_mutable_python.txt
Q: Does a Python 3 SOAP client module exist? Possible Duplicate: What’s the best SOAP library for Python 3.x? I couldn't find one that works with Python 3.1. Any suggestions for a WSDL-consuming Python 3 SOAP client module/library? A: You could port an existing library that you like and provide your changes to t...
Does a Python 3 SOAP client module exist?
Possible Duplicate: What’s the best SOAP library for Python 3.x? I couldn't find one that works with Python 3.1. Any suggestions for a WSDL-consuming Python 3 SOAP client module/library?
[ "You could port an existing library that you like and provide your changes to the author of the package.\n" ]
[ 3 ]
[]
[]
[ "python", "python_3.x", "soap" ]
stackoverflow_0001534554_python_python_3.x_soap.txt
Q: Calling a RPC function in a running Windows service (process) using Python I have Windows service (acts as a server) that I want to test using Python scripts. This service is written in C++ and exposes several RPC functions that other services consume. I want to mock those other services using my Python program an...
Calling a RPC function in a running Windows service (process) using Python
I have Windows service (acts as a server) that I want to test using Python scripts. This service is written in C++ and exposes several RPC functions that other services consume. I want to mock those other services using my Python program and call those RPC functions from the script. This is the first stage. The second ...
[ "What kind of RPC are you thinking of? If it is XML-RPC, then Python comes with the SimpleXMLRPCServer module, which, well, allows you to write RPC servers in Python.\nIf the remote server uses DCOM, you can use PythonCOM.\n" ]
[ 1 ]
[]
[]
[ "interprocess", "python", "rpc" ]
stackoverflow_0001534686_interprocess_python_rpc.txt
Q: C++ or Python for C# programmer? I am a corporate C# programmer. I found some time to invest into myself and stumbed upon a dilemma. Where to go from now? C#/.NET is easy to learn, develop for, etc. In future I would want to apply to Microsoft or Google, and want to invest spare time wisely, so what I will learn w...
C++ or Python for C# programmer?
I am a corporate C# programmer. I found some time to invest into myself and stumbed upon a dilemma. Where to go from now? C#/.NET is easy to learn, develop for, etc. In future I would want to apply to Microsoft or Google, and want to invest spare time wisely, so what I will learn will flourish in future. So: Python or ...
[ "\nI Am a little scared of C++ because developing anything in it takes ages.\n\nI'm not sure how you can say that when you say yourself that you have no experience in the language. C++ is a good tool for some things, Python is good for other things. What you want to do should be driving this decision, not the tec...
[ 7, 5, 3, 2, 1, 1, 1, 1, 0, 0 ]
[]
[]
[ "c#", "c++", "python" ]
stackoverflow_0001534450_c#_c++_python.txt
Q: Need a workaround: Python's select.select() doesn't work with subprocess' stdout? From within my master python program, I am spawning a child program with this code: child = subprocess.Popen(..., stdout=subprocess.PIPE, stdin=subprocess.PIPE) FWIW, the child is a PHP script which needs to communicate back and for...
Need a workaround: Python's select.select() doesn't work with subprocess' stdout?
From within my master python program, I am spawning a child program with this code: child = subprocess.Popen(..., stdout=subprocess.PIPE, stdin=subprocess.PIPE) FWIW, the child is a PHP script which needs to communicate back and forth with the python program. The master python program actually needs to listen for comm...
[ "Unfortunately, many uses of pipes on Windows don't work as nicely as they do on Unix, and this is one of them. On Windows, the better solution is probably to have your master program spawn threads to listen to each of its subprocesses. If you know the granularity of data that you expect back from your subprocess...
[ 4 ]
[]
[]
[ "python", "select", "sockets", "subprocess" ]
stackoverflow_0001534825_python_select_sockets_subprocess.txt
Q: Turbogears: Can not start paster after updateing to mac osx 10.6 After updateing to mac osx 10.6 I had to switch back to python 2.5 in order to make virtual env work. But still I can not start my turbogears project. Paster is giving this : Traceback (most recent call last): File ".../tg2env/bin/paster", line 5, ...
Turbogears: Can not start paster after updateing to mac osx 10.6
After updateing to mac osx 10.6 I had to switch back to python 2.5 in order to make virtual env work. But still I can not start my turbogears project. Paster is giving this : Traceback (most recent call last): File ".../tg2env/bin/paster", line 5, in <module> from pkg_resources import load_entry_point File "......
[ "Why did you need to switch back to 2.5 to make virtualenv work? I have upgraded to 10.6 and am happily using virtualenv in Python 2.6.\n", "Probably eggs are installed for 2.6 distro. Please run in your terminal:\ndefaults write com.apple.versioner.python Version 2.5\nexport VERSIONER_PYTHON_VERSION=2.5\nsudo ea...
[ 0, 0, 0 ]
[]
[]
[ "macos", "python", "turbogears2" ]
stackoverflow_0001533388_macos_python_turbogears2.txt
Q: Is there any way to affect locals at runtime? I actually want to create a new local. I know it sounds dubious, but I think I have a nice use case for this. Essentially my problem is that this code throws "NameError: global name 'eggs' is not defined" when I try to print eggs: def f(): import inspect frame_...
Is there any way to affect locals at runtime?
I actually want to create a new local. I know it sounds dubious, but I think I have a nice use case for this. Essentially my problem is that this code throws "NameError: global name 'eggs' is not defined" when I try to print eggs: def f(): import inspect frame_who_called = inspect.stack()[1][0] frame_who_ca...
[ "I am highly curious as to your use case. Why on Earth are you trying to poke a new local into the caller's frame, rather than simply doing something like this:\ndef f():\n return 123\n\ndef g():\n eggs = f()\n print(eggs)\n\nAfter all, you can return a tuple with as many values as you like:\ndef f():\n ...
[ 3, 2, 1 ]
[]
[]
[ "locals", "python", "python_3.x" ]
stackoverflow_0001534368_locals_python_python_3.x.txt
Q: How to remove these duplicates in a list (python) biglist = [ {'title':'U2 Band','link':'u2.com'}, {'title':'ABC Station','link':'abc.com'}, {'title':'Live Concert by U2','link':'u2.com'} ] I would like to remove the THIRD element inside the list...because it has "u2.com" as a duplicate. I don...
How to remove these duplicates in a list (python)
biglist = [ {'title':'U2 Band','link':'u2.com'}, {'title':'ABC Station','link':'abc.com'}, {'title':'Live Concert by U2','link':'u2.com'} ] I would like to remove the THIRD element inside the list...because it has "u2.com" as a duplicate. I don't want duplicate "link" element. What is the most effi...
[ "Probably the fastest approach, for a really big list, if you want to preserve the exact order of the items that remain, is the following...:\nbiglist = [ \n {'title':'U2 Band','link':'u2.com'}, \n {'title':'ABC Station','link':'abc.com'}, \n {'title':'Live Concert by U2','link':'u2.com'} \n]\n\nknown_link...
[ 8, 3, 2, 1, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0001534736_list_python.txt
Q: Python instance method making multiple instance method calls Here is some snippet code. I have tested the methods listed and they work correctly, yet when I run and test this method (countLOC) it only seems to initialize the first variable that has an instance method call (i = self.countBlankLines()). Anyone know ...
Python instance method making multiple instance method calls
Here is some snippet code. I have tested the methods listed and they work correctly, yet when I run and test this method (countLOC) it only seems to initialize the first variable that has an instance method call (i = self.countBlankLines()). Anyone know the obvious reason I'm obviously missing? def countLOC(self): ...
[ "If local variables were not initialized (impossible given your code!) they wouldn't be 0 -- rather, you'd get a NameError exception when you try to use them. It's 100% certain that those other method calls (except the first one) are returning 0 (or numbers totaling to 0 in the expression).\nHard to guess, not bei...
[ 5 ]
[]
[]
[ "method_call", "methods", "python" ]
stackoverflow_0001535313_method_call_methods_python.txt
Q: Need help in designing a phone book application on python running on google app engine Hi I want some help in building a Phone book application on python and put it on google app engine. I am running a huge db of 2 million user lists and their contacts in phonebook. I want to upload all that data from my servers d...
Need help in designing a phone book application on python running on google app engine
Hi I want some help in building a Phone book application on python and put it on google app engine. I am running a huge db of 2 million user lists and their contacts in phonebook. I want to upload all that data from my servers directly onto the google servers and then use a UI to retrieve the phone book contacts of eac...
[ "For building your UI, AppEngine has it's own web framework called webapp that is pretty easy to get working. I've also had a good experience using the Jinja2 templating engine, which you can include in your source, or package as a zip file (example shows Django, you can do the same type of thing for Jinja).\nAs fo...
[ 1, 0 ]
[]
[]
[ "bulk_load", "google_app_engine", "python" ]
stackoverflow_0001518725_bulk_load_google_app_engine_python.txt
Q: Jump to Model/View/Controller in emacs Most rails modes for emacs have this kind of functionality. You are in a controller file over a function "kaboosh" in "app/controller/bla.rb" and with a keyboard shortcut you switch to "app/views/kaboosh.erb" or to app/models/bla.rb". A similar functionality exists for .c and...
Jump to Model/View/Controller in emacs
Most rails modes for emacs have this kind of functionality. You are in a controller file over a function "kaboosh" in "app/controller/bla.rb" and with a keyboard shortcut you switch to "app/views/kaboosh.erb" or to app/models/bla.rb". A similar functionality exists for .c and .h files using ff-find-other-file. I checke...
[ "Tags is set up well to jump you to the definition of a function. M-. will take you to the first occurrence of a function definition, C-u M-. will take you to the next (and one after that, and after that...). Perhaps the C-u M-. solves some of your problem.\nRegarding associations between files, and wanting a rai...
[ 1 ]
[]
[]
[ "emacs", "python" ]
stackoverflow_0001534969_emacs_python.txt
Q: How to do email-confirmation after registration in Django? I am using Django's authentication system. Is there an easy way to do this? A: Have a look at James Bennett's django-registration project.
How to do email-confirmation after registration in Django?
I am using Django's authentication system. Is there an easy way to do this?
[ "Have a look at James Bennett's django-registration project.\n" ]
[ 8 ]
[]
[]
[ "django", "python" ]
stackoverflow_0001536766_django_python.txt
Q: Can't Delete Function Call This question is just out of general curiosity. I've just noticed it when working on my current project (surprisingly I haven't came across before today). Take this code: List = ["hi","stack","over","flow","how","you","doing"] del List(len(List)-1) Error: SyntaxError: can't delete funct...
Can't Delete Function Call
This question is just out of general curiosity. I've just noticed it when working on my current project (surprisingly I haven't came across before today). Take this code: List = ["hi","stack","over","flow","how","you","doing"] del List(len(List)-1) Error: SyntaxError: can't delete function call I don't understand why...
[ "You meant to delete the last element of the list, not somehow call List as a function:\ndel List[len(List)-1]\n\nPython's del statement must take specific forms like deleting a variable, list[element], or object.property. These forms can be nested deeply, but must be followed. It parallels the assignment statement...
[ 13, 5, 1 ]
[]
[]
[ "python", "syntax_error" ]
stackoverflow_0001536890_python_syntax_error.txt
Q: Python not a standardized language? I stumbled upon this 'list of programming' languages and found that popular languages like Python are not standardized? Why is that, and what does 'Standardized' mean anyway? A: "Standardized" means that the language has a formal, approved standard, generally written by ISO or...
Python not a standardized language?
I stumbled upon this 'list of programming' languages and found that popular languages like Python are not standardized? Why is that, and what does 'Standardized' mean anyway?
[ "\"Standardized\" means that the language has a formal, approved standard, generally written by ISO or ANSI or ECMA. Many modern open-source languages, like Python, Perl, are not formally standardized by an external body, and instead have a de-facto standard: whatever the original working implementation does.\nThe ...
[ 48, 7, 4 ]
[]
[]
[ "python", "standardized" ]
stackoverflow_0001535702_python_standardized.txt
Q: Python: how to show results on a web page? Most likely it's a dumb question for those who knows the answer, but I'm a beginner, and here it goes: I have a Python script which I run in a command-line with some parameter, and it prints me some results. Let's say results are some HTML code. I never done any Python pr...
Python: how to show results on a web page?
Most likely it's a dumb question for those who knows the answer, but I'm a beginner, and here it goes: I have a Python script which I run in a command-line with some parameter, and it prints me some results. Let's say results are some HTML code. I never done any Python programming for web, and couldn't figure it out......
[ "For such a simple task, you probably don't need more than CGI. Luckily Python has a built-in cgi module which should do what you want.\nOr you could look into some of the minimal web frameworks, such as web.py.\n", "Sounds like you just need to enable CGI on apache, which pretty much will redirect your output to...
[ 4, 4, 2, 1, 0, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0001534070_python.txt
Q: Reading from sockets and download speed Just for fun, I develop a download manager and I'd like to know if reading a large stack of data (i.e. 80 or 100KB) from a socket over the net makes the download speed higher, instead of reading 4KB for each loop iteration? (My average download speed is 200KBPS when I downlo...
Reading from sockets and download speed
Just for fun, I develop a download manager and I'd like to know if reading a large stack of data (i.e. 80 or 100KB) from a socket over the net makes the download speed higher, instead of reading 4KB for each loop iteration? (My average download speed is 200KBPS when I download a file with firefox for example) Thanks, N...
[ "The answer is NO.\nyour network transfer rate (200kbps) indicates that buffering 4k or 8k or 200k will hardly make a difference. The time spent between reads is too small. The bottleneck seems to be your transfer rate anyway.\nLet's try with a stackoverflow 30.9MB mp3 podcast:\n\nNOTE: This is a unreliable hack wh...
[ 2 ]
[]
[]
[ "python", "sockets" ]
stackoverflow_0001537161_python_sockets.txt
Q: Customizing time zones for Django users using geography I am working on a Django app that needs to report the local time relative to the user. I would prefer not ask the user to input the time zone directly because I have his address stored in the database. I am only considering American users. Since most state...
Customizing time zones for Django users using geography
I am working on a Django app that needs to report the local time relative to the user. I would prefer not ask the user to input the time zone directly because I have his address stored in the database. I am only considering American users. Since most states in the USA are in only one time zone it is possible to calc...
[ "I am not sure such a library exists. Every state in the USA doesn't have only one time zone.\nHave a look here: List of U.S. states by time zone\nMany states have more than one.\nI guess you could still use that list and pick the timezone that the majority of the state uses and then allow the users to customize th...
[ 3, 0, 0 ]
[]
[]
[ "django", "python", "timezone" ]
stackoverflow_0001536392_django_python_timezone.txt
Q: Creating Title / Slug based on PK ID What would be the generic way to create record title and slub based on the ID? I am working with django-photologue here. I want to save a record with title and slug based on the PK. The generic problem is that I can't get the PK until the record is saved into database. On the o...
Creating Title / Slug based on PK ID
What would be the generic way to create record title and slub based on the ID? I am working with django-photologue here. I want to save a record with title and slug based on the PK. The generic problem is that I can't get the PK until the record is saved into database. On the other side, I can't save it without title a...
[ "Normally you don't use the primary key at all. If your concern is just to automatically generate unique slugs (which is the only reason I can see to do what you're trying to do), then you want an AutoSlugField, which creates a unique slug by increasing an appended number on the slug until it is unique.\nThere's an...
[ 1, 1, 0 ]
[]
[]
[ "django", "django_profiles", "python" ]
stackoverflow_0001537149_django_django_profiles_python.txt
Q: What do I need to know/learn for automated python deployment? I'm starting a new webapp project in Python to get into the Agile mind-set and I'd like to do things "properly" with regards to deployment. However, I'm finding the whole virtualenv/fabric/zc.buildout/etc stuff a little confusing - I'm used to just FTP'...
What do I need to know/learn for automated python deployment?
I'm starting a new webapp project in Python to get into the Agile mind-set and I'd like to do things "properly" with regards to deployment. However, I'm finding the whole virtualenv/fabric/zc.buildout/etc stuff a little confusing - I'm used to just FTP'ing PHP files to a server and pointing a webserver at it. After dep...
[ "Your deployment story depends on your app. Are you using Django? Then the Apache + mod_wsgi deployment docs make for a good starting point. Then you can google around for more detail, such as this 2-part series using pip, virtualenv, git, and fabric.\nReally, fabric, virtualenv, and all those other tools are desig...
[ 4, 2, 2 ]
[]
[]
[ "deployment", "python", "virtualenv" ]
stackoverflow_0001537298_deployment_python_virtualenv.txt
Q: Lua as a general-purpose scripting language? When I see Lua, the only thing I ever read is "great for embedding", "fast", "lightweight" and more often than anything else: "World of Warcraft" or in short "WoW". Why is it limited to embedding the whole thing into another application? Why not write general-purpose sc...
Lua as a general-purpose scripting language?
When I see Lua, the only thing I ever read is "great for embedding", "fast", "lightweight" and more often than anything else: "World of Warcraft" or in short "WoW". Why is it limited to embedding the whole thing into another application? Why not write general-purpose scripts like you do with Python or Perl? Lua seems t...
[ "Lua is a cool language, light-weight and extremely fast!\nBut the point is: Is performance so important for those\ntasks you mentioned?\n\nRenaming a bunch of files\nDownload some files from the web\nWebscraping\n\nYou write those programs once, and run them once, too maybe.\nWhy do you care about performance so m...
[ 40, 23, 12, 10, 9, 6, 5, 4, 4, 4, 3 ]
[]
[]
[ "lua", "python", "scripting" ]
stackoverflow_0000250151_lua_python_scripting.txt
Q: Identifying twitter user's longitude and latitude As per my requirement in need to search twitter and display user's location on map. Can anyone help me identifying longitude and latitude from search api result? A: Last time I looked it didn't include it officially, unless the specific client (such as an iphone ...
Identifying twitter user's longitude and latitude
As per my requirement in need to search twitter and display user's location on map. Can anyone help me identifying longitude and latitude from search api result?
[ "Last time I looked it didn't include it officially, unless the specific client (such as an iphone client) specifically updated your location to lat+long coordinates.\nWhen I did something similar I passed the Twitter RSS output through an rss geotagging service, then used the output from that to map. It worked, bu...
[ 1, 1, 0 ]
[]
[]
[ "asp.net", "c#", "python", "twitter" ]
stackoverflow_0001537303_asp.net_c#_python_twitter.txt
Q: Read bytes from string as floats I've got a python webserver where small binary files are POST:ed. The posted data is represented as strings. I want to examine the contents of these strings. But to do that, I need to convert each 4 bytes to floats (little endian). How do you do that? A: You use the struct module...
Read bytes from string as floats
I've got a python webserver where small binary files are POST:ed. The posted data is represented as strings. I want to examine the contents of these strings. But to do that, I need to convert each 4 bytes to floats (little endian). How do you do that?
[ "You use the struct module:\n>>> import struct\n>>> struct.unpack_from(\"f\", \"\\43\\a3\\12\\32\")\n(8.6198787687447256e-33,)\n\n", "While struct is best for unpacking collection of \"scalar\" binary values, when you what you have is a sequence of 4-byte binary floats in a string one after the other, the array m...
[ 7, 5, 1 ]
[]
[]
[ "byte", "python", "string" ]
stackoverflow_0001537862_byte_python_string.txt
Q: QGraphicsView with automatic items placing I would like to write an asset browser using QGraphicsView. It's a little different from examples using QGraphicsView and QGraphicsItems, because I want only one scrollbar and I want items to move automatically, when the viewport size changes. For example, when viewport w...
QGraphicsView with automatic items placing
I would like to write an asset browser using QGraphicsView. It's a little different from examples using QGraphicsView and QGraphicsItems, because I want only one scrollbar and I want items to move automatically, when the viewport size changes. For example, when viewport width is large enough to display 4 asssets, they ...
[ "QGraphicsView supports layouts. What you have to do is implement your own layout manager, inheriting from QGraphicsLayout.\nFor the layout you require, take a look at the Flow Layout example of Qt. Converting that example will give you a QGraphicsFlowLayout. Add your QGraphicsItems to this layout and set your QGra...
[ 5, 1 ]
[ "I would use a custom layout to do this. Try to create your custom Layout class that inherits from QGraphicsLayout and manage the way it is placing items.\n" ]
[ -1 ]
[ "pyqt", "python", "qgraphicsview", "qt" ]
stackoverflow_0001538308_pyqt_python_qgraphicsview_qt.txt
Q: Is the single underscore "_" a built-in variable in Python? I don't understand what this single underscore means. Is it a magic variable? I can't see it in locals() and globals(). >>> 'abc' 'abc' >>> len(_) 3 >>> A: In the standard Python REPL, _ represents the last returned value -- at the point where you call...
Is the single underscore "_" a built-in variable in Python?
I don't understand what this single underscore means. Is it a magic variable? I can't see it in locals() and globals(). >>> 'abc' 'abc' >>> len(_) 3 >>>
[ "In the standard Python REPL, _ represents the last returned value -- at the point where you called len(_), _ was the value 'abc'.\nFor example:\n>>> 10\n10\n>>> _\n10\n>>> _ + 5\n15\n>>> _ + 5\n20\n\nThis is handled by sys.displayhook, and the _ variable goes in the builtins namespace with things like int and sum,...
[ 53, 18, 2 ]
[]
[]
[ "python" ]
stackoverflow_0001538832_python.txt
Q: Is there a way around coding in Python without the tab, indent & whitespace criteria? I want to start using Python for small projects but the fact that a misplaced tab or indent can throw a compile error is really getting on my nerves. Is there some type of setting to turn this off? I'm currently using NotePad++. ...
Is there a way around coding in Python without the tab, indent & whitespace criteria?
I want to start using Python for small projects but the fact that a misplaced tab or indent can throw a compile error is really getting on my nerves. Is there some type of setting to turn this off? I'm currently using NotePad++. Is there maybe an IDE that would take care of the tabs and indenting?
[ "The answer is no.\nAt least, not until something like the following is implemented:\nfrom __future__ import braces\n\n", "No. Indentation-as-grammar is an integral part of the Python language, for better and worse.\n", "Emacs! Seriously, its use of \"tab is a command, not a character\", is absolutely perfect ...
[ 45, 37, 10, 6, 5, 5, 4, 3, 3, 3, 2, 2, 2, 2, 1, 1, 1, 1, 0, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0000063086_python.txt
Q: Using Python's xml.dom.minidom I'm trying to use Python's xml.dom.minidom, and I'm getting the following error: >>> from xml.dom import minidom >>> xdocument = minidom.Document() >>> xrss = minidom.Element("rss") >>> xdocument.appendChild(xrss) <DOM Element: rss at 0xc1d0f8> >>> xchannel = minidom.Element("channel...
Using Python's xml.dom.minidom
I'm trying to use Python's xml.dom.minidom, and I'm getting the following error: >>> from xml.dom import minidom >>> xdocument = minidom.Document() >>> xrss = minidom.Element("rss") >>> xdocument.appendChild(xrss) <DOM Element: rss at 0xc1d0f8> >>> xchannel = minidom.Element("channel") >>> xrss.appendChild(xchannel) Tr...
[ "Use xdocument.createElement('name') to create new elements. This is the standard way to do that in DOM.\n", "Replace xdocument.appendChild(xrss) with xrss = xdocument.appendChild(xrss). From the docs:\n\nNode.appendChild(newChild) Add a new\n child node to this node at the end of\n the list of children, return...
[ 3, 0 ]
[]
[]
[ "python", "xml" ]
stackoverflow_0001539023_python_xml.txt
Q: How to sort all possible words out of a string? I'm wondering how to proceed with this task, take this string for example "thingsandstuff". How could I generate all possible strings out of this string as to look them up individually against an english dictionary? The goal is to find valid english words in a string...
How to sort all possible words out of a string?
I'm wondering how to proceed with this task, take this string for example "thingsandstuff". How could I generate all possible strings out of this string as to look them up individually against an english dictionary? The goal is to find valid english words in a string that does not contain space. Thanks
[ "Another possibility is going the other way around, instead of generating substrings from a string, grab all your candidate words and match them against your string. \nYou can store as a result (start,end) pairs of indexes of the words in the original string.\nThis could be easily done in regex, or, if not performa...
[ 5, 5, 3, 2, 1, 0, 0, 0, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0001538589_python.txt
Q: Changing document's attributes in Python's xml.dom.minidom I created a xml.dom.minidom.Document. How do I give it attributes so that when I do .toprettyxml() it will show like this: <?xml version="1.0" encoding="iso-8859-2"?> A: .toprettyxml() has an encoding keyword argument: Document.toprettyxml(self, indent='...
Changing document's attributes in Python's xml.dom.minidom
I created a xml.dom.minidom.Document. How do I give it attributes so that when I do .toprettyxml() it will show like this: <?xml version="1.0" encoding="iso-8859-2"?>
[ ".toprettyxml() has an encoding keyword argument:\nDocument.toprettyxml(self, indent='\\t', newl='\\n', encoding=None)\n\n" ]
[ 1 ]
[]
[]
[ "python", "xml" ]
stackoverflow_0001539555_python_xml.txt
Q: Weird behaviour with two Trac instances under Apache + mod_wsgi I am trying to configure two Trac instances in order to access them via browser each one with a different url: http://trac.domain.com/trac1 http://trac.domain.com/trac2 First time I access them Apache response is fine, I get the first Trac with /trac...
Weird behaviour with two Trac instances under Apache + mod_wsgi
I am trying to configure two Trac instances in order to access them via browser each one with a different url: http://trac.domain.com/trac1 http://trac.domain.com/trac2 First time I access them Apache response is fine, I get the first Trac with /trac1, then the second one in /trac2. But when I access /trac1 again, it ...
[ "I found the solution myself, it was on the Trac documentation (\"important note\" section), and I did not event take look, fool of me :P\nhttp://trac.edgewall.org/wiki/TracModWSGI\n", "Move your egg cache to separate dirs\ntrac1.wsgi:\nimport os\n\nos.environ['TRAC_ENV'] = '/home/myuser/trac/trac1' \nos.environ[...
[ 2, 0 ]
[]
[]
[ "apache", "mod_wsgi", "python", "trac" ]
stackoverflow_0001539203_apache_mod_wsgi_python_trac.txt
Q: How to redirect and then display errors with Google App Engine I'm working on a Google App Engine project that collects stories submitted by users. This is how I handle submission errors in the post method of my Request Handler: # get the title and content using self.request.get() errors = [] if not title: err...
How to redirect and then display errors with Google App Engine
I'm working on a Google App Engine project that collects stories submitted by users. This is how I handle submission errors in the post method of my Request Handler: # get the title and content using self.request.get() errors = [] if not title: errors.append("Please enter a title.") if not content: errors.appen...
[ "You could redirect to /Share including the errors in a GET variable in the URL, if you're absolutely sure you need to use separate URLs. Of course, this makes your URL ugly since it now has all of the error information in it.\nAnother option would be to redirect back to Share and have the errors stored in cookies...
[ 1, 1 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0001538287_google_app_engine_python.txt
Q: Why isn't getopt working if sys.argv is passed fully? If I'm using this with getopt: import getopt import sys opts,args = getopt.getopt(sys.argv,"a:bc") print opts print args opts will be empty. No tuples will be created. If however, I'll use sys.argv[1:], everything works as expected. I don't understand why tha...
Why isn't getopt working if sys.argv is passed fully?
If I'm using this with getopt: import getopt import sys opts,args = getopt.getopt(sys.argv,"a:bc") print opts print args opts will be empty. No tuples will be created. If however, I'll use sys.argv[1:], everything works as expected. I don't understand why that is. Anyone care to explain?
[ "The first element of sys.argv (sys.argv[0]) is the name of the script currently being executed. Because this script name is (likely) not a valid argument (and probably doesn't begin with a - or -- anyway), getopt does not recognize it as an argument. Due to the nature of how getopt works, when it sees something th...
[ 16, 7 ]
[]
[]
[ "getopt", "python" ]
stackoverflow_0001540365_getopt_python.txt
Q: Should I Start With Python 3.0? Recently I decided to expand my programming horizons and learn the python programming language. While I have used python a little bit for classes in college and for a project or two at work I am by no means an expert. My question is as follows: should I bother with the 2.x releases ...
Should I Start With Python 3.0?
Recently I decided to expand my programming horizons and learn the python programming language. While I have used python a little bit for classes in college and for a project or two at work I am by no means an expert. My question is as follows: should I bother with the 2.x releases or should I jump straight to 3.0? I a...
[ "Absolutely not 3.0 - 3.1 is out and is stabler, better, faster in every respect; it makes absolutely no sense to start with 3.0 at this time, if you want to take up the 3 series it should on all accounts be 3.1.\nAs for 2.6 vs 3.1, 3.1 is a better language (especially because some cruft was removed that had accumu...
[ 20, 8, 7, 4, 3, 2, 2, 2 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0001222782_python_python_3.x.txt
Q: the fastest way to create checksum for large files in python i need to transfer large files across network and need to create checksum for them on hourly basis. so the speed for generating checksum is critical for me. somehow i can't make zlib.crc32 and zlib.adler32 working with files larger than 4GB on Windows XP...
the fastest way to create checksum for large files in python
i need to transfer large files across network and need to create checksum for them on hourly basis. so the speed for generating checksum is critical for me. somehow i can't make zlib.crc32 and zlib.adler32 working with files larger than 4GB on Windows XP Pro 64bit machine. i suspect i've hit the 32bit limitation here? ...
[ "It's an algorithm selection problem, rather than a library/language selection problem!\nThere appears to be two points to consider primarily:\n\nhow much would the disk I/O affect the overall performance?\nwhat is the expected reliability of the error detection feature?\n\nApparently, the answer to the second ques...
[ 5, 3, 2, 1, 1, 0 ]
[]
[]
[ "crc32", "hashlib", "md5", "multithreading", "python" ]
stackoverflow_0001532720_crc32_hashlib_md5_multithreading_python.txt
Q: Python 'object' type and inheritance In Python I can define a class 'foo' in the following ways: class foo: pass or class foo(object): pass What is the difference? I have tried to use the function issubclass(foo, object) to see if it returns True for both class definitions. It does not. IDLE 2.6.3 ...
Python 'object' type and inheritance
In Python I can define a class 'foo' in the following ways: class foo: pass or class foo(object): pass What is the difference? I have tried to use the function issubclass(foo, object) to see if it returns True for both class definitions. It does not. IDLE 2.6.3 >>> class foo: pass >>> issubc...
[ "Inheriting from object makes a class a \"new-style class\". There is a discussion of old-style vs. new-style here: What is the difference between old style and new style classes in Python?\nAs @CrazyJugglerDrummer commented below, in Python 3 all classes are \"new-style\" classes. In Python 3, the following two ...
[ 9, 2, 2 ]
[]
[]
[ "inheritance", "object", "python" ]
stackoverflow_0001540975_inheritance_object_python.txt
Q: python regular expression to parse div tags a question about python regular expression. I would like to match a div block like <div class="leftTail"><ul class="hotnews">any news stuff</ul></div> I was thinking a pattern like p = re.compile(r'<div\s+class=\"leftTail\">[^(div)]+</div>') but it seems not working p...
python regular expression to parse div tags
a question about python regular expression. I would like to match a div block like <div class="leftTail"><ul class="hotnews">any news stuff</ul></div> I was thinking a pattern like p = re.compile(r'<div\s+class=\"leftTail\">[^(div)]+</div>') but it seems not working properly another pattern p = re.compile(r'<div\s+c...
[ "You might want to consider graduating to an actual HTML parser. I suggest you give Beautiful Soup a try. There are many crazy ways for HTML to be formatted, and the regular expressions may not work correctly all the time, even if you write them correctly.\n", "Don't use regular expressions to parse XML or HTML...
[ 12, 4, 4 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0001541281_python_regex.txt
Q: Difference between GET and FILTER in Django model layer What is the difference, please explain them in laymen's terms with examples. Thanks! A: I don't know if you really need an example, it's quite easy: if you know it's one object that matches your query, use get. It will fail if it's more than one. otherwise...
Difference between GET and FILTER in Django model layer
What is the difference, please explain them in laymen's terms with examples. Thanks!
[ "I don't know if you really need an example, it's quite easy:\n\nif you know it's one object that matches your query, use get. It will fail if it's more than one.\notherwise use filter, which gives you a list of objects.\n\nTo be more precise:\n\nMyTable.objects.get(id=x).whatever gives you the whatever property of...
[ 48 ]
[]
[]
[ "django", "python" ]
stackoverflow_0001541249_django_python.txt
Q: How can I make images so that appengine doesn't make transparent into black on resize? I'm on the google appengine, and trying to resize images. I do : from google.appengine.api import images image = images.resize(contents, w, h) And for some images I get a nice transparent resize, and others I get a black backgr...
How can I make images so that appengine doesn't make transparent into black on resize?
I'm on the google appengine, and trying to resize images. I do : from google.appengine.api import images image = images.resize(contents, w, h) And for some images I get a nice transparent resize, and others I get a black background. How can I keep the transparency for all images? Original : http://www.stdicon.com/g-f...
[ "Article on this problem: http://doesnotvalidate.com/2009/resizing-transparent-images-with-django-pil/\nGoogle-code patch: http://code.google.com/p/sorl-thumbnail/issues/detail?id=56\n", "Is this on the dev appserver, or in production? There's a known bug on the dev appserver that turns transparent to black when ...
[ 0, 0, 0 ]
[]
[]
[ "google_app_engine", "python", "python_imaging_library", "resize" ]
stackoverflow_0001476514_google_app_engine_python_python_imaging_library_resize.txt
Q: Debugging swig extensions for Python Is there any other way to debug swig extensions except for doing gdb python stuff.py ? I have wrapped the legacy library libkdtree++ and followed all the swig related memory managemant points (borrowed ref vs. own ref, etc.). But still, I am not sure whether my binding is not...
Debugging swig extensions for Python
Is there any other way to debug swig extensions except for doing gdb python stuff.py ? I have wrapped the legacy library libkdtree++ and followed all the swig related memory managemant points (borrowed ref vs. own ref, etc.). But still, I am not sure whether my binding is not eating up memory. It would be helpful to ...
[ "gdb 7.0 supports python scripting. It might help you in this particular case.\n", "Well, for debugging, you use a debugger ;-).\nWhen debugging, it may be a good idea to configure Python with '--with-pydebug' and recompile. It does additional checks then.\nIf you are looking for memory leaks, there is a simple ...
[ 3, 1 ]
[]
[]
[ "debugging", "python", "swig" ]
stackoverflow_0000828843_debugging_python_swig.txt
Q: Django SELECT statement, Order by Suppose I have 2 models. The 2nd model has a one-to-one relationship with the first model. I'd like to select information from the first model, but ORDER BY the 2nd model. How can I do that? class Content(models.Model): link = models.TextField(blank=True) title = mode...
Django SELECT statement, Order by
Suppose I have 2 models. The 2nd model has a one-to-one relationship with the first model. I'd like to select information from the first model, but ORDER BY the 2nd model. How can I do that? class Content(models.Model): link = models.TextField(blank=True) title = models.TextField(blank=True) is_channel...
[ "I think you can do:\nContent.objects.filter(...).order_by('score__counter')\n\nMore generally, when models have a relationship, you can select, order, and filter by fields on the \"other\" model using the relationshipName__fieldName pseudo attribute of the model which you are selecting on.\n" ]
[ 7 ]
[]
[]
[ "django", "python" ]
stackoverflow_0001541376_django_python.txt
Q: Building universal binaries on Mac - Forcing single compiler child process Cheers, at company, we're creating a port of our games, and we need to compile PythonOgre, a wrapper of Ogre3d for Python. This is an enormous chunk of code, particularly the generated wrapper code. We have a Mac Mini with 1GB RAM. We've bu...
Building universal binaries on Mac - Forcing single compiler child process
Cheers, at company, we're creating a port of our games, and we need to compile PythonOgre, a wrapper of Ogre3d for Python. This is an enormous chunk of code, particularly the generated wrapper code. We have a Mac Mini with 1GB RAM. We've built i386 version. Since we have only 1GB of RAM, we've forced the build system t...
[ "I've checked the source of Apple's GCC driver (the one that supports those -arch options and runs the children processes), and there's no option or environment variable that you can choose.\nThe only options I see left to you are:\n\ndownload the Apple driver (e.g. from there; end of the page) and modify the file ...
[ 2, 1 ]
[]
[]
[ "gcc", "macos", "multicore", "python" ]
stackoverflow_0001536897_gcc_macos_multicore_python.txt
Q: Why Does List Argument in Python Behave Like ByRef? This may be for most languages in general, but I'm not sure. I'm a beginner at Python and have always worked on copies of lists in C# and VB. But in Python whenever I pass a list as an argument and enumerate through using a "for i in range," and then change the...
Why Does List Argument in Python Behave Like ByRef?
This may be for most languages in general, but I'm not sure. I'm a beginner at Python and have always worked on copies of lists in C# and VB. But in Python whenever I pass a list as an argument and enumerate through using a "for i in range," and then change the value of the list argument, the input values actually ch...
[ "Python does pass arguments by value but the value you are receiving is a copy of the reference (incidentally this is the exact same way that C#, VB.NET, and Java behave as well).\nThis is the important thing to remember:\n\nObjects are not passed by reference - object references are passed by value.\n\nSince you h...
[ 8, 4, 0 ]
[]
[]
[ "argument_passing", "object_reference", "python", "reference" ]
stackoverflow_0001541620_argument_passing_object_reference_python_reference.txt
Q: Why is subprocess.Popen not waiting until the child process terminates? I'm having a problem with Python's subprocess.Popen method. Here's a test script which demonstrates the problem. It's being run on a Linux box. #!/usr/bin/env python import subprocess import time def run(cmd): p = subprocess.Popen(cmd, she...
Why is subprocess.Popen not waiting until the child process terminates?
I'm having a problem with Python's subprocess.Popen method. Here's a test script which demonstrates the problem. It's being run on a Linux box. #!/usr/bin/env python import subprocess import time def run(cmd): p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE) return p ### START MAIN # copy some rows ...
[ "subprocess.Popen, when instantiated, runs the program. It does not, however, wait for it -- it fires it off in the background as if you'd typed cmd & in a shell. So, in the code above, you've essentially defined a race condition -- if the inserts can finish in time, it will appear normal, but if not you get the ...
[ 21, 7, 3 ]
[]
[]
[ "mysql", "python" ]
stackoverflow_0001541273_mysql_python.txt
Q: Definition of mathematical operations (sin…) on NumPy arrays containing objects I would like to provide "all" mathematical functions for the number-like objects created by a module (the uncertainties.py module, which performs calculations with error propagation)—these objects are numbers with uncertainties. What i...
Definition of mathematical operations (sin…) on NumPy arrays containing objects
I would like to provide "all" mathematical functions for the number-like objects created by a module (the uncertainties.py module, which performs calculations with error propagation)—these objects are numbers with uncertainties. What is the best way to do this? Currently, I redefine most of the functions from math in t...
[ "It looks like following what NumPy itself does keeps things clean: \"extended\" mathematical operations (sin…) that work on new objects can be put in a separate name space. Thus, NumPy has numpy.sin, etc. These operations are mostly compatible with those from math, but also work on NumPy arrays.\nTherefore, it s...
[ 0 ]
[]
[]
[ "arrays", "numpy", "operations", "python" ]
stackoverflow_0001530598_arrays_numpy_operations_python.txt
Q: Python Class Members Initialization I have just recently battled a bug in Python. It was one of those silly newbie bugs, but it got me thinking about the mechanisms of Python (I'm a long time C++ programmer, new to Python). I will lay out the buggy code and explain what I did to fix it, and then I have a couple of...
Python Class Members Initialization
I have just recently battled a bug in Python. It was one of those silly newbie bugs, but it got me thinking about the mechanisms of Python (I'm a long time C++ programmer, new to Python). I will lay out the buggy code and explain what I did to fix it, and then I have a couple of questions... The scenario: I have a clas...
[ "What you keep referring to as a bug is the documented, standard behavior of Python classes.\nDeclaring a dict outside of __init__ as you initially did is declaring a class-level variable. It is only created once at first, whenever you create new objects it will reuse this same dict. To create instance variables, y...
[ 62, 2, 2, 0, 0 ]
[]
[]
[ "class", "initialization", "python" ]
stackoverflow_0000867219_class_initialization_python.txt
Q: Sort string collection in Python using various locale settings I want to sort list of strings with respect to user language preference. I have a multilanguage Python webapp and what is the correct way to sort strings such way? I know I can set up locale, like this: import locale locale.setlocale(locale.LC_ALL, ''...
Sort string collection in Python using various locale settings
I want to sort list of strings with respect to user language preference. I have a multilanguage Python webapp and what is the correct way to sort strings such way? I know I can set up locale, like this: import locale locale.setlocale(locale.LC_ALL, '') But this should be done on application start (and doc says it is ...
[ "I would recommend pyICU -- Python bindings for IBM's rich open-source ICU internationalization library. You make a Collator object e.g. with:\n collator = PyICU.Collator.createInstance(PyICU.Locale.getFrance())\n\nand then you can sort e.g. a list of utf-8 encoded strings by the rules for French, e.g. by using...
[ 4, 1, 0, 0 ]
[]
[]
[ "collation", "google_app_engine", "python", "sorting", "web_applications" ]
stackoverflow_0001526109_collation_google_app_engine_python_sorting_web_applications.txt
Q: How to write this "model" in Django? I am currently using Django Users model. Very simple. However, I'd like to add one feature: Adding friends! I would like to create 2 columns in my table: UID (the ID of the User) friend_id (the ID of his friend! ...of course, this ID is also in Django's User model. The UID-fri...
How to write this "model" in Django?
I am currently using Django Users model. Very simple. However, I'd like to add one feature: Adding friends! I would like to create 2 columns in my table: UID (the ID of the User) friend_id (the ID of his friend! ...of course, this ID is also in Django's User model. The UID-friend_id combination must be unique! For exa...
[ "You should create a model that defines the relationship between two users, and then define two foreign-key fields, each one to a User. You can then add a unique constraint to make sure you don't have duplicates.\nThere is a article here explaining exactly how to do this: http://www.packtpub.com/article/building-fr...
[ 11 ]
[]
[]
[ "django", "python" ]
stackoverflow_0001542659_django_python.txt
Q: Does python's print function handle unicode differently now than when Dive Into Python was written? I'm trying to work my way through some frustrating encoding issues by going back to basics. In Dive Into Python example 9.14 (here) we have this: >>> s = u'La Pe\xf1a' >>> print s Traceback (innermost last): File "...
Does python's print function handle unicode differently now than when Dive Into Python was written?
I'm trying to work my way through some frustrating encoding issues by going back to basics. In Dive Into Python example 9.14 (here) we have this: >>> s = u'La Pe\xf1a' >>> print s Traceback (innermost last): File "<interactive input>", line 1, in ? UnicodeError: ASCII encoding error: ordinal not in range(128) >>> prin...
[ "The default encoding for print doesn't depend on sys.getdefaultencoding(), but on sys.stdout.encoding. If you launch python with e.g. LANG=C or redirect a python script to a file, the encoding for stdout will be ANSI_X3.4-1968. On the other hand, if sys.stdout is a terminal, it will use the terminal's encoding.\nT...
[ 6 ]
[]
[]
[ "character_encoding", "python", "unicode" ]
stackoverflow_0001542785_character_encoding_python_unicode.txt
Q: Help in the following code def startConnection(self): from ftplib import FTP self.ftp = FTP(self.loginServer) print 'Loging In' print self.ftp.login(self.username, self.password) data = [] self.ftp.dir(data.append) for line in data: try: self.date_str = ' '.join(line...
Help in the following code
def startConnection(self): from ftplib import FTP self.ftp = FTP(self.loginServer) print 'Loging In' print self.ftp.login(self.username, self.password) data = [] self.ftp.dir(data.append) for line in data: try: self.date_str = ' '.join(line.split()[5:8]) newDa...
[ "Try\nself.ftp.dir('-lTr', data.append)\n\n", "If you are using a command that gives a short-form date, or want to cope with different arguments being handed to ls you'll have to make multiple attempts to parse the date with different format strings, until you don't get a ValueError, post-processing the successfu...
[ 1, 0 ]
[]
[]
[ "ftplib", "python" ]
stackoverflow_0001542991_ftplib_python.txt
Q: Determine which Button was pressed in Tkinter? I'm making a simple little utility while learning Python. It dynamically generates a list of buttons: for method in methods: button = Button(self.methodFrame, text=method, command=self.populateMethod) button.pack({'fill': 'x', 'expand': 1, 'padx': 5, 'pady': ...
Determine which Button was pressed in Tkinter?
I'm making a simple little utility while learning Python. It dynamically generates a list of buttons: for method in methods: button = Button(self.methodFrame, text=method, command=self.populateMethod) button.pack({'fill': 'x', 'expand': 1, 'padx': 5, 'pady': 3}) That part works fine. However, I need to know ...
[ "You can use lambda to pass arguments to a command:\ndef populateMethod(self, method):\n print \"method:\", method\n\nfor method in [\"one\",\"two\",\"three\"]:\n button = Button(self.methodFrame, text=method, \n command=lambda m=method: self.populateMethod(m))\n button.pack({'fill': 'x', 'expand': ...
[ 24, 2 ]
[]
[]
[ "button", "python", "tkinter" ]
stackoverflow_0001539787_button_python_tkinter.txt
Q: binding local variables in python I wonder if there is a good way to bind local variables in python. Most of my work involves cobbling together short data or text processing scripts with a series of expressions (when python permits), so defining object classes (to use as namespaces) and instantiating them seems a ...
binding local variables in python
I wonder if there is a good way to bind local variables in python. Most of my work involves cobbling together short data or text processing scripts with a series of expressions (when python permits), so defining object classes (to use as namespaces) and instantiating them seems a bit much. So what I had in mind was so...
[ "I can only second Lennart and Daniel - Python is not Lisp, and trying to write language X into language Y is usually inefficient and frustrating at best.\nFirst point: your example code\ndata = [1,2,3]\noutput = ((lambda x: x + x)\n (data[2]))\n\nwould be much more readable as:\ndata = [1, 2, 3]\noutput =...
[ 3, 2, 2, 1 ]
[]
[]
[ "lisp", "python" ]
stackoverflow_0001542551_lisp_python.txt
Q: Pure Python persistent key and value based container (a hash like interface) with large file system support? I am looking for a (possibly) pure Python library for persistent hash table (btree or b+tree which would provide following features Large file support (possibly in terabytes) Fast enough and low memory foo...
Pure Python persistent key and value based container (a hash like interface) with large file system support?
I am looking for a (possibly) pure Python library for persistent hash table (btree or b+tree which would provide following features Large file support (possibly in terabytes) Fast enough and low memory footprint (looking for a descent balance between speed and memory) Low cost of management Reliability i.e. doesn't co...
[ "ZODB\nhttp://pypi.python.org/pypi/ZODB3\nLike Lennart says, use the latest version of course\n", "Use a relational database. \n\nReally fast when retrieving data based on a key, if you put an index in the key. \nGood scaling\nDon't get easily corrupted\nTools already available for:\n\n\nBackups\nReplication\nClu...
[ 2, 2, 1 ]
[]
[]
[ "hash", "persistence", "python" ]
stackoverflow_0001543087_hash_persistence_python.txt
Q: Attribute as dict of lists using middleman table with SQLAlchemy My question is about SQLAlchemy but I'm having troubles explaining it in words so I figured I explain it with a simple example of what I'm trying to achieve: parent = Table('parent', metadata, Column('parent_id', Integer, primary_key=True), C...
Attribute as dict of lists using middleman table with SQLAlchemy
My question is about SQLAlchemy but I'm having troubles explaining it in words so I figured I explain it with a simple example of what I'm trying to achieve: parent = Table('parent', metadata, Column('parent_id', Integer, primary_key=True), Column('name', Unicode), ) parent_child = Table('parent_child', metadat...
[ "You have to define your own collection class. There are only 3 methods to implement: appender, remover, and converter. See sqlalchemy.orm.collections.MappedCollection as an example.\nUpdate: Here is quick-n-dirty implementation according to your requirements:\nfrom sqlalchemy import *\nfrom sqlalchemy.orm import m...
[ 2 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0001534673_python_sqlalchemy.txt
Q: Can't get django-registration to work (on Windows) Trying to add django-registration to my app. I have installed setup tools to use easy_install. I think that works.. I run easy_install django-registation and a cmd prompt window flashes up, does something and closes. I don't think it's an error. But when I look in...
Can't get django-registration to work (on Windows)
Trying to add django-registration to my app. I have installed setup tools to use easy_install. I think that works.. I run easy_install django-registation and a cmd prompt window flashes up, does something and closes. I don't think it's an error. But when I look in my app folder, theres nothing relation to django-regist...
[ "Django-registration will be installed on your python path, not in the project itself. You can see if it installed correctly by entering your python prompt and running:\n>>>import registration\n\nIf you don't get an error it is working and installed. Just add 'registration' to your INSTALLED_APPS. \n" ]
[ 4 ]
[]
[]
[ "django", "easy_install", "python", "registration", "setuptools" ]
stackoverflow_0001543601_django_easy_install_python_registration_setuptools.txt
Q: Zero results in Query/GqlQuery How do I know if the results of my query either using the Query interface or the GqlQuery interface returned zero results? Would using .get() on zero results produce an error? If yes, what's the best way to handle it? A: when doing a get() if there are no results you will have an o...
Zero results in Query/GqlQuery
How do I know if the results of my query either using the Query interface or the GqlQuery interface returned zero results? Would using .get() on zero results produce an error? If yes, what's the best way to handle it?
[ "when doing a get() if there are no results you will have an object containing None\nI normally do \nresult = query.get()\nif result is None:\n #do the following\n\nor if you want to check that its not none then\nif result is not None:\n #do the following\n\n", "if a query returns no results, fetch() returns an...
[ 5, 2 ]
[]
[]
[ "google_app_engine", "gql", "gqlquery", "python", "queryinterface" ]
stackoverflow_0001509407_google_app_engine_gql_gqlquery_python_queryinterface.txt
Q: What are some useful non-built-in Django tags? I'm relatively new to Django and I'm trying to build up my toolbox for future projects. In my last project, when a built-in template tag didn't do quite what I needed, I would make a mangled mess of the template to shoe-horn in the feature. I later would find a temp...
What are some useful non-built-in Django tags?
I'm relatively new to Django and I'm trying to build up my toolbox for future projects. In my last project, when a built-in template tag didn't do quite what I needed, I would make a mangled mess of the template to shoe-horn in the feature. I later would find a template tag that would have saved me time and ugly code...
[ "I'll start.\nhttp://www.djangosnippets.org/snippets/1350/\nSmart {% if %} template tag\nIf you've ever found yourself needing more than a test for True, this tag is for you. It supports equality, greater than, and less than operators.\nSimple Example\n{% block list-products %}\n {% if products|length > 12 %}\n...
[ 4, 3, 1, 1 ]
[]
[]
[ "django", "django_tagging", "favorites", "python" ]
stackoverflow_0001532021_django_django_tagging_favorites_python.txt
Q: Comprehensions in Python and Javascript are only very basic? Looking at comprehensions in Python and Javascript, so far I can't see some of the main features that I consider most powerful in comprehensions in languages like Haskell. Do they allow things like multiple generators? Or are they just a basic map-fil...
Comprehensions in Python and Javascript are only very basic?
Looking at comprehensions in Python and Javascript, so far I can't see some of the main features that I consider most powerful in comprehensions in languages like Haskell. Do they allow things like multiple generators? Or are they just a basic map-filter form? If they don't allow multiple generators, I find them qui...
[ "Python allows multiple generators:\n>>> [(x,y,x*y) for x in range(1,5) for y in range(1,5)]\n[(1, 1, 1), (1, 2, 2), (1, 3, 3), (1, 4, 4), \n (2, 1, 2), (2, 2, 4), (2, 3, 6), (2, 4, 8), \n (3, 1, 3), (3, 2, 6), (3, 3, 9), (3, 4, 12),\n (4, 1, 4), (4, 2, 8), (4, 3, 12), (4, 4, 16)]\n\nAnd also restrictions:\n>>> [(x...
[ 12, 3, 1, 1 ]
[]
[]
[ "haskell", "javascript", "list_comprehension", "python" ]
stackoverflow_0001543820_haskell_javascript_list_comprehension_python.txt
Q: simple dropping elements from the list in python I'd like to achieve following effect a=[11, -1, -1, -1] msg=['one','two','tree','four'] msg[where a<0] ['two','tree','four'] In similar simple fashion (without nasty loops). PS. For curious people this if statement is working natively in one of functional languages...
simple dropping elements from the list in python
I'd like to achieve following effect a=[11, -1, -1, -1] msg=['one','two','tree','four'] msg[where a<0] ['two','tree','four'] In similar simple fashion (without nasty loops). PS. For curious people this if statement is working natively in one of functional languages. //EDIT I know that below text is different that the...
[ "You can use list comprehensions for this. You need to match the items from the two lists, for which the zip function is used. This will generate a list of tuples, where each tuple contains one item from each of the original lists (i.e., [(11, 'one'), ...]). Once you have this, you can iterate over the result, chec...
[ 10, 2, 1, 0 ]
[]
[]
[ "filter", "python" ]
stackoverflow_0001543456_filter_python.txt
Q: Non-intrusively unlock file on Windows Is there a way to unlock a file on Windows with a Python script? The file is exclusively locked by another process. I need a solution without killing or interupting the locking process. I already had a look at portalocker, a portable locking implementation. But this needs a f...
Non-intrusively unlock file on Windows
Is there a way to unlock a file on Windows with a Python script? The file is exclusively locked by another process. I need a solution without killing or interupting the locking process. I already had a look at portalocker, a portable locking implementation. But this needs a file handle to unlock, which I can not get, a...
[ "Anything you do will affect the other process if that process thinks it has a lock on the file then breaking the lock means that the program has unexpected brhaviour and could brek or corrupt things.\nThus only do this if you know exactly what will happen.\nThe api used by the other program probably uses msdn Lock...
[ 1, 1 ]
[]
[]
[ "file", "locking", "python", "winapi", "windows" ]
stackoverflow_0001544275_file_locking_python_winapi_windows.txt
Q: Django Reuseable Apps I came across many resources about the difference between Django projects and reusable apps, most prominently the DjangoCon talk, and Pinax Project. However, being a newbie, writing my own projects and reusable software seems to a bit challenging. I don't quite understand how where models go...
Django Reuseable Apps
I came across many resources about the difference between Django projects and reusable apps, most prominently the DjangoCon talk, and Pinax Project. However, being a newbie, writing my own projects and reusable software seems to a bit challenging. I don't quite understand how where models go (and how apps can be flexi...
[ "James Bennett's Practical Django Projects does a pretty good job of covering those topics in general and even includes a chapter specifically on \"Writing Reusable Django Applications\" that goes through an example of splitting one of the example projects in the book out into its own app.\n", "You can watch vide...
[ 4, 3, 3 ]
[]
[]
[ "django", "django_apps", "python" ]
stackoverflow_0001539485_django_django_apps_python.txt
Q: Condense this Python statement without destroying readability I'm pretty new to Python still, so I'm trying to figure out how to do this and need some help. I use return codes to verify that my internal functions return successfully. For example (from internal library functions): result = some_function(arg1,arg2) ...
Condense this Python statement without destroying readability
I'm pretty new to Python still, so I'm trying to figure out how to do this and need some help. I use return codes to verify that my internal functions return successfully. For example (from internal library functions): result = some_function(arg1,arg2) if result != OK: return result or (from main script level): result...
[ "Could you use exceptions to indicate failure, rather than return codes? Then most of your if result != OK: statements would simply go away.\n", "pythonic:\n\nAn idea or piece of code which closely follows the most common idioms of the Python language, rather than implementing code using concepts common to other...
[ 10, 3, 3, 1 ]
[ "In addition to exceptions, using a decorator is a good solution to this problem:\n# Create a function that creates a decorator given a value to fail on...\ndef fail_unless(ok_val):\n def _fail_unless(f):\n def g(*args, **kwargs):\n val = f(*args, **kwargs)\n if val != ok_val:\n ...
[ -1 ]
[ "python" ]
stackoverflow_0001544350_python.txt
Q: Storing parameters in a class, and how to access them I'm writing a program that randomly assembles mathematical expressions using the values stored in this class. The operators are stored in a dictionary along with the number of arguements they need. The arguements are stored in a list. (the four x's ensure that ...
Storing parameters in a class, and how to access them
I'm writing a program that randomly assembles mathematical expressions using the values stored in this class. The operators are stored in a dictionary along with the number of arguements they need. The arguements are stored in a list. (the four x's ensure that the x variable gets chosen often) depth, ratio, method and ...
[ "What you have there are object properties. You mean to use class variables:\nclass Params(object):\n atoms =['1.0','2.0','3.0','4.0','5.0','6.0','7.0','8.0','9.0','x','x','x','x']\n operators = {'+': 2, '-': 2, '*': 2, '/': 2,'+': 2, '-': 2, '*': 2, '/': 2, '**': 2, '%': 2}\n depth = 1\n ratio = .4\n ...
[ 7, 0 ]
[]
[]
[ "python" ]
stackoverflow_0001544672_python.txt
Q: (i'm close - i think) Python loop through list of subdomains with selenium starting with a base URL, I'm trying to have selenium loop through a short list of subdomains in csv format (ie: one column of 20 subdomains) and printing the html for each. I'm having trouble figuring it out. Thanks! from selenium import s...
(i'm close - i think) Python loop through list of subdomains with selenium
starting with a base URL, I'm trying to have selenium loop through a short list of subdomains in csv format (ie: one column of 20 subdomains) and printing the html for each. I'm having trouble figuring it out. Thanks! from selenium import selenium import unittest, time, re, csv, logging subds = csv.reader(open('listof...
[ "You're defining the same function again and again in the body of the class. The class is completely created before unittest.main() starts, so only one test method will remain in the class.\n" ]
[ 1 ]
[]
[]
[ "for_loop", "python", "selenium" ]
stackoverflow_0001544701_for_loop_python_selenium.txt
Q: Python one-line "for" expression I'm not sure if I need a lambda, or something else. But still, I need the following: I have an array = [1,2,3,4,5]. I need to put this array, for instance, into another array. But write it all in one line. for item in array: array2.append(item) I know that this is completely p...
Python one-line "for" expression
I'm not sure if I need a lambda, or something else. But still, I need the following: I have an array = [1,2,3,4,5]. I need to put this array, for instance, into another array. But write it all in one line. for item in array: array2.append(item) I know that this is completely possible to iterate through the items a...
[ "The keyword you're looking for is list comprehensions:\n>>> x = [1, 2, 3, 4, 5]\n>>> y = [2*a for a in x if a % 2 == 1]\n>>> print(y)\n[2, 6, 10]\n\n", "for item in array: array2.append (item)\n\nOr, in this case:\narray2 += array\n\n", "If you really only need to add the items in one array to another, the '+'...
[ 121, 29, 3, 3, 2 ]
[]
[]
[ "lambda", "python" ]
stackoverflow_0001545050_lambda_python.txt
Q: python numpy savetxt Can someone indicate what I am doing wrong here? import numpy as np a = np.array([1,2,3,4,5],dtype=int) b = np.array(['a','b','c','d','e'],dtype='|S1') np.savetxt('test.txt',zip(a,b),fmt="%i %s") The output is: Traceback (most recent call last): File "loadtxt.py", line 6, in <module> ...
python numpy savetxt
Can someone indicate what I am doing wrong here? import numpy as np a = np.array([1,2,3,4,5],dtype=int) b = np.array(['a','b','c','d','e'],dtype='|S1') np.savetxt('test.txt',zip(a,b),fmt="%i %s") The output is: Traceback (most recent call last): File "loadtxt.py", line 6, in <module> np.savetxt('test.txt',zip(...
[ "You need to construct you array differently:\nz = np.array(zip([1,2,3,4,5], ['a','b','c','d','e']), dtype=[('int', int), ('str', '|S1')])\nnp.savetxt('test.txt', z, fmt='%i %s')\n\nwhen you're passing a sequence, savetext performs asarray(sequence) call and resulting array is of type |S4, that is all elements are ...
[ 12, 4, 1 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0001544948_numpy_python.txt
Q: Is there a free python library for phone calling? I'm writting a small python script notify me when certain condition met. I used smtplib which does the emailing for me, but I also want the script to call my cell phone as well. I can't find a free library for phone callings. Does anyone know any? A: Make the cal...
Is there a free python library for phone calling?
I'm writting a small python script notify me when certain condition met. I used smtplib which does the emailing for me, but I also want the script to call my cell phone as well. I can't find a free library for phone callings. Does anyone know any?
[ "Make the calls using Skype, and use the Skype4Py API.\nIf you want other suggestions, please specify how you want to make the call (modem? Some software bridge? What?).\nAlso, might I suggest that you send an SMS instead of placing a call? You can do that via Skype too, btw.\n", "Twilio can make calls through th...
[ 8, 4, 1 ]
[]
[]
[ "phone_call", "python" ]
stackoverflow_0001544550_phone_call_python.txt
Q: How to apply Loop to working Python Selenium Script? I'm trying to figure out how to apply a for-loop to this script and I'm having a lot of trouble. I want to iterate through a list of subdomains which are stored in csv format (ie: one column with 20 subdomains) and print the html for each. They all have the sa...
How to apply Loop to working Python Selenium Script?
I'm trying to figure out how to apply a for-loop to this script and I'm having a lot of trouble. I want to iterate through a list of subdomains which are stored in csv format (ie: one column with 20 subdomains) and print the html for each. They all have the same SourceDomain. Thanks! #Python 2.6 from selenium import...
[ "#Python 2.6\nfrom selenium import selenium\nimport unittest, time, re, csv, logging\n\nclass Untitled(unittest.TestCase):\n def setUp(self):\n self.verificationErrors = []\n self.selenium = selenium(\"localhost\", 4444, \"*firefox\", \"http://www.SourceDomain.com\")\n self.selenium.start()\...
[ 3 ]
[]
[]
[ "csv", "list", "loops", "python", "selenium" ]
stackoverflow_0001545602_csv_list_loops_python_selenium.txt
Q: Python mechanize doesn't click a button check the following script: from mechanize import Browser br = Browser() page = br.open('http://scottishladiespool.com/register.php') br.select_form(nr = 5) r = br.click(type = "submit", nr = 0) print r.data #prints username=&password1=&password2=&email=&user_hide_email=1...
Python mechanize doesn't click a button
check the following script: from mechanize import Browser br = Browser() page = br.open('http://scottishladiespool.com/register.php') br.select_form(nr = 5) r = br.click(type = "submit", nr = 0) print r.data #prints username=&password1=&password2=&email=&user_hide_email=1&captcha_code=&user_msn=&user_yahoo=&user_web...
[ "There is a disabled=disabled attribute on the register button. This prevents the user from clicking and presumably mechanize respects the disabled attribute as well.\nYou'll need to change the source code of that button. Enabling the control means completely removing the disabled=disabled text. \n" ]
[ 2 ]
[]
[]
[ "clientform", "mechanize", "python" ]
stackoverflow_0001545698_clientform_mechanize_python.txt
Q: Is there a version of os.getcwd() that doesn't dereference symlinks? Possible Duplicate: How to get/set logical directory path in python I have a Python script that I run from a symlinked directory, and I call os.getcwd() in it, expecting to get the symlinked path I ran it from. Instead it gives me the "real" pa...
Is there a version of os.getcwd() that doesn't dereference symlinks?
Possible Duplicate: How to get/set logical directory path in python I have a Python script that I run from a symlinked directory, and I call os.getcwd() in it, expecting to get the symlinked path I ran it from. Instead it gives me the "real" path, and in this case that's not helpful. I need it to actually give me th...
[ "Workaround: os.getenv('PWD')\n", "In general this is not possible. os.getcwd() calls getcwd(3), and according to POSIX.1-2008 (IEEE Std 1003.1-2008):\n\nThe pathname shall contain no components that are dot or dot-dot, or are symbolic links.\n\nos.getenv['PWD'] is shell-dependent and will not work for example wi...
[ 17, 13 ]
[]
[]
[ "path", "python", "symlink" ]
stackoverflow_0001542803_path_python_symlink.txt
Q: How do I replace all punctuation in my string with "" in Python? If my string was: Business -- way's I'd like to turn this into: Business ways ie. replace NON abc/123 into "" A: Simple regular expression: import re >>> s = "Business -- way's" >>> s = re.sub(r'[^\w\s]', '', s) >>> s "Business ways" A: Or,...
How do I replace all punctuation in my string with "" in Python?
If my string was: Business -- way's I'd like to turn this into: Business ways ie. replace NON abc/123 into ""
[ "Simple regular expression:\nimport re\n\n>>> s = \"Business -- way's\"\n>>> s = re.sub(r'[^\\w\\s]', '', s)\n>>> s\n\"Business ways\"\n\n", "Or, if you don't want to use a regular expression for some reason:\n''.join([x for x in foo if x.isalpha() or x.isspace()])\n\n" ]
[ 16, 6 ]
[ "(regular expression) replace\n[[:punct:]]\n\nwith '' (if Python supports that).\n[] is a character class, [::] is posix class syntax. [:punct:] is punctuation, so the character class for all punctuation marks would be [[:punct:]]\nAn alternate way of the same thing is \\p and friends:\n\\p{IsPunct}\nSee just belo...
[ -3 ]
[ "python", "regex" ]
stackoverflow_0001545655_python_regex.txt
Q: How to replace the quote " and hyphen character in a string with nothing in Python? I'd like to replace " and - with "" nothing! make it disappear. s = re.sub(r'[^\w\s]', '', s) this makes all punctuation disappear, but I just want those 2 characters. Thanks. A: I'm curious as to why you are using a regular expr...
How to replace the quote " and hyphen character in a string with nothing in Python?
I'd like to replace " and - with "" nothing! make it disappear. s = re.sub(r'[^\w\s]', '', s) this makes all punctuation disappear, but I just want those 2 characters. Thanks.
[ "I'm curious as to why you are using a regular expression for this simple string replacement. The only advantage that I can see is that you can do it in one line of code instead of two, but I personally think that a replacement method is clearer than a regex for something like this.\nThe string object has a replace...
[ 6, 2, 2, 1, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0001545878_python_regex.txt
Q: web scraping a problem site I'm trying to scrape some information from a web site, but am having trouble reading the relevant pages. The pages seem to first send a basic setup, then more detailed info. My download attempts only seem to capture the basic setup. I've tried urllib and mechanize so far. Firefox and...
web scraping a problem site
I'm trying to scrape some information from a web site, but am having trouble reading the relevant pages. The pages seem to first send a basic setup, then more detailed info. My download attempts only seem to capture the basic setup. I've tried urllib and mechanize so far. Firefox and Chrome have no trouble displayin...
[ "The page uses JavaScript to load the data. Firefox and Chrome are only working because you have JavaScript enabled - try disabling it and you'll get a mostly empty page.\nPython isn't going to be able to do this by itself - your best compromise would be to control a real browser (Internet Explorer is easiest, if ...
[ 2, 1, 0, 0 ]
[]
[]
[ "python", "screen_scraping" ]
stackoverflow_0001546089_python_screen_scraping.txt