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:
Social network architecture, C++ Clients Neo4j database what between?
I'm currently working on the implementation of a social network.
The architecture is:
- Distributed C++/Qt clients
- Neo4j server database
I could directly query the database since it has a REST interface from my Qt apps.
I'm not quite comforta... | Social network architecture, C++ Clients Neo4j database what between? | I'm currently working on the implementation of a social network.
The architecture is:
- Distributed C++/Qt clients
- Neo4j server database
I could directly query the database since it has a REST interface from my Qt apps.
I'm not quite comfortable with this approach because it is not secured, and no optimizations (cac... | [
"REST will be fast enough. Use it until you can measure and have some real data that tells you it's a problem.\nBut I wouldn't use the REST API to deal directly with the database.\nI'd add layers between the two that manages security, validation and binding, use cases and error handling, logging, transactions, etc... | [
2
] | [] | [] | [
"c++",
"java",
"neo4j",
"python",
"social_networking"
] | stackoverflow_0005604906_c++_java_neo4j_python_social_networking.txt |
Q:
wrapping ssh tunnel in ssl with openssl (python) almost finished
Some of you might remember a question very similar to this, as I seeked your help writin the original util in C (using libssh2 and openssl).
I'm now trying to port it to python and got stuck at an unexpected place. Ported about 80% of the core and fu... | wrapping ssh tunnel in ssl with openssl (python) almost finished | Some of you might remember a question very similar to this, as I seeked your help writin the original util in C (using libssh2 and openssl).
I'm now trying to port it to python and got stuck at an unexpected place. Ported about 80% of the core and functionality in 30 minutes, and then spend 10hours+ and still haven't f... | [
"Okay, so I think I manged to sort it out.\nsarnold, you'll like this updated version:\n def ftp_read(self, trim=False):\n if self.proxy is None:\n temp = self.s.read(READBUFF)\n else:\n temp = \"\"\n while True:\n try:\n temp += self.sock.recv(READBUFF)\n break\n ... | [
0
] | [] | [] | [
"openssl",
"pyopenssl",
"python",
"ssh"
] | stackoverflow_0005603782_openssl_pyopenssl_python_ssh.txt |
Q:
Backup File Script
I am writing a script to backup files from one dir(Master) to another dir(Clone).
And the script will monitor the two directories.
If a file inside clone is missing then the script will copy the missing file from Master to
Clone.Now I have a problem creating the missing folder.
I have read the ... | Backup File Script | I am writing a script to backup files from one dir(Master) to another dir(Clone).
And the script will monitor the two directories.
If a file inside clone is missing then the script will copy the missing file from Master to
Clone.Now I have a problem creating the missing folder.
I have read the documentation and found ... | [
"Sorry, but the documentation doesn't say that. Here's a reproduction of the full documentation for the function:\n\nshutil.copyfile(src, dst) \nCopy the\n contents (no metadata) of the file\n named src to a file named dst. dst\n must be the complete target file name;\n look at copy() for a copy that accepts\n ... | [
3
] | [] | [] | [
"backup",
"python"
] | stackoverflow_0005604956_backup_python.txt |
Q:
How do I set a world background texture in Blender 2.49 using Python?
I'm trying to set a background World Texture in Blender 2.49.
I've made a texture:
import Blender
from Blender import *
import bpy
world = World.GetCurrent()
worldTex = Texture.New('worldTex')
worldTex.setType('Image')
worldIm = Image.Loa... | How do I set a world background texture in Blender 2.49 using Python? | I'm trying to set a background World Texture in Blender 2.49.
I've made a texture:
import Blender
from Blender import *
import bpy
world = World.GetCurrent()
worldTex = Texture.New('worldTex')
worldTex.setType('Image')
worldIm = Image.Load('//blender_scene/tex/bg 001.jpg')
worldIm.source = Image.Sources.SEQUENC... | [
"Blender 2.5x has a much better Python API. I really recommend watching this video from PyCon talk by Christopher Webber about it.\nSetting texture in 2.5x API :\nimport bpy\n# create new clouds texture\nbpy.ops.texture.new()\nt = bpy.data.textures[-1]\n# set World texture\nw = bpy.data.world['World']\nslot = w.tex... | [
1
] | [] | [] | [
"3d",
"blender",
"bpython",
"python",
"textures"
] | stackoverflow_0003284382_3d_blender_bpython_python_textures.txt |
Q:
Listing indices using sqlalchemy
Is it possible to list all indices in a db using sqlalchemy?
A:
yes.
from sqlalchemy import create_engine
from sqlalchemy.engine import reflection
engine = create_engine('...')
insp = reflection.Inspector.from_engine(engine)
for name in insp.get_table_names():
for index in in... | Listing indices using sqlalchemy | Is it possible to list all indices in a db using sqlalchemy?
| [
"yes.\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.engine import reflection\nengine = create_engine('...')\ninsp = reflection.Inspector.from_engine(engine)\nfor name in insp.get_table_names():\n for index in insp.get_indexes(name):\n print index\n\n"
] | [
11
] | [] | [] | [
"indexing",
"python",
"sql",
"sqlalchemy"
] | stackoverflow_0005605019_indexing_python_sql_sqlalchemy.txt |
Q:
GAE datastore - best practice when there are more writes than reads
I'm trying to do some practicing with the GAE datastore to get a feeling about the queries and billings mechanisms.
I've read the Oreilly book about the GAE, and watched the Google videos about the datastore. My problem is that the best practice ... | GAE datastore - best practice when there are more writes than reads | I'm trying to do some practicing with the GAE datastore to get a feeling about the queries and billings mechanisms.
I've read the Oreilly book about the GAE, and watched the Google videos about the datastore. My problem is that the best practice methods are usually concerning more reads than writes to the datastore.
I... | [
"Answer 1\nStore Links as separate entities. Also store an entity per user with a ListProperty having keys to the most recent 20 links. As user chooses more links you just update the ListProperty of keys. ListProperty maintains order so you dont need to worry about the chronological orders of links chosen as lon... | [
1,
1
] | [] | [] | [
"google_app_engine",
"google_cloud_datastore",
"python"
] | stackoverflow_0005603591_google_app_engine_google_cloud_datastore_python.txt |
Q:
What do these python `import` statements mean?
At the beginning of a python script, there are some import statements. Could someone explain what they imply?
import getopt
import os
import re
import string
import sys
import getpass
import urllib
import subprocess
A:
The import statements are simila... | What do these python `import` statements mean? | At the beginning of a python script, there are some import statements. Could someone explain what they imply?
import getopt
import os
import re
import string
import sys
import getpass
import urllib
import subprocess
| [
"The import statements are similar (but different) to the #include statements in C: they allow you to use functions defined elsewhere (either in a standard module, or your own).\nFor example, module sys allows you to do this:\nimport sys\n# ... somewhere down in the file\nsys.exit(0)\n\nWhich would terminate your p... | [
15,
1
] | [] | [] | [
"python"
] | stackoverflow_0005605299_python.txt |
Q:
What is the difference between the various ZODB blobstorage layouts?
The ZODB blobstorage directory contains a .layout file with the string 'lawn', 'bushy'.
What is the difference between the various blob storage directory formats?
A:
It is explained here: https://github.com/zopefoundation/ZODB/blob/master/src/Z... | What is the difference between the various ZODB blobstorage layouts? | The ZODB blobstorage directory contains a .layout file with the string 'lawn', 'bushy'.
What is the difference between the various blob storage directory formats?
| [
"It is explained here: https://github.com/zopefoundation/ZODB/blob/master/src/ZODB/tests/blob_layout.txt\nFTA:\n\n======================\nBlob directory layouts\nThe internal structure of the blob directories is governed by so called\nlayouts. The current default layout is called bushy.\nThe original blob implement... | [
7,
2
] | [] | [] | [
"python",
"zodb",
"zope"
] | stackoverflow_0004866646_python_zodb_zope.txt |
Q:
How do I run tests in a product being developed in Plone 4?
I am developing a product for Plone 4, inside the zeocluster/src/... directory of an installation, and I have an automated test. Unfortunately, when I run 'bin/client1 shell' and then (path to Plone's Python)/bin/python setup.py test, it fails. The error ... | How do I run tests in a product being developed in Plone 4? | I am developing a product for Plone 4, inside the zeocluster/src/... directory of an installation, and I have an automated test. Unfortunately, when I run 'bin/client1 shell' and then (path to Plone's Python)/bin/python setup.py test, it fails. The error is
File "buildout-cache/eggs/Products.PloneTestCase-0.9.12-py2.6.... | [
"Best is to edit your buildout.cfg and add a part that creates a 'bin/test' script. Something like this:\n[test]\nrecipe = zc.recipe.testrunner\n# Note that only tests for packages that are explicitly named (instead\n# of 'implicitly' added to the instance as dependency) can be found.\neggs =\n# Use the name of the... | [
3,
3,
2
] | [] | [] | [
"nose",
"plone",
"python"
] | stackoverflow_0005599844_nose_plone_python.txt |
Q:
Plone 4 Table View Work Around
I'm writing a custom view to get around the bug that displays the wrong start and end times for events in table view in Plone 4. However, when I call my view I get the following error:
Traceback (innermost last):
Module ZPublisher.Publish, line 116, in publish
Module ZPublis... | Plone 4 Table View Work Around | I'm writing a custom view to get around the bug that displays the wrong start and end times for events in table view in Plone 4. However, when I call my view I get the following error:
Traceback (innermost last):
Module ZPublisher.Publish, line 116, in publish
Module ZPublisher.BaseRequest, line 498, in traver... | [
"A much better workaround would be to customize the formatCatalogMetadata.py skin script from the ATContentTypes skin layer.\nReplace the line reading:\nif same_type(value, '') and value[4:-1:3] == '-- ::':\n\nwith:\nif same_type(value, '') and (value[4:-1:3] == '-- ::' or value[4:19:3] == '--T::'):\n\nand the even... | [
1,
1
] | [
"But it's python!\nThe definition for a class method is:\ndef __init__(context, request):\n\nself is understood by default (because the method is called as Class.__init__(context,request)) (or, again, shortened to Class()).\n"
] | [
-1
] | [
"plone",
"python"
] | stackoverflow_0005600161_plone_python.txt |
Q:
PyLab: Plotting axes to log scale, but labelling specific points on the axes
Basically, I'm doing scalability analysis, so I'm working with numbers like 2,4,8,16,32... etc and the only way graphs look rational is using a log scale.
But instead of the usual 10^1, 10^2, etc labelling, I want to have these datapoints... | PyLab: Plotting axes to log scale, but labelling specific points on the axes | Basically, I'm doing scalability analysis, so I'm working with numbers like 2,4,8,16,32... etc and the only way graphs look rational is using a log scale.
But instead of the usual 10^1, 10^2, etc labelling, I want to have these datapoints (2,4,8...) indicated on the axes
Any ideas?
| [
"There's more than one way to do it, depending on how flexible/fancy you want to be.\nThe simplest way is just to do something like this:\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib as mpl\n\nx = np.exp2(np.arange(10))\n\nplt.semilogy(x)\nplt.yticks(x, x)\n\n# Turn y-axis minor ticks off... | [
8
] | [] | [] | [
"graph",
"matplotlib",
"python"
] | stackoverflow_0005605503_graph_matplotlib_python.txt |
Q:
web2py PDF - Where do I put this code?
http://code.google.com/p/pyfpdf/wiki/Web2Py#Sample_Table_Listing
This would be my first time using web2py, I'm using it because the example code is exactly what I need for part of a project.
My problem is I have no idea where to put this code. I'm using Google App Engine.
A:... | web2py PDF - Where do I put this code? | http://code.google.com/p/pyfpdf/wiki/Web2Py#Sample_Table_Listing
This would be my first time using web2py, I'm using it because the example code is exactly what I need for part of a project.
My problem is I have no idea where to put this code. I'm using Google App Engine.
| [
"To understand where to put that code, you'll need at least a basic understanding of how web2py applications are structured. I recommend at least looking at the Overview chapter of the book.\nThe function definitions shown (i.e., report(), listing(), and invoice()) would go in a controller file in your applications... | [
3
] | [] | [] | [
"google_app_engine",
"python",
"web2py"
] | stackoverflow_0005604803_google_app_engine_python_web2py.txt |
Q:
Sorting list of lists with mixed numerical values
Scenario: List containing 'rows' of list records with a variety of values
Problem: List.sort doesn't take the numeric values into consideration so values end up all over the place
i.e 9 is appearing in the list after 80
I've tried using
list.sort(key=operator.item... | Sorting list of lists with mixed numerical values | Scenario: List containing 'rows' of list records with a variety of values
Problem: List.sort doesn't take the numeric values into consideration so values end up all over the place
i.e 9 is appearing in the list after 80
I've tried using
list.sort(key=operator.itemgetter[index])
and doing a
list.sort(lambda x,y:int(x... | [
"Use the converted number as the key.\nL.sort(key=lambda x: int(x[index]))\n\n",
"You're on the right track, but operator.itemgetter is a function, so the syntax is:\nlist.sort(key=operator.itemgetter(index))\n\nOr alternatively, use a lambda:\nlist.sort(key=lambda x: x[index])\n\nThe key parameter is the way to ... | [
3,
2
] | [] | [] | [
"list",
"numbers",
"python",
"sorting"
] | stackoverflow_0005605674_list_numbers_python_sorting.txt |
Q:
Python's NLTK vs. related Java Libraries?
I've used LingPipe, Stanford's NER, RiTa and various sentence similarity libraries for my previous Java projects that focused on text (pre)processing (indexing, xml tagging, topic detection, etc.) of large amounts of English text (around 10,000 documents summing to > 1gb o... | Python's NLTK vs. related Java Libraries? | I've used LingPipe, Stanford's NER, RiTa and various sentence similarity libraries for my previous Java projects that focused on text (pre)processing (indexing, xml tagging, topic detection, etc.) of large amounts of English text (around 10,000 documents summing to > 1gb of text). Maybe I'm a bad Java programmer, but ... | [
"NLTK is good for natural language processing. I've used it for my data-mining project. You can train your own analyzer. The learning curve is not steep.\nNLTK got huge corpus for training of your analyzer. You can also provide your own set of data, for example, a journal which a part-of-speech tagged.\nBecause pyt... | [
12,
7
] | [] | [] | [
"information_retrieval",
"java",
"nltk",
"python",
"wordnet"
] | stackoverflow_0005589593_information_retrieval_java_nltk_python_wordnet.txt |
Q:
Encoding a string to ascii
I have a long string that I want to encode to ascii. I'm doing:
s = s.encode('ascii', 'replace')
but I get:
'ascii' codec can't decode byte 0xc3 in position 2646: ordinal not in range(128)
(I've also tried 'ignore' but it doesn't help.)
What am I doing wrong?
A:
Your string is alread... | Encoding a string to ascii | I have a long string that I want to encode to ascii. I'm doing:
s = s.encode('ascii', 'replace')
but I get:
'ascii' codec can't decode byte 0xc3 in position 2646: ordinal not in range(128)
(I've also tried 'ignore' but it doesn't help.)
What am I doing wrong?
| [
"Your string is already encoded with some encoding. Before encoding it to ascii, you must decode it first.\nPython is implicity trying to decode it (That's why you get a UnicodeDecodeError not UnicodeEncodeError).\nYou can solve the problem by explicity decoding your bytestring (using the appropriate encoding) befo... | [
19,
2
] | [] | [] | [
"ascii",
"encoding",
"python"
] | stackoverflow_0001762564_ascii_encoding_python.txt |
Q:
extract multiple fields from a string
I have a string
"name1:value1, ... name2:value2, ... name3:value3, ...",
i want to extract value1, value2, value3 to var1, var2, var3. Is there simple solution in bash or python? The simpler the better.
A:
>>> s = "name1:value1,name2:value2, name3:value3"
>>> d = dict(e.spl... | extract multiple fields from a string | I have a string
"name1:value1, ... name2:value2, ... name3:value3, ...",
i want to extract value1, value2, value3 to var1, var2, var3. Is there simple solution in bash or python? The simpler the better.
| [
">>> s = \"name1:value1,name2:value2, name3:value3\"\n>>> d = dict(e.split(':') for e in s.split(','))\n>>> for count, values in zip(range(1, len(d)+1), sorted(d.itervalues())):\n... globals()['var{0}'.format(count)] = values\n... \n>>> var1\n'value1'\n>>> var2\n'value2'\n>>> var3\n'value3'\n\nPretty hack-ish, ... | [
3,
3,
2,
1,
0
] | [] | [] | [
"awk",
"bash",
"python",
"sed"
] | stackoverflow_0005604256_awk_bash_python_sed.txt |
Q:
Python- File Parsing
Write a program which reads a text
file called input.txt which contains
an arbitrary number of lines of the
form ", " then records this
information using a dictionary, and
finally outputs to the screen a list
of countries represented in the file
and the number of cities contained... | Python- File Parsing |
Write a program which reads a text
file called input.txt which contains
an arbitrary number of lines of the
form ", " then records this
information using a dictionary, and
finally outputs to the screen a list
of countries represented in the file
and the number of cities contained.
For example, if input.... | [
"I don't understand what you are trying to do, so I can't really explain how to fix it. In particular, why are you execing the lines of the file? And why write exec \"foo\" instead of just foo? I think you should go back to a basic Python tutorial...\nAnyway, what you need to do is:\n\nopen the file using its full ... | [
4,
3,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0005606127_python.txt |
Q:
Why do I not need to free this memory?
I'm writing a Python C extension, and in the examples listed here, there is a snippet of code:
static PyObject * spam_system(PyObject *self, PyObject *args) {
const char *command;
int sts;
if (!PyArg_ParseTuple(args, "s", &command)) return NULL;
sts = system(... | Why do I not need to free this memory? | I'm writing a Python C extension, and in the examples listed here, there is a snippet of code:
static PyObject * spam_system(PyObject *self, PyObject *args) {
const char *command;
int sts;
if (!PyArg_ParseTuple(args, "s", &command)) return NULL;
sts = system(command);
return Py_BuildValue("i", sts)... | [
"The documentation says this about the \"s\" format specifier to PyArg_ParseTuple:\n\ns (string or Unicode) [const char *]\n Convert a Python string or Unicode object to a C pointer to a character string. You must not provide storage for the string itself; a pointer to an existing string is stored into the charact... | [
10
] | [] | [] | [
"c",
"memory_leaks",
"python"
] | stackoverflow_0005606589_c_memory_leaks_python.txt |
Q:
Check if a record exists in App Engine Datastore
From what I've read, this is how I should check for any records...
v = PC_Applications.all().filter('column =', value)
if not v:
return False
But this returns an error!
IndexError: The query returned fewer than 1 results
Any ideas to doing this? I've read... | Check if a record exists in App Engine Datastore | From what I've read, this is how I should check for any records...
v = PC_Applications.all().filter('column =', value)
if not v:
return False
But this returns an error!
IndexError: The query returned fewer than 1 results
Any ideas to doing this? I've read that .count() is a bad option. I'm new to Python and ... | [
"if not v.get():\n\nFrom App Engine, Query Class get()\n\nExecutes the query, then returns the\n first result, or None if the query\n returned no results.\n\n",
"This should work:\nq = db.Query(PC_Applications, keys_only = True)\nif not q.get():\n return false\n\nI think .all().filter('column =', value) is e... | [
7,
3,
0
] | [] | [] | [
"google_app_engine",
"google_cloud_datastore",
"python"
] | stackoverflow_0005601869_google_app_engine_google_cloud_datastore_python.txt |
Q:
python string formatting in javascript
Is there a better way to do this? I'm using the underscore js lib here, which is where the _. comes from. I'm used to this sort of procedure to format strings in python and i'd like something simple for javascript without doing + + + + all the time. This works, but it feel... | python string formatting in javascript | Is there a better way to do this? I'm using the underscore js lib here, which is where the _. comes from. I'm used to this sort of procedure to format strings in python and i'd like something simple for javascript without doing + + + + all the time. This works, but it feels like i reinvented the wheel.
function foo... | [
"try out the sprintf lib, specifically vsprintf.\nvsprintf('The first 4 letters of the english alphabet are: %s, %s, %s and %s', ['a', 'b', 'c', 'd']);\n\n"
] | [
1
] | [] | [] | [
"javascript",
"python",
"underscore.js"
] | stackoverflow_0005606402_javascript_python_underscore.js.txt |
Q:
Points appear on map google python code
I'm using python to develop a map (Google Maps) and add some points in specific location. After searching I found it can be done using pygmaps. So I installed it using pip, then I wrote this code and I need to add points and open a webpage for the map find the points there.
... | Points appear on map google python code | I'm using python to develop a map (Google Maps) and add some points in specific location. After searching I found it can be done using pygmaps. So I installed it using pip, then I wrote this code and I need to add points and open a webpage for the map find the points there.
import pygmaps
import webbrowser
mymap = py... | [
"Changing \nmymap.draw('./mymap.draw.html') \nurl = url = './mymap.draw.html'\n\nto\nmymap.draw('mymap.draw.html') \nurl = 'mymap.draw.html'\n\nworked for me.\nEdit: added screenshot.\n\n"
] | [
3
] | [] | [] | [
"google_maps",
"point",
"pygmaps",
"python",
"webpage"
] | stackoverflow_0005606229_google_maps_point_pygmaps_python_webpage.txt |
Q:
md5 search using exceptions
import httplib
import re
md5 = raw_input('Enter MD5: ')
conn = httplib.HTTPConnection("www.md5.rednoize.com")
conn.request("GET", "?q="+ md5)
try:
response = conn.getresponse()
data = response.read()
result = re.findall('<div id="result" >(.+?)</div', data)
pri... | md5 search using exceptions | import httplib
import re
md5 = raw_input('Enter MD5: ')
conn = httplib.HTTPConnection("www.md5.rednoize.com")
conn.request("GET", "?q="+ md5)
try:
response = conn.getresponse()
data = response.read()
result = re.findall('<div id="result" >(.+?)</div', data)
print result
except:
print "cou... | [
"Since re.findall doesn't raise exceptions, that's probably not how you want to check for results. Instead, you could write something like\nresult = re.findall('<div id=\"result\" >(.+?)</div', data)\nif result:\n print result\nelse:\n print 'Could not find the hash'\n\n",
"If you realy like to have an exc... | [
2,
1
] | [] | [] | [
"exception",
"httplib",
"md5",
"python"
] | stackoverflow_0005607004_exception_httplib_md5_python.txt |
Q:
how do I use py2app?
Ok - here goes. I am trying to learn how to use py2app, so I created a simple python file; just hello_world.py
#! /usr/bin/env python
def main():
print "Hello"
if __name__=="__main__":
main()
I followed a tutorial and did the following:
py2applet --make-setup hello.py
python setup.py py2... | how do I use py2app? | Ok - here goes. I am trying to learn how to use py2app, so I created a simple python file; just hello_world.py
#! /usr/bin/env python
def main():
print "Hello"
if __name__=="__main__":
main()
I followed a tutorial and did the following:
py2applet --make-setup hello.py
python setup.py py2app -A
This created two s... | [
"You have successfully used py2app - it just opens, prints \"hello\" and then closes really quickly!\nIf you want to see something, then make it pause for a bit:\nprint \"Hello\"\nimport time\ntime.sleep(5)\n\ntime.sleep pauses a program for the number of seconds given.\n",
"You really only want to use py2app wit... | [
9,
5,
1
] | [] | [] | [
"macos",
"py2app",
"python"
] | stackoverflow_0005607121_macos_py2app_python.txt |
Q:
IRC Bot TypeError (python)
if data.find('!search') != -1:
nick = data.split('!')[ 0 ].replace(':','')
conn = httplib.HTTPConnection("www.md5.rednoize.com")
conn.request("GET", "?q=" + arg)
response = conn.getresponse()
data = response.read()
result = re.findall('<div id="result" >... | IRC Bot TypeError (python) | if data.find('!search') != -1:
nick = data.split('!')[ 0 ].replace(':','')
conn = httplib.HTTPConnection("www.md5.rednoize.com")
conn.request("GET", "?q=" + arg)
response = conn.getresponse()
data = response.read()
result = re.findall('<div id="result" >(.+?)</div', data)
if resul... | [
"Where does arg come from? Do you know what it's supposed to contain?\narg is apparently a list, not a string. Try replacing arg with str(arg[0]) and see if that works.\n"
] | [
2
] | [] | [] | [
"irc",
"python",
"sockets",
"typeerror"
] | stackoverflow_0005607274_irc_python_sockets_typeerror.txt |
Q:
Upload images from from web-page
I want to implement a feature similar to this http://www.tineye.com/parse?url=yahoo.com - allow user upload images from any web page.
Main problem for me is that it takes too much time for web pages with big number of images.
I'm doing this in Django (using curl or urllib) accordin... | Upload images from from web-page | I want to implement a feature similar to this http://www.tineye.com/parse?url=yahoo.com - allow user upload images from any web page.
Main problem for me is that it takes too much time for web pages with big number of images.
I'm doing this in Django (using curl or urllib) according to the next scheme:
Grab html of th... | [
"You can use the headers attribute of the file like object returned by urllib2.urlopen (I don't know about urllib).\nHere's a test I wrote for it. As you can see, it is rather fast, though I imagine some websites would block too many repeated requests.\n|milo|laurie|¥ cat test.py\nimport urllib2\nuri = \"http://dow... | [
1,
1
] | [] | [] | [
"curl",
"django",
"python",
"urllib"
] | stackoverflow_0005607101_curl_django_python_urllib.txt |
Q:
ipython for python 2.6.1 uninstall needed?
I installed ipython for python 2.6.1 using easy_install. After realizing that I needed the 2.7 version to use matplotlib, I downloaded and installed the resources to use ipython with python 2.7 using sudo. Do I need to uninstall the "old" ipython? If yes, how do I do this... | ipython for python 2.6.1 uninstall needed? | I installed ipython for python 2.6.1 using easy_install. After realizing that I needed the 2.7 version to use matplotlib, I downloaded and installed the resources to use ipython with python 2.7 using sudo. Do I need to uninstall the "old" ipython? If yes, how do I do this?
| [
"No you shouldn't have to, the ipython package data is stored in the site-packages directory for the python version you installed it for, the ipython executable file basically contains\n#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n\"\"\" \n long comment about IPython.Shell that you \n might want to read; omi... | [
2
] | [] | [] | [
"ipython",
"python"
] | stackoverflow_0005607472_ipython_python.txt |
Q:
Python sqlite3 parameterized drop table
I have a problem with dropping sqlite3 table in python. I am using standard sqlite3 module.
self.conn = sqlite3.connect(...)
sql = """ drop table ? """
self.conn.execute( sql, (u'table_name',) )
gives me OperationalError: near "?": syntax error
When I change sql to:
sql ... | Python sqlite3 parameterized drop table | I have a problem with dropping sqlite3 table in python. I am using standard sqlite3 module.
self.conn = sqlite3.connect(...)
sql = """ drop table ? """
self.conn.execute( sql, (u'table_name',) )
gives me OperationalError: near "?": syntax error
When I change sql to:
sql = """ drop table table_name """
it works fin... | [
"You cannot use parameters for table names nor column names.\nAlternatively you could make it a two-step process, e.g.:\na_table_name = \"table_a\"\nsql_stmt = f\"\"\"DROP TABLE {a_table_name}\"\"\"\nself.conn.execute(sql_stmt)\n\nAnd if you're doing that you may want to explicitly specify which tables can be delet... | [
12
] | [] | [] | [
"parameterized_query",
"python",
"sql_drop",
"sqlite"
] | stackoverflow_0005607737_parameterized_query_python_sql_drop_sqlite.txt |
Q:
Installing Python JSON library onto webserver
This question is based on 2 parts I think: (TL;DR at bottom)
1-How do I install libraries or modules for Python onto my webserver? I've already emailed my webhosts to ask if I have permissions to or if they need to, but so far I don't think they know what I'm talking a... | Installing Python JSON library onto webserver | This question is based on 2 parts I think: (TL;DR at bottom)
1-How do I install libraries or modules for Python onto my webserver? I've already emailed my webhosts to ask if I have permissions to or if they need to, but so far I don't think they know what I'm talking about, so while I'm waiting for the next reply I'll ... | [
"To answer the 1st part:\nJust download the src of the library and put it anywhere. Then, add the path to that directory to sys.path list. That's it. When you import the package, the compiler will be able to find it since it will look at all the dirs in the sys.path list.\nLet's say u download the package py-json a... | [
2,
1
] | [] | [] | [
"json",
"python"
] | stackoverflow_0005607818_json_python.txt |
Q:
Defining class relations in django
I am new to Django/Python, so excuse me if my question is straightforwardly obvious!
I am trying to create a User class, and each user will have the option to select (one or more) sports disciplines as his hobbies.
So far I defined all the sports activities in a class called Hobb... | Defining class relations in django | I am new to Django/Python, so excuse me if my question is straightforwardly obvious!
I am trying to create a User class, and each user will have the option to select (one or more) sports disciplines as his hobbies.
So far I defined all the sports activities in a class called Hobbies:
class Hobbies(models.Model):
sp... | [
"Add a many-to-many field to your profile model, which enables you to create a relationship between users and hobbies:\nclass Profile(models.Model):\n user = models.ForeignKey(User, unique=True)\n gender = models.CharField(max_length=1, blank=True)\n hobbies = models.ManyToManyField(Hobbies)\n\nYou can then get ... | [
1,
0,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0005607965_django_python.txt |
Q:
Python: Getting image dimensions from URL
I'm working on a Python app (using the Django framework and running on Google Appengine). I'm trying to obtain the dimensions (width/height) of a remote image, from its url.
Is there any I can do this without having to download the image? I haven't found anything so far...... | Python: Getting image dimensions from URL | I'm working on a Python app (using the Django framework and running on Google Appengine). I'm trying to obtain the dimensions (width/height) of a remote image, from its url.
Is there any I can do this without having to download the image? I haven't found anything so far...
| [
"There is no general way that you can know anything about an image until you retrieve (download) it. However, if the site you're downloading from has some standardized size in the URL (http://example.com/images/64x64/scary_clown.jpg), you might be able to use that -- assuming you trust them to enforce those sizes.... | [
0
] | [] | [] | [
"django",
"image",
"python",
"url"
] | stackoverflow_0005608019_django_image_python_url.txt |
Q:
Debugging pyjamas python code
I am using pyjamas to develop a web page. I write python code which is translated to javascript by pyjamas. This way debugging programming error is caught only when testing the web page. It would be much more efficient if we can run the code first in the Python interpreter before comp... | Debugging pyjamas python code | I am using pyjamas to develop a web page. I write python code which is translated to javascript by pyjamas. This way debugging programming error is caught only when testing the web page. It would be much more efficient if we can run the code first in the Python interpreter before compiling to javascript. This seems wou... | [
"Pylint is probably the first place to start - it can be installed with easy_install then run as \n$ pylint my_python.py\n\nThe verbosity of errors can be easily edited - but any major problems will be highlighted immediately - and you don't need those extra pyjamas-desktop modules installed! Other similar tools (t... | [
4
] | [] | [] | [
"gwt",
"pyjamas",
"python"
] | stackoverflow_0005606029_gwt_pyjamas_python.txt |
Q:
Django Reimport Module when tests.py is Run
I am working on a Django app that performs some class introspection ahead of time on all models.
This seems to work fine if those models are defined in models.py, but if I define them in my tests.py, __init__.py doesn't see those models.
The goal is to have a module leve... | Django Reimport Module when tests.py is Run | I am working on a Django app that performs some class introspection ahead of time on all models.
This seems to work fine if those models are defined in models.py, but if I define them in my tests.py, __init__.py doesn't see those models.
The goal is to have a module level dictionary that is run once when __init__.py is... | [
"Your core task here seems to be running some code for each model exactly once. There's a good existing solution for this: class_prepared signal from django builtins.\nhttp://docs.djangoproject.com/en/1.3/ref/signals/#class-prepared\nAs for doing introspection ahead of time, this might be not desirable in some cir... | [
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0005607864_django_python.txt |
Q:
How can I get input and raw_imput functions to work in Python?
Whenever I use input and raw_imput in Python, it gives me an error report. Such as in the simple number guessing game. This is what happens:
>>> import random
>>> number= random.randint(1,100)
>>> guess= input("guess a number. ")
Traceback (most recent... | How can I get input and raw_imput functions to work in Python? | Whenever I use input and raw_imput in Python, it gives me an error report. Such as in the simple number guessing game. This is what happens:
>>> import random
>>> number= random.randint(1,100)
>>> guess= input("guess a number. ")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name '... | [
"\"imput\" is not a standard function in Python. Spell it like \"input\".\n",
"You've misspelled input. It should be input and raw_input, not imput and raw_imput.\n",
"Note that the meaning and purpose of both input() and raw_input() have changed between Python 2 and Python 3.\nPython 2\n\ninput() reads keyboa... | [
4,
3,
0
] | [] | [] | [
"python",
"random"
] | stackoverflow_0005608380_python_random.txt |
Q:
Using Python to crop an AVI file
I have a media file (AVI or mpeg doesn't really matter) I'd like to just get the top half of the each frame and remove the lower half from my video. IS there any library in python that can help me?
A:
I'd recommend ffmpeg. There's a wrapper for python (http://code.google.com/p/py... | Using Python to crop an AVI file | I have a media file (AVI or mpeg doesn't really matter) I'd like to just get the top half of the each frame and remove the lower half from my video. IS there any library in python that can help me?
| [
"I'd recommend ffmpeg. There's a wrapper for python (http://code.google.com/p/pyffmpeg/), though I never tried it.\nIf that doesn't work, you could just launch a child process for the ffmpeg command-line tool from the interpreter.\n",
"I am experimenting with the Python interface to OpenCV. It is capable of doing... | [
5,
0
] | [] | [] | [
"pygame",
"python",
"python_imaging_library"
] | stackoverflow_0005560291_pygame_python_python_imaging_library.txt |
Q:
struggling with Timer objects in python
again i am struggling with something although it might be a little simpler to fix unlike the binary arrays with my last post. Basically, I created a timer object with a function name. Yet, I keep getting a problem because it says that the function that i call is not defined ... | struggling with Timer objects in python | again i am struggling with something although it might be a little simpler to fix unlike the binary arrays with my last post. Basically, I created a timer object with a function name. Yet, I keep getting a problem because it says that the function that i call is not defined under Name Error.
class DrawBot():
waiti... | [
"Because it's not defined until you get to the actual definition. Plus, you probably don't want to have a single timer shared across every instance of the class... try this instead:\nclass DrawBot():\n def __init__(self):\n self.waitingt = Timer(30.0, self.lockmap)\n ...\n def onlockmap(self, user):... | [
2,
1
] | [] | [] | [
"multithreading",
"python",
"timer"
] | stackoverflow_0005608830_multithreading_python_timer.txt |
Q:
RESTful API across multiple users
I am somewhat new to RESTful APIs.
I'm trying to implement a python system that will control various tasks across multiple computers, with one computer acting as the controller.
I would like all these tasks to be divided amongst multiple users (ex. task foo runs as user foo, and t... | RESTful API across multiple users | I am somewhat new to RESTful APIs.
I'm trying to implement a python system that will control various tasks across multiple computers, with one computer acting as the controller.
I would like all these tasks to be divided amongst multiple users (ex. task foo runs as user foo, and task bar runs as user bar) while handlin... | [
"Sure, you just need the clients to POST their notifications URL to the server, so that the server can then POST them back with the requests. These are called Webhooks by some people.\nAlso see RESTful Webhooks.\n",
"Yes. Keep in mind that being RESTful is merely a way to organize your web application's URL's in... | [
1,
0
] | [] | [] | [
"linux",
"python",
"rest",
"xml"
] | stackoverflow_0005608319_linux_python_rest_xml.txt |
Q:
python2.6 with MySQLdb, NameError 'MySQLdb' not defined
from the interpreter i can issue >>> from MySQLdb just fine. so, I'm assuming the module did actually load. My source looks as follows:
from Tkinter import *
from MySQLdb import *
"""
Inventory control for Affordable Towing
Functions:
connection(... | python2.6 with MySQLdb, NameError 'MySQLdb' not defined | from the interpreter i can issue >>> from MySQLdb just fine. so, I'm assuming the module did actually load. My source looks as follows:
from Tkinter import *
from MySQLdb import *
"""
Inventory control for Affordable Towing
Functions:
connection() - Controls database connection
delete() - Remove item fro... | [
"This is due to the way you're importing the module and then referencing it. \nChange:\nfrom MySQLdb import *\n\nto\nimport MySQLdb\n\nif you plan on referencing it the fashion that you are. \nAnyway, here’s how these statements and functions work:\nFrom: http://effbot.org/zone/import-confusion.htm\nimport X imp... | [
2,
1
] | [] | [] | [
"mysql",
"network_programming",
"programming_languages",
"python"
] | stackoverflow_0005609322_mysql_network_programming_programming_languages_python.txt |
Q:
Parsing text with Python: unstructured but similar information with different formatting
I'm trying to parse thousands of spec sheet text files containing company, material, chemical properties, etc. (Material Safety Data Sheets, to be specific) with Python. The text files contain similar information in loosely st... | Parsing text with Python: unstructured but similar information with different formatting | I'm trying to parse thousands of spec sheet text files containing company, material, chemical properties, etc. (Material Safety Data Sheets, to be specific) with Python. The text files contain similar information in loosely structured formatting such that it's human readable, but unstructured enough that it's not easil... | [
"I'd write a for loop with lots of state variables, processing each line, and use the state variables to keep track of what is going on. The condtionals (if) inside the for loop would make the same \"questions\" a human would have to do would he be parsing the file by hand.\n\"\nfor line in file:\n Is there a co... | [
2
] | [] | [] | [
"parsing",
"python",
"text_parsing"
] | stackoverflow_0005608486_parsing_python_text_parsing.txt |
Q:
Weird python/tkinter error
So I have this code:
from urllib2 import *
import re
import tkSimpleDialog
import os
import glob
from Tkinter import *
class App:
def __init__(self, master):
frame = Frame(master)
frame.pack()
image1 = PhotoImage(file="picture.gif")
w = image1.width()
h = image1.he... | Weird python/tkinter error | So I have this code:
from urllib2 import *
import re
import tkSimpleDialog
import os
import glob
from Tkinter import *
class App:
def __init__(self, master):
frame = Frame(master)
frame.pack()
image1 = PhotoImage(file="picture.gif")
w = image1.width()
h = image1.height()
master.geomet... | [
"it seems that parsed is some times shorter than 10 items \nthe 0-9 variables should be in a list rather than as individual variables this would allow one to use a loop to repeat the same actions on the values rather than duplicating the code for each variable\n"
] | [
1
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0005609554_python_tkinter.txt |
Q:
Default initial value of an integer variable in Python?
What is the default initial value of an integer variable in Python?
A:
Names don't exist until bound. But the default int:
>>> print int()
0
A:
Python doesn't allow you to reference an undefined variable, and trying to do so will raise a NameError. Often,... | Default initial value of an integer variable in Python? | What is the default initial value of an integer variable in Python?
| [
"Names don't exist until bound. But the default int:\n>>> print int()\n0\n\n",
"Python doesn't allow you to reference an undefined variable, and trying to do so will raise a NameError. Often, when you create a variable that contains an integer, you will also assign some value to it.\n>>> x = 42\n\n"
] | [
20,
4
] | [] | [] | [
"default",
"integer",
"python"
] | stackoverflow_0005609632_default_integer_python.txt |
Q:
Python del on classes
Lets assume we have a class in python:
class A(object):
def __del__(self):
print "Del!"
__del__ is called upon deleting/garbage collection of any A instance.
Is is possible to do the same for a class? I would like to have some method called when the class itself is garbage colle... | Python del on classes | Lets assume we have a class in python:
class A(object):
def __del__(self):
print "Del!"
__del__ is called upon deleting/garbage collection of any A instance.
Is is possible to do the same for a class? I would like to have some method called when the class itself is garbage collected, which I assume is bei... | [
"The problem is that classes contain circular references back to themselves - so when they are deleted they are not easily collected - thus the __del__ method odf the metaclass is not called.\nI could trigger it being called using Pypy's Python implementation, but not using cpython - either 2.6 or 3.2. And even to ... | [
7
] | [] | [] | [
"class",
"del",
"python"
] | stackoverflow_0005607937_class_del_python.txt |
Q:
Convert a list of words to list of numbers that were previously assigned in Python(2.7.1)
I have a code "aaabbbcccdddeee" that I split up into 3 letter words (such as 'aaa','bbb','ccc' . . . and so on) and assigned a number value to them using
d=dict(zip(('aaa','bbb','ccc','ddd','eee'),('123','234','345','456','5... | Convert a list of words to list of numbers that were previously assigned in Python(2.7.1) | I have a code "aaabbbcccdddeee" that I split up into 3 letter words (such as 'aaa','bbb','ccc' . . . and so on) and assigned a number value to them using
d=dict(zip(('aaa','bbb','ccc','ddd','eee'),('123','234','345','456','567')))
If random sequence that has
random='aaabbbdddccceeedddbbbaaaeeeccc'
How can I create ... | [
"mapping = <your dictionary>\ninstr = <your data>\nresult = [mapping[instr[i:i+3] ] for i in range(0, len(instr), 3) ]\n\n"
] | [
3
] | [] | [] | [
"list",
"numbers",
"python"
] | stackoverflow_0005609667_list_numbers_python.txt |
Q:
How do I avoid duplicating strings in my Django templates?
I'm wondering how to duplicate a few strings in my templates. Specifically, I'm looking to create a table of contents sort of navigation at the top of my pages with anchor links to content farther down (like http://www.google.com/transparencyreport/faq/). ... | How do I avoid duplicating strings in my Django templates? | I'm wondering how to duplicate a few strings in my templates. Specifically, I'm looking to create a table of contents sort of navigation at the top of my pages with anchor links to content farther down (like http://www.google.com/transparencyreport/faq/). I want the links to have the same text as the section headers fa... | [
"This seems like a situation for just using a template variable that you've passed from a view (e.g. {{ link_name }}).\nYou could use also possibly use template inclusion tag that includes another template with your duplicate information.\n",
"In your view, you could potentially break your content up so that the ... | [
2,
0
] | [] | [] | [
"django",
"django_templates",
"python"
] | stackoverflow_0005603827_django_django_templates_python.txt |
Q:
How to fake keyboard input with Python
Does anyone know if it is possible to have a Python script running in the background that can enter keyboard input into the app in the foreground. Maybe a python library that someone knows about. I'm wanting to fake my Mac's keyboard input in order to automate a very specific... | How to fake keyboard input with Python | Does anyone know if it is possible to have a Python script running in the background that can enter keyboard input into the app in the foreground. Maybe a python library that someone knows about. I'm wanting to fake my Mac's keyboard input in order to automate a very specific task.
| [
"It's probably easiest (but non-portable - this would be mac only) to use appscript. That is, of course, assuming that either the app you want to control supports applescript, or you have another tool which can type/click that can be controlled via applescript (ala Quickeys).\n",
"Use Appscript plus GUI scriptin... | [
0,
0
] | [] | [] | [
"keyboard",
"macos",
"python"
] | stackoverflow_0004356447_keyboard_macos_python.txt |
Q:
sqlite3 'insert into' error
im getting this error:
cursor.execute('INSERT INTO COURSE (title) VALUES (?)',(title))
sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 11 supplied.
Here is my code:
try:
cursor.execute("""CREATE TABLE COURSE
... | sqlite3 'insert into' error | im getting this error:
cursor.execute('INSERT INTO COURSE (title) VALUES (?)',(title))
sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 11 supplied.
Here is my code:
try:
cursor.execute("""CREATE TABLE COURSE
(course_id INTEGER PRIMARY KEY,... | [
"Try passing a tuple:\ncursor.execute('''INSERT INTO COURSE (title) VALUES (?)''',(title,)) \n\nIt's iterating over title.\n"
] | [
3
] | [] | [] | [
"python",
"sqlite"
] | stackoverflow_0005609837_python_sqlite.txt |
Q:
Python is not catching XMLSyntaxError
I have the following python + lxml code:
def doXMLValidation (xml_file, schema_file):
'''Validates xml file against schema'''
s_doc = etree.parse (schema_file)
schema = etree.XMLSchema (s_doc)
x_file = etree.parse(xml_file)
try:
schema.assertValid(... | Python is not catching XMLSyntaxError | I have the following python + lxml code:
def doXMLValidation (xml_file, schema_file):
'''Validates xml file against schema'''
s_doc = etree.parse (schema_file)
schema = etree.XMLSchema (s_doc)
x_file = etree.parse(xml_file)
try:
schema.assertValid(x_file)
except etree.XMLSyntaxError as ... | [
"you don't have a try before the statement causing the error. look at the stacktrace more carefully.\n"
] | [
2
] | [] | [] | [
"exception",
"lxml",
"python"
] | stackoverflow_0005610043_exception_lxml_python.txt |
Q:
Python return values?
How do I do this? Can I do this?
def aFunction(argument):
def testSomething():
if thisValue == 'whatItShouldBe':
return True
else:
return False
if argument == 'theRightValue': # this is actually a switch using elif's in my code
... | Python return values? | How do I do this? Can I do this?
def aFunction(argument):
def testSomething():
if thisValue == 'whatItShouldBe':
return True
else:
return False
if argument == 'theRightValue': # this is actually a switch using elif's in my code
testSomething()
... | [
"The only thing I see wrong right now is you need a return before testSomething() on line 9.\n",
"Perhaps a sub-function is not the right encapsulation tool for you here. You want to expose internal functionality to an external entity. Python classes provide a better mechanism for expressing this than sub-functio... | [
4,
0,
0
] | [] | [] | [
"function",
"python",
"return_value"
] | stackoverflow_0005610064_function_python_return_value.txt |
Q:
Implementing "title formatting" in Python
I'm writing a "title formatting" parser in Python, a la foobar2000 and Winamp. It basically works like this:
"%artist% - %title%" -> "The Beatles - Yellow Submarine"
"%title% by $upper(%artist%)" -> "Yellow Submarine by THE BEATLES"
That's a simple example; look here or h... | Implementing "title formatting" in Python | I'm writing a "title formatting" parser in Python, a la foobar2000 and Winamp. It basically works like this:
"%artist% - %title%" -> "The Beatles - Yellow Submarine"
"%title% by $upper(%artist%)" -> "Yellow Submarine by THE BEATLES"
That's a simple example; look here or here for reference.
Can anyone point me in the r... | [
"Does it have to be in that exact format? Python's own string formatting is nice:\n>>> tags = {'title': 'Yellow Submarine', 'artist': 'The Beatles'}\n>>> tags['upperartist'] = tags['artist'].upper()\n>>> '{title} by {upperartist}'.format(**tags)\n'Yellow Submarine by THE BEATLES'\n\nFor anything much more complicat... | [
1,
0,
0
] | [] | [] | [
"parsing",
"python"
] | stackoverflow_0005608550_parsing_python.txt |
Q:
socket simple question python
i am building a voice messenger type application ... my server application is expected to receive several connections and should b given the option to choose one connection...
my problem is i do not know how to display the ip adress of all the connections that are coming before i pick... | socket simple question python | i am building a voice messenger type application ... my server application is expected to receive several connections and should b given the option to choose one connection...
my problem is i do not know how to display the ip adress of all the connections that are coming before i pick one specific ip and connect to it ... | [
"There is no API mechanism that allows you to read the peer address of a potential connection before you accept(2) that connection. It doesn't exist at the sockets level, so it's not going to be in Python, either.\nIf you want to build way too much knowledge of your operating environment into your application, you ... | [
3
] | [] | [] | [
"python",
"sockets"
] | stackoverflow_0005610497_python_sockets.txt |
Q:
Checking tuples values in dictionary
I have a dictionary having tuple as its key and also tuple as its values. I need a way to access the values of dictionary based on its keys.
For example:
d = {}
d = { (1, 2) : ('A', 'B'),(3, 4) : ('C', 'B') }
Now, first I need to check if keys (1, 2) already exists in a dictio... | Checking tuples values in dictionary | I have a dictionary having tuple as its key and also tuple as its values. I need a way to access the values of dictionary based on its keys.
For example:
d = {}
d = { (1, 2) : ('A', 'B'),(3, 4) : ('C', 'B') }
Now, first I need to check if keys (1, 2) already exists in a dictionary.
Something like:
if d.has_key(1,2)
... | [
"You can simply use a literal tuple as the key:\n>>> d = {(1, 2): ('A', 'B'), (3, 4): ('C', 'D')}\n>>> (1, 2) in d\nTrue\n>>> d[(1, 2)]\n('A', 'B')\n>>> d[(1, 2)][0]\n'A'\n\n",
"The problem is that f(a, b) is treated as \"call f with two arguments\" because the parens and commas are consumed as part of the functi... | [
6,
2,
0
] | [] | [] | [
"dictating",
"python",
"tuples"
] | stackoverflow_0005610609_dictating_python_tuples.txt |
Q:
Is it worth it to leave PHP and study Python just for Google App Engine?
I'm a PHP developer and don't have any experience with Python.
Since GAE seems promising, I really want to use it as my back-end for web apps and mobile games.
I found 'Quercus' but I just want more native way.
Does it worth to leave PHP and ... | Is it worth it to leave PHP and study Python just for Google App Engine? | I'm a PHP developer and don't have any experience with Python.
Since GAE seems promising, I really want to use it as my back-end for web apps and mobile games.
I found 'Quercus' but I just want more native way.
Does it worth to leave PHP and study Python just for Google App Engine?
Or will PHP be available for GAE in t... | [
"Just for GAE? No. For many other reasons -- absolutely.\nRelated question on programmers.stackexchange\n"
] | [
4
] | [] | [] | [
"google_app_engine",
"php",
"python"
] | stackoverflow_0005610765_google_app_engine_php_python.txt |
Q:
Sieve of Eratosthenes algorithm question (Python Syntax)
So I was reading the Wikipedia article on the Sieve of Eratosthenes and it included a Python implementation:
http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes#Algorithm_complexity_and_implementation
def eratosthenes_sieve(n):
# Create a candidate list w... | Sieve of Eratosthenes algorithm question (Python Syntax) | So I was reading the Wikipedia article on the Sieve of Eratosthenes and it included a Python implementation:
http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes#Algorithm_complexity_and_implementation
def eratosthenes_sieve(n):
# Create a candidate list within which non-primes will be
# marked as None; only cand... | [
"candidates[2*i::i] = [None] * (n//i - 1)\n\nis just a terse way of writing\nfor j in range(2 * i, n, i):\n candidates[j] = None\n\nwhich works by assigning an list of Nones to a slice of candidates.\n",
"L * N creates and concatenates N (shallow) copies of L, so [None] * (n//i - 1) gives a list of ceil(n / i)... | [
3,
2
] | [] | [] | [
"python",
"syntax",
"wikipedia"
] | stackoverflow_0005610825_python_syntax_wikipedia.txt |
Q:
How to translate the cast of a memory address in C into python ctypes call?
Sorry if the title isn't accurate, I am not 100% sure it describes the situation correctly:
I am attempting to interface with the FreeTDS C-library using Python's ctypes module. I have some code running surprisingly well, but have run int... | How to translate the cast of a memory address in C into python ctypes call? | Sorry if the title isn't accurate, I am not 100% sure it describes the situation correctly:
I am attempting to interface with the FreeTDS C-library using Python's ctypes module. I have some code running surprisingly well, but have run into one snag. I am not sure how to to translate the last parameter of the dbbind()... | [
"I think you should just check what is behind these DBINT,DBCHAR,DBFLT8 types. Probably this is int, char and double. And for those basic types you can find ctypes - probably c_int, c_char, c_double.\nSo you can now create python instances that will hold values returned by function. To pass these values as a pointe... | [
3
] | [] | [] | [
"ctypes",
"freetds",
"python"
] | stackoverflow_0005610439_ctypes_freetds_python.txt |
Q:
Faster replacing in list with a lot of matches
just a small problem with list and replacing some list entries.
Maybe some informations around my problem. My idea is really simple and easy. I use the module mmap to read out bigger files. It's some FORTRAN-files which have 7 columns and one million lines. Some valu... | Faster replacing in list with a lot of matches | just a small problem with list and replacing some list entries.
Maybe some informations around my problem. My idea is really simple and easy. I use the module mmap to read out bigger files. It's some FORTRAN-files which have 7 columns and one million lines. Some values didn't fulfill the format of the FORTRAN-output a... | [
"If you are eventually going to convert this to an array, you might consider using numpy and the np.genfromtxt which has the ability to deal with missing data:\nhttp://docs.scipy.org/doc/numpy/reference/generated/numpy.genfromtxt.html\nWith a binary file, you can use np.memmap and then use masked arrays to deal wit... | [
2,
2,
0,
0,
0
] | [] | [] | [
"list",
"python"
] | stackoverflow_0005608943_list_python.txt |
Q:
Extract base class pointer
I was told that I can extract reference to base class from any boost::python::object.
The simple code looks like:
// c++:
class Base {};
// Export Base into python module
// python:
class Der(Base):
pass
//c++:
boost::python::object obj; // It points to some Der class object made f... | Extract base class pointer | I was told that I can extract reference to base class from any boost::python::object.
The simple code looks like:
// c++:
class Base {};
// Export Base into python module
// python:
class Der(Base):
pass
//c++:
boost::python::object obj; // It points to some Der class object made from python
boost::shared_ptr<Obj... | [
"So, using this thread I've managed out my question. First of all, my Base class was exported into python this way:\nbp::class_<Base, boost::noncopyable>(\"Base\", bp::no_init)\n\nI had to remove bp::no_init. Why? Look at next update (the answer in stackoverflow post I gave before):\nclass Der(Base):\n def __ini... | [
2
] | [] | [] | [
"boost",
"c++",
"extract",
"object",
"python"
] | stackoverflow_0005610981_boost_c++_extract_object_python.txt |
Q:
Jython missing functions in sys module
I have an python script which I need to run in my java application. I tried to execute it from jython but I have strange problem:
from sys import getdlopenflags
I get:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: cannot import name get... | Jython missing functions in sys module | I have an python script which I need to run in my java application. I tried to execute it from jython but I have strange problem:
from sys import getdlopenflags
I get:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: cannot import name getdlopenflags
When I try to check contents of ... | [
"It says \"Availability: Unix\" in the documentation. The Jython docs seem to have copied that unchanged from the CPython docs. So this function is only available on a Unix installation. Possibly Jython doesn't have it at all - I don't know Java well enough, but since it's supposedly platform-independent, it can't ... | [
2
] | [] | [] | [
"java",
"python"
] | stackoverflow_0005604378_java_python.txt |
Q:
optimizing conditions for speed
example code:
e = [[1,2,3,4],[0,...,10000],[4,5,6,7]]
for n in range(0,1000000):
if n in e[0] and n in e[1] and n in e[2]:
yield n
I'm trying to optimize for speed to avoid e[1] lookup for every iteration if i can find out before that e[1] == range. Same goes for e[0] == rang... | optimizing conditions for speed | example code:
e = [[1,2,3,4],[0,...,10000],[4,5,6,7]]
for n in range(0,1000000):
if n in e[0] and n in e[1] and n in e[2]:
yield n
I'm trying to optimize for speed to avoid e[1] lookup for every iteration if i can find out before that e[1] == range. Same goes for e[0] == range or e[2] == range
let me clarify thi... | [
"Looks like you want to find all elements that are common to all three lists. This is essentially the same as finding the intersection of the sets represented by the lists. In Python we can simply use set and find the intersection.\n#! /usr/bin/env python\n\ndef get_values(lst):\n sets=map(set,lst)\n common=r... | [
4,
0,
0
] | [] | [] | [
"optimization",
"python"
] | stackoverflow_0005611474_optimization_python.txt |
Q:
Python version and Tcl/Tk compatibility
I have installed Tcl and Tk, and I am running into the oh-so-familiar "No module named _tkinter" error.
My 'python' Bash command runs Python version 2.4.2, but Synaptic says I have 2.6.6 installed. I even tried installing 3.0, but that also failed.
I have configured and buil... | Python version and Tcl/Tk compatibility | I have installed Tcl and Tk, and I am running into the oh-so-familiar "No module named _tkinter" error.
My 'python' Bash command runs Python version 2.4.2, but Synaptic says I have 2.6.6 installed. I even tried installing 3.0, but that also failed.
I have configured and built the Tcl/Tk tarballs myself, and tried using... | [
"Here are a few commands which could help you diagnose your problem.\nFirst, try to run the python command with the version number appended. Since\nSynaptic says you have 2.6.6 installed you should be able to run python2.6 to\nget that version:\n(type 'python' and hit TAB to see possible completions)\n\n% python<ta... | [
1,
1
] | [] | [] | [
"linux",
"python",
"tcl",
"tk_toolkit",
"tkinter"
] | stackoverflow_0005435592_linux_python_tcl_tk_toolkit_tkinter.txt |
Q:
Can someone explain this floating-point behavior?
Inspired by this question, I was trying to find out what exactly happens there (my answer was more intuitive, but I cannot exactly understand the why of it).
I believe it comes down to this (running 64 bit Python):
>>> sys.maxint
9223372036854775807
>>> float(sys.m... | Can someone explain this floating-point behavior? | Inspired by this question, I was trying to find out what exactly happens there (my answer was more intuitive, but I cannot exactly understand the why of it).
I believe it comes down to this (running 64 bit Python):
>>> sys.maxint
9223372036854775807
>>> float(sys.maxint)
9.2233720368547758e+18
Python uses the IEEE 754... | [
"Perhaps the following will help clear things up:\n>>> hex(int(float(sys.maxint)))\n'0x8000000000000000L'\n\nThis shows that float(sys.maxint) is in fact a power of 2. Therefore, in binary its mantissa is exactly 1. In IEEE 754 the leading 1. is implied, so in the machine representation this number's mantissa consi... | [
6,
2,
1
] | [] | [] | [
"floating_point",
"ieee_754",
"python"
] | stackoverflow_0005431517_floating_point_ieee_754_python.txt |
Q:
How do I spawn a separate python process?
I need to spawn a separate python process that runs a sub script.
For example:
main.py runs and prints some output to the console. It then spawns sub.py which starts a new process. Once main.py has spawned sub.py it should terminate whilst sub.py continues to run.
Thank y... | How do I spawn a separate python process? | I need to spawn a separate python process that runs a sub script.
For example:
main.py runs and prints some output to the console. It then spawns sub.py which starts a new process. Once main.py has spawned sub.py it should terminate whilst sub.py continues to run.
Thank you.
Edit:
When I run main.py it prints 'main.py... | [
"execfile\nThe straightforward approach:\nexecfile('main.py')\n\nSubprocess\nOffers fine-grained control over input and output, can run processes in background:\nimport subprocess as sp\nprocess=sp.Popen('other_file.py', shell=True, stdout=sp.PIPE, stderr=sp.PIPE)\nout, err = process.communicate() # The output and... | [
4
] | [] | [] | [
"python",
"spawn",
"subprocess"
] | stackoverflow_0005611576_python_spawn_subprocess.txt |
Q:
Reading BerkleyDB files from python: `\x01\x0b\x88\x0c\x01`?
This question in a nutshell: what do \x04++HLMh7EjP3ILSfF\x00 and
'\x01\x0b\x88\x0c\x01-\x10\x02\x06!\x05"\x05#\n$\x0c\'\x0e%\x0b\x01&\x02\'\x06(\n\x00\x00'
mean?
Hi all,
I'm trying to read palm pre 2 database files. Some information is available in the... | Reading BerkleyDB files from python: `\x01\x0b\x88\x0c\x01`? | This question in a nutshell: what do \x04++HLMh7EjP3ILSfF\x00 and
'\x01\x0b\x88\x0c\x01-\x10\x02\x06!\x05"\x05#\n$\x0c\'\x0e%\x0b\x01&\x02\'\x06(\n\x00\x00'
mean?
Hi all,
I'm trying to read palm pre 2 database files. Some information is available in the documentation, but not enough for me to clearly understand the fo... | [
"Educated guess\nFrom simple inspection, The message is probably \"sms successful\", with a phone number:\n\n\n\nunicode(s, errors='ignore')\n u'\\x01\\x0b\\r\\x00\\x05\\x10\\x029\\x060\\x04\\x00/\\x03\\x04++HQqD0wWr_hZP75\\x00\\x00 \\x02\"\\x06\\x00$\\x04inbox\\x001\\x02+\\x04+33626320868\\x00\\x00%\\x0e\\x00... | [
1,
0
] | [] | [] | [
"character_encoding",
"encoding",
"python"
] | stackoverflow_0005610340_character_encoding_encoding_python.txt |
Q:
How to set the max_results value from the gdata.codesearch API higher than 10?
Hi can someone tell me how to use the gdata Codesearch API and augment the number of results from the Query higher than 10 ?
I allready check the CodesearchExample.py from Code Google Gdata - CodesearchExample , but couldn't find a way ... | How to set the max_results value from the gdata.codesearch API higher than 10? | Hi can someone tell me how to use the gdata Codesearch API and augment the number of results from the Query higher than 10 ?
I allready check the CodesearchExample.py from Code Google Gdata - CodesearchExample , but couldn't find a way to do it.
Anyone got an idea ?
| [
"You can't directly use GetSnippetsFeed like the example does. GetSnippetsFeed is actually a wrapper that creates a CodesearchQuery object without any parameters. If you create that object yourself you can set the max_results property.\nservice = gdata.codesearch.service.CodesearchService(source='my_test_app-1.0')\... | [
0
] | [] | [] | [
"api",
"gdata",
"python"
] | stackoverflow_0005574840_api_gdata_python.txt |
Q:
Taking screenshot from a python script by selecting the area
I saw that post (that is really helpful : Take a screenshot via a python script. [Linux]) about taking a screenshot from python. It works well but I'd like to have the same behavior as gnome-screenshot : having the possibility to choose between :
Captu... | Taking screenshot from a python script by selecting the area | I saw that post (that is really helpful : Take a screenshot via a python script. [Linux]) about taking a screenshot from python. It works well but I'd like to have the same behavior as gnome-screenshot : having the possibility to choose between :
Capturing the whole desktop
Capturing an active window
Capturing an are... | [
"I have a wrapper project (pyscreenshot) for scrot, imagemagick, pyqt, wx and pygtk.\nIf you have one of them, you can use it.\nCapturing an active window is missing.\nInstall:\neasy_install pyscreenshot\n\nExample:\nimport pyscreenshot as ImageGrab\n\n# fullscreen\nim=ImageGrab.grab()\nim.show()\n\n# part of the s... | [
2,
1
] | [] | [] | [
"gnome",
"python",
"screenshot"
] | stackoverflow_0004921954_gnome_python_screenshot.txt |
Q:
How can I tell why a rollback is happening in SQLAlchemy?
When I insert into MySQL with SQLAlchemy, I see the message "ROLLBACK" appear in the outputed log for the development server. How can I tell why the rollback is happening?
2011-04-10 00:35:32,736 INFO [sqlalchemy.engine.base.Engine.0x...4710][MainThread] ... | How can I tell why a rollback is happening in SQLAlchemy? | When I insert into MySQL with SQLAlchemy, I see the message "ROLLBACK" appear in the outputed log for the development server. How can I tell why the rollback is happening?
2011-04-10 00:35:32,736 INFO [sqlalchemy.engine.base.Engine.0x...4710][MainThread] INSERT INTO pageview (time, unit_id, visitor_id, url_id, referr... | [
"You can always print out the error when exception occurs:\ntry:\n transaction.commit()\nexcept Exception, e:\n session.rollback()\n print str(e)\n\n"
] | [
2
] | [
"Search the Sqlalchemy documentation for enabling the logging of the generatef\nd SQL statements and Sql responses. This will usually give you all related information for further debugging.\n"
] | [
-2
] | [
"mysql",
"pyramid",
"python",
"sqlalchemy"
] | stackoverflow_0005610463_mysql_pyramid_python_sqlalchemy.txt |
Q:
gql query returns BadQueryError: Parse Error
This is my gql code:
data = db.GqlQuery("SELECT * FROM Playlist " + "WHERE tags = :1" + "ORDER BY :2", tag, order)
and I get this error:
BadQueryError: Parse Error: Expected no additional symbols at symbol BY
Does anyone know what I am doing wrong?
thanks for the help
... | gql query returns BadQueryError: Parse Error | This is my gql code:
data = db.GqlQuery("SELECT * FROM Playlist " + "WHERE tags = :1" + "ORDER BY :2", tag, order)
and I get this error:
BadQueryError: Parse Error: Expected no additional symbols at symbol BY
Does anyone know what I am doing wrong?
thanks for the help
J
| [
"You seem to be concatenating the GQL string for some unknown reason and have missed a space. Try:\ndata = db.GqlQuery(\"SELECT * FROM Playlist WHERE tags = :1 ORDER BY :2\", tag, order)\n\n",
"You're missing a space before ORDER.\n"
] | [
5,
3
] | [] | [] | [
"google_app_engine",
"gql",
"python"
] | stackoverflow_0005612123_google_app_engine_gql_python.txt |
Q:
Seeing what's new in json list in Python
I'm calling a list of objects via json in Python, and I want to do something with each of them.
How can I make sure, when I run this script for the 2nd time, I don't use the objects I've already used the first time?
Example:
The first time I run the script, I get this:
{u's... | Seeing what's new in json list in Python | I'm calling a list of objects via json in Python, and I want to do something with each of them.
How can I make sure, when I run this script for the 2nd time, I don't use the objects I've already used the first time?
Example:
The first time I run the script, I get this:
{u'status': u'active', u'due_date': None, u'group'... | [
"old_list = json.loads(old_json)\nnew_list = json.loads(new_json)\n\nnew_items_list = list(set(new_list) - set(old_list))\n\n"
] | [
3
] | [] | [] | [
"json",
"python"
] | stackoverflow_0005612225_json_python.txt |
Q:
related_name argument not working as expected in Django model?
I recently got a ForeignKey clash in my Django model. I have the need to have two foreign keys (owner, assigned_to) ultimately pointing to the same model (a user).
From what I understand I need a related_name argument to solve that problem. So I did th... | related_name argument not working as expected in Django model? | I recently got a ForeignKey clash in my Django model. I have the need to have two foreign keys (owner, assigned_to) ultimately pointing to the same model (a user).
From what I understand I need a related_name argument to solve that problem. So I did that:
assigned_to = models.ForeignKey(TaskUser, blank=True, null=True,... | [
"If you have ForeignKey relationships in an abstract base class every class inheriting from it will have this relationship. As a result of this you must not 'hardcode' its related_name, because all sub classes will try to create the same accessor on the realted class (TaskUser in this case). \nYou should better do ... | [
95,
9
] | [] | [] | [
"django",
"python"
] | stackoverflow_0005611410_django_python.txt |
Q:
Converting date into hours
I want to find time difference between two date and then compare the difference time in hours. Something like this,
StartTime = 2011-03-10 15:45:48
EndTime = 2011-03-10 18:04:00
And then find the difference as,
timeDifference = abs(StartTime - EndTime)
And then I need to compare the r... | Converting date into hours | I want to find time difference between two date and then compare the difference time in hours. Something like this,
StartTime = 2011-03-10 15:45:48
EndTime = 2011-03-10 18:04:00
And then find the difference as,
timeDifference = abs(StartTime - EndTime)
And then I need to compare the results as,
If timeDifference > 6... | [
"Let's assume that you have your two dates and times as datetime objects (see datetime.datetime):\n>>> import datetime\n>>> start_time = datetime.datetime(2011,3,10,15,45,48)\n>>> end_time = datetime.datetime(2011,3,10,18,4,0)\n\nSubtracting one datetime from another gives you a timedelta object, and you can use ab... | [
13
] | [] | [] | [
"datetime",
"hour",
"python"
] | stackoverflow_0005612129_datetime_hour_python.txt |
Q:
Guess File Type Windows Similar to Linux `file`
Is there an equivalent to the Linux file command on Linux? I would prefer something with Python bindings, but anything will do as long as it can be accessed through a DLL or launched a subprocess.
A:
There is no native function in Windows, but you can use TrID. Thi... | Guess File Type Windows Similar to Linux `file` | Is there an equivalent to the Linux file command on Linux? I would prefer something with Python bindings, but anything will do as long as it can be accessed through a DLL or launched a subprocess.
| [
"There is no native function in Windows, but you can use TrID. This tools has been around since 2003 and still gets maintained.\n",
"The file from GnuWin32 doesn't need Cygwin. file includes a (BSD licensed) library and Python bindings for it.\n"
] | [
2,
1
] | [] | [] | [
"file",
"mime",
"python",
"types"
] | stackoverflow_0005611862_file_mime_python_types.txt |
Q:
Basic pySQLite example?
Gang, I am beginning to play around with pySQLite and I'm trying to find an example that illustrates how to query the db for existing records before inserting a new record if it doesn't already exist in the db. I feel I am overlooking a very basic function.
Thanks!
A:
Use the UNIQUE key... | Basic pySQLite example? | Gang, I am beginning to play around with pySQLite and I'm trying to find an example that illustrates how to query the db for existing records before inserting a new record if it doesn't already exist in the db. I feel I am overlooking a very basic function.
Thanks!
| [
"Use the UNIQUE keyword when creating the table, and use INSERT OR INGORE to insert only if the record is \"new\" (unique):\nconnection=sqlite3.connect(':memory:')\ncursor=connection.cursor()\ncursor.execute('CREATE TABLE foo (bar INTEGER UNIQUE, baz INTEGER)')\n\nHere we insert the row once:\ncursor.execute('INSER... | [
11
] | [] | [] | [
"pysqlite",
"python",
"sqlite"
] | stackoverflow_0005612745_pysqlite_python_sqlite.txt |
Q:
Differences between compiler and ast module in python
The compiler module has been deprecated in python 2.6.
Does anybody know what is the reason behind the deprecation ?
Is the ast module a direct replacement ? Will the ast module be supported in python 3k ?
A:
The compiler module was a Python compiler written ... | Differences between compiler and ast module in python | The compiler module has been deprecated in python 2.6.
Does anybody know what is the reason behind the deprecation ?
Is the ast module a direct replacement ? Will the ast module be supported in python 3k ?
| [
"The compiler module was a Python compiler written in Python. It was horribly slow and a pain to maintain.\nThe ast module is a smarter solution to the same problem: it provides Python level access to the actual compiler used when importing modules. Since it is just a visible API for the builtin compiler, it isn't ... | [
6,
4
] | [] | [] | [
"python"
] | stackoverflow_0005612312_python.txt |
Q:
Using matplotlib slider widget to change clim in image
I have virtually no experience with python, but I am trying to create a simple script which loads an image and uses the slider widget to adjust the minimum and maximum of the colorbar, and redraws the image data accordingly.
I am trying to follow this example:... | Using matplotlib slider widget to change clim in image | I have virtually no experience with python, but I am trying to create a simple script which loads an image and uses the slider widget to adjust the minimum and maximum of the colorbar, and redraws the image data accordingly.
I am trying to follow this example: http://matplotlib.sourceforge.net/examples/widgets/slider_d... | [
"Mostly, you just had lots and lots of syntax problems.\nFor example, you were trying to unpack a single value (im1,=ax.imshow(im)) giving you the TypeError you mentioned in your question (as it should). You also set a function to a value when you meant to call it: (im1.set_clim=(smin.val,smax.val)).\nAlso, I remo... | [
11,
1
] | [] | [] | [
"matplotlib",
"python",
"widget"
] | stackoverflow_0005611805_matplotlib_python_widget.txt |
Q:
How to create a list() of partially sequenced alphanumeric items?
I thought it rather simple but can't figure out by myself. I have a range of non-continuous items, like this:
farm011 - farm018, farm020, farm022 - farm033, farm041 - farm052, ......
which I want to put in a list(). What's the easiest way of doing t... | How to create a list() of partially sequenced alphanumeric items? | I thought it rather simple but can't figure out by myself. I have a range of non-continuous items, like this:
farm011 - farm018, farm020, farm022 - farm033, farm041 - farm052, ......
which I want to put in a list(). What's the easiest way of doing that? Just to make it clear[er], I think the list should look like this:... | [
"for rng in ncitems.split(','):\n l = re.findall(\"(\\w+\\d+)\", rng)\n if len(l) == 1:\n items.extend(l)\n elif len(l) == 2:\n w1,s,w2,e = re.findall(\"(\\w+)(\\d+)\", rng) # w1 and w2 should be same...\n for i in range(s,e):\n items.append(\"%s%03d\"%(w1,i))\n\n",
"This is a simple solution:\n#... | [
1,
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0005610605_python.txt |
Q:
Want to have a display table with sorting , searching, paging functionality on the html page using jquery
The following are the details of the issue I am facing:
A] Technologies being used in the project:
jQuery, Python, Django, google app engine.
B] Question/ feature I am trying to add to the html page
1] Want to... | Want to have a display table with sorting , searching, paging functionality on the html page using jquery | The following are the details of the issue I am facing:
A] Technologies being used in the project:
jQuery, Python, Django, google app engine.
B] Question/ feature I am trying to add to the html page
1] Want to add a table on the html page
2] Table should have multi column sorting functionality, if possible.
3] Table ro... | [
"Have a look at the DataTables plugin for jQuery. It will solve your problems\nhttp://www.datatables.net/\n",
"Isotope lets you use dynamic ordering and layout on different properties on client side and it's based on jQuery. You should definitely check it out.\n"
] | [
6,
0
] | [] | [] | [
"google_app_engine",
"jquery",
"jquery_plugins",
"python"
] | stackoverflow_0005611373_google_app_engine_jquery_jquery_plugins_python.txt |
Q:
[Python]How to sort a string with two variables?
Hello I am somewhat new to python so please bear with me.
My python program has the following lines:
print "Player 1: " +str(player1points)
print "Player 2: " +str(player2points)
print "Player 3: " +str(player3points)
print "Player 4: " +str(player4points)
The playe... | [Python]How to sort a string with two variables? | Hello I am somewhat new to python so please bear with me.
My python program has the following lines:
print "Player 1: " +str(player1points)
print "Player 2: " +str(player2points)
print "Player 3: " +str(player3points)
print "Player 4: " +str(player4points)
The player#points are what my program has calculated it to be, ... | [
"Look at the examples of \nhttp://wiki.python.org/moin/HowTo/Sorting#Operator_Module_Functions\n",
"If you already have player objects or dictionaries, you could sort with:\nplayers.sort(key=lambda player: player.score, reverse=True)\n\nIf not, process your array and split at each ':'\nSample:\n#!/usr/bin/env pyt... | [
2,
2,
0,
0,
0
] | [] | [] | [
"python",
"sorting",
"variables"
] | stackoverflow_0005613766_python_sorting_variables.txt |
Q:
append to a dictionary in python
My problem is this,
i need to try to create a dictionary that will hold the count values of each cluster from a dataset i am using.
I want my programme to use a while loop to enter keys into the dictionary based on an integer from user input.
here is some code
numberofclusters = r... | append to a dictionary in python | My problem is this,
i need to try to create a dictionary that will hold the count values of each cluster from a dataset i am using.
I want my programme to use a while loop to enter keys into the dictionary based on an integer from user input.
here is some code
numberofclusters = raw_input("Enter the number of clusters... | [
">>> num_of_clusters = int(raw_input('Number: '))\nNumber: 3\n>>> clusters = {}\n>>> for i in range(1, num_of_clusters+1):\n clusters['cluster{0}'.format(i)] = 0\n\n>>> clusters\n{'cluster2': 0, 'cluster3': 0, 'cluster1': 0}\n\n",
"For starters, you'll want to re-think your loop logic. As it stands now, yo... | [
0,
0
] | [] | [] | [
"append",
"dictionary",
"python"
] | stackoverflow_0005614104_append_dictionary_python.txt |
Q:
Cross-platform method for finding python include folder
I have python extension code that I need to cross-platform compile, and to do so, I need to be able to find the python include folder. On Linux and Mac OSX, I can do python-config --include and it gives me something like -I/Library/Frameworks/Python.framewor... | Cross-platform method for finding python include folder | I have python extension code that I need to cross-platform compile, and to do so, I need to be able to find the python include folder. On Linux and Mac OSX, I can do python-config --include and it gives me something like -I/Library/Frameworks/Python.framework/Versions/6.3/include/python2.6. This is fine and dandy, ex... | [
"You can try this:\n>>> from distutils import sysconfig\n>>> sysconfig.get_python_inc()\n'/usr/include/python2.6'\n>>> sysconfig.get_python_inc(plat_specific=True)\n'/usr/include/python2.6'\n\nNote: I found this out by looking at python-config source.\n"
] | [
4
] | [] | [] | [
"python"
] | stackoverflow_0005614192_python.txt |
Q:
Python: Save dynamically created object types
I'm creating some object types dynamically using type function. Ex
return type('DynamicType', (object,), dict)
The dict depends on user input. Now I want that I should be able to save this returned class type and use the same one over different sessions. One possible ... | Python: Save dynamically created object types | I'm creating some object types dynamically using type function. Ex
return type('DynamicType', (object,), dict)
The dict depends on user input. Now I want that I should be able to save this returned class type and use the same one over different sessions. One possible method is to save the dict as text(or into database... | [
"You can't pickle classes, even if you solve your \"... not found as ...\" problem it still won't work (as in save the name of the class, without the content, then fail to unpickle because the class doesn't exist after your program restarts)\nYou will have to manually serialize dict and reconstruct the class from i... | [
3,
3,
0,
0,
0,
0,
0
] | [] | [] | [
"class",
"django",
"python",
"types"
] | stackoverflow_0005349398_class_django_python_types.txt |
Q:
Python -- Quotations around filenames
I'm not quite sure when I need to put quotations around the filenames in Python.
For example, when I set
f = open(file)
I can run something like
len(f.read())
and it will run fine.
However, when I do it directly, it only works with
len(open("file").read())
Likewise, in term... | Python -- Quotations around filenames | I'm not quite sure when I need to put quotations around the filenames in Python.
For example, when I set
f = open(file)
I can run something like
len(f.read())
and it will run fine.
However, when I do it directly, it only works with
len(open("file").read())
Likewise, in terminal when running from Python I always have... | [
"In python you can always use the name of a variable or function outside quotations, but the name of a file is usually not a variable. \nIf file is the name of a string variable you can always do open(file).read(), however if it is literally the filename you must always do open(\"file\").read().\n",
"Quotations ... | [
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0005614269_python.txt |
Q:
What is the simplest way to send an email with an attachment using Python?
What is the simplest way to send an email with an mp3 attachment using Python? I've written scripts in the past which used a pipe to sendmail to send basic email messages, but I've never bothered with attachments before.
Thanks in advance.
... | What is the simplest way to send an email with an attachment using Python? | What is the simplest way to send an email with an mp3 attachment using Python? I've written scripts in the past which used a pipe to sendmail to send basic email messages, but I've never bothered with attachments before.
Thanks in advance.
| [
"Use email package. It's pretty simple.\nIn the URL I linked, you'll find straight examples on how to do just that.\nHope it helps.\n",
"You can also take a look at the python code used for: http://caspian.dotconf.net/menu/Software/SendEmail/\n"
] | [
3,
0
] | [] | [] | [
"attachment",
"email",
"python"
] | stackoverflow_0005614123_attachment_email_python.txt |
Q:
Parsing repeated characters
I'm new to parsing (obviously). I am using LEPL library to parse some markup language.
I have a problem with this code (I've omitted details for the sake of clarity).
from lepl import *
a = Literal('a')[0:,...] # 0 or more, join the result
b = Literal('b')
c = (a | b)[0:]
print c.par... | Parsing repeated characters | I'm new to parsing (obviously). I am using LEPL library to parse some markup language.
I have a problem with this code (I've omitted details for the sake of clarity).
from lepl import *
a = Literal('a')[0:,...] # 0 or more, join the result
b = Literal('b')
c = (a | b)[0:]
print c.parse("abaabaaab")
The last line sh... | [
"I am pretty sure that, in your first example, you want\na = Literal('a')[1:]\n\nWith two [0:] repeats in your grammar, the parser will indeed run into effectively infinite backtracking.\n"
] | [
7
] | [] | [] | [
"lepl",
"parsing",
"python"
] | stackoverflow_0005614163_lepl_parsing_python.txt |
Q:
How to change a strings encoding as utf 8 in C
How can i change character encoding of a string to UTF-8? I am making some execv calls to a python program but python returns the strings with the some characters cut of. I don't know if this a python issue or c issue but i thought if i can change the strings encoding... | How to change a strings encoding as utf 8 in C | How can i change character encoding of a string to UTF-8? I am making some execv calls to a python program but python returns the strings with the some characters cut of. I don't know if this a python issue or c issue but i thought if i can change the strings encoding in c and then pass it to python, it should do the t... | [
"There is no such thing as character encoding in C.\nA char* can hold any data, how you interpret the characters is up to you. For instance, printf will typically dump the characters as they are to the standard output, and if your console interprets those characters as UFT8, they'll appear as such.\nIf you want to ... | [
3,
3
] | [] | [] | [
"c",
"encoding",
"python"
] | stackoverflow_0005614372_c_encoding_python.txt |
Q:
convert gtkglade to libglade for a backwards compatibility
I have a python gtk app that I am porting to an environment that can only use pygtk2.10. pygtk2.10 doesn't not use the gtkbuilder infrastructure but rather the libglade infrastructure I have a 2 goals
1) convert the gtkbuilder glade file format to libglade... | convert gtkglade to libglade for a backwards compatibility | I have a python gtk app that I am porting to an environment that can only use pygtk2.10. pygtk2.10 doesn't not use the gtkbuilder infrastructure but rather the libglade infrastructure I have a 2 goals
1) convert the gtkbuilder glade file format to libglade format. Basically I want to do the opposite of gtk-builder-conv... | [
"To solve #1, you can still save Libglade files in Glade. There is a control at the bottom of the Save dialog where you can select Libglade or GtkBuilder.\nTo solve #2, I suggest you read the documentation of gtk.Builder and gtk.glade.XML and find out what is appropriate to the way you use each one in your applicat... | [
2
] | [] | [] | [
"backwards_compatibility",
"glade",
"gtkbuilder",
"pygtk",
"python"
] | stackoverflow_0005599394_backwards_compatibility_glade_gtkbuilder_pygtk_python.txt |
Q:
In Python in GAE, what is the best way to limit the risk of executing untrusted code?
I would like to enable students to submit python code solutions to a few simple python problems. My applicatoin will be running in GAE. How can I limit the risk from malicios code that is sumitted? I realize that this is a hard p... | In Python in GAE, what is the best way to limit the risk of executing untrusted code? | I would like to enable students to submit python code solutions to a few simple python problems. My applicatoin will be running in GAE. How can I limit the risk from malicios code that is sumitted? I realize that this is a hard problem and I have read related Stackoverflow and other posts on the subject. I am curious i... | [
"@mjv's smiley comment is actually spot-on: make sure the submitter IS identified and associated with the code in question (which presumably is going to be sent to a task queue), and log any diagnostics caused by an individual's submissions.\nBeyond that, you can indeed prepare a test-space that's more restrictive ... | [
5,
2,
0
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0001496115_google_app_engine_python.txt |
Q:
Delaying declaring static files/folders with CherryPy
I have a single CherryPy application serving two websites, each having their static files stored in respective sub-folders of my app folder (each subfolder is named after the respective domain). In my main top-level program (Main.py), the site is launched with... | Delaying declaring static files/folders with CherryPy | I have a single CherryPy application serving two websites, each having their static files stored in respective sub-folders of my app folder (each subfolder is named after the respective domain). In my main top-level program (Main.py), the site is launched with
cherrypy.quickstart(Root(), '/',config='cherrypy.cfg'). S... | [
"All Tools are just callables with some configuration sugar, so you can hold off until your index method via:\ndef index(self, ...):\n root = my_domain_map[cherrypy.request.headers['Host']]\n cherrypy.lib.staticdir(section='', dir='', root=root)\n # And then this funky hack...\n return cherrypy.response... | [
1
] | [] | [] | [
"cherrypy",
"python",
"static"
] | stackoverflow_0005613631_cherrypy_python_static.txt |
Q:
Can't use a list of methods in a Python class, it breaks deepcopy. Workaround?
I'm trying to learn more about Python by implementing a k-Nearest Neighbor classifier. KNN works by labeling the new data based on what existing data its most similar to. So for a given table of data, you try to determine the 3 most si... | Can't use a list of methods in a Python class, it breaks deepcopy. Workaround? | I'm trying to learn more about Python by implementing a k-Nearest Neighbor classifier. KNN works by labeling the new data based on what existing data its most similar to. So for a given table of data, you try to determine the 3 most similar points (if k = 3) and pick whatever label is more frequent. There's different... | [
"It was a bug: http://bugs.python.org/issue1515\nYou can put this at the top of your file to make it work:\nimport copy\nimport types\n\ndef _deepcopy_method(x, memo):\n return type(x)(x.im_func, copy.deepcopy(x.im_self, memo), x.im_class)\ncopy._deepcopy_dispatch[types.MethodType] = _deepcopy_method\n\n"
] | [
4
] | [] | [] | [
"deep_copy",
"design_patterns",
"python"
] | stackoverflow_0005614741_deep_copy_design_patterns_python.txt |
Q:
Cell segmentation and fluorescence counting in Python
How can I segment cells from an image taken on a microscope, along the lines of what was done here in Matlab?
http://blogs.mathworks.com/steve/2006/06/02/cell-segmentation/
Also, if I take multiple image in different fluorescent channels (after staining the cel... | Cell segmentation and fluorescence counting in Python | How can I segment cells from an image taken on a microscope, along the lines of what was done here in Matlab?
http://blogs.mathworks.com/steve/2006/06/02/cell-segmentation/
Also, if I take multiple image in different fluorescent channels (after staining the cells with some antibody/maker), how can I automatically quant... | [
"You can do this in Python using the OpenCV library.\nIn particular, you'll be interested in the following features:\n\nhistogram stretching (cv.EqualizeHist). This is missing from the current Python API, but if you download the latest SVN release of OpenCV, you can use it. This part is for display purposes only,... | [
7,
5,
2,
1
] | [] | [] | [
"image_processing",
"matlab",
"python",
"scientific_computing",
"scipy"
] | stackoverflow_0005560507_image_processing_matlab_python_scientific_computing_scipy.txt |
Q:
example for twisted dns python
can anyone provide dns client examples for twisted except the one given in twisted source files?
I found most of examples are dns servers.
A:
Four years ago, I wrote oftcdns, a load-balancing DNS server using python twsited. In particular, I think you'll want to review the MyAutho... | example for twisted dns python | can anyone provide dns client examples for twisted except the one given in twisted source files?
I found most of examples are dns servers.
| [
"Four years ago, I wrote oftcdns, a load-balancing DNS server using python twsited. In particular, I think you'll want to review the MyAuthority class in oftcdns.tac. Hope this helps.\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0004117272_python.txt |
Q:
DatabaseError: You must not use 8-bit bytestrings unless you use a text_factory that can interpret 8-bit bytestrings
I am trying to setup a database for a django application.
So when i attempt to create database everything works fine except one thing. At the end, this message comes up:
You just installed Django's... | DatabaseError: You must not use 8-bit bytestrings unless you use a text_factory that can interpret 8-bit bytestrings | I am trying to setup a database for a django application.
So when i attempt to create database everything works fine except one thing. At the end, this message comes up:
You just installed Django's auth system, which means you don't have any superusers defined.
Would you like to create one now? (yes/no):
If... | [
"It looks like this is due to a bug in Django related to system usernames that contain non-8-bit characters.\nAs a workaround, you can say \"no\" when asked to create a superuser and use the createsuperuser command to create a new superuser with a different name:\n$ python manage.py syncdb\nCreating table auth_perm... | [
2
] | [] | [] | [
"django",
"python",
"sqlite"
] | stackoverflow_0005614313_django_python_sqlite.txt |
Q:
Python Mock: Unexpected result with patch and return_value
I'll post some code first so it's more clear.
My class:
from tools import get_knife, sharpen
class Banana(object):
def chop(self):
knife = get_knife()
sharpen(knife)
My test:
from mock import patch, sentinel
from banana import Banana
... | Python Mock: Unexpected result with patch and return_value | I'll post some code first so it's more clear.
My class:
from tools import get_knife, sharpen
class Banana(object):
def chop(self):
knife = get_knife()
sharpen(knife)
My test:
from mock import patch, sentinel
from banana import Banana
class TestBanana(unittest.TestCase):
@patch('banana.get_kn... | [
"\nNote that the decorators are applied from the bottom upwards. This is the standard way that Python applies decorators. The order of the created mocks passed into your test function matches this order.\n\nhttp://www.voidspace.org.uk/python/mock/patch.html#nesting-patch-decorators\n"
] | [
4
] | [] | [] | [
"mocking",
"python"
] | stackoverflow_0005614976_mocking_python.txt |
Q:
Problems with custom time widget
I have a model that has an attribute that referrers to when this object wont be publicly available anymore.
class Story(models.Model):
...
deadline = models.models.DateTimeField()
What I want to do is present to the user the possibility to to set this date but in a very ea... | Problems with custom time widget | I have a model that has an attribute that referrers to when this object wont be publicly available anymore.
class Story(models.Model):
...
deadline = models.models.DateTimeField()
What I want to do is present to the user the possibility to to set this date but in a very easy way and restricted way. I´ll give t... | [
"You need to exclude deadline field from the form and override save() method:\nclass StoryForm(ModelForm):\n\n fecha_cierre = forms.TypedChoiceField(\n choices=DAYS_CHOICES, widget=forms.Select)\n\n class Meta:\n models = Story\n exclude = ('deadline',)\n\n def save(self):\n stor... | [
1
] | [] | [] | [
"django",
"forms",
"python",
"widget"
] | stackoverflow_0005614992_django_forms_python_widget.txt |
Q:
How do I change this particular string into a certain input
I have the following line in my python program
print "Player 1: " +str(player1points)
where 'player1points' is calculate in my program.
The results yield:
Player 1: 3
where the '3' was what the program calculated for that run.
However for one particular... | How do I change this particular string into a certain input | I have the following line in my python program
print "Player 1: " +str(player1points)
where 'player1points' is calculate in my program.
The results yield:
Player 1: 3
where the '3' was what the program calculated for that run.
However for one particular function I managed to get help from here
def sort_players(player... | [
"'Player 1: +str(player1points)\\n'\n\nIs just a string, even though it contains something that may be Python code. Thankfully, Python won't magically evaluate that. That string will be passed literally to the function. Look at the syntax highlighting of the line above and compare it to this, which actually adds pl... | [
3,
0,
0
] | [] | [] | [
"integer",
"python",
"sorting",
"string"
] | stackoverflow_0005614871_integer_python_sorting_string.txt |
Q:
Python - Serialise HTML and output as JSON
I have a HTML page that displays a few values. I also have a little app that displays data from some other pages I have, but these other pages are JSON, not HTML.
I want to consume these values from the HTML page, convert to JSON, then output.
The reason I want to do this... | Python - Serialise HTML and output as JSON | I have a HTML page that displays a few values. I also have a little app that displays data from some other pages I have, but these other pages are JSON, not HTML.
I want to consume these values from the HTML page, convert to JSON, then output.
The reason I want to do this is so that I can simply reuse my code, and just... | [
"If you truly need to parse an HTML page in Python, you should be using Beautiful Soup. I question whether you really should be doing this though. Are the HTML pages and JSON outputs using the same Django instance? Are they all apart of the same project?\nIf they are apart of the same project, then you can use some... | [
2
] | [] | [] | [
"django",
"html",
"json",
"python"
] | stackoverflow_0005614928_django_html_json_python.txt |
Q:
JSON->String in python
Say I get this line of JSON
[{u'status': u'active', u'due_date': None, u'group': u'later', u'task_id': 73286}]
How can I convert those separate values to strings? So I can say
Print Status
And it returns
active
A:
That is NOT a "line of JSON" as received from an external source. It looks... | JSON->String in python | Say I get this line of JSON
[{u'status': u'active', u'due_date': None, u'group': u'later', u'task_id': 73286}]
How can I convert those separate values to strings? So I can say
Print Status
And it returns
active
| [
"That is NOT a \"line of JSON\" as received from an external source. It looks like the result of json.loads(external_JSON_string). Also Print Status won't work; you mean print status.\n>>> result = [{u'status': u'active', u'due_date': None, u'group': u'later', u'task_id': 73286}]\n>>> print result[0]['status']\nact... | [
25,
4,
0
] | [] | [] | [
"json",
"python"
] | stackoverflow_0005614572_json_python.txt |
Q:
Django polymorphism hack
I'm trying to bake out a sort of "single table inheritence" a.k.a. "table per hierarchy" model in Django.
Here's what I'd like to do:
class PolymorphicModel(models.Model):
content_type = models.ForeignKey(ContentType)
class Meta:
abstract = True
def __init__(self, *args,... | Django polymorphism hack | I'm trying to bake out a sort of "single table inheritence" a.k.a. "table per hierarchy" model in Django.
Here's what I'd like to do:
class PolymorphicModel(models.Model):
content_type = models.ForeignKey(ContentType)
class Meta:
abstract = True
def __init__(self, *args, **kwargs):
super(Polym... | [
"Ups, well apparently content_type is a reserved name. I changed the property name to ct and it works now.\nI've published by solution here:\nhttp://djangosnippets.org/snippets/2408/\n"
] | [
1
] | [] | [] | [
"django",
"django_models",
"inheritance",
"python"
] | stackoverflow_0005615343_django_django_models_inheritance_python.txt |
Q:
Python HTML parsing specific information within tags
I am trying to parse out specific information within tags.
For example, on the website:
http://www.epicurious.com/articlesguides/bestof/toprecipes/bestchickenrecipes/recipes/food/views/My-Favorite-Simple-Roast-Chicken-231348
I am trying to parse out very speci... | Python HTML parsing specific information within tags | I am trying to parse out specific information within tags.
For example, on the website:
http://www.epicurious.com/articlesguides/bestof/toprecipes/bestchickenrecipes/recipes/food/views/My-Favorite-Simple-Roast-Chicken-231348
I am trying to parse out very specific information like the ingredients. If you go to the pag... | [
"Have a look at http://www.crummy.com/software/BeautifulSoup/ Your approach works for simple cases, but will cause you headache as soon as the html and/or your requirements get a bit more complicated.\n",
"I will get a ticking-off from all the people that say HTML texts can't be analysed by regexes.\nOk, ok, but ... | [
3,
1
] | [] | [] | [
"html",
"parsing",
"python",
"tags"
] | stackoverflow_0005615123_html_parsing_python_tags.txt |
Q:
subprocess Popen blocking PyQt GUI
I'm trying to build a simple gui for a video converter application called "HandBrake" using PyQt.
My problem is that when I choose a video file to convert, subprocess Popen starts handbrake application with the necessary args but while waiting for handbrake to finish the gui gets... | subprocess Popen blocking PyQt GUI | I'm trying to build a simple gui for a video converter application called "HandBrake" using PyQt.
My problem is that when I choose a video file to convert, subprocess Popen starts handbrake application with the necessary args but while waiting for handbrake to finish the gui gets blocked so I can't do any changes. (Ex:... | [
"Since you are in Qt land already you could do something like this:\nfrom PyQt4.QtCore import QProcess\n\nclass YourClass(QObject):\n\n [...]\n\n def videoProcess(self):\n self.pushButton.setEnabled(0)\n self.pushButton.setText(\"Please Wait\")\n command = \"handbrake.exe\"\n args ... | [
10,
1
] | [] | [] | [
"popen",
"pyqt",
"python",
"subprocess",
"user_interface"
] | stackoverflow_0005613922_popen_pyqt_python_subprocess_user_interface.txt |
Q:
Python Inserting values into dictionary using a loop
I have a verses dictionary that contains these values:
{cluster1: 0, cluster2: 0, cluster3: 0}
i have a data file that has been read in and each line in the file has been represented as a string in a dictionary like this.
[ "0,1,0,0,0,0,0,0,0,1,1,No,cluster3",... | Python Inserting values into dictionary using a loop | I have a verses dictionary that contains these values:
{cluster1: 0, cluster2: 0, cluster3: 0}
i have a data file that has been read in and each line in the file has been represented as a string in a dictionary like this.
[ "0,1,0,0,0,0,0,0,0,1,1,No,cluster3"," 0,1,0,0,1,0,0,0,0,1,1,No,cluster2" ]
I want to be able ... | [
"You're quite close. You need to look through keys of the dictionary:\n\nfor verse in verses:\n for k in cluster:\n if k in verse:\n clusters[k] += 1\n else: print \"not in\"\n\n",
"Use defaultdict and rsplit (split from right)\nverses = [ \"0,1,0,0,0,0,0,0,0,1,1,No,cluster3\",\" 0,1,0,0,1,0,0,0,0,1,... | [
4,
1,
0
] | [] | [] | [
"counting",
"dictionary",
"python"
] | stackoverflow_0005615489_counting_dictionary_python.txt |
Q:
a question on using xhtml2pdf to parse css from website
I am trying to use xhtml2pdf to convert a webpage to pdf. After reading out the content of the webpage using urllib2, I found pisa.CreatePDF needs to process every link in the webpage content too. Especially, whenever it tried to parse .css file after I tried... | a question on using xhtml2pdf to parse css from website | I am trying to use xhtml2pdf to convert a webpage to pdf. After reading out the content of the webpage using urllib2, I found pisa.CreatePDF needs to process every link in the webpage content too. Especially, whenever it tried to parse .css file after I tried several websites, I got the following error:
pisa-3.0.33-py2... | [
"\npisa-3.0.33-py2.6.egg/sx/w3c/cssParser.py\", line 1020, in\n _parseExpressionTerm sx.w3c.cssParser.CSSParseError: Terminal function expression expected closing ')':: (u'Alpha(Opacity', u'=0);\n }\\n\\n\\n\\n.ui-state-')\n\nI think it was because it didn't recognize your css, which is alpha(opacity bla.. bla\nI... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0004494392_python.txt |
Q:
How can I call a function within a class?
I have this code which calculates the distance between two coordinates. The two functions are both within the same class.
However, how do I call the function distToPoint in the function isNear?
class Coordinates:
def distToPoint(self, p):
"""
Use pythag... | How can I call a function within a class? | I have this code which calculates the distance between two coordinates. The two functions are both within the same class.
However, how do I call the function distToPoint in the function isNear?
class Coordinates:
def distToPoint(self, p):
"""
Use pythagoras to find distance
(a^2 = b^2 + c^2)... | [
"Since these are member functions, call it as a member function on the instance, self.\ndef isNear(self, p):\n self.distToPoint(p)\n ...\n\n",
"That doesn't work because distToPoint is inside your class, so you need to prefix it with the classname if you want to refer to it, like this: classname.distToPoint... | [
576,
71
] | [] | [] | [
"call",
"class",
"function",
"python"
] | stackoverflow_0005615648_call_class_function_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.