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:
Sorting a string in array, making it sparsely populated
For example, say I have string like:
duck duck duck duck goose goose goose dog
And I want it to be as sparsely populated as possible, say in this case
duck goose duck goose dog duck goose duck
What sort of algorithm would you recommend? Snippets of code or... | Sorting a string in array, making it sparsely populated | For example, say I have string like:
duck duck duck duck goose goose goose dog
And I want it to be as sparsely populated as possible, say in this case
duck goose duck goose dog duck goose duck
What sort of algorithm would you recommend? Snippets of code or general pointers would be useful, languages welcome Python, ... | [
"I would sort the array by number of duplicates, starting from the most duplicated element, spread those elements as far apart as possible\nin your example, duck is duplicated 4 times, so duck will be put in position n*8/4 for n from 0 to 3 inclusive.\nThen put the next most repeated one (goose) in positions n*8/3 ... | [
5,
3,
2,
2,
1,
1
] | [] | [] | [
"algorithm",
"bash",
"c++",
"python"
] | stackoverflow_0002897067_algorithm_bash_c++_python.txt |
Q:
How to connect to a LDAP server using a p12 certificate
I want to connect to a LDAP server using a .p12 certificate instead of using a username and password. The Java solution for this looks like
String ldapURL = "ldaps://"+host+":"+port;
System.setProperty("javax.net.ssl.keyStoreType", "PKCS12" );
System.se... | How to connect to a LDAP server using a p12 certificate | I want to connect to a LDAP server using a .p12 certificate instead of using a username and password. The Java solution for this looks like
String ldapURL = "ldaps://"+host+":"+port;
System.setProperty("javax.net.ssl.keyStoreType", "PKCS12" );
System.setProperty("javax.net.ssl.keyStore",keystore);
System.setPrope... | [
"If you use python-ldap, you can use the TLS options to set these parameters.\nldap.set_option(ldap.OPT_X_TLS_CACERTFILE, \"/path/to/trustedcerts.pem\")\nldap.set_option(ldap.OPT_X_TLS_CERTFILE, \"/path/to/usercert.pem\")\nldap.set_option(ldap.OPT_X_TLS_KEYFILE, \"/path/to/user.key.pem\")\n\nds = ldap.initialize(\"... | [
2,
0
] | [] | [] | [
"certificate",
"ldap",
"pkcs#12",
"python"
] | stackoverflow_0002193362_certificate_ldap_pkcs#12_python.txt |
Q:
What methods and tools do you use to design and analyze the workflow in a web application (for a tiny team)
Note: I use TRAC integrated with SVN, framework testing tools, an excellent mixture of staging servers, development servers, and other tools to speed development and keep track of tasks.
I am asking about th... | What methods and tools do you use to design and analyze the workflow in a web application (for a tiny team) | Note: I use TRAC integrated with SVN, framework testing tools, an excellent mixture of staging servers, development servers, and other tools to speed development and keep track of tasks.
I am asking about the specific process of design, and even more specifically, the design of functionality and flow in a web applicati... | [
"Another mainly solo developer here. I recommend using a bug/issue tracker. I use TRAC (although I'm looking at alternatives). It might seem strange, since you're the one creating, assigning, and closing all tickets, but it really helps to plan out/prioritize development. I also use the wiki to organize my thoughts... | [
1,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0003081412_python.txt |
Q:
Portable version of pyCrypto? - Python
does a portable version of pyCrypto exist? would one be easy to create?
Help would be awesome!
A:
I still don't quite understand what you mean by portable or by using a "drag and drop" folder. But pre-built binaries for Windows can be found here.
| Portable version of pyCrypto? - Python | does a portable version of pyCrypto exist? would one be easy to create?
Help would be awesome!
| [
"I still don't quite understand what you mean by portable or by using a \"drag and drop\" folder. But pre-built binaries for Windows can be found here.\n"
] | [
1
] | [] | [] | [
"aes",
"django",
"portability",
"pycrypto",
"python"
] | stackoverflow_0003084142_aes_django_portability_pycrypto_python.txt |
Q:
python apt-get list upgrades
How can I get a list of upgrade packages available and write it to file using python?
When I run apt-get upgrade > output
it works in bash. I think I have to send the trap signal (Ctrl+C) in the python program.
Any suggestions on how to achieve this?
I tried this on the code now:
#!/... | python apt-get list upgrades | How can I get a list of upgrade packages available and write it to file using python?
When I run apt-get upgrade > output
it works in bash. I think I have to send the trap signal (Ctrl+C) in the python program.
Any suggestions on how to achieve this?
I tried this on the code now:
#!/usr/bin/env python
import subproce... | [
"Why not use the python-apt module eg.\nimport apt\ncache=apt.Cache()\ncache.update()\ncache.open(None)\ncache.upgrade()\nfor pkg in cache.getChanges():\n print pkg.sourcePackageName, pkg.isUpgradeable\n\nalso read the link in badp's comment\n",
"Use the Python module subprocess and close stdin to tell the chi... | [
3,
2,
0
] | [] | [] | [
"apt_get",
"python"
] | stackoverflow_0003092613_apt_get_python.txt |
Q:
growing python process memory over time
My python code process memory increases dynamically as it stores dynamic data in list, dictionary and tuples wherever necessary. Though all those dynamic data is cleared physically in their variables after then, the memory is not shooting down.
Hence i felt like there is a ... | growing python process memory over time | My python code process memory increases dynamically as it stores dynamic data in list, dictionary and tuples wherever necessary. Though all those dynamic data is cleared physically in their variables after then, the memory is not shooting down.
Hence i felt like there is a memory leak and i used gc.collect() method to... | [
"It's very hard, in general, for a process to \"give memory back to the OS\" (until the process terminates and the OS gets back all the memory, of course) because (in most implementation) what malloc returns is carved out of big blocks for efficiency, but the whole block can't be given back if any part of it is sti... | [
10,
0
] | [] | [] | [
"memory_management",
"python"
] | stackoverflow_0003097236_memory_management_python.txt |
Q:
How do I get the page content from PAMIE?
I'm using PAMIE to control IE to automatically browse to a list of URLs. I want to find which URLs return IE's malware warning and which ones don't. I'm new to PAMIE, and PAMIE's documentation is non-existent or cryptic at best. How can I get a page's content from PAMIE so... | How do I get the page content from PAMIE? | I'm using PAMIE to control IE to automatically browse to a list of URLs. I want to find which URLs return IE's malware warning and which ones don't. I'm new to PAMIE, and PAMIE's documentation is non-existent or cryptic at best. How can I get a page's content from PAMIE so I can work with it in Python?
| [
"Browsing the CPamie.py file did the trick. Turns out, I didn't even need the page content - PAMIE's findText method lets you match any string on the page. Works great!\n"
] | [
0
] | [] | [] | [
"pamie",
"python"
] | stackoverflow_0003073151_pamie_python.txt |
Q:
Waiting on event with Twisted and PB
I have a python app that uses multiple threads and I am curious about the best way to wait for something in python without burning cpu or locking the GIL.
my app uses twisted and I spawn a thread to run a long operation so I do not stomp on the reactor thread. This long operat... | Waiting on event with Twisted and PB | I have a python app that uses multiple threads and I am curious about the best way to wait for something in python without burning cpu or locking the GIL.
my app uses twisted and I spawn a thread to run a long operation so I do not stomp on the reactor thread. This long operation also spawns some threads using twisted... | [
"If you're already using Twisted, you should never need to \"wait\" like this.\nAs you've described it:\n\nI spawn a thread to run a long operation ... This long operation also spawns some threads using twisted's deferToThread ...\n\nThat implies that you're calling deferToThread from your \"long operation\" threa... | [
13,
5,
5,
2,
1
] | [] | [] | [
"multithreading",
"python",
"twisted"
] | stackoverflow_0003096241_multithreading_python_twisted.txt |
Q:
need help sending command to server by ssh python
I am trying to connect to the server via ssh and dump the "df- h" output in some text file.
p=pexpect.spawn('ssh some.some.com')
i=p.expect([ssh_newkey,'password:',pexpect.EOF])
if i==0:
print "I say yes"
p.sendline('yes')
i=p.expect([ssh_newkey,'passw... | need help sending command to server by ssh python | I am trying to connect to the server via ssh and dump the "df- h" output in some text file.
p=pexpect.spawn('ssh some.some.com')
i=p.expect([ssh_newkey,'password:',pexpect.EOF])
if i==0:
print "I say yes"
p.sendline('yes')
i=p.expect([ssh_newkey,'password:',pexpect.EOF])
if i==1:
p.sendline("somesome")... | [
"You probably want to use paramiko to manage operations over an SSH connection.\n",
"\nMy problem is i = p.sendline('df -h >\n /home/test/output.txt') is not doing\n anything\n\nIsn't it setting i to 29? Is that what you mean?\n\nBasically my output file is empty.\n\nHow do you know that? Nothing in this code... | [
3,
1,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0003096938_python.txt |
Q:
Most efficient way to sort/categories objects in list based on object attribute
I have an unsorted list of objects that each have a end_date attribute.
The list just looks like [obj1, obj2, obj3, <...>] in no specific order.
I want to end up with a list that looks like this:
[["Saturday, May 5", [obj3, obj5]], ... | Most efficient way to sort/categories objects in list based on object attribute | I have an unsorted list of objects that each have a end_date attribute.
The list just looks like [obj1, obj2, obj3, <...>] in no specific order.
I want to end up with a list that looks like this:
[["Saturday, May 5", [obj3, obj5]], ["Monday, May 7", [obj1, obj8, obj9]] ... etc ]
Basically just a list of lists, where... | [
"itertools.groupby(sorted(L, key=operator.attrgetter('end_date')),\n key=operator.attrgetter('end_date'))\n\n",
"You said you know how to get it to a dict. So, just sort the results:\nd = ToDict(...)\nsorted_values = sorted(((date,list) for date,list in d.iteritems()))\n\nShould be O(n log n)\nYou can provide a... | [
1,
0,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0003098485_django_python.txt |
Q:
date library, capable of calculating things like "every third tuesday"?
I'd like to find a library or command that given input like "every third tuesday" will provide a list of dates such as (2010-06-15, 2010-07-20, 2010-08-17), etc.
Something that can be called from python, unix command line, or a web api would b... | date library, capable of calculating things like "every third tuesday"? | I'd like to find a library or command that given input like "every third tuesday" will provide a list of dates such as (2010-06-15, 2010-07-20, 2010-08-17), etc.
Something that can be called from python, unix command line, or a web api would be perfect.
| [
"There's always dateutil.\nExample below is based on ~unutbu's excellent answer to this very similar SO question:\n>>> from datetime import date\n>>> from dateutil import rrule, relativedelta\n>>> every_third_tuesday = rrule.rrule(rrule.MONTHLY, \n byweekday=relativedelta.TU(3),... | [
7,
1
] | [] | [] | [
"date",
"python"
] | stackoverflow_0003099007_date_python.txt |
Q:
ImportError: No module named Foundation
Hey all, I'm pretty new to python, so bear with me.
I want to write a simple script using some components of PyObjC. I'm running on Mac OS 10.5, so from what I've read, it's included.
However, opening up a simple python prompt and typing import Foundation gives me the error ... | ImportError: No module named Foundation | Hey all, I'm pretty new to python, so bear with me.
I want to write a simple script using some components of PyObjC. I'm running on Mac OS 10.5, so from what I've read, it's included.
However, opening up a simple python prompt and typing import Foundation gives me the error ImportError: No module named Foundation.
For ... | [
"I found it - for some reason, it was located under /System/Library/Frameworks/Python.framework/Versions/2.5/Extras/lib/python, so I had to just add that whole directory to my $PYTHONPATH\n",
"Where is the module Foundation located? Assuming it's in the same place as PyObjC -- /Library/Frameworks/Python.framework... | [
4,
0
] | [] | [] | [
"pyobjc",
"python"
] | stackoverflow_0003098932_pyobjc_python.txt |
Q:
It's possible to make a program that shows FPS (frame per second) in Python?
I was wondering...
It's possible to do it?
A simple console command based program that shows how are your FPS, for your currently running game/program?
A:
Short answer: Yes.
Long answer: Beside that it is much simpler to gather statisti... | It's possible to make a program that shows FPS (frame per second) in Python? | I was wondering...
It's possible to do it?
A simple console command based program that shows how are your FPS, for your currently running game/program?
| [
"Short answer: Yes.\nLong answer: Beside that it is much simpler to gather statistics when you have hooks inside the measured program, it is possible also to hook on lower level: directly to DirectX or OpenGL. Start your discovery from some existing posts. They are in C++ but that's another deal: you can use SWIG t... | [
1,
0,
0
] | [] | [] | [
"frame_rate",
"python"
] | stackoverflow_0003098980_frame_rate_python.txt |
Q:
Are the two codes equivalent to each other?
i know ive asked similar questions like this before, but: Is this pseudocode here the same as my code? upper case variables are the variables in the pseudocode with " ' " and the values with conditions are all in lists, such as: all "s" conditions are in list "s", and " ... | Are the two codes equivalent to each other? | i know ive asked similar questions like this before, but: Is this pseudocode here the same as my code? upper case variables are the variables in the pseudocode with " ' " and the values with conditions are all in lists, such as: all "s" conditions are in list "s", and " s' " conditions in list "S"
for i in xrange(t):
... | [
"The pseudocode you point to defines a function f, constants K and K', selectors r and r', etc -- where are all of these things hiding in the code you're showing? You seem to be using them, but, how do we (and you) know they're right, without any inspection?\nYour bug, after all, could be in all this code you're h... | [
3,
0
] | [] | [] | [
"cryptography",
"hashcode",
"python",
"ripemd"
] | stackoverflow_0003097762_cryptography_hashcode_python_ripemd.txt |
Q:
What does this "for i in [...]" loop code do?
I am new to python,can anybody please explain the following syntax,
for i in [line.split('"') for line in open('a.txt')]:
......
......
......
A:
afile = open('a.txt')
for line in afile:
f... | What does this "for i in [...]" loop code do? | I am new to python,can anybody please explain the following syntax,
for i in [line.split('"') for line in open('a.txt')]:
......
......
......
| [
"afile = open('a.txt')\nfor line in afile:\n for field in line.split('\"'):\n # do something\n\nThere really isn't much good reason for crowding such a simple concept in such a hard to read expression.\n",
"The file a.txt is opened and read line by line\nFor each line from the file, the line is split on... | [
6,
4,
4,
1,
1,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0003099041_python.txt |
Q:
set user session in django
<?php
session_start();
$_SESSION['username'] = "johndoe" // Must be already set
?>
How to write equivalent code for the above in django
A:
When SessionMiddleware is activated, each HttpRequest object – the first argument to any Django view function – wi... | set user session in django | <?php
session_start();
$_SESSION['username'] = "johndoe" // Must be already set
?>
How to write equivalent code for the above in django
| [
"\nWhen SessionMiddleware is activated, each HttpRequest object – the first argument to any Django view function – will have a session attribute, which is a dictionary-like object. You can read it and write to it.\n\nRead more ...\n\nExample: \ndef login(request):\n m = Member.objects.get(username=request.POST['... | [
4
] | [] | [] | [
"django",
"django_models",
"django_templates",
"django_views",
"python"
] | stackoverflow_0003099850_django_django_models_django_templates_django_views_python.txt |
Q:
Retrieving the Return Value of a Stackless Python Tasklet Bound Function?
Stackless Experts,
I have managed to create tasklets under Stackless Python (both from the Stackless and the C side).
It seems to me that in order to create a tasklet in Stackless, you bind an arbitrary Python callable (function) to the task... | Retrieving the Return Value of a Stackless Python Tasklet Bound Function? | Stackless Experts,
I have managed to create tasklets under Stackless Python (both from the Stackless and the C side).
It seems to me that in order to create a tasklet in Stackless, you bind an arbitrary Python callable (function) to the tasklet (as well as the required parameters), so the bound callable would be run as... | [
"From Stackless.com:\n\"... But I have yet to see a way to retrieve the return value of the bound callable running as a tasklet. ...\"\nI do not know that there is one.\n\"...important return value to be used later. It seems that writing such a Micromanaging function on the C side is not very feasible, since I h... | [
1
] | [] | [] | [
"python",
"python_stackless",
"stackless"
] | stackoverflow_0003092614_python_python_stackless_stackless.txt |
Q:
GtkTreeView's row-activated and cursor-changed signals
I have a treeview and I am watching for the cursor-changed and row-activated signals. The problem is that in order to trigger the row-activate I first have to click on the row (triggering cursor-changed) and then do the double click, requiring 3 clicks.
Is th... | GtkTreeView's row-activated and cursor-changed signals | I have a treeview and I am watching for the cursor-changed and row-activated signals. The problem is that in order to trigger the row-activate I first have to click on the row (triggering cursor-changed) and then do the double click, requiring 3 clicks.
Is there a way to respond to both signals with 2 clicks?
| [
"It's not very clear what you're trying to achieve. I guess you're trying to respond to the user changing the selection in the treeview.\nIf this is the case, connect to the [changed][1] signal on the gtk.TreeSelection:\nselection = treeview.get_selection()\nselection.connect('changed', self.on_treeview_selection_c... | [
4,
3
] | [] | [] | [
"gtk",
"gtktreeview",
"pygtk",
"python"
] | stackoverflow_0002256794_gtk_gtktreeview_pygtk_python.txt |
Q:
Running Python & Django on IIS
Is it possible to run Python & Django on IIS?
I am going to be a Lead Developer in some web design company and right now they are using classic ASP and ASP.NET.
As far as I can see ASP.NET MVC is not mature. Should I recommend Python & Django stack?
If it's not possible to run Python... | Running Python & Django on IIS | Is it possible to run Python & Django on IIS?
I am going to be a Lead Developer in some web design company and right now they are using classic ASP and ASP.NET.
As far as I can see ASP.NET MVC is not mature. Should I recommend Python & Django stack?
If it's not possible to run Python on IIS what do you think I should d... | [
"There's two issue here, technological and psycological.\nTechnologically, yes, it's definitely possible. In fact, Django has a wiki article about this. Google also shows a lot of similar tutorials. Apache and IIS can also run on the same machine (I'm actually doing that right now from a development machine).\nThe ... | [
7,
5
] | [] | [] | [
"apache",
"asp.net",
"asp.net_mvc",
"iis",
"python"
] | stackoverflow_0002112525_apache_asp.net_asp.net_mvc_iis_python.txt |
Q:
using link grammar parser
Is it adequate to use the link grammar parser to do POS tagging? How is the performance when it comes to informal english with a little of my country's lingo?
Does the link grammar parser also performs a subject-object relationship identification?
Doing POS tagging is the first step towar... | using link grammar parser | Is it adequate to use the link grammar parser to do POS tagging? How is the performance when it comes to informal english with a little of my country's lingo?
Does the link grammar parser also performs a subject-object relationship identification?
Doing POS tagging is the first step towards NER right?
| [
"The link grammar parser provides some deep grammar information like connection between nouns and various kinds of post-noun modifiers (see M and many other).\nHowever postprocess the resulting parse graph can be tedious, if you are only interested in tagging and/or NER, take a look at:\nhttp://nlp.stanford.edu/sof... | [
3
] | [] | [] | [
"link_grammar",
"parsing",
"python"
] | stackoverflow_0003100219_link_grammar_parsing_python.txt |
Q:
how to read rss feed to gae-database
any gae-lib to do this
i think maybe jquery can do this too , yes ?
thanks
A:
Here is a list of Python RSS processing libraries available by searching "python rss" in google.com
A:
One option is to avoid the hassle of polling, error handling, parsing, handling invalid f... | how to read rss feed to gae-database | any gae-lib to do this
i think maybe jquery can do this too , yes ?
thanks
| [
"Here is a list of Python RSS processing libraries available by searching \"python rss\" in google.com\n",
"One option is to avoid the hassle of polling, error handling, parsing, handling invalid feeds, and so on and so forth, by making someone else do it for you. This blog post describes how you can use PubSubHu... | [
1,
1
] | [] | [] | [
"google_app_engine",
"jquery",
"python",
"rss"
] | stackoverflow_0003098875_google_app_engine_jquery_python_rss.txt |
Q:
Libraries for manipulating multivariate polynomials
I need to write some code that deals with generating and manipulating multivariable polynomials. I'll outline my task with a simplified example.
Lets say I am given three expressions: 2x^2, 3y + 1, and 1z. I then need to multiply these together which would give ... | Libraries for manipulating multivariate polynomials | I need to write some code that deals with generating and manipulating multivariable polynomials. I'll outline my task with a simplified example.
Lets say I am given three expressions: 2x^2, 3y + 1, and 1z. I then need to multiply these together which would give me 6x^2yz + 2x^2z. Then I would like to find the partial ... | [
"Sympy is perfect for this: http://code.google.com/p/sympy/\nDocumentation: http://docs.sympy.org/\nExamples of differentiation from the tutorial: http://docs.sympy.org/tutorial.html#differentiation\nimport sympy\n\nx, y, z = sympy.symbols('xyz')\n\np1 = 2*x*x\np2 = 3*y + 1\np3 = z\n\np4 = p1*p2*p3\n\nprint p4\n\np... | [
9,
2,
1
] | [] | [] | [
"math",
"matlab",
"numpy",
"python",
"scipy"
] | stackoverflow_0003097464_math_matlab_numpy_python_scipy.txt |
Q:
issue while matching special char '\' in regular expression using '\\'
I have very simple python script to match some special characters like -,+,-,.
But Im not getting expected result while using regex \ to match a single '\' char.
import re
pat = r'[-+*\\]'
text = 'fdkjdfk\sdsdd'
if re.search(pat,text):
print... | issue while matching special char '\' in regular expression using '\\' | I have very simple python script to match some special characters like -,+,-,.
But Im not getting expected result while using regex \ to match a single '\' char.
import re
pat = r'[-+*\\]'
text = 'fdkjdfk\sdsdd'
if re.search(pat,text):
print re.search(pat,text).group()
else:
print "not found"
On running above co... | [
"\\ is an escape character.\nTry escaping it:\ntext = 'fdkjdfk\\\\sdsdd' \n\n"
] | [
2
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0003100580_python_regex.txt |
Q:
Datetime.now() abnormality - Python
I'm serving a Python app through Django. Within the app I'm storing the classic "created" field within a few tables.
This is how the field looks like within the Django form:
created = models.DateTimeField(blank=True, default=datetime.now())
Unfortunately, datetime.now() is not ... | Datetime.now() abnormality - Python | I'm serving a Python app through Django. Within the app I'm storing the classic "created" field within a few tables.
This is how the field looks like within the Django form:
created = models.DateTimeField(blank=True, default=datetime.now())
Unfortunately, datetime.now() is not accurate. In fact in the database I have... | [
"This is a common newbie mistake, unfortunately. You have called the datetime.now() method in the definition - this means the default will be the time at which the definition was executed, ie when your server process starts up.\nYou need to pass the callable instead: \ncreated = models.DateTimeField(blank=True, def... | [
10,
6,
2
] | [] | [] | [
"datetime",
"django",
"django_models",
"iis",
"python"
] | stackoverflow_0003100612_datetime_django_django_models_iis_python.txt |
Q:
Wrapping C++ dynamic array with Python+ctypes, segfault
I wanted to wrap a small C++ code allocating an array with ctypes and there is something wrong with storing the address in a c_void_p object.
(Note: the pointers are intentionally cast to void*, 'cause later I want to do the allocation the same way for arrays... | Wrapping C++ dynamic array with Python+ctypes, segfault | I wanted to wrap a small C++ code allocating an array with ctypes and there is something wrong with storing the address in a c_void_p object.
(Note: the pointers are intentionally cast to void*, 'cause later I want to do the allocation the same way for arrays of C++ objects, too.)
The C(++) functions to be wrapped:
voi... | [
"From just looking at it, it seems that the problem is not in the small/big array allocation, but in a mix of 32bit and 64bit addresses.\nIn your example, the address of the small array fits in 32 bits, but the address of the big array doesn't.\n"
] | [
1
] | [] | [] | [
"c++",
"ctypes",
"memory_management",
"python",
"segmentation_fault"
] | stackoverflow_0003100554_c++_ctypes_memory_management_python_segmentation_fault.txt |
Q:
Java equivalent of python's String partition
Java's string split(regex) function splits at all instances of the regex. Python's partition function only splits at the first instance of the given separator, and returns a tuple of {left,separator,right}.
How do I achieve what partition does in Java?
e.g.
"foo bar he... | Java equivalent of python's String partition | Java's string split(regex) function splits at all instances of the regex. Python's partition function only splits at the first instance of the given separator, and returns a tuple of {left,separator,right}.
How do I achieve what partition does in Java?
e.g.
"foo bar hello world".partition(" ")
should become
"foo", " ... | [
"While not exactly what you want, there's a second version of split which takes a \"limit\" parameter, telling it the maximum number of partitions to split the string into.\nSo if you called (in Java):\n\"foo bar hello world\".split(\" \", 2);\n\nYou'd get the array:\n[\"foo\", \"bar hello world\"]\n\nwhich is more... | [
5,
5,
2,
0,
0
] | [] | [] | [
"java",
"python",
"split",
"string"
] | stackoverflow_0003100739_java_python_split_string.txt |
Q:
How to add abilities to strings in Python
This is more of a curiosity question than anything else. I'm new with Python and playing around with it. I've just looked at the base64 module. What if instead of doing:
import base64
string = 'Foo Bar'
encoded = base664.b64encode
I wanted to do something like:
>>> class ... | How to add abilities to strings in Python | This is more of a curiosity question than anything else. I'm new with Python and playing around with it. I've just looked at the base64 module. What if instead of doing:
import base64
string = 'Foo Bar'
encoded = base664.b64encode
I wanted to do something like:
>>> class b64string():
>>> <something>
>>>
>>> string =... | [
"I don't think creating such complex string-like classes is a good idea, but if you really want to, here's a simple snippet that runs your examples.\nFirst, we define a class that's a generic string-wrapper. Its core is a __getattr__ function that forwards every method call to a given self.module, adding self.strin... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0003100789_python.txt |
Q:
Extracting some HTML tag values in Python
How to get a value of nested <b> HTML tag in Python using regular expressions?
<a href="/model.xml?hid=90971&modelid=4636873&show-uid=678650012772883921" class="b-offers__name"><b>LG</b> X110</a>
# => LG X110
A:
You don't.
Regular Expressions are not well suite... | Extracting some HTML tag values in Python | How to get a value of nested <b> HTML tag in Python using regular expressions?
<a href="/model.xml?hid=90971&modelid=4636873&show-uid=678650012772883921" class="b-offers__name"><b>LG</b> X110</a>
# => LG X110
| [
"You don't. \nRegular Expressions are not well suited to deal with the nested structure of HTML. Use an HTML parser instead.\n",
"Don't use regular expressions for parsing HTML. Use an HTML parser like BeautifulSoup. Just look how easy it is:\nfrom BeautifulSoup import BeautifulSoup\nhtml = r'<a href=\"removed be... | [
7,
6,
1,
1,
0
] | [] | [] | [
"html",
"parsing",
"python",
"regex"
] | stackoverflow_0003100896_html_parsing_python_regex.txt |
Q:
python: trouble printing short utf-encoded strings
(The following is using Python 2.6.1)
I have 2 strings:
>>> a = u'\u05e8\u05db\u05e1'
>>> b = u'\u05e8\u05db\u05e1 \u05d4\u05d9\u05d0 \u05de\u05d0\u05d9\u05e8\u05d4 \u05d1\u05e4\u05e0\u05e1'
I encode them:
>>> ua = a.encode('utf-8')
>>> ub = b.encode('utf-8')
>>>... | python: trouble printing short utf-encoded strings | (The following is using Python 2.6.1)
I have 2 strings:
>>> a = u'\u05e8\u05db\u05e1'
>>> b = u'\u05e8\u05db\u05e1 \u05d4\u05d9\u05d0 \u05de\u05d0\u05d9\u05e8\u05d4 \u05d1\u05e4\u05e0\u05e1'
I encode them:
>>> ua = a.encode('utf-8')
>>> ub = b.encode('utf-8')
>>> ua
'\xd7\xa8\xd7\x9b\xd7\xa1'
>>> ub
'\xd7\xa8\xd7\x9b\... | [
"Must be something with your terminal settings; ua prints three Hebrew characters on my terminal (Terminal.app on OS X), exactly the rightmost three characters of ub. (Since Hebrew is a right-to-left script, the rightmost three characters are the first three).\nFor the record, I've tried it with Python 2.6.1.\n"
] | [
1
] | [] | [] | [
"python",
"python_2.x",
"unicode"
] | stackoverflow_0003101100_python_python_2.x_unicode.txt |
Q:
How to pad all the numbers in a string
I've got lots of address style strings and I want to sort them in a rational way.
I'm looking to pad all the numbers in a string so that: "Flat 12A High Rise" becomes "Flat 00012A High Rise", there may be multiple numbers in the string.
So far I've got:
def pad_numbers_in_str... | How to pad all the numbers in a string | I've got lots of address style strings and I want to sort them in a rational way.
I'm looking to pad all the numbers in a string so that: "Flat 12A High Rise" becomes "Flat 00012A High Rise", there may be multiple numbers in the string.
So far I've got:
def pad_numbers_in_string(string, padding=5):
numbers = re.fin... | [
"Instead of changing your data to accommodate your sorting algorithm, change your sorting algorithm to accommodate your data.\nSee Sorting For Humans: Natural Sort Order on Coding Horror:\nimport re \n\ndef sort_nicely( l ): \n \"\"\" Sort the given list in the way that humans expect. \n \"\"\" \n convert = lamb... | [
9,
8
] | [] | [] | [
"python",
"string"
] | stackoverflow_0003101778_python_string.txt |
Q:
Stack recommendations for small/medium-sized web application in Python
I'm looking for some recommendations for a python web application. We have some memory restrictions and we try to keep it small and lean.
We thought about using WSGI (and a python webserver) and build the rest ourself. We already have a templat... | Stack recommendations for small/medium-sized web application in Python | I'm looking for some recommendations for a python web application. We have some memory restrictions and we try to keep it small and lean.
We thought about using WSGI (and a python webserver) and build the rest ourself. We already have a template engine we'd like to use, but we are open for some suggestions regarding th... | [
"I've been using Werkzeug because it's more a small collection of really useful components than a whole framework. It runs behind a wsgi server of your choice (and comes with a built-in one). If you want something even easier, Flask might be worth a look. Also, you might want to bookmark the rather speedy Jinja ... | [
3,
2,
2,
1,
0,
0
] | [] | [] | [
"python",
"wsgi"
] | stackoverflow_0002847593_python_wsgi.txt |
Q:
Python ctypes.WinDLL error , _dlopen(self._name, mode) can't be found
ctypes.WinDLL("C:\Program Files\AHSDK\bin\ahscript.dll")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python26\lib\ctypes\__init__.py", line 353, in __init__
self._handle = _dlopen(self._name, mode)
Wi... | Python ctypes.WinDLL error , _dlopen(self._name, mode) can't be found | ctypes.WinDLL("C:\Program Files\AHSDK\bin\ahscript.dll")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python26\lib\ctypes\__init__.py", line 353, in __init__
self._handle = _dlopen(self._name, mode)
WindowsError: [Error 126] The specified module could not be found
How can I ... | [
"Backslashes are an escape character within strings, as demonstrated in the example below:\n>>> print \"C:\\Program Files\\AHSDK\\bin\\ahscript.dll\"\nC:\\Program Files\\AHSDinhscript.dll\n\nYou can solve the problem by placing an r before the string, which prevents the backslash from working as an escape character... | [
8
] | [] | [] | [
"ctypes",
"dll",
"dllimport",
"python",
"windows"
] | stackoverflow_0003101981_ctypes_dll_dllimport_python_windows.txt |
Q:
Any smarter/faster/ligher replacement for this line of code?
file = [float(line.partition(' ')[0]) for line in file]
the file is object of open file...
thnq
A:
Smarter would be to not shadow file.
A:
For measurement of speed, see the Python standard library module timeit:
$ python -m timeit -s 'f = file("/tmp... | Any smarter/faster/ligher replacement for this line of code? | file = [float(line.partition(' ')[0]) for line in file]
the file is object of open file...
thnq
| [
"Smarter would be to not shadow file.\n",
"For measurement of speed, see the Python standard library module timeit:\n$ python -m timeit -s 'f = file(\"/tmp/numbers.txt\")' '[float(line.partition(\" \")[0]) for line in f]'\n10000000 loops, best of 3: 0.123 usec per loop\n$ python -m timeit -s 'f = file(\"/tmp/numb... | [
2,
1,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0003099565_python.txt |
Q:
Python : How to import a module if I have its path as a string?
Lets say I have path to a module in a string module_to_be_imported = 'a.b.module'
How can I import it ?
A:
>>> m = __import__('xml.sax')
>>> m.__name__
'xml'
>>> m = __import__('xml.sax', fromlist=[''])
>>> m.__name__
'xml.sax'
A:
You can use the ... | Python : How to import a module if I have its path as a string? | Lets say I have path to a module in a string module_to_be_imported = 'a.b.module'
How can I import it ?
| [
">>> m = __import__('xml.sax')\n>>> m.__name__\n'xml'\n>>> m = __import__('xml.sax', fromlist=[''])\n>>> m.__name__\n'xml.sax'\n\n",
"You can use the build-in __import__ function. For example:\nimport sys\n\nmyconfigfile = sys.argv[1]\n\ntry:\n config = __import__(myconfigfile)\n for i in config.__dict__:\n... | [
6,
3,
0
] | [] | [] | [
"import",
"python"
] | stackoverflow_0003102252_import_python.txt |
Q:
python - gtk treeview - liststore with real-time update
i am having a issue with treeview liststore trying to get a real-time update, and I created a example to simulate what I'd like to do.
I want liststore1 updated each loop.
http://img204.imageshack.us/i/capturadetela5.png/
it should update the treeview column ... | python - gtk treeview - liststore with real-time update | i am having a issue with treeview liststore trying to get a real-time update, and I created a example to simulate what I'd like to do.
I want liststore1 updated each loop.
http://img204.imageshack.us/i/capturadetela5.png/
it should update the treeview column 'speed' and give to it a different number every second,
somet... | [
"If that's your full code, you're missing the GTK main loop invocation.\nYou need to do two things (in this order)\n1 - Connect your window's destroy signal to a function that calls gtk.main_quit()\ndef on_destroy(widget, user_data=None):\n # Exit the app\n gtk.main_quit()\n\nwindow.connect('destroy', on_dest... | [
2
] | [] | [] | [
"pygtk",
"python"
] | stackoverflow_0003102464_pygtk_python.txt |
Q:
Mysql database Import Error in python
i have installed python 2.6.4. i have downloaded mysql database module. but i don't know where to place that module in python package. when i execute the program it shows import error "no module named mysql db". please tell me where to place the module.
A:
it's case-sensitiv... | Mysql database Import Error in python | i have installed python 2.6.4. i have downloaded mysql database module. but i don't know where to place that module in python package. when i execute the program it shows import error "no module named mysql db". please tell me where to place the module.
| [
"it's case-sensitive, module name is 'MySQLdb'\nyed@rublan ~/skript $ python\nPython 2.6.5 (release26-maint, Jun 19 2010, 18:42:45) \n[GCC 4.4.4] on linux2\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> import MySQLdb\n>>> print dir(MySQLdb)\n['BINARY', 'Binary', 'Connect', 'Co... | [
3
] | [] | [] | [
"installation",
"mysql",
"python"
] | stackoverflow_0003102528_installation_mysql_python.txt |
Q:
Controlling Music and Video in Python
I'm trying to write a karaoke program in python. Every karaoke software has basic functionality like seeking in the video as well as modulating the pitch of music by half steps. What are some modules that I can use to permit this functionality?
I'm going to use wxPython to wri... | Controlling Music and Video in Python | I'm trying to write a karaoke program in python. Every karaoke software has basic functionality like seeking in the video as well as modulating the pitch of music by half steps. What are some modules that I can use to permit this functionality?
I'm going to use wxPython to write the gui portion if that makes a differen... | [
"Honestly you might want to take a look at PyGame - it has fairly robust libraries for handling stuff like music and movies: http://www.pygame.org/docs/\n",
"wxPython has a built in media controller, wx.MediaCtrl, which can play both audio and video. It has most of the basic functionality built in, like seek, pa... | [
2,
0
] | [] | [] | [
"python",
"video",
"wxpython"
] | stackoverflow_0003100976_python_video_wxpython.txt |
Q:
sound way to feed commands to twisted ssh after reactor.run()
Guys this is a question about python twisted ssh lib.
All sample code even production code I saw acting as a ssh client based on twisted.conch.ssh are all interacting with server in such a mode:
prepare some commands to run remotely;
define call backs;... | sound way to feed commands to twisted ssh after reactor.run() | Guys this is a question about python twisted ssh lib.
All sample code even production code I saw acting as a ssh client based on twisted.conch.ssh are all interacting with server in such a mode:
prepare some commands to run remotely;
define call backs;
kick off reactor then suspend for new feedback;
After the reactor... | [
"joefis' answer is basically sound, but I bet some examples would be helpful. First, there are a few ways you can have some code run right after the reactor starts.\nThis one is pretty straightforward:\ndef f():\n print \"the reactor is running now\"\n\nreactor.callWhenRunning(f)\n\nAnother way is to use timed ... | [
4,
0
] | [] | [] | [
"python",
"ssh",
"twisted"
] | stackoverflow_0003102098_python_ssh_twisted.txt |
Q:
Use latin characters in appengine
How can store latin characters in appengine? (e.g. "peña") when I want to store this I get this error:
UnicodeDecodeError: 'ascii' codec can't decode byte 0xf1 in position 2: ordinal not in range(128)
I can change the Ñ by N, but, there not another and better way?
And if i encode... | Use latin characters in appengine | How can store latin characters in appengine? (e.g. "peña") when I want to store this I get this error:
UnicodeDecodeError: 'ascii' codec can't decode byte 0xf1 in position 2: ordinal not in range(128)
I can change the Ñ by N, but, there not another and better way?
And if i encode the value, how can print "Peña" again?... | [
"GAE stores strings in unicode. Perhaps encode your string in unicode before saving it.\nvalue = \"peña\"\n\nvalue.encode(\"utf8\")\n\n",
"From the error (\"Unicode Decode Error\"), it seems you could have more luck using Unicode - I'd try UTF-8.\n"
] | [
2,
0
] | [] | [] | [
"google_app_engine",
"latin1",
"python",
"string"
] | stackoverflow_0003102856_google_app_engine_latin1_python_string.txt |
Q:
Why are Google API queries through simplejson returning "responseData": null?
I'm trying to screenscrape the first result of a Google search using Python and simplejson, but I can't access the search results the way that many examples online demonstrate. Here's a snippet:
url = 'http://ajax.googleapis.com/ajax/ser... | Why are Google API queries through simplejson returning "responseData": null? | I'm trying to screenscrape the first result of a Google search using Python and simplejson, but I can't access the search results the way that many examples online demonstrate. Here's a snippet:
url = 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&%s' % (query)
search_results = urllib.urlopen(url)
json = si... | [
"You missed the &q=. You also should consider using an api-key. http://code.google.com/intl/de/apis/ajaxsearch/documentation/. Besides that plain string contaction wont work, you need to escape the parameter. \n url = 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q= ' + urllib.quote_plus(query)\n\n"
] | [
2
] | [] | [] | [
"ajax",
"google_search_api",
"python",
"simplejson"
] | stackoverflow_0003103116_ajax_google_search_api_python_simplejson.txt |
Q:
not getting output from parmiko/ssh command
I am using paramiko/ssh/python to attempt to run a command on a remote server. When I ssh manually and run the command in question, I get the results I want. But if I use the python (co-opted from another thread on this site) below, there is no returned data. If I modify... | not getting output from parmiko/ssh command | I am using paramiko/ssh/python to attempt to run a command on a remote server. When I ssh manually and run the command in question, I get the results I want. But if I use the python (co-opted from another thread on this site) below, there is no returned data. If I modify the command to be something more basic like 'pwd... | [
"I found a fix, though not necessarily the root cause: When paramiko created the ssh connection, it did not run my bash_profile in my home directory on the remote server. So, I copied the commands from the bash_profile into the cmd variable and thus loaded various environment variables that I thought would have loa... | [
1
] | [] | [] | [
"paramiko",
"python",
"ssh"
] | stackoverflow_0003049134_paramiko_python_ssh.txt |
Q:
How does this Python decorator work?
I was looking at some lazy loading property decorators in Python and happened across this example (http://code.activestate.com/recipes/363602-lazy-property-evaluation/):
class Lazy(object):
def __init__(self, calculate_function):
self._calculate = calculate_function... | How does this Python decorator work? | I was looking at some lazy loading property decorators in Python and happened across this example (http://code.activestate.com/recipes/363602-lazy-property-evaluation/):
class Lazy(object):
def __init__(self, calculate_function):
self._calculate = calculate_function
def __get__(self, obj, _=None):
... | [
"When an attribute named someprop is accessed on instance o of class SomeClass, if SomeClass contains a descriptor named o, then that descriptor's class's __get__ method is used. For more on descriptors, see this guide. Don't let the fact that Lazy is here used, syntactically, as a decorator, blind you to the fac... | [
8
] | [] | [] | [
"decorator",
"python"
] | stackoverflow_0003103463_decorator_python.txt |
Q:
What is the Python equivalent of java.util.zip.Inflater?
I have a Java program that opens a socket connection to a server that streams Zip compressed data. I read(bytebuffer) from the stream, setInput(bytebuffer) on the zip object, and inflate(outputbuffer) to get my uncompressed data.
What would be the equivalent... | What is the Python equivalent of java.util.zip.Inflater? | I have a Java program that opens a socket connection to a server that streams Zip compressed data. I read(bytebuffer) from the stream, setInput(bytebuffer) on the zip object, and inflate(outputbuffer) to get my uncompressed data.
What would be the equivalent in python?
Here is the java code:
byte[] compressedBytes = ne... | [
"Have a look at zlib.decompressobj(). I think that should give you what you want. See http://docs.python.org/library/zlib.html\n",
"You're looking for the zlib module. java.util.zip is actually an implementation using zlib, not Zip(aka PKZIP).\n"
] | [
1,
1
] | [] | [] | [
"python",
"zip"
] | stackoverflow_0003103719_python_zip.txt |
Q:
Does ctypes provide anything for enums and flags?
I have an API I'd like to use from python. That API contains flags and enums implemented with #define.
// it's just almost C so don't bother adding the typedef and parenthesis diarrhea here.
routine(API_SOMETHING | API_OTHERTHING)
stuff = getflags()
? stuff & API_S... | Does ctypes provide anything for enums and flags? | I have an API I'd like to use from python. That API contains flags and enums implemented with #define.
// it's just almost C so don't bother adding the typedef and parenthesis diarrhea here.
routine(API_SOMETHING | API_OTHERTHING)
stuff = getflags()
? stuff & API_SOMETHING
action(API_INTERESTING)
mode = getaction()
? ... | [
"Why don't you use c_uint for the enum parameter and then use a mapping like this (enums are usually unsigned integer values):\nin C:\ntypedef enum {\n MY_VAR = 1,\n MY_OTHERVAR = 2\n} my_enum_t;\n\nand in Python:\nclass MyEnum():\n __slots__ = ('MY_VAR', 'MY_OTHERVAR')\n\n MY_VAR = 1\n MY_OTHERVAR ... | [
3,
3
] | [] | [] | [
"ctypes",
"python"
] | stackoverflow_0003100704_ctypes_python.txt |
Q:
How do I install .pl plugins for nagios?
I am trying to install the "check_mssql_sproc.pl" plug in for nagios. Where and how do I install it?
A:
Add the command definition to your nagios/etc/objects/commands.cfg
Where the pl file is actually installed doesnt matter... just make sure you can run it from the comma... | How do I install .pl plugins for nagios? | I am trying to install the "check_mssql_sproc.pl" plug in for nagios. Where and how do I install it?
| [
"Add the command definition to your nagios/etc/objects/commands.cfg\nWhere the pl file is actually installed doesnt matter... just make sure you can run it from the command line and set it up like that in your commands.cfg\n"
] | [
3
] | [] | [] | [
"nagios",
"plugins",
"python"
] | stackoverflow_0003104267_nagios_plugins_python.txt |
Q:
What is the space complexity of HashTable, Array, ArrayList, LinkedList etc(if anything more)
I want to know the space complexities of the basic data structures in popular languages.
A:
All of these have space complexity O(n). All that changes is the coefficient, and that is completely dependent on the implement... | What is the space complexity of HashTable, Array, ArrayList, LinkedList etc(if anything more) | I want to know the space complexities of the basic data structures in popular languages.
| [
"All of these have space complexity O(n). All that changes is the coefficient, and that is completely dependent on the implementation. Especially when you start getting into things like pre-allocating space to reduce time complexity.\nFor instance, array list structures generally pre-allocate extra space. Therefore... | [
3,
2,
1
] | [] | [] | [
"c#",
"c++",
"java",
"javascript",
"python"
] | stackoverflow_0003104281_c#_c++_java_javascript_python.txt |
Q:
Getting a WxPython panel item to expand
I have a WxPython frame containing a single item, such as:
class Panel(wx.Panel):
def __init__(self, parent):
wx.Panel.__init__(self, parent)
self.text = wx.StaticText(self, label='Panel 1')
I have a frame containing several panels, including this one, a... | Getting a WxPython panel item to expand | I have a WxPython frame containing a single item, such as:
class Panel(wx.Panel):
def __init__(self, parent):
wx.Panel.__init__(self, parent)
self.text = wx.StaticText(self, label='Panel 1')
I have a frame containing several panels, including this one, and dimensions are ruled by sizers.
I would li... | [
"A wx.Frame will automatically do this if it only has one child. However, a wx.Panel will not do this automatically. You're stuck using a sizer. If you find yourself doing it a lot, just make a convenience function:\ndef expanded(widget, padding=0):\n sizer = wx.BoxSizer(wx.VERTICAL)\n sizer.Add(widget, 1,... | [
8
] | [] | [] | [
"frame",
"python",
"sizer",
"wxpython"
] | stackoverflow_0003104323_frame_python_sizer_wxpython.txt |
Q:
Selecting data from Google App Engine datastore by field value
I'm just staring off with GAE. So like many I'm used to standard SQL.
Typically when you want to select data that has a certain field value you use:
SELECT <columns> FROM <table> WHERE <column> = <wanted value>
Is the correct way to do this in GAE
<Mo... | Selecting data from Google App Engine datastore by field value | I'm just staring off with GAE. So like many I'm used to standard SQL.
Typically when you want to select data that has a certain field value you use:
SELECT <columns> FROM <table> WHERE <column> = <wanted value>
Is the correct way to do this in GAE
<Model Class>.all().filter('<column> =', <wanted value>)
Or is there a... | [
"Your code is pretty close to what you're looking for - it constructs a Query object which can be used to query the datastore. To actually get a result, you'll need to execute the query. To get a single result, you'll want to use the get() method:\nresult = <Model Class>.all().filter('<column> =', <wanted value>)... | [
6,
1
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0003104400_google_app_engine_python.txt |
Q:
Python/django inherit from 2 classes
In my django project I have 2 variations of users. One subclasses User class from django.auth and second uses almost the same fields but is not a real user (so it doesn't inherit from User). Is there a way to create a FieldUser class (that stores fields only) and for RealUser s... | Python/django inherit from 2 classes | In my django project I have 2 variations of users. One subclasses User class from django.auth and second uses almost the same fields but is not a real user (so it doesn't inherit from User). Is there a way to create a FieldUser class (that stores fields only) and for RealUser subclass both FieldUser and User, but for F... | [
"sure, I've used multiple inheritance in django models, it works fine.\nsounds like you want to setup an abstract class for FieldUser:\nclass FieldUser(models.Model):\n field1 = models.IntegerField()\n field2 = models.CharField() #etc\n class Meta:\n abstract=True #abstract class does not create a d... | [
4
] | [] | [] | [
"django",
"django_users",
"python"
] | stackoverflow_0003104463_django_django_users_python.txt |
Q:
google-app-engine full-text-search ,which is better , "google custom search" or whoosh
this is whoosh
so ,did you know which is better ?
thanks
A:
Google Custom Search Engine won't search over your models unless they are published fairly completely on a page which Google has crawled and indexed. Think of CSE as... | google-app-engine full-text-search ,which is better , "google custom search" or whoosh | this is whoosh
so ,did you know which is better ?
thanks
| [
"Google Custom Search Engine won't search over your models unless they are published fairly completely on a page which Google has crawled and indexed. Think of CSE as a very configurable search engine over existing Google search results.\nWhoosh appears to be a better fit if you want to search over models in your ... | [
2
] | [] | [] | [
"full_text_search",
"google_app_engine",
"python",
"whoosh"
] | stackoverflow_0003104828_full_text_search_google_app_engine_python_whoosh.txt |
Q:
Concatenate tuples in empty dict
errors = {}
#errorexample
errors['id'] += ('error1',)
errors['id'] += ('error2',)
#works but ugly
errors['id'] = ('error1',)
errors['id'] += ('error2',)
If 'error1' is not present it will fail. Do I really have to extend dict?
A:
Use a collections.defaultdict instead of a plai... | Concatenate tuples in empty dict | errors = {}
#errorexample
errors['id'] += ('error1',)
errors['id'] += ('error2',)
#works but ugly
errors['id'] = ('error1',)
errors['id'] += ('error2',)
If 'error1' is not present it will fail. Do I really have to extend dict?
| [
"Use a collections.defaultdict instead of a plain dict -- this kind of convenience, after all, is exactly what the default-dict type was introduced for:\n>>> import collections\n>>> errors = collections.defaultdict(tuple)\n>>> errors['id'] += ('error1',)\n>>> errors['id'] += ('error2',)\n>>> errors['id']\n('error1'... | [
4,
3,
1
] | [] | [] | [
"dictionary",
"error_handling",
"list",
"python",
"tuples"
] | stackoverflow_0003105215_dictionary_error_handling_list_python_tuples.txt |
Q:
Using C++ from Python? (not boost)
I'm currently using boost-python to wrap a small C++ library and make it usable from Python. However, I'd like to stop using boost (mainly due to reasons relating to building/linking). So what other options are there?
Is there something that's equally convenient to use?
A:
Th... | Using C++ from Python? (not boost) | I'm currently using boost-python to wrap a small C++ library and make it usable from Python. However, I'd like to stop using boost (mainly due to reasons relating to building/linking). So what other options are there?
Is there something that's equally convenient to use?
| [
"There's Riverbank's SIP, Beazley's Swig, and Scott's/Dubois'/Furnish's Cxx. See also this page with other potentially relevant projects (but no direct answer to your immediate needs, I believe).\n",
"Take a look at SWIG.\n",
"Cython's syntax is very Pythonic, breaking the rules only where necessary.\n"
] | [
2,
2,
0
] | [] | [] | [
"c++",
"python"
] | stackoverflow_0003105258_c++_python.txt |
Q:
Python: Printing Unicode to File
file = open('unicode.txt', 'wb')
for i in range(10):
file.write(str(unichr(i) ))
What i would like to do is to print all of the Unicode values to a text file
A:
somefile = codecs.open('unicode.txt', 'wb', someencoding)
for i in range(10):
somefile.write(unic... | Python: Printing Unicode to File | file = open('unicode.txt', 'wb')
for i in range(10):
file.write(str(unichr(i) ))
What i would like to do is to print all of the Unicode values to a text file
| [
"somefile = codecs.open('unicode.txt', 'wb', someencoding)\n\nfor i in range(10):\n somefile.write(unichr(i))\n\n"
] | [
2
] | [
"You shouldn't need the str() call around unichr(i). Python unicode objects are printable. \nThis:\nfile = open('unicode.txt', 'wb')\nfor i in range(10):\n file.write(unichr(i))\n\nSeems to work for me, it prints 0x0000, 0x0001, 0x0002, etc. to the text file. \n"
] | [
-1
] | [
"python",
"unicode"
] | stackoverflow_0003104983_python_unicode.txt |
Q:
index a list in a Python for loop
I'm making a for loop within a for loop. I'm looping through a list and finding a specific string that contains a regular expression pattern. Once I find the line, I need to search to find the next line of a certain pattern. I need to store both lines to be able to parse out the ... | index a list in a Python for loop | I'm making a for loop within a for loop. I'm looping through a list and finding a specific string that contains a regular expression pattern. Once I find the line, I need to search to find the next line of a certain pattern. I need to store both lines to be able to parse out the time for them. I've created a counter t... | [
"matchExposure = re.search('taking \\d\\d\\d sec. exposure', lineString)\n\nshould probably be\nmatchExposure = re.search('taking \\d\\d\\d sec. exposure', line)\n\n",
"Depending on your exact needs, you can just use an iterator on the list, or two of them as mae by itertools.tee. I.e., if you want to search lin... | [
1,
1
] | [] | [] | [
"nested_loops",
"python"
] | stackoverflow_0003105482_nested_loops_python.txt |
Q:
Running subversion under apache and mod_python
My Apache server runs on some non-default (not-root) account. When it tries to run a python script which in turn executes a subversion check-out command, 'svn checkout' fails with the following error message:
svn: Can't open file '/root/.subversion/servers': Permissio... | Running subversion under apache and mod_python | My Apache server runs on some non-default (not-root) account. When it tries to run a python script which in turn executes a subversion check-out command, 'svn checkout' fails with the following error message:
svn: Can't open file '/root/.subversion/servers': Permission denied
At the same time running that python scrip... | [
"It sounds like the environment you apache process is running under is a little unusual. For whatever reason, svn seems to think the user configuration files it needs are in /root. You can avoid having svn use the root versions of the files by specifying on the command line which config directory to use, like so:... | [
5,
0,
0,
0,
0,
0
] | [] | [] | [
"apache",
"python",
"svn"
] | stackoverflow_0000133860_apache_python_svn.txt |
Q:
Python: shutil.copytree , lack of ignore arg in python 2.5
Short of essentially rewriting copytree to accept an ignore callback, what is a simple way to achieve this in versions prior to python 2.6? (I don't want to stray from my debian packages)
A:
You can copy the source for copytree from the 2.6 tree, and pu... | Python: shutil.copytree , lack of ignore arg in python 2.5 | Short of essentially rewriting copytree to accept an ignore callback, what is a simple way to achieve this in versions prior to python 2.6? (I don't want to stray from my debian packages)
| [
"You can copy the source for copytree from the 2.6 tree, and put it into your project's source tree.\n"
] | [
0
] | [] | [] | [
"copytree",
"python",
"python_2.5",
"shutil"
] | stackoverflow_0003105747_copytree_python_python_2.5_shutil.txt |
Q:
Google App Engine/Python - Change logging formatting
How can one change the formatting of output from the logging module in Google App Engine?
I've tried, e.g.:
log_format = "* %(asctime)s %(levelname)-8s %(message)s"
date_format = "%a, %d %b %Y %H:%M:%S"
console = logging.StreamHandler()
fr = logging.For... | Google App Engine/Python - Change logging formatting | How can one change the formatting of output from the logging module in Google App Engine?
I've tried, e.g.:
log_format = "* %(asctime)s %(levelname)-8s %(message)s"
date_format = "%a, %d %b %Y %H:%M:%S"
console = logging.StreamHandler()
fr = logging.Formatter(log_format)
console.setFormatter(fr)
logger = ... | [
"Here is one way you can change the logging format without duplicating output:\n# directly access the default handler and set its format directly\nlogging.getLogger().handlers[0].setFormatter(fr)\n\nThis is a bit of a hack because you have to directly access the handlers list stored in the root logger. The problem... | [
11
] | [] | [] | [
"google_app_engine",
"logging",
"python"
] | stackoverflow_0003105521_google_app_engine_logging_python.txt |
Q:
Retrieving a method by using string of method's name? Python
I'm wondering if it's possible in Python to find a method in a different function by using it's string name.
In one function, I pass in a method:
def register(methods):
for m in methods:
messageType = m.__name__
python_client_socket.s... | Retrieving a method by using string of method's name? Python | I'm wondering if it's possible in Python to find a method in a different function by using it's string name.
In one function, I pass in a method:
def register(methods):
for m in methods:
messageType = m.__name__
python_client_socket.send(messageType)
register(Foo)
In a different method that takes... | [
"If you're certain of the method name (do not use this with arbitrary input):\ngetattr(someobj, methodDict[someval])\n\n",
"This accomplishes that type of \"if it's defined use it, otherwise let the user know it's not ready yet\" feel.\nif hasattr(self, method):\n getattr(self, method)()\nelse:\n print 'No meth... | [
6,
3,
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0003105684_python.txt |
Q:
Boost-Python raw pointers constructors
I am trying to expose a C++ library to python using boost-python. The library actually wraps an underlying C api, so uses raw pointers a lot.
// implementation of function that creates a Request object
inline Request Service::createRequest(const char* operation) const
{
... | Boost-Python raw pointers constructors | I am trying to expose a C++ library to python using boost-python. The library actually wraps an underlying C api, so uses raw pointers a lot.
// implementation of function that creates a Request object
inline Request Service::createRequest(const char* operation) const
{
blpapi_Request_t *request;
ExceptionUtil... | [
"Your class_<blpapi_Request_t>; does not declare anything; is that code the correct version?\nIf so, then update it:\nclass_<blpapi_Request_t>(\"blpapi_Request_t\");\n\nThat said, what that error indicates is that you are trying to use the Request object with an automatic conversion to a python object which has not... | [
1
] | [] | [] | [
"boost",
"c++",
"pointers",
"python"
] | stackoverflow_0003100341_boost_c++_pointers_python.txt |
Q:
Is it possible to make Python etags a bit smarter with emacs?
I work on my Django project with emacs. In my virtualenv "postactivate" script I have the following simple command:
find -L . -type f -name "*.py" | xargs etags -e > /dev/null 2>&1 &
The TAGS file generates just fine but the system seems rather dumb. W... | Is it possible to make Python etags a bit smarter with emacs? | I work on my Django project with emacs. In my virtualenv "postactivate" script I have the following simple command:
find -L . -type f -name "*.py" | xargs etags -e > /dev/null 2>&1 &
The TAGS file generates just fine but the system seems rather dumb. When the cursor is a model filter call, e.g.
MyModel.objects.filter(... | [
"Getting correct module analysis with a language like python is very hard, due to his dynamic nature the best way to get correct information is doing static analysis or heuristics.\nCurrently the best I've found is exploring methods with the ropemacs extension that has great features like code assist (quite smart) ... | [
3
] | [] | [] | [
"django",
"emacs",
"python",
"tags"
] | stackoverflow_0002964906_django_emacs_python_tags.txt |
Q:
Python pass in variable assignments through a function wrapper
So I know that you can wrap a function around another function by doing the following.
def foo(a=4,b=3):
return a+b
def bar(func,args):
return func(*args)
so if I then called
bar(foo,[2,3])
the return value would be 5.
I am wondering is there a... | Python pass in variable assignments through a function wrapper | So I know that you can wrap a function around another function by doing the following.
def foo(a=4,b=3):
return a+b
def bar(func,args):
return func(*args)
so if I then called
bar(foo,[2,3])
the return value would be 5.
I am wondering is there a way to use bar to call foo with foo(b=12) where bar would return 16... | [
"This requires the **kwargs (keyword arguments) syntax.\ndef foo(a=4, b=3):\n return a+b\ndef bar(func, *args, **kwargs):\n return func(*args, **kwargs)\n\nprint bar(foo, b=12) # prints 16\n\nWhere *args is any number of positional arguments, **kwargs is all the named arguments that were passed in.\nAnd of co... | [
11,
4
] | [] | [] | [
"argument_passing",
"function",
"python",
"variables"
] | stackoverflow_0003106216_argument_passing_function_python_variables.txt |
Q:
Vector Class - emulating numeric type
I have a python class
class Vector2D(object):
def __init__(self, x, y):
self.x = float(x)
self.y = float(y)
def mag(self):
return sqrt(self.x**2 + self.y**2)
...
I want to be able to multiply vectors together like vector1 * vector2, so I... | Vector Class - emulating numeric type | I have a python class
class Vector2D(object):
def __init__(self, x, y):
self.x = float(x)
self.y = float(y)
def mag(self):
return sqrt(self.x**2 + self.y**2)
...
I want to be able to multiply vectors together like vector1 * vector2, so I added
def __mul__(self, v):
re... | [
"Check to see if v is a Vector2D, and if not pass it to float() and multiply appropriately.\n",
"There is no function overload in Python, you have to do it manually.\nclass Vector(object):\n def __init__(self, x, y):\n self.x = x\n self.y = y\n def __mul__(self, k):\n if type(k) == float or type(k) == ... | [
2,
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0003106534_python.txt |
Q:
Any productive way to install a bunch of packages
I had one machine with my commonly used python package installed.
and i would like to install the same package on another machine or same machine with different python version. I would like to know whether pip or easy-install or some other method can let me install... | Any productive way to install a bunch of packages | I had one machine with my commonly used python package installed.
and i would like to install the same package on another machine or same machine with different python version. I would like to know whether pip or easy-install or some other method can let me install those packages in a batch. When i use perl, it has som... | [
"Pip has some great features for this.\nIt lets you save all requirements from an environment in a file using pip freeze > reqs.txt\nYou can then later do : pip install -r reqs.txt and you'll get the same exact environnement.\nYou can also bundle several libraries into a .pybundle file with the command pip bundle M... | [
9,
0
] | [] | [] | [
"pip",
"python"
] | stackoverflow_0003106736_pip_python.txt |
Q:
Determine user connecting a local socket with Python
If Python, if you are developing a system service that communicates with user applications through sockets, and you want to treat sockets connected by different users differently, how would you go about that?
If I know that all connecting sockets will be from lo... | Determine user connecting a local socket with Python | If Python, if you are developing a system service that communicates with user applications through sockets, and you want to treat sockets connected by different users differently, how would you go about that?
If I know that all connecting sockets will be from localhost, is there a way to lookup through the OS (either o... | [
"On Linux and other unixy system, you can use the ident service.\nI'm not sure if Windows offers something similar.\n",
"Unfortunately, at this point in time the python libraries don't support the usual SCM_CREDENTIALS method of passing credentials along a Unix socket.\nYou'll need to use an \"ugly\" method as de... | [
3,
1,
0
] | [] | [] | [
"python",
"sockets"
] | stackoverflow_0003105705_python_sockets.txt |
Q:
How to set element's id in Python's xml.dom.minidom?
How to? Created a document and an element:
import xml.dom.minidom as d
a=d.Document()
b=a.createElement('test')
setIdAttribute doesn't work :(
b.setIdAttribute('something')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/li... | How to set element's id in Python's xml.dom.minidom? | How to? Created a document and an element:
import xml.dom.minidom as d
a=d.Document()
b=a.createElement('test')
setIdAttribute doesn't work :(
b.setIdAttribute('something')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.6/xml/dom/minidom.py", line 835, in setIdAttribu... | [
"Two things are wrong here.\n\nDocument.getElementById will only find elements that are actually in the document. Here you've created b but not actually added it to the document. (It's exactly the same in JavaScript.)\nYou have to mark id as an ID attribute using setIdAttribute. (There's no need to do this in JavaS... | [
8,
2
] | [] | [] | [
"dom",
"minidom",
"python",
"xml"
] | stackoverflow_0001971186_dom_minidom_python_xml.txt |
Q:
currying functions in python in a loop
So here is some code that simplifies what I've been working on:
vars = {
'a':'alice',
'b':'bob',
}
cnames = ['charlie', 'cindy']
commands = []
for c in cnames:
kwargs = dict(vars)
kwargs['c'] = c
print kwargs
commands.append(lambda:a_function(**kwarg... | currying functions in python in a loop | So here is some code that simplifies what I've been working on:
vars = {
'a':'alice',
'b':'bob',
}
cnames = ['charlie', 'cindy']
commands = []
for c in cnames:
kwargs = dict(vars)
kwargs['c'] = c
print kwargs
commands.append(lambda:a_function(**kwargs))
print commands
def a_function(a=None, ... | [
"You're encountering a classic binding-time problem, and @Mike's solution is the classic one. A good alternative is to write a higher order function:\ndef makecall(kwargs):\n def callit():\n return a_function(**kwargs)\n return callit\n\nand use commands.append(makecall(kwargs)) in your loop. Both solutions w... | [
5,
4
] | [] | [] | [
"currying",
"lambda",
"python"
] | stackoverflow_0003107231_currying_lambda_python.txt |
Q:
Python input that ends without showing a newline
Is there an python function similar to raw_input but that doesn't show a newline when you press enter. For example, when you press enter in a Forth prompt it doesn't show a newline.
Edit:
If I use the code:
data = raw_input('Prompt: ')
print data
than the output co... | Python input that ends without showing a newline | Is there an python function similar to raw_input but that doesn't show a newline when you press enter. For example, when you press enter in a Forth prompt it doesn't show a newline.
Edit:
If I use the code:
data = raw_input('Prompt: ')
print data
than the output could be:
Prompt: Hello
Hello
because it printed a newl... | [
"Yes, there are other ways to read a line like raw_input\nYou can use sys.stdin():\nimport sys\nline = sys.stdin.readline()\n\nOr if you want to get a password you can also use getpass.getpass():\nimport getpass\nline = getpass.getpass()\n\nBut if you want something more fancy you will need to use curses\n"
] | [
3
] | [] | [] | [
"newline",
"python",
"textinput"
] | stackoverflow_0003105971_newline_python_textinput.txt |
Q:
Is there a more pythonic way to access the child elements of parents using lxml
I am poking at XBRL documents trying to get my head around how to effectively extract and use the data. One thing I have been struggling with is making sure I use the context information correctly. Below is a snippet from one of the ... | Is there a more pythonic way to access the child elements of parents using lxml | I am poking at XBRL documents trying to get my head around how to effectively extract and use the data. One thing I have been struggling with is making sure I use the context information correctly. Below is a snippet from one of the documents I am playing with (this is from Mattel's latest 10-K)
I want to be able to... | [
"Using the element-tree interface (which lxml also supports), getiterator iterates over all the nodes in the subtree rooted at the current element.\nSo, [list(c.getiterator()) for c in contextlist] gives you the list of lists you want (or you may want to keep c in the resulting list to avoid having to zip it with c... | [
3
] | [] | [] | [
"lxml",
"python",
"xbrl"
] | stackoverflow_0003106658_lxml_python_xbrl.txt |
Q:
Really simple way to deal with XML in Python?
Musing over a recently asked question, I started to wonder if there is a really simple way to deal with XML documents in Python. A pythonic way, if you will.
Perhaps I can explain best if i give example: let's say the following - which i think is a good example of how ... | Really simple way to deal with XML in Python? | Musing over a recently asked question, I started to wonder if there is a really simple way to deal with XML documents in Python. A pythonic way, if you will.
Perhaps I can explain best if i give example: let's say the following - which i think is a good example of how XML is (mis)used in web services - is the response ... | [
"lxml has been mentioned. You might also check out lxml.objectify for some really simple manipulation.\n>>> from lxml import objectify\n>>> tree = objectify.fromstring(your_xml)\n>>> tree.weather.attrib[\"module_id\"]\n'0'\n>>> tree.weather.forecast_information.city.attrib[\"data\"]\n'Mountain View, CA'\n>>> tree.w... | [
17,
9,
4,
4,
2,
1,
1,
0
] | [
"If you haven't already, I'd suggest looking into the DOM API for Python. DOM is a pretty widely used XML interpretation system, so it should be pretty robust.\nIt's probably a little more complicated than what you describe, but that comes from its attempts to preserve all the information implicit in XML markup rat... | [
-1
] | [
"python",
"xml"
] | stackoverflow_0003106480_python_xml.txt |
Q:
Python string format character for __unicode__?
Firstly, is there one?
If not, is there a nice way to force something like
print '%s' % obj
to call obj.__unicode__ instead of obj.__str__?
A:
Just use a unicode format string, rather than having a byte string in that role:
>>> class X(object):
... def __str__(s... | Python string format character for __unicode__? | Firstly, is there one?
If not, is there a nice way to force something like
print '%s' % obj
to call obj.__unicode__ instead of obj.__str__?
| [
"Just use a unicode format string, rather than having a byte string in that role:\n>>> class X(object):\n... def __str__(self): return 'str'\n... def __unicode__(self): return u'unicode'\n... \n>>> x = X()\n>>> print u'%s' % x\nunicode\n\n",
"No. It wouldn't make sense for this to be the case.\nprint (u\"%s\"... | [
4,
1,
0
] | [] | [] | [
"python",
"string",
"syntax",
"unicode"
] | stackoverflow_0003107235_python_string_syntax_unicode.txt |
Q:
What a base controller that will look for a session cookie, and if present, set the User object
I want to use a custom base controller for my wep application that has a User object as a property, and a boolean IsLoggedIn property.
In the constructor of the base controller (or whatever event I need to do this in??)... | What a base controller that will look for a session cookie, and if present, set the User object | I want to use a custom base controller for my wep application that has a User object as a property, and a boolean IsLoggedIn property.
In the constructor of the base controller (or whatever event I need to do this in??) I want to look for a session cookie, if present, load the user and set the User object and set the I... | [
"Also you can use before method of controller like this:\nclass MyControllerWithUserProperty(BaseController):\n\n def __before__(self, action, **params):\n # check the cookies\n # ...\n\n self.user = <user object>\n\n # set others properties\n # ...\n\n",
"In your code that is resp... | [
2,
0
] | [] | [] | [
"pylons",
"python"
] | stackoverflow_0003087207_pylons_python.txt |
Q:
Template tags like Django with Mako and Pylons
For my site need some "widgets" that elaborate output from various data models, because this widgets are visible in any page is possible with mako to retrieve the data without pass (and elaborate) every time with render() in controllers?
A:
May be you need use helpe... | Template tags like Django with Mako and Pylons | For my site need some "widgets" that elaborate output from various data models, because this widgets are visible in any page is possible with mako to retrieve the data without pass (and elaborate) every time with render() in controllers?
| [
"May be you need use helpers\nin lib/helpers.py\ndef tweets(**params):\n context = {}\n return render('tweets.mako', context)\n\nIn you page template do this to render you tweets widget:\n h.tweets()\n\n",
"It sounds like you're looking for some combination of FormAlchemy, ToscaWidgets and/or Sprox. I woul... | [
2,
0
] | [] | [] | [
"mako",
"pylons",
"python"
] | stackoverflow_0003081193_mako_pylons_python.txt |
Q:
Python script reading from a csv file
"Type","Name","Description","Designation","First-term assessment","Second-term assessment","Total"
"Subject","Nick","D1234","F4321",10,19,29
"Unit","HTML","D1234-1","F4321",18,,
"Topic","Tags","First Term","F4321",18,,
"Su... | Python script reading from a csv file | "Type","Name","Description","Designation","First-term assessment","Second-term assessment","Total"
"Subject","Nick","D1234","F4321",10,19,29
"Unit","HTML","D1234-1","F4321",18,,
"Topic","Tags","First Term","F4321",18,,
"Subtopic","Review of representation of HTML",... | [
"You're importing the csv module but never use it. Why?\nIf you do\nimport csv\nreader = csv.reader(open(file, \"rb\"), dialect=\"excel\") # Python 2.x\n# Python 3: reader = csv.reader(open(file, newline=\"\"), dialect=\"excel\")\n\nyou get a reader object that will contain all you need; the first row will contain ... | [
11
] | [] | [] | [
"csv",
"python"
] | stackoverflow_0003107793_csv_python.txt |
Q:
Shortcut to testing PHP code
Having a python interpreter is really useful as it lets you quickly type in few commands and verify output; making it easier to understand syntax.
However, in PHP, every time I want to try something out I have to - create a PHP script, save it, run it in my browser.
Is there a shortcu... | Shortcut to testing PHP code | Having a python interpreter is really useful as it lets you quickly type in few commands and verify output; making it easier to understand syntax.
However, in PHP, every time I want to try something out I have to - create a PHP script, save it, run it in my browser.
Is there a shortcut that I am missing out on for PHP... | [
"You can run php CLI in interactive mode ;)\nphp -a \n\nin interactive mode you need to type the script with start and end tags \n<?php echo 'Hello!'; ?>\n\n",
"Use PHP Designer. It will make your job much easier.\n",
"Or you could use phpUnit , unit testing for php\n"
] | [
3,
2,
1
] | [] | [] | [
"interpreter",
"php",
"python",
"shortcut"
] | stackoverflow_0003108009_interpreter_php_python_shortcut.txt |
Q:
Scipy sparse triangular matrix?
I am using Scipy to construct a large, sparse (250k X 250k) co-occurrence matrix using scipy.sparse.lil_matrix. Co-occurrence matrices are triangular; that is, M[i,j] == M[j,i]. Since it would be highly inefficient (and in my case, impossible) to store all the data twice, I'm curr... | Scipy sparse triangular matrix? | I am using Scipy to construct a large, sparse (250k X 250k) co-occurrence matrix using scipy.sparse.lil_matrix. Co-occurrence matrices are triangular; that is, M[i,j] == M[j,i]. Since it would be highly inefficient (and in my case, impossible) to store all the data twice, I'm currently storing data at the coordinate ... | [
"I would say that you can't have the cake and eat it too: if you want efficient storage, you cannot store full rows (as you say); if you want efficient row access, I'd say that you have to store full rows.\nWhile real performances depend on your application, you could check whether the following approach works for ... | [
2
] | [] | [] | [
"matrix",
"python",
"scipy"
] | stackoverflow_0003107073_matrix_python_scipy.txt |
Q:
Python httplib.HTTPSConnection and password
I use httplib.HTTPSConnection with private key:
h = httplib.HTTPSConnection(url, key_file='../cert/priv.pem', cert_file='../cert/srv_test.crt')
Then I am asked to enter the password to that private key. Is there any option to enter such password not from user input (con... | Python httplib.HTTPSConnection and password | I use httplib.HTTPSConnection with private key:
h = httplib.HTTPSConnection(url, key_file='../cert/priv.pem', cert_file='../cert/srv_test.crt')
Then I am asked to enter the password to that private key. Is there any option to enter such password not from user input (console) but from other source (code, environment)? ... | [
"The private key file is loaded in Python's _ssl module (the part that's written in C). From _ssl.c, line 333:\nret = SSL_CTX_use_PrivateKey_file(self->ctx, key_file, SSL_FILETYPE_PEM);\n\nThis is an OpenSSL function which loads the given key file. If a password is provided, it will call a password callback functio... | [
4
] | [] | [] | [
"httplib",
"https",
"passwords",
"python",
"ssl"
] | stackoverflow_0003108067_httplib_https_passwords_python_ssl.txt |
Q:
Django url.py without method names
In my Django project, my url.py module looks something like this:
urlpatterns = patterns('',
(r'^$', 'web.views.home.index'),
(r'^home/index', 'web.views.home.index'),
(r'^home/login', 'web.views.home.login'),
(r'^home/logout', 'web.views.home.logout'),
(r'^ho... | Django url.py without method names | In my Django project, my url.py module looks something like this:
urlpatterns = patterns('',
(r'^$', 'web.views.home.index'),
(r'^home/index', 'web.views.home.index'),
(r'^home/login', 'web.views.home.login'),
(r'^home/logout', 'web.views.home.logout'),
(r'^home/register', 'web.views.home.register')... | [
"You could use a class-based view with a dispatcher method:\nclass MyView(object):\n def __call__(self, method_name):\n if hasattr(self, method_name):\n return getattr(self, method_name)()\n\n\n def index(self):\n ...etc...\n\nand your urls.py would look like this:\nfrom web.views imp... | [
3,
2
] | [] | [] | [
"django",
"python",
"url",
"url_pattern"
] | stackoverflow_0003106992_django_python_url_url_pattern.txt |
Q:
MySQLdb install problem
I need to install MySQLdb.
I write:
$ tar xfz MySQL-python-1.2.1.tar.gz
$ cd MySQL-python-1.2.1
$ python setup.py build #it is ok
$ su root setup.py install #return list of errors
error list:
setup.py: line 3: import: command not
found
setup.py: line 4: import: command not
found... | MySQLdb install problem | I need to install MySQLdb.
I write:
$ tar xfz MySQL-python-1.2.1.tar.gz
$ cd MySQL-python-1.2.1
$ python setup.py build #it is ok
$ su root setup.py install #return list of errors
error list:
setup.py: line 3: import: command not
found
setup.py: line 4: import: command not
found-
setup.py: line 5: from: com... | [
"You forgot an important word in your example: \"python\"\n$ su root python setup.py install\n\n"
] | [
1
] | [] | [] | [
"installation",
"mysql",
"python"
] | stackoverflow_0003108239_installation_mysql_python.txt |
Q:
python httplib: getting the outgoing request headers
I do:
con = HTTPConnection(SERVER_NAME)
con.request('GET', PATH, HEADERS)
resp = con.getresponse()
For debugging reasons, I want to see the request I used (it's fields, path, method,..). I would expect there to be some sort of con.getRequest() or something of t... | python httplib: getting the outgoing request headers | I do:
con = HTTPConnection(SERVER_NAME)
con.request('GET', PATH, HEADERS)
resp = con.getresponse()
For debugging reasons, I want to see the request I used (it's fields, path, method,..). I would expect there to be some sort of con.getRequest() or something of the sort but didn't find anything. Ideas?
| [
"Try\ncon.setdebuglevel(1)\n\nThat will enable debugging output, which among other things, will print out all the data it sends.\nIf you only want to get the headers and request line, not the request body (or any other debugging output), you can subclass HTTPConnection and override the _output method, which is call... | [
3
] | [] | [] | [
"httpconnection",
"httplib",
"python"
] | stackoverflow_0003108488_httpconnection_httplib_python.txt |
Q:
Lets say I have a string...how do I convert that to a datetime?
s = "June 19, 2010"
How do I conver that to a datetime object?
A:
There's also the very good dateutil library, that can parse also stranger cases:
from dateutil.parsers import parse
d = parse(s)
A:
Use datetime.strptime. It takes the string to co... | Lets say I have a string...how do I convert that to a datetime? | s = "June 19, 2010"
How do I conver that to a datetime object?
| [
"There's also the very good dateutil library, that can parse also stranger cases:\nfrom dateutil.parsers import parse\nd = parse(s)\n\n",
"Use datetime.strptime. It takes the string to convert and a format code as arguments. The format code depends on the format of the string you want to convert, of course; detai... | [
2,
1,
0,
0
] | [] | [] | [
"datetime",
"python"
] | stackoverflow_0003108532_datetime_python.txt |
Q:
How to open a file on app engine patch?
I tried to read a file in a view like this:
def foo(request):
f = open('foo.txt', 'r')
data = f.read()
return HttpResponse(data)
I tried to place the foo.txt in almost every folder in the project but it still returns
[Errno 2] No such file or directory:
'foo.... | How to open a file on app engine patch? | I tried to read a file in a view like this:
def foo(request):
f = open('foo.txt', 'r')
data = f.read()
return HttpResponse(data)
I tried to place the foo.txt in almost every folder in the project but it still returns
[Errno 2] No such file or directory:
'foo.txt'
So does anybody knows how to open a fil... | [
"In App Engine, patch or otherwise, you should be able to open (read-only) any file that gets uploaded with your app's sources. Is 'foo.txt' in the same directory as the py file? Does it get uploaded (what does your app.yaml say?)?\n",
"Put './' in front of your file path:\nf = open('./foo.txt')\n\nIf you don't, ... | [
2,
1,
0
] | [] | [] | [
"django",
"google_app_engine",
"python"
] | stackoverflow_0001077691_django_google_app_engine_python.txt |
Q:
Django signals file, cannot import model names
I have such file order:
project/
app/
models.py
signals.py
I am keeping signals inside signals.py as it should be. and at the top of the signals.py file, I include myapp models as I do queries in these signals with
from myproject.myapp.models imp... | Django signals file, cannot import model names | I have such file order:
project/
app/
models.py
signals.py
I am keeping signals inside signals.py as it should be. and at the top of the signals.py file, I include myapp models as I do queries in these signals with
from myproject.myapp.models import Foo
However it doesnt seem to find it, as I run... | [
"Most likely you have a circular dependency. Does your models.py import the signals? If so, this can't work as both modules now depend on each other. You may need to import the models within a function in the signals file, rather than at the top level.\n"
] | [
15
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0003108694_django_django_models_python.txt |
Q:
Problem executing script using Python and subprocces.call yet works in Bash
For the first time, I am asking a little bit of help over here as I am more of a ServerFault person.
I am doing some scripting in Python and I've been loving the language so far yet I have this little problem which is keeping my script fro... | Problem executing script using Python and subprocces.call yet works in Bash | For the first time, I am asking a little bit of help over here as I am more of a ServerFault person.
I am doing some scripting in Python and I've been loving the language so far yet I have this little problem which is keeping my script from working.
Here is the code line in question :
subprocess.call('xen-create-image ... | [
"You (in most cases) don't want to use subprocess with shell=True.\nPass it a list of arguments to the command. That is\n\nmore secure: Imagine a user manages to pass foo; rm -rf /; echo as some of the values.\nmore reliable: Imagine one of the strings contains a $ or something – it will be expanded by the shell an... | [
2,
0,
0,
0
] | [] | [] | [
"bash",
"python",
"subprocess",
"xen"
] | stackoverflow_0002908935_bash_python_subprocess_xen.txt |
Q:
How can I import the enviroment variables of a completed process in python?
I need to write a python script that launches a shell script and import the environment variables AFTER a script is completed.
Immagine you have a shell script "a.sh":
export MYVAR="test"
In python I would like to do something like:
impo... | How can I import the enviroment variables of a completed process in python? | I need to write a python script that launches a shell script and import the environment variables AFTER a script is completed.
Immagine you have a shell script "a.sh":
export MYVAR="test"
In python I would like to do something like:
import os
env={}
os.spawnlpe(os.P_WAIT,'sh', 'sh', 'a.sh',env)
print env
and get:
{'... | [
"Nope, any changes made to environment variables in a subprocess stay in that subprocess. (As far as I know, that is) When the subprocess terminates, its environment is lost.\nI'd suggest getting the shell script to print its environment, or at least the variables you care about, to its standard output (or standard... | [
5,
0
] | [] | [] | [
"environment_variables",
"python",
"shell",
"unix"
] | stackoverflow_0003108951_environment_variables_python_shell_unix.txt |
Q:
Dynamically generating a generator function from a blob of text
(Simplified from an excessively verbose question I posted earlier!)
Given a Python string containing valid Python code that contains a "yield" statement, how can I construct a generator that exec's that string?
For example, given the string:
code_stri... | Dynamically generating a generator function from a blob of text | (Simplified from an excessively verbose question I posted earlier!)
Given a Python string containing valid Python code that contains a "yield" statement, how can I construct a generator that exec's that string?
For example, given the string:
code_string = """for x in range(0, 10):
yield x
"""
I want to construct a... | [
"What do you care what indentation is used within the function? Indentation is relative and does not have to be consistent. Tack \"def f():\\n\" on the front, add a single space to each line in your function and exec it, and you're done. This works just as well as your answer:\nexec \"def f():\\n \" + \" \\n\".joi... | [
2,
1
] | [] | [] | [
"generator",
"python"
] | stackoverflow_0003105458_generator_python.txt |
Q:
Django Model/Database design for subclasses
Ok, i'm shit at describing. Here's a relationship diag.
In Django i've made my models like:
from django.db import models
from datetime import datetime
class Survey(models.Model):
name = models.CharField(max_length=100)
pub_date = models.DateTimeField('date publ... | Django Model/Database design for subclasses | Ok, i'm shit at describing. Here's a relationship diag.
In Django i've made my models like:
from django.db import models
from datetime import datetime
class Survey(models.Model):
name = models.CharField(max_length=100)
pub_date = models.DateTimeField('date published',default=datetime.now)
def __unicode__... | [
"You could have one section class as well, having an attribute type that could either be rating or multiplechoice - which would be rendered in the admin then as select box.\nBut I think you should have a look at Django's possibility to create abstract models: http://docs.djangoproject.com/en/dev/topics/db/models/#i... | [
0
] | [] | [] | [
"database_design",
"django",
"django_admin",
"django_models",
"python"
] | stackoverflow_0003103685_database_design_django_django_admin_django_models_python.txt |
Q:
Django Admin - Displaying Intermediary Fields for M2M Models
We have a Django app which contains a list of newspaper articles. Each article has a m2m relationship with both a "spokesperson", as well as a "firm" (company mentioned in the article).
At the moment, the Add Article page for creating new Articles is qui... | Django Admin - Displaying Intermediary Fields for M2M Models | We have a Django app which contains a list of newspaper articles. Each article has a m2m relationship with both a "spokesperson", as well as a "firm" (company mentioned in the article).
At the moment, the Add Article page for creating new Articles is quite close to what we want - it's just the stock Django Admin, and w... | [
"The problem is that the admin's method formfield_for_manytomany in django.contrib.admin.options doesn't return a form field for manytomany fields with an intermediary model! http://code.djangoproject.com/browser/django/trunk/django/contrib/admin/options.py#L157 \nYou would have to override this method in your Mode... | [
8
] | [] | [] | [
"django",
"m2m",
"python"
] | stackoverflow_0003108257_django_m2m_python.txt |
Q:
Django, creating user with add user permission
I have gone through a strange behavior while creating a user, using Django admin interface.
I have to create a user which can add other users, but for that Django requires two permissions i.e. add user and change user. But when I gave user the change permission, its e... | Django, creating user with add user permission | I have gone through a strange behavior while creating a user, using Django admin interface.
I have to create a user which can add other users, but for that Django requires two permissions i.e. add user and change user. But when I gave user the change permission, its even able to change the superuser of the site.
What ... | [
"This isn't supported by default in Django. You could subclass the normal UserAdmin and make your own, that disables the \"superuser\"-checkbox for non-superusers:\nfrom django.contrib.auth.admin import UserAdmin\nfrom django.contrib.auth.models import User\nfrom django.contrib import admin\n\nclass MyUserAdmin(Use... | [
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0003109335_django_python.txt |
Q:
Generate a waveform image from an audio file
Building a python application that converts raw audio files into wave using sox on a linux system. I want it to be able to generate an image (PNG or Jpeg) of the audio waveform pattern but I am unable to find a command line tool or python package that will do this. Not ... | Generate a waveform image from an audio file | Building a python application that converts raw audio files into wave using sox on a linux system. I want it to be able to generate an image (PNG or Jpeg) of the audio waveform pattern but I am unable to find a command line tool or python package that will do this. Not being an experience Python programmer my options a... | [
"If you can get the raw audio data as a list of numbers, you can use matplotlib to draw your waveform as a chart. The code would look something like this:\nmatplotlib.pyplot.plot(raw_audio_data)\n\n"
] | [
4
] | [] | [] | [
"audio",
"linux",
"python",
"sox"
] | stackoverflow_0003109260_audio_linux_python_sox.txt |
Q:
C++ or Python (maybe else) to create GUI for console application in C
I have a Visual C console application (created in VC++2008EE) and I need to add GUI to it.
One idea was to invoke the console app as a subprocess and communicate with it using stdin and stdout. I tried to do that with Python subprocess module - ... | C++ or Python (maybe else) to create GUI for console application in C | I have a Visual C console application (created in VC++2008EE) and I need to add GUI to it.
One idea was to invoke the console app as a subprocess and communicate with it using stdin and stdout. I tried to do that with Python subprocess module - but it deadlocks (probably because my console app is running continuously).... | [
"If you own the code for the console app, don't mess around trying to talk to it using input and output streams. Extract the logic of your console app into a library, and call that library from a GUI of your choice - either Windows.Forms from C#, Python GTK, ordinary GTK. \n",
"The reason that VS turns your appli... | [
5,
1
] | [] | [] | [
"c",
"c++",
"console_application",
"python",
"user_interface"
] | stackoverflow_0003109565_c_c++_console_application_python_user_interface.txt |
Q:
dynamic module creation
I'd like to dynamically create a module from a dictionary, and I'm wondering if adding an element to sys.modules is really the best way to do this. EG
context = { a: 1, b: 2 }
import types
test_context_module = types.ModuleType('TestContext', 'Module created to provide a context for tests'... | dynamic module creation | I'd like to dynamically create a module from a dictionary, and I'm wondering if adding an element to sys.modules is really the best way to do this. EG
context = { a: 1, b: 2 }
import types
test_context_module = types.ModuleType('TestContext', 'Module created to provide a context for tests')
test_context_module.__dict_... | [
"Hmm, well one thing I can tell you is that the timeit function actually executes its code using the module's global variables. So in your example, you could write\nimport timeit\ntimeit.a = 1\ntimeit.b = 2\ntimeit.Timer('a + b').timeit()\n\nand it would work. But that doesn't address your more general problem of d... | [
4
] | [] | [] | [
"dynamic",
"module",
"python",
"timing"
] | stackoverflow_0002931950_dynamic_module_python_timing.txt |
Q:
Django Form Display Meta
I am still on Django tutorial and currently here:
def display_meta(request):
values = request.META.items()
values.sort()
html = []
for k, v in values:
html.append('<tr><td>%s</td><td>%s</td></tr>' % (k, v))
return HttpResponse('<table>%s</table>' % '\n'.join(htm... | Django Form Display Meta | I am still on Django tutorial and currently here:
def display_meta(request):
values = request.META.items()
values.sort()
html = []
for k, v in values:
html.append('<tr><td>%s</td><td>%s</td></tr>' % (k, v))
return HttpResponse('<table>%s</table>' % '\n'.join(html))
I understand what it is m... | [
"Is the method of iterating a Python dictionary {'key':value, ...}\nk is the key and v is its value.\n"
] | [
1
] | [] | [] | [
"python"
] | stackoverflow_0003109741_python.txt |
Q:
How to delete specific tags
I have the following XML file:
<book>
<bookname child="test">
<text> Works </text>
<text> Doesn't work </text>
</bookname>
</book>
This is just a one block, there are more than one <bookname> tags. I need to iterate through the whole document and remove specific <text> tags. How ... | How to delete specific tags | I have the following XML file:
<book>
<bookname child="test">
<text> Works </text>
<text> Doesn't work </text>
</bookname>
</book>
This is just a one block, there are more than one <bookname> tags. I need to iterate through the whole document and remove specific <text> tags. How do I do that?
My approach is to c... | [
"Just call parentNode.remove(childNode). Something like this:\n>>> etree.tostring(tree)\n'<book> <bookname child=\"test\"> <text> Works </text> <text> Doesnt work </text> </bookname></book>'\n>>> bookname=tree[0]\n>>> text2=bookname[1]\n>>> bookname.remove(text2)\n>>> etree.tostring(tree)\n'<book> <bookname ch... | [
1
] | [] | [] | [
"lxml",
"python"
] | stackoverflow_0003109794_lxml_python.txt |
Q:
How to define the "MODULE DOCS" for display with pydoc?
The pydoc documentation of some Python modules (like math and sys) has a "MODULE DOCS" section that contains a useful link to some HTML documentation:
Help on module math:
NAME
math
FILE
/sw/lib/python2.6/lib-dynload/math.so
MODULE DOCS
/sw/sha... | How to define the "MODULE DOCS" for display with pydoc? | The pydoc documentation of some Python modules (like math and sys) has a "MODULE DOCS" section that contains a useful link to some HTML documentation:
Help on module math:
NAME
math
FILE
/sw/lib/python2.6/lib-dynload/math.so
MODULE DOCS
/sw/share/doc/python26/html/math.html
How can such a section be inc... | [
"After looking in the code of the pydoc module, I think that the \"MODULE DOCS\" link is only available for standard modules, not custom ones.\nHere is the relevant code:\ndef getdocloc(self, object):\n \"\"\"Return the location of module docs or None\"\"\"\n\n try:\n file = inspect.getabsfile(object)\... | [
3,
0
] | [] | [] | [
"module",
"pydoc",
"python"
] | stackoverflow_0003078735_module_pydoc_python.txt |
Q:
Python: problem processing a string
I have a string as follows:
names = "name:fred, name:wilma, name:barney, name2:gauss, name2:riemann"
let's say the string names has name and name2 attributes.
How do I write a function, is_name_attribute(), that checks if a value is a name attribute? That is is_name_attribute('... | Python: problem processing a string | I have a string as follows:
names = "name:fred, name:wilma, name:barney, name2:gauss, name2:riemann"
let's say the string names has name and name2 attributes.
How do I write a function, is_name_attribute(), that checks if a value is a name attribute? That is is_name_attribute('fred') should return True, whereas is_nam... | [
"Something like this:\n>>> names = \"name:fred, name:wilma, name:barney, name2:gauss, name2:riemann\"\n>>> pairs = [x.split(':') for x in names.split(\", \")]\n>>> attrs = [x[1] for x in pairs if x[0]=='name']\n>>> attrs \n['fred', 'wilma', 'barney']\n>>> def is_name_attribute(x):\n... return x in attrs\n...\n>... | [
5,
0,
0
] | [
"I think writing als this stuff in a String is not the best solution, but:\nimport re\n\nnames = \"name:fred, name:wilma, name:barney, name2:gauss, name2:riemann\"\n\ndef is_name_attribute(names, name):\n list = names.split()\n compiler = re.compile('^name:(.*)$')\n for line in list:\n line = line.r... | [
-1
] | [
"data_structures",
"python",
"string"
] | stackoverflow_0003110053_data_structures_python_string.txt |
Q:
UnicodeEncodeError: 'ascii' codec can't encode character when trying a HTTP POST in Python
I'm trying to do a HTTP POST with a unicode string (u'\xe4\xf6\xfc') as a parameter in Python, but I receive the following error:
UnicodeEncodeError: 'ascii' codec can't encode character
This is to the code used to make the ... | UnicodeEncodeError: 'ascii' codec can't encode character when trying a HTTP POST in Python | I'm trying to do a HTTP POST with a unicode string (u'\xe4\xf6\xfc') as a parameter in Python, but I receive the following error:
UnicodeEncodeError: 'ascii' codec can't encode character
This is to the code used to make the HTTP POST (with httplib2)
http = httplib2.Http()
userInfo = [('Name', u'\xe4\xf6\xfc')]
dat... | [
"You cannot POST Python Unicode objects directly. You should encode it as a UTF-8 string first:\nname = u'\\xe4\\xf6\\xfc'.encode('utf-8')\nuserInfo = [('Name', name)]\n\n"
] | [
13
] | [] | [] | [
"ascii",
"http_post",
"python",
"unicode"
] | stackoverflow_0003110104_ascii_http_post_python_unicode.txt |
Q:
How to open write reserved excel file in python with win32com?
I'm trying to open a write-protected ms excel 2007 file using win32com in python -- I know the password. I can open it with user input of the password into the excel dialog box. I want to be able to open the file without any user interaction. I've t... | How to open write reserved excel file in python with win32com? | I'm trying to open a write-protected ms excel 2007 file using win32com in python -- I know the password. I can open it with user input of the password into the excel dialog box. I want to be able to open the file without any user interaction. I've tried the following, but it still pops up the dialog box.
app.Workboo... | [
"I can get the above code to work if I don't try to use named function parameters. I.e. the following works:\napp.Workbooks.Open(\"filename.xls\", 2, True, None, None, \"secret\")\n\n"
] | [
3
] | [] | [] | [
"excel",
"python",
"win32com"
] | stackoverflow_0002887339_excel_python_win32com.txt |
Q:
Algorithm to calculate percent difference between two blobs of text
I've been researching on finding an efficient solution to this. I've looked into diffing engines (google's diff-match-patch, python's diff) and some some longest common chain algorithms.
I was hoping on getting you guys suggestions on how to solv... | Algorithm to calculate percent difference between two blobs of text | I've been researching on finding an efficient solution to this. I've looked into diffing engines (google's diff-match-patch, python's diff) and some some longest common chain algorithms.
I was hoping on getting you guys suggestions on how to solve this issue. Any algorithm or library in particular you would like to re... | [
"I don't know what \"longest common [[chain? substring?]]\" has to do with \"percent difference\", especially after seeing in a comment that you expect a very small % difference between two strings that differ by one character in the middle (so their longest common substring is about one half of the strings' length... | [
6,
2,
1,
0
] | [] | [] | [
"algorithm",
"python",
"string"
] | stackoverflow_0003106994_algorithm_python_string.txt |
Q:
Django template doesn't render a Variable's method
I am obviously victim of some dark magic...
Here is a template that I render :
context = Context({'my_cube': c})
template = Template(
'{% load cube_templatetags %}'
'{{ my_cube|inspect }} {{ my_cube.measure }}'
)
Here is the implementation of the inspect ... | Django template doesn't render a Variable's method | I am obviously victim of some dark magic...
Here is a template that I render :
context = Context({'my_cube': c})
template = Template(
'{% load cube_templatetags %}'
'{{ my_cube|inspect }} {{ my_cube.measure }}'
)
Here is the implementation of the inspect filter :
def inspect_object(obj):
return obj.measure... | [
"Well... I found the damn thing !\nThe object I was trying to render had a __getitem__ method that was just empty, so dictionnary indexing worked on this object (no error thrown), so of course the function call was not made !\n",
"Inspect is being registered as a filter, yep? I'm assuming so else the whole templa... | [
2,
0
] | [] | [] | [
"django",
"django_templates",
"python"
] | stackoverflow_0003109951_django_django_templates_python.txt |
Q:
Why type(classInstance) is returning 'instance'?
I have a method that accepts a parameter that can be of several types, and has to do one thing or other depending on the type, but if I check the type of said parameter, I don't get the 'real' type, I always get <type 'instance'>, and that is messing up with my comp... | Why type(classInstance) is returning 'instance'? | I have a method that accepts a parameter that can be of several types, and has to do one thing or other depending on the type, but if I check the type of said parameter, I don't get the 'real' type, I always get <type 'instance'>, and that is messing up with my comparisons.
I have something like:
from classes import C... | [
"Old-style classes do that. Derive your classes from object in their definitions.\n",
"you should really use isinstance:\nIn [26]: def foo(param):\n ....: print type(param)\n ....: print isinstance(param, Class1)\n ....:\n\nIn [27]: foo(x)\n<type 'instance'>\nTrue\n\nType is better for built-in type... | [
16,
10,
9
] | [] | [] | [
"class",
"instance",
"python",
"types"
] | stackoverflow_0003110624_class_instance_python_types.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.