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:
Can't parse JSON data structure in JavaScript
How do pass back values to a form that was posted to the server using Ajax?
In the view (shown below), I am just returning a simple data structure to test things:
def detail(request, widget_id):
widget = get_object_or_404(Widget, pk=widget_id)
if request.meth... | Can't parse JSON data structure in JavaScript | How do pass back values to a form that was posted to the server using Ajax?
In the view (shown below), I am just returning a simple data structure to test things:
def detail(request, widget_id):
widget = get_object_or_404(Widget, pk=widget_id)
if request.method == 'POST':
form = WidgetDetailsForm(requ... | [
"Because data is a string (of JSON) - note the output of your first alert().\nTry something like:\n$('#updateform').wl_Form({ \n onSuccess: function(response, status){\n var data = $.parseJSON(response); \n alert(data);\n alert(data.page);\n //...\n }\n});\n\n",
"Maybe do\ndata =... | [
2,
0
] | [] | [] | [
"django",
"javascript",
"json",
"python"
] | stackoverflow_0006799770_django_javascript_json_python.txt |
Q:
program of Recursion for Maximum Independent Set in a Graph
I am getting difficulty in writing a program for the above mentioned problem.. I have the following graph....
A-----B------C D
A is connected to B
B is connected to C
D is connected with no body!!
The maximum Independent set in this is {A,C, D}... ... | program of Recursion for Maximum Independent Set in a Graph | I am getting difficulty in writing a program for the above mentioned problem.. I have the following graph....
A-----B------C D
A is connected to B
B is connected to C
D is connected with no body!!
The maximum Independent set in this is {A,C, D}...
The Adjacency Matrix for the graph is below:-
I drew the follo... | [
"There is a well known and simple algorithm to solve this problem:\n\nInitially color all your vertices green.\nFind a green vertex. Color it's neighbors red.\nFor every red vertex, color it's green neighbors red. (Here's the recursion part)\nWhen there are no more red vertices with green neighbors, the set of red... | [
3,
0
] | [] | [] | [
"algorithm",
"c",
"c++",
"data_structures",
"python"
] | stackoverflow_0006798953_algorithm_c_c++_data_structures_python.txt |
Q:
Changing mp4ize.py to work on Windows
Mp4ize (python) is a utility for converting video files to mp4 for use on iPhone and iPod. I'm trying to get it to run on Windows.
The python script relies on the library fcntl, and according to another question ( fcntl substitute on Windows ), the Windows equivalent is win32... | Changing mp4ize.py to work on Windows | Mp4ize (python) is a utility for converting video files to mp4 for use on iPhone and iPod. I'm trying to get it to run on Windows.
The python script relies on the library fcntl, and according to another question ( fcntl substitute on Windows ), the Windows equivalent is win32api. The other question also says:
If you ... | [
"This command sets the NONBLOCK option of the standard error file descriptor. This lets it pass data through before the entirety of the data has been written to it.\nThe patch at http://pastebin.com/Zr5LN8Ui will work, with progress indicators, on Windows. However, it will sometimes report a bad encode even when th... | [
2
] | [] | [] | [
"fcntl",
"linux",
"python",
"winapi",
"windows"
] | stackoverflow_0006799693_fcntl_linux_python_winapi_windows.txt |
Q:
NameError: name 'process' is not defined (python)
I have a python script which looks like:
if options.benchmark == 'perlbench':
process = Mybench.perlbench
elif options.benchmark == 'bzip2':
process = Mybench.bzip2
elif options.benchmark == 'gcc':
process = Mybench.gcc
....
np = 1
....
for i ... | NameError: name 'process' is not defined (python) | I have a python script which looks like:
if options.benchmark == 'perlbench':
process = Mybench.perlbench
elif options.benchmark == 'bzip2':
process = Mybench.bzip2
elif options.benchmark == 'gcc':
process = Mybench.gcc
....
np = 1
....
for i in xrange(np):
...
system.cpu[i].workload... | [
"That means that your block\nif options.benchmark == 'perlbench':\n process = Mybench.perlbench\nelif options.benchmark == 'bzip2':\n process = Mybench.bzip2\nelif options.benchmark == 'gcc':\n process = Mybench.gcc\n\ndidn't match any of options.benchmark so the variable process was never assigned anyt... | [
3,
3
] | [] | [] | [
"nameerror",
"python"
] | stackoverflow_0006799983_nameerror_python.txt |
Q:
Python String Concatenation - concatenating '\n'
I am new to Python and need help trying to understand two problems i am getting relating to concatenating strings. I am aware that strings can be added to concatenate each other using + symbol like so.
>>> 'a' + 'b'
'ab'
However, i just recently found out you do no... | Python String Concatenation - concatenating '\n' | I am new to Python and need help trying to understand two problems i am getting relating to concatenating strings. I am aware that strings can be added to concatenate each other using + symbol like so.
>>> 'a' + 'b'
'ab'
However, i just recently found out you do not even need to use the + symbol to concatenate strings... | [
"When \"a\" \"b\" is turned into \"ab\", this ins't the same as concatenating the strings with +. When the Python source code is being read, adjacent strings are automatically joined for convenience. \nThis isn't a normal operation, which is why it isn't following the order of operations you expect for + and *.\npr... | [
17,
2,
1,
1
] | [] | [] | [
"concatenation",
"newline",
"python",
"repeater"
] | stackoverflow_0006800040_concatenation_newline_python_repeater.txt |
Q:
first web.py form doesn't work
Every time I try this the browser raises an error
app.py
import web
urls = (
'/hello','/file_upload_form','Index'
)
app = web.application(urls, globals())
render = web.template.render('templates/', base = "layout")
class Index(object):
def POST(self):
uploaded_file = w... | first web.py form doesn't work | Every time I try this the browser raises an error
app.py
import web
urls = (
'/hello','/file_upload_form','Index'
)
app = web.application(urls, globals())
render = web.template.render('templates/', base = "layout")
class Index(object):
def POST(self):
uploaded_file = web.input(uploaded_file_loc = 'file')... | [
"Error is caused by wrong urls param. I think it should be: \nurls = (\n '/hello', 'Index',\n '/file_upload_form','Index'\n)\n\nSee http://webpy.org/cookbook/url_handling:\n\nThe format of this tuple is: url-path-pattern, handler-class this pattern will repeat as more url patterns are defined.\n\nBy the wa... | [
4
] | [] | [] | [
"python",
"web.py"
] | stackoverflow_0006799824_python_web.py.txt |
Q:
Find lines beginning with same string and keep last occurance
I have this data:
E 71484666NC 1201011060240260 387802-1227810 1022 25 0 5 2 313D 0 1G5
E 71484666NC 1201011060240263 387902-1227910 1300 10 0 2 1 300D 0 1A5
E 10115693AK 1201011060617450 658160-1517007 021 10 0 896 71 4 ... | Find lines beginning with same string and keep last occurance | I have this data:
E 71484666NC 1201011060240260 387802-1227810 1022 25 0 5 2 313D 0 1G5
E 71484666NC 1201011060240263 387902-1227910 1300 10 0 2 1 300D 0 1A5
E 10115693AK 1201011060617450 658160-1517007 021 10 0 896 71 4 131L 2 AA2
E 10310002PR 0201011060102315 191509 -664820 39726 5 5... | [
"from collections import OrderedDict\n\nlines = OrderedDict()\nfor line in file:\n lines[line[0:12]] = line\n\nThis will preserve the order of the lines while eliminating duplicates.\nEdit: This version of OrderedDict works on Python 2.4, 2.5, and 2.6.\n",
"from collections import OrderedDict\n\nmydata = \"\"\... | [
4,
1,
0
] | [] | [] | [
"duplicates",
"ordereddictionary",
"python",
"search",
"text"
] | stackoverflow_0006800154_duplicates_ordereddictionary_python_search_text.txt |
Q:
regarding 20 scheduled jobs limit on GAE
Google App Engine does not allow us to schedule more than 20 cron jobs. I'm wondering if there is a way to schedule more jobs in a single go.
A:
Check out Google App Engine - Task Queues vs Cron Jobs.
It will give you some ideas for how you can replace some cron jobs wit... | regarding 20 scheduled jobs limit on GAE | Google App Engine does not allow us to schedule more than 20 cron jobs. I'm wondering if there is a way to schedule more jobs in a single go.
| [
"Check out Google App Engine - Task Queues vs Cron Jobs. \nIt will give you some ideas for how you can replace some cron jobs with tasks. This is the only way to do more things that are not user initiated, other than having multiple accounts that each do a separate thing.\n"
] | [
1
] | [] | [] | [
"cron",
"google_app_engine",
"python"
] | stackoverflow_0006800330_cron_google_app_engine_python.txt |
Q:
Progress Update Between Python and jQuery.ajax Call
I have two functions that I need to run, both take quite some time to complete. The second is dependent on the first, so they need to be in order. The first MUST be done with an ajax call to Python from JavaScript (using jquery.ajax). The second is some parsin... | Progress Update Between Python and jQuery.ajax Call | I have two functions that I need to run, both take quite some time to complete. The second is dependent on the first, so they need to be in order. The first MUST be done with an ajax call to Python from JavaScript (using jquery.ajax). The second is some parsing and HTML generation, so it can be done in either JavaSc... | [
"You can cut the python part in 2 functions and call first, then call 2nd when first is finished all with jQuery.ajax(...)\nOr use HTML5 Web Sockets to discuss with server...\n"
] | [
0
] | [] | [] | [
"javascript",
"progress",
"python"
] | stackoverflow_0006800641_javascript_progress_python.txt |
Q:
writing the calculated data into a file
Hello everyone,
I am implementing a cubic bezier curve for my project and I have to store the calculated control points in a file. I have to use the output file in gnuplot to view the curve. Following one of the posts here, I understood how to implement but I a... | writing the calculated data into a file | Hello everyone,
I am implementing a cubic bezier curve for my project and I have to store the calculated control points in a file. I have to use the output file in gnuplot to view the curve. Following one of the posts here, I understood how to implement but I am confused on how to get my output to a file.... | [
"f = open('somefile.dat', 'w+') opens (and creates) a file. With f.write() you can write a string to the file. In you case, you have to substitute the print call with the writecall:\nimport math\npoints = [(0,0), (5,0), (5,5), (10,5)]\nn = 20\nf = open('somefile.dat', 'w+')\n\nfor i in range(n) :\n\n u = i / flo... | [
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0006800861_python.txt |
Q:
Import django doesn't work? Pythonpath?
I'm running Windows with Python 2.7 and (I believe) Django 1.0. I installed Django using the Bitnami Djangostack. The strange thing is, when I typed "import django" in python, I got this error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
Import... | Import django doesn't work? Pythonpath? | I'm running Windows with Python 2.7 and (I believe) Django 1.0. I installed Django using the Bitnami Djangostack. The strange thing is, when I typed "import django" in python, I got this error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named django
I searched onl... | [
"It means that you need to install Django under Python 2.7 as well.\n",
"if you type the following at the command line what does it say? \npython --version\n\nMy guess is that bitnami installed into one python version and you are using another, or when they installed it they didn't put it in the pythonpath. I don... | [
3,
0
] | [] | [] | [
"django",
"python",
"pythonpath"
] | stackoverflow_0006800869_django_python_pythonpath.txt |
Q:
skip a parent loop from a loop inside for loop in python
Possible Duplicate:
Python: Continuing to next iteration in outer loop
Maybe the title is kind of confusing but you will understand what i mean in the code:
for item in items: #i want to skip one loop of this bucle
for i in item: #loop nº2
if ... | skip a parent loop from a loop inside for loop in python |
Possible Duplicate:
Python: Continuing to next iteration in outer loop
Maybe the title is kind of confusing but you will understand what i mean in the code:
for item in items: #i want to skip one loop of this bucle
for i in item: #loop nº2
if i==5:
continue #but this only skip a loop in nº2,... | [
"Set a flag, break out of the inner loop, check the flag in the main loop, and continue as appropriate.\n for i = 1 to N do\n flag = false\n for j = 1 to M do\n ...\n if condition then\n flag = true\n break\n ...\n if flag then continue\n ...\n\n"
] | [
4
] | [] | [] | [
"loops",
"python"
] | stackoverflow_0006801026_loops_python.txt |
Q:
Python: how to increment a ctypes POINTER instance
Assume p = ctypes.cast("foo", ctypes.POINTER(ctypes.c_char)).
Thus, we have p.contents.value == "f".
How can I directly access and manipulate (e.g. increment) the pointer? E.g. like (p + 1).contents.value == "o".
A:
You have to use indexing:
>>> p = ctypes.cast(... | Python: how to increment a ctypes POINTER instance | Assume p = ctypes.cast("foo", ctypes.POINTER(ctypes.c_char)).
Thus, we have p.contents.value == "f".
How can I directly access and manipulate (e.g. increment) the pointer? E.g. like (p + 1).contents.value == "o".
| [
"You have to use indexing:\n>>> p = ctypes.cast(\"foo\", ctypes.POINTER(ctypes.c_char))\n>>> p[0]\n'f'\n>>> p[1]\n'o'\n>>> p[3]\n'\\x00'\n\nHave a look at ctypes documentation to find out more about using pointers.\nUPDATE: It seems that it's not what you need. Let's, then, try another approach: first cast the poin... | [
8,
4
] | [] | [] | [
"ctypes",
"pointers",
"python"
] | stackoverflow_0006692185_ctypes_pointers_python.txt |
Q:
Fetching a simple list of entries
This should be a very basic question about backbone.js, I am a complete beginner in javascript/backbone.js, I have read several tutorials, but I do not manage to do a fairly simple task: "fetching a list of entries from a database".
The whole applications is on Google App Engine. ... | Fetching a simple list of entries | This should be a very basic question about backbone.js, I am a complete beginner in javascript/backbone.js, I have read several tutorials, but I do not manage to do a fairly simple task: "fetching a list of entries from a database".
The whole applications is on Google App Engine. The database already includes several e... | [
"If I understand your question correctly, you're trying to understand why Words isn't populated when you run Words.fetch(). I have a few questions for you:\n\nWhat is the value of WordList.url? It should be \"/words\" for your example.\nThe fetch method accepts success and error callbacks...\n\nThat means that you ... | [
1
] | [] | [] | [
"backbone.js",
"coffeescript",
"flask",
"google_app_engine",
"python"
] | stackoverflow_0006800595_backbone.js_coffeescript_flask_google_app_engine_python.txt |
Q:
How do I fix there is no such module error in python 2.6?
I've been using python 2.7 and after installation of python 2.7. All of the scripts have run successfully, but suddenly today, when I run python, it is recognized with python 2.6, so for one of the python packages I get the following error:
/Library/Framew... | How do I fix there is no such module error in python 2.6? | I've been using python 2.7 and after installation of python 2.7. All of the scripts have run successfully, but suddenly today, when I run python, it is recognized with python 2.6, so for one of the python packages I get the following error:
/Library/Frameworks/Python.framework/Versions/2.6/Resources/Python.app/Content... | [
"If your code relies on a particular version of Python, you should specify python2.7 or python2.6 instead of just python.\nIf this \"suddenly\" happened it's possible that installing some other software modified your $PATH so that the old version of Python now has priority (it's possible for multiple versions to be... | [
3,
0
] | [] | [] | [
"macos",
"python"
] | stackoverflow_0006801541_macos_python.txt |
Q:
Python fastcgi client
I'm writing a tool on python for monitoring fastcgi application. The only thing I need from fastcgi is to load ping and status pages (and return some kind of error if it fails).
There are a lot of libraries (from python-fasctgi bindings to twisted) which seems to be capable of this, but most ... | Python fastcgi client | I'm writing a tool on python for monitoring fastcgi application. The only thing I need from fastcgi is to load ping and status pages (and return some kind of error if it fails).
There are a lot of libraries (from python-fasctgi bindings to twisted) which seems to be capable of this, but most of them are simply overkill... | [
"Although flup is primarily used as a fastcgi server, it also includes a fastcgi client. \nhttp://hg.saddi.com/flup-server/file/tip/flup/client/fcgi_app.py\nIt appears to be a single file standalone implementation with no dependencies. It has a permissive license.\n"
] | [
6
] | [] | [] | [
"client",
"fastcgi",
"python"
] | stackoverflow_0006801673_client_fastcgi_python.txt |
Q:
Doesn't work django-localization
In settings:
USE_I18N = True
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware
.....
LANGUAGE_CODE = 'en_US'
django.mo compiled and has strings transla... | Doesn't work django-localization | In settings:
USE_I18N = True
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware
.....
LANGUAGE_CODE = 'en_US'
django.mo compiled and has strings translate.
I put django_language=ru in cookie... | [
"Are your string ins _() that are in english something that you added or is it from the default django install? If it is something you added you will need to build and compile your message files.\nHave you followed these instructions?\nhttps://docs.djangoproject.com/en/1.3/topics/i18n/localization/\n",
"Make sure... | [
0,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0006800752_django_python.txt |
Q:
How do I get the IDENTITY / AUTONUMBER value for the row I inserted in pymysql
Is possible to get ID for the row I inserted using pymysql?
curr = db.cursor()
curr.execute("INSERT INTO `accounts` (`name`, `password`) VALUES ('%s', '%s')", accName, passwd)
curr.execute("INSERT INTO `person` (`name`, `accoiunt_id`) V... | How do I get the IDENTITY / AUTONUMBER value for the row I inserted in pymysql | Is possible to get ID for the row I inserted using pymysql?
curr = db.cursor()
curr.execute("INSERT INTO `accounts` (`name`, `password`) VALUES ('%s', '%s')", accName, passwd)
curr.execute("INSERT INTO `person` (`name`, `accoiunt_id`) VALUES ('%s', '%d')", pName, HERE_I_NEED_ACCID)
There is autoincrement primary key "... | [
"You can use lastrowid property of your cursor object.\nOr you can execute SELECT LAST_INSERT_ID(), and fetch the result as scalar with fetchone()\n"
] | [
15
] | [] | [] | [
"mysql",
"python"
] | stackoverflow_0006802061_mysql_python.txt |
Q:
Python - From DST-adjusted local time to UTC
A specific bank has branches in all major cities in the world. They all open at 10:00 AM local time. If within a timezone that uses DST, then of course the local opening time also follows the DST-adjusted time. So how do I go from the local time to the utc time.
What I... | Python - From DST-adjusted local time to UTC | A specific bank has branches in all major cities in the world. They all open at 10:00 AM local time. If within a timezone that uses DST, then of course the local opening time also follows the DST-adjusted time. So how do I go from the local time to the utc time.
What I need is a function to_utc(localdt, tz) like this:... | [
"Using pytz, and in particular its localize method:\nimport pytz\nimport datetime as dt\n\ndef to_utc(localdt,tz):\n timezone=pytz.timezone(tz)\n utc=pytz.utc\n return timezone.localize(localdt).astimezone(utc)\n\nif __name__=='__main__':\n for tz in ('Europe/Berlin','Africa/Lagos'):\n for date i... | [
9,
1
] | [] | [] | [
"dst",
"python",
"pytz",
"timezone",
"utc"
] | stackoverflow_0006801429_dst_python_pytz_timezone_utc.txt |
Q:
Sorting containers in Python/numpy
I need to sort a special numpy array, in which blocks of size 19 constitute an element, using a user-defined function to determine the value of such a block.
The first attempt has been to wrap the array in a class and overload the [] operator:
class W:
def __init__(self, file... | Sorting containers in Python/numpy | I need to sort a special numpy array, in which blocks of size 19 constitute an element, using a user-defined function to determine the value of such a block.
The first attempt has been to wrap the array in a class and overload the [] operator:
class W:
def __init__(self, filename="nn.txt"):
self.nn = array(... | [
"have you tried sorted(u, key=average)? this would only calculate the average of each column once.\nif the size of the array is always divisible by 19 without remainder:\n>>> import numpy as np\n>>> n = 2\n>>> u = np.array([v for v in range(19*n)])\n\n>>> u = u.reshape(n,19)\n\n>>> sorted(c, key=np.average)\n\n[arr... | [
4
] | [] | [] | [
"numpy",
"python",
"sorting"
] | stackoverflow_0006802367_numpy_python_sorting.txt |
Q:
what does this do
This is a question Im trying to figure out for a job pre-interview questioniar. and i dont know python that well so im struggling with this problem.
the real questions for the job are big-o performance and making it better but i can do that i just need to understand this code
question A: in is_... | what does this do | This is a question Im trying to figure out for a job pre-interview questioniar. and i dont know python that well so im struggling with this problem.
the real questions for the job are big-o performance and making it better but i can do that i just need to understand this code
question A: in is_bar they compare the it... | [
"the function can be simplified to:\ndef foo(a, b):\n \"\"\" a and b are both lists \"\"\"\n return list(set(a)&set(b))\n\n",
"A: No. It compares each element of a to b. So if b is an element of a it returns True.\nB: Change based on the above.\nC: b is not an array. It's a dictionary (the b = {}).\n"
] | [
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0006802676_python.txt |
Q:
Is there any xml parsers that allow to add element by path in python
Is there any way to add to xml document a bunch of entries using "path" like this:
element = xmldoc.createElement("Work\\MainProject\\prj\\project.vcproj")
xmldoc.appendChild(element)
Which will automatically create all necessary entries in xml ... | Is there any xml parsers that allow to add element by path in python | Is there any way to add to xml document a bunch of entries using "path" like this:
element = xmldoc.createElement("Work\\MainProject\\prj\\project.vcproj")
xmldoc.appendChild(element)
Which will automatically create all necessary entries in xml file?
Thanks a lot,
Roman
| [
"I'm not sure if this is exactly what you are looking for (it's a bit unclear what \"all necessary entries\" means). Anyway, here is how you can create two kinds of XML hierarchies based on a \"path string\" using ElementTree (tested with Python 2.6). Note: minidom is not really necessary; it is only used for prett... | [
1
] | [] | [] | [
"parsing",
"path",
"python",
"xml"
] | stackoverflow_0006795467_parsing_path_python_xml.txt |
Q:
Why is reading a sqlite database slower on different machines with identical hardware?
Okay, so I'm observing some behavior that I would certainly call 'unexpected' and I'm curious if anyone can offer and insight as to what on earth is going on. I'll try to keep it concise...
I have a sqlite database that I'm acce... | Why is reading a sqlite database slower on different machines with identical hardware? | Okay, so I'm observing some behavior that I would certainly call 'unexpected' and I'm curious if anyone can offer and insight as to what on earth is going on. I'll try to keep it concise...
I have a sqlite database that I'm accessing with Python (150k rows, 11 tables) for the purposes of neural network training. The en... | [
"If you aren't running the databases with auto_vacuum=FULL, it could be that you have some fragmentation of the data structure in the database file. Have you tried to run VACUUM on your databases?\n",
"Is the filesystem itself also configured identically?\nAnd ext3 does fragment: superuser fragmentation\n"
] | [
2,
0
] | [] | [] | [
"neural_network",
"performance",
"python",
"sqlite"
] | stackoverflow_0006801248_neural_network_performance_python_sqlite.txt |
Q:
How to print a table from lists with different lengths in Python
How do I print a table from two lists that have varying lengths (each list being a column)?
Example:
>>> l1=['Cat', 'Dog', 'Gorilla', 'Ladybug']
>>> l2=['Cat', 'Dog']
>>> print_chart(l1, l2)
Cat Cat
Dog Dog
Gorilla
Ladybug
Using rjust ... | How to print a table from lists with different lengths in Python | How do I print a table from two lists that have varying lengths (each list being a column)?
Example:
>>> l1=['Cat', 'Dog', 'Gorilla', 'Ladybug']
>>> l2=['Cat', 'Dog']
>>> print_chart(l1, l2)
Cat Cat
Dog Dog
Gorilla
Ladybug
Using rjust may be useful.
| [
"Using itertools.izip_longest:\nfor a, b in izip_longest(l1, l2, fillvalue=''):\n print \"{0:20s}\\t{1:20s}\".format(a, b)\n\n"
] | [
6
] | [] | [] | [
"list",
"python",
"python_2.x"
] | stackoverflow_0006802877_list_python_python_2.x.txt |
Q:
Using BeautifulSoup to extract anchor tag values
I'm trying to use BeautifulSoup to extract values from a site. The values are essentially search results, in this case pharmacies in a particular region. The source of the page I'm trying to extract from contains the following HTML:
<a id="body_BusinessSearchResultS... | Using BeautifulSoup to extract anchor tag values | I'm trying to use BeautifulSoup to extract values from a site. The values are essentially search results, in this case pharmacies in a particular region. The source of the page I'm trying to extract from contains the following HTML:
<a id="body_BusinessSearchResultSummaryList_repBusinessList_lnkBusinessProfile_1" class... | [
"from BeautifulSoup import BeautifulSoup\n\ntxt = '''<a id=\"body_BusinessSearchResultSummaryList_repBusinessList_lnkBusinessProfile_1\" class=\"sr-item-link\" href=\"http://www.mocality.co.ke/b/natros-pharmacy/natrosoh/innercore/medical-services/_/_/0cfe6a11-7bee-41f8-8d2e-6a472557201f?skw=pharmacys&rcnt=10\">... | [
4,
0
] | [] | [] | [
"beautifulsoup",
"python"
] | stackoverflow_0006803034_beautifulsoup_python.txt |
Q:
Define the Cost of a single process
I am currently trying to come up with some business metrics related to how much my web application costs per customer. I know the price we pay per month for servers on amazon and can delimit the number of processes attached to that customer. However, some customers have extra da... | Define the Cost of a single process | I am currently trying to come up with some business metrics related to how much my web application costs per customer. I know the price we pay per month for servers on amazon and can delimit the number of processes attached to that customer. However, some customers have extra data which incurs extra database overhead, ... | [
"If it's your own Python code it is possible for each process to do it's own accounting. The process collects information about itself and submits to the database under the customer id.\nThe metric here what you are looking for is \"CPU time\" - how much the process has been using CPU. \nCPU Usage Per Process in Py... | [
1
] | [] | [] | [
"monitoring",
"python"
] | stackoverflow_0006801509_monitoring_python.txt |
Q:
Creating Anonymous Modules in Python
Edit: I've added some more info on why I'm looking to do this.
The example code below is purely for example purposes. In the end, I need to have my code walk over a directory structure, and when it finds a python file, import the file to grab data and possibly function definiti... | Creating Anonymous Modules in Python | Edit: I've added some more info on why I'm looking to do this.
The example code below is purely for example purposes. In the end, I need to have my code walk over a directory structure, and when it finds a python file, import the file to grab data and possibly function definitions from it. That will then be used when d... | [
"Mark, as I understand you wonder, if imp.load_source() can import a module with a name \"blah\" overwriting the previous import. Well, you can't do that via imp.load_source(), and here is the reason:\nTake a look at a part of Python's import.c source code:\nPyObject *\nPyImport_ExecCodeModuleEx(char *name, PyObjec... | [
6,
1
] | [] | [] | [
"python"
] | stackoverflow_0006802986_python.txt |
Q:
Python clist widget not returning expected list, returns only the first character of each item
I wrote a simple program to print out all non-hidden files and subdirectories in a given directory.
I am now trying to migrate my code into a clist widget example I found on Google. Other than ripping out some unneeded ... | Python clist widget not returning expected list, returns only the first character of each item | I wrote a simple program to print out all non-hidden files and subdirectories in a given directory.
I am now trying to migrate my code into a clist widget example I found on Google. Other than ripping out some unneeded buttons, all I changed was the top portion to integrate my code, and it partially works except that ... | [
"When you adding data to CList through append method, you must pass a sequence. Rewrite your code:\ndef button_add_clicked(self, data):\n dirList = os.listdir(\"/usr/bin\")\n for item in dirList: \n if not item.startswith('.'):\n data.append([item])\n data.sort()\n\nWhen you creating CList i... | [
2
] | [] | [] | [
"clist",
"list",
"pygtk",
"python",
"widget"
] | stackoverflow_0006801370_clist_list_pygtk_python_widget.txt |
Q:
Run __init__ after panel is created?
Is there a way, from a button to reinitialize a specific panel? I have a section of an app that looks for specific files in the OS and then creates some checkboxes and textctrls and then adds them to the sizer dynamically:
for db in numDB:
if xIndex >= 12:
... | Run __init__ after panel is created? | Is there a way, from a button to reinitialize a specific panel? I have a section of an app that looks for specific files in the OS and then creates some checkboxes and textctrls and then adds them to the sizer dynamically:
for db in numDB:
if xIndex >= 12:
pass
xIndex += 1
e... | [
"You're missing parentheses:\nself.__init__() # now, this is a method call\n\n",
"A simple solution is to have your __init__ do nothing but call another method, then you can call that method whenever you want:\ndef __init__(self, ...):\n super(...)\n self.initialize()\n\ndef initialize(self):\n <actual i... | [
2,
1
] | [] | [] | [
"init",
"python",
"wxpython"
] | stackoverflow_0006801949_init_python_wxpython.txt |
Q:
Python: Keyword to Links
I am building a blog on Google App Engine. I would like to convert some keywords in my blog posts to links, just like what you see in many WordPress blogs.
Here is one WP plugin which do the same thing:http://wordpress.org/extend/plugins/blog-mechanics-keyword-link-plugin-v01/
A plugin th... | Python: Keyword to Links | I am building a blog on Google App Engine. I would like to convert some keywords in my blog posts to links, just like what you see in many WordPress blogs.
Here is one WP plugin which do the same thing:http://wordpress.org/extend/plugins/blog-mechanics-keyword-link-plugin-v01/
A plugin that allows you to define keywor... | [
"This would probably be better suited to client-side code. You could easily modify a word highlighter to get the desired results. By keeping this client-side, you can avoid having to expire page caches when your 'tags' change.\nIf you really need it to be processed server-side, then you need to look at using re.sub... | [
1,
1
] | [] | [] | [
"google_app_engine",
"python",
"regex"
] | stackoverflow_0006799550_google_app_engine_python_regex.txt |
Q:
Txt file substitution in Python
I very new to programming and I have a simple problem that I just do not know the syntax to. I have a regular text file that I want to substitute all of the letters for numbers. i.e. if I find an "a" or an "A", I want to substitute the number "1". If I find a "b" or "B" I want to su... | Txt file substitution in Python | I very new to programming and I have a simple problem that I just do not know the syntax to. I have a regular text file that I want to substitute all of the letters for numbers. i.e. if I find an "a" or an "A", I want to substitute the number "1". If I find a "b" or "B" I want to substitute the number "2" ect. Can some... | [
"E.g.\nmappings = { \"a\" : \"1\", \"b\" : \"2\" }\n\nf = open(\"myfile.txt\")\nfor line in f:\n for oldc, newc in mappings.items():\n line = line.replace(oldc, newc)\n\n print line\n\n",
"Using translation tables, string.maketrans and s.translate:\nimport string\ntr_from = string.lowercase\n\n# r... | [
2,
2,
0
] | [] | [] | [
"parsing",
"python",
"text_files"
] | stackoverflow_0006803742_parsing_python_text_files.txt |
Q:
Why yield returns an iterator?
I'm trying to understand how yield works and after I had read this text I believed that it's quite understandable.
However I still don't understand what's the connection between yield and __iter__ because I've just found out that this code works:
class Vect():
def __init__(self, ... | Why yield returns an iterator? | I'm trying to understand how yield works and after I had read this text I believed that it's quite understandable.
However I still don't understand what's the connection between yield and __iter__ because I've just found out that this code works:
class Vect():
def __init__(self, *args):
self.__a = list(args... | [
"yield returns whatever object is passed to it, even if that object is a sequence or a generator or other iterator. Thus:\n>>> def g():\n... yield [1,2,3]\n... yield 1\n... yield 2\n... yield 3\n... \n>>> gen = g()\n>>> gen.next()\n[1, 2, 3]\n>>> gen.next()\n1\n>>> gen.next()\n2\n>>> gen.next()\n3\n... | [
9,
1,
1
] | [] | [] | [
"python",
"yield"
] | stackoverflow_0006803877_python_yield.txt |
Q:
Django version of Zend's Layouts?
Does Django have something like Zend's Layouts?
I use layouts in Zend a lot to provide the common elements of a website (I often call it the 'frame' around the content), e.g. the header, footer, etc. Then I render a view inside the layout to provide the custom content.
Is such a t... | Django version of Zend's Layouts? | Does Django have something like Zend's Layouts?
I use layouts in Zend a lot to provide the common elements of a website (I often call it the 'frame' around the content), e.g. the header, footer, etc. Then I render a view inside the layout to provide the custom content.
Is such a thing possible in Django?
| [
"I've never used Zend, but from the sounds of what you are asking, you can use Django's templates.\nBasically you are going to create a base.html template that has your 'frame' and you can have other templates inherit from that.\nYour base.html will look like\n<html>\n<head>\n<title>{% block title %}title{% endbloc... | [
2
] | [] | [] | [
"django",
"php",
"python",
"zend_framework"
] | stackoverflow_0006804051_django_php_python_zend_framework.txt |
Q:
Pygames import image from file Error:"couldn't open
hi guys im having problem in importing an image to my pygames script.
my code:
from gasp import*
begin_graphics(800,600,"My Game",color.GREEN)
Image("C:\Users\Yuvinng\Downloads\982960f3d1joong.jpg",(400,300), None, None)
end_graphics()
errors:
Traceback (most... | Pygames import image from file Error:"couldn't open | hi guys im having problem in importing an image to my pygames script.
my code:
from gasp import*
begin_graphics(800,600,"My Game",color.GREEN)
Image("C:\Users\Yuvinng\Downloads\982960f3d1joong.jpg",(400,300), None, None)
end_graphics()
errors:
Traceback (most recent call last):
File "C:\Python32\testing idle code... | [
"Does the file exist in the first place at the designated location? The error message says it cannot find it there. One of the good practices is to use raw string by prefixing the path with an r to prevent inadvertent escapes.\nImage(r\"C:\\Users\\Yuvinng\\Downloads\\982960f3d1joong.jpg\",(400,300), None, None)\n\n... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0006804183_python.txt |
Q:
what's the difference between "python scriptname.py" and just "scriptname.py"
what's the difference between "python scriptname.py" and just "scriptname.py"?
I meet the problem when using commands in Django, and this really confuse me
A:
You mean when executing those statements on the command line? The differenc... | what's the difference between "python scriptname.py" and just "scriptname.py" | what's the difference between "python scriptname.py" and just "scriptname.py"?
I meet the problem when using commands in Django, and this really confuse me
| [
"You mean when executing those statements on the command line? The difference is \"python scriptname.py\" explicitly invokes the program named \"python\" in your path (in Linux, typing \"which python\" will tell you where the program lives), wheras \"scriptname.py\" is just executing that file, feeding it to the s... | [
2
] | [] | [] | [
"python"
] | stackoverflow_0006804243_python.txt |
Q:
Txt Parsing in Python
I know this is an easy one but I am brand new to programming and any help would be greatly appreciated.
I have a text file that has a bunch of numbers in it (one per line). I need to open the file and split the number into three. If the number is "123456" i need to split it into "14","25","36... | Txt Parsing in Python | I know this is an easy one but I am brand new to programming and any help would be greatly appreciated.
I have a text file that has a bunch of numbers in it (one per line). I need to open the file and split the number into three. If the number is "123456" i need to split it into "14","25","36" in other words I need it ... | [
"One simple suggestion. Covert your number to a list and operate on the elements of the list.\n>>> list(\"123456\")\n['1', '2', '3', '4', '5', '6']\n>>> \n\nNow, it would much easier for you to handle. If not, then you should perhaps start with some Python tutorials.\n",
"This should satisfy your example:\ns = \"... | [
2,
1,
0
] | [] | [] | [
"parsing",
"python",
"text_files"
] | stackoverflow_0006804045_parsing_python_text_files.txt |
Q:
How to remove lines from stdout in python?
I have a program that grabs some data through ssh using paramiko:
ssh = paramiko.SSHClient()
ssh.connect(main.Server_IP, username=main.Username, password=main.Password)
ssh_stdin_host, ssh_stdout_host, ssh_stderr_host =ssh_session.exec_command(setting.GetHostData)
I wo... | How to remove lines from stdout in python? | I have a program that grabs some data through ssh using paramiko:
ssh = paramiko.SSHClient()
ssh.connect(main.Server_IP, username=main.Username, password=main.Password)
ssh_stdin_host, ssh_stdout_host, ssh_stderr_host =ssh_session.exec_command(setting.GetHostData)
I would like to remove the first 4 lines from ssh_st... | [
"How to remove lines from stdout in python?\n(this is a general answer for removing lines from the stdout Python console window, and has nothing to do with specific question involving paramiko, ssh etc)\nsee also: here and here\nInstead of using the print command or print() function, use sys.stdout.write(\"...\") c... | [
5,
2
] | [] | [] | [
"paramiko",
"python"
] | stackoverflow_0003732928_paramiko_python.txt |
Q:
How does one load data into the local Development Server using Python?
I know this is covered amply in the GAE help site. It's not working out for me. I'm a little green on Python. But I also know how imports work. The entities module is right there in the same folder with the loader. So what are the GAE scrip... | How does one load data into the local Development Server using Python? | I know this is covered amply in the GAE help site. It's not working out for me. I'm a little green on Python. But I also know how imports work. The entities module is right there in the same folder with the loader. So what are the GAE scripts doing?
Here's my loader:
from google.appengine.ext import db
from google... | [
"The traceback describes a ImportError: the module entities wasn't found. Is that where your models are? If so, you must be sure it can be found (add its directory to sys.path if needed).\n"
] | [
0
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0006803997_google_app_engine_python.txt |
Q:
Having Trouble Raising Exception for urllib2.urlopen()
I'm using the following code and I can't figure out why it's not raising an exception when the urlopen() is failing..
In my particular case, I know why it's failing.. My url's don't have http:// in front of them... but I want to catch those cases so the scrip... | Having Trouble Raising Exception for urllib2.urlopen() | I'm using the following code and I can't figure out why it's not raising an exception when the urlopen() is failing..
In my particular case, I know why it's failing.. My url's don't have http:// in front of them... but I want to catch those cases so the script can continue to run my code rather than exiting.
req =... | [
"From what you've pasted, it looks like you're catching the wrong type of exception. The code should say\ntry:\n url=urllib2.urlopen(req)\nexcept ValueError:\n # etc etc etc.\n\nIf it's critical that the entirety of your code run, you can also have a plain except: with an unspecified exception type, or even ... | [
6
] | [] | [] | [
"exception_handling",
"python",
"urllib2"
] | stackoverflow_0006804620_exception_handling_python_urllib2.txt |
Q:
How do you improve search?
I just got haystack with solr installed and created a custom view:
from haystack.query import SearchQuerySet
def post_search(request, template_name='search/search.html'):
getdata = request.GET.copy()
try:
results = SearchQuerySet().filter(title=getdata['search'])[:10]
... | How do you improve search? | I just got haystack with solr installed and created a custom view:
from haystack.query import SearchQuerySet
def post_search(request, template_name='search/search.html'):
getdata = request.GET.copy()
try:
results = SearchQuerySet().filter(title=getdata['search'])[:10]
except:
results = None
... | [
"When you use Haystack/Solr, the idea is that you have to tell Haystack/Solr what you want indexed for a particular object. So say you wanted to build a find as you type index for a basic dictionary. If you wanted it to just match prefixes, for the word Boston, you'd need to tell it to index B, Bo, Bos, etc. and th... | [
1
] | [] | [] | [
"django",
"django_haystack",
"python",
"search",
"solr"
] | stackoverflow_0006804536_django_django_haystack_python_search_solr.txt |
Q:
python module memory usage
I have this python module that imports many other modules. On monitoring the vm usage of the module, I see the usage continuously growing. I tried to go through the whole code and assigned None to the objects\variables whereever possible. But I suspect there still could be something that... | python module memory usage | I have this python module that imports many other modules. On monitoring the vm usage of the module, I see the usage continuously growing. I tried to go through the whole code and assigned None to the objects\variables whereever possible. But I suspect there still could be something that is not freeing up the memory. I... | [
"Check out How do I profile memory usage in Python? and Which Python memory profiler is recommended?. You need to dig into the docs, but those tools will allow you to breakdown memory usage by module.\n"
] | [
3
] | [] | [] | [
"memory",
"python"
] | stackoverflow_0006804493_memory_python.txt |
Q:
pyQt4 QGraphicsView on mouse event help needed
I have done a fair amount of searching for this problem, which is probably trivial. However I am new to pyQT and am completely stuck. Any help would be appreciated.
I simply want to place, move and draw objects on a QGraphicsView widget using QGraphicsScene.
The follo... | pyQt4 QGraphicsView on mouse event help needed | I have done a fair amount of searching for this problem, which is probably trivial. However I am new to pyQT and am completely stuck. Any help would be appreciated.
I simply want to place, move and draw objects on a QGraphicsView widget using QGraphicsScene.
The following code to handle mouse press events works, but it... | [
"Try extending QtGui.QGraphicsScene and using its mousePressEvent and the coordinates from scenePos(). Something like:\nclass QScene(QtGui.QGraphicsScene):\n def __init__(self, *args, **kwds):\n QtGui.QGraphicsScene.__init__(self, *args, **kwds)\n\n def mousePressEvent(self, ev):\n if ev.button(... | [
6
] | [] | [] | [
"pyqt",
"python",
"qt"
] | stackoverflow_0006804595_pyqt_python_qt.txt |
Q:
extract strings from a binary file in python
I have a project where I am given a file and i need to extract the strings from the file. Basically think of the "strings" command in linux but i'm doing this in python. The next condition is that the file is given to me as a stream (e.g. string) so the obvious answer o... | extract strings from a binary file in python | I have a project where I am given a file and i need to extract the strings from the file. Basically think of the "strings" command in linux but i'm doing this in python. The next condition is that the file is given to me as a stream (e.g. string) so the obvious answer of using one of the subprocess functions to run str... | [
"Of similar speed to David Wolever's, using re, Python's regular expression library. The short story of optimisation is that the less code you write, the faster it is. A library function that loops is often implemented in C and will be faster than you can hope to be. Same goes for the char in set() being faster tha... | [
9,
5
] | [] | [] | [
"python",
"string_search"
] | stackoverflow_0006804582_python_string_search.txt |
Q:
What are some examples of thread-unsafe Python code?
What are some examples of Python code that is not safe to run in a threaded environment? Examples need not be framework-related -- simple Python examples and caveats are preferred. Thanks!
A:
The following function may write to the file / overwrite the file in... | What are some examples of thread-unsafe Python code? | What are some examples of Python code that is not safe to run in a threaded environment? Examples need not be framework-related -- simple Python examples and caveats are preferred. Thanks!
| [
"The following function may write to the file / overwrite the file in an unpredictable way.\n import threading\n\n fp = open('f','w')\n\n def work1():\n for x in range(10000):\n fp.write('1')\n def work2():\n for x in range(10000):\n fp.write('2')\n\n t1 = threading.Thread(target = work1)\n ... | [
3
] | [] | [] | [
"python"
] | stackoverflow_0006804960_python.txt |
Q:
web.py script keeps saying, "'return' outside function"
Whenever I try to run this script with web.py I get the error message
<type 'exceptions.SyntaxError'> at /hello
'return' outside function (app.py, line 19)
Here is my source:
import web
urls = (
'/hello', 'Index',
'/file_upload_form', 'ThatFile'
)
app = web... | web.py script keeps saying, "'return' outside function" | Whenever I try to run this script with web.py I get the error message
<type 'exceptions.SyntaxError'> at /hello
'return' outside function (app.py, line 19)
Here is my source:
import web
urls = (
'/hello', 'Index',
'/file_upload_form', 'ThatFile'
)
app = web.application(urls, globals())
render = web.template.render('... | [
"Your code has mixed tabs and spaces, which is confusing Python. You can choose to use tabs, or you can choose to use spaces (PEP 8 recommends spaces), but you must be consistent.\nCheck your editor settings to see whether you can tell it to show you tabs and spaces differently (most editors can do this).\n"
] | [
3
] | [] | [] | [
"error_handling",
"python",
"web.py"
] | stackoverflow_0006805344_error_handling_python_web.py.txt |
Q:
"TypeError: 'type' object does not support item assignment" when trying to use dictionaries
This is a very basic snippet adder/viewer/remover. The way I want it to work, the user would enter a name (dictionary key) and then the text body (value of key), to add entries. For example- "Testsnippet" which is the key f... | "TypeError: 'type' object does not support item assignment" when trying to use dictionaries | This is a very basic snippet adder/viewer/remover. The way I want it to work, the user would enter a name (dictionary key) and then the text body (value of key), to add entries. For example- "Testsnippet" which is the key for the value "This is a test text snippet."
I don't know what's wrong with it. Trying to use the ... | [
"I think you meant clip_list[str(snippet_name)] wherever you wrote dict[str(snippet_name)]. But if all the keys and values are the same then you should be using a set instead.\n",
"I agree with Ignacio Vazquez-Abrams you should using your global dict clip_list.\nBTW: your action remove should modify too. \ndel cl... | [
1,
0,
0
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0006805371_dictionary_python.txt |
Q:
How do I update a dictionary value having the user choose the key to update and then the new value, in Python?
I am trying to write a program where my brother and I can enter and edit information from our football game rosters to compare teams and manage players, etc.
This is my first 'big' project i've tried.
I h... | How do I update a dictionary value having the user choose the key to update and then the new value, in Python? | I am trying to write a program where my brother and I can enter and edit information from our football game rosters to compare teams and manage players, etc.
This is my first 'big' project i've tried.
I have a nested dictionary inside a dictionary, I'm able to get the user to create the dictionaries etc. But when i t... | [
"The problems seems that after this line \nplayer = raw_input('which player? ')\n\nthe player will be the string, containing what the user have typed in, and not the dictionary, like player1. This explains, why Python fails to assign to its part. You can instead write like this:\nplayer = raw_input('which player? '... | [
2
] | [] | [] | [
"dictionary",
"python",
"raw_input"
] | stackoverflow_0006805640_dictionary_python_raw_input.txt |
Q:
"find . -regex ..." in Python or How to find files whose whole name (path + name) matches a regular expression?
I would like to find files whose whole name (relative, although absolute is nice too) matches a given regular expression (i.e., like the glob module, but for regex matches instead of shell wildcard match... | "find . -regex ..." in Python or How to find files whose whole name (path + name) matches a regular expression? | I would like to find files whose whole name (relative, although absolute is nice too) matches a given regular expression (i.e., like the glob module, but for regex matches instead of shell wildcard matches). Using find, one would do, for example:
find . -regex ./foo/\w+/bar/[0-9]+-\w+.dat
Of course, I could use find ... | [
"From help(os.walk):\n\nWhen topdown is true, the caller can modify the dirnames list in-place\n (e.g., via del or slice assignment), and walk will only recurse into\n the subdirectories whose names remain in dirnames; this can be used to\n prune the search...\n\nSo once a subdirectory (listed in dirnames) is de... | [
6,
1
] | [] | [] | [
"find",
"python",
"regex"
] | stackoverflow_0006798097_find_python_regex.txt |
Q:
Difference between loading time and running time in python?
I am quoting a part of Python documentation:
"A program doesn’t run any faster when it is read from a .pyc or .pyo file than when it is read from a .py file; the only thing that’s faster about .pyc or .pyo files is the speed with which they are loaded."
I... | Difference between loading time and running time in python? | I am quoting a part of Python documentation:
"A program doesn’t run any faster when it is read from a .pyc or .pyo file than when it is read from a .py file; the only thing that’s faster about .pyc or .pyo files is the speed with which they are loaded."
I don't understand what does it mean when it says it doesn't affec... | [
"When you import a module test.py, Python must read the source and convert it into the bytecode Python can execute. This takes time, but Python will store this in test.pyc. This Bytecode is the result of breaking your code down into simpler terms able to run directly on the CPython Virtual Machine.\nIf you load tes... | [
3,
2
] | [] | [] | [
"loading",
"module",
"python",
"time"
] | stackoverflow_0006803126_loading_module_python_time.txt |
Q:
Java analogous to Python os.path.expanduser / os.path.expandvars
Is there such a thing as Python's os.path.expanduser and os.path.expandvars (documentation) in Java?
If not, is there a library somewhere that does this?
A:
It's a shame that Java doesn't come with "batteries included" :(
import java.util.regex.Mat... | Java analogous to Python os.path.expanduser / os.path.expandvars | Is there such a thing as Python's os.path.expanduser and os.path.expandvars (documentation) in Java?
If not, is there a library somewhere that does this?
| [
"It's a shame that Java doesn't come with \"batteries included\" :(\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\npublic class Path {\n\n static Pattern pv=Pattern.compile(\"\\\\$\\\\{(\\\\w+)\\\\}\");\n\n /*\n * os.path.expanduser\n */\n public static String expanduser(Strin... | [
2,
1
] | [] | [] | [
"java",
"python"
] | stackoverflow_0006803913_java_python.txt |
Q:
FTP files default download path(python)
when i download a file from ftp in python using retrbinary where are the files downloaded by default.Is there a way to change this default folder?
thanx in advance
A:
The retrbinary function in the ftplib library takes a callback function that is called once for each block... | FTP files default download path(python) | when i download a file from ftp in python using retrbinary where are the files downloaded by default.Is there a way to change this default folder?
thanx in advance
| [
"The retrbinary function in the ftplib library takes a callback function that is called once for each block of data retrieved. You write this callback function yourself, and can therefore change the folder files are saved to.\nSome example code:\n#!/usr/bin/env python\n\nimport sys\nfrom ftplib import FTP\n\n\n\nft... | [
2
] | [] | [] | [
"ftp",
"python"
] | stackoverflow_0006805797_ftp_python.txt |
Q:
Python urllib2 cannot open localhost on alternate port (not 80)? Error 10013
Here is my server.py:
import BaseHTTPServer
import SocketServer
class TestRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
def do_GET(self):
self.wfile.write("hello world at %s" % __file__)
server = BaseHTTPServer.HTTP... | Python urllib2 cannot open localhost on alternate port (not 80)? Error 10013 | Here is my server.py:
import BaseHTTPServer
import SocketServer
class TestRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
def do_GET(self):
self.wfile.write("hello world at %s" % __file__)
server = BaseHTTPServer.HTTPServer(('', 10000), TestRequestHandler)
#server = SocketServer.ThreadingTCPServer(... | [
"The local firewall prevented the connection. When it's disabled, everything works.\n"
] | [
5
] | [] | [] | [
"error_handling",
"httplib",
"localhost",
"python",
"urllib2"
] | stackoverflow_0006805786_error_handling_httplib_localhost_python_urllib2.txt |
Q:
Replace Ctr+H copy row and change it
I need some help.
I have many rows in my text file with this :
invoke glVertex3f,-0.352848,0.081168,-0.123057
I want to copy each row before him and change glVertex3f with glColor3f.
The result will be like this:
invoke glColor3f,-0.352848,0.081168,-0.123057
invoke glVertex3f... | Replace Ctr+H copy row and change it | I need some help.
I have many rows in my text file with this :
invoke glVertex3f,-0.352848,0.081168,-0.123057
I want to copy each row before him and change glVertex3f with glColor3f.
The result will be like this:
invoke glColor3f,-0.352848,0.081168,-0.123057
invoke glVertex3f,-0.352848,0.081168,-0.123057
I want to ma... | [
"With Python 2.7/3.1+ you can do this:\nwith open('input.txt') as input, open('output.txt', 'w') as output:\n for line in input:\n output.write(line.replace('glVertex3f', 'glColor3f'))\n output.write(line)\n\nIn earlier versions would nest the with statements.\n"
] | [
3
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0006806224_python_regex.txt |
Q:
pexpect ssh not able to handle command options
am using pexpect ssh to write down a script for compilation, the ssh automation looks like this,
enter code here
child = ssh_expect('root', server2, cmd)
child.expect(pexpect.EOF)
print child.before
where cmd is this:
cmd = "./configure CFLAGS=\"-g -O0 -DDEBUG\""
th... | pexpect ssh not able to handle command options | am using pexpect ssh to write down a script for compilation, the ssh automation looks like this,
enter code here
child = ssh_expect('root', server2, cmd)
child.expect(pexpect.EOF)
print child.before
where cmd is this:
cmd = "./configure CFLAGS=\"-g -O0 -DDEBUG\""
the problem happens is that it says,
configure: error:... | [
"The reason it's working if you're doing commands.getoutput is that all commands there are run though a shell, which will parse your commandline and understand that what's between the double quotes after CFLAGS is part of the same parameter.\nWhen you're running cmds through pexpect, no shell is involved. Also, the... | [
0
] | [] | [] | [
"pexpect",
"python"
] | stackoverflow_0006805999_pexpect_python.txt |
Q:
Sharing settings\constants between Python projects
What would be a neat way to share configuration parameters\settings\constants between various projects in Python?
Using a DB seems like an overkill. Using a file raises the question of which project should host the file in its source control...
I'm open for sugges... | Sharing settings\constants between Python projects | What would be a neat way to share configuration parameters\settings\constants between various projects in Python?
Using a DB seems like an overkill. Using a file raises the question of which project should host the file in its source control...
I'm open for suggestions :)
UPDATE:
For clarification - assume the various ... | [
"I find that in many cases, using a configuration file is really worth the (minor) hassle. The builtin ConfigParser module is very handy, especially the fact that it's really easy to parse multiple files and let the module merge them together, with values in files parsed later overriding values from files parsed ea... | [
5,
3,
3,
2
] | [] | [] | [
"constants",
"projects",
"python"
] | stackoverflow_0006805977_constants_projects_python.txt |
Q:
Finding selected option in HTML page
How do I find the selected option in HTML page using python?
e.g. in the following example, how do I find the "BOB" string?
<select id="worker" name="worker">
<option value="Eve">EVE</option>
<option value="Bob" selected>BOB</option>
<option value="Alice">ALICE</option>
</selec... | Finding selected option in HTML page | How do I find the selected option in HTML page using python?
e.g. in the following example, how do I find the "BOB" string?
<select id="worker" name="worker">
<option value="Eve">EVE</option>
<option value="Bob" selected>BOB</option>
<option value="Alice">ALICE</option>
</select>
| [
"Let's suppose you are inside a python script and have all your HTML document inside a variable html. Most straightforward way would be like this:\nfrom xml.dom.minidom import parseString\ndom = parseString(html)\nfor element in dom.getElementsByTagName('option'):\n if element.getAttribute('selected'):\n #... | [
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0006805368_python.txt |
Q:
lxml.etree.iterparse closes input file handler?
filterous is using iterparse to parse a simple XML StringIO object in a unit test. However, when trying to access the StringIO object afterwards, Python exits with a "ValueError: I/O operation on closed file" message. According to the iterparse documentation, "Starti... | lxml.etree.iterparse closes input file handler? | filterous is using iterparse to parse a simple XML StringIO object in a unit test. However, when trying to access the StringIO object afterwards, Python exits with a "ValueError: I/O operation on closed file" message. According to the iterparse documentation, "Starting with lxml 2.3, the .close() method will also be ca... | [
"Seems to work fine with StringIO, try using that instead of cStringIO. No idea why it's getting closed.\n",
"Docs-fu is the problem. What you quoted \"Starting with lxml 2.3, the .close() method will also be called in the error case,\" is nothing to do with iterparse. It appears on your linked page before the se... | [
1,
0
] | [] | [] | [
"iterparse",
"python",
"stringio"
] | stackoverflow_0006806760_iterparse_python_stringio.txt |
Q:
How to: django template pass array and use it in javascript?
Ok so here is a problem,
I have an html template which looks something like this:
<script>
$(function() {
var vCountries = {{ visitedCountriesList }};
});
</script>
<..>
{{ visitedCountriesList }}
from server I pass an list to this... | How to: django template pass array and use it in javascript? | Ok so here is a problem,
I have an html template which looks something like this:
<script>
$(function() {
var vCountries = {{ visitedCountriesList }};
});
</script>
<..>
{{ visitedCountriesList }}
from server I pass an list to this item, but after rendering it looks like this:
<script>
$(func... | [
"The problem is the string representation of the array isn't valid JavaScript. The u' at the start is no good. This:\n[u'Afghanistan', u'Japan', u'United Arab Emirates']\n\nshould be this:\n['Afghanistan', 'Japan', 'United Arab Emirates']\n\nYou have two options. In the view function, encode it as JSON there there:... | [
8,
1
] | [] | [] | [
"django",
"google_app_engine",
"python",
"templates"
] | stackoverflow_0006806371_django_google_app_engine_python_templates.txt |
Q:
Time notation standard
I have the following script defining a tzinfo object:
import time
from datetime import datetime, timedelta, tzinfo
class ManilaTime(tzinfo):
def utcoffset(self, dt):
return timedelta(hours=8)
def tzname(self, dt):
return "Manila"
manila = ManilaTime()
Now, I'm going to say
t ... | Time notation standard | I have the following script defining a tzinfo object:
import time
from datetime import datetime, timedelta, tzinfo
class ManilaTime(tzinfo):
def utcoffset(self, dt):
return timedelta(hours=8)
def tzname(self, dt):
return "Manila"
manila = ManilaTime()
Now, I'm going to say
t = datetime(tzinfo=manila, *t... | [
"12:52:06+08:00 in general means it's the given time in a timezone 8 hours ahead of UTC. So B would be correct.\nHowever, you generated the time string incorrectly. time.gmtime() just returns a time, without any timezone, and you told datetime() that time was in the Manilla time zone. So for this particular case, A... | [
5
] | [] | [] | [
"python",
"timezone"
] | stackoverflow_0006806939_python_timezone.txt |
Q:
Python twisted - Need to go through all connections and find a client
I am trying to create a simple voucher program.
Client connects to server and asks if a voucher has time left on it, if yes the server responds with how much time.
I have control of the server and the clients, the client side is coded by me as w... | Python twisted - Need to go through all connections and find a client | I am trying to create a simple voucher program.
Client connects to server and asks if a voucher has time left on it, if yes the server responds with how much time.
I have control of the server and the clients, the client side is coded by me as well.
Right now this is what I have for my server side, the client side is s... | [
"If a voucher becomes \"in use\" when a client checks it and then becomes unused when the client disconnects, it sounds like you just need to keep a set of vouchers which you add to when the check is done and remove from when the client disconnects. You could keep this on the factory so it is shared between all cl... | [
6
] | [] | [] | [
"connection",
"python",
"twisted"
] | stackoverflow_0006797434_connection_python_twisted.txt |
Q:
Can I set user-defined variable in Python MySQLdb?
So My problem is this, I have a query that uses Mysql User-defined variable like:
@x:=0 SELECT @X:=@X+1 from some_table and this code returns a column from 1-1000.
However, this query doesn't work if I sent it through mySQLdb in Python.
connection =MySQLdb.Conne... | Can I set user-defined variable in Python MySQLdb? | So My problem is this, I have a query that uses Mysql User-defined variable like:
@x:=0 SELECT @X:=@X+1 from some_table and this code returns a column from 1-1000.
However, this query doesn't work if I sent it through mySQLdb in Python.
connection =MySQLdb.Connect(host='xxx',user='xxx',passwd='xxx',db = 'xxx')
cursor... | [
"Try to execute one query at a time:\ncursor.execute(\"SET @X:=0;\");\ncursor.execute(\"SELECT @X:=@X+1 FROM some_table\");\n\n",
"Try it as two queries.\nIf you want it to be one query, the examples in the comments to the MySQL User Variables documentation look like this:\nSELECT @rownum:=@rownum+1 rownum, t.* F... | [
10,
3
] | [] | [] | [
"database",
"mysql",
"python",
"sql"
] | stackoverflow_0006807219_database_mysql_python_sql.txt |
Q:
python array error
hello I am trying to load coordinates for plotting from a text file and I keep getting an error I don't understand. The coordinates look like this in the file (0.1, 0.0, 0.0),
(0.613125, 0.52202, 0.19919) Here is the code I am trying to run:
from visual import *
with open ('/Desktop/Coordlist... | python array error | hello I am trying to load coordinates for plotting from a text file and I keep getting an error I don't understand. The coordinates look like this in the file (0.1, 0.0, 0.0),
(0.613125, 0.52202, 0.19919) Here is the code I am trying to run:
from visual import *
with open ('/Desktop/Coordlist2.txt','r') as open_file... | [
"The problem is here:\nfor line in open_file.readlines():\n coords = line\n\nWhen you read a line from a file, you always get a string. You then have to process that string to produce whatever data structure you need. So if you have a line that looks like this (for example)\nl = '(5, 6, 7)'\n\nyou have to explic... | [
2,
2
] | [] | [] | [
"io",
"python",
"text_files",
"vpython"
] | stackoverflow_0006807300_io_python_text_files_vpython.txt |
Q:
How to execute python cgi script?
My server supports Python 2.7. It is located under /usr/bin/python2.7.
What do I have to take care of when trying to execute a cgi script ? I don't want to use Django or anything like that. I only want the script to be running and the text that was printed within the script to be ... | How to execute python cgi script? | My server supports Python 2.7. It is located under /usr/bin/python2.7.
What do I have to take care of when trying to execute a cgi script ? I don't want to use Django or anything like that. I only want the script to be running and the text that was printed within the script to be shown as it was an html file.
print """... | [
"To get a CGI script to run you have to setup your webserver to run the CGI scripts.\nIt pretty much depends on the server you are running:\nCGI and Apache explains the basics for CGI and apache.\nAnother good resource is probably the web programming guide in the python documentation:\nPython web programming\n"
] | [
2
] | [] | [] | [
"cgi",
"python"
] | stackoverflow_0006807824_cgi_python.txt |
Q:
Python Grahics from Linux CLI
I am anticipating the answer to be no, but I wanted to verify. If I write a Python program that was a GUI, can I launch that from a Linux CLI and still get the GUI? I am trying to build an embedded Linux system and I want to exclude everything that isn't necessary. This is a kiosk-lik... | Python Grahics from Linux CLI | I am anticipating the answer to be no, but I wanted to verify. If I write a Python program that was a GUI, can I launch that from a Linux CLI and still get the GUI? I am trying to build an embedded Linux system and I want to exclude everything that isn't necessary. This is a kiosk-like device, so all I need is my Pytho... | [
"Various widget toolkits (GTK+, Qt, etc.) can run on DirectFB instead of X11, which will allow you to have a GUI running on the Linux framebuffer device instead of requiring a full X server.\n",
"To run GUI anything on Linux you'll need an X server at a minimum.\nThere are curses based sorta-GUI libraries that as... | [
4,
0
] | [] | [] | [
"linux",
"python"
] | stackoverflow_0006807836_linux_python.txt |
Q:
python code completion in Emacs
I tried make PythonIDE using emacs like in this article http://www.enigmacurry.com/2009/01/21/autocompleteel-python-code-completion-in-emacs/ But emacs said me "auto-complete-mode not enabled". It is possible use emacs for python coding?
A:
You want to activate the auto-complete m... | python code completion in Emacs | I tried make PythonIDE using emacs like in this article http://www.enigmacurry.com/2009/01/21/autocompleteel-python-code-completion-in-emacs/ But emacs said me "auto-complete-mode not enabled". It is possible use emacs for python coding?
| [
"You want to activate the auto-complete mode in the context where you get that message, either\n\nevery time you open python files, by adding the following to your .emacs:\n(add-hook 'python-mode-hook\n (lambda ()\n (auto-complete-mode 1)))\n\nor when you open any file, by adding the following to your .ema... | [
5
] | [] | [] | [
"autocomplete",
"emacs",
"pymacs",
"python"
] | stackoverflow_0006806777_autocomplete_emacs_pymacs_python.txt |
Q:
error in configure mod_wsgi with Apache2.2
I am follow this http://pradyumnajoshi.wordpress.com/2009/06/09/setting-up-mod_wsgi-for-apache-and-django-on-windows/
I am using python2.6, Apache2.2, Django1.3 and mod_wsgi>3 on windows xp. now I have installed Apache correctly it is running well. and I have add the foll... | error in configure mod_wsgi with Apache2.2 | I am follow this http://pradyumnajoshi.wordpress.com/2009/06/09/setting-up-mod_wsgi-for-apache-and-django-on-windows/
I am using python2.6, Apache2.2, Django1.3 and mod_wsgi>3 on windows xp. now I have installed Apache correctly it is running well. and I have add the following line in httpd.conf file:-
LoadModule wsgi_... | [
"Whenever debugging Apache, the first place to check is the error and access logs. I've never used apache with Windows, but if you find logs, you'll get a much more descriptive error message.\nFYI, I believe it is normally recommended to make the wsgi_handler use a .wsgi extension (though I think this is probably b... | [
0,
0
] | [] | [] | [
"apache",
"django",
"mod_wsgi",
"python"
] | stackoverflow_0003701373_apache_django_mod_wsgi_python.txt |
Q:
Any working python mirrors?
Is there anywhere on the web where I can download files needed to setup Python development environment on windows? Trying to learn the language, but everything points to python.org which seems to be down for quite a while.
A:
You can still use the web.archive.org mirror of python.org.... | Any working python mirrors? | Is there anywhere on the web where I can download files needed to setup Python development environment on windows? Trying to learn the language, but everything points to python.org which seems to be down for quite a while.
| [
"You can still use the web.archive.org mirror of python.org.\nHere's a direct link to the Python 3.2.1 installer for windows. Don't forget to check the checksum (MD5: c148e89b97cd07352c42ecb3bb4f42e2).\n",
"ActivePython is a alternate Python distribution.\n",
"The mirror I linked before was an old copy. I don't... | [
4,
1,
0
] | [] | [] | [
"ide",
"python",
"windows"
] | stackoverflow_0006808365_ide_python_windows.txt |
Q:
Trying to connect Trac 0.12 (privately hosted) with GitHub
Any ideas on connecting GitHub with a locally hosted Trac 0.12 instance? We were thinking of using GitHub's email service hook to shoot off an email anytime GitHub is pushed to, which would fire off a script to have our local repo pull from GitHub, and als... | Trying to connect Trac 0.12 (privately hosted) with GitHub | Any ideas on connecting GitHub with a locally hosted Trac 0.12 instance? We were thinking of using GitHub's email service hook to shoot off an email anytime GitHub is pushed to, which would fire off a script to have our local repo pull from GitHub, and also tell Trac to re-sync the repo. Any ideas to improve on what we... | [
"You should use a webhook, not the email service.\nhttp://help.github.com/post-receive-hooks/\n",
"We were trying to avoid opening a port on on our firewall, so we thought an email might be easier than using the post-receive url service hook. If we had a publicly hosted Trac instance, we would definitely go the r... | [
0,
0
] | [] | [] | [
"git",
"github",
"python",
"trac"
] | stackoverflow_0006794100_git_github_python_trac.txt |
Q:
Apache mod_wsgi Django setup - Forbidden You don't have permission to access /mysite on this server
I have install python 26, Apache 2.2, modwsgi ap2.2 py26 On windows XP.
and apache loads modwsgi fine.
when I check localhost: apache says - It works!
but when i try to open the Django directory mysite: localhost/my... | Apache mod_wsgi Django setup - Forbidden You don't have permission to access /mysite on this server | I have install python 26, Apache 2.2, modwsgi ap2.2 py26 On windows XP.
and apache loads modwsgi fine.
when I check localhost: apache says - It works!
but when i try to open the Django directory mysite: localhost/mysite i
get :
Forbidden
You don't have permission to access /mysite on this server.
I have re-installed an... | [
"This configuration snippet is from Linux, not Windows, but (pathname differences aside) should be pretty representative of a good mod_wsgi configuration. Given the symptoms you've described, it sounds like you didn't get the directory permissions block for mysite.wsgi correct. In short, anyone you want to view a... | [
2,
0
] | [] | [] | [
"apache",
"django",
"mod_wsgi",
"python"
] | stackoverflow_0003777678_apache_django_mod_wsgi_python.txt |
Q:
Does python has methods similar to __setattr__ but for python class?
Currently __setattr__ only works for instance. Is there any similar method for class? I am asking this question because I want to collect the list of defined attribute in order when user define it in class as below:
class CfgObj(object):
_fie... | Does python has methods similar to __setattr__ but for python class? | Currently __setattr__ only works for instance. Is there any similar method for class? I am asking this question because I want to collect the list of defined attribute in order when user define it in class as below:
class CfgObj(object):
_fields = []
def __setattr__(self, name, value):
self._fields.appe... | [
"Yes, but that's not how you want to do it.\nclass MC(type):\n def __init__(cls, name, bases, dct):\n print dct\n super(MC, cls).__init__(name, bases, dct)\n\nclass C(object):\n __metaclass__ = MC\n foo = 42\n\n",
"If you define __setattr__() on the metaclass of a class, it will be called when setting a... | [
3,
3,
0
] | [] | [] | [
"python"
] | stackoverflow_0006808012_python.txt |
Q:
Deleting a super classes variable
I have this class which I need to inherit.
class AuthenticationForm(forms.Form):
username = forms.CharField(label=_("Username"), max_length=30)
password = forms.CharField(label=_("Password"), widget=forms.PasswordInput)
def __init__(self, request=None, *args, **kwargs... | Deleting a super classes variable | I have this class which I need to inherit.
class AuthenticationForm(forms.Form):
username = forms.CharField(label=_("Username"), max_length=30)
password = forms.CharField(label=_("Password"), widget=forms.PasswordInput)
def __init__(self, request=None, *args, **kwargs):
super(AuthenticationForm, se... | [
"Since this is Django, you can just remove it from the fields dict:\nclass LoginForm(…):\n def __init__(…):\n super(LoginForm, self).__init__(…)\n self.fields.pop('username')\n\n"
] | [
3
] | [] | [] | [
"inheritance",
"oop",
"python"
] | stackoverflow_0006809067_inheritance_oop_python.txt |
Q:
Python multiple if statements in a single if statement
How do I write the following in a single if statement:
if x != 5:
if y < 4:
statement
A:
if x != 5 and y < 4:
statement
| Python multiple if statements in a single if statement | How do I write the following in a single if statement:
if x != 5:
if y < 4:
statement
| [
"if x != 5 and y < 4:\n statement\n\n"
] | [
10
] | [] | [] | [
"if_statement",
"python"
] | stackoverflow_0006809190_if_statement_python.txt |
Q:
Best way to profile/optimize a website on Google App Engine
I'm currently trying to optimize my website, which is run on the Google App Engine. It's not an easy task, because I'm not using any powerful tool.
Does anyone have experience in optimizing Python code for this purpose?
Have you find a good Python profile... | Best way to profile/optimize a website on Google App Engine | I'm currently trying to optimize my website, which is run on the Google App Engine. It's not an easy task, because I'm not using any powerful tool.
Does anyone have experience in optimizing Python code for this purpose?
Have you find a good Python profiler?
| [
"I have found Gprof2Dot extremely useful. The output of the profiling modules I've tried as pretty unintuitive to interpret.\nGprof2Dot turns the cProfile output into a pretty looking graph, with the slowest chain(?) highlighted, and a bit of information on each function (function name, percentage of time spend on ... | [
13,
8,
3,
1
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0000679670_google_app_engine_python.txt |
Q:
Python: Store a num in Google App Engine
I am using Google App Engine Python.
I would like to store a simple variable number somewhere, so I can add, deduct and use this number.
examplenum=5
example+=1
Next time I use this examplenum, it wil become 6.
I know I can build a Model and add an IntegerProperty varible... | Python: Store a num in Google App Engine | I am using Google App Engine Python.
I would like to store a simple variable number somewhere, so I can add, deduct and use this number.
examplenum=5
example+=1
Next time I use this examplenum, it wil become 6.
I know I can build a Model and add an IntegerProperty varible. But I guess that would be too much hassle be... | [
"All the answers to the question you linked are relevent to you. If you want persistance you will have to create a model. Look at using get_or_insert to fetch/initialize an entity and give your entity a key_name so that you can keep fetching it easily whenever you need to store your values.\nclass MyAppData(db.Mode... | [
3
] | [] | [] | [
"google_app_engine",
"google_cloud_datastore",
"python"
] | stackoverflow_0006809128_google_app_engine_google_cloud_datastore_python.txt |
Q:
Manage class instancing on a global scope in python
I wish to control the time of instancing of a class MyClass, it needs to be unique and be able to reference it globally
# myclass.py
class MyClass():
def __init__(self):
pass
def hello(self):
return 'world'
class MyManager():
def __i... | Manage class instancing on a global scope in python | I wish to control the time of instancing of a class MyClass, it needs to be unique and be able to reference it globally
# myclass.py
class MyClass():
def __init__(self):
pass
def hello(self):
return 'world'
class MyManager():
def __init__(self):
self.instance = None
def create... | [
"You never actually call myclass.manager.create(), since you forgot the parens. Add them. You probably meant to call MyManager() and MyClass() as well, in order to instantiate them.\n"
] | [
3
] | [] | [] | [
"python"
] | stackoverflow_0006809304_python.txt |
Q:
Problem setting time.struct_time properties in Python
After I parsed a date in Python I need to patch it. But structure time.struct_time has read-only properties only:
parsed = time.strptime("23:59", "%H:%M")
parsed.tm_year = 2011
> TypeError: readonly attribute
How do I get a patched datetime value in a short & ... | Problem setting time.struct_time properties in Python | After I parsed a date in Python I need to patch it. But structure time.struct_time has read-only properties only:
parsed = time.strptime("23:59", "%H:%M")
parsed.tm_year = 2011
> TypeError: readonly attribute
How do I get a patched datetime value in a short & clever way?
| [
"Use datetime:\n>>> p = datetime.datetime.strptime(\"23:59\", \"%H:%M\")\n>>> p = p.replace(year=2011)\n>>> p\ndatetime.datetime(2011, 1, 1, 23, 59)\n\n"
] | [
2
] | [] | [] | [
"datetime",
"python"
] | stackoverflow_0006809558_datetime_python.txt |
Q:
C and Python - communicating with sockets
I'm trying to use UNIX domain sockets to communicate between a C program, and a Python script. The Python script sends data via UNIX domain sockets to the C program.
Here is the relevant code from my C program:
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#in... | C and Python - communicating with sockets | I'm trying to use UNIX domain sockets to communicate between a C program, and a Python script. The Python script sends data via UNIX domain sockets to the C program.
Here is the relevant code from my C program:
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/un.h>
#include <sys/types.h>
#includ... | [
"Looking at an example I found, it seems that the length you pass bind should not count the terminating or padding nulls in the sockaddr_un.\nTry:\nsize_t addrlen;\nconst char* sockname = \"/tmp/demo_socket\";\n\n/* ... */\n\naddress.sun_family = AF_UNIX;\nsnprintf(address.sun_path, UNIX_PATH_MAX, sockname);\naddrl... | [
2,
2
] | [] | [] | [
"c",
"dns",
"python",
"sockets",
"unix"
] | stackoverflow_0006809521_c_dns_python_sockets_unix.txt |
Q:
How to prevent the command line argument from being encoded?
(Problem solved, please see the updates)
I have some files that have incorrect filenames because of encoding issues. So I want to write a python script to process it. However, I encounter a strange problem.
To better illustrate, I will use an example: t... | How to prevent the command line argument from being encoded? | (Problem solved, please see the updates)
I have some files that have incorrect filenames because of encoding issues. So I want to write a python script to process it. However, I encounter a strange problem.
To better illustrate, I will use an example: the file name is displayed as ¹þÀï·ÑÇ.mp3.
However, the following... | [
"The problem is that MacOS X's default filesystem changes all filenames you give it to an unusual normalization form which does not use precomposed characters. The unicodedata Python module allows converting between these forms, for example:\nimport unicodedata\nprint len(unicodedata.normalize(\"NFD\", u\"\\u00C7\"... | [
3,
0
] | [] | [] | [
"character_encoding",
"command_line_arguments",
"encoding",
"python",
"shell"
] | stackoverflow_0006803621_character_encoding_command_line_arguments_encoding_python_shell.txt |
Q:
Storing a directed, weighted, complete graph in the GAE datastore
I have a directed, weighted, complete graph with 100 vertices. The vertices represent movies, and the edges represent preferences between two movies. Each time a user visits my site, I query a set of 5 vertices to show to the user (the set changes f... | Storing a directed, weighted, complete graph in the GAE datastore | I have a directed, weighted, complete graph with 100 vertices. The vertices represent movies, and the edges represent preferences between two movies. Each time a user visits my site, I query a set of 5 vertices to show to the user (the set changes frequently). Let's call these vertices A, B, C, D, E. The user orders th... | [
"I solved my own problem with a minor modification to the first design I suggested in my question.\nI learned about the key_name argument that lets me set my own key names. So every time I create a new edge, I pass in the following argument to the constructor:\nkey_name = vertex1.name + ' > ' + vertex2.name\n\nThen... | [
1
] | [] | [] | [
"google_app_engine",
"google_cloud_datastore",
"python"
] | stackoverflow_0006798490_google_app_engine_google_cloud_datastore_python.txt |
Q:
Python: ctypes pointer to local variables; how to ensure they don't get freed?
I have some code somewhat similar to this:
def castArgToCtype(arg, ctyp):
if issubclass(ctyp, _ctypes._Pointer): return createPtr(arg, ctyp)
return ctyp(arg)
def createPtr(arg, ctyp):
assert isinstance(arg, (list,tuple))
... | Python: ctypes pointer to local variables; how to ensure they don't get freed? | I have some code somewhat similar to this:
def castArgToCtype(arg, ctyp):
if issubclass(ctyp, _ctypes._Pointer): return createPtr(arg, ctyp)
return ctyp(arg)
def createPtr(arg, ctyp):
assert isinstance(arg, (list,tuple))
assert issubclass(ctyp, _ctypes._Pointer)
o = (ctyp._type_ * (len(arg) + 1))()... | [
"This seems to work:\nimport ctypes, _ctypes\n\ndef castArgToCtype(arg, ctyp):\n if issubclass(ctyp, _ctypes._Pointer): return createPtr(arg, ctyp)\n return ctyp(arg)\n\ndef createPtr(arg, ctyp):\n assert isinstance(arg, (list,tuple))\n assert issubclass(ctyp, _ctypes._Pointer)\n o = (ctyp._type_ * (... | [
1,
0
] | [] | [] | [
"ctypes",
"pointers",
"python"
] | stackoverflow_0006800664_ctypes_pointers_python.txt |
Q:
z-axis formatting in mplot3d
I am trying to make a surface plot in matplotlib, but I am unable to make the formatting of the z-axis look good. I want it to be on scientific notation, with the prefix along the axis and the exponent above the axis (like what you usually get in matlab). At the moment I can only get t... | z-axis formatting in mplot3d | I am trying to make a surface plot in matplotlib, but I am unable to make the formatting of the z-axis look good. I want it to be on scientific notation, with the prefix along the axis and the exponent above the axis (like what you usually get in matlab). At the moment I can only get the values without scientific notat... | [
"When you create your ScalarFormatter, try the \"use Math Text\" parameter:\nfrom matplotlib import ticker\nniceMathTextForm = ticker.ScalarFormatter(useMathText=True)\nax.w_zaxis.set_major_formatter(niceMathTextForm)\n\n"
] | [
4
] | [] | [] | [
"matplotlib",
"mplot3d",
"python"
] | stackoverflow_0006596583_matplotlib_mplot3d_python.txt |
Q:
Python error checking
I have code snippet below I would like to add error checking Like
"If p > 10000 dont append list with record,
How would I do this?
for line in idata.split("\r\n"):
if line == '':
continue
s, p, v, time = line.split(',')
try:
if isRecordValid... | Python error checking | I have code snippet below I would like to add error checking Like
"If p > 10000 dont append list with record,
How would I do this?
for line in idata.split("\r\n"):
if line == '':
continue
s, p, v, time = line.split(',')
try:
if isRecordValid(s,p,v,time):
... | [
"What about adding something in the isRecordValid method? Without knowing what the rest of it looks like, you could simple add this to start:\ndef isRecordValid(s, p, v, time):\n if p > 10000:\n return False\n ... \n # rest of existing method\n\n"
] | [
1
] | [] | [] | [
"error_checking",
"python"
] | stackoverflow_0006810191_error_checking_python.txt |
Q:
tkFileDialog filesave method not working
I have just started using Tkinter for a programming class and am having a bit of trouble using file dialog handlers. The fileopen and filesaveas methods work correctly, but the filesave method is not.
The specification requires that the filesave method should save to the l... | tkFileDialog filesave method not working | I have just started using Tkinter for a programming class and am having a bit of trouble using file dialog handlers. The fileopen and filesaveas methods work correctly, but the filesave method is not.
The specification requires that the filesave method should save to the last saved file; if no file has been saved, the... | [
"Pretty clear to me that your file handles self.lastopen and self.lastsave are set to some equivalent of False by the time you call filesave. Did you check that they persist after your fileopen and filesave functions exit? Pretty simple to debug this way, try:\nmy_man = FileMan()\nmy_man.fileopen()\nmy_man.filesave... | [
2,
2
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0006798312_python_tkinter.txt |
Q:
Where is function overriding done?
Where in the process of creating the program, compiler, linker etc., is the overriding of functions and operator overloading done?
I'm particularly interested where it is done in C++, Ruby and Python.
A:
Function overloading is (at least in C++) handled internally inside the co... | Where is function overriding done? | Where in the process of creating the program, compiler, linker etc., is the overriding of functions and operator overloading done?
I'm particularly interested where it is done in C++, Ruby and Python.
| [
"Function overloading is (at least in C++) handled internally inside the compiler. The idea is that the code that the compiler ultimately generates will be hardcoded to call the appropriate function, as if the functions all had different names and you called the function uniquely suited to the arguments. More gen... | [
4,
3,
0
] | [] | [] | [
"c++",
"overloading",
"overriding",
"python",
"ruby"
] | stackoverflow_0006809998_c++_overloading_overriding_python_ruby.txt |
Q:
Numpy: arr[...,0,:] works. But how do I store the data contained in the slice command (..., 0, :)?
In Numpy (and Python in general, I suppose), how does one store a slice-index, such as (...,0,:), in order to pass it around and apply it to various arrays? It would be nice to, say, be able to pass a slice-index to ... | Numpy: arr[...,0,:] works. But how do I store the data contained in the slice command (..., 0, :)? | In Numpy (and Python in general, I suppose), how does one store a slice-index, such as (...,0,:), in order to pass it around and apply it to various arrays? It would be nice to, say, be able to pass a slice-index to and from functions.
| [
"Python creates special objects out of the slice syntax, but only inside the square brackets for indexing. You can either create those objects by hand (in this case, (...,0,:) is (Ellipsis, 0, slice(None, None, None)), or you can create a little helper object:\nclass ExtendedSliceMaker(object):\n def __getitem__... | [
9,
5,
3,
3,
0
] | [] | [] | [
"indexing",
"numpy",
"python",
"slice"
] | stackoverflow_0006795657_indexing_numpy_python_slice.txt |
Q:
Regex Python / group quantifiers
I want to match a list of variables which look like directories, e.g.:
Same/Same2/Foot/Ankle/Joint/Actuator/Sensor/Temperature/Value=4.123
Same/Same2/Battery/Name=SomeString
Same/Same2/Home/Land/Some/More/Stuff=0.34
The length of the "subdirectories" is variable having an upper bo... | Regex Python / group quantifiers | I want to match a list of variables which look like directories, e.g.:
Same/Same2/Foot/Ankle/Joint/Actuator/Sensor/Temperature/Value=4.123
Same/Same2/Battery/Name=SomeString
Same/Same2/Home/Land/Some/More/Stuff=0.34
The length of the "subdirectories" is variable having an upper bound (above it's 9).
I want to group e... | [
"I probably misunderstood what exactly you want to do, but here is how you would do it without regex:\nfor entry in list_of_vars:\n key, value = entry.split('=')\n key_components = key.split('/')\n if 4 <= len(key_components) <= 8:\n # here the actual work is done\n print \"%s=%s\" % ('_'.joi... | [
2,
2,
1,
1
] | [] | [] | [
"python",
"quantifiers",
"regex",
"regex_group"
] | stackoverflow_0006806811_python_quantifiers_regex_regex_group.txt |
Q:
Storing/working with tags in mongodb for a document management system
So I am working on a pet project where I'm storing various text files. I have setup my app to save the tags as a string in one of my collections so an example would be:
tags: "Linux Apache WSGI"
Storing them and searching for them work just fine... | Storing/working with tags in mongodb for a document management system | So I am working on a pet project where I'm storing various text files. I have setup my app to save the tags as a string in one of my collections so an example would be:
tags: "Linux Apache WSGI"
Storing them and searching for them work just fine but my question comes when I want to do something like a tag cloud, count ... | [
"\nOr should I be storing them some other way?\n\nThe standard way to store tags is to store them as an array. In your case, the DB would look something like:\ntags: ['linux', 'apached', 'wsgi']\n\n\n... what is the best way to break them up to work with?\n\nThis is what Map/Reduce is designed for. This effectively... | [
6
] | [] | [] | [
"mongodb",
"pymongo",
"python"
] | stackoverflow_0006810440_mongodb_pymongo_python.txt |
Q:
Mixing python with a faster language for optimization in GAE
I'm a newbie in the Python and GAE world and I have a question.
With Python the normal approach is to only optimize the code when needed, fixing the more urgent bottlenecks.
And one of the ways to achieve that is by rewriting the most critical parts of t... | Mixing python with a faster language for optimization in GAE | I'm a newbie in the Python and GAE world and I have a question.
With Python the normal approach is to only optimize the code when needed, fixing the more urgent bottlenecks.
And one of the ways to achieve that is by rewriting the most critical parts of the program in C.
By using GAE are we losing this possibility forev... | [
"See Can I write parts of the Google App Engine code in Java, other parts in Python? for how to use multiple languages. \nBasically, each version of a given app can only use one runtime language. \nBut, you can have two different versions of your app, written in different languages, and they can pass information ba... | [
9,
5
] | [] | [] | [
"go",
"google_app_engine",
"java",
"performance",
"python"
] | stackoverflow_0006807119_go_google_app_engine_java_performance_python.txt |
Q:
numpy.poly1d , root-finding optimization, shifting polynom on x-axis
it is commonly an easy task to build an n-th order polynomial
and find the roots with numpy:
import numpy
f = numpy.poly1d([1,2,3])
print numpy.roots(f)
array([-1.+1.41421356j, -1.-1.41421356j])
However, suppose you want a polynomial of type:
f(... | numpy.poly1d , root-finding optimization, shifting polynom on x-axis | it is commonly an easy task to build an n-th order polynomial
and find the roots with numpy:
import numpy
f = numpy.poly1d([1,2,3])
print numpy.roots(f)
array([-1.+1.41421356j, -1.-1.41421356j])
However, suppose you want a polynomial of type:
f(x) = a*(x-x0)**0 + b(x-x0)**1 + ... + n(x-x0)**n
Is there a simple way to... | [
"First of all, surely you mean polynomial, not polygon?\nIn terms of providing an answer, are you using the same value of \"x0\" in all the terms? If so, let y = x - x0, solve for y and get x using x = y + x0.\nYou could even wrap it in a lambda function if you want. Say, you want to represent\nf(x) = 1 + 3(x-1) + ... | [
4,
3
] | [] | [] | [
"numpy",
"optimization",
"polygons",
"python",
"scipy"
] | stackoverflow_0006791159_numpy_optimization_polygons_python_scipy.txt |
Q:
How to Insert tags in texts
I have a text like that
Or like that
I want to insert tags into them:
<tag1>I have a text like that</tag1>
<tag1>Or like that</tag1>
how can I achieve this in python ?
A:
Sounds more like you want to insert text between tags. Right?
'<tag1>{0}</tag1>'.format('I have a text like that'... | How to Insert tags in texts | I have a text like that
Or like that
I want to insert tags into them:
<tag1>I have a text like that</tag1>
<tag1>Or like that</tag1>
how can I achieve this in python ?
| [
"Sounds more like you want to insert text between tags. Right?\n'<tag1>{0}</tag1>'.format('I have a text like that')\n\nIf it's a list of strings:\n>>> l = ['I have a text like that', 'Or like that']\n>>> ['<tag1>{0}</tag1>'.format(s) for s in l]\n['<tag1>I have a text like that</tag1>', '<tag1>Or like that</tag1>'... | [
1,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0006810752_python.txt |
Q:
Parsing hh:mm in Python
Sometimes I get a string like "02:40" indicating 2 hours and 40 minutes. I'd like to parse that string into the number of minutes (160 in this case) using Python.
Sure, I can parse the string and multiply the hours by 60, but is there something in the standard lib that does this?
A:
Perso... | Parsing hh:mm in Python | Sometimes I get a string like "02:40" indicating 2 hours and 40 minutes. I'd like to parse that string into the number of minutes (160 in this case) using Python.
Sure, I can parse the string and multiply the hours by 60, but is there something in the standard lib that does this?
| [
"Personally, I think simply parsing the string is far easier to read:\n>>> s = '02:40'\n>>> int(s[:-3]) * 60 + int(s[-2:])\n160\n\nNote that using negative indexing means it will handle strings without the leading zero on the hour:\n>>> s = '2:40'\n>>> int(s[:-3]) * 60 + int(s[-2:])\n160\n\nYou could also use the s... | [
10,
9,
4,
1,
0
] | [
"There is:\nfrom time import strptime\nfrom calendar import timegm\n\nT = '02:40'\nt = timegm(strptime('19700101'+T,'%Y%m%d%H:%M'))\nprint t\n\nBut is this really better than brute calculus ?\n.\nAn exotic solution, that doesn't need importing functions :\nT = '02:40'\nexec('x = %s' % T.replace(':','*60+'))\nprint ... | [
-3
] | [
"calendar",
"parsing",
"python"
] | stackoverflow_0006808064_calendar_parsing_python.txt |
Q:
How can I tidy up this file name cleaner?
I know there's a better way to do this, but I don't know what it is. I'm sorting through a list of files, and I would like to remove 'the usual suspects' so I can compare one list to another.
From what I understand, name.replace() look at each and every item in the listTo... | How can I tidy up this file name cleaner? | I know there's a better way to do this, but I don't know what it is. I'm sorting through a list of files, and I would like to remove 'the usual suspects' so I can compare one list to another.
From what I understand, name.replace() look at each and every item in the listToClean for the phrases I picked, and replace the... | [
"bad_names = ['1080p', '720p'] # and so on\nfor bad_name in bad_names:\n name = name.replace(bad_name, '')\n\nObviously, your declaration of words to clean from each name would happen at the top of the function, not for each iteration over the list of file names.\n",
"# do this once\nimport re\nbad_strings = [... | [
5,
1
] | [] | [] | [
"indexing",
"python"
] | stackoverflow_0006811076_indexing_python.txt |
Q:
simple setup.py seemingly broken
On Windows 7, running Python 2.7, python setup.py install installs python-money, but doesn't install the included money.django package.
The setup.py file can be found here. I've included it below for convenience:
import os
from setuptools import setup
def read(fname):
retu... | simple setup.py seemingly broken | On Windows 7, running Python 2.7, python setup.py install installs python-money, but doesn't install the included money.django package.
The setup.py file can be found here. I've included it below for convenience:
import os
from setuptools import setup
def read(fname):
return open(os.path.join(os.path.dirname(_... | [
"Use packages = find_packages(). It should automatically pick up your packages. You can even run find_packages() and copy-paste it's output into setup.py -- this way you'll know what you're doing wrong.\nhttp://peak.telecommunity.com/DevCenter/setuptools#using-find-packages\n"
] | [
1
] | [] | [] | [
"python",
"setup.py",
"setuptools"
] | stackoverflow_0006809891_python_setup.py_setuptools.txt |
Q:
Implementing Multicore Threading on this algorithm
I'm trying to find a way to make the following algorithm being processed on multiple cores, but I don't get on a good point. Using a locked iterator shared between multiple processes wouldn't be the most efficient way I think.
def sortCharset(set):
_set = ""
... | Implementing Multicore Threading on this algorithm | I'm trying to find a way to make the following algorithm being processed on multiple cores, but I don't get on a good point. Using a locked iterator shared between multiple processes wouldn't be the most efficient way I think.
def sortCharset(set):
_set = ""
for c in set:
if c not in _set:
_set += c
... | [
"The question isn't really about naming style or how to get a sorted set of characters out of a string.\nYou might want to look into the multiprocessing module. I'm pretty much a n00b w/r/t multi-core parallelism but got something working:\nimport multiprocessing, itertools\n\ndef stringForInt(args):\n num, char... | [
2
] | [] | [] | [
"multiprocess",
"python"
] | stackoverflow_0006809814_multiprocess_python.txt |
Q:
ReferenceProperty filter
I have a List kind, and an User kind. I'm currently using IntegerProperty to associate User IDs with Lists, but I want to switch to ReferenceProperty. Currently, I'm using this code (with IntegerProperty):
db.GqlQuery("SELECT * FROM List WHERE UserID = :1", userid)
How should the code wit... | ReferenceProperty filter | I have a List kind, and an User kind. I'm currently using IntegerProperty to associate User IDs with Lists, but I want to switch to ReferenceProperty. Currently, I'm using this code (with IntegerProperty):
db.GqlQuery("SELECT * FROM List WHERE UserID = :1", userid)
How should the code with ReferenceProperty look like?... | [
"First, you need to construct a key from your ID. You can do that like this (presuming your User entity has no parent):\nuser_key = db.Key.from_path('UserInfo', user_id)\n\nNow you can use it in a query just as you would anything else:\ndb.GqlQuery(\"SELECT * FROM List WHERE user_key = :1\", user_key)\n\nOr equival... | [
3,
1
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0006790850_google_app_engine_python.txt |
Q:
how to install pycairo for python 3 on Ubuntu 10.04
i am trying to install pycairo 1.10.0 for use with my custom-build python 3.1. however,
sudo /flower/bin/easy_install-3.1 pycairo
fails with
XXX@XXXX:/adventures$ sudo /flower/bin/easy_install-3.1 pycairo
install_dir /flower/lib/python3.1/site-packages/
Searchi... | how to install pycairo for python 3 on Ubuntu 10.04 | i am trying to install pycairo 1.10.0 for use with my custom-build python 3.1. however,
sudo /flower/bin/easy_install-3.1 pycairo
fails with
XXX@XXXX:/adventures$ sudo /flower/bin/easy_install-3.1 pycairo
install_dir /flower/lib/python3.1/site-packages/
Searching for pycairo
Reading http://pypi.python.org/simple/pyca... | [
"By looking at the python.py file in that subdir I decided to try setting an environment var before executing the waf thru python3:\nexport PYTHON=\"python3\"\nAnd then the install mysteriously succeeded...\n",
"I'm using Ubuntu Karmic, but installing with python2.7 compiled from source, so this is a work around ... | [
10,
4,
2
] | [] | [] | [
"cairo",
"pycairo",
"python",
"python_3.x",
"ubuntu_10.04"
] | stackoverflow_0006232529_cairo_pycairo_python_python_3.x_ubuntu_10.04.txt |
Q:
Find a way to add a string to a tuple
y="Peter Email: peter@rp.com Phone: 91291212"
z="Alan Email: alan@rp.com Phone: 98884444"
w="John Email: john@rp.com Phone: 93335555"
add_book=str(y) ,"" + str(z) ,"" + str(w)
**I am trying to add a contact into my address book but I am not sure how to add the string "details... | Find a way to add a string to a tuple | y="Peter Email: peter@rp.com Phone: 91291212"
z="Alan Email: alan@rp.com Phone: 98884444"
w="John Email: john@rp.com Phone: 93335555"
add_book=str(y) ,"" + str(z) ,"" + str(w)
**I am trying to add a contact into my address book but I am not sure how to add the string "details" into the add_book. I also found that I ca... | [
"firstly [] is a list. a tuple is (,);\nso what you want is \naddress_book['Alan'] = ('alan@rp.com', '91234567')\n\nBut this seems quite odd. What i would do is create a class\nclass Contact(object):\n name = \"Contact Name\"\n email = \"Contact Email\"\n ph_number = \"00000000\"\n\n def __str__(self):\... | [
2,
2
] | [] | [] | [
"append",
"dictionary",
"python",
"string",
"tuples"
] | stackoverflow_0006811894_append_dictionary_python_string_tuples.txt |
Q:
Qt designer: Custom code for custom actions
I've been looking around and I didn't found anything yet, except old doc for Qt3 with version 3.x of qt designer.
I'll leave an example, not that I can't give code as my project is GPL but for simplicity.
Example: You are designing a GUI for your application. You insert ... | Qt designer: Custom code for custom actions | I've been looking around and I didn't found anything yet, except old doc for Qt3 with version 3.x of qt designer.
I'll leave an example, not that I can't give code as my project is GPL but for simplicity.
Example: You are designing a GUI for your application. You insert some buttons in the GUI, and you want those butto... | [
"You don't need to create a header file or modify the pyuic generated file. Assuming your action object is named myaction and you want to signal myaction_slot when it's toggled:\nimport sys\nfrom PyQt4 import QtCore, QtGui\n\n# import pyuic generated user interface file\nfrom ui_mainwindow import Ui_MainWindow\n\nc... | [
7
] | [] | [] | [
"designer",
"pyqt",
"python",
"signals_slots"
] | stackoverflow_0006811532_designer_pyqt_python_signals_slots.txt |
Q:
How do I iterate over a SQLite database using the Python API?
Basically I want to be able to choose an amount of numbers using for x...in range(y amount of numbers) and inject them into an SQLite database. However I receive the following error:
line 17, in <module>
values (?)""") (number)
sqlite3.ProgrammingError:... | How do I iterate over a SQLite database using the Python API? | Basically I want to be able to choose an amount of numbers using for x...in range(y amount of numbers) and inject them into an SQLite database. However I receive the following error:
line 17, in <module>
values (?)""") (number)
sqlite3.ProgrammingError: Incorrect number of bindings supplied.
The current statement uses... | [
"execute takes a tuple of values in the case of \"?\" parameters, so you need to write:\nc.execute(\"\"\"insert into numbers values (?)\"\"\", (number,))\n\n(number,) is a way to define a tuple with one element.\nAnd by the way, you can do this more efficiently using the executemany method:\nc.executemany(\n \"\... | [
1,
0
] | [] | [] | [
"python",
"sql"
] | stackoverflow_0006811860_python_sql.txt |
Q:
numpy array access
I need to create a numpy array of N elements, but I want to access the
array with an offset Noff, i.e. the first element should be at Noff and
not at 0. In C this is simple to do with some simple pointer arithmetic, i.e.
I malloc the array and then define a pointer and shift it appropriately.
Fu... | numpy array access | I need to create a numpy array of N elements, but I want to access the
array with an offset Noff, i.e. the first element should be at Noff and
not at 0. In C this is simple to do with some simple pointer arithmetic, i.e.
I malloc the array and then define a pointer and shift it appropriately.
Furthermore, I do not want... | [
"Use A[n-offset]. this turns offset to offset+len(A) into 0 to len(A).\n",
"I would be very cautious about over-riding the [] operator through the __getitem__() method. Although it will be fine with your own code, I can easily imagine that when the array gets passed to an arbitrary library function, you could get... | [
2,
2,
1
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0006800534_numpy_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.