content
stringlengths
85
101k
title
stringlengths
0
150
question
stringlengths
15
48k
answers
list
answers_scores
list
non_answers
list
non_answers_scores
list
tags
list
name
stringlengths
35
137
Q: Python framework for SOAP web services I need an advice. What python framework I can use to develop a SOAP web service? I know about SOAPpy and ZSI but that libraries aren't under active development. Is there something better? Thanks. A: I've used SOAPpy before and wouldn't recommend it unless you need to highly customize your web service to get it to interface with other non-standard SOAP implementations. I haven't used ZSI, but I understand that they tried to incorporate some of SOAPpy's features into ZSI. You might try looking at soaplib for creating a SOAP web service. I've heard good things, but haven't used it myself yet. A: If library is not under active development, then there are two options: it was abandoned, it has no errors anymore. Why are you looking something else? Did you test these two? A: I've used suds successfully for a project where I had tried and failed to use SOAPpy. http://sourceforge.net/projects/python-suds/
Python framework for SOAP web services
I need an advice. What python framework I can use to develop a SOAP web service? I know about SOAPpy and ZSI but that libraries aren't under active development. Is there something better? Thanks.
[ "I've used SOAPpy before and wouldn't recommend it unless you need to highly customize your web service to get it to interface with other non-standard SOAP implementations.\nI haven't used ZSI, but I understand that they tried to incorporate some of SOAPpy's features into ZSI.\nYou might try looking at soaplib for ...
[ 1, 0, 0 ]
[]
[]
[ "python", "soap" ]
stackoverflow_0003195437_python_soap.txt
Q: Find n greatest numbers in a sparse matrix I am using sparse matrices as a mean of compressing data, with loss of course, what I do is I create a sparse dictionary from all the values greater than a specified treshold. I'd want my compressed data size to be a variable which my user can choose. My problem is, I have a sparse matrix with alot of near-zero values, and what I must do is choose a treshold so that my sparse dictionary is of a specific size (or eventually that the reconstruction error is of a specific rate) Here's how I create my dictionary (taken from stackoverflow I think >.< ): n = abs(smat) > treshold #smat is flattened(1D) i = mega_range[n] #mega range is numpy.arange(smat.shape[0]) v = smat[n] sparse_dict = dict(izip(i,v)) How can I find treshold so that it is equal to the nth greatest value of my array (smat)? A: scipy.stats.scoreatpercentile(arr,per) returns the value at a given percentile: import scipy.stats as ss print(ss.scoreatpercentile([1, 4, 2, 3], 75)) # 3.25 The value is interpolated if the desired percentile lies between two points in arr. So if you set per=(len(smat)-n)/len(smat) then threshold = ss.scoreatpercentile(abs(smat), per) should give you (close to) the nth greatest value of the array smat.
Find n greatest numbers in a sparse matrix
I am using sparse matrices as a mean of compressing data, with loss of course, what I do is I create a sparse dictionary from all the values greater than a specified treshold. I'd want my compressed data size to be a variable which my user can choose. My problem is, I have a sparse matrix with alot of near-zero values, and what I must do is choose a treshold so that my sparse dictionary is of a specific size (or eventually that the reconstruction error is of a specific rate) Here's how I create my dictionary (taken from stackoverflow I think >.< ): n = abs(smat) > treshold #smat is flattened(1D) i = mega_range[n] #mega range is numpy.arange(smat.shape[0]) v = smat[n] sparse_dict = dict(izip(i,v)) How can I find treshold so that it is equal to the nth greatest value of my array (smat)?
[ "scipy.stats.scoreatpercentile(arr,per) returns the value at a given percentile:\nimport scipy.stats as ss\nprint(ss.scoreatpercentile([1, 4, 2, 3], 75))\n# 3.25\n\nThe value is interpolated if the desired percentile lies between two points in arr.\nSo if you set per=(len(smat)-n)/len(smat) then \nthreshold = ss.sc...
[ 2 ]
[]
[]
[ "numpy", "python", "sparse_matrix" ]
stackoverflow_0003195781_numpy_python_sparse_matrix.txt
Q: Need help sorting list of objects by key I am unable to get this code to sort a list of objects using either .sort() or sorted(). What am I missing here? P.S. My solution.distance() method could use some cosmetic surgery too if anyone has any suggestions. Thanks! import random import math POPULATION_SIZE = 100 data = [[1, 565.0, 575.0], [2, 25.0, 185.0], [3, 345.0, 750.0], [4, 945.0, 685.0], [5, 845.0, 655.0], [6, 880.0, 660.0], [7, 25.0, 230.0], [8, 525.0, 1000.0], [9, 580.0, 1175.0], [10, 650.0, 1130.0] ] class Solution(): def __init__(self): self.dna = [] self.randomize() def randomize(self): temp = data[:] while len(temp) > 0: self.dna.append( temp.pop( random.randint( 0,len(temp)-1 ) ) ) def distance(self): total = 0 #There has to be a better way to access two adjacent elements. for i, points in enumerate(self.dna): if i < (len(self.dna)-1): total += math.sqrt( (points[1]-self.dna[i+1][1])**2 + (points[2]-self.dna[i+1][2])**2 ) else: total += math.sqrt( (points[1]-self.dna[0][1])**2 + (points[2]-self.dna[0][2])**2 ) return int(total) class Population(): def __init__(self): self.solutions = [] self.generation = 0 #Populate with solutions self.solutions = [Solution() for i in range(POPULATION_SIZE)] def __str__(self): result = '' #This is the part that is not returning sorted results. I tried sorted() too. self.solutions.sort(key=lambda solution: solution.distance, reverse=True) for solution in self.solutions: result += 'ID: %s - Distance: %s\n' % ( id(solution), solution.distance() ) return result if __name__ == '__main__': p = Population() print p A: Change key=lambda solution: solution.distance to key=lambda solution: solution.distance() (The parentheses are needed to call the function.) Alternatively, you could make the distance method a property: @property def distance(self): .... In this case, change all occurances of solution.distance() to solution.distance. I think this alternate solution is a little bit nicer, since it removes two characters of clutter (the parens) every time you wish to talk about the distance. PS. key=lambda solution: solution.distance was returning the bound method solution.distance for each solution in self.solutions. Since the same object was being returned as the key for each solution, no desired ordering occurred. A: Here's an attempt at cleaning up your class, using functional programming techniques: import random class Solution(): def __init__(self): self.dna = [] self.randomize() def randomize(self): self.dna = data random.shuffle(self.dna) def distance(self): # Return the distance between two points. def point_distance((p1, p2)): return math.sqrt((p1[1]-p2[1])**2) + (p1[2]-p2[2])**2) # sums the distances between consecutive points. # zip pairs consecutive points together, wrapping around at end. return int(sum(map(point_distance, zip(self.dna, self.dna[1:]+self.dna[0:1]))) This is untested, but should be close to working. Also, a suggestion would be to use a class instead of a 3-element list for data. It will make your code much clearer to read: def point_distance((p1, p2)): return math.sqrt((p1.x-p2.x)**2) + (p1.y-p2.y)**2) A: Here's a better way to write the loop in distance(): put the following function definition, taken from the itertools documentation, in your code: from itertools import izip, tee def pairwise(iterable): a, b = tee(iterable) next(b, None) return izip(a, b) Then you can write distance to take advantage of Python's efficient iterator manipulation routines, like so: from itertools import chain, islice def distance(self): all_pairs = islice(pairwise(chain(self.dna, self.dna)), 0, len(self.dna)) return sum(math.sqrt((p[1]-q[1])**2 + (p[2]-q[2])**2) for p,q in all_pairs) This should be reasonably efficient even if the dna array is very long.
Need help sorting list of objects by key
I am unable to get this code to sort a list of objects using either .sort() or sorted(). What am I missing here? P.S. My solution.distance() method could use some cosmetic surgery too if anyone has any suggestions. Thanks! import random import math POPULATION_SIZE = 100 data = [[1, 565.0, 575.0], [2, 25.0, 185.0], [3, 345.0, 750.0], [4, 945.0, 685.0], [5, 845.0, 655.0], [6, 880.0, 660.0], [7, 25.0, 230.0], [8, 525.0, 1000.0], [9, 580.0, 1175.0], [10, 650.0, 1130.0] ] class Solution(): def __init__(self): self.dna = [] self.randomize() def randomize(self): temp = data[:] while len(temp) > 0: self.dna.append( temp.pop( random.randint( 0,len(temp)-1 ) ) ) def distance(self): total = 0 #There has to be a better way to access two adjacent elements. for i, points in enumerate(self.dna): if i < (len(self.dna)-1): total += math.sqrt( (points[1]-self.dna[i+1][1])**2 + (points[2]-self.dna[i+1][2])**2 ) else: total += math.sqrt( (points[1]-self.dna[0][1])**2 + (points[2]-self.dna[0][2])**2 ) return int(total) class Population(): def __init__(self): self.solutions = [] self.generation = 0 #Populate with solutions self.solutions = [Solution() for i in range(POPULATION_SIZE)] def __str__(self): result = '' #This is the part that is not returning sorted results. I tried sorted() too. self.solutions.sort(key=lambda solution: solution.distance, reverse=True) for solution in self.solutions: result += 'ID: %s - Distance: %s\n' % ( id(solution), solution.distance() ) return result if __name__ == '__main__': p = Population() print p
[ "Change \nkey=lambda solution: solution.distance\n\nto\nkey=lambda solution: solution.distance()\n\n(The parentheses are needed to call the function.)\nAlternatively, you could make the distance method a property:\n @property\n def distance(self): \n ....\n\nIn this case, change all occurances of solution.di...
[ 3, 1, 1 ]
[]
[]
[ "genetic_algorithm", "key", "list", "python", "sorting" ]
stackoverflow_0003196112_genetic_algorithm_key_list_python_sorting.txt
Q: Using subprocess to find out when a process ends I wish to sequentially run some c scripts that fork their own processes (in a new command line window) and give the "Press any key to continue..." when they are completed. Technically, it is a special compiler. It pops up with acommand line window and tells me whether the compile was successful or not. But that command line window forks new processes to compile, which are making this return 0 before it should.. My first attempt at this was process = subprocess.Popen(cmd) process.wait() while iterating over each file. Unfortunately, this does not wait for the "Press any key to continue..." and blows up in my face. It seems that the wait() call is passed when an internal process is completed (which I have no access to). How can I, instead, wait for "Press any key to continue..."? It's also printing some other information before the press any key to continue line.. Currently, this is what my code is: process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stdin=subprocess.PIPE) completed = False while not completed: if process.poll() is not None: completed = True print "communicating" process.communicate("k") print "communicated" A: You can use subprocess.poll to check the status without blocking, and subprocess.communicate to send information to the subprocess.
Using subprocess to find out when a process ends
I wish to sequentially run some c scripts that fork their own processes (in a new command line window) and give the "Press any key to continue..." when they are completed. Technically, it is a special compiler. It pops up with acommand line window and tells me whether the compile was successful or not. But that command line window forks new processes to compile, which are making this return 0 before it should.. My first attempt at this was process = subprocess.Popen(cmd) process.wait() while iterating over each file. Unfortunately, this does not wait for the "Press any key to continue..." and blows up in my face. It seems that the wait() call is passed when an internal process is completed (which I have no access to). How can I, instead, wait for "Press any key to continue..."? It's also printing some other information before the press any key to continue line.. Currently, this is what my code is: process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stdin=subprocess.PIPE) completed = False while not completed: if process.poll() is not None: completed = True print "communicating" process.communicate("k") print "communicated"
[ "You can use subprocess.poll to check the status without blocking, and subprocess.communicate to send information to the subprocess. \n" ]
[ 2 ]
[]
[]
[ "build_automation", "fork", "process", "python", "windows" ]
stackoverflow_0003196546_build_automation_fork_process_python_windows.txt
Q: Can you pass multiple paths to the Django runserver --pythonpath directive? For each of my projects I create an apps directory that holds all the apps I need. Satchmo also has an apps directory. Can I do something like python manage.py runserver --pythonpath=/path/to/my/apps /path/to/satchmo/apps? Is there some separator that it can take? A: There's no --pythonpath option to runserver. You either want to add it to your .bashrc file or in your settings.py file add something like the following at the top: import os,sys PROJECT_ROOT = os.path.realpath(os.path.dirname(__file__)) sys.path.append(PROJECT_ROOT, 'to', 'my', 'apps') sys.path.append(os.path.join('path', 'to', 'satchmo', 'apps'))
Can you pass multiple paths to the Django runserver --pythonpath directive?
For each of my projects I create an apps directory that holds all the apps I need. Satchmo also has an apps directory. Can I do something like python manage.py runserver --pythonpath=/path/to/my/apps /path/to/satchmo/apps? Is there some separator that it can take?
[ "There's no --pythonpath option to runserver. You either want to add it to your .bashrc file or in your settings.py file add something like the following at the top:\nimport os,sys\nPROJECT_ROOT = os.path.realpath(os.path.dirname(__file__))\nsys.path.append(PROJECT_ROOT, 'to', 'my', 'apps')\nsys.path.append(os.pat...
[ 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003196510_django_python.txt
Q: How do I get my Python date in the format that I want? I'm reading a date from an Excel cell in Python (using .Value on the cell)... the result that I get is: 07/06/10 00:00:00 I thought this was a string, and so went about trying to figure out how to convert this to the format I need ("yyyyMMdd", or "20100706" in this example). However, after some playing around I realized that it is not being pulled as a string... Running type() on it returns <type 'time'> . I then assumed that it was a Python time object, and tried using strftime on it to convert it to a string... but that didn't work either. It doesn't recognize the strftime method on the value. Any idea on how to parse this properly and get the format I want? What am I doing wrong? (And if this clearly contains a date as well as a time, why is Python automatically considering it a time object?) A: You can convert it to a time object like this: import time time.strptime(str(thetime), '%m/%d/%y %H:%M:%S') And then you should be able to manipulate it to your hearts content. HTH A: Have you tried str(time)? That should give it to you in a string and then you can play around with the formatting all you like.
How do I get my Python date in the format that I want?
I'm reading a date from an Excel cell in Python (using .Value on the cell)... the result that I get is: 07/06/10 00:00:00 I thought this was a string, and so went about trying to figure out how to convert this to the format I need ("yyyyMMdd", or "20100706" in this example). However, after some playing around I realized that it is not being pulled as a string... Running type() on it returns <type 'time'> . I then assumed that it was a Python time object, and tried using strftime on it to convert it to a string... but that didn't work either. It doesn't recognize the strftime method on the value. Any idea on how to parse this properly and get the format I want? What am I doing wrong? (And if this clearly contains a date as well as a time, why is Python automatically considering it a time object?)
[ "You can convert it to a time object like this:\nimport time\ntime.strptime(str(thetime), '%m/%d/%y %H:%M:%S')\n\nAnd then you should be able to manipulate it to your hearts content.\nHTH\n", "Have you tried str(time)? That should give it to you in a string and then you can play around with the formatting all you...
[ 4, 2 ]
[]
[]
[ "date_formatting", "date_parsing", "python", "time" ]
stackoverflow_0003196592_date_formatting_date_parsing_python_time.txt
Q: Regular expression not matching what I think it should In python, I'm compiling a regular expression pattern like so: rule_remark_pattern = re.compile('access-list shc-[(in)(out)] [(remark)(extended)].*') I would expect it to match any of the following lines: access-list shc-in remark C883101 Permit http from UPHC outside to Printers inside access-list shc-in extended permit tcp object-group UPHC-Group-Outside object-group PRINTER-Group-Inside object-group http-https access-list shc-out remark C890264 - Permit (UDP 123) from UPHC-Group-Inside to metronome.usc.edu access-list shc-out extended permit udp object-group UPHC-Group-Inside host 68.181.195.12 eq ntp Unfortunately, it doesn't match any of them. However, if I write the regular expression as: rule_remark_pattern = re.compile('access-list shc-in [(remark)(extended)].*') It matches the first 2 just fine. Similarly, if I write: rule_remark_pattern = re.compile('access-list shc-out [(remark)(extended)].*') It matches the last 2. Anybody know what's going on here? A: My regex-fu is not Python-based, but assuming it is anything like standard, I think you are misunderstanding the use of '[' and ']'. They represent a character class and it seems like you need an alternation. Try replacing your "[(word1)(word2)]" constructs with "(word1|word2)". EDIT: Just checked the Python docs (here: http://docs.python.org/library/re.html) and I don't see any relevant differences between Python regexen and what I'm used to (ie nothing that should affect the accuracy of this answer.) A: That's mainly because you completely mis-understood how "defining alternatives" works in regular expressions: access-list shc-(in|out) (remark|extended).* Your attempt creates character classes. Every character in a character class stands on its own, and the class itself really only matches a single character from the allowed list. So your try: [(in)(out)] really is the same as [intou(())] which actually is the same as [intou()] because repeated characters in a character class are ignored.
Regular expression not matching what I think it should
In python, I'm compiling a regular expression pattern like so: rule_remark_pattern = re.compile('access-list shc-[(in)(out)] [(remark)(extended)].*') I would expect it to match any of the following lines: access-list shc-in remark C883101 Permit http from UPHC outside to Printers inside access-list shc-in extended permit tcp object-group UPHC-Group-Outside object-group PRINTER-Group-Inside object-group http-https access-list shc-out remark C890264 - Permit (UDP 123) from UPHC-Group-Inside to metronome.usc.edu access-list shc-out extended permit udp object-group UPHC-Group-Inside host 68.181.195.12 eq ntp Unfortunately, it doesn't match any of them. However, if I write the regular expression as: rule_remark_pattern = re.compile('access-list shc-in [(remark)(extended)].*') It matches the first 2 just fine. Similarly, if I write: rule_remark_pattern = re.compile('access-list shc-out [(remark)(extended)].*') It matches the last 2. Anybody know what's going on here?
[ "My regex-fu is not Python-based, but assuming it is anything like standard, I think you are misunderstanding the use of '[' and ']'. They represent a character class and it seems like you need an alternation.\nTry replacing your \"[(word1)(word2)]\" constructs with \"(word1|word2)\".\nEDIT: Just checked the Python...
[ 3, 2 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0003197013_python_regex.txt
Q: Dilemma: Should I learn Seaside or a Python framework? I know it's kinda subjective but, if you were to put yourself in my shoes which would you invest the time in learning? I want to write a web app which deals securely with relatively modest amounts of peoples private data, a few thousand records of a few Kb each but stuff that needs to be kept safe, addresses, phone numbers etc. I've done several web projects in PHP/MYSQL and have decided, handy though it is I really don't like PHP and don't want to do another large project in it... As such I figure I'd best learn something new and so I am considering 2 options (although I'll happily entertain others if you have suggestions). I'm having terrible trouble deciding though. They both look quite involved so rather than just jump in and potentially waste days getting up to speed enough on both of them to make an informed choice I thought I'd come here and canvas some opinion. So the two options I'm considering are... One of the PYTHON Web frameworks - TurboGears seems well regarded? Advantage: Of all the languages I ever tried Python is by far and away my favorite. There's loads of frameworks to choose from and I have done quite a lot of non web python coding over the last few years. Disadvantage: There's loads to choose from so it's hard to pick! Need to run single server process? or mod_python? which I don't like the sound of. What I do like is the notion of process separation and compartmentalization, i.e. if one users account is compromised it gives an attacker no leverage against the rest of the system. I'm not clear to what extent a python solution would handle that. Writing it as a SEASIDE app Which I guess runs on a squeak app server? Adv: From what I've heard it would permit good compartmentalization of users as each would have their own little private VM independent of all the systems other users which sounds wonderful from a security, scaling and redundancy standpoint. Dis: I've not done any Smalltalk since Uni 15 years back and I never dug too deep into it then. I don't see much entry level help for seaside or that many projects using it. I suspect setting a server up to run it is hard for the same reason i.e. not because it's inherently hard but just cause there will be less help online and a presumption you are already rather au fait with Sqeak/Smalltalk. So, what do people think? Would I be able to efficiently get the kind of strong separation and compartmentalization I'm after with a Python framework? Is Seaside as good as I think in terms of insulating users from each other? Might I be better off, security wise, sticking to the languages I'm most familiar with so I don't make any n00b mistakes or will Seaside be worth worth scaling the learning curve and prove more secure, comprehensible and maintainable in the long run? At the end of the day it's not a life or death decision and I can always bail if I start with one and then hate it so pls nobody get all holy language war and start flaming anyone! ;-) Cheers for any replies this gets, Roger :) A: Forget about mod_python, there is WSGI. I'd recommend Django. It runs on any WSGI server, there are a lot to choose from. There is mod_wsgi for Apache, wsgiref - reference implementation included in Python and many more. Also Google App Engine is WSGI, and includes Django. Django is very popular and it's community is rapidly growing. A: Disclaimer: I really don't like PHP, Python is nice, but doesn't come close to Smalltalk in my book. But I am a biased Smalltalker. Some answers about Seaside/Squeak: Q: Which I guess runs on a squeak app server? Seaside runs in several different Smalltalks (VW, Gemstone, Squeak etc). The term "app server" is not really used in Smalltalk country. :) Q: From what I've heard it would permit good compartmentalization of users as each would have their own little private VM independent of all the systems other users which sounds wonderful from a security, scaling and redundancy standpoint. Yes, each user has its own WASession and all UI components the user sees are instances living on the server side in that session. So sharing of state between sessions is something you must do explicitly, typically through a db. Q: I've not done any Smalltalk since Uni 15 years back and I never dug too deep into it then. I don't see much entry level help for seaside or that many projects using it. Smalltalk is easy to get going with and there is a whole free online book on Seaside. Q: I suspect setting a server up to run it is hard for the same reason i.e. not because it's inherently hard but just cause there will be less help online and a presumption you are already rather au fait with Sqeak/Smalltalk. No, not hard. :) In fact, quite trivial. Tons of help - Seaside ml, IRC on freenode, etc. Q: Is Seaside as good as I think in terms of insulating users from each other? I would say so. Q: Might I be better off, security wise, sticking to the languages I'm most familiar with so I don't make any n00b mistakes or will Seaside be worth worth scaling the learning curve and prove more secure, comprehensible and maintainable in the long run? The killer argument in favor of Seaside IMHO is the true component model. It really, really makes it wonderful for complex UIs and maintenance. If you are afraid of learning "something different" (but then you wouldn't even consider it in the first place I guess) then I would warn you. But if you are not afraid then you will probably love it. Also - Squeak (or VW) is a truly awesome development environment - debugging live Seaside sessions, changing code in the debugger and resuming etc etc. It rocks. A: I'd say take a look at Django. It's a Python framework with a ready-made authentication system that's independent of the hosting OS, which means that compromises are limited to the app that was compromised (barring some exploit against the web server hosting the Python process). A: I've been getting into seaside myself but in many ways it is very hard to get started, which has nothing to do with the smalltalk which can be picked up extremely quickly. The challenge is that you are really protected from writing html directly. I find in most frameworks when you get stuck on how to do something there is always a work around of solving it by using the template. You may later discover that this solution causes problems with clarity down the road and there is in fact a better solutions built into the framework but you were able to move on from that problem until you learned the right way to do it. Seaside doesn't have templates so you don't get that crutch. No problems have permanently stumped me but some have taken me longer to solve than I would have liked. The flip side of this is you end up learning the seaside methodology much quicker because you can't cheat. If you decide to go the seaside route don't be afraid to post to the seaside mailing list at squeakfoundation.org. I found it intimidating at first because you don't see a lot of beginner questions there due to the low traffic but people are willing to help beginners there. Also there are a handful of seaside developers who monitor stackoverflow regularly. Good luck. A: Have you taken a look at www.nagare.org ? A framework particularly for web apps rather than web sites. It is based around the Seaside concepts but you program in Python (nagare deploys a distribution of python called Stackless Python to get the continuations working). Like Seaside it will auto generate HTML, but additionally can use templates as required. It has been recently open sourced by http://www.net-ng.com/ who themselves have many years experience in delivering web apps/sites in quality web frameworks like zope and plone. I am researching it myself at the moment to see if it fits my needs, so can't tell you what I think of it in the wild. If you take a look, please give your feedback. A: While considering a Smalltalk web framework, look at Aida/Web as well. Aida has built-in security with user/group/role management and strong access control, which can help you a lot in your case. That way you can achieve safe enough separation of users at the user level in one image. But if you really want, you can separate them with running many images as well. But this brings increased maintenance and I'd think twice if it is worth. A: I'm toying with Seaside myself and found this tutorial to be invaluable in gaining insight into the capabilities of the framework. A: I think you've pretty much summed up the pros and cons. Seaside isn't that hard to set up (I've installed it twice for various projects) but using it will definitely affect how you work--in addition to re-learning the language you'll probably have to adjust lots of assumptions about your work flow. It also depends on two other factors If other people will eventually be maintaining it, you'll have better luck finding python programmers If you are doing a highly stateful site, Seaside is going to beat the pants off any other framework I've seen. A: There is now an online book on Seaside to complete the tutorial pointed out earlier.
Dilemma: Should I learn Seaside or a Python framework?
I know it's kinda subjective but, if you were to put yourself in my shoes which would you invest the time in learning? I want to write a web app which deals securely with relatively modest amounts of peoples private data, a few thousand records of a few Kb each but stuff that needs to be kept safe, addresses, phone numbers etc. I've done several web projects in PHP/MYSQL and have decided, handy though it is I really don't like PHP and don't want to do another large project in it... As such I figure I'd best learn something new and so I am considering 2 options (although I'll happily entertain others if you have suggestions). I'm having terrible trouble deciding though. They both look quite involved so rather than just jump in and potentially waste days getting up to speed enough on both of them to make an informed choice I thought I'd come here and canvas some opinion. So the two options I'm considering are... One of the PYTHON Web frameworks - TurboGears seems well regarded? Advantage: Of all the languages I ever tried Python is by far and away my favorite. There's loads of frameworks to choose from and I have done quite a lot of non web python coding over the last few years. Disadvantage: There's loads to choose from so it's hard to pick! Need to run single server process? or mod_python? which I don't like the sound of. What I do like is the notion of process separation and compartmentalization, i.e. if one users account is compromised it gives an attacker no leverage against the rest of the system. I'm not clear to what extent a python solution would handle that. Writing it as a SEASIDE app Which I guess runs on a squeak app server? Adv: From what I've heard it would permit good compartmentalization of users as each would have their own little private VM independent of all the systems other users which sounds wonderful from a security, scaling and redundancy standpoint. Dis: I've not done any Smalltalk since Uni 15 years back and I never dug too deep into it then. I don't see much entry level help for seaside or that many projects using it. I suspect setting a server up to run it is hard for the same reason i.e. not because it's inherently hard but just cause there will be less help online and a presumption you are already rather au fait with Sqeak/Smalltalk. So, what do people think? Would I be able to efficiently get the kind of strong separation and compartmentalization I'm after with a Python framework? Is Seaside as good as I think in terms of insulating users from each other? Might I be better off, security wise, sticking to the languages I'm most familiar with so I don't make any n00b mistakes or will Seaside be worth worth scaling the learning curve and prove more secure, comprehensible and maintainable in the long run? At the end of the day it's not a life or death decision and I can always bail if I start with one and then hate it so pls nobody get all holy language war and start flaming anyone! ;-) Cheers for any replies this gets, Roger :)
[ "Forget about mod_python, there is WSGI. \nI'd recommend Django. It runs on any WSGI server, there are a lot to choose from. There is mod_wsgi for Apache, wsgiref - reference implementation included in Python and many more. Also Google App Engine is WSGI, and includes Django.\nDjango is very popular and it's commun...
[ 10, 10, 8, 6, 5, 4, 3, 1, 1 ]
[]
[]
[ "frameworks", "python", "seaside" ]
stackoverflow_0000697866_frameworks_python_seaside.txt
Q: python - refresh with webbrowser module I need a code portion to refresh the current page. I get the controller object from webbrowser module and start my webpage. And at a certain point I want to refresh my page inside the python code. According to the documentation at http://docs.python.org/library/webbrowser.html, when I call the open() function of the controller object with the same url and with new = 0 it should not open a new tab. But it opens a new tab. (Tested in both Chrome and Firefox) Do you have any suggestions? Thanks in advance. A: I think there is no portable way to do such refresh. The codes for "new" are just hints and they aren't guaranteed. If you can, you could add a refresh into your webpage, but I don't know if you have access to the webpage you're accessing, but you can create a "webpage wrapper" which opens the page you want as an iframe or something like that and then refreshes it in a defined interval.
python - refresh with webbrowser module
I need a code portion to refresh the current page. I get the controller object from webbrowser module and start my webpage. And at a certain point I want to refresh my page inside the python code. According to the documentation at http://docs.python.org/library/webbrowser.html, when I call the open() function of the controller object with the same url and with new = 0 it should not open a new tab. But it opens a new tab. (Tested in both Chrome and Firefox) Do you have any suggestions? Thanks in advance.
[ "I think there is no portable way to do such refresh. The codes for \"new\" are just hints and they aren't guaranteed. If you can, you could add a refresh into your webpage, but I don't know if you have access to the webpage you're accessing, but you can create a \"webpage wrapper\" which opens the page you want as...
[ 0 ]
[]
[]
[ "browser", "python", "refresh" ]
stackoverflow_0003195815_browser_python_refresh.txt
Q: Twisted Web Proxy Help! I wrote a Twisted Python HTTP proxy, and keep getting the following Traceback after navigating to a page through the proxy. Traceback (most recent call last): File "C:\ZBrownTechnology\Web Lock\Proxy.py", line 57, in <module> reactor.run() File "C:\Python26\lib\site-packages\twisted\internet\base.py", line 1165, in run self.mainLoop() File "C:\Python26\lib\site-packages\twisted\internet\base.py", line 1177, in mainLoop self.doIteration(t) File "C:\Python26\lib\site-packages\twisted\internet\selectreactor.py", line 140, in doSelect _logrun(selectable, _drdw, selectable, method, dict) --- <exception caught here> --- File "C:\Python26\lib\site-packages\twisted\python\log.py", line 84, in callWithLogger return callWithContext({"system": lp}, func, *args, **kw) File "C:\Python26\lib\site-packages\twisted\python\log.py", line 69, in callWithContext return context.call({ILogContext: newCtx}, func, *args, **kw) File "C:\Python26\lib\site-packages\twisted\python\context.py", line 59, in ca llWithContext return self.currentContext().callWithContext(ctx, func, *args, **kw) File "C:\Python26\lib\site-packages\twisted\python\context.py", line 37, in callWithContext return func(*args,**kw) File "C:\Python26\lib\site-packages\twisted\internet\selectreactor.py", line 156, in _doReadOrWrite self._disconnectSelectable(selectable, why, method=="doRead") File "C:\Python26\lib\site-packages\twisted\internet\posixbase.py", line 250, in _disconnectSelectable selectable.readConnectionLost(f) File "C:\Python26\lib\site-packages\twisted\internet\tcp.py", line 508, in readConnectionLost self.connectionLost(reason) File "C:\Python26\lib\site-packages\twisted\internet\tcp.py", line 677, in connectionLost Connection.connectionLost(self, reason) File "C:\Python26\lib\site-packages\twisted\internet\tcp.py", line 519, in connectionLost protocol.connectionLost(reason) File "C:\Python26\lib\site-packages\twisted\web\http.py", line 489, in connectionLost self.handleResponseEnd() File "C:\Python26\lib\site-packages\twisted\web\proxy.py", line 88, in handleResponseEnd self.father.finish() File "C:\Python26\lib\site-packages\twisted\web\http.py", line 900, in finish "Request.finish called on a request after its connection was lost; " exceptions.RuntimeError: Request.finish called on a request after its connection was lost; use Request.notifyFinish to keep track of this. What does this mean? How do I fix it? Is it a module problem, or a problem in my code? I am on Windows XP using Python 2.6 A: This is a known bug in twisted.web.proxy. It's typically harmless. If it's causing problems for you, please consider contributing a patch to fix it!
Twisted Web Proxy Help!
I wrote a Twisted Python HTTP proxy, and keep getting the following Traceback after navigating to a page through the proxy. Traceback (most recent call last): File "C:\ZBrownTechnology\Web Lock\Proxy.py", line 57, in <module> reactor.run() File "C:\Python26\lib\site-packages\twisted\internet\base.py", line 1165, in run self.mainLoop() File "C:\Python26\lib\site-packages\twisted\internet\base.py", line 1177, in mainLoop self.doIteration(t) File "C:\Python26\lib\site-packages\twisted\internet\selectreactor.py", line 140, in doSelect _logrun(selectable, _drdw, selectable, method, dict) --- <exception caught here> --- File "C:\Python26\lib\site-packages\twisted\python\log.py", line 84, in callWithLogger return callWithContext({"system": lp}, func, *args, **kw) File "C:\Python26\lib\site-packages\twisted\python\log.py", line 69, in callWithContext return context.call({ILogContext: newCtx}, func, *args, **kw) File "C:\Python26\lib\site-packages\twisted\python\context.py", line 59, in ca llWithContext return self.currentContext().callWithContext(ctx, func, *args, **kw) File "C:\Python26\lib\site-packages\twisted\python\context.py", line 37, in callWithContext return func(*args,**kw) File "C:\Python26\lib\site-packages\twisted\internet\selectreactor.py", line 156, in _doReadOrWrite self._disconnectSelectable(selectable, why, method=="doRead") File "C:\Python26\lib\site-packages\twisted\internet\posixbase.py", line 250, in _disconnectSelectable selectable.readConnectionLost(f) File "C:\Python26\lib\site-packages\twisted\internet\tcp.py", line 508, in readConnectionLost self.connectionLost(reason) File "C:\Python26\lib\site-packages\twisted\internet\tcp.py", line 677, in connectionLost Connection.connectionLost(self, reason) File "C:\Python26\lib\site-packages\twisted\internet\tcp.py", line 519, in connectionLost protocol.connectionLost(reason) File "C:\Python26\lib\site-packages\twisted\web\http.py", line 489, in connectionLost self.handleResponseEnd() File "C:\Python26\lib\site-packages\twisted\web\proxy.py", line 88, in handleResponseEnd self.father.finish() File "C:\Python26\lib\site-packages\twisted\web\http.py", line 900, in finish "Request.finish called on a request after its connection was lost; " exceptions.RuntimeError: Request.finish called on a request after its connection was lost; use Request.notifyFinish to keep track of this. What does this mean? How do I fix it? Is it a module problem, or a problem in my code? I am on Windows XP using Python 2.6
[ "This is a known bug in twisted.web.proxy. It's typically harmless. If it's causing problems for you, please consider contributing a patch to fix it!\n" ]
[ 3 ]
[]
[]
[ "proxy", "python", "traceback", "twisted" ]
stackoverflow_0003196528_proxy_python_traceback_twisted.txt
Q: Python authentication I want to be able to authenticate to a website and then access some of the private pages in that site. I've looked at some examples and tutorials but I can't get it to work. For example, I want to access https://www.billmonk.com/home which is available only after authentication. Here's the code I'm using: url = 'https://www.billmonk.com/home' values = {'usercontact' : 'myemail@gmail.com', 'password' : 'somepass'} data = urllib.urlencode(values) req = urllib2.Request(url, data) cj = cookielib.CookieJar() opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) urllib2.install_opener(opener) response = opener.open(req) the_page = response.read() This doesn't seem to be working. I always get a page with a "You must be logged in to access this page" page. Am I missing something obvious? Thanks! A: Looking at the source of the BillMonk page, it looks like the login action is a POST to /sign_in (not /home as your code uses).
Python authentication
I want to be able to authenticate to a website and then access some of the private pages in that site. I've looked at some examples and tutorials but I can't get it to work. For example, I want to access https://www.billmonk.com/home which is available only after authentication. Here's the code I'm using: url = 'https://www.billmonk.com/home' values = {'usercontact' : 'myemail@gmail.com', 'password' : 'somepass'} data = urllib.urlencode(values) req = urllib2.Request(url, data) cj = cookielib.CookieJar() opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) urllib2.install_opener(opener) response = opener.open(req) the_page = response.read() This doesn't seem to be working. I always get a page with a "You must be logged in to access this page" page. Am I missing something obvious? Thanks!
[ "Looking at the source of the BillMonk page, it looks like the login action is a POST to /sign_in (not /home as your code uses).\n" ]
[ 1 ]
[]
[]
[ "authentication", "python" ]
stackoverflow_0003197171_authentication_python.txt
Q: How to use list comprehension to add an element to copies of a dictionary? given: template = {'a': 'b', 'c': 'd'} add = ['e', 'f'] k = 'z' I want to use list comprehension to generate [{'a': 'b', 'c': 'd', 'z': 'e'}, {'a': 'b', 'c': 'd', 'z': 'f'}] I know I can do this: out = [] for v in add: t = template.copy() t[k] = v out.append(t) but it is a little verbose and has no advantage over what I'm trying to replace. This slightly more general question on merging dictionaries is somewhat related but more or less says don't. A: [dict(template,z=value) for value in add] or (to use k): [dict(template,**{k:value}) for value in add]
How to use list comprehension to add an element to copies of a dictionary?
given: template = {'a': 'b', 'c': 'd'} add = ['e', 'f'] k = 'z' I want to use list comprehension to generate [{'a': 'b', 'c': 'd', 'z': 'e'}, {'a': 'b', 'c': 'd', 'z': 'f'}] I know I can do this: out = [] for v in add: t = template.copy() t[k] = v out.append(t) but it is a little verbose and has no advantage over what I'm trying to replace. This slightly more general question on merging dictionaries is somewhat related but more or less says don't.
[ "[dict(template,z=value) for value in add]\n\nor (to use k):\n[dict(template,**{k:value}) for value in add]\n\n" ]
[ 31 ]
[]
[]
[ "dictionary", "list_comprehension", "python" ]
stackoverflow_0003197342_dictionary_list_comprehension_python.txt
Q: Integrity Error in Sqlite Database I am trying to import large amounts of data into a sqlite DB through python 2.5. The data consists of strings, but there are multiple duplicates in the data. An example; addres,type_code, location 123,01,work 123,01,mall 132,49,home 132,33,home My issue is that when loading the data I get an Integrity error, address and type_code are not unique. This is true, in fact there will be thousands of times when these 2 rows are not unique. How am I able to enter this data into my database? A: your table probably has primary key set as addres + typ_code. If those three fields are indeed should be unique in that particular table then redefine primary key to include all three fields addres, type_code and location. That would fix the problem you facing.
Integrity Error in Sqlite Database
I am trying to import large amounts of data into a sqlite DB through python 2.5. The data consists of strings, but there are multiple duplicates in the data. An example; addres,type_code, location 123,01,work 123,01,mall 132,49,home 132,33,home My issue is that when loading the data I get an Integrity error, address and type_code are not unique. This is true, in fact there will be thousands of times when these 2 rows are not unique. How am I able to enter this data into my database?
[ "your table probably has primary key set as addres + typ_code. If those three fields are indeed should be unique in that particular table then redefine primary key to include all three fields addres, type_code and location. That would fix the problem you facing.\n" ]
[ 3 ]
[]
[]
[ "python", "sqlite" ]
stackoverflow_0003197578_python_sqlite.txt
Q: django views urllib2.py https error twilio api I'm looking to send an SMS with the Twilio api, but I'm getting the following error: "unknown url type: https" I've recompiled python with Openssl, so my code runs fine from the python interpretor, but whenever I try to run it in one of my django views I get this error. Here is my code from my view: def send_sms(request): recipient = '1234567890' account = twilio.Account(settings.TWILIO_ID, settings.TWILIO_TOKEN) params = { 'From': settings.TWILIO_NUM, 'To': recipient, 'Body': 'This is a test message.', } account.request('/%s/Accounts/%s/SMS/Messages' % (settings.TWILIO_API_VERSION, settings.TWILIO_ID), 'POST', params) Edit- More info (thanks for bringing that up Stefan) The project is hosted on dreamhost via Passenger wsgi. Django is using the same python install location and interp. I appreciate any insight anyone may have, thanks! A: Looks like it was just user error. My wsgi file was using a different interpreter but the paths were so similar I was just over looking it. Once I fixed that django was using the python version that I compiled with openssl and everything worked fine. Always check if the tv is plugged in before you take it apart. Thanks stefanw!
django views urllib2.py https error twilio api
I'm looking to send an SMS with the Twilio api, but I'm getting the following error: "unknown url type: https" I've recompiled python with Openssl, so my code runs fine from the python interpretor, but whenever I try to run it in one of my django views I get this error. Here is my code from my view: def send_sms(request): recipient = '1234567890' account = twilio.Account(settings.TWILIO_ID, settings.TWILIO_TOKEN) params = { 'From': settings.TWILIO_NUM, 'To': recipient, 'Body': 'This is a test message.', } account.request('/%s/Accounts/%s/SMS/Messages' % (settings.TWILIO_API_VERSION, settings.TWILIO_ID), 'POST', params) Edit- More info (thanks for bringing that up Stefan) The project is hosted on dreamhost via Passenger wsgi. Django is using the same python install location and interp. I appreciate any insight anyone may have, thanks!
[ "Looks like it was just user error. My wsgi file was using a different interpreter but the paths were so similar I was just over looking it. Once I fixed that django was using the python version that I compiled with openssl and everything worked fine.\nAlways check if the tv is plugged in before you take it apart. ...
[ 1 ]
[]
[]
[ "django", "https", "python", "twilio", "urllib2" ]
stackoverflow_0003169589_django_https_python_twilio_urllib2.txt
Q: Regular expression to search for a string1 that is never followed by string2 How to construct a regular expression search pattern to find string1 that is not followed by string2 (immediately or not)? For for instance, if string1="MAN" and string2="PN", example search results would be: "M": Not found "MA": Not found "MAN": Found "BLAH_MAN_BLEH": Found "MAN_PN": Not found "BLAH_MAN_BLEH_PN": Not found "BLAH_MAN_BLEH_PN_MAN": Not found Ideally, a one-linear search, instead of doing a second search for string2. PS: Language being used is Python A: It looks like you can use MAN(?!.*PN). This matches MAN and uses negative lookahead to make sure that it's not followed by PN (as seen on rubular.com). Given MAN_PN_MAN_BLEH, the above pattern will find the second MAN, since it's not followed by PN. If you want to validate the entire string and make sure that there's no MAN.*PN, then you can use something like ^(?!.*MAN.*PN).*MAN.*$ (as seen on rubular.com). References regular-expressios.info/Lookarounds Related questions How can I check if every substring of four zeros is followed by at least four ones using regular expressions? Non-regex option If the strings are to be matched literally, then you can also check for indices of substring occurrences. In Python, find and rfind return lowest and highest index of substring occurrences respectively. So to make sure that string1 occurs but never followed by string2, and both returns -1 if the string is not found, so it looks like you can just test for this condition: string.rfind(s, string2) < string.find(s, string1) This compares the leftmost occurrence of string1 and the rightmost occurrence of string2. If neither occurs, both are -1, and result is false If string1 occurs, but string2 doesn't, then result is true as expected If both occurs, then the rightmost string2 must be to the left of the leftmost string1 That is, no string1 is ever followed by string2 API links find rfind
Regular expression to search for a string1 that is never followed by string2
How to construct a regular expression search pattern to find string1 that is not followed by string2 (immediately or not)? For for instance, if string1="MAN" and string2="PN", example search results would be: "M": Not found "MA": Not found "MAN": Found "BLAH_MAN_BLEH": Found "MAN_PN": Not found "BLAH_MAN_BLEH_PN": Not found "BLAH_MAN_BLEH_PN_MAN": Not found Ideally, a one-linear search, instead of doing a second search for string2. PS: Language being used is Python
[ "It looks like you can use MAN(?!.*PN). This matches MAN and uses negative lookahead to make sure that it's not followed by PN (as seen on rubular.com).\nGiven MAN_PN_MAN_BLEH, the above pattern will find the second MAN, since it's not followed by PN. If you want to validate the entire string and make sure that the...
[ 3 ]
[]
[]
[ "expression", "python", "regex" ]
stackoverflow_0003197765_expression_python_regex.txt
Q: Return an image to the browser in python, cgi-bin I'm trying to set up a python script in cgi-bin that simply returns a header with content-type: image/png and returns the image. I've tried opening the image and returning it with print f.read() but that isn't working. EDIT: the code I'm trying to use is: print "Content-type: image/png\n\n" with open("/home/user/tmp/image.png", "r") as f: print f.read() This is using apache on ubuntu server 10.04. When I load the page in chrome I get the broken image image, and when I load the page in firefox I get The image http://localhost/cgi-bin/test.py" cannot be displayed, because it contains errors. A: You may need to open the file as "rb" (in windows based environments it's usually the case. Simply printing may not work (as it adds '\n' and stuff), better just write it to sys.stdout. The statement print "Content-type: image/png\n\n" actually prints 3 newlines (as print automatically adds one "\n" in the end. This may break your PNG file. Try: sys.stdout.write( "Content-type: image/png\r\n\r\n" + file(filename,"rb").read() ) HTML responses require carriage-return, new-line A: Are you including the blank line after the header? If not, it's not the end of your headers! print 'Content-type: image/png' print print f.read()
Return an image to the browser in python, cgi-bin
I'm trying to set up a python script in cgi-bin that simply returns a header with content-type: image/png and returns the image. I've tried opening the image and returning it with print f.read() but that isn't working. EDIT: the code I'm trying to use is: print "Content-type: image/png\n\n" with open("/home/user/tmp/image.png", "r") as f: print f.read() This is using apache on ubuntu server 10.04. When I load the page in chrome I get the broken image image, and when I load the page in firefox I get The image http://localhost/cgi-bin/test.py" cannot be displayed, because it contains errors.
[ "\nYou may need to open the file as \"rb\" (in windows based environments it's usually the case.\nSimply printing may not work (as it adds '\\n' and stuff), better just write it to sys.stdout.\nThe statement print \"Content-type: image/png\\n\\n\" actually prints 3 newlines (as print automatically adds one \"\\n\" ...
[ 7, 0 ]
[]
[]
[ "apache2", "cgi_bin", "image", "python" ]
stackoverflow_0003198093_apache2_cgi_bin_image_python.txt
Q: does google-app-engine has "required_admin" method @required_admin def get(self): I want to use this method to make user must be admin. A: The standard route is to use login: admin in your app.yaml, but here's a decorator: def admin_required(handler_method): def check_admin(self, *args): if not users.is_current_user_admin(): self.redirect(users.create_login_url(self.request.uri)) return else: handler_method(self, *args) return check_admin
does google-app-engine has "required_admin" method
@required_admin def get(self): I want to use this method to make user must be admin.
[ "The standard route is to use login: admin in your app.yaml, but here's a decorator:\ndef admin_required(handler_method):\n def check_admin(self, *args):\n if not users.is_current_user_admin():\n self.redirect(users.create_login_url(self.request.uri))\n return\n else:\n handler_method(self, *a...
[ 4 ]
[]
[]
[ "admin", "google_app_engine", "python", "require" ]
stackoverflow_0003197894_admin_google_app_engine_python_require.txt
Q: How can I explode a tuple so that it can be passed as a parameter list? Let's say I have a method definition like this: def myMethod(a, b, c, d, e) Then, I have a variable and a tuple like this: myVariable = 1 myTuple = (2, 3, 4, 5) Is there a way I can pass explode the tuple so that I can pass its members as parameters? Something like this (although I know this won't work as the entire tuple is considered the second parameter): myMethod(myVariable, myTuple) I'd like to avoid referencing each tuple member individually if possible... A: You are looking for the argument unpacking operator *: myMethod(myVariable, *myTuple) A: From the Python documentation: The reverse situation occurs when the arguments are already in a list or tuple but need to be unpacked for a function call requiring separate positional arguments. For instance, the built-in range() function expects separate start and stop arguments. If they are not available separately, write the function call with the *-operator to unpack the arguments out of a list or tuple: >>> range(3, 6) # normal call with separate arguments [3, 4, 5] >>> args = [3, 6] >>> range(*args) # call with arguments unpacked from a list [3, 4, 5] In the same fashion, dictionaries can deliver keyword arguments with the **-operator: >>> def parrot(voltage, state='a stiff', action='voom'): ... print "-- This parrot wouldn't", action, ... print "if you put", voltage, "volts through it.", ... print "E's", state, "!" ... >>> d = {"voltage": "four million", "state": "bleedin' demised", "action": "VOOM"} >>> parrot(**d) -- This parrot wouldn't VOOM if you put four million volts through it. E's bleedin' demised !
How can I explode a tuple so that it can be passed as a parameter list?
Let's say I have a method definition like this: def myMethod(a, b, c, d, e) Then, I have a variable and a tuple like this: myVariable = 1 myTuple = (2, 3, 4, 5) Is there a way I can pass explode the tuple so that I can pass its members as parameters? Something like this (although I know this won't work as the entire tuple is considered the second parameter): myMethod(myVariable, myTuple) I'd like to avoid referencing each tuple member individually if possible...
[ "You are looking for the argument unpacking operator *:\nmyMethod(myVariable, *myTuple)\n\n", "From the Python documentation:\n\nThe reverse situation occurs when the\n arguments are already in a list or\n tuple but need to be unpacked for a\n function call requiring separate\n positional arguments. For insta...
[ 44, 7 ]
[]
[]
[ "iterable_unpacking", "parameters", "python", "tuples" ]
stackoverflow_0003198218_iterable_unpacking_parameters_python_tuples.txt
Q: Python socket server craps out after receiving data I'm currently dabbling in sockets. I've got a jquery script that uses a very small flash swf file to establish a true socket connection. As a server I'd like to use python. Everything works, but I can only send information to the server just once. I've tried 2 pieces of python code for the server. I guess since they both have the same problem the problem's not here. # TCP server example import socket server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_socket.bind(("", 2000)) server_socket.listen(5) print "TCPServer Waiting for client on port 2000" while 1: client_socket, address = server_socket.accept() print "I got a connection from ", address while 1: data = client_socket.recv(512) print "RECIEVED:" , data Or this one: import socket mySocket = socket.socket ( socket.AF_INET, socket.SOCK_STREAM ) mySocket.bind ( ( '', 2000 ) ) mySocket.listen ( 1 ) while True: channel, details = mySocket.accept() print 'We have opened a connection with', details print channel.recv ( 100 ) channel.close() On the client side I use http://devpro.it/xmlsocket/ Sending a piece of data is as simple as executing xmls.send('some text'); Which arrives, but after that it stops working. Does anyone know a solution? Or possibly a better javascript/swf combination I could use? A: I think you need to 'listen' again after you close the connection. Also, Sockets deliver data as per the tcp specifications. You're not guaranteed to get all of any data sent in one socket read. I see nothing to perform multiple reads and assemble a complete 'message' A: For communicating between flash and python, I use: http://pyamf.org/ You can either set up a socket server, or better, a small django application. Then you can have secure authentication, tokens, cookies, and strong typing if you want it.
Python socket server craps out after receiving data
I'm currently dabbling in sockets. I've got a jquery script that uses a very small flash swf file to establish a true socket connection. As a server I'd like to use python. Everything works, but I can only send information to the server just once. I've tried 2 pieces of python code for the server. I guess since they both have the same problem the problem's not here. # TCP server example import socket server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_socket.bind(("", 2000)) server_socket.listen(5) print "TCPServer Waiting for client on port 2000" while 1: client_socket, address = server_socket.accept() print "I got a connection from ", address while 1: data = client_socket.recv(512) print "RECIEVED:" , data Or this one: import socket mySocket = socket.socket ( socket.AF_INET, socket.SOCK_STREAM ) mySocket.bind ( ( '', 2000 ) ) mySocket.listen ( 1 ) while True: channel, details = mySocket.accept() print 'We have opened a connection with', details print channel.recv ( 100 ) channel.close() On the client side I use http://devpro.it/xmlsocket/ Sending a piece of data is as simple as executing xmls.send('some text'); Which arrives, but after that it stops working. Does anyone know a solution? Or possibly a better javascript/swf combination I could use?
[ "I think you need to 'listen' again after you close the connection.\nAlso, Sockets deliver data as per the tcp specifications. You're not guaranteed to get all of any data sent in one socket read. I see nothing to perform multiple reads and assemble a complete 'message'\n", "For communicating between flash and py...
[ 2, 1 ]
[]
[]
[ "flash", "javascript", "python", "sockets" ]
stackoverflow_0003198050_flash_javascript_python_sockets.txt
Q: Adding methods to a simple RPC server in a clean and separated way I created a simple RPC server to perform certain tasks common to our teams, but which are called from different networks. The server looks like this (I don't include error handling for brevity): from twisted.internet.protocol import Protocol, Factory from twisted.internet import reactor import json class MyProtocol(Protocol): def dataReceived(self, data): req = json.loads(data) # create a dictionary from JSON string method = getattr(self, req['method']) # get the method method(req['params']) # call the method def add(self, params): result = {} # initialize a dictionary to convert later to JSON result['result'] = sum(params) result['error'] = None result['id'] = 1 self.transport.write(json.dumps(result)) # return a JSON string self.transport.loseConnection() # close connection factory = Factory() factory.protocol = MyProtocol reactor.listenTCP(8080, factory) reactor.run() This is very simple: the server receives a JSON RPC request from the client, looks for the method, and calls the method passing the parameters. The method itself is the one returning the JSON RPC response. For the less familiar, a JSON RPC looks approximately like this: request: {"method":"my_method", "params":[1,2,3], "id":"my_id"} response: {"result":"my_result", "error":null, "id":"my_id"} The RPC server as I have it serves my current purposes very well (as you can imagine, my task is very simple). But I will need to continue adding methods as the complexity of the task increases. I don't want to open the main file and add yet another def method3(...) and, two weeks later, add def method4(...) and so forth; the code would grow too quickly and the maintenance would be harder and harder. So, my question is: how can I create an architecture that allows me to register methods into the Server. A bonus would be to have a separate folder holding one file per method, so that they can easily be shared and maintained. This "architecture" would also allow me to defer maintenance of some methods to someone else, regardless of their understanding of Twisted. I don't care if I need to restart the server every time a new method is registered, but an obvious plus would be if I don't have too :). Thanks. A: A bit of a largish order ;) but here's some initial steps for you (very heavily mocked-up, twisted specifics ommited in the examples): # your twisted imports... import json class MyProtocol(object): # Would be Protocol instead of object in real code def dataReceived(self, data): req = json.loads(data) # create a dictionary from JSON string modname, funcname = req['method'].split('.') m = __import__(modname) method = getattr(m, funcname) # get the method method(self, req['params']) # call the method Assuming you try it out as if we executed this: mp = MyProtocol() mp.dataReceived('{"method":"somemod.add", "params":[1,2,3]}') You wold have a module somemod.py in the same directory as the example with the following contents (mirroring your example method .add() above): import json def add(proto, params): result = {} # initialize a dictionary to convert later to JSON result['result'] = sum(params) result['error'] = None result['id'] = 1 proto.transport.write(json.dumps(result)) # return a JSON string proto.transport.loseConnection() # close connection This allows you to have one module per method served. The method(.. call above will always pass your MyProtocol instance to the serving callable. (If you really want instance methods, here's instructions on how to add methods using python: http://irrepupavel.com/documents/python/instancemethod/ ) You will need a lot of error handling added. For example you need a lot of error checking at the split() call on line 2 of dataReceived(). With this you can have separate files with one function in them for every method you need to support. By no means a complete example but it might get you going, since what your'e looking for is quite complex. For a more formal registering, I'd recommend a dict in MyProtocol with names of methods that you support, along the lines of: # in MyProtocol's __init__() method: self.methods = {} And a register method.. def register(self, name, callable): self.methods[name] = callable ..modify dataReceived().. def dataReceived(self, data): # ... modname, funcname = self.methods.get(req['method'], False) # ..continue along the lines of the dataReceived() method above Quick summary of a too long post: the __import__ function ( http://docs.python.org/library/functions.html ) will most certainly be a key part of your solution.
Adding methods to a simple RPC server in a clean and separated way
I created a simple RPC server to perform certain tasks common to our teams, but which are called from different networks. The server looks like this (I don't include error handling for brevity): from twisted.internet.protocol import Protocol, Factory from twisted.internet import reactor import json class MyProtocol(Protocol): def dataReceived(self, data): req = json.loads(data) # create a dictionary from JSON string method = getattr(self, req['method']) # get the method method(req['params']) # call the method def add(self, params): result = {} # initialize a dictionary to convert later to JSON result['result'] = sum(params) result['error'] = None result['id'] = 1 self.transport.write(json.dumps(result)) # return a JSON string self.transport.loseConnection() # close connection factory = Factory() factory.protocol = MyProtocol reactor.listenTCP(8080, factory) reactor.run() This is very simple: the server receives a JSON RPC request from the client, looks for the method, and calls the method passing the parameters. The method itself is the one returning the JSON RPC response. For the less familiar, a JSON RPC looks approximately like this: request: {"method":"my_method", "params":[1,2,3], "id":"my_id"} response: {"result":"my_result", "error":null, "id":"my_id"} The RPC server as I have it serves my current purposes very well (as you can imagine, my task is very simple). But I will need to continue adding methods as the complexity of the task increases. I don't want to open the main file and add yet another def method3(...) and, two weeks later, add def method4(...) and so forth; the code would grow too quickly and the maintenance would be harder and harder. So, my question is: how can I create an architecture that allows me to register methods into the Server. A bonus would be to have a separate folder holding one file per method, so that they can easily be shared and maintained. This "architecture" would also allow me to defer maintenance of some methods to someone else, regardless of their understanding of Twisted. I don't care if I need to restart the server every time a new method is registered, but an obvious plus would be if I don't have too :). Thanks.
[ "A bit of a largish order ;) but here's some initial steps for you (very heavily mocked-up, twisted specifics ommited in the examples):\n# your twisted imports...\nimport json\n\nclass MyProtocol(object): # Would be Protocol instead of object in real code\n\n def dataReceived(self, data):\n req = json.loa...
[ 1 ]
[]
[]
[ "architecture", "json_rpc", "network_protocols", "python", "twisted" ]
stackoverflow_0003197988_architecture_json_rpc_network_protocols_python_twisted.txt
Q: pylons file uploading - access 1st file Currently, I'm using request.params["filename"] to access uploaded files. In Pylons, what is the syntax to access a file if you don't know the filename, something like request.files[0]? A: Based on what this: http://pylonshq.com/docs/en/1.0/forms/#file-uploads page says, you could search through the params or request.POST looking for values of the type cgi.FieldStorage A: It's not the file name that's used as a key in request.params, it's the field name that was used in the HTML: <input type="file" name="fieldname">
pylons file uploading - access 1st file
Currently, I'm using request.params["filename"] to access uploaded files. In Pylons, what is the syntax to access a file if you don't know the filename, something like request.files[0]?
[ "Based on what this: http://pylonshq.com/docs/en/1.0/forms/#file-uploads page says, you could search through the params or request.POST looking for values of the type cgi.FieldStorage\n", "It's not the file name that's used as a key in request.params, it's the field name that was used in the HTML: <input type=\"f...
[ 1, 0 ]
[]
[]
[ "file_upload", "pylons", "python" ]
stackoverflow_0003073572_file_upload_pylons_python.txt
Q: Returning Database Blobs in TurboGears 2.x / FCGI / Lighttpd extremely slow I am running a TG2 App on lighttpd via flup/fastcgi. We are reading images (~30kb each) from BlobFields in a MySQL database and return those images with a custom mime type via a controller method. Caching these images on the hard disk makes no sense because they change with every request, the only reason we cache these in the DB is that creating these images is quite expensive and the data used to create the images is also present in plain text on the website. Now to the problem itself: When returning such an image, things get extremely slow. The code runs totally fine on paster itself with no visible delay, but as soon as its running via fcgi/lighttpd the described phenomenon happens. I profiled the method of my controller that returns my blob, and the entire method runs in a few miliseconds, but when "return" executes, the entire app hangs for roughly 10 seconds. We could not reproduce the same error with PHP on FCGI. This only seems to happen with Turbogears or Pylons. Here for your consideration the concerned piece of source code: @expose(content_type=CUSTOM_CONTENT_TYPE) def return_img(self, img_id): """ Return a DB persisted image when requested """ img = model.Images.by_id(img_id) #get image from DB response.headers['content-type'] = 'image/png' return img.data # this causes the app to hang for 10 seconds A: I've no clue, really, but seeing as there are no answers here, I'll try a wild guess. Perhaps response.headers['content-length'] = len(img.data) would help?
Returning Database Blobs in TurboGears 2.x / FCGI / Lighttpd extremely slow
I am running a TG2 App on lighttpd via flup/fastcgi. We are reading images (~30kb each) from BlobFields in a MySQL database and return those images with a custom mime type via a controller method. Caching these images on the hard disk makes no sense because they change with every request, the only reason we cache these in the DB is that creating these images is quite expensive and the data used to create the images is also present in plain text on the website. Now to the problem itself: When returning such an image, things get extremely slow. The code runs totally fine on paster itself with no visible delay, but as soon as its running via fcgi/lighttpd the described phenomenon happens. I profiled the method of my controller that returns my blob, and the entire method runs in a few miliseconds, but when "return" executes, the entire app hangs for roughly 10 seconds. We could not reproduce the same error with PHP on FCGI. This only seems to happen with Turbogears or Pylons. Here for your consideration the concerned piece of source code: @expose(content_type=CUSTOM_CONTENT_TYPE) def return_img(self, img_id): """ Return a DB persisted image when requested """ img = model.Images.by_id(img_id) #get image from DB response.headers['content-type'] = 'image/png' return img.data # this causes the app to hang for 10 seconds
[ "I've no clue, really, but seeing as there are no answers here, I'll try a wild guess.\nPerhaps\nresponse.headers['content-length'] = len(img.data)\n\nwould help?\n" ]
[ 0 ]
[]
[]
[ "fastcgi", "pylons", "python", "turbogears" ]
stackoverflow_0002911867_fastcgi_pylons_python_turbogears.txt
Q: How to display multiple images? I'm trying to get multiple image paths from my database in order to display them, but it currently doesn't work. Here's what i'm using: def get_image(self, userid, id): image = meta.Session.query(Image).filter_by(userid=userid) permanent_file = open(image[id].image_path, 'rb') if not os.path.exists(image.image_path): return 'No such file' data = permanent_file.read() permanent_file.close() response.content_type = guess_type(image.image_path)[0] or 'text/plain' return data I'm getting an error regarding this part: image[id].image_path What i want is for Pylons to display several jpg files on 1 page. Any idea how i could achieve this? A: Twice you use image.image_path, but in one spot (where, you tell us, you get a mistake) you use image[id].image_path instead. What's id that you believe could be a proper index into image, and why the discrepancy in usage among different spots of your code? If you want a certain number of images, why not use slicing syntax? E.g. you can get the first 10 images (be sure to include an order_by to get predictable, repeatable results) you can slice the results of the filter_by by [0:10]; the second 10 images, [10:20]; and so forth. A: My guess is that what you were assuming/hoping is that the result of the filter_by query contains a dictionary mapping the images retrieved to their ids. Instead it holds a query object which represents a promise to return an iterable result set when it is forced to by an access to either a slice expression like Alex mentioned or an iteration operation. This probably isn't the best way to solve this problem, but my guess is that modifying your code to look like this will probably accomplish what you want: def get_image(self, userid, id): image = meta.Session.query(Image).filter_by(userid=userid) image = dict((img.id, img) for img in image) permanent_file = open(image[id].image_path, 'rb') if not os.path.exists(image.image_path): return 'No such file' data = permanent_file.read() permanent_file.close() response.content_type = guess_type(image.image_path)[0] or 'text/plain' return data The more sensible way would be something like this: def get_image(self, userid, id): image = meta.Session.query(Image).filter_by(userid=userid).filter_by(id=id).first() # TODO: Handle the case when image is None permanent_file = open(image[id].image_path, 'rb') if not os.path.exists(image.image_path): return 'No such file' data = permanent_file.read() permanent_file.close() response.content_type = guess_type(image.image_path)[0] or 'text/plain' return data Of course you're assuming that an image exists that matches the query and it may not, so you should probably have some error handling for that where I left the TODO comment. Of course any of these changes will only return the data for a single image. If you want multiple images, you're going to have to call this function once for each image, probably in the request handler for some sort of image view. If you really do want to return the raw image data for multiple images at once, then Alex's suggestion to use slicing to get back e.g. 10 records at a time from the database is probably the best way to go, but then you'll have to modify the rest of the code to iterate over the list of N images and retrieve the data for each from the file system and return something like a list of the raw image data blobs. A: Assuming that "id" contains a number from 0 to however many images there are, you need to convert it from a string into an int before you can index an array. I'd do something like def get_image(self, userid, id): images = meta.Session.query(Image).filter_by(userid=userid) try: image = images[int(id)] with open(image.image_path, 'rb') as f: data = f.read() except (IndexError, ValueError, IOError): abort(404) response.content_type = guess_type(image.image_path)[0] or 'application/octet-stream' return data
How to display multiple images?
I'm trying to get multiple image paths from my database in order to display them, but it currently doesn't work. Here's what i'm using: def get_image(self, userid, id): image = meta.Session.query(Image).filter_by(userid=userid) permanent_file = open(image[id].image_path, 'rb') if not os.path.exists(image.image_path): return 'No such file' data = permanent_file.read() permanent_file.close() response.content_type = guess_type(image.image_path)[0] or 'text/plain' return data I'm getting an error regarding this part: image[id].image_path What i want is for Pylons to display several jpg files on 1 page. Any idea how i could achieve this?
[ "Twice you use image.image_path, but in one spot (where, you tell us, you get a mistake) you use image[id].image_path instead. What's id that you believe could be a proper index into image, and why the discrepancy in usage among different spots of your code?\nIf you want a certain number of images, why not use sli...
[ 1, 1, 0 ]
[]
[]
[ "pylons", "python", "sqlalchemy" ]
stackoverflow_0002841917_pylons_python_sqlalchemy.txt
Q: Python or Java? Whats better for mobile development, and GUI applications I know Python apps are faster to write, but it seems Java is the 800 lb gorilla for mobile and GUI development. Are there any mobile platforms that run Python, or should I go the Java route? A: Java is certainly available on more platforms. I would pick a target platform (or set of targets) and see what language(s) would require the least number of redundant implementations. Also, when you get to a certain level of complexity, the language often doesn't factor into speed. For initial prototypes, sure some languages are lightning fast to develop in, but by the time you've taken care of all the exception cases and tripled the entire schedule due to QA, you'll find that the prototype development speed wasn't all that big a deal. Of course, depending on the complexity of your app, this may prove to be untrue--a small simple app can be delivered in near "prototype time". A: Google have released the Android Scripting Environment (ASE) which lets you write programs for Android in a variety of scripting languages including Python and Ruby. However currently there is no way to release an app written in these languages, although Google are rumoured to be working on it. More generally the biggest resource constraint on mobile devices is battery power. Since dynamic interpreted languages generally have a higher CPU overhead than a statically typed language a Python program will be a bigger battery drain than the Java equivalent. On top of this you will need to ship the entire Python runtime with the program, while the Java runtime will already be included on the device. This means more memory overhead - another scarce resource on a mobile. For the moment at least I would not use Python or similar scripting language for serious Android development - it can be useful for rapid prototyping but not for production quality apps. I say this with a heavy heart, since I love Python and strongly dislike Java. A possible compromise is Scala - it is statically typed but uses type inference to remove a lot of the overhead of Java, and feels more like Python to develop in. Also like Python it is a mixed Object Oriented and functional language (unlike Java, which is Object Disoriented and disfunctional). There are a lot of people experimenting with using Scala for Android development, since it compiles down to Java class files that are as efficient as the equivalent Java code. I don't know what the situation is on the iPhone - given Apple's prohibition on the iStore carrying apps written any anything other that the officially sanctioned languages I think it is an unlikely fit. I know there is a version of Python for Window Mobile, but again AFAIK there is no way to package a python program up into a releasable app. A: The first question is whether you really need to develop an app, which requires per-platform work, vs a webapp. If you really need an app, then you might likely need a separate language for each platform! For Android you'd want to use Java, and for iPhone/iPad you'd want to use Objective-C. A good argument for really trying to go the webapp route.
Python or Java? Whats better for mobile development, and GUI applications
I know Python apps are faster to write, but it seems Java is the 800 lb gorilla for mobile and GUI development. Are there any mobile platforms that run Python, or should I go the Java route?
[ "Java is certainly available on more platforms. I would pick a target platform (or set of targets) and see what language(s) would require the least number of redundant implementations. \nAlso, when you get to a certain level of complexity, the language often doesn't factor into speed. For initial prototypes, sure...
[ 2, 1, 0 ]
[]
[]
[ "java", "mobile", "python", "user_interface" ]
stackoverflow_0003198646_java_mobile_python_user_interface.txt
Q: Where did Pylons beautiful error handling go? Using Nginx + Paster + Flup#fcgi_thread I need to run my development through nginx due to some complicated subdomain routing rules in my pylons app that wouldn't be handled otherwise. I had been using lighttpd + paster + Flup#scgi_thread and the nice error reporting by Pylons had been working fine in that environment. Yesterday I recompiled Python and MySQL for 64bit, and also switched to Ngix + paster + Flup#fcgi_thread for my development environment. Everything is working great, but I miss the fancy error reports. This is what I get now, and it is a mess compared to what I got used to: http://drp.ly/Iygeg Valid XHTML http://drp.ly/Iygeg. And here are the pylons/nginx configs. Pylons: [server:main] use = egg:Flup#fcgi_thread host = 0.0.0.0 port = 6500 Nginx: location / { #include /usr/local/nginx/conf/fastcgi.conf; fastcgi_param PATH_INFO $fastcgi_script_name; fastcgi_param REQUEST_METHOD $request_method; fastcgi_param QUERY_STRING $query_string; fastcgi_param CONTENT_TYPE $content_type; fastcgi_param CONTENT_LENGTH $content_length; fastcgi_param SERVER_ADDR $server_addr; fastcgi_param SERVER_PORT $server_port; fastcgi_param SERVER_NAME $server_name; fastcgi_param SERVER_PROTOCOL $server_protocol; fastcgi_param REMOTE_ADDR $remote_addr; fastcgi_pass_header Authorization; fastcgi_intercept_errors off; fastcgi_pass 127.0.0.1:6500; } A: I would guess that you need to configure Flup to disable its own error handling, so that the nice one one used by Paster could pass through. A: It looks like you are not getting the trackback css from _debug/media/traceback.css You might want to see if you can view the actual CSS and investigate whether nginx should serve your static content directly.
Where did Pylons beautiful error handling go? Using Nginx + Paster + Flup#fcgi_thread
I need to run my development through nginx due to some complicated subdomain routing rules in my pylons app that wouldn't be handled otherwise. I had been using lighttpd + paster + Flup#scgi_thread and the nice error reporting by Pylons had been working fine in that environment. Yesterday I recompiled Python and MySQL for 64bit, and also switched to Ngix + paster + Flup#fcgi_thread for my development environment. Everything is working great, but I miss the fancy error reports. This is what I get now, and it is a mess compared to what I got used to: http://drp.ly/Iygeg Valid XHTML http://drp.ly/Iygeg. And here are the pylons/nginx configs. Pylons: [server:main] use = egg:Flup#fcgi_thread host = 0.0.0.0 port = 6500 Nginx: location / { #include /usr/local/nginx/conf/fastcgi.conf; fastcgi_param PATH_INFO $fastcgi_script_name; fastcgi_param REQUEST_METHOD $request_method; fastcgi_param QUERY_STRING $query_string; fastcgi_param CONTENT_TYPE $content_type; fastcgi_param CONTENT_LENGTH $content_length; fastcgi_param SERVER_ADDR $server_addr; fastcgi_param SERVER_PORT $server_port; fastcgi_param SERVER_NAME $server_name; fastcgi_param SERVER_PROTOCOL $server_protocol; fastcgi_param REMOTE_ADDR $remote_addr; fastcgi_pass_header Authorization; fastcgi_intercept_errors off; fastcgi_pass 127.0.0.1:6500; }
[ "I would guess that you need to configure Flup to disable its own error handling, so that the nice one one used by Paster could pass through.\n", "It looks like you are not getting the trackback css from _debug/media/traceback.css You might want to see if you can view the actual CSS and investigate whether nginx...
[ 2, 0 ]
[]
[]
[ "error_handling", "nginx", "paster", "pylons", "python" ]
stackoverflow_0002549611_error_handling_nginx_paster_pylons_python.txt
Q: Function expects 2 arguments when should only one I have a function friend_exists like this: def friend_exists(request, pid): result = False try: user = Friend.objects.get(pid=pid) except Friend.DoesNotExist: pass if user: result = True return result I'm calling it from my other function like this: exists = friend_exists(form.cleaned_data['pid']) where pid = u'12345678'. Why I'm getting: Exception Type: TypeError at /user/register/ Exception Value: friend_exists() takes exactly 2 arguments (1 given) Any ideas? A: Why do you think it should only take one? You've clearly got two arguments in the function definition: def friend_exists(request, pid): Right there it says it expects request and pid. A: It takes two arguments and you are only giving it one, the value of form.cleaned_data['pid']. If that value is actually a tuple/list of the two arguments, you want to expand it with the asterisk like: exists = friend_exists(*form.cleaned_data['pid']) A cleaner approach in that case might then be: request, pid = form.cleaned_data['pid'] exists = friend_exists(request, pid) A: This looks like django, so the way to properly call your function would be friend_exists(request, form.cleaned_data['pid']. When a view function is called, the request is automatically populated, so it may seem like that should happen for every call in a django app, but as you are calling the function manually, you will have to manually pass it the request object.
Function expects 2 arguments when should only one
I have a function friend_exists like this: def friend_exists(request, pid): result = False try: user = Friend.objects.get(pid=pid) except Friend.DoesNotExist: pass if user: result = True return result I'm calling it from my other function like this: exists = friend_exists(form.cleaned_data['pid']) where pid = u'12345678'. Why I'm getting: Exception Type: TypeError at /user/register/ Exception Value: friend_exists() takes exactly 2 arguments (1 given) Any ideas?
[ "Why do you think it should only take one? You've clearly got two arguments in the function definition:\ndef friend_exists(request, pid):\n\nRight there it says it expects request and pid.\n", "It takes two arguments and you are only giving it one, the value of form.cleaned_data['pid']. If that value is actually ...
[ 6, 2, 1 ]
[]
[]
[ "argument_passing", "django", "function", "python" ]
stackoverflow_0003199181_argument_passing_django_function_python.txt
Q: Unable to access database from within a method I keep receiving the error, "TypeError: 'Shard' object is unsubscriptable." #Establish an on-demand connection to the central database def connectCentral(): engine = engine_from_config(config, 'sqlalchemy.central.') central.engine = engine central.Session.configure(bind=engine) #Establish an on-demand connection to a shard that contains #data for the supplied id def connectShard(id): #If no connection has been made to the central database #make one to determine the shard info if central.engine == None: print 'Connecting to central database' connectCentral() shard_info = central.Session.query(Shard).filter_by(id=id).first() #If no shard exists for the given id, return false if shard_info == None: return 'None' shard.engine = shard_info['sqlite'] shard.Session.configure(bind=shard.engine) c_shard = sa.Table("Shard", central.metadata, sa.Column("id", sa.types.Integer, primary_key=True), sa.Column("ip",sa.types.String(100), nullable=False), sa.Column("username",sa.types.String(100), nullable=False), sa.Column("password",sa.types.String(100), nullable=False), sa.Column("port",sa.types.String(100), nullable=False), sa.Column("active",sa.types.String(100), nullable=False), sa.Column("sqlite",sa.types.String(100), nullable=True) ) The error output is: connectShard(232) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/project/project/model/__init__.py", line 39, in connectShard shard.Session.configure(bind=shard.engine) TypeError: 'Shard' object is unsubscriptable A: Given the incomplete snippet of code you've given, the only relevant line is: shard.Session.configure(bind=shard.engine) The error indication is a base Python type error, a scalar (or None) needed to be subscripted inside SQLAlchemy. This almost certainly is the result of an incompletely or erroneously constructed session in part of the code that you haven't shown. A: My guess is that the error is in this line: shard.engine = shard_info['sqlite'] because shard_info is the only object of Shard class that I can see, and it's the only subscription operation in the code pasted. The traceback shows a different line, so perhaps you edited the source after it was imported? Back to the error: SQLAlchemy objects aren't dictionaries, so what you want is shard.engine = shard_info.sqlite but that would assign a string (filename? sqlalchemy url?) to engine, which is not what you should be passing to Session.configure(). I'm guessing you want something like dbname = shard_info.sqlite shard.engine = create_engine('sqlite:///' + dbname) shard.Session.configure(bind=shard.engine)
Unable to access database from within a method
I keep receiving the error, "TypeError: 'Shard' object is unsubscriptable." #Establish an on-demand connection to the central database def connectCentral(): engine = engine_from_config(config, 'sqlalchemy.central.') central.engine = engine central.Session.configure(bind=engine) #Establish an on-demand connection to a shard that contains #data for the supplied id def connectShard(id): #If no connection has been made to the central database #make one to determine the shard info if central.engine == None: print 'Connecting to central database' connectCentral() shard_info = central.Session.query(Shard).filter_by(id=id).first() #If no shard exists for the given id, return false if shard_info == None: return 'None' shard.engine = shard_info['sqlite'] shard.Session.configure(bind=shard.engine) c_shard = sa.Table("Shard", central.metadata, sa.Column("id", sa.types.Integer, primary_key=True), sa.Column("ip",sa.types.String(100), nullable=False), sa.Column("username",sa.types.String(100), nullable=False), sa.Column("password",sa.types.String(100), nullable=False), sa.Column("port",sa.types.String(100), nullable=False), sa.Column("active",sa.types.String(100), nullable=False), sa.Column("sqlite",sa.types.String(100), nullable=True) ) The error output is: connectShard(232) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/project/project/model/__init__.py", line 39, in connectShard shard.Session.configure(bind=shard.engine) TypeError: 'Shard' object is unsubscriptable
[ "Given the incomplete snippet of code you've given, the only relevant line is: \nshard.Session.configure(bind=shard.engine)\n\nThe error indication is a base Python type error, a scalar (or None) needed to be subscripted inside SQLAlchemy. This almost certainly is the result of an incompletely or erroneously constr...
[ 0, 0 ]
[]
[]
[ "pylons", "python", "sqlalchemy" ]
stackoverflow_0002349614_pylons_python_sqlalchemy.txt
Q: Setting Up virtualenv with python2.6 I'm setting up a virtualenv, but it seems to be using python2.5 by default. I'm using this command virtualenv newenv --no-site-packages -p python because the python found on my path is python2.6. I believe this to be true because when I type python and go into the shell, it tells me it's 2.6. When I create the virtualenv with the above command and launch the shell, it tells me I'm in 2.5. Anyone else have this issue? A: using this as the location of python works on OSX 10.6 /System/Library/Frameworks/Python.framework/Versions/2.6/Python
Setting Up virtualenv with python2.6
I'm setting up a virtualenv, but it seems to be using python2.5 by default. I'm using this command virtualenv newenv --no-site-packages -p python because the python found on my path is python2.6. I believe this to be true because when I type python and go into the shell, it tells me it's 2.6. When I create the virtualenv with the above command and launch the shell, it tells me I'm in 2.5. Anyone else have this issue?
[ "using this as the location of python works on OSX 10.6\n/System/Library/Frameworks/Python.framework/Versions/2.6/Python\n" ]
[ 1 ]
[]
[]
[ "python", "virtualenv" ]
stackoverflow_0002784398_python_virtualenv.txt
Q: How do I slice a sequence to get the last item? I am practicing slicing, and I want to run a program that prints a name backwards. Mainly, I want to know how to access the last item in the sequence. I wrote the following: name = raw_input("Enter Your Name: ") backname = ??? print backname Is this a sound approach? Obviously, the ??? is not a part of my syntax, just asking what should go there. A: To access the last item in a sequence, use: print name[-1] This is the same as: print name[len(name) - 1] Reversing a sequence has a common idiom in Python: backname = name[::-1] The Good primer for Python slice notation question has more complete information. A: backname[-1] #the last item in the sequence #To reverse backname (the long way): aList = [c for c in backname] #will give you ['1', '2', ..., 'n'] aList.reverse() #aList will be ['n', ..., '2', '1] backname = "".join(aList) #backname reversed #To reverse backname, as other answers replied: backname[::-1] A: You want name[::-1]. The -1 is the "step" of the slice-- if you wanted every other letter, for example, you would use name[::2]. A: You can use negative indices to access items counting from the end of a list, so name[-1] will give you the last character. However, the third slice argument is a step, which can also be negative, so this will give you the whole string in reverse: name[::-1] A: With slice syntax, you would use: backname = name[::-1] The two colons show that the first two parameters to the slice are left at their defaults, so start at the beginning, process to the end, but step backwards (the -1). A: You probably want to read the docs: http://docs.python.org/library/stdtypes.html#sequence-types-str-unicode-list-tuple-buffer-xrange There's a method to reverse the string for you, if you want. For the specific question you asked, to access the last item of a sequence you use "seq[-1]". A: It does look sound. And your second line should be backname = name[::-1]
How do I slice a sequence to get the last item?
I am practicing slicing, and I want to run a program that prints a name backwards. Mainly, I want to know how to access the last item in the sequence. I wrote the following: name = raw_input("Enter Your Name: ") backname = ??? print backname Is this a sound approach? Obviously, the ??? is not a part of my syntax, just asking what should go there.
[ "To access the last item in a sequence, use:\nprint name[-1]\n\nThis is the same as:\nprint name[len(name) - 1]\n\nReversing a sequence has a common idiom in Python:\nbackname = name[::-1]\n\nThe Good primer for Python slice notation question has more complete information.\n", "backname[-1] #the last item in the ...
[ 3, 1, 1, 1, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003199447_python.txt
Q: Fill a table horiziantally say i have a list e.g. apple car bin How to i get it to fill horizonatlly in a table rather than vertically i.e so it looks like this in a table: apple car bin The code im using just repeats each entry of the list for the entire row, code below: <body> <div metal:fill-slot="main"> <h1>List of Species in the Database</h1> <table border="0" width="100%"> <tr tal:repeat="records container/Query_Species"> <td tal:content="records/gene_bank_species">Species</td> <td tal:content="records/gene_bank_species">Species</td> </tr> </div> </body> A: <table border="0" width="100%"> <tr tal:repeat="records container/Query_Species"> <td tal:content="records/gene_bank_species">Species</td> </tr> <tr tal:repeat="records container/Query_Species"> <td tal:content="records/gene_bank_species">Species</td> </tr> </table>
Fill a table horiziantally
say i have a list e.g. apple car bin How to i get it to fill horizonatlly in a table rather than vertically i.e so it looks like this in a table: apple car bin The code im using just repeats each entry of the list for the entire row, code below: <body> <div metal:fill-slot="main"> <h1>List of Species in the Database</h1> <table border="0" width="100%"> <tr tal:repeat="records container/Query_Species"> <td tal:content="records/gene_bank_species">Species</td> <td tal:content="records/gene_bank_species">Species</td> </tr> </div> </body>
[ "<table border=\"0\" width=\"100%\">\n <tr tal:repeat=\"records container/Query_Species\">\n <td tal:content=\"records/gene_bank_species\">Species</td>\n </tr>\n <tr tal:repeat=\"records container/Query_Species\">\n <td tal:content=\"records/gene_bank_species\">Species</td> \n <...
[ 0 ]
[]
[]
[ "html", "python" ]
stackoverflow_0003199487_html_python.txt
Q: pydev and twisted framework It seems like my Eclipse PyDev does not recognize that Twisted is installed on my system. I can't make auto suggest working. Does anyone know how to solve it? A: go to preferences->Pydev->Interpreter - Python and hit the apply button. That will rescan your modules directory and add any missing modules. That should fix any normal import errors. Some modules do some runtime magic that PyDev cant follow.
pydev and twisted framework
It seems like my Eclipse PyDev does not recognize that Twisted is installed on my system. I can't make auto suggest working. Does anyone know how to solve it?
[ "go to preferences->Pydev->Interpreter - Python and hit the apply button. That will rescan your modules directory and add any missing modules.\nThat should fix any normal import errors. Some modules do some runtime magic that PyDev cant follow.\n" ]
[ 12 ]
[]
[]
[ "eclipse", "pydev", "python", "twisted" ]
stackoverflow_0003199702_eclipse_pydev_python_twisted.txt
Q: Configuring pep8 in Textmate Textmate has a Python PEP8 bundle that will run pep8 validation on your file. How can I set it to do the equivalent of pep8 --ignore=E501 my_file.py? A: The author of the pep8 bundle has added a feature to hide user-specified error codes. http://github.com/ppierre/python-pep8-tmbundle
Configuring pep8 in Textmate
Textmate has a Python PEP8 bundle that will run pep8 validation on your file. How can I set it to do the equivalent of pep8 --ignore=E501 my_file.py?
[ "The author of the pep8 bundle has added a feature to hide user-specified error codes.\nhttp://github.com/ppierre/python-pep8-tmbundle\n" ]
[ 1 ]
[]
[]
[ "pep8", "python", "textmate", "textmatebundles" ]
stackoverflow_0003193871_pep8_python_textmate_textmatebundles.txt
Q: Threaded SOAP requests in Python (Django) application? I'm working with an application that needs to be make some time consuming SOAP requests (using suds, as it were). There are several instances where a user will change the state of an object and in doing so trigger one or more SOAP requests that fetch some data. This could be done in the background, and right now the user has to wait while these finish. Is this a reasonable use case for Python threads? Or is that just asking for trouble? Better suggestions? A: That sounds great! You almost always want to do long running stuff in a background thread, and many soap requests spend a lot of time waiting on network IO... The only question is how do you get the data back to the user. Is this a GUI app, or a web app, or what? A: I use the producer consumer model with a RPCXML server for just this sort of thing. I start a pool of 3 threads, when someone requests something done (add file, etc) I add the work to the queue and return a key. an ajax request can check on the status of the key to set a progress bar, etc.
Threaded SOAP requests in Python (Django) application?
I'm working with an application that needs to be make some time consuming SOAP requests (using suds, as it were). There are several instances where a user will change the state of an object and in doing so trigger one or more SOAP requests that fetch some data. This could be done in the background, and right now the user has to wait while these finish. Is this a reasonable use case for Python threads? Or is that just asking for trouble? Better suggestions?
[ "That sounds great! You almost always want to do long running stuff in a background thread, and many soap requests spend a lot of time waiting on network IO...\nThe only question is how do you get the data back to the user. Is this a GUI app, or a web app, or what? \n", "I use the producer consumer model with a ...
[ 1, 0 ]
[]
[]
[ "asynchronous", "django", "multithreading", "python", "soap" ]
stackoverflow_0003200004_asynchronous_django_multithreading_python_soap.txt
Q: BadStatusLine Error in Python (On Windows Only) I am developing an application with PyQT4 which will POST some data to a web service to send SMS. The application works perfectly on Ubuntu 10.04. But when I deploy it on Windows, I get the BadStatusLine Error. I am running Python 2.6.4 on Windows 7. The Error Message and the source codes follow. I didn't put the gui.py since it was auto generated by the Qt Designer. Please help me debug it. Error Message: Exception in thread Thread-1: Traceback (most recent call last): File "C:\Python26\lib\threading.py", line 525, in __bootstrap_inner self.run() File "D:\Temp\gp\library.py", line 14, in run f = urllib2.urlopen(urllib2.Request("http://masnun.com/aloashbei/sms/send",u rllib.urlencode(self.data))) File "C:\Python26\lib\urllib2.py", line 124, in urlopen return _opener.open(url, data, timeout) File "C:\Python26\lib\urllib2.py", line 389, in open response = self._open(req, data) File "C:\Python26\lib\urllib2.py", line 407, in _open '_open', req) File "C:\Python26\lib\urllib2.py", line 367, in _call_chain result = func(*args) File "C:\Python26\lib\urllib2.py", line 1146, in http_open return self.do_open(httplib.HTTPConnection, req) File "C:\Python26\lib\urllib2.py", line 1119, in do_open r = h.getresponse() File "C:\Python26\lib\httplib.py", line 974, in getresponse response.begin() File "C:\Python26\lib\httplib.py", line 391, in begin version, status, reason = self._read_status() File "C:\Python26\lib\httplib.py", line 355, in _read_status raise BadStatusLine(line) BadStatusLine App.Py #!/usr/bin/python import os, sys from PyQt4 import QtCore, QtGui import gui, library app = QtGui.QApplication(sys.argv) mainWindow = QtGui.QMainWindow() mainWindow.ui = gui.Ui_MainWindow() mainWindow.ui.setupUi(mainWindow) appUi = mainWindow.ui # Add the application logic handler = library.Application(mainWindow) appUi.sendButton.clicked.connect(handler.send) appUi.actionQuit.triggered.connect(sys.exit) mainWindow.show() sys.exit(app.exec_()) library.py #!/usr/bin/python from PyQt4 import QtGui from threading import Thread class Req(Thread): def __init__(self,data,callback): self.data = data self.callback = callback Thread.__init__(self) def run(self): import urllib, urllib2, json f = urllib2.urlopen(urllib2.Request("http://masnun.com/aloashbei/sms/send",urllib.urlencode(self.data))) resp = json.loads(f.read()) status = resp['SendSMSResponse']['status'] self.callback(status) #8801711960803 class Application(object): def __init__(self,mainWindow): self.mainWindow = mainWindow self.ui = mainWindow.ui self.status = "" def quit(self): import sys sys.exit() def send(self): data = {} data['registrationID'] = self.ui.username.text() data['password'] = self.ui.password.text() data['sourceMsisdn'] = self.ui.phoneNumber.text() data['destinationMsisdn'] = self.ui.toBox.text() data['smsPort'] = 7424 data['msgType'] = 4 data['charge'] = 0.00 data['chargedParty'] = self.ui.phoneNumber.text() data['contentArea'] = 'gpgp_psms'; data['msgContent'] = self.ui.smsText.text(); req = Req(data,self.getStatus) req.start() req.join() if self.status == 'OK': QtGui.QMessageBox.information(None,"SMS Sent","SMS Sent successfully!") self.status = "" else: QtGui.QMessageBox.critical(None, "ERROR!","The SMS could not be sent!",QtGui.QMessageBox.Ok | QtGui.QMessageBox.Default,QtGui.QMessageBox.NoButton) self.status = "" def getStatus(self,status): self.status = status A: Well, I just got id of it. You can not mix up Unicode and Strings. I also used urllib instead of urllib2. It worked. But I am not yet sure where the problem came from :(
BadStatusLine Error in Python (On Windows Only)
I am developing an application with PyQT4 which will POST some data to a web service to send SMS. The application works perfectly on Ubuntu 10.04. But when I deploy it on Windows, I get the BadStatusLine Error. I am running Python 2.6.4 on Windows 7. The Error Message and the source codes follow. I didn't put the gui.py since it was auto generated by the Qt Designer. Please help me debug it. Error Message: Exception in thread Thread-1: Traceback (most recent call last): File "C:\Python26\lib\threading.py", line 525, in __bootstrap_inner self.run() File "D:\Temp\gp\library.py", line 14, in run f = urllib2.urlopen(urllib2.Request("http://masnun.com/aloashbei/sms/send",u rllib.urlencode(self.data))) File "C:\Python26\lib\urllib2.py", line 124, in urlopen return _opener.open(url, data, timeout) File "C:\Python26\lib\urllib2.py", line 389, in open response = self._open(req, data) File "C:\Python26\lib\urllib2.py", line 407, in _open '_open', req) File "C:\Python26\lib\urllib2.py", line 367, in _call_chain result = func(*args) File "C:\Python26\lib\urllib2.py", line 1146, in http_open return self.do_open(httplib.HTTPConnection, req) File "C:\Python26\lib\urllib2.py", line 1119, in do_open r = h.getresponse() File "C:\Python26\lib\httplib.py", line 974, in getresponse response.begin() File "C:\Python26\lib\httplib.py", line 391, in begin version, status, reason = self._read_status() File "C:\Python26\lib\httplib.py", line 355, in _read_status raise BadStatusLine(line) BadStatusLine App.Py #!/usr/bin/python import os, sys from PyQt4 import QtCore, QtGui import gui, library app = QtGui.QApplication(sys.argv) mainWindow = QtGui.QMainWindow() mainWindow.ui = gui.Ui_MainWindow() mainWindow.ui.setupUi(mainWindow) appUi = mainWindow.ui # Add the application logic handler = library.Application(mainWindow) appUi.sendButton.clicked.connect(handler.send) appUi.actionQuit.triggered.connect(sys.exit) mainWindow.show() sys.exit(app.exec_()) library.py #!/usr/bin/python from PyQt4 import QtGui from threading import Thread class Req(Thread): def __init__(self,data,callback): self.data = data self.callback = callback Thread.__init__(self) def run(self): import urllib, urllib2, json f = urllib2.urlopen(urllib2.Request("http://masnun.com/aloashbei/sms/send",urllib.urlencode(self.data))) resp = json.loads(f.read()) status = resp['SendSMSResponse']['status'] self.callback(status) #8801711960803 class Application(object): def __init__(self,mainWindow): self.mainWindow = mainWindow self.ui = mainWindow.ui self.status = "" def quit(self): import sys sys.exit() def send(self): data = {} data['registrationID'] = self.ui.username.text() data['password'] = self.ui.password.text() data['sourceMsisdn'] = self.ui.phoneNumber.text() data['destinationMsisdn'] = self.ui.toBox.text() data['smsPort'] = 7424 data['msgType'] = 4 data['charge'] = 0.00 data['chargedParty'] = self.ui.phoneNumber.text() data['contentArea'] = 'gpgp_psms'; data['msgContent'] = self.ui.smsText.text(); req = Req(data,self.getStatus) req.start() req.join() if self.status == 'OK': QtGui.QMessageBox.information(None,"SMS Sent","SMS Sent successfully!") self.status = "" else: QtGui.QMessageBox.critical(None, "ERROR!","The SMS could not be sent!",QtGui.QMessageBox.Ok | QtGui.QMessageBox.Default,QtGui.QMessageBox.NoButton) self.status = "" def getStatus(self,status): self.status = status
[ "Well, I just got id of it. You can not mix up Unicode and Strings. I also used urllib instead of urllib2. It worked. But I am not yet sure where the problem came from :(\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0003176934_python.txt
Q: Python: Redis as session backend to Beaker Anyone had success with using Redis as Beaker backend? Can you tell me link or library how to do it? I am looking for any library which does this but could not get anything out of google search. A: I have posted to pylons user group and this information resolve my question.. http://groups.google.com/group/pylons-discuss/msg/a1144aa1ca8e0417 Here are the steps that worked for me: easy_install redis easy_install pip pip install git+git://github.com/bbangert/beaker_extensions.git Edit Pylons' development.ini [app:main] full_stack = true static_files = true cache_dir = %(here)s/data beaker.session.type = redis beaker.session.url:127.0.0.1:6379 beaker.session.key = appname (Optional) Edit this file and change the serialization method to JSON. Even though JSON is not as efficient byte for byte I like how it is easily readable and relatively well supported across the technologies I've chosen: https://github.com/bbangert/beaker_extensions/blob/master/beaker_extensions/redis_.py Posted by Jeff Tchang
Python: Redis as session backend to Beaker
Anyone had success with using Redis as Beaker backend? Can you tell me link or library how to do it? I am looking for any library which does this but could not get anything out of google search.
[ "I have posted to pylons user group and this information resolve my question..\nhttp://groups.google.com/group/pylons-discuss/msg/a1144aa1ca8e0417\nHere are the steps that worked for me:\n\neasy_install redis\neasy_install pip\npip install git+git://github.com/bbangert/beaker_extensions.git\nEdit Pylons' developmen...
[ 11 ]
[]
[]
[ "beaker", "pylons", "python", "redis", "session" ]
stackoverflow_0003192677_beaker_pylons_python_redis_session.txt
Q: sqlalchemy filter using in_ Is there a more efficient way to do the following? I am more interested in knowing if there is a way to set "mylist" to match anything if day is equal to 'all' because in other scenarios, "mylist" can contain a lot more elements. if day == 'all': mylist = ['monday','tuesday','wednesday','thursday','friday','saturday','sunday'] else: mylist = [day] # day equal to one of the above records = meta.Session.query(Transaction).filter(Transaction.day.in_(mylist)).all() A: What about just not filtering on the day if it's equal to 'all'? query = meta.session.query(Transaction) if day != 'all': query = query.filter(Transaction.day == day) records = query.all()
sqlalchemy filter using in_
Is there a more efficient way to do the following? I am more interested in knowing if there is a way to set "mylist" to match anything if day is equal to 'all' because in other scenarios, "mylist" can contain a lot more elements. if day == 'all': mylist = ['monday','tuesday','wednesday','thursday','friday','saturday','sunday'] else: mylist = [day] # day equal to one of the above records = meta.Session.query(Transaction).filter(Transaction.day.in_(mylist)).all()
[ "What about just not filtering on the day if it's equal to 'all'?\nquery = meta.session.query(Transaction)\nif day != 'all':\n query = query.filter(Transaction.day == day)\nrecords = query.all()\n\n" ]
[ 7 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0003200395_python_sqlalchemy.txt
Q: How to add Tkinter support for PIL Python library Okay, well supposedly PIL is supposed to be able to work with Tkinter automatically, but mine is not. I found this text file in the Imaging directories Tk directory. Using PIL With Tkinter Starting with 1.0 final (release candidate 2 and later, to be precise), PIL can attach itself to Tkinter in flight. As a result, you no longer need to rebuild the Tkinter extension to be able to use PIL. However, if you cannot get the this to work on your platform, you can do it in the old way: * Adding Tkinter support 1. Compile Python's _tkinter.c with the WITH_APPINIT and WITH_PIL flags set, and link it with tkImaging.c and tkappinit.c. To do this, copy the former to the Modules directory, and edit the _tkinter line in Setup (or Setup.in) according to the instructions in that file. NOTE: if you have an old Python version, the tkappinit.c file is not included by default. If this is the case, you will have to add the following lines to tkappinit.c, after the MOREBUTTONS stuff: { extern void TkImaging_Init(Tcl_Interp* interp); TkImaging_Init(interp); } This registers a Tcl command called "PyImagingPhoto", which is use to communicate between PIL and Tk's PhotoImage handler. You must also change the _tkinter line in Setup (or Setup.in) to something like: _tkinter _tkinter.c tkImaging.c tkappinit.c -DWITH_APPINIT -I/usr/local/include -L/usr/local/lib -ltk8.0 -ltcl8.0 -lX11 Unfortunately I have no idea how to do any of this, and I couldn't find any guides online. Can someone please walk me through how I compile Python's _tkinter.c with the flags set and so on? A: What versions of Python and PIL are you using (and on what platform, etc)? All reasonably recent versions should already support all of these required options (with setup.py as well as Modules/Setup.dict) -- e.g., including tkappinit.c etc -- so it's particularly hard to know what to suggest "in a vacuum". Also, how to compile things (supposing you do need to) can be very platform-dependent, so in case you do need any recompiling (unlikely as that may be), knowing your platform can be important.
How to add Tkinter support for PIL Python library
Okay, well supposedly PIL is supposed to be able to work with Tkinter automatically, but mine is not. I found this text file in the Imaging directories Tk directory. Using PIL With Tkinter Starting with 1.0 final (release candidate 2 and later, to be precise), PIL can attach itself to Tkinter in flight. As a result, you no longer need to rebuild the Tkinter extension to be able to use PIL. However, if you cannot get the this to work on your platform, you can do it in the old way: * Adding Tkinter support 1. Compile Python's _tkinter.c with the WITH_APPINIT and WITH_PIL flags set, and link it with tkImaging.c and tkappinit.c. To do this, copy the former to the Modules directory, and edit the _tkinter line in Setup (or Setup.in) according to the instructions in that file. NOTE: if you have an old Python version, the tkappinit.c file is not included by default. If this is the case, you will have to add the following lines to tkappinit.c, after the MOREBUTTONS stuff: { extern void TkImaging_Init(Tcl_Interp* interp); TkImaging_Init(interp); } This registers a Tcl command called "PyImagingPhoto", which is use to communicate between PIL and Tk's PhotoImage handler. You must also change the _tkinter line in Setup (or Setup.in) to something like: _tkinter _tkinter.c tkImaging.c tkappinit.c -DWITH_APPINIT -I/usr/local/include -L/usr/local/lib -ltk8.0 -ltcl8.0 -lX11 Unfortunately I have no idea how to do any of this, and I couldn't find any guides online. Can someone please walk me through how I compile Python's _tkinter.c with the flags set and so on?
[ "What versions of Python and PIL are you using (and on what platform, etc)? All reasonably recent versions should already support all of these required options (with setup.py as well as Modules/Setup.dict) -- e.g., including tkappinit.c etc -- so it's particularly hard to know what to suggest \"in a vacuum\". Als...
[ 0 ]
[]
[]
[ "compilation", "python", "python_imaging_library", "tkinter" ]
stackoverflow_0003200308_compilation_python_python_imaging_library_tkinter.txt
Q: How to make a group for each word in a sentence? This may be a silly question but... Say you have a sentence like: The quick brown fox Or you might get a sentence like: The quick brown fox jumped over the lazy dog The simple regexp (\w*) finds the first word "The" and puts it in a group. For the first sentence, you could write (\w*)\s*(\w*)\s*(\w*)\s*(\w*)\s* to put each word in its own group, but that assumes you know the number of words in the sentence. Is it possible to write a regular expression that puts each word in any arbitrary sentence into its own group? It would be nice if you could do something like (?:(\w*)\s*)* to have it group each instance of (\w*), but that doesn't work. I am doing this in Python, and my use case is obviously a little more complex than "The quick brown fox", so it would be nifty if Regex could do this in one line, but if that's not possible then I assume the next best solution is to loop over all the matches using re.findall() or something similar. Thanks for any insight you may have. Edit: For completeness's sake here's my actual use case and how I solved it using your help. Thanks again. >>> s = '1 0 5 test1 5 test2 5 test3 5 test4 5 test5' >>> s = re.match(r'^\d+\s\d+\s?(.*)', s).group(1) >>> print s 5 test1 5 test2 5 test3 5 test4 5 test5 >>> list = re.findall(r'\d+\s(\w+)', s) >>> print list ['test1', 'test2', 'test3', 'test4', 'test5'] A: You can also use the function findall in the module re import re >>> re.findall("\w+", "The quick brown fox") ['The', 'quick', 'brown', 'fox'] A: I don't believe that it is possible. Regexes pair the captures with the parentheses in the given regular expression... if you only listed one group, like '((\w+)\s+){0,99}', then it would just repeatedly capture to the same first and second group... not create new groups for each match found. You could use split, but that only splits on one character value, not a class of characters like whitespace. Instead, you can use re.split, which can split on a regular expression, and give it '\s' to match any whitespace. You probably want it to match '\s+' to gather the whitespace greedily. >>> import re >>> help(re.split) Help on function split in module re: split(pattern, string, maxsplit=0) Split the source string by the occurrences of the pattern, returning a list containing the resulting substrings. >>> re.split('\s+', 'The quick brown\t fox') ['The', 'quick', 'brown', 'fox'] >>> A: Why use a regex when string.split does the same thing? >>> "The quick brown fox".split() ['The', 'quick', 'brown', 'fox'] A: Regular expressions can't group into unknown number of groups. But there is hope in your case. Look into the 'split' method, it should help in your case.
How to make a group for each word in a sentence?
This may be a silly question but... Say you have a sentence like: The quick brown fox Or you might get a sentence like: The quick brown fox jumped over the lazy dog The simple regexp (\w*) finds the first word "The" and puts it in a group. For the first sentence, you could write (\w*)\s*(\w*)\s*(\w*)\s*(\w*)\s* to put each word in its own group, but that assumes you know the number of words in the sentence. Is it possible to write a regular expression that puts each word in any arbitrary sentence into its own group? It would be nice if you could do something like (?:(\w*)\s*)* to have it group each instance of (\w*), but that doesn't work. I am doing this in Python, and my use case is obviously a little more complex than "The quick brown fox", so it would be nifty if Regex could do this in one line, but if that's not possible then I assume the next best solution is to loop over all the matches using re.findall() or something similar. Thanks for any insight you may have. Edit: For completeness's sake here's my actual use case and how I solved it using your help. Thanks again. >>> s = '1 0 5 test1 5 test2 5 test3 5 test4 5 test5' >>> s = re.match(r'^\d+\s\d+\s?(.*)', s).group(1) >>> print s 5 test1 5 test2 5 test3 5 test4 5 test5 >>> list = re.findall(r'\d+\s(\w+)', s) >>> print list ['test1', 'test2', 'test3', 'test4', 'test5']
[ "You can also use the function findall in the module re\nimport re\n>>> re.findall(\"\\w+\", \"The quick brown fox\")\n['The', 'quick', 'brown', 'fox']\n\n", "I don't believe that it is possible. Regexes pair the captures with the parentheses in the given regular expression... if you only listed one group, like '...
[ 6, 4, 3, 1 ]
[]
[]
[ "python", "regex", "regex_group" ]
stackoverflow_0003200467_python_regex_regex_group.txt
Q: Django: How to define the models when parent model has two foreign keys come from one same model? I want to define two model fields: created_by, modified_by in a parent model, they will be acting as common fields for the child models. class ExtendedModel(models.Model): created_by = models.ForeignKey(User,related_name='r_created_by') modified_by = models.ForeignKey(User,related_name='r_modified_by') class Meta: abstract = True class ChildModel1(ExtendedModel): pass class ChildModel2(ExtendedModel): pass this gives errors as ChildModel1 and ChildModel2 has related_name clashed with each other on their created_by and modified_by fields. A: The Django docs explain how to work around this: http://docs.djangoproject.com/en/dev/topics/db/models/#abstract-related-name class ExtendedModel(models.Model): created_by = models.ForeignKey(User,related_name='"%(app_label)s_%(class)s_created_by') modified_by = models.ForeignKey(User,related_name='"%(app_label)s_%(class)s_modified_by') class Meta: abstract = True class ChildModel1(ExtendedModel): pass class ChildModel2(ExtendedModel): pass
Django: How to define the models when parent model has two foreign keys come from one same model?
I want to define two model fields: created_by, modified_by in a parent model, they will be acting as common fields for the child models. class ExtendedModel(models.Model): created_by = models.ForeignKey(User,related_name='r_created_by') modified_by = models.ForeignKey(User,related_name='r_modified_by') class Meta: abstract = True class ChildModel1(ExtendedModel): pass class ChildModel2(ExtendedModel): pass this gives errors as ChildModel1 and ChildModel2 has related_name clashed with each other on their created_by and modified_by fields.
[ "The Django docs explain how to work around this: http://docs.djangoproject.com/en/dev/topics/db/models/#abstract-related-name\nclass ExtendedModel(models.Model):\n created_by = models.ForeignKey(User,related_name='\"%(app_label)s_%(class)s_created_by')\n modified_by = models.ForeignKey(User,related_n...
[ 3 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0003200519_django_django_models_python.txt
Q: Python: does calling a method 'directly' instantiate the object? I am new to Python and while unit testing some methods on my object I noticed something 'weird'. class Ape(object): def __init__(self): print 'ooook' def say(self, s): print s def main(): Ape().say('eeek') if __name__ == '__main__': main() I wrote this little example to illustrate where I got confused. If you do Ape().say('eeek') does this actually instantiate an Ape object and run the init method? I thought it wouldn't but I had some weird side effects so now I am thinking it does? A: If you want to call a method directly without creating an instance you can use the staticmethod decorator. Notice that there is no self when you use a static method class Ape(object): def __init__(self): print 'ooook' @staticmethod def say(s): print s def main(): Ape.say('eeek') if __name__ == '__main__': main() Compare with class methods where the class is the first parameter instead of an instance class Ape(object): def __init__(self): print 'ooook' @classmethod def say(cls, s): print "the class is:", cls print s def main(): Ape.say('eeek') if __name__ == '__main__': main() A: Yes it does. That's what Ape() does: it creates an new Ape object, and as part of that process the __init__ method gets run. In your example, you then call the say method of that object. Note that there would be no way to call say if you didn't have an Ape object. A: Yes. Ape() instantiates an object of class Ape, although since there is no assignment, no label is associated with it. At this point its __init__ function is called. Then, the say function is called. To be clear: Ape().say('eeek') is equivalent to: (Ape()).say('eeek') Which more clearly indicates what happens first.
Python: does calling a method 'directly' instantiate the object?
I am new to Python and while unit testing some methods on my object I noticed something 'weird'. class Ape(object): def __init__(self): print 'ooook' def say(self, s): print s def main(): Ape().say('eeek') if __name__ == '__main__': main() I wrote this little example to illustrate where I got confused. If you do Ape().say('eeek') does this actually instantiate an Ape object and run the init method? I thought it wouldn't but I had some weird side effects so now I am thinking it does?
[ "If you want to call a method directly without creating an instance you can use the staticmethod decorator. Notice that there is no self when you use a static method\nclass Ape(object):\n def __init__(self):\n print 'ooook'\n\n @staticmethod\n def say(s):\n print s\n\ndef main():\n Ape.say...
[ 14, 12, 3 ]
[]
[]
[ "python" ]
stackoverflow_0003200309_python.txt
Q: excess positional arguments, unpacking argument lists or tuples, and extended iterable unpacking This question is going to be rather long, so I apologize preemptively. In Python we can use * in the following three cases: I. When defining a function that we want to be callable with an arbitrary number of arguments, such as in this example: def write_multiple_items(file, separator, *args): file.write(separator.join(args)) In this case, the excess positional arguments are collected into a tuple. II. The reverse case is when the arguments are already in either a list or a tuple and we wish to unpack them for a function call requiring separate positional arguments, such as in this example: >>> range(3, 6) # normal call with separate arguments [3, 4, 5] >>> args = [3, 6] >>> range(*args) # call with arguments unpacked from a list [3, 4, 5] III. Starting with Python 3, * is also used in the context of extended list or tuple unpacking, such as in this example for tuples: >>> a, *b, c = range(5) >>> b [1, 2, 3] or for lists: >>> [a, *b, c] = range(5) >>> b [1, 2, 3] In both cases, all items from the iterable being unpacked that are not assigned to any of the mandatory expressions are assigned to a list. So here's the question: in case I the extra args are collected into a tuple, while in case III the extra items are assigned to a list. Whence this discrepancy? The only explanation I could find was in PEP 3132 which says that: Possible changes discussed were: [...] Make the starred target a tuple instead of a list. This would be consistent with a function's *args, but make further processing of the result harder. However, from a pedagogical perspective this lack of consistency is problematic, especially given that if you wanted to process the result, you could always say list(b) (assuming b in the above examples was a tuple). Am I missing something? A: You missed one. IV. Also, in Python 3, a bare * in the argument list marks the end of positional arguments, allowing for keyword-only arguments. def foo(a, b, *, key = None): pass This can be called foo(1, 2, key = 3) but not foo(1, 2, 3). A: In Python we can use * in the following three cases: You mean prefix * , of course -- infix * is used for multiplication. However, from a pedagogical perspective this lack of consistency is problematic, especially given that if you wanted to process the result, you could always say list(b) (assuming b in the above examples was a tuple). Am I missing something? I would say that the design problem (old and very long in the tooth!) is with the fact that when you're receiving arbitrary arguments you're getting them as a tuple, when a list would be more useful in many cases with no real downside (the tiny amount of extra processing and memory that may be needed to make a list instead of a tuple is negligible in the context of function call overhead -- or sequence unpacking, for that matter; the extra processing and memory needed to make a list as well as a tuple is really more annoying). There's very little that you can do with a tuple but not a list -- basically, just hashing it (to use as a set item or dict key) -- while a list offers much more extra functionality, and not just for purposes of altering it... methods such as count and index are also useful.
excess positional arguments, unpacking argument lists or tuples, and extended iterable unpacking
This question is going to be rather long, so I apologize preemptively. In Python we can use * in the following three cases: I. When defining a function that we want to be callable with an arbitrary number of arguments, such as in this example: def write_multiple_items(file, separator, *args): file.write(separator.join(args)) In this case, the excess positional arguments are collected into a tuple. II. The reverse case is when the arguments are already in either a list or a tuple and we wish to unpack them for a function call requiring separate positional arguments, such as in this example: >>> range(3, 6) # normal call with separate arguments [3, 4, 5] >>> args = [3, 6] >>> range(*args) # call with arguments unpacked from a list [3, 4, 5] III. Starting with Python 3, * is also used in the context of extended list or tuple unpacking, such as in this example for tuples: >>> a, *b, c = range(5) >>> b [1, 2, 3] or for lists: >>> [a, *b, c] = range(5) >>> b [1, 2, 3] In both cases, all items from the iterable being unpacked that are not assigned to any of the mandatory expressions are assigned to a list. So here's the question: in case I the extra args are collected into a tuple, while in case III the extra items are assigned to a list. Whence this discrepancy? The only explanation I could find was in PEP 3132 which says that: Possible changes discussed were: [...] Make the starred target a tuple instead of a list. This would be consistent with a function's *args, but make further processing of the result harder. However, from a pedagogical perspective this lack of consistency is problematic, especially given that if you wanted to process the result, you could always say list(b) (assuming b in the above examples was a tuple). Am I missing something?
[ "You missed one.\nIV. Also, in Python 3, a bare * in the argument list marks the end of positional arguments, allowing for keyword-only arguments.\ndef foo(a, b, *, key = None):\n pass\n\nThis can be called foo(1, 2, key = 3) but not foo(1, 2, 3).\n", "\nIn Python we can use * in the\n following three cases:\...
[ 8, 7 ]
[]
[]
[ "list", "python", "tuples" ]
stackoverflow_0003200120_list_python_tuples.txt
Q: What is the best way to get Facebook Connect going with a Django app? (Given the new data permissions.) I'm new to Django and trying to set up a Facebook connected site. There seem to be three available options at the moment: Use middleware with PyFacebook. I was able to get the django-facebookconnect app going fairly easily and mod it to suit my needs, but it is currently unclear whether PyFacebook even supports extended permissions / if PyFacebook is still even under development? Do everything with javascript. Teebes' javascript only django-facebookconnect seems promising along with reviewing the updated facebook authentication guide Roll my own Python code a la Facebook's example Can anyone point me in the right direction here? I plan to have users authenticate only through Facebook connect and then maintain dummy Django user accounts for each on the backend. Thanks! A: I plan to have users authenticate only through Facebook connect and then maintain dummy Django user accounts for each on the backend. Seems you want exactly what http://github.com/flashingpumpkin/django-socialregistration does
What is the best way to get Facebook Connect going with a Django app? (Given the new data permissions.)
I'm new to Django and trying to set up a Facebook connected site. There seem to be three available options at the moment: Use middleware with PyFacebook. I was able to get the django-facebookconnect app going fairly easily and mod it to suit my needs, but it is currently unclear whether PyFacebook even supports extended permissions / if PyFacebook is still even under development? Do everything with javascript. Teebes' javascript only django-facebookconnect seems promising along with reviewing the updated facebook authentication guide Roll my own Python code a la Facebook's example Can anyone point me in the right direction here? I plan to have users authenticate only through Facebook connect and then maintain dummy Django user accounts for each on the backend. Thanks!
[ "\nI plan to have users authenticate only through Facebook connect and then maintain dummy Django user accounts for each on the backend. \n\nSeems you want exactly what http://github.com/flashingpumpkin/django-socialregistration does\n" ]
[ 0 ]
[]
[]
[ "django", "facebook", "javascript", "python" ]
stackoverflow_0003192764_django_facebook_javascript_python.txt
Q: Getting return values from a class How would I get return values in this case. (as I would a function) class A(object): def __init__(self,a,b): self.a = a self.b = b self.run() def run(self): return a + b When I do that I get an instance, how would I get a return value? Thanks James A: Are you trying to do something like: class A(object): def __init__(self,a,b): self.a = a self.b = b def __call__(self): return self.a + self.b a = A(3, 4) a() # returns 7 It's not clear what you want and why. __init__ modifies the self object, but is required to return None (i.e. no return). Anything else will cause a TypeError. EDIT: To avoid creating an instance, you can override __new__: class A(object): def __new__(self,a,b): return A.run(a, b); @staticmethod def run(a, b): return a + b You still haven't quite explained why you need this. A: The main purpose of calling a type is to create (and return) an instance of that type -- though you may play tricks with __new__ to work around that, why, in the name of everything that matters, would you want to code a type that's intrinsically impossible to instantiate by the normal means?! Looks like you have something "clever" in mind, but, remember, "clever" is not a compliment in the Python community... rather, Python is about simplicity. Just use a function (or any other callable, e.g. an instance of a class with a __call__ method, for advanced but still quite reasonable use cases)!
Getting return values from a class
How would I get return values in this case. (as I would a function) class A(object): def __init__(self,a,b): self.a = a self.b = b self.run() def run(self): return a + b When I do that I get an instance, how would I get a return value? Thanks James
[ "Are you trying to do something like:\nclass A(object):\n def __init__(self,a,b):\n self.a = a\n self.b = b\n def __call__(self):\n return self.a + self.b\n\na = A(3, 4)\na() # returns 7\n\nIt's not clear what you want and why. __init__ modifies the self object, but is required to return...
[ 4, 1 ]
[]
[]
[ "python" ]
stackoverflow_0003199931_python.txt
Q: Keeping track of data types in Python So I hope this is a valid question... I've recently (today actually) decided to learn how a scripting language, so I chose Python. While glancing over code, I felt overwhelmed, and I soon realized that the reason was that I didn't know what data type conversions and stuff were going on. My question is: Is there any convention of keeping track of what the data type is? I come from more of a C background, so I find this quite confusing. Any tips? A: The normal Python approach is duck typing -- from the old phrase "if it quacks like a duck, and walks like a duck, it's duck enough for me". In exceptional cases where you really must check what type something is (to do different things to otherwise similar types... usually not a good idea), that's what isinstance is for. isinstance used to be considered a last-ditch measure, with serious warnings against overusing it... but while the gist of that classic tirade remains valid, since Python 2.6 it has acquired an important proviso: while checking if something is an instance of a specific concrete class remains in the "rarely a good idea" category, checking if it's an instance of an abstract base class (aka ABC) is a more frequently useful idea, because it just offers a nice and flexible way to check if something implements or not some interface. For example, to check if an object is callable, one used to have to do something like: if hasattr(type(obj), '__call__'): ... Since 2.6, the preferred alternative has become: import collections if isinstance(obj, collections.Callable): ... much more direct and cleaner. Richer ABCs such as, e.g., collections.MutableSequence, which imply the existence and coordination of many different methods, make this exponentially stronger. The fact that checking (with isinstance) the membership in a concrete type is not so good, while checking the membership in an ABC is more often useful, lies in a principle that the "Gang of 4" expressed clearly and intensely in the first part of their wonderful book "Design Patterns" (in a mostly C++ context, but it really applies much more widely than that!): program to an interface, not to an implementation. Checking membership of a concrete class indicates you're probably guilty of programming to an implementation; with an ABC, you're basically checking an interface, so many issues just aren't big problems any more (ABCs are more than just interfaces -- they can also offer "implementation help" to their concrete subclasses -- but, when we're talking about isinstance, thinking of them as interfaces is probably the most helpful stance). A: use isinstance(object, classinfo) and type(object). http://docs.python.org/library/functions.html#type http://docs.python.org/library/functions.html#isinstance
Keeping track of data types in Python
So I hope this is a valid question... I've recently (today actually) decided to learn how a scripting language, so I chose Python. While glancing over code, I felt overwhelmed, and I soon realized that the reason was that I didn't know what data type conversions and stuff were going on. My question is: Is there any convention of keeping track of what the data type is? I come from more of a C background, so I find this quite confusing. Any tips?
[ "The normal Python approach is duck typing -- from the old phrase \"if it quacks like a duck, and walks like a duck, it's duck enough for me\".\nIn exceptional cases where you really must check what type something is (to do different things to otherwise similar types... usually not a good idea), that's what isinsta...
[ 6, 0 ]
[]
[]
[ "python", "types" ]
stackoverflow_0003200683_python_types.txt
Q: "Deparsing" a list using pyparsing Is it possible to give pyparsing a parsed list and have it return the original string? A: Yes, you can if you've instructed the parser not to throw away any input. You do it with the Combine combinator. Let's say your input is: >>> s = 'abc,def, ghi' Here's a parser that grabs the exact text of the list: >>> from pyparsing import * >>> myList = Word(alphas) + ZeroOrMore(',' + Optional(White()) + Word(alphas)) >>> myList.leaveWhitespace() >>> myList.parseString(s) (['abc', ',', 'def', ',', ' ', 'ghi'], {}) To "deparse": >>> reconstitutedList = Combine(myList) >>> reconstitutedList.parseString(s) (['abc,def, ghi'], {}) which gives you the initial input back. But this comes at a cost: having all that extra whitespace floating around as tokens is usually not convenient, and you'll note that we had to explicitly turn whitespace skipping off in myList. Here's a version that strips whitespace: >>> myList = Word(alphas) + ZeroOrMore(',' + Word(alphas)) >>> myList.parseString(s) (['abc', ',', 'def', ',', 'ghi'], {}) >>> reconstitutedList = Combine(myList, adjacent=False) >>> reconstitutedList.parseString(s) (['abc,def,ghi'], {}) Note you're not getting the literal input back at this point, but this may be good enough for you. Also note we had to explicitly tell Combine to allow the skipping of whitespace. Really, though, in many cases you don't even care about the delimiters; you want the parser to focus on the items themselves. There's a function called commaSeparatedList that conveniently strips both delimiters and whitespace for you: >>> myList = commaSeparatedList >>> myList.parseString(s) (['abc', 'def', 'ghi'], {}) In this case, though, the "deparsing" step doesn't have enough information for the reconstituted string to make sense: >>> reconstitutedList = Combine(myList, adjacent=False) >>> reconstitutedList.parseString(s) (['abcdefghi'], {})
"Deparsing" a list using pyparsing
Is it possible to give pyparsing a parsed list and have it return the original string?
[ "Yes, you can if you've instructed the parser not to throw away any input. You do it with the Combine combinator.\nLet's say your input is:\n>>> s = 'abc,def, ghi'\n\nHere's a parser that grabs the exact text of the list:\n>>> from pyparsing import *\n>>> myList = Word(alphas) + ZeroOrMore(',' + Optional(White()) ...
[ 7 ]
[]
[]
[ "parsing", "pyparsing", "python" ]
stackoverflow_0003188746_parsing_pyparsing_python.txt
Q: Python lib for publishing email to web I want to read email and publish it to the web. Is there a good python library available to read email, understand headers, data, attachments etc. and which can easily convert this data to web publishable format? A: Try python email module This tutorial will also be helpful.
Python lib for publishing email to web
I want to read email and publish it to the web. Is there a good python library available to read email, understand headers, data, attachments etc. and which can easily convert this data to web publishable format?
[ "Try python email module\nThis tutorial will also be helpful.\n" ]
[ 0 ]
[]
[]
[ "email", "python" ]
stackoverflow_0003200759_email_python.txt
Q: google app engine (python) confusing class 'object has no attribute' error I have a 2 classes. One looks like this: class Feed(db.Model): bid = db.StringProperty() title = db.StringProperty() url = db.StringProperty() datecreated = db.DateProperty(auto_now_add=True) voice = db.StringProperty() lastchecked = db.DateProperty(auto_now=True) language = db.StringProperty() active = db.BooleanProperty() posts = db.ListProperty(db.Key) The other looks like this: class Post(db.Model): title = db.StringProperty() postdate = db.DateTimeProperty() author = db.StringProperty() body = db.TextProperty() link = db.LinkProperty() hasmp3 = db.BooleanProperty() mp3location = db.StringProperty() processed = db.BooleanProperty() voice = db.StringProperty() length = db.FloatProperty() inprocess = db.BooleanProperty() haspict = db.BooleanProperty() pictures = db.ListProperty(db.Key) I am trying to update a Feed by appending a Post like this: blogid = cgi.escape(self.request.get('bid')) postid = cgi.escape(self.request.get('pid')) blog = Feed.get_by_key_name(blogid) post = Post.get_by_key_name(postid) if post.key() not in blog.posts: blog.posts.append(post.key()) blog.put() When I attempt to 'put' the blog with the post information, python doesn't like it and tells me AttributeError: 'Feed' object has no attribute 'posts' The reason I am so confused is because I have nearly the exact logic in adding a 'Feed' to a 'UserClass' where the 'UserClass' has 'Feeds' designated as a ListProperty in the same way that a 'Feed' has a 'Post' designated as a ListProperty. This is an example of what I mean: class UserClass(db.Model): synccode = db.StringProperty() firstname = db.StringProperty() lastname = db.StringProperty() address = db.StringProperty() address2 = db.StringProperty() city = db.StringProperty() state = db.StringProperty() zipcode = db.StringProperty() emailaddress = db.StringProperty() password = db.StringProperty() mobile = db.StringProperty() is_authenticated = db.BooleanProperty() groupid = db.StringProperty() mobilesynched = db.BooleanProperty() devicemodel = db.StringProperty() isatmoscast = db.BooleanProperty() registerdate = db.DateProperty(auto_now_add=True) pack = db.StringProperty() personalcontact = db.BooleanProperty() lastlogin = db.DateProperty(auto_now_add=True) isactive = db.BooleanProperty() feeds = db.ListProperty(db.Key) This works fine: if blog.key() not in user.feeds: user.feeds.append(blog.key()) user.put() This throws the error: if post.key() not in blog.posts: blog.posts.append(post.key()) blog.put() Any help would be appreciated. A: I've pasted your models in a "hello world" main.py; then running it on the local SDK, I enter on the interactive console: import main as m p = m.Post() p.put() f = m.Feed() f.put() if p.key() not in f.posts: f.posts.append(p.key()) f.put() print f.posts and I see, just as expected, in the results window to the right: [datastore_types.Key.from_path(u'Post', 7, _app=u'helow')] In other words, it seems impossible to reproduce the problem you report in a simple case. Please make a showstheproblem.py, as simple as possible (i.e., no code that's not indispensable to reproduce the problem!), that shows the problem, and edit your question to add that code (minus the models, we've already seen those and of course the vast majority of their fields is utterly irrelevant to this problem). This is always the right way to go about reporting a suspected bug or getting help with it; more often than not, you'll find that in the process of whittling down a copy of your code in order to get the "minimum possible reproduction of the problem"... the problem disappears in a way that shows you what was wrong with your code in the first place -- so you won't actually even have to ask for help about, or report, the non-existent bug in the library!-)
google app engine (python) confusing class 'object has no attribute' error
I have a 2 classes. One looks like this: class Feed(db.Model): bid = db.StringProperty() title = db.StringProperty() url = db.StringProperty() datecreated = db.DateProperty(auto_now_add=True) voice = db.StringProperty() lastchecked = db.DateProperty(auto_now=True) language = db.StringProperty() active = db.BooleanProperty() posts = db.ListProperty(db.Key) The other looks like this: class Post(db.Model): title = db.StringProperty() postdate = db.DateTimeProperty() author = db.StringProperty() body = db.TextProperty() link = db.LinkProperty() hasmp3 = db.BooleanProperty() mp3location = db.StringProperty() processed = db.BooleanProperty() voice = db.StringProperty() length = db.FloatProperty() inprocess = db.BooleanProperty() haspict = db.BooleanProperty() pictures = db.ListProperty(db.Key) I am trying to update a Feed by appending a Post like this: blogid = cgi.escape(self.request.get('bid')) postid = cgi.escape(self.request.get('pid')) blog = Feed.get_by_key_name(blogid) post = Post.get_by_key_name(postid) if post.key() not in blog.posts: blog.posts.append(post.key()) blog.put() When I attempt to 'put' the blog with the post information, python doesn't like it and tells me AttributeError: 'Feed' object has no attribute 'posts' The reason I am so confused is because I have nearly the exact logic in adding a 'Feed' to a 'UserClass' where the 'UserClass' has 'Feeds' designated as a ListProperty in the same way that a 'Feed' has a 'Post' designated as a ListProperty. This is an example of what I mean: class UserClass(db.Model): synccode = db.StringProperty() firstname = db.StringProperty() lastname = db.StringProperty() address = db.StringProperty() address2 = db.StringProperty() city = db.StringProperty() state = db.StringProperty() zipcode = db.StringProperty() emailaddress = db.StringProperty() password = db.StringProperty() mobile = db.StringProperty() is_authenticated = db.BooleanProperty() groupid = db.StringProperty() mobilesynched = db.BooleanProperty() devicemodel = db.StringProperty() isatmoscast = db.BooleanProperty() registerdate = db.DateProperty(auto_now_add=True) pack = db.StringProperty() personalcontact = db.BooleanProperty() lastlogin = db.DateProperty(auto_now_add=True) isactive = db.BooleanProperty() feeds = db.ListProperty(db.Key) This works fine: if blog.key() not in user.feeds: user.feeds.append(blog.key()) user.put() This throws the error: if post.key() not in blog.posts: blog.posts.append(post.key()) blog.put() Any help would be appreciated.
[ "I've pasted your models in a \"hello world\" main.py; then running it on the local SDK, I enter on the interactive console:\nimport main as m\n\np = m.Post()\np.put()\nf = m.Feed()\nf.put()\n\nif p.key() not in f.posts:\n f.posts.append(p.key())\n f.put()\n\nprint f.posts\n\nand I see, just as expected, in t...
[ 5 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0003199408_google_app_engine_python.txt
Q: Reading files to list of strings in Python When you use the fileName.readlines() function in Python, is there a symbol for the end of the file that is included in the list? For example, if the file is read into a list of strings and the last line is 'End', will there be another place in the list with a symbol indicating the end of the file? Thanks. A: No, the list contains one element for each line in the file. You can do something with each line in a for look like this: lines = infile.readlines() for line in lines: # Do something with this line process(line) Python has a shorter way of accomplishing this that avoids reading the whole file into memory at once for line in infile: # Do something with this line process(line) If you just want the last line of the file lines = infile.readlines() last_line = lines[-1] Why do you think you need a special symbol at the end? A: The list returned by .readlines(), like any other Python list, has no "end" marker -- assumin e.g. you start with L = myfile.readlines(), you can see how many items L has with len(L), get the last one with L[-1], loop over all items one after the other with for item in L:, and so forth ... again -- just like any other list. If for some peculiar reason you want, after the last line, some special "sentinel" value, you could for example do L.append('') to add just such a sentinel, or marker -- the empty string is never going to be the value of any other line (since each item is a complete line including the trailing '\n', so it will never be an empty string!). You could use other arbitrary markers, such as None, but often it's simpler, when feasible [[and it's obviously feasible in this case, as I've just shown]], if the sentinel is of exactly the same type as any other item. That depends on what processing you're doing that needs a past-the-end "sentinel" (I'm not going to guess because you give us no indication, and only relatively rare problems are best solved that way in Python, anyway;-), but in almost every conceivable case of sentinel use a '' sentinel will be just fine. A: It simply returns a list containing each line -- there's no "EOF" item in the list.
Reading files to list of strings in Python
When you use the fileName.readlines() function in Python, is there a symbol for the end of the file that is included in the list? For example, if the file is read into a list of strings and the last line is 'End', will there be another place in the list with a symbol indicating the end of the file? Thanks.
[ "No, the list contains one element for each line in the file.\nYou can do something with each line in a for look like this:\nlines = infile.readlines()\nfor line in lines:\n # Do something with this line\n process(line)\n\nPython has a shorter way of accomplishing this that avoids reading the whole file into ...
[ 5, 1, 0 ]
[]
[]
[ "file", "list", "python" ]
stackoverflow_0003199363_file_list_python.txt
Q: to merge two columns in a csv file merge two columns in a csv file A: Here is an example, dont know your delimiter. if you want to write it to the same file you have to buffer the whole file first, modify the rows, then write it back to the same file. import csv for row in csv.reader(open('test.txt'),delimiter="\t"): print row[0]+row[1] A: fin = open('file.csv', 'r+') fout = open('NEW.csv','w') for line in fin.xreadlines(): new = line.replace(',', ' ', 1) fout.write (new) fin.close() fout.close() Assuming that "file.csv" is the input, and "NEW.csv" is the output. Also the first comma is getting replaced by space. You can alter that by modifying new = line.replace(',', ' ', 1) and replacing the second argument with anything you want
to merge two columns in a csv file
merge two columns in a csv file
[ "Here is an example, dont know your delimiter. if you want to write it to the same file you have to buffer the whole file first, modify the rows, then write it back to the same file.\n import csv\n for row in csv.reader(open('test.txt'),delimiter=\"\\t\"):\n print row[0]+row[1]\n\n", " fin = open('file.csv...
[ 3, 0 ]
[]
[]
[ "csv", "python" ]
stackoverflow_0003200857_csv_python.txt
Q: How does the decimal accuracy of Python compare to that of C? I was looking at the Golden Ratio formula for finding the nth Fibonacci number, and it made me curious. I know Python handles arbitrarily large integers, but what sort of precision do you get with decimals? Is it just straight on top of a C double or something, or does it use a a more accurate modified implementation too? (Obviously not with arbitrary accuracy. ;D) A: almost all platforms map Python floats to IEEE-754 “double precision”. http://docs.python.org/tutorial/floatingpoint.html#representation-error there's also the decimal module for arbitrary precision floating point math A: Python floats use the double type of the underlying C compiler. As Bwmat says, this is generally IEEE-754 double precision. However if you need more precision than that you can use the Python decimal module which was added in Python 2.4. Python 2.6 also added the fraction module which may be a better fit for some problems. Both of these are going to be slower than using the float type, but that is the price for more precision.
How does the decimal accuracy of Python compare to that of C?
I was looking at the Golden Ratio formula for finding the nth Fibonacci number, and it made me curious. I know Python handles arbitrarily large integers, but what sort of precision do you get with decimals? Is it just straight on top of a C double or something, or does it use a a more accurate modified implementation too? (Obviously not with arbitrary accuracy. ;D)
[ "almost all platforms map Python floats to IEEE-754 “double precision”.\nhttp://docs.python.org/tutorial/floatingpoint.html#representation-error\nthere's also the decimal module for arbitrary precision floating point math\n", "Python floats use the double type of the underlying C compiler. As Bwmat says, this is...
[ 3, 2 ]
[]
[]
[ "c", "floating_accuracy", "language_implementation", "programming_languages", "python" ]
stackoverflow_0003201319_c_floating_accuracy_language_implementation_programming_languages_python.txt
Q: Faster Deserialization in Python What do you think is the fastest deserialization method? Pickle? YAML? or JSONPickle? A: I'd imagine cPickle would be the fastest method of serialisation, though it's just an (educated) guess. It's written in pure C, with Python bindings, and uses a binary format for storing objects, thus should be pretty fast!
Faster Deserialization in Python
What do you think is the fastest deserialization method? Pickle? YAML? or JSONPickle?
[ "I'd imagine cPickle would be the fastest method of serialisation, though it's just an (educated) guess. It's written in pure C, with Python bindings, and uses a binary format for storing objects, thus should be pretty fast!\n" ]
[ 1 ]
[]
[]
[ "python", "serialization" ]
stackoverflow_0003201545_python_serialization.txt
Q: what's a good module for writing an http web service interface for a daemon? To give a little background, I'm writing (or am going to write) a daemon in Python for scheduling tasks to run at user-specified dates. The scheduler daemon also needs to have a JSON-based HTTP web service interface (buzzword mania, I know) for adding tasks to the queue and monitoring the scheduler's status. The interface needs to receive requests while the daemon is running, so they either need to run in a separate thread or cooperatively multitask somehow. Ideally the web service interface should run in the same process as the daemon, too. I could think of a few ways to do it, but I'm wondering if there's some obvious module out there that's specifically tailored for this kind of thing. Any suggestions about what to use, or about the project in general are quite welcome. Thanks! :) A: Check out the class BaseHTTPServer -- a "Basic HTTP server" bundled with Python. http://docs.python.org/library/basehttpserver.html You can spin up a second thread and have it serve your requests for you very easily (probably < 30 lines of code). And it all runs in the same process and Python interpreter space, so it can access all your objects, etc. A: I'm not sure I understand your question properly, but take a look at Twisted A: Don't re-invent the bicycle! Run jobs via cron script, and create a separate web interface using, for example, Django or Tornado. Connect them via a database. Even sqlite will do the job if you don't want to scale on more machines. A: I believed all kinds of python web framework is useful. You can pick up one like CherryPy, which is small enough to integrate into your system. Also CherryPy includes a pure python WSGI server for production. Also the performance may not be as good as apache, but it's already very stable.
what's a good module for writing an http web service interface for a daemon?
To give a little background, I'm writing (or am going to write) a daemon in Python for scheduling tasks to run at user-specified dates. The scheduler daemon also needs to have a JSON-based HTTP web service interface (buzzword mania, I know) for adding tasks to the queue and monitoring the scheduler's status. The interface needs to receive requests while the daemon is running, so they either need to run in a separate thread or cooperatively multitask somehow. Ideally the web service interface should run in the same process as the daemon, too. I could think of a few ways to do it, but I'm wondering if there's some obvious module out there that's specifically tailored for this kind of thing. Any suggestions about what to use, or about the project in general are quite welcome. Thanks! :)
[ "Check out the class BaseHTTPServer -- a \"Basic HTTP server\" bundled with Python.\nhttp://docs.python.org/library/basehttpserver.html\nYou can spin up a second thread and have it serve your requests for you very easily (probably < 30 lines of code). And it all runs in the same process and Python interpreter spac...
[ 1, 0, 0, 0 ]
[]
[]
[ "python", "web_services" ]
stackoverflow_0003201446_python_web_services.txt
Q: How to get the point in time of (last) vertical retrace under Python? I am using Pygame to pageflip different stimuli on the screen. The problem is that pygame's flip function, although syncing the flip to the vertical retrace, does not tell me when the retrace was. Does anyone know of a way to get this information (preferably platform independent) in Python? Regards, fladd A: Just poll for the time immediately after the flip call, if that one syncs to the vertical retrace.
How to get the point in time of (last) vertical retrace under Python?
I am using Pygame to pageflip different stimuli on the screen. The problem is that pygame's flip function, although syncing the flip to the vertical retrace, does not tell me when the retrace was. Does anyone know of a way to get this information (preferably platform independent) in Python? Regards, fladd
[ "Just poll for the time immediately after the flip call, if that one syncs to the vertical retrace.\n" ]
[ 0 ]
[]
[]
[ "flip", "pygame", "python" ]
stackoverflow_0003201685_flip_pygame_python.txt
Q: Kick off daemonized service using djangos manage.py custom command? I got a custom command in my reusable django app which I want to kick off a daemonized service and then return, leaving the service running. I've implemented my service as a simple class with a start-method. When start is called it runs in an eternal loop, sleeping for 10 seconds, then using the django orm to check the database configured in the projects settings.py file, checks for entries in a given folder. I want to be able to: ./manage.py startservice which kicks of my service and returns. Then in the same shell: ./manage.py runserver and start adding entries in a specific database table which within 5 seconds are picked up by the service running in the background and processed. I've looked at celery for a more message-queue-based approach, but it relies on too much other stuff. It's important that the whole thing follows django's reusable app pattern. Any hints or thoughts? A: I have the beginnings of a library, django-initd, to handle this: see the project on GitHub. Django actually includes a utility for a process to daemonize itself, in django.utils.daemonize, my library takes care of the startup/shutdown, logging, and interaction with the management command. I'd be interested to know if it's helpful for you. A: Why do you want to start service as a separte process? Run in a Thread, in the same process as runserver.
Kick off daemonized service using djangos manage.py custom command?
I got a custom command in my reusable django app which I want to kick off a daemonized service and then return, leaving the service running. I've implemented my service as a simple class with a start-method. When start is called it runs in an eternal loop, sleeping for 10 seconds, then using the django orm to check the database configured in the projects settings.py file, checks for entries in a given folder. I want to be able to: ./manage.py startservice which kicks of my service and returns. Then in the same shell: ./manage.py runserver and start adding entries in a specific database table which within 5 seconds are picked up by the service running in the background and processed. I've looked at celery for a more message-queue-based approach, but it relies on too much other stuff. It's important that the whole thing follows django's reusable app pattern. Any hints or thoughts?
[ "I have the beginnings of a library, django-initd, to handle this: see the project on GitHub. \nDjango actually includes a utility for a process to daemonize itself, in django.utils.daemonize, my library takes care of the startup/shutdown, logging, and interaction with the management command. I'd be interested to k...
[ 2, 0 ]
[]
[]
[ "command", "django", "python", "service" ]
stackoverflow_0003201799_command_django_python_service.txt
Q: Mod_python on django and debug variable I have a problem with my django application. On django developer server its work perfect, but when I switch it to apache something strange happening. Lets check the code: class Criteria(models.Model): district = models.ManyToManyField(District, verbose_name=u"Województwo", blank=True) respondents = models.ManyToManyField(User, verbose_name=u"Respondenci") def getData(self): # return self.district.all() - good return self.respondents.all() # error When I set in settings.py debug variable to true (DEBUG=True) nothing bad happens. But when I switch it to false (DEBUG=False) I get an error when I call that method. MOD_PYTHON ERROR ProcessId: 19463 Interpreter: 'www.panelbadawczy.pl' ServerName: 'www.panelbadawczy.pl' DocumentRoot: '/htdocs' URI: '/edytuj-badanie,3/ustal-kryteria/' Location: None Directory: None Filename: '/htdocs' PathInfo: '/edytuj-badanie,3/ustal-kryteria/' Phase: 'PythonHandler' Handler: 'django.core.handlers.modpython' Traceback (most recent call last): File "/usr/lib/python2.6/site-packages/mod_python/importer.py", line 1537, in HandlerDispatch default=default_handler, arg=req, silent=hlist.silent) File "/usr/lib/python2.6/site-packages/mod_python/importer.py", line 1229, in _process_target result = _execute_target(config, req, object, arg) File "/usr/lib/python2.6/site-packages/mod_python/importer.py", line 1128, in _execute_target result = object(arg) File "/usr/lib/python2.6/site-packages/django/core/handlers/modpython.py", line 228, in handler return ModPythonHandler()(req) File "/usr/lib/python2.6/site-packages/django/core/handlers/modpython.py", line 201, in __call__ response = self.get_response(request) File "/usr/lib/python2.6/site-packages/django/core/handlers/base.py", line 134, in get_response return self.handle_uncaught_exception(request, resolver, exc_info) File "/usr/lib/python2.6/site-packages/django/core/handlers/base.py", line 166, in handle_uncaught_exception return callback(request, **param_dict) File "/usr/lib/python2.6/site-packages/django/views/defaults.py", line 24, in server_error return http.HttpResponseServerError(t.render(Context({}))) File "/usr/lib/python2.6/site-packages/django/template/__init__.py", line 178, in render return self.nodelist.render(context) File "/usr/lib/python2.6/site-packages/django/template/__init__.py", line 779, in render bits.append(self.render_node(node, context)) File "/usr/lib/python2.6/site-packages/django/template/__init__.py", line 792, in render_node return node.render(context) File "/usr/lib/python2.6/site-packages/django/template/loader_tags.py", line 97, in render return compiled_parent.render(context) File "/usr/lib/python2.6/site-packages/django/template/__init__.py", line 178, in render return self.nodelist.render(context) File "/usr/lib/python2.6/site-packages/django/template/__init__.py", line 779, in render bits.append(self.render_node(node, context)) File "/usr/lib/python2.6/site-packages/django/template/__init__.py", line 792, in render_node return node.render(context) File "/usr/lib/python2.6/site-packages/django/template/loader_tags.py", line 24, in render result = self.nodelist.render(context) File "/usr/lib/python2.6/site-packages/django/template/__init__.py", line 779, in render bits.append(self.render_node(node, context)) File "/usr/lib/python2.6/site-packages/django/template/__init__.py", line 792, in render_node return node.render(context) File "/usr/lib/python2.6/site-packages/django/template/__init__.py", line 930, in render resolved_vars = [var.resolve(context) for var in self.vars_to_resolve] File "/usr/lib/python2.6/site-packages/django/template/__init__.py", line 687, in resolve value = self._resolve_lookup(context) File "/usr/lib/python2.6/site-packages/django/template/__init__.py", line 740, in _resolve_lookup raise VariableDoesNotExist("Failed lookup for key [%s] in %r", (bit, current)) # missing attribute VariableDoesNotExist: Failed lookup for key [user] in u"[{'block': <Block Node: loginBox. Contents: [<Text Node: '\r\n '>, <django.template.InclusionNode object at 0x91a002c>, <Text Node: '\r\n\t\t\t'>]>}, {}]" Any ideas ? A: I would look into this block node "loginBox" and the required parameter 'user' if I were you.
Mod_python on django and debug variable
I have a problem with my django application. On django developer server its work perfect, but when I switch it to apache something strange happening. Lets check the code: class Criteria(models.Model): district = models.ManyToManyField(District, verbose_name=u"Województwo", blank=True) respondents = models.ManyToManyField(User, verbose_name=u"Respondenci") def getData(self): # return self.district.all() - good return self.respondents.all() # error When I set in settings.py debug variable to true (DEBUG=True) nothing bad happens. But when I switch it to false (DEBUG=False) I get an error when I call that method. MOD_PYTHON ERROR ProcessId: 19463 Interpreter: 'www.panelbadawczy.pl' ServerName: 'www.panelbadawczy.pl' DocumentRoot: '/htdocs' URI: '/edytuj-badanie,3/ustal-kryteria/' Location: None Directory: None Filename: '/htdocs' PathInfo: '/edytuj-badanie,3/ustal-kryteria/' Phase: 'PythonHandler' Handler: 'django.core.handlers.modpython' Traceback (most recent call last): File "/usr/lib/python2.6/site-packages/mod_python/importer.py", line 1537, in HandlerDispatch default=default_handler, arg=req, silent=hlist.silent) File "/usr/lib/python2.6/site-packages/mod_python/importer.py", line 1229, in _process_target result = _execute_target(config, req, object, arg) File "/usr/lib/python2.6/site-packages/mod_python/importer.py", line 1128, in _execute_target result = object(arg) File "/usr/lib/python2.6/site-packages/django/core/handlers/modpython.py", line 228, in handler return ModPythonHandler()(req) File "/usr/lib/python2.6/site-packages/django/core/handlers/modpython.py", line 201, in __call__ response = self.get_response(request) File "/usr/lib/python2.6/site-packages/django/core/handlers/base.py", line 134, in get_response return self.handle_uncaught_exception(request, resolver, exc_info) File "/usr/lib/python2.6/site-packages/django/core/handlers/base.py", line 166, in handle_uncaught_exception return callback(request, **param_dict) File "/usr/lib/python2.6/site-packages/django/views/defaults.py", line 24, in server_error return http.HttpResponseServerError(t.render(Context({}))) File "/usr/lib/python2.6/site-packages/django/template/__init__.py", line 178, in render return self.nodelist.render(context) File "/usr/lib/python2.6/site-packages/django/template/__init__.py", line 779, in render bits.append(self.render_node(node, context)) File "/usr/lib/python2.6/site-packages/django/template/__init__.py", line 792, in render_node return node.render(context) File "/usr/lib/python2.6/site-packages/django/template/loader_tags.py", line 97, in render return compiled_parent.render(context) File "/usr/lib/python2.6/site-packages/django/template/__init__.py", line 178, in render return self.nodelist.render(context) File "/usr/lib/python2.6/site-packages/django/template/__init__.py", line 779, in render bits.append(self.render_node(node, context)) File "/usr/lib/python2.6/site-packages/django/template/__init__.py", line 792, in render_node return node.render(context) File "/usr/lib/python2.6/site-packages/django/template/loader_tags.py", line 24, in render result = self.nodelist.render(context) File "/usr/lib/python2.6/site-packages/django/template/__init__.py", line 779, in render bits.append(self.render_node(node, context)) File "/usr/lib/python2.6/site-packages/django/template/__init__.py", line 792, in render_node return node.render(context) File "/usr/lib/python2.6/site-packages/django/template/__init__.py", line 930, in render resolved_vars = [var.resolve(context) for var in self.vars_to_resolve] File "/usr/lib/python2.6/site-packages/django/template/__init__.py", line 687, in resolve value = self._resolve_lookup(context) File "/usr/lib/python2.6/site-packages/django/template/__init__.py", line 740, in _resolve_lookup raise VariableDoesNotExist("Failed lookup for key [%s] in %r", (bit, current)) # missing attribute VariableDoesNotExist: Failed lookup for key [user] in u"[{'block': <Block Node: loginBox. Contents: [<Text Node: '\r\n '>, <django.template.InclusionNode object at 0x91a002c>, <Text Node: '\r\n\t\t\t'>]>}, {}]" Any ideas ?
[ "I would look into this block node \"loginBox\" and the required parameter 'user' if I were you.\n" ]
[ 0 ]
[]
[]
[ "apache2", "django", "mod_python", "python" ]
stackoverflow_0003198916_apache2_django_mod_python_python.txt
Q: BeautifulSoup get innerhtml data I am trying to read data from a website. I can see the value I need but the value does not appear in the downloaded html code (using urllib2). The value is created by some js file and embedded into the webpage as innerhtml for that id. PS: How can that be extracted? raw source code cannot render js unlike the browsers! A: Another way of getting data is leaving the browser do all the stuff using Selenium and read the rendered html. A bit slow but surely effective. Here you can find a getting started guide for using Selenium with Python: http://jimmyg.org/blog/2009/getting-started-with-selenium-and-python.html A: You have two options: Have the browser save the DOM (this includes all changes made by scripts) or use a JavaScript engine to execute the embedded scripts. For the latter route, try a Java based engine like Rhino and emulate the browser with env.js.
BeautifulSoup get innerhtml data
I am trying to read data from a website. I can see the value I need but the value does not appear in the downloaded html code (using urllib2). The value is created by some js file and embedded into the webpage as innerhtml for that id. PS: How can that be extracted? raw source code cannot render js unlike the browsers!
[ "Another way of getting data is leaving the browser do all the stuff using Selenium and read the rendered html. A bit slow but surely effective.\nHere you can find a getting started guide for using Selenium with Python:\nhttp://jimmyg.org/blog/2009/getting-started-with-selenium-and-python.html\n", "You have two o...
[ 4, 1 ]
[]
[]
[ "beautifulsoup", "innerhtml", "javascript", "python", "urllib2" ]
stackoverflow_0003201824_beautifulsoup_innerhtml_javascript_python_urllib2.txt
Q: Django: Saving an image file from a form I want to save the image which as been uploaded via the PaletteGenForm as such: #Form class PaletteGenForm(forms.Form): im = forms.ImageField(required=True) #View def palette_gen_view(request): PATH_OF_IMAGE_TO_BE_PALETTED= MEDIA_ROOT+ "/tobesaved.png" if request.method == 'POST': form = PaletteGenForm(request.POST, request.FILES) if form.is_valid(): im = Image.open(StringIO(request.FILES['im']['content'])) im.save(PATH_OF_IMAGE_TO_BE_PALETTED, "PNG") #call some functions to generate pallete return #returns the palette of the image. else: form = PaletteGenForm() return render_to_response('palette_generate.html', {'form': form,}) However here is my error when calling this URL: 'InMemoryUploadedFile' object is unsubscriptable A: Try this: im = Image.open(StringIO(request.FILES['im'].read())) A: Not sure you need to wrap it in a StringIO at all. Try im = Image.open(request.FILES['im']['content']) A: try reading the data from form cleaned_data im = Image.open(StringIO(form.cleaned_data['im'].read())) for me this worked (didn't tried reading from the request)
Django: Saving an image file from a form
I want to save the image which as been uploaded via the PaletteGenForm as such: #Form class PaletteGenForm(forms.Form): im = forms.ImageField(required=True) #View def palette_gen_view(request): PATH_OF_IMAGE_TO_BE_PALETTED= MEDIA_ROOT+ "/tobesaved.png" if request.method == 'POST': form = PaletteGenForm(request.POST, request.FILES) if form.is_valid(): im = Image.open(StringIO(request.FILES['im']['content'])) im.save(PATH_OF_IMAGE_TO_BE_PALETTED, "PNG") #call some functions to generate pallete return #returns the palette of the image. else: form = PaletteGenForm() return render_to_response('palette_generate.html', {'form': form,}) However here is my error when calling this URL: 'InMemoryUploadedFile' object is unsubscriptable
[ "Try this:\nim = Image.open(StringIO(request.FILES['im'].read()))\n\n", "Not sure you need to wrap it in a StringIO at all. Try\nim = Image.open(request.FILES['im']['content'])\n\n", "try reading the data from form cleaned_data\nim = Image.open(StringIO(form.cleaned_data['im'].read()))\n\nfor me this worked (di...
[ 4, 1, 0 ]
[]
[]
[ "django", "django_forms", "django_views", "python" ]
stackoverflow_0003201777_django_django_forms_django_views_python.txt
Q: Django - Selecting related set : how many times does it hit the database? I took this sample code here : Django ORM: Selecting related set polls = Poll.objects.filter(category='foo') choices = Choice.objects.filter(poll__in=polls) My question is very simple : do you hit twice the database when you finally use the queryset choices ? A: It will be one query, but containing an inner SELECT; if you want to do some debugging on that, you could either use the marvellous django-debug-toolbar, or do something like print str(choices.query) which will output the raw sql of your query!
Django - Selecting related set : how many times does it hit the database?
I took this sample code here : Django ORM: Selecting related set polls = Poll.objects.filter(category='foo') choices = Choice.objects.filter(poll__in=polls) My question is very simple : do you hit twice the database when you finally use the queryset choices ?
[ "It will be one query, but containing an inner SELECT; if you want to do some debugging on that, you could either use the marvellous django-debug-toolbar, or do something like print str(choices.query) which will output the raw sql of your query!\n" ]
[ 1 ]
[]
[]
[ "django", "django_orm", "performance", "python" ]
stackoverflow_0003202186_django_django_orm_performance_python.txt
Q: Insert inline image into Lotus Notes message I've been able to send emails using Lotus Notes and VBA and Python using the COM API like this: Can I use Lotus Notes to send mail? My question is how can I insert an image inline with the body text (not as an attachment) in a programmatic way (equivalent to the Edit | Paste Special)? I haven't been able to find any workable solutions from a few Google searches. Any solution using stock VBA or Python would be appreciated. Thanks! A: It should be possible to do this using the DXLImporter class, available from VBA through the COM interface. DXL is a Notes-specific XML, which you can generate to a temp file, then import into your database. There is sample code on this blog entry, which may be close to what you are looking for (this imports a rich-text body, including in-line image, and then attaches that rich text to a mail document). http://www.cubetoon.com/2008/notes-rich-text-manipulation-using-dxl/ Other options you might consider are: (1) using the C or C++ API's - definitely more effort, especially when working with rich-text, but would essentially have no limits. (http://www.ibm.com/developerworks/lotus/library/capi-nd/index.html) (2) using the MIDAS Toolkit from Genii (http://www.geniisoft.com) - extends the Lotuscript API's and exposes much of what is in the C API. A: If you don't need to do anything specific to Notes, i.e. work with a specific form with @functions etc, then you are much better off constructing the message as a multipart mime message. You need to set up the session so that when you create the document it is mime and you can then set up your message appropriately, see NotesSession.ConvertMIME. You will then use NotesMIMEEntity and NotesMIMEHeader objects to construct the mime message. If you are unfamiliar with how mime messages are constructed then this is going to be a little tricky, so you may want to have a look at some raw mime messages to see what they look like. From there you should be able to work out how to use the api for the NotesMIMEEntity and NotesMIMEHeader classes to construct the message.
Insert inline image into Lotus Notes message
I've been able to send emails using Lotus Notes and VBA and Python using the COM API like this: Can I use Lotus Notes to send mail? My question is how can I insert an image inline with the body text (not as an attachment) in a programmatic way (equivalent to the Edit | Paste Special)? I haven't been able to find any workable solutions from a few Google searches. Any solution using stock VBA or Python would be appreciated. Thanks!
[ "It should be possible to do this using the DXLImporter class, available from VBA through the COM interface. DXL is a Notes-specific XML, which you can generate to a temp file, then import into your database. There is sample code on this blog entry, which may be close to what you are looking for (this imports a ric...
[ 1, 1 ]
[]
[]
[ "lotus_notes", "python", "vba" ]
stackoverflow_0003189622_lotus_notes_python_vba.txt
Q: What's the best way to store quickly-changing data in Python? On a quest to learn a bit about Python and sockets I'm writing a little 2d-game server. And although I don't see more than a few people on this server at any given time, I want to write it as efficiently as I can. I have a global dictionary called "globuser", in it is another dictionary containing the user stats (like the X & Y coordinates) Is that the best way to store them? How big can a dictionary get? I guess you could also try to use a regular database, but that would be insanely slow. Or should I use an entirely different scheme? Can multiple threads access the same variable at the same time, or are they put on hold? I guess when lots of users are on-line, every move would require an update. If they can happen at the same time, great! But if they each require to "lock" the variable, that would be less great. A: One thing I might look at is storing the users as a list of Player objects. Look into __slots__, as that will save you memory when creating many instances. I also would not worry much about performance at this stage. Write the code first and then run it through a profiler to find out where it is slowest -- making blind changes in the name of optimization is bad juju. Regarding thread safety and sharing of data, I found this, which seems to give some info on the subject. A: Use multiprocessing instead of threading . Its has lots of advantage and one of advantage is to handling global storage for all process. This module use global dictionary which is initiated by manager. Here is sample example taken from PyMOTW The Manager is responsible for coordinating shared information state between all of its users. By creating the list through the manager, the list is updated in all processes when anyone modifies it. In addition to lists, dictionaries are also supported. import multiprocessing def worker(d, key, value): d[key] = value if __name__ == '__main__': mgr = multiprocessing.Manager() d = mgr.dict() jobs = [ multiprocessing.Process(target=worker, args=(d, i, i*2)) for i in range(10) ] for j in jobs: j.start() for j in jobs: j.join() print 'Results:', d $ python multiprocessing_manager_dict.py Results: {0: 0, 1: 2, 2: 4, 3: 6, 4: 8, 5: 10, 6: 12, 7: 14, 8: 16, 9: 18} Namespaces In addition to dictionaries and lists, a Manager can create a shared Namespace. Any named value added to the Namespace is visible across all of the clients. import multiprocessing def producer(ns, event): ns.value = 'This is the value' event.set() def consumer(ns, event): try: value = ns.value except Exception, err: print 'Before event, consumer got:', str(err) event.wait() print 'After event, consumer got:', ns.value if __name__ == '__main__': mgr = multiprocessing.Manager() namespace = mgr.Namespace() event = multiprocessing.Event() p = multiprocessing.Process(target=producer, args=(namespace, event)) c = multiprocessing.Process(target=consumer, args=(namespace, event)) c.start() p.start() c.join() p.join() $ python multiprocessing_namespaces.py Before event, consumer got: 'Namespace' object has no attribute 'value' After event, consumer got: This is the value
What's the best way to store quickly-changing data in Python?
On a quest to learn a bit about Python and sockets I'm writing a little 2d-game server. And although I don't see more than a few people on this server at any given time, I want to write it as efficiently as I can. I have a global dictionary called "globuser", in it is another dictionary containing the user stats (like the X & Y coordinates) Is that the best way to store them? How big can a dictionary get? I guess you could also try to use a regular database, but that would be insanely slow. Or should I use an entirely different scheme? Can multiple threads access the same variable at the same time, or are they put on hold? I guess when lots of users are on-line, every move would require an update. If they can happen at the same time, great! But if they each require to "lock" the variable, that would be less great.
[ "One thing I might look at is storing the users as a list of Player objects. Look into __slots__, as that will save you memory when creating many instances.\nI also would not worry much about performance at this stage. Write the code first and then run it through a profiler to find out where it is slowest -- making...
[ 3, 2 ]
[]
[]
[ "python", "variables" ]
stackoverflow_0003202376_python_variables.txt
Q: Good practices for a flexible search page - Django I'm just wondering if there is any example I could take from others on the topic. I have a page within Django which uses filters, in order to perform searches. At the moment I'm doing a simple check for the GET parameters and adding a .filter() to a queryset accordingly: if color: query.filter(color=color) This feels a bit like an ugly way to do, and I've been a bit stuck wondering how I could make it more dynamic. Any ideas? A: Try this: ALLOWED = ('color', 'size', 'model') kwargs = dict( (key, value) for key, value in request.GET.items() if key in ALLOWED ) query.filter(**kwargs) This will allow you to make requests like this /search/?color=red&size=1 or /search/?model=Nikon&color=black.
Good practices for a flexible search page - Django
I'm just wondering if there is any example I could take from others on the topic. I have a page within Django which uses filters, in order to perform searches. At the moment I'm doing a simple check for the GET parameters and adding a .filter() to a queryset accordingly: if color: query.filter(color=color) This feels a bit like an ugly way to do, and I've been a bit stuck wondering how I could make it more dynamic. Any ideas?
[ "Try this:\nALLOWED = ('color', 'size', 'model')\nkwargs = dict(\n (key, value)\n for key, value in request.GET.items()\n if key in ALLOWED\n)\nquery.filter(**kwargs)\n\nThis will allow you to make requests like this /search/?color=red&size=1 or /search/?model=Nikon&color=black.\n" ]
[ 5 ]
[]
[]
[ "django", "django_models", "django_queryset", "filter", "python" ]
stackoverflow_0003202922_django_django_models_django_queryset_filter_python.txt
Q: Images are not being stored?? - Django These are my following settings: MEDIA_ROOT = '/home/webapps/test_project/media/' MEDIA_URL = 'http://192.168.0.2:8090/site_media/' ADMIN_MEDIA_PREFIX = '/media/' These are my model fields: large = models.ImageField(blank=True, null=True, upload_to="images") thumb = models.ImageField(blank=True, null=True, upload_to="images") What happens is... when I save a model with the images, the paths to the images are stored but not the actual images. http://192.168.0.2:8090/site_media/images/BluUnicorn.png http://192.168.0.2:8090/site_media/images/DarkNinja.png ... Django behaves as if the images have been saved succesfully under the images folder, but the images are not actually there!! Anyone have a clue of what I did wrong? PS: I'm using Django 2.1+ SVN A: Mistyped MEDIA_ROOT = '/home/webapps/test_project/media/' wrote home instead of root
Images are not being stored?? - Django
These are my following settings: MEDIA_ROOT = '/home/webapps/test_project/media/' MEDIA_URL = 'http://192.168.0.2:8090/site_media/' ADMIN_MEDIA_PREFIX = '/media/' These are my model fields: large = models.ImageField(blank=True, null=True, upload_to="images") thumb = models.ImageField(blank=True, null=True, upload_to="images") What happens is... when I save a model with the images, the paths to the images are stored but not the actual images. http://192.168.0.2:8090/site_media/images/BluUnicorn.png http://192.168.0.2:8090/site_media/images/DarkNinja.png ... Django behaves as if the images have been saved succesfully under the images folder, but the images are not actually there!! Anyone have a clue of what I did wrong? PS: I'm using Django 2.1+ SVN
[ "Mistyped \nMEDIA_ROOT = '/home/webapps/test_project/media/'\n\nwrote home instead of root\n" ]
[ 1 ]
[]
[]
[ "django", "django_models", "django_uploads", "python" ]
stackoverflow_0003203119_django_django_models_django_uploads_python.txt
Q: how do i store the output of my cursor object to a text file? I have accessed a database and have the result in a cursor object. when I try to save it to a text file, python says TypeError: argument 1 must be string or read-only character buffer, not sqlite3.Cursor can someone tell me what I should do here? curobject.execute('select * from device_auth') for row in curobject: print row myfile =open('out.txt', 'w') myfile.write(curobject) A: You can't just write objects to a file, you have to either serialize them or write your own string representation of the object. For records of a database the csv module could make sense. Which approach is better depends on what you want to do with the file later. A: For example something like this: with open('out.txt', 'w') as file: file.writelines(', '.join(row) + '\n' for row in curobject) # assuming row of strings
how do i store the output of my cursor object to a text file?
I have accessed a database and have the result in a cursor object. when I try to save it to a text file, python says TypeError: argument 1 must be string or read-only character buffer, not sqlite3.Cursor can someone tell me what I should do here? curobject.execute('select * from device_auth') for row in curobject: print row myfile =open('out.txt', 'w') myfile.write(curobject)
[ "You can't just write objects to a file, you have to either serialize them or write your own string representation of the object. For records of a database the csv module could make sense.\nWhich approach is better depends on what you want to do with the file later.\n", "For example something like this:\nwith ope...
[ 1, 0 ]
[]
[]
[ "file_io", "python", "sqlite" ]
stackoverflow_0003203241_file_io_python_sqlite.txt
Q: How to debug Python code that is partially covered by passing unit tests but produces wrong results when being reused? I have a Python class and its methods are partially covered by unit tests like this: class MyClass: def __init__(self): self.instancevar1 = None # some methods change this value self.instancevar2 = None # some methods change this value ... def method1(self, input_data): ... <self.instancevar1 and self.instancevar2 are used here> <return True or False> ... class TestMyClass(unittest.TestCase): def test_method1(self): mc = MyClass() input_data = 'foo' self.assertEqual(mc.method1(input_data), True) The tests are passing for simple cases like this. I also have other classes that use instances of MyClass like this: class MyOtherClass: def __init__(self): self.mc = MyClass() Now, in some method of MyOtherClass, I have a situation like this: class MyOtherClass: ... def some_method(self): ... result = self.mc.method1('foo') # result is expected to be True, but it is False I think I understand the reason why this might happen. In the test case, I instantiate MyClass and call the test. In MyOtherClass, self.mc is referenced multiple times, misc methods of it are called and they probably change the internal state of the object (some values of instance variables), thus producing a different return value. What are the suggested best practices for debugging such issues? The fact that I have some tests for MyClass is good, but doesn't seem to help much here. Does this example contain some design flaws which cause my problems? A: As Rudi said, there's either a bug in MyClass.method1() that causes it to return False when it shouldn't, or there's a bug in other parts of the code that puts mc in a state you didn't expect. You can address both problems with additional unit tests: If there's a bug in MyClass.method1() when mc is in a particular state, you should add more unit tests to verify that mc.method1() returns the correct value for each state that mc is in. Also, add unit tests for MyOtherClass and other relevant parts of the code to ensure that self.mc is always in the state you're expecting, regardless of what operations you perform on the MyClass instance. It's hard to come up with more specific advice than this since your example is fairly abstract, but I think you should get an idea about where to start looking and how to improve your tests to handle these issues better. A: At first you need to find out if the MyClass object is in a correct state when some_method calls the defect method. If the state is correct, there is a bug in MyClass.method1, if it is not you need to search for the wrong state transition. If there was a wrong state transition, you can add code to MyClass to detect the fault, and raise an exception or assert, when the wrong state is entered.
How to debug Python code that is partially covered by passing unit tests but produces wrong results when being reused?
I have a Python class and its methods are partially covered by unit tests like this: class MyClass: def __init__(self): self.instancevar1 = None # some methods change this value self.instancevar2 = None # some methods change this value ... def method1(self, input_data): ... <self.instancevar1 and self.instancevar2 are used here> <return True or False> ... class TestMyClass(unittest.TestCase): def test_method1(self): mc = MyClass() input_data = 'foo' self.assertEqual(mc.method1(input_data), True) The tests are passing for simple cases like this. I also have other classes that use instances of MyClass like this: class MyOtherClass: def __init__(self): self.mc = MyClass() Now, in some method of MyOtherClass, I have a situation like this: class MyOtherClass: ... def some_method(self): ... result = self.mc.method1('foo') # result is expected to be True, but it is False I think I understand the reason why this might happen. In the test case, I instantiate MyClass and call the test. In MyOtherClass, self.mc is referenced multiple times, misc methods of it are called and they probably change the internal state of the object (some values of instance variables), thus producing a different return value. What are the suggested best practices for debugging such issues? The fact that I have some tests for MyClass is good, but doesn't seem to help much here. Does this example contain some design flaws which cause my problems?
[ "As Rudi said, there's either a bug in MyClass.method1() that causes it to return False when it shouldn't, or there's a bug in other parts of the code that puts mc in a state you didn't expect.\nYou can address both problems with additional unit tests:\n\nIf there's a bug in MyClass.method1() when mc is in a partic...
[ 2, 1 ]
[]
[]
[ "debugging", "python", "unit_testing" ]
stackoverflow_0003203101_debugging_python_unit_testing.txt
Q: read file from server with some offset How can I read file from server starting with some offset (Similar behavior to wget -c)? What headers I must send to server? What futures must server support? A: You should use the Range header in the request. But you may use it only if the server informs you that it accept range request by Accept-Ranges response header. This is an example session. Suppose we are interested in getting a part of this picture. First, we send a HTTP HEAD request to determine: a) if the server supports byte ranges, b) the content-length: > HEAD /2238/2758537173_670161cac7_b.jpg HTTP/1.1 > Host: farm3.static.flickr.com > Accept: */* > < HTTP/1.1 200 OK < Date: Thu, 08 Jul 2010 12:22:12 GMT < Content-Type: image/jpeg < Connection: keep-alive < Server: Apache/2.0.52 (Red Hat) < Expires: Mon, 28 Jul 2014 23:30:00 GMT < Last-Modified: Wed, 13 Aug 2008 06:13:54 GMT < Accept-Ranges: bytes < Content-Length: 350015 Next, we send a GET request with the Range header asking for the first 11 bytes of the picure: > GET /2238/2758537173_670161cac7_b.jpg HTTP/1.1 > Host: farm3.static.flickr.com > Accept: */* > Range: bytes=0-10 > < HTTP/1.1 206 Partial Content < Date: Thu, 08 Jul 2010 12:26:54 GMT < Content-Type: image/jpeg < Connection: keep-alive < Server: Apache/2.0.52 (Red Hat) < Expires: Mon, 28 Jul 2014 23:30:00 GMT < Last-Modified: Wed, 13 Aug 2008 06:13:54 GMT < Accept-Ranges: bytes < Content-Range: bytes 0-10/350015 < Content-Length: 11 < This is a hex dump of the first 11 bytes: 00000000 ff d8 ff e0 00 10 4a 46 49 46 00 |......JFIF.| 0000000b For more info see the Range header specification in HTTP RFC 2616. A: In http://www.gnu.org/software/wget/manual/wget.html Note that ‘-c’ only works with ftp servers and with http servers that support the Range header. In https://www.rfc-editor.org/rfc/rfc2616 Examples of byte-ranges-specifier values (assuming an entity-body of length 10000): - The first 500 bytes (byte offsets 0-499, inclusive): bytes=0- 499 - The second 500 bytes (byte offsets 500-999, inclusive): bytes=500-999 - The final 500 bytes (byte offsets 9500-9999, inclusive): bytes=-500 - Or bytes=9500- - The first and last bytes only (bytes 0 and 9999): bytes=0-0,-1 - Several legal but not canonical specifications of the second 500 bytes (byte offsets 500-999, inclusive): bytes=500-600,601-999 bytes=500-700,601-999 So you should send Range:bytes=9500- To test if a server support it you can test the accept-range as such Origin servers that accept byte-range requests MAY send Accept-Ranges: bytes but are not required to do so. Clients MAY generate byte-range requests without having received this header for the resource involved. Range units are defined in section 3.12. Servers that do not accept any kind of range request for a resource MAY send Accept-Ranges: none to advise the client not to attempt a range request.
read file from server with some offset
How can I read file from server starting with some offset (Similar behavior to wget -c)? What headers I must send to server? What futures must server support?
[ "You should use the Range header in the request. But you may use it only if the server informs you that it accept range request by Accept-Ranges response header.\nThis is an example session. Suppose we are interested in getting a part of this picture. First, we send a HTTP HEAD request to determine: a) if the serve...
[ 18, 3 ]
[]
[]
[ "http", "python" ]
stackoverflow_0003203217_http_python.txt
Q: How to make persistent a python dictionary on google appengine Using datastore framework of appengine, what's the pythonic way to make persistent a {}? A: You would only need to use the expando option if you intend to query on the individual dictionary elements. Assuming you don't want to do this, then you can use a custom property - class ObjectProperty(db.Property): data_type = db.Blob def get_value_for_datastore(self, model_instance): value = self.__get__(model_instance, model_instance.__class__) pickled_val = pickle.dumps(value) if value is not None: return db.Blob(pickled_val) def make_value_from_datastore(self, value): if value is not None: return pickle.loads(str(value)) def default_value(self): return copy.copy(self.default) Note that the above property def I got from some code that Nick Johnson produced. It's a project on git hub, and contains a number of other custom properties. A: You should store it using pickle.dumps and retrieve it using pickle.loads see http://docs.python.org/library/pickle.html A: I think there are 2 options. Using expando. You can store anything in that as long as you omit the reserved fields: class SomeModel(db.Expando): pass your_model = SomeModel() for k, v in your_dict.iteritems(): setattr(your_model, k, v) It might be possible to use your_model.__dict__.update(your_dict) but I'm not sure about that. Store it in a textfield using pickle: class SomeModel(db.Model): pickled_data = db.BlobProperty() your_model = SomeModel() your_model.pickled_data = pickle.dumps(your_dict)
How to make persistent a python dictionary on google appengine
Using datastore framework of appengine, what's the pythonic way to make persistent a {}?
[ "You would only need to use the expando option if you intend to query on the individual dictionary elements.\nAssuming you don't want to do this, then you can use a custom property -\nclass ObjectProperty(db.Property):\n data_type = db.Blob\n\n def get_value_for_datastore(self, model_instance):\n value = self....
[ 5, 3, 2 ]
[]
[]
[ "dictionary", "persistence", "python" ]
stackoverflow_0003203543_dictionary_persistence_python.txt
Q: Is there a way to set the value of wsgi.input when testing? When using wsgiref.util.setup_testing_defaults() to set up a WSGI environ is it possible to set the wsgi.input value so that one can test HTTP POST requests? Investigating the wsgi.input value created by setup_testing_defaults() shows that it's a wsgi.validate.InputWrapper object with read, readline, readlines, input, close, and __iter__ methods, but no write methods. Edit: I'm working on Python 2.6.1 A: According to the WSGI spec, the wsgi.input is just a file-like object. So even if your helper library assigns some weird object to the environ['wsgi.input'], you may replace it with any file-like object you want. In particular, with a StringIO object: e = {} setup_testing_defaults(e) s = urlencode({'q': 'is there a way to set the value of wsgi input'}) e['wsgi.input'] = StringIO(s)
Is there a way to set the value of wsgi.input when testing?
When using wsgiref.util.setup_testing_defaults() to set up a WSGI environ is it possible to set the wsgi.input value so that one can test HTTP POST requests? Investigating the wsgi.input value created by setup_testing_defaults() shows that it's a wsgi.validate.InputWrapper object with read, readline, readlines, input, close, and __iter__ methods, but no write methods. Edit: I'm working on Python 2.6.1
[ "According to the WSGI spec, the wsgi.input is just a file-like object. So even if your helper library assigns some weird object to the environ['wsgi.input'], you may replace it with any file-like object you want. In particular, with a StringIO object:\ne = {}\nsetup_testing_defaults(e)\ns = urlencode({'q': 'is the...
[ 3 ]
[]
[]
[ "python", "unit_testing", "wsgi" ]
stackoverflow_0003203422_python_unit_testing_wsgi.txt
Q: What's the meaning of '@' in python code? Reading some Python (PyQt) code, I came across as follows. @pyqtSignature("QString") def on_findLineEdit_textEdited(self, text): self.__index = 0 self.updateUi() How does this @pyqtSignature work? How Python treat this @? A: It is the decorator syntax, simply it is equivalent to this form: on_findLineEdit_textEdited = pyqtSignature("Qstring")(on_findLineEdit_textEdited) Really simple. A typical decorator takes as the first argument the function that has to be decorated, and perform stuff/adds functionalities to it. A typical example would be: def echo_fname(f): def newfun(): print f.__name__ f() return newfun The steps are: define a new function that add functionalities to f return this new function. A: It is a syntax for function decorators.
What's the meaning of '@' in python code?
Reading some Python (PyQt) code, I came across as follows. @pyqtSignature("QString") def on_findLineEdit_textEdited(self, text): self.__index = 0 self.updateUi() How does this @pyqtSignature work? How Python treat this @?
[ "It is the decorator syntax, simply it is equivalent to this form:\non_findLineEdit_textEdited = pyqtSignature(\"Qstring\")(on_findLineEdit_textEdited)\n\nReally simple.\nA typical decorator takes as the first argument the function that has to be decorated, and perform stuff/adds functionalities to it. A typical ex...
[ 5, 2 ]
[]
[]
[ "python", "syntax" ]
stackoverflow_0003203824_python_syntax.txt
Q: Django script add field to database I added a slug field to my database and now need to go through and add those. I want to run a script that looks at the slug field in the database and if empty generates and saves. Here is what I thought was along the lines, but is not working. from project.apps.tracks.models import * def process_slug(): if not track.slug: slug = slugify("%s - %s" % (track.name, track.artist)) else: slug = "" super(process_slug, track).save() A: From your posted code it is not evident, that you are actually looping through all your Track objects. from project.apps.tracks.models import Track # import for slugify def process_slug(): """ Populate slug field, if they are empty. """ for track in Track.objects.all(): if not track.slug: slug = slugify("%s - %s" % (track.name, track.artist)) track.slug = slug track.save() One preferred place for such occasionally recurring commands would be under management/commands inside your application. Another way to implement would be to override your Track model's save method. It would check for emtpy slugs on every save (which is not performant). A: You can set the default like this: slug = models.SlugField(default=process_slug)
Django script add field to database
I added a slug field to my database and now need to go through and add those. I want to run a script that looks at the slug field in the database and if empty generates and saves. Here is what I thought was along the lines, but is not working. from project.apps.tracks.models import * def process_slug(): if not track.slug: slug = slugify("%s - %s" % (track.name, track.artist)) else: slug = "" super(process_slug, track).save()
[ "From your posted code it is not evident, that you are actually looping through all your Track objects. \nfrom project.apps.tracks.models import Track\n# import for slugify\n\ndef process_slug():\n \"\"\" Populate slug field, if they are empty. \n \"\"\"\n for track in Track.objects.all():\n if not ...
[ 1, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003203823_django_python.txt
Q: How to read String in java that was written using python’s struct.pack method out.write( struct.pack(">f", 1.1) ); out.write( struct.pack(">i", 12) ); out.write( struct.pack(">3s", "abc") ); how to import struct package in java it says .. no package found when i am trying to execute it so kindly tell me any suggestions if any Thanking you i took that code from How to read String in java that was written using python's struct.pack method A: Read the answer to the question you referenced. The sample code in the question was incorrect. Also, you don't import the struct package in Java. It's a Python package. Also as described in the other question, you use java.io.DataInputStream to read the file created from Python.
How to read String in java that was written using python’s struct.pack method
out.write( struct.pack(">f", 1.1) ); out.write( struct.pack(">i", 12) ); out.write( struct.pack(">3s", "abc") ); how to import struct package in java it says .. no package found when i am trying to execute it so kindly tell me any suggestions if any Thanking you i took that code from How to read String in java that was written using python's struct.pack method
[ "Read the answer to the question you referenced. The sample code in the question was incorrect.\nAlso, you don't import the struct package in Java. It's a Python package. Also as described in the other question, you use java.io.DataInputStream to read the file created from Python.\n" ]
[ 0 ]
[]
[]
[ "binary", "java", "python", "struct" ]
stackoverflow_0003203930_binary_java_python_struct.txt
Q: How to call process by name or tags in python I am using multiprocessing module. This module is works on Queue that is its pick random process and assign the entery from Queue. I want to decide which process will work on which entry of Queue Here is my requirements, I will pass 2 parameters to queue Initiator Process name Action/method ( What process is going to do) Its should pass queue Entry to given Process only. A: multiprocessing.Process objects take an optional name argument on initialization. You can use that name as a key in a dictionary: child_procs = {'name1' : Process(target=myprocfunc, name='name1'), ...} As for IPC between the parent process and the children, you should be fine with just maintaining a separate multiprocessing.Queue for each child process. You'll need a task distribution object/function to assign work. This function would probably be responsible for popping the task from the main/central queue and then assigning it to the correct child process queue (based on the architecture I am gleaming from your question).
How to call process by name or tags in python
I am using multiprocessing module. This module is works on Queue that is its pick random process and assign the entery from Queue. I want to decide which process will work on which entry of Queue Here is my requirements, I will pass 2 parameters to queue Initiator Process name Action/method ( What process is going to do) Its should pass queue Entry to given Process only.
[ "multiprocessing.Process objects take an optional name argument on initialization. You can use that name as a key in a dictionary:\nchild_procs = {'name1' : Process(target=myprocfunc, name='name1'), ...}\nAs for IPC between the parent process and the children, you should be fine with just maintaining a separate mu...
[ 1 ]
[]
[]
[ "multiprocessing", "python" ]
stackoverflow_0003204037_multiprocessing_python.txt
Q: how to check if a file is a directory or regular file in python? How do you check if a path is a directory or file in python? A: os.path.isfile("bob.txt") # Does bob.txt exist? Is it a file, or a directory? os.path.isdir("bob") A: use os.path.isdir(path) more info here http://docs.python.org/library/os.path.html A: Many of the Python directory functions are in the os.path module. import os os.path.isdir(d) A: An educational example from the stat documentation: import os, sys from stat import * def walktree(top, callback): '''recursively descend the directory tree rooted at top, calling the callback function for each regular file''' for f in os.listdir(top): pathname = os.path.join(top, f) mode = os.stat(pathname)[ST_MODE] if S_ISDIR(mode): # It's a directory, recurse into it walktree(pathname, callback) elif S_ISREG(mode): # It's a file, call the callback function callback(pathname) else: # Unknown file type, print a message print 'Skipping %s' % pathname def visitfile(file): print 'visiting', file if __name__ == '__main__': walktree(sys.argv[1], visitfile)
how to check if a file is a directory or regular file in python?
How do you check if a path is a directory or file in python?
[ "os.path.isfile(\"bob.txt\") # Does bob.txt exist? Is it a file, or a directory?\nos.path.isdir(\"bob\")\n\n", "use os.path.isdir(path) \nmore info here http://docs.python.org/library/os.path.html\n", "Many of the Python directory functions are in the os.path module.\nimport os\nos.path.isdir(d)\n\n", "An ed...
[ 671, 146, 73, 22 ]
[]
[]
[ "python" ]
stackoverflow_0003204782_python.txt
Q: How to write Russian characters in file? In console when I'm trying output Russian characters It gives me ??????????????? Who know why? I tried write to file - in this case the same situation. for example f=open('tets.txt','w') f.write('some russian text') f.close inside file is - ?????????????????????????/ or p="some russian text" print p ????????????? In additional Notepad don't allow me to save file with Russian letters. I give this: This file contains characters in Unicode format which will be lost if you save this file as an ANSI encoded text file. To keep the Unicode information, click Cancel below and then select one of the Unicode options from the Encoding drop down list. Continue? How to adjust my system, so I will don't have this problems. A: Here is a worked-out example, please read the comments: #!/usr/bin/env python2 # -*- coding: utf-8 -*- # The above encoding declaration is required and the file must be saved as UTF-8 from __future__ import with_statement # Not required in Python 2.6 any more import codecs p = u"абвгдежзийкл" # note the 'u' prefix print p # probably won't work on Windows due to a complex issue with codecs.open("tets.txt", "w", "utf-16") as stream: # or utf-8 stream.write(p + u"\n") # Now you should have a file called "tets.txt" that can be opened with Notepad or any other editor A: Try opening the file using codecs, you need to import codecs and then writefile = codecs.open('write.txt', 'w', 'utf-8') A: You need to define file encoding if it contains non-ASCII chars. http://www.python.org/dev/peps/pep-0263/ A: What console are you using? Chances are, your console doesn't support that language. Make sure that your console supports Unicode (and that your app is sending Unicode strings). Update: To address the update to your question regarding problems with Windows' Notepad: Click File->Save As, and then choose "Unicode" from the "Encoding" drop-down list. A: Are you typing in console too or only seing the results in console? This looks a pep-0263 problem as petraszd said. print p.decode('your-system-encoding') should work in console (I don't know what is the encoding system you use for Russian) If you are using a .py file, you need to place # -*- coding: UTF-8 -*- (replacing utf-8 with Rusian encoding) on the top of the file and I think there is no need for the .decode in print if your OS is configured with the right encoding. (at least I don't need it but I don't know how it works with Russian)
How to write Russian characters in file?
In console when I'm trying output Russian characters It gives me ??????????????? Who know why? I tried write to file - in this case the same situation. for example f=open('tets.txt','w') f.write('some russian text') f.close inside file is - ?????????????????????????/ or p="some russian text" print p ????????????? In additional Notepad don't allow me to save file with Russian letters. I give this: This file contains characters in Unicode format which will be lost if you save this file as an ANSI encoded text file. To keep the Unicode information, click Cancel below and then select one of the Unicode options from the Encoding drop down list. Continue? How to adjust my system, so I will don't have this problems.
[ "Here is a worked-out example, please read the comments:\n#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n# The above encoding declaration is required and the file must be saved as UTF-8\n\nfrom __future__ import with_statement # Not required in Python 2.6 any more\n\nimport codecs\n\np = u\"абвгдежзийкл\" # no...
[ 19, 9, 2, 1, 0 ]
[]
[]
[ "python", "python_2.x", "python_unicode", "unicode", "windows" ]
stackoverflow_0003198765_python_python_2.x_python_unicode_unicode_windows.txt
Q: How do I convert a tuple of tuples to a one-dimensional list using list comprehension? I have a tuple of tuples - for example: tupleOfTuples = ((1, 2), (3, 4), (5,)) I want to convert this into a flat, one-dimensional list of all the elements in order: [1, 2, 3, 4, 5] I've been trying to accomplish this with list comprehension. But I can't seem to figure it out. I was able to accomplish it with a for-each loop: myList = [] for tuple in tupleOfTuples: myList = myList + list(tuple) But I feel like there must be a way to do this with a list comprehension. A simple [list(tuple) for tuple in tupleOfTuples] just gives you a list of lists, instead of individual elements. I thought I could perhaps build on this by using the unpacking operator to then unpack the list, like so: [*list(tuple) for tuple in tupleOfTuples] or [*(list(tuple)) for tuple in tupleOfTuples] ... but that didn't work. Any ideas? Or should I just stick to the loop? A: it's typically referred to as flattening a nested structure. >>> tupleOfTuples = ((1, 2), (3, 4), (5,)) >>> [element for tupl in tupleOfTuples for element in tupl] [1, 2, 3, 4, 5] Just to demonstrate efficiency: >>> import timeit >>> it = lambda: list(chain(*tupleOfTuples)) >>> timeit.timeit(it) 2.1475738355700913 >>> lc = lambda: [element for tupl in tupleOfTuples for element in tupl] >>> timeit.timeit(lc) 1.5745135182887857 ETA: Please don't use tuple as a variable name, it shadows built-in. A: Just use sum if you don't have a lot of tuples. >>> tupleOfTuples = ((1, 2), (3, 4), (5,)) >>> sum(tupleOfTuples, ()) (1, 2, 3, 4, 5) >>> list(sum(tupleOfTuples, ())) # if you really need a list [1, 2, 3, 4, 5] If you do have a lot of tuples, use list comprehension or chain.from_iterable to prevent the quadratic behavior of sum. Micro-benchmarks: Python 2.6 Long tuple of short tuples $ python2.6 -m timeit -s 'tot = ((1, 2), )*500' '[element for tupl in tot for element in tupl]' 10000 loops, best of 3: 134 usec per loop $ python2.6 -m timeit -s 'tot = ((1, 2), )*500' 'list(sum(tot, ()))' 1000 loops, best of 3: 1.1 msec per loop $ python2.6 -m timeit -s 'tot = ((1, 2), )*500; from itertools import chain; ci = chain.from_iterable' 'list(ci(tot))' 10000 loops, best of 3: 60.1 usec per loop $ python2.6 -m timeit -s 'tot = ((1, 2), )*500; from itertools import chain' 'list(chain(*tot))' 10000 loops, best of 3: 64.8 usec per loop Short tuple of long tuples $ python2.6 -m timeit -s 'tot = ((1, )*500, (2, )*500)' '[element for tupl in tot for element in tupl]' 10000 loops, best of 3: 65.6 usec per loop $ python2.6 -m timeit -s 'tot = ((1, )*500, (2, )*500)' 'list(sum(tot, ()))' 100000 loops, best of 3: 16.9 usec per loop $ python2.6 -m timeit -s 'tot = ((1, )*500, (2, )*500); from itertools import chain; ci = chain.from_iterable' 'list(ci(tot))' 10000 loops, best of 3: 25.8 usec per loop $ python2.6 -m timeit -s 'tot = ((1, )*500, (2, )*500); from itertools import chain' 'list(chain(*tot))' 10000 loops, best of 3: 26.5 usec per loop Python 3.1 Long tuple of short tuples $ python3.1 -m timeit -s 'tot = ((1, 2), )*500' '[element for tupl in tot for element in tupl]' 10000 loops, best of 3: 121 usec per loop $ python3.1 -m timeit -s 'tot = ((1, 2), )*500' 'list(sum(tot, ()))' 1000 loops, best of 3: 1.09 msec per loop $ python3.1 -m timeit -s 'tot = ((1, 2), )*500; from itertools import chain; ci = chain.from_iterable' 'list(ci(tot))' 10000 loops, best of 3: 59.5 usec per loop $ python3.1 -m timeit -s 'tot = ((1, 2), )*500; from itertools import chain' 'list(chain(*tot))' 10000 loops, best of 3: 63.2 usec per loop Short tuple of long tuples $ python3.1 -m timeit -s 'tot = ((1, )*500, (2, )*500)' '[element for tupl in tot for element in tupl]' 10000 loops, best of 3: 66.1 usec per loop $ python3.1 -m timeit -s 'tot = ((1, )*500, (2, )*500)' 'list(sum(tot, ()))' 100000 loops, best of 3: 16.3 usec per loop $ python3.1 -m timeit -s 'tot = ((1, )*500, (2, )*500); from itertools import chain; ci = chain.from_iterable' 'list(ci(tot))' 10000 loops, best of 3: 25.4 usec per loop $ python3.1 -m timeit -s 'tot = ((1, )*500, (2, )*500); from itertools import chain' 'list(chain(*tot))' 10000 loops, best of 3: 25.6 usec per loop Observation: sum is faster if the outer tuple is short. list(chain.from_iterable(x)) is faster if the outer tuple is long. A: You're chaining the tuples together: from itertools import chain print list(chain(*listOfTuples)) Should be pretty readable if you're familiar with itertools, and without the explicit list you even have your result in generator form. A: I like using 'reduce' in this situation (this is what reduce made for!) lot = ((1, 2), (3, 4), (5,)) print list(reduce(lambda t1, t2: t1 + t2, lot)) > [1,2,3,4,5] A: Most of these answers will only work for a single level of flattening. For a more comprehensive solution, try this (from http://rightfootin.blogspot.com/2006/09/more-on-python-flatten.html): def flatten(l, ltypes=(list, tuple)): ltype = type(l) l = list(l) i = 0 while i < len(l): while isinstance(l[i], ltypes): if not l[i]: l.pop(i) i -= 1 break else: l[i:i + 1] = l[i] i += 1 return ltype(l) A: Another solution using itertools.chain >>> tupleOfTuples = ((1, 2), (3, 4), (5,)) >>> from itertools import chain >>> [x for x in chain.from_iterable(tupleOfTuples)] [1, 2, 3, 4, 5] A: For multilevel, and readable code: def flatten(bla): output = [] for item in bla: output += flatten(item) if hasattr (item, "__iter__") or hasattr (item, "__len__") else [item] return output I could not get this to fit in one line (and remain readable, even by far)
How do I convert a tuple of tuples to a one-dimensional list using list comprehension?
I have a tuple of tuples - for example: tupleOfTuples = ((1, 2), (3, 4), (5,)) I want to convert this into a flat, one-dimensional list of all the elements in order: [1, 2, 3, 4, 5] I've been trying to accomplish this with list comprehension. But I can't seem to figure it out. I was able to accomplish it with a for-each loop: myList = [] for tuple in tupleOfTuples: myList = myList + list(tuple) But I feel like there must be a way to do this with a list comprehension. A simple [list(tuple) for tuple in tupleOfTuples] just gives you a list of lists, instead of individual elements. I thought I could perhaps build on this by using the unpacking operator to then unpack the list, like so: [*list(tuple) for tuple in tupleOfTuples] or [*(list(tuple)) for tuple in tupleOfTuples] ... but that didn't work. Any ideas? Or should I just stick to the loop?
[ "it's typically referred to as flattening a nested structure.\n>>> tupleOfTuples = ((1, 2), (3, 4), (5,))\n>>> [element for tupl in tupleOfTuples for element in tupl]\n[1, 2, 3, 4, 5]\n\nJust to demonstrate efficiency:\n>>> import timeit\n>>> it = lambda: list(chain(*tupleOfTuples))\n>>> timeit.timeit(it)\n2.147573...
[ 74, 46, 13, 9, 9, 4, 4 ]
[]
[]
[ "iterable_unpacking", "list_comprehension", "python", "tuples" ]
stackoverflow_0003204245_iterable_unpacking_list_comprehension_python_tuples.txt
Q: HTTP based authentication/encryption protocol in a custom system We have a custom built program that needs authenticated/encrypted communication between a client and a server[both in Python]. We are doing an overhaul from custom written Diffie-Hellman+AES to RSA+AES in a non-orthodox way. So I would be very interested in comments about my idea. Prequisites: Klient has a 128bit RegistrationKey which needs to remain a secret during the authentication - this key is also the only shared secret between the server and client. Client contacts the server over an insecure channel and asks the servers RSA PubKey Client then queries the server: [pseudocode follows] RegistrationKey = "1dbe665ac7a944beb67f106f779e890b" clientname = "foobar" randomkey = random(bits=128) rsa_cp = RSA(key=pubkey, data=randomkey+clientname) aes_cp = AES(key=RegistrationKey, data=RegistrationKey+rsa_cp) send(aes_cp) 3. Server then responds: [pseudocode follows] # Server decrypts the data and sees if it has a valid RegistrationKey, if it does... clientuuid = random(bits=128) sharedkey = random(bits=128) rsa_cp = RSA(key=privkey, data=clientuuid+sharedkey) aes_cp = AES(key=randomkey[got from client], data= rsa_cp) send(aes_cp) Now both sides know the "clientuuid", "sharedkey" which the client can use later to authenticate itself. The method above should be secure even when the attacker learns the regkey later since he would have to crack the RSA key AND man-in-the-middle attacks(on RSA) should stop the auth. from completing correctly. The only possible attack method I see would be the case where the attacker knows the regkey AND can alter the traffic during the authentication. Am i correct? I really want to hear your ides on what to add/remove from this method and If you know a much better way to do this kind of exchange. PS! We are currently using Diffie-Hellman(my own lib, so it probably has flaws) and we have tried TLSv1.2 with PreSharedKeys(didn't work for some reason) and we are CONSTRICTED to http protocols since we need to do this in django. And because we are doing this in http we try to keep the request/answer count as low as possible(no sessions would be the best) - 1 would be the best :) If you have any questions about the specifics, please ask. So, you crypto/security geeks, please give me a helping hand :) A: Don't re-invent the wheal, use HTTPS. The server can issue certificates to the client and store them in the Database. Clients can be distributed with the server's self-signed certificate for verification. The server can verify clients by using Apache's HTTPS Environment Variables. A: No. Use SSL. Reinventing cryptosystems is a bad idea. What you can easily do is set up a reverse proxy. Run your Django app on a higher port (e.g., 8080) and set it to respond only to connections from the loopback address (127.0.0.1). Run the reverse proxy on port 443 (standard HTTPS port) and proxy all requests to the Django app. But setup the reverse proxy with the site's certificate and have it be an SSL endpoint. The proxied requests going to the Django app would then just be "regular old" HTTP, not HTTPS. Apache Mod_Proxy NginX as a Reverse Proxy A: I don't think RegistrationKey adds any real security. It needs more nonces (against replay attacks). It needs more padding (or else the messages are small and thus easy to decrypt). An algorithm can be proven to be secure, you may want to do this. Most flaws in crypto are in the implementation, not in the algorithm (timing attacks, for example).
HTTP based authentication/encryption protocol in a custom system
We have a custom built program that needs authenticated/encrypted communication between a client and a server[both in Python]. We are doing an overhaul from custom written Diffie-Hellman+AES to RSA+AES in a non-orthodox way. So I would be very interested in comments about my idea. Prequisites: Klient has a 128bit RegistrationKey which needs to remain a secret during the authentication - this key is also the only shared secret between the server and client. Client contacts the server over an insecure channel and asks the servers RSA PubKey Client then queries the server: [pseudocode follows] RegistrationKey = "1dbe665ac7a944beb67f106f779e890b" clientname = "foobar" randomkey = random(bits=128) rsa_cp = RSA(key=pubkey, data=randomkey+clientname) aes_cp = AES(key=RegistrationKey, data=RegistrationKey+rsa_cp) send(aes_cp) 3. Server then responds: [pseudocode follows] # Server decrypts the data and sees if it has a valid RegistrationKey, if it does... clientuuid = random(bits=128) sharedkey = random(bits=128) rsa_cp = RSA(key=privkey, data=clientuuid+sharedkey) aes_cp = AES(key=randomkey[got from client], data= rsa_cp) send(aes_cp) Now both sides know the "clientuuid", "sharedkey" which the client can use later to authenticate itself. The method above should be secure even when the attacker learns the regkey later since he would have to crack the RSA key AND man-in-the-middle attacks(on RSA) should stop the auth. from completing correctly. The only possible attack method I see would be the case where the attacker knows the regkey AND can alter the traffic during the authentication. Am i correct? I really want to hear your ides on what to add/remove from this method and If you know a much better way to do this kind of exchange. PS! We are currently using Diffie-Hellman(my own lib, so it probably has flaws) and we have tried TLSv1.2 with PreSharedKeys(didn't work for some reason) and we are CONSTRICTED to http protocols since we need to do this in django. And because we are doing this in http we try to keep the request/answer count as low as possible(no sessions would be the best) - 1 would be the best :) If you have any questions about the specifics, please ask. So, you crypto/security geeks, please give me a helping hand :)
[ "Don't re-invent the wheal, use HTTPS. \nThe server can issue certificates to the client and store them in the Database. Clients can be distributed with the server's self-signed certificate for verification. The server can verify clients by using Apache's HTTPS Environment Variables.\n", "No. Use SSL. Reinvent...
[ 4, 3, 1 ]
[]
[]
[ "authentication", "cryptography", "encryption", "python", "security" ]
stackoverflow_0003205349_authentication_cryptography_encryption_python_security.txt
Q: Making HTTPS Requests in Twisted I am trying to write a client that can make both HTTP and HTTPS requests depending on how it is configured. For normal HTTP, I have been using twisted.web.client.Agent and using agent.request(METHOD, HOST, HEADERS, CONTENT) to make the requests. What I care about is that host field, when I do HTTP it works doing something like "http://localhost:8000", but if I switch to HTTPS, I get an error: Failure: twisted.web.error.SchemeNotSupported: Unsupported scheme: 'https' I am aware of the existence of the client.getPage method, but I was wondering if there was any similarly awesome and high level methods that I can make requests with just like agent.request, but using HTTPS? A: HTTPS support was only recently added to twisted.web.client.Agent. If you can use Twisted 10.1, very recently released, then Agent will accept your HTTPS URLs.
Making HTTPS Requests in Twisted
I am trying to write a client that can make both HTTP and HTTPS requests depending on how it is configured. For normal HTTP, I have been using twisted.web.client.Agent and using agent.request(METHOD, HOST, HEADERS, CONTENT) to make the requests. What I care about is that host field, when I do HTTP it works doing something like "http://localhost:8000", but if I switch to HTTPS, I get an error: Failure: twisted.web.error.SchemeNotSupported: Unsupported scheme: 'https' I am aware of the existence of the client.getPage method, but I was wondering if there was any similarly awesome and high level methods that I can make requests with just like agent.request, but using HTTPS?
[ "HTTPS support was only recently added to twisted.web.client.Agent. If you can use Twisted 10.1, very recently released, then Agent will accept your HTTPS URLs.\n" ]
[ 5 ]
[]
[]
[ "client", "https", "python", "request", "twisted" ]
stackoverflow_0003204509_client_https_python_request_twisted.txt
Q: How do I implement something like Digg Swarm in PHP or Python? http://labs.digg.com/swarm/ A: http://raphaeljs.com/ For the Javascript data representation and i guess use PHP to talk with the API.
How do I implement something like Digg Swarm in PHP or Python?
http://labs.digg.com/swarm/
[ "http://raphaeljs.com/ For the Javascript data representation and i guess use PHP to talk with the API.\n" ]
[ 1 ]
[]
[]
[ "data_warehouse", "javascript", "php", "python" ]
stackoverflow_0003205157_data_warehouse_javascript_php_python.txt
Q: combining two string variables I'm a novice Python user trying to do something that I think should be simple but can't figure it out. I've got 2 variables defined: a = 'lemon' b = 'lime' Can someone tell me how to combine these in a new variable? If I try: >>> soda = "a" + "b" >>> soda 'ab' I want soda to be 'lemonlime'. How is this done? Thanks! A: you need to take out the quotes: soda = a + b (You want to refer to the variables a and b, not the strings "a" and "b") A: IMO, froadie's simple concatenation is fine for a simple case like you presented. If you want to put together several strings, the string join method seems to be preferred: the_text = ''.join(['the ', 'quick ', 'brown ', 'fox ', 'jumped ', 'over ', 'the ', 'lazy ', 'dog.']) Edit: Note that join wants an iterable (e.g. a list) as its single argument.
combining two string variables
I'm a novice Python user trying to do something that I think should be simple but can't figure it out. I've got 2 variables defined: a = 'lemon' b = 'lime' Can someone tell me how to combine these in a new variable? If I try: >>> soda = "a" + "b" >>> soda 'ab' I want soda to be 'lemonlime'. How is this done? Thanks!
[ "you need to take out the quotes:\nsoda = a + b\n\n(You want to refer to the variables a and b, not the strings \"a\" and \"b\")\n", "IMO, froadie's simple concatenation is fine for a simple case like you presented. If you want to put together several strings, the string join method seems to be preferred:\nthe_t...
[ 46, 21 ]
[]
[]
[ "python" ]
stackoverflow_0003205532_python.txt
Q: Next question about russian encoding, mssql and python Next question about russian encoding, mssql and python. I have this simple code: import pymssql import codecs conn=pymssql.connect(host='localhost:1433', user='sa', password='password', database='TvPgms') cur = conn.cursor() cur.execute('SELECT TOP 5 CAST( Name AS nvarchar(400) ), CONVERT(nvarchar(400), idProgram) FROM dbo.Programs') p=cur.fetchone() h=p[0] d=codecs.lookup(h) print h conn.close() I get the error: LookUp Error : Unnown Encoding: ????? ?????? ??????? I cant reed russian varchar filds from MSSQL. But when i just print string in the same code all is ok, it print me normal russian characters. Who know how? If I truing just print h insted of codecs.lookup than i get no error, but it prints me ???????? ????????? A: codecs.lookup takes an encoding name, not some random string, and you probably don't need it here anyway. I think at the moment you cannot reliably print Unicode strings from Python to the Windows console due to deep technical problems. Try writing to a file or using the WriteConsoleW function directly (via ctypes) instead.
Next question about russian encoding, mssql and python
Next question about russian encoding, mssql and python. I have this simple code: import pymssql import codecs conn=pymssql.connect(host='localhost:1433', user='sa', password='password', database='TvPgms') cur = conn.cursor() cur.execute('SELECT TOP 5 CAST( Name AS nvarchar(400) ), CONVERT(nvarchar(400), idProgram) FROM dbo.Programs') p=cur.fetchone() h=p[0] d=codecs.lookup(h) print h conn.close() I get the error: LookUp Error : Unnown Encoding: ????? ?????? ??????? I cant reed russian varchar filds from MSSQL. But when i just print string in the same code all is ok, it print me normal russian characters. Who know how? If I truing just print h insted of codecs.lookup than i get no error, but it prints me ???????? ?????????
[ "codecs.lookup takes an encoding name, not some random string, and you probably don't need it here anyway. I think at the moment you cannot reliably print Unicode strings from Python to the Windows console due to deep technical problems. Try writing to a file or using the WriteConsoleW function directly (via ctypes...
[ 2 ]
[]
[]
[ "console", "pymssql", "python", "unicode", "windows" ]
stackoverflow_0003205586_console_pymssql_python_unicode_windows.txt
Q: How to synchronize the output of Python subprocess I think I'm having issues to synchronize the output of two Popen running concurrently. It seems that the output from these two different command lines are interleaved with one another. I also tried using RLock to prevent this from happening but it didn't work. A sample output would be: cmd1 cmd1 cmd2 cmd2 cmd2 cmd2 cmd1 cmd2 The code is as attached: import subprocess import threading class PopenWorkerThread(threading.Thread): def __init__(self, cmdLine): self.lock = threading.RLock() self.WebSphereCmdLine = cmdLine threading.Thread.__init__(self) def run(self): logger.error('Runninf: ' + self.WebSphereCmdLine) proc = subprocess.Popen(self.WebSphereCmdLine, shell=False, stdout=subprocess.PIPE) while True: self.lock.acquire() print proc.stdout.readline() self.lock.release() def launch(): commandLine = ['ls -l', 'netstat'] for cmdLine in commandLine: workerThread = PopenWorkerThread(cmdLine) workerThread.start() launch() Is there a way to synchronize the outputs so that they look like such? cmd1 cmd1 cmd1 cmd1 cmd1 cmd2 cmd2 cmd2 cmd2 cmd2 A: Maybe you are looking for the wait method http://docs.python.org/library/subprocess.html#subprocess.Popen.wait A: You're locking with a granularity of a line, so of course lines from one thread can and do alternate with lines from the other. As long as you're willing to wait until a process ends before showing any of its output, you can lock with the larger "process" granularity. Of course you have to use the SAME lock for both threads -- having each thread use a completely separate lock, as you're doing now, cannot achieve anything at all, obviously. So, for example: import subprocess import threading class PopenWorkerThread(threading.Thread): lock = threading.RLock() # per-class, NOT per-instance! def __init__(self, cmdLine): self.WebSphereCmdLine = cmdLine threading.Thread.__init__(self) def run(self): logger.error('Runninf: ' + self.WebSphereCmdLine) proc = subprocess.Popen(self.WebSphereCmdLine, shell=False, stdout=subprocess.PIPE) result, _ = proc.communicate() with self.lock: print result, def launch(): commandLine = ['ls -l', 'netstat'] for cmdLine in commandLine: workerThread = PopenWorkerThread(cmdLine) workerThread.start() launch()
How to synchronize the output of Python subprocess
I think I'm having issues to synchronize the output of two Popen running concurrently. It seems that the output from these two different command lines are interleaved with one another. I also tried using RLock to prevent this from happening but it didn't work. A sample output would be: cmd1 cmd1 cmd2 cmd2 cmd2 cmd2 cmd1 cmd2 The code is as attached: import subprocess import threading class PopenWorkerThread(threading.Thread): def __init__(self, cmdLine): self.lock = threading.RLock() self.WebSphereCmdLine = cmdLine threading.Thread.__init__(self) def run(self): logger.error('Runninf: ' + self.WebSphereCmdLine) proc = subprocess.Popen(self.WebSphereCmdLine, shell=False, stdout=subprocess.PIPE) while True: self.lock.acquire() print proc.stdout.readline() self.lock.release() def launch(): commandLine = ['ls -l', 'netstat'] for cmdLine in commandLine: workerThread = PopenWorkerThread(cmdLine) workerThread.start() launch() Is there a way to synchronize the outputs so that they look like such? cmd1 cmd1 cmd1 cmd1 cmd1 cmd2 cmd2 cmd2 cmd2 cmd2
[ "Maybe you are looking for the wait method\nhttp://docs.python.org/library/subprocess.html#subprocess.Popen.wait\n", "You're locking with a granularity of a line, so of course lines from one thread can and do alternate with lines from the other. As long as you're willing to wait until a process ends before showi...
[ 1, 1 ]
[]
[]
[ "popen", "python" ]
stackoverflow_0003205990_popen_python.txt
Q: Semantics of python loops and strings Consider: args = ['-sdfkj'] print args for arg in args: print arg.replace("-", '') arg = arg.replace("-", '') print args This yields: ['-sdfkj'] sdfkj ['-sdfkj'] Where I expected it to be ['sdfkj']. Is arg in the loop a copy? It behaves as if it is a copy (or perhaps an immutable thingie, but then I expect an error would be thrown...) Note: I can get the right behavior with a list comprehension. I am curious as to the cause of the above behavior. A: Is arg in the loop a copy? Yes, it contains a copy of the reference. When you reassign arg you aren't modifying the original array, nor the string inside it (strings are immutable). You modify only what the local variable arg points to. Before assignment After assignment args arg args arg | | | | | | | | (array) / (array) 'sdfkj' |[0] / |[0] \ / | \ / | '-sdfkj' '-sdfkj' A: Since you mention in your question that you know it can be done using list comprehensions, I'm not going to show you that way. What is happening there is that the reference to each value is copied into the variable arg. Initially they both refer to the same variable. Once arg is reassigned, it refers to the newly created variable, while the reference in the list remains unchanged. It has nothing to do with the fact that strings are immutable in Python. Try it out using mutable types. A non-list comprehension way would be to modify the list in place: for i in xrange(len(args)): args[i]=args[i].replace('-','') print args A: If you want to modify the actual list you have to specifically assign the changes to the list 'args.' i.e. for arg in args: if arg == "-": args[arg] = args[arg].replace("-", '') A: for a list I'd try: args = [x.replace("-", '') for x in args]
Semantics of python loops and strings
Consider: args = ['-sdfkj'] print args for arg in args: print arg.replace("-", '') arg = arg.replace("-", '') print args This yields: ['-sdfkj'] sdfkj ['-sdfkj'] Where I expected it to be ['sdfkj']. Is arg in the loop a copy? It behaves as if it is a copy (or perhaps an immutable thingie, but then I expect an error would be thrown...) Note: I can get the right behavior with a list comprehension. I am curious as to the cause of the above behavior.
[ "\nIs arg in the loop a copy?\n\nYes, it contains a copy of the reference.\nWhen you reassign arg you aren't modifying the original array, nor the string inside it (strings are immutable). You modify only what the local variable arg points to. \nBefore assignment After assignment\n\nargs arg ...
[ 8, 1, 0, 0 ]
[]
[]
[ "python", "semantics" ]
stackoverflow_0003206375_python_semantics.txt
Q: matplotlib. How do I switch between subplots, rather than replotting them from scratch? I create a figure and fill it with a couple of subplots. As new data arrives, I'd like to draw it on a given subplot. How do I switch between subplots so that I don't have to create new subplot objects each time? Example: from matplotlib.pyplot import figure, figure() subplot(2,1,1) subplot(2,1,2) # now go back and plot something on subplot 1 ...? A: Assign subplot to a variable: fig = matplotlib.pyplot.figure() plt1 = fig.add_subplot(2,1,1) plt2 = fig.add_subplot(2,1,2) Then you can draw lines and points and whatever else you want with references to plt1 and plt2 Take a look at the reference for everything you can do with the plot.
matplotlib. How do I switch between subplots, rather than replotting them from scratch?
I create a figure and fill it with a couple of subplots. As new data arrives, I'd like to draw it on a given subplot. How do I switch between subplots so that I don't have to create new subplot objects each time? Example: from matplotlib.pyplot import figure, figure() subplot(2,1,1) subplot(2,1,2) # now go back and plot something on subplot 1 ...?
[ "Assign subplot to a variable:\nfig = matplotlib.pyplot.figure()\n\nplt1 = fig.add_subplot(2,1,1)\nplt2 = fig.add_subplot(2,1,2)\n\nThen you can draw lines and points and whatever else you want with references to plt1 and plt2\nTake a look at the reference for everything you can do with the plot.\n" ]
[ 8 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0003206335_matplotlib_python.txt
Q: Cannot concatenate 'str' and 'list' objects I'm getting a TypeError: cannot concatenate 'str' and 'list' objects. I'm trying to pass an object from a list to create a new variable by concatenating it with another variable. Example: I want to take the value from the group list and concatenate it with "All.dbf" so it will do something with that file for each value in my list. If working properly, it would set the value for dbname equal to AdministrativeAll.dbf, CadastralAll.dbf and PlanimetericAll.dbf respectively each time it runs through but I am getting the 'str' and 'list' error.... group = ['Administrative', 'Cadastral', 'Planimetric'] for i in group: dbname = i + "All.dbf" blah, blah, blah.... I suppose I could add the "All.dbf" onto the values in the group list but thought there must be a better way to process this with a function or something that I don't know about....any thoughts?? Cheers A: I suppose I could add the "All.dbf" onto the values in the group list but thought there must be a better way to process this with a function or something that I don't know about... You could use a list comprehension: group = [x + 'All.dbf' for x in group] A: dbname = [i+"All.dbf" for i in group] A: you will need to go though each item in the list and concatenate the two. A for each loop is your best bet. I'm not as familiar with python, so you might have to iterate over the list. A: Running this in 2.6.5: group = ['Administrative', 'Cadastral', 'Planimetric'] for i in group: dbname = i + "All.dbf" print 'Concat', dbname Gives the following output: Concat AdministrativeAll.dbf Concat CadastralAll.dbf Concat PlanimetricAll.dbf Worst case you can iterate through a range that is the length of the list, then do group[i] + "string to concatenate"
Cannot concatenate 'str' and 'list' objects
I'm getting a TypeError: cannot concatenate 'str' and 'list' objects. I'm trying to pass an object from a list to create a new variable by concatenating it with another variable. Example: I want to take the value from the group list and concatenate it with "All.dbf" so it will do something with that file for each value in my list. If working properly, it would set the value for dbname equal to AdministrativeAll.dbf, CadastralAll.dbf and PlanimetericAll.dbf respectively each time it runs through but I am getting the 'str' and 'list' error.... group = ['Administrative', 'Cadastral', 'Planimetric'] for i in group: dbname = i + "All.dbf" blah, blah, blah.... I suppose I could add the "All.dbf" onto the values in the group list but thought there must be a better way to process this with a function or something that I don't know about....any thoughts?? Cheers
[ "\nI suppose I could add the \"All.dbf\" onto the values in the group list but thought there must be a better way to process this with a function or something that I don't know about...\n\nYou could use a list comprehension:\ngroup = [x + 'All.dbf' for x in group]\n\n", "dbname = [i+\"All.dbf\" for i in group]\n\...
[ 5, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003206601_python.txt
Q: .class file from jython with pydev My first attempt at jython is a java/jython project I'm writing in eclipse with pydev. I created a java project and then made it a pydev project by the RightClick project >> pydev >> set as... you get the idea. I then added two source folders, one for java and one for jython, and each source folder has a package. And I set each folder as a buildpath for the project. I guess I'm letting you know all this so hopefully you can tell me wether or not I set the project up correctly. But the real question is: how do I get my jython code made into a class file so the java code can use it? The preferred method would be that eclipse/pydev would do this for me automatically, but I can't figure it out. Something mentioned in the jython users guide implies that it's possible but I can't find info on it anywhere. EDIT: I did find some information here and here, but things are not going too smooth. I've been following the guide in the second link pretty closely but I can't figure out how to get jythonc to make a constructor for my python class. A: Jythonc doesn't exist anymore, it has been forked off to another project called Clamp, but with that said... ...you can pre-compile your python scripts to .class files using: jython [jython home]/Lib/compileall.py [the directory where you keep your python code] Source - Jython Newsletter, March 2009 When I fed it a folder with Python 2.7 code (knowing it would fail in Jython 2.5) it did output a .class file, even though it doesn't function. Try that with your Jython scripts. If it works, please let us know, because I'll be where you are soon enough. Once you're that far, it isn't hard to convert your command line statement to an External Tool in PyDev that can be called as needed. A: Following the "Accessing Jython from Java Without Using jythonc" tutorial it became possible to use the jython modules inside java code. The only tricky point is that the *.py modules do not get compiled to *.class files. So it turns out to be exotic scripting inside java. The performance may of course degrade vs jythonc'ed py modules, but as I got from the jython community pages they are not going to support jythonc (and in fact have already dropped it in jython2.5.1). So if you decide to follow non-jythonc approach, the above tutorial is perfect. I had to modify the JythonFactory.java code a bit: String objectDef = "=" + javaClassName + "(your_constructor_params here)"; try { Class JavaInterface = Class.forName(interfaceName); System.out.println("JavaInterface=" + JavaInterface); javaInt = interpreter.get("instance name of a jython class from jython main function").__tojava__(JavaInterface); } catch (ClassNotFoundException ex) { ex.printStackTrace(); // Add logging here }
.class file from jython with pydev
My first attempt at jython is a java/jython project I'm writing in eclipse with pydev. I created a java project and then made it a pydev project by the RightClick project >> pydev >> set as... you get the idea. I then added two source folders, one for java and one for jython, and each source folder has a package. And I set each folder as a buildpath for the project. I guess I'm letting you know all this so hopefully you can tell me wether or not I set the project up correctly. But the real question is: how do I get my jython code made into a class file so the java code can use it? The preferred method would be that eclipse/pydev would do this for me automatically, but I can't figure it out. Something mentioned in the jython users guide implies that it's possible but I can't find info on it anywhere. EDIT: I did find some information here and here, but things are not going too smooth. I've been following the guide in the second link pretty closely but I can't figure out how to get jythonc to make a constructor for my python class.
[ "Jythonc doesn't exist anymore, it has been forked off to another project called Clamp, but with that said...\n\n...you can pre-compile\n your python scripts to .class files\n using:\njython [jython home]/Lib/compileall.py\n [the directory where you keep your\n python code]\n\nSource - Jython Newsletter, March ...
[ 5, 0 ]
[]
[]
[ "eclipse", "java", "jython", "pydev", "python" ]
stackoverflow_0001075905_eclipse_java_jython_pydev_python.txt
Q: __bases__ doesn't work! What's next? The following code doesn't work in Python 3.x, but it used to work with old-style classes: class Extender: def extension(self): print("Some work...") class Base: pass Base.__bases__ += (Extender,) Base().extension() Question is simple: How can I add dynamically (at runtime) a super class to a class in Python 3.x? But I'm ready the answer will be hard! ) A: It appears that it is possible to dynamically change Base.__bases__ if Base.__base__ is not object. (By dynamically change, I mean in such a way that all pre-existing instances that inherit from Base also get dynamically changed. Otherwise see Mykola Kharechko's solution). If Base.__base__ is some dummy class TopBase, then assignment to Base.__bases__ seems to work: class Extender(object): def extension(self): print("Some work...") class TopBase(object): pass class Base(TopBase): pass b=Base() print(Base.__bases__) # (<class '__main__.TopBase'>,) Base.__bases__ += (Extender,) print(Base.__bases__) # (<class '__main__.TopBase'>, <class '__main__.Extender'>) Base().extension() # Some work... b.extension() # Some work... Base.__bases__ = (Extender, TopBase) print(Base.__bases__) # (<class '__main__.Extender'>, <class '__main__.TopBase'>) Base().extension() # Some work... b.extension() # Some work... This was tested to work in Python 2 (for new- and old-style classes) and for Python 3. I have no idea why it works while this does not: class Extender(object): def extension(self): print("Some work...") class Base(object): pass Base.__bases__ = (Extender, object) # TypeError: __bases__ assignment: 'Extender' deallocator differs from 'object' A: As for me it is impossible. But you can create new class dynamically: class Extender(object): def extension(self): print("Some work...") class Base(object): pass Base = type('Base', (Base, Extender, object), {}) Base().extension()
__bases__ doesn't work! What's next?
The following code doesn't work in Python 3.x, but it used to work with old-style classes: class Extender: def extension(self): print("Some work...") class Base: pass Base.__bases__ += (Extender,) Base().extension() Question is simple: How can I add dynamically (at runtime) a super class to a class in Python 3.x? But I'm ready the answer will be hard! )
[ "It appears that it is possible to dynamically change Base.__bases__\nif Base.__base__ is not object. (By dynamically change, I mean in such a way that all pre-existing instances that inherit from Base also get dynamically changed. Otherwise see Mykola Kharechko's solution).\nIf Base.__base__ is some dummy class To...
[ 6, 5 ]
[]
[]
[ "multiple_inheritance", "python", "python_3.x", "runtime" ]
stackoverflow_0003193158_multiple_inheritance_python_python_3.x_runtime.txt
Q: How to use python build script with teamcity CI? I am currently researching using the TeamCity CI software for our comapanies CI automation needs but have had trouble finding information about using different build scripts with TeamCity. We have C++ projects that need to have build/test automation and we currently have licenses for TeamCity. I have looked into using scons for the build automation but havent been able to find much information about using a python build script with TeamCity. If anyone could provide information about this to a CI beginner would be much appreciated. Thanks A: We use TeamCity to run our acceptance test suite (which uses Robot Framework - done in python). Getting it to run was as simple as wrapping the python call with a very simple NAnt script. It does 2 things: Uses an exec task to run python with the script as an argument. Gets the xml output from the build and transforms it into something teamcity can understand. There are probably tasks to run python scripts directly with NAnt but we've not had to use them - it was pretty easy to get up and running. You could do the same sort of thing using Ant or whatever depending on what your platform was.
How to use python build script with teamcity CI?
I am currently researching using the TeamCity CI software for our comapanies CI automation needs but have had trouble finding information about using different build scripts with TeamCity. We have C++ projects that need to have build/test automation and we currently have licenses for TeamCity. I have looked into using scons for the build automation but havent been able to find much information about using a python build script with TeamCity. If anyone could provide information about this to a CI beginner would be much appreciated. Thanks
[ "We use TeamCity to run our acceptance test suite (which uses Robot Framework - done in python).\nGetting it to run was as simple as wrapping the python call with a very simple NAnt script. It does 2 things:\n\nUses an exec task to run python with the script as an argument.\nGets the xml output from the build and t...
[ 2 ]
[]
[]
[ "c++", "continuous_integration", "python", "teamcity" ]
stackoverflow_0003178165_c++_continuous_integration_python_teamcity.txt
Q: How to force using 64 bit python on Mac OS X? I got the following error when compiling sip with --arch x86_64 option. prosseek:siplib smcho$ python -c 'import sip; print sip' Traceback (most recent call last): File "", line 1, in ImportError: dlopen(./sip.so, 2): no suitable image found. Did find: ./sip.so: mach-o, but wrong architecture I found that the prebuilt Mac OS X python (snow leopard) is universal, and it doesn't get the 64 bit library. I guess it's running on 32bit mode. file /usr/bin/python /usr/bin/python: Mach-O universal binary with 3 architectures /usr/bin/python (for architecture x86_64): Mach-O 64-bit executable x86_64 /usr/bin/python (for architecture i386): Mach-O executable i386 /usr/bin/python (for architecture ppc7400): Mach-O executable ppc prosseek:siplib smcho$ file sip.so sip.so: Mach-O 64-bit bundle x86_64 How can I force python to run on 64bit mode? When I run the same code on Textmate, there's no problem. So, I think Textmate should run on 64 bit mode anyway. Added This link shows how to identify if a python that I'm running is 32bit or 64bit. And I checked my python is 32 bit. This link shows how to make 32/64bit python. But it doesn't work for me. A: Try using arch(1), and supply the specific version of Python: arch -x86_64 /usr/bin/python2.6 Actually the system should choose the first suitable architecture for you. As $ file /usr/bin/python2.5 /usr/bin/python2.5: Mach-O universal binary with 2 architectures /usr/bin/python2.5 (for architecture i386): Mach-O executable i386 /usr/bin/python2.5 (for architecture ppc7400): Mach-O executable ppc $ file /usr/bin/python2.6 /usr/bin/python2.6: Mach-O universal binary with 3 architectures /usr/bin/python2.6 (for architecture x86_64): Mach-O 64-bit executable x86_64 /usr/bin/python2.6 (for architecture i386): Mach-O executable i386 /usr/bin/python2.6 (for architecture ppc7400): Mach-O executable ppc If that python somehow chooses 2.5, then you can't use 64-bit, but if it chooses 2.6 then the x86_64 variant should be automatically selected, as commented below. If it's the former, try to get python_select and change the version to 2.6. A: Okay, be REALLY careful when you do this, it's going to require other things to also be 64-bit. All of a sudden, if mod_python won't work, then you need to recompile apache. Then all your python modules like tkinter/tix. If you're on 10.5 like me, don't go there, just live with 32-bit for it. And if you don't know about http://www.macports.org/ then remember that it's your friend. :-)
How to force using 64 bit python on Mac OS X?
I got the following error when compiling sip with --arch x86_64 option. prosseek:siplib smcho$ python -c 'import sip; print sip' Traceback (most recent call last): File "", line 1, in ImportError: dlopen(./sip.so, 2): no suitable image found. Did find: ./sip.so: mach-o, but wrong architecture I found that the prebuilt Mac OS X python (snow leopard) is universal, and it doesn't get the 64 bit library. I guess it's running on 32bit mode. file /usr/bin/python /usr/bin/python: Mach-O universal binary with 3 architectures /usr/bin/python (for architecture x86_64): Mach-O 64-bit executable x86_64 /usr/bin/python (for architecture i386): Mach-O executable i386 /usr/bin/python (for architecture ppc7400): Mach-O executable ppc prosseek:siplib smcho$ file sip.so sip.so: Mach-O 64-bit bundle x86_64 How can I force python to run on 64bit mode? When I run the same code on Textmate, there's no problem. So, I think Textmate should run on 64 bit mode anyway. Added This link shows how to identify if a python that I'm running is 32bit or 64bit. And I checked my python is 32 bit. This link shows how to make 32/64bit python. But it doesn't work for me.
[ "Try using arch(1), and supply the specific version of Python:\narch -x86_64 /usr/bin/python2.6\n\nActually the system should choose the first suitable architecture for you. As\n$ file /usr/bin/python2.5\n/usr/bin/python2.5: Mach-O universal binary with 2 architectures\n/usr/bin/python2.5 (for architecture i386): M...
[ 6, 1 ]
[]
[]
[ "64_bit", "macos", "python", "python_sip" ]
stackoverflow_0003207324_64_bit_macos_python_python_sip.txt
Q: how do i set my python path for success with my import statements? I'm trying to install djangobb and when running manage.py syncdb it returns with Traceback (most recent call last): File "manage.py", line 2, in <module> from django.core.management import execute_manage ImportError: No module named django.core.management I know that deep in my python installation there is django/core/management, but I just don't know how to get manage.py to find it for me. Can someone point me in the right direction please? A: Make sure that the base directory for where django/ lives is on your $PYTHONPATH
how do i set my python path for success with my import statements?
I'm trying to install djangobb and when running manage.py syncdb it returns with Traceback (most recent call last): File "manage.py", line 2, in <module> from django.core.management import execute_manage ImportError: No module named django.core.management I know that deep in my python installation there is django/core/management, but I just don't know how to get manage.py to find it for me. Can someone point me in the right direction please?
[ "Make sure that the base directory for where django/ lives is on your $PYTHONPATH\n" ]
[ 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003207049_django_python.txt
Q: DTML: How to prevent formatting loss I have a DTML document which only contains: <dtml-var public_blast_results> and displays when i view it as: YP_001336283 100.00 345 0 0 23 367 23 367 0.0 688 When I edit the DTML page for example just adding a header like: <h3>Header</h3> <dtml-var public_blast_results> The "public_blast_results" loeses its formatting and displayes as: Header YP_001336283 100.00 345 0 0 23 367 23 367 0.0 688 Is there a way for maintaining the formatting? public_blast_results is a python function which just simply reads the contents of a file and returns it. A: This is nothing to do with DTML - it's a basic issue with HTML, which is that it ignores whitespace. If you want to preserve it, you need to wrap the content with <pre>. <pre><dtml-var public_blast_results></pre>
DTML: How to prevent formatting loss
I have a DTML document which only contains: <dtml-var public_blast_results> and displays when i view it as: YP_001336283 100.00 345 0 0 23 367 23 367 0.0 688 When I edit the DTML page for example just adding a header like: <h3>Header</h3> <dtml-var public_blast_results> The "public_blast_results" loeses its formatting and displayes as: Header YP_001336283 100.00 345 0 0 23 367 23 367 0.0 688 Is there a way for maintaining the formatting? public_blast_results is a python function which just simply reads the contents of a file and returns it.
[ "This is nothing to do with DTML - it's a basic issue with HTML, which is that it ignores whitespace. If you want to preserve it, you need to wrap the content with <pre>.\n<pre><dtml-var public_blast_results></pre>\n\n" ]
[ 2 ]
[]
[]
[ "html", "python" ]
stackoverflow_0003206812_html_python.txt
Q: PyCrypto and GMP library not found error [Mac OS 10.6.3] I'm trying to install pycrypto-2.1.0 but attempt to do with 'python setup.py build' elicits: running build running build_py running build_ext warning: GMP library not found; Not building Crypto.PublicKey._fastmath. I installed GMP (gmp-4.3.2) and it's in: /usr/local/lib How do I get python/pycrypto to recognize that GMP is already present on my system? Mac OS: 10.6.3 Python version: 2.6.1 A: Looking at setup.py for pycrypto, it only searches for GMP in /lib and /usr/lib. To fix this, either change setup.py to also search /usr/local/lib by adding it to the list on line 155 (recommended), or reinstall GMP into /lib or /usr/lib (not recommended but would work). You may also need to add self.__add_compiler_option('-I/usr/local/include'); self.__add_compiler_option('-L/usr/local/lib') in order for the compiler to find the proper include files and static libraries if it doesn't include those paths by default. A: I have the same problem but libgmp located in /usr/lib, and /usr/local/lib is empty. Problem solved by installing gmp-devel and python-devel packages. A: sudo ln -s /usr/local/lib/libgmp.dylib /usr/lib/libgmp.dylib A: Mmm, you should put more log lines. I had that error, but my problem was that I didn't install the python-dev package in my Ubuntu Karmic.
PyCrypto and GMP library not found error [Mac OS 10.6.3]
I'm trying to install pycrypto-2.1.0 but attempt to do with 'python setup.py build' elicits: running build running build_py running build_ext warning: GMP library not found; Not building Crypto.PublicKey._fastmath. I installed GMP (gmp-4.3.2) and it's in: /usr/local/lib How do I get python/pycrypto to recognize that GMP is already present on my system? Mac OS: 10.6.3 Python version: 2.6.1
[ "Looking at setup.py for pycrypto, it only searches for GMP in /lib and /usr/lib. To fix this, either change setup.py to also search /usr/local/lib by adding it to the list on line 155 (recommended), or reinstall GMP into /lib or /usr/lib (not recommended but would work).\nYou may also need to add self.__add_compi...
[ 3, 3, 2, 0 ]
[]
[]
[ "macos", "python" ]
stackoverflow_0002709661_macos_python.txt
Q: AdaBoost ML algorithm python implementation Is there anyone that has some ideas on how to implement the AdaBoost (Boostexter) algorithm in python? Cheers! A: It looks as if the sdpy project has an AdaBoost implementation. Specifically look at the sdpy/cs/ml/cla/boosting.py file. Perhaps you can get some motivation from there. A: Thanks a million Steve! In fact, your suggestion had some compatibility issues with MacOSX (a particular library was incompatible with the system) BUT it helped me find out a more interesting package : icsi.boost.macosx. I am just denoting that in case any Mac-eter finds it interesting! Thank you again! Tim
AdaBoost ML algorithm python implementation
Is there anyone that has some ideas on how to implement the AdaBoost (Boostexter) algorithm in python? Cheers!
[ "It looks as if the sdpy project has an AdaBoost implementation. Specifically look at the sdpy/cs/ml/cla/boosting.py file.\nPerhaps you can get some motivation from there.\n", "Thanks a million Steve! In fact, your suggestion had some compatibility issues with MacOSX (a particular library was incompatible with th...
[ 3, 2 ]
[]
[]
[ "adaboost", "machine_learning", "python" ]
stackoverflow_0003193756_adaboost_machine_learning_python.txt
Q: Caching the results of a function with two parameters in Python I have a method with two parameters that does some complex computation. It is called very often with the same parameters, so I am using a dictionary for caching. Currently this looks something like this: def foo(self, a, b): params = frozenset([a, b]) if not params in self._cache: self._cache[params] = self._calculate(a, b) return self._cache[params] The reason for building the frozenset is that the parameters can be in any order, but the result will be the same. I am wondering if there is a simpler (and most importantly more efficient) solution for this. A: There's nothing particularly inefficient or complicated about how you implemented your caching; that's essentially what needs to happen. It isn't very general, however. You can implement some sort of more generalized caching strategy, using decorators if you like, for convenience. One possible approach might be: class Memoizer(object): def __init__(self): self._cache = dict() def memoize_unordered(self, f): def wrapper(s, *args, **kwargs): key = (s, f, frozenset(args), frozenset(kwargs.iteritems())) if key not in self._cache: print 'calculating', args, kwargs self._cache[key] = f(s, *args, **kwargs) return self._cache[key] return wrapper def memoize_ordered(self, f): def wrapper(s, *args, **kwargs): key = (s, f, tuple(args), frozenset(kwargs.iteritems())) if key not in self._cache: print 'calculating', args, kwargs self._cache[key] = f(s, *args, **kwargs) return self._cache[key] return wrapper memoizer = Memoizer() class Foo(object): @memoizer.memoize_unordered def foo(self, a, b): return self._calculate(a, b) def _calculate(self, a, b): return frozenset([a,b]) foo = Foo() results = [foo.foo(*a) for a in [(1, 5), (1, 5), (5, 1), (9, 12), (12, 9)]] for result in results: print 'RESULT', result printing: calculating (1, 5) {} calculating (9, 12) {} RESULT frozenset([1, 5]) RESULT frozenset([1, 5]) RESULT frozenset([1, 5]) RESULT frozenset([9, 12]) RESULT frozenset([9, 12]) The downside of course, to implementing caching outside of your object, is that the cache data doesn't get deleted when your object goes away, unless you take some care to make this happen. A: You can either combine the two values into one hash value like str(a)+'\0'+str(b) and then put it into a cache, or you can make a two-dimensional array so that cache[a][b] returns the value you want. You may also want to turn this functionality into a @decorator kind of function, then you can reuse the decorator on several functions and maintain one code location for the caching. A: I'd just store it in the cache twice, once for each ordering. def foo(self, a, b): try: return self._cache[(a, b)] except KeyError: value = self._calculate(a, b) self._cache[(a, b)] = self._cache[(b, a)] = value return value A: You could use beaker.cache for that (http://beaker.groovie.org/index.html) # define a cache manager cache = CacheManager(dict_of_config_options) # in your class, apply a cache decorator @cache.cache('mycache') def foo(self, a,b): return self._calculate I think it works like you want by default. Not sure if this uses self as part of the key. It assumes that a, b are pickleable. A: Your code has two problems: (1) It uses the old dict.has_key() method which is slow and has vanished in Python 3.x. Instead use "key in dict" or "key not in dict". So: def foo(self, a, b): params = frozenset([a, b]) if params in self._cache: self._cache[params] = self._calculate(a, b) return self._cache[params] (2) "key in dict" is more readable, and exposes the much worse problem: your code doesn't work! If the args are in the dict, it recalculates. If they're not in the dict, it will blow up with a KeyError. Consider copy/paste instead of typing from memory. So: def foo(self, a, b): params = frozenset([a, b]) if params not in self._cache: self._cache[params] = self._calculate(a, b) return self._cache[params] (3) Some more efficiency suggestions: def foo(self, a, b): if a < b: params = (a, b) else: params = (b, a) try: return self._cache[params] except KeyError: v = self._cache[params] = self._calculate(a, b) return v
Caching the results of a function with two parameters in Python
I have a method with two parameters that does some complex computation. It is called very often with the same parameters, so I am using a dictionary for caching. Currently this looks something like this: def foo(self, a, b): params = frozenset([a, b]) if not params in self._cache: self._cache[params] = self._calculate(a, b) return self._cache[params] The reason for building the frozenset is that the parameters can be in any order, but the result will be the same. I am wondering if there is a simpler (and most importantly more efficient) solution for this.
[ "There's nothing particularly inefficient or complicated about how you implemented your caching; that's essentially what needs to happen. It isn't very general, however.\nYou can implement some sort of more generalized caching strategy, using decorators if you like, for convenience. One possible approach might be...
[ 2, 0, 0, 0, 0 ]
[]
[]
[ "caching", "python" ]
stackoverflow_0003207253_caching_python.txt
Q: Email to HTML in Python I am looking for a library which can take a raw email message and convert it to appropriate HTML in Python. Any help will be appreciated. A: Use the MIME package included in email http://docs.python.org/library/email Here some examples http://docs.python.org/library/email-examples.html A: Here's some Python code to convert text to HTML A: You have two choices, If the email has a HTML payload, you can use that - maybe put a simple template together to wrap whatever metadata fields (from, to, subject, date etc.) you need. If there is no html body, you can just wrap it in a <pre></pre> - use the same template. Sorry, I can't name a library - there is not a lot to do. What you can do is identify an open source app that handles email in a way you like it and take a look at the code. like this ppwm at sourceforge
Email to HTML in Python
I am looking for a library which can take a raw email message and convert it to appropriate HTML in Python. Any help will be appreciated.
[ "Use the MIME package included in email\nhttp://docs.python.org/library/email\nHere some examples http://docs.python.org/library/email-examples.html\n", "Here's some Python code to convert text to HTML\n", "You have two choices, \nIf the email has a HTML payload, you can use that - maybe put a simple template t...
[ 1, 0, 0 ]
[]
[]
[ "email", "html", "python" ]
stackoverflow_0003206371_email_html_python.txt
Q: question about splitting a large file Hey I need to split a large file in python into smaller files that contain only specific lines. How do I do this? A: You're probably going to want to do something like this: big_file = open('big_file', 'r') small_file1 = open('small_file1', 'w') small_file2 = open('small_file2', 'w') for line in big_file: if 'Charlie' in line: small_file1.write(line) if 'Mark' in line: small_file2.write(line) big_file.close() small_file1.close() small_file2.close() Opening a file for reading returns an object that allows you to iterate over the lines. You can then check each line (which is just a string of whatever that line contains) for whatever condition you want, then write it to the appropriate file that you opened for writing. It is worth noting that when you open a file with 'w' it will overwrite anything already written to that file. If you want to simply add to the end, you should open it with 'a', to append. Additionally, if you expect there to be some possibility of error in your reading/writing code, and want to make sure the files are closed, you can use: with open('big_file', 'r') as big_file: <do stuff prone to error> A: Do you mean breaking it down into subsections? Like if I had a file with chapter 1, chapter 2, and chapter 3, you want it to be broken down into separate files for each chapter? The way I've done this is similar to Wilduck's response, but closes the input file as soon as it reads in the data and keeps all the lines read in. data_file = open('large_file_name', 'r') lines = data_file.readlines() data_file.close() outputFile = open('output_file_one', 'w') for line in lines: if 'SomeName' in line: outputFile.write(line) outputFile.close() If you wanted to have more than one output file you could either add more loops or open more than one outputFile at a time. I'd recommend using Wilducks response, however, as it uses less space and will take less time with larger files since the file is read only once. A: How big and does it need to be done in python? If this is on unix, would split/csplit/grep suffice? A: First, open the big file for reading. Second, open all the smaller file names for writing. Third, iterate through every line. Every iteration, check to see what kind of line it is, then write it to that file. More info on File I/O: http://docs.python.org/tutorial/inputoutput.html
question about splitting a large file
Hey I need to split a large file in python into smaller files that contain only specific lines. How do I do this?
[ "You're probably going to want to do something like this:\nbig_file = open('big_file', 'r')\nsmall_file1 = open('small_file1', 'w')\nsmall_file2 = open('small_file2', 'w')\n\nfor line in big_file:\n if 'Charlie' in line: small_file1.write(line)\n if 'Mark' in line: small_file2.write(line)\n\nbig_file.close()\...
[ 5, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003207719_python.txt
Q: python: access multiple values in the value portion of a key:value pair I am trying to perform a calculation on multiple values in the value portion of a list of key:value pairs. So I have something like: [('apples', ['254', '234', '23', '33']), ('bananas', ['732', '28']), ('squash', ['3'])] I'm trying to create a list of y-values that are the averages of those integers above. What I'm trying to write is the following pseudocode if item[1] contains 0 elements: ys.append(item[1]) else if item[1] contains > 0 elements: add up elements, divide by number of elements ys.append average number What I'm not sure how to do is how to access all of the values that might exist in each key's value set. A: Where pairs is your list of pairs: averages = [float(sum(values)) / len(values) for key, values in pairs] will give you a list of average values. If your numbers are strings, as in your example, replace sum(values) above with sum([int(i) for i in values]). EDIT: And if you rather want a dictionary then a list of averages: averages = dict([(key, float(sum(values)) / len(values)) for key, values in pairs]) A: ys = [] for k, v in items: avg = sum(map(float, v))/len(v) ys.append(v) A: You can find the mean of a list by sum(float(i) for i in lst) / len(lst) If the elements of the list were integers, you could do float(sum(lst)) / len(lst) but in your example they're strings, so you have to convert them. In this case I would actually recommend using Python's list comprehension facility to automatically create a list of the averages. If your original list of pairs is named, say, fruit_list (I know squash is not a fruit, so sue me): averages = [[] if len(values) == 0 else sum(float(i) for i in values)/len(values) for fruit, values in fruit_list] Although it seems a little odd, because then you'll get a list in which some elements are floating-point numbers and other elements are empty lists. Are you sure you didn't mean to use, say, 0 instead of [] when there are no values in item[1]?
python: access multiple values in the value portion of a key:value pair
I am trying to perform a calculation on multiple values in the value portion of a list of key:value pairs. So I have something like: [('apples', ['254', '234', '23', '33']), ('bananas', ['732', '28']), ('squash', ['3'])] I'm trying to create a list of y-values that are the averages of those integers above. What I'm trying to write is the following pseudocode if item[1] contains 0 elements: ys.append(item[1]) else if item[1] contains > 0 elements: add up elements, divide by number of elements ys.append average number What I'm not sure how to do is how to access all of the values that might exist in each key's value set.
[ "Where pairs is your list of pairs:\naverages = [float(sum(values)) / len(values) for key, values in pairs]\n\nwill give you a list of average values.\nIf your numbers are strings, as in your example, replace sum(values) above with sum([int(i) for i in values]).\nEDIT: And if you rather want a dictionary then a lis...
[ 2, 0, 0 ]
[]
[]
[ "dictionary", "key_value", "python" ]
stackoverflow_0003208076_dictionary_key_value_python.txt
Q: Regex to match Domain.CCTLD Does anyone know a regular expression to match Domain.CCTLD? I don't want subdomains, only the "atomic domain". For example, docs.google.com doesn't get matched, but google.com does. However, this gets complicated with stuff like .co.uk, CCTLDs. Does anyone know a solution? Thanks in advance. EDIT: I've realized I also have to deal with multiple subdomains, like john.doe.google.co.uk. Need a solution now more than ever :P. A: It sounds like you are looking for the information available through the Public Suffix List project. A "public suffix" is one under which Internet users can directly register names. Some examples of public suffixes are ".com", ".co.uk" and "pvt.k12.wy.us". The Public Suffix List is a list of all known public suffixes. There is no single regular expression that will reasonably match the list of public suffixes. You will need to implement code to use the public suffix list, or find an existing library that already does so. A: Based on your comment above, I'm going to reinterpret the question -- rather than making a regex that will match them, we'll create a function that will match them, and apply that function to filter a list of domain names to only include first class domains, e.g. google.com, amazon.co.uk. First, we'll need a list of TLDs. As Greg mentioned, the public suffix list is a great place to start. Let's assume you've parsed the list into a python array called suffixes. If this isn't something your comfortable with, comment and I can add some code that will do it. suffixes = parse_suffix_list("suffix_list.txt") Now we'll need code that identifies whether a given domain name matches the pattern some-name.suffix: def is_domain(d): for suffix in suffixes: if d.endswith(suffix): # Get the base domain name without suffix base_name = d[0:-(suffix.length + 1)] # If it contains '.', it's a subdomain. if not base_name.contains('.'): return true # If we get here, no matches were found return false A: I would probably solve this by getting a complete list of TLDs and using it to create the regex. For example (in Ruby, sorry, not a Pythonista yet): tld_alternation = ['\.com','\.co\.uk','\.eu','\.org',...].join('|') regex = /^[a-z0-9]([a-z0-9\-]*[a-z0-9])?(#{tld_alternation})$/i I don't think it's possible to properly differentiate between a real two part TLD and a subdomain without knowing the actual list of TLDs (ie: you could always construct a subdomain that looks like a TLD if you knew how the regex worked.)
Regex to match Domain.CCTLD
Does anyone know a regular expression to match Domain.CCTLD? I don't want subdomains, only the "atomic domain". For example, docs.google.com doesn't get matched, but google.com does. However, this gets complicated with stuff like .co.uk, CCTLDs. Does anyone know a solution? Thanks in advance. EDIT: I've realized I also have to deal with multiple subdomains, like john.doe.google.co.uk. Need a solution now more than ever :P.
[ "It sounds like you are looking for the information available through the Public Suffix List project. \n\nA \"public suffix\" is one under which Internet users can directly register names. Some examples of public suffixes are \".com\", \".co.uk\" and \"pvt.k12.wy.us\". The Public Suffix List is a list of all known ...
[ 8, 3, 2 ]
[]
[]
[ "dns", "python", "regex", "subdomain", "tld" ]
stackoverflow_0003199343_dns_python_regex_subdomain_tld.txt
Q: Nested exceptions? Will this work? try: try: field.value = filter(field.value, fields=self.fields, form=self, field=field) except TypeError: field.value = filter(field.value) except ValidationError, e: field.errors += e.args field.value = revert valid = False break Namely, if that first line throws a ValidationError, will the second except catch it? I would have written it un-nested, but the second filter statement can fail too! And I want to use the same ValidationError block to catch that as well. I'd test it myself, but this code is so interwoven now it's difficult to trip it properly :) As a side note, is it bad to rely on it catching the TypeError and passing in only one arg instead? i.e., deliberately omitting some arguments where they aren't needed? A: If the filter statement in the inner try raises an exception, it will first get checked against the inner set of "except" statements and then if none of those catch it, it will be checked against the outer set of "except" statements. You can convince yourself this is the case just by doing something simple like this (this will only print "Caught the value error"): try: try: raise ValueError('1') except TypeError: print 'Caught the type error' except ValueError: print 'Caught the value error!' As another example, this one should print "Caught the inner ValueError" only: try: try: raise ValueError('1') except TypeError: pass except ValueError: print 'Caught the inner ValueError!' except ValueError: print 'Caught the outer value error!' A: To compliment Brent's answer, and test the other case: class ValidationError(Exception): pass def f(a): raise ValidationError() try: try: f() except TypeError: f(1) except ValidationError: print 'caught1' try: try: f(1) except TypeError: print 'oops' except ValidationError: print 'caught2' Which prints: caught1 caught2
Nested exceptions?
Will this work? try: try: field.value = filter(field.value, fields=self.fields, form=self, field=field) except TypeError: field.value = filter(field.value) except ValidationError, e: field.errors += e.args field.value = revert valid = False break Namely, if that first line throws a ValidationError, will the second except catch it? I would have written it un-nested, but the second filter statement can fail too! And I want to use the same ValidationError block to catch that as well. I'd test it myself, but this code is so interwoven now it's difficult to trip it properly :) As a side note, is it bad to rely on it catching the TypeError and passing in only one arg instead? i.e., deliberately omitting some arguments where they aren't needed?
[ "If the filter statement in the inner try raises an exception, it will first get checked against the inner set of \"except\" statements and then if none of those catch it, it will be checked against the outer set of \"except\" statements. \nYou can convince yourself this is the case just by doing something simple ...
[ 25, 2 ]
[]
[]
[ "python" ]
stackoverflow_0003208566_python.txt
Q: Get Mac idle time C or Python How can i get system idle time (no keys pressed - mouse moved) in C or Python? EDIT: My program suspend a counter when idle time > 10 sec A: I don't have a Mac to test on at the moment, so cannot confirm this works, but this thread seems to offer the solution you're looking for: http://www.dssw.co.uk/sleepcentre/threads/system_idle_time_how_to_retrieve.html In a nutshell, use the subprocess module and call: ioreg -c IOHIDSystem Then parse the output, and divide the value by 10^9 to get the idle time in seconds. A: If you mean the time spent during the course of a program, after the program is done, then the easiest thing to do is run the unix "time" function: # echo foo foo # time echo foo foo real 0m0.000s user 0m0.000s sys 0m0.000s There's a more technical answer if you really need to be doing the data collection while the program is running - I'll take a look at the unix book for you... Update: clock_t times( struct tms *buf ); Look up the details on the manpage or in section 8.15 of "Advanced Programming in the UNIX Environment" - Stevens - the bible for these kinds of questions. Update 2: Run "sar" in another process (it's like a stdout-printing version of top), look for a result you want, and send a signal to the process. Alternately, the other solution posted regarding "ioreg". However, if you have a program that is itself "kernel-like" in nature, with a big action loop at its core, you may find it best to keep track of unused cycles yourself. Otherwise, this is a non-trivial problem to solve. A: what about that in python ( win ) ? like time module in standard lib of python ... ? A: Is your application GUI-driven? If so, you could start a timer when the GUI comes up and then have keyboard and mouse callbacks at the top level. Every time the keyboard or mouse callback is triggered, reset the timer. Otherwise when the timer goes off, it's handler code should suspend your counter. If not, ignore this... ;-)
Get Mac idle time C or Python
How can i get system idle time (no keys pressed - mouse moved) in C or Python? EDIT: My program suspend a counter when idle time > 10 sec
[ "I don't have a Mac to test on at the moment, so cannot confirm this works, but this thread seems to offer the solution you're looking for:\nhttp://www.dssw.co.uk/sleepcentre/threads/system_idle_time_how_to_retrieve.html\nIn a nutshell, use the subprocess module and call:\nioreg -c IOHIDSystem\n\nThen parse the out...
[ 3, 0, 0, 0 ]
[]
[]
[ "c", "macos", "python", "python_idle" ]
stackoverflow_0003208450_c_macos_python_python_idle.txt
Q: Suggest category for a piece of text I've been searching for a opensource solution to suggest a category given a question or text. For example, "who is Lady Gaga?" would probably return 'Entertainment', 'Music', or 'Celebrity'. "How many strike out there are for baseball?" would give me 'Baseball', or 'Sport'. The categorization doesn't have to be perfect but should be some what close. Also is there anywhere I can get a list of popular categories? A: This is a document classification problem - your "document" is simply the query or text. You'll first need to decide what the list of possible categories is. "Who is Lady Gaga?" could be Entertainment, Celebrity, Questions-In-English, Biography, People, etc. Next you'll apply a decision framework to assign a score for each category to the text. The highest score is its category - as long as it's above a noise threshold and there isn't a second-place category that's too close to differentiate. Decision frameworks can include approaches like a Bayesian network or a set of custom rules. Some open source projects that implement classifiers include: Classifier4J Matlab Classification Toolbox POPFile (for email) OpenNLP Maximum Entropy Package A: Screen scrape Wolfram alpha. http://www.wolframalpha.com/input/?i=Who+is+lady+gaga http://www.wolframalpha.com/input/?i=What+is+baseball You can probably get a good list of categories from dmoz. A: Not much of an answer, but perhaps this categorized dictionary would help: http://www.provalisresearch.com/wordstat/WordNet.html I imagine you could extract the uncommon words from the string, look them up in the categorized dictionary, and return the categories that get the most matches on your terms. It'll be tricky to deal with pop culture references like "Lady Gaga", though...maybe you could do a Google search and analyze the results of that. A: Others have done quite a bit of work on your behalf, so I'd suggest just using something like the OpenCalais API. There's a python wrapper to the API at http://code.google.com/p/python-calais/. "Who is Lady Gaga?" seems to be too short a piece of text for them to give a decent response. However, if you took the trouble to do a two step process and grab the first paragraph from wikipedia for Lady Gaga, and then supply that to the OpenCalais API you get very good results. You can check it out quickly by just cut and pasting the first paragraph from wikipedia into the OpenCalais viewer. The result is a classification into the topic "Entertainment Culture" with a 100% confidence estimate. Similarly, the baseball example returns "sports" as the topic with further social tags of "recreation", "baseball" etc. Edit Here's another thought prompted by Calais' use of social tags: sending the wikipedia url for Lady Gaga to the delicious API with curl -k https://user:password@api.del.icio.us/v1/posts/suggest?url=http://en .wikipedia.org/wiki/Lady_gaga returns <?xml version="1.0" encoding="UTF-8"?> <suggest> <recommended>music</recommended> <recommended>wikipedia</recommended> <recommended>wiki</recommended> <recommended>people</recommended> <recommended>bio</recommended> <recommended>cool</recommended> <recommended>facts</recommended> <popular>music</popular> <popular>gaga</popular> <popular>ladygaga</popular> <popular>wikipedia</popular> <popular>lady</popular> etc. Should be easy enough to ignore the wikipedia/wiki type entries.
Suggest category for a piece of text
I've been searching for a opensource solution to suggest a category given a question or text. For example, "who is Lady Gaga?" would probably return 'Entertainment', 'Music', or 'Celebrity'. "How many strike out there are for baseball?" would give me 'Baseball', or 'Sport'. The categorization doesn't have to be perfect but should be some what close. Also is there anywhere I can get a list of popular categories?
[ "This is a document classification problem - your \"document\" is simply the query or text. \nYou'll first need to decide what the list of possible categories is. \"Who is Lady Gaga?\" could be Entertainment, Celebrity, Questions-In-English, Biography, People, etc. Next you'll apply a decision framework to assign a...
[ 3, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003208398_python.txt
Q: additional python installed upon installing matplotlib with macports I am having trouble installing matplotlib on mac os 10.6, so I used macports and installed all dependencies it needed, which is great, but on top of it a new python version. Now I have two python versions and that bothers me. The matplotlib is working fine on the macport python, and the rest of my stuff is with the default python. What is the best solution for integrating both into one, and which one to use as the default python? I tried copying all packages from my default python /defaultPython/../site-packages into the /opt/../site-packages. Same thing would be to add /defaultPython/../site-packages on the PYTHONPATH of macports python. Some did work fine, but not all. For example on import scipy.sparse I got this error import _csr ImportError: dlopen(/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/scipy/sparse/sparsetools/_csr.so, 2): no suitable image found. Did find: /opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/scipy/sparse/sparsetools/_csr.so: no matching architecture in universal wrapper Any thoughts or dirty fix for this? Thanks a lot! A: You should never remove or alter the system Python that Apple supplies with Mac OS X -- that's the specific build they've tested their OS with, and you really don't want to break that. If you want to use handy macports-installed extensions, you need the macports version of Python for that purpose, so you can't remove that either. There is no real reason to worry because you have more than one Python version on your system (I typically have at least half a dozen on mine;-). Just put /opt/... (wherever macports keeps its bin directory) at the start of your PATH environment variable (e.g. in .bashrc) and make sure you install with the macports Python any extension you need there.
additional python installed upon installing matplotlib with macports
I am having trouble installing matplotlib on mac os 10.6, so I used macports and installed all dependencies it needed, which is great, but on top of it a new python version. Now I have two python versions and that bothers me. The matplotlib is working fine on the macport python, and the rest of my stuff is with the default python. What is the best solution for integrating both into one, and which one to use as the default python? I tried copying all packages from my default python /defaultPython/../site-packages into the /opt/../site-packages. Same thing would be to add /defaultPython/../site-packages on the PYTHONPATH of macports python. Some did work fine, but not all. For example on import scipy.sparse I got this error import _csr ImportError: dlopen(/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/scipy/sparse/sparsetools/_csr.so, 2): no suitable image found. Did find: /opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/scipy/sparse/sparsetools/_csr.so: no matching architecture in universal wrapper Any thoughts or dirty fix for this? Thanks a lot!
[ "You should never remove or alter the system Python that Apple supplies with Mac OS X -- that's the specific build they've tested their OS with, and you really don't want to break that.\nIf you want to use handy macports-installed extensions, you need the macports version of Python for that purpose, so you can't re...
[ 1 ]
[]
[]
[ "macports", "matplotlib", "python" ]
stackoverflow_0003208803_macports_matplotlib_python.txt