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: Mechanize not logging in to site properly After spending the best part of 3 hours getting nowhere, i thought i would ask a question myself. i am using python and mechanize's Browser. I am trying to login to my home router. i can get to the login page, fill the password field (eg br.form['password'] = 'mypassword' ...
Mechanize not logging in to site properly
After spending the best part of 3 hours getting nowhere, i thought i would ask a question myself. i am using python and mechanize's Browser. I am trying to login to my home router. i can get to the login page, fill the password field (eg br.form['password'] = 'mypassword' etc), but now i am stuck because no matter what...
[ "Here's some sample code for mechanize implementing cookies and a fake user-agent -- might help out...\nimport mechanize\n\ncookies = mechanize.CookieJar()\nopener = mechanize.build_opener(mechanize.HTTPCookieProcessor(cookies))\nopener.addheaders = [(\"User-agent\", \"Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6...
[ 0, 0, 0 ]
[]
[]
[ "mechanize", "python" ]
stackoverflow_0005232770_mechanize_python.txt
Q: how to do automatic updates of a python/bash script? I have some scripts that I would like to automatically update when there is a newer version available (using a cronjob to do the regular checks and download from ftp?). Is there a way (not too complicated/advanced) to achieve that? thanks in advance A: Use svn...
how to do automatic updates of a python/bash script?
I have some scripts that I would like to automatically update when there is a newer version available (using a cronjob to do the regular checks and download from ftp?). Is there a way (not too complicated/advanced) to achieve that? thanks in advance
[ "Use svn or git instead of ftp. \nTo set svn up, go to a svn repository (ie. assembla or github) and read the instructions. You can upload your code then, starting an svn or git repository. each time you update your code you can just write (for svn): \nsvn commit /path/where/you/code \n\nYou have to do a first ch...
[ 2 ]
[]
[]
[ "bash", "ftp", "python" ]
stackoverflow_0005249231_bash_ftp_python.txt
Q: Find index in PCM WAV file after silence with Python I need to be able to find the index, preferably in milliseconds, of a WAV segment immediately after a pause (silence). I'll use this index to indicate where speech starts for a new sentence after the pause of the previous sentence. I can provide a segment of two...
Find index in PCM WAV file after silence with Python
I need to be able to find the index, preferably in milliseconds, of a WAV segment immediately after a pause (silence). I'll use this index to indicate where speech starts for a new sentence after the pause of the previous sentence. I can provide a segment of two or three seconds that will contain the pause and speech o...
[ "I used this in my application once, but I copied/pasted it from SO. Thanks to the person who wrote it ;)\nimport wave\n\nhandle = wave.open('file', 'r')\n\nfor i in range(handle.getnframes()):\n frame = handle.readframes(i)\n\n zero = True\n\n for j in range(len(frame)):\n if ord(frame[j]) > 0:\n zero =...
[ 0 ]
[]
[]
[ "audio", "indexing", "python", "wav" ]
stackoverflow_0005250841_audio_indexing_python_wav.txt
Q: Back end process in windows I need to run the python program in the backend. To the script I have given one input file and the code is processing that file and creating new output file. Now if I change the input file content I don't want to run the code again. It should run in the back end continously and generate...
Back end process in windows
I need to run the python program in the backend. To the script I have given one input file and the code is processing that file and creating new output file. Now if I change the input file content I don't want to run the code again. It should run in the back end continously and generate the output file. Please if someo...
[ "Basically, you have to set up a so-called FileWatcher, i.e. some mechanism which looks out for changes in a file.\nThere are several techniques for watching file/directory changes in python. Have a look at this question: Monitoring contents of files/directories?. Another link is here, this is about directory chang...
[ 0 ]
[]
[]
[ "backend", "process", "python" ]
stackoverflow_0005250851_backend_process_python.txt
Q: Python isn't catching KeyError properly I've tried two different versions of the same function: def position_of(self, table_name, column_name): positions = self.heading_positions() position = positions['{t}.{c}'.format(t=table_name, c=column_name)] return position - def position_of(self, table_name, c...
Python isn't catching KeyError properly
I've tried two different versions of the same function: def position_of(self, table_name, column_name): positions = self.heading_positions() position = positions['{t}.{c}'.format(t=table_name, c=column_name)] return position - def position_of(self, table_name, column_name): positions = self.heading_pos...
[ "The second version of position_of works fine for me. I have turned it into a minimal complete program as follows:\nclass Test(object):\n\n def heading_positions(self):\n return {}\n\n def position_of(self, table_name, column_name):\n positions = self.heading_positions()\n try:\n ...
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0005183013_python.txt
Q: Create Python objects from strings Some Python classes like float can parse strings to create objects: number_string = "4.5" assert float(number_string) == 4.5 What is that technically? A constructor call with a string? But what if the constructor would also take other parameters for usual object construction (no...
Create Python objects from strings
Some Python classes like float can parse strings to create objects: number_string = "4.5" assert float(number_string) == 4.5 What is that technically? A constructor call with a string? But what if the constructor would also take other parameters for usual object construction (not from strings)? How to implement a cla...
[ "It is a constructor call with a string. If you have a constructor that needs more than the string value, then you could define a classmethod factory method that takes a string, extracts the additional data from it (however you have encoded it), and then calls the constructor with all the necessary args. @tiagobol...
[ 3, 2, 1 ]
[ "What you're doing is a cast. The best way to implement a constructor from a string is to use the init method and pass the string to it.\nA more complex example (more than just one string): http://www.java2s.com/Code/Python/Class/Averysimpleclasswithaconstructor.htm\n" ]
[ -1 ]
[ "constructor", "parsing", "python" ]
stackoverflow_0005249813_constructor_parsing_python.txt
Q: Python:How can you get a substring out of string without indices? I have a string s = "* * * * * * * = a b = c b = * * * * * * * " and I would like to print for every item != "*" a substring containing 7 items before and 7 after, e.g.: * * * * * * * = a b = c b = * * * * * * * = a b = c b = * * * * * * * = a b =...
Python:How can you get a substring out of string without indices?
I have a string s = "* * * * * * * = a b = c b = * * * * * * * " and I would like to print for every item != "*" a substring containing 7 items before and 7 after, e.g.: * * * * * * * = a b = c b = * * * * * * * = a b = c b = * * * * * * * = a b = c b = * * * * * * * = a b = c b = * * * * * * * = a b = c b = * * * * ...
[ "Use enumerate() so that you have both the current item and its index available:\nitems = s.split(' ')\nfor index, item in enumerate(items):\n if item != \"*\":\n print items[index-7:index+8]\n\nNote: if it's possible for there to be fewer than 7 * characters at the start of the set, you may want to use a...
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0005251143_python.txt
Q: Twitter Stream response for key words i have small python program to extract tweets from twitter stream for keywords. want to link the keyword with received tweets.how can i do that in python efficiently. I may have more than 200 keys. eg: keywords = "key1,key2,key3" received 4 tweets and i want to directly link ...
Twitter Stream response for key words
i have small python program to extract tweets from twitter stream for keywords. want to link the keyword with received tweets.how can i do that in python efficiently. I may have more than 200 keys. eg: keywords = "key1,key2,key3" received 4 tweets and i want to directly link incoming text and key.. like below 1)tweet...
[ "Use defaultdict from Python's collection module.\nIn [1]: from collections import defaultdict\n\nIn [2]: tweet_keyword_storage = defaultdict(list)\n\nIn [3]: tweet_keyword_storage['key1'].append('tweets msgs key1 tweets tweets text')\n\nIn [4]: tweet_keyword_storage['key2'].append('tweets msgs key2 tweets tweets t...
[ 0 ]
[]
[]
[ "python", "twitter" ]
stackoverflow_0005251168_python_twitter.txt
Q: pyplot of array crashes I am attempting to plot array values obtained from summing individual columns of a numpy array. Working on Win XP, Python 2.5, matplotlib-1.0.1, numpy-1.5.1, PIL-1.1.7 Here is the code: import Image import numpy as np import matplotlib.pyplot as plt im = Image.open("tish.pnm") im = im.conv...
pyplot of array crashes
I am attempting to plot array values obtained from summing individual columns of a numpy array. Working on Win XP, Python 2.5, matplotlib-1.0.1, numpy-1.5.1, PIL-1.1.7 Here is the code: import Image import numpy as np import matplotlib.pyplot as plt im = Image.open("tish.pnm") im = im.convert("1") # convert necessary ...
[ "It should also be noted, that besides the fact that you are attempting to plot a dict rather than a numpy array (this is why your code is producing an error), that you could achieve the same results without using an explicit python loop by using\nsums = np.sum(data,axis=0)\n\nand then plot the data using\nplt.plot...
[ 0 ]
[]
[]
[ "matplotlib", "numpy", "python" ]
stackoverflow_0005251127_matplotlib_numpy_python.txt
Q: Python function to make arbitrary strings valid filenames Is there a built-in function which strips all characters which cannot be in Windows filenames from a string or replaces them somehow? E.g. function("Some:unicode\symbols") --> "Some-unicode-symbols" A: import re arbitrary_string = "File!name?.txt" cleane...
Python function to make arbitrary strings valid filenames
Is there a built-in function which strips all characters which cannot be in Windows filenames from a string or replaces them somehow? E.g. function("Some:unicode\symbols") --> "Some-unicode-symbols"
[ "import re\n\narbitrary_string = \"File!name?.txt\"\ncleaned_up_filename = re.sub(r'[/\\\\:*?\"<>|]', '', arbitrary_string)\nfilepath = os.path.join(\"/tmp\", cleaned_up_filename)\n\nwith open(filepath, 'wb') as f:\n # ...\n\nTaken from User gx \nObviously adapt to your situation.\n" ]
[ 5 ]
[]
[]
[ "filenames", "python", "string", "windows" ]
stackoverflow_0005251330_filenames_python_string_windows.txt
Q: Problem using Python to slice lists to map data One of my new duties requires me to translate or map data from one format to another, usually from xcel, csv or ms mdb into xml, sql or per a spec that I am given so usually each mapping is different. I have taken to learning Python to do this as a precursor to Lisp....
Problem using Python to slice lists to map data
One of my new duties requires me to translate or map data from one format to another, usually from xcel, csv or ms mdb into xml, sql or per a spec that I am given so usually each mapping is different. I have taken to learning Python to do this as a precursor to Lisp. I am learning more each day and am actually having f...
[ "You are comparing strings. Look at that comparisions:\n>>> \"23\"<\"3\"\nTrue\n>>> \"04\"<\"3\"\nTrue\n\nI think you want to compare the integer values. Try this:\n...\n if int(csvitem[63:64]) <= 3:\n...\netc.\n", "When you tell python to compare things, it will very rarely complain. If you tell it to compare...
[ 1, 1, 1, 0, 0 ]
[]
[]
[ "python", "slice" ]
stackoverflow_0005251356_python_slice.txt
Q: Dictionary of dictionaries in python! How do I create a dictionary in python whose values are also a dictionary? Basically, my question is that I have this list of lists: ['http://a11y.in/a11ypi/idea/a11y_firesafety.html', ['lang:hi', 'lang:kn'], ['a11y_firesafety.html:div1', 'a11y_firesafety.html:div1'], ['hi...
Dictionary of dictionaries in python!
How do I create a dictionary in python whose values are also a dictionary? Basically, my question is that I have this list of lists: ['http://a11y.in/a11ypi/idea/a11y_firesafety.html', ['lang:hi', 'lang:kn'], ['a11y_firesafety.html:div1', 'a11y_firesafety.html:div1'], ['hi', 'kn'] ] and I want to convert it to: {'...
[ "Building off of phooji's answer, you can use a function similar to itertools.chain to take care of the nested lists.\ndef forget_torpedoes(mylist):\n return reduce(lambda acc, x: {x : acc}, reversed(mylist))\n\ndef chain(iterable):\n for it in iterable:\n if isinstance(it, str):\n yield it\...
[ 2, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0005250319_python.txt
Q: Python prime number code running slow I am trying to solve the problem mentioned here: https://www.spoj.pl/problems/PRIME1/ I am also giving the description below. Peter wants to generate some prime numbers for his cryptosystem. Help him! Your task is to generate all prime numbers between two given numbers! Input...
Python prime number code running slow
I am trying to solve the problem mentioned here: https://www.spoj.pl/problems/PRIME1/ I am also giving the description below. Peter wants to generate some prime numbers for his cryptosystem. Help him! Your task is to generate all prime numbers between two given numbers! Input The input begins with the number t of test...
[ "A primality testing function will perform best. There's pseudocode on the Miller-Rabin wikipedia page\n", "Instead of removing the element that is not a prime, why not replace it with some sentinel value, perhaps -1 or None? Then when printing, just print the values that aren't sentinels.\nUse a list of length ...
[ 3, 2, 1, 1 ]
[]
[]
[ "algorithm", "data_structures", "primes", "python" ]
stackoverflow_0005208074_algorithm_data_structures_primes_python.txt
Q: determine if a list contains other lists if I have a list, is there any way to check if it contains any other lists? what i mean to say is, I want to know if a list has this strcuture: [] as opposed to this structure [[]] so, compare [1,2,3,4] to [1,[2,3],4] this is complicated by the fact that i have a list of st...
determine if a list contains other lists
if I have a list, is there any way to check if it contains any other lists? what i mean to say is, I want to know if a list has this strcuture: [] as opposed to this structure [[]] so, compare [1,2,3,4] to [1,[2,3],4] this is complicated by the fact that i have a list of strings. well, phihag's solution seems to be wor...
[ "any(isinstance(el, list) for el in input_list)\n\n", "You can take phihag's answer even further if you actually want a list of all the lists inside the list:\noutput_list = filter( lambda x: isinstance(x,list), input_list)\n\n" ]
[ 129, 5 ]
[ "lst1 in lst2\n\nYields True iff lst1 is in lst2.\n" ]
[ -4 ]
[ "python" ]
stackoverflow_0005251663_python.txt
Q: Python - Django - How to handle a multiple page form correctly I have an application that is used to store vehicle information. I created a Vehicle Model which has many foreign keys including a Consumption Model, Capacity Model, Tires Model, Fuel Model etc. Multiple Page Form: When a user wants to add a vehicle t...
Python - Django - How to handle a multiple page form correctly
I have an application that is used to store vehicle information. I created a Vehicle Model which has many foreign keys including a Consumption Model, Capacity Model, Tires Model, Fuel Model etc. Multiple Page Form: When a user wants to add a vehicle to the inventory I wanted to use a multiple page form to break up the...
[ "You are looking for the form wizard: \n\nDjango comes with an optional “form wizard” application that splits forms across multiple Web pages. It maintains state in hashed HTML fields so that the full server-side processing can be delayed until the submission of the final form.\nYou might want to use this if you h...
[ 2 ]
[]
[]
[ "django", "django_forms", "python" ]
stackoverflow_0005251652_django_django_forms_python.txt
Q: Django - Join 2 Models in Query class Person(models.Model): name = models.CharField(max_length=20) employer = models.CharField(max_length=20) class Phone(models.Model): person = models.ForeignKey(Person) number = models.CharField(max_length=10) vendor = models.CharField(max_length=20) How to ...
Django - Join 2 Models in Query
class Person(models.Model): name = models.CharField(max_length=20) employer = models.CharField(max_length=20) class Phone(models.Model): person = models.ForeignKey(Person) number = models.CharField(max_length=10) vendor = models.CharField(max_length=20) How to write a query to retrieve all the Pho...
[ "\"Lookups that span relationships\"\nPhone.objects.filter(number=u'945678987', person__employer=u'xyz')\n\n", "Phone.objects.filter(number='945678987', person__employer='xyz')\n\n" ]
[ 10, 4 ]
[]
[]
[ "django", "django_models", "django_queryset", "python" ]
stackoverflow_0005251868_django_django_models_django_queryset_python.txt
Q: get dbus.Struct properties I'm trying to write a notification script using python-dbus. How can I get properties from a dbus.Struct object? For example if I print it out as string, it is dbus.Struct((dbus.String(u'msg_subject:Re: email subject'),), signature=None) I need to get the inner string. A: Looks like ...
get dbus.Struct properties
I'm trying to write a notification script using python-dbus. How can I get properties from a dbus.Struct object? For example if I print it out as string, it is dbus.Struct((dbus.String(u'msg_subject:Re: email subject'),), signature=None) I need to get the inner string.
[ "Looks like dbus.Struct inherits from tuple, so you should be able to do this:\n>>> msg = dbus.Struct((dbus.String(u'msg_subject:Re: email subject'),), signature=None)\n>>> msg[0]\ndbus.String(u'msg_subject:Re: email subject')\n\n" ]
[ 4 ]
[]
[]
[ "dbus", "python" ]
stackoverflow_0005251808_dbus_python.txt
Q: error producing SVG from sympy / svgmath I am trying to render algebra as an SVG using sympy and svgmath. I have the file 'svgmath.xml' in the root directory. Unfortunately I get: 'ImportError: No module named libxml2'. I'm not sure of the best way to sort this out. I would much appreciate any help/advice. My code...
error producing SVG from sympy / svgmath
I am trying to render algebra as an SVG using sympy and svgmath. I have the file 'svgmath.xml' in the root directory. Unfortunately I get: 'ImportError: No module named libxml2'. I'm not sure of the best way to sort this out. I would much appreciate any help/advice. My code is: from xml import sax from xml.sax.saxutils...
[ "Install the libxml2 library. For example, on ubuntu this is the python-libxml2 package. I too tried the sympy -> mathml -> svg route once, I also had to install the package (iirc it's needed for c2p(), which applies a XSLT to convert content to presentation MathML). \n" ]
[ 3 ]
[]
[]
[ "mathml", "python", "svg", "sympy" ]
stackoverflow_0005251419_mathml_python_svg_sympy.txt
Q: Ld wrong symbol I'm buildnig application with boost.python library. I want to link it. Here is the code: #include <boost/python.hpp> using namespace boost::python; // Boost.python definitions to expose classes to Python BOOST_PYTHON_MODULE(arrayClasses) { } And makefile for it: PYTHON = /usr/include/python2.7 B...
Ld wrong symbol
I'm buildnig application with boost.python library. I want to link it. Here is the code: #include <boost/python.hpp> using namespace boost::python; // Boost.python definitions to expose classes to Python BOOST_PYTHON_MODULE(arrayClasses) { } And makefile for it: PYTHON = /usr/include/python2.7 BOOST_INC = /usr/inclu...
[ "\nYou have -fPIC for your .o target, but not\n for the .so target. See if adding it helps.\n\nEdit: Ignore that. This compiles for me on a 32-bit Ubuntu system using Python 2.6 and Boost 1.44. As Ignacio Vazquez-Abrams pointed out, you should probably check if your Python and Boost libraries were compiled for the...
[ 1 ]
[]
[]
[ "boost", "c++", "linker", "python", "symbols" ]
stackoverflow_0005252091_boost_c++_linker_python_symbols.txt
Q: Does python's `os.system` ever throw an exception? Might the esteemed os.system of Python fame throw an exception? If so, which ones? A: Short answer: yes: >>> import os >>> os.system(None) TypeError ... Long answer: look here http://docs.python.org/library/subprocess.html#subprocess-replacements to see how to ...
Does python's `os.system` ever throw an exception?
Might the esteemed os.system of Python fame throw an exception? If so, which ones?
[ "Short answer: yes:\n>>> import os\n>>> os.system(None)\nTypeError ...\n\nLong answer: look here http://docs.python.org/library/subprocess.html#subprocess-replacements to see how to avoid using os.system. \n", "On POSIX systems it appears to be a straight pass-through to system() (listing from Python 2.7.1's posi...
[ 9, 5, 4, 3 ]
[]
[]
[ "command_line", "exception", "exception_handling", "operating_system", "python" ]
stackoverflow_0005251771_command_line_exception_exception_handling_operating_system_python.txt
Q: Blender, UV Layer, Image and Python I'm trying to access UV Layer in Blender from Python and basically API returns UV Layer only as a string. Thing is I want to assign new Image object to current UV Layer ( I use TexFace on the side of material ) and then just bake lighting. All meshes are currently unwrapped, the...
Blender, UV Layer, Image and Python
I'm trying to access UV Layer in Blender from Python and basically API returns UV Layer only as a string. Thing is I want to assign new Image object to current UV Layer ( I use TexFace on the side of material ) and then just bake lighting. All meshes are currently unwrapped, the only thing which is missing is an Image ...
[ "What you could do is (if you are using Blender 2.49b) set the image of the Texture object and the uvlayer property of the MTex object.\n" ]
[ 0 ]
[]
[]
[ "blender", "python", "textures" ]
stackoverflow_0003290443_blender_python_textures.txt
Q: is it possible to find random floats in range [a,b] in python? I'm trying to generate in python random floats in the range of [0.8,0.9] , but unfortanetly all the tools i found could only generate randoms in the range of [a,b) for floats. ( like Random.uniform(a,b) ) Meanwhile , I tried doing something like this :...
is it possible to find random floats in range [a,b] in python?
I'm trying to generate in python random floats in the range of [0.8,0.9] , but unfortanetly all the tools i found could only generate randoms in the range of [a,b) for floats. ( like Random.uniform(a,b) ) Meanwhile , I tried doing something like this : uniform(0.8,0.90000000001) but thats realy bad any ideas ?
[ "The difference between [0.8, 0.9] and [0.8,0.9) is vanishingly small. Given the limitations of binary floating-point, I don't think there even is a difference, since 0.9 can't be precisely represented anyway. Use [0.8,0.9).\n", "Quoting the random.uniform() docstring:\n\nGet a random number in the range [a, b)...
[ 8, 4, 3, 2, 1 ]
[]
[]
[ "floating_point", "python", "random" ]
stackoverflow_0005249717_floating_point_python_random.txt
Q: Borg pattern or just module with functions I was thinking about using Singleton pattern in my project, so I searched StackOverflow to find a pythonic way to implement it. I found this question with the accepted answer saying that "a module with functions (and not a class) would serve well as a singleton". On other...
Borg pattern or just module with functions
I was thinking about using Singleton pattern in my project, so I searched StackOverflow to find a pythonic way to implement it. I found this question with the accepted answer saying that "a module with functions (and not a class) would serve well as a singleton". On other hand the second answer had a suggestion to use ...
[ "The difference is that in the Borg pattern you'll have different objects whose attributes are the same while using the module version gets you one object (the module).\nAlso an object and a module are slightly different: you cannot pickle modules but you can pickle classes. Also, you can have operations on objects...
[ 3, 3, 2, 1 ]
[]
[]
[ "design_patterns", "python" ]
stackoverflow_0004248213_design_patterns_python.txt
Q: how to perform word by word slicing of a scanned page with python? Is there any way to slice a scanned image of a text into a number of images containing one word each? ie if we scan a page with 'n' words thent the script should produce 'n' seperate images. (using python) A: This is not an area I'm very famile...
how to perform word by word slicing of a scanned page with python?
Is there any way to slice a scanned image of a text into a number of images containing one word each? ie if we scan a page with 'n' words thent the script should produce 'n' seperate images. (using python)
[ "This is not an area I'm very familer with but, assuming you are not able to use OCR (because your text is illegible or something), I would (probably naively) try something like:\n\nload image data into memory\nsplit the pixel data into rows of the image\nfind each \"row\" that has only white pixels all the way acr...
[ 3, 2 ]
[]
[]
[ "image_processing", "python", "python_imaging_library" ]
stackoverflow_0005251066_image_processing_python_python_imaging_library.txt
Q: how to use str.replace() as the function in map() I have a list of rows returned from an excel sheet. I want to use the replace function on each item in row to replace ' with \' however, this does not work: row = map(replace('\'', "\\'"), row) this just gives an error about replace taking at most 3 arguments but ...
how to use str.replace() as the function in map()
I have a list of rows returned from an excel sheet. I want to use the replace function on each item in row to replace ' with \' however, this does not work: row = map(replace('\'', "\\'"), row) this just gives an error about replace taking at most 3 arguments but only having 2. is there a way to use replace with map i...
[ "map( lambda s: s.replace(...), row )\n\nor use a list comprehension\n[s.replace(...) for s in row]\n\n", "The idiomatic Python here is probably to use a list comprehension:\nrow = [ x.replace('\\'', \"\\\\'\") for x in row ]\n\n", "The first arg to replace is a function; what you have is an attempt at a functi...
[ 23, 6, 2, 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0005252834_python.txt
Q: Run Windows CMD commands via Python I want to create a folder with symlinks to all files in a large directory structure. I used subprocess.call(["cmd", "/C", "mklink", linkname, filename]) first, and it worked, but opened a new command windows for each symlink. I couldn't figure out how to run the command in the ...
Run Windows CMD commands via Python
I want to create a folder with symlinks to all files in a large directory structure. I used subprocess.call(["cmd", "/C", "mklink", linkname, filename]) first, and it worked, but opened a new command windows for each symlink. I couldn't figure out how to run the command in the background without a window popping up, s...
[ "Python strings are Unicode, but the pipe you're writing to only supports bytes. Try:\ncmdprocess.stdin.write((\"mklink \" + linkname + \" \" + fullname + \"\\r\\n\").encode(\"utf-8\"))\n\n" ]
[ 1 ]
[]
[]
[ "mklink", "popen", "python", "python_3.x", "windows" ]
stackoverflow_0005253206_mklink_popen_python_python_3.x_windows.txt
Q: Python - Calculating Distance in Dijkstra I am having some trouble in determining the distance of each node from the start node, or rather getting any information back at all. I get no output from my function, attached in the following link. #Values to assign to each node class Node: distFromSource = infinit...
Python - Calculating Distance in Dijkstra
I am having some trouble in determining the distance of each node from the start node, or rather getting any information back at all. I get no output from my function, attached in the following link. #Values to assign to each node class Node: distFromSource = infinity previous = invalid_node visited = F...
[ "You're setting nearestNeighbour to be an empty list, and then you're looping over it with for currentNode in nearestNeighbour -- which does nothing, because the list is empty -- and then you're returning from the function.\n(I assume tentativeDistance is the function you're calling and seeing nothing from.)\n", ...
[ 2, 1 ]
[]
[]
[ "dijkstra", "python" ]
stackoverflow_0005253116_dijkstra_python.txt
Q: Determining Paths for Loaded Modules in Node.js In Node.js, is there any way to determine where on the filesystem a module was loaded from? I do NOT mean, what directory context Node.js is executing in--which you can determine with process.cwd(). I want to know something specific about whatever module is in memory...
Determining Paths for Loaded Modules in Node.js
In Node.js, is there any way to determine where on the filesystem a module was loaded from? I do NOT mean, what directory context Node.js is executing in--which you can determine with process.cwd(). I want to know something specific about whatever module is in memory. For instance, in Python I can do the following... >...
[ "You should be able to use require.resolve('module_name') \n", "Maybe you could use the require.resolve(...) function to get what you are looking for.\n" ]
[ 7, 0 ]
[]
[]
[ "commonjs", "javascript", "module", "node.js", "python" ]
stackoverflow_0005253183_commonjs_javascript_module_node.js_python.txt
Q: Very Long If Statement in Python I have a very long if statement in Python. What is the best way to break it up into several lines? By best I mean most readable/common. A: According to PEP8, long lines should be placed in parentheses. When using parentheses, the lines can be broken up without using backslashes...
Very Long If Statement in Python
I have a very long if statement in Python. What is the best way to break it up into several lines? By best I mean most readable/common.
[ "According to PEP8, long lines should be placed in parentheses. When using parentheses, the lines can be broken up without using backslashes. You should also try to put the line break after boolean operators.\nFurther to this, if you're using a code style check such as pycodestyle, the next logical line needs to ha...
[ 244, 53 ]
[]
[]
[ "python" ]
stackoverflow_0005253348_python.txt
Q: How to stream a video online while it is being generated and a failed CGI approach I have a program that can generate video in real time. Now I would like to stream this video online while it is being generated. Does anybody know an easy way to do it? I am describing a CGI approach I tried but did not work, but p...
How to stream a video online while it is being generated and a failed CGI approach
I have a program that can generate video in real time. Now I would like to stream this video online while it is being generated. Does anybody know an easy way to do it? I am describing a CGI approach I tried but did not work, but please note that I am open to all options that would achieve my goal. I am just wondering...
[ "What type of file is test2.mpg?\nIf it's an mpeg4 file your approach won't work because you will have headers at the start or end of the file.\nIf your file is an mpeg2 transport stream, then this should work.\n", "You're probably hitting end-of-file and so your loop is failing, either with EOFError or crashing ...
[ 2, 1 ]
[]
[]
[ "cgi", "live_streaming", "python", "streaming", "video_streaming" ]
stackoverflow_0005228014_cgi_live_streaming_python_streaming_video_streaming.txt
Q: Cannot import edu.stanford.nlp - Stanford parser with jython problem Can someone help me out with the stanford parser from http://nlp.stanford.edu/software/lex-parser.shtml? I've only downloaded and unzipped the parser. I've also installed the jython fully but i cannot parse a sentence, it seems like i've instal...
Cannot import edu.stanford.nlp - Stanford parser with jython problem
Can someone help me out with the stanford parser from http://nlp.stanford.edu/software/lex-parser.shtml? I've only downloaded and unzipped the parser. I've also installed the jython fully but i cannot parse a sentence, it seems like i've installed some modules or something. http://wiki.python.org/jython/InstallationIn...
[ "You have a typo in your sys.append statement. The filename says 2011 when it should be 2010:\nimport sys\nsys.path.append('./stanford-parser-2010-11-30/stanford-parser-2010-11-30.jar')\nfrom edu.stanford.nlp import *\nprint fsm\n<java package edu.stanford.nlp.fsm 1>\n\n", "You might also look here for some start...
[ 1, 1 ]
[]
[]
[ "java", "jython", "nlp", "python", "stanford_nlp" ]
stackoverflow_0005241079_java_jython_nlp_python_stanford_nlp.txt
Q: Using CouchDB in a DAL-like way from web2py It looks like using CouchDB with the standard web2py DAL is still a ways off: User suggestion for couchdb DAL in web2py Discussion with mdipierro almost a year ago I'm working on using CouchDB from web2py. python-couchdb looks fairly powerful and well designed but not ...
Using CouchDB in a DAL-like way from web2py
It looks like using CouchDB with the standard web2py DAL is still a ways off: User suggestion for couchdb DAL in web2py Discussion with mdipierro almost a year ago I'm working on using CouchDB from web2py. python-couchdb looks fairly powerful and well designed but not particularly well documented. Does anybody have g...
[ "The new web2py DAL is in trunk (still being tested before release), and it looks like it will have support for CouchDB and MongoDB (also here and here), and probably more to come.\n", "Look into the file gluon/contrib/gql.py which overrides the DAL to work on GAE. couchdb would work very much the same. we have o...
[ 2, 1, 1 ]
[]
[]
[ "couchdb", "database", "python", "web2py" ]
stackoverflow_0004208578_couchdb_database_python_web2py.txt
Q: debugging: how to check what where my Python program is hanging? A fairly large Python program I write, runs, but sometimes, after running for minutes or hours, in a non easily reproducible moment, hangs and outputs nothing to the screen. I have no idea what it is doing at that moment, and in what part of code it ...
debugging: how to check what where my Python program is hanging?
A fairly large Python program I write, runs, but sometimes, after running for minutes or hours, in a non easily reproducible moment, hangs and outputs nothing to the screen. I have no idea what it is doing at that moment, and in what part of code it is. How can I run this in a debugger or something to see what lines of...
[ "This could be useful to you. I usually do\n>>> import pdb\n>>> import program2debug\n>>> pdb.run('program2debug.test()')\n\nI usually add a -v option to my programs, which enables tons of print statements explaining what I'm doing in detail. When you write a program in the future, consider doing the same before i...
[ 5, 0, 0 ]
[]
[]
[ "debugging", "python", "trace" ]
stackoverflow_0005145868_debugging_python_trace.txt
Q: Convert list of dicts to string I'm very new to Python, so forgive me if this is easier than it seems to me. I'm being presented with a list of dicts as follows: [{'directMember': 'true', 'memberType': 'User', 'memberId': 'address1@example.com'}, {'directMember': 'true', 'memberType': 'User', 'memberId': 'addre...
Convert list of dicts to string
I'm very new to Python, so forgive me if this is easier than it seems to me. I'm being presented with a list of dicts as follows: [{'directMember': 'true', 'memberType': 'User', 'memberId': 'address1@example.com'}, {'directMember': 'true', 'memberType': 'User', 'memberId': 'address2@example.com'}, {'directMember'...
[ "', '.join(d['memberId'] for d in my_list)\n\nSince you said you are new to Python, I'll explain how this works.\nThe str.join() method combines each element of an iterable (like a list), and uses the string that the method is called on as the separator. \nThe iterable that is provided to the method is the generat...
[ 22, 8, 2 ]
[]
[]
[ "dictionary", "list", "python", "string" ]
stackoverflow_0005253773_dictionary_list_python_string.txt
Q: Problem with unescaping unicode strings I have a problem with unescapting unicode string. I tried the following, but it doesn't work with unicode chars. >>> s = ur"\'test\'" >>> s.decode("string_escape") "'test'" >>> s = ur"\'test \u2014\'" >>> s.decode("string_escape") Traceback (most recent call last): File "<...
Problem with unescaping unicode strings
I have a problem with unescapting unicode string. I tried the following, but it doesn't work with unicode chars. >>> s = ur"\'test\'" >>> s.decode("string_escape") "'test'" >>> s = ur"\'test \u2014\'" >>> s.decode("string_escape") Traceback (most recent call last): File "<stdin>", line 1, in <module> UnicodeEncodeErr...
[ "First, there's \"string_escape\" and \"unicode_escape\", either can't decode the string that you have given. The first reads a bytestring escaped as a bytestring, and decodes it as a bytestring. The second reads an unicode string escaped and saved in a bytestring, so it can't read an input unicode objects, at leas...
[ 2, 0 ]
[]
[]
[ "python", "unicode" ]
stackoverflow_0005252739_python_unicode.txt
Q: Wrapping Python int/float objects I am working on a Python concurrency framework (I know, YACF) and would like to be able to return variables as Futures, but without the user noticing it. Right now I am doing: x = someAsyncMethod(args) print "Return value is %d" % x.get_value( ) Because the method return a Futur...
Wrapping Python int/float objects
I am working on a Python concurrency framework (I know, YACF) and would like to be able to return variables as Futures, but without the user noticing it. Right now I am doing: x = someAsyncMethod(args) print "Return value is %d" % x.get_value( ) Because the method return a Future object, but I would like it to be: x ...
[ ">>> class I(object):\n... def __int__(self):\n... return 42\n... \n>>> i = I()\n>>> print '%d' % i\n42\n>>> class F(object):\n... def __float__(self):\n... return 3.14\n... \n>>> f = F()\n>>> print '%f' % f\n3.140000\n>>> class S(object):\n... def __str__(self):\n... return 'foo'\n... \n>>> s = S...
[ 1, 0 ]
[]
[]
[ "concurrency", "metaprogramming", "python" ]
stackoverflow_0005253386_concurrency_metaprogramming_python.txt
Q: How do you convert a string to a function in python? How do you convert a string (for example, input from a textbox) into a proper function? A: You can use eval. But be very careful! This opens up lots of security holes. >>> s = '3+4' >>> eval(s) 7 If you want it callable: >>> s = '3+4' >>> f = eval('lambda: ' ...
How do you convert a string to a function in python?
How do you convert a string (for example, input from a textbox) into a proper function?
[ "You can use eval. But be very careful! This opens up lots of security holes.\n>>> s = '3+4'\n>>> eval(s)\n7\n\nIf you want it callable:\n>>> s = '3+4'\n>>> f = eval('lambda: ' + s)\n>>> f()\n7\n\nMore information on eval here.\n", "try this \nfunc = ___import___('func_name')\n\nor\nif hasattr(your_module, func_n...
[ 6, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0001515601_python.txt
Q: Which shell command can I use In windows (XP or older) to bring me the print picture dialog? In Python, if I want to open/launch the default browser using shell, I can import os and execute run "www.google.com". Is there any similar way to open the print pictures dialog for a given image.jpg as if right clicking i...
Which shell command can I use In windows (XP or older) to bring me the print picture dialog?
In Python, if I want to open/launch the default browser using shell, I can import os and execute run "www.google.com". Is there any similar way to open the print pictures dialog for a given image.jpg as if right clicking it and selecting print in the context menu that I can use to call this routine from python??? Thank...
[ "You can call win32api.ShellExecute with the \"print\" verb. An example: http://timgolden.me.uk/python/win32_how_do_i/print.html\n", "At least on my Windows system (Windows 7), there seems to be no trivial way to achieve this. I found that a naive call to ShellExecute appeared to do nothing. Then I tried this:\ni...
[ 3, 2 ]
[]
[]
[ "printing", "python", "shell", "windows" ]
stackoverflow_0005253846_printing_python_shell_windows.txt
Q: Python Windows CMD mklink, stops working without error message I want to create symlinks for each file in a nested directory structure, where all symlinks will be put in one large flat folder, and have the following code by now: # loop over directory structure: # for all items in current directory, # if item is di...
Python Windows CMD mklink, stops working without error message
I want to create symlinks for each file in a nested directory structure, where all symlinks will be put in one large flat folder, and have the following code by now: # loop over directory structure: # for all items in current directory, # if item is directory, recurse into it; # else it's a file, then create a symlink ...
[ "Why not just execute mklink directly?\n", "Try this at the end:\nif not os.path.exists(linkname):\n fullcmd = \"mklink \" + linkname + \" \" + fullname + \"\\r\\n\"\n print fullcmd\n cmdprocess.stdin.write(fullcmd)\n\nSee what commands it prints. You may see a problem.\nIt may need double quotes around ...
[ 0, 0 ]
[]
[]
[ "cmd", "mklink", "popen", "python", "windows" ]
stackoverflow_0005253835_cmd_mklink_popen_python_windows.txt
Q: form.is_valid() always returning false Form.is_valid() is always returning false, and it never shows any kind of error. Following is the code snippet from forms.py, views.py and template/transaction_add_page.html Form class TransactionForm(forms.Form): account = forms.ModelChoiceField(queryset=Account.objects.no...
form.is_valid() always returning false
Form.is_valid() is always returning false, and it never shows any kind of error. Following is the code snippet from forms.py, views.py and template/transaction_add_page.html Form class TransactionForm(forms.Form): account = forms.ModelChoiceField(queryset=Account.objects.none()) transactions = forms.CharField(widge...
[ "if you set on the initializer the user argument, you need to use it.\nif request.method == 'POST':\n form = TransactionForm(user=request.user, data=request.POST)\n\n" ]
[ 2 ]
[]
[]
[ "django", "django_forms", "python" ]
stackoverflow_0005254470_django_django_forms_python.txt
Q: Using django aggregates as filter clauses Is there a better way to do this? # Get an instance of the class I am interested in. It has a manytomany relation instance = Class.objects.get(pk=1) # Get the highest start date out of all the objects in the manytomany set max_date = instance.related_set.aggregate(Max("st...
Using django aggregates as filter clauses
Is there a better way to do this? # Get an instance of the class I am interested in. It has a manytomany relation instance = Class.objects.get(pk=1) # Get the highest start date out of all the objects in the manytomany set max_date = instance.related_set.aggregate(Max("start_date")) # Return the object with the highe...
[ "Would using the latest() method for getting the \"max\" date suit your needs?\ndjango-query-using-order-by-and-latest\nmight be of interest.\n" ]
[ 1 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0005254322_django_django_models_python.txt
Q: GAE User registry without Google Accounts, want to restric to specific domain I am planning on creating an application for the students of my school, and I want to restrict user registration to emails of the form person@myschool.edu. I would prefer to not manually create the user table and do the password hashing ...
GAE User registry without Google Accounts, want to restric to specific domain
I am planning on creating an application for the students of my school, and I want to restrict user registration to emails of the form person@myschool.edu. I would prefer to not manually create the user table and do the password hashing and such. Are there any libraries you can recommend for this? Thanks for the help.
[ "Sometimes, if you just send the user to a login screen you will end in a redirect loop if the user is already logged with a Google Account.\nWhat i have found to be a good answer to this problem is to redirect the user to a log out page so he can later login with the domain you want.\nI have used this for my code\...
[ 2, 0 ]
[]
[]
[ "google_app_engine", "python", "web_applications" ]
stackoverflow_0002316255_google_app_engine_python_web_applications.txt
Q: wxpython link and open new window apps I have one dialog app and one frame app (two files) and I want them to interact with each other. I would like to to click a button on my dialog app and it will close the dialog app and open my frame app. Any idea how I can achieve this? my dialog app is very simple and looks ...
wxpython link and open new window apps
I have one dialog app and one frame app (two files) and I want them to interact with each other. I would like to to click a button on my dialog app and it will close the dialog app and open my frame app. Any idea how I can achieve this? my dialog app is very simple and looks something like this class ThisClass(wx.Dialo...
[ "You'll want to create a frame around your Dialog app so it doesn't act strangely. No one ever said you have to Show it:\nclass ThisFrame(wx.Frame):\n def __init__(self, parent, title):\n wx.Frame.__init__(self, parent, title=title, size=(0, 0))\n dlg = ThisClass(self, -1, \"buttons.py\")\n\n ...
[ 1 ]
[]
[]
[ "python", "user_interface", "wxpython" ]
stackoverflow_0005254067_python_user_interface_wxpython.txt
Q: Why does float() fail to convert my string to a float? My program is giving me an error when it tries to convert a string from a list of strings to a floating point number. The list is read from a line in a CSV text file and then separated into a list. How do I make this work and why is it going wrong? Here are th...
Why does float() fail to convert my string to a float?
My program is giving me an error when it tries to convert a string from a list of strings to a floating point number. The list is read from a line in a CSV text file and then separated into a list. How do I make this work and why is it going wrong? Here are the relevant bits of code: def Main(): srcf = open(bkp, 'r...
[ "You need to strip the double quotes off the string. This will then you give a legitimate floating point string that float() can convert.\n" ]
[ 9 ]
[]
[]
[ "python" ]
stackoverflow_0005255011_python.txt
Q: File sharing problem with Python inside Excel I have python 2.6 script that creates a bunch of csv files on windows. This script can be run stand alone or inside Excel via VBA shell command. There are no problems when runs as stand alone, followed by VBA script. When I run script inside Excel with a shell call. ...
File sharing problem with Python inside Excel
I have python 2.6 script that creates a bunch of csv files on windows. This script can be run stand alone or inside Excel via VBA shell command. There are no problems when runs as stand alone, followed by VBA script. When I run script inside Excel with a shell call. I have file sharing problems. The Script creates r...
[ "You may want to create a delay after the shell call (doEvents or sleep(100) might work) to allow the OS to properly close the file and remove all pointers to the file. \n" ]
[ 0 ]
[]
[]
[ "excel", "file_io", "python", "vba", "windows" ]
stackoverflow_0005253587_excel_file_io_python_vba_windows.txt
Q: Is it necessary for all these checks in my boss's django code? This is my boss's code: if hasattr(request, 'rk_user') and request.rk_user: request.rk_user.focus_update() but i think it is not necessary to check both I think it should be either: if hasattr(request, 'rk_user') : request.rk_u...
Is it necessary for all these checks in my boss's django code?
This is my boss's code: if hasattr(request, 'rk_user') and request.rk_user: request.rk_user.focus_update() but i think it is not necessary to check both I think it should be either: if hasattr(request, 'rk_user') : request.rk_user.focus_update() or: if request.rk_user: request.rk_...
[ "Although the other answerers are right that they check different things, you can collapse the two checks into a single command: \nif getattr(request, 'rk_user', None):\n\nThis gets the attribute if it exists, and if not, gets None; then it checks that whatever value it got is not empty.\n", "They check for diffe...
[ 7, 3, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0005255296_django_python.txt
Q: How to install pygame font This is a beginner level question. I am teaching myself pygame on ubuntu 10.10. I downloaded a couple of examples and pygame isn't working right. I suspect an install problem. But I'm not sure how to figure it out. Is there something else I have to install to make this work? My ex...
How to install pygame font
This is a beginner level question. I am teaching myself pygame on ubuntu 10.10. I downloaded a couple of examples and pygame isn't working right. I suspect an install problem. But I'm not sure how to figure it out. Is there something else I have to install to make this work? My example: http://cid-bb9549bdfdec7...
[ "Instead of installing through easy_install, install the Ubuntu package for pygame: python-pygame (it's in universe).\n" ]
[ 4 ]
[]
[]
[ "linux", "pygame", "python", "ubuntu" ]
stackoverflow_0005255385_linux_pygame_python_ubuntu.txt
Q: Match set of dictionaries. Most elegant solution. Python Given two lists of dictionaries, new one and old one. Dictionaries represent the same objects in both lists. I need to find differences and produce new list of dictionaries where will be objects from new dictionaries only and updated attributes from old dict...
Match set of dictionaries. Most elegant solution. Python
Given two lists of dictionaries, new one and old one. Dictionaries represent the same objects in both lists. I need to find differences and produce new list of dictionaries where will be objects from new dictionaries only and updated attributes from old dictionaries. Example: list_new=[ { 'id':1, ...
[ "Can't quite get it to one line, but here's a simpler version:\ndef match_new(new_list, old_list) :\n ids = dict((item['id'], item) for item in new_list)\n return [ids[item['id']] for item in old_list if item['id'] in ids]\n\n", "Not knowing the constraints of your data, I will suppose that id is unique in ...
[ 3, 2, 1, 1, 1, 1, 0, 0, 0 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0005252519_dictionary_python.txt
Q: What's the problem with executing commands in Windows CMD from Python? I'm having huge trouble with passing commands to CMD from Python. First, I open a CMD process: cmdprocess = subprocess.Popen("cmd", stdin = subprocess.PIPE, stdout = subpr...
What's the problem with executing commands in Windows CMD from Python?
I'm having huge trouble with passing commands to CMD from Python. First, I open a CMD process: cmdprocess = subprocess.Popen("cmd", stdin = subprocess.PIPE, stdout = subprocess.PIPE, stderr = subprocess.PIPE) The...
[ "Are you handling the output in the PIPES? They might be filling. If you fill up the stdout or stderror buffers from the process, it will stop execution.\n", "I think you'd better to use pywin32 package. there are win32pipe and win32process modules.\nI also had same issue but I could not resolve it without pywin3...
[ 3, 1 ]
[]
[]
[ "cmd", "popen", "python", "windows" ]
stackoverflow_0005254960_cmd_popen_python_windows.txt
Q: Search in PDF, index it? I have 1000+ PDF searchables. I need some plugin or aplication to index it, such as (http) joomla.natemaxfield.com A: We use Swish-e to index our website which includes thousands of PDF's, Word files and even WordPerfect files. It works great. It is free, open source and integrates we...
Search in PDF, index it?
I have 1000+ PDF searchables. I need some plugin or aplication to index it, such as (http) joomla.natemaxfield.com
[ "We use Swish-e to index our website which includes thousands of PDF's, Word files and even WordPerfect files. It works great. It is free, open source and integrates well with PHP.\nhttp://swish-e.org/index.html\nFrom their homepage: \n\nSwish-e is a fast, flexible, and free\n open source system for indexing\n ...
[ 2, 1 ]
[]
[]
[ "pdf", "php", "python" ]
stackoverflow_0005252187_pdf_php_python.txt
Q: python removing duplicates In an array I have the following tuples: ('0000233/02', 50.0, None, None, None, None, 'Yes') ('0000233/02', 200.0, None, None, None, None, 'Yes') if im iterating through the list, how could I eliminate duplicates based solely on the first element? A: Put them in a dict using the...
python removing duplicates
In an array I have the following tuples: ('0000233/02', 50.0, None, None, None, None, 'Yes') ('0000233/02', 200.0, None, None, None, None, 'Yes') if im iterating through the list, how could I eliminate duplicates based solely on the first element?
[ "Put them in a dict using the first element as the key. If you check before adding then you'll get the first item with that key, otherwise you'll get the last.\n", "Look first: http://docs.python.org/faq/programming.html#how-do-you-remove-duplicates-from-a-list\n>>> l=[('0000233/02', 50.0, None, None, None, None,...
[ 3, 1, 1, 1, 0, 0 ]
[]
[]
[ "duplicates", "list", "python", "tuples" ]
stackoverflow_0005251429_duplicates_list_python_tuples.txt
Q: Why does Django call it "views.py" instead of controller? Possible Duplicate: Confused by Django's claim to MVC, what is it exactly? Because in MVC, the "view" is usually the template... A: Django appears to be a MVC framework, but you call the Controller the “view”, and the View the “template”. How come you d...
Why does Django call it "views.py" instead of controller?
Possible Duplicate: Confused by Django's claim to MVC, what is it exactly? Because in MVC, the "view" is usually the template...
[ "Django appears to be a MVC framework, but you call the Controller the “view”, and the View the “template”. How come you don’t use the standard names?\n\nWell, the standard names are\ndebatable.\nIn our interpretation of MVC, the\n“view” describes the data that gets\npresented to the user. It’s not\nnecessarily how...
[ 27, 3 ]
[]
[]
[ "django", "python" ]
stackoverflow_0005249792_django_python.txt
Q: Simple curve smoothing in matplotlib --- equivalent to gnuplot's "smooth bezier"? I have a set of points I want to plot in matplotlib, say: x = [1,4,6,7,8] y = [0.2, 0.4, 0.5, 0.6, 0.6] In gnuplot, I used to be able to directly use the 'plot' command's smooth property to get a smooth curve on a graph, without hav...
Simple curve smoothing in matplotlib --- equivalent to gnuplot's "smooth bezier"?
I have a set of points I want to plot in matplotlib, say: x = [1,4,6,7,8] y = [0.2, 0.4, 0.5, 0.6, 0.6] In gnuplot, I used to be able to directly use the 'plot' command's smooth property to get a smooth curve on a graph, without having to preprocess the data. Is there an equivalent in matplotlib---specify a set of poi...
[ "I think scipy's interpolation and curve-fitting functions are the closest you are going to get. I don't know of anything built into matplotlib.\n" ]
[ 6 ]
[]
[]
[ "matplotlib", "python", "smoothing" ]
stackoverflow_0005255932_matplotlib_python_smoothing.txt
Q: MVP: Presenter-Model communication I have a design question about the communication between the model and the presenter in the MVP design pattern -- or more accurately its derived form the passive view. Let's assume the following simple GUI as an example: I have a window where my view is a list and there is the po...
MVP: Presenter-Model communication
I have a design question about the communication between the model and the presenter in the MVP design pattern -- or more accurately its derived form the passive view. Let's assume the following simple GUI as an example: I have a window where my view is a list and there is the possibility to open a file dialog to selec...
[ "This problem is probably long solved, but I hit it from a search engine so here's my answer:\nUse B. Forget mixing.\nIf you want add in bits of A for efficiency you'll have to have two methods for the model: one returning a boolean, the other emitting events. If the synchronous Model.add method emits events, then ...
[ 1 ]
[]
[]
[ "design_patterns", "mvp", "passive_view", "python" ]
stackoverflow_0003541625_design_patterns_mvp_passive_view_python.txt
Q: google appengine does not print array value I was starting with the google app engine and was trying some quick learning.I stumbled across this issue which does not occur on my local development environment.Here is the code import random, math random.seed() quotesArray=[] quotesArray.append("This is a Test1") quo...
google appengine does not print array value
I was starting with the google app engine and was trying some quick learning.I stumbled across this issue which does not occur on my local development environment.Here is the code import random, math random.seed() quotesArray=[] quotesArray.append("This is a Test1") quotesArray.append("This is a Test2") quotesArray.ap...
[ "I can't explain why the behavior is different between the dev server and production, but in a web application, if you simply print stuff to stdout without first sending HTTP headers, you should expect that your output is going to get mangled. You should at a minimum be printing \"\\r\\n\" before any other output,...
[ 0, 0 ]
[]
[]
[ "arrays", "google_app_engine", "python", "random" ]
stackoverflow_0005238755_arrays_google_app_engine_python_random.txt
Q: Framework for python with sqlite i am new in python.before this i done some work in php with codeigniter framework. now i want to develop website using python and sqlite3. so which framework will you suggest me. i also want to know IDE for sqlite. A: Do you mean something similar to sqliteman or dbeaver? These a...
Framework for python with sqlite
i am new in python.before this i done some work in php with codeigniter framework. now i want to develop website using python and sqlite3. so which framework will you suggest me. i also want to know IDE for sqlite.
[ "Do you mean something similar to sqliteman or dbeaver? These are not not IDEs for SQLite, but instead, are GUI interfaces. There are more here: http://www.google.com/search?&q=sqlite+gui\n3rd link down is another stack overflow question: What are good open source GUI SQLite database managers?\nFor Python web frame...
[ 2, 2 ]
[]
[]
[ "frameworks", "python", "sqlite" ]
stackoverflow_0005242544_frameworks_python_sqlite.txt
Q: how to store the input of radio into datastore template_values = {'Answer1':Answer1, 'Answer2':Answer2, 'Answer3':Answer3, 'Answer4':Answer4, 'Answer5':Answer5, ...
how to store the input of radio into datastore
template_values = {'Answer1':Answer1, 'Answer2':Answer2, 'Answer3':Answer3, 'Answer4':Answer4, 'Answer5':Answer5, 'QuestionText': QuestionText, ...
[ "If your radio buttons are located within the form being POST'ed to your request handler, then you can get the value associated with the selected radio button like this:\n select_answer = self.request.get('answer')\n\nThis quite similar to how you retrieved the value entered for the name text field you described in...
[ 0, 0 ]
[]
[]
[ "django", "google_app_engine", "python" ]
stackoverflow_0005254332_django_google_app_engine_python.txt
Q: Tab-delimited file into dictionary (python) I have a tab separated file How can I input this file into a dictionary? A: You can use the csv module with its DictReader class. A: import csv with open(filename) as file_object: # skip the first two lines file_object.next() file_object.next() list...
Tab-delimited file into dictionary (python)
I have a tab separated file How can I input this file into a dictionary?
[ "You can use the csv module with its DictReader class.\n", "import csv\n\nwith open(filename) as file_object:\n # skip the first two lines\n file_object.next()\n file_object.next()\n list_of_dicts = list(csv.DictReader(file_object, dialect='excel-tab'))\n\n# list_of_dicts now will contain a list of di...
[ 3, 3 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0005256845_dictionary_python.txt
Q: how to execute multiple async queries in google app engine? I want to execute multiple queries asynchronously. Now for that I have searched but nothing special I found. Ya one thing I found is of Asynctools at http://code.google.com/p/asynctools/ but in the code given i am getting the error NameError: global name ...
how to execute multiple async queries in google app engine?
I want to execute multiple queries asynchronously. Now for that I have searched but nothing special I found. Ya one thing I found is of Asynctools at http://code.google.com/p/asynctools/ but in the code given i am getting the error NameError: global name 'AsyncMultiTask' is not defined and I dont kn what to import for ...
[ "A couple of months ago Guido announced a new experimental datastore API, which allows asynchronous calls:\nhttp://neopythonic.blogspot.com/2011/01/new-app-engine-datastore-api.html\n" ]
[ 5 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0005256890_google_app_engine_python.txt
Q: how can I load my .el file only while editing python code I have collected a list of emacs customizations in a file my-python-setup.el. How can I ensure that emacs will first load python-mode and then load this library only when I'm editing python files? I've tried putting (load-library "my-python-setup") in my ...
how can I load my .el file only while editing python code
I have collected a list of emacs customizations in a file my-python-setup.el. How can I ensure that emacs will first load python-mode and then load this library only when I'm editing python files? I've tried putting (load-library "my-python-setup") in my .emacs file, but that loads these customizations for all kinds ...
[ "I'm by no means an Emacs expert, but I think you could just stick add a python-mode-hook function and load your library in there. Something like:\n;; define your hook function\n(defun python-mode-setup ()\n (message \"Custom python hook run\")\n (load-library \"my-python-setup\"))\n\n;; install your hook so it ...
[ 5, 1 ]
[]
[]
[ "emacs", "python" ]
stackoverflow_0005253482_emacs_python.txt
Q: What is an appropriate way to datamine the total number of results of a keyword search? newbie programmer and lurker here, hoping for some sensible advice. :) Using a combination of Python, BeautifulSoup, and the Bing API, I was able to find what I wanted with the following code: import urllib2 from BeautifulSoup ...
What is an appropriate way to datamine the total number of results of a keyword search?
newbie programmer and lurker here, hoping for some sensible advice. :) Using a combination of Python, BeautifulSoup, and the Bing API, I was able to find what I wanted with the following code: import urllib2 from BeautifulSoup import BeautifulStoneSoup Appid = #My Appid query = #My query soup = BeautifulStoneSoup(url...
[ "There are three approaches I can think of that have helped previously when I had to do large scale URL resolution.\n\nHTTP Pipelining (another snippet here)\nRate-limiting server requests per IP (i.e., each IP can only issue 3 requests / second). Some suggestions can be found here: How to limit rate of requests to...
[ 1, 0 ]
[]
[]
[ "beautifulsoup", "bing_api", "google_search_api", "python", "yahoo_boss_api" ]
stackoverflow_0005257288_beautifulsoup_bing_api_google_search_api_python_yahoo_boss_api.txt
Q: Python - convert strings into json and combine I h've two strings got from an api url pagehandle = urllib2.urlopen(ariel_url+"?%s" % params1) data1 = pagehandle.read(); pagehandle = urllib2.urlopen(ariel_url+"?%s" % params2) data2 = pagehandle.read(); data1 and data2 contain the following string {"priority":"...
Python - convert strings into json and combine
I h've two strings got from an api url pagehandle = urllib2.urlopen(ariel_url+"?%s" % params1) data1 = pagehandle.read(); pagehandle = urllib2.urlopen(ariel_url+"?%s" % params2) data2 = pagehandle.read(); data1 and data2 contain the following string {"priority":"HIGH", "titles":["Brand", "Likes"], "values":[["addi...
[ "These are not strings, but dictionaries. You can combine those dictionary like this:\ndef combine(dict1, dict2):\n if dict1['priority'] == dict2['priority'] and dict1['titles'] == dict2['titles']:\n return {\n 'priority': dict1['priority'],\n 'titles': dict1['titles'],\n ...
[ 3, 3 ]
[]
[]
[ "json", "python", "simplejson" ]
stackoverflow_0005257582_json_python_simplejson.txt
Q: Cross-domain Ajax POST and user verification I'm working on app which saves things from many cross domains via Ajax POST method to my server/app. I need to find a solution how to send a POST and verify if the user who sent it is already signed on my site and than save it to the database. I am pretty sure that I ne...
Cross-domain Ajax POST and user verification
I'm working on app which saves things from many cross domains via Ajax POST method to my server/app. I need to find a solution how to send a POST and verify if the user who sent it is already signed on my site and than save it to the database. I am pretty sure that I need Chrome, Firefox extension to do it, because I n...
[ "When the user logons at http://yourserver.com, you can set a permanent cookie to identify him. (see SESSION_EXPIRE_AT_BROWSER_CLOSE and COOKIE_AGE variables in django)\nThen, when he embeds any JS from another site from yourserver.com domain, the cookies are automatically sent for this domain, and you can check on...
[ 1 ]
[]
[]
[ "ajax", "django", "python" ]
stackoverflow_0005257434_ajax_django_python.txt
Q: Python Kombu consumer not notified of rabbitmq message (queue.get does work) If I run the following code, the callback (test) passed to the consumer is never triggered. However, if I keep an eye on the rabbitmq GUI, I do see that the message is retrieved (but not acknowledged). So it seems the consumer is getting...
Python Kombu consumer not notified of rabbitmq message (queue.get does work)
If I run the following code, the callback (test) passed to the consumer is never triggered. However, if I keep an eye on the rabbitmq GUI, I do see that the message is retrieved (but not acknowledged). So it seems the consumer is getting the message, but not passing it on to my callback. If I set no_ack to true, the ...
[ "Turns out its a simple error. Adding\nconnection.drain_events()\n\nto the while loop causes messages to arrive.\n" ]
[ 5 ]
[]
[]
[ "amqp", "python", "rabbitmq" ]
stackoverflow_0005236195_amqp_python_rabbitmq.txt
Q: Receiving WM_COPYDATA in Python I am trying to read from Python the WM_COPYDATA message some applications (I'm trying with Spotify) send to WindowsLiveMessenger to update the "What I'm listening to..." phrase. From what I have been able to find, WM_COPYDATA messages come in a COPYDATASTRUCT with the following stru...
Receiving WM_COPYDATA in Python
I am trying to read from Python the WM_COPYDATA message some applications (I'm trying with Spotify) send to WindowsLiveMessenger to update the "What I'm listening to..." phrase. From what I have been able to find, WM_COPYDATA messages come in a COPYDATASTRUCT with the following structure: dwData in our case 0x547 so t...
[ "I wrote the following trivial win32gui app:\nimport win32con, win32api, win32gui, ctypes, ctypes.wintypes\n\nclass COPYDATASTRUCT(ctypes.Structure):\n _fields_ = [\n ('dwData', ctypes.wintypes.LPARAM),\n ('cbData', ctypes.wintypes.DWORD),\n ('lpData', ctypes.c_void_p)\n ]\nPCOPYDATASTRUC...
[ 7 ]
[]
[]
[ "ctypes", "python", "pywin32", "winapi", "windows" ]
stackoverflow_0005249903_ctypes_python_pywin32_winapi_windows.txt
Q: How do I copy an entire column(including the datatype) from an sqlite table to another table using python? I'm trying to write a function for removing columns in sqlite(Because sometimes I might want to delete columns which are too old). A: From SQLite FAQ: SQLite has limited ALTER TABLE support that you can ...
How do I copy an entire column(including the datatype) from an sqlite table to another table using python?
I'm trying to write a function for removing columns in sqlite(Because sometimes I might want to delete columns which are too old).
[ "From SQLite FAQ:\n\nSQLite has limited ALTER TABLE support\n that you can use to add a column to\n the end of a table or to change the\n name of a table. If you want to make\n more complex changes in the structure\n of a table, you will have to recreate\n the table. You can save existing data\n to a tempora...
[ 1 ]
[]
[]
[ "python", "sqlite" ]
stackoverflow_0005257692_python_sqlite.txt
Q: Python Four Digits Counter How do we use python to generate a four digit counter? range(0,9999) will have 1 digits, 2 digits and 3 digits. We only want 4 digits. i.e. 0000 to 9999 Of course, the simplest Pythonic way. A: Format the string to be padded with 0's. To get a list of 0 to 9999 padded with zeroes: ["%...
Python Four Digits Counter
How do we use python to generate a four digit counter? range(0,9999) will have 1 digits, 2 digits and 3 digits. We only want 4 digits. i.e. 0000 to 9999 Of course, the simplest Pythonic way.
[ "Format the string to be padded with 0's. To get a list of 0 to 9999 padded with zeroes:\n[\"%04d\" % x for x in range(10000)]\n\nSame thing works for 5, 6, 7, 8 zeroes, etc. Note that this will give you a list of strings. There's no way to have an integer variable padded with zeroes, so the string is as close as y...
[ 21, 19, 5, 2, 0 ]
[]
[]
[ "counter", "python" ]
stackoverflow_0005256428_counter_python.txt
Q: Import module from other directory in Wing Ide In module MainClass.py which is in c:\MyProject\ModelClasses I'm trying import module MainHelper.py from c:\MyProject\Helpers from Helpers.MainHelper import MainHelper x=MainHelper() and I get error ImportError: No module named Helpers.MainHelper In WIng IDe I've a...
Import module from other directory in Wing Ide
In module MainClass.py which is in c:\MyProject\ModelClasses I'm trying import module MainHelper.py from c:\MyProject\Helpers from Helpers.MainHelper import MainHelper x=MainHelper() and I get error ImportError: No module named Helpers.MainHelper In WIng IDe I've added path c:\MyProject\Helpers Project->ProjectPrope...
[ "If c:\\MyProject\\Helpers is in PYTHONPATH, you should write\nfrom MainHelper import MainHelper\n\nin the MainClass.py module.\nIf you want to treat the Helpers directory as a package, do the following:\n\nPYTHONPATH should be c:\\MyProject\nThe Helpers directory should have a (possibly empty) __init__.py file in ...
[ 3 ]
[]
[]
[ "import", "python", "wing_ide" ]
stackoverflow_0005258104_import_python_wing_ide.txt
Q: Deleting a record from database using Python I have created a Django app and tested the application's performance by populating some 10,0000 records. Now i want to delete it using a python script. Can somebody help me in doing this. This is the script i created to populate data into sql db. def dumpdata(): fo...
Deleting a record from database using Python
I have created a Django app and tested the application's performance by populating some 10,0000 records. Now i want to delete it using a python script. Can somebody help me in doing this. This is the script i created to populate data into sql db. def dumpdata(): for i in range(2,10): userName = "Bryan" ...
[ "QuerySet.delete()\nEmployeeDetails.objects.filter(...).delete()\n\n" ]
[ 58 ]
[]
[]
[ "django", "django_models", "django_queryset", "django_views", "python" ]
stackoverflow_0005258326_django_django_models_django_queryset_django_views_python.txt
Q: Interrelated requests MySQL, analogue in MongoDB Good day dear colleagues, I decided to move some projects from MySQL to MongoDB and faced several difficulties: For example there are two tables in MySQL: Users: CREATE TABLE `testdb`.`users` ( `id` INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY , `name` VARCHAR( 5...
Interrelated requests MySQL, analogue in MongoDB
Good day dear colleagues, I decided to move some projects from MySQL to MongoDB and faced several difficulties: For example there are two tables in MySQL: Users: CREATE TABLE `testdb`.`users` ( `id` INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY , `name` VARCHAR( 55 ) NOT NULL , `password` VARCHAR( 32 ) NOT NULL ) ENG...
[ "MongoDB does not support joins, unlike RDBMS's like mysql. And that's because MongoDB is not a relational database. Modelling data in MongoDB in the same way as you do in an RDBMS is therefore generally a bad idea - you have to design your schemas in a whole different mindset.\nIn this case for example, in MongoDB...
[ 2 ]
[]
[]
[ "mongodb", "mongoengine", "mongokit", "mysql", "python" ]
stackoverflow_0005258256_mongodb_mongoengine_mongokit_mysql_python.txt
Q: Python sqlite parameter extension problem I have a table with three columns, cell, trx and type. This is the query I'm trying to run: db.execute("SELECT cell,trx FROM tchdrop").fetchall() It gives the correct output. However when I try a = ("cell", "trx") and then db.execute("SELECT ?,? FROM tchdrop", t).fetcha...
Python sqlite parameter extension problem
I have a table with three columns, cell, trx and type. This is the query I'm trying to run: db.execute("SELECT cell,trx FROM tchdrop").fetchall() It gives the correct output. However when I try a = ("cell", "trx") and then db.execute("SELECT ?,? FROM tchdrop", t).fetchall() the output is [(u'cell', u'trx'), (u'cell...
[ "The place holder (?) of python DB-API (like sqlite3) don't support columns names to be passed, so you have to use python string formatting like this:\na = (\"cell\", \"trx\")\n\nquery = \"SELECT {0},{1} FROM tchdrop\".format(*a)\ndb.execute(query)\n\nEDIT:\nif you don't know the length of the columns that you want...
[ 3, 0 ]
[]
[]
[ "python", "sqlite" ]
stackoverflow_0005258610_python_sqlite.txt
Q: Expanding Environment variable in string using python I have a string containing an environment variable, e.g. my_path = '$HOME/dir/dir2' I want parse the string, looking up the variable and replacing it in the string: print "HOME =",os.environ['HOME'] my_expanded_path = parse_string(my_path) print "PATH =", my_e...
Expanding Environment variable in string using python
I have a string containing an environment variable, e.g. my_path = '$HOME/dir/dir2' I want parse the string, looking up the variable and replacing it in the string: print "HOME =",os.environ['HOME'] my_expanded_path = parse_string(my_path) print "PATH =", my_expanded_path So I should see the output: HOME = /home/user...
[ "Use : os.path.expandvars\n", "import string, os\nmy_path = '$HOME/dir/dir2'\nprint string.Template(my_path).substitute(os.environ)\n\n", "You could use a Template:\nfrom string import Template\nimport os\n\nt = Template(\"$HOME/dir/dir2\")\nresult = t.substitute(os.environ)\n\n" ]
[ 36, 12, 4 ]
[]
[]
[ "posix", "python" ]
stackoverflow_0005258647_posix_python.txt
Q: Icons Affecting Menu Style in wxPython on Windows 7 The following bit of code populates a class that inherits from the wx.Menu class, with menu items. So self is basically a wx.Menu. When I run the flowing code snippet, the line about.SetBitmap(wx.Bitmap('Icon24.ico')) seems to change the highlighting from the def...
Icons Affecting Menu Style in wxPython on Windows 7
The following bit of code populates a class that inherits from the wx.Menu class, with menu items. So self is basically a wx.Menu. When I run the flowing code snippet, the line about.SetBitmap(wx.Bitmap('Icon24.ico')) seems to change the highlighting from the default: to this plain blue style: The line about.SetBitma...
[ "Well, according to the WxWidgets doc, the version 2.8 doesn't support Windows Vista or 7, so I think this is expected since looks like it reset the entire menu theme to the XP style, I think the best you can try is to use the testing version 2.9, which support Vista (but not 7).\n" ]
[ 1 ]
[]
[]
[ "highlighting", "menu", "python", "windows_7", "wxpython" ]
stackoverflow_0005257158_highlighting_menu_python_windows_7_wxpython.txt
Q: how to log model inserts,updates and deletes in django how to log model inserts,updates and deletes? I am not using django admin,in my app there are multiple tables i just want to records only which model or table name, field name,previous value,who edited,and what time to log table? Who edited (my app uses SSO,...
how to log model inserts,updates and deletes in django
how to log model inserts,updates and deletes? I am not using django admin,in my app there are multiple tables i just want to records only which model or table name, field name,previous value,who edited,and what time to log table? Who edited (my app uses SSO,it should pick up remote user automatically) can you please...
[ "You can try this:\nfrom django.db.models.signals import post_save\n\ndef logging_function(sender, **kwargs):\n # do your logging\n\npost_save.connect(logging_function)\n\n", "Python has a logger http://docs.python.org/library/logging.html What's wrong with that?\nYou can, also, add an event table to your Dja...
[ 1, 0 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0005258887_django_django_models_python.txt
Q: Check for valid utf8 string in Python I'm reading filenames from file system and I want to send them as JSON encoded array. The problem is that files on file system can be stored in invalid encoding, and I need to handle this situation to omit invalid filenames before passing it to json.dump, otherwise it will fai...
Check for valid utf8 string in Python
I'm reading filenames from file system and I want to send them as JSON encoded array. The problem is that files on file system can be stored in invalid encoding, and I need to handle this situation to omit invalid filenames before passing it to json.dump, otherwise it will fail. Is there a way to check that my string (...
[ "How about trying the following?\nvalid_utf8 = True\ntry:\n filename.decode('utf-8')\nexcept UnicodeDecodeError:\n valid_utf8 = False\n\n... based on an answer to a similar question here: How to write a check in python to see if file is valid UTF-8?\n" ]
[ 19 ]
[]
[]
[ "invalid_characters", "json", "python", "utf_8" ]
stackoverflow_0005259135_invalid_characters_json_python_utf_8.txt
Q: remove special characters from string i have a string "Mikael Håfström" which contains some special characters how do i remove this using python? A: You can use the unicodedata module to normalize unicode strings and encode them in their ASCII form like so: >>> import unicodedata >>> source = u'Mikael Håfström' ...
remove special characters from string
i have a string "Mikael Håfström" which contains some special characters how do i remove this using python?
[ "You can use the unicodedata module to normalize unicode strings and encode them in their ASCII form like so:\n>>> import unicodedata\n>>> source = u'Mikael Håfström'\n>>> unicodedata.normalize('NFKD', source).encode('ascii', 'ignore')\n'Mikael Hafstrom'\n\nOne notable exception is that the letters 'đ' and 'Đ' are ...
[ 13, 5, 1 ]
[]
[]
[ "python" ]
stackoverflow_0005258623_python.txt
Q: How to count the number of currently connected Protocols in Python twisted framework I was trying to count the number of active protocols in twisted but i got an error: exceptions.AttributeError: Factory instance has no attribute 'numProtocols' Below is the code: class EchoPro(Protocol): def connectionMade(se...
How to count the number of currently connected Protocols in Python twisted framework
I was trying to count the number of active protocols in twisted but i got an error: exceptions.AttributeError: Factory instance has no attribute 'numProtocols' Below is the code: class EchoPro(Protocol): def connectionMade(self): self.factory.numProtocols = self.factory.numProtocols+1 if self.facto...
[ "That's because self.factory does not contain the numProtocols attribute. \nTo customise the protocol's factory you create a Factory for your protocol by subclassing twisted.internet.protocol.Factory.\nExample:\nfrom twisted.internet.protocol import Protocol, Factory\nfrom twisted.internet import reactor\n\nclass E...
[ 5 ]
[]
[]
[ "python", "twisted", "twisted.internet" ]
stackoverflow_0005257822_python_twisted_twisted.internet.txt
Q: How do I add a link to an external marketing video to the site home page? I'm not much of a programmer and I need some assistance in adding an external link to the home page of my site. It's a JavaScript hosted on a provider's site that will integrate a marketing video on my site (Plone 3.2). I looked at the por...
How do I add a link to an external marketing video to the site home page?
I'm not much of a programmer and I need some assistance in adding an external link to the home page of my site. It's a JavaScript hosted on a provider's site that will integrate a marketing video on my site (Plone 3.2). I looked at the portal_javascripts registry, but I'm not clear on how to ensure the link is only r...
[ "In JavaScript registry fill the condition field with this expression:\npython:(folder.meta_type=='Plone Site') and (context.getId()==folder.getDefaultPage())\n\nWhere:\n\ncontext is the current object.\nfolder is the container for current object. In case of objects in Plone site root, it is the site itself.\nfolde...
[ 1, 0 ]
[]
[]
[ "javascript", "plone", "python" ]
stackoverflow_0005253772_javascript_plone_python.txt
Q: 'Cannot alter upload handlers' while trying to upload file I'm trying to upload file using uploadhandler in Django. But it's returning the error: You cannot alter upload handlers after the upload has been processed Code: def upload_form(request): if request.method == 'POST': outPath = '/opt/workspace...
'Cannot alter upload handlers' while trying to upload file
I'm trying to upload file using uploadhandler in Django. But it's returning the error: You cannot alter upload handlers after the upload has been processed Code: def upload_form(request): if request.method == 'POST': outPath = '/opt/workspace/jup2/juppro/uploads/23232' if not os.path.exists(outPat...
[ "You have to define the uploadhandler before you start uploading. The moment you can access request.POST the file has allready been uploaded to the memory or a temporary file. This makes defining an uploadhandler pointless, as the upload has allready been finished. \nDjango docs are quite clear about when to defin...
[ 1 ]
[]
[]
[ "ajax", "django", "python" ]
stackoverflow_0005258850_ajax_django_python.txt
Q: Serizalize an array in Python I ´m trying to serialize an array in python to insert it on a database of MySQL... I try with pickle.dump() method but it returns byte... what can I use?? thanks!! (I ´m working in python 3) A: You can try to use json to turn it into a string, like this: import json v = [1, 2, 4] s...
Serizalize an array in Python
I ´m trying to serialize an array in python to insert it on a database of MySQL... I try with pickle.dump() method but it returns byte... what can I use?? thanks!! (I ´m working in python 3)
[ "You can try to use json to turn it into a string, like this:\nimport json\n\nv = [1, 2, 4]\ns = json.dumps(v)\n\n", "Pickle is a binary serialization, that's why you get a byte string.\nPros:\n\nmore compact\ncan express most of Python's objects.\n\nCon's:\n\nbytes can be harder to handle\nPython only.\n\nJSON i...
[ 5, 1, 0, 0 ]
[]
[]
[ "mysql", "python" ]
stackoverflow_0005259329_mysql_python.txt
Q: Python write unicode characters wrong I'm having some problem with getting Python to handle my unicode text correctly. I've boiled it down to the following: >>>print 'Høst' Høst >>>print u'Høst' HÃ,st >>>u = u'Høst' >>>u u'H\xf8st' sys.stdout.encoding says that it's using UTF-8, which is most likely why the first...
Python write unicode characters wrong
I'm having some problem with getting Python to handle my unicode text correctly. I've boiled it down to the following: >>>print 'Høst' Høst >>>print u'Høst' HÃ,st >>>u = u'Høst' >>>u u'H\xf8st' sys.stdout.encoding says that it's using UTF-8, which is most likely why the first, non-unicode, print works. If I just need ...
[ "ø is \\xc3\\xb8 in ISO-8859-1. \\xc3\\xb8 is also UTF-8 for the Unicode 00F8 character (ø). Maybe your console really accepts ISO-8859-1 rather than UTF-8 as input, meaning that sys.stdout.encoding is wrong.\n", "Are you using ipython? Its unicode support is broken and I'm able to reproduce your output with ipy...
[ 3, 0 ]
[]
[]
[ "python", "unicode" ]
stackoverflow_0005259362_python_unicode.txt
Q: using python and urllib2 how to authenticate to a webpage before reading the source code ok, so I have a code that is designed to read from a webpage and parse the source to find the amount of money in my google adsense accout. the read from part goes something like this: import urllib2 import re s = urllib2.urlo...
using python and urllib2 how to authenticate to a webpage before reading the source code
ok, so I have a code that is designed to read from a webpage and parse the source to find the amount of money in my google adsense accout. the read from part goes something like this: import urllib2 import re s = urllib2.urlopenopen('https://www.google.com/adsense/report/overview?timePeriod=alltime').read() results = ...
[ "You can try to use mechanize, a third-party package that acts like a browser.\nThe idea would be to get mechanize to fill the authentication forms you would normally fill manually while at your browser.\n", "I am afraid, you are going to have much luck trying to get easy solution for what you are trying to do.\n...
[ 2, 1, 0, 0 ]
[]
[]
[ "authentication", "python" ]
stackoverflow_0004515796_authentication_python.txt
Q: Python to Java translation of short code I found this really simple code written in Python: opener = urllib2.build_opener() data=opener.open(request) data.read(1024) length=ord(data.read(1))*8 print data.read(length) and I want to rewrite it in Java. Can you help me? I can't seem to find what the data.read() meth...
Python to Java translation of short code
I found this really simple code written in Python: opener = urllib2.build_opener() data=opener.open(request) data.read(1024) length=ord(data.read(1))*8 print data.read(length) and I want to rewrite it in Java. Can you help me? I can't seem to find what the data.read() methods are for, Python docs really confuse me. Ne...
[ "It opens a URL for reading, reads 1 kibibyte of data and discards it, reads one byte of data, turns that byte into a number, multiplies it by 8, and reads that many more bytes.\n" ]
[ 3 ]
[]
[]
[ "java", "python" ]
stackoverflow_0005259658_java_python.txt
Q: How can I authenticate my mobile application and underlying server using Facebook? The behaviour I want is simple: User starts up the application. User is prompted for their Facebook username and password. On successful login, user is now authenticated for the application and the web server. There is now a user i...
How can I authenticate my mobile application and underlying server using Facebook?
The behaviour I want is simple: User starts up the application. User is prompted for their Facebook username and password. On successful login, user is now authenticated for the application and the web server. There is now a user in the server associated with the Facebook ID. All further HTTP requests will have a cook...
[]
[]
[ "You can try using the OAuth framework\n" ]
[ -1 ]
[ "django", "google_app_engine", "iphone", "python" ]
stackoverflow_0005171905_django_google_app_engine_iphone_python.txt
Q: using eval to programmatically define an SQLQuery q object I'm using SQLObject and want to programmatically build a query using the .q objects (or some other way) -- but do not want to revert to actual SQL. I'm trying to do something like: column = 'name' value = 'todd' Users.select(Users.q.column==value) I've go...
using eval to programmatically define an SQLQuery q object
I'm using SQLObject and want to programmatically build a query using the .q objects (or some other way) -- but do not want to revert to actual SQL. I'm trying to do something like: column = 'name' value = 'todd' Users.select(Users.q.column==value) I've got this: Users.select(eval('Users.q.%s' % column)==value) But it...
[ "Users.select(getattr(Users.q, column)==value)\n\n" ]
[ 2 ]
[]
[]
[ "eval", "python", "sqlobject" ]
stackoverflow_0005259834_eval_python_sqlobject.txt
Q: How convert email subject from "?UTF-8?...?=" to readable string? Possible Duplicate: string encode / decode Now the subject looks like: =?UTF-8?B?0J/RgNC+0LLQtdGA0LrQsA==?= A: Maybe you can use decode_header function: http://docs.python.org/library/email.header.html#email.header.decode_header A: The part be...
How convert email subject from "?UTF-8?...?=" to readable string?
Possible Duplicate: string encode / decode Now the subject looks like: =?UTF-8?B?0J/RgNC+0LLQtdGA0LrQsA==?=
[ "Maybe you can use decode_header function: http://docs.python.org/library/email.header.html#email.header.decode_header\n", "The part between =?UTF-8?B? and ?= is a base64-encoded string. Extract that part, and then decode it.\nimport base64\n\n#My buggy SSH account needs this to write unicode output, you hopefull...
[ 11, 11 ]
[]
[]
[ "email", "python", "utf_8" ]
stackoverflow_0005259601_email_python_utf_8.txt
Q: Converting pyparsing.ParseResults back to html string I'm brand new to pyparsing. How can I convert instance of class pyparsing.ParseResults back to a html string. ex. >>> type(gcdata) <type 'unicode'> >>> pat {<"div"> SkipTo:(</"div">) </"div">} >>> type(pat) <class 'pyparsing.And'> >>> >>> l = pat.searchStrin...
Converting pyparsing.ParseResults back to html string
I'm brand new to pyparsing. How can I convert instance of class pyparsing.ParseResults back to a html string. ex. >>> type(gcdata) <type 'unicode'> >>> pat {<"div"> SkipTo:(</"div">) </"div">} >>> type(pat) <class 'pyparsing.And'> >>> >>> l = pat.searchString( gcdata ) >>> l[0] (['div', ([u'class', u'shoveler'], {}...
[ "You would be much better off using an HTML parser which returns a DOM, like lxml.html but I suspect you're doing this more to learn Pyparsing. Since you didn't post a snippet of source code I've taken a few guesses and made an example using pyparsing.makeHTMLTags, listed below. \nimport cgi\nfrom pyparsing import ...
[ 1, 1 ]
[]
[]
[ "html_parsing", "parsing", "pyparsing", "python", "xml_parsing" ]
stackoverflow_0005243546_html_parsing_parsing_pyparsing_python_xml_parsing.txt
Q: Reading a Serial Port with Python. How does the buffers work? I am just wondering how the buffers work on a com port.. The code below is a snip of how I am reading a com port. I am wondering if by doing serial_connection.close() and serial_connection.open() I would be losing any data, or would it remain in the buf...
Reading a Serial Port with Python. How does the buffers work?
I am just wondering how the buffers work on a com port.. The code below is a snip of how I am reading a com port. I am wondering if by doing serial_connection.close() and serial_connection.open() I would be losing any data, or would it remain in the buffer? You might ask why I am closing and opening the comport.. The r...
[ "PySerial has a separate thread that sits there listening for data to make sure that nothing gets lost. However, the OS itself does not buffer data. There is a slim chance that you could lose some data for the brief period of time between when you close the port and open it again.\n" ]
[ 4 ]
[]
[]
[ "buffer", "python", "serial_port" ]
stackoverflow_0005260046_buffer_python_serial_port.txt
Q: mingw + python eagerly translating path I am using: Windows XP Python 2.6.2 (standard install from python.org) git version 1.6.5.1-preview20091022 (installed from http://code.google.com/p/msysgit/) I have an environment variable looking like an absolute path (/path/to/dir) but I'm using it to construct a git URL...
mingw + python eagerly translating path
I am using: Windows XP Python 2.6.2 (standard install from python.org) git version 1.6.5.1-preview20091022 (installed from http://code.google.com/p/msysgit/) I have an environment variable looking like an absolute path (/path/to/dir) but I'm using it to construct a git URL. At some point, it's getting translated to C...
[ "The problem definitely sounds like it's caused by MSYS. When an MSYS process execs a non-MSYS process (e.g. your msysgit bash shell calling native Windows Python), the arguments are checked for anything that looks like an absolute POSIX path (e.g. things that start with a single '/') and these are translated to t...
[ 2, 1, 1 ]
[]
[]
[ "bash", "mingw", "msysgit", "python" ]
stackoverflow_0001773763_bash_mingw_msysgit_python.txt
Q: How do I create an EC2 image from a running instance using boto? I'm trying to create a simple python backup script for my EC2 instances. This script's purpose is to create daily/weekly snapshots of the current machine (see this question on ServerFault). I'm using the boto python package for EC2 API, and would lik...
How do I create an EC2 image from a running instance using boto?
I'm trying to create a simple python backup script for my EC2 instances. This script's purpose is to create daily/weekly snapshots of the current machine (see this question on ServerFault). I'm using the boto python package for EC2 API, and would like to create an EBS AMI from a given instance (like ElasticFox's "Creat...
[ "You want the \"create_image\" method of the EC2Connection object. See the docs here. You can also ask questions on the boto-users Google Group.\n" ]
[ 9 ]
[]
[]
[ "amazon_ec2", "boto", "python" ]
stackoverflow_0005256665_amazon_ec2_boto_python.txt
Q: delegation vs inheritance python I have just come across delegation in python and cannot wrap my head around the difference between delegation and inheritance. Why would one want to use delegation rather than inheritance?? A: Delegation is a powerful mechanism where by you delegate a task away from one class to ...
delegation vs inheritance python
I have just come across delegation in python and cannot wrap my head around the difference between delegation and inheritance. Why would one want to use delegation rather than inheritance??
[ "Delegation is a powerful mechanism where by you delegate a task away from one class to another. This has the main advantage that changes in one of your classes will not cascade down or into any others.\nFurthermore, if you are not getting this principle your classes are probably doing more than they should. By thi...
[ 4, 1 ]
[]
[]
[ "delegation", "python" ]
stackoverflow_0005260675_delegation_python.txt
Q: A list of everything I need for running my app on a web server What I want to know are actually 2 things. Part 1: I have a developed source code for an application in python that uses Django framework. What I want is to be able to run the code on a developer machine and see the result. What do I need for it? (my ...
A list of everything I need for running my app on a web server
What I want to know are actually 2 things. Part 1: I have a developed source code for an application in python that uses Django framework. What I want is to be able to run the code on a developer machine and see the result. What do I need for it? (my guesses): Python development enironment (Eclipse/PyDev/Aptana Studio...
[ "To answer your questions:\n\nWhat you need: A list of requirements and instructions to get started with Django is available here: http://djangobook.com/en/2.0/chapter02/. \nDatabase: that chapter also includes a section on configuring access to your database, with a specific section on postgreSQL.\nDev server: To ...
[ 5, 1 ]
[]
[]
[ "django", "python", "web_application_project" ]
stackoverflow_0005260801_django_python_web_application_project.txt
Q: python class definition some time i see some classes defined as subclass of object class, as class my_class(object): pass how is if different from the simple definition as class my_class(): pass A: This syntax declares a new-style class. A: The first one is a new style class and the second is the ol...
python class definition
some time i see some classes defined as subclass of object class, as class my_class(object): pass how is if different from the simple definition as class my_class(): pass
[ "This syntax declares a new-style class.\n", "The first one is a new style class and the second is the old style class.\nEDIT\nIn [1]: class A:\n ...: pass\n ...: \n\nIn [2]: class B(object):\n ...: pass\n ...: \n\nIn [3]: a = A()\n\nIn [4]: b = B()\n\nIn [5]: dir(a)\nOut[5]: ['__doc__', '__module...
[ 8, 4, 3, 3, 2 ]
[]
[]
[ "python" ]
stackoverflow_0005261018_python.txt
Q: value error for seive of eratosthenes problem in python Here's my version of the Sieve of Eratosthenes for finding prime numbers up to a limit n. I feel like it should work but I get an error and I don't really understand why: mylist.remove(i) ValueError: list.remove(x): x not in list Why does it mention x? ...
value error for seive of eratosthenes problem in python
Here's my version of the Sieve of Eratosthenes for finding prime numbers up to a limit n. I feel like it should work but I get an error and I don't really understand why: mylist.remove(i) ValueError: list.remove(x): x not in list Why does it mention x? Here's the code: def number_list(n): mylist = [] for...
[ "You are modifying mylist while iterating over it. This will yield strange results. During the first run of your loop, i will be assigned the first item of your list, i.e. 2. Then, the statement\np = mylist.pop(0)\n\nremoves this very item from the beginning of the list, and p is also set to 2. Next, your check...
[ 2, 1, 0, 0 ]
[]
[]
[ "primes", "python", "sieve_of_eratosthenes" ]
stackoverflow_0005260584_primes_python_sieve_of_eratosthenes.txt
Q: How to manage cookies - with JavaScript or with HTTP Set-Cookie? I am creating a web application within GAE environment. It heavily uses AJAX/JSON to send/receive data and all about that. I don't worry much about browsers with JS disabled and obsolete browsers as it's my personal project and I am trying to make it...
How to manage cookies - with JavaScript or with HTTP Set-Cookie?
I am creating a web application within GAE environment. It heavily uses AJAX/JSON to send/receive data and all about that. I don't worry much about browsers with JS disabled and obsolete browsers as it's my personal project and I am trying to make it simple and not bloated in code. So, I use JavaScript heavily in the p...
[ "You should set your cookies wherever it's most convenient.\nThat probably means that some cookies will come from the server and some from the client.\nNote, however, that, for security reasons, high-risk cookies (such as a login token) should be HTTP-Only so that they cannot be accessed from Javascript.\n(It goes ...
[ 3, 1, 0 ]
[]
[]
[ "cookies", "javascript", "python" ]
stackoverflow_0005260657_cookies_javascript_python.txt
Q: How to know key in hash by value? I have hash: test = { 'a': ['localhost'], 'b': ['bb','aa'], 'c': ['cc'] } For example I want to know key for bb ? (b). A: In general you can construct a reverse dictionary like this: test_reversed = dict((v, k) for k, values in test.iteritems() for v in values) A: ...
How to know key in hash by value?
I have hash: test = { 'a': ['localhost'], 'b': ['bb','aa'], 'c': ['cc'] } For example I want to know key for bb ? (b).
[ "In general you can construct a reverse dictionary like this:\ntest_reversed = dict((v, k) for k, values in test.iteritems() for v in values)\n\n", "There's not an easy way to do this other than iterating over the keys and values. If you need to do this a lot, it would be worth constructing the reversed mapping ...
[ 4, 3, 2 ]
[]
[]
[ "python" ]
stackoverflow_0005261381_python.txt
Q: Remove/Delete Page from multipage TIFF file I need to delete a page from a multipaged TIFF file. I am currently working in .NET but can move to another language if some one knows how to do it in that language. The page would be either the second to last, or the last page in the file. And I need to do it with out d...
Remove/Delete Page from multipage TIFF file
I need to delete a page from a multipaged TIFF file. I am currently working in .NET but can move to another language if some one knows how to do it in that language. The page would be either the second to last, or the last page in the file. And I need to do it with out decompressing the previous pages in the file, so n...
[ "Ok, got a solution working in python.\nimport mmap\nfrom struct import *\n\ndef main():\n filename = raw_input(\"Input file name: \")\n f = open(filename, \"r+b\")\n offList, compList = getOffsets(f)\n for i in range(len(offList)):\n print \"offset: \", offList[i], \"\\t Compression: \", compLis...
[ 3 ]
[]
[]
[ ".net", "libtiff", "libtiff.net", "python", "tiff" ]
stackoverflow_0005221576_.net_libtiff_libtiff.net_python_tiff.txt
Q: SOAP 1.2 python client I am looking for a python SOAP 1.2 client but it seems that it does not exist . All of the existing clients are either not maintainted or only compatible with SOAP 1.1: suds SOAPpy ZSI A: Even though this question has an accepted answer, there's a few notes I'd like regarding suds. I'm cu...
SOAP 1.2 python client
I am looking for a python SOAP 1.2 client but it seems that it does not exist . All of the existing clients are either not maintainted or only compatible with SOAP 1.1: suds SOAPpy ZSI
[ "Even though this question has an accepted answer, there's a few notes I'd like regarding suds.\nI'm currently writing some code for interfacing with .tel community hosting for work and I needed a Python SOAP library, and suds was pretty much ideal except for its lack of support for SOAP 1.2.\nI managed to hack aro...
[ 12, 9, 5, 1 ]
[]
[]
[ "python", "soap" ]
stackoverflow_0002370573_python_soap.txt
Q: How to translate javascript-files in Pylons We're making an application by using Pylons and JQuery. We have used standard way of making translations, but it doesn't quite work with javascript. The awkwardness of js-translation methods is that we should make duplicate processes for selecting languages etc. Is ther...
How to translate javascript-files in Pylons
We're making an application by using Pylons and JQuery. We have used standard way of making translations, but it doesn't quite work with javascript. The awkwardness of js-translation methods is that we should make duplicate processes for selecting languages etc. Is there a proper support in Pylons for javascript-trans...
[ "An alternative method is to use the pylons gettext to generate your own javascript string ids like this:\nhtml template:\n<script type=\"text/javascript\">\n var i18n_strings = {\n hello_world = '${ugettext('Hello World!')}',\n goodbye_world = '${ugettext('Goodbye World!')}',\n enter_name = '${uge...
[ 1, 0 ]
[]
[]
[ "javascript", "jquery", "pylons", "python", "translation" ]
stackoverflow_0003288726_javascript_jquery_pylons_python_translation.txt
Q: when to use try/except blocks in GAE I've recently started developing my first web app with GAE and Python, and it is a lot of fun. One problem I've been having is exceptions being raised when I don't expect them (since I'm new to web apps). I want to: Prevent users from ever seeing exceptions Properly handle ex...
when to use try/except blocks in GAE
I've recently started developing my first web app with GAE and Python, and it is a lot of fun. One problem I've been having is exceptions being raised when I don't expect them (since I'm new to web apps). I want to: Prevent users from ever seeing exceptions Properly handle exceptions so they don't break my app Shoul...
[ "You can create a method called handle_exception on your request handlers to deal with un-expected situations.\nThe webapp framework will call this automatically when it hits an issue\nclass YourHandler(webapp.RequestHandler):\n\n def handle_exception(self, exception, mode):\n # run the default exception ...
[ 10, 1 ]
[]
[]
[ "exception_handling", "google_app_engine", "python" ]
stackoverflow_0005262146_exception_handling_google_app_engine_python.txt