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:
Could use some help with this soundex coding
The US census bureau uses a special encoding called “soundex” to locate information about a person. The soundex is an encoding of surnames (last names) based on the way a surname sounds rather than the way it is spelled. Surnames that sound the same, but are spelled dif... | Could use some help with this soundex coding | The US census bureau uses a special encoding called “soundex” to locate information about a person. The soundex is an encoding of surnames (last names) based on the way a surname sounds rather than the way it is spelled. Surnames that sound the same, but are spelled differently, like SMITH and SMYTH, have the same code... | [
"A few hints:\n\nBy using an array where each Soundex code is stored and indexed by the ASCII value (or a value in a shorter numeric range derived thereof) of the letter it corresponds to, you will both make the code for efficient and more readable. This is a very common technique: understand, use and reuse ;-)\nAs... | [
0,
0
] | [] | [] | [
"python",
"soundex"
] | stackoverflow_0001562438_python_soundex.txt |
Q:
Python - Overwriting __getattribute__ for an instance?
This one seems a bit tricky to me. Sometime ago I already managed to overwrite an instance's method with something like:
def my_method(self, attr):
pass
instancemethod = type(self.method_to_overwrite)
self.method_to_overwrite = instancemethod(my_method, s... | Python - Overwriting __getattribute__ for an instance? | This one seems a bit tricky to me. Sometime ago I already managed to overwrite an instance's method with something like:
def my_method(self, attr):
pass
instancemethod = type(self.method_to_overwrite)
self.method_to_overwrite = instancemethod(my_method, self, self.__class__)
which worked very well for me; but now... | [
"You want to override the attribute lookup algorithm on an per instance basis? Without knowing why you are trying to do this, I would hazard a guess that there is a cleaner less convoluted way of doing what you need to do. If you really need to then as Aaron said, you'll need to install a redirecting __getattribute... | [
6,
4,
2,
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0001560853_django_python.txt |
Q:
How to encrypt text into a image using python
I was wondering how can someone use python to encrypt text into an image.
A:
Google search for "python steganography" and you find some stuff.
Here's a Python library module: stepic
| How to encrypt text into a image using python | I was wondering how can someone use python to encrypt text into an image.
| [
"Google search for \"python steganography\" and you find some stuff.\nHere's a Python library module: stepic\n"
] | [
7
] | [] | [] | [
"python",
"steganography"
] | stackoverflow_0001562664_python_steganography.txt |
Q:
How to make complex contains queries in Django?
I need to make query like this:
WHERE Comment like '%ev% 3628%' or Comment like '%ew% 3628%'
the number '3628' is a parametr. So I've tried in my view:
First try:
wherestr = "Comment like '%%ev%% %s%%' or Comment like '%%ew%% %s%%'" % (rev_number, rev_number) ... | How to make complex contains queries in Django? | I need to make query like this:
WHERE Comment like '%ev% 3628%' or Comment like '%ew% 3628%'
the number '3628' is a parametr. So I've tried in my view:
First try:
wherestr = "Comment like '%%ev%% %s%%' or Comment like '%%ew%% %s%%'" % (rev_number, rev_number)
comment_o = Issuecomments.objects.extra(where=[whe... | [
"You need something similar to this:\nfrom django.db.models import Q\n\ndef myview(request):\n query = \"hi\" #string to search for\n items = self.filter(Q(comment__contains=query) | Q(comment__contains=query))\n ...\n\nJust make sure the query string is properly escaped.\n",
"You almost got it right... Th... | [
1,
1,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0001557850_django_python.txt |
Q:
Python procedure return values
In Python it's possible to create a procedure that has no explicit return. i.e.:
def test(val):
if 0 == val:
return 8
Further, it's possible to assign the results of that function to a variable:
>>> a = test(7)
>>> print `a`
'None'
Why the heck is that? What language l... | Python procedure return values | In Python it's possible to create a procedure that has no explicit return. i.e.:
def test(val):
if 0 == val:
return 8
Further, it's possible to assign the results of that function to a variable:
>>> a = test(7)
>>> print `a`
'None'
Why the heck is that? What language logic is behind that baffling design ... | [
"While every function might not have an explicit return it will have an implicit one, that is None, which incidentally is a normal Python object. Further, functions often return None explicitly.\nI suppose returning None implicitly is just an ease-of-use optimisation.\nP.S. I wonder what you propose compile would ... | [
28,
12,
8,
3,
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0001563074_python.txt |
Q:
URLs stored in database for Django site
I've produced a few Django sites but up until now I have been mapping individual views and URLs in urls.py.
Now I've tried to create a small custom CMS but I'm having trouble with the URLs. I have a database table (SQLite3) which contains code for the pages like a column for... | URLs stored in database for Django site | I've produced a few Django sites but up until now I have been mapping individual views and URLs in urls.py.
Now I've tried to create a small custom CMS but I'm having trouble with the URLs. I have a database table (SQLite3) which contains code for the pages like a column for header, one for right menu, one for content.... | [
"You dont have to to it in the flatpage-way\nFor models, that should be addressable, I do this:\nIn urls.py I have a url-mapping like\n url(r'(?P<slug>[a-z1-3_]{1,})/$','cms.views.category_view', name=\"category-view\")\n\nin this case the regular expression (?P<slug>[a-z1-3_]{1,}) will return a variable called sl... | [
6,
1
] | [] | [] | [
"content_management_system",
"database",
"django",
"python",
"url"
] | stackoverflow_0001563088_content_management_system_database_django_python_url.txt |
Q:
Python library/framework to write an application that sends emails periodically
I am considering to write an application that would covert the comments in reddit threads (example) to emails. The idea is to parse the reddit json data (example) and send new comments as plain EMails to subscribed users. One of the us... | Python library/framework to write an application that sends emails periodically | I am considering to write an application that would covert the comments in reddit threads (example) to emails. The idea is to parse the reddit json data (example) and send new comments as plain EMails to subscribed users. One of the users can be gmane, so you can also read the comments over there. The motivation for wr... | [
"I would go with AppEngine to tackle this: integrated cron + email support.\n",
"I've used Flexget to parse RSS feeds and email them.\nYou can get ideas from there.\n",
"Lamson aims to be an 'email app framework' (taking after the recent developments in web app frameworks). It seems like it would be a good fit ... | [
1,
0,
0
] | [] | [] | [
"email",
"frameworks",
"python",
"reddit"
] | stackoverflow_0001563468_email_frameworks_python_reddit.txt |
Q:
Install custom modules in a python virtual enviroment
I am doing some pylons work in a virtual python enviorment, I want to use MySQL with SQLalchemy but I can't install the MySQLdb module on my virtual enviorment, I can't use easyinstall because I am using a version that was compiled for python 2.6 in a .exe form... | Install custom modules in a python virtual enviroment | I am doing some pylons work in a virtual python enviorment, I want to use MySQL with SQLalchemy but I can't install the MySQLdb module on my virtual enviorment, I can't use easyinstall because I am using a version that was compiled for python 2.6 in a .exe format, I tried running the install from inside the virtual en... | [
"Ok Got it all figured out, After I installed the module on my normal python 2.6 install I went into my Python26 folder and low and behold I happened to find a file called MySQL-python-wininst which happened to be a list of all of the installed module files. Basicly it was two folders called MySQLdb and another cal... | [
0
] | [] | [] | [
"module",
"mysql",
"pylons",
"python",
"virtualenv"
] | stackoverflow_0001557972_module_mysql_pylons_python_virtualenv.txt |
Q:
Retrieving and displaying UTF-8 from a .CSV in Python
Basically I have been having real fun with this today. I have this data file called test.csv which is encoded as UTF-8:
"Nguyễn", 0.500
"Trần", 0.250
"Lê", 0.250
Now I am attempting to read it with this code and it displays all funny like this: Trần
Now I hav... | Retrieving and displaying UTF-8 from a .CSV in Python | Basically I have been having real fun with this today. I have this data file called test.csv which is encoded as UTF-8:
"Nguyễn", 0.500
"Trần", 0.250
"Lê", 0.250
Now I am attempting to read it with this code and it displays all funny like this: Trần
Now I have gone through all the Python docs for 2.6 which is the one... | [
"unicode_csv_reader(open(familynamelist)) is trying to pass non-unicode data (byte strings with utf-8 encoding) to a function you wrote expecting unicode data. You could solve the problem with codecs.open (from standard library module codecs), but that's to roundabout: the codecs would be doing utf8->unicode for y... | [
1,
0
] | [
"There's the unicode_csv_reader demo in the python docs:\nhttp://docs.python.org/library/csv.html\n"
] | [
-2
] | [
"csv",
"python",
"utf_8"
] | stackoverflow_0001561833_csv_python_utf_8.txt |
Q:
Bundle additional executables with py2exe
I have a python script that calls out to two Sysinternals tools (sigcheck and accesschk). Is there a way I can bundle these executables into a py2exe so that subprocess.Popen can see it when it runs?
Full explanation: My script is made to execute over a network share (S:\... | Bundle additional executables with py2exe | I have a python script that calls out to two Sysinternals tools (sigcheck and accesschk). Is there a way I can bundle these executables into a py2exe so that subprocess.Popen can see it when it runs?
Full explanation: My script is made to execute over a network share (S:\share\my_script.exe) and it makes hundreds of c... | [
"I could be wrong about this, but I don't believe this is what py2exe was intended for. It's more about what you're distributing than about how you're distributing. I think what you may be looking for is the option to create a windows installer. You could probably add the executables as data files or scripts usi... | [
2
] | [] | [] | [
"bundle",
"executable",
"py2exe",
"python"
] | stackoverflow_0001563948_bundle_executable_py2exe_python.txt |
Q:
List of tuples to Numpy recarray
Given a list of tuples, where each tuple represents a row in a table, e.g.
tab = [('a',1),('b',2)]
Is there an easy way to convert this to a record array? I tried
np.recarray(tab,dtype=[('name',str),('value',int)])
which doesn't seem to work.
A:
try
np.rec.fromrecords(tab)
rec... | List of tuples to Numpy recarray | Given a list of tuples, where each tuple represents a row in a table, e.g.
tab = [('a',1),('b',2)]
Is there an easy way to convert this to a record array? I tried
np.recarray(tab,dtype=[('name',str),('value',int)])
which doesn't seem to work.
| [
"try\nnp.rec.fromrecords(tab)\n\nrec.array([('a', 1), ('b', 2)], \n dtype=[('f0', '|S1'), ('f1', '<i4')])\n\n"
] | [
4
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0001564000_numpy_python.txt |
Q:
Performance difference on insert-sort in C and python
I was curious about the performance of insert-sort using C and python but the results I've got just make me think if I've done something wrong. I suspected that C would be faster, but not that much.
I've profiled both codes and the insert-sort function is the p... | Performance difference on insert-sort in C and python | I was curious about the performance of insert-sort using C and python but the results I've got just make me think if I've done something wrong. I suspected that C would be faster, but not that much.
I've profiled both codes and the insert-sort function is the place where the time is most spent.
Here is the C function:
... | [
"Python is a dynamic language and the standard implementation uses an interpreter to evaluate code. This means that where the compiled C code can escape with a single machine instruction, for instance assigning to vec->v[i+1], Python's interpreter has to look up the sequence variable from the local scope, look up i... | [
13,
5,
4,
2
] | [
"What's wrong with:\nln.sort()\n\n"
] | [
-3
] | [
"c",
"performance",
"profiling",
"python"
] | stackoverflow_0001561596_c_performance_profiling_python.txt |
Q:
non-blocking read/log from an http stream
I have a client that connects to an HTTP stream and logs the text data it consumes.
I send the streaming server an HTTP GET request... The server replies and continuously publishes data... It will either publish text or send a ping (text) message regularly... and will ... | non-blocking read/log from an http stream | I have a client that connects to an HTTP stream and logs the text data it consumes.
I send the streaming server an HTTP GET request... The server replies and continuously publishes data... It will either publish text or send a ping (text) message regularly... and will never close the connection.
I need to read and ... | [
"Hey, that's three questions in one! ;-)\nIt could block sometimes - even if your server is generating data quite quickly, network bottlenecks could in theory cause your reads to block.\nReading the URL data using \"for dat in req\" will mean reading a line at a time - not really useful if you're reading binary dat... | [
6,
3,
2,
1
] | [] | [] | [
"http",
"logging",
"python",
"urllib2"
] | stackoverflow_0001557175_http_logging_python_urllib2.txt |
Q:
How does the Jinja2 "recursive" tag actually work?
I'm trying to write a very simple, tree-walking template in jinja2, using some custom objects with overloaded special methods (getattr, getitem, etc) It seems straightforward, and the equivalent python walk of the tree works fine, but there's something about the ... | How does the Jinja2 "recursive" tag actually work? | I'm trying to write a very simple, tree-walking template in jinja2, using some custom objects with overloaded special methods (getattr, getitem, etc) It seems straightforward, and the equivalent python walk of the tree works fine, but there's something about the way that Jinja's recursion works that I don't understand... | [
"As I see from your code you understand recursive correctly, except one thing: it does replace iterable in the for statement, but doesn't update variable (category in your code) originally used in it. Thus, you nested loop iterates through children, but set tag lookups in original category, not one passed to the lo... | [
8
] | [] | [] | [
"jinja2",
"python",
"recursion",
"templates"
] | stackoverflow_0001563276_jinja2_python_recursion_templates.txt |
Q:
python expression for this: max_value = max(firstArray) that is not in secondArray
I wasn't sure if there was any good way of doing this. But I thought I'd give stackoverflow a try :)
I have a list/array with integers, and a second array also with integers. I want to find the max value from the first list, but the... | python expression for this: max_value = max(firstArray) that is not in secondArray | I wasn't sure if there was any good way of doing this. But I thought I'd give stackoverflow a try :)
I have a list/array with integers, and a second array also with integers. I want to find the max value from the first list, but the value can not be in the second array.
Is there any "fancy" way in python to put this do... | [
"Use sets to get the values in firstArray that are not in secondArray:\nmax_value = max(set(firstArray) - set(secondArray))\n\n",
"Here's one way:\nmax_value = [x for x in sorted(first) if x not in second][0]\n\nIt's less efficient than sorting then using a for loop to test if elements are in the second array, bu... | [
12,
1
] | [] | [] | [
"expression",
"python"
] | stackoverflow_0001565095_expression_python.txt |
Q:
Extracting substrings at specified positions
How to extract substrings from a string at specified positions
For e.g.: ‘ABCDEFGHIJKLM’. I have To extract the substring from 3 to 6 and 8 to 10.
Required output: DEFG, IJK
Thanks in advance.
A:
Here you go
myString = 'ABCDEFGHIJKLM'
first = myString[3:7] # => DEFG... | Extracting substrings at specified positions | How to extract substrings from a string at specified positions
For e.g.: ‘ABCDEFGHIJKLM’. I have To extract the substring from 3 to 6 and 8 to 10.
Required output: DEFG, IJK
Thanks in advance.
| [
"Here you go\nmyString = 'ABCDEFGHIJKLM'\nfirst = myString[3:7] # => DEFG\nsecond = myString[8:11] # => IJK\n\nIn the slicing syntax, the first number is inclusive and the second is excluded.\nYou can read more about String slicing from python docs\n",
"Look into Python's concept called sequence slicing!\n",
"a... | [
8,
3,
3,
2,
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0001564414_python.txt |
Q:
How to get multiple properties at the same time?
I am using Appscript - a Python interface to AppleScript - in a project of mine that basically gets data from a Mac application.
Here is a sample code:
asobj = app('Things').to_dos()[0]
self.id = asobj.id()
self.name = asobj.name()
self.status = asob... | How to get multiple properties at the same time? | I am using Appscript - a Python interface to AppleScript - in a project of mine that basically gets data from a Mac application.
Here is a sample code:
asobj = app('Things').to_dos()[0]
self.id = asobj.id()
self.name = asobj.name()
self.status = asobj.status()
Every invocation of the properties (id, na... | [
"I'm not 100% sure how this would be expressed in Python, but most Applescript objects support a \"properties\" property which will return a dictionary containing key/value pairs for each of the supported properties of that object. I'm guessing that calling asobj.properties() would return an appropriate data struc... | [
3,
0
] | [] | [] | [
"macos",
"py_appscript",
"python",
"sourceforge_appscript"
] | stackoverflow_0001557910_macos_py_appscript_python_sourceforge_appscript.txt |
Q:
Python: imports at the beginning of the main program & PEP 8
The PEP 8 recommends that modules be imported at the beginning of programs.
Now, I feel that importing some of them at the beginning of the main program (i.e., after if __name__ == '__main__') makes sense. For instance, if the main program reads argumen... | Python: imports at the beginning of the main program & PEP 8 | The PEP 8 recommends that modules be imported at the beginning of programs.
Now, I feel that importing some of them at the beginning of the main program (i.e., after if __name__ == '__main__') makes sense. For instance, if the main program reads arguments from the command line, I tend to do import sys at the beginning... | [
"I can't really tell you how bad this is to do.\nHowever, I've greatly improved performance (response time, load) for a web app by importing certain libraries only at the first usage.\nBTW, the following is also from PEP 8:\n\nBut most importantly: know when to be\n inconsistent -- sometimes the style \n guide ju... | [
9,
6,
2,
2,
2
] | [] | [] | [
"import",
"pep",
"pep8",
"program_entry_point",
"python"
] | stackoverflow_0001565173_import_pep_pep8_program_entry_point_python.txt |
Q:
CMake output name for dynamic-loaded library?
I'm trying to write cmake rules to build dynamic-loaded library for python using boost.python on linux. I'd like to use 'foo' for python module name. So, the library must be called foo.so.
But by default, cmake uses standard rules for library naming, so if I write
add_... | CMake output name for dynamic-loaded library? | I'm trying to write cmake rules to build dynamic-loaded library for python using boost.python on linux. I'd like to use 'foo' for python module name. So, the library must be called foo.so.
But by default, cmake uses standard rules for library naming, so if I write
add_library(foo foo.cpp)
I will get libfoo.so on outpu... | [
"You can unset the prefix with this line:\nset_target_properties(foo PROPERTIES PREFIX \"\")\n\n",
"The prefix \"lib\" is a convention for unix/linux and is exploited widely by compilers (e.g. when you link you write -lfoo). \nI don't know if you can force cmake to create foo.so instead of libfoo.so, but maybe yo... | [
57,
1
] | [] | [] | [
"boost_python",
"cmake",
"python",
"shared_libraries"
] | stackoverflow_0001564696_boost_python_cmake_python_shared_libraries.txt |
Q:
python csv help
Sometimes I need to parse string that is CSV, but I am having trouble whit quoted comas. As this code demonstrated. I am using python 2.4
import csv
for row in csv.reader(['one",f",two,three']):
print row
i get 4 elements ['one"', 'f"', 'two', 'three'] but I would like to get this ['one", f"'... | python csv help | Sometimes I need to parse string that is CSV, but I am having trouble whit quoted comas. As this code demonstrated. I am using python 2.4
import csv
for row in csv.reader(['one",f",two,three']):
print row
i get 4 elements ['one"', 'f"', 'two', 'three'] but I would like to get this ['one", f"', 'two', 'three'] or ... | [
"Actually the result you get is correct—your CSV syntax is wrong.\nIf you want to quote commas or other characters in a CSV value, you have to use quotes surrounding the whole value, not parts of it. If a value does not start with the quote character, Python's CSV implementation does not assume the value is quoted.... | [
6,
3,
1
] | [] | [] | [
"csv",
"python"
] | stackoverflow_0001565566_csv_python.txt |
Q:
Python newbie - Understanding class functions
If you take the following simple class:
class AltString:
def __init__(self, str = "", size = 0):
self._contents = str
self._size = size
self._list = [str]
def append(self, str):
self._list.append(str)
def output(self):
... | Python newbie - Understanding class functions | If you take the following simple class:
class AltString:
def __init__(self, str = "", size = 0):
self._contents = str
self._size = size
self._list = [str]
def append(self, str):
self._list.append(str)
def output(self):
return "".join(self._list)
And I successfully... | [
"as is a bad variable name, it is reserved keyword in Python. don't name your variables like this. once you fix it, everything else will be alright. of course you should be doing: \nalt_str.output()\n\nedit: I was able to replicate your error messages when trying to apply output to the class: AltString.output, then... | [
8,
1,
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0001566314_python.txt |
Q:
What is an "app" in Django?
According to the documentation:
An app is a Web application that does
something -- e.g., a weblog system, a
database of public records or a simple
poll app. A project is a collection of
configuration and apps for a
particular Web site. A project can
contain multiple apps. A... | What is an "app" in Django? | According to the documentation:
An app is a Web application that does
something -- e.g., a weblog system, a
database of public records or a simple
poll app. A project is a collection of
configuration and apps for a
particular Web site. A project can
contain multiple apps. An app can be
in multiple projec... | [
"What makes an app (for us) is one thing:\nAn App Is The Unit Of Reuse\nIf we might want to split it off to use somewhere else, it's an app. \nIf it has a reusable data model, it's an app. User Profiles: App. Customers: App. Customer Statistical History (this is hard to explain without providing too many detail... | [
14,
5,
2
] | [] | [] | [
"django",
"python"
] | stackoverflow_0001563457_django_python.txt |
Q:
Separating Models and Request Handlers In Google App Engine
I'd like to move my models to a separate directory, similar to the way it's done with Rails to cut down on code clutter. Is there any way to do this easily?
Thanks,
Collin
A:
I assume you're using the basic webkit and not Django or something fancy. In ... | Separating Models and Request Handlers In Google App Engine | I'd like to move my models to a separate directory, similar to the way it's done with Rails to cut down on code clutter. Is there any way to do this easily?
Thanks,
Collin
| [
"I assume you're using the basic webkit and not Django or something fancy. In that case just create a subdirectory called models. Put any python files you use for your models in here. Create also one blank file in this folder called __init__.py.\nThen in your main.py or \"controller\" or what have you, put:\nimport... | [
7,
1
] | [] | [] | [
"google_app_engine",
"model",
"python"
] | stackoverflow_0000652449_google_app_engine_model_python.txt |
Q:
Is there a dictionary that contains the function's parameters in Python?
I'd like to be able to get a dictionary of all the parameters passed to a function.
def myfunc( param1, param2, param3 ):
print 'Param1=%(param1)s, Param2=%(param2)s Param3=%(param3)' % __method_param_dict__
So my question is does the di... | Is there a dictionary that contains the function's parameters in Python? | I'd like to be able to get a dictionary of all the parameters passed to a function.
def myfunc( param1, param2, param3 ):
print 'Param1=%(param1)s, Param2=%(param2)s Param3=%(param3)' % __method_param_dict__
So my question is does the dictionary method_param_dict exist, and if so what is it called.
Thanks
| [
"A solution for your specific example:\ndef myfunc(param1, param2, param3):\n dict_param = locals()\n\nBut be sure to have a look at this article for a complete explanation of the possiblities (args, kwargs, mixed etc...)\n",
"If you need to do that, you should use *args and **kwargs.\ndef foo(*args, **kwargs)... | [
7,
3,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0001566878_python.txt |
Q:
Why is BeautifulSoup modifying my self-closing elements?
This is the script I have:
import BeautifulSoup
if __name__ == "__main__":
data = """
<root>
<obj id="3"/>
<obj id="5"/>
<obj id="3"/>
</root>
"""
soup = BeautifulSoup.BeautifulStoneSoup(data)
print soup
When... | Why is BeautifulSoup modifying my self-closing elements? | This is the script I have:
import BeautifulSoup
if __name__ == "__main__":
data = """
<root>
<obj id="3"/>
<obj id="5"/>
<obj id="3"/>
</root>
"""
soup = BeautifulSoup.BeautifulStoneSoup(data)
print soup
When ran, this prints:
<root>
<obj id="3"></obj>
<obj id="5"><... | [
"From the Beautiful Soup documentation:\n\nThe most common shortcoming of BeautifulStoneSoup is that it doesn't know about self-closing tags. HTML has a fixed set of self-closing tags, but with XML it depends on what the DTD says. You can tell BeautifulStoneSoup that certain tags are self-closing by passing in thei... | [
7
] | [] | [] | [
"beautifulsoup",
"python",
"xml"
] | stackoverflow_0001567402_beautifulsoup_python_xml.txt |
Q:
Wrapping an interactive command line application in a Python script
I am interested in controlling an interactive CLI application from Python calls.
I guess at the most basic level I need a Python script that will start a CLI application on the host operating system. Pipe anything from standard input to the CLI ap... | Wrapping an interactive command line application in a Python script | I am interested in controlling an interactive CLI application from Python calls.
I guess at the most basic level I need a Python script that will start a CLI application on the host operating system. Pipe anything from standard input to the CLI application, and then pipe any output from the CLI application to standard ... | [
"Maybe you want something from Subprocess (MOTW).\nI use code like this to make calls out to the shell:\nfrom subprocess import Popen, PIPE\n\n## shell out, prompt\ndef shell(args, input_=''):\n ''' uses subprocess pipes to call out to the shell.\n \n args: args to the command\n input: stdin\n \n ... | [
16,
11
] | [] | [] | [
"command_line",
"python"
] | stackoverflow_0001567371_command_line_python.txt |
Q:
Validate XML against DTD using python on google app engine
I've got validation working on client side using lxml, but I'm not quite sure how to get it work on Google App Engine, since it doesn't have the lxml package. I tried copying the whole lxml folder and place it in the root of my Google application, but it s... | Validate XML against DTD using python on google app engine | I've got validation working on client side using lxml, but I'm not quite sure how to get it work on Google App Engine, since it doesn't have the lxml package. I tried copying the whole lxml folder and place it in the root of my Google application, but it seems like it cannot use it properly. I'm guessing it has to do w... | [
"Compiled C extensions (like lxml) will not work on Google App Engine.\nPyXML is no longer maintained, but it does have a pure-Python XML validator. See this code snippet for an example.\n"
] | [
1
] | [] | [] | [
"dtd",
"google_app_engine",
"python",
"validation",
"xml"
] | stackoverflow_0001566951_dtd_google_app_engine_python_validation_xml.txt |
Q:
Python and random keys of 21 char max
I am using an api which takes a name of 21 char max to represent an internal session which has a lifetime of around "two days". I would like the name not to be meaningfull using some kind of hasing ? md5 generates 40 chars, is there something else i could use ?
For now i use '... | Python and random keys of 21 char max | I am using an api which takes a name of 21 char max to represent an internal session which has a lifetime of around "two days". I would like the name not to be meaningfull using some kind of hasing ? md5 generates 40 chars, is there something else i could use ?
For now i use 'userid[:10]' + creation time: ddhhmmss + ra... | [
"If I read your question correctly, you want to generate some arbitrary identifier token which must be 21 characters max. Does it need to be highly resistant to guessing? The example you gave isn't \"crytographically strong\" in that it can be guessed by searching well less than 1/2 of the entire possible keyspace.... | [
23,
4,
2,
2,
0
] | [] | [] | [
"encryption",
"key",
"python"
] | stackoverflow_0000621649_encryption_key_python.txt |
Q:
finding substring
Thanks in advance.
I have a string:
A = 'asdfghjklmn'
How can I get a substring having a maximum length which is a multiple of three?
A:
You can use slice notation and integer arithmetic.
>>> a = 'asdfghjklmn'
>>> a[:len(a)//3*3]
'asdfghjkl'
>>> len(a)
11
>>> len(a[:len(a)//3*3])
9
In ... | finding substring | Thanks in advance.
I have a string:
A = 'asdfghjklmn'
How can I get a substring having a maximum length which is a multiple of three?
| [
"You can use slice notation and integer arithmetic.\n>>> a = 'asdfghjklmn'\n>>> a[:len(a)//3*3]\n'asdfghjkl' \n>>> len(a)\n11\n>>> len(a[:len(a)//3*3])\n9\n\nIn general, n//k*k will yield the largest multiple of k less than or equal to n.\n",
"It seems like you're looking for something like this:\n>>> A = 'asdf... | [
4,
1,
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0001567607_python.txt |
Q:
Should I keep my Python code at 2.x or migrate to 3.x if I plan to eventually use Jython?
I have a large infrastructure that is written in Python 2.6, and I recently took a stab at porting to 3.1 (was much smoother than I expected) despite the lack of backwards compatibility.
I eventually want to integrate some of... | Should I keep my Python code at 2.x or migrate to 3.x if I plan to eventually use Jython? | I have a large infrastructure that is written in Python 2.6, and I recently took a stab at porting to 3.1 (was much smoother than I expected) despite the lack of backwards compatibility.
I eventually want to integrate some of this Python code with a lot of Java based code that we have, and was thinking about giving Jyt... | [
"Jython will not support Python 3.x in the near future. For your code, I recommend to keep it in 2.x form, such that 3.x support becomes available by merely running 2to3 (i.e. with no further source changes). IOW, port to 3.x in a way so that the code remains compatible with 2.x.\n",
"I would expect that the deve... | [
5,
0,
0
] | [] | [] | [
"jython",
"python"
] | stackoverflow_0001566411_jython_python.txt |
Q:
Decrypt MD5 hash
Is there any way to decrypt the encrypted MD5 string, given the key?
A:
MD5 is a one-way hash. It cannot be decrypted. The closest thing to decrypting an MD5 hash would be to do a lookup against a pre-generated rainbow table. Also, I'm not sure what you mean by "I have the key". There is no "key... | Decrypt MD5 hash | Is there any way to decrypt the encrypted MD5 string, given the key?
| [
"MD5 is a one-way hash. It cannot be decrypted. The closest thing to decrypting an MD5 hash would be to do a lookup against a pre-generated rainbow table. Also, I'm not sure what you mean by \"I have the key\". There is no \"key\" in an MD5 hash. Perhaps you are thinking of a salt? If your data has a salt value inc... | [
22,
5,
4,
4,
2
] | [] | [] | [
"cracking",
"cryptography",
"md5",
"python"
] | stackoverflow_0001562064_cracking_cryptography_md5_python.txt |
Q:
How can I view a text representation of an lxml element?
If I'm parsing an XML document using lxml, is it possible to view a text representation of an element?
I tried to do :
print repr(node)
but this outputs
<Element obj at b743c0>
What can I use to see the node like it exists in the XML file? Is there some ... | How can I view a text representation of an lxml element? | If I'm parsing an XML document using lxml, is it possible to view a text representation of an element?
I tried to do :
print repr(node)
but this outputs
<Element obj at b743c0>
What can I use to see the node like it exists in the XML file? Is there some to_xml method or something?
| [
"From http://lxml.de/tutorial.html#serialisation\n>>> root = etree.XML('<root><a><b/></a></root>')\n\n>>> etree.tostring(root)\nb'<root><a><b/></a></root>'\n\n>>> print(etree.tostring(root, xml_declaration=True))\n<?xml version='1.0' encoding='ASCII'?>\n<root><a><b/></a></root>\n\n>>> print(etree.tostring(root, enc... | [
45
] | [] | [] | [
"lxml",
"python",
"xml"
] | stackoverflow_0001567903_lxml_python_xml.txt |
Q:
deleting an object in a loop that runs through the range of the list?
I have a list composed of [start position, stop position, [sample names with those positions]]
My goal is to remove the duplicates with exact start and stop positions and just add the extra sample to the sample names section. The problem I'm e... | deleting an object in a loop that runs through the range of the list? | I have a list composed of [start position, stop position, [sample names with those positions]]
My goal is to remove the duplicates with exact start and stop positions and just add the extra sample to the sample names section. The problem I'm encountering is that when I delete from the list, I end up with an out of ra... | [
"I not sure I understand what you want, but it might be this:\nfrom collections import defaultdict\nd = defaultdict(list)\nfor start, stop, samples in L1:\n d[start, stop].extend(samples)\nL2 = [[start, stop, samples] for (start, stop), samples in d.items()]\n\nWhich will take L1:\nL1 = [ [1, 5, [\"a\", \"b\", \... | [
3,
2,
1,
0
] | [] | [] | [
"for_loop",
"list",
"python"
] | stackoverflow_0001567669_for_loop_list_python.txt |
Q:
What is a good example of an __eq__ method for a collection class?
I'm working on a collection class that I want to create an __eq__ method for. It's turning out to be more nuanced than I thought it would be and I've noticed several intricacies as far as how the built-in collection classes work.
What would really... | What is a good example of an __eq__ method for a collection class? | I'm working on a collection class that I want to create an __eq__ method for. It's turning out to be more nuanced than I thought it would be and I've noticed several intricacies as far as how the built-in collection classes work.
What would really help me the most is a good example. Are there any pure Python implemen... | [
"Parts are hard. Parts should be simple delegation.\ndef __eq__( self, other ):\n if len(self) != len(other):\n # Can we continue? If so, what rule applies? Pad shorter? Truncate longer?\n else:\n return all( self[i] == other[i] for i in range(len(self)) )\n\n",
"Take a look at \"collections.p... | [
7,
1
] | [] | [] | [
"api",
"collections",
"equality",
"python"
] | stackoverflow_0001560245_api_collections_equality_python.txt |
Q:
Python's libxml2 can't parse unicode strings
OK, the docs for Python's libxml2 bindings are really ****. My problem:
An XML document is stored in a string variable in Python. The string is a instance of Unicode, and there are non-ASCII characters in it. I want to parse it with libxml2, looking something like this:... | Python's libxml2 can't parse unicode strings | OK, the docs for Python's libxml2 bindings are really ****. My problem:
An XML document is stored in a string variable in Python. The string is a instance of Unicode, and there are non-ASCII characters in it. I want to parse it with libxml2, looking something like this:
# -*- coding: utf-8 -*-
import libxml2
DOC = u""... | [
"It should be\n# -*- coding: utf-8 -*-\nimport libxml2\n\nDOC = u\"\"\"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<data>\n <something>Bäääh!</something>\n</data>\n\"\"\".encode(\"UTF-8\")\n\nxml_doc = libxml2.parseDoc(DOC)\n\nThe .encode(\"UTF-8\") is needed to get the binary representation of the unicode string ... | [
9,
6
] | [] | [] | [
"libxml2",
"python",
"unicode",
"xml"
] | stackoverflow_0001569076_libxml2_python_unicode_xml.txt |
Q:
RPC for multiprocessing, design issues
what's a good way to do rpc across multiprocessing.Process'es ?
I am also open to design advise on the following architecture:
Process A * 10, Process B * 1. Each process A has to check with proces B on whether a particular item needs to be queried.
So I was thinking of imp... | RPC for multiprocessing, design issues | what's a good way to do rpc across multiprocessing.Process'es ?
I am also open to design advise on the following architecture:
Process A * 10, Process B * 1. Each process A has to check with proces B on whether a particular item needs to be queried.
So I was thinking of implementing multiprocessing.Pipe() object for ... | [
"Personally, I always tend to lean towards socket-based RPC, because that frees me from the confine of a single node if and when I need to expand more. Twisted offers a great way to handle socket-based communications, but of course there are other alternatives too. HTTP 1.1 is a great \"transport\" layer to use f... | [
6,
1,
1
] | [] | [] | [
"multiprocessing",
"python",
"rpc"
] | stackoverflow_0001353055_multiprocessing_python_rpc.txt |
Q:
Inserting two related objects fail in SQLAlchemy
I'm getting the (probably trivial) error, but completely clueless about the possible causes. I want to insert two object in the DB using SQLAlchemy. Those objects are related, here are the declarations. Class User:
class User(Base):
__tablename__ = 'cp_user'
... | Inserting two related objects fail in SQLAlchemy | I'm getting the (probably trivial) error, but completely clueless about the possible causes. I want to insert two object in the DB using SQLAlchemy. Those objects are related, here are the declarations. Class User:
class User(Base):
__tablename__ = 'cp_user'
id = Column(Integer, Sequence('id_seq'), primary_key... | [
"Your code fails if the not(user) branch is not taken.\nYou query User.name which is a column and not a bound object.\nuser = s.query(User).filter(\"...some filter here...\").first()\n\nAn object gets it's id designed as soon as it is transmitted to the database. You are doing this in the branch with a commit. This... | [
5
] | [] | [] | [
"orm",
"python",
"sql",
"sqlalchemy"
] | stackoverflow_0001569112_orm_python_sql_sqlalchemy.txt |
Q:
App Engine Python how to handle urls?
I just want to ask a simple question, as I don't imagine how to do it.
In the app.yaml, when I want to declare query string parameter, how do I do it?
For example, to make a multi language site, I create the url in this format:
mysite.com/english/aboutus
mysite.com/italiano/a... | App Engine Python how to handle urls? | I just want to ask a simple question, as I don't imagine how to do it.
In the app.yaml, when I want to declare query string parameter, how do I do it?
For example, to make a multi language site, I create the url in this format:
mysite.com/english/aboutus
mysite.com/italiano/aboutus
and in app.yaml the script to handl... | [
"I remember doing something like this:\nin app.yaml put\n- url: /(.*)/(.*)/?\n script: main.py\n\nand in main.py\nclass MainHandler(webapp.RequestHandler):\n def get(self, Urlpart1, Urlpart2):\n\ndef main():\n application = webapp.WSGIApplication([('/(.*)/(.*)/', MainHandler),\n ... | [
4,
2,
1,
0
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0001499485_google_app_engine_python.txt |
Q:
Library to read a MySQL dump?
I am looking for a library that will allow me to read a mysql dump.
I don't want to have to create a MySQL database and import the library and use the MySQL API. I would prefer simply a library that can parse the mysql dump format.
I prefer a python library, but other scripting langua... | Library to read a MySQL dump? | I am looking for a library that will allow me to read a mysql dump.
I don't want to have to create a MySQL database and import the library and use the MySQL API. I would prefer simply a library that can parse the mysql dump format.
I prefer a python library, but other scripting languages are okay.
| [
"Import into MySQL and dump using --xml seems to be the best option.\nI wrote up the reasoning in this blog post: Use flag –xml when you run mysqldump\n",
"I came across sqldump.py while looking for something similar - might be of use...\n"
] | [
5,
1
] | [] | [] | [
"api",
"mysql",
"mysqldump",
"python"
] | stackoverflow_0001568838_api_mysql_mysqldump_python.txt |
Q:
How to use Python to log into Facebook/Myspace and crawl the content?
Right now, I can crawl regular pages using urllib2.
request = urllib2.Request('http://stackoverflow.com')
request.add_header('User-Agent',random.choice(agents))
response = urllib2.urlopen(request)
htmlSource = response.read()
print htmlSource
H... | How to use Python to log into Facebook/Myspace and crawl the content? | Right now, I can crawl regular pages using urllib2.
request = urllib2.Request('http://stackoverflow.com')
request.add_header('User-Agent',random.choice(agents))
response = urllib2.urlopen(request)
htmlSource = response.read()
print htmlSource
However...I would like to simulate a POST (or fake sessions)? so that I can ... | [
"You'll need to keep the cookie your site of choice sends you when you log in; that's what keeps your session. With urllib2, you do this by creating an Opener object that supports cookie processing:\nimport urllib2, cookielib\njar = cookielib.CookieJar()\nopener = urllib2.build_opener(urllib2.HTTPCookieProcessor(ja... | [
7,
4,
1,
1
] | [] | [] | [
"authentication",
"post",
"python",
"session",
"web_crawler"
] | stackoverflow_0001569206_authentication_post_python_session_web_crawler.txt |
Q:
How to create a custom 404 page for my Django/Apache?
I know that you use .htaccess in the document-root directory in standard Apache.
What if I use Django? Can someone give me step by step how to create a custom 404 page?
A:
The default 404 handler calls 404.html . You could edit that if you don't need anythi... | How to create a custom 404 page for my Django/Apache? | I know that you use .htaccess in the document-root directory in standard Apache.
What if I use Django? Can someone give me step by step how to create a custom 404 page?
| [
"The default 404 handler calls 404.html . You could edit that if you don't need anything fancy or can override the 404 handler by setting the handler404 view -- more here\n"
] | [
14
] | [] | [] | [
"apache",
"django",
"python"
] | stackoverflow_0001569682_apache_django_python.txt |
Q:
Relative imports from __init__ in multi-file Django apps
I have a Django project located at /var/django/project/ where /var/django/ is in the PATH
within that project I have:
___init__.py
manage.py
utils/
__init__.py
tools.py
utils/__init__.py contains a function named get_preview
utils/tools.py contains ... | Relative imports from __init__ in multi-file Django apps | I have a Django project located at /var/django/project/ where /var/django/ is in the PATH
within that project I have:
___init__.py
manage.py
utils/
__init__.py
tools.py
utils/__init__.py contains a function named get_preview
utils/tools.py contains a function named get_related
How can utils/__init__.py import ... | [
"You can't (and shouldn't). You are structuring your code very poorly if files in your module are referencing code in the __init__.py associated with it. Either move both functions into __init__.py or both of them out of __init__.py or put them into separate modules. Those are your only options.\n",
"Yeah, this i... | [
2,
2,
0
] | [] | [] | [
"django",
"import",
"python"
] | stackoverflow_0001569703_django_import_python.txt |
Q:
Django - how can I get permalink to work with "throwaway" slug
I'm trying to add slugs to the url in my django app, much like SO does.
Currently, I have pages that work just fine with a url like this:
http://example.com/foo/123/
I'd like to add 'slugified' urls like so:
http://example.com/foo/123/foo-name-here
I... | Django - how can I get permalink to work with "throwaway" slug | I'm trying to add slugs to the url in my django app, much like SO does.
Currently, I have pages that work just fine with a url like this:
http://example.com/foo/123/
I'd like to add 'slugified' urls like so:
http://example.com/foo/123/foo-name-here
I can get it to work just fine, by simply modifying the urlconf and a... | [
"One thing to check for, because I also ran into this problem:\n(?P<name_slug>\\w+)\n\nIs slugify adding hyphens anywhere? If so the regex won't match, hypens are a non-word character. To fix use [\\w-]+ or similar.\n"
] | [
7
] | [] | [] | [
"django",
"django_urls",
"permalinks",
"python"
] | stackoverflow_0001569837_django_django_urls_permalinks_python.txt |
Q:
How to install matplotlib without gcc errors?
I downloaded the source and untarred it.
sudo python setup.py install
And below are the errors I get. By the way, Numpy is installed.
src/_image.cpp:5:17: error: png.h: No such file or directory
src/_image.cpp: In member function 'Py::Object Image::write_png(const Py... | How to install matplotlib without gcc errors? | I downloaded the source and untarred it.
sudo python setup.py install
And below are the errors I get. By the way, Numpy is installed.
src/_image.cpp:5:17: error: png.h: No such file or directory
src/_image.cpp: In member function 'Py::Object Image::write_png(const Py::Tuple&)':
src/_image.cpp:646: error: 'png_structp... | [
"Those particular errors stem from the lack of the development package for libpng.\nIf you use Debian/Ubuntu, try apt-get install libpng-dev first.\n",
"if you are apt-based try\n$ sudo apt-get build-dep matplotlib\n",
"You don't need to compile from source:\n \n sudo apt-get install python-matplotlib\n... | [
20,
9,
4
] | [] | [] | [
"installation",
"matplotlib",
"python"
] | stackoverflow_0001570495_installation_matplotlib_python.txt |
Q:
Pylons/Formencode With Multiple Checkboxes
I ran up against a few problems with Pylons/Formencode today when it came to validating multiple checkboxes. As a bit of background I have something like this in my Mako template:
<input type="checkbox" name="Project" value="1">Project 1</input>
<input type="checkbox" nam... | Pylons/Formencode With Multiple Checkboxes | I ran up against a few problems with Pylons/Formencode today when it came to validating multiple checkboxes. As a bit of background I have something like this in my Mako template:
<input type="checkbox" name="Project" value="1">Project 1</input>
<input type="checkbox" name="Project" value="2">Project 2</input>
<input t... | [
"maybe using formencode.validators.Set:\n>>> Set.to_python(None)\n[]\n>>> Set.to_python('this')\n['this']\n>>> Set.to_python(('this', 'that'))\n['this', 'that']\n>>> s = Set(use_set=True)\n>>> s.to_python(None)\nset([])\n>>> s.to_python('this')\nset(['this'])\n>>> s.to_python(('this',))\nset(['this'])\n\n"
] | [
2
] | [
"redrockettt,\nHave you looked at the docstring to variabledecode? It suggests you use something like:\n<input type=\"checkbox\" name=\"Project-1\" value=\"1\">Project 1</input>\n<input type=\"checkbox\" name=\"Project-2\" value=\"2\">Project 2</input>\n<input type=\"checkbox\" name=\"Project-3\" value=\"3\">Projec... | [
-1
] | [
"formencode",
"pylons",
"python",
"validation"
] | stackoverflow_0001565035_formencode_pylons_python_validation.txt |
Q:
In Python, how do I transform a string into a file?
There is a read-only library function that takes a file as an argument.
But I have a string.
How do I convert a string to a file, that if you read the file it will return this string?
I don't want to write to disk.
A:
The StringIO module:
>>> import StringIO
>>... | In Python, how do I transform a string into a file? | There is a read-only library function that takes a file as an argument.
But I have a string.
How do I convert a string to a file, that if you read the file it will return this string?
I don't want to write to disk.
| [
"The StringIO module:\n>>> import StringIO\n>>> f = StringIO.StringIO(\"foo\")\n>>> f.read()\n'foo'\n\nThe cStringIO module has the same interface, and is faster, but can't deal with Unicode strings that have non-ASCII characters.\nStringIO documentation\n",
"what do you want?\nif you want to read from file just ... | [
15,
0
] | [] | [] | [
"file",
"python",
"string",
"types"
] | stackoverflow_0001570230_file_python_string_types.txt |
Q:
Displaying the Length of Individual Sequences in File
I have a file that contains two sequences. I have a program that could read all sequences, combine them together, and display the length of both sequences together. Now I want to display the length individually. The two sequences are separated by the symbol >.... | Displaying the Length of Individual Sequences in File | I have a file that contains two sequences. I have a program that could read all sequences, combine them together, and display the length of both sequences together. Now I want to display the length individually. The two sequences are separated by the symbol >.
Example:
SEQ1 >ATGGGACTAGCAGT
SEQ2 >AGGATGATGAGTGA
Prog... | [
"for line in open(\"clostp1.fa\"):\n name, sequence = map(str.strip,line.split('>'))\n print \"The length of %s is %s\"%(name, len(sequence))\n\n",
"If I understood correctly, you want to print out each individual sequence followed by its length, right? I believe you just have a function to return the seque... | [
4,
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0001570873_python.txt |
Q:
Vim, Python and curses
I wrote a small python script for vim that uses the curses library.
When I try to call the function curses complains about:
Traceback (most recent call last):
File "<string>", line 9, in <module>
File "/usr/lib/python2.6/curses/__init__.py", line 33, in initscr
fd=_sys.__stdout__.fileno())
_... | Vim, Python and curses | I wrote a small python script for vim that uses the curses library.
When I try to call the function curses complains about:
Traceback (most recent call last):
File "<string>", line 9, in <module>
File "/usr/lib/python2.6/curses/__init__.py", line 33, in initscr
fd=_sys.__stdout__.fileno())
_curses.error: setupterm: cou... | [
"I'm not very sure about the context, but \"GVIM complains Vim works fine\" is very insightful: curses are used in the console, gvim is run in a X window, thus there's no console.\n"
] | [
7
] | [] | [] | [
"curses",
"python",
"vim"
] | stackoverflow_0001571032_curses_python_vim.txt |
Q:
Average difference between dates in Python
I have a series of datetime objects and would like to calculate the average delta between them.
For example, if the input was (2008-10-01 12:15:00, 2008-10-01 12:25:00, 2008-10-01 12:35:00), then the average delta would be exactly 00:10:00, or 10 minutes.
Any suggestions ... | Average difference between dates in Python | I have a series of datetime objects and would like to calculate the average delta between them.
For example, if the input was (2008-10-01 12:15:00, 2008-10-01 12:25:00, 2008-10-01 12:35:00), then the average delta would be exactly 00:10:00, or 10 minutes.
Any suggestions on how to calculate this using Python?
| [
"As far as algorithms go, that's an easy one. Just find the max and min datetimes, take the difference, and divide by the number of datetimes you looked at.\nIf you have an array a of datetimes, you can do:\nmx = max(a)\nmn = min(a)\navg = (mx-mn)/(len(a)-1)\n\nto get back the average difference.\nEDIT: fixed the... | [
13,
3,
2,
0,
0
] | [] | [] | [
"algorithm",
"datetime",
"python"
] | stackoverflow_0000179716_algorithm_datetime_python.txt |
Q:
Choose Python version for egg installation or install parallel versions of site-package
Via fink install I put the following Python version on my Mac OS X computer:
python2.3,
python2.4,
python2.5,
python2.6.
Further, python is alias for python2.6 on my system.
I want to install an egg, e.g. easy_install networ... | Choose Python version for egg installation or install parallel versions of site-package | Via fink install I put the following Python version on my Mac OS X computer:
python2.3,
python2.4,
python2.5,
python2.6.
Further, python is alias for python2.6 on my system.
I want to install an egg, e.g. easy_install networkx-0.36-py2.5.egg, where I have to use python 2.5 instead of version 2.6. Is this possible wi... | [
"easy_install is part of the setuptools package. Fink has separate setuptools packages for python 2.5 and python 2.6:\nfink install setuptools-py25 setuptools-py26\n\nYou can then download and install networkx to both versions:\n/sw/bin/easy_install-2.5 networkx\n/sw/bin/easy_install-2.6 networkx\n\nIf you need a ... | [
3,
2
] | [] | [] | [
"easy_install",
"egg",
"python"
] | stackoverflow_0001571047_easy_install_egg_python.txt |
Q:
Iterating through a list in Python
I am trying to iterate through a list and take each part of the list, encode it and join the result up when it is all done. As an example, I have a string which produces a list with each element being 16 characters in length.
message = (u'sixteen-letters.sixteen-letters.sixteen-... | Iterating through a list in Python | I am trying to iterate through a list and take each part of the list, encode it and join the result up when it is all done. As an example, I have a string which produces a list with each element being 16 characters in length.
message = (u'sixteen-letters.sixteen-letters.sixteen-letters.sixteen-letters.')
result = spli... | [
"Are you trying to do something like this?\n';'.join(encode(i) for i in message.split('.'))\n\nof course it could be just \n';'.join(encode(i) for i in result)\n\nif your split16 function complicated enough.\n",
"I am a bit confused about what you are exactly trying to do, which is compounded by a missing paren i... | [
1,
1,
0
] | [] | [] | [
"list",
"list_comprehension",
"python"
] | stackoverflow_0001571651_list_list_comprehension_python.txt |
Q:
Select specific child elements with BeautifulSoup
I'm reading up on BeautifulSoup to screen-scrape some pretty heavy html pages. Going through the documentation of BeautifulSoup I can't seem to find a easy way to select child elements.
Given the html:
<div id="top">
<div>Content</div>
<div>
<div>Content I ... | Select specific child elements with BeautifulSoup | I'm reading up on BeautifulSoup to screen-scrape some pretty heavy html pages. Going through the documentation of BeautifulSoup I can't seem to find a easy way to select child elements.
Given the html:
<div id="top">
<div>Content</div>
<div>
<div>Content I Want</div>
</div>
</div>
I want a easy way to to get... | [
"You are more flexible with find, and to get what you want you just need to run:\nnode = p.find('div', text=\"Content I Want\")\n\nBut since it might not be how you want to get there, following options might suit you better:\nxml = \"\"\"<div id=\"top\"><div>Content</div><div><div>Content I Want</div></div></div>\"... | [
2
] | [] | [] | [
"beautifulsoup",
"html_parsing",
"python"
] | stackoverflow_0001571699_beautifulsoup_html_parsing_python.txt |
Q:
Clojure equivalent to Python's lxml library?
I'm looking for the Clojure/Java equivalent to Python's lxml library.
I've used it a ton in the past for parsing all sorts of html (as a replacement for BeautifulSoup) and it's great to be able to use the same elementtree api for xml as well -- really a trusted friend... | Clojure equivalent to Python's lxml library? | I'm looking for the Clojure/Java equivalent to Python's lxml library.
I've used it a ton in the past for parsing all sorts of html (as a replacement for BeautifulSoup) and it's great to be able to use the same elementtree api for xml as well -- really a trusted friend! Can anyone recommend a similar Java/Clojure lib... | [
"Enlive: http://github.com/cgrand/enlive\nI've used it for screen-scraping and it works quite well for that. It uses a CSS selector like syntax for getting at elements in the document.\n",
"For Java (and thus usable from Clojure) is the tagsoup-library, which, like lxml, is a tolerant parser for faulty SGML-varia... | [
8,
5
] | [] | [] | [
"clojure",
"java",
"lxml",
"python"
] | stackoverflow_0001569223_clojure_java_lxml_python.txt |
Q:
How do I request data securely via Google OAuth?
Until recently users of my site were able to import data from Google, via OAuth. However, recently they have received the warning below, in a yellow box, when authorising (although the import still works).
I've also noticed this same warning on Facebook's GMail auth... | How do I request data securely via Google OAuth? | Until recently users of my site were able to import data from Google, via OAuth. However, recently they have received the warning below, in a yellow box, when authorising (although the import still works).
I've also noticed this same warning on Facebook's GMail authenticator!
What's changed / am I missing?
This websit... | [
"Did you try Googling the error message? Doing so took me to this page, which states:\n\nRegistered with enhanced security: Registered applications with a security certificate on file can use secure tokens. The Access Request page removes cautions, displaying this message: \" Google is not affiliated with , and we ... | [
1
] | [] | [] | [
"oauth",
"python"
] | stackoverflow_0001572450_oauth_python.txt |
Q:
Python Vs C - Handling environment variable in Windows
I see a variation in output between C and python code in Windows trying to get the same functionality. The c code ( similar to unix shell scripts ) shows the TEST1 environment variable in 'test.bat.output' with its value as empty string whereas the python cod... | Python Vs C - Handling environment variable in Windows | I see a variation in output between C and python code in Windows trying to get the same functionality. The c code ( similar to unix shell scripts ) shows the TEST1 environment variable in 'test.bat.output' with its value as empty string whereas the python code removes this environment variable.
Is there a way to ask... | [
"Cross-platform compatibility between Windows and \"most everybody else\" (operating systems derived or inspired from Unix) is often hard to get, especially in the innumerable corner cases that inevitably arise (e.g., as in this question, \"does setting an environment variable to empty mean unsetting it\"). Sometim... | [
2,
0,
0
] | [] | [] | [
"c",
"environment_variables",
"python"
] | stackoverflow_0001572153_c_environment_variables_python.txt |
Q:
Unexpected result in a simple example
def solve(numLegs, numHeads):
for numSpiders in range(0, numHeads + 1):
for numChicks in range(0, numHeads - numSpiders + 1):
numPigs = numHeads - numChicks - numSpiders
totLegs = 4*numPigs + 2*numChicks + 6*numSpiders
... | Unexpected result in a simple example | def solve(numLegs, numHeads):
for numSpiders in range(0, numHeads + 1):
for numChicks in range(0, numHeads - numSpiders + 1):
numPigs = numHeads - numChicks - numSpiders
totLegs = 4*numPigs + 2*numChicks + 6*numSpiders
if totLegs == numLegs:
... | [
"Your code is correct - in the first iteration of the outermost for loop, numChicks is 0. Since solve returns as soon as it finds a valid match, another possible valid match won't be attempted.\nYou could change the return statement into a yield statement and iterate over solve's results to get all possible combina... | [
5,
2,
2
] | [] | [] | [
"python"
] | stackoverflow_0001572676_python.txt |
Q:
converting strptime into 'X hours ago'
I have a a date in strptime that I want to show as 'X hours ago'. I can happily convert hours into days and weeks etc. but I don't know how to do the initial sum. Here is how I'm converting the string into strptime:
time.strptime(obj.created_at, '%a %b %d %H:%M:%S +0000 %Y')
... | converting strptime into 'X hours ago' | I have a a date in strptime that I want to show as 'X hours ago'. I can happily convert hours into days and weeks etc. but I don't know how to do the initial sum. Here is how I'm converting the string into strptime:
time.strptime(obj.created_at, '%a %b %d %H:%M:%S +0000 %Y')
p.s. bonus points for figuring out why it w... | [
"It seems the timesince in Django could help you out without you having to convert. The source for timesince is available here.\n",
"The datetime module is definitely easier to use, but, if you insist, you can do it with the time module instead. I.e.:\n>>> import time\n>>> fmt = '%a %b %d %H:%M:%S +0000 %Y'\n>>>... | [
4,
2,
0
] | [] | [] | [
"python",
"strptime",
"timestamp"
] | stackoverflow_0001571272_python_strptime_timestamp.txt |
Q:
Importing Python modules from a distant directory
What's the shortest way to import a module from a distant, relative directory?
We've been using this code which isn't too bad except your current working directory has to be the same as the directory as this code's or the relative path breaks, which can be error pr... | Importing Python modules from a distant directory | What's the shortest way to import a module from a distant, relative directory?
We've been using this code which isn't too bad except your current working directory has to be the same as the directory as this code's or the relative path breaks, which can be error prone and confusing to users.
import sys
sys.path.append(... | [
"Since you don't want to install it in site-packages, you should use buildout or virtualenv to create isolated development environments. That solves the problem, and means you don't have to fiddle with sys.path anymore (in fact, because Buildout does exactly that for you).\n",
"You've explained in a comment why y... | [
4,
2,
1
] | [
"You have several ways to handle imports, all documented in the Python language manual.\nSee http://docs.python.org/library/site.html and http://docs.python.org/reference/simple_stmts.html#the-import-statement\n\nPut it in site-packages and have multiple Python installations. You select the installation using the ... | [
-1
] | [
"python"
] | stackoverflow_0001572967_python.txt |
Q:
Modifying state of other objects in a constructor: design no-no?
I'm refactoring some code and found this (simplified of course, but general idea):
class Variable:
def __init__(self):
self.__constraints = []
def addConstraint(self, c):
self.__constraints.append(c)
class Constraint:
de... | Modifying state of other objects in a constructor: design no-no? | I'm refactoring some code and found this (simplified of course, but general idea):
class Variable:
def __init__(self):
self.__constraints = []
def addConstraint(self, c):
self.__constraints.append(c)
class Constraint:
def __init__(self, variables):
for v in variables:
v... | [
"I see it as a self registration pattern. \"Hello I'm new here, please allow me to join.\" \nI might prefer to have a differently named method so that the purpose is more clear, but I do actually quite like the approach.\n",
"I entirely concur with @djna's answer that the specific use case is perfectly legit -- h... | [
4,
2,
0,
0,
0
] | [] | [] | [
"constructor",
"oop",
"python",
"refactoring"
] | stackoverflow_0001573054_constructor_oop_python_refactoring.txt |
Q:
How do you implement a web-based direct deposit/eCheck payment system?
I'm trying to develop a site that will allow users to pay for services with eChecks that other users are offering.
The purchaser would pay money that would go into my account via direct deposit. The service provider could later withdraw money u... | How do you implement a web-based direct deposit/eCheck payment system? | I'm trying to develop a site that will allow users to pay for services with eChecks that other users are offering.
The purchaser would pay money that would go into my account via direct deposit. The service provider could later withdraw money up to the amount they accumulated to their bank account.
Every time I ask pay... | [
"I'm certain that you would not be able to do facilitated ACH/EFT transfers directly from one user's account to another user's account. However, as long as there's a third party in between the two users, this should be possible. But I'm assuming you'd want to do that anyways, so that you can get paid. The trick ... | [
4
] | [] | [] | [
"django",
"payment",
"payment_gateway",
"python"
] | stackoverflow_0001573383_django_payment_payment_gateway_python.txt |
Q:
convert exponential to decimal in python
I have an array in python that contains a set of values, some of them are
2.32313e+07
2.1155e+07
1.923e+07
11856
112.32
How do I convert the exponential formats to the decimal format
Additional: Is there a way I can convert the exponent directly to decimal when printing out... | convert exponential to decimal in python | I have an array in python that contains a set of values, some of them are
2.32313e+07
2.1155e+07
1.923e+07
11856
112.32
How do I convert the exponential formats to the decimal format
Additional: Is there a way I can convert the exponent directly to decimal when printing out in UNIX with awk?
| [
"I imagine you have a list rather than an array, but here it doesn't make much of a difference; in 2.6 and earlier versions of Python, something like:\n>>> L = [2.32313e+07, 2.1155e+07, 1.923e+07, 11856, 112.32]\n>>> for x in L: print '%f' % x\n... \n23231300.000000\n21155000.000000\n19230000.000000\n11856.000000\n... | [
5,
1,
0
] | [] | [] | [
"awk",
"exponent",
"python",
"unix"
] | stackoverflow_0001573080_awk_exponent_python_unix.txt |
Q:
Given a Python class, how can I inspect and find the place in my code where it is defined?
I'm building a debugging tool.
IPython lets me do stuff like
MyCls??
And it will show me the source.
A:
sys.modules[MyCls.__module__].__file__
or
inspect.getsourcefile(MyCls)
There are more __xxx__ attributes on various... | Given a Python class, how can I inspect and find the place in my code where it is defined? | I'm building a debugging tool.
IPython lets me do stuff like
MyCls??
And it will show me the source.
| [
"sys.modules[MyCls.__module__].__file__\n\nor\ninspect.getsourcefile(MyCls)\n\nThere are more __xxx__ attributes on various objects you might find useful.\n",
"Here's a pretty good overview of many of Python's meta-info capabilities:\nhttp://www.ibm.com/developerworks/library/l-pyint.html\n",
"The inspect modul... | [
8,
4,
2,
2
] | [] | [] | [
"python"
] | stackoverflow_0001568544_python.txt |
Q:
How to find duplicates in MySQL
Suppose I have many columns. If 2 columns match and are exactly the same, then they are duplicates.
ID | title | link | size | author
Suppose if link and size are similar for 2 rows or more, then those rows are duplicates.
How do I get those duplicates into a list and process them... | How to find duplicates in MySQL | Suppose I have many columns. If 2 columns match and are exactly the same, then they are duplicates.
ID | title | link | size | author
Suppose if link and size are similar for 2 rows or more, then those rows are duplicates.
How do I get those duplicates into a list and process them?
| [
"Will return all records that have dups:\nSELECT theTable.*\nFROM theTable\nINNER JOIN (\n SELECT link, size\n FROM theTable \n GROUP BY link, size\n HAVING count(ID) > 1\n) dups ON theTable.link = dups.link AND theTable.size = dups.size\n\nI like the subquery b/c I can do things like select all but the first o... | [
7,
1,
1,
0
] | [] | [] | [
"mysql",
"python"
] | stackoverflow_0001574064_mysql_python.txt |
Q:
How to match columns in MySQL
Everyone knows the "=" sign.
SELECT * FROM mytable WHERE column1 = column2;
However, what if I have different contents in column1 and column2...but they are VERY similar? (maybe off by a space, or have a word that's different).
Is it possible to:
SELECT * FROM mytable WHERE ....colum... | How to match columns in MySQL | Everyone knows the "=" sign.
SELECT * FROM mytable WHERE column1 = column2;
However, what if I have different contents in column1 and column2...but they are VERY similar? (maybe off by a space, or have a word that's different).
Is it possible to:
SELECT * FROM mytable WHERE ....column matches column2 with .4523423 "Sc... | [
"What you are looking for is called Levenstein distance. It gives you the number value which discribes the difference between two strings. \nIn MySQL you have to write stored procedure for that. Here is the articla that may help.\n",
"Lukasz Lysik posted a reference to a stored procedure that can do the fuzzy mat... | [
5,
0
] | [] | [] | [
"mysql",
"pattern_matching",
"python",
"sql",
"string"
] | stackoverflow_0001574418_mysql_pattern_matching_python_sql_string.txt |
Q:
syntax error on `If` line
My code:
#!/usr/bin/env python
def Runaaall(aaa):
Objects9(1.0, 2.0)
def Objects9(aaa1, aaa2):
If aaa2 != 0: print aaa1 / aaa2
The error I receive:
$ python test2.py
File "test2.py", line 7
If aaa2 != 0: print aaa1 / aaa2
^
SyntaxError: invalid syntax
I'm at a los... | syntax error on `If` line | My code:
#!/usr/bin/env python
def Runaaall(aaa):
Objects9(1.0, 2.0)
def Objects9(aaa1, aaa2):
If aaa2 != 0: print aaa1 / aaa2
The error I receive:
$ python test2.py
File "test2.py", line 7
If aaa2 != 0: print aaa1 / aaa2
^
SyntaxError: invalid syntax
I'm at a loss to why this error is happenin... | [
"if must be written in lower case.\nFurthermore,\n\nWrite function names in lower case (see PEP 8, the Python style guide).\nWrite the body of an if-clause on a separate line.\nThough in this case you'll probably not run into trouble, be careful with comparing floats for equality.\nSince you've just started learnin... | [
16,
4,
3
] | [] | [] | [
"python",
"syntax"
] | stackoverflow_0001574530_python_syntax.txt |
Q:
Building Django app using Comet/Orbited on Apache, use mod_wsgi or mod_python?
Building a Django app on a VPS. I am not very experienced with setting up my own server, but I decided to try a VPS this time around.
I have been doing a bunch of research to learn how to "properly" setup a LAMPython server using the A... | Building Django app using Comet/Orbited on Apache, use mod_wsgi or mod_python? | Building a Django app on a VPS. I am not very experienced with setting up my own server, but I decided to try a VPS this time around.
I have been doing a bunch of research to learn how to "properly" setup a LAMPython server using the Apache worker MPM. Naturally, the mod_python vs mod_wsgi debate came up.
Reading Gr... | [
"\nYes, absolutely.\nI would probably use Orbited as implemented by Dark Porter - It's the simplest solution to get your code running, and implemented in pure python. Not to mention, based on Twisted and thus very scalable, and has a well-established community of Django users.\n\n"
] | [
3
] | [] | [] | [
"apache",
"comet",
"django",
"python"
] | stackoverflow_0001574513_apache_comet_django_python.txt |
Q:
Efficient way to convert strings from split function to ints in Python
I have a string of data with the following format: xpos-ypos-zoom (i.e. 8743-12083-15) that I want to split up and store in the variables xpos, ypos, and zoom. Since I need to do some calculations with these number I'd like to convert them to i... | Efficient way to convert strings from split function to ints in Python | I have a string of data with the following format: xpos-ypos-zoom (i.e. 8743-12083-15) that I want to split up and store in the variables xpos, ypos, and zoom. Since I need to do some calculations with these number I'd like to convert them to integers right from the beginning. Currently, the way I'm doing this is with ... | [
"My original suggestion with a list comprehension.\ntest = '8743-12083-15'\nlst_int = [int(x) for x in test.split(\"-\")]\n\nEDIT:\nAs to which is most efficient (cpu-cyclewise) is something that should always be tested.\nSome quick testing on my Python 2.6 install indicates map is probably the most efficient candi... | [
96,
20,
14,
12
] | [] | [] | [
"casting",
"python",
"variables"
] | stackoverflow_0001574678_casting_python_variables.txt |
Q:
script to find pagerank of domain
how can I automate finding the pagerank of a domain? I came across this Python script but it no longer works. Seems Google doesn't like people automating this.
So, is there an alternative provider of page rank scores? I do not need the exact same result as Google, but something co... | script to find pagerank of domain | how can I automate finding the pagerank of a domain? I came across this Python script but it no longer works. Seems Google doesn't like people automating this.
So, is there an alternative provider of page rank scores? I do not need the exact same result as Google, but something comparable.
| [
"Here is a python script which does work. I had to do exactly the same thing recently!\n",
"Have you tried HalOtis Marketing's Page Rank script at http://www.halotis.com/2009/08/02/google-page-range-python-script/? He generally writes good, simple Python code for exactly this kind of stuff.\n"
] | [
4,
2
] | [] | [] | [
"api",
"pagerank",
"python"
] | stackoverflow_0001572183_api_pagerank_python.txt |
Q:
Finding words from random input letters in python. What algorithm to use/code already there?
I am trying to code a word descrambler like this one here and was wondering what algorithms I should use to implement this. Also, if anyone can find existing code for this that would be great as well. Basically the functio... | Finding words from random input letters in python. What algorithm to use/code already there? | I am trying to code a word descrambler like this one here and was wondering what algorithms I should use to implement this. Also, if anyone can find existing code for this that would be great as well. Basically the functionality is going to be like a boggle solver but without being a matrix, just searching for all word... | [
"I'd use a Trie. Here's an implementation in Python: http://jtauber.com/2005/02/trie.py (credit to James Tauber)\n",
"I may be missing an understanding of the game but barring some complications in the rules, such as with the introduction of \"joker\" (wildcard) letters, missing or additional letters, multiple wo... | [
3,
2,
2,
1,
1
] | [] | [] | [
"anagram",
"boggle",
"python",
"ruby",
"word"
] | stackoverflow_0001570242_anagram_boggle_python_ruby_word.txt |
Q:
How to write a RESTful URL path regex in GAE/Python for n parameters?
Currently I have three URL paths that map to ServiceHandler. How do I combine the three into one neat regex that can pass n number of arguments to ServiceHandler?
(r'/s/([^/]*)', ServiceHandler),
(r'/s/([^/]*)/([^/]*)', ServiceHandler),
(r'/s/([... | How to write a RESTful URL path regex in GAE/Python for n parameters? | Currently I have three URL paths that map to ServiceHandler. How do I combine the three into one neat regex that can pass n number of arguments to ServiceHandler?
(r'/s/([^/]*)', ServiceHandler),
(r'/s/([^/]*)/([^/]*)', ServiceHandler),
(r'/s/([^/]*)/([^/]*)/([^/]*)', ServiceHandler)
| [
"(r'^/s/(([^/]*)((/[^/]+)*))$', ServiceHandler)\n\nShould do the trick to match any amount of \n/s/foo/bar/baz/to/infinity/and/beyond/\nYou can also limit it to a range by doing something like\n^/s/(([^/]*)((/[^/]+){0,2}))$\n\nWhich would only match things like\n/s/foo/bar/baz\n/s/foo/bar\n/s/foo\n\nbut not \n/s/fo... | [
1,
0,
0
] | [] | [] | [
"google_app_engine",
"python",
"regex",
"url_mapping"
] | stackoverflow_0001570198_google_app_engine_python_regex_url_mapping.txt |
Q:
How to read .ARC files from the Heritrix crawler using Python?
I looked at the Heritrix documentation website, and they listed a Python .ARC file reader. However, it is 404 not found when I clicked on it. http://crawler.archive.org/articles/developer_manual/arcs.html
Does anyone else know any Heritrix ARC reader t... | How to read .ARC files from the Heritrix crawler using Python? | I looked at the Heritrix documentation website, and they listed a Python .ARC file reader. However, it is 404 not found when I clicked on it. http://crawler.archive.org/articles/developer_manual/arcs.html
Does anyone else know any Heritrix ARC reader that uses Python?
(I asked this question before, but closed it due to... | [
"Nothing a little Googling can't find:\nhttp://archive-access.cvs.sourceforge.net/viewvc/archive-access/archive-access/projects/hedaern/\n"
] | [
1
] | [] | [] | [
"python",
"web_crawler"
] | stackoverflow_0001575442_python_web_crawler.txt |
Q:
GAE load data into datastore without using CSV
I've used bulkloader.Loader to load stuff into the GAE dev and live datastore, but my next thing to to create objects from non-CSV data and push it into the datastore.
So say my object is something like:
class CainEvent(db.Model):
name =db.StringProperty(requir... | GAE load data into datastore without using CSV | I've used bulkloader.Loader to load stuff into the GAE dev and live datastore, but my next thing to to create objects from non-CSV data and push it into the datastore.
So say my object is something like:
class CainEvent(db.Model):
name =db.StringProperty(required=True)
birthdate = db.DateProperty()
Can an... | [
"Here's an extremely simplified example of what we're doing to use the bulkloader to load JSON data instead of CSV data:\nclass JSONLoader(bulkloader.Loader):\n def generate_records(self, filename):\n for item in json.load(open(filename)):\n yield item['fields']\n\nIn this example, I'm assuming... | [
2,
0
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0001422270_google_app_engine_python.txt |
Q:
Preempting __del__ hmmm
I need to preempt __del__ and I want to know what is the right way to do this. Basically my question in code is this..
class A:
def __init__(self):
self.log = logging.getLogger()
self.log.debug("In init")
self.closed = False
def close(self):
self.lo... | Preempting __del__ hmmm | I need to preempt __del__ and I want to know what is the right way to do this. Basically my question in code is this..
class A:
def __init__(self):
self.log = logging.getLogger()
self.log.debug("In init")
self.closed = False
def close(self):
self.log.debug("Doing some magic")
... | [
"__del__ isn't a true destructor. It is called before an object is destroyed to free any resources it is holding. It need not worry about freeing memory itself.\nYou can always call the parent class' __del__, too, if you are inheriting a class which may also have open resources.\n",
"Please use the with statement... | [
4,
3,
1
] | [] | [] | [
"class",
"python"
] | stackoverflow_0001575567_class_python.txt |
Q:
How can I read how many pixels an image has in Python
Possible Duplicate:
How to check dimensions of all images in a directory using python?
I was wondering if somebody knows how can I read an image total amount of pixels in a python sript. Could you provide and example?
Thanks a lot.
A:
here is an example:
fr... | How can I read how many pixels an image has in Python |
Possible Duplicate:
How to check dimensions of all images in a directory using python?
I was wondering if somebody knows how can I read an image total amount of pixels in a python sript. Could you provide and example?
Thanks a lot.
| [
"here is an example:\nfrom PIL import Image\n\ndef get_num_pixels(filepath):\n width, height = Image.open(filepath).size\n return width*height\n\nprint(get_num_pixels(\"/path/to/my/file.jpg\"))\n\n",
"Use PIL to load the image. The total number of pixels will be its width multiplied by its height.\n",
"He... | [
21,
6,
4,
1
] | [] | [] | [
"pixels",
"python"
] | stackoverflow_0001575625_pixels_python.txt |
Q:
Python on multiprocessor machines: multiprocessing or a non-GIL interpreter
This is more a style question. For CPU bound processes that really benefit for having multiple cores, do you typically use the multiprocessing module or use threads with an interpreter that doesn't have the GIL? I've used the multiproces... | Python on multiprocessor machines: multiprocessing or a non-GIL interpreter | This is more a style question. For CPU bound processes that really benefit for having multiple cores, do you typically use the multiprocessing module or use threads with an interpreter that doesn't have the GIL? I've used the multiprocessing library only lightly, but also have no experience with anything besides CPyt... | [
"I don't really see a \"style\" argument to be made here, either way -- both multiprocessing in CPython 2.6, and threading in (e.g.) the current versions of Jython and IronPython, let you code in extremely similar ways (and styles;-). So, I'd choose on the basis of very \"hard-nosed\" considerations -- what is per... | [
3,
1
] | [] | [] | [
"multiprocessing",
"python"
] | stackoverflow_0001575985_multiprocessing_python.txt |
Q:
Sorting strings with integers and text in Python
I'm making a stupid little game that saves your score in a highscores.txt file.
My problem is sorting the lines. Here's what I have so far.
Maybe an alphanumeric sorter for python would help? Thanks.
import os.path
import string
def main():
#Check if the fi... | Sorting strings with integers and text in Python | I'm making a stupid little game that saves your score in a highscores.txt file.
My problem is sorting the lines. Here's what I have so far.
Maybe an alphanumeric sorter for python would help? Thanks.
import os.path
import string
def main():
#Check if the file exists
file_exists = os.path.exists("highscores... | [
"after words = f.readlines(), try something like:\nheaders = words.pop(0)\n\ndef myway(aline):\n i = 0\n while aline[i].isdigit():\n i += 1\n score = int(aline[:i])\n return score\n\nwords.sort(key=myway, reverse=True)\n\nwords.insert(0, headers)\n\nThe key (;-) idea is to make a function that returns the \"... | [
4,
1,
0,
0,
0
] | [] | [] | [
"alphanumeric",
"python",
"string"
] | stackoverflow_0001575971_alphanumeric_python_string.txt |
Q:
Output in two rows for multiple columns in python
I'm working with an output list that contains the following information:
[start position, stop position, chromosome,
[('sample name', 'sample value'),
('sample name','sample value')...]]
[[59000, 59500, chr1,
[('cn_04', '1.362352462'), ('cn_01', '... | Output in two rows for multiple columns in python | I'm working with an output list that contains the following information:
[start position, stop position, chromosome,
[('sample name', 'sample value'),
('sample name','sample value')...]]
[[59000, 59500, chr1,
[('cn_04', '1.362352462'), ('cn_01', '1.802001235')]],
[100000, 110000, chr1,
[... | [
"For sending data to Excel, I would use CSV instead of a fixed-length text format; that way, if it turns out (say) that you need more significant figures in your float values, the format of your output doesn't change. Also, you can just open CSV files in Excel; you don't have to import them. And the csv.writer de... | [
3,
0,
0,
0
] | [
"Never do these types of nested lists/dictionary, they are not pythonic and are very likely to bring you to an error.\nInstead, either use a class:\n>>> class Gene:\n def __init__(self, start, end, chromosome, transcripts):\n self.start = start\n self.end = end\n self.chromosome ... | [
-1
] | [
"bioinformatics",
"file",
"format",
"python"
] | stackoverflow_0001573671_bioinformatics_file_format_python.txt |
Q:
Why does else behave differently in for/while statements as opposed to if/try statements?
I have recently stumbled over a seeming inconsistency in Python's way of dealing with else clauses in different compound statements. Since Python is so well designed, I'm sure that there is a good explanation, but I can't thi... | Why does else behave differently in for/while statements as opposed to if/try statements? | I have recently stumbled over a seeming inconsistency in Python's way of dealing with else clauses in different compound statements. Since Python is so well designed, I'm sure that there is a good explanation, but I can't think of it.
Consider the following:
if condition:
do_something()
else:
do_something_else()
... | [
"The for else construct executes the else clause if no break statement was executed for the loop, as described here For example, this else clause is never evaluated\nfor i in range(1,10):\n if i % 5 == 0:\n print i\n break\nelse:\n print \"nothing divisible by 5\"\n\n",
"Well, it depends how yo... | [
13,
5,
4
] | [] | [] | [
"control_flow",
"python"
] | stackoverflow_0001576537_control_flow_python.txt |
Q:
In regex, what does [\w*] mean?
What does this regex mean?
^[\w*]$
A:
Quick answer: ^[\w*]$ will match a string consisting of a single character, where that character is alphanumeric (letters, numbers) an underscore (_) or an asterisk (*).
Details:
The "\w" means "any word character" which usually means alphanu... | In regex, what does [\w*] mean? | What does this regex mean?
^[\w*]$
| [
"Quick answer: ^[\\w*]$ will match a string consisting of a single character, where that character is alphanumeric (letters, numbers) an underscore (_) or an asterisk (*).\nDetails:\n\nThe \"\\w\" means \"any word character\" which usually means alphanumeric (letters, numbers, regardless of case) plus underscore (_... | [
71,
2,
1,
0,
0,
0
] | [] | [] | [
"python",
"regex",
"syntax"
] | stackoverflow_0001576789_python_regex_syntax.txt |
Q:
How to use ? and ?: and : in REGEX for Python?
I understand that
* = "zero or more"
? = "zero or more" ...what's the difference?
Also, ?: << my book uses this, it says its a "subtlety" but I don't know what exactly these do!
A:
As Manu already said, ? means "zero or one time". It is the same as {0,1}.
And by ?... | How to use ? and ?: and : in REGEX for Python? | I understand that
* = "zero or more"
? = "zero or more" ...what's the difference?
Also, ?: << my book uses this, it says its a "subtlety" but I don't know what exactly these do!
| [
"As Manu already said, ? means \"zero or one time\". It is the same as {0,1}.\nAnd by ?:, you probably meant (?:X), where X is some other string. This is called a \"non-capturing group\".\nNormally when you wrap parenthesis around something, you group what is matched by those parenthesis. For example, the regex .(.... | [
6,
4,
2,
1
] | [] | [] | [
"python",
"regex",
"syntax"
] | stackoverflow_0001576957_python_regex_syntax.txt |
Q:
What does this function do?
def fun1(a):
for i in range(len(a)):
a[i] = a[i] * a[i]
return a
A:
It takes an array as parameter and returns the same array with each member squared.
EDIT:
Since you modified your question from 'What does this function do' to 'What is some code to execute this funct... | What does this function do? | def fun1(a):
for i in range(len(a)):
a[i] = a[i] * a[i]
return a
| [
"It takes an array as parameter and returns the same array with each member squared.\nEDIT:\nSince you modified your question from 'What does this function do' to 'What is some code to execute this function', here is an example:\ndef fun1(a):\n for i in range(len(a)):\n a[i] = a[i] * a[i]\n return a\n\... | [
12,
3,
3,
2,
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0001577031_python.txt |
Q:
Structuring a program. Classes and functions in Python
I'm writing a program that uses genetic techniques to evolve equations.
I want to be able to submit the function 'mainfunc' to the Parallel Python 'submit' function.
The function 'mainfunc' calls two or three methods defined in the Utility class.
They instanti... | Structuring a program. Classes and functions in Python | I'm writing a program that uses genetic techniques to evolve equations.
I want to be able to submit the function 'mainfunc' to the Parallel Python 'submit' function.
The function 'mainfunc' calls two or three methods defined in the Utility class.
They instantiate other classes and call various methods.
I think what I w... | [
"It's fine to structure your program that way. A lot of command line utilities follow the same pattern:\n#imports, utilities, other functions\n\ndef main(arg):\n #...\n\nif __name__ == '__main__':\n import sys\n main(sys.argv[1])\n\nThat way you can call the main function from another module by importing i... | [
3,
1,
0
] | [] | [] | [
"parallel_python",
"python"
] | stackoverflow_0001561282_parallel_python_python.txt |
Q:
What does this function do?
def fun1(a,x):
z = 0
for i in range(len(a)):
if a[i] == x:
z = z + 1
return z
A:
It counts and returns the number of occurrences of x in the array a. More broadly, a can be any indexable object. See 5.3.2 Subscriptions of the Python Language Reference v... | What does this function do? | def fun1(a,x):
z = 0
for i in range(len(a)):
if a[i] == x:
z = z + 1
return z
| [
"It counts and returns the number of occurrences of x in the array a. More broadly, a can be any indexable object. See 5.3.2 Subscriptions of the Python Language Reference v2.6.3:\n\n5.3.2. Subscriptions\nA subscription selects an item of a\n sequence (string, tuple or list) or\n mapping (dictionary) object:\n su... | [
9,
4,
3,
3,
1
] | [] | [] | [
"python"
] | stackoverflow_0001577169_python.txt |
Q:
Lossless PDF rotation
is there a way to rotate a PDF 90 degrees losslessly, with Python or using the command line?
I'm looking for a REAL rotation, not just adding a "/ROTATE 90" inside the PDF, because afterwards I have to send the PDF via Hylafax and it looks like that it ignores those commands.
I tried with Ima... | Lossless PDF rotation | is there a way to rotate a PDF 90 degrees losslessly, with Python or using the command line?
I'm looking for a REAL rotation, not just adding a "/ROTATE 90" inside the PDF, because afterwards I have to send the PDF via Hylafax and it looks like that it ignores those commands.
I tried with ImageMagick's convert but the ... | [
"The best resolution you will normally obtain from a standard fax machine is about 200dpi; standard faxes are about 100dpi. If you need your faxed documents to work with an artitrary fax machine you can't go above this.\nErgo, rendering your PDF to a 100 or 200dpi bitmap and rotating it 90 degress should work as w... | [
3,
3
] | [] | [] | [
"lossless",
"pdf",
"python",
"rotation",
"ubuntu"
] | stackoverflow_0001577168_lossless_pdf_python_rotation_ubuntu.txt |
Q:
Weird lxml behavior
Consider the following snippet:
import lxml.html
html = '<div><br />Hello text</div>'
doc = lxml.html.fromstring(html)
text = doc.xpath('//text()')[0]
print lxml.html.tostring(text.getparent())
#prints <br>Hello text
I was expecting to see '<div><br />Hello text</div>', because br can't have ... | Weird lxml behavior | Consider the following snippet:
import lxml.html
html = '<div><br />Hello text</div>'
doc = lxml.html.fromstring(html)
text = doc.xpath('//text()')[0]
print lxml.html.tostring(text.getparent())
#prints <br>Hello text
I was expecting to see '<div><br />Hello text</div>', because br can't have nested text and is "self-... | [
"HTML doesn't have self-closing tags. It is a xml thing.\nimport lxml.etree\n\nhtml = '<div><br />Hello text</div>'\ndoc = lxml.etree.fromstring(html)\ntext = doc.xpath('//text()')[0]\nprint lxml.etree.tostring(text.getparent())\n\nprints\n<br/>Hello text\n\nNote that the text is not inside the tag. lxml has a \"ta... | [
8,
2
] | [] | [] | [
"lxml",
"python"
] | stackoverflow_0001577732_lxml_python.txt |
Q:
Django - Custom SQL in the connection string
I have had some issues with downtime as a result of hitting the max_user_connections limit in MySql.
The default connection timeout is 8 hours, so once we hit the limit (and having no access to kill the connections on our shared hosting) I simply had to wait 8 hours for... | Django - Custom SQL in the connection string | I have had some issues with downtime as a result of hitting the max_user_connections limit in MySql.
The default connection timeout is 8 hours, so once we hit the limit (and having no access to kill the connections on our shared hosting) I simply had to wait 8 hours for the connections to time out.
I would like to add ... | [
"You can specify a list of commands to send to MySQL when the connection is open, by setting the DATABASE_OPTIONS dictionary in settings.py. \n(Incidentally, note that Django doesn't open a new connection for every view.)\n"
] | [
1
] | [] | [] | [
"connection_string",
"django",
"python",
"sql"
] | stackoverflow_0001577800_connection_string_django_python_sql.txt |
Q:
Releasing Python GIL while in C++ code
I've got a library written in C++ which I wrap using SWIG and use in python. Generally there is one class with few methods. The problem is that calling these methods may be time consuming - they may hang my application (GIL is not released when calling these methods). So my q... | Releasing Python GIL while in C++ code | I've got a library written in C++ which I wrap using SWIG and use in python. Generally there is one class with few methods. The problem is that calling these methods may be time consuming - they may hang my application (GIL is not released when calling these methods). So my question is:
What is the simplest way to rel... | [
"Not having any idea what SWIG is I'll attempt an answer anyway :)\nUse something like this to release/acquire the GIL:\nclass GILReleaser {\n GILReleaser() : save(PyEval_SaveThread()) {}\n\n ~GILReleaser() {\n PyEval_RestoreThread(save);\n }\n\n PyThreadState* save;\n};\n\nAnd in the code-block ... | [
9,
9,
0
] | [] | [] | [
"c++",
"gil",
"python",
"swig"
] | stackoverflow_0001576737_c++_gil_python_swig.txt |
Q:
How can I make Zenoss recognize skin changes?
I'm writing a ZenPack for Zenoss which includes a new DataSource. The DataSource has a ToOne relationship with another persistent object and I'm trying to construct the user interface to allow a user to specify the value of this relationship. I've given the DataSourc... | How can I make Zenoss recognize skin changes? | I'm writing a ZenPack for Zenoss which includes a new DataSource. The DataSource has a ToOne relationship with another persistent object and I'm trying to construct the user interface to allow a user to specify the value of this relationship. I've given the DataSource a factory_type_information attribute with an "imm... | [
"The problem turned out to be that none of the template changes I made actually had any impact on the final page output. The changes were picked up, they just didn't matter.\n"
] | [
1
] | [] | [] | [
"python",
"zenoss",
"zope"
] | stackoverflow_0001572661_python_zenoss_zope.txt |
Q:
Python Singletons - How do you get rid of (__del__) them in your testbench?
Many thanks for the advice you have given me thus far. Using testbenches is something this forum has really shown me the light on and for that I am appreciative. My problem is that I am playing with a singleton and normally I won't del i... | Python Singletons - How do you get rid of (__del__) them in your testbench? | Many thanks for the advice you have given me thus far. Using testbenches is something this forum has really shown me the light on and for that I am appreciative. My problem is that I am playing with a singleton and normally I won't del it, but in a testbench I will need to. So can anyone show me how to del the thing... | [
"As Borg's author I obviously second @mjv's comment, but, with either Borg (aka \"monostate\") or Highlander (aka \"singleton\"), you need to add a \"drop everything\" method to support the tearDown in your test suite. Naming such method with a single leading underscore tells other parts of the sw to leave it alon... | [
8,
0
] | [] | [] | [
"python",
"singleton",
"unit_testing"
] | stackoverflow_0001578566_python_singleton_unit_testing.txt |
Q:
Communication between Windows Client and Linux Server
I want to provide my colleagues with an interface (using Windows Forms or WPF) to control the states of virtual machines (KVM based) on a linux host. On the command line of this server, I'm using a tool, called libvirt, which provides python bindings to access ... | Communication between Windows Client and Linux Server | I want to provide my colleagues with an interface (using Windows Forms or WPF) to control the states of virtual machines (KVM based) on a linux host. On the command line of this server, I'm using a tool, called libvirt, which provides python bindings to access its functionality.
What whould be the best pratice to remot... | [
"I'd develop an intranet web application, using any python web framework of choice.\nThat way you don't have to develop/install software on your client. They just point the browser and it works.\n",
"Proxmox VE is a complete solution to manage KVM (and OpenVZ) based virtual machines, including a comprehensive web... | [
2,
1,
1
] | [] | [] | [
"communication",
"linux",
"python",
"windows"
] | stackoverflow_0001577804_communication_linux_python_windows.txt |
Q:
Python GUI Library for Windows/Gnome
I need to create a desktop app that will work with Windows and Gnome(Ubuntu). I would like to use Python to do this. The GUI part of the app will be a single form with a message area and a couple of buttons.
The list of GUI's for Python seems overwhelming. I am looking for s... | Python GUI Library for Windows/Gnome | I need to create a desktop app that will work with Windows and Gnome(Ubuntu). I would like to use Python to do this. The GUI part of the app will be a single form with a message area and a couple of buttons.
The list of GUI's for Python seems overwhelming. I am looking for something simple if possible, the main requ... | [
"You might want to check out wxPython. It's a mature project and should work on Windows\nand Linux (Gnome).\n",
"PyGTK is a very popular GUI toolkit, but usually quite a bit easier to use on Linux than on Windows.\n",
"Have you checked the extensive list of GUI libs for Python? For something simple I recommend,... | [
4,
3,
2,
2
] | [] | [] | [
"cross_platform",
"python",
"user_interface"
] | stackoverflow_0001577175_cross_platform_python_user_interface.txt |
Q:
Python: Extracting data from buffer with ctypes
I am able to successfully call a function with ctypes in Python. I now have a buffer that is filled with Structures of data I want to extract. What is the best strategy for this? Anything else I should post?
Function:
class list():
def __init__(self):
... | Python: Extracting data from buffer with ctypes | I am able to successfully call a function with ctypes in Python. I now have a buffer that is filled with Structures of data I want to extract. What is the best strategy for this? Anything else I should post?
Function:
class list():
def __init__(self):
#[...]
def getdirentries(self, path):
se... | [
"I wonder why you are using os.stat() instead of calling statinfo and os.path.walk() instead of calling getdirentries?\nNormally, when you have buffers of data that you want to pass in and out of C, you would use the struct modules pack and unpack methods to do this. \n"
] | [
0
] | [] | [] | [
"buffer",
"ctypes",
"extract",
"python"
] | stackoverflow_0001578752_buffer_ctypes_extract_python.txt |
Q:
Where should I check state / throw exception?
My situation is something like this:
class AbstractClass:
def __init__(self, property_a):
self.property_a = property_a
@property
def some_value(self):
"""Code here uses property_a but not property_b to determine some_value"""
@property... | Where should I check state / throw exception? | My situation is something like this:
class AbstractClass:
def __init__(self, property_a):
self.property_a = property_a
@property
def some_value(self):
"""Code here uses property_a but not property_b to determine some_value"""
@property
def property_a(self):
return self.prop... | [
"Add a method _validate_b(self, b) (single leading underscore to indicate \"protected\", i.e., callable from derived classes but not by general client code) that validates the value of b (which only subclasses know) vs the value of a (which the abstract superclass does know).\nMake subclasses responsible for callin... | [
3,
1,
0
] | [] | [] | [
"exception",
"python"
] | stackoverflow_0001578395_exception_python.txt |
Q:
Python Access to BaseRequestHandler
My code basically needs to start up a simple chat server with a client. Where the server and the client can talk back and forth to each other. I've gotten everything to be implemented correctly, but I can't figure out how to shut down the server whenever I'm done. (I know it'... | Python Access to BaseRequestHandler | My code basically needs to start up a simple chat server with a client. Where the server and the client can talk back and forth to each other. I've gotten everything to be implemented correctly, but I can't figure out how to shut down the server whenever I'm done. (I know it's ss.shutdown()).
I'm wanting to end ri... | [
"Please fix your code so it works, and include some way to use it. You need to add\nclass ThreadedTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):\n pass\n\nsince SocketServer doesn't actually include that class (at least not in my version of 2.6 nor 2.7). Instead, it's an example from the SocketS... | [
2,
1
] | [] | [] | [
"python",
"requesthandler",
"serversocket",
"sockets",
"tcp"
] | stackoverflow_0001578932_python_requesthandler_serversocket_sockets_tcp.txt |
Q:
py2exe'd version of GTK app can't read png files
I'm working on making a py2exe version of my app. Py2exe fails at copying some
modules in. My original app loads .png files fine, but the exe version does not:
Traceback (most recent call last):
File "app.py", line 1, in <module>
from gui.main import run
Fil... | py2exe'd version of GTK app can't read png files | I'm working on making a py2exe version of my app. Py2exe fails at copying some
modules in. My original app loads .png files fine, but the exe version does not:
Traceback (most recent call last):
File "app.py", line 1, in <module>
from gui.main import run
File "gui\main.pyc", line 14, in <module>
File "gui\co... | [
"This is a known problem with PIL and py2exe\nPIL (python image library) imports its plugins dynamically which py2exe doesn't pick up on, so it doesn't include the plugins in the .exe file.\nThe fix (hopefully!) is to import the drivers explicitly like this in one of your .py files\nimport Image\nimport PngImagePlu... | [
4,
2,
2
] | [] | [] | [
"gtk",
"image",
"py2exe",
"pygtk",
"python"
] | stackoverflow_0001511916_gtk_image_py2exe_pygtk_python.txt |
Q:
numpy.extract and numpy.any functions, is it possible to make it simpler way?
If there is any possibility to make this code simpler, I'd really appreciate it! I am trying to get rid of rows with zeros. The first column is date. If all other columns are zero, they have to be deleted. Number of columns varies.
impo... | numpy.extract and numpy.any functions, is it possible to make it simpler way? | If there is any possibility to make this code simpler, I'd really appreciate it! I am trying to get rid of rows with zeros. The first column is date. If all other columns are zero, they have to be deleted. Number of columns varies.
import numpy as np
condition = [ np.any( list(x)[1:] ) for x in r]
r = np.extract( con... | [
"You can avoid the list comprehension and instead use fancy indexing:\n#!/usr/bin/env python\nimport numpy as np\nimport datetime\nr=np.array([(datetime.date(2000,1,1),0,1),\n (datetime.date(2000,1,1),1,1),\n (datetime.date(2000,1,1),1,0),\n (datetime.date(2000,1,1),0,0), ... | [
4
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0001579218_numpy_python.txt |
Q:
Running Tests From a Module
I am attempting to run some unit tests in python from what I believe is a module. I have a directory structure like
TestSuite.py
UnitTests
|__init__.py
|TestConvertStringToNumber.py
In testsuite.py I have
import unittest
import UnitTests
class TestSuite:
def __init__(self):
... | Running Tests From a Module | I am attempting to run some unit tests in python from what I believe is a module. I have a directory structure like
TestSuite.py
UnitTests
|__init__.py
|TestConvertStringToNumber.py
In testsuite.py I have
import unittest
import UnitTests
class TestSuite:
def __init__(self):
pass
print "Starting tes... | [
"Here is some code which will run all the unit tests in a directory:\n#!/usr/bin/env python\nimport unittest\nimport sys\nimport os\n\nunit_dir = sys.argv[1] if len(sys.argv) > 1 else '.'\nos.chdir(unit_dir)\nsuite = unittest.TestSuite()\nfor filename in os.listdir('.'):\n if filename.endswith('.py') and filenam... | [
4,
0
] | [] | [] | [
"import",
"python",
"python_unittest",
"tdd",
"unit_testing"
] | stackoverflow_0001579350_import_python_python_unittest_tdd_unit_testing.txt |
Q:
How can I get all days between two days?
I need all the weekdays between two days.
Example:
Wednesday - Friday = Wednesday, Thursday, Friday
3 - 5 = 3, 4, 5
Saturday - Tuesday = Saturday, Sunday, Monday, Tuesday
6 - 2 = 6, 7, 1, 2
I'm pretty sure there is a clever algorithm out t... | How can I get all days between two days? | I need all the weekdays between two days.
Example:
Wednesday - Friday = Wednesday, Thursday, Friday
3 - 5 = 3, 4, 5
Saturday - Tuesday = Saturday, Sunday, Monday, Tuesday
6 - 2 = 6, 7, 1, 2
I'm pretty sure there is a clever algorithm out there to solve this. The only algorithms I can ... | [
">>> def weekdays_between(s, e):\n... return [n % 7 for n in range(s, e + (1 if e > s else 8))]\n... \n>>> weekdays_between(2, 4)\n[2, 3, 4]\n>>> weekdays_between(5, 1)\n[5, 6, 0, 1]\n\nIt's a bit more complex if you have to convert from/to actual days.\n>>> days = 'Mon Tue Wed Thu Fri Sat Sun'.split()\n>>> day... | [
10,
9,
2,
1,
1,
0,
0
] | [] | [] | [
"algorithm",
"python"
] | stackoverflow_0001577538_algorithm_python.txt |
Q:
Is there a random function in python that accepts variables?
I'm attempting to create a simple dice roller, and I want it to create a random number between 1 and the number of sides the dice has. However, randint will not accept a variable. Is there a way to do what I'm trying to do?
code below:
import random
a=0
... | Is there a random function in python that accepts variables? | I'm attempting to create a simple dice roller, and I want it to create a random number between 1 and the number of sides the dice has. However, randint will not accept a variable. Is there a way to do what I'm trying to do?
code below:
import random
a=0
final=0
working=0
sides = input("How many dice do you want to rol... | [
"If looks like you're confused about the number of dice and the number of sides\nI've changed the code to use raw_input(). input()is not recommended because Python\nliterally evaluates the user input which could be malicious python code\nimport random\na=0\nfinal=0\nworking=0\n\nrolls = int(raw_input(\"How many di... | [
3,
2,
1,
1
] | [] | [] | [
"python",
"random"
] | stackoverflow_0001579741_python_random.txt |
Q:
What's the best way to search for a Python dictionary value in a list of dictionaries?
I have the following data structure:
data = [
{'site': 'Stackoverflow', 'id': 1},
{'site': 'Superuser', 'id': 2},
{'site': 'Serverfault', 'id': 3}
]
I want to search the above list to see if it has any si... | What's the best way to search for a Python dictionary value in a list of dictionaries? | I have the following data structure:
data = [
{'site': 'Stackoverflow', 'id': 1},
{'site': 'Superuser', 'id': 2},
{'site': 'Serverfault', 'id': 3}
]
I want to search the above list to see if it has any site with a specific value. For instance, search the above to see if the list contain a dictio... | [
"any(d['site'] == 'Superuser' for d in data)\n\n",
"filter( lambda x: x['site']=='Superuser', data )\n\n",
"Lists absolutely require loops. That's what lists are for.\nTo avoid looping you have to avoid lists.\nYou want dictionaries of search keys and objects.\nsites = dict( (d['site'],d) for d in data )\nids ... | [
28,
9,
4,
1
] | [] | [] | [
"python"
] | stackoverflow_0001580270_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.