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: How can I determine the final URL after redirection using python / urllib2? I need to get the final URL after redirection in python. What's a good way to do that? A: >>> import urllib2 >>> var = urllib2.urlopen('http://www.stackoverflow.com/') >>> var.geturl() 'http://stackoverflow.com/'
How can I determine the final URL after redirection using python / urllib2?
I need to get the final URL after redirection in python. What's a good way to do that?
[ ">>> import urllib2\n>>> var = urllib2.urlopen('http://www.stackoverflow.com/')\n>>> var.geturl()\n'http://stackoverflow.com/'\n\n" ]
[ 8 ]
[]
[]
[ "python", "redirect", "urllib2" ]
stackoverflow_0002374122_python_redirect_urllib2.txt
Q: Django - Working with multiple forms What I'm trying to do is to manage several forms in one page, I know there are formsets, and I know how the form management works, but I got some problems with the idea I have in mind. Just to help you to imagine what my problem is I'm going to use the django example models: from django.db import models class Poll(models.Model): question = models.CharField(max_length=200) pub_date = models.DateTimeField() class Choice(models.Model): poll = models.ForeignKey(Poll) choice = models.CharField(max_length=200) votes = models.IntegerField(default=0) Now, imagine I've already made the form clases: from django import forms from mysite.polls.models import Poll, Choice class PollForm(forms.ModelForm): class Meta: model = Poll class ChoiceForm(forms.ModelForm): class Meta: model = Choice exclude = ('poll',) So what I want to do is to have several form instances of the Poll and Choice model in a single page, but mind that these models can be repeated too: <form action="{{url}}" method="post"> {{pollform}} {{choiceform}} {{pollform}} </form> As you can see there are two Poll forms and one Choice form, but the Poll forms are separated by the Choice form. I do need that the forms keep their order in the page, so is a little harder to use formsets. The problem I got, is that the values that comes in the post are all by the name "answer", so I get a list of all the elements from all forms by the name "answer" and I can't identify which ones belong to each form. Don't know if this explanation get a clear view of my problem. Any ideas to get this stuff done? Thanks for your help! PD: Don't pay attention to the relation between Poll and Choice, those models are just to clarify the problen, so the relation doesn't matter at all. A: Use the prefix kwarg You can declare your form as: form = MyFormClass(prefix='some_prefix') and then, as long as the prefix is the same, process data as: form = MyFormClass(request.POST, prefix='some_prefix') Django will handle the rest. This way you can have as many forms of the same type as you want on the page
Django - Working with multiple forms
What I'm trying to do is to manage several forms in one page, I know there are formsets, and I know how the form management works, but I got some problems with the idea I have in mind. Just to help you to imagine what my problem is I'm going to use the django example models: from django.db import models class Poll(models.Model): question = models.CharField(max_length=200) pub_date = models.DateTimeField() class Choice(models.Model): poll = models.ForeignKey(Poll) choice = models.CharField(max_length=200) votes = models.IntegerField(default=0) Now, imagine I've already made the form clases: from django import forms from mysite.polls.models import Poll, Choice class PollForm(forms.ModelForm): class Meta: model = Poll class ChoiceForm(forms.ModelForm): class Meta: model = Choice exclude = ('poll',) So what I want to do is to have several form instances of the Poll and Choice model in a single page, but mind that these models can be repeated too: <form action="{{url}}" method="post"> {{pollform}} {{choiceform}} {{pollform}} </form> As you can see there are two Poll forms and one Choice form, but the Poll forms are separated by the Choice form. I do need that the forms keep their order in the page, so is a little harder to use formsets. The problem I got, is that the values that comes in the post are all by the name "answer", so I get a list of all the elements from all forms by the name "answer" and I can't identify which ones belong to each form. Don't know if this explanation get a clear view of my problem. Any ideas to get this stuff done? Thanks for your help! PD: Don't pay attention to the relation between Poll and Choice, those models are just to clarify the problen, so the relation doesn't matter at all.
[ "Use the prefix kwarg\nYou can declare your form as:\nform = MyFormClass(prefix='some_prefix')\n\nand then, as long as the prefix is the same, process data as:\nform = MyFormClass(request.POST, prefix='some_prefix')\n\nDjango will handle the rest.\nThis way you can have as many forms of the same type as you want on the page\n" ]
[ 58 ]
[]
[]
[ "django", "django_forms", "forms", "python" ]
stackoverflow_0002374224_django_django_forms_forms_python.txt
Q: 2D integrals in SciPy I am trying to integrate a multivariable function in SciPy over a 2D area. What would be the equivalent of the following Mathematica code? In[1]:= F[x_, y_] := Cos[x] + Cos[y] In[2]:= Integrate[F[x, y], {x, -\[Pi], \[Pi]}, {y, -\[Pi], \[Pi]}] Out[2]= 0 Looking at the SciPy documentation I could only find support for one-dimensional quadrature. Is there a way to do multidimensional integrals in SciPy? A: I think it would work something like this: def func(x,y): return cos(x) + cos(y) def func2(y, a, b): return integrate.quad(func, a, b, args=(y,))[0] print integrate.quad(func2, -pi/2, pi/2, args=(-pi/2, pi/2))[0] Wolfram|Alpha agrees edit: I just discovered dblquad which seems to do exactly what you want: print integrate.dblquad(func, -pi/2, pi/2, lambda x:-pi/2, lambda x:pi/2)[0] A: If you want to do symbolic integration, have a look at sympy (code.google.com/p/sympy): import sympy as s x, y = s.symbols('x, y') expr = s.cos(x) + s.sin(y) expr.integrate((x, -s.pi, s.pi), (y, -s.pi, s.pi))
2D integrals in SciPy
I am trying to integrate a multivariable function in SciPy over a 2D area. What would be the equivalent of the following Mathematica code? In[1]:= F[x_, y_] := Cos[x] + Cos[y] In[2]:= Integrate[F[x, y], {x, -\[Pi], \[Pi]}, {y, -\[Pi], \[Pi]}] Out[2]= 0 Looking at the SciPy documentation I could only find support for one-dimensional quadrature. Is there a way to do multidimensional integrals in SciPy?
[ "I think it would work something like this:\ndef func(x,y):\n return cos(x) + cos(y)\n\ndef func2(y, a, b):\n return integrate.quad(func, a, b, args=(y,))[0]\n\nprint integrate.quad(func2, -pi/2, pi/2, args=(-pi/2, pi/2))[0]\n\nWolfram|Alpha agrees\nedit: I just discovered dblquad which seems to do exactly what you want:\nprint integrate.dblquad(func, -pi/2, pi/2, lambda x:-pi/2, lambda x:pi/2)[0]\n\n", "If you want to do symbolic integration, have a look at sympy (code.google.com/p/sympy):\nimport sympy as s\nx, y = s.symbols('x, y')\nexpr = s.cos(x) + s.sin(y)\nexpr.integrate((x, -s.pi, s.pi), (y, -s.pi, s.pi))\n\n" ]
[ 13, 9 ]
[]
[]
[ "integration", "multidimensional_array", "python", "scipy", "wolfram_mathematica" ]
stackoverflow_0002368337_integration_multidimensional_array_python_scipy_wolfram_mathematica.txt
Q: How does the following code to work? How to work with struct_time objects? If I do the following I can convert from a time_struct object to a datetime object: mydate = datetime.datetime(*time.localtime()[:6]) How does this code work? What do the * and the [:6] mean? A: * is argument unpacking, [:6] is slicing. That is whatever is returned from time.localtime() (i.e., time.struct_time) is sliced and first 6 elements are unpacked and 6 arguments passed to datetime.datetime. There are plenty of question on SO re all of these topics. A: *time.localtime() means, that the tuple returned from localtime is unpacked (turned into arguments passed to datetime). [:6] means that only a slice of the tuple is used, this operator returns new tuple of first six elements. This code takes localtime from the time module in the form of a tuple and passes it into nice datetime object constructor. It's good to work on datetime objects, they are much nicer then localtime tuples. localtime returns a tuple with values representing local time.
How does the following code to work? How to work with struct_time objects?
If I do the following I can convert from a time_struct object to a datetime object: mydate = datetime.datetime(*time.localtime()[:6]) How does this code work? What do the * and the [:6] mean?
[ "* is argument unpacking, [:6] is slicing. That is whatever is returned from time.localtime() (i.e., time.struct_time) is sliced and first 6 elements are unpacked and 6 arguments passed to datetime.datetime. \nThere are plenty of question on SO re all of these topics.\n", "*time.localtime() means, that the tuple returned from localtime is unpacked (turned into arguments passed to datetime). [:6] means that only a slice of the tuple is used, this operator returns new tuple of first six elements.\nThis code takes localtime from the time module in the form of a tuple and passes it into nice datetime object constructor. It's good to work on datetime objects, they are much nicer then localtime tuples. localtime returns a tuple with values representing local time.\n" ]
[ 4, 3 ]
[]
[]
[ "python" ]
stackoverflow_0002375101_python.txt
Q: In Django, how do I clear a sessionkey? I set a session like this: request.session['mykey']= 33 How do I clear it? I just want to DELETE it. A: del request.session['mykey']
In Django, how do I clear a sessionkey?
I set a session like this: request.session['mykey']= 33 How do I clear it? I just want to DELETE it.
[ " del request.session['mykey']\n\n" ]
[ 37 ]
[]
[]
[ "django", "python", "session" ]
stackoverflow_0002375335_django_python_session.txt
Q: Generate image for each font on a linux system using Python I'm looking for a way to list all fonts installed on a linux/Debian system, and then generate images of some strings using these fonts. I'm looking for your advice as I kind of see how to do each part, but not to do both: To list all fonts on a UNIX system, xlsfonts can do the trick: import os list_of_fonts=os.popen("xslfonts").readlines() To render a string into an image using a font, I could use PIL (Python Imaging Library) and the ImageFont class. However, ImagesFont.load expects a file name, whereas xlsfonts gives a kind of normalized font name, and the correspondence between the two doesn't seems obvious (I tried to search my system for files named as the output of xlsfonts, without results). Does anyone has an idea on how I can do that? Thanks! A: You can do this using pango, through the pygtk package. Pango can list fonts and render them. A: you best bet is to do a find on all the fonts on the system, and then use ImagesFont.load() on the results of that list. I don't know where the fonts are on Debian, but they should be in a well known folder you can just do an os.walk and then feed the filenames in that way.
Generate image for each font on a linux system using Python
I'm looking for a way to list all fonts installed on a linux/Debian system, and then generate images of some strings using these fonts. I'm looking for your advice as I kind of see how to do each part, but not to do both: To list all fonts on a UNIX system, xlsfonts can do the trick: import os list_of_fonts=os.popen("xslfonts").readlines() To render a string into an image using a font, I could use PIL (Python Imaging Library) and the ImageFont class. However, ImagesFont.load expects a file name, whereas xlsfonts gives a kind of normalized font name, and the correspondence between the two doesn't seems obvious (I tried to search my system for files named as the output of xlsfonts, without results). Does anyone has an idea on how I can do that? Thanks!
[ "You can do this using pango, through the pygtk package. Pango can list fonts and render them.\n", "you best bet is to do a find on all the fonts on the system, and then use ImagesFont.load() on the results of that list. I don't know where the fonts are on Debian, but they should be in a well known folder you can just do an os.walk and then feed the filenames in that way.\n" ]
[ 1, 1 ]
[]
[]
[ "debian", "fonts", "linux", "python", "python_imaging_library" ]
stackoverflow_0002375125_debian_fonts_linux_python_python_imaging_library.txt
Q: What is the best, python or bash for generating strings from combinations of letters? I need to generate the strings STA and STB. STA and STB are strings of length 10, and each one can contain only the characters A,T,G or C. I have to generate all possible combinations of STA, and depending on STA, I generate STB. The ways is that the character A is always associated with T and viceversa and G with C and viceversa. so it is possible combinations like: STA: ATGC... STB: TACG... or STA: GTTA... STB: CAAT... and so on. I wonder what would be the best way of doing this using bash or python Thanks A: I'd say Python. Have a look here for string permutations: Permutations using a Combinations Generator (Python). Another thing to look at is itertools in Python 2.6+ - Generating all permutations of a list in python. I do note however that your requirements are more in depth, however you will probably find it easier to add in the necessary constraints in Python rather than Bash. Simple, clean and easy. Now, I'm not expert on Bash, but looking at it, you would have to have multiple lines that repeat pretty much the same text over and over depending on your combinations. It would be great to use simple combinations, but not linked combinations. A: While I don't know bash and don't see how permutations would solve your problem, it seems that itertools.product is a fairly straightforward way to do this: >>> s = 'atgc' >>> d = dict(zip(s, 'tacg')) >>> import itertools >>> for i in itertools.product(s, repeat=10): sta = ''.join(i) stb = ''.join(d[x] for x in i) while proposed method is valid in terms of obtaining all possible permutations with replacement of the 'atgc' string, i.e., finding sta string, finding stb would be more efficient not through the dictionary look-up, but rather the translation mechanism: >>> trans = str.maketrans(s, 'tacg') >>> for i in itertools.product(s, repeat=10): sta = ''.join(i) stb = sta.translate(trans) Thanks to Dave, for highlighting more efficient solution. A: Others have said how to generate STA. The most efficient way to convert a string STA into the equivalent string STB is to use the string translate & maketrans functions. >>> import string >>> s = "AGTC" * 100 >>> trans = string.maketrans("ATGC", "TACG") >>> s.translate(trans) 'TCAG...TCAG' On my system this is ~100 times faster than doing a dictionary lookup on each character as suggested by SilentGhost. A: Here you go: >>> from itertools import product >>> seq = ("AGCT",) * 10 >>> STA = [''.join(a) for a in product(*seq)] >>> STB = list(reversed(STA)) Incidentally, len(STA) is 220. itertools.product is available in Python 2.6. See @hop's answer here for an implementation of product in Python 2.5 A: bash baby :) STA=$(echo {A,C,T,G}{A,C,T,G}{A,C,T,G}{A,C,T,G}{A,C,T,G}{A,C,T,G}{A,C,T,G}{A,C,T,G}{A,C,T,G}{A,C,T,G}) STB=$(echo $STA | tr ATCG TAGC) echo $STA echo $STB A: Unrelated to your actual question but related to what you're (apparently) doing, have you checked out BioPython?
What is the best, python or bash for generating strings from combinations of letters?
I need to generate the strings STA and STB. STA and STB are strings of length 10, and each one can contain only the characters A,T,G or C. I have to generate all possible combinations of STA, and depending on STA, I generate STB. The ways is that the character A is always associated with T and viceversa and G with C and viceversa. so it is possible combinations like: STA: ATGC... STB: TACG... or STA: GTTA... STB: CAAT... and so on. I wonder what would be the best way of doing this using bash or python Thanks
[ "I'd say Python.\nHave a look here for string permutations: Permutations using a Combinations Generator (Python). Another thing to look at is itertools in Python 2.6+ - Generating all permutations of a list in python. I do note however that your requirements are more in depth, however you will probably find it easier to add in the necessary constraints in Python rather than Bash.\nSimple, clean and easy.\nNow, I'm not expert on Bash, but looking at it, you would have to have multiple lines that repeat pretty much the same text over and over depending on your combinations. It would be great to use simple combinations, but not linked combinations.\n", "While I don't know bash and don't see how permutations would solve your problem, it seems that itertools.product is a fairly straightforward way to do this:\n>>> s = 'atgc'\n>>> d = dict(zip(s, 'tacg'))\n>>> import itertools\n>>> for i in itertools.product(s, repeat=10):\n sta = ''.join(i)\n stb = ''.join(d[x] for x in i)\n\nwhile proposed method is valid in terms of obtaining all possible permutations with replacement of the 'atgc' string, i.e., finding sta string, finding stb would be more efficient not through the dictionary look-up, but rather the translation mechanism:\n>>> trans = str.maketrans(s, 'tacg')\n>>> for i in itertools.product(s, repeat=10):\n sta = ''.join(i)\n stb = sta.translate(trans)\n\nThanks to Dave, for highlighting more efficient solution.\n", "Others have said how to generate STA.\nThe most efficient way to convert a string STA into the equivalent string STB is to use the string translate & maketrans functions.\n>>> import string\n>>> s = \"AGTC\" * 100\n>>> trans = string.maketrans(\"ATGC\", \"TACG\")\n>>> s.translate(trans)\n'TCAG...TCAG'\n\nOn my system this is ~100 times faster than doing a dictionary lookup on each character as suggested by SilentGhost.\n", "Here you go: \n>>> from itertools import product\n>>> seq = (\"AGCT\",) * 10\n>>> STA = [''.join(a) for a in product(*seq)]\n>>> STB = list(reversed(STA))\n\nIncidentally, len(STA) is 220. \nitertools.product is available in Python 2.6.\nSee @hop's answer here for an implementation of product in Python 2.5\n", "bash baby :)\nSTA=$(echo {A,C,T,G}{A,C,T,G}{A,C,T,G}{A,C,T,G}{A,C,T,G}{A,C,T,G}{A,C,T,G}{A,C,T,G}{A,C,T,G}{A,C,T,G})\nSTB=$(echo $STA | tr ATCG TAGC)\n\necho $STA\necho $STB\n\n", "Unrelated to your actual question but related to what you're (apparently) doing, have you checked out BioPython?\n" ]
[ 2, 2, 2, 1, 1, 0 ]
[]
[]
[ "bash", "python" ]
stackoverflow_0002374201_bash_python.txt
Q: Python Type Conversion Whats the best way to convert int's, long's, double's to strings and vice versa in python. I am looping through a list and passing longs to a dict that should be turned into a unicode string. I do for n in l: {'my_key':n[0],'my_other_key':n[1]} Why are some of the most obvious things so complicated? A: To convert from a numeric type to a string: str(100) To convert from a string to an int: int("100") To convert from a string to a float: float("100") A: You could do it like this in Python 2.x: >>> l = ((1,2),(3,4)) >>> dict(map(lambda n: (n[0], unicode(n[1])), l)) {1: u'2', 3: u'4'} or in Python 3.x: >>> l = ((1,2),(3,4)) >>> {n[0] : str(n[1]) for n in l} {1: '2', 3: '4'} Note that strings in Python 3 are the same as unicode strings in Python 2. A: You can do it this way for n in l: {'my_key':unicode(n[0]),'my_other_key':unicode(n[1])} Perhaps this is clearer if there are only 2 or 3 keys/values for my_value, my_other_value in l: {'my_key':unicode(my_value),'my_other_key':unicode(my_other_value)} I think this would be better if there are more than 3 keys/values for n in l: dict(zip(('my_key','myother_key'),map(unicode,n)))
Python Type Conversion
Whats the best way to convert int's, long's, double's to strings and vice versa in python. I am looping through a list and passing longs to a dict that should be turned into a unicode string. I do for n in l: {'my_key':n[0],'my_other_key':n[1]} Why are some of the most obvious things so complicated?
[ "To convert from a numeric type to a string:\nstr(100)\n\nTo convert from a string to an int:\nint(\"100\")\n\nTo convert from a string to a float:\nfloat(\"100\")\n\n", "You could do it like this in Python 2.x:\n>>> l = ((1,2),(3,4))\n>>> dict(map(lambda n: (n[0], unicode(n[1])), l))\n{1: u'2', 3: u'4'}\n\nor in Python 3.x:\n>>> l = ((1,2),(3,4))\n>>> {n[0] : str(n[1]) for n in l}\n{1: '2', 3: '4'}\n\nNote that strings in Python 3 are the same as unicode strings in Python 2.\n", "You can do it this way\nfor n in l:\n {'my_key':unicode(n[0]),'my_other_key':unicode(n[1])}\n\nPerhaps this is clearer if there are only 2 or 3 keys/values\nfor my_value, my_other_value in l:\n {'my_key':unicode(my_value),'my_other_key':unicode(my_other_value)}\n\nI think this would be better if there are more than 3 keys/values\nfor n in l:\n dict(zip(('my_key','myother_key'),map(unicode,n)))\n\n" ]
[ 37, 2, 0 ]
[]
[]
[ "int", "python", "types" ]
stackoverflow_0002375334_int_python_types.txt
Q: How to do a dregradê on wx.Panel Background? I want to color the background (SetBackgroundColour) of a wx.Panel with a blue to black degradê. How can I make it? A: Adapted from DaniWeb: import wx class MyFrame(wx.Frame): def __init__(self, parent=None, title=None): wx.Frame.__init__(self, parent, wx.ID_ANY, title) self.panel = wx.Panel(self, size=(350, 450)) # this sets up the painting canvas self.panel.Bind(wx.EVT_PAINT, self.on_paint) # set frame size to fit panel self.Fit() def on_paint(self, event): # establish the painting canvas dc = wx.PaintDC(self.panel) x = 0 y = 0 w, h = self.GetSize() dc.GradientFillLinear((x, y, w, h), 'blue', 'black') app = wx.App(0) MyFrame(title='Gradient Test').Show() app.MainLoop() And an alternative way to generate a gradient bitmap, using NumPy (from wxpython.org): import numpy as np def GetBitmap( self, width=640, height=480, leftColour=(255,128,0), rightColour=(64,0,255) ): ## Create a horizontal gradient array = np.zeros( (height, width, 3),'uint8') # alpha is a one dimensional array with a linear gradient from 0.0 to 1.0 alpha = np.linspace( 0., 1., width ) # This uses alpha to linearly interpolate between leftColour and rightColour colourGradient = np.outer(alpha, leftColour) + np.outer((1.-alpha), rightColour) # NumPy's broadcasting rules will assign colourGradient to every row of the destination array array[:,:,:] = colourGradient image = wx.EmptyImage(width,height) image.SetData( array.tostring()) return image.ConvertToBitmap()# wx.BitmapFromImage(image)
How to do a dregradê on wx.Panel Background?
I want to color the background (SetBackgroundColour) of a wx.Panel with a blue to black degradê. How can I make it?
[ "Adapted from DaniWeb:\nimport wx\n\nclass MyFrame(wx.Frame):\n def __init__(self, parent=None, title=None):\n wx.Frame.__init__(self, parent, wx.ID_ANY, title)\n self.panel = wx.Panel(self, size=(350, 450))\n # this sets up the painting canvas\n self.panel.Bind(wx.EVT_PAINT, self.on_paint)\n # set frame size to fit panel\n self.Fit()\n\n def on_paint(self, event):\n # establish the painting canvas\n dc = wx.PaintDC(self.panel)\n x = 0\n y = 0\n w, h = self.GetSize()\n dc.GradientFillLinear((x, y, w, h), 'blue', 'black')\n\n\napp = wx.App(0)\nMyFrame(title='Gradient Test').Show()\napp.MainLoop()\n\nAnd an alternative way to generate a gradient bitmap, using NumPy (from wxpython.org):\nimport numpy as np\n\ndef GetBitmap( self, width=640, height=480, leftColour=(255,128,0), rightColour=(64,0,255) ):\n ## Create a horizontal gradient\n array = np.zeros( (height, width, 3),'uint8')\n # alpha is a one dimensional array with a linear gradient from 0.0 to 1.0\n alpha = np.linspace( 0., 1., width )\n # This uses alpha to linearly interpolate between leftColour and rightColour\n colourGradient = np.outer(alpha, leftColour) + np.outer((1.-alpha), rightColour)\n # NumPy's broadcasting rules will assign colourGradient to every row of the destination array\n array[:,:,:] = colourGradient\n image = wx.EmptyImage(width,height)\n image.SetData( array.tostring())\n return image.ConvertToBitmap()# wx.BitmapFromImage(image)\n\n" ]
[ 5 ]
[]
[]
[ "colors", "panel", "python", "wxpython" ]
stackoverflow_0002375158_colors_panel_python_wxpython.txt
Q: Create a python function procedurally (specifically the arguments) Question How do you procedurally create a function in Python which takes specific named arguments but allow those argument names to be data-driven? Example Say, you want to create a class decorator, with_init, which adds an __init__ method with specific named arguments such that the following two classes are equivalent. class C1(object): def __init__(self, x, y, z): self.x = x self.y = y self.z = z @with_init('x y z') class C2(object): pass My first attempt cheats by making a function which accepts *args instead of the specific named parameters: class with_init(object): def __init__(self, params): self.params = params.split() def __call__(self, cls): def init(cls_self, *args): for param, value in zip(self.params, args): setattr(cls_self, param, value) cls.__init__ = init return cls It works in some situations: >>> C1(1,2,3) <__main__.C1 object at 0x100c410> >>> C2(1,2,3) <__main__.C2 object at 0x100ca70> But not so much in others: >>> C2(1,2,3,4) # Should fail, but doesn't. <__main__.C2 object at 0x100cc90> >>> C2(x=1, y=2, z=3) # Should succeed, but doesn't. Traceback (most recent call last): File "<string>", line 1, in <fragment> TypeError: init() got an unexpected keyword argument 'y' Of course I can add code to the nested init function to try and check for every possible situation, but it seems like there should be an easier way. I've noticed that collections.namedtuple avoids these issues by making a string to pass to exec. That seems very round-about to me, but perhaps that's the solution. What is the correct implementation of with_init.__call__? Note: I'd like a Python 2.x solution please. A: Very roughly. This accepts kw args and checks to see that the number of args is correct def __call__(self, cls): def init(cls_self, *args, **kw): if len(args)+len(kw) != len(self.params): raise RuntimeError("Wrong number of arguments") for param, value in zip(self.params, args): setattr(cls_self, param, value) vars(cls_self).update(kw) cls.__init__ = init return cls This version has a few improvements def __call__(self, cls): def init(cls_self, *args, **kw): for param, value in zip(self.params, args): if param in kw: raise TypeError("Multiple values for %s"%param) kw[param]=value if len(args) > len(self.params) or set(kw) != set(self.params): raise TypeError("Wrong number of arguments") vars(cls_self).update(kw) cls.__init__ = init return cls This version also tells you about unexpected keyword args def __call__(self, cls): def init(cls_self, *args, **kw): for param, value in zip(self.params, args): if param in kw: raise TypeError("Multiple values for %s"%param) kw[param]=value unexpected_args = list(set(kw)-set(self.params)) if unexpected_args: raise TypeError("Unexpected args %s"%unexpected_args) missing_args = list(set(self.params)-set(kw)) if missing_args: raise TypeError("Expected args %s"%missing_args) vars(cls_self).update(kw) cls.__init__ = init return cls A: Here's my namedtuple inspired answer. It's currently open to template injection attacks but you don't have to handle any of the parameter errors yourself. def __call__(self, cls): paramtxt = ', '.join(['self'] + self.params) bodytxt = '\n\t'.join('self.%(param)s = %(param)s' % locals() for param in self.params) template = 'def __init__(%(paramtxt)s):\n\t%(bodytxt)s' % locals() namespace = dict() exec template in namespace cls.__init__ = namespace['__init__'] return cls
Create a python function procedurally (specifically the arguments)
Question How do you procedurally create a function in Python which takes specific named arguments but allow those argument names to be data-driven? Example Say, you want to create a class decorator, with_init, which adds an __init__ method with specific named arguments such that the following two classes are equivalent. class C1(object): def __init__(self, x, y, z): self.x = x self.y = y self.z = z @with_init('x y z') class C2(object): pass My first attempt cheats by making a function which accepts *args instead of the specific named parameters: class with_init(object): def __init__(self, params): self.params = params.split() def __call__(self, cls): def init(cls_self, *args): for param, value in zip(self.params, args): setattr(cls_self, param, value) cls.__init__ = init return cls It works in some situations: >>> C1(1,2,3) <__main__.C1 object at 0x100c410> >>> C2(1,2,3) <__main__.C2 object at 0x100ca70> But not so much in others: >>> C2(1,2,3,4) # Should fail, but doesn't. <__main__.C2 object at 0x100cc90> >>> C2(x=1, y=2, z=3) # Should succeed, but doesn't. Traceback (most recent call last): File "<string>", line 1, in <fragment> TypeError: init() got an unexpected keyword argument 'y' Of course I can add code to the nested init function to try and check for every possible situation, but it seems like there should be an easier way. I've noticed that collections.namedtuple avoids these issues by making a string to pass to exec. That seems very round-about to me, but perhaps that's the solution. What is the correct implementation of with_init.__call__? Note: I'd like a Python 2.x solution please.
[ "Very roughly. This accepts kw args and checks to see that the number of args is correct\ndef __call__(self, cls):\n def init(cls_self, *args, **kw):\n if len(args)+len(kw) != len(self.params):\n raise RuntimeError(\"Wrong number of arguments\")\n for param, value in zip(self.params, args):\n setattr(cls_self, param, value)\n vars(cls_self).update(kw)\n cls.__init__ = init\n return cls\n\nThis version has a few improvements\ndef __call__(self, cls):\n def init(cls_self, *args, **kw):\n for param, value in zip(self.params, args):\n if param in kw:\n raise TypeError(\"Multiple values for %s\"%param)\n kw[param]=value\n if len(args) > len(self.params) or set(kw) != set(self.params):\n raise TypeError(\"Wrong number of arguments\")\n vars(cls_self).update(kw)\n cls.__init__ = init\n return cls\n\nThis version also tells you about unexpected keyword args\ndef __call__(self, cls):\n def init(cls_self, *args, **kw):\n for param, value in zip(self.params, args):\n if param in kw:\n raise TypeError(\"Multiple values for %s\"%param)\n kw[param]=value\n unexpected_args = list(set(kw)-set(self.params))\n if unexpected_args:\n raise TypeError(\"Unexpected args %s\"%unexpected_args)\n missing_args = list(set(self.params)-set(kw))\n if missing_args:\n raise TypeError(\"Expected args %s\"%missing_args)\n vars(cls_self).update(kw)\n cls.__init__ = init\n return cls\n\n", "Here's my namedtuple inspired answer. It's currently open to template injection attacks but you don't have to handle any of the parameter errors yourself.\ndef __call__(self, cls):\n paramtxt = ', '.join(['self'] + self.params)\n bodytxt = '\\n\\t'.join('self.%(param)s = %(param)s' % locals() for param in self.params)\n template = 'def __init__(%(paramtxt)s):\\n\\t%(bodytxt)s' % locals()\n\n namespace = dict()\n exec template in namespace\n\n cls.__init__ = namespace['__init__']\n\n return cls\n\n" ]
[ 3, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002375316_python.txt
Q: Is it possible to dock wx.auiManager panes onto tops/bottoms of another panes? with this code: import wx import wx.aui class MyFrame(wx.Frame): def __init__(self, parent, id=-1, title='wx.aui Test', pos=wx.DefaultPosition, size=(800, 600), style=wx.DEFAULT_FRAME_STYLE): wx.Frame.__init__(self, parent, id, title, pos, size, style) self._mgr = wx.aui.AuiManager(self) # create several text controls text1 = wx.TextCtrl(self, -1, 'Pane 1 - sample text', wx.DefaultPosition, wx.Size(200,150), wx.NO_BORDER | wx.TE_MULTILINE) text2 = wx.TextCtrl(self, -1, 'Pane 2 - sample text', wx.DefaultPosition, wx.Size(200,150), wx.NO_BORDER | wx.TE_MULTILINE) info = wx.aui.AuiPaneInfo() info.CaptionVisible(True) info.BottomDockable(False) info.LeftDockable(False) info.RightDockable(False) info.PaneBorder(False) info.Top() info.Row(1) info2 = wx.aui.AuiPaneInfo() info2.CaptionVisible(True) info2.BottomDockable(False) info2.LeftDockable(False) info2.RightDockable(False) info2.Top() info2.Row(2) self._mgr.AddPane(text1, info, 'Pane Number One') self._mgr.AddPane(text2, info2, 'Pane Number Two') self._mgr.Update() self.Bind(wx.EVT_CLOSE, self.OnClose) def OnClose(self, event): self._mgr.UnInit() self.Destroy() app = wx.App() frame = MyFrame(None) frame.Show() app.MainLoop() the two panes that I create are docked in the Top. The info.Row(1) and info2.Row(2) put the two panes one after another: _TOP_ Pane1 Pane2 Now, if I move on Pane2, this docks in the Top and this situation occurs: _TOP_ Pane1|Pane2 I want: 1. to avoid this situation (only one pane per row!) 2. if I move, dock the pane in the bottom/top of another pane Is this possible? A: Maybe the AuiNotebook wxPython sample works for you? import wx import wx.aui ######################################################################## class TabPanel(wx.Panel): """ This will be the first notebook tab """ #---------------------------------------------------------------------- def __init__(self, parent): """""" wx.Panel.__init__(self, parent=parent, id=wx.ID_ANY) sizer = wx.BoxSizer(wx.VERTICAL) txtOne = wx.TextCtrl(self, wx.ID_ANY, "") txtTwo = wx.TextCtrl(self, wx.ID_ANY, "") sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(txtOne, 0, wx.ALL, 5) sizer.Add(txtTwo, 0, wx.ALL, 5) self.SetSizer(sizer) class DemoPanel(wx.Panel): """ This will be the first notebook tab """ #---------------------------------------------------------------------- def __init__(self, parent): """""" wx.Panel.__init__(self, parent=parent, id=wx.ID_ANY) # create the AuiNotebook instance nb = wx.aui.AuiNotebook(self) # add some pages to the notebook pages = [(TabPanel(nb), "Tab 1"), (TabPanel(nb), "Tab 2"), (TabPanel(nb), "Tab 3")] for page, label in pages: nb.AddPage(page, label) sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(nb, 1, wx.EXPAND) self.SetSizer(sizer) ######################################################################## class DemoFrame(wx.Frame): """ Frame that holds all other widgets """ #---------------------------------------------------------------------- def __init__(self): """Constructor""" wx.Frame.__init__(self, None, wx.ID_ANY, "AUI-Notebook Tutorial", size=(600,400)) panel = DemoPanel(self) self.Show() #---------------------------------------------------------------------- if __name__ == "__main__": app = wx.PySimpleApp() frame = DemoFrame() app.MainLoop()
Is it possible to dock wx.auiManager panes onto tops/bottoms of another panes?
with this code: import wx import wx.aui class MyFrame(wx.Frame): def __init__(self, parent, id=-1, title='wx.aui Test', pos=wx.DefaultPosition, size=(800, 600), style=wx.DEFAULT_FRAME_STYLE): wx.Frame.__init__(self, parent, id, title, pos, size, style) self._mgr = wx.aui.AuiManager(self) # create several text controls text1 = wx.TextCtrl(self, -1, 'Pane 1 - sample text', wx.DefaultPosition, wx.Size(200,150), wx.NO_BORDER | wx.TE_MULTILINE) text2 = wx.TextCtrl(self, -1, 'Pane 2 - sample text', wx.DefaultPosition, wx.Size(200,150), wx.NO_BORDER | wx.TE_MULTILINE) info = wx.aui.AuiPaneInfo() info.CaptionVisible(True) info.BottomDockable(False) info.LeftDockable(False) info.RightDockable(False) info.PaneBorder(False) info.Top() info.Row(1) info2 = wx.aui.AuiPaneInfo() info2.CaptionVisible(True) info2.BottomDockable(False) info2.LeftDockable(False) info2.RightDockable(False) info2.Top() info2.Row(2) self._mgr.AddPane(text1, info, 'Pane Number One') self._mgr.AddPane(text2, info2, 'Pane Number Two') self._mgr.Update() self.Bind(wx.EVT_CLOSE, self.OnClose) def OnClose(self, event): self._mgr.UnInit() self.Destroy() app = wx.App() frame = MyFrame(None) frame.Show() app.MainLoop() the two panes that I create are docked in the Top. The info.Row(1) and info2.Row(2) put the two panes one after another: _TOP_ Pane1 Pane2 Now, if I move on Pane2, this docks in the Top and this situation occurs: _TOP_ Pane1|Pane2 I want: 1. to avoid this situation (only one pane per row!) 2. if I move, dock the pane in the bottom/top of another pane Is this possible?
[ "Maybe the AuiNotebook wxPython sample works for you?\nimport wx\nimport wx.aui\n\n########################################################################\nclass TabPanel(wx.Panel):\n \"\"\"\n This will be the first notebook tab\n \"\"\"\n #----------------------------------------------------------------------\n def __init__(self, parent):\n \"\"\"\"\"\"\n\n wx.Panel.__init__(self, parent=parent, id=wx.ID_ANY)\n\n sizer = wx.BoxSizer(wx.VERTICAL)\n txtOne = wx.TextCtrl(self, wx.ID_ANY, \"\")\n txtTwo = wx.TextCtrl(self, wx.ID_ANY, \"\")\n\n sizer = wx.BoxSizer(wx.VERTICAL)\n sizer.Add(txtOne, 0, wx.ALL, 5)\n sizer.Add(txtTwo, 0, wx.ALL, 5)\n\n self.SetSizer(sizer)\n\nclass DemoPanel(wx.Panel):\n \"\"\"\n This will be the first notebook tab\n \"\"\"\n #----------------------------------------------------------------------\n def __init__(self, parent):\n \"\"\"\"\"\"\n wx.Panel.__init__(self, parent=parent, id=wx.ID_ANY)\n\n # create the AuiNotebook instance\n nb = wx.aui.AuiNotebook(self)\n\n # add some pages to the notebook\n pages = [(TabPanel(nb), \"Tab 1\"),\n (TabPanel(nb), \"Tab 2\"),\n (TabPanel(nb), \"Tab 3\")]\n for page, label in pages:\n nb.AddPage(page, label)\n\n sizer = wx.BoxSizer(wx.VERTICAL)\n sizer.Add(nb, 1, wx.EXPAND)\n self.SetSizer(sizer)\n\n########################################################################\nclass DemoFrame(wx.Frame):\n \"\"\"\n Frame that holds all other widgets\n \"\"\"\n\n #----------------------------------------------------------------------\n def __init__(self):\n \"\"\"Constructor\"\"\"\n wx.Frame.__init__(self, None, wx.ID_ANY,\n \"AUI-Notebook Tutorial\",\n size=(600,400))\n panel = DemoPanel(self)\n self.Show()\n\n#----------------------------------------------------------------------\nif __name__ == \"__main__\":\n app = wx.PySimpleApp()\n frame = DemoFrame()\n app.MainLoop()\n\n" ]
[ 1 ]
[]
[]
[ "dock", "python", "wxpython" ]
stackoverflow_0002375613_dock_python_wxpython.txt
Q: Debugging Python Crash I am building Python 2.6 4 from source on a Linux server and am experiencing a Segmentation Fault when running the tests (make test) (test_hashlib.py and test_hmac.py). When I opened the core dump file in gdb, I am told that the error is at 0x00002b73379ac446 in ??. I then recompiled python with both my CFLAGS and CPPFLAGS set to -g to enable debug symbols and reran the failing test. When I opened the core dump file in gdb, I got the same useless stuff as I got before enabling debug symbols. I then tried to run python within gdb, but go the same result. Here is the script (install-python.sh) that I used to build and install Python: #!/bin/sh VER=2.6.4 wget http://www.python.org/ftp/python/${VER}/Python-${VER}.tar.bz2 tar -xjf Python-${VER}.tar.bz2 cd Python-${VER} export CFLAGS="-g" export CPPFLAGS="${CFLAGS}" ./configure --prefix=${HOME}/packages/python --exec-prefix=${HOME}/packages/python make && make test make install cd .. #rm -rf Python-${VER}* Does anyone know how to get a usable backtrace out of my hand-rolled Python? A: Typically you need to set CFLAGS before calling ./configure - it is usually written to bake a CFLAGS value into the Makefile.
Debugging Python Crash
I am building Python 2.6 4 from source on a Linux server and am experiencing a Segmentation Fault when running the tests (make test) (test_hashlib.py and test_hmac.py). When I opened the core dump file in gdb, I am told that the error is at 0x00002b73379ac446 in ??. I then recompiled python with both my CFLAGS and CPPFLAGS set to -g to enable debug symbols and reran the failing test. When I opened the core dump file in gdb, I got the same useless stuff as I got before enabling debug symbols. I then tried to run python within gdb, but go the same result. Here is the script (install-python.sh) that I used to build and install Python: #!/bin/sh VER=2.6.4 wget http://www.python.org/ftp/python/${VER}/Python-${VER}.tar.bz2 tar -xjf Python-${VER}.tar.bz2 cd Python-${VER} export CFLAGS="-g" export CPPFLAGS="${CFLAGS}" ./configure --prefix=${HOME}/packages/python --exec-prefix=${HOME}/packages/python make && make test make install cd .. #rm -rf Python-${VER}* Does anyone know how to get a usable backtrace out of my hand-rolled Python?
[ "Typically you need to set CFLAGS before calling ./configure - it is usually written to bake a CFLAGS value into the Makefile.\n" ]
[ 0 ]
[]
[]
[ "debugging", "gdb", "linux", "python" ]
stackoverflow_0002376029_debugging_gdb_linux_python.txt
Q: Static Variables in Python C API How would one expose "static" variables like this class MyClass: X = 1 Y = 2 via the C API? The only variable on the PyTypeObject that looks like it would work is tp_members, but I see no flag in the PyMemberDef to indicate that the member should be per-class, not per-instance. For a bit more clarification, since it may change the answer, I'm trying to expose a C enum to Python such that the enumeration enum MyFlags { Alpha = 0, Beta = 1 }; Can be accessed in Python as: module.MyFlags.Alpha module.MyFlags.Beta A: Just put them in the type's tp_dict e.g. with PyDict_SetItemString.
Static Variables in Python C API
How would one expose "static" variables like this class MyClass: X = 1 Y = 2 via the C API? The only variable on the PyTypeObject that looks like it would work is tp_members, but I see no flag in the PyMemberDef to indicate that the member should be per-class, not per-instance. For a bit more clarification, since it may change the answer, I'm trying to expose a C enum to Python such that the enumeration enum MyFlags { Alpha = 0, Beta = 1 }; Can be accessed in Python as: module.MyFlags.Alpha module.MyFlags.Beta
[ "Just put them in the type's tp_dict e.g. with PyDict_SetItemString.\n" ]
[ 12 ]
[]
[]
[ "python", "python_c_api" ]
stackoverflow_0002374334_python_python_c_api.txt
Q: Emacs collaborative buffers open in the wrong mode I am using Emacs and Rudel to collaborate with a remote programmer. Rudel has a concept of published buffers. When my partner publishes a buffer, I can subscribe to it and the we can both edit it simultaneously. My problem is that when he publishes a Python file with a *.py extension and I subscribe to it, my buffer is not set to python-mode automatically (it is in fundamental mode). How can I get it so that the buffer opens with the correct language mode? A: I don't know Rudel well enough to give a 100% solution, but what you want to do is something like this: (add-hook 'rudel-document-attach-hook 'my-rudel-set-mode-appropriately) (defun my-rudel-set-mode-appropriately (document buffer) "try to set the mode appropriately" (set-buffer buffer) (let ((buffer-file-name ...get-name-from-document...)) (set-auto-mode))) Only, you need to replace the ...get-name-from-document... portion of the code with something that evaluates to the file name that you want, for example, if the buffer is named myfile.py, then you can change that to (buffer-name). But, if the buffers get odd names, perhaps you need to extract the name from the document object (Rudel internally uses a document object to represent the thing you are sharing). So, if (buffer-name) doesn't work, you can try (rudel-suggested-buffer-name document). i.e. try the above code but using one of these lines: (let ((buffer-file-name (buffer-name))) and (let ((buffer-file-name (rudel-suggested-buffer-name document))) The set-auto-mode will use value of buffer-file-name to determine the major mode using the general Emacs mechanisms. A: I know absolutely nothing about how rudel works. However, have you tried explicitly setting the mode in the text file? Try adding something like this to the first line of the file: # -*- mode: python; fill-column: 75; comment-column: 50; -*- Putting a line like this first in the file will cause emacs to ignore the file's extension and open in the given mode.
Emacs collaborative buffers open in the wrong mode
I am using Emacs and Rudel to collaborate with a remote programmer. Rudel has a concept of published buffers. When my partner publishes a buffer, I can subscribe to it and the we can both edit it simultaneously. My problem is that when he publishes a Python file with a *.py extension and I subscribe to it, my buffer is not set to python-mode automatically (it is in fundamental mode). How can I get it so that the buffer opens with the correct language mode?
[ "I don't know Rudel well enough to give a 100% solution, but what you want to do is something like this:\n(add-hook 'rudel-document-attach-hook 'my-rudel-set-mode-appropriately)\n(defun my-rudel-set-mode-appropriately (document buffer)\n \"try to set the mode appropriately\"\n (set-buffer buffer)\n (let ((buffer-file-name ...get-name-from-document...))\n (set-auto-mode)))\n\nOnly, you need to replace the ...get-name-from-document... portion of the code with something that evaluates to the file name that you want, for example, if the buffer is named myfile.py, then you can change that to (buffer-name). But, if the buffers get odd names, perhaps you need to extract the name from the document object (Rudel internally uses a document object to represent the thing you are sharing). So, if (buffer-name) doesn't work, you can try (rudel-suggested-buffer-name document).\ni.e. try the above code but using one of these lines:\n (let ((buffer-file-name (buffer-name)))\n\nand\n (let ((buffer-file-name (rudel-suggested-buffer-name document)))\n\nThe set-auto-mode will use value of buffer-file-name to determine the major mode using the general Emacs mechanisms.\n", "I know absolutely nothing about how rudel works. However, have you tried explicitly setting the mode in the text file? Try adding something like this to the first line of the file:\n# -*- mode: python; fill-column: 75; comment-column: 50; -*-\n\nPutting a line like this first in the file will cause emacs to ignore the file's extension and open in the given mode.\n" ]
[ 3, 0 ]
[]
[]
[ "collaboration", "emacs", "pair_programming", "python" ]
stackoverflow_0002375473_collaboration_emacs_pair_programming_python.txt
Q: Python:Which way gives better precision Is there any difference in precision between one time assignment: res=n/k and multiple assignment in for cycle: for i in range(n): res+=1/k ? A: Floating-point division a/b is not mathematical division a ÷ b, except in very rare* circumstances. Generally, floating point division a/b is a ÷ b + ε. This is true for two reasons. Float numbers (except in rare cases) are an approximation of the decimal number. a is a + εa. b is b + εb. Float numbers uses a base 2 encoding of the digits to the right of the decimal place. When you write 3.1, this is expanded to a base-2 approximation that differs from the real value by a small amount. Real decimal numbers have the same problem, by the way. Write down the decimal expansion of 1/3. Oops. You have to stop writing decimal places at some point. Binary floating point numbers have the same problem. Division has a fixed number of binary places, meaning the answer is truncated. If there's a repeating binary pattern, it gets chopped. In rare cases, this doesn't matter. In general, you've introduced error by doing division. Therefore, when you do something like repeatedly add 1/k values you're computing 1 ÷ k + ε And adding those up. Your result (if you had the right range) would be n × (1 ÷ k + ε) = n ÷ k + n × ε You've multiplied the small error, ε, by n. Making it a big error. (Except in rare cases.) This is bad. Very bad. All floating point division introduces an error. Your job as a programmer is to do the algebra to avoid or defer division to prevent this. Good software design means good algebra to prevent errors being introduced by the division operator. [* The rare cases. In rare cases, the small error happens to be zero. The rare cases occur when your floating point values are small whole numbers or fractions that are sums of powers of two 1/2, 1/4, 1/8, etc. In the rare case that you have a benign number with a benign fractional part, the error will be zero.] A: Sure, they are different, because of how floating point division works. >>> res = 0 >>> for x in xrange(5000): res += 0.1 ... >>> res == 5000 * 0.1 False There's a good explanation in the python official tutorial. A: Well if k divides n then definitely the first one is more precise :-) To be serious, if the division is floating point and n > 1 then the first one will be more precise anyway though they will probably give different results, as nosklo said. BTW, in Python 2.6 the division is integer by default so you'll have very different results. 1/k will always give 0 unless k <= 1. A: Floating point arithmetic has representation and roundoff errors. For the types of data floating point numbers are intended to represent, real numbers of reasonable size, these errors are generally acceptable. If you want to calculate the quotient of two numbers, the right way is simply to say result = n / k (beware if these are both integers and you have not said from __future__ import division, this is not what you may expect). The second way is silly, error-prone, and ugly. There is some discussion of floating point inexactness in the Python tutorial: http://docs.python.org/tutorial/floatingpoint.html A: Even if we charitably assume a floating-point division, there's very definitely a difference in precision; the for loop is executed n - 1 times! assert (n-1) / k != n / k Also depends on what res is initialised to in the second case :-) A: Certainly there is a difference if you use floating point numbers, unless the Python interpreter/compiler you are using is capable of optimizing away the loop (Maybe Jython or IronPython might be able to? C compilers are pretty good at this). If you actually want these two approaches to be the same precision though, and you are using integers for your numerator and denominator, you can use the python fractions package from fractions import Fraction n,k = 999,1000 res = Fraction(0,1) for i in range(0,n): res += Fraction(1,k) print float(res)
Python:Which way gives better precision
Is there any difference in precision between one time assignment: res=n/k and multiple assignment in for cycle: for i in range(n): res+=1/k ?
[ "Floating-point division a/b is not mathematical division a ÷ b, except in very rare* circumstances. \nGenerally, floating point division a/b is a ÷ b + ε. \nThis is true for two reasons.\n\nFloat numbers (except in rare cases) are an approximation of the decimal number.\na is a + εa. \nb is b + εb.\nFloat numbers uses a base 2 encoding of the digits to the right of the decimal place. When you write 3.1, this is expanded to a base-2 approximation that differs from the real value by a small amount. \nReal decimal numbers have the same problem, by the way. Write down the decimal expansion of 1/3. Oops. You have to stop writing decimal places at some point. Binary floating point numbers have the same problem.\nDivision has a fixed number of binary places, meaning the answer is truncated. If there's a repeating binary pattern, it gets chopped. In rare cases, this doesn't matter. In general, you've introduced error by doing division.\n\nTherefore, when you do something like repeatedly add 1/k values you're computing\n1 ÷ k + ε\nAnd adding those up. Your result (if you had the right range) would be\nn × (1 ÷ k + ε) = n ÷ k + n × ε\nYou've multiplied the small error, ε, by n. Making it a big error. (Except in rare cases.)\nThis is bad. Very bad. All floating point division introduces an error. Your job as a programmer is to do the algebra to avoid or defer division to prevent this. Good software design means good algebra to prevent errors being introduced by the division operator.\n[* The rare cases. In rare cases, the small error happens to be zero. The rare cases occur when your floating point values are small whole numbers or fractions that are sums of powers of two 1/2, 1/4, 1/8, etc. In the rare case that you have a benign number with a benign fractional part, the error will be zero.] \n", "Sure, they are different, because of how floating point division works.\n>>> res = 0\n>>> for x in xrange(5000): res += 0.1\n... \n>>> res == 5000 * 0.1\nFalse\n\nThere's a good explanation in the python official tutorial.\n", "Well if k divides n then definitely the first one is more precise :-) To be serious, if the division is floating point and n > 1 then the first one will be more precise anyway though they will probably give different results, as nosklo said.\nBTW, in Python 2.6 the division is integer by default so you'll have very different results. 1/k will always give 0 unless k <= 1.\n", "Floating point arithmetic has representation and roundoff errors. For the types of data floating point numbers are intended to represent, real numbers of reasonable size, these errors are generally acceptable. \nIf you want to calculate the quotient of two numbers, the right way is simply to say result = n / k (beware if these are both integers and you have not said from __future__ import division, this is not what you may expect). The second way is silly, error-prone, and ugly.\nThere is some discussion of floating point inexactness in the Python tutorial: http://docs.python.org/tutorial/floatingpoint.html\n", "Even if we charitably assume a floating-point division, there's very definitely a difference in precision; the for loop is executed n - 1 times!\nassert (n-1) / k != n / k\n\nAlso depends on what res is initialised to in the second case :-)\n", "Certainly there is a difference if you use floating point numbers, unless the Python interpreter/compiler you are using is capable of optimizing away the loop (Maybe Jython or IronPython might be able to? C compilers are pretty good at this).\nIf you actually want these two approaches to be the same precision though, and you are using integers for your numerator and denominator, you can use the python fractions package\nfrom fractions import Fraction\nn,k = 999,1000\nres = Fraction(0,1)\n\nfor i in range(0,n):\n res += Fraction(1,k)\n\nprint float(res)\n\n" ]
[ 8, 3, 1, 0, 0, 0 ]
[]
[]
[ "precision", "python" ]
stackoverflow_0002368626_precision_python.txt
Q: Regex redefinition error I am using python, and run into some redefinition error, I know they are redefinition but logically its not possible to reach that since its an or. Is there a way to get around this? I appreciate for any help in advance /python-2.5/lib/python2.5/re.py", line 233, in _compile raise error, v # invalid expression sre_constants.error: redefinition of group name 'id' as group 9; was group 6 import re DOB_RE = "(^|;)DOB +(?P<dob>\d{2}-\d{2}-\d{4})" ID_RE = "(^|;)ID +(?P<id>[A-Z0-9]{12})" INFO_RE = "- (?P<info>.*)" PERSON_RE = "((" + DOB_RE + ".*" + ID_RE + ")|(" + \ ID_RE + ".*" + DOB_RE + ")|(" + \ DOB_RE + "|" + ID_RE + ")).*(" + INFO_RE + ")*" PARSER = re.compile(PERSON_RE) samplestr1 = garbage;DOB 10-10-2010;more garbage\nID PARI12345678;more garbage samplestr2 = garbage;ID PARI12345678;more garbage\nDOB 10-10-2010;more garbage samplestr3 = garbage;DOB 10-10-2010 samplestr4 = garbage;ID PARI12345678;more garbage- I am cool A: Regular expression syntax simply does not allow multiple occurrences of identically-named groups -- groups that aren't "reached" are defined to be "empty" (None) on a match. So you have to change those names e.g. to dob0, dob1, dob2 and id0, id1, id2 (then you can easily "collapse" these sets of keys to make the dict you actually want after you have a groups dictionary from a match). E.g., make the DOB_RE a function instead of a constant, say: def DOB_RE(i): return "(^|;)DOB +(?P<dob%s>\d{2}-\d{2}-\d{4})" % i and similarly for the others, and change the three occurrences of DOB_RE in the statement where you compute PERSON_RE to DOB_RE(0), DOB_RE(1) etc (and similarly for the others). A: I was originally going to post a pyparsing example using the Each class (which picks out expressions that can be in any order), but then I saw that there was intermixed garbage, so searching through your string using searchString seemed a better fit. This intrigued me because searchString returns a sequence of ParseResults, one for each match (including any corresponding named results). So I thought, "What if I combine the returned ParseResults using sum - what a hack!", er, "How novel!" So here's a never-before-seen pyparsing hack: from pyparsing import * # define the separate expressions to be matched, with results names dob_ref = "DOB" + Regex(r"\d{2}-\d{2}-\d{4}")("dob") id_ref = "ID" + Word(alphanums,exact=12)("id") info_ref = "-" + restOfLine("info") # create an overall expression person_data = dob_ref | id_ref | info_ref for test in (samplestr1,samplestr2,samplestr3,samplestr4,): # retrieve a list of separate matches separate_results = person_data.searchString(test) # combine the results using sum # (NO ONE HAS EVER DONE THIS BEFORE!) person = sum(separate_results, ParseResults([])) # now we have a uber-ParseResults object! print person.id print person.dump() print Giving this output: PARI12345678 ['DOB', '10-10-2010', 'ID', 'PARI12345678'] - dob: 10-10-2010 - id: PARI12345678 PARI12345678 ['ID', 'PARI12345678', 'DOB', '10-10-2010'] - dob: 10-10-2010 - id: PARI12345678 ['DOB', '10-10-2010'] - dob: 10-10-2010 PARI12345678 ['ID', 'PARI12345678', '-', ' I am cool'] - id: PARI12345678 - info: I am cool But I do also speak regex. Here is a similar approach using re's. import re # define each individual re, with group names dobRE = r"DOB +(?P<dob>\d{2}-\d{2}-\d{4})" idRE = r"ID +(?P<id>[A-Z0-9]{12})" infoRE = r"- (?P<info>.*)" # one re to rule them all person_dataRE = re.compile('|'.join([dobRE, idRE, infoRE])) # using findall with person_dataRE will return a 3-tuple, so let's create # a tuple-merger merge = lambda a,b : tuple(aa or bb for aa,bb in zip(a,b)) # let's create a Person class to collect the different data bits # (or if you are running Py2.6, use a namedtuple class Person: def __init__(self,*args): self.dob, self.id, self.info = args def __str__(self): return "- id: %s\n- dob: %s\n- info: %s" % (self.id, self.dob, self.info) for test in (samplestr1,samplestr2,samplestr3,samplestr4,): # could have used reduce here, but let's err on the side of explicity persontuple = ('','','') for data in person_dataRE.findall(test): persontuple = merge(persontuple,data) # make a person person = Person(*persontuple) # print out the collected results print person.id print person print With this output: PARI12345678 - id: PARI12345678 - dob: 10-10-2010 - info: PARI12345678 - id: PARI12345678 - dob: 10-10-2010 - info: - id: - dob: 10-10-2010 - info: PARI12345678 - id: PARI12345678 - dob: - info: I am cool A: Perhaps in this case it is better to loop through a list of regular expressions. >>> strs=[ ... "garbage;DOB 10-10-2010;more garbage\nID PARI12345678;more garbage", ... "garbage;ID PARI12345678;more garbage\nDOB 10-10-2010;more garbage", ... "garbage;DOB 10-10-2010", ... "garbage;ID PARI12345678;more garbage- I am cool"] >>> import re >>> >>> DOB_RE = "(^|;|\n)DOB +(?P<dob>\d{2}-\d{2}-\d{4})" >>> ID_RE = "(^|;|\n)ID +(?P<id>[A-Z0-9]{12})" >>> INFO_RE = "(- (?P<info>.*))?" >>> >>> REGEX = map(re.compile,[DOB_RE + ".*" + ID_RE + "[^-]*" + INFO_RE, ... ID_RE + ".*" + DOB_RE + "[^-]*" + INFO_RE, ... DOB_RE + "[^-]*" + INFO_RE, ... ID_RE + "[^-]*" + INFO_RE]) >>> >>> def get_person(s): ... for regex in REGEX: ... res = re.search(regex,s) ... if res: ... return res.groupdict() ... >>> for s in strs: ... print get_person(s) ... {'dob': '10-10-2010', 'info': None, 'id': 'PARI12345678'} {'dob': '10-10-2010', 'info': None, 'id': 'PARI12345678'} {'dob': '10-10-2010', 'info': None} {'info': 'I am cool', 'id': 'PARI12345678'}
Regex redefinition error
I am using python, and run into some redefinition error, I know they are redefinition but logically its not possible to reach that since its an or. Is there a way to get around this? I appreciate for any help in advance /python-2.5/lib/python2.5/re.py", line 233, in _compile raise error, v # invalid expression sre_constants.error: redefinition of group name 'id' as group 9; was group 6 import re DOB_RE = "(^|;)DOB +(?P<dob>\d{2}-\d{2}-\d{4})" ID_RE = "(^|;)ID +(?P<id>[A-Z0-9]{12})" INFO_RE = "- (?P<info>.*)" PERSON_RE = "((" + DOB_RE + ".*" + ID_RE + ")|(" + \ ID_RE + ".*" + DOB_RE + ")|(" + \ DOB_RE + "|" + ID_RE + ")).*(" + INFO_RE + ")*" PARSER = re.compile(PERSON_RE) samplestr1 = garbage;DOB 10-10-2010;more garbage\nID PARI12345678;more garbage samplestr2 = garbage;ID PARI12345678;more garbage\nDOB 10-10-2010;more garbage samplestr3 = garbage;DOB 10-10-2010 samplestr4 = garbage;ID PARI12345678;more garbage- I am cool
[ "Regular expression syntax simply does not allow multiple occurrences of identically-named groups -- groups that aren't \"reached\" are defined to be \"empty\" (None) on a match.\nSo you have to change those names e.g. to dob0, dob1, dob2 and id0, id1, id2 (then you can easily \"collapse\" these sets of keys to make the dict you actually want after you have a groups dictionary from a match).\nE.g., make the DOB_RE a function instead of a constant, say:\ndef DOB_RE(i): return \"(^|;)DOB +(?P<dob%s>\\d{2}-\\d{2}-\\d{4})\" % i\n\nand similarly for the others, and change the three occurrences of DOB_RE in the statement where you compute PERSON_RE to DOB_RE(0), DOB_RE(1) etc (and similarly for the others).\n", "I was originally going to post a pyparsing example using the Each class (which picks out expressions that can be in any order), but then I saw that there was intermixed garbage, so searching through your string using searchString seemed a better fit. This intrigued me because searchString returns a sequence of ParseResults, one for each match (including any corresponding named results). So I thought, \"What if I combine the returned ParseResults using sum - what a hack!\", er, \"How novel!\" So here's a never-before-seen pyparsing hack:\nfrom pyparsing import *\n# define the separate expressions to be matched, with results names\ndob_ref = \"DOB\" + Regex(r\"\\d{2}-\\d{2}-\\d{4}\")(\"dob\")\nid_ref = \"ID\" + Word(alphanums,exact=12)(\"id\")\ninfo_ref = \"-\" + restOfLine(\"info\")\n\n# create an overall expression\nperson_data = dob_ref | id_ref | info_ref\n\nfor test in (samplestr1,samplestr2,samplestr3,samplestr4,):\n # retrieve a list of separate matches\n separate_results = person_data.searchString(test)\n\n # combine the results using sum\n # (NO ONE HAS EVER DONE THIS BEFORE!)\n person = sum(separate_results, ParseResults([]))\n\n # now we have a uber-ParseResults object!\n print person.id\n print person.dump()\n print\n\nGiving this output:\nPARI12345678\n['DOB', '10-10-2010', 'ID', 'PARI12345678']\n- dob: 10-10-2010\n- id: PARI12345678\n\nPARI12345678\n['ID', 'PARI12345678', 'DOB', '10-10-2010']\n- dob: 10-10-2010\n- id: PARI12345678\n\n\n['DOB', '10-10-2010']\n- dob: 10-10-2010\n\nPARI12345678\n['ID', 'PARI12345678', '-', ' I am cool']\n- id: PARI12345678\n- info: I am cool\n\nBut I do also speak regex. Here is a similar approach using re's.\nimport re\n\n# define each individual re, with group names\ndobRE = r\"DOB +(?P<dob>\\d{2}-\\d{2}-\\d{4})\"\nidRE = r\"ID +(?P<id>[A-Z0-9]{12})\"\ninfoRE = r\"- (?P<info>.*)\"\n\n# one re to rule them all\nperson_dataRE = re.compile('|'.join([dobRE, idRE, infoRE]))\n\n# using findall with person_dataRE will return a 3-tuple, so let's create \n# a tuple-merger\nmerge = lambda a,b : tuple(aa or bb for aa,bb in zip(a,b))\n\n# let's create a Person class to collect the different data bits \n# (or if you are running Py2.6, use a namedtuple\nclass Person:\n def __init__(self,*args):\n self.dob, self.id, self.info = args\n def __str__(self):\n return \"- id: %s\\n- dob: %s\\n- info: %s\" % (self.id, self.dob, self.info)\n\nfor test in (samplestr1,samplestr2,samplestr3,samplestr4,):\n # could have used reduce here, but let's err on the side of explicity\n persontuple = ('','','')\n for data in person_dataRE.findall(test):\n persontuple = merge(persontuple,data)\n\n # make a person\n person = Person(*persontuple)\n\n # print out the collected results\n print person.id\n print person\n print\n\nWith this output:\nPARI12345678\n- id: PARI12345678\n- dob: 10-10-2010\n- info: \n\nPARI12345678\n- id: PARI12345678\n- dob: 10-10-2010\n- info: \n\n\n- id: \n- dob: 10-10-2010\n- info: \n\nPARI12345678\n- id: PARI12345678\n- dob: \n- info: I am cool\n\n", "Perhaps in this case it is better to loop through a list of regular expressions. \n>>> strs=[\n... \"garbage;DOB 10-10-2010;more garbage\\nID PARI12345678;more garbage\",\n... \"garbage;ID PARI12345678;more garbage\\nDOB 10-10-2010;more garbage\",\n... \"garbage;DOB 10-10-2010\",\n... \"garbage;ID PARI12345678;more garbage- I am cool\"]\n>>> import re\n>>> \n>>> DOB_RE = \"(^|;|\\n)DOB +(?P<dob>\\d{2}-\\d{2}-\\d{4})\"\n>>> ID_RE = \"(^|;|\\n)ID +(?P<id>[A-Z0-9]{12})\"\n>>> INFO_RE = \"(- (?P<info>.*))?\"\n>>> \n>>> REGEX = map(re.compile,[DOB_RE + \".*\" + ID_RE + \"[^-]*\" + INFO_RE,\n... ID_RE + \".*\" + DOB_RE + \"[^-]*\" + INFO_RE,\n... DOB_RE + \"[^-]*\" + INFO_RE,\n... ID_RE + \"[^-]*\" + INFO_RE])\n>>> \n>>> def get_person(s):\n... for regex in REGEX:\n... res = re.search(regex,s)\n... if res:\n... return res.groupdict()\n... \n>>> for s in strs:\n... print get_person(s)\n... \n{'dob': '10-10-2010', 'info': None, 'id': 'PARI12345678'}\n{'dob': '10-10-2010', 'info': None, 'id': 'PARI12345678'}\n{'dob': '10-10-2010', 'info': None}\n{'info': 'I am cool', 'id': 'PARI12345678'}\n\n" ]
[ 2, 2, 1 ]
[]
[]
[ "python", "regex", "scripting" ]
stackoverflow_0002376049_python_regex_scripting.txt
Q: How do I remove a column from a table in beautifulsoup (Python) I have an html table, and I would like to remove a column. What is the easiest way to do this with BeautifulSoup or any other python library? A: lxml.html is nicer for manipulating HTML, IMO. Here's some code that will remove the second column of an HTML table. from lxml import html text = """ <table> <tr><th>head 1</th><th>head 2</th><th>head 3</th></tr> <tr><td>item 1</td><td>item 2</td><td>item 3</td></tr> </table> """ table = html.fragment_fromstring(text) # remove middle column for row in table.iterchildren(): row.remove(row.getchildren()[1]) print html.tostring(table, pretty_print=True) Result: <table> <tr> <th>head 1</th> <th>head 3</th> </tr> <tr> <td>item 1</td> <td>item 3</td> </tr> </table>
How do I remove a column from a table in beautifulsoup (Python)
I have an html table, and I would like to remove a column. What is the easiest way to do this with BeautifulSoup or any other python library?
[ "lxml.html is nicer for manipulating HTML, IMO. Here's some code that will remove the second column of an HTML table.\nfrom lxml import html\n\ntext = \"\"\"\n<table>\n<tr><th>head 1</th><th>head 2</th><th>head 3</th></tr>\n<tr><td>item 1</td><td>item 2</td><td>item 3</td></tr>\n</table>\n\"\"\"\n\ntable = html.fragment_fromstring(text)\n\n# remove middle column\nfor row in table.iterchildren():\n row.remove(row.getchildren()[1])\n\nprint html.tostring(table, pretty_print=True)\n\nResult:\n<table>\n<tr>\n<th>head 1</th>\n<th>head 3</th>\n</tr>\n<tr>\n<td>item 1</td>\n<td>item 3</td>\n</tr>\n</table>\n\n" ]
[ 2 ]
[]
[]
[ "beautifulsoup", "html_table", "python" ]
stackoverflow_0002376427_beautifulsoup_html_table_python.txt
Q: Apache using Python 2.4, Python 2.5 scripts failing Using CentOS5, I have Apache configured with the following directives. Alias /pscript/ /var/www/pscript/ <Directory "/var/www/pscript/"> Options +ExecCGI DirectoryIndex thetest.py AddHandler cgi-script .py </Directory> When I call www.domain.com/pscript/ then my python script runs and prints out my sys.path, which is displaying python2.4. When I call a different script that requires Python 2.5, I get a 500 Internal Server Error. Looking at my Apache error_log, I see the following line: [Wed Mar 03 16:58:44 2010] [error] [client 000.000.000.000] Please use Python 2.5 or greater From the command line, running python -V returns Python 2.5.5. I have both 2.4 and 2.5.5 installed, but only 2.5.5 should be in use. In an attempt to remedy the Apache problem I recompiled Python 2.5.5 to be safe, and made sure to enable shared library. Then I recompiled mod_python in case that was affecting something, but my sys.path is still python2.4. I wonder, do I need to recompile Apache 2.2.3 itself? I simply need Apache to utilize Python 2.5.5. Thanks in advance. A: Does the Python script have a first line something like: #!/usr/bin/python If so, maybe /usr/bin/python is Python version 2.4, while running python directly from the command line is running a different Python executable (version 2.5) from somewhere else in your path. Try: which python to see what executable is being run when you run python from the command line.
Apache using Python 2.4, Python 2.5 scripts failing
Using CentOS5, I have Apache configured with the following directives. Alias /pscript/ /var/www/pscript/ <Directory "/var/www/pscript/"> Options +ExecCGI DirectoryIndex thetest.py AddHandler cgi-script .py </Directory> When I call www.domain.com/pscript/ then my python script runs and prints out my sys.path, which is displaying python2.4. When I call a different script that requires Python 2.5, I get a 500 Internal Server Error. Looking at my Apache error_log, I see the following line: [Wed Mar 03 16:58:44 2010] [error] [client 000.000.000.000] Please use Python 2.5 or greater From the command line, running python -V returns Python 2.5.5. I have both 2.4 and 2.5.5 installed, but only 2.5.5 should be in use. In an attempt to remedy the Apache problem I recompiled Python 2.5.5 to be safe, and made sure to enable shared library. Then I recompiled mod_python in case that was affecting something, but my sys.path is still python2.4. I wonder, do I need to recompile Apache 2.2.3 itself? I simply need Apache to utilize Python 2.5.5. Thanks in advance.
[ "Does the Python script have a first line something like:\n#!/usr/bin/python\n\nIf so, maybe /usr/bin/python is Python version 2.4, while running python directly from the command line is running a different Python executable (version 2.5) from somewhere else in your path. Try:\nwhich python\n\nto see what executable is being run when you run python from the command line.\n" ]
[ 3 ]
[]
[]
[ "apache", "python" ]
stackoverflow_0002376768_apache_python.txt
Q: Markdown and Syntax Highlighting in Django with mixed code I have some problems with following string while trying to syntax highlight them: Example <code class="php"><? echo "<input type=\"text\">"; ?></code> The php part is rendered correctly, but the html part breaks. I use the Markdown and Syntax Highlighting snippet from http://www.djangosnippets.org/snippets/119/ Any idea how to escape the html part inside the php code correctly ? A: Looks like you need to pass your PHP/HTML hybrid code through the escape filter, to convert instances of < to &lt; etc. Use it like this in a template, assuming you've got your code in a template context variable called mycode: {{ mycode|escape }} A: Python markdown integrates with Pygments that do the syntax highlighting. You can go from markdown to html formatted text with source code with highlighted syntax. The short version is: import markdown html = markdown.markdown(text,['codehilite']) html contains the html formatted text with the source code highlighted. You just need to point to css style, that's it. Have a look at how to setup markdow and pygments to do syntax highlight for blogger. In your solution you can just include a reference to css which makes it even easier.
Markdown and Syntax Highlighting in Django with mixed code
I have some problems with following string while trying to syntax highlight them: Example <code class="php"><? echo "<input type=\"text\">"; ?></code> The php part is rendered correctly, but the html part breaks. I use the Markdown and Syntax Highlighting snippet from http://www.djangosnippets.org/snippets/119/ Any idea how to escape the html part inside the php code correctly ?
[ "Looks like you need to pass your PHP/HTML hybrid code through the escape filter, to convert instances of < to &lt; etc.\nUse it like this in a template, assuming you've got your code in a template context variable called mycode:\n{{ mycode|escape }}\n\n", "Python markdown integrates with Pygments that do the syntax highlighting.\nYou can go from markdown to html formatted text with source code with highlighted syntax.\nThe short version is:\nimport markdown\nhtml = markdown.markdown(text,['codehilite'])\n\nhtml contains the html formatted text with the source code highlighted. You just need to point to css style, that's it.\nHave a look at how to setup markdow and pygments to do syntax highlight for blogger.\nIn your solution you can just include a reference to css which makes it even easier.\n" ]
[ 1, 1 ]
[]
[]
[ "django", "markdown", "python", "syntax_highlighting" ]
stackoverflow_0002070831_django_markdown_python_syntax_highlighting.txt
Q: wx.TR_HAS_VARIABLE_ROW_HEIGHT has no effect? I created a TreeListCtrl in wxPython like following. self.tree = wx.gizmos.TreeListCtrl(self, style = wx.TR_DEFAULT_STYLE | wx.TR_FULL_ROW_HIGHLIGHT | wx.TR_HIDE_ROOT | wx.TR_HAS_VARIABLE_ROW_HEIGHT) As you see i set wx.TR_HAS_VARIABLE_ROW_HEIGHT but there is no effect. All the rows have same height. How can i change the row height in TreeListCtrl. Regards, A: wx.TR_HAS_VARIABLE_ROW_HEIGHT applies to wx.TreeCntrl not wx.gizmos.TreeListCtrl, read http://www.wxpython.org/docs/api/wx.gizmos.TreeListCtrl-class.html to see what that tree cntrl can do If you see the doc or code for wx.gizmos.TreeListCtrl it derives from wx.Control, so it seems to be a a generic implementation of TreeCtrl with extra columns but doesn't seem to inherit from wxTreeCntrl
wx.TR_HAS_VARIABLE_ROW_HEIGHT has no effect?
I created a TreeListCtrl in wxPython like following. self.tree = wx.gizmos.TreeListCtrl(self, style = wx.TR_DEFAULT_STYLE | wx.TR_FULL_ROW_HIGHLIGHT | wx.TR_HIDE_ROOT | wx.TR_HAS_VARIABLE_ROW_HEIGHT) As you see i set wx.TR_HAS_VARIABLE_ROW_HEIGHT but there is no effect. All the rows have same height. How can i change the row height in TreeListCtrl. Regards,
[ "wx.TR_HAS_VARIABLE_ROW_HEIGHT applies to wx.TreeCntrl not wx.gizmos.TreeListCtrl, read http://www.wxpython.org/docs/api/wx.gizmos.TreeListCtrl-class.html to see what that tree cntrl can do\nIf you see the doc or code for wx.gizmos.TreeListCtrl it derives from wx.Control, so it seems to be a a generic implementation of TreeCtrl with extra columns but doesn't seem to inherit from wxTreeCntrl\n" ]
[ 0 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0002377094_python_wxpython.txt
Q: How do I print number of notes to be played? How do I do the second line in my main argument? def main(): pic= makePicture( pickAFile()) ### It will print the number of notes to be played(which is the number of pixels in the pic divided by 16, why?)### listenToPicture(pic) def listenToPicture(pic): show(pic) w= getWidth(pic) h= getHeight(pic) for i in range(0, w, 4): for j in range(0, h, 4): for px in getPixels(pic): r= getRed(px) g= getGreen(px) b= getBlue(px) tot= (r+g+b)/9 playNote= tot + 24 A: in function listenToPicture(), you have this code: w= getWidth(pic) h= getHeight(pic) for i in range(0, w, 4): for j in range(0, h, 4): .... strangely, i and j are not used in the rest of the code, but seem to explain why the number of notes are the number of pixels divided by 16. the key is in range(0, w, 4) and range(0,h,4). do you know what they mean ? what are the 2 loops performing ? (if you need, draw yourself a small picture on a grid paper, and execute your algorithm by hand)
How do I print number of notes to be played?
How do I do the second line in my main argument? def main(): pic= makePicture( pickAFile()) ### It will print the number of notes to be played(which is the number of pixels in the pic divided by 16, why?)### listenToPicture(pic) def listenToPicture(pic): show(pic) w= getWidth(pic) h= getHeight(pic) for i in range(0, w, 4): for j in range(0, h, 4): for px in getPixels(pic): r= getRed(px) g= getGreen(px) b= getBlue(px) tot= (r+g+b)/9 playNote= tot + 24
[ "in function listenToPicture(), you have this code:\nw= getWidth(pic)\nh= getHeight(pic)\nfor i in range(0, w, 4):\n for j in range(0, h, 4):\n ....\n\nstrangely, i and j are not used in the rest of the code, but seem to explain why the number of notes are the number of pixels divided by 16.\nthe key is in range(0, w, 4) and range(0,h,4). do you know what they mean ? what are the 2 loops performing ? (if you need, draw yourself a small picture on a grid paper, and execute your algorithm by hand)\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0002376788_python.txt
Q: How do I loop through every 4th pixel in every 4th row, using Python? Write a function called listenToPicture that takes one picture as an argument. It first shows the picture. Next , it will loop through every 4th pixel in every 4th row and do the following. It will compute the total of the red, green and blue levels of the pixel, divide that by 9, then add the result to 24. That number will be the note number played by playNote. That means that the darker the pixel, the lower the note; the lighter the pixel, the higher the note. It will play that note at full volume (127) for a tenth of a second (100 milliseconds). Every time it moves to a new row, it prints out the row number (y value) on the console. Your main function will ask the user to select a file with a picture. It will print the number of notes to be played (which is the number of pixels in the picture divided by 16; why?). It will then call the listenToPicture function. Here's what I have so far, and I'm not sure how to set up looping through every 4th pixels in every 4th row. Any help will be greatly appreciate. def main(): pic= makePicture( pickAFile()) printNow (getPixels(pic)/16) listenToPicture(pic) def listenToPicture(pic): show(pic) w=getWidth(pic) h=getHeight(pic) for px in getPixels(pic): r= getRed(px) g= getGreen(px) b= getBlue(px) tot= (r+g+b)/9 playNote= tot + 24 A: Stepped ranges come to mind range(0, len(), 4) but I don't know the type of your pic. A: Here's some building blocks you could base your program on: #!/usr/bin/env python import easygui import Image import numpy filename = easygui.fileopenbox() # pick a file im = Image.open(filename) # make picture image_width, image_height = im.size im.show() # show picture ar = numpy.asarray(im) # get all pixels N = 4 pixels = ar[::N,::4] # every 4th pixel in every N-th row notes = pixels.sum(axis=2) / 9 + 24 # compute notes [0, 52] print "number of notes to play:", notes.size Notes can correspond to different tones. I use here equal tempered scale: # play the notes import audiere import time d = audiere.open_device() # Notes in equal tempered scale f0, a = 440, 2**(1/12.) tones = [d.create_tone(f0*a**n) for n in range(-26, 27)] # 53 for y, row in enumerate(notes): print N*y # print original row number for t in (tones[note] for note in row): t.volume = 1.0 # maximum volume t.play() time.sleep(0.1) # wait around 100 milliseconds t.stop() A: You might want to look at this question. The person who asked that question seems to working on the same project as you. A: I would guess the best way is to calculate the offset of 4 rows, and, when at the end of the row, add it to the current position. So you ave two iterations: one within the row, that skip 3 pixels, and one at the end of each row that skip 3 lines. But, as msw noted, without any information on your pic object, we can't help more.
How do I loop through every 4th pixel in every 4th row, using Python?
Write a function called listenToPicture that takes one picture as an argument. It first shows the picture. Next , it will loop through every 4th pixel in every 4th row and do the following. It will compute the total of the red, green and blue levels of the pixel, divide that by 9, then add the result to 24. That number will be the note number played by playNote. That means that the darker the pixel, the lower the note; the lighter the pixel, the higher the note. It will play that note at full volume (127) for a tenth of a second (100 milliseconds). Every time it moves to a new row, it prints out the row number (y value) on the console. Your main function will ask the user to select a file with a picture. It will print the number of notes to be played (which is the number of pixels in the picture divided by 16; why?). It will then call the listenToPicture function. Here's what I have so far, and I'm not sure how to set up looping through every 4th pixels in every 4th row. Any help will be greatly appreciate. def main(): pic= makePicture( pickAFile()) printNow (getPixels(pic)/16) listenToPicture(pic) def listenToPicture(pic): show(pic) w=getWidth(pic) h=getHeight(pic) for px in getPixels(pic): r= getRed(px) g= getGreen(px) b= getBlue(px) tot= (r+g+b)/9 playNote= tot + 24
[ "Stepped ranges come to mind range(0, len(), 4) but I don't know the type of your pic.\n", "Here's some building blocks you could base your program on:\n#!/usr/bin/env python\nimport easygui\nimport Image\nimport numpy\n\nfilename = easygui.fileopenbox() # pick a file\nim = Image.open(filename) # make picture\nimage_width, image_height = im.size\nim.show() # show picture\nar = numpy.asarray(im) # get all pixels\nN = 4\npixels = ar[::N,::4] # every 4th pixel in every N-th row\nnotes = pixels.sum(axis=2) / 9 + 24 # compute notes [0, 52]\nprint \"number of notes to play:\", notes.size\n\nNotes can correspond to different tones. I use here equal tempered scale:\n# play the notes\nimport audiere\nimport time\n\nd = audiere.open_device()\n# Notes in equal tempered scale \nf0, a = 440, 2**(1/12.)\ntones = [d.create_tone(f0*a**n) for n in range(-26, 27)] # 53\n\nfor y, row in enumerate(notes):\n print N*y # print original row number\n for t in (tones[note] for note in row):\n t.volume = 1.0 # maximum volume\n t.play()\n time.sleep(0.1) # wait around 100 milliseconds\n t.stop()\n\n", "You might want to look at this question. The person who asked that question seems to working on the same project as you.\n", "I would guess the best way is to calculate the offset of 4 rows, and, when at the end of the row, add it to the current position. So you ave two iterations: one within the row, that skip 3 pixels, and one at the end of each row that skip 3 lines. But, as msw noted, without any information on your pic object, we can't help more.\n" ]
[ 3, 1, 1, 0 ]
[]
[]
[ "audio", "image", "python" ]
stackoverflow_0002376505_audio_image_python.txt
Q: Django form INSERTs when I want it to UPDATE I'm new to Django but I seem to have nearly identical code working on another site. I can update a record in the Django shell, but in view.py the same code insists on INSERTing a new record when I run this form. I have a "DisciplineEvent" object in the model. I let Django create the "id" field for the primary key. I can see the "id" int column has been created with auto_increment in MySQL The form DisciplineEventEntryForm is created from the "DisciplineEvent" model object. To edit a record, the entry form is populated and the pk is put in a hidden field named "id", which appears to be submitted along with the POST data. So the relevant part of the view.py is this: if request.method == 'POST': incidentId = request.POST['id'] editedEvent = DisciplineEvent.objects.get(pk=int(incidentId)) form = DisciplineEventEntryForm(request.POST, instance=editedEvent) form.save() variables = Context({ 'account': account, 'date': request.POST['event_date'], 'description': request.POST['incident_description'], 'incident_id':incidentId, }) template = get_template('disciplineform_confirm_entry.html') output = template.render(variables) response = HttpResponse(output) return response I thought this would pull the record in question, save the new form data into it, and UPDATE the record. Instead it creates a new record with all the data and an incremented primary key. A: What you are trying to do is unconventional and a possible security hole. You should not get the instance of the object from the hidden id key you populated in the form. Users can easily change this one and get your code to overwrite some other model instance that they may not even have permission for. The standard way to do it is to obtain the object based on the url. def view_function(request,id): object_to_edit = get_object_or_404(Model,id=id) #Or slug=slug form = ModelForm(data = request.POST or None, instance=object_to_edit) if form.is_valid(): form.save() redirect() return render_to_response('template_name',{},RequestContext(request)) Hope it helps!
Django form INSERTs when I want it to UPDATE
I'm new to Django but I seem to have nearly identical code working on another site. I can update a record in the Django shell, but in view.py the same code insists on INSERTing a new record when I run this form. I have a "DisciplineEvent" object in the model. I let Django create the "id" field for the primary key. I can see the "id" int column has been created with auto_increment in MySQL The form DisciplineEventEntryForm is created from the "DisciplineEvent" model object. To edit a record, the entry form is populated and the pk is put in a hidden field named "id", which appears to be submitted along with the POST data. So the relevant part of the view.py is this: if request.method == 'POST': incidentId = request.POST['id'] editedEvent = DisciplineEvent.objects.get(pk=int(incidentId)) form = DisciplineEventEntryForm(request.POST, instance=editedEvent) form.save() variables = Context({ 'account': account, 'date': request.POST['event_date'], 'description': request.POST['incident_description'], 'incident_id':incidentId, }) template = get_template('disciplineform_confirm_entry.html') output = template.render(variables) response = HttpResponse(output) return response I thought this would pull the record in question, save the new form data into it, and UPDATE the record. Instead it creates a new record with all the data and an incremented primary key.
[ "What you are trying to do is unconventional and a possible security hole.\nYou should not get the instance of the object from the hidden id key you populated in the form. Users can easily change this one and get your code to overwrite some other model instance that they may not even have permission for.\nThe standard way to do it is to obtain the object based on the url.\ndef view_function(request,id):\n object_to_edit = get_object_or_404(Model,id=id) #Or slug=slug\n form = ModelForm(data = request.POST or None, instance=object_to_edit)\n if form.is_valid():\n form.save()\n redirect()\n return render_to_response('template_name',{},RequestContext(request))\n\nHope it helps!\n" ]
[ 9 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002376797_django_python.txt
Q: deprecation of apply decorator There was a beautiful way to organize class property in frame of one function, by using the apply decorator. class Example(object): @apply def myattr(): doc = """This is the doc string.""" def fget(self): return self._half * 2 def fset(self, value): self._half = value / 2 def fdel(self): del self._half return property(**locals()) But now apply has been deprecated. Is there any possibility to achieve such simplicity and readability for property, with new, came instead “extended call syntax”? My approach is same as Anurag’s, but, I don’t now witch one is better, please look: def prop(f): return property(**f()) class A(object): @prop def myattr(): def fget(self): return self._myattr def fset(self, value): self._myattr = value return locals() A: Is there any possibility to achieve such simplicity and readability for property The new Python 2.6 way is: @property def myattr(self): """This is the doc string.""" return self._half * 2 @myattr.setter def myattr(self, value): self._half = value / 2 @myattr.deleter def myattr(self): del self._half A: :) that is a clever user of apply, though i am not sure if there are any pitfalls? anyway you can do this class Example(object): def myattr(): doc = """This is the doc string.""" def fget(self): return self._half * 2 def fset(self, value): self._half = value / 2 def fdel(self): del self._half return property(**locals()) myattr = myattr() A: You can always write your own: def apply(f, a): return f(*a) However, I'm not quite sure I see the benefit of using apply as a decorator in this way. What's the use case?
deprecation of apply decorator
There was a beautiful way to organize class property in frame of one function, by using the apply decorator. class Example(object): @apply def myattr(): doc = """This is the doc string.""" def fget(self): return self._half * 2 def fset(self, value): self._half = value / 2 def fdel(self): del self._half return property(**locals()) But now apply has been deprecated. Is there any possibility to achieve such simplicity and readability for property, with new, came instead “extended call syntax”? My approach is same as Anurag’s, but, I don’t now witch one is better, please look: def prop(f): return property(**f()) class A(object): @prop def myattr(): def fget(self): return self._myattr def fset(self, value): self._myattr = value return locals()
[ "\nIs there any possibility to achieve such simplicity and readability for property\n\nThe new Python 2.6 way is:\n@property\ndef myattr(self):\n \"\"\"This is the doc string.\"\"\"\n return self._half * 2\n\n@myattr.setter\ndef myattr(self, value):\n self._half = value / 2\n\n@myattr.deleter\ndef myattr(self):\n del self._half\n\n", ":) that is a clever user of apply, though i am not sure if there are any pitfalls?\nanyway you can do this\nclass Example(object):\n def myattr():\n doc = \"\"\"This is the doc string.\"\"\"\n\n def fget(self):\n return self._half * 2\n\n def fset(self, value):\n self._half = value / 2\n\n def fdel(self):\n del self._half\n\n return property(**locals())\n myattr = myattr()\n\n", "You can always write your own:\ndef apply(f, a):\n return f(*a)\n\nHowever, I'm not quite sure I see the benefit of using apply as a decorator in this way. What's the use case?\n" ]
[ 12, 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002377573_python.txt
Q: Python check for blank CSV value not working I have a CSV file and I am running a script against it to insert into a database. If the value is blank then I don't want to insert it. Here is what I have if attrs[attr] != '' and attrs[attr] != None: log.info('Attriute ID: %s' % attr) log.info('Attriute Value: %s' % attrs[attr]) sql = insert_attr_query(attrs[attr], object_id, attr) cursor.execute(sql) It's blank and it doesn't = '' or None, then wth does it =? A: It's probably whitespace i.e. a tab or string with spaces try:- attrs[attr].strip() A: Presumably it contains whitespace. You could check this by printing repr(attrs[attr]) which will put quotes round it and show tabs at "\t" Change the code to if attrs[attr] is not None and attrs[attr].strip() !="": A: You should (almost) always normalise whitespace in any text string that is intended for insertion in a database (or for many other purposes). To normalise whitespace is to (1) strip any leading whitespace (2) strip any trailing whitespace (3) replace any internal runs (length >= 1) of whitespace by exactly 1 SPACE (U+0020). Whitespace should not be limited to what standard Python provides, especially if you are working in Python 2.X and not using unicode objects. For example, in the default "C" locale, "\xA0" is not treated as whitespace but it's very likely to represent NO-BREAK SPACE (U+00A0). Sample code for Python 2.X: def normalize_white_space_u(unicode_object): return u' '.join(unicode_object.split()) def normalize_white_space_s(str_object): return ' '.join(str_object.replace('\xA0', ' ').split()) Generalizing the second function: replace each occurrence of a non-standard whitespace character by a single space and then do the split-join dance.
Python check for blank CSV value not working
I have a CSV file and I am running a script against it to insert into a database. If the value is blank then I don't want to insert it. Here is what I have if attrs[attr] != '' and attrs[attr] != None: log.info('Attriute ID: %s' % attr) log.info('Attriute Value: %s' % attrs[attr]) sql = insert_attr_query(attrs[attr], object_id, attr) cursor.execute(sql) It's blank and it doesn't = '' or None, then wth does it =?
[ "It's probably whitespace i.e. a tab or string with spaces try:-\nattrs[attr].strip()\n\n", "Presumably it contains whitespace. You could check this by printing repr(attrs[attr]) which will put quotes round it and show tabs at \"\\t\"\nChange the code to if attrs[attr] is not None and attrs[attr].strip() !=\"\":\n", "You should (almost) always normalise whitespace in any text string that is intended for insertion in a database (or for many other purposes).\nTo normalise whitespace is to (1) strip any leading whitespace (2) strip any trailing whitespace (3) replace any internal runs (length >= 1) of whitespace by exactly 1 SPACE (U+0020).\nWhitespace should not be limited to what standard Python provides, especially if you are working in Python 2.X and not using unicode objects. For example, in the default \"C\" locale, \"\\xA0\" is not treated as whitespace but it's very likely to represent NO-BREAK SPACE (U+00A0).\nSample code for Python 2.X:\ndef normalize_white_space_u(unicode_object):\n return u' '.join(unicode_object.split())\n\ndef normalize_white_space_s(str_object):\n return ' '.join(str_object.replace('\\xA0', ' ').split())\n\nGeneralizing the second function: replace each occurrence of a non-standard whitespace character by a single space and then do the split-join dance.\n" ]
[ 4, 3, 1 ]
[]
[]
[ "csv", "null", "python" ]
stackoverflow_0002375604_csv_null_python.txt
Q: Django Timed Events I want to schedule events to happen for my users. Is there an efficient way to do this in Python/Django easily? I'd prefer not to poll a priority queue. Thanks! Edit: I want to clarify that this job is run per user, for potentially hundreds or thousands of users. A: This may help: Django - Set Up A Scheduled Job? A: You should probably look at: http://celeryproject.org/ From the website: "Celery is already used in production to process millions of tasks a day." A: How about django-cron?
Django Timed Events
I want to schedule events to happen for my users. Is there an efficient way to do this in Python/Django easily? I'd prefer not to poll a priority queue. Thanks! Edit: I want to clarify that this job is run per user, for potentially hundreds or thousands of users.
[ "This may help:\nDjango - Set Up A Scheduled Job?\n", "You should probably look at: http://celeryproject.org/\nFrom the website:\n\n\"Celery is already used in production to process millions of tasks a day.\"\n\n", "How about django-cron? \n" ]
[ 2, 2, 0 ]
[]
[]
[ "django", "python", "scheduled_tasks", "scheduling" ]
stackoverflow_0002377661_django_python_scheduled_tasks_scheduling.txt
Q: Imports in Python project with doctests I have a Python project with following directory structure: /(some files) /model/(python files) /tools/(more python files) ... So, I have Python files in couple subdirectories and there are some dependencies between directories as well: tools are used by model, etc. Now my problem is that I want to make doctests for both models and tools, and I want be able to run tests from command line like this: ./model/car.py . I can make this work, but only with messy boilerplate code. I would like to know what is the correct way, or is there any? Question: How should I write my imports? Thanx. Here is an example... Content of tools/tool.py: #!/usr/bin/env python """ >>> is_four(21) False >>> is_four(4) True """ def is_four(val): return val == 4 if __name__ == '__main__': import doctest doctest.testmod() ... and model/car.py: #!/usr/bin/env python """ >>> car = Car() >>> car.ok() True """ from tools.tool import * class Car(object): def __init__(self): self.tire_count = 4 def ok(self): return is_four(self.tire_count) if __name__ == '__main__': import doctest doctest.testmod() By adding following lines in the begin of car.py it works, but doesn't look nice. :( if __name__ == '__main__': import sys import os sys.path.append(os.path.abspath(os.path.dirname('..'))) A: What you are trying to do is a relative import. It works fine in Python, but on the module level, not on the file system level. I know, this is confusing. It means that if you run a script in a subdir, it doesn't see the upper dirs because for the running script, the root of the module is the current dir: there is no upper module. So what are relative imports for? Well, module in subdirs car import module in upper dirs as long as they are themself imported from a upperdir. In your case it means you must run your scripts from "/" so it becomes the root of the module, and the submodules are allowed to use relative import. A possible solution to your problem is to remove your if __name__ == "__main__" block and create /tests.py: import doctest from model import car from tools import tool doctest.testmod(car) doctest.testmod(tool) Then run in too launch all the tests. Ultimately you will want to automatize the process, a simple solution is to use unittest so you can create test suites and just add the module names you want to test: import unittest import doctest modules = ("model.car", "tools.tool") suite = unittest.TestSuite() for mod in modules: suite.addTest(doctest.DocTestSuite(mod)) runner = unittest.TextTestRunner() runner.run(suite) Another solution (recommended) is to use a tool such as nose that automates this for you. easy_install nose nosetests --with-doctest # done :-) And by the way, avoid from x import *. This works for quick scripts, but when your program will grow, you really will need to explicitly name what you import. Either import x or from x import y A: Use packages. Add an __init__.py file to your working directory and all subfolders then your imports will search the parent directories if it doesn't find the module in the current directory. See http://www.network-theory.co.uk/docs/pytut/Packages.html Also this question is a duplicate of: Import a module from a relative path A: Don't frob sys.path in this manner. Instead either use $PYTHONPATH to force the base directory in when invoking python, or use python -m model.car from that directory.
Imports in Python project with doctests
I have a Python project with following directory structure: /(some files) /model/(python files) /tools/(more python files) ... So, I have Python files in couple subdirectories and there are some dependencies between directories as well: tools are used by model, etc. Now my problem is that I want to make doctests for both models and tools, and I want be able to run tests from command line like this: ./model/car.py . I can make this work, but only with messy boilerplate code. I would like to know what is the correct way, or is there any? Question: How should I write my imports? Thanx. Here is an example... Content of tools/tool.py: #!/usr/bin/env python """ >>> is_four(21) False >>> is_four(4) True """ def is_four(val): return val == 4 if __name__ == '__main__': import doctest doctest.testmod() ... and model/car.py: #!/usr/bin/env python """ >>> car = Car() >>> car.ok() True """ from tools.tool import * class Car(object): def __init__(self): self.tire_count = 4 def ok(self): return is_four(self.tire_count) if __name__ == '__main__': import doctest doctest.testmod() By adding following lines in the begin of car.py it works, but doesn't look nice. :( if __name__ == '__main__': import sys import os sys.path.append(os.path.abspath(os.path.dirname('..')))
[ "What you are trying to do is a relative import. It works fine in Python, but on the module level, not on the file system level. I know, this is confusing.\nIt means that if you run a script in a subdir, it doesn't see the upper dirs because for the running script, the root of the module is the current dir: there is no upper module.\nSo what are relative imports for? \nWell, module in subdirs car import module in upper dirs as long as they are themself imported from a upperdir.\nIn your case it means you must run your scripts from \"/\" so it becomes the root of the module, and the submodules are allowed to use relative import.\nA possible solution to your problem is to remove your if __name__ == \"__main__\" block and create /tests.py:\nimport doctest\nfrom model import car\nfrom tools import tool\n\ndoctest.testmod(car)\ndoctest.testmod(tool)\n\nThen run in too launch all the tests. \nUltimately you will want to automatize the process, a simple solution is to use unittest so you can create test suites and just add the module names you want to test:\nimport unittest\nimport doctest\n\nmodules = (\"model.car\", \n \"tools.tool\")\n\nsuite = unittest.TestSuite()\nfor mod in modules:\n suite.addTest(doctest.DocTestSuite(mod))\nrunner = unittest.TextTestRunner()\nrunner.run(suite)\n\nAnother solution (recommended) is to use a tool such as nose that automates this for you.\neasy_install nose\nnosetests --with-doctest # done :-)\n\nAnd by the way, avoid from x import *. This works for quick scripts, but when your program will grow, you really will need to explicitly name what you import. Either import x or from x import y\n", "Use packages. Add an __init__.py file to your working directory and all subfolders then your imports will search the parent directories if it doesn't find the module in the current directory.\nSee http://www.network-theory.co.uk/docs/pytut/Packages.html\nAlso this question is a duplicate of:\nImport a module from a relative path\n", "Don't frob sys.path in this manner. Instead either use $PYTHONPATH to force the base directory in when invoking python, or use python -m model.car from that directory.\n" ]
[ 2, 1, 0 ]
[]
[]
[ "linux", "path", "python", "unix" ]
stackoverflow_0002372125_linux_path_python_unix.txt
Q: Need help on python sqlite? 1.I have a list of data and a sqlite DB filled with past data along with some stats on each data. I have to do the following operations with them. Check if each item in the list is present in DB. if no then collect some stats on the new item and add them to DB. Check if each item in DB is in the list. if no delete it from DB. I cannot just create a new DB, coz I have other processing to do on the new items and the missing items. In short, i have to update the DB with the new data in list. What is best way to do it? 2.I had to use sqlite with python threads. So I put a lock for every DB read and write operation. Now it has slowed down the DB access. What is the overhead for thread lock operation? And Is there any other way to use the DB with multiple threads? Can someone help me on this?I am using python3.1. A: It does not need to check anything, just use INSERT OR IGNORE in first case (just make sure you have corresponding unique fields so INSERT would not create duplicates) and DELETE FROM tbl WHERE data NOT IN ('first item', 'second item', 'third item') in second case. As it is stated in the official SQLite FAQ, "Threads are evil. Avoid them." As far as I remember there were always problems with threads+sqlite. It's not that sqlite is not working with threads at all, just don't rely much on this feature. You can also make single thread working with database and pass all queries to it first, but effectiveness of such approach is heavily dependent on style of database usage in your program.
Need help on python sqlite?
1.I have a list of data and a sqlite DB filled with past data along with some stats on each data. I have to do the following operations with them. Check if each item in the list is present in DB. if no then collect some stats on the new item and add them to DB. Check if each item in DB is in the list. if no delete it from DB. I cannot just create a new DB, coz I have other processing to do on the new items and the missing items. In short, i have to update the DB with the new data in list. What is best way to do it? 2.I had to use sqlite with python threads. So I put a lock for every DB read and write operation. Now it has slowed down the DB access. What is the overhead for thread lock operation? And Is there any other way to use the DB with multiple threads? Can someone help me on this?I am using python3.1.
[ "\nIt does not need to check anything, just use INSERT OR IGNORE in first case (just make sure you have corresponding unique fields so INSERT would not create duplicates) and DELETE FROM tbl WHERE data NOT IN ('first item', 'second item', 'third item') in second case.\nAs it is stated in the official SQLite FAQ, \"Threads are evil. Avoid them.\" As far as I remember there were always problems with threads+sqlite. It's not that sqlite is not working with threads at all, just don't rely much on this feature. You can also make single thread working with database and pass all queries to it first, but effectiveness of such approach is heavily dependent on style of database usage in your program.\n\n" ]
[ 0 ]
[]
[]
[ "multithreading", "python", "sqlite" ]
stackoverflow_0002378364_multithreading_python_sqlite.txt
Q: python datetime.time operation t1 = datetime.time(12, 10, 0, tzinfo=GMT1()) # 12:10 t2 = datetime.time(13, 13, 0, tzinfo=GMT1()) #13:13 t3 = datetime.time(23, 55, 0, tzinfo=GMT1()) #23:55 t4 = datetime.time(01, 10, 0, tzinfo=GMT1()) #01:10 I need the minute interval between between two times. For instance a non working one: def minute_interval(start,end): return end - start minute_interval(t1,t2) #should give 63 mins. Also if the end time is smaller than start, it should do the calculation by understaing the end is from the next days time. ie: minute_interval(t3,t4) #should give 75 mins. How can this be achieved ? I need to rewrite the minute_interval function for this aim. A: Assuming time are in same timezone and no DST import datetime def minute_interval(start, end): reverse = False if start > end: start, end = end, start reverse = True delta = (end.hour - start.hour)*60 + end.minute - start.minute + (end.second - start.second)/60.0 if reverse: delta = 24*60 - delta return delta t1 = datetime.time(12, 10, 0) # 12:10 t2 = datetime.time(13, 13, 0) #13:13 t3 = datetime.time(23, 55, 0) #23:55 t4 = end = datetime.time(01, 10, 0) #01:10 print minute_interval(t1, t2) print minute_interval(t3, t4) output: 63 75 otherwise you are better of using datetime.datetime, which supports subtraction and gives datetime.timedelta, for timezone you can use pytz library. A: How's this? def minute_interval(start,end): start_sec= (start.hour*60+start.minute)*60+start.second end_sec= (end.hour*60+end.minute)*60+end.second return (end_sec-start_sec)/60.0 A: >>> import datetime >>> t1 = datetime.time(12, 10, 0) >>> t2 = datetime.time(13, 13, 0) >>> today = datetime.datetime.today() >>> t1n = datetime.datetime.combine(today, t1) >>> t2n = datetime.datetime.combine(today + datetime.timedelta(days=int(t2 < t1)), t2) >>> d = t2n - t1n >>> (d.days * 86400 + d.seconds) // 60 63
python datetime.time operation
t1 = datetime.time(12, 10, 0, tzinfo=GMT1()) # 12:10 t2 = datetime.time(13, 13, 0, tzinfo=GMT1()) #13:13 t3 = datetime.time(23, 55, 0, tzinfo=GMT1()) #23:55 t4 = datetime.time(01, 10, 0, tzinfo=GMT1()) #01:10 I need the minute interval between between two times. For instance a non working one: def minute_interval(start,end): return end - start minute_interval(t1,t2) #should give 63 mins. Also if the end time is smaller than start, it should do the calculation by understaing the end is from the next days time. ie: minute_interval(t3,t4) #should give 75 mins. How can this be achieved ? I need to rewrite the minute_interval function for this aim.
[ "Assuming time are in same timezone and no DST\nimport datetime\n\ndef minute_interval(start, end):\n reverse = False\n if start > end:\n start, end = end, start\n reverse = True\n\n delta = (end.hour - start.hour)*60 + end.minute - start.minute + (end.second - start.second)/60.0\n if reverse:\n delta = 24*60 - delta\n return delta\n\nt1 = datetime.time(12, 10, 0) # 12:10\nt2 = datetime.time(13, 13, 0) #13:13\nt3 = datetime.time(23, 55, 0) #23:55 \nt4 = end = datetime.time(01, 10, 0) #01:10\n\nprint minute_interval(t1, t2)\nprint minute_interval(t3, t4)\n\noutput:\n63\n75\n\notherwise you are better of using datetime.datetime, which supports subtraction and gives datetime.timedelta, for timezone you can use pytz library.\n", "How's this?\ndef minute_interval(start,end):\n start_sec= (start.hour*60+start.minute)*60+start.second\n end_sec= (end.hour*60+end.minute)*60+end.second\n return (end_sec-start_sec)/60.0\n\n", ">>> import datetime\n>>> t1 = datetime.time(12, 10, 0)\n>>> t2 = datetime.time(13, 13, 0)\n>>> today = datetime.datetime.today()\n>>> t1n = datetime.datetime.combine(today, t1)\n>>> t2n = datetime.datetime.combine(today + datetime.timedelta(days=int(t2 < t1)), t2)\n>>> d = t2n - t1n\n>>> (d.days * 86400 + d.seconds) // 60\n63\n\n" ]
[ 3, 1, 0 ]
[]
[]
[ "datetime", "intervals", "python" ]
stackoverflow_0002378521_datetime_intervals_python.txt
Q: Why does nose finds tests in files with only 644 permission? Today I ran a bunch of doctests using Python 2.6 on a Ubuntu 9.10 with nose : nosetests --with-doctest Ran 0 tests in 0.001s OK WTF? I had tests in that files, why didn't that work? I changed permission to 644: sudo chmod 644 * -R nosetests --with-doctest Ran 11 test in 0.004s FAILED (errors=1) Changing it back to 777: sudo chmod 777 * -R nosetests --with-doctest Ran 0 tests in 0.001s OK Why is that? Using 644, I can't even edit my files! A: Try the --exe flag: $ nosetests --help ... --exe Look for tests in python modules that are executable. Normal behavior is to exclude executable modules, since they may not be import-safe [NOSE_INCLUDE_EXE]
Why does nose finds tests in files with only 644 permission?
Today I ran a bunch of doctests using Python 2.6 on a Ubuntu 9.10 with nose : nosetests --with-doctest Ran 0 tests in 0.001s OK WTF? I had tests in that files, why didn't that work? I changed permission to 644: sudo chmod 644 * -R nosetests --with-doctest Ran 11 test in 0.004s FAILED (errors=1) Changing it back to 777: sudo chmod 777 * -R nosetests --with-doctest Ran 0 tests in 0.001s OK Why is that? Using 644, I can't even edit my files!
[ "Try the --exe flag:\n$ nosetests --help\n\n... \n\n--exe Look for tests in python modules that are executable.\n Normal behavior is to exclude executable modules,\n since they may not be import-safe [NOSE_INCLUDE_EXE]\n\n" ]
[ 11 ]
[]
[]
[ "doctest", "nose", "permissions", "python" ]
stackoverflow_0002378146_doctest_nose_permissions_python.txt
Q: How to use Corba with Python I'm wondering if anyone have a good resource for working with Corba in Python? I've googled around and saw that fnorb was recommended by some, but that it doesn't support some new features in Corba. Omniorb seemed like a good alternative, but I have no idea how to use it with Python (not fnorb either). Any advice is appreciated, I've only implemented some simple examples in Java before so my understanding of Corba is sparse. Thanks! A: What's wrong with the omniORBpy User's Guide ?
How to use Corba with Python
I'm wondering if anyone have a good resource for working with Corba in Python? I've googled around and saw that fnorb was recommended by some, but that it doesn't support some new features in Corba. Omniorb seemed like a good alternative, but I have no idea how to use it with Python (not fnorb either). Any advice is appreciated, I've only implemented some simple examples in Java before so my understanding of Corba is sparse. Thanks!
[ "What's wrong with the omniORBpy User's Guide ?\n" ]
[ 9 ]
[]
[]
[ "corba", "python" ]
stackoverflow_0002338331_corba_python.txt
Q: Accessing child nodein an xml in python How to retrieve the value of type in the below XML <info><category>Flip</category><info>2</info><type>Tree</type></info> A: Using ElementTree: import xml.etree.ElementTree as E e = E.parse("test.xml") print(e.find("type").text) Using minidom: import xml.dom.minidom d = xml.dom.minidom.parse("test.xml") print(d.getElementsByTagName("type")[0].firstChild.data) Using BeautifulSoup: from BeautifulSoup import BeautifulStoneSoup soup = BeautifulStoneSoup(open("test.xml")) print(soup.find("type").text)
Accessing child nodein an xml in python
How to retrieve the value of type in the below XML <info><category>Flip</category><info>2</info><type>Tree</type></info>
[ "Using ElementTree:\nimport xml.etree.ElementTree as E\ne = E.parse(\"test.xml\")\nprint(e.find(\"type\").text)\n\nUsing minidom:\nimport xml.dom.minidom\nd = xml.dom.minidom.parse(\"test.xml\")\nprint(d.getElementsByTagName(\"type\")[0].firstChild.data)\n\nUsing BeautifulSoup:\nfrom BeautifulSoup import BeautifulStoneSoup\nsoup = BeautifulStoneSoup(open(\"test.xml\"))\nprint(soup.find(\"type\").text)\n\n" ]
[ 2 ]
[]
[]
[ "python", "xml", "xml_parsing" ]
stackoverflow_0002378834_python_xml_xml_parsing.txt
Q: Accessing python variables in a list In the following code below, how to retrieve the value of id,Id has multiple values in it.How to access the values of id and update it to result1 def parse_results (): try: xml = minidom.parseString(new_results) for xmlchild in xmldoc.childNodes[0].childNodes : result1 = {} result1.update ({'firstname': xmlchild.getElementsByTagName("firstname")[0].childNodes[0].nodeValue}) result1.update ({'lastname': xmlchild.getElementsByTagName("lastname")[0].childNodes[0].nodeValue}) result1.update ({'address': address}) if xmlchild.getElementsByTagName("id")[0].childNodes[0].nodeValue: logging.debug(xmlchild.getElementsByTagName("id")[0].childNodes[0].nodeValue.lower()) result1.update ({'id': id}) Edit: xmlchild.getElementsByTagName("id")[0].childNodes[0].nodeValue -this statement gives an exception Adding XML: <info><firstname>firstname</firstname><lastname>lastname</lastname><id>2</id></info> <info><firstname>firstname</firstname><lastname>lastname</lastname><id>3</id></info> <info><firstname>firstname</firstname><lastname>lastname</lastname><id>4</id></info> A: Why are you using minidom? It is really boring to use. I suggest you move to element tree: import xml.etree.ElementTree as et d = et.fromstring(''' <doc> <info><firstname>firstname</firstname><lastname>lastname</lastname><id>2</id></info> <info><firstname>firstname</firstname><lastname>lastname</lastname><id>3</id></info> <info><firstname>firstname</firstname><lastname>lastname</lastname><id>4</id></info> </doc> ''') result = [dict((el.tag, el.text) for el in info) for info in d.findall('info')] print result That prints: [{'firstname': 'firstname', 'id': '2', 'lastname': 'lastname'}, {'firstname': 'firstname', 'id': '3', 'lastname': 'lastname'}, {'firstname': 'firstname', 'id': '4', 'lastname': 'lastname'}]
Accessing python variables in a list
In the following code below, how to retrieve the value of id,Id has multiple values in it.How to access the values of id and update it to result1 def parse_results (): try: xml = minidom.parseString(new_results) for xmlchild in xmldoc.childNodes[0].childNodes : result1 = {} result1.update ({'firstname': xmlchild.getElementsByTagName("firstname")[0].childNodes[0].nodeValue}) result1.update ({'lastname': xmlchild.getElementsByTagName("lastname")[0].childNodes[0].nodeValue}) result1.update ({'address': address}) if xmlchild.getElementsByTagName("id")[0].childNodes[0].nodeValue: logging.debug(xmlchild.getElementsByTagName("id")[0].childNodes[0].nodeValue.lower()) result1.update ({'id': id}) Edit: xmlchild.getElementsByTagName("id")[0].childNodes[0].nodeValue -this statement gives an exception Adding XML: <info><firstname>firstname</firstname><lastname>lastname</lastname><id>2</id></info> <info><firstname>firstname</firstname><lastname>lastname</lastname><id>3</id></info> <info><firstname>firstname</firstname><lastname>lastname</lastname><id>4</id></info>
[ "Why are you using minidom? It is really boring to use.\nI suggest you move to element tree:\nimport xml.etree.ElementTree as et\nd = et.fromstring('''\n<doc>\n <info><firstname>firstname</firstname><lastname>lastname</lastname><id>2</id></info>\n <info><firstname>firstname</firstname><lastname>lastname</lastname><id>3</id></info>\n <info><firstname>firstname</firstname><lastname>lastname</lastname><id>4</id></info>\n</doc>\n''')\n\nresult = [dict((el.tag, el.text) for el in info) for info in d.findall('info')]\nprint result\n\nThat prints:\n[{'firstname': 'firstname', 'id': '2', 'lastname': 'lastname'},\n {'firstname': 'firstname', 'id': '3', 'lastname': 'lastname'},\n {'firstname': 'firstname', 'id': '4', 'lastname': 'lastname'}]\n\n" ]
[ 0 ]
[]
[]
[ "class", "django_views", "python" ]
stackoverflow_0002378393_class_django_views_python.txt
Q: Installing a python module on windows I am trying to install a module called Swish-E 0.5 and for some reason im getting an error when running the command python setup.py install I keep getting this error no matter what module i try to install. I have tried installing other modules to see if the problem lay in that specific module however it does not. c:\Program Files\Microsoft Visual Studio 9.0\VC\BIN\cl.exe /c /nologo /Ox /MD /W 3 /GS- /DNDEBUG -I/usr/local/include -I/usr/include -IC:\Python26\include -IC:\P ython26\PC /TcSwishE.c /Fobuild\temp.win32-2.6\Release\SwishE.obj SwishE.c SwishE.c(35) : fatal error C1083: Cannot open include file: 'swish-e.h': No such file or directory error: command '"c:\Program Files\Microsoft Visual Studio 9.0\VC\BIN\cl.exe"' fa iled with exit status 2 This is the error DOS keeps dumping, no matter what module. Unfortunately i cannot find the binary file for the module i need therefore i must fix this problem. I have a feeling it is something to do with my C compiler if someone could please help it would be greatly appreciated. A: I you haven't already, install Swish-e. If you have, then grab the development files from the source tarball and put them somewhere the compiler can find them. A: Search your hard disk for the file swish-e.h and make sure the directory is mentioned in the command line after a -I (= add include path). A: You probably need to install/compile Swish-e itself before building Python module for it. Also missing header points to this cause - the Python module uses Swish-e library and headers.
Installing a python module on windows
I am trying to install a module called Swish-E 0.5 and for some reason im getting an error when running the command python setup.py install I keep getting this error no matter what module i try to install. I have tried installing other modules to see if the problem lay in that specific module however it does not. c:\Program Files\Microsoft Visual Studio 9.0\VC\BIN\cl.exe /c /nologo /Ox /MD /W 3 /GS- /DNDEBUG -I/usr/local/include -I/usr/include -IC:\Python26\include -IC:\P ython26\PC /TcSwishE.c /Fobuild\temp.win32-2.6\Release\SwishE.obj SwishE.c SwishE.c(35) : fatal error C1083: Cannot open include file: 'swish-e.h': No such file or directory error: command '"c:\Program Files\Microsoft Visual Studio 9.0\VC\BIN\cl.exe"' fa iled with exit status 2 This is the error DOS keeps dumping, no matter what module. Unfortunately i cannot find the binary file for the module i need therefore i must fix this problem. I have a feeling it is something to do with my C compiler if someone could please help it would be greatly appreciated.
[ "I you haven't already, install Swish-e. If you have, then grab the development files from the source tarball and put them somewhere the compiler can find them.\n", "Search your hard disk for the file swish-e.h and make sure the directory is mentioned in the command line after a -I (= add include path).\n", "You probably need to install/compile Swish-e itself before building Python module for it. Also missing header points to this cause - the Python module uses Swish-e library and headers.\n" ]
[ 0, 0, 0 ]
[]
[]
[ "python", "windows" ]
stackoverflow_0002379238_python_windows.txt
Q: Python modules matching a pattern I'd like to run doctests for a set of modules (glob: invenio.webtag*) from a single module, but I'll need a way to import all these (and only these) modules and run doctest.testmod() on all of them. Any ideas? Edit: The solution: import doctest import glob import os import pkgutil pkgpath = pkgutil.extend_path([], 'invenio')[0] for module_path in glob.glob(pkgpath + '/webtag*.py'): module_name = os.path.splitext(os.path.basename(module_path))[0] module = __import__('invenio.' + module_name) doctest.testmod(module) A: A module can be dynamically loaded using __import__ e.g. my_module = __import__("mymodule") and then passed to testmod e.g. doctest.testmod(my_module) Assuming you can build a list of the matching modules using either glob.glob or filtering the results from os.listdir you should be able to use this approach. Update: To import invenio.webtag try using a fromlist: module = __import__('invenio.webtag', globals(), locals(), ['invenio'], -1) see this documentation for the explanation.
Python modules matching a pattern
I'd like to run doctests for a set of modules (glob: invenio.webtag*) from a single module, but I'll need a way to import all these (and only these) modules and run doctest.testmod() on all of them. Any ideas? Edit: The solution: import doctest import glob import os import pkgutil pkgpath = pkgutil.extend_path([], 'invenio')[0] for module_path in glob.glob(pkgpath + '/webtag*.py'): module_name = os.path.splitext(os.path.basename(module_path))[0] module = __import__('invenio.' + module_name) doctest.testmod(module)
[ "A module can be dynamically loaded using __import__ e.g.\nmy_module = __import__(\"mymodule\")\n\nand then passed to testmod e.g.\ndoctest.testmod(my_module)\n\nAssuming you can build a list of the matching modules using either glob.glob or filtering the results from os.listdir you should be able to use this approach.\nUpdate:\nTo import invenio.webtag try using a fromlist:\nmodule = __import__('invenio.webtag', globals(), locals(), ['invenio'], -1)\n\nsee this documentation for the explanation.\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0002379285_python.txt
Q: Getting pubsubhubbub hub working I have followed the instructions found at http://code.google.com/p/pubsubhubbub/wiki/DeveloperGettingStartedGuide to setup a hub. When I start the hub I get following warnings $ sudo python2.5 google_appengine/dev_appserver.py pubsubhubbub/hub/ INFO 2010-03-04 12:29:57,928 appengine_rpc.py:157] Server: appengine.google.com INFO 2010-03-04 12:29:57,959 appcfg.py:329] Checking for updates to the SDK. WARNING 2010-03-04 12:29:58,272 datastore_file_stub.py:418] Could not read datastore data from /tmp/dev_appserver.datastore WARNING 2010-03-04 12:29:58,273 datastore_file_stub.py:418] Could not read datastore data from /tmp/dev_appserver.datastore.history INFO 2010-03-04 12:29:58,349 dev_appserver_main.py:465] Running application pubsubhubbub on port 8080: http://localhost:8080 http://pastie.org/853356 When I point my browser to http://localhost:8080 I get a nasty exceptions.AttributeError thrown in my browser & console ERROR 2010-03-04 12:31:27,735 dev_appserver.py:3000] Exception encountered handling request Traceback (most recent call last): File "/home/pentarim/webdev/pshb/google_appengine/google/appengine/tools/dev_appserver.py", line 2969, in _HandleRequest base_env_dict=env_dict) File "/home/pentarim/webdev/pshb/google_appengine/google/appengine/tools/dev_appserver.py", line 406, in Dispatch base_env_dict=base_env_dict) File "/home/pentarim/webdev/pshb/google_appengine/google/appengine/tools/dev_appserver.py", line 2238, in Dispatch self._module_dict) File "/home/pentarim/webdev/pshb/google_appengine/google/appengine/tools/dev_appserver.py", line 2156, in ExecuteCGI reset_modules = exec_script(handler_path, cgi_path, hook) File "/home/pentarim/webdev/pshb/google_appengine/google/appengine/tools/dev_appserver.py", line 2052, in ExecuteOrImportScript exec module_code in script_module.__dict__ File "/home/pentarim/webdev/pshb/pubsubhubbub/hub/main.py", line 116, in <module> import dos File "/home/pentarim/webdev/pshb/google_appengine/google/appengine/tools/dev_appserver.py", line 1158, in Decorate return func(self, *args, **kwargs) File "/home/pentarim/webdev/pshb/google_appengine/google/appengine/tools/dev_appserver.py", line 1806, in load_module return self.FindAndLoadModule(submodule, fullname, search_path) File "/home/pentarim/webdev/pshb/google_appengine/google/appengine/tools/dev_appserver.py", line 1158, in Decorate return func(self, *args, **kwargs) File "/home/pentarim/webdev/pshb/google_appengine/google/appengine/tools/dev_appserver.py", line 1708, in FindAndLoadModule description) File "/home/pentarim/webdev/pshb/google_appengine/google/appengine/tools/dev_appserver.py", line 1158, in Decorate return func(self, *args, **kwargs) File "/home/pentarim/webdev/pshb/google_appengine/google/appengine/tools/dev_appserver.py", line 1659, in LoadModuleRestricted description) File "/home/pentarim/webdev/pshb/pubsubhubbub/hub/dos.py", line 219, in <module> offset_multi=memcache.offset_multi, AttributeError: 'module' object has no attribute 'offset_multi' INFO 2010-03-04 12:31:27,749 dev_appserver.py:3029] "GET / HTTP/1.1" 500 - http://pastie.org/853357 As a python newbie would need help, any ideas? A: The tutorial at http://code.google.com/p/pubsubhubbub/wiki/DeveloperGettingStartedGuide is outdated, you need to use at least google app engine 1.2.8 to make it work (where New memcache offset_multi method and batch support in incr and decr. is added)
Getting pubsubhubbub hub working
I have followed the instructions found at http://code.google.com/p/pubsubhubbub/wiki/DeveloperGettingStartedGuide to setup a hub. When I start the hub I get following warnings $ sudo python2.5 google_appengine/dev_appserver.py pubsubhubbub/hub/ INFO 2010-03-04 12:29:57,928 appengine_rpc.py:157] Server: appengine.google.com INFO 2010-03-04 12:29:57,959 appcfg.py:329] Checking for updates to the SDK. WARNING 2010-03-04 12:29:58,272 datastore_file_stub.py:418] Could not read datastore data from /tmp/dev_appserver.datastore WARNING 2010-03-04 12:29:58,273 datastore_file_stub.py:418] Could not read datastore data from /tmp/dev_appserver.datastore.history INFO 2010-03-04 12:29:58,349 dev_appserver_main.py:465] Running application pubsubhubbub on port 8080: http://localhost:8080 http://pastie.org/853356 When I point my browser to http://localhost:8080 I get a nasty exceptions.AttributeError thrown in my browser & console ERROR 2010-03-04 12:31:27,735 dev_appserver.py:3000] Exception encountered handling request Traceback (most recent call last): File "/home/pentarim/webdev/pshb/google_appengine/google/appengine/tools/dev_appserver.py", line 2969, in _HandleRequest base_env_dict=env_dict) File "/home/pentarim/webdev/pshb/google_appengine/google/appengine/tools/dev_appserver.py", line 406, in Dispatch base_env_dict=base_env_dict) File "/home/pentarim/webdev/pshb/google_appengine/google/appengine/tools/dev_appserver.py", line 2238, in Dispatch self._module_dict) File "/home/pentarim/webdev/pshb/google_appengine/google/appengine/tools/dev_appserver.py", line 2156, in ExecuteCGI reset_modules = exec_script(handler_path, cgi_path, hook) File "/home/pentarim/webdev/pshb/google_appengine/google/appengine/tools/dev_appserver.py", line 2052, in ExecuteOrImportScript exec module_code in script_module.__dict__ File "/home/pentarim/webdev/pshb/pubsubhubbub/hub/main.py", line 116, in <module> import dos File "/home/pentarim/webdev/pshb/google_appengine/google/appengine/tools/dev_appserver.py", line 1158, in Decorate return func(self, *args, **kwargs) File "/home/pentarim/webdev/pshb/google_appengine/google/appengine/tools/dev_appserver.py", line 1806, in load_module return self.FindAndLoadModule(submodule, fullname, search_path) File "/home/pentarim/webdev/pshb/google_appengine/google/appengine/tools/dev_appserver.py", line 1158, in Decorate return func(self, *args, **kwargs) File "/home/pentarim/webdev/pshb/google_appengine/google/appengine/tools/dev_appserver.py", line 1708, in FindAndLoadModule description) File "/home/pentarim/webdev/pshb/google_appengine/google/appengine/tools/dev_appserver.py", line 1158, in Decorate return func(self, *args, **kwargs) File "/home/pentarim/webdev/pshb/google_appengine/google/appengine/tools/dev_appserver.py", line 1659, in LoadModuleRestricted description) File "/home/pentarim/webdev/pshb/pubsubhubbub/hub/dos.py", line 219, in <module> offset_multi=memcache.offset_multi, AttributeError: 'module' object has no attribute 'offset_multi' INFO 2010-03-04 12:31:27,749 dev_appserver.py:3029] "GET / HTTP/1.1" 500 - http://pastie.org/853357 As a python newbie would need help, any ideas?
[ "The tutorial at http://code.google.com/p/pubsubhubbub/wiki/DeveloperGettingStartedGuide is outdated, you need to use at least google app engine 1.2.8 to make it work (where New memcache offset_multi method and batch support in incr and decr. is added)\n" ]
[ 3 ]
[]
[]
[ "google_app_engine", "python", "websub" ]
stackoverflow_0002379263_google_app_engine_python_websub.txt
Q: problem opening a text document - unicode error i have probably rather simple question. however, i am just starting to use python and it just drives me crazy. i am following the instructions of a book and would like to open a simple text file. the code i am using: import sys try: d = open("p0901aus.txt" , "W") except: print("Unsucessfull") sys.exit(0) i am either getting the news, that i was unsucessfull in opening the document or pop up appears saying: (unicode eror) 'unicodeescape' codec can't decode bytes in position 2-4: truncated \UXXXXXXXX escape i have no clue what the problem is. i tried to save the document in different codes, tried different path...always the same problem does anybody know any help? thank you very much in advance, georg ps: i am using windows vista A: (unicode eror) 'unicodeescape' codec can't decode bytes in position 2-4: truncated \UXXXXXXXX escape This probably means that the file you are trying to read is not in the encoding that open() expects. Apparently open() expects some Unicode encoding (most likely UTF-8 or UTF-16), but your file is not encoded like that. You should not normally use plain open() for reading text files, as it is impossible to correctly read a text file (unless it's pure ASCII) without specifying an encoding. Use codecs instead: import codecs fileObj = codecs.open( "someFile", "r", "utf-8" ) u = fileObj.read() # Returns a Unicode string from the UTF-8 bytes in the file A: Change that to # for Python 2.5+ import sys try: d = open("p0901aus.txt","w") except Exception, ex: print "Unsuccessful." print ex sys.exit(0) # for Python 3 import sys import codecs try: d = codecs.open("p0901aus.txt","w","utf-8") except Exception as ex: print("Unsuccessful.") print(ex) sys.exit(0) The W is case-sensitive. I do not want to hit you with all the Python syntax at once, but it will be useful for you to know how to display what exception was raised, and this is one way to do it. Also, you are opening the file for writing, not reading. Is that what you wanted? If there is already a document named p0901aus.txt, and you want to read it, do this: #for Python 2.5+ import sys try: d = open("p0901aus.txt","r") print "Awesome, I opened p0901aus.txt. Here is what I found there:" for l in d: print l except Exception, ex: print "Unsuccessful." print ex sys.exit(0) #for Python 3+ import sys import codecs try: d = codecs.open("p0901aus.txt","r","utf-8") print "Awesome, I opened p0901aus.txt. Here is what I found there:" for l in d: print(l) except Exception, ex: print("Unsuccessful.") print(ex) sys.exit(0) You can of course use the codecs in Python 2.5 also, and your code will be higher quality ("correct") if you do. Python 3 appears to treat the Byte Order Mark as something between a curiosity and line noise which is a bummer. A: import csv data = csv.reader(open('c:\x\list.csv' )) for row in data: print(row) print('ready') Brings up "(unicode error)'unicodeescape' codec can't decode bytes in position 2-4: truncated \xXX escape" Try c:\\x\\list.csv instead of c:\x\list.csv This is Python 3 code.
problem opening a text document - unicode error
i have probably rather simple question. however, i am just starting to use python and it just drives me crazy. i am following the instructions of a book and would like to open a simple text file. the code i am using: import sys try: d = open("p0901aus.txt" , "W") except: print("Unsucessfull") sys.exit(0) i am either getting the news, that i was unsucessfull in opening the document or pop up appears saying: (unicode eror) 'unicodeescape' codec can't decode bytes in position 2-4: truncated \UXXXXXXXX escape i have no clue what the problem is. i tried to save the document in different codes, tried different path...always the same problem does anybody know any help? thank you very much in advance, georg ps: i am using windows vista
[ "\n(unicode eror) 'unicodeescape' codec can't decode bytes in position 2-4: truncated \\UXXXXXXXX escape\n\nThis probably means that the file you are trying to read is not in the encoding that open() expects. Apparently open() expects some Unicode encoding (most likely UTF-8 or UTF-16), but your file is not encoded like that.\nYou should not normally use plain open() for reading text files, as it is impossible to correctly read a text file (unless it's pure ASCII) without specifying an encoding.\nUse codecs instead:\nimport codecs\nfileObj = codecs.open( \"someFile\", \"r\", \"utf-8\" )\nu = fileObj.read() # Returns a Unicode string from the UTF-8 bytes in the file\n\n", "Change that to\n# for Python 2.5+\nimport sys\ntry:\n d = open(\"p0901aus.txt\",\"w\")\nexcept Exception, ex:\n print \"Unsuccessful.\"\n print ex\n sys.exit(0)\n\n# for Python 3\nimport sys\nimport codecs\ntry:\n d = codecs.open(\"p0901aus.txt\",\"w\",\"utf-8\")\nexcept Exception as ex:\n print(\"Unsuccessful.\")\n print(ex)\n sys.exit(0)\n\nThe W is case-sensitive. I do not want to hit you with all the Python syntax at once, but it will be useful for you to know how to display what exception was raised, and this is one way to do it.\nAlso, you are opening the file for writing, not reading. Is that what you wanted?\nIf there is already a document named p0901aus.txt, and you want to read it, do this:\n#for Python 2.5+\nimport sys\ntry:\n d = open(\"p0901aus.txt\",\"r\")\n print \"Awesome, I opened p0901aus.txt. Here is what I found there:\"\n for l in d:\n print l\nexcept Exception, ex:\n print \"Unsuccessful.\"\n print ex\n sys.exit(0)\n\n#for Python 3+\nimport sys\nimport codecs\ntry:\n d = codecs.open(\"p0901aus.txt\",\"r\",\"utf-8\")\n print \"Awesome, I opened p0901aus.txt. Here is what I found there:\"\n for l in d:\n print(l)\nexcept Exception, ex:\n print(\"Unsuccessful.\")\n print(ex)\n sys.exit(0)\n\nYou can of course use the codecs in Python 2.5 also, and your code will be higher quality (\"correct\") if you do. Python 3 appears to treat the Byte Order Mark as something between a curiosity and line noise which is a bummer.\n", "import csv\n\ndata = csv.reader(open('c:\\x\\list.csv' ))\n\nfor row in data:\n\n print(row)\n\nprint('ready')\n\nBrings up \"(unicode error)'unicodeescape' codec can't decode bytes in position 2-4: truncated \\xXX escape\"\nTry c:\\\\x\\\\list.csv instead of c:\\x\\list.csv\nThis is Python 3 code.\n" ]
[ 5, 2, 2 ]
[]
[]
[ "python", "unicode" ]
stackoverflow_0000778096_python_unicode.txt
Q: Converting date/time in YYYYMMDD/HHMMSS format to Python datetime I have a date in YYYYMMDD format and a time in HHMMSS format as strings in the 4th and 5th elements in a list. I.E.: data[4] = '20100304' data[5] = '082835' I am creating an instance of datetime (in a field named generates) like this: generatedtime = datetime.datetime(int(data[4][:4]),int(data[4][4:6]),int(data[4][6:]),int(data[5][:2]),int(data[5][2:4]),int(data[5][4:6])) Given that the input format cannot change, is there a cleaner way I should be creating my instance of the datetime object? A: No need to import time; datetime.datetime.strptime can do it by itself. import datetime dt=datetime.datetime.strptime(data[4]+data[5],'%Y%m%d%H%M%S') print(dt) # 2010-03-04 08:28:35 For information on the format codes (e.g. %Y%m%d%H%M%S) available, see the docs for strftime. A: You might take a look at time.strptime. import time time.strptime('20100304 082835', '%Y%m%d %H%M%S') The above assumes a 24-hour clock (%H). Use %I instead if using a 12-hour clock. For a complete list of available format directives, check out the docs for time.strftime A: You could clean up your existing code a bit with a generator (equivalent to a map): generatedtime = datetime.datetime( *(int(x) for x in (data[4][:4], data[4][4:6], data[4][6:], data[5][:2], data[5][2:4],data[5][4:6]) ) ) or even, if you're crazy like a fox, you could make the datetime statement even cleaner (at the expense of adding a ridiculous line): slices = ( (4, slice(4)), (4, slice(4,6) ), (4, slice(6,None)), (5, slice(2) ), (5, slice(2,4) ), (5, slice(4,6)) ) generatedtime = datetime.datetime( *(int(data[i][s]) for (i,s) in slices) )
Converting date/time in YYYYMMDD/HHMMSS format to Python datetime
I have a date in YYYYMMDD format and a time in HHMMSS format as strings in the 4th and 5th elements in a list. I.E.: data[4] = '20100304' data[5] = '082835' I am creating an instance of datetime (in a field named generates) like this: generatedtime = datetime.datetime(int(data[4][:4]),int(data[4][4:6]),int(data[4][6:]),int(data[5][:2]),int(data[5][2:4]),int(data[5][4:6])) Given that the input format cannot change, is there a cleaner way I should be creating my instance of the datetime object?
[ "No need to import time; datetime.datetime.strptime can do it by itself.\nimport datetime\ndt=datetime.datetime.strptime(data[4]+data[5],'%Y%m%d%H%M%S')\nprint(dt)\n# 2010-03-04 08:28:35\n\nFor information on the format codes (e.g. %Y%m%d%H%M%S) available, see the docs for strftime.\n", "You might take a look at time.strptime.\nimport time\ntime.strptime('20100304 082835', '%Y%m%d %H%M%S')\n\nThe above assumes a 24-hour clock (%H). Use %I instead if using a 12-hour clock.\nFor a complete list of available format directives, check out the docs for time.strftime\n", "You could clean up your existing code a bit with a generator (equivalent to a map):\ngeneratedtime = datetime.datetime( *(int(x) for x in\n (data[4][:4], data[4][4:6], data[4][6:], data[5][:2], data[5][2:4],data[5][4:6])\n ) )\n\nor even, if you're crazy like a fox, you could make the datetime statement even cleaner (at the expense of adding a ridiculous line):\nslices = ( (4, slice(4)), (4, slice(4,6) ), (4, slice(6,None)), (5, slice(2) ), (5, slice(2,4) ), (5, slice(4,6)) )\ngeneratedtime = datetime.datetime( *(int(data[i][s]) for (i,s) in slices) )\n\n" ]
[ 55, 8, 0 ]
[]
[]
[ "datetime", "python" ]
stackoverflow_0002380013_datetime_python.txt
Q: Determine current Mac Safari web page using Python Is there a way to determine programmatically, using Python, which web page is currently active in Safari? A: An Applescript example is here, and the relevant part is: tell application "Safari" set url_list to URL of every document end tell Python/AppleScript translation is covered here. E.g., install appscript as described here: sudo easy_install appscript and then, as shown here, you can do e.g.: >>> import appscript >>> print appscript.app("Safari").windows.first.current_tab.URL() http://wiki.python.org/moin/MacPython/Safari
Determine current Mac Safari web page using Python
Is there a way to determine programmatically, using Python, which web page is currently active in Safari?
[ "An Applescript example is here, and the relevant part is:\ntell application \"Safari\"\n set url_list to URL of every document\nend tell\n\nPython/AppleScript translation is covered here. E.g., install appscript as described here:\nsudo easy_install appscript\n\nand then, as shown here, you can do e.g.:\n>>> import appscript\n>>> print appscript.app(\"Safari\").windows.first.current_tab.URL()\nhttp://wiki.python.org/moin/MacPython/Safari\n\n" ]
[ 6 ]
[]
[]
[ "macos", "python", "safari" ]
stackoverflow_0002380031_macos_python_safari.txt
Q: Django/App Engine/Python 2.5: default __new__ takes no parameters New to app engine and django. I think this is an issue with my django install, which is 1.1.1, but I've also read that I can just use the django packaged with the app engine SDK. Any help on why I'm getting this error when I test locally would be greatly appreciated. The callback: Variable Value callback <class 'ourlat.main.views.SettingsPage'> callback_args () callback_kwargs {} e TypeError('default __new__ takes no parameters',) exc_info (<type 'exceptions.TypeError'>, TypeError('default __new__ takes no parameters',), <traceback object at 0x02201B48>) exceptions <module 'django.core.exceptions' from 'C:\Documents and Settings\Jeremy Gordon\eclipse-workspace\ourlat\django\core\exceptions.pyc'> middleware_method <bound method CommonMiddleware.process_request of <django.middleware.common.CommonMiddleware object at 0x021F5170>> receivers [(<function _rollback_on_exception at 0x02063730>, None)] request <WSGIRequest GET:<QueryDict: {}>, POST:<QueryDict: {}>, COOKIES:{}, META:{'APPLICATION_ID': 'ourlat', 'AUTH_DOMAIN': 'gmail.com', 'CONTENT_LENGTH': '', 'CONTENT_TYPE': 'application/x-www-form-urlencoded', 'CURRENT_VERSION_ID': '1.1', 'GATEWAY_INTERFACE': 'CGI/1.1', 'HTTP_ACCEPT': 'application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5', 'HTTP_ACCEPT_CHARSET': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3', 'HTTP_ACCEPT_LANGUAGE': 'en-US,en;q=0.8', 'HTTP_CACHE_CONTROL': 'max-age=0', 'HTTP_CONNECTION': 'keep-alive', 'HTTP_HOST': 'localhost:8080', 'HTTP_USER_AGENT': 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/533.1 (KHTML, like Gecko) Chrome/5.0.335.1 Safari/533.1', 'PATH_INFO': u'/', 'PATH_TRANSLATED': 'C:\\Documents and Settings\\Jeremy Gordon\\eclipse-workspace\\ourlat\\main.py', 'QUERY_STRING': '', 'REMOTE_ADDR': '127.0.0.1', 'REQUEST_METHOD': 'GET', 'SCRIPT_NAME': u'', 'SERVER_NAME': 'localhost', 'SERVER_PORT': '8080', 'SERVER_PROTOCOL': 'HTTP/1.0', 'SERVER_SOFTWARE': 'Development/1.0', 'TZ': 'UTC', 'USER_EMAIL': '', 'USER_ID': '', 'USER_ORGANIZATION': '', 'wsgi.errors': <open file '<stderr>', mode 'w' at 0x00B1F0B0>, 'wsgi.input': <cStringIO.StringI object at 0x022A0260>, 'wsgi.multiprocess': False, 'wsgi.multithread': False, 'wsgi.run_once': True, 'wsgi.url_scheme': 'http', 'wsgi.version': (1, 0)}> resolver <RegexURLResolver urls (None:None) ^/> response None self <django.core.handlers.wsgi.WSGIHandler object at 0x021F5790> settings <django.conf.LazySettings object at 0x01E997B0> urlconf 'urls' urlresolvers <module 'django.core.urlresolvers' from 'C:\Documents and Settings\Jeremy Gordon\eclipse-workspace\ourlat\django\core\urlresolvers.pyc'> The error: TypeError at / default __new__ takes no parameters Request Method: GET Request URL: http://localhost:8080/ Exception Type: TypeError Exception Value: default __new__ takes no parameters Exception Location: C:\Documents and Settings\Jeremy Gordon\eclipse-workspace\ourlat\django\core\handlers\base.py in get_response, line 92 Python Executable: C:\Python25\python.exe Python Version: 2.5.0 Python Path: ['C:\\Documents and Settings\\Jeremy Gordon\\eclipse-workspace\\ourlat', 'C:\\Program Files\\Google\\google_appengine', 'C:\\Program Files\\Google\\google_appengine\\lib\\antlr3', 'C:\\Program Files\\Google\\google_appengine\\lib\\django', 'C:\\Program Files\\Google\\google_appengine\\lib\\ipaddr', 'C:\\Program Files\\Google\\google_appengine\\lib\\webob', 'C:\\Program Files\\Google\\google_appengine\\lib\\yaml\\lib', 'C:\\Program Files\\Google\\google_appengine', 'C:\\Python25\\lib\\site-packages\\beautifulsoup-3.1.0.1-py2.5.egg', 'C:\\Python25\\lib\\site-packages\\django-1.1.1-py2.5.egg', 'C:\\Documents and Settings\\Jeremy Gordon\\eclipse-workspace\\ourlat\\ourlat', 'C:\\Program Files\\Google\\google_appengine', 'C:\\Program Files\\Google\\google_appengine\\lib\\webob', 'C:\\Program Files\\Google\\google_appengine\\lib\\yaml', 'C:\\Program Files\\Google\\google_appengine\\lib', 'C:\\Program Files\\Google\\google_appengine\\lib\\simplejson-2.0.9', 'C:\\Program Files\\Google\\google_appengine\\lib\\geopy', 'C:\\Program Files\\Google\\google_appengine\\lib\\BeautifulSoup-3.0.8', 'C:\\Documents and Settings\\Jeremy Gordon\\eclipse-workspace\\ourlat\\django', 'C:\\Python25', 'C:\\Python25\\DLLs', 'C:\\Python25\\lib', 'C:\\Python25\\lib\\lib-tk', 'C:\\Python25\\lib\\plat-win', 'C:\\Python25\\lib\\site-packages', 'C:\\Python25\\lib\\site-packages\\setuptools-0.6c7-py2.5.egg', 'C:\\Python25\\lib\\site-packages\\simplejson-2.0.9-py2.5.egg', 'C:\\Python25\\Lib\\site-packages\\geopy-0.93dev_r0-py2.5.egg', 'C:\\WINDOWS\\system32\\python25.zip'] Server time: Sat, 6 Mar 2010 01:18:27 +0000 SettingsPage source class SettingsPage(webapp.RequestHandler): def get(self): if users.get_current_user(): url = users.create_logout_url(self.request.uri) url_linktext = 'Logout' account_query = OLAccount.all().filter('owner =',users.get_current_user()) if account_query.count() < 1: thisuser = OLAccount(owner = users.get_current_user()) thisuser.put() else: thisuser = account_query.fetch(1)[0] tracks = [db.get(key) for key in thisuser.track_keys] template_values = { 'url': url, 'url_linktext': url_linktext, 'thisuser': thisuser, 'tracks': tracks } path = os.path.join(os.path.dirname(__file__), 'html/settings.html') self.response.out.write(template.render(path, template_values)) else: self.redirect(users.create_login_url(self.request.uri)) A: You appear to have subclassed (at least once) a Django's view class with an __init__ (but not a __new__) with a non-standard signature. If you click on the triangle towards the beginning of this message (in your own environment -- the click doesn't work on this copy/pasted msg in SO, of course;-) you should see the local variables, including for example the callback which is the view you're trying to call (comes from your URL resolver, see the source at line 68) -- this information will help further debugging. Edit: looks like the problem is that you're mixing and matching Django's urlresolvers (which expect Django-id callables, taking the request as the argument) with a subclass of Google's webapp.RequestHandler (which doesn't take arguments in __init__): don't do that. Use app.yaml to pick what .py script handles requests to each group of paths in your app, and in each .py script use only Django or only webapp -- no mixing. BTW, the Django that comes with the app engine SDK is 0.96, like the default one on google's servers; but on google's servers you can easily switch to more modern versions of django with use_library, while on your SDK you can't -- that is, not without installing your own django locally &c. See the page I just pointed you to and links therefrom.
Django/App Engine/Python 2.5: default __new__ takes no parameters
New to app engine and django. I think this is an issue with my django install, which is 1.1.1, but I've also read that I can just use the django packaged with the app engine SDK. Any help on why I'm getting this error when I test locally would be greatly appreciated. The callback: Variable Value callback <class 'ourlat.main.views.SettingsPage'> callback_args () callback_kwargs {} e TypeError('default __new__ takes no parameters',) exc_info (<type 'exceptions.TypeError'>, TypeError('default __new__ takes no parameters',), <traceback object at 0x02201B48>) exceptions <module 'django.core.exceptions' from 'C:\Documents and Settings\Jeremy Gordon\eclipse-workspace\ourlat\django\core\exceptions.pyc'> middleware_method <bound method CommonMiddleware.process_request of <django.middleware.common.CommonMiddleware object at 0x021F5170>> receivers [(<function _rollback_on_exception at 0x02063730>, None)] request <WSGIRequest GET:<QueryDict: {}>, POST:<QueryDict: {}>, COOKIES:{}, META:{'APPLICATION_ID': 'ourlat', 'AUTH_DOMAIN': 'gmail.com', 'CONTENT_LENGTH': '', 'CONTENT_TYPE': 'application/x-www-form-urlencoded', 'CURRENT_VERSION_ID': '1.1', 'GATEWAY_INTERFACE': 'CGI/1.1', 'HTTP_ACCEPT': 'application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5', 'HTTP_ACCEPT_CHARSET': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3', 'HTTP_ACCEPT_LANGUAGE': 'en-US,en;q=0.8', 'HTTP_CACHE_CONTROL': 'max-age=0', 'HTTP_CONNECTION': 'keep-alive', 'HTTP_HOST': 'localhost:8080', 'HTTP_USER_AGENT': 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/533.1 (KHTML, like Gecko) Chrome/5.0.335.1 Safari/533.1', 'PATH_INFO': u'/', 'PATH_TRANSLATED': 'C:\\Documents and Settings\\Jeremy Gordon\\eclipse-workspace\\ourlat\\main.py', 'QUERY_STRING': '', 'REMOTE_ADDR': '127.0.0.1', 'REQUEST_METHOD': 'GET', 'SCRIPT_NAME': u'', 'SERVER_NAME': 'localhost', 'SERVER_PORT': '8080', 'SERVER_PROTOCOL': 'HTTP/1.0', 'SERVER_SOFTWARE': 'Development/1.0', 'TZ': 'UTC', 'USER_EMAIL': '', 'USER_ID': '', 'USER_ORGANIZATION': '', 'wsgi.errors': <open file '<stderr>', mode 'w' at 0x00B1F0B0>, 'wsgi.input': <cStringIO.StringI object at 0x022A0260>, 'wsgi.multiprocess': False, 'wsgi.multithread': False, 'wsgi.run_once': True, 'wsgi.url_scheme': 'http', 'wsgi.version': (1, 0)}> resolver <RegexURLResolver urls (None:None) ^/> response None self <django.core.handlers.wsgi.WSGIHandler object at 0x021F5790> settings <django.conf.LazySettings object at 0x01E997B0> urlconf 'urls' urlresolvers <module 'django.core.urlresolvers' from 'C:\Documents and Settings\Jeremy Gordon\eclipse-workspace\ourlat\django\core\urlresolvers.pyc'> The error: TypeError at / default __new__ takes no parameters Request Method: GET Request URL: http://localhost:8080/ Exception Type: TypeError Exception Value: default __new__ takes no parameters Exception Location: C:\Documents and Settings\Jeremy Gordon\eclipse-workspace\ourlat\django\core\handlers\base.py in get_response, line 92 Python Executable: C:\Python25\python.exe Python Version: 2.5.0 Python Path: ['C:\\Documents and Settings\\Jeremy Gordon\\eclipse-workspace\\ourlat', 'C:\\Program Files\\Google\\google_appengine', 'C:\\Program Files\\Google\\google_appengine\\lib\\antlr3', 'C:\\Program Files\\Google\\google_appengine\\lib\\django', 'C:\\Program Files\\Google\\google_appengine\\lib\\ipaddr', 'C:\\Program Files\\Google\\google_appengine\\lib\\webob', 'C:\\Program Files\\Google\\google_appengine\\lib\\yaml\\lib', 'C:\\Program Files\\Google\\google_appengine', 'C:\\Python25\\lib\\site-packages\\beautifulsoup-3.1.0.1-py2.5.egg', 'C:\\Python25\\lib\\site-packages\\django-1.1.1-py2.5.egg', 'C:\\Documents and Settings\\Jeremy Gordon\\eclipse-workspace\\ourlat\\ourlat', 'C:\\Program Files\\Google\\google_appengine', 'C:\\Program Files\\Google\\google_appengine\\lib\\webob', 'C:\\Program Files\\Google\\google_appengine\\lib\\yaml', 'C:\\Program Files\\Google\\google_appengine\\lib', 'C:\\Program Files\\Google\\google_appengine\\lib\\simplejson-2.0.9', 'C:\\Program Files\\Google\\google_appengine\\lib\\geopy', 'C:\\Program Files\\Google\\google_appengine\\lib\\BeautifulSoup-3.0.8', 'C:\\Documents and Settings\\Jeremy Gordon\\eclipse-workspace\\ourlat\\django', 'C:\\Python25', 'C:\\Python25\\DLLs', 'C:\\Python25\\lib', 'C:\\Python25\\lib\\lib-tk', 'C:\\Python25\\lib\\plat-win', 'C:\\Python25\\lib\\site-packages', 'C:\\Python25\\lib\\site-packages\\setuptools-0.6c7-py2.5.egg', 'C:\\Python25\\lib\\site-packages\\simplejson-2.0.9-py2.5.egg', 'C:\\Python25\\Lib\\site-packages\\geopy-0.93dev_r0-py2.5.egg', 'C:\\WINDOWS\\system32\\python25.zip'] Server time: Sat, 6 Mar 2010 01:18:27 +0000 SettingsPage source class SettingsPage(webapp.RequestHandler): def get(self): if users.get_current_user(): url = users.create_logout_url(self.request.uri) url_linktext = 'Logout' account_query = OLAccount.all().filter('owner =',users.get_current_user()) if account_query.count() < 1: thisuser = OLAccount(owner = users.get_current_user()) thisuser.put() else: thisuser = account_query.fetch(1)[0] tracks = [db.get(key) for key in thisuser.track_keys] template_values = { 'url': url, 'url_linktext': url_linktext, 'thisuser': thisuser, 'tracks': tracks } path = os.path.join(os.path.dirname(__file__), 'html/settings.html') self.response.out.write(template.render(path, template_values)) else: self.redirect(users.create_login_url(self.request.uri))
[ "You appear to have subclassed (at least once) a Django's view class with an __init__ (but not a __new__) with a non-standard signature. If you click on the triangle towards the beginning of this message (in your own environment -- the click doesn't work on this copy/pasted msg in SO, of course;-) you should see the local variables, including for example the callback which is the view you're trying to call (comes from your URL resolver, see the source at line 68) -- this information will help further debugging.\nEdit: looks like the problem is that you're mixing and matching Django's urlresolvers (which expect Django-id callables, taking the request as the argument) with a subclass of Google's webapp.RequestHandler (which doesn't take arguments in __init__): don't do that. Use app.yaml to pick what .py script handles requests to each group of paths in your app, and in each .py script use only Django or only webapp -- no mixing.\nBTW, the Django that comes with the app engine SDK is 0.96, like the default one on google's servers; but on google's servers you can easily switch to more modern versions of django with use_library, while on your SDK you can't -- that is, not without installing your own django locally &c. See the page I just pointed you to and links therefrom.\n" ]
[ 2 ]
[]
[]
[ "django", "google_app_engine", "python" ]
stackoverflow_0002377627_django_google_app_engine_python.txt
Q: How to write back to a certain cell in google doc spreadsheet using python So the problem is, i get some information from first column of the row (for example A2 ) from the spreadsheet, then i will do some checking with that information, after that i want to write back to the next column in the row the result, how do i do that? Is there a certain function to allow me to indicate the column behind, in front, above, below? So i can write information in that cell. A: Sure, the docs for Google Spreadsheet API in Python are here. To create or update a cell, see here; to get the "cell range feed" you need, see here -- basically to say "below" for example, get the cell feed for the specific column you want and the two rows (the one you're reading and the one you're writing), read one of the cells (the top one in the range), update the other one (the bottom one in the range). For details of the protocol underlying the Python API, see here (that's where you get info on what attributes &c exist for the various objects involved, for example).
How to write back to a certain cell in google doc spreadsheet using python
So the problem is, i get some information from first column of the row (for example A2 ) from the spreadsheet, then i will do some checking with that information, after that i want to write back to the next column in the row the result, how do i do that? Is there a certain function to allow me to indicate the column behind, in front, above, below? So i can write information in that cell.
[ "Sure, the docs for Google Spreadsheet API in Python are here. To create or update a cell, see here; to get the \"cell range feed\" you need, see here -- basically to say \"below\" for example, get the cell feed for the specific column you want and the two rows (the one you're reading and the one you're writing), read one of the cells (the top one in the range), update the other one (the bottom one in the range).\nFor details of the protocol underlying the Python API, see here (that's where you get info on what attributes &c exist for the various objects involved, for example).\n" ]
[ 1 ]
[]
[]
[ "google_sheets_api", "python" ]
stackoverflow_0002378104_google_sheets_api_python.txt
Q: Python AST processing I have a Python AST [as returned by ast.parse()]. I know this is an AST of a class method. How do I find all calls to other methods of the same class? Basically, I want to collect something like: ['foo', 'bar'] for a code snippet like: def baz(self): # this is a class method '''baz docstring''' self.foo() + self.bar() I need a function that will accept an AST and will return the list of other methods [method names as strings] of the class that are being invoked inside a method of the same class. A: The general approach is to subclass ast.NodeVisitor: >>> class VisitCalls(ast.NodeVisitor): ... def visit_Call(self, what): ... if what.func.value.id == 'self': ... print what.func.attr ... >>> f='''def x(self): ... return self.bar() + self.baz() ... ''' >>> xx = ast.parse(f) >>> VisitCalls().visit(xx) bar baz However, this will only catch "immediate" calls to self.something. In the general case you could have e.g. somelist.append(self.blah) and then much later in the code somelist[i + j](): the problem of determining whether the latter is a call to self.blah or to some other callable that has nothing to do with methods of the current instance is Turing-complete (CS jargon for "completely insoluble in the general case", much like a mathematician might say "NP-hard";-). But if all you need is to solve the simple "immediate call" case, you're good to go;-).
Python AST processing
I have a Python AST [as returned by ast.parse()]. I know this is an AST of a class method. How do I find all calls to other methods of the same class? Basically, I want to collect something like: ['foo', 'bar'] for a code snippet like: def baz(self): # this is a class method '''baz docstring''' self.foo() + self.bar() I need a function that will accept an AST and will return the list of other methods [method names as strings] of the class that are being invoked inside a method of the same class.
[ "The general approach is to subclass ast.NodeVisitor:\n>>> class VisitCalls(ast.NodeVisitor):\n... def visit_Call(self, what):\n... if what.func.value.id == 'self':\n... print what.func.attr\n... \n>>> f='''def x(self):\n... return self.bar() + self.baz()\n... '''\n>>> xx = ast.parse(f)\n>>> VisitCalls().visit(xx)\nbar\nbaz\n\nHowever, this will only catch \"immediate\" calls to self.something. In the general case you could have e.g. somelist.append(self.blah) and then much later in the code somelist[i + j](): the problem of determining whether the latter is a call to self.blah or to some other callable that has nothing to do with methods of the current instance is Turing-complete (CS jargon for \"completely insoluble in the general case\", much like a mathematician might say \"NP-hard\";-).\nBut if all you need is to solve the simple \"immediate call\" case, you're good to go;-).\n" ]
[ 18 ]
[]
[]
[ "abstract_syntax_tree", "python" ]
stackoverflow_0002379355_abstract_syntax_tree_python.txt
Q: urllib ignore authentication requests I'm having little trouble creating a script working with URLs. I'm using urllib.urlopen() to get content of desired URL. But some of these URLs requires authentication. And urlopen prompts me to type in my username and then password. What I need is to ignore every URL that'll require authentication, just easily skip it and continue, is there a way to do this? I was wondering about catching HTTPError exception, but in fact, exception is handled by urlopen() method, so it's not working. Thanks for every reply. A: You are right about the urllib2.HTTPError exception: exception urllib2.HTTPError Though being an exception (a subclass of URLError), an HTTPError can also function as a non-exceptional file-like return value (the same thing that urlopen() returns). This is useful when handling exotic HTTP errors, such as requests for authentication. code An HTTP status code as defined in RFC 2616. This numeric value corresponds to a value found in the dictionary of codes as found in BaseHTTPServer.BaseHTTPRequestHandler.responses. The code attribute of the exception can be used to verify that authentication is required - code 401. >>> try: ... conn = urllib2.urlopen('http://www.example.com/admin') ... # read conn and process data ... except urllib2.HTTPError, x: ... print 'Ignoring', x.code ... Ignoring 401 >>>
urllib ignore authentication requests
I'm having little trouble creating a script working with URLs. I'm using urllib.urlopen() to get content of desired URL. But some of these URLs requires authentication. And urlopen prompts me to type in my username and then password. What I need is to ignore every URL that'll require authentication, just easily skip it and continue, is there a way to do this? I was wondering about catching HTTPError exception, but in fact, exception is handled by urlopen() method, so it's not working. Thanks for every reply.
[ "You are right about the urllib2.HTTPError exception:\n\nexception urllib2.HTTPError\nThough being an exception (a subclass of URLError), an HTTPError can also function as a non-exceptional file-like return value (the same thing that urlopen() returns). This is useful when handling exotic HTTP errors, such as requests for authentication.\ncode\nAn HTTP status code as defined in RFC 2616. This numeric value corresponds to a value found in the dictionary of codes as found in BaseHTTPServer.BaseHTTPRequestHandler.responses.\n\nThe code attribute of the exception can be used to verify that authentication is required - code 401.\n>>> try: \n... conn = urllib2.urlopen('http://www.example.com/admin')\n... # read conn and process data\n... except urllib2.HTTPError, x:\n... print 'Ignoring', x.code\n... \nIgnoring 401\n>>> \n\n" ]
[ 1 ]
[]
[]
[ "python", "urllib", "urlopen" ]
stackoverflow_0002380623_python_urllib_urlopen.txt
Q: Error installing scrapy on Mac Os X 10.6 Trying to install Scrapy on Mac OSX 10.6 using this guide: When running these commands from Terminal: cd libxml2-2.7.3/python sudo make install I get the following error: Making install in . make[1]: *** No rule to make target `../libxslt/libxslt.la', needed by `libxsltmod.la'. Stop. make: *** [install-recursive] Error 1 Following the first steps in the Guide, which involved building and installing the libxml2 and libxslt packages seemed to be successful... A: The simplest approach is to use MacPorts to install python and the libraries you need. A: Credit to @Ned Deily These steps seem to work if you want to run Scrapy 0.8 on OS X 10.6. It uses Macports install of Python 2.6 rather than the one bundled with the OS. Steps assume Macports is not installed yet. Get latest MacPorts installer from here and install: http://www.macports.org/install.php sudo port install py26-libxml2 py26-twisted py26-openssl py26-simplejson py26-setuptools python_select sudo /opt/local/bin/easy_install-2.6 scrapy Change your ~.profile to: export PATH=/opt/local/Library/Frameworks/Python.framework/Versions/2.6/bin:/opt/local/bin:/opt/local/sbin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:$PATH
Error installing scrapy on Mac Os X 10.6
Trying to install Scrapy on Mac OSX 10.6 using this guide: When running these commands from Terminal: cd libxml2-2.7.3/python sudo make install I get the following error: Making install in . make[1]: *** No rule to make target `../libxslt/libxslt.la', needed by `libxsltmod.la'. Stop. make: *** [install-recursive] Error 1 Following the first steps in the Guide, which involved building and installing the libxml2 and libxslt packages seemed to be successful...
[ "The simplest approach is to use MacPorts to install python and the libraries you need. \n", "Credit to @Ned Deily\nThese steps seem to work if you want to run Scrapy 0.8 on OS X 10.6. It uses Macports install of Python 2.6 rather than the one bundled with the OS. Steps assume Macports is not installed yet.\nGet latest MacPorts installer from here and install:\nhttp://www.macports.org/install.php\nsudo port install py26-libxml2 py26-twisted py26-openssl py26-simplejson py26-setuptools python_select\n\nsudo /opt/local/bin/easy_install-2.6 scrapy\n\nChange your ~.profile to:\nexport PATH=/opt/local/Library/Frameworks/Python.framework/Versions/2.6/bin:/opt/local/bin:/opt/local/sbin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:$PATH\n\n" ]
[ 2, 1 ]
[]
[]
[ "libxml2", "macos", "python", "scrapy" ]
stackoverflow_0002372758_libxml2_macos_python_scrapy.txt
Q: C++ iostreams and python Is it possible to interoperate with a C++ iostream and python? I'm using boost-python and want to wrap a function that has istream and ostream as arguments. A: Is http://cci.lbl.gov/cctbx_sources/boost_adaptbx/python_streambuf.h what you are looking for? It comes from the Phenix project. (license information at http://cci.lbl.gov/cctbx_sources/boost_adaptbx/LICENSE_2_0.txt)
C++ iostreams and python
Is it possible to interoperate with a C++ iostream and python? I'm using boost-python and want to wrap a function that has istream and ostream as arguments.
[ "Is http://cci.lbl.gov/cctbx_sources/boost_adaptbx/python_streambuf.h what you are looking for? It comes from the Phenix project. \n(license information at http://cci.lbl.gov/cctbx_sources/boost_adaptbx/LICENSE_2_0.txt)\n" ]
[ 3 ]
[]
[]
[ "boost_python", "iostream", "python" ]
stackoverflow_0002378005_boost_python_iostream_python.txt
Q: Loading a document on OpenOffice using an external Python program I'm trying to create a python program (using pyUNO ) to make some changes on a OpenOffice calc sheet. I've launched previously OpenOffice on "accept" mode to be able to connect from an external program. Apparently, should be as easy as: import uno # get the uno component context from the PyUNO runtime localContext = uno.getComponentContext() # create the UnoUrlResolver resolver = localContext.ServiceManager.createInstanceWithContext( "com.sun.star.bridge.UnoUrlResolver", localContext) # connect to the running office ctx = resolver.resolve("uno:socket,host=localhost,port=2002;" "urp;StarOffice.ComponentContext") smgr = ctx.ServiceManager # get the central desktop object DESKTOP =smgr.createInstanceWithContext("com.sun.star.frame.Desktop", ctx) #The calling it's not exactly this way, just to simplify the code DESKTOP.loadComponentFromURL('file.ods') But I get an AttributeError when I try to access loadComponentFromURL. If I make a dir(DESKTOP), I've see only the following attributes/methods: ['ActiveFrame', 'DispatchRecorderSupplier', 'ImplementationId', 'ImplementationName', 'IsPlugged', 'PropertySetInfo', 'SupportedServiceNames', 'SuspendQuickstartVeto', 'Title', 'Types', 'addEventListener', 'addPropertyChangeListener', 'addVetoableChangeListener', 'dispose', 'disposing', 'getImplementationId', 'getImplementationName', 'getPropertySetInfo', 'getPropertyValue', 'getSupportedServiceNames', 'getTypes', 'handle', 'queryInterface', 'removeEventListener', 'removePropertyChangeListener', 'removeVetoableChangeListener', 'setPropertyValue', 'supportsService'] I've read that there are where a bug doing the same, but on OpenOffice 3.0 (I'm using OpenOffice 3.1 over Red Hat5.3). I've tried to use the workaround stated here, but they don't seems to be working. Any ideas? A: It has been a long time since I did anything with PyUNO, but looking at the code that worked last time I ran it back in '06, I did my load document like this: def urlify(path): return uno.systemPathToFileUrl(os.path.realpath(path)) desktop.loadComponentFromURL( urlify(tempfilename), "_blank", 0, ()) Your example is a simplified version, and I'm not sure if you've removed the extra arguments intentionally or not intentionally. If loadComponentFromURL isn't there, then the API has changed or there's something else wrong, I've read through your code and it looks like you're doing all the same things I have. I don't believe that the dir() of the methods on the desktop object will be useful, as I think there's a __getattr__ method being used to proxy through the requests, and all the methods you've printed out are utility methods used for the stand-in object for the com.sun.star.frame.Desktop. I think perhaps the failure could be that there's no method named loadComponentFromURL that has exactly 1 argument. Perhaps giving the 4 argument version will result in the method being found and used. This could simply be an impedance mismatch between Python and Java, where Java has call-signature method overloading. A: This looks like issue 90701: http://www.openoffice.org/issues/show_bug.cgi?id=90701 See also http://piiis.blogspot.com/2008/10/pyuno-broken-in-ooo-30-with-system.html and http://udk.openoffice.org/python/python-bridge.html
Loading a document on OpenOffice using an external Python program
I'm trying to create a python program (using pyUNO ) to make some changes on a OpenOffice calc sheet. I've launched previously OpenOffice on "accept" mode to be able to connect from an external program. Apparently, should be as easy as: import uno # get the uno component context from the PyUNO runtime localContext = uno.getComponentContext() # create the UnoUrlResolver resolver = localContext.ServiceManager.createInstanceWithContext( "com.sun.star.bridge.UnoUrlResolver", localContext) # connect to the running office ctx = resolver.resolve("uno:socket,host=localhost,port=2002;" "urp;StarOffice.ComponentContext") smgr = ctx.ServiceManager # get the central desktop object DESKTOP =smgr.createInstanceWithContext("com.sun.star.frame.Desktop", ctx) #The calling it's not exactly this way, just to simplify the code DESKTOP.loadComponentFromURL('file.ods') But I get an AttributeError when I try to access loadComponentFromURL. If I make a dir(DESKTOP), I've see only the following attributes/methods: ['ActiveFrame', 'DispatchRecorderSupplier', 'ImplementationId', 'ImplementationName', 'IsPlugged', 'PropertySetInfo', 'SupportedServiceNames', 'SuspendQuickstartVeto', 'Title', 'Types', 'addEventListener', 'addPropertyChangeListener', 'addVetoableChangeListener', 'dispose', 'disposing', 'getImplementationId', 'getImplementationName', 'getPropertySetInfo', 'getPropertyValue', 'getSupportedServiceNames', 'getTypes', 'handle', 'queryInterface', 'removeEventListener', 'removePropertyChangeListener', 'removeVetoableChangeListener', 'setPropertyValue', 'supportsService'] I've read that there are where a bug doing the same, but on OpenOffice 3.0 (I'm using OpenOffice 3.1 over Red Hat5.3). I've tried to use the workaround stated here, but they don't seems to be working. Any ideas?
[ "It has been a long time since I did anything with PyUNO, but looking at the code that worked last time I ran it back in '06, I did my load document like this:\ndef urlify(path):\n return uno.systemPathToFileUrl(os.path.realpath(path))\n\ndesktop.loadComponentFromURL(\n urlify(tempfilename), \"_blank\", 0, ())\n\nYour example is a simplified version, and I'm not sure if you've removed the extra arguments intentionally or not intentionally.\nIf loadComponentFromURL isn't there, then the API has changed or there's something else wrong, I've read through your code and it looks like you're doing all the same things I have.\nI don't believe that the dir() of the methods on the desktop object will be useful, as I think there's a __getattr__ method being used to proxy through the requests, and all the methods you've printed out are utility methods used for the stand-in object for the com.sun.star.frame.Desktop.\nI think perhaps the failure could be that there's no method named loadComponentFromURL that has exactly 1 argument. Perhaps giving the 4 argument version will result in the method being found and used. This could simply be an impedance mismatch between Python and Java, where Java has call-signature method overloading.\n", "This looks like issue 90701: http://www.openoffice.org/issues/show_bug.cgi?id=90701\nSee also http://piiis.blogspot.com/2008/10/pyuno-broken-in-ooo-30-with-system.html and http://udk.openoffice.org/python/python-bridge.html\n" ]
[ 4, 3 ]
[]
[]
[ "python", "pyuno" ]
stackoverflow_0002153843_python_pyuno.txt
Q: Turning on DEBUG on a Django production site I'm using the Django ORM in a non-Django application and would like to turn on the DEBUG setting so that I can periodically log my queries. So I have something vaguely like this: from django.db import connection def thread_main_loop(): while keep_going: connection.queries[:] = [] do_something() some_logging_function(connection.queries) I would like to do this on my production server, but the doc warns, "It is also important to remember that when running with DEBUG turned on, Django will remember every SQL query it executes. This is useful when you are debugging, but on a production server, it will rapidly consume memory." Because the connection.queries list is cleared every time through the main loop of each thread, I believe that Django query logging will not cause my application to consume memory. Is this correct? And are there any other reasons not to turn DEBUG on in a production environment if I'm only using the Django ORM? A: In DEBUG mode any error in your application will lead to the detailed Django stacktrace. This is very undesirable in a production environment as it will probably leak sensitive information that attackers can use against your site. Even if your application seems pretty stable, I wouldn't risk it. I would rather employ a middleware that somehow logs queries to a file. Or take statistics of the database directly, e.g (for MySQL). watch -n 1 mysqladmin --user=<user> --password=<password> processlist Edit: If you are only using the Django ORM, then afaik only two things will be different: Queries will be saved with the CursorDebugWrapper If a query results in a database warning, this will raise an exception.
Turning on DEBUG on a Django production site
I'm using the Django ORM in a non-Django application and would like to turn on the DEBUG setting so that I can periodically log my queries. So I have something vaguely like this: from django.db import connection def thread_main_loop(): while keep_going: connection.queries[:] = [] do_something() some_logging_function(connection.queries) I would like to do this on my production server, but the doc warns, "It is also important to remember that when running with DEBUG turned on, Django will remember every SQL query it executes. This is useful when you are debugging, but on a production server, it will rapidly consume memory." Because the connection.queries list is cleared every time through the main loop of each thread, I believe that Django query logging will not cause my application to consume memory. Is this correct? And are there any other reasons not to turn DEBUG on in a production environment if I'm only using the Django ORM?
[ "In DEBUG mode any error in your application will lead to the detailed Django stacktrace. This is very undesirable in a production environment as it will probably leak sensitive information that attackers can use against your site. Even if your application seems pretty stable, I wouldn't risk it.\nI would rather employ a middleware that somehow logs queries to a file. Or take statistics of the database directly, e.g (for MySQL).\nwatch -n 1 mysqladmin --user=<user> --password=<password> processlist\n\nEdit:\nIf you are only using the Django ORM, then afaik only two things will be different:\n\nQueries will be saved with the CursorDebugWrapper\nIf a query results in a database warning, this will raise an exception.\n\n" ]
[ 3 ]
[]
[]
[ "debugging", "django", "python" ]
stackoverflow_0002380726_debugging_django_python.txt
Q: set() runtime in python Just wondering what the run time of lookup for set() is? O(1) or O(n)? if I have x = set() whats the runtime of if "a" in x: print a in set! A: set is implemented using a hash, so the lookup is, on average, close to O(1). The worst case is O(n), where n objects have colliding hashes.
set() runtime in python
Just wondering what the run time of lookup for set() is? O(1) or O(n)? if I have x = set() whats the runtime of if "a" in x: print a in set!
[ "set is implemented using a hash, so the lookup is, on average, close to O(1). The worst case is O(n), where n objects have colliding hashes.\n" ]
[ 12 ]
[]
[]
[ "python" ]
stackoverflow_0002381026_python.txt
Q: Can hotshot be used in multiple threads? I have a long-running multithreaded program, and I'd like to occasionally like to call a function with Profile.runcall and dump the data to a file. The hotshot documentation states: Note: The hotshot profiler does not yet work well with threads. It is useful to use an unthreaded script to run the profiler over the code you’re interested in measuring if at all possible. However, I've test having multiple threads profile a function simultaneously, and I've encountered no problems. In my case, the functions being profiled are all self-contained and do not spawn any additional threads during execution. And I make sure that every Profile object has its own file so that they don't clobber each other. So my guess is that the warning about multiple threads means that I would have problems if the function being profiled spawned additional threads itself. When I profile a test function that does spawn other threads, the spawned threads are not profiled. However, this still doesn't seem to cause any problems, since the function being profiled seems to work just fine. Can someone confirm or refute that hotshot is safe to run in a multithreaded program? I don't want to deploy something that might crash later, even if it seems to pass my initial tests. A: For what it's worth, we have a setting in CubicWeb (which uses multiple threads) to enable hotshot profiling, and so far I've never experienced issues when enabling profiling.
Can hotshot be used in multiple threads?
I have a long-running multithreaded program, and I'd like to occasionally like to call a function with Profile.runcall and dump the data to a file. The hotshot documentation states: Note: The hotshot profiler does not yet work well with threads. It is useful to use an unthreaded script to run the profiler over the code you’re interested in measuring if at all possible. However, I've test having multiple threads profile a function simultaneously, and I've encountered no problems. In my case, the functions being profiled are all self-contained and do not spawn any additional threads during execution. And I make sure that every Profile object has its own file so that they don't clobber each other. So my guess is that the warning about multiple threads means that I would have problems if the function being profiled spawned additional threads itself. When I profile a test function that does spawn other threads, the spawned threads are not profiled. However, this still doesn't seem to cause any problems, since the function being profiled seems to work just fine. Can someone confirm or refute that hotshot is safe to run in a multithreaded program? I don't want to deploy something that might crash later, even if it seems to pass my initial tests.
[ "For what it's worth, we have a setting in CubicWeb (which uses multiple threads) to enable hotshot profiling, and so far I've never experienced issues when enabling profiling. \n" ]
[ 1 ]
[]
[]
[ "multithreading", "profile", "profiler", "profiling", "python" ]
stackoverflow_0002379954_multithreading_profile_profiler_profiling_python.txt
Q: Python's AppKit and ObjectiveC Delegates AppKit allows Python programs on a Mac to use ObjectiveC classes. I am not very familiar with ObjectiveC, but I want to access the NSSound class using AppKit in order to create an audio player. My player should perform some action, such as loading the next item from the playlist, when the current audio finishes playing. There is a method named sound:didFinishPlaying:, which is called at that moment, I suppose. According to the documentation, a delegate has to be set which receives this method call. Can somebody help me translate that to Python/AppKit? How can I implement a delegate in Python and let it receive the didFinishPlaying notification? A: The first step towards successful development of a PyObjC based Cocoa/AppKit application is to learn Objective-C and then learn Cocoa. The second step is to drop Python and just use Objective-C for your application. PyObjC (and MacRuby) are awesome technologies, but success with both requires that you understand the patterns and APIs of the system frameworks. That, in turn, requires a working knowledge of Objective-C, enough to build simple apps. Now, if you were need to integrate some massive Python library -- say, Twisted -- then using Python as the primary language of implementation would be totally appropriate. But you would still need a good foundation of knowledge/comfort with Objective-C and the Cocoa APIs.
Python's AppKit and ObjectiveC Delegates
AppKit allows Python programs on a Mac to use ObjectiveC classes. I am not very familiar with ObjectiveC, but I want to access the NSSound class using AppKit in order to create an audio player. My player should perform some action, such as loading the next item from the playlist, when the current audio finishes playing. There is a method named sound:didFinishPlaying:, which is called at that moment, I suppose. According to the documentation, a delegate has to be set which receives this method call. Can somebody help me translate that to Python/AppKit? How can I implement a delegate in Python and let it receive the didFinishPlaying notification?
[ "The first step towards successful development of a PyObjC based Cocoa/AppKit application is to learn Objective-C and then learn Cocoa.\nThe second step is to drop Python and just use Objective-C for your application.\nPyObjC (and MacRuby) are awesome technologies, but success with both requires that you understand the patterns and APIs of the system frameworks. That, in turn, requires a working knowledge of Objective-C, enough to build simple apps.\nNow, if you were need to integrate some massive Python library -- say, Twisted -- then using Python as the primary language of implementation would be totally appropriate. But you would still need a good foundation of knowledge/comfort with Objective-C and the Cocoa APIs.\n" ]
[ 4 ]
[]
[]
[ "appkit", "macos", "objective_c", "python" ]
stackoverflow_0002379473_appkit_macos_objective_c_python.txt
Q: How does one produce a specific unicode character with Python's C-API? I'm writing a Python extension that runs through a Py_UNICODE array, finds specific (ASCII, if it matters) characters, i.e. '\' or '\n', and does some additional stuff for each one that it finds. Is there a way to write those characters as literals? If not, what is the correct way to obtain Py_UNICODEs for them, keeping in mind that Py_UNICODE's size and internal representation may differ from system to system? A: Use PyUnicode_FromWideChar() or one of the built-in codec decode functions.
How does one produce a specific unicode character with Python's C-API?
I'm writing a Python extension that runs through a Py_UNICODE array, finds specific (ASCII, if it matters) characters, i.e. '\' or '\n', and does some additional stuff for each one that it finds. Is there a way to write those characters as literals? If not, what is the correct way to obtain Py_UNICODEs for them, keeping in mind that Py_UNICODE's size and internal representation may differ from system to system?
[ "Use PyUnicode_FromWideChar() or one of the built-in codec decode functions.\n" ]
[ 1 ]
[]
[]
[ "python", "python_c_api", "unicode" ]
stackoverflow_0002381132_python_python_c_api_unicode.txt
Q: Redirect Python standard input/output to C# forms application I apologize if this is a duplicate question, I searched a bit and couldn't find anything similar - I have a Python library that connects to my C# application via a socket in order to allow simple Python scripting (IronPython isn't an option right now for a couple of reasons). I would like to create a Windows Forms control that would be basically a graphical front-end for the Python interpreter, so that the user could run the interpreter without having to have a separate console window open. I attached a simple demo of what I've tried so far below, but I haven't been able to get it to work. The DataReceived event handlers are never called, and when I try to write to the standard input nothing happens in the interpreter. Does anyone have any feedback about what I'm doing wrong, or if this is even possible? public partial class Form1 : Form { Process _pythonProc; public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { ProcessStartInfo psi = new ProcessStartInfo() { FileName = @"C:\Python26\Python.exe", CreateNoWindow = true, UseShellExecute = false, RedirectStandardInput = true, RedirectStandardOutput = true, RedirectStandardError = true }; _pythonProc = new Process(); _pythonProc.OutputDataReceived += OutputDataReceived; _pythonProc.ErrorDataReceived += ErrorDataReceived; _pythonProc.StartInfo = psi; _pythonProc.Start(); } private void cmdExecute_Click(object sender, EventArgs e) { string cmd = textInput.Text; _pythonProc.StandardInput.WriteLine(cmd); _pythonProc.StandardInput.Flush(); textInput.Text = string.Empty; } private void Form1_FormClosed(object sender, FormClosedEventArgs e) { if (!_pythonProc.HasExited) _pythonProc.Kill(); } private void OutputDataReceived(object sender, DataReceivedEventArgs args) { textOutput.Text += args.Data; } private void ErrorDataReceived(object sender, DataReceivedEventArgs args) { textOutput.Text += args.Data; } } A: In case anyone else stumbles across this, I figured out the problem - by default, the Python interpreter only enters interactive mode if it detects that a TTY device is connected to standard input (which is normally only true if the program is run from the console). In order to redirect the standard IO streams, you have to set UseShellExecute in the ProcessStartInfo to false, which causes the interpreter to think that there is no TTY connected, meaning it immediately exits since it has nothing to do. The solution is to run the Python interpreter with the "-i" command line argument, which forces the interpreter to interactive mode, regardless of whether there is a TTY connected to standard in. This makes the example above work correctly. A: write in separate thread: while(cond) { string s = _pythonProc.StandardOutput.ReadLine(); textOutput.Invoke( () => { textOutput.Text += s; } ); }
Redirect Python standard input/output to C# forms application
I apologize if this is a duplicate question, I searched a bit and couldn't find anything similar - I have a Python library that connects to my C# application via a socket in order to allow simple Python scripting (IronPython isn't an option right now for a couple of reasons). I would like to create a Windows Forms control that would be basically a graphical front-end for the Python interpreter, so that the user could run the interpreter without having to have a separate console window open. I attached a simple demo of what I've tried so far below, but I haven't been able to get it to work. The DataReceived event handlers are never called, and when I try to write to the standard input nothing happens in the interpreter. Does anyone have any feedback about what I'm doing wrong, or if this is even possible? public partial class Form1 : Form { Process _pythonProc; public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { ProcessStartInfo psi = new ProcessStartInfo() { FileName = @"C:\Python26\Python.exe", CreateNoWindow = true, UseShellExecute = false, RedirectStandardInput = true, RedirectStandardOutput = true, RedirectStandardError = true }; _pythonProc = new Process(); _pythonProc.OutputDataReceived += OutputDataReceived; _pythonProc.ErrorDataReceived += ErrorDataReceived; _pythonProc.StartInfo = psi; _pythonProc.Start(); } private void cmdExecute_Click(object sender, EventArgs e) { string cmd = textInput.Text; _pythonProc.StandardInput.WriteLine(cmd); _pythonProc.StandardInput.Flush(); textInput.Text = string.Empty; } private void Form1_FormClosed(object sender, FormClosedEventArgs e) { if (!_pythonProc.HasExited) _pythonProc.Kill(); } private void OutputDataReceived(object sender, DataReceivedEventArgs args) { textOutput.Text += args.Data; } private void ErrorDataReceived(object sender, DataReceivedEventArgs args) { textOutput.Text += args.Data; } }
[ "In case anyone else stumbles across this, I figured out the problem - by default, the Python interpreter only enters interactive mode if it detects that a TTY device is connected to standard input (which is normally only true if the program is run from the console). In order to redirect the standard IO streams, you have to set UseShellExecute in the ProcessStartInfo to false, which causes the interpreter to think that there is no TTY connected, meaning it immediately exits since it has nothing to do.\nThe solution is to run the Python interpreter with the \"-i\" command line argument, which forces the interpreter to interactive mode, regardless of whether there is a TTY connected to standard in. This makes the example above work correctly.\n", "write in separate thread:\nwhile(cond)\n{\n string s = _pythonProc.StandardOutput.ReadLine();\n textOutput.Invoke( () => { textOutput.Text += s; } );\n}\n\n" ]
[ 21, 1 ]
[]
[]
[ "c#", "python", "redirect", "stdin", "stdout" ]
stackoverflow_0002380649_c#_python_redirect_stdin_stdout.txt
Q: Replace a string of characters with some special characters? when i input some texts/strings, i want them to appear either as hidden or with some special characters(as we do while entering password). . . how can i implement it in a python program? pls help me. A: Use getpass import getpass getpass.getpass() A: You want the getpass module.
Replace a string of characters with some special characters?
when i input some texts/strings, i want them to appear either as hidden or with some special characters(as we do while entering password). . . how can i implement it in a python program? pls help me.
[ "Use getpass\nimport getpass\ngetpass.getpass()\n\n", "You want the getpass module.\n" ]
[ 4, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002381423_python.txt
Q: wsdl2py requests I'm trying to get results from a SOAP service called Chrome ADS (for vehicle data). They provided php and Java samples, but I need python (our site is in Django). My question is: What should I be passing as a request to the SOAP service when using wsdl2py-generated classes? Following the examples I'm using a DataVersionsRequest object as the request parameter, but the code generated by wsdl2py seems to want a getDataVersions object, and there's something like that defined at the bottom of the generated _client.py file. But that too seems to throw an error. So I'm not sure what I should be passing as the request obj. Any suggestions? $sudo apt-get install python-zsi $wsdl2py http://platform.chrome.com/*********** $python >>> url = "http://platform.chrome.com/***********" >>> from AutomotiveDescriptionService6_client import * >>> from AutomotiveDescriptionService6_types import * >>> locator = AutomotiveDescriptionService6Locator() >>> service = locator.getAutomotiveDescriptionService6Port() >>> locale = ns0.Locale_Def('locale') >>> locale._country="US" >>> locale._language="English" >>> acctInfo = ns0.AccountInfo_Def('accountInfo') >>> acctInfo._accountNumber=***** >>> acctInfo._accountSecret="*****" >>> acctInfo._locale = locale >>> dataVersionsRequest = ns0.DataVersionsRequest_Dec() >>> dataVersionsRequest._accountInfo = acctInfo >>> service.getDataVersions(dataVersionsRequest) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "AutomotiveDescriptionService6_client.py", line 36, in getDataVersions raise TypeError, "%s incorrect request type" % (request.__class__) TypeError: <class 'AutomotiveDescriptionService6_types.DataVersionsRequest_Dec'> incorrect request type >>> dataVersionsRequest = getDataVersions >>> dataVersionsRequest._accountInfo = acctInfo >>> service.getDataVersions(dataVersionsRequest) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "AutomotiveDescriptionService6_client.py", line 36, in getDataVersions raise TypeError, "%s incorrect request type" % (request.__class__) AttributeError: class DataVersionsRequest_Holder has no attribute '__class__' >>> quit() $cat AutomotiveDescriptionService6_client.py ..... # Locator class AutomotiveDescriptionService6Locator: AutomotiveDescriptionService6Port_address = "http://platform.chrome.com:80/AutomotiveDescriptionService/AutomotiveDescriptionService6" def getAutomotiveDescriptionService6PortAddress(self): return AutomotiveDescriptionService6Locator.AutomotiveDescriptionService6Port_address def getAutomotiveDescriptionService6Port(self, url=None, **kw): return AutomotiveDescriptionService6BindingSOAP(url or AutomotiveDescriptionService6Locator.AutomotiveDescriptionService6Port_address, **kw) # Methods class AutomotiveDescriptionService6BindingSOAP: def __init__(self, url, **kw): kw.setdefault("readerclass", None) kw.setdefault("writerclass", None) # no resource properties self.binding = client.Binding(url=url, **kw) # no ws-addressing # op: getDataVersions def getDataVersions(self, request, **kw): if isinstance(request, getDataVersions) is False: raise TypeError, "%s incorrect request type" % (request.__class__) # no input wsaction self.binding.Send(None, None, request, soapaction="", **kw) # no output wsaction response = self.binding.Receive(getDataVersionsResponse.typecode) return response ..... getDataVersions = GED("urn:description6.kp.chrome.com", "DataVersionsRequest").pyclass Also, as an aside, I'm not sure that the strings I'm passing to the pname parameter are correct, I assume that those are the ones I see inside the XML when I explore the service with SOAP UI, right? A: It looks like you might be passing a class to service.getDataVersions() the second time instead of an instance (it can't be an instance if it doesn't have __class__). What's happening is isinstance() returns false, and in the process of trying to raise a type error, an attribute error gets raised instead because it's trying to access __class__ which apparently doesn't exist. What happens if you try: >>> dataVersionsRequest = getDataVersions**()** >>> dataVersionsRequest._accountInfo = acctInfo >>> service.getDataVersions(dataVersionsRequest) ? Based on the line: if isinstance(request, getDataVersions) is False: raise TypeError, "%s incorrect request type" % (request.__class__) it definitely looks like you should be passing an instance of getDataVersions, so you're probably on the right track. A: You probably need to be instantiating your definition objects and then populating them. Look for type == pyclass_type objects associated with the request you're wanting to make and instantiate them. e.g. (just guessing) >>> versionrequest = getDataVersions() >>> versionrequest.AccountInfo = versionrequest.new_AccountInfo() >>> versionrequest.AccountInfo.accountNumber = "123" >>> versionrequest.AccountInfo.accountSecret = "shhhh!" >>> service.getDataVersions(versionrequest) I found that the code generated by wsdl2py was too slow for my purposes. Good luck.
wsdl2py requests
I'm trying to get results from a SOAP service called Chrome ADS (for vehicle data). They provided php and Java samples, but I need python (our site is in Django). My question is: What should I be passing as a request to the SOAP service when using wsdl2py-generated classes? Following the examples I'm using a DataVersionsRequest object as the request parameter, but the code generated by wsdl2py seems to want a getDataVersions object, and there's something like that defined at the bottom of the generated _client.py file. But that too seems to throw an error. So I'm not sure what I should be passing as the request obj. Any suggestions? $sudo apt-get install python-zsi $wsdl2py http://platform.chrome.com/*********** $python >>> url = "http://platform.chrome.com/***********" >>> from AutomotiveDescriptionService6_client import * >>> from AutomotiveDescriptionService6_types import * >>> locator = AutomotiveDescriptionService6Locator() >>> service = locator.getAutomotiveDescriptionService6Port() >>> locale = ns0.Locale_Def('locale') >>> locale._country="US" >>> locale._language="English" >>> acctInfo = ns0.AccountInfo_Def('accountInfo') >>> acctInfo._accountNumber=***** >>> acctInfo._accountSecret="*****" >>> acctInfo._locale = locale >>> dataVersionsRequest = ns0.DataVersionsRequest_Dec() >>> dataVersionsRequest._accountInfo = acctInfo >>> service.getDataVersions(dataVersionsRequest) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "AutomotiveDescriptionService6_client.py", line 36, in getDataVersions raise TypeError, "%s incorrect request type" % (request.__class__) TypeError: <class 'AutomotiveDescriptionService6_types.DataVersionsRequest_Dec'> incorrect request type >>> dataVersionsRequest = getDataVersions >>> dataVersionsRequest._accountInfo = acctInfo >>> service.getDataVersions(dataVersionsRequest) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "AutomotiveDescriptionService6_client.py", line 36, in getDataVersions raise TypeError, "%s incorrect request type" % (request.__class__) AttributeError: class DataVersionsRequest_Holder has no attribute '__class__' >>> quit() $cat AutomotiveDescriptionService6_client.py ..... # Locator class AutomotiveDescriptionService6Locator: AutomotiveDescriptionService6Port_address = "http://platform.chrome.com:80/AutomotiveDescriptionService/AutomotiveDescriptionService6" def getAutomotiveDescriptionService6PortAddress(self): return AutomotiveDescriptionService6Locator.AutomotiveDescriptionService6Port_address def getAutomotiveDescriptionService6Port(self, url=None, **kw): return AutomotiveDescriptionService6BindingSOAP(url or AutomotiveDescriptionService6Locator.AutomotiveDescriptionService6Port_address, **kw) # Methods class AutomotiveDescriptionService6BindingSOAP: def __init__(self, url, **kw): kw.setdefault("readerclass", None) kw.setdefault("writerclass", None) # no resource properties self.binding = client.Binding(url=url, **kw) # no ws-addressing # op: getDataVersions def getDataVersions(self, request, **kw): if isinstance(request, getDataVersions) is False: raise TypeError, "%s incorrect request type" % (request.__class__) # no input wsaction self.binding.Send(None, None, request, soapaction="", **kw) # no output wsaction response = self.binding.Receive(getDataVersionsResponse.typecode) return response ..... getDataVersions = GED("urn:description6.kp.chrome.com", "DataVersionsRequest").pyclass Also, as an aside, I'm not sure that the strings I'm passing to the pname parameter are correct, I assume that those are the ones I see inside the XML when I explore the service with SOAP UI, right?
[ "It looks like you might be passing a class to service.getDataVersions() the second time instead of an instance (it can't be an instance if it doesn't have __class__).\nWhat's happening is isinstance() returns false, and in the process of trying to raise a type error, an attribute error gets raised instead because it's trying to access __class__ which apparently doesn't exist.\nWhat happens if you try:\n>>> dataVersionsRequest = getDataVersions**()**\n>>> dataVersionsRequest._accountInfo = acctInfo\n>>> service.getDataVersions(dataVersionsRequest)\n\n?\nBased on the line:\nif isinstance(request, getDataVersions) is False:\n raise TypeError, \"%s incorrect request type\" % (request.__class__)\n\nit definitely looks like you should be passing an instance of getDataVersions, so you're probably on the right track.\n", "You probably need to be instantiating your definition objects and then populating them. Look for type == pyclass_type objects associated with the request you're wanting to make and instantiate them.\ne.g. (just guessing)\n>>> versionrequest = getDataVersions()\n>>> versionrequest.AccountInfo = versionrequest.new_AccountInfo()\n>>> versionrequest.AccountInfo.accountNumber = \"123\"\n>>> versionrequest.AccountInfo.accountSecret = \"shhhh!\"\n>>> service.getDataVersions(versionrequest)\n\nI found that the code generated by wsdl2py was too slow for my purposes. Good luck.\n" ]
[ 1, 0 ]
[]
[]
[ "python", "soap", "wsdl" ]
stackoverflow_0002375956_python_soap_wsdl.txt
Q: Can someone explain pipe buffer deadlock? Python documentation to Popen states: Warning Use communicate() rather than .stdin.write, .stdout.read or .stderr.read to avoid deadlocks due to any of the other OS pipe buffers filling up and blocking the child process. Now, I'm trying to figure out how this deadlock can occur and why. My mental model: subproccess produces something to stdout/err, which is buffered and after buffer is filled, it's flushed to stdout/err of subproccess, which is send through pipe to parent process. From what documentation states, pipe has it's own buffer and when it's filled or subprocess terminates, it's flushed to to the parent process. Either way (with pipe buffer or not), I'm not entirely sure how deadlock can occur. Only thing I can think of is some kind of "global" OS pipe buffer processes will be striving for, which sounds strange. Another is that more processes will share same pipe, which should not happen on it's own. Can someone please explain this? A: Careful, this has a subtle mistake in it. My mental model: subproccess produces something to stdout/err, which is buffered and after buffer is filled, it's flushed to stdout/err of subproccess, which is send through pipe to parent process. The buffer is shared by parent and child process. Subprocess produces something to stdout, which is the same buffer the parent process is supposed to be reading from. When the buffer is filled, writing stops until the buffer is emptied. Flush doesn't mean anything to a pipe, since two processes share the same buffer. Flushing to disk means that the device driver must push the bytes down to the device. Flushing a socket means to tell TCP/IP to stop waiting to accumulate a buffer and send stuff. Flushing to a console means stop waiting for a newline and push the bytes through the device driver to the device. A: A deadlock can occur when both buffers (stdin and stdout) are full: your program is waiting to write more input to the external program, and the external program is waiting for you to read from its output buffer first. This can be solved by using non-blocking I/O and properly prioritizing the buffers. You can try to make it work yourself, but communicate() just does that for you.
Can someone explain pipe buffer deadlock?
Python documentation to Popen states: Warning Use communicate() rather than .stdin.write, .stdout.read or .stderr.read to avoid deadlocks due to any of the other OS pipe buffers filling up and blocking the child process. Now, I'm trying to figure out how this deadlock can occur and why. My mental model: subproccess produces something to stdout/err, which is buffered and after buffer is filled, it's flushed to stdout/err of subproccess, which is send through pipe to parent process. From what documentation states, pipe has it's own buffer and when it's filled or subprocess terminates, it's flushed to to the parent process. Either way (with pipe buffer or not), I'm not entirely sure how deadlock can occur. Only thing I can think of is some kind of "global" OS pipe buffer processes will be striving for, which sounds strange. Another is that more processes will share same pipe, which should not happen on it's own. Can someone please explain this?
[ "Careful, this has a subtle mistake in it.\n\nMy mental model: subproccess produces\n something to stdout/err, which is\n buffered and after buffer is filled,\n it's flushed to stdout/err of\n subproccess, which is send through\n pipe to parent process.\n\nThe buffer is shared by parent and child process. \nSubprocess produces something to stdout, which is the same buffer the parent process is supposed to be reading from.\nWhen the buffer is filled, writing stops until the buffer is emptied. Flush doesn't mean anything to a pipe, since two processes share the same buffer.\nFlushing to disk means that the device driver must push the bytes down to the device. Flushing a socket means to tell TCP/IP to stop waiting to accumulate a buffer and send stuff. Flushing to a console means stop waiting for a newline and push the bytes through the device driver to the device.\n", "A deadlock can occur when both buffers (stdin and stdout) are full: your program is waiting to write more input to the external program, and the external program is waiting for you to read from its output buffer first.\nThis can be solved by using non-blocking I/O and properly prioritizing the buffers. You can try to make it work yourself, but communicate() just does that for you.\n" ]
[ 10, 5 ]
[]
[]
[ "operating_system", "pipe", "python" ]
stackoverflow_0002381751_operating_system_pipe_python.txt
Q: How to write a unittest for importing a module in Python What is the pythonic way of writing a unittest to see if a module is properly installed? By properly installed I mean, it does not raise an ImportError: No module named foo. A: As I have to deploy my Django application on a different server and it requires some extra modules I want to make sure that all required modules are installed. This is not a unit test scenario at all. This is a production readiness process and it isn't -- technically -- a test of your application. It's a query about the environment. Ours includes dozens of things. Start with a simple script like this. Add each thing you need to be sure exists. try: import simplejson except ImportError: print "***FAILURE: simplejson missing***" sys.exit( 2 ) sys.exit( 0 ) Just run this script in each environment as part of installation. It's not a unit test at all. It's a precondition for setup install. A: I don't see why you'd need to test this, but something like: def my_import_test(self): import my_module If an import error is raised the test has failed, if not it passes.
How to write a unittest for importing a module in Python
What is the pythonic way of writing a unittest to see if a module is properly installed? By properly installed I mean, it does not raise an ImportError: No module named foo.
[ "\nAs I have to deploy my Django\n application on a different server and\n it requires some extra modules I want\n to make sure that all required modules\n are installed.\n\nThis is not a unit test scenario at all.\nThis is a production readiness process and it isn't -- technically -- a test of your application.\nIt's a query about the environment. Ours includes dozens of things.\nStart with a simple script like this. Add each thing you need to be sure exists.\ntry:\n import simplejson\nexcept ImportError:\n print \"***FAILURE: simplejson missing***\"\n sys.exit( 2 )\nsys.exit( 0 )\n\nJust run this script in each environment as part of installation. It's not a unit test at all. It's a precondition for setup install.\n", "I don't see why you'd need to test this, but something like:\ndef my_import_test(self):\n import my_module\n\nIf an import error is raised the test has failed, if not it passes.\n" ]
[ 5, 1 ]
[]
[]
[ "django", "python", "unit_testing" ]
stackoverflow_0002381535_django_python_unit_testing.txt
Q: Python Lambda with Or Reading the documentation it seems this might not be possible, but it seems that a lot of people have been able to beat more complicated functionality into pythons lambda function. I'm leveraging the scapy libraries to do some packet creation. Specially this questions is about the ConditionalField which takes it a field and a comparison function, the field only being added to the packet if the comparison is true, but I need to do 2 comparisons. Example with only one check, this works: ConditionalField(XShortField("chksum",None),lambda pkt:pkt.chksumpresent==1) What I want: ConditionalField(XShortField("chksum",None),lambda pkt:pkt.chksumpresent==1 or (lamba pkt:pkt.special == 1)) This isn't giving expected results. Is there a way to do this? A: lambda pkt:((pkt.chksumpresent == 1) or (pkt.special == 1)) A: Is lambda the most readable/maintainable? The following is just as performant: def checksum_condition(pkt): return pkt.chksumpresent == 1 or pkt.special == 1 ConditionalField(XShortField("chksum",None), checksum_condition)
Python Lambda with Or
Reading the documentation it seems this might not be possible, but it seems that a lot of people have been able to beat more complicated functionality into pythons lambda function. I'm leveraging the scapy libraries to do some packet creation. Specially this questions is about the ConditionalField which takes it a field and a comparison function, the field only being added to the packet if the comparison is true, but I need to do 2 comparisons. Example with only one check, this works: ConditionalField(XShortField("chksum",None),lambda pkt:pkt.chksumpresent==1) What I want: ConditionalField(XShortField("chksum",None),lambda pkt:pkt.chksumpresent==1 or (lamba pkt:pkt.special == 1)) This isn't giving expected results. Is there a way to do this?
[ "lambda pkt:((pkt.chksumpresent == 1) or (pkt.special == 1))\n\n", "Is lambda the most readable/maintainable? The following is just as performant:\ndef checksum_condition(pkt):\n return pkt.chksumpresent == 1 or pkt.special == 1\n\nConditionalField(XShortField(\"chksum\",None), checksum_condition)\n\n" ]
[ 8, 6 ]
[]
[]
[ "lambda", "python" ]
stackoverflow_0002382023_lambda_python.txt
Q: wsdl2py ComplexTypes How do I add complex types to a SOAP request? I'm using WSDL2py generated requests, and trying to use the other TypeDefinitions that it made in the ***_types.py file (like AccountInfo, for authentication, that goes into every request). Then passing it the wsdl2py generated server, and I'm getting this error: >>> from AutomotiveDescriptionService6_client import * >>> from AutomotiveDescriptionService6_types import * >>> loc = AutomotiveDescriptionService6Locator() >>> server = loc.getAutomotiveDescriptionService6Port() >>> request = getDataVersions() >>> auth = ns0.AccountInfo_Def() >>> auth._accountName="**" >>> auth._accountSecret="***" >>> request._accountInfo = auth >>> server.getDataVersions(request) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "AutomotiveDescriptionService6_client.py", line 38, in getDataVersions self.binding.Send(None, None, request, soapaction="", **kw) File "/usr/lib/pymodules/python2.6/ZSI/client.py", line 246, in Send sw.serialize(obj, tc) File "/usr/lib/pymodules/python2.6/ZSI/writer.py", line 117, in serialize elt = typecode.serialize(self.body, self, pyobj, **kw) File "/usr/lib/pymodules/python2.6/ZSI/TC.py", line 609, in serialize pyobj.typecode.serialize(elt, sw, pyobj, **kw) File "/usr/lib/pymodules/python2.6/ZSI/TCcompound.py", line 275, in serialize self.cb(elt, sw, pyobj, name=name, **kw) File "/usr/lib/pymodules/python2.6/ZSI/TCcompound.py", line 424, in cb what.serialize(elem, sw, v, **kw) File "/usr/lib/pymodules/python2.6/ZSI/TCcompound.py", line 275, in serialize self.cb(elt, sw, pyobj, name=name, **kw) File "/usr/lib/pymodules/python2.6/ZSI/TCcompound.py", line 437, in cb sw.Backtrace(elt)) ZSI.EvaluateException: Got None for nillable(False), minOccurs(1) element (urn:description6.kp.chrome.com,accountNumber), <ns1:accountInfo xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ZSI="http://www.zolera.com/schemas/ZSI/" xmlns:ns1="urn:description6.kp.chrome.com" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"></ns1:accountInfo> [Element trace: /SOAP-ENV:Body/ns1:DataVersionsRequest] As you can see, it's easy to generate request objects, wsdl2py uses GED() to give us those, but it DOESN'T expose the classes that those requests need. For the life of me, I can't figure out how the hell to get that complex type properly into the request object, without getting that error. I've been trying to instantiate the definition in the **_types.py file, and I've been trying just plain dicts. NOTHING seems to work. Here's what the auto-generated definition looks like, any suggestions? class ns0: targetNamespace = "urn:description6.kp.chrome.com" class AccountInfo_Def(ZSI.TCcompound.ComplexType, TypeDefinition): schema = "urn:description6.kp.chrome.com" type = (schema, "AccountInfo") def __init__(self, pname, ofwhat=(), attributes=None, extend=False, restrict=False, **kw): ns = ns0.AccountInfo_Def.schema TClist = [ZSI.TC.String(pname=(ns,"accountNumber"), aname="_accountNumber", minOccurs=1, maxOccurs=1, nillable=False, typed=False, encoded=kw.get("encoded")), ZSI.TC.String(pname=(ns,"accountSecret"), aname="_accountSecret", minOccurs=1, maxOccurs=1, nillable=False, typed=False, encoded=kw.get("encoded")), GTD("urn:description6.kp.chrome.com","Locale",lazy=False)(pname=(ns,"locale"), aname="_locale", minOccurs=1, maxOccurs=1, nillable=False, typed=False, encoded=kw.get("encoded"))] self.attribute_typecode_dict = attributes or {} if extend: TClist += ofwhat if restrict: TClist = ofwhat ZSI.TCcompound.ComplexType.__init__(self, None, TClist, pname=pname, inorder=0, **kw) class Holder: typecode = self def __init__(self): # pyclass self._accountNumber = None self._accountSecret = None return Holder.__name__ = "AccountInfo_Holder" self.pyclass = Holder A: So... found out that the problem is I needed to run wsdl2py with the --complextypes flag.This creates a whole slew of awesome methods inside of the reqeust object. methods like new_XXXXX where X is the name of the complex type that's required by that request.
wsdl2py ComplexTypes
How do I add complex types to a SOAP request? I'm using WSDL2py generated requests, and trying to use the other TypeDefinitions that it made in the ***_types.py file (like AccountInfo, for authentication, that goes into every request). Then passing it the wsdl2py generated server, and I'm getting this error: >>> from AutomotiveDescriptionService6_client import * >>> from AutomotiveDescriptionService6_types import * >>> loc = AutomotiveDescriptionService6Locator() >>> server = loc.getAutomotiveDescriptionService6Port() >>> request = getDataVersions() >>> auth = ns0.AccountInfo_Def() >>> auth._accountName="**" >>> auth._accountSecret="***" >>> request._accountInfo = auth >>> server.getDataVersions(request) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "AutomotiveDescriptionService6_client.py", line 38, in getDataVersions self.binding.Send(None, None, request, soapaction="", **kw) File "/usr/lib/pymodules/python2.6/ZSI/client.py", line 246, in Send sw.serialize(obj, tc) File "/usr/lib/pymodules/python2.6/ZSI/writer.py", line 117, in serialize elt = typecode.serialize(self.body, self, pyobj, **kw) File "/usr/lib/pymodules/python2.6/ZSI/TC.py", line 609, in serialize pyobj.typecode.serialize(elt, sw, pyobj, **kw) File "/usr/lib/pymodules/python2.6/ZSI/TCcompound.py", line 275, in serialize self.cb(elt, sw, pyobj, name=name, **kw) File "/usr/lib/pymodules/python2.6/ZSI/TCcompound.py", line 424, in cb what.serialize(elem, sw, v, **kw) File "/usr/lib/pymodules/python2.6/ZSI/TCcompound.py", line 275, in serialize self.cb(elt, sw, pyobj, name=name, **kw) File "/usr/lib/pymodules/python2.6/ZSI/TCcompound.py", line 437, in cb sw.Backtrace(elt)) ZSI.EvaluateException: Got None for nillable(False), minOccurs(1) element (urn:description6.kp.chrome.com,accountNumber), <ns1:accountInfo xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ZSI="http://www.zolera.com/schemas/ZSI/" xmlns:ns1="urn:description6.kp.chrome.com" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"></ns1:accountInfo> [Element trace: /SOAP-ENV:Body/ns1:DataVersionsRequest] As you can see, it's easy to generate request objects, wsdl2py uses GED() to give us those, but it DOESN'T expose the classes that those requests need. For the life of me, I can't figure out how the hell to get that complex type properly into the request object, without getting that error. I've been trying to instantiate the definition in the **_types.py file, and I've been trying just plain dicts. NOTHING seems to work. Here's what the auto-generated definition looks like, any suggestions? class ns0: targetNamespace = "urn:description6.kp.chrome.com" class AccountInfo_Def(ZSI.TCcompound.ComplexType, TypeDefinition): schema = "urn:description6.kp.chrome.com" type = (schema, "AccountInfo") def __init__(self, pname, ofwhat=(), attributes=None, extend=False, restrict=False, **kw): ns = ns0.AccountInfo_Def.schema TClist = [ZSI.TC.String(pname=(ns,"accountNumber"), aname="_accountNumber", minOccurs=1, maxOccurs=1, nillable=False, typed=False, encoded=kw.get("encoded")), ZSI.TC.String(pname=(ns,"accountSecret"), aname="_accountSecret", minOccurs=1, maxOccurs=1, nillable=False, typed=False, encoded=kw.get("encoded")), GTD("urn:description6.kp.chrome.com","Locale",lazy=False)(pname=(ns,"locale"), aname="_locale", minOccurs=1, maxOccurs=1, nillable=False, typed=False, encoded=kw.get("encoded"))] self.attribute_typecode_dict = attributes or {} if extend: TClist += ofwhat if restrict: TClist = ofwhat ZSI.TCcompound.ComplexType.__init__(self, None, TClist, pname=pname, inorder=0, **kw) class Holder: typecode = self def __init__(self): # pyclass self._accountNumber = None self._accountSecret = None return Holder.__name__ = "AccountInfo_Holder" self.pyclass = Holder
[ "So... found out that the problem is I needed to run wsdl2py with the --complextypes flag.This creates a whole slew of awesome methods inside of the reqeust object. methods like new_XXXXX where X is the name of the complex type that's required by that request.\n" ]
[ 2 ]
[]
[]
[ "python", "soap", "wsdl" ]
stackoverflow_0002382650_python_soap_wsdl.txt
Q: Creating a palindrome list with reverse() I want to take a list [0,1,2] and turn it into [0,1,2,2,1,0]. Right now, I've got r = list(mus) r.reverse() mus = mus + r but it seems like there should be a better way. Can anyone come up with a good, pythonic one-liner? A: It looks like you might be in need of mus.extend(reversed(mus)) Or if you simply need to iterate over this and not necessarily form the list, use import itertools for item in itertools.chain(mus, reversed(mus)): do_something... A: Just a few of the many ways to do this are: m = l + reversed(l) m = l + l[::-1] l.extend(reversed(l)) l.extend(l[::-1]) The first two assign the output to a new list, and the second two update the list in place. If I was being clever, I would probably use 2 or 4, but if I wanted there to be no mistake about what I was doing, then I would opt for 1 or 3. Hope this helps. Edit: As pointed out in the comments, #1 doesn't work, as reversed returns an iterator. You could make it work by changing it to: m = l + list(reversed(l)) But I can't recommend it. Go with 2 instead. BTW, thanks for the correction and sorry for any confusion.
Creating a palindrome list with reverse()
I want to take a list [0,1,2] and turn it into [0,1,2,2,1,0]. Right now, I've got r = list(mus) r.reverse() mus = mus + r but it seems like there should be a better way. Can anyone come up with a good, pythonic one-liner?
[ "It looks like you might be in need of\nmus.extend(reversed(mus))\n\nOr if you simply need to iterate over this and not necessarily form the list, use\nimport itertools\nfor item in itertools.chain(mus, reversed(mus)):\n do_something...\n\n", "Just a few of the many ways to do this are:\n\nm = l + reversed(l)\nm = l + l[::-1]\nl.extend(reversed(l))\nl.extend(l[::-1])\n\nThe first two assign the output to a new list, and the second two update the list in place. If I was being clever, I would probably use 2 or 4, but if I wanted there to be no mistake about what I was doing, then I would opt for 1 or 3.\nHope this helps.\nEdit:\nAs pointed out in the comments, #1 doesn't work, as reversed returns an iterator. You could make it work by changing it to:\nm = l + list(reversed(l))\nBut I can't recommend it. Go with 2 instead.\nBTW, thanks for the correction and sorry for any confusion.\n" ]
[ 3, 2 ]
[]
[]
[ "python" ]
stackoverflow_0002382905_python.txt
Q: What is the associativity of Python's ** operator? I was just playing around with the python command line and the ** operator, which as far as I know performs a power function. So 2 ** 3 should be (and is) 8 because 2 * 2 * 2 = 8. Can someone explain the behavior I found? I don't see any way to group the operations with parentheses to actually get a result of 65536 like was attained here. >>> 2 ** 2 ** 2 16 >>> 2 ** 2 ** 2 ** 2 65536 >>> (2 ** 2 ** 2) ** 2 256 A: 2** (2**(2**2)) from http://docs.python.org/reference/expressions.html Operators in the same box group left to right (except for comparisons, including tests, which all have the same precedence and chain from left to right — see section Comparisons — and exponentiation, which groups from right to left). A: Either it associates to the left or the right. To discover the answer yourself, do the experiment. >>> 3 ** 3 ** 3 7625597484987 >>> (3 ** 3) ** 3 19683 >>> 3 ** (3 ** 3) 7625597484987 Thus, it associates to the right. Or you can read the docs. google: "python power" and the first result is http://www.python.org/doc/2.5.2/ref/power.html The second sentence is: Thus, in an unparenthesized sequence of power and unary operators, the operators are evaluated from right to left (this does not constrain the evaluation order for the operands). Confirming the experimental results. A: Also: 2 ** (2 ** 2 ** 2) One way or the other, it becomes 2 ** 16. This is following standard mathematical operations, where: 234 becomes 2 81, instead of 84 and thus is 2417851639229258349412352, instead of 4096. A: The ** operator is right associative: 2 ** (2 ** (2 ** 2)) = 2 ** (2 ** 4) = 2 ** 16 = 65536
What is the associativity of Python's ** operator?
I was just playing around with the python command line and the ** operator, which as far as I know performs a power function. So 2 ** 3 should be (and is) 8 because 2 * 2 * 2 = 8. Can someone explain the behavior I found? I don't see any way to group the operations with parentheses to actually get a result of 65536 like was attained here. >>> 2 ** 2 ** 2 16 >>> 2 ** 2 ** 2 ** 2 65536 >>> (2 ** 2 ** 2) ** 2 256
[ "2** (2**(2**2))\n\nfrom http://docs.python.org/reference/expressions.html\nOperators in the same box group left to right (except for comparisons, including tests, which all have the same precedence and chain from left to right — see section Comparisons — and exponentiation, which groups from right to left).\n", "Either it associates to the left or the right. To discover the answer yourself, do the experiment.\n>>> 3 ** 3 ** 3\n7625597484987\n>>> (3 ** 3) ** 3\n19683\n>>> 3 ** (3 ** 3)\n7625597484987\n\nThus, it associates to the right.\nOr you can read the docs. google: \"python power\" and the first result is\nhttp://www.python.org/doc/2.5.2/ref/power.html\nThe second sentence is:\n\nThus, in an unparenthesized sequence\n of power and unary operators, the\n operators are evaluated from right to\n left (this does not constrain the\n evaluation order for the operands).\n\nConfirming the experimental results.\n", "Also:\n2 ** (2 ** 2 ** 2)\n\nOne way or the other, it becomes 2 ** 16.\nThis is following standard mathematical operations, where: 234 becomes 2 81, instead of 84 and thus is 2417851639229258349412352, instead of 4096.\n", "The ** operator is right associative:\n\n 2 ** (2 ** (2 ** 2)) = 2 ** (2 ** 4) = 2 ** 16 = 65536\n\n" ]
[ 6, 5, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002383034_python.txt
Q: Does Django support multi-value cookies? I'd like to set a cookie via Django with that has several different values to it, similar to .NET's HttpCookie.Values property. Looking at the documentation, I can't tell if this is possible. It looks like it just takes a string, so is there another way? I've tried passing it an array ([10, 20, 30]) and dictionary ({'name': 'Scott', 'id': 1}) but they just get converted to their string format. My current solution is to just use an arbitrary separator and then parse it when reading it in, which feels icky. If multi-values aren't possible, is there a better way? I'd rather not use lots of cookies, because that would get annoying. A: .NETs multi-value cookies work exactly the same way as what you're doing in django using a separator. They've just abstracted that away for you. What you're doing is fine and proper, and I don't think Django has anything specific to 'solve' this problem. I will say that you're doing the right thing, in not using multiple cookies. Keep the over-the-wire overhead down by doing what you're doing. A: If you're looking for something a little more abstracted, try using sessions. I believe the way they work is by storing an id in the cookie that matches a database record. You can store whatever you want in it. It's not exactly the same as what you're looking for, but it could work if you don't mind a small amount of db overhead. A: (Late answer!) This will be bulkier, but you call always use python's built in serializing. You could always do something like: import pickle class MultiCookie(): def __init__(self,cookie=None,values=None): if cookie != None: try: self.values = pickle.loads(cookie) except: # assume that it used to just hold a string value self.values = cookie elif values != None: self.values = values else: self.values = None def __str__(self): return pickle.dumps(self.values) Then, you can get the cookie: newcookie = MultiCookie(cookie=request.COOKIES.get('multi')) values_for_cookie = newcookie.values Or set the values: mylist = [ 1, 2, 3 ] newcookie = MultiCookie(values=mylist) request.set_cookie('multi',value=newcookie) A: Django does not support it. The best way would be to separate the values with arbitrary separator and then just split the string, like you already said.
Does Django support multi-value cookies?
I'd like to set a cookie via Django with that has several different values to it, similar to .NET's HttpCookie.Values property. Looking at the documentation, I can't tell if this is possible. It looks like it just takes a string, so is there another way? I've tried passing it an array ([10, 20, 30]) and dictionary ({'name': 'Scott', 'id': 1}) but they just get converted to their string format. My current solution is to just use an arbitrary separator and then parse it when reading it in, which feels icky. If multi-values aren't possible, is there a better way? I'd rather not use lots of cookies, because that would get annoying.
[ ".NETs multi-value cookies work exactly the same way as what you're doing in django using a separator. They've just abstracted that away for you. What you're doing is fine and proper, and I don't think Django has anything specific to 'solve' this problem.\nI will say that you're doing the right thing, in not using multiple cookies. Keep the over-the-wire overhead down by doing what you're doing.\n", "If you're looking for something a little more abstracted, try using sessions. I believe the way they work is by storing an id in the cookie that matches a database record. You can store whatever you want in it. It's not exactly the same as what you're looking for, but it could work if you don't mind a small amount of db overhead.\n", "(Late answer!) \nThis will be bulkier, but you call always use python's built in serializing.\nYou could always do something like:\nimport pickle\nclass MultiCookie():\n def __init__(self,cookie=None,values=None):\n if cookie != None:\n try:\n self.values = pickle.loads(cookie)\n except:\n # assume that it used to just hold a string value\n self.values = cookie\n elif values != None:\n self.values = values\n else:\n self.values = None\n\n def __str__(self):\n return pickle.dumps(self.values)\n\nThen, you can get the cookie:\nnewcookie = MultiCookie(cookie=request.COOKIES.get('multi'))\nvalues_for_cookie = newcookie.values\n\nOr set the values:\nmylist = [ 1, 2, 3 ]\nnewcookie = MultiCookie(values=mylist)\nrequest.set_cookie('multi',value=newcookie)\n\n", "Django does not support it. The best way would be to separate the values with arbitrary separator and then just split the string, like you already said.\n" ]
[ 7, 1, 1, 0 ]
[]
[]
[ "cookies", "django", "python" ]
stackoverflow_0000128815_cookies_django_python.txt
Q: %windir% in Python? How can I do something like if sys.argv[0] != '%windir%\\blabla.exe' I'm having no success at all A: import os if sys.argv[0] != os.path.join(os.environ['WINDIR'],'blalah.exe'): A: This should illustrate how to get the location of Windows: >>> import os >>> os.environ['windir'] 'C:\\Windows' A: if sys.argv[0] != '%windir%\\blabla.exe' What are you trying to do here? argv[0] is, generally, the filename of the script you are invoking. It would seem unlikely to be blabla.exe, unless you're using some packaging tool to compile yourself into an EXE. If you want to look at the first argument passed to the script, see sys.argv[1]. Also, when you use an %EnvironmentVariable% from the console, the Windows shell will replace the variable name with its content. So when you type myscript.py %windir%\blabla.exe, Windows will replace that with myscript.py C:\Windows\blabla.exe (or similar) before your script gets a look in, and your comparison will fail because the variable name is no longer there. You can use os.path.expandvars to do the same replacement to your own strings (or just read os.environ yourself). You may also want to absolutize the path so you can compare the real effective path without having to worry about relative paths: blapath= os.path.expandvars(r'%WinDir%\blabla.exe') if os.path.abspath(sys.argv[1])==os.path.abspath(blapath): ... In this case, you could also consider os.path.normcase​ing both paths, to allow for Windows's case-insensitivity. A: Use os.environ to get the value of the environment variable, and string interpolation to put it with the rest of the string: execfile = r'%s\blabla.exe' % (os.environ['windir'],) if sys.argv[0] != execfile: .... A: You need: if sys.argv[0] != os.environ.get("windir") That should do it for you. Just add your blabla.exe on the end of that.
%windir% in Python?
How can I do something like if sys.argv[0] != '%windir%\\blabla.exe' I'm having no success at all
[ "import os\nif sys.argv[0] != os.path.join(os.environ['WINDIR'],'blalah.exe'):\n\n", "This should illustrate how to get the location of Windows:\n>>> import os\n>>> os.environ['windir']\n'C:\\\\Windows'\n\n", "if sys.argv[0] != '%windir%\\\\blabla.exe'\n\nWhat are you trying to do here?\nargv[0] is, generally, the filename of the script you are invoking. It would seem unlikely to be blabla.exe, unless you're using some packaging tool to compile yourself into an EXE. If you want to look at the first argument passed to the script, see sys.argv[1].\nAlso, when you use an %EnvironmentVariable% from the console, the Windows shell will replace the variable name with its content. So when you type myscript.py %windir%\\blabla.exe, Windows will replace that with myscript.py C:\\Windows\\blabla.exe (or similar) before your script gets a look in, and your comparison will fail because the variable name is no longer there.\nYou can use os.path.expandvars to do the same replacement to your own strings (or just read os.environ yourself). You may also want to absolutize the path so you can compare the real effective path without having to worry about relative paths:\nblapath= os.path.expandvars(r'%WinDir%\\blabla.exe')\nif os.path.abspath(sys.argv[1])==os.path.abspath(blapath):\n ...\n\nIn this case, you could also consider os.path.normcase​ing both paths, to allow for Windows's case-insensitivity.\n", "Use os.environ to get the value of the environment variable, and string interpolation to put it with the rest of the string:\nexecfile = r'%s\\blabla.exe' % (os.environ['windir'],)\n\nif sys.argv[0] != execfile:\n ....\n\n", "You need:\nif sys.argv[0] != os.environ.get(\"windir\")\n\nThat should do it for you. Just add your blabla.exe on the end of that.\n" ]
[ 5, 4, 2, 0, 0 ]
[]
[]
[ "python", "windows" ]
stackoverflow_0002383306_python_windows.txt
Q: Opening links in external browser in Amarok 1.4 I've tried asking this question on the KDE development forum, but haven't received a satisfying answer so far. I've developed a Python script for Amarok 1.4 which retrieves upcoming events for the currently playing artist and displays them in the context browser. The user can click each event to know more about it, but so far clicking takes him to another Amarok tab, in which he must then click another button to finally get the link to open in the external browser. What I'd like to know is whether there is a way to open the link directly in the external browser. Update: I recently started using Pana, which actually opens the links directly in the Wikipedia tab, so I guess I'll stick to that player in the future. A: I know nothing about Amarok, but in general you can spawn the platform's default web browser on a URL: on modern open-source desktops (KDE, GNOME, Xfce) by spawning the xdg-open command; on OS X with the open command; on Windows with the built-in os.startfile method. There is also the webbrowser module, but it will often pick the wrong browser and everything about it is outmoded and ugly.
Opening links in external browser in Amarok 1.4
I've tried asking this question on the KDE development forum, but haven't received a satisfying answer so far. I've developed a Python script for Amarok 1.4 which retrieves upcoming events for the currently playing artist and displays them in the context browser. The user can click each event to know more about it, but so far clicking takes him to another Amarok tab, in which he must then click another button to finally get the link to open in the external browser. What I'd like to know is whether there is a way to open the link directly in the external browser. Update: I recently started using Pana, which actually opens the links directly in the Wikipedia tab, so I guess I'll stick to that player in the future.
[ "I know nothing about Amarok, but in general you can spawn the platform's default web browser on a URL:\n\non modern open-source desktops (KDE, GNOME, Xfce) by spawning the xdg-open command;\non OS X with the open command;\non Windows with the built-in os.startfile method.\n\nThere is also the webbrowser module, but it will often pick the wrong browser and everything about it is outmoded and ugly.\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0002382263_python.txt
Q: Rendering mathematical notation in Python / OpenGL? How can I render mathematical notations / expressions in Python with OpenGL? I'm actually using pyglet however it uses OpenGL. Such things as this: I can't store static images as I am generating the expressions as well. A: I would say generate suitable latex expression, rendering it into an image, then load the image as a texture. A: You can use GL_TEXTURE_RECTANGLE_ARB opengl extension to quickly load dynamicaly generated image of arbitrary size into OpenGL texture. You can look for python examples of using dynamic vector graphics with opengl at http://cairographics.org/OpenGL/, though if you want to render complex formulas you also have to look at the some appropriate system like latex. A: I don't know about the OpenGL bit. But matplotlib has a matplotlib.mathtext module for rendering a sub-set of TeX mathematical expressions. Screenshots Tutorial
Rendering mathematical notation in Python / OpenGL?
How can I render mathematical notations / expressions in Python with OpenGL? I'm actually using pyglet however it uses OpenGL. Such things as this: I can't store static images as I am generating the expressions as well.
[ "I would say generate suitable latex expression, rendering it into an image, then load the image as a texture.\n", "You can use GL_TEXTURE_RECTANGLE_ARB opengl extension to quickly load dynamicaly generated image of arbitrary size into OpenGL texture. \nYou can look for python examples of using dynamic vector graphics with opengl at http://cairographics.org/OpenGL/, though if you want to render complex formulas you also have to look at the some appropriate system like latex.\n", "I don't know about the OpenGL bit. But matplotlib has a matplotlib.mathtext module for rendering a sub-set of TeX mathematical expressions.\n\nScreenshots\nTutorial\n\n" ]
[ 10, 3, 1 ]
[]
[]
[ "math", "opengl", "pyglet", "python", "rendering" ]
stackoverflow_0002377944_math_opengl_pyglet_python_rendering.txt
Q: How to I make the result of this a variable? right now its set up to write to a file, but I want it to output the value to a variable. not sure how. from BeautifulSoup import BeautifulSoup import sys, re, urllib2 import codecs woof1 = urllib2.urlopen('someurl').read() woof_1 = BeautifulSoup(woof1) woof2 = urllib2.urlopen('someurl').read() woof_2 = BeautifulSoup(woof2) GE_DB = open('GE_DB.txt', 'a') for row in woof_1.findAll("tr", { "class" : "row_b" }): for col in row.findAll(re.compile('td')): GE_DB.write(col.string if col.string else '') GE_DB.write(" ") GE_DB.write("\n") GE_DB.close() for row in woof_2.findAll("tr", { "class" : "row_b" }): for col in row.findAll(re.compile('td')): GE_DB.write(col.string if col.string else '') GE_DB.write("\n") GE_DB.close() A: values = [] for row in woof_1.findAll("tr", { "class" : "row_b" }): for col in row.findAll(re.compile('td')): if col.string: values.append(col.string) result = ''.join(values)
How to I make the result of this a variable?
right now its set up to write to a file, but I want it to output the value to a variable. not sure how. from BeautifulSoup import BeautifulSoup import sys, re, urllib2 import codecs woof1 = urllib2.urlopen('someurl').read() woof_1 = BeautifulSoup(woof1) woof2 = urllib2.urlopen('someurl').read() woof_2 = BeautifulSoup(woof2) GE_DB = open('GE_DB.txt', 'a') for row in woof_1.findAll("tr", { "class" : "row_b" }): for col in row.findAll(re.compile('td')): GE_DB.write(col.string if col.string else '') GE_DB.write(" ") GE_DB.write("\n") GE_DB.close() for row in woof_2.findAll("tr", { "class" : "row_b" }): for col in row.findAll(re.compile('td')): GE_DB.write(col.string if col.string else '') GE_DB.write("\n") GE_DB.close()
[ "values = []\nfor row in woof_1.findAll(\"tr\", { \"class\" : \"row_b\" }):\n for col in row.findAll(re.compile('td')):\n if col.string:\n values.append(col.string)\nresult = ''.join(values)\n\n" ]
[ -1 ]
[ "maybe like this.\ngedb = \"\";\nfor row in woof_1.findAll(\"tr\", { \"class\" : \"row_b\" }):\n for col in row.findAll(re.compile('td')):\n if col.string:\n gedb += col.string\n\n\n", "Get rid of all mentions of GE_DB.\nDo a\n outputtext = \"\"\ntowards the beginning.\nReplace GE_DB.write(col.string if col.string else '') with outputtext += col.string if col.string else ''\n", "import cStringIO as StringIO # or import StringIO if on a fringe platform\nbuf = StringIO.StringIO()\nfor row in woof_1.findAll(\"tr\", { \"class\" : \"row_b\" }):\n for col in row.findAll(re.compile('td')):\n buf.write(col.string if col.string else '')\n\nresult = buf.getvalue()\n\n" ]
[ -1, -1, -2 ]
[ "beautifulsoup", "python", "scrape", "variables" ]
stackoverflow_0002383546_beautifulsoup_python_scrape_variables.txt
Q: strcmp for python or how to sort substrings efficiently (without copy) when building a suffix array Here's a very simple way to build an suffix array from a string in python: def sort_offsets(a, b): return cmp(content[a:], content[b:]) content = "foobar baz foo" suffix_array.sort(cmp=sort_offsets) print suffix_array [6, 10, 4, 8, 3, 7, 11, 0, 13, 2, 12, 1, 5, 9] However, "content[a:]" makes a copy of content, which becomes very inefficient when content gets large. So i wonder if there's a way to compare the two substrings without having to copy them. I've tried to use the buffer-builtin, but it didn't worked. A: The buffer function does not copy the whole string, but creates an object that only references the source string. Using interjay's suggestion, that would be: suffix_array.sort(key=lambda a: buffer(content, a)) A: I don't know if there's a fast way to compare substrings, but you can make your code much faster (and simpler) by using key instead of cmp: suffix_array.sort(key=lambda a: content[a:]) This will create the substring just once for each value of a. Edit: A possible downside is that it will require O(n^2) memory for the substrings. A: +1 for a very interesting problem! I can't see any obvious way to do this directly, but I was able to get a significant speedup (an order of magnitude for 100000 character strings) by using the following comparison function in place of yours: def compare_offsets2(a, b): return (cmp(content[a:a+10], content[b:b+10]) or cmp(content[a:], content[b:])) In other words, start by comparing the first 10 characters of each suffix; only if the result of that comparison is 0, indicating that you've got a match for the first 10 characters, do you go on to compare the entire suffices. Obviously 10 could be anything: experiment to find the best value. This comparison function is also a nice example of something that isn't easily replaced with a key function. A: You could use the blist extension type that I wrote. A blist works like the built-in list, but (among other things) uses copy-on-write so that taking a slice takes O(log n) time and memory. from blist import blist content = "foobar baz foo" content = blist(content) suffix_array = range(len(content)) suffix_array.sort(key = lambda a: content[a:]) print suffix_array [6, 10, 4, 8, 3, 7, 11, 0, 13, 2, 12, 1, 5, 9] I was able to create a suffix_array from a randomly generated 100,000-character string in under 5 seconds, and that includes generating the string.
strcmp for python or how to sort substrings efficiently (without copy) when building a suffix array
Here's a very simple way to build an suffix array from a string in python: def sort_offsets(a, b): return cmp(content[a:], content[b:]) content = "foobar baz foo" suffix_array.sort(cmp=sort_offsets) print suffix_array [6, 10, 4, 8, 3, 7, 11, 0, 13, 2, 12, 1, 5, 9] However, "content[a:]" makes a copy of content, which becomes very inefficient when content gets large. So i wonder if there's a way to compare the two substrings without having to copy them. I've tried to use the buffer-builtin, but it didn't worked.
[ "The buffer function does not copy the whole string, but creates an object that only references the source string. Using interjay's suggestion, that would be:\nsuffix_array.sort(key=lambda a: buffer(content, a))\n\n", "I don't know if there's a fast way to compare substrings, but you can make your code much faster (and simpler) by using key instead of cmp:\nsuffix_array.sort(key=lambda a: content[a:])\n\nThis will create the substring just once for each value of a.\nEdit: A possible downside is that it will require O(n^2) memory for the substrings.\n", "+1 for a very interesting problem! I can't see any obvious way to do this directly, but I was able to get a significant speedup (an order of magnitude for 100000 character strings) by using the following comparison function in place of yours:\ndef compare_offsets2(a, b):\n return (cmp(content[a:a+10], content[b:b+10]) or\n cmp(content[a:], content[b:]))\n\nIn other words, start by comparing the first 10 characters of each suffix; only if the result of that comparison is 0, indicating that you've got a match for the first 10 characters, do you go on to compare the entire suffices.\nObviously 10 could be anything: experiment to find the best value.\nThis comparison function is also a nice example of something that isn't easily replaced with a key function.\n", "You could use the blist extension type that I wrote. A blist works like the built-in list, but (among other things) uses copy-on-write so that taking a slice takes O(log n) time and memory.\nfrom blist import blist\n\ncontent = \"foobar baz foo\"\ncontent = blist(content)\nsuffix_array = range(len(content))\nsuffix_array.sort(key = lambda a: content[a:])\nprint suffix_array\n[6, 10, 4, 8, 3, 7, 11, 0, 13, 2, 12, 1, 5, 9]\n\nI was able to create a suffix_array from a randomly generated 100,000-character string in under 5 seconds, and that includes generating the string.\n" ]
[ 6, 5, 3, 0 ]
[]
[]
[ "python", "sorting", "string", "suffix_array" ]
stackoverflow_0002282579_python_sorting_string_suffix_array.txt
Q: Regex: Using lookahead assertion to check if character exist at most a certain number of times How do I use lookahead assertion to determine if a certain character exist at most a certain number of times in a string. For example, let's say I want to check a string that has at least one character to make sure that it contains "@" at most 2 times. Thanks in advance. Using python if that matters. A: There are lots of ways to do this, for example: /^(?=([^@]*@){,2}[^@]*$)./ A: Using a negative lookahead assertion, you can make sure that @ doesn't occur three times: (?!.*@.*@.*@.*).* A: I believe Mark's answer wont quite work as you need to exclude the @ from being matched at other times. Try this: ^(?=(([^@]*@){0,2}[^@]*$)) Edit: Mark fixed his answer, ours should be the same now. Also, fixed.
Regex: Using lookahead assertion to check if character exist at most a certain number of times
How do I use lookahead assertion to determine if a certain character exist at most a certain number of times in a string. For example, let's say I want to check a string that has at least one character to make sure that it contains "@" at most 2 times. Thanks in advance. Using python if that matters.
[ "There are lots of ways to do this, for example:\n/^(?=([^@]*@){,2}[^@]*$)./\n\n", "Using a negative lookahead assertion, you can make sure that @ doesn't occur three times:\n(?!.*@.*@.*@.*).*\n\n", "I believe Mark's answer wont quite work as you need to exclude the @ from being matched at other times. Try this:\n^(?=(([^@]*@){0,2}[^@]*$))\nEdit:\nMark fixed his answer, ours should be the same now. Also, fixed.\n" ]
[ 5, 0, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0002383682_python_regex.txt
Q: Change Node Display Size in Networkx I am not using GraphViz because I am having problems with making it play nice with Networkx. I know this is weird, but I've tried many suggestions to fix this problem, but I just seem to have some of the worst luck in the world. Therefore the problem that I have must be solved withing Networkx without using GraphViz. My program reads a document and and tries to draw something of a MindMap based on the contents of the document. However, Networkx seems to have a default size when it comes to actually drawing the node. This is bad for me because a lot of text goes into each of my nodes. I need a way to increase the display-size of my nodes (arbitrarily, based on the size of the text that belongs in that node). I have tried looking at the Networkx site, other questions on SO and about 200 search results from Google, with no luck. A: Try nx.draw(G, node_size=size), where size can be a scalar or an array of length equal to the number of nodes.
Change Node Display Size in Networkx
I am not using GraphViz because I am having problems with making it play nice with Networkx. I know this is weird, but I've tried many suggestions to fix this problem, but I just seem to have some of the worst luck in the world. Therefore the problem that I have must be solved withing Networkx without using GraphViz. My program reads a document and and tries to draw something of a MindMap based on the contents of the document. However, Networkx seems to have a default size when it comes to actually drawing the node. This is bad for me because a lot of text goes into each of my nodes. I need a way to increase the display-size of my nodes (arbitrarily, based on the size of the text that belongs in that node). I have tried looking at the Networkx site, other questions on SO and about 200 search results from Google, with no luck.
[ "Try nx.draw(G, node_size=size), where size can be a scalar or an array of length equal to the number of nodes.\n" ]
[ 31 ]
[]
[]
[ "networkx", "python" ]
stackoverflow_0002383121_networkx_python.txt
Q: key/value (general) and tokyo cabinet (python tc-specific) question i have been in the RDBMS world for many years now but wish to explore the whole nosql movement. so here's my first question: is it bad practice to have the possibility of duplicate keys? for example, an address book keyed off of last name (most probably search item?) could have multiple entities. is it bad practice to use the last name then? is the key supposed to be the most "searchable" definition of the entity? are there any resources for "best practices" in this whole new world (for me)? i'm intrigued by tokyo cabinet (and specifically the tc interface) but don't know how to iterate through different entities that have the same key (e.g. see above). i can only get the first entity. anyway, thanks in advance for the help A: This depend on no-sql implementation. Cassandra, for example, allows range queries, so you could model data to do queries on last name, or with full name (starting with last name, then first name). Beyond this, many simpler key-value stores would indeed require you to store a list structure (or such) for multi-valued entries. Whether this is feasible or not depends on expected number of "duplicates" -- with last name, number could be rather high I presume, so it does not sound like an ideal model for many cases. A: In a key-value store you cannot have duplicate keys, there's a single value behind a key. To have duplicate keys you can use the B+ Tree database in Tokyo Cabinet that has values ordered and allows duplicate (you can acces them by going to the first item with that key and iterating). Not all problems are easily solved by a key-value store as you need the key to retrieve the item. Maybe something like MongoDB is more appropriate as allows more complex queries.
key/value (general) and tokyo cabinet (python tc-specific) question
i have been in the RDBMS world for many years now but wish to explore the whole nosql movement. so here's my first question: is it bad practice to have the possibility of duplicate keys? for example, an address book keyed off of last name (most probably search item?) could have multiple entities. is it bad practice to use the last name then? is the key supposed to be the most "searchable" definition of the entity? are there any resources for "best practices" in this whole new world (for me)? i'm intrigued by tokyo cabinet (and specifically the tc interface) but don't know how to iterate through different entities that have the same key (e.g. see above). i can only get the first entity. anyway, thanks in advance for the help
[ "This depend on no-sql implementation. Cassandra, for example, allows range queries, so you could model data to do queries on last name, or with full name (starting with last name, then first name).\nBeyond this, many simpler key-value stores would indeed require you to store a list structure (or such) for multi-valued entries. Whether this is feasible or not depends on expected number of \"duplicates\" -- with last name, number could be rather high I presume, so it does not sound like an ideal model for many cases.\n", "In a key-value store you cannot have duplicate keys, there's a single value behind a key. To have duplicate keys you can use the B+ Tree database in Tokyo Cabinet that has values ordered and allows duplicate (you can acces them by going to the first item with that key and iterating).\nNot all problems are easily solved by a key-value store as you need the key to retrieve the item. Maybe something like MongoDB is more appropriate as allows more complex queries.\n" ]
[ 1, 0 ]
[]
[]
[ "python", "tokyo_cabinet" ]
stackoverflow_0002068473_python_tokyo_cabinet.txt
Q: Why aren't there any dates in the Netflix.com NewWatchInstantlyRSS feed entries (when parsed with feedparser)? The output from the following: import feedparser d = feedparser.parse('http://www.netflix.com/NewWatchInstantlyRSS') d.entries[177].keys() is: ['summary_detail', 'links', 'title', 'summary', 'guidislink', 'title_detail', 'link', 'id'] According to http://feedparser.org/docs/common-rss-elements.html, there should be a "date" element in the entries. A clue perhaps is that when I open http://www.netflix.com/NewWatchInstantlyRSS on Firefox or Safari (on Mac OS X), I don't see any dates. (Actually Safari puts the date & time that I opened the feed beside each element.) But somehow Google Reader gets the unique dates for each element. (That's the reason I chose entry 177 above--that's the index to 'Dare', which is the first entry for today according to Google Reader, which shows "8:32 AM" beside it.) Is there something I'm not understanding about RSS? Am I missing some kind of cross-reference feed with the dates? I've combed through all the entries in the feed and in several entries and don't see anything that might point to a different URL or any kind of dates. A: IF you look at the raw source of the RSS feed at http://www.netflix.com/NewWatchInstantlyRSS (Open in a web browser and view the source) you'll see they did not include a date element. There SHOULD be, but there is not. EDIT: Sorry I didn't read your question completely. I don't know where Google is getting its value for the date. I put the feed in google as well and I'm getting 10:32 AM Today for Dare which is not equal to yours no matter what timezone. I would say their own cache as to when they retrieved the updated feed and perhaps they have different servers which would explain our differences. There's no special properties of RSS feeds to get this value when it simply isn't there. IF you need it. I suggest using a method similar to what I believe Google is using.
Why aren't there any dates in the Netflix.com NewWatchInstantlyRSS feed entries (when parsed with feedparser)?
The output from the following: import feedparser d = feedparser.parse('http://www.netflix.com/NewWatchInstantlyRSS') d.entries[177].keys() is: ['summary_detail', 'links', 'title', 'summary', 'guidislink', 'title_detail', 'link', 'id'] According to http://feedparser.org/docs/common-rss-elements.html, there should be a "date" element in the entries. A clue perhaps is that when I open http://www.netflix.com/NewWatchInstantlyRSS on Firefox or Safari (on Mac OS X), I don't see any dates. (Actually Safari puts the date & time that I opened the feed beside each element.) But somehow Google Reader gets the unique dates for each element. (That's the reason I chose entry 177 above--that's the index to 'Dare', which is the first entry for today according to Google Reader, which shows "8:32 AM" beside it.) Is there something I'm not understanding about RSS? Am I missing some kind of cross-reference feed with the dates? I've combed through all the entries in the feed and in several entries and don't see anything that might point to a different URL or any kind of dates.
[ "IF you look at the raw source of the RSS feed at http://www.netflix.com/NewWatchInstantlyRSS (Open in a web browser and view the source) you'll see they did not include a date element. There SHOULD be, but there is not.\nEDIT: Sorry I didn't read your question completely. I don't know where Google is getting its value for the date. I put the feed in google as well and I'm getting 10:32 AM Today for Dare which is not equal to yours no matter what timezone. I would say their own cache as to when they retrieved the updated feed and perhaps they have different servers which would explain our differences.\nThere's no special properties of RSS feeds to get this value when it simply isn't there. IF you need it. I suggest using a method similar to what I believe Google is using.\n" ]
[ 1 ]
[]
[]
[ "feedparser", "netflix", "python", "rss" ]
stackoverflow_0002384056_feedparser_netflix_python_rss.txt
Q: Using Numpy to find the average distance in a set of points I have an array of points in unknown dimensional space, such as: data=numpy.array( [[ 115, 241, 314], [ 153, 413, 144], [ 535, 2986, 41445]]) and I would like to find the average euclidean distance between all points. Please note that I have over 20,000 points, so I would like to do this as efficiently as possible. Thanks. A: If you have access to scipy, you could try the following: scipy.spatial.distance.cdist(data,data) A: Well, I don't think that there is a super fast way to do this, but this should do it: tot = 0. for i in xrange(data.shape[0]-1): tot += ((((data[i+1:]-data[i])**2).sum(1))**.5).sum() avg = tot/((data.shape[0]-1)*(data.shape[0])/2.) A: There's no getting around the number of evaluations: Sum[n-i, {i, 0, n}] = http://www.equationsheet.com/latexrender/pictures/27744c0bd81116aa31c138ab38a2aa87.gif But you can save yourself the expense of all those square roots if you can get by with an approximate result. It depends on your needs. If you're going to calculate an average, I would advise you to not try putting all the values into an array before calculating. Just calculate the sum (and sum of squares if you need standard deviation as well) and throw away each value as you calculate it. Since and , I don't know if this means you have to multiply by two somewhere. A: Now that you've stated your goal of finding the outliers, you are probably better off computing the sample mean and, with that, the sample variance, since both those operations will give you an O(nd) operation. With that, you should be able to find outliers (e.g. excluding points further from the mean than some fraction of the std. dev.), and that filtering process should be possible to perform in O(nd) time for a total of O(nd). You might be interested in a refresher on Chebyshev's inequality. A: Is it ever worthwhile to optimize without a working solution? Also, computation of a distance matrix over the entire data set rarely needs to be fast because you only do it once--when you need to know a distance between two points, you just look it up, it's already calculated. So if you don't have a place to start, here's one. If you want to do this in Numpy without the need to write any inline fortran or C, that should be no problem, though perhaps you want to include this small vector-based virtual machine called "numexpr" (available on PyPI, trivial to intall) which in this case gave a 5x performance boost versus Numpy alone. Below i've calculated a distance matrix for 10,000 points in 2D space (a 10K x 10k matrix giving the distance between all 10k points). This took 59 seconds on my MBP. import numpy as NP import numexpr as NE # data are points in 2D space (x, y)--obviously, this code can accept data of any dimension x = NP.random.randint(0, 10, 10000) y = NP.random.randint(0, 10, 10000) fnx = lambda q : q - NP.reshape(q, (len(q), 1)) delX = fnx(x) delY = fnx(y) dist_mat = NE.evaluate("(delX**2 + delY**2)**0.5") A: If you want a fast and inexact solution, you could probably adapt the Fast Multipole Method algorithm. Points that are separated by a small distance have a smaller contribution to the final average distance, so it would make sense to group points into clusters and compare the clusters distances.
Using Numpy to find the average distance in a set of points
I have an array of points in unknown dimensional space, such as: data=numpy.array( [[ 115, 241, 314], [ 153, 413, 144], [ 535, 2986, 41445]]) and I would like to find the average euclidean distance between all points. Please note that I have over 20,000 points, so I would like to do this as efficiently as possible. Thanks.
[ "If you have access to scipy, you could try the following:\nscipy.spatial.distance.cdist(data,data)\n", "Well, I don't think that there is a super fast way to do this, but this should do it:\ntot = 0.\n\nfor i in xrange(data.shape[0]-1):\n tot += ((((data[i+1:]-data[i])**2).sum(1))**.5).sum()\n\navg = tot/((data.shape[0]-1)*(data.shape[0])/2.)\n\n", "There's no getting around the number of evaluations: \nSum[n-i, {i, 0, n}] = http://www.equationsheet.com/latexrender/pictures/27744c0bd81116aa31c138ab38a2aa87.gif \nBut you can save yourself the expense of all those square roots if you can get by with an approximate result. It depends on your needs.\nIf you're going to calculate an average, I would advise you to not try putting all the values into an array before calculating. Just calculate the sum (and sum of squares if you need standard deviation as well) and throw away each value as you calculate it.\nSince \n and \n, I don't know if this means you have to multiply by two somewhere.\n", "Now that you've stated your goal of finding the outliers, you are probably better off computing the sample mean and, with that, the sample variance, since both those operations will give you an O(nd) operation. With that, you should be able to find outliers (e.g. excluding points further from the mean than some fraction of the std. dev.), and that filtering process should be possible to perform in O(nd) time for a total of O(nd).\nYou might be interested in a refresher on Chebyshev's inequality.\n", "Is it ever worthwhile to optimize without a working solution? Also, computation of a distance matrix over the entire data set rarely needs to be fast because you only do it once--when you need to know a distance between two points, you just look it up, it's already calculated. \nSo if you don't have a place to start, here's one. If you want to do this in Numpy without the need to write any inline fortran or C, that should be no problem, though perhaps you want to include this small vector-based virtual machine called \"numexpr\" (available on PyPI, trivial to intall) which in this case gave a 5x performance boost versus Numpy alone.\nBelow i've calculated a distance matrix for 10,000 points in 2D space (a 10K x 10k matrix giving the distance between all 10k points). This took 59 seconds on my MBP.\nimport numpy as NP\nimport numexpr as NE\n\n# data are points in 2D space (x, y)--obviously, this code can accept data of any dimension\nx = NP.random.randint(0, 10, 10000)\ny = NP.random.randint(0, 10, 10000)\nfnx = lambda q : q - NP.reshape(q, (len(q), 1))\ndelX = fnx(x)\ndelY = fnx(y)\ndist_mat = NE.evaluate(\"(delX**2 + delY**2)**0.5\")\n\n", "If you want a fast and inexact solution, you could probably adapt the Fast Multipole Method algorithm.\nPoints that are separated by a small distance have a smaller contribution to the final average distance, so it would make sense to group points into clusters and compare the clusters distances.\n" ]
[ 13, 5, 4, 4, 4, 1 ]
[]
[]
[ "algorithm", "distance", "numpy", "performance", "python" ]
stackoverflow_0002383645_algorithm_distance_numpy_performance_python.txt
Q: Why is '' > 0 True in Python 2? In Python 2.x: >>> '' > 0 True Why is that? A: The original design motivation for allowing order-comparisons of arbitrary objects was to allow sorting of heterogeneous lists -- usefully, that would put all strings next to each other in alphabetical order, and all numbers next to each other in numerical order, although which of the two blocks came first was not guaranteed by the language. For example, this allowed getting only unique items in any list (even one with non-hashable items) in O(N log N) worst-case time Over the years, this pragmatic arrangement eroded. The first crack came when the ability to order-compare complex numbers was taken away, quite a few versions ago. Suddenly, the ability to sort any list disappeared: it did not apply any more if the list contained complex numbers, possibly together with items of other types. Then Guido started disliking heterogeneous lists more generally, and thus started thinking that it didn't really matter if such lists could be usefully sorted or not... because such lists should not exist in the first place, according to his new thinking. He didn't do anything to forbid them, but was not inclined to accept any compromises to support them either. Note that both changes move the balance a little bit away from the "practicality beats purity" item of the Zen of Python (which was written earlier, back when complex numbers still could be order-compared ;-) – a bit more purity, a bit less practicality. Nevertheless the ability to order-compare two arbitrary objects (as long as neither was a complex number ;-) remained for a long time, because around that same time Guido started really insisting on maintaining strong backwards compatibility (a shift that's both practical and pure ;-). So, it's only in Python 3, which explicitly and deliberately removed the constraint of strong backwards compatibility to allow some long-desired but backwards incompatible enhancements (especially simplifications and removal of obsolete, redundant way to perform certain tasks), that order comparison of instances of different types became an error. So this historical and philosophical treatise is basically the only way to truly respond to your "why" question...! :-) A: from https://docs.python.org/2.7/tutorial/datastructures.html#id1 Note that comparing objects of different types is legal. The outcome is deterministic but arbitrary: the types are ordered by their name. Thus, a list is always smaller than a string, a string is always smaller than a tuple, etc. [1] Mixed numeric types are compared according to their numeric value, so 0 equals 0.0, etc.
Why is '' > 0 True in Python 2?
In Python 2.x: >>> '' > 0 True Why is that?
[ "The original design motivation for allowing order-comparisons of arbitrary objects was to allow sorting of heterogeneous lists -- usefully, that would put all strings next to each other in alphabetical order, and all numbers next to each other in numerical order, although which of the two blocks came first was not guaranteed by the language. For example, this allowed getting only unique items in any list (even one with non-hashable items) in O(N log N) worst-case time\nOver the years, this pragmatic arrangement eroded. The first crack came when the ability to order-compare complex numbers was taken away, quite a few versions ago. Suddenly, the ability to sort any list disappeared: it did not apply any more if the list contained complex numbers, possibly together with items of other types. Then Guido started disliking heterogeneous lists more generally, and thus started thinking that it didn't really matter if such lists could be usefully sorted or not... because such lists should not exist in the first place, according to his new thinking. He didn't do anything to forbid them, but was not inclined to accept any compromises to support them either.\nNote that both changes move the balance a little bit away from the \"practicality beats purity\" item of the Zen of Python (which was written earlier, back when complex numbers still could be order-compared ;-) – a bit more purity, a bit less practicality.\nNevertheless the ability to order-compare two arbitrary objects (as long as neither was a complex number ;-) remained for a long time, because around that same time Guido started really insisting on maintaining strong backwards compatibility (a shift that's both practical and pure ;-).\nSo, it's only in Python 3, which explicitly and deliberately removed the constraint of strong backwards compatibility to allow some long-desired but backwards incompatible enhancements (especially simplifications and removal of obsolete, redundant way to perform certain tasks), that order comparison of instances of different types became an error.\nSo this historical and philosophical treatise is basically the only way to truly respond to your \"why\" question...! :-)\n", "from https://docs.python.org/2.7/tutorial/datastructures.html#id1\n\nNote that comparing objects of different types is legal. The outcome\n is deterministic but arbitrary: the types are ordered by their name.\n Thus, a list is always smaller than a string, a string is always\n smaller than a tuple, etc. [1] Mixed numeric types are compared\n according to their numeric value, so 0 equals 0.0, etc.\n\n" ]
[ 92, 23 ]
[]
[]
[ "logic", "operators", "python", "python_2.x" ]
stackoverflow_0002384078_logic_operators_python_python_2.x.txt
Q: python: _winreg problem the windows registry may contain keys whose names with embedded nulls when i call _winreg.OpenKey(key, subkey_string_with_embbeded_null) i get the following error: TypeError: OpenKey() argument 2 must be string without null bytes or None, not str Q1: is the meaning of the error that python _winreg module has a limitation that it cannot open keys whose names have embbeded nulls? Q2: how do i get around this limitation? A: Q1: right. Q2: download and install win32all.
python: _winreg problem
the windows registry may contain keys whose names with embedded nulls when i call _winreg.OpenKey(key, subkey_string_with_embbeded_null) i get the following error: TypeError: OpenKey() argument 2 must be string without null bytes or None, not str Q1: is the meaning of the error that python _winreg module has a limitation that it cannot open keys whose names have embbeded nulls? Q2: how do i get around this limitation?
[ "Q1: right.\nQ2: download and install win32all.\n" ]
[ 4 ]
[]
[]
[ "python", "winreg" ]
stackoverflow_0002384064_python_winreg.txt
Q: Crontab job does not start... ideas? thanks for helping me setting my cron jobs, crontab has really been a gold mine for me. Unfortunately I have a problem, and have no idea what so ever what it might be... basically a job does not start while the neighbour jobs do. I'll explain This is my crontabs job list: */10 * * * * python /webapps/foo/manage.py fetch_articles */10 * * * * python /webapps/bar/manage.py fetch_books I wrote them as they are in a file and stored them using crontab /path/to/file . Checked with crontab -l and the jobs are there. The strange thing is that 1 of these executes every 10 minutes normally... but the other one does not. I tried typing in the command manually, and it works fine without a problem. Does anyone have suggestions? Help would be much appreciated, thanks guys. Update: I've been in the system log files and I found this: Mar 5 02:50:01 localhost CRON[21652]: (root) CMD (python /webapps/foo/manage.py fetch_books) Does this mean crontab is calling the job fine? Thanks for your replies guys! FIXED IT! thank you very much everyone!! The problem was that the script silently failed, I believe it's due to the PYTHON_PATH changing due to where the script is called from... I'm entirely sure. A: Cron always runs in an environment different to what you think :-) I always have my cronjobs set up like: */10 * * * * ( date ; python /webapps/foo/manage.py fetch_articles ) >>/tmp/fetch.out 2>&1 to ensure that there's something logged that I can look at. This will narrow your problem down to either: cron, if the temp file doesn't appear; or your script, if it does appear. And, in the latter case, hopefully there'll be some output you can debug. If not, put output in there. One way to do that is to put: set -x at the top of the script which will cause all lines to be output before execution. All of my scripts tend to start: #!/bin/bash #set -x so I can just uncomment that second line while debugging. A: From the crontab manpage: BUGS Although cron requires that each entry in a crontab end in a newline character, neither the crontab command nor the cron daemon will detect this error. Instead, the crontab will appear to load normally. However, the command will never run. The best choice is to ensure that your crontab has a blank line at the end. (my emphasis). A: I think ~unutbu's answer is probably correct if it's the second job that isn't running. However another thing to check is whether /webapps/bar/manage.py requires exclusive access to any resources, eg network sockets/tempfiles etc. Since you are starting 2 processes at the same time, you may be triggering a race condition.
Crontab job does not start... ideas?
thanks for helping me setting my cron jobs, crontab has really been a gold mine for me. Unfortunately I have a problem, and have no idea what so ever what it might be... basically a job does not start while the neighbour jobs do. I'll explain This is my crontabs job list: */10 * * * * python /webapps/foo/manage.py fetch_articles */10 * * * * python /webapps/bar/manage.py fetch_books I wrote them as they are in a file and stored them using crontab /path/to/file . Checked with crontab -l and the jobs are there. The strange thing is that 1 of these executes every 10 minutes normally... but the other one does not. I tried typing in the command manually, and it works fine without a problem. Does anyone have suggestions? Help would be much appreciated, thanks guys. Update: I've been in the system log files and I found this: Mar 5 02:50:01 localhost CRON[21652]: (root) CMD (python /webapps/foo/manage.py fetch_books) Does this mean crontab is calling the job fine? Thanks for your replies guys! FIXED IT! thank you very much everyone!! The problem was that the script silently failed, I believe it's due to the PYTHON_PATH changing due to where the script is called from... I'm entirely sure.
[ "Cron always runs in an environment different to what you think :-)\nI always have my cronjobs set up like:\n*/10 * * * * ( date ; python /webapps/foo/manage.py fetch_articles ) >>/tmp/fetch.out 2>&1\n\nto ensure that there's something logged that I can look at.\nThis will narrow your problem down to either:\n\ncron, if the temp file doesn't appear; or\nyour script, if it does appear.\n\nAnd, in the latter case, hopefully there'll be some output you can debug. If not, put output in there.\nOne way to do that is to put:\nset -x\n\nat the top of the script which will cause all lines to be output before execution. All of my scripts tend to start:\n#!/bin/bash\n#set -x\n\nso I can just uncomment that second line while debugging.\n", "From the crontab manpage:\n\nBUGS\n Although cron requires that each entry in a crontab end in a\n newline character,\n neither the crontab command nor the cron daemon will detect this\n error. Instead,\n the crontab will appear to load normally. However, the command\n will never run.\n The best choice is to ensure that your crontab has a blank line at\n the end.\n\n(my emphasis). \n", "I think ~unutbu's answer is probably correct if it's the second job that isn't running.\nHowever another thing to check is whether /webapps/bar/manage.py requires exclusive access to any resources, eg network sockets/tempfiles etc. Since you are starting 2 processes at the same time, you may be triggering a race condition.\n" ]
[ 6, 4, 1 ]
[]
[]
[ "cron", "crontab", "linux", "python", "ubuntu" ]
stackoverflow_0002384225_cron_crontab_linux_python_ubuntu.txt
Q: Python in SU cron gives different output than manually execution Ubuntu Server 9.10, Here is my file, test.py import commands blkid = commands.getoutput('blkid') print blkid When I manually run (as SU) this: python test.py I get the output of the blkid as expected: /dev/sda1: UUID="3f0ac5bb-f0da-4574-81f5-77844530b561" TYPE="ext4" /dev/sda5: UUID="67df0e7c-74fb-47dd-8520-ad720fbed67d" TYPE="swap" /dev/sdb1: UUID="85466892-8dae-461c-95da-b8f91c2e766b" TYPE="ext3" /dev/sdc1: UUID="91b84635-21c2-4d9a-84f8-2bbaab16d41f" SEC_TYPE="ext2" TYPE="ext3" /dev/sdd1: UUID="6a52c830-0029-4154-80cb-f17274eb6fed" SEC_TYPE="ext2" TYPE="ext3" However when I add this to my SU crontab: * * * * * python /home/myusername/test.py > /home/myusername/output The content of output becomes: sh: blkid: not found What am I missing here? Is the Python commands module only for certain SH-specific commands? I'm just try to run a system command and capture the output into a variable that I can parse. A: The problem is probably with your $PATH versus root's (os.environ['PATH'] if you're looking at it in Python rather than shell;-). root's PATH is typically very conservative (it would be risky for it NOT to be!) and since you're running blkid without specifying an absolute path that may easily mean that it's on your PATH but not root's. So do which blkid as yourself at a shell prompt, sudo su or anyway become root, and echo $PATH -- you can rapidly verify the problem. Then you fix it by using blkid's absolute complete path in the getoutput call rather than just the bare identifier blkid as you're doing now. A: The environment (and PATH) of a cron job is not necessarily the same as your login shell.
Python in SU cron gives different output than manually execution
Ubuntu Server 9.10, Here is my file, test.py import commands blkid = commands.getoutput('blkid') print blkid When I manually run (as SU) this: python test.py I get the output of the blkid as expected: /dev/sda1: UUID="3f0ac5bb-f0da-4574-81f5-77844530b561" TYPE="ext4" /dev/sda5: UUID="67df0e7c-74fb-47dd-8520-ad720fbed67d" TYPE="swap" /dev/sdb1: UUID="85466892-8dae-461c-95da-b8f91c2e766b" TYPE="ext3" /dev/sdc1: UUID="91b84635-21c2-4d9a-84f8-2bbaab16d41f" SEC_TYPE="ext2" TYPE="ext3" /dev/sdd1: UUID="6a52c830-0029-4154-80cb-f17274eb6fed" SEC_TYPE="ext2" TYPE="ext3" However when I add this to my SU crontab: * * * * * python /home/myusername/test.py > /home/myusername/output The content of output becomes: sh: blkid: not found What am I missing here? Is the Python commands module only for certain SH-specific commands? I'm just try to run a system command and capture the output into a variable that I can parse.
[ "The problem is probably with your $PATH versus root's (os.environ['PATH'] if you're looking at it in Python rather than shell;-). root's PATH is typically very conservative (it would be risky for it NOT to be!) and since you're running blkid without specifying an absolute path that may easily mean that it's on your PATH but not root's.\nSo do which blkid as yourself at a shell prompt, sudo su or anyway become root, and echo $PATH -- you can rapidly verify the problem. Then you fix it by using blkid's absolute complete path in the getoutput call rather than just the bare identifier blkid as you're doing now.\n", "The environment (and PATH) of a cron job is not necessarily the same as your login shell.\n" ]
[ 2, 0 ]
[]
[]
[ "cron", "crontab", "python", "sudo" ]
stackoverflow_0002384327_cron_crontab_python_sudo.txt
Q: py2app Not Finding BeautifulSoup I have a script that uses BeautifulSoup that I want to make into a standalone app using py2app. When I run the app made by py2app I get an error saying that the module BeautifulSoup could not be found. My sys.path has '/Library/Python/2.6/site-packages/BeautifulSoup-3.1.0.1-py2.6.egg' so it seems like it should be there, any advice? A: Ppy2app doesn't work with python eggs. You need to extract the contents of the egg (a zip file), or install BeuatifulSoup from a different source. I Believe BeautifulSoup is 1 source file, so you could just copy it into you app folder.
py2app Not Finding BeautifulSoup
I have a script that uses BeautifulSoup that I want to make into a standalone app using py2app. When I run the app made by py2app I get an error saying that the module BeautifulSoup could not be found. My sys.path has '/Library/Python/2.6/site-packages/BeautifulSoup-3.1.0.1-py2.6.egg' so it seems like it should be there, any advice?
[ "Ppy2app doesn't work with python eggs. You need to extract the contents of the egg (a zip file), or install BeuatifulSoup from a different source. I Believe BeautifulSoup is 1 source file, so you could just copy it into you app folder.\n" ]
[ 1 ]
[]
[]
[ "beautifulsoup", "py2app", "python" ]
stackoverflow_0002384296_beautifulsoup_py2app_python.txt
Q: How to get the Python date object for last Wednesday Using Python I would like to find the date object for last Wednesday. I can figure out where today is on the calendar using isocalendar, and determine whether or not we need to go back a week to get to the previous Wednesday. However, I can't figure out how to create a new date object with that information. Essentially, I need to figure out how to create a date from an iso calendar tuple. from datetime import date today = date.today() if today.isocalendar()[2] > 3: #day of week starting with Monday #get date for Wednesday of last week else: #get date for Wednesday of this current week A: I think you want this. If the specified day is a Wednesday it will give you that day. from datetime import date from datetime import timedelta from calendar import WEDNESDAY today = date.today() offset = (today.weekday() - WEDNESDAY) % 7 last_wednesday = today - timedelta(days=offset) Example, the last wednesday for every day in March: for x in xrange(1, 32): today = date(year=2010, month=3, day=x) offset = (today.weekday() - WEDNESDAY) % 7 last_wednesday = today - timedelta(days=offset) print last_wednesday A: Assuming that "last Wednesday" can't be the same as "today", this shows how to do it for any day of the week: >>> from datetime import date >>> from datetime import timedelta >>> >>> MON, TUE, WED, THU, FRI, SAT, SUN = range(7) >>> >>> def lastWday(adate, w): ... """Mon:w=0, Sun:w=6""" ... delta = (adate.weekday() + 6 - w) % 7 + 1 ... return adate - timedelta(days=delta) ... >>> for x in range(8, 16): ... start = date(year=2010, month=3, day=x) ... prev = lastWday(start, WED) ... print start, start.weekday(), prev, prev.weekday() ... 2010-03-08 0 2010-03-03 2 2010-03-09 1 2010-03-03 2 2010-03-10 2 2010-03-03 2 2010-03-11 3 2010-03-10 2 2010-03-12 4 2010-03-10 2 2010-03-13 5 2010-03-10 2 2010-03-14 6 2010-03-10 2 2010-03-15 0 2010-03-10 2
How to get the Python date object for last Wednesday
Using Python I would like to find the date object for last Wednesday. I can figure out where today is on the calendar using isocalendar, and determine whether or not we need to go back a week to get to the previous Wednesday. However, I can't figure out how to create a new date object with that information. Essentially, I need to figure out how to create a date from an iso calendar tuple. from datetime import date today = date.today() if today.isocalendar()[2] > 3: #day of week starting with Monday #get date for Wednesday of last week else: #get date for Wednesday of this current week
[ "I think you want this. If the specified day is a Wednesday it will give you that day.\nfrom datetime import date\nfrom datetime import timedelta\nfrom calendar import WEDNESDAY\n\ntoday = date.today()\noffset = (today.weekday() - WEDNESDAY) % 7\nlast_wednesday = today - timedelta(days=offset)\n\nExample, the last wednesday for every day in March:\nfor x in xrange(1, 32):\n today = date(year=2010, month=3, day=x)\n offset = (today.weekday() - WEDNESDAY) % 7\n last_wednesday = today - timedelta(days=offset)\n\n print last_wednesday\n\n", "Assuming that \"last Wednesday\" can't be the same as \"today\", this shows how to do it for any day of the week:\n>>> from datetime import date\n>>> from datetime import timedelta\n>>>\n>>> MON, TUE, WED, THU, FRI, SAT, SUN = range(7)\n>>>\n>>> def lastWday(adate, w):\n... \"\"\"Mon:w=0, Sun:w=6\"\"\"\n... delta = (adate.weekday() + 6 - w) % 7 + 1\n... return adate - timedelta(days=delta)\n...\n>>> for x in range(8, 16):\n... start = date(year=2010, month=3, day=x)\n... prev = lastWday(start, WED)\n... print start, start.weekday(), prev, prev.weekday()\n...\n2010-03-08 0 2010-03-03 2\n2010-03-09 1 2010-03-03 2\n2010-03-10 2 2010-03-03 2\n2010-03-11 3 2010-03-10 2\n2010-03-12 4 2010-03-10 2\n2010-03-13 5 2010-03-10 2\n2010-03-14 6 2010-03-10 2\n2010-03-15 0 2010-03-10 2\n\n" ]
[ 58, 9 ]
[ "read http://docs.python.org/library/datetime.html\nWrite your own function using date2 = date1 - timedelta(days=1) and date.isoweekday() iterating over previous days while isoweek is not equal to 3(Wednesday)\n", "I'm not sure if this meets your requirements, but it should get you the Wednesday closest to a given date the Wednesday in the same week as the given date, assuming weeks start on Monday:\nimport datetime\n\ndef find_closest_wednesday(date):\n WEDNESDAY = 3\n year, week, day = date.isocalendar()\n delta = datetime.timedelta(days=WEDNESDAY-day)\n return date + delta\n\ntoday = datetime.date.today()\nprint 'Today: ', today\nprint 'Closest Wendesday: ', find_closest_wednesday(today)\n\n" ]
[ -1, -1 ]
[ "date", "datetime", "python" ]
stackoverflow_0002381786_date_datetime_python.txt
Q: Sqlalchemy - Can we use date comparison in relation definition? I have this mapper defined: mapper(Resource, resource_table, properties = {'type' : relation(ResourceType,lazy = False), 'groups' : relation(Group, secondary = model.tables['resource_group'], backref = 'resources'), 'parent' : relation(Relation, uselist=False, primaryjoin = and_(relation_table.c.res_id == resource_table.c.res_id, relation_table.c.end_date > datetime.now())), 'children' : relation(Relation, primaryjoin = and_(relation_table.c.parent_id == resource_table.c.res_id, relation_table.c.end_date > func.now()))}) But for some reason, if I create a new row in the relation table and change the end_date of the old row in the relation to an old date, the property parent is not updated. Also if a reload the resource row, the old relation with the old date is displayed, so I am pretty sure it has to do with the date comparison in the mapper. If I replace the end_date by a flag column string or integer and do a comparison on the flag I get the proper behaviour, but I do want to use dates. Any help is welcome. Thanks, Richard Lopes A: I have actually found what was wrong. The relation is actually working. The problem was solved by setting the end_date to something like datetime.now() - 1 second, so it happens before the resource is actually refreshed by SQLAlchemy. A milliseconds issue I suppose. Richard Lopes
Sqlalchemy - Can we use date comparison in relation definition?
I have this mapper defined: mapper(Resource, resource_table, properties = {'type' : relation(ResourceType,lazy = False), 'groups' : relation(Group, secondary = model.tables['resource_group'], backref = 'resources'), 'parent' : relation(Relation, uselist=False, primaryjoin = and_(relation_table.c.res_id == resource_table.c.res_id, relation_table.c.end_date > datetime.now())), 'children' : relation(Relation, primaryjoin = and_(relation_table.c.parent_id == resource_table.c.res_id, relation_table.c.end_date > func.now()))}) But for some reason, if I create a new row in the relation table and change the end_date of the old row in the relation to an old date, the property parent is not updated. Also if a reload the resource row, the old relation with the old date is displayed, so I am pretty sure it has to do with the date comparison in the mapper. If I replace the end_date by a flag column string or integer and do a comparison on the flag I get the proper behaviour, but I do want to use dates. Any help is welcome. Thanks, Richard Lopes
[ "I have actually found what was wrong.\nThe relation is actually working.\nThe problem was solved by setting the end_date to something like datetime.now() - 1 second, so it happens before the resource is actually refreshed by SQLAlchemy.\nA milliseconds issue I suppose.\nRichard Lopes\n" ]
[ 0 ]
[]
[]
[ "database", "mapper", "orm", "python", "sqlalchemy" ]
stackoverflow_0002384438_database_mapper_orm_python_sqlalchemy.txt
Q: SQLAlchemy - Problem with an association table and dates in primary join I am working on defining my mapping with SQLAlchemy and I am pretty much done except one thing. I have a 'resource' object and an association table 'relation' with several properties and a relationship between 2 resources. What I have been trying to do almost successfully so far, is to provide on the resource object 2 properties: parent and children to traverse the tree stored by the association table. A relation between 2 properties only last for a while, so there is a start and end date. Only one resource can be the parent of another resource at a time. My problem is that if I expire one relation and create a new one, the parent property is not refreshed. I am thinking maybe there an issue with the primaryjoin for the parent property of resource. Here is some code: resource_table = model.tables['resource'] relation_table = model.tables['resource_relation'] mapper(Resource, resource_table, properties = { 'type' : relation(ResourceType,lazy = False), 'groups' : relation(Group, secondary = model.tables['resource_group'], backref = 'resources'), 'parent' : relation(Relation, uselist=False, primaryjoin = and_( relation_table.c.res_id == resource_table.c.res_id, relation_table.c.end_date > func.now())), 'children' : relation(Relation, primaryjoin = and_( relation_table.c.parent_id == resource_table.c.res_id, relation_table.c.end_date > func.now())) } ) mapper(Relation, relation_table, properties = { 'resource' : relation(Resource, primaryjoin = (relation_table.c.res_id == resource_table.c.res_id)), 'parent' : relation(Resource, primaryjoin = (relation_table.c.parent_id == resource_table.c.res_id)) } ) oldrelation = resource.parent oldrelation.end_date = datetime.today() relation = self.createRelation(parent, resource) # Here the relation object has not replaced oldrelation in the resource object Any idea ? Thanks, Richard Lopes A: Consider using >= instead of > in date comparison.
SQLAlchemy - Problem with an association table and dates in primary join
I am working on defining my mapping with SQLAlchemy and I am pretty much done except one thing. I have a 'resource' object and an association table 'relation' with several properties and a relationship between 2 resources. What I have been trying to do almost successfully so far, is to provide on the resource object 2 properties: parent and children to traverse the tree stored by the association table. A relation between 2 properties only last for a while, so there is a start and end date. Only one resource can be the parent of another resource at a time. My problem is that if I expire one relation and create a new one, the parent property is not refreshed. I am thinking maybe there an issue with the primaryjoin for the parent property of resource. Here is some code: resource_table = model.tables['resource'] relation_table = model.tables['resource_relation'] mapper(Resource, resource_table, properties = { 'type' : relation(ResourceType,lazy = False), 'groups' : relation(Group, secondary = model.tables['resource_group'], backref = 'resources'), 'parent' : relation(Relation, uselist=False, primaryjoin = and_( relation_table.c.res_id == resource_table.c.res_id, relation_table.c.end_date > func.now())), 'children' : relation(Relation, primaryjoin = and_( relation_table.c.parent_id == resource_table.c.res_id, relation_table.c.end_date > func.now())) } ) mapper(Relation, relation_table, properties = { 'resource' : relation(Resource, primaryjoin = (relation_table.c.res_id == resource_table.c.res_id)), 'parent' : relation(Resource, primaryjoin = (relation_table.c.parent_id == resource_table.c.res_id)) } ) oldrelation = resource.parent oldrelation.end_date = datetime.today() relation = self.createRelation(parent, resource) # Here the relation object has not replaced oldrelation in the resource object Any idea ? Thanks, Richard Lopes
[ "Consider using >= instead of > in date comparison.\n" ]
[ 0 ]
[]
[]
[ "database", "mapping", "orm", "python", "sqlalchemy" ]
stackoverflow_0002377220_database_mapping_orm_python_sqlalchemy.txt
Q: Why does Django say I haven't set DATABASE_ENGINE yet? I have a Django project, and I'm somewhat of a newbie in it. I have the following PyUnit test trying to save an object into a PostgreSQL database: import unittest from foo.models import ObjectType class DbTest(unittest.TestCase): def testDBConnection(self): object_type = ObjectType() object_type.name = 'Test Object' object_type.description = 'For testing purposes' object_type.save() And my database settings are like this: DATABASE_ENGINE = 'postgresql_psycopg2' DATABASE_NAME = 'FOO' DATABASE_USER = 'username' DATABASE_PASSWORD = 'password' DATABASE_HOST = 'localhost' DATABASE_PORT = '5432' I ran python manage.py syncdb for my project, which worked successfully, so my database should be setup properly. However I get the following error when I try to run the above unit test: File "C:\Python26\lib\site-packages\django\db\backends\dummy\base.py", line 15, in complain raise ImproperlyConfigured, "You haven't set the DATABASE_ENGINE setting yet." ImproperlyConfigured: You haven't set the DATABASE_ENGINE setting yet. Has anyone ever had experience with a problem like this? If so, any advice on where to start? Thanks! A: That's probably because you're running tests directly, i.e. just python testfile.py. This way you effectively bypass all Django mechanisms and use Model classes directly. The downside is, the DB backend isn't set up automatically (by Django, which loads settings.py and connects to the appropriate DB), hence the error you're experiencing. I suppose there is a workaround around this problem, but it requires knowledge of internal Django workings for sure. What you should do, instead, is launch your test via Django's testing framework (check out the documentation). It will take care of setting the DB connection properly, etc. There are also snazzy features like test fixtures. A: Your Django settings file needs to have been loaded before you can import your models. If you can't use Django's testing framework, then perhaps you can use this code in your tests: from django.conf import settings settings.configure( DATABASE_ENGINE='postgresql_psycopg2', DATABASE_NAME='FOO', DATABASE_USER='username', DATABASE_PASSWORD='password', DATABASE_HOST='localhost', DATABASE_PORT='5432', INSTALLED_APPS=('foo',) ) or, if you don't need to be so explicit, then you can probably just do this: import django.core.management from foo import settings django.core.management.setup_environ(settings) A: You should be able to set the environment variable DJANGO_SETTINGS_MODULE=myapp.settings and have that work for standalone scripts. in Linux/bash you'd do: export DJANGO_SETTINGS_MODULE=myapp.settings
Why does Django say I haven't set DATABASE_ENGINE yet?
I have a Django project, and I'm somewhat of a newbie in it. I have the following PyUnit test trying to save an object into a PostgreSQL database: import unittest from foo.models import ObjectType class DbTest(unittest.TestCase): def testDBConnection(self): object_type = ObjectType() object_type.name = 'Test Object' object_type.description = 'For testing purposes' object_type.save() And my database settings are like this: DATABASE_ENGINE = 'postgresql_psycopg2' DATABASE_NAME = 'FOO' DATABASE_USER = 'username' DATABASE_PASSWORD = 'password' DATABASE_HOST = 'localhost' DATABASE_PORT = '5432' I ran python manage.py syncdb for my project, which worked successfully, so my database should be setup properly. However I get the following error when I try to run the above unit test: File "C:\Python26\lib\site-packages\django\db\backends\dummy\base.py", line 15, in complain raise ImproperlyConfigured, "You haven't set the DATABASE_ENGINE setting yet." ImproperlyConfigured: You haven't set the DATABASE_ENGINE setting yet. Has anyone ever had experience with a problem like this? If so, any advice on where to start? Thanks!
[ "That's probably because you're running tests directly, i.e. just python testfile.py. This way you effectively bypass all Django mechanisms and use Model classes directly.\nThe downside is, the DB backend isn't set up automatically (by Django, which loads settings.py and connects to the appropriate DB), hence the error you're experiencing.\nI suppose there is a workaround around this problem, but it requires knowledge of internal Django workings for sure.\nWhat you should do, instead, is launch your test via Django's testing framework (check out the documentation). It will take care of setting the DB connection properly, etc. There are also snazzy features like test fixtures. \n", "Your Django settings file needs to have been loaded before you can import your models. If you can't use Django's testing framework, then perhaps you can use this code in your tests:\nfrom django.conf import settings\nsettings.configure(\n DATABASE_ENGINE='postgresql_psycopg2',\n DATABASE_NAME='FOO',\n DATABASE_USER='username',\n DATABASE_PASSWORD='password',\n DATABASE_HOST='localhost',\n DATABASE_PORT='5432',\n INSTALLED_APPS=('foo',)\n\n)\nor, if you don't need to be so explicit, then you can probably just do this:\nimport django.core.management\nfrom foo import settings\ndjango.core.management.setup_environ(settings)\n\n", "You should be able to set the environment variable DJANGO_SETTINGS_MODULE=myapp.settings and have that work for standalone scripts.\nin Linux/bash you'd do: export DJANGO_SETTINGS_MODULE=myapp.settings\n" ]
[ 3, 2, 2 ]
[]
[]
[ "django", "postgresql", "python" ]
stackoverflow_0001895916_django_postgresql_python.txt
Q: Sqlalchemy file organization Does anyone has any insight on organizing sqlalchemy based projects? I have many tables and classes with foreign keys, and relations. What is everyone doing in terms of separating classes, tables, and mappers ? I am relatively new to the framework, so any help would be appreciated. Example: classA.py # table definition and class A definition classB.py # table definition and class B definition ### model.py import classA,classB map(classA.classA,clasSA.table) map(classB.classB,clasSB.table) Including mappers inside classA, and classB works, but poses cross import issues when building relations.. Maybe I am missing something :) A: Take a look at Pylons project including SA setup. meta.py includes engine and metadata objects models package includes declerative classes (no mapper needed). Inside that package, structure your classes by relavance into modules. Maybe a good example would be reddit source code:) A: There are two features in SQLAlchemy design to avoid cross imports when defining relations: backref argument of relation() allows you to define backward relation. Using strings (model class and their fields names). Unfortunately this works for declarative only, which is not your case. See this chapter in tutorial for more information.
Sqlalchemy file organization
Does anyone has any insight on organizing sqlalchemy based projects? I have many tables and classes with foreign keys, and relations. What is everyone doing in terms of separating classes, tables, and mappers ? I am relatively new to the framework, so any help would be appreciated. Example: classA.py # table definition and class A definition classB.py # table definition and class B definition ### model.py import classA,classB map(classA.classA,clasSA.table) map(classB.classB,clasSB.table) Including mappers inside classA, and classB works, but poses cross import issues when building relations.. Maybe I am missing something :)
[ "Take a look at Pylons project including SA setup.\nmeta.py includes engine and metadata objects\nmodels package includes declerative classes (no mapper needed). Inside that package, structure your classes by relavance into modules. \nMaybe a good example would be reddit source code:)\n", "There are two features in SQLAlchemy design to avoid cross imports when defining relations:\n\nbackref argument of relation() allows you to define backward relation.\nUsing strings (model class and their fields names). Unfortunately this works for declarative only, which is not your case. \n\nSee this chapter in tutorial for more information.\n" ]
[ 3, 1 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0002377549_python_sqlalchemy.txt
Q: pycurl and lot of callback functions I have big URL list, which I have to download in parallel and check one of headers that is returned with each response. I can use CurlMulti for parallelization. I can use /dev/null as fb, because I am not interested in body, only headers. But how can I check each header? To receive header, I must set HEADERFUNCTION callback. I get that. But in this callback function I get only buffer with headers. How can I distinguish one request from another? I don't like the idea of creating as much callback functions as there are URLs. Should I create some class and as much instances of that class? Also not very clever. A: I would use Python's built in httplib and threading modules. I don't see need for a 3rd party module. A: I know you're asking about pycurl, but I find it too hard and unpythonic to use. The API is weird. Here's a twisted example: from twisted.web.client import Agent from twisted.internet import reactor, defer def get_headers(response, url): '''Extract a dict of headers from the response''' return url, dict(response.headers.getAllRawHeaders()) def got_everything(all_headers): '''print results and end program''' print dict(all_headers) reactor.stop() agent = Agent(reactor) urls = (line.strip() for line in open('urls.txt')) reqs = [agent.request('HEAD', url).addCallback(get_headers, url) for url in urls if url] defer.gatherResults(reqs).addCallback(got_everything) reactor.run() This example starts all requests asynchronously, and gather all results. Here's the output for a file with 3 urls: {'http://debian.org': {'Content-Type': ['text/html; charset=iso-8859-1'], 'Date': ['Thu, 04 Mar 2010 13:27:25 GMT'], 'Location': ['http://www.debian.org/'], 'Server': ['Apache'], 'Vary': ['Accept-Encoding']}, 'http://google.com': {'Cache-Control': ['public, max-age=2592000'], 'Content-Type': ['text/html; charset=UTF-8'], 'Date': ['Thu, 04 Mar 2010 13:27:25 GMT'], 'Expires': ['Sat, 03 Apr 2010 13:27:25 GMT'], 'Location': ['http://www.google.com/'], 'Server': ['gws'], 'X-Xss-Protection': ['0']}, 'http://stackoverflow.com': {'Cache-Control': ['private'], 'Content-Type': ['text/html; charset=utf-8'], 'Date': ['Thu, 04 Mar 2010 13:27:24 GMT'], 'Expires': ['Thu, 04 Mar 2010 13:27:25 GMT'], 'Server': ['Microsoft-IIS/7.5']}} A: The solution is to use a little bit of functional programming to 'stick' some additional information to our callback function. functools.partial
pycurl and lot of callback functions
I have big URL list, which I have to download in parallel and check one of headers that is returned with each response. I can use CurlMulti for parallelization. I can use /dev/null as fb, because I am not interested in body, only headers. But how can I check each header? To receive header, I must set HEADERFUNCTION callback. I get that. But in this callback function I get only buffer with headers. How can I distinguish one request from another? I don't like the idea of creating as much callback functions as there are URLs. Should I create some class and as much instances of that class? Also not very clever.
[ "I would use Python's built in httplib and threading modules. I don't see need for a 3rd party module.\n", "I know you're asking about pycurl, but I find it too hard and unpythonic to use. The API is weird.\nHere's a twisted example:\nfrom twisted.web.client import Agent\nfrom twisted.internet import reactor, defer\n\ndef get_headers(response, url):\n '''Extract a dict of headers from the response'''\n return url, dict(response.headers.getAllRawHeaders())\n\ndef got_everything(all_headers):\n '''print results and end program'''\n print dict(all_headers)\n reactor.stop()\n\nagent = Agent(reactor)\nurls = (line.strip() for line in open('urls.txt'))\nreqs = [agent.request('HEAD', url).addCallback(get_headers, url) for url in urls if url]\ndefer.gatherResults(reqs).addCallback(got_everything)\nreactor.run()\n\nThis example starts all requests asynchronously, and gather all results. Here's the output for a file with 3 urls:\n{'http://debian.org': {'Content-Type': ['text/html; charset=iso-8859-1'],\n 'Date': ['Thu, 04 Mar 2010 13:27:25 GMT'],\n 'Location': ['http://www.debian.org/'],\n 'Server': ['Apache'],\n 'Vary': ['Accept-Encoding']},\n 'http://google.com': {'Cache-Control': ['public, max-age=2592000'],\n 'Content-Type': ['text/html; charset=UTF-8'],\n 'Date': ['Thu, 04 Mar 2010 13:27:25 GMT'],\n 'Expires': ['Sat, 03 Apr 2010 13:27:25 GMT'],\n 'Location': ['http://www.google.com/'],\n 'Server': ['gws'],\n 'X-Xss-Protection': ['0']},\n 'http://stackoverflow.com': {'Cache-Control': ['private'],\n 'Content-Type': ['text/html; charset=utf-8'],\n 'Date': ['Thu, 04 Mar 2010 13:27:24 GMT'],\n 'Expires': ['Thu, 04 Mar 2010 13:27:25 GMT'],\n 'Server': ['Microsoft-IIS/7.5']}}\n\n", "The solution is to use a little bit of functional programming to 'stick' some additional information to our callback function.\nfunctools.partial\n" ]
[ 1, 0, 0 ]
[]
[]
[ "libcurl", "pycurl", "python" ]
stackoverflow_0002379240_libcurl_pycurl_python.txt
Q: Debug/Monitor middleware for python wsgi applications I'm searching a wsgi middleware which I can warp around a wsgi applications and which lets me monitor incoming and outgoing http requests and header fields. Something like firefox live headers, but for the server side. A: That shouldn't be too hard to write yourself as long as you only need the headers. Try that: import sys def log_headers(app, stream=None): if stream is None: stream = sys.stdout def proxy(environ, start_response): for key, value in environ.iteritems(): if key.startswith('HTTP_'): stream.write('%s: %s\n' % (key[5:].title().replace('_', '-'), value)) return app(environ, start_response) return proxy A: The middleware from wsgiref.util import request_uri import sys def logging_middleware(application, stream=sys.stdout): def _logger(environ, start_response): stream.write('REQUEST\n') stream.write('%s %s\n' %( environ['REQUEST_METHOD'], request_uri(environ), )) for name, value in environ.items(): if name.startswith('HTTP_'): stream.write(' %s: %s\n' %( name[5:].title().replace('_', '-'), value, )) stream.flush() def _start_response(code, headers): stream.write('RESPONSE\n') stream.write('%s\n' % code) for data in headers: stream.write(' %s: %s\n' % data) stream.flush() start_response(code, headers) return application(environ, _start_response) return _logger The test def application(environ, start_response): start_response('200 OK', [ ('Content-Type', 'text/html') ]) return ['Hello World'] if __name__ == '__main__': logger = logging_middleware(application) from wsgiref.simple_server import make_server httpd = make_server('', 1234, logger) httpd.serve_forever() See also the werkzeug debugger Armin wrote, it's usefull for interactive debugging. A: If you want Apache-style logs, try paste.translogger But for something more complete, though not in a very handy or stable location (maybe copy it into your source) is wsgifilter.proxyapp.DebugHeaders And writing one using WebOb: import webob, sys class LogHeaders(object): def __init__(self, app, stream=sys.stderr): self.app = app self.stream = stream def __call__(self, environ, start_response): req = webob.Request(environ) resp = req.get_response(self.app) print >> self.stream, 'Request:\n%s\n\nResponse:\n%s\n\n\n' % (req, resp) return resp(environ, start_response) A: The mod_wsgi documentation provides various tips on debugging which are applicable to any WSGI hosting mechanism and not just mod_wsgi. See: http://code.google.com/p/modwsgi/wiki/DebuggingTechniques This includes an example WSGI middleware that captures request and response. A: My WebCore project has a bit of middleware that logs the entire WSGI environment (thus Beaker sessions, headers, etc.) for the incoming request, headers for outbound responses, as well as performance information to a MongoDB database. Average overhead is around 4ms. The module has been removed from the core package, but hasn’t yet been integrated into its own. The current version as of this answer is available in the Git history: http://github.com/GothAlice/WebCore/blob/cd1d6dcbd081323869968c51a78eceb1a32007d8/web/extras/cprofile.py
Debug/Monitor middleware for python wsgi applications
I'm searching a wsgi middleware which I can warp around a wsgi applications and which lets me monitor incoming and outgoing http requests and header fields. Something like firefox live headers, but for the server side.
[ "That shouldn't be too hard to write yourself as long as you only need the headers. Try that:\nimport sys\n\ndef log_headers(app, stream=None):\n if stream is None:\n stream = sys.stdout\n def proxy(environ, start_response):\n for key, value in environ.iteritems():\n if key.startswith('HTTP_'):\n stream.write('%s: %s\\n' % (key[5:].title().replace('_', '-'), value))\n return app(environ, start_response)\n return proxy\n\n", "The middleware\nfrom wsgiref.util import request_uri\nimport sys\n\ndef logging_middleware(application, stream=sys.stdout):\n def _logger(environ, start_response):\n stream.write('REQUEST\\n')\n stream.write('%s %s\\n' %(\n environ['REQUEST_METHOD'],\n request_uri(environ),\n ))\n\n for name, value in environ.items():\n if name.startswith('HTTP_'):\n stream.write(' %s: %s\\n' %(\n name[5:].title().replace('_', '-'),\n value,\n ))\n stream.flush()\n def _start_response(code, headers):\n stream.write('RESPONSE\\n')\n stream.write('%s\\n' % code)\n for data in headers:\n stream.write(' %s: %s\\n' % data)\n stream.flush()\n start_response(code, headers)\n return application(environ, _start_response)\n return _logger\n\nThe test\ndef application(environ, start_response):\n start_response('200 OK', [\n ('Content-Type', 'text/html')\n ])\n return ['Hello World']\n\nif __name__ == '__main__':\n logger = logging_middleware(application)\n from wsgiref.simple_server import make_server\n httpd = make_server('', 1234, logger)\n httpd.serve_forever()\n\nSee also the werkzeug debugger Armin wrote, it's usefull for interactive debugging.\n", "If you want Apache-style logs, try paste.translogger\nBut for something more complete, though not in a very handy or stable location (maybe copy it into your source) is wsgifilter.proxyapp.DebugHeaders\nAnd writing one using WebOb:\nimport webob, sys\nclass LogHeaders(object):\n def __init__(self, app, stream=sys.stderr):\n self.app = app\n self.stream = stream\n def __call__(self, environ, start_response):\n req = webob.Request(environ)\n resp = req.get_response(self.app)\n print >> self.stream, 'Request:\\n%s\\n\\nResponse:\\n%s\\n\\n\\n' % (req, resp)\n return resp(environ, start_response)\n\n", "The mod_wsgi documentation provides various tips on debugging which are applicable to any WSGI hosting mechanism and not just mod_wsgi. See:\nhttp://code.google.com/p/modwsgi/wiki/DebuggingTechniques\nThis includes an example WSGI middleware that captures request and response.\n", "My WebCore project has a bit of middleware that logs the entire WSGI environment (thus Beaker sessions, headers, etc.) for the incoming request, headers for outbound responses, as well as performance information to a MongoDB database. Average overhead is around 4ms.\nThe module has been removed from the core package, but hasn’t yet been integrated into its own. The current version as of this answer is available in the Git history:\nhttp://github.com/GothAlice/WebCore/blob/cd1d6dcbd081323869968c51a78eceb1a32007d8/web/extras/cprofile.py\n" ]
[ 2, 2, 2, 1, 1 ]
[]
[]
[ "debugging", "middleware", "python", "wsgi" ]
stackoverflow_0000117986_debugging_middleware_python_wsgi.txt
Q: can't call __add__ through __getattr__( __getattribute__ ) It is object of the class A, in container's class tmpA. Not all method from A are in the tmpA. So for example: A + B is present , tmpA + B isn't present. I try to call method from A for tmpA. I can to call simple method, such as change(), but __add__ - don't work. If to remove inheritance from object, the code works. #-------------------------------------- class A(object): def __init__( self, x, y ): self.x = x self.y = y pass #------- def __add__( self, arg ): tmp1 = self.x + arg.x tmp2 = self.y + arg.y return tmpA( A( tmp1, tmp2 ) ) def change( self, x, y ): self.x = x self.y = y pass pass #------------------------------------------ class tmpA( object ): def __init__( self, theA ): self.A = theA pass #------- def _print ( self ): print " x =", self.A.x print " y =", self.A.y pass #------- def __call__( self ): return self.A #------- def __coerce__( self, *args ): return None #------- def __getattr__( self, *args ): name = args[ 0 ] try: attr = None exec "attr = self.__call__().%s" % name return attr except : raise AttributeError #-------------------------------------- class B( object ): def __init__( self, x, y): self.x = x self.y = y pass #------------------------------------- a=A( 1,2 ); b=B( 3,4 ); tmp_a = a + b; tmp_a.change( 0, 0 ) # very well v = tmp_a + b #TypeError: "unsupported operand type(s) for +: 'tmpA' and 'B'" A: Special methods are looked up on the class, that is, not on the instance of the class (except for some irregularities in old-style classes, which just mean a huge headache). So in particular the class's __getattr__ (for sane, new-style classes) is not getting called to look up __add__ when a + is performed - the metaclass's (type's, here) __getattr__ is. "Removing inheritance from object" means popping right back into the hellzapoppin world of old-style classes and only stores up pain for the future: don't! Rather, if you have a class that must delegate some special methods, code them explicitly in the class (directly or via a class decorator), or make a custom metaclass that knows about this quirk (the metaclass's __getattr__, or other means, can then perform the task you crave). A: I think X + Y is taken as X.__add__(Y). So if you use class tempA(A) then temp_a + b works because it inherits __add__ method and uses it like temp_a.__add__(b). but if you use class tempA(object) then it does not have __add__ method in class tempA to call when it encounters temp_a + b. A: When you say tmp_a + b, Python looks in tmp_a.__class__.__dict__ and then object.__dict__ for the __add__ method (bypassing the hasattr/getattr type lookup) Since it is not found anywhere, Python then looks to see if b has an __radd__ method that can handle tmp_a as the other parameter. Since it can't, the exception is thrown. You will have to add a bunch of special methods to tmpA to get those to work properly.
can't call __add__ through __getattr__( __getattribute__ )
It is object of the class A, in container's class tmpA. Not all method from A are in the tmpA. So for example: A + B is present , tmpA + B isn't present. I try to call method from A for tmpA. I can to call simple method, such as change(), but __add__ - don't work. If to remove inheritance from object, the code works. #-------------------------------------- class A(object): def __init__( self, x, y ): self.x = x self.y = y pass #------- def __add__( self, arg ): tmp1 = self.x + arg.x tmp2 = self.y + arg.y return tmpA( A( tmp1, tmp2 ) ) def change( self, x, y ): self.x = x self.y = y pass pass #------------------------------------------ class tmpA( object ): def __init__( self, theA ): self.A = theA pass #------- def _print ( self ): print " x =", self.A.x print " y =", self.A.y pass #------- def __call__( self ): return self.A #------- def __coerce__( self, *args ): return None #------- def __getattr__( self, *args ): name = args[ 0 ] try: attr = None exec "attr = self.__call__().%s" % name return attr except : raise AttributeError #-------------------------------------- class B( object ): def __init__( self, x, y): self.x = x self.y = y pass #------------------------------------- a=A( 1,2 ); b=B( 3,4 ); tmp_a = a + b; tmp_a.change( 0, 0 ) # very well v = tmp_a + b #TypeError: "unsupported operand type(s) for +: 'tmpA' and 'B'"
[ "Special methods are looked up on the class, that is, not on the instance of the class (except for some irregularities in old-style classes, which just mean a huge headache). So in particular the class's __getattr__ (for sane, new-style classes) is not getting called to look up __add__ when a + is performed - the metaclass's (type's, here) __getattr__ is.\n\"Removing inheritance from object\" means popping right back into the hellzapoppin world of old-style classes and only stores up pain for the future: don't! Rather, if you have a class that must delegate some special methods, code them explicitly in the class (directly or via a class decorator), or make a custom metaclass that knows about this quirk (the metaclass's __getattr__, or other means, can then perform the task you crave).\n", "I think X + Y is taken as X.__add__(Y).\nSo if you use\nclass tempA(A) then temp_a + b works because it inherits __add__ method and uses it like temp_a.__add__(b).\nbut if you use\nclass tempA(object) then it does not have __add__ method in class tempA to call when it encounters temp_a + b.\n", "When you say tmp_a + b, Python looks in tmp_a.__class__.__dict__ and then object.__dict__ for the __add__ method (bypassing the hasattr/getattr type lookup)\nSince it is not found anywhere, Python then looks to see if b has an __radd__ method that can handle tmp_a as the other parameter. Since it can't, the exception is thrown.\nYou will have to add a bunch of special methods to tmpA to get those to work properly.\n" ]
[ 7, 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0002384905_python.txt
Q: wx.ProgressDialog too small My program uses wx.ProgressDialog to give feedback on a process that is in multiple stages. At the beginning of each stage, I use the second argument of Update to change the message in the dialog. The problem is that the width of the dialog is determined from the message in the constructor, and the dialog is not resized if a later call to Update sets the message to something longer. Apart from giving a long message in the constructor, is there a way to make the dialog bigger? A: call wx.Fit() on the dialog, or you can use SetSize((x, y))
wx.ProgressDialog too small
My program uses wx.ProgressDialog to give feedback on a process that is in multiple stages. At the beginning of each stage, I use the second argument of Update to change the message in the dialog. The problem is that the width of the dialog is determined from the message in the constructor, and the dialog is not resized if a later call to Update sets the message to something longer. Apart from giving a long message in the constructor, is there a way to make the dialog bigger?
[ "call wx.Fit() on the dialog, or you can use SetSize((x, y))\n" ]
[ 6 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0002384397_python_wxpython.txt
Q: Counting Duplicates Integers in Python How do I find the total number of duplicates in a string? i.e., if it was j= [1,1,1,2,2,2] it would find 4 duplicates? I've only been able to find counting which shows how many times each individual number occurred. A: >>> j= [1,1,1,2,2,2] >>> len(j) - len(set(j)) 4 and btw, j is a list and not a string, although for the purpose of this exercise it doesn't really matter. A: There seems to be a popular answer already, but if you would like to maintain the individual duplicate counts as well, the new Counter() collection object in Python 2.7 is perfect for this. >>> from collections import Counter >>> j = [1,1,1,2,2,2] >>> Counter(j) Counter({1: 3, 2: 3}) >>> sum([i - 1 for i in c.values() if i > 1]) 4 >>> {k: v - 1 for k, v in c.items()} # individual dupes {1: 2, 2: 2} There is a backport for Counter at ActiveState
Counting Duplicates Integers in Python
How do I find the total number of duplicates in a string? i.e., if it was j= [1,1,1,2,2,2] it would find 4 duplicates? I've only been able to find counting which shows how many times each individual number occurred.
[ ">>> j= [1,1,1,2,2,2]\n>>> len(j) - len(set(j))\n4\n\nand btw, j is a list and not a string, although for the purpose of this exercise it doesn't really matter.\n", "There seems to be a popular answer already, but if you would like to maintain the individual duplicate counts as well, the new Counter() collection object in Python 2.7 is perfect for this.\n>>> from collections import Counter\n\n>>> j = [1,1,1,2,2,2]\n\n>>> Counter(j)\nCounter({1: 3, 2: 3})\n\n>>> sum([i - 1 for i in c.values() if i > 1])\n4\n\n>>> {k: v - 1 for k, v in c.items()} # individual dupes\n{1: 2, 2: 2}\n\nThere is a backport for Counter at ActiveState\n" ]
[ 17, 8 ]
[]
[]
[ "count", "duplicates", "python" ]
stackoverflow_0002385867_count_duplicates_python.txt
Q: Why does the "name" parameter to __setattr__ include the class, but __getattr__ doesn't? The following code: class MyClass(): def test(self): self.__x = 0 def __setattr__(self, name, value): print name def __getattr__(self, name): print name raise AttributeError(name) x = MyClass() x.test() x.__y Outputs: _MyClass__x __y Traceback (most recent call last): ... AttributeError: __y The documentation is utterly unhelpful stating the "name" is the "name of the attribute", yet for some reason it's different depending on whether you are setting it or getting it. What I want to know is: Am I doing something fundamentally wrong here? How do I get x in the first case instead of _MyClass__x? A: The double underscore invokes name mangling. If you don't need name mangling, don't use double undescore What is the meaning of a single- and a double-underscore before an object name? From the Python docs 9.6. Private Variables “Private” instance variables that cannot be accessed except from inside an object, don’t exist in Python. However, there is a convention that is followed by most Python code: a name prefixed with an underscore (e.g. _spam) should be treated as a non-public part of the API (whether it is a function, a method or a data member). It should be considered an implementation detail and subject to change without notice. Since there is a valid use-case for class-private members (namely to avoid name clashes of names with names defined by subclasses), there is limited support for such a mechanism, called name mangling. Any identifier of the form __spam (at least two leading underscores, at most one trailing underscore) is textually replaced with _classname__spam, where classname is the current class name with leading underscore(s) stripped. This mangling is done without regard to the syntactic position of the identifier, as long as it occurs within the definition of a class. Note that the mangling rules are designed mostly to avoid accidents; it still is possible to access or modify a variable that is considered private. This can even be useful in special circumstances, such as in the debugger. Notice that code passed to exec, eval() or execfile() does not consider the classname of the invoking class to be the current class; this is similar to the effect of the global statement, the effect of which is likewise restricted to code that is byte-compiled together. The same restriction applies to getattr(), setattr() and delattr(), as well as when referencing __dict__ directly. A: I'm not sure exactly why this occurs, but if you use _x rather than __x it works as you would expect.
Why does the "name" parameter to __setattr__ include the class, but __getattr__ doesn't?
The following code: class MyClass(): def test(self): self.__x = 0 def __setattr__(self, name, value): print name def __getattr__(self, name): print name raise AttributeError(name) x = MyClass() x.test() x.__y Outputs: _MyClass__x __y Traceback (most recent call last): ... AttributeError: __y The documentation is utterly unhelpful stating the "name" is the "name of the attribute", yet for some reason it's different depending on whether you are setting it or getting it. What I want to know is: Am I doing something fundamentally wrong here? How do I get x in the first case instead of _MyClass__x?
[ "The double underscore invokes name mangling. If you don't need name mangling, don't use double undescore\nWhat is the meaning of a single- and a double-underscore before an object name?\nFrom the Python docs\n\n9.6. Private Variables\n“Private” instance variables that cannot be accessed except from inside an object, don’t exist in Python. However, there is a convention that is followed by most Python code: a name prefixed with an underscore (e.g. _spam) should be treated as a non-public part of the API (whether it is a function, a method or a data member). It should be considered an implementation detail and subject to change without notice.\nSince there is a valid use-case for class-private members (namely to avoid name clashes of names with names defined by subclasses), there is limited support for such a mechanism, called name mangling. Any identifier of the form __spam (at least two leading underscores, at most one trailing underscore) is textually replaced with _classname__spam, where classname is the current class name with leading underscore(s) stripped. This mangling is done without regard to the syntactic position of the identifier, as long as it occurs within the definition of a class.\nNote that the mangling rules are designed mostly to avoid accidents; it still is possible to access or modify a variable that is considered private. This can even be useful in special circumstances, such as in the debugger.\nNotice that code passed to exec, eval() or execfile() does not consider the classname of the invoking class to be the current class; this is similar to the effect of the global statement, the effect of which is likewise restricted to code that is byte-compiled together. The same restriction applies to getattr(), setattr() and delattr(), as well as when referencing __dict__ directly.\n\n", "I'm not sure exactly why this occurs, but if you use _x rather than __x it works as you would expect.\n" ]
[ 6, 1 ]
[]
[]
[ "getattr", "python", "setattr" ]
stackoverflow_0002386418_getattr_python_setattr.txt
Q: Python 2.6 - I can not write dwords greater than 0x7fffffff into registry using _winreg.SetValueEx() using regedit.exe I have manually created a key in registry called HKEY_CURRENT_USER/00_Just_a_Test_Key and created two dword values dword_test_1 and dword_test_2 I am trying to write some values into those two keys using following program import _winreg aReg = _winreg.ConnectRegistry(None,_winreg.HKEY_CURRENT_USER) aKey = _winreg.OpenKey(aReg, r"00_Just_a_Test_Key", 0, _winreg.KEY_WRITE) _winreg.SetValueEx(aKey,"dword_test_1",0, _winreg.REG_DWORD, 0x0edcba98) _winreg.SetValueEx(aKey,"dword_test_2",0, _winreg.REG_DWORD, 0xfedcba98) _winreg.CloseKey(aKey) _winreg.CloseKey(aReg) I can write into the first key, dword_test_1, but when I attempt to write into the second, I get following message Traceback (most recent call last): File "D:/src/registry/question.py", line 7, in <module> _winreg.SetValueEx(aKey,"dword_test_2",0, _winreg.REG_DWORD, 0xfedcba98) ValueError: Could not convert the data to the specified type. How do I write the second value 0xfedcba98, or any value greater than 0x7fffffff as a dword value? Originally I was writing script to switch the "My documents" icon on or off by writing "0xf0500174" to hide or "0xf0400174" to display the icon into [HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\CLSID{450D8FBA-AD25-11D0-98A8-0800361B1103}\ShellFolder] A: Most likely the function expects an int within the limits of a signed C integer, so you'll need to subtract 0x100000000 before passing to the function. Yes, ideally this would be solved in the bindings. Unfortunately someone let this one slide. A: I have solved the problem the following way import _winreg def complement(n,radix=32): if n < (1<<(radix-1)) : return n # n is less than 0x80000000 and we do not do anything else : return n - (1<<radix) # n is greater than 0x80000000 and we have to convert it # (1<<31) can be written in binary as 1 followed by 31 zeroes - that is 0x80000000 # n - (1<<radix) is how to get the representation of the number as a signed dword. # See http://stackoverflow.com/questions/1604464/twos-complement-in-python # for explanation aReg = _winreg.ConnectRegistry(None,_winreg.HKEY_CURRENT_USER) aKey = _winreg.OpenKey(aReg, r"00_Just_a_Test_Key", 0, _winreg.KEY_WRITE) _winreg.SetValueEx(aKey,"dword_test_1",0, _winreg.REG_DWORD, complement(0x0edcba98)) _winreg.SetValueEx(aKey,"dword_test_2",0, _winreg.REG_DWORD, complement(0xfedcba98)) _winreg.CloseKey(aKey) _winreg.CloseKey(aReg)
Python 2.6 - I can not write dwords greater than 0x7fffffff into registry using _winreg.SetValueEx()
using regedit.exe I have manually created a key in registry called HKEY_CURRENT_USER/00_Just_a_Test_Key and created two dword values dword_test_1 and dword_test_2 I am trying to write some values into those two keys using following program import _winreg aReg = _winreg.ConnectRegistry(None,_winreg.HKEY_CURRENT_USER) aKey = _winreg.OpenKey(aReg, r"00_Just_a_Test_Key", 0, _winreg.KEY_WRITE) _winreg.SetValueEx(aKey,"dword_test_1",0, _winreg.REG_DWORD, 0x0edcba98) _winreg.SetValueEx(aKey,"dword_test_2",0, _winreg.REG_DWORD, 0xfedcba98) _winreg.CloseKey(aKey) _winreg.CloseKey(aReg) I can write into the first key, dword_test_1, but when I attempt to write into the second, I get following message Traceback (most recent call last): File "D:/src/registry/question.py", line 7, in <module> _winreg.SetValueEx(aKey,"dword_test_2",0, _winreg.REG_DWORD, 0xfedcba98) ValueError: Could not convert the data to the specified type. How do I write the second value 0xfedcba98, or any value greater than 0x7fffffff as a dword value? Originally I was writing script to switch the "My documents" icon on or off by writing "0xf0500174" to hide or "0xf0400174" to display the icon into [HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\CLSID{450D8FBA-AD25-11D0-98A8-0800361B1103}\ShellFolder]
[ "Most likely the function expects an int within the limits of a signed C integer, so you'll need to subtract 0x100000000 before passing to the function.\nYes, ideally this would be solved in the bindings. Unfortunately someone let this one slide.\n", "I have solved the problem the following way\nimport _winreg\n\ndef complement(n,radix=32):\n if n < (1<<(radix-1)) : return n # n is less than 0x80000000 and we do not do anything\n else : return n - (1<<radix) # n is greater than 0x80000000 and we have to convert it\n # (1<<31) can be written in binary as 1 followed by 31 zeroes - that is 0x80000000\n # n - (1<<radix) is how to get the representation of the number as a signed dword.\n # See http://stackoverflow.com/questions/1604464/twos-complement-in-python\n # for explanation\n\naReg = _winreg.ConnectRegistry(None,_winreg.HKEY_CURRENT_USER)\naKey = _winreg.OpenKey(aReg, r\"00_Just_a_Test_Key\", 0, _winreg.KEY_WRITE)\n\n_winreg.SetValueEx(aKey,\"dword_test_1\",0, _winreg.REG_DWORD, complement(0x0edcba98)) \n_winreg.SetValueEx(aKey,\"dword_test_2\",0, _winreg.REG_DWORD, complement(0xfedcba98)) \n\n_winreg.CloseKey(aKey)\n_winreg.CloseKey(aReg)\n\n" ]
[ 3, 1 ]
[]
[]
[ "python", "registry", "winreg" ]
stackoverflow_0002381205_python_registry_winreg.txt
Q: Is it possible to generate and return a ZIP file with App Engine? I have a small project that would be perfect for Google App Engine. Implementing it hinges on the ability to generate a ZIP file and return it. Due to the distributed nature of App Engine, from what I can tell, the ZIP file couldn't be created "in-memory" in the traditional sense. It would basically have to be generated and and sent in a single request/response cycle. Does the Python zip module even exist in the App Engine environment? A: zipfile is available at appengine and reworked example follows: from contextlib import closing from zipfile import ZipFile, ZIP_DEFLATED from google.appengine.ext import webapp from google.appengine.api import urlfetch def addResource(zfile, url, fname): # get the contents contents = urlfetch.fetch(url).content # write the contents to the zip file zfile.writestr(fname, contents) class OutZipfile(webapp.RequestHandler): def get(self): # Set up headers for browser to correctly recognize ZIP file self.response.headers['Content-Type'] ='application/zip' self.response.headers['Content-Disposition'] = \ 'attachment; filename="outfile.zip"' # compress files and emit them directly to HTTP response stream with closing(ZipFile(self.response.out, "w", ZIP_DEFLATED)) as outfile: # repeat this for every URL that should be added to the zipfile addResource(outfile, 'https://www.google.com/intl/en/policies/privacy/', 'privacy.html') addResource(outfile, 'https://www.google.com/intl/en/policies/terms/', 'terms.html') A: import zipfile import StringIO text = u"ABCDEFGHIJKLMNOPQRSTUVWXYVabcdefghijklmnopqqstuvweyxáéöüï东 廣 広 广 國 国 国 界" zipstream=StringIO.StringIO() file = zipfile.ZipFile(file=zipstream,compression=zipfile.ZIP_DEFLATED,mode="w") file.writestr("data.txt.zip",text.encode("utf-8")) file.close() zipstream.seek(0) self.response.headers['Content-Type'] ='application/zip' self.response.headers['Content-Disposition'] = 'attachment; filename="data.txt.zip"' self.response.out.write(zipstream.getvalue()) A: From What is Google App Engine: You can upload other third-party libraries with your application, as long as they are implemented in pure Python and do not require any unsupported standard library modules. So, even if it doesn't exist by default you can (potentially) include it yourself. (I say potentially because I don't know if the Python zip library requires any "unsupported standard library modules".
Is it possible to generate and return a ZIP file with App Engine?
I have a small project that would be perfect for Google App Engine. Implementing it hinges on the ability to generate a ZIP file and return it. Due to the distributed nature of App Engine, from what I can tell, the ZIP file couldn't be created "in-memory" in the traditional sense. It would basically have to be generated and and sent in a single request/response cycle. Does the Python zip module even exist in the App Engine environment?
[ "zipfile is available at appengine and reworked example follows:\nfrom contextlib import closing\nfrom zipfile import ZipFile, ZIP_DEFLATED\n\nfrom google.appengine.ext import webapp\nfrom google.appengine.api import urlfetch\n\ndef addResource(zfile, url, fname):\n # get the contents \n contents = urlfetch.fetch(url).content\n # write the contents to the zip file\n zfile.writestr(fname, contents)\n\nclass OutZipfile(webapp.RequestHandler):\n def get(self):\n # Set up headers for browser to correctly recognize ZIP file\n self.response.headers['Content-Type'] ='application/zip'\n self.response.headers['Content-Disposition'] = \\\n 'attachment; filename=\"outfile.zip\"' \n\n # compress files and emit them directly to HTTP response stream\n with closing(ZipFile(self.response.out, \"w\", ZIP_DEFLATED)) as outfile:\n # repeat this for every URL that should be added to the zipfile\n addResource(outfile, \n 'https://www.google.com/intl/en/policies/privacy/', \n 'privacy.html')\n addResource(outfile, \n 'https://www.google.com/intl/en/policies/terms/', \n 'terms.html')\n\n", "import zipfile\nimport StringIO\n\ntext = u\"ABCDEFGHIJKLMNOPQRSTUVWXYVabcdefghijklmnopqqstuvweyxáéöüï东 廣 広 广 國 国 国 界\"\n\nzipstream=StringIO.StringIO()\nfile = zipfile.ZipFile(file=zipstream,compression=zipfile.ZIP_DEFLATED,mode=\"w\")\nfile.writestr(\"data.txt.zip\",text.encode(\"utf-8\"))\nfile.close()\nzipstream.seek(0)\nself.response.headers['Content-Type'] ='application/zip'\nself.response.headers['Content-Disposition'] = 'attachment; filename=\"data.txt.zip\"'\nself.response.out.write(zipstream.getvalue())\n\n", "From What is Google App Engine:\n\nYou can upload other third-party\n libraries with your application, as\n long as they are implemented in pure\n Python and do not require any\n unsupported standard library modules.\n\nSo, even if it doesn't exist by default you can (potentially) include it yourself. (I say potentially because I don't know if the Python zip library requires any \"unsupported standard library modules\".\n" ]
[ 33, 9, 2 ]
[]
[]
[ "google_app_engine", "in_memory", "python", "zip" ]
stackoverflow_0000583791_google_app_engine_in_memory_python_zip.txt
Q: Is it possible to get the width of a character when using OpenGL bitmap fonts? I am trying to align my bitmap font text in my OpenGL application but I can't find anything on getting the width of each character. This is my renderText function: def renderText( self, text, fontFace, position ): ..... (omitted code to make post shorter) glRasterPos2i( position[0], self.windowSize[1] - position[1] ) glPushAttrib( GL_LIST_BIT ) glListBase( self.fonts[ fontFace ] - 32 ) glCallLists( text ) glPopAttrib() ...... I create the bitmap font and use glGenList to store it. self.fonts[ fontFace ] = glGenLists( 96 ) font = win32ui.CreateFont( fontProperties ) font = hDisplayContext.SelectObject( font ) wglUseFontBitmaps( displayContext, 32, 96, self.fonts[ fontFace ] ) Anyone know if it's possible to get the character widths or even just the final rendered text's total width? A: glutBitmapWidth, glutBitmapLength — returns the width/length of a bitmap character/string. Python Specification: glutBitmapWidth(font, character) -> None glutBitmapLength(font, string) -> None
Is it possible to get the width of a character when using OpenGL bitmap fonts?
I am trying to align my bitmap font text in my OpenGL application but I can't find anything on getting the width of each character. This is my renderText function: def renderText( self, text, fontFace, position ): ..... (omitted code to make post shorter) glRasterPos2i( position[0], self.windowSize[1] - position[1] ) glPushAttrib( GL_LIST_BIT ) glListBase( self.fonts[ fontFace ] - 32 ) glCallLists( text ) glPopAttrib() ...... I create the bitmap font and use glGenList to store it. self.fonts[ fontFace ] = glGenLists( 96 ) font = win32ui.CreateFont( fontProperties ) font = hDisplayContext.SelectObject( font ) wglUseFontBitmaps( displayContext, 32, 96, self.fonts[ fontFace ] ) Anyone know if it's possible to get the character widths or even just the final rendered text's total width?
[ "glutBitmapWidth, glutBitmapLength — returns the width/length of a bitmap character/string.\nPython Specification:\nglutBitmapWidth(font, character) -> None\nglutBitmapLength(font, string) -> None\n\n" ]
[ 1 ]
[]
[]
[ "fonts", "opengl", "python", "text", "width" ]
stackoverflow_0002386849_fonts_opengl_python_text_width.txt
Q: OperationalError creating an index in sqlite EDIT: TL;DR version I typed this CREATE INDEX IF NOT EXISTS IDX_FILE_SIZE table_name (file_size); instead of this CREATE INDEX IF NOT EXISTS IDX_FILE_SIZE ON table_name (file_size); Don't do that. A: Some silly questions: Is it a concidence that the offending statement is missing the word ON? CREATE INDEX IF NOT EXISTS IDX_FILE_FULLPATH_FILE_PARENT_DIR ON table_name (file_fullpath, file_parent_dir); CREATE INDEX IF NOT EXISTS IDX_FILE_SIZE table_name (file_size); -- missing ON CREATE INDEX IF NOT EXISTS IDX_TAG_TITLE ON table_name (tag_title); Somewhere in all the verbiage in your question, did I see the phrase "syntax error"? Did you try the simple step of running the SQL statements in the sqlite3 command interpreter and seeing which syntax error you were actually getting? E.g. SQLite version 3.6.14 Enter ".help" for instructions Enter SQL statements terminated with a ";" sqlite> create table foo (bar int, zot int); sqlite> create index barx on foo(bar); sqlite> create index zotx foo(zot); SQL error: near "foo": syntax error sqlite> Have you considered perusing TFRRD (The Fantastic Rail-Road Diagram) in the docs? You wrote: """when I run that command in the smaller script (verifyIndexSmaller), it gives no error. If I then try to run the larger script again, even though the index has been created by the smaller script, I still get the error""". Have you considered the possibility that you didn't run that command in the smaller script, but actually ran another (fixed!) version of that command? Do you now understand why S.Lott was trying to get you to cut the waffle and focus on the piece of SQL that was causing the error?
OperationalError creating an index in sqlite
EDIT: TL;DR version I typed this CREATE INDEX IF NOT EXISTS IDX_FILE_SIZE table_name (file_size); instead of this CREATE INDEX IF NOT EXISTS IDX_FILE_SIZE ON table_name (file_size); Don't do that.
[ "Some silly questions:\nIs it a concidence that the offending statement is missing the word ON?\nCREATE INDEX IF NOT EXISTS IDX_FILE_FULLPATH_FILE_PARENT_DIR ON table_name (file_fullpath, file_parent_dir);\nCREATE INDEX IF NOT EXISTS IDX_FILE_SIZE table_name (file_size); -- missing ON\nCREATE INDEX IF NOT EXISTS IDX_TAG_TITLE ON table_name (tag_title); \nSomewhere in all the verbiage in your question, did I see the phrase \"syntax error\"?\nDid you try the simple step of running the SQL statements in the sqlite3 command interpreter and seeing which syntax error you were actually getting?\nE.g.\nSQLite version 3.6.14\nEnter \".help\" for instructions\nEnter SQL statements terminated with a \";\"\nsqlite> create table foo (bar int, zot int);\nsqlite> create index barx on foo(bar);\nsqlite> create index zotx foo(zot);\nSQL error: near \"foo\": syntax error\nsqlite>\n\nHave you considered perusing TFRRD (The Fantastic Rail-Road Diagram) in the docs?\nYou wrote: \"\"\"when I run that command in the smaller script (verifyIndexSmaller), it gives no error. If I then try to run the larger script again, even though the index has been created by the smaller script, I still get the error\"\"\".\nHave you considered the possibility that you didn't run that command in the smaller script, but actually ran another (fixed!) version of that command?\nDo you now understand why S.Lott was trying to get you to cut the waffle and focus on the piece of SQL that was causing the error?\n" ]
[ 5 ]
[]
[]
[ "indexing", "python", "sql", "sqlite" ]
stackoverflow_0002384754_indexing_python_sql_sqlite.txt
Q: Creating a custom Django form field that uses two s How can I make a Django field that renders itself as a pair of input fields? Reasoning: I am trying to write a new custom field. I will use it for a captcha-like service. The service works by requesting a question - then receiving one and a token. The validation happens by sending the answer along with the token. I want to write a form field that encapsulates this logic. The elements should render (IMO) like <input type="hidden" name="_token" value="1234567890" /> <input type="text" name="answer" /> And on submit I need the value of _token and answer to validate the answer. A: I think you're looking for the MultiWidget, you can simply give it 2 regular widgets and it will render the combination. A: Here you have a ready example(taken from my blog): class ComplexMultiWidget(forms.MultiWidget): def __init__(self, attrs=None): widgets = ( forms.TextInput(), forms.SelectMultiple(choices=(('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo'))), forms.SplitDateTimeWidget(), ) super(ComplexMultiWidget, self).__init__(widgets, attrs) def decompress(self, value): if value: data = value.split(',') return [data[0], data[1], datetime.datetime(*time.strptime(data[2], "%Y-%m-%d %H:%M:%S")[0:6])] return [None, None, None] def format_output(self, rendered_widgets): return u'\n'.join(rendered_widgets) class ComplexField(forms.MultiValueField): def __init__(self, required=True, widget=None, label=None, initial=None): fields = ( forms.CharField(), forms.MultipleChoiceField(choices=(('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo'))), forms.SplitDateTimeField() ) super(ComplexField, self).__init__(fields, required, widget, label, initial) def compress(self, data_list): if data_list: return '%s,%s,%s' % (data_list[0],''.join(data_list[1]), data_list[2]) return None Example how to use: >>> f = ComplexField(widget=ComplexMultiWidget()) >>> f.clean(['some text', ['J','P'], ['2007-04-25','6:24:00']]) u'some text,JP,2007-04-25 06:24:00' >>> f.clean(['some text',['X'], ['2007-04-25','6:24:00']]) Traceback (most recent call last): ... ValidationError: [u'Select a valid choice. X is not one of the available choices.'] >>> f.clean(['some text',['JP']]) Traceback (most recent call last): >>> class ComplexFieldForm(Form): field1 = ComplexField(widget=ComplexMultiWidget()) >>> f = ComplexFieldForm({'field1_0':'some text','field1_1':['J','P'], 'field1_2_0':'2007-04-25', 'field1_2_1':'06:24:00'}) >>> print f <tr><th><label for="id_field1_0">Field1:</label></th><td><input type="text" name="field1_0" value="some text" id="id_field1_0" /> <select multiple="multiple" name="field1_1" id="id_field1_1"> <option value="J" selected="selected">John</option> <option value="P" selected="selected">Paul</option> <option value="G">George</option> <option value="R">Ringo</option> </select> <input type="text" name="field1_2_0" value="2007-04-25" id="id_field1_2_0" /><input type="text" name="field1_2_1" value="06:24:00" id="id_field1_2_1" /></td></tr> >>> f.cleaned_data {'field1': u'some text,JP,2007-04-25 06:24:00'} A: Have a look at the SelectDateWidget. It splits the input of a date into three select boxes. And the doc string says: This also serves as an example of a Widget that has more than one HTML element and hence implements value_from_datadict.
Creating a custom Django form field that uses two s
How can I make a Django field that renders itself as a pair of input fields? Reasoning: I am trying to write a new custom field. I will use it for a captcha-like service. The service works by requesting a question - then receiving one and a token. The validation happens by sending the answer along with the token. I want to write a form field that encapsulates this logic. The elements should render (IMO) like <input type="hidden" name="_token" value="1234567890" /> <input type="text" name="answer" /> And on submit I need the value of _token and answer to validate the answer.
[ "I think you're looking for the MultiWidget, you can simply give it 2 regular widgets and it will render the combination.\n", "Here you have a ready example(taken from my blog):\nclass ComplexMultiWidget(forms.MultiWidget):\n def __init__(self, attrs=None):\n widgets = (\n forms.TextInput(),\n forms.SelectMultiple(choices=(('J', 'John'),\n ('P', 'Paul'),\n ('G', 'George'),\n ('R', 'Ringo'))),\n forms.SplitDateTimeWidget(),\n )\n super(ComplexMultiWidget, self).__init__(widgets, attrs)\n\n def decompress(self, value):\n if value:\n data = value.split(',')\n return [data[0], data[1],\n datetime.datetime(*time.strptime(data[2],\n \"%Y-%m-%d %H:%M:%S\")[0:6])]\n return [None, None, None]\n def format_output(self, rendered_widgets):\n return u'\\n'.join(rendered_widgets)\n\n\nclass ComplexField(forms.MultiValueField):\n def __init__(self, required=True, widget=None, label=None, initial=None):\n fields = (\n forms.CharField(),\n forms.MultipleChoiceField(choices=(('J', 'John'),\n ('P', 'Paul'),\n ('G', 'George'),\n ('R', 'Ringo'))),\n forms.SplitDateTimeField()\n )\n super(ComplexField, self).__init__(fields, required,\n widget, label, initial)\n\n def compress(self, data_list):\n if data_list:\n return '%s,%s,%s' % (data_list[0],''.join(data_list[1]),\n data_list[2])\n return None\n\nExample how to use:\n>>> f = ComplexField(widget=ComplexMultiWidget())\n>>> f.clean(['some text', ['J','P'], ['2007-04-25','6:24:00']])\nu'some text,JP,2007-04-25 06:24:00'\n>>> f.clean(['some text',['X'], ['2007-04-25','6:24:00']])\nTraceback (most recent call last):\n...\nValidationError: [u'Select a valid choice. X is not one of the available choices.']\n\n>>> f.clean(['some text',['JP']])\nTraceback (most recent call last):\n\n>>> class ComplexFieldForm(Form):\n field1 = ComplexField(widget=ComplexMultiWidget())\n\n>>> f = ComplexFieldForm({'field1_0':'some text','field1_1':['J','P'], 'field1_2_0':'2007-04-25', 'field1_2_1':'06:24:00'})\n>>> print f\n<tr><th><label for=\"id_field1_0\">Field1:</label></th><td><input type=\"text\" name=\"field1_0\" value=\"some text\" id=\"id_field1_0\" />\n<select multiple=\"multiple\" name=\"field1_1\" id=\"id_field1_1\">\n<option value=\"J\" selected=\"selected\">John</option>\n<option value=\"P\" selected=\"selected\">Paul</option>\n<option value=\"G\">George</option>\n<option value=\"R\">Ringo</option>\n</select>\n<input type=\"text\" name=\"field1_2_0\" value=\"2007-04-25\" id=\"id_field1_2_0\" /><input type=\"text\" name=\"field1_2_1\" value=\"06:24:00\" id=\"id_field1_2_1\" /></td></tr>\n\n>>> f.cleaned_data\n{'field1': u'some text,JP,2007-04-25 06:24:00'}\n\n", "Have a look at the SelectDateWidget. It splits the input of a date into three select boxes.\nAnd the doc string says:\n\nThis also serves as an example of a Widget that has more than one HTML element and hence implements value_from_datadict.\n\n" ]
[ 9, 4, 2 ]
[]
[]
[ "django", "django_forms", "python" ]
stackoverflow_0002386541_django_django_forms_python.txt
Q: Calculating difference within lists I have two files and the content is as follows: alt text http://img144.imageshack.us/img144/4423/screencapture2b.png alt text http://img229.imageshack.us/img229/9153/screencapture1c.png Please only consider the bolded column and the red column. The remaining text is junk and unnecessary. As evident from the two files they are similar in many ways. I am trying to compare the bolded text in file_1 and file_2 (it is not bolded but hope you can make out it is the same column) and if they are different, I want to print out the red text from file_1. I achieved this by the following script: import string import itertools chain_id=[] for file in os.listdir("."): basename = os.path.basename(file) if basename.startswith("d.complex"): chain_id.append(basename) for i in chain_id: print i g=codecs.open(i, encoding='utf-8') f=codecs.open("ac_chain_dssp.dssp", encoding='utf-8') for (x, y) in itertools.izip(g, f): if y[11]=="C": if y[35:38]!= "EN": if y[35:38] != "OTE": if x[11]=="C": if x[12] != "C": if y[35:38] !=x[35:38]: print x [7:10] g.close() f.close() But the results I got were not what I expected. Now I want to modify the above code in such a way that when I compare the bolded column, if the difference between the values is more than 2, then it has to print out the results. For example, row-1 of bolded column in file_1 is 83 and in file_2 it is 84 since the difference between the two is less than two, I want it to be rejected. Can someone help me in adding the remaining code? Cheers, Chavanak PS: This is not homework :) A: The direct answer to your question is to alter the last condition, if y[35:38] !=x[35:38]: so that instead the "field" at [35:38] get converted to int (or float...) and a difference can be applied to them. Giving something like try: iy = int(y[35:38]) ix = int(x[35:38]) except ValueError: # here for whatever action is appropriate, including silent ignoring. print("Unexpected value for record # %s" % x[7:10]) if abs(ix - iy) > 2: print(x[7:10]) More indirectly, the snippet in the question prompt the following remarks,which may in turn suggest different approaches to the problem. first off, if the files are strictly "fixed format", if they are very big, and/or if nothing else is done with any of the other "fields" values found in the file, the current approach is valid and probably very efficient. alternatively, the logic may be made more resilient to possible variations in the file structure etc, by parsing in the "fields" of the file, rather than addressing these as slices of a long string. Loot into the standard library's csv module for possible parser support. some tests seem goofy / always true etc (like comparing a 3 characters slice to a 2 character string literal. Aside from being logically wrong, this too points to a more "parsed" solution where such logical error are more readily avoided or more obvious. A: Nothing to do with your problem, but this: if y[11]=="C": if y[35:38]!= "EN": # I don't see any "EN" or "OTE" anywhere in your sample input. # In any case the above condition will always be true, because # y[35:38] appears to be a 3-byte string but "EN" is a 2-byte string. if y[35:38] != "OTE": if x[11]=="C": if x[12] != "C": if y[35:38] !=x[35:38]: print x [7:10] is ummmmm ... You may wish to consider an alternative way of expression e.g. if (x[11] == "C" == y[11] and x[12] != "C" and y[35:38] not in ("EN?", "OTE") and y[35:38] != x[35:38]): print x[7:10] A: I haven't understood your problem fully but File 1 100 C 20.2 300 B 33.3 File 2 110 C 20.23 320 B 33.34 and you want to compare 3rd column of the two files. lines1 = file1.readlines() list1 = [float(line.split()[2]) for line in lines1] # list of 3rd column values lines2 = file2.readlines() list2 = [float(line.split()[2]) for line in lines2] result = map(lambda x,y: x-y < 2,list1,list2) OR result = [list1[i]-list2[i] for i in range(len(list1)) if list1[i] - list2[i] > 2] Is this what you want??
Calculating difference within lists
I have two files and the content is as follows: alt text http://img144.imageshack.us/img144/4423/screencapture2b.png alt text http://img229.imageshack.us/img229/9153/screencapture1c.png Please only consider the bolded column and the red column. The remaining text is junk and unnecessary. As evident from the two files they are similar in many ways. I am trying to compare the bolded text in file_1 and file_2 (it is not bolded but hope you can make out it is the same column) and if they are different, I want to print out the red text from file_1. I achieved this by the following script: import string import itertools chain_id=[] for file in os.listdir("."): basename = os.path.basename(file) if basename.startswith("d.complex"): chain_id.append(basename) for i in chain_id: print i g=codecs.open(i, encoding='utf-8') f=codecs.open("ac_chain_dssp.dssp", encoding='utf-8') for (x, y) in itertools.izip(g, f): if y[11]=="C": if y[35:38]!= "EN": if y[35:38] != "OTE": if x[11]=="C": if x[12] != "C": if y[35:38] !=x[35:38]: print x [7:10] g.close() f.close() But the results I got were not what I expected. Now I want to modify the above code in such a way that when I compare the bolded column, if the difference between the values is more than 2, then it has to print out the results. For example, row-1 of bolded column in file_1 is 83 and in file_2 it is 84 since the difference between the two is less than two, I want it to be rejected. Can someone help me in adding the remaining code? Cheers, Chavanak PS: This is not homework :)
[ "The direct answer to your question is to alter the last condition, \nif y[35:38] !=x[35:38]:\nso that instead the \"field\" at [35:38] get converted to int (or float...) and a difference can be applied to them. Giving something like\n try:\n iy = int(y[35:38])\n ix = int(x[35:38])\n except ValueError:\n # here for whatever action is appropriate, including silent ignoring.\n print(\"Unexpected value for record # %s\" % x[7:10])\n\n if abs(ix - iy) > 2:\n print(x[7:10])\n\nMore indirectly, the snippet in the question prompt the following remarks,which may in turn suggest different approaches to the problem.\n\nfirst off, if the files are strictly \"fixed format\", if they are very big, and/or if nothing else is done with any of the other \"fields\" values found in the file, the current approach is valid and probably very efficient.\nalternatively, the logic may be made more resilient to possible variations in the file structure etc, by parsing in the \"fields\" of the file, rather than addressing these as slices of a long string. Loot into the standard library's csv module for possible parser support.\nsome tests seem goofy / always true etc (like comparing a 3 characters slice to a 2 character string literal. Aside from being logically wrong, this too points to a more \"parsed\" solution where such logical error are more readily avoided or more obvious.\n\n", "Nothing to do with your problem, but this:\n if y[11]==\"C\":\n if y[35:38]!= \"EN\":\n# I don't see any \"EN\" or \"OTE\" anywhere in your sample input.\n# In any case the above condition will always be true, because\n# y[35:38] appears to be a 3-byte string but \"EN\" is a 2-byte string.\n if y[35:38] != \"OTE\":\n if x[11]==\"C\":\n if x[12] != \"C\":\n if y[35:38] !=x[35:38]:\n print x [7:10]\n\nis ummmmm ...\nYou may wish to consider an alternative way of expression e.g.\nif (x[11] == \"C\" == y[11]\nand x[12] != \"C\"\nand y[35:38] not in (\"EN?\", \"OTE\")\nand y[35:38] != x[35:38]):\n print x[7:10]\n\n", "I haven't understood your problem fully but \nFile 1\n100 C 20.2\n300 B 33.3\n\nFile 2\n110 C 20.23\n320 B 33.34\n\nand you want to compare 3rd column of the two files.\nlines1 = file1.readlines()\nlist1 = [float(line.split()[2]) for line in lines1] # list of 3rd column values\n\nlines2 = file2.readlines()\nlist2 = [float(line.split()[2]) for line in lines2]\n\nresult = map(lambda x,y: x-y < 2,list1,list2)\n\nOR \n result = [list1[i]-list2[i] for i in range(len(list1)) if list1[i] - list2[i] > 2]\n\nIs this what you want??\n" ]
[ 2, 2, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0002387126_list_python.txt
Q: Django: Manually getting the view corresponding to a URL I have a Django project. Given a url, how can I know which view will be dispatched to handle the request? A: You want django.core.urlresolvers.resolve, which allows you to map an URL to a view and to keep your URL & view logic separate. This is the opposite of django.core.urlresolvers.reverse which allows you to map a view to a URL. See the documentation for how to use it!
Django: Manually getting the view corresponding to a URL
I have a Django project. Given a url, how can I know which view will be dispatched to handle the request?
[ "You want django.core.urlresolvers.resolve, which allows you to map an URL to a view and to keep your URL & view logic separate. This is the opposite of django.core.urlresolvers.reverse which allows you to map a view to a URL.\nSee the documentation for how to use it!\n" ]
[ 6 ]
[]
[]
[ "django", "python", "url" ]
stackoverflow_0002387427_django_python_url.txt
Q: Batch Paypal Payments Can you send a paypal payment with a script? I've been googling for this, but I can't seem to find the answer I want (yes) ;-) An example of what I am talking about: Lets say I have a site where users share in the profit. Instead of sending each users payment out manually at the end of the month, I would like to automate this with code, preferably django / python. A: Yes. This page may help: https://cms.paypal.com/us/cgi-bin/?cmd=_render-content&content_ID=developer/howto_api_masspay Clarification edit: Basically you use the mass-pay API call. However, even though it's called mass pay, I believe you can send payments to just one person with it. A: You might want to check out the Paypal API documentation
Batch Paypal Payments
Can you send a paypal payment with a script? I've been googling for this, but I can't seem to find the answer I want (yes) ;-) An example of what I am talking about: Lets say I have a site where users share in the profit. Instead of sending each users payment out manually at the end of the month, I would like to automate this with code, preferably django / python.
[ "Yes. This page may help:\nhttps://cms.paypal.com/us/cgi-bin/?cmd=_render-content&content_ID=developer/howto_api_masspay\nClarification edit:\nBasically you use the mass-pay API call. However, even though it's called mass pay, I believe you can send payments to just one person with it.\n", "You might want to check out the Paypal API documentation\n" ]
[ 2, 2 ]
[]
[]
[ "django", "paypal", "python" ]
stackoverflow_0002387591_django_paypal_python.txt
Q: What is the most pythonic way to extend a list with the reversal of another? I have one list that I want to take a slice of, reverse that slice and append each of those items onto the end of another list. The following are the options I have thought of (although if you have others please share), which of these is the most pythonic? # Option 1 tmp = color[-bits:] tmp.reverse() my_list.extend(tmp) # Option 2 my_list.extend(list(reversed(color[-bits:]))) # Option 3 my_list.extend((color[-bits:])[::-1]) A: I like my_list.extend(reversed(color[-bits:])) It explains what you are doing ( extending a list by reverse of another list's slice) and is short too. and a obligatory itertools solution my_list.extend( itertools.islice( reversed(color), 0, bits)) A: my_list.extend(color[:-(bits + 1):-1]) A: For Option #2, you can cut out the call to list. You could also use += instead of extend, like so: my_list += reversed(color[-bits:])
What is the most pythonic way to extend a list with the reversal of another?
I have one list that I want to take a slice of, reverse that slice and append each of those items onto the end of another list. The following are the options I have thought of (although if you have others please share), which of these is the most pythonic? # Option 1 tmp = color[-bits:] tmp.reverse() my_list.extend(tmp) # Option 2 my_list.extend(list(reversed(color[-bits:]))) # Option 3 my_list.extend((color[-bits:])[::-1])
[ "I like\nmy_list.extend(reversed(color[-bits:]))\n\nIt explains what you are doing ( extending a list by reverse of another list's slice) and is short too.\nand a obligatory itertools solution\nmy_list.extend( itertools.islice( reversed(color), 0, bits))\n\n", "my_list.extend(color[:-(bits + 1):-1])\n\n", "For Option #2, you can cut out the call to list. You could also use += instead of extend, like so:\nmy_list += reversed(color[-bits:])\n\n" ]
[ 4, 0, 0 ]
[]
[]
[ "list", "python", "reverse" ]
stackoverflow_0002387558_list_python_reverse.txt
Q: how can I make a suggestion for a new feature in python Suppose I think I have a great idea for some feature that should be in python's standard library. Not something of the magnitude of a new keyword etc, just a suggestion for another decorator that would help a lot, IMO. How can I suggest such a feature to the consideration of the "python committee :)"? A: It really depends on the nature of the suggestion. If it's a bug, it should definitely be put on the tracker. Otherwise, it probably should not go in the tracker right away. Python developers have specifically asked that the tracker not be used to create discussions, but to track implementation-specific aspects. You can also post to Python-dev, though you should also be careful there also. Python is a complex project. Because it's more of a platform than a project, it has vastly more restrictions on it than a typical open-source application. Therefore, developers will be resistant to any change which isn't an immediate and obvious benefit. In general, I would advise against posting to Python-dev unless you've had at least some time to read through some of the interactions there to get a feel for the types of suggestions and discussions that go on there. Generally, I think the python-dev list would recommend you post first to comp.lang.python and start a discussion. Rally some support from a vetted Python maintainer and others in the community. Be sure to show that you have considered the negative implications of any change you are considering and how you would mitigate them. A lot of times, it's good at this stage to have a reference implementation (maybe even something on the package index) that others can install--if it is indeed useful, people will use it and the need will be more apparent. After you've gathered some support from the community, you can then move it (possibly) to python-dev to get more feedback from the core developers before submitting a PEP (Python Enhancement Proposal). Good luck! A: Python is Open Source, which means that all of these processes are very open. It also means that you will have far more success if you implement the suggestion and prove its merits yourself. Normally you should establish that your proposal is a good way to solve the particular problem. This can be discussed in comp.lang.python or python-list. A more serious suggestion's details can be ironed out on the mailing list python-ideas. This is normally a free forum for proposals. When the proposal is finally ready, and you think it might be approved, it can be submitted as a Python Enhancement Proposal (PEP) to the mailing list python-dev. Posting on python-dev prematurely will probably not lead to good results. For many years now, most significant changes in Python have gone through the PEP process. This answer is written in all generality; writing a PEP for a single added decorator is probably overkill, it's something that is more expected for, exactly, a new keyword or so. A: You can add your suggestion to the issue tracker http://bugs.python.org/. they usually implement things posted there. A: Perhaps post your idea on the Python mailing list A: Either add it to the tracker, or join the developer mailing list and suggest it there. Better to do that if you feel you can contribute at least to developing the specification, if not the feature itself. A: An alternative to the issue tracker suggested by mpalcona: you can submit it for discussion on the python-dev mailing list. And always, a reference implementation (something that works, even if not in all cases and not efficiently) is always welcomed. A: Don't waste time "suggesting" things. Invest time doing things. Simply do this. Build it. Use it. Post it to SourceForge. Put a link to the SourceForge project on PyPi. Done. If it's actually a "great" idea, then everyone will use it and someone will recommend adding it to the standard library. If it's not a "great" idea, but merely good, then everyone will use it. If it's just an idea, you'll notice the number of downloads will remain small.
how can I make a suggestion for a new feature in python
Suppose I think I have a great idea for some feature that should be in python's standard library. Not something of the magnitude of a new keyword etc, just a suggestion for another decorator that would help a lot, IMO. How can I suggest such a feature to the consideration of the "python committee :)"?
[ "It really depends on the nature of the suggestion.\nIf it's a bug, it should definitely be put on the tracker. Otherwise, it probably should not go in the tracker right away. Python developers have specifically asked that the tracker not be used to create discussions, but to track implementation-specific aspects.\nYou can also post to Python-dev, though you should also be careful there also. Python is a complex project. Because it's more of a platform than a project, it has vastly more restrictions on it than a typical open-source application. Therefore, developers will be resistant to any change which isn't an immediate and obvious benefit. In general, I would advise against posting to Python-dev unless you've had at least some time to read through some of the interactions there to get a feel for the types of suggestions and discussions that go on there.\nGenerally, I think the python-dev list would recommend you post first to comp.lang.python and start a discussion. Rally some support from a vetted Python maintainer and others in the community. Be sure to show that you have considered the negative implications of any change you are considering and how you would mitigate them. A lot of times, it's good at this stage to have a reference implementation (maybe even something on the package index) that others can install--if it is indeed useful, people will use it and the need will be more apparent. After you've gathered some support from the community, you can then move it (possibly) to python-dev to get more feedback from the core developers before submitting a PEP (Python Enhancement Proposal).\nGood luck!\n", "Python is Open Source, which means that all of these processes are very open. It also means that you will have far more success if you implement the suggestion and prove its merits yourself.\nNormally you should establish that your proposal is a good way to solve the particular problem. This can be discussed in comp.lang.python or python-list.\nA more serious suggestion's details can be ironed out on the mailing list python-ideas. This is normally a free forum for proposals.\nWhen the proposal is finally ready, and you think it might be approved, it can be submitted as a Python Enhancement Proposal (PEP) to the mailing list python-dev. Posting on python-dev prematurely will probably not lead to good results. For many years now, most significant changes in Python have gone through the PEP process.\nThis answer is written in all generality; writing a PEP for a single added decorator is probably overkill, it's something that is more expected for, exactly, a new keyword or so.\n", "You can add your suggestion to the issue tracker http://bugs.python.org/. they usually implement things posted there.\n", "Perhaps post your idea on the Python mailing list\n", "Either add it to the tracker, or join the developer mailing list and suggest it there. Better to do that if you feel you can contribute at least to developing the specification, if not the feature itself.\n", "An alternative to the issue tracker suggested by mpalcona: you can submit it for discussion on the python-dev mailing list.\nAnd always, a reference implementation (something that works, even if not in all cases and not efficiently) is always welcomed.\n", "Don't waste time \"suggesting\" things. Invest time doing things.\nSimply do this.\n\nBuild it.\nUse it.\nPost it to SourceForge.\nPut a link to the SourceForge project on PyPi.\n\nDone.\nIf it's actually a \"great\" idea, then everyone will use it and someone will recommend adding it to the standard library.\nIf it's not a \"great\" idea, but merely good, then everyone will use it.\nIf it's just an idea, you'll notice the number of downloads will remain small.\n" ]
[ 10, 5, 3, 1, 0, 0, 0 ]
[]
[]
[ "pep", "python" ]
stackoverflow_0002386421_pep_python.txt
Q: Python - Can I access the object who call me? If I have this: class A: def callFunction(self, obj): obj.otherFunction() class B: def callFunction(self, obj): obj.otherFunction() class C: def otherFunction(self): # here I wan't to have acces to the instance of A or B who call me. ... # in main or other object (not matter where) a = A() b = B() c = C() a.callFunction(c) # How 'c' know that is called by an instance of A... b.callFunction(c) # ... or B Despite the design or other issues, this is only a question of an inquiring mind. Note: This has to be done without changing otherFunction signature A: If this is for debugging purposes you can use inspect.currentframe(): import inspect class C: def otherFunction(self): print inspect.currentframe().f_back.f_locals Here is the output: >>> A().callFunction(C()) {'self': <__main__.A instance at 0x96b4fec>, 'obj': <__main__.C instance at 0x951ef2c>} A: Here is a quick hack, get the stack and from last frame get locals to access self class A: def callFunction(self, obj): obj.otherFunction() class B: def callFunction(self, obj): obj.otherFunction() import inspect class C: def otherFunction(self): lastFrame = inspect.stack()[1][0] print lastFrame.f_locals['self'], "called me :)" c = C() A().callFunction(c) B().callFunction(c) output: <__main__.A instance at 0x00C1CAA8> called me :) <__main__.B instance at 0x00C1CAA8> called me :) A: Examine the stack with the inspect module with inspect.stack(). You can then get the instance from each element in the list with f_locals['self']
Python - Can I access the object who call me?
If I have this: class A: def callFunction(self, obj): obj.otherFunction() class B: def callFunction(self, obj): obj.otherFunction() class C: def otherFunction(self): # here I wan't to have acces to the instance of A or B who call me. ... # in main or other object (not matter where) a = A() b = B() c = C() a.callFunction(c) # How 'c' know that is called by an instance of A... b.callFunction(c) # ... or B Despite the design or other issues, this is only a question of an inquiring mind. Note: This has to be done without changing otherFunction signature
[ "If this is for debugging purposes you can use inspect.currentframe():\nimport inspect\n\nclass C:\n def otherFunction(self):\n print inspect.currentframe().f_back.f_locals\n\nHere is the output:\n>>> A().callFunction(C())\n{'self': <__main__.A instance at 0x96b4fec>, 'obj': <__main__.C instance at 0x951ef2c>}\n\n", "Here is a quick hack, get the stack and from last frame get locals to access self\nclass A:\n def callFunction(self, obj):\n obj.otherFunction()\n\nclass B:\n def callFunction(self, obj):\n obj.otherFunction()\n\nimport inspect\n\nclass C:\n def otherFunction(self):\n lastFrame = inspect.stack()[1][0]\n print lastFrame.f_locals['self'], \"called me :)\"\n\nc = C()\n\nA().callFunction(c)\nB().callFunction(c)\n\noutput:\n<__main__.A instance at 0x00C1CAA8> called me :)\n<__main__.B instance at 0x00C1CAA8> called me :)\n\n", "Examine the stack with the inspect module with inspect.stack(). You can then get the instance from each element in the list with f_locals['self']\n" ]
[ 11, 3, 1 ]
[]
[]
[ "function_calls", "oop", "python" ]
stackoverflow_0002387756_function_calls_oop_python.txt
Q: Calling Java app with "subprocess" from Python and reading the Java app output What is the nicest way to read the output (i.e. via System.out.println) of a Java app which is called from Python with subprocess.Popen("java MyClass", shell=True) without writing and reading a file? (Using Jython etc is not a possible solution) A: p1 = subprocess.Popen(["/usr/bin/java", "MyClass"], stdout=subprocess.PIPE) print p1.stdout.read() A: I just found the solution: p = subprocess.Popen("java MyClass", shell=True, stdout=subprocess.PIPE) output, errors = p.communicate() S.Mark's is fine too!
Calling Java app with "subprocess" from Python and reading the Java app output
What is the nicest way to read the output (i.e. via System.out.println) of a Java app which is called from Python with subprocess.Popen("java MyClass", shell=True) without writing and reading a file? (Using Jython etc is not a possible solution)
[ "p1 = subprocess.Popen([\"/usr/bin/java\", \"MyClass\"], stdout=subprocess.PIPE)\nprint p1.stdout.read() \n\n", "I just found the solution:\np = subprocess.Popen(\"java MyClass\",\n shell=True,\n stdout=subprocess.PIPE)\noutput, errors = p.communicate()\n\nS.Mark's is fine too!\n" ]
[ 5, 3 ]
[]
[]
[ "communication", "java", "python" ]
stackoverflow_0002388423_communication_java_python.txt
Q: unbound python method, potentially scope issue I'm using iPython right now to interactively set up a Twisted network. The script that I run in iPython describes best of what I have to do: import router, pdb # creates nodes which encapsulate RandomVector and VectorAdder objects a = router.LocalNode(router.RandomVector, '/topic/a_c') b = router.LocalNode(router.RandomVector, '/topic/b_c') c = router.LocalNode(router.VectorAdder) c.registerAsListener('/topic/a_c') c.registerAsListener('/topic/b_c') def conn(): global a global b a.onConnect() b.onConnect() router.r.loadOnConnect(conn) router.STOMPconnect(router.r) router.reactor.run() What's happening is that conn() is being passed to a Twisted protocol, which runs conn() every time the connection is lost. onConnect looks like this: def onConnect(self): self._lc = LoopingCall(self.advance) self._lc.start(1) Whenever onConnect gets run, I get the error: TypeError: 'unbound method onConnect() must be called with RandomVector instance as first argument (got nothing instead)' Does anyone know why this is happening? A: I don't think this is a scoping issue. Are you sure you don't need to use: a = router.LocalNode(router.RandomVector(), '/topic/a_c') b = router.LocalNode(router.RandomVector(), '/topic/b_c') i.e. instantiate the RandomVector you pass to LocalNode? This recommendation is triggered by the Unboud method error message : an unbound method is one which is linked to a class and not to an instance / object. As your message complains about a.onConnect being an unbound method, it looks like you need to pass an instance and not a class.
unbound python method, potentially scope issue
I'm using iPython right now to interactively set up a Twisted network. The script that I run in iPython describes best of what I have to do: import router, pdb # creates nodes which encapsulate RandomVector and VectorAdder objects a = router.LocalNode(router.RandomVector, '/topic/a_c') b = router.LocalNode(router.RandomVector, '/topic/b_c') c = router.LocalNode(router.VectorAdder) c.registerAsListener('/topic/a_c') c.registerAsListener('/topic/b_c') def conn(): global a global b a.onConnect() b.onConnect() router.r.loadOnConnect(conn) router.STOMPconnect(router.r) router.reactor.run() What's happening is that conn() is being passed to a Twisted protocol, which runs conn() every time the connection is lost. onConnect looks like this: def onConnect(self): self._lc = LoopingCall(self.advance) self._lc.start(1) Whenever onConnect gets run, I get the error: TypeError: 'unbound method onConnect() must be called with RandomVector instance as first argument (got nothing instead)' Does anyone know why this is happening?
[ "I don't think this is a scoping issue. Are you sure you don't need to use:\na = router.LocalNode(router.RandomVector(), '/topic/a_c')\nb = router.LocalNode(router.RandomVector(), '/topic/b_c')\n\ni.e. instantiate the RandomVector you pass to LocalNode?\nThis recommendation is triggered by the Unboud method error message : an unbound method is one which is linked to a class and not to an instance / object. As your message complains about a.onConnect being an unbound method, it looks like you need to pass an instance and not a class. \n" ]
[ 2 ]
[]
[]
[ "python", "twisted" ]
stackoverflow_0002388359_python_twisted.txt