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: Redirecting when user presses refresh button or back button Once user presses refresh or browser back button,then I want to redirect the user to one of the page for restart the application.My javaScript code is as follow: var workIsDone = false; window.onbeforeunload =confirmBrowseAway; function confirmBrowseAway(...
Redirecting when user presses refresh button or back button
Once user presses refresh or browser back button,then I want to redirect the user to one of the page for restart the application.My javaScript code is as follow: var workIsDone = false; window.onbeforeunload =confirmBrowseAway; function confirmBrowseAway() { if (!workIsDone) { alert("You are moving to choice pag...
[ "You could try this, but it only works in IE (ie8 that I tested):\n<script language=\"javascript\">\nfunction document.onkeydown() {\nif (event.keyCode == 116) {\n alert(\"MOVING AWAY\");\n window.location.href=\"/choice_page/\"; \n event.keyCode = 0; \n event.cancelBubble = true; \n return false; } \n} \...
[ 0, 0, 0 ]
[]
[]
[ "django_nonrel", "html", "javascript", "python" ]
stackoverflow_0005339549_django_nonrel_html_javascript_python.txt
Q: In list definition, can I use an else statement (for base case handling)? what I'd like to do is something like: sum([probabilities[ngram] for ngram in combination if probabilities.has_key(ngram)]) this part is just fine. What I'd like to do is make something which handles a 'base case', that is to say assumes ...
In list definition, can I use an else statement (for base case handling)?
what I'd like to do is something like: sum([probabilities[ngram] for ngram in combination if probabilities.has_key(ngram)]) this part is just fine. What I'd like to do is make something which handles a 'base case', that is to say assumes a certain probability, say .0001, if not probabilities.has_key(ngram): su...
[ "No.\nsum(probabilities.get(ngram, 0.0001) for ngram in combination)\n\n" ]
[ 3 ]
[]
[]
[ "definition", "if_statement", "list", "python" ]
stackoverflow_0005348258_definition_if_statement_list_python.txt
Q: Python program debugging: infinite loop Background: for my computer science class, we were asked to create a program that would help elementary school children learn basic math. They would select which operation they would like to learn (addition, subtraction, multiplication, or division), or choose random which w...
Python program debugging: infinite loop
Background: for my computer science class, we were asked to create a program that would help elementary school children learn basic math. They would select which operation they would like to learn (addition, subtraction, multiplication, or division), or choose random which would choose one of these operations at random...
[ "You need to put the raw_input within the while loop.\nChange main to this:\ndef main():\n \"\"\"\n main function that brings it all together\n [PURPOSE]\n \"\"\"\n show_instructions()\n selection = None\n while selection != \"q\":\n selection = raw_input ('Please select the skill you wa...
[ 5, 0 ]
[]
[]
[ "debugging", "infinite", "loops", "python" ]
stackoverflow_0005348265_debugging_infinite_loops_python.txt
Q: XMPP intregration with Facebook Chat, using Python I'm starting a project using the XMPP protocol and haven't done anything with it thus far. I would like some advice/direction in regards to my questions below. At the present moment, I know Facebook's Chat API says to use PyXMPP and pyFacebook, which is what I wil...
XMPP intregration with Facebook Chat, using Python
I'm starting a project using the XMPP protocol and haven't done anything with it thus far. I would like some advice/direction in regards to my questions below. At the present moment, I know Facebook's Chat API says to use PyXMPP and pyFacebook, which is what I will be using initially. However can someone give me an ide...
[ "You need to register your application at http://developers.facebook.com/apps and get the API keys. Both Gtalk and Facebook chat are built on XMPP protocol. So you can set up an XMPP chat client which will connect to both.\nRefer to the book written by Jack Mofitt: http://professionalxmpp.com/ \nIt talks about sett...
[ 0 ]
[ "Yes you can connect using digest MD5, where you need to pass the username and password. Go through the XMPP protocol to get a better understanding on digest MD5.\n" ]
[ -1 ]
[ "facebook", "facebook_chat", "python", "xmpp" ]
stackoverflow_0005138615_facebook_facebook_chat_python_xmpp.txt
Q: How to associate parameters with a function object? I am new to python and I find the "even functions are objects" thing really cool, so I was just playing with functions in the PyShell. The following code worked fine. def add_num(a,b): c = a + b return c x = add_num x(5,2) I was wondering whether we can sto...
How to associate parameters with a function object?
I am new to python and I find the "even functions are objects" thing really cool, so I was just playing with functions in the PyShell. The following code worked fine. def add_num(a,b): c = a + b return c x = add_num x(5,2) I was wondering whether we can store the parameters when we are assigning x = add_num. So t...
[ "The partial function in the functools module (documentation) can create a new function object behaving like you want.\nimport functools\n\ndef add_num(a, b):\n c = a + b\n return c\n\nx = functools.partial(add_num, 5, 2)\nprint(x()) # prints 7\n\nYou can also specify only one argument, and provide the other ...
[ 5, 1, 1, 0 ]
[]
[]
[ "function", "object", "python" ]
stackoverflow_0005348491_function_object_python.txt
Q: generating exception classes via decorators in python While coding, I have to do this frequently; class MyClassException(Exception): def __init__(self, _message): self.message = _message class MyClass(object): def __init__(self, value): raise MyClassException("What's up?") It'd be nice to...
generating exception classes via decorators in python
While coding, I have to do this frequently; class MyClassException(Exception): def __init__(self, _message): self.message = _message class MyClass(object): def __init__(self, value): raise MyClassException("What's up?") It'd be nice to be able to have my Exception classes via a decorator call,...
[ "Here's one possibility. Note that the exception class will be a member of the decorated class, it is not at global scope.\n# The decorator\ndef class_with_exception(cls):\n def init(self, _message=''):\n self.message = _message\n excname = 'ClsException'\n excclass = type(excname, (Exception,), {'...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0005348464_python.txt
Q: Python: UnicodeEncodeError when reading from stdin When running a Python program that reads from stdin, I get the following error: UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 320: ordinal not in range(128) How can I fix it? Note: The error occurs internal to antlr and the line looks like ...
Python: UnicodeEncodeError when reading from stdin
When running a Python program that reads from stdin, I get the following error: UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 320: ordinal not in range(128) How can I fix it? Note: The error occurs internal to antlr and the line looks like that: self.strdata = unicode(data) Since I don'...
[ "The problem is, that when reading from stdin, python decodes\nit using the system default encoding:\n>>> import sys\n>>> sys.getdefaultencoding()\n'ascii'\n\nThe input is very likely UTF-8 or Windows-CP-1252, so the program\nchokes on non-ASCII-characters.\nTo convert sys.stdin to a stream with the proper decoder,...
[ 14, 1, 1 ]
[]
[]
[ "antlr", "python", "stdin", "unicode" ]
stackoverflow_0002467928_antlr_python_stdin_unicode.txt
Q: How to call view from view.py in /admin url in django How we can provide all objects of class which are stored in mysql data when application start with /admin url. A: By using a sql query. This is really basic stuff, like the other questions you have asked. Buy a book or use google, there's plenty of info out t...
How to call view from view.py in /admin url in django
How we can provide all objects of class which are stored in mysql data when application start with /admin url.
[ "By using a sql query. This is really basic stuff, like the other questions you have asked. Buy a book or use google, there's plenty of info out there on this stuff.\n" ]
[ 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0005348981_django_python.txt
Q: How can I arrange multichoice-field items alphabetically? I have a multichoice-field in my forms in which names of various staffs are populated. I want these names to appear in an alphabetic order, they are populated in a random order currently. A: In your models.py you need to set the ordering in the Meta class...
How can I arrange multichoice-field items alphabetically?
I have a multichoice-field in my forms in which names of various staffs are populated. I want these names to appear in an alphabetic order, they are populated in a random order currently.
[ "In your models.py you need to set the ordering in the Meta class of your staff class.\nFor example, assuming this is your class:\nclass Staff(models.Model):\n name = models.CharField(max_length=100)\n ...\n class Meta:\n ordering = [u'name']\n\n" ]
[ 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0005349130_django_python.txt
Q: Is it possible to colour a specific item in a Listbox widget? I'm referring to a specific element in the Listbox widget. Colouring the background is most desired but any form of colouring for a specific cell would be fantastic. A: According to the effbot.org documentation regarding the Listbox widget you cannot...
Is it possible to colour a specific item in a Listbox widget?
I'm referring to a specific element in the Listbox widget. Colouring the background is most desired but any form of colouring for a specific cell would be fantastic.
[ "According to the effbot.org documentation regarding the Listbox widget you cannot change the color of spefic items:\n\nThe listbox can only contain text items, and all items must have the same font and color\n\nBut actually you can change both the font and background colors of specific items, by using the itemconf...
[ 44 ]
[]
[]
[ "colors", "listbox", "python", "tkinter", "user_interface" ]
stackoverflow_0005348454_colors_listbox_python_tkinter_user_interface.txt
Q: Approach for parsing file and creating dynamic data structure for use by another program All, Background: I have a customer who has some build scripts for their datacenter based on python that I've inherited. I did not work on the original design so I'm sort of limited to some degree on what I can and can't change...
Approach for parsing file and creating dynamic data structure for use by another program
All, Background: I have a customer who has some build scripts for their datacenter based on python that I've inherited. I did not work on the original design so I'm sort of limited to some degree on what I can and can't change. That said, my customer has a properties file that they use in their datacenter. Some of the ...
[ "\nCreate a sqlite database to\nrepresent the data in the properties\nfile. \nWrite a script to dump the data from\n the properties file into the sqlite\n database.\nWrite a script that can regenerate\n the properties file based on the\n data in the sqlite database. New hosts can now be added by inserti...
[ 3, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005344547_python.txt
Q: Retrieving date from a datetime column in python/django I have a column in my database which is named date... in this column i am storing a datetime value...now when i want to filter the table according to date value(only date and not datetime)..say i want to retrieve all coloums having a particular date..then how...
Retrieving date from a datetime column in python/django
I have a column in my database which is named date... in this column i am storing a datetime value...now when i want to filter the table according to date value(only date and not datetime)..say i want to retrieve all coloums having a particular date..then how can i apply such filtering(i.e getting date out of datetime ...
[ "For example, to match March 18, 2011:\nqueryset = MyModel.objects.filter(date__year=2011, date__month=3, date__day=18)\n\nDjango docs: http://docs.djangoproject.com/en/1.2/ref/models/querysets/#year\n", "You can also do:\nMyModel.objects.filter(date__gte=date, date__lt=date+datetime.timedelta(1))\n\nNot sure whi...
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005348520_python.txt
Q: Why does importing httplib2 work on the command line, but not in Eclipse with PyDev? As you can see ,I use windows command line running one line: import httplib2 There is no error. But when using Eclipse and PyDev, I got an error! And the version of Python is same. I did have two versions of python, 2.7.1 and 3.1...
Why does importing httplib2 work on the command line, but not in Eclipse with PyDev?
As you can see ,I use windows command line running one line: import httplib2 There is no error. But when using Eclipse and PyDev, I got an error! And the version of Python is same. I did have two versions of python, 2.7.1 and 3.1.3, and my system path points to 2.7.1. Who can explain this to me? Thanks.
[ "You've called your script http.py. This shadows the http package in the stdlib. Rename your script.\n" ]
[ 4 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0005349503_python_python_3.x.txt
Q: Do list comprehensions in Python reduce in a memory efficient manner? I am a beginner at Python, and this is my first post, so don't be too harsh :). I've been playing around with Python lately and was wondering if something like max([x for x in range(25)]) would result in Python first creating a list of all the...
Do list comprehensions in Python reduce in a memory efficient manner?
I am a beginner at Python, and this is my first post, so don't be too harsh :). I've been playing around with Python lately and was wondering if something like max([x for x in range(25)]) would result in Python first creating a list of all the elements and then finding the max, resulting in O(2n) time, or it would ke...
[ "Your example will result in Python first building the entire list. If you want to avoid that, you can use a generator expression instead:\nmax((x for x in range(25)))\n\nor simply:\nmax(x for x in range(25))\n\nOf course (in Python 2), range itself builds an entire list, so what you really want in this case is:\n...
[ 14, 2 ]
[]
[]
[ "list", "python", "reduce" ]
stackoverflow_0005349755_list_python_reduce.txt
Q: Writing a multiplayer game in Django I'm planning to write a multiplayer card game in Django. There may be several concurrent games. I already have a Python CardGame class that contains the engine for the game, and for every game that is created I will need one instance of this class, to be open until the game is ...
Writing a multiplayer game in Django
I'm planning to write a multiplayer card game in Django. There may be several concurrent games. I already have a Python CardGame class that contains the engine for the game, and for every game that is created I will need one instance of this class, to be open until the game is closed. This object will basically keep th...
[ "You could look into serializing your data and store it in a key-value store like redis for example (which is superfast).\n" ]
[ 3 ]
[]
[]
[ "database", "django", "game_engine", "python" ]
stackoverflow_0005349672_database_django_game_engine_python.txt
Q: Pymacs error starting Emacs after installing Python I installed python using one of the msi files. But when I start up emacs, it gives me: Problem 1, which I thought I'd fixed When I run cmd and type in python, I get "python" is not recognized as an internal or external command, operable program or batch file. So...
Pymacs error starting Emacs after installing Python
I installed python using one of the msi files. But when I start up emacs, it gives me: Problem 1, which I thought I'd fixed When I run cmd and type in python, I get "python" is not recognized as an internal or external command, operable program or batch file. So from online sources, (windows 7 btw) Went to System Prop...
[ "I think that your executable must be \"python\" instead of \"python2.7\" (for example).\nIn addition, Pymacs must be installed into the site-packages directory (or a directory in your PYTHONPATH env variable) of your python directory (on UNIX based systems, I use 'pip' or 'easy_install').\nFinally, pymacs.el must ...
[ 1 ]
[]
[]
[ "emacs", "pymacs", "python" ]
stackoverflow_0003963273_emacs_pymacs_python.txt
Q: Python image filtering with PIL and Numpy too slow I'm trying to implement the simpliest Gauss filter in Python with PIL and Numpy. All works fine but very slowly :( Can't figure out how to speed up. Could you help? import os, sys import Image, ImageEnhance import numpy as np if (len(sys.argv) > 1): i...
Python image filtering with PIL and Numpy too slow
I'm trying to implement the simpliest Gauss filter in Python with PIL and Numpy. All works fine but very slowly :( Can't figure out how to speed up. Could you help? import os, sys import Image, ImageEnhance import numpy as np if (len(sys.argv) > 1): im = Image.open(sys.argv[1]) data = np.array(im.res...
[ "Have a look at the answers for this question here.\nGaussian blur filters are separable, which means you can reduce the complexity of your algorithm quite a bit (on top of looking into the suggestions from other answers, i.e. parallelization).\n", "Have you tried profiling this? If you find where you're spending...
[ 1, 0 ]
[]
[]
[ "numpy", "python", "python_imaging_library" ]
stackoverflow_0005349521_numpy_python_python_imaging_library.txt
Q: how to map the string using python this is my code : a= ''' ddwqqf{x}''' def b(): ... c=b(a,{'x':'!!!!!'}) print c i want to get ddwqqf!!!!! , so how to create the b function , thanks updated: but how to do this thing : a= ''' ddwqqf{x},{'a':'aaaa'}''' c = a.format(x="!!!!!") d= open('a.txt','a') d.write...
how to map the string using python
this is my code : a= ''' ddwqqf{x}''' def b(): ... c=b(a,{'x':'!!!!!'}) print c i want to get ddwqqf!!!!! , so how to create the b function , thanks updated: but how to do this thing : a= ''' ddwqqf{x},{'a':'aaaa'}''' c = a.format(x="!!!!!") d= open('a.txt','a') d.write(c) it show error : Traceback (most rece...
[ "Try\ndef b(a, d):\n return a.format(**d)\n\nThis works in Python 2.6 or above. Of course you would not need to define a function for this:\na = \" ddwqqf{x}\"\nc = a.format(x=\"!!!!!\")\n\nwill be enough.\nEdit regarding your update:\na = \" ddwqqf{x},{{'a':'aaaa'}}\"\n\nto avoid substitutions for the second p...
[ 3 ]
[]
[]
[ "python", "string" ]
stackoverflow_0005350566_python_string.txt
Q: How can i simply detect mouse movement in python? How can i detect mouse movement in a python script in linux? I want to then send those events to a handler which will dispatch that where i can process it later. There is no gui installed if that matters. A: You could try reading /dev/input/mice. A: You can rea...
How can i simply detect mouse movement in python?
How can i detect mouse movement in a python script in linux? I want to then send those events to a handler which will dispatch that where i can process it later. There is no gui installed if that matters.
[ "You could try reading /dev/input/mice.\n", "You can read from the event device node. But the data is a stream of structures. Here is some python code that does that already. You can use it as an example (or just use it). :-)\n" ]
[ 2, 1 ]
[]
[]
[ "linux", "python" ]
stackoverflow_0005350491_linux_python.txt
Q: Storing/Retrieving/Editing project specific data with Django I'm new to Django and I'm working on the public website for a small company. I'm facing an issue that I guess has already been encountered by lots a django noobs, but I can't manage to find a good solution. My problem is that there some informations (co...
Storing/Retrieving/Editing project specific data with Django
I'm new to Django and I'm working on the public website for a small company. I'm facing an issue that I guess has already been encountered by lots a django noobs, but I can't manage to find a good solution. My problem is that there some informations (contact address, office phone number, company description...) that ...
[ "If you look into caching solutions, they will probably do what you need.\nThe general queryset caching solution I use in johnny-cache, but for what you need, you can probably just load it up from the db and store it in the cache.\n", "What you want to do is use select_related('contact_profile','office_data') etc...
[ 1, 0 ]
[]
[]
[ "django", "django_admin", "django_models", "python" ]
stackoverflow_0005350089_django_django_admin_django_models_python.txt
Q: Generate a django queryset based on dict keys I have a dict like: { 'key1' : val1, 'key2' : val2 } And I need a queryset like Q(key1__icontains = val1) | Q(key2__icontains = val2) Thanks A: reduce(operator.or_, Q(**{key + '__icontains': val}) for (key, val) in D.iteritems()) A: There's a more pragmat...
Generate a django queryset based on dict keys
I have a dict like: { 'key1' : val1, 'key2' : val2 } And I need a queryset like Q(key1__icontains = val1) | Q(key2__icontains = val2) Thanks
[ "reduce(operator.or_, Q(**{key + '__icontains': val}) for (key, val) in D.iteritems())\n\n", "There's a more pragmatic approach, as I need to generate various keys from one.\nquery = None\nfor key, value in d.iteritems():\n if query is None:\n query = Q(**{key + \"__icontains\" : value})\n else:\n ...
[ 8, 1 ]
[]
[]
[ "dictionary", "django", "django_queryset", "python" ]
stackoverflow_0005350846_dictionary_django_django_queryset_python.txt
Q: class with changing parameters I want to define a Python class that accepts different variables as input. However I only want to declare one of them when calling the class, because the variables determine each other and in different situations I have different inputs at hand. So it should be something like a class...
class with changing parameters
I want to define a Python class that accepts different variables as input. However I only want to declare one of them when calling the class, because the variables determine each other and in different situations I have different inputs at hand. So it should be something like a class price that I call as: foo = price(d...
[ "You should use dictionary for keyword arguments. Here is how you can define it in constructor:\nclass Price:\n def __init__(self, **kwargs):\n if 'dollar' in kwargs and 'euro' in kwargs:\n raise Exception(..)\n if 'dollar' in kwargs:\n self.dollar = kwargs['dollar']\n e...
[ 4 ]
[]
[]
[ "python" ]
stackoverflow_0005351069_python.txt
Q: Is this a safe use of python eval()? If an attacker can control the value of attacker_controlled_nasty_variable, is this segment of code vulnerable? dic={"one":1, "nasty":attacker_controlled_nasty_variable, } store=str(dict) ... dic=eval(store) A: Use ast.literal_eval() instead of eval(). A: Yes. I...
Is this a safe use of python eval()?
If an attacker can control the value of attacker_controlled_nasty_variable, is this segment of code vulnerable? dic={"one":1, "nasty":attacker_controlled_nasty_variable, } store=str(dict) ... dic=eval(store)
[ "Use ast.literal_eval() instead of eval().\n", "Yes. It could be replaced with an object that has a __repr__() method that either has a payload itself, or returns a string that could be unsafe when passed to eval().\nProof of Concept:\nclass MyClass(object):\n def __repr__(self):\n return 'os.system(\"format ...
[ 11, 6, 3, 1 ]
[]
[]
[ "python", "security" ]
stackoverflow_0005351059_python_security.txt
Q: Why my sql doesn't execute? I have a python script that needs to update a database information. So, in my init() method, I start the connection. But when I call the update method, the script does not give me any answer, it seems like it is into an infinite loop. def update(self,id,newDescription): try: ...
Why my sql doesn't execute?
I have a python script that needs to update a database information. So, in my init() method, I start the connection. But when I call the update method, the script does not give me any answer, it seems like it is into an infinite loop. def update(self,id,newDescription): try: sql="""UPDATE table SET table....
[ "You are forgetting to call commit.\n", "Not sure about how to do it in python script, but i think you need to call a \"commit\" before closing connection. Otherwise oracle rollsback your transaction.\nTry adding con.commit() before close()\n" ]
[ 2, 1 ]
[]
[]
[ "oracle", "python" ]
stackoverflow_0005351208_oracle_python.txt
Q: stretching an image to fill a canvas in tkinter I have a PhotoImage that I am loading into my cavas using create_image(). I can anchor this image and move it around the canvas, but I can't seem to find a way to stretch it so it fills the canvas. I can zoom() on the PhotoImage, but this takes an integer zoom coeffi...
stretching an image to fill a canvas in tkinter
I have a PhotoImage that I am loading into my cavas using create_image(). I can anchor this image and move it around the canvas, but I can't seem to find a way to stretch it so it fills the canvas. I can zoom() on the PhotoImage, but this takes an integer zoom coefficent, so if the canvas is much larger than the image ...
[ "No, there isn't a way. Tkinter can only scale images by integer factors. Your only solution is to use another library (such as PIL) to resize the image. \n" ]
[ 1 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0005351012_python_tkinter.txt
Q: Django form QuerySet for ModelChoiceField I've got a Form which I'm using the following field in. contact_country = forms.ModelChoiceField(queryset=Country.objects.all()) The Country model looks like this class Country(models.Model): iso = models.CharField(max_length=2) name = models.CharField(max_length=...
Django form QuerySet for ModelChoiceField
I've got a Form which I'm using the following field in. contact_country = forms.ModelChoiceField(queryset=Country.objects.all()) The Country model looks like this class Country(models.Model): iso = models.CharField(max_length=2) name = models.CharField(max_length=80) printable_name = models.CharField(max_l...
[ "Does contact_country = forms.ModelChoiceField(queryset=Country.objects.order_by('special')) work?\n", "This is untested, so you may give it a try, but it may not give it what you want...\nin your view do this:\nspecials = Country.objects.filter(special=True)\nall_of = Country.objects.all()\n\n# worst thing is, t...
[ 2, 0, 0 ]
[]
[]
[ "django", "django_forms", "python" ]
stackoverflow_0003978059_django_django_forms_python.txt
Q: Can i set float128 as the standard float-array in numpy So I have a problem with my numerical program, and I'm curious about whether it is a precision problem (i.e. round-off error). Is there a quick way to change all the float arrays in my program into float128 arrays, without going through my code and typing dty...
Can i set float128 as the standard float-array in numpy
So I have a problem with my numerical program, and I'm curious about whether it is a precision problem (i.e. round-off error). Is there a quick way to change all the float arrays in my program into float128 arrays, without going through my code and typing dtype='float128' all over the place. My arrays are all float64, ...
[ "I don't think there is a central \"configuration\" you could change to achieve this. Some options what you could do:\n\nIf you are creating arrays only by very few of NumPy's factory functions, substitute these functions by your own versions. If you import these functions like\nfrom numpy import empty\n\nyou can...
[ 19 ]
[]
[]
[ "numpy", "python", "types" ]
stackoverflow_0005350342_numpy_python_types.txt
Q: Compile DLL from python code Hi does anyone know if you can compile Python code into a Windows DLL file? How would you go about doing this? A: One way would be to create a C or C++ library that embeds the Python interpreter and runs your Python code. Another option would be to translate you Python code to C++ wi...
Compile DLL from python code
Hi does anyone know if you can compile Python code into a Windows DLL file? How would you go about doing this?
[ "One way would be to create a C or C++ library that embeds the Python interpreter and runs your Python code.\nAnother option would be to translate you Python code to C++ with ShedSkin and make that a DLL, although I wouldn't expect a very clean API to come out of this.\n" ]
[ 5 ]
[]
[]
[ "compilation", "dll", "python" ]
stackoverflow_0005351715_compilation_dll_python.txt
Q: Django filter_horizontal in form In admin definition attribute filter_horizontal can be specified, that creates cool javascript using widget for ManyToMany field. I would like to use such widget in my Model form. How can I specify this? A: http://www.hoboes.com/Mimsy/hacks/replicating-djangos-admin/reusing-djang...
Django filter_horizontal in form
In admin definition attribute filter_horizontal can be specified, that creates cool javascript using widget for ManyToMany field. I would like to use such widget in my Model form. How can I specify this?
[ "http://www.hoboes.com/Mimsy/hacks/replicating-djangos-admin/reusing-djangos-filter_horizontal/\n" ]
[ 1 ]
[]
[]
[ "django", "django_forms", "python" ]
stackoverflow_0005348595_django_django_forms_python.txt
Q: help with changing icon of Tk window root = Tk() w=350 h=200 # get screen width and height ws = root.winfo_screenwidth() hs = root.winfo_screenheight() # calculate position x, y x = (ws/2) - (w/2) y = (hs/2) - (h/2) root.geometry('%dx%d+%d+%d' % (w, h, x, y)) root.iconbitmap(default='images/account.gif') ...
help with changing icon of Tk window
root = Tk() w=350 h=200 # get screen width and height ws = root.winfo_screenwidth() hs = root.winfo_screenheight() # calculate position x, y x = (ws/2) - (w/2) y = (hs/2) - (h/2) root.geometry('%dx%d+%d+%d' % (w, h, x, y)) root.iconbitmap(default='images/account.gif') Label(root, text='Window with transparen...
[ "You have to give it a bitmap argument, you can't just give it a default. Also, you can't use .gif as an image. It needs to be a .xbm, or I think a .ico on windows. \n" ]
[ 2 ]
[]
[]
[ "python", "tk_toolkit" ]
stackoverflow_0005351703_python_tk_toolkit.txt
Q: How to shorten this expression using regex I have the following if statement: if not fileName.startswith(".") and re.search("(.exe|.EXE)$", fileName) is not None and not fileName.endswith("-xyz.exe"): pass Essentially, I would like to check that the filename does not start with a period and ends with either ....
How to shorten this expression using regex
I have the following if statement: if not fileName.startswith(".") and re.search("(.exe|.EXE)$", fileName) is not None and not fileName.endswith("-xyz.exe"): pass Essentially, I would like to check that the filename does not start with a period and ends with either .exe or .EXE extension, but not with the -xyz.exe...
[ "This one is pretty simple actually:\nif re.search(\n r\"\"\"# Always use VERBOSE when composing non-trivial regex!\n ^ # Anchor to start of string.\n # Apply multiple lookahead assertions from string start:\n (?!\\.) # Assert does NOT begin with dot.\n (?=.*\\.exe$) #...
[ 2, 2, 1, 1, 1, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0005348327_python_regex.txt
Q: How to select all objects that aren't in a manytomany relation in Django I have the following models (resumed) in an application: class Account(models.Model): name = models.CharField(max_length=64) plans = models.ManyToManyField('Plan') extra_services = models.ManyToManyField('Service') class Plan(mod...
How to select all objects that aren't in a manytomany relation in Django
I have the following models (resumed) in an application: class Account(models.Model): name = models.CharField(max_length=64) plans = models.ManyToManyField('Plan') extra_services = models.ManyToManyField('Service') class Plan(models.Model): name = models.CharField(max_length=64) services = models.M...
[ "Service.objects.filter(plan_set__isnull=True) should do.\nYou may find further explanation in the documentation.\n", "OK, I got this using a raw SQL query:\nservices = Service.objects.raw('SELECT * FROM accounts_service WHERE id NOT IN(SELECT service_id FROM accounts_plan_services);')\n\nAnyway, can I do this wi...
[ 4, 1 ]
[]
[]
[ "django", "django_admin", "manytomanyfield", "python" ]
stackoverflow_0005351392_django_django_admin_manytomanyfield_python.txt
Q: How do I build a python string from a ctype struct? I'm using ctypes and I've defined this struct in order to pass parameters class my_struct(ctypes.Structure): _fields_ = [ ("buffer", ctypes.c_char * BUFSIZE), ("size", ctypes.c_int )] Then I call the C function using the following code, but ...
How do I build a python string from a ctype struct?
I'm using ctypes and I've defined this struct in order to pass parameters class my_struct(ctypes.Structure): _fields_ = [ ("buffer", ctypes.c_char * BUFSIZE), ("size", ctypes.c_int )] Then I call the C function using the following code, but I don't know how to create a string from the struct I've ...
[ "Your problem is that ctypes tries to do some magic for you with char arrays, auto-converting them into NUL-terminated strings. You can get around this magic by using the ctypes.c_byte type instead of ctypes.c_char and retrieving the value as a string with ctypes.string_at. You can make accessing the member a lit...
[ 3, 0 ]
[]
[]
[ "c", "ctypes", "python", "string" ]
stackoverflow_0005082753_c_ctypes_python_string.txt
Q: Verification needed: Clearable Python Queue class Since I'm not an expert for Python and multi-threaded programming I'd like to ask you if my implementation is correct. My aim was to extend the Queue class so it can be cleared. And the removed items should be returned. That's all. My implementation is: import Queu...
Verification needed: Clearable Python Queue class
Since I'm not an expert for Python and multi-threaded programming I'd like to ask you if my implementation is correct. My aim was to extend the Queue class so it can be cleared. And the removed items should be returned. That's all. My implementation is: import Queue class ClearableQueue(Queue.Queue): def __init__...
[ "If you look at the source, you'll see that the standard way to access the mutex wraps the mutating code in a try: finally block in case something goes wrong:\nimport Queue\n\nclass ClearableQueue(Queue.Queue):\n\n def __init__(self, maxsize):\n Queue.Queue.__init__(self, maxsize)\n\n def clear(self):\...
[ 3, 1 ]
[]
[]
[ "python", "queue", "verification" ]
stackoverflow_0005349101_python_queue_verification.txt
Q: regex script in python or perl It would really make my work easier if someone could help me with writing script in python or perl in which from given file it retreives all sentences like: [LANG::...] ... means anything for ecxample: [LANG::Sample text with digits 0123] and writes it to the fileeach in single li...
regex script in python or perl
It would really make my work easier if someone could help me with writing script in python or perl in which from given file it retreives all sentences like: [LANG::...] ... means anything for ecxample: [LANG::Sample text with digits 0123] and writes it to the fileeach in single line. Thanks very much for help EDIT:...
[ "import re\n\nwith open('input.txt', 'w') as f:\n text = f.read()\n#text = 'Intro [LANG::First text 1] goes on [LANG::Second text 2] and finishes.'\n\nwith open('output.txt', 'w') as f:\n for match in re.findall('\\[LANG::.*?\\]', text):\n f.write(match+'\\n')\n\noutputs:\n[LANG::First text 1]\n[LANG::...
[ 5, 4, 2, 0 ]
[]
[]
[ "perl", "python", "regex" ]
stackoverflow_0005349783_perl_python_regex.txt
Q: Python list dictionary comprehension I have a few 'list' containing few dictionaries- say 3 dicts. 3 dictionaries as follows: lstone = [{'dc_test': 1}, {'ac_test':2}, {'con_test':3}] lsttwo = [{'dc_test': 4}, {'ac_test':5}, {'con_test':6}] How do i create new lists as follows: newlistone = ['dc_test',1,4] newlist...
Python list dictionary comprehension
I have a few 'list' containing few dictionaries- say 3 dicts. 3 dictionaries as follows: lstone = [{'dc_test': 1}, {'ac_test':2}, {'con_test':3}] lsttwo = [{'dc_test': 4}, {'ac_test':5}, {'con_test':6}] How do i create new lists as follows: newlistone = ['dc_test',1,4] newlisttwo = ['ac_test',2,5] newlistthree = ['con...
[ "First convert your list to dictionaries\nd = [dict(itertools.chain(*(d.iteritems() for d in a)))\n for a in [lstone, lsttwo]]\n\nNext build the transposed list:\nkeys = d[0].keys()\ntransposed = [[e[k] for k in keys] for e in d]\n\nFinally, transpose and use csv.writer to write this to a file:\nwith open(\"a.c...
[ 7, 2, 1 ]
[]
[]
[ "dictionary", "list", "list_comprehension", "python" ]
stackoverflow_0005351985_dictionary_list_list_comprehension_python.txt
Q: QScrollView with no scrollbars I'm trying to make a QScrollView with around 100 different labels and buttons. But after I add them, the scrollbars do not appear. here is an example of the code I wrote: self.btn = {} self.scroll = QScrollView(self) self.scroll.setGeometry(QRect(0,0,300,300)) self.scroll.enableClip...
QScrollView with no scrollbars
I'm trying to make a QScrollView with around 100 different labels and buttons. But after I add them, the scrollbars do not appear. here is an example of the code I wrote: self.btn = {} self.scroll = QScrollView(self) self.scroll.setGeometry(QRect(0,0,300,300)) self.scroll.enableClipper(True) vp = self.scroll.viewport(...
[ "You don't add all your little items to the scrollview. You have to insert a single, large container (a QFrame derived class, for example) into the scrollview that contains all your smaller widgets.\n", "Actually you just need to give the scroll-view a layout and add your widgets to this. Adding them as sub-widge...
[ 1, 0 ]
[]
[]
[ "python", "qt", "qt3" ]
stackoverflow_0005352998_python_qt_qt3.txt
Q: Errors during downloading data from Google App Engine using bulkloader I am trying to download some data from the datastore using the following command: appcfg.py download_data --config_file=bulkloader.yaml --application=myappname --kind=mykindname --filename=myappname_mykindname.csv ...
Errors during downloading data from Google App Engine using bulkloader
I am trying to download some data from the datastore using the following command: appcfg.py download_data --config_file=bulkloader.yaml --application=myappname --kind=mykindname --filename=myappname_mykindname.csv --url=http://myappname.appspot.com/_ah/remote_api When ...
[ "I am going to make a completely uneducated guess at this just based on the fact that I saw the word \"unicode\" in the first error; I had an issue that was related to my data being user generated from the web. A user put in a few unicode characters and a whole load of stuff started breaking - probably my fault - a...
[ 0 ]
[]
[]
[ "bulkloader", "google_app_engine", "python" ]
stackoverflow_0005263690_bulkloader_google_app_engine_python.txt
Q: Python - How do I write a more efficient, Pythonic reduce? I'm trying to build a very lightweight Node class to serve as a Python-based hierarchy search tool. See the definition below. from functools import reduce from operator import or_ class Node: def __init__(self, name): self.name = name ...
Python - How do I write a more efficient, Pythonic reduce?
I'm trying to build a very lightweight Node class to serve as a Python-based hierarchy search tool. See the definition below. from functools import reduce from operator import or_ class Node: def __init__(self, name): self.name = name self.children = [] def add_child(self, child_node): ...
[ "I think (not tested) that you instead of reduce should use any like this, which will stop on the first hit:\nreturn any(child.contains(other_node) for child in self.children)\n\nBy the way, did you mean for a.contains(b) to return False when a == b and len(a.children) > 0?\nEdit: If your tree contains a loop, like...
[ 5 ]
[]
[]
[ "algorithm", "graph", "python", "tree" ]
stackoverflow_0005353727_algorithm_graph_python_tree.txt
Q: proximity matrix in python What is the best way to compute the distance/proximity matrix for very large sparse vectors? For example you are given the following design matrix, where each row is 68771 dimensional sparse vector. designMatrix <5830x68771 sparse matrix of type '' with 1229041 stored el...
proximity matrix in python
What is the best way to compute the distance/proximity matrix for very large sparse vectors? For example you are given the following design matrix, where each row is 68771 dimensional sparse vector. designMatrix <5830x68771 sparse matrix of type '' with 1229041 stored elements in Compressed Sparse Ro...
[ "Have you tried the routines in scipy.spatial.distance?\nhttp://docs.scipy.org/doc/scipy/reference/spatial.distance.html\nIf this forces you to go to a dense representation, then you may be better off rolling your own, depending on the density of nonzero elements. You could squeeze out the zeros while retaining a m...
[ 1 ]
[]
[]
[ "python", "scipy" ]
stackoverflow_0005353708_python_scipy.txt
Q: Iterating over the grouped union of many interators I'm trying to loop over a dict of many iterators ... they are many terabytes in size but sorted. A simple example is like this: t = { 'a': iter([1,1,1,2,2,3,3,4,6,7,7,7]), 'b': iter([2,2,2,3,3,4,6,6,6,7,7,7]), 'c': iter([1,1,1,4,4,6,6,7,7]), 'd': iter([1,1,1,3,3,...
Iterating over the grouped union of many interators
I'm trying to loop over a dict of many iterators ... they are many terabytes in size but sorted. A simple example is like this: t = { 'a': iter([1,1,1,2,2,3,3,4,6,7,7,7]), 'b': iter([2,2,2,3,3,4,6,6,6,7,7,7]), 'c': iter([1,1,1,4,4,6,6,7,7]), 'd': iter([1,1,1,3,3,3,7,7,7]) } I need to yield a dict for each unique item ...
[ "So far I've been able to come up with something like this:\ngrouped = {}\nfor key, item in t.items():\n grouped[key] = groupby(item):\n\ncurrent_items = {}\nfor key, val in grouped.items():\n current_items[key] = val.next()\n\nwhile current_items:\n #find the first one\n this_item = min((item for item, _ in cu...
[ 0 ]
[]
[]
[ "iteration", "python" ]
stackoverflow_0005353596_iteration_python.txt
Q: Why isn't this infinite recursion? I would like to ask you about a code in Python: class UserDict: def __init__(self, dict=None, **kwargs): self.data = {} if dict is not None: self.update(dict) if len(kwargs): self.update(kwargs) def clear(self): self.data.c...
Why isn't this infinite recursion?
I would like to ask you about a code in Python: class UserDict: def __init__(self, dict=None, **kwargs): self.data = {} if dict is not None: self.update(dict) if len(kwargs): self.update(kwargs) def clear(self): self.data.clear() Here, clear(self) is a method of ...
[ "UserDict.clear() calls self.data.clear(). self.data is of type dict, not UserDict, so it calls a different method, not itself. It would be an infinite recursion if UserDict.clear() called self.clear() instead of self.data.clear().\n", "No, This method calls the clear method of the data dict, which is totally u...
[ 6, 2 ]
[]
[]
[ "function", "python", "recursion" ]
stackoverflow_0005353940_function_python_recursion.txt
Q: Google App Engine Static Files GET 404 The following app.yaml works great on my local dev server.. but when I deploy it to production all static files throw 404. Server isn't able to locate any static files. Have been searching for hours couldn't find a valid solution. Note: I am developing with mac, so aware of ...
Google App Engine Static Files GET 404
The following app.yaml works great on my local dev server.. but when I deploy it to production all static files throw 404. Server isn't able to locate any static files. Have been searching for hours couldn't find a valid solution. Note: I am developing with mac, so aware of the case sensitive nature of the system. app...
[ "Take a look at the app.yaml in this gist:\nhttps://gist.github.com/873098\nIt successfully serves a static site. The main differences I see are the lack of the './' as noted by @Wooble above, and the use of (.*) instead of (.+) as the main regular expression. (.+) should work in theory though.\n" ]
[ 7 ]
[]
[]
[ "google_app_engine", "http_status_code_404", "python" ]
stackoverflow_0005349671_google_app_engine_http_status_code_404_python.txt
Q: Python equivalent from a very simple Java program example I'm currently reading the official Java tutorial and I'd like to compare an example of code given to its equivalent in Python. Could someone please give me the equivalent Python code for the following Java code : class Bicycle { int cadence = 0; int ...
Python equivalent from a very simple Java program example
I'm currently reading the official Java tutorial and I'd like to compare an example of code given to its equivalent in Python. Could someone please give me the equivalent Python code for the following Java code : class Bicycle { int cadence = 0; int speed = 0; int gear = 1; void changeCadence(int newValue...
[ "Relevant Information located at docs.python.org\n", "It should be :\nclass Bicycle:\n\n def __init__(self):\n self.cadence = 0\n self.speed = 0 \n self.gear =1\n\n\n\n\n def changeCadence(self, newValue):\n self.cadence = newValue\n\n\n def changeGear(self, newValue):\n ...
[ 1, 1, 0 ]
[ "More complete and more correct code - object is important since it change class model - contructor in this case is not since not input parameters - python have faster initialization in this case.\nHave a fun ...\nclass Bicycle(object):\n cadence = 0\n speed = 0\n gear = 1\n\n def changeCadence(self, newValue):...
[ -5 ]
[ "java", "oop", "python" ]
stackoverflow_0005351102_java_oop_python.txt
Q: Nosegae Unit Tests with gae-session on a Python Google App Engine Project I can't get gae-sessions to work when I use unit tests. I'm not sure if it's a cookie issue or an internal gae-sessions issue (it uses memcache/the datastore for persistance). It works fine on the actual app when accessed through a browser. ...
Nosegae Unit Tests with gae-session on a Python Google App Engine Project
I can't get gae-sessions to work when I use unit tests. I'm not sure if it's a cookie issue or an internal gae-sessions issue (it uses memcache/the datastore for persistance). It works fine on the actual app when accessed through a browser. I'm using Python 2.5 on Mac OS 10.6.6, Google App Engine SDK 1.4.2, nosetests v...
[ "I think you'll have to manually save the session in this test.\n if not 'message' in s:\n self.response.out.write('No session value')\n s['message'] = 'This value is stored in a session'\n s.save()\n\nUpdate:\ngae-sessions retrieves the session cookie from the os.environ['HTTP_COOKIE'] varia...
[ 4 ]
[]
[]
[ "cookies", "google_app_engine", "nosetests", "python", "webtest" ]
stackoverflow_0005348896_cookies_google_app_engine_nosetests_python_webtest.txt
Q: Python multiple comparisons style? I am wondering if there is a way to do the following in a more compact style: if (text == "Text1" or text=="Text2" or text=="Text3" or text=="Text4"): do_something() The problem is i have more than just 4 comparisons in the if statement and it's starting to look rather long,...
Python multiple comparisons style?
I am wondering if there is a way to do the following in a more compact style: if (text == "Text1" or text=="Text2" or text=="Text3" or text=="Text4"): do_something() The problem is i have more than just 4 comparisons in the if statement and it's starting to look rather long, ambiguous, and ugly. Any ideas?
[ "How about this:\nif text in ( 'Text1', 'Text2', 'Text3', 'Text4' ):\n do_something()\n\nI've always found that simple and elegant.\n", "The \"if text in\" answer is good, but you might also think about the re (regular expressions) package if your text strings fit a pattern.\nFor example, taking your example l...
[ 16, 7 ]
[]
[]
[ "coding_style", "comparison", "python", "readability" ]
stackoverflow_0005354048_coding_style_comparison_python_readability.txt
Q: IronPython - DynamicWebServiceHelpers.dll in linux? The examples shown in the IronPython sample scripts show the ability to use DynamicWebServiceHelpers.dll as so: import clr clr.AddReference('DynamicWebServiceHelpers.dll') import DynamicWebServiceHelpers This does not however work... IOError: Could not add r...
IronPython - DynamicWebServiceHelpers.dll in linux?
The examples shown in the IronPython sample scripts show the ability to use DynamicWebServiceHelpers.dll as so: import clr clr.AddReference('DynamicWebServiceHelpers.dll') import DynamicWebServiceHelpers This does not however work... IOError: Could not add reference to assembly DynamicWebServiceHelpers So I tried...
[ "DynamicWebServiceHelpers is one of the sample projects for IronPython. You are correct in that you would have to build it from source. In looking at the source code, all of the referenced C# assemblies/namespaces should have Mono support.\nMake sure you have the most recent version of Mono installed along with I...
[ 2 ]
[]
[]
[ "ironpython", "linux", "mono", "python" ]
stackoverflow_0005345753_ironpython_linux_mono_python.txt
Q: high cpu usage in fabric 1.0.0 In fabric 0.9, everything runs OK, but in 1.0.0, the following fabric script shows 100% CPU usage in top: from fabric.api import run def test(): run("sleep 1000") I'm running the file like this: fab -H localhost Why is this happening? A: This is a known issue which will hope...
high cpu usage in fabric 1.0.0
In fabric 0.9, everything runs OK, but in 1.0.0, the following fabric script shows 100% CPU usage in top: from fabric.api import run def test(): run("sleep 1000") I'm running the file like this: fab -H localhost Why is this happening?
[ "This is a known issue which will hopefully be addressed in a day or two:\nhttp://code.fabfile.org/issues/show/312\n" ]
[ 7 ]
[]
[]
[ "fabric", "python" ]
stackoverflow_0005266851_fabric_python.txt
Q: Storing and Processing Large Amounts of Temporal-Spatial Data As part of our research group, we're collecting large amounts of location data. Our data essentially looks like (user id, lat/long co-ordinates, timestamp). There's other metadata involved too, but that's not relevant here. We're collecting about 2-3 mi...
Storing and Processing Large Amounts of Temporal-Spatial Data
As part of our research group, we're collecting large amounts of location data. Our data essentially looks like (user id, lat/long co-ordinates, timestamp). There's other metadata involved too, but that's not relevant here. We're collecting about 2-3 million records a week, and expect to collect about a year's worth of...
[ "PostGIS is probably what you are looking for. \n" ]
[ 1 ]
[]
[]
[ "gis", "python" ]
stackoverflow_0005353697_gis_python.txt
Q: python floating point nature and converting to a smaller type I am trying to understand the exact nature of float when it comes to python. Apparently, python stores floats in a PyFloatObject type which contains a double. However, how can I force it to behave like a 32 bit floating point variable ? Is there another...
python floating point nature and converting to a smaller type
I am trying to understand the exact nature of float when it comes to python. Apparently, python stores floats in a PyFloatObject type which contains a double. However, how can I force it to behave like a 32 bit floating point variable ? Is there another type for this ?
[ "The built-in float type of Python always uses double precision (unless you compile a custom version of the interpreter). You can use the array module to get 32-bit floats:\na = array.array(\"f\")\n\nwill define an array of 32-bit floats.\nThe external NumPy package also provides a scalar 32-bit floating-point typ...
[ 6, 1 ]
[]
[]
[ "floating_point", "python" ]
stackoverflow_0005354436_floating_point_python.txt
Q: Modulo Result Starting At '1' This is a sort of beginner question but I couldn't find a good answer. I have: self.date = ( self.date + 1 ) % 31 So the results start at 0 1 2 3 ... and ends in 29 30 0 1 .... How do I shift it such that it starts at 1 2 3 4 and results in 30 31 1 2 3 ... with as clean as a syntax a...
Modulo Result Starting At '1'
This is a sort of beginner question but I couldn't find a good answer. I have: self.date = ( self.date + 1 ) % 31 So the results start at 0 1 2 3 ... and ends in 29 30 0 1 .... How do I shift it such that it starts at 1 2 3 4 and results in 30 31 1 2 3 ... with as clean as a syntax as possible?
[ "self.date = (self.date % 31) + 1\n\nI think this is what you mean.\nEDIT: I saw your comment on the other answer, and here's an explanation of what you're doing:\n(self.date % 31) means to take the value of date and find the remainder when you divide by 31 (which you know). If you use self.date +1 % 31, then start...
[ 2, 1 ]
[]
[]
[ "modulo", "python" ]
stackoverflow_0005354829_modulo_python.txt
Q: installing opencv for python issues I'm running OS X Leopard. I followed this site to install it. Trying to run any demo script, I now get "No module named opencv.cv", which is obviously stopping me from doing any programming. I am running python 2.5.1 (yes, I know it's kind of old). Why would this be, and how ...
installing opencv for python issues
I'm running OS X Leopard. I followed this site to install it. Trying to run any demo script, I now get "No module named opencv.cv", which is obviously stopping me from doing any programming. I am running python 2.5.1 (yes, I know it's kind of old). Why would this be, and how can I solve it? Thanks
[ "You need to compile openCV unfortunately. It's not that hard to do though at least. \n", "A nice route is to use MacPorts: First, be sure to have py26-numpy installed to have support for basic functions such as cv.fromarray :\nsudo port install py26-numpy\n\nThen, opencv will compile (with no problem on my sid...
[ 0, 0, 0 ]
[]
[]
[ "installation", "macos", "opencv", "python" ]
stackoverflow_0003027257_installation_macos_opencv_python.txt
Q: Setting the value of a global variable in the context of a function raises UnboundLocalError? Maybe my coffee is not strong enough this morning, but this behavior is confusing me right now: >>> a = 'foo' >>> def func1(): ... print a ... >>> def func2(): ... print a ... a = 'bar' ... >>> func1() foo >>> fun...
Setting the value of a global variable in the context of a function raises UnboundLocalError?
Maybe my coffee is not strong enough this morning, but this behavior is confusing me right now: >>> a = 'foo' >>> def func1(): ... print a ... >>> def func2(): ... print a ... a = 'bar' ... >>> func1() foo >>> func2() Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", lin...
[ "Because a is being set inside func2, Python assumes it's a local variable. Put a global a declaration before the print statement:\ndef func2():\n global a\n print a\n a = 'bar'\n\nSee also this question about Python scoping rules.\n" ]
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0005354911_python.txt
Q: I found a memoization code snippet, and I'm wondering how it would behave under copy.copy I found this nice memoizing decorator: http://wiki.python.org/moin/PythonDecoratorLibrary#Memoize The particular application is in artificial intelligence, and it will live inside an immutable state class. The trouble is tha...
I found a memoization code snippet, and I'm wondering how it would behave under copy.copy
I found this nice memoizing decorator: http://wiki.python.org/moin/PythonDecoratorLibrary#Memoize The particular application is in artificial intelligence, and it will live inside an immutable state class. The trouble is that I perform application of operators by returning a copy.copy of the parent state, with request...
[ "Yes. copy.copy is shallow, so it just copies a reference to the memoizing wrapper object. You can try it out like this if you remove the __get__ method of memoized (otherwise, you'd get a partial object that's used to support bound methods):\nclass C(object):\n @memoized\n def foo(): pass\n\no1 = C()\no2 = c...
[ 1, 1 ]
[]
[]
[ "decorator", "memoization", "python" ]
stackoverflow_0005354759_decorator_memoization_python.txt
Q: Multiple different results returned on case-sensitive 'exact' query in django I have an instance of django 1.2.1 running on ubuntu with a mysql 5 backend. I am trying to make a case-sensitive query that should only return one result, but I am getting two results back that have the same content but with different c...
Multiple different results returned on case-sensitive 'exact' query in django
I have an instance of django 1.2.1 running on ubuntu with a mysql 5 backend. I am trying to make a case-sensitive query that should only return one result, but I am getting two results back that have the same content but with different cases. I want to get an entry with the following title: Cat on the Internet synd...
[ "http://code.djangoproject.com/ticket/2170\n\nTo get the functionally correctly,\n change the Collation of the MySql?\n database to latin1_swedish_cs or\n utf8_bin for case sensitive\n comparisons.\n\n", "This is probably due to a setting at the MySQL level. From the documentation:\n\nBy default, with a UTF-...
[ 11, 3, 1 ]
[]
[]
[ "case_sensitive", "django", "django_models", "python" ]
stackoverflow_0005354061_case_sensitive_django_django_models_python.txt
Q: Efficiently Strip Out Punctuation but not ".com" I found this thread: Best way to strip punctuation from a string in Python But was hoping to come up with a way to do this except not to strip out the periods in links. So if the string is I love using stackoverflow.com on Fridays, Saturdays and Mondays! It would ...
Efficiently Strip Out Punctuation but not ".com"
I found this thread: Best way to strip punctuation from a string in Python But was hoping to come up with a way to do this except not to strip out the periods in links. So if the string is I love using stackoverflow.com on Fridays, Saturdays and Mondays! It would return I love using stackoverflow.com on Fridays Satu...
[ "You can use negative look-aheads:\n[,!?]|\\.(?!(com|org|ly))\n\n", "Conventions suggest that you use a space after . , ! or things like that. If you can count on correct typing you can create a regex which strips these character only if they are followed by spaces. (Or at least do like this with the fullstop cha...
[ 5, 3, 1 ]
[]
[]
[ "python", "string" ]
stackoverflow_0005354881_python_string.txt
Q: Passing dict to constructor? I'd like to pass a dict to an object's constructor for use as kwargs. Obviously: foo = SomeClass(mydict) Simply passes a single argument, rather than the dict's contents. Alas: foo = SomeClass(kwargs=mydict) Which seems more sensible doesn't work either. What am I missing? A: Use ...
Passing dict to constructor?
I'd like to pass a dict to an object's constructor for use as kwargs. Obviously: foo = SomeClass(mydict) Simply passes a single argument, rather than the dict's contents. Alas: foo = SomeClass(kwargs=mydict) Which seems more sensible doesn't work either. What am I missing?
[ "Use :\nfoo = SomeClass(**mydict)\n\nthis will unpack the dict value and pass them to the function.\nFor example:\nmydict = {'a': 1, 'b': 2}\n\nSomeClass(**mydict) # Equivalent to : SomeClass(a=1, b=2)\n\n", "To pass a dictionary to a constructor you have to do so by reference, which is by preceding it with **, l...
[ 31, 3, 1 ]
[]
[]
[ "constructor", "dictionary", "python" ]
stackoverflow_0005355121_constructor_dictionary_python.txt
Q: How should I arrange methods in a class in Python? How should (or is a clean way) of organising methods in Python? I always put the __init__ method first, followed by any other __foo__ (What do you call them?) methods. But then it leads into a jumble. A: My preference is to place the __init__ method first, then ...
How should I arrange methods in a class in Python?
How should (or is a clean way) of organising methods in Python? I always put the __init__ method first, followed by any other __foo__ (What do you call them?) methods. But then it leads into a jumble.
[ "My preference is to place the __init__ method first, then assign the other methods alphabetically afterward.\n", "I like to organize them like this:\nFirst: Constructor (__init__)\nSecond: Any other __ methods\nThird: Regular methods that roughly can be categorized under \"get\"\nFourth: Regular methods that rou...
[ 4, 4, 1, 1 ]
[]
[]
[ "code_organization", "methods", "python" ]
stackoverflow_0005355239_code_organization_methods_python.txt
Q: Verify that files aren't modified I'd like to verify that a bunch of files (ten files or so) are unchanged. I thought it create a CRC/MD5 hash lists for these files and compare them with realtime hashes. What's more recommended? CRC or MD5? What is the right way to do it with Python? Thanks. A: CRC is simpler ...
Verify that files aren't modified
I'd like to verify that a bunch of files (ten files or so) are unchanged. I thought it create a CRC/MD5 hash lists for these files and compare them with realtime hashes. What's more recommended? CRC or MD5? What is the right way to do it with Python? Thanks.
[ "CRC is simpler and faster, but only really designed to detect unintentional changes. MD5 is more secure. \nBoth are built into the Python Standard Library, check out hashlib for details. \nhttp://docs.python.org/library/hashlib.html\n", "Also worth considering is SHA1 which is far more secure, but it really depe...
[ 2, 2 ]
[]
[]
[ "hash", "python" ]
stackoverflow_0005355574_hash_python.txt
Q: Is there a way to traverse all modules that can be imported I need to block some modules and I need to know if some module don't import it. So I need a way to traverse all modules to see if a module have sub module, that I need to block. Is there a way to check all installed modules for existence of modules I nee...
Is there a way to traverse all modules that can be imported
I need to block some modules and I need to know if some module don't import it. So I need a way to traverse all modules to see if a module have sub module, that I need to block. Is there a way to check all installed modules for existence of modules I need to block? I don't need cross-platform solution.
[ "Sounds like you're trying to build a sandbox. The Python wiki lists some good approaches.\nI took a look at your webapp and it's quite easy to hack:\n\nyou can import modules like ctypes.util or logging or hundreds of others that import os, sys.\nyou can even import the modules directly like x = [__import__(\"os\"...
[ 2, 1, 1, 0 ]
[]
[]
[ "import", "module", "python", "traversal" ]
stackoverflow_0005293987_import_module_python_traversal.txt
Q: Virtualenv issue with flask-werkzeug I have installed virtualenv along with flask, werkzeug, jinja2 and SQLAlchemy. I was following the tutorial mentioned on the flask website and i came across the below error when executing flask code Traceback (most recent call last): File "hello.py", line 1, in ? from fl...
Virtualenv issue with flask-werkzeug
I have installed virtualenv along with flask, werkzeug, jinja2 and SQLAlchemy. I was following the tutorial mentioned on the flask website and i came across the below error when executing flask code Traceback (most recent call last): File "hello.py", line 1, in ? from flask import Flask File "/root/myproject/e...
[ "The import .module syntax is introduced in Python 2.5 (relative import). So you have to use at least 2.5 for this thing.\n", "dunno what you did and how old your virtualenv is .. but you make your own virtualenv by:\n% python -c \"import urllib, os; os.mkdir('py-env'); \\\n urllib.urlretrieve('http://goo.gl/...
[ 3, 2, 1, 0 ]
[]
[]
[ "flask", "python", "virtualenv", "werkzeug" ]
stackoverflow_0004969540_flask_python_virtualenv_werkzeug.txt
Q: Matplotlib 3d colour plot - is it possible? I've googled around for this and am unable to find anything which suggests that it may not exist, but I wanted to ask stackoverflow. I'm using python, together with matplotlib and I'm looking to plot something like this: http://en.wikipedia.org/wiki/File:Spherical_harmo...
Matplotlib 3d colour plot - is it possible?
I've googled around for this and am unable to find anything which suggests that it may not exist, but I wanted to ask stackoverflow. I'm using python, together with matplotlib and I'm looking to plot something like this: http://en.wikipedia.org/wiki/File:Spherical_harmonics.png Essentially what I would call a 3d heatm...
[ "You can use the mplot3d toolkit, http://matplotlib.sourceforge.net/mpl_toolkits/mplot3d/index.html\n" ]
[ 2 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0005355901_matplotlib_python.txt
Q: How to configure the display fonts in qtwebkit through the console? I'm trying to achieve maximum accuracy in rendering pages in qtwebkit in python (via xvfb). I am I have a problem with fonts. Here's an example (image). This example shows that there is a problem with displaying in italics, but there is not at al...
How to configure the display fonts in qtwebkit through the console?
I'm trying to achieve maximum accuracy in rendering pages in qtwebkit in python (via xvfb). I am I have a problem with fonts. Here's an example (image). This example shows that there is a problem with displaying in italics, but there is not at all sites. System is ubuntu 10.10 server and it set the standard packs of f...
[ "I think the problem is: what is \"maximum accuracy\" in this case?\nWhere does the \"true\" image come from? I assume that is what you saw when you visited the site in your browser. Depending on your browser's settings (your personal settings and/or default settings) and on what styling information (css, style att...
[ 0 ]
[]
[]
[ "fonts", "python", "qtwebkit", "text_rendering" ]
stackoverflow_0005354620_fonts_python_qtwebkit_text_rendering.txt
Q: Wxpython textctrl sluggish when using SetStringItem on a loop In wxpython, To update a series of items on a textCtrl widget, I am using: for i in LARGELIST: list.SetStringItem(i, 1, str(a)) This works, but just like in an excel macro - which becomes sluggish if you allow it to display every single update on t...
Wxpython textctrl sluggish when using SetStringItem on a loop
In wxpython, To update a series of items on a textCtrl widget, I am using: for i in LARGELIST: list.SetStringItem(i, 1, str(a)) This works, but just like in an excel macro - which becomes sluggish if you allow it to display every single update on the screen instead of disabling it and refreshing the spreadsheet la...
[ "use:\nwindow.Freeze()\nfor i in LARGELIST:\n list.SetStringItem(i, 1, str(a))\nwindow.Thaw()\n\nwhere \"window\" is the reference to your window\n" ]
[ 1 ]
[]
[]
[ "forms", "performance", "python", "wxpython" ]
stackoverflow_0005356018_forms_performance_python_wxpython.txt
Q: Is it safe to access ._meta directly in your django app? Django uses Meta class for lots of additional object information. However, they store this information in an object '_meta' which by naming convention is private. All over the django admin (and other places) I see stuff like opts = model._meta and then they ...
Is it safe to access ._meta directly in your django app?
Django uses Meta class for lots of additional object information. However, they store this information in an object '_meta' which by naming convention is private. All over the django admin (and other places) I see stuff like opts = model._meta and then they use the various options like app_label and verbose_name. Can I...
[ "I use _meta frequently and haven't had any issues so far. You can see in the django documentation an example of them using it too here, so I have felt its more or less ok to do. Just tread carefully and write good tests so you know of any problems when you upgrade your django version later on down the road.\n", ...
[ 4, 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0005353984_django_python.txt
Q: python: can executable zip files include data files? Being fairly new to python I only recently discovered the ability to directly execute a .zip file by placing a __main__.py file at the top of the file. This works great for python code, but can I bundle other types of files and access them with my scripts? If so...
python: can executable zip files include data files?
Being fairly new to python I only recently discovered the ability to directly execute a .zip file by placing a __main__.py file at the top of the file. This works great for python code, but can I bundle other types of files and access them with my scripts? If so, how? My ultimate goal would be to bundle some image file...
[ "You could use pkg_resources functions to access files:\n# __main__.py\nimport pkg_resources\nfrom PIL import Image\n\nprint pkg_resources.resource_string(__name__, 'README.txt')\n\nim = Image.open(pkg_resources.resource_stream('app', 'im.png'))\nim.rotate(45).show()\n\nWhere zipfile contains:\n.\n|-- app\n| |-- ...
[ 21, 6, 6, 0 ]
[]
[]
[ "python", "zipapp" ]
stackoverflow_0005355694_python_zipapp.txt
Q: Defining two different extension to the User model class CustomerProfile(models.Model): user = models.ForeignKey(User, unique=True) gender = models.CharField(max_length=1,blank=True) zip_code = models.IntegerField() class StoreProfile(models.Model): user = models.ForeignKey(User, unique=True) ...
Defining two different extension to the User model
class CustomerProfile(models.Model): user = models.ForeignKey(User, unique=True) gender = models.CharField(max_length=1,blank=True) zip_code = models.IntegerField() class StoreProfile(models.Model): user = models.ForeignKey(User, unique=True) phone_number = models.IntegerField() I would like to be...
[ "AFAIK this can't be done. But you can try this:\nclass UserProfile(models.Model):\n user = ForeignKey(User, unique=True)\n store = OneToOneField(Store, blank=True, null=True)\n customer = OneToOneField(Customer, blank=True, null=True)\n\nand set only one of store or customer when creating profile for user...
[ 2, 2, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0005356533_django_python.txt
Q: How do I give focus to a python Tkinter text widget? I'd like to be able to open the App GUI and have it automatically place the cursor into a particular text widget. Best case scenario is: as soon as the app is launched someone can start typing without having to click on the text widget. This is just a small exam...
How do I give focus to a python Tkinter text widget?
I'd like to be able to open the App GUI and have it automatically place the cursor into a particular text widget. Best case scenario is: as soon as the app is launched someone can start typing without having to click on the text widget. This is just a small example displaying the issue: from Tkinter import * root = Tk(...
[ "You use the focus_set method. For example:\nfrom Tkinter import *\nroot = Tk()\nWindow = Frame(root)\nTextWidget = Text(Window)\nTextWidget.pack()\nWindow.pack()\nTextWidget.focus_set()\nroot.mainloop()\n\n" ]
[ 26 ]
[]
[]
[ "python", "text", "tkinter", "widget" ]
stackoverflow_0005356655_python_text_tkinter_widget.txt
Q: Export type into python I want to export singleton into python using boost.python and use it there. Here is the code: class ConfigManager : public boost::serialization::singleton<ConfigManager> {}; inline ConfigManager &configManager() { return ConfigManager::get_mutable_instance(); } BOOST_PYTHON_MODULE(ConfigMa...
Export type into python
I want to export singleton into python using boost.python and use it there. Here is the code: class ConfigManager : public boost::serialization::singleton<ConfigManager> {}; inline ConfigManager &configManager() { return ConfigManager::get_mutable_instance(); } BOOST_PYTHON_MODULE(ConfigManager) { bp::class_<Confi...
[ "copy_non_const_reference will try to copy your reference to a Python object, you should use instead bp::reference_existing_object, I tried here and the error message disappeared \n" ]
[ 2 ]
[]
[]
[ "boost", "c++", "export", "python", "types" ]
stackoverflow_0005356706_boost_c++_export_python_types.txt
Q: How to move a python 2.6 project to UTF-8? We are moving from latin1 to UTF-8 and have 100k lines of python code. Plus I'm new in python (ha-ha-ha!). I already know that str() function fails when receiving Unicode so we should use unicode() instead of it with almost the same effect. What are the other "dangerous" ...
How to move a python 2.6 project to UTF-8?
We are moving from latin1 to UTF-8 and have 100k lines of python code. Plus I'm new in python (ha-ha-ha!). I already know that str() function fails when receiving Unicode so we should use unicode() instead of it with almost the same effect. What are the other "dangerous" places of code? Are there any basic guidelines/a...
[ "str and unicode are classes, not functions. When you call str(u'abcd') you are initialising a new string which takes 'abcd' as a variable. It just so happens that str() can be used to convert a string of any type to an ascii str.\nOther areas to look out for are when reading from a file/input, or basically anythin...
[ 4, 2, 0 ]
[]
[]
[ "python", "unicode" ]
stackoverflow_0005350958_python_unicode.txt
Q: Scraping Javascript driven web pages with PyQt4 - how to access pages that need authentication? I have to scrape a very, very simple page on our company's intranet in order to automate one of our internal processes (returning a function's output as successful or not). I found the following example: import sys from...
Scraping Javascript driven web pages with PyQt4 - how to access pages that need authentication?
I have to scrape a very, very simple page on our company's intranet in order to automate one of our internal processes (returning a function's output as successful or not). I found the following example: import sys from PyQt4.QtGui import * from PyQt4.QtCore import * from PyQt4.QtWebKit import * class Render(QWebPage)...
[ "I figured it out. Here's what I ended up with in case it can help someone else.\n#!/usr/bin/python\n# -*- coding: latin-1 -*-\nimport sys\nimport base64\nfrom PyQt4.QtGui import *\nfrom PyQt4.QtCore import *\nfrom PyQt4.QtWebKit import *\nfrom PyQt4 import QtNetwork\n\nclass Render(QWebPage):\n def __init__(self...
[ 7, 0 ]
[]
[]
[ "pyqt", "pyqt5", "python", "ssl", "web_scraping" ]
stackoverflow_0005356948_pyqt_pyqt5_python_ssl_web_scraping.txt
Q: Django: dealing with non-ascii parameters I'm running into an issue dealing with non-ascii POST parameters. Here's a CURL request that shows the problem: curl "http://localhost:8000/api/txt/" -d \ "sender=joe&comments=Bus%20%A3963.33%20London%20to%20Sydney" The pound sign in comments is causing the issue: when I ...
Django: dealing with non-ascii parameters
I'm running into an issue dealing with non-ascii POST parameters. Here's a CURL request that shows the problem: curl "http://localhost:8000/api/txt/" -d \ "sender=joe&comments=Bus%20%A3963.33%20London%20to%20Sydney" The pound sign in comments is causing the issue: when I try to do just about anything with request.POST...
[ "%A3 is wrong. It should in fact be %C2%A3 or %C5%81 in order to be correct UTF-8.\nAlso, \"Unicode In Python, Completely Demystified\".\n", "I think you have to pass it first into urllib.unquote() to remove the quoting performed by HTTP, then, you can convert the string to unicode with the proper encoding\n>>> u...
[ 2, 0 ]
[]
[]
[ "django", "python", "unicode" ]
stackoverflow_0005357647_django_python_unicode.txt
Q: Assistance with re module script I posted this question earlier Approach for parsing file and creating dynamic data structure for use by another program and got some good suggestions. So now I have something working and I want to see if there is a better way of doing it. Background Information: I basically need ...
Assistance with re module script
I posted this question earlier Approach for parsing file and creating dynamic data structure for use by another program and got some good suggestions. So now I have something working and I want to see if there is a better way of doing it. Background Information: I basically need to parse a static properties file that...
[ "with open(propertyfile_name) as f: \n content= f.read()\n for (server,h) in re.findall(RE,content): \n dico[server]['host']=h\n\n for (server,n) in re.findall(RE1,content): \n dico[server]['name']=n\n\n for (server,s) in re.findall(RE2,content): \n dico[server]['sslport']=s\n\n ...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0005357726_python.txt
Q: __coerce__ vs. __ihook__ difference? in python, you have __coerce__ and __ihook__. According to PEP 203 (Augmented Assigments) they are both invoked, in this order to perform in place operations on objects, with __coerce__ called first, and __ihook__ next. I don't know if these methods have been made specifically ...
__coerce__ vs. __ihook__ difference?
in python, you have __coerce__ and __ihook__. According to PEP 203 (Augmented Assigments) they are both invoked, in this order to perform in place operations on objects, with __coerce__ called first, and __ihook__ next. I don't know if these methods have been made specifically for augmented assignment, but I would like...
[ "The __ihook__ in that PEP stands for one of the following methods:\n __iadd__\n __isub__\n __imul__\n __idiv__\n __imod__\n __ipow__\n __ilshift__\n __irshift__\n __iand__\n __ixor__\n __ior__\n\nThey are in place operations of their respective __hook__s. For example, a+=b does som...
[ 7 ]
[]
[]
[ "python" ]
stackoverflow_0005357648_python.txt
Q: What's the easiest way to iterate on a file's lines, keeping a counter? What's the cleanest code that iterates on the lines of a text file, while simultaniously increamenting a counter? I understand that with multiple assignment, there's a cleaner syntax than i = 0 for line in f: ... ++i A: for i, line i...
What's the easiest way to iterate on a file's lines, keeping a counter?
What's the cleanest code that iterates on the lines of a text file, while simultaniously increamenting a counter? I understand that with multiple assignment, there's a cleaner syntax than i = 0 for line in f: ... ++i
[ "for i, line in enumerate(f):\n print i, line\n\nAs seen here: http://docs.python.org/library/functions.html#enumerate\n", "for count, line in enumerate(f):\n\nEnumerate starts at index 0 unless told otherwise providing a counter iterated at the same time as each item of your for loop\nEDIT: As a side note you c...
[ 12, 9 ]
[]
[]
[ "python" ]
stackoverflow_0005357948_python.txt
Q: py2exe and numpy not getting along I am trying to use py2exe-0.6.9.win32 to wrap up an application that I have written in Python2.6.5 using the following object libraries with associated download file names: matplotlib-0.99.3.win32 numpy-1.4.1-win32 scipy-0.8.0b1-win32 wxPython2.8-win32-unicode-2.8.11.0 I am getti...
py2exe and numpy not getting along
I am trying to use py2exe-0.6.9.win32 to wrap up an application that I have written in Python2.6.5 using the following object libraries with associated download file names: matplotlib-0.99.3.win32 numpy-1.4.1-win32 scipy-0.8.0b1-win32 wxPython2.8-win32-unicode-2.8.11.0 I am getting error messages when I try to launch t...
[ "Seems like the problem mentioned on the bottom of this: http://www.py2exe.org/index.cgi/MatPlotLib\nLooks like you need to make a few small changes to mlab.py:\npsd.__doc__ = psd.__doc__ % kwdocd\n\nto\nif psd.__doc__ is not None:\n psd.__doc__ = psd.__doc__ % kwdocd\nelse:\n psd.__doc__ = \"\"\n\nIf you hav...
[ 2, 0, 0 ]
[]
[]
[ "matplotlib", "numpy", "py2exe", "python", "scipy" ]
stackoverflow_0004895153_matplotlib_numpy_py2exe_python_scipy.txt
Q: Programmatically Save Draft in Gmail drafts folder Preferably using Python or Java, I want to compose an email and save it into gmail drafts without user intervention, A: Here's a Python script to access a Gmail account. First you need to generate an OAuth token. Download Google's xoauth.py module and run it. ...
Programmatically Save Draft in Gmail drafts folder
Preferably using Python or Java, I want to compose an email and save it into gmail drafts without user intervention,
[ "Here's a Python script to access a Gmail account. First you need to generate an OAuth token. Download Google's\nxoauth.py module and run it. It will walk you through the steps. You'll get a url to obtain a verification code -- paste this into the script and it will spit out your token and secret:\n% python xoaut...
[ 9, 1 ]
[]
[]
[ "api", "gmail", "java", "python" ]
stackoverflow_0005355067_api_gmail_java_python.txt
Q: Establishing an IPv6 connection using sockets in python I am trying to run this very basic socket example: import socket host = 'ipv6hostnamegoeshere' port=9091 ourSocket = socket.socket(socket.AF_INET6, socket.SOCK_STREAM, 0) ourSocket.connect((host, port)) Yet, I get the error: ourSocket.connect((host, por...
Establishing an IPv6 connection using sockets in python
I am trying to run this very basic socket example: import socket host = 'ipv6hostnamegoeshere' port=9091 ourSocket = socket.socket(socket.AF_INET6, socket.SOCK_STREAM, 0) ourSocket.connect((host, port)) Yet, I get the error: ourSocket.connect((host, port)) File "<string>", line 1, in connect socket.error: [Errn...
[ "As the socket.connect docs says, AF_INET6 expects a 4-tuple:\n\nsockaddr is a tuple describing a\n socket address, whose format depends\n on the returned family (a (address,\n port) 2-tuple for AF_INET, a (address,\n port, flow info, scope id) 4-tuple for\n AF_INET6), and is meant to be passed\n to the socke...
[ 18 ]
[]
[]
[ "ipv6", "networking", "python", "sockets" ]
stackoverflow_0005358021_ipv6_networking_python_sockets.txt
Q: why doesn't eclipse-python have magic refactor? Eclipse is able to utilize compiled bytecode to enable "magic refactor" functionality--renaming methods, tracing up and down class hierarchies and tracing through method calls. What technical barriers exist that make this harder to do for languages like Python and Ja...
why doesn't eclipse-python have magic refactor?
Eclipse is able to utilize compiled bytecode to enable "magic refactor" functionality--renaming methods, tracing up and down class hierarchies and tracing through method calls. What technical barriers exist that make this harder to do for languages like Python and Javascript?
[ "Because of dynamic binding. Python is a dynamic language in a way that you can do almost everything with your variables. You can even access the globals-dict and introduce new variables composed of runtime values.\nSo an IDE can’t be sure which variables exist when. See this example:\n#silly.py\n\nimport sys\n\nif...
[ 6, 1 ]
[]
[]
[ "automated_refactoring", "eclipse", "javascript", "python", "refactoring" ]
stackoverflow_0004995842_automated_refactoring_eclipse_javascript_python_refactoring.txt
Q: Django : Listing model field names and values in template Possible Duplicate: Django - Iterate over model instance field names and values in template Hi, I'm trying to list fields and corresponding values of generic Django models in the templates. However I can't find an inbuilt solution for a fairly common prob...
Django : Listing model field names and values in template
Possible Duplicate: Django - Iterate over model instance field names and values in template Hi, I'm trying to list fields and corresponding values of generic Django models in the templates. However I can't find an inbuilt solution for a fairly common problem. I'm pretty close to the solution but can't find a way out...
[ "Unfortunately, you can't do lookups like that in the template engine. \nYou'll have to deal with that in the view.\ndef showdetails(request, template):\n objects = newivr1_model.objects.all()\n\n for object in objects:\n object.fields = dict((field.name, field.value_to_string(object))\n ...
[ 5, 3 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0005358800_django_django_models_python.txt
Q: Regular Expression to test the presence and match a string at the same time I would like to determine whether a string S has a substring MYSUBSTRING preceded by two consecutive digits I need to determine. For example: 'aaa79bbbMYSUBSTRINGccc' ==> I want 7, 9 and True (or 7, 9 and MYSUBSTRING) 'aaa79bbbccc' ==> I w...
Regular Expression to test the presence and match a string at the same time
I would like to determine whether a string S has a substring MYSUBSTRING preceded by two consecutive digits I need to determine. For example: 'aaa79bbbMYSUBSTRINGccc' ==> I want 7, 9 and True (or 7, 9 and MYSUBSTRING) 'aaa79bbbccc' ==> I want 7, 9 and False (or 7, 9 and None) Can I do that with a SINGLE regex? If so, w...
[ "The following regex should do it:\n(\\d)(\\d)(?:.*?(MYSUBSTRING))?\n>>> re.search(r'(\\d)(\\d)(?:.*?(MYSUBSTRING))?', 'aaa79bbbMYSUBSTRINGccc').groups()\n('7', '9', 'MYSUBSTRING')\n>>> re.search(r'(\\d)(\\d)(?:.*?(MYSUBSTRING))?', 'aaa79bbbccc').groups()\n('7', '9', None)\n\n", "Sure, you can use (\\d)(\\d).*?(M...
[ 4, 0, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0005358692_python_regex.txt
Q: virtualenv won't symlink warnings.py for python 2.7 I have a problem with creating virtualenv (1.5.2) with python2.7 on Lucid. It seems, like virtualenv is skipping creation of symlink for warnings.py. Running virtualenv with interpreter /usr/local/bin/python2.7 Creating test/lib/python2.7 Symlinking Python bootst...
virtualenv won't symlink warnings.py for python 2.7
I have a problem with creating virtualenv (1.5.2) with python2.7 on Lucid. It seems, like virtualenv is skipping creation of symlink for warnings.py. Running virtualenv with interpreter /usr/local/bin/python2.7 Creating test/lib/python2.7 Symlinking Python bootstrap modules Symlinking test/lib/python2.7/sre_compile.p...
[ "So I've checked virtualenv.py code and it has a list REQUIRED_MODULES, which seems to have names of modules to attach in /lib dir of new environment. This list is extended by module 'warnings' after satisfying a condition:\nsys.version_info[:2] >= (2, 6)\n\nVersion of python was correctly indentified, so there was...
[ 4 ]
[]
[]
[ "python", "virtualenv" ]
stackoverflow_0005358523_python_virtualenv.txt
Q: Manipulating well-formed xml (in any language running under linux) I have well-formed xml (open-tags are closed, etc), but there's no dtd, namespaces are not always correct, and there are random entities. I found an error in some of my xml files, and want to fix this, automatically. Essentially the xml file looks ...
Manipulating well-formed xml (in any language running under linux)
I have well-formed xml (open-tags are closed, etc), but there's no dtd, namespaces are not always correct, and there are random entities. I found an error in some of my xml files, and want to fix this, automatically. Essentially the xml file looks like this: <foo> <bar> hi </bar> <!-- ... --> <math><sometag>...
[ "In Perl you could use XML::Twig, for example like this:\n#!/usr/bin/perl\n\nuse strict;\nuse warnings;\n\nuse XML::Twig;\n\nXML::Twig->new( twig_roots => { math => \\&add_prefix },\n twig_print_outside_roots => 1,\n )\n ->parse( \\*DATA);\n\nsub add_prefix\n { my( $t, $math)= @...
[ 6, 4, 2, 1, 1 ]
[]
[]
[ "perl", "python", "ruby", "xml" ]
stackoverflow_0005351382_perl_python_ruby_xml.txt
Q: Best practice for allowing Markdown in Python, while preventing XSS attacks? I need to let users enter Markdown content to my web app, which has a Python back end. I don’t want to needlessly restrict their entries (e.g. by not allowing any HTML, which goes against the spirit and spec of Markdown), but obviously I ...
Best practice for allowing Markdown in Python, while preventing XSS attacks?
I need to let users enter Markdown content to my web app, which has a Python back end. I don’t want to needlessly restrict their entries (e.g. by not allowing any HTML, which goes against the spirit and spec of Markdown), but obviously I need to prevent cross-site scripting (XSS) attacks. I can’t be the first one with ...
[ "I was unable to determine “best practice,” but generally you have three choices when accepting Markdown input:\n\nAllow HTML within Markdown content (this is how Markdown originally/officially works, but if treated naïvely, this can invite XSS attacks).\nJust treat any HTML as plain text, essentially letting your ...
[ 21, 2 ]
[]
[]
[ "markdown", "python", "sanitization", "xss" ]
stackoverflow_0005266134_markdown_python_sanitization_xss.txt
Q: md5 from pil object how i can get md5 of the pil object without saving to file ? imq.save('out.png') hash = hashlib.md5(open('out.png','rb').read()).hexdigest() A: Actually there is simpler solution: hashlib.md5(img.tostring()).hexdigest() A: Turning @Ignacio's answer into code, using this answer to h...
md5 from pil object
how i can get md5 of the pil object without saving to file ? imq.save('out.png') hash = hashlib.md5(open('out.png','rb').read()).hexdigest()
[ "Actually there is simpler solution:\nhashlib.md5(img.tostring()).hexdigest()\n\n", "Turning @Ignacio's answer into code, using this answer to help:\nimport StringIO, hashlib\n\noutput = StringIO.StringIO()\nimg.save(output)\nhash = hashlib.md5(output.getvalue()).hexdigest()\n\nAs the referenced other answer note...
[ 17, 5, 4, 1 ]
[]
[]
[ "md5", "python", "python_imaging_library" ]
stackoverflow_0004294317_md5_python_python_imaging_library.txt
Q: Model Definitions: Ordering Importo Avoid ImportError Having trouble getting all of my imports working correctly. They're calling each other before they're defined. match.models: from player.models import Player class Match(models.Model): player = models.ForeignKey(Player) player.models: class Player(models....
Model Definitions: Ordering Importo Avoid ImportError
Having trouble getting all of my imports working correctly. They're calling each other before they're defined. match.models: from player.models import Player class Match(models.Model): player = models.ForeignKey(Player) player.models: class Player(models.Model): #yadda yadda from match.models import Match cl...
[ "Lazy Relationships\nmatch models.py\nclass Match(models.Model):\n player = models.ForeignKey('player.Player')\n\nplayer models.py\nclass Skill(models.Model):\n player = ForeignKey('Player')\n match = ForeignKey('match.Match')\n\nclass Player(models.Model):\n #yadda yadda\n\n def get_skill():\n ...
[ 2 ]
[]
[]
[ "django", "models", "python" ]
stackoverflow_0005359271_django_models_python.txt
Q: python eval and string indexing Let's say I have a string string = '1234567890' and I want a slice of that string defined by another string slice = '5:8' This is easy to do with >>>string[5:8] '678' However the slice is passed in through a file and changes on user input. Is their a way of doing something suc...
python eval and string indexing
Let's say I have a string string = '1234567890' and I want a slice of that string defined by another string slice = '5:8' This is easy to do with >>>string[5:8] '678' However the slice is passed in through a file and changes on user input. Is their a way of doing something such as >>>string[eval(slice)] '678' Wh...
[ "You are getting the syntax error since 5:8 isn't a valid Python statement on its own; eval expects normal Python code, not just fragments.\nIf you really want to use eval, you can say:\nstring = '1234567890'\nsliceInput = '5:8'\nresult = eval('string[' + sliceInput + ']')\n\nHowever this is not at all secure if yo...
[ 3, 1, 0 ]
[]
[]
[ "python", "string" ]
stackoverflow_0005359288_python_string.txt
Q: python+windows automation - windows glitch sometimes I'm automating some windows stuff with Python, using PIL to take screenshots and such. the issue is that sometimes, deep in some function, I'll do a time.sleep(1) and the GUI app I'm interfacing with will freeze for that second. This is weird cause doing time.sl...
python+windows automation - windows glitch sometimes
I'm automating some windows stuff with Python, using PIL to take screenshots and such. the issue is that sometimes, deep in some function, I'll do a time.sleep(1) and the GUI app I'm interfacing with will freeze for that second. This is weird cause doing time.sleep in other places doesn't cause the freeze. I haven't be...
[ "\nI feel I just need like a \"chill out\"\n function to cause Python to stop\n whatever it is it's doing, let the\n targeted UI recover and refresh and\n process input, then bring it back to\n Python. What function would do that?\n\nCalling sleep() (any variant of it) will block execution of the thread from w...
[ 1, 1, 0 ]
[]
[]
[ "automation", "python", "pywin32", "ui_automation", "windows" ]
stackoverflow_0005346169_automation_python_pywin32_ui_automation_windows.txt
Q: Set and require default Python script OptionParser The following "parser.add_option" statements work but if the script is run without an option/arg it will not complain. If an option/argument are not specified I would like it to display help (-h / --help) as default. usage = "usage: %prog [options] arg" parser = O...
Set and require default Python script OptionParser
The following "parser.add_option" statements work but if the script is run without an option/arg it will not complain. If an option/argument are not specified I would like it to display help (-h / --help) as default. usage = "usage: %prog [options] arg" parser = OptionParser(usage) parser.add_option('-d', '--directory'...
[ "I would do something like this:\nfrom optparse import OptionParser\nimport sys\n\ndef main():\n usage = \"usage: %prog [options] arg\"\n parser = OptionParser(usage)\n parser.add_option('-d', '--directory',\n action='store', dest='directory',\n default=None, help='specify directory')...
[ 1 ]
[]
[]
[ "arguments", "optionparser", "python" ]
stackoverflow_0005359306_arguments_optionparser_python.txt
Q: Python findall and regular expressions I am parsing an xml file (called xml below) that has lines of two varying types: 1. <line a="a1" b="b1" c="c1"> 2. <line a="a2" c="c2"> I am trying to pull a2 and c2 only from the second type, however this regular expression also captures the first type: >>> list = re.findal...
Python findall and regular expressions
I am parsing an xml file (called xml below) that has lines of two varying types: 1. <line a="a1" b="b1" c="c1"> 2. <line a="a2" c="c2"> I am trying to pull a2 and c2 only from the second type, however this regular expression also captures the first type: >>> list = re.findall('<line a="(.*)" c="(.*)">', xml) >>> print...
[ "This makes much more sense with a proper XML parsing library like ElementTree, instead of resorting to regex. For instance:\n>>> xmlstr = \"\"\"\\\n... <root>\n... <line a=\"a1\" b=\"b1\" c=\"c1\"></line>\n... <line a=\"a2\" c=\"c2\"></line>\n... </root>\n... \"\"\"\n>>> import xml.etree.ElementTree as ET\n>>>...
[ 8, 5 ]
[]
[]
[ "findall", "python", "regex" ]
stackoverflow_0005359437_findall_python_regex.txt
Q: CSV Module's writer won't let me write binary out I tried to just use the 'w' tag while opening the file, but it double spaced the lines which caused the read to not work. So I found that changing to 'wb' will be the correct formatting. Now that I am using the 'wb' flag I can't get the csv.writer.writerow() to w...
CSV Module's writer won't let me write binary out
I tried to just use the 'w' tag while opening the file, but it double spaced the lines which caused the read to not work. So I found that changing to 'wb' will be the correct formatting. Now that I am using the 'wb' flag I can't get the csv.writer.writerow() to work. I have encoded all my strings and am lost as to w...
[ "You appear to be running Python 3.x. Advice about using binary mode for csv files applies to Python 2.x. The codecs module is not required for 3.x -- just use encoding=whatever when you open the file. What is needed for 3.x is that the file be opened with newline=''. This applies to both reading and writing, altho...
[ 15, 1, 0 ]
[ "I'm hardly surprised. If you were to write out a byte of value 13, how is the module supposed to tell if this is part of a binary field, or the start of a new record in the CSV? CSV files are not suitable for storing binary data.\nIf you absolutely need it to be in there, you could look into BASE 64 encoding...\nM...
[ -2 ]
[ "csv", "python", "python_3.x" ]
stackoverflow_0005358322_csv_python_python_3.x.txt
Q: Numpy table - advanced multiple criteria selection I have a table that goes something like this: IDs Timestamp Values 124 300.6 1.23 124 350.1 -2.4 309 300.6 10.3 12 123.4 9.00 18 350.1 2.11 309 350.1 8.3 ... and I'd like to ...
Numpy table - advanced multiple criteria selection
I have a table that goes something like this: IDs Timestamp Values 124 300.6 1.23 124 350.1 -2.4 309 300.6 10.3 12 123.4 9.00 18 350.1 2.11 309 350.1 8.3 ... and I'd like to select all the rows that belong to a group of IDs. I kno...
[ "You can do it like this:\nsubset = table[np.array([i in id_list for i in table.IDs])]\n\nIf you have a more recent version of numpy, you can use the in1d function to make it a bit more compact:\nsubset = table[np.in1d(table.IDs, id_list)]\n\nSee also this question: numpy recarray indexing based on intersection wit...
[ 7, 0 ]
[]
[]
[ "numpy", "python", "selection" ]
stackoverflow_0005359235_numpy_python_selection.txt
Q: PyPE ansi or unicode? I want to start programming in python and I read on the internet that PyPE is a good editor. When I went to the website There is the option to download an ansi or unicode version. Witch one should I use? A: I'd recommend the Unicode version, you can always write your code in plain ANSI, but...
PyPE ansi or unicode?
I want to start programming in python and I read on the internet that PyPE is a good editor. When I went to the website There is the option to download an ansi or unicode version. Witch one should I use?
[ "I'd recommend the Unicode version, you can always write your code in plain ANSI, but the features of Unicode are there if you need them.\n" ]
[ 2 ]
[]
[]
[ "ansi", "editor", "python", "text_editor", "unicode" ]
stackoverflow_0005359454_ansi_editor_python_text_editor_unicode.txt
Q: XML embedded in Python docstring, use syntax highlighting I'm working on a Python project where there are some blocks of XML defined inside docstrings. The code contains strings like this xml_str = """<a> <b>text</b> </a>""" In reality, the blocks of embedded XML are much larger. The problem is this XML beco...
XML embedded in Python docstring, use syntax highlighting
I'm working on a Python project where there are some blocks of XML defined inside docstrings. The code contains strings like this xml_str = """<a> <b>text</b> </a>""" In reality, the blocks of embedded XML are much larger. The problem is this XML becomes difficult to read. Since an IDE renders the XML as a String...
[ "Use syntax highlighting plugin http://colorer.sf.net/eclipsecolorer/ for eclipse. It Automatic folding support for mostly all (200+) supported languages.\n" ]
[ 2 ]
[]
[]
[ "python", "syntax_highlighting", "xml" ]
stackoverflow_0005359357_python_syntax_highlighting_xml.txt
Q: How can I add scrollable whitespace at the bottom of a QTreeView When expanding an item at the bottom of a QTreeView, the view does not automatically scroll to show the newly-expanded items. I can fix this by detecting expansion and performing the scroll myself when appropriate. However, I would instead like to al...
How can I add scrollable whitespace at the bottom of a QTreeView
When expanding an item at the bottom of a QTreeView, the view does not automatically scroll to show the newly-expanded items. I can fix this by detecting expansion and performing the scroll myself when appropriate. However, I would instead like to allow the user to scroll the view farther than is currently allowed. Cur...
[ "you can add extra white space to the treeview by increasing its vertical scrollbar maximum value. Smth like this:\nmax = self.treeview.verticalScrollBar().maximum()\nself.treeview.verticalScrollBar().setMaximum(max*2)\n\nhope this helps, regards \n" ]
[ 2 ]
[]
[]
[ "pyqt", "python", "qt" ]
stackoverflow_0005359722_pyqt_python_qt.txt
Q: hdf5 and ndarray append / time-efficient approach for large data-sets Background I have a k n-dimensional time-series, each represented as m x (n+1) array holding float values (n columns plus one that represents the date). Example: k (around 4 million) time-series that look like 20100101 0.12 0.34 0.45 ...
hdf5 and ndarray append / time-efficient approach for large data-sets
Background I have a k n-dimensional time-series, each represented as m x (n+1) array holding float values (n columns plus one that represents the date). Example: k (around 4 million) time-series that look like 20100101 0.12 0.34 0.45 ... 20100105 0.45 0.43 0.21 ... ... ... ... ....
[ "Have you looked at PyTables? It's a hierarchical database built on top of the HDF5 library.\nIt has several array types, but the \"table\" type sounds like it would work for your data format. It's basically an on-disk version of a NumPy record array, where each column can be a unique data type. Tables have an a...
[ 0 ]
[]
[]
[ "hdf5", "numpy", "performance", "python" ]
stackoverflow_0005359880_hdf5_numpy_performance_python.txt
Q: AppEngine Analytics Model with Lists of Times I want to log analytics data (when someone loads page X, loads a js plugin, cancels a transaction) for my AppEngine app. I'm going to set it up as follows: 1. Event X occurs. 2. Add to taskqueue to put this event in the datastore. 3. Filter over datastore to graph and ...
AppEngine Analytics Model with Lists of Times
I want to log analytics data (when someone loads page X, loads a js plugin, cancels a transaction) for my AppEngine app. I'm going to set it up as follows: 1. Event X occurs. 2. Add to taskqueue to put this event in the datastore. 3. Filter over datastore to graph and analyze usage data. So here's the issue: I'd like...
[ "There's no reason to shard a model. There's no limit on the number of entities you can have with a given kind name - they're all stored in the same Bigtable anyway!\nIt's not clear what you're trying to do that requires filtering on a list. Can you clarify? What sort of query do you want to perform?\n", "Instead...
[ 0, 0 ]
[]
[]
[ "google_app_engine", "google_cloud_datastore", "model", "python", "transactions" ]
stackoverflow_0005250236_google_app_engine_google_cloud_datastore_model_python_transactions.txt
Q: Why am I getting 'IOError Exception Value: [Errno 2] No such file or directory' When saving file with PIL I am building a site using Django/Python and there is one page where the user can upload a photo which is then re-sized and saved using the following function: from PIL import Image, ImageFile def resize(file...
Why am I getting 'IOError Exception Value: [Errno 2] No such file or directory' When saving file with PIL
I am building a site using Django/Python and there is one page where the user can upload a photo which is then re-sized and saved using the following function: from PIL import Image, ImageFile def resize(file_to_resize, string_id,): parser = ImageFile.Parser() while True: s = file_to_resize.read(1024) ...
[ "You have no directory called \"http:\" in the current directory.\nIf you're actually trying to save a file over HTTP, this is not how.\n" ]
[ 3 ]
[]
[]
[ "django", "ioerror", "python", "python_imaging_library" ]
stackoverflow_0005360271_django_ioerror_python_python_imaging_library.txt
Q: Google App Engine, How to make native file object? I'm trying to convert some data got from urlfetch to native python file object. Does anyone know how to do this? I understand GAE can't save files to local. But I need file object due to library's specification. A: You can use python's StringIO class to wrap a a...
Google App Engine, How to make native file object?
I'm trying to convert some data got from urlfetch to native python file object. Does anyone know how to do this? I understand GAE can't save files to local. But I need file object due to library's specification.
[ "You can use python's StringIO class to wrap a a file-like object around any data retrieved by URL Fetch.\nIf you use python's urllib2.urlopen() instead of Google's URL Fetch API, you'll get a file-like object which might work with your library.\n", "If you just need a file-like object, you can use urllib2, which...
[ 4, 1 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0005360064_google_app_engine_python.txt
Q: Import error when adding tweepy in subdirectory I am trying to package tweepy in a subdirectory. But I can't get the imports working. This is the case: import socialmedia import tweepy import logging # This file is in socialmedia / twitter / __init__.py # Tweepy is located in socialmedia / twitter / tweepy / __in...
Import error when adding tweepy in subdirectory
I am trying to package tweepy in a subdirectory. But I can't get the imports working. This is the case: import socialmedia import tweepy import logging # This file is in socialmedia / twitter / __init__.py # Tweepy is located in socialmedia / twitter / tweepy / __init__.py # I am getting this error: """ Traceback (...
[ "Looks like tweepy expects to be on the Python path--it tries to load tweepy.models. However, since you put tweepy in a subdirectory, the models module is now located at socialmedia.twitter.tweepy.models. \nYou either have to add socialmedia/twitter/ to the Python path, or you have to change tweepy's imports to c...
[ 3 ]
[]
[]
[ "import", "importerror", "python", "tweepy" ]
stackoverflow_0005360035_import_importerror_python_tweepy.txt