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:
Change elements order in a matrix (python)
mat = [[0],[1],[2]]
I want to "cycle" the element of my matrix like this:
mat = [[2],[0],[1]]
mat = [[1],[2],[0]]
mat = [[0],[1],[2]]
...
How can I change the index of these elements to loop like above?
A:
>>> for i in xrange(len(mat)):
... print(mat[i:] + mat[:i])
.... | Change elements order in a matrix (python) | mat = [[0],[1],[2]]
I want to "cycle" the element of my matrix like this:
mat = [[2],[0],[1]]
mat = [[1],[2],[0]]
mat = [[0],[1],[2]]
...
How can I change the index of these elements to loop like above?
| [
">>> for i in xrange(len(mat)):\n... print(mat[i:] + mat[:i])\n... \n[[0], [1], [2]]\n[[1], [2], [0]]\n[[2], [0], [1]]\n\n",
"For large lists using a combination of deque and a generator will be most efficient:\n>>> import collections.deque\n>>> def list_cycler_gen(lst):\n q = collections.deque(lst,len(ls... | [
2,
1
] | [] | [] | [
"matrix",
"python"
] | stackoverflow_0008020531_matrix_python.txt |
Q:
scipy -- how to extract randomly an array from a list
i have these:
a=sc.array([0,1])
b=sc.array([1,0])
c=sc.array([0,-1])
d=sc.array([-1,0])
orientation_list=(sc.array([a,b,c,d])).tolist()
#---------------------------------------------------------------------
#i am trying sth like thi... | scipy -- how to extract randomly an array from a list | i have these:
a=sc.array([0,1])
b=sc.array([1,0])
c=sc.array([0,-1])
d=sc.array([-1,0])
orientation_list=(sc.array([a,b,c,d])).tolist()
#---------------------------------------------------------------------
#i am trying sth like this
tab=sc.random.random_integers(orientation_list)
I wa... | [
">>> import random\n>>> tab = random.choice([[0, 1], [1, 0], [0, -1], [-1, 0]])\n>>> tab\n[-1, 0]\n\nYour code creates a bunch of NumPy arrays, then a list of these NumPy arrays, then transforms this list itself into a NumPy array and finally transforms everything back to a list. The code above skips all those (ra... | [
2
] | [] | [] | [
"python",
"random",
"scipy"
] | stackoverflow_0008021025_python_random_scipy.txt |
Q:
Stop Python alphabetically ordering dicts within dicts
If I create a dict of dicts
mydict = {
'zstuff':{
'zzz':True,
'aaa':True
},
'astuff':{
'zzz':True,
'aaa':True
}
}
Then use 'for' to cycle the dicts
for key in mydict:
for tag in mydict[key]:
print "{... | Stop Python alphabetically ordering dicts within dicts | If I create a dict of dicts
mydict = {
'zstuff':{
'zzz':True,
'aaa':True
},
'astuff':{
'zzz':True,
'aaa':True
}
}
Then use 'for' to cycle the dicts
for key in mydict:
for tag in mydict[key]:
print "{}:{}".format(key,tag)
Python outputs
zstuff:aaa
zstuff:zzz
... | [
"Python does not order dictionaries alphabetically. In fact, it orders dictionaries arbitrarily. If you need a dictionary object that keeps the original order, have a look at the collections.OrderedDict class available in Python 2.7.\n",
"from collections import OrderedDict\n\nmydict = {'zstuff' : OrderedDict(z... | [
7,
1
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0008021012_dictionary_python.txt |
Q:
limit time for command
I run command: run('sleep 1000'). How to limit time ( for example 100) for this command ?
A:
Several points to be precised in your question
your question is not really a python one, but is more focused on the sleep command, right ? I did not find any run command for any standard python pa... | limit time for command | I run command: run('sleep 1000'). How to limit time ( for example 100) for this command ?
| [
"Several points to be precised in your question\n\nyour question is not really a python one, but is more focused on the sleep command, right ? I did not find any run command for any standard python package... Or you may want to use python's time.sleep instead ??\nI guess you want to set a max value for the sleep co... | [
0,
0
] | [] | [] | [
"fabric",
"python"
] | stackoverflow_0005377167_fabric_python.txt |
Q:
DOMDocument interface for python lxml
I have written a small application that needs to have access to the DOM representation of the underlying HTML page. Lxml is really great but I have not been able to find such an interface. Does someone know if one exists or if there is another tool that does it?
A:
According... | DOMDocument interface for python lxml | I have written a small application that needs to have access to the DOM representation of the underlying HTML page. Lxml is really great but I have not been able to find such an interface. Does someone know if one exists or if there is another tool that does it?
| [
"According to the lxml documentation, it's possible to use lxml to parse the document, and its SAX parser can interface with the Python xml.dom.pulldom module to create a DOM object. From the documentation, the code might look like:\nfrom xml.dom.pulldom import SAX2DOM\nhandler = SAX2DOM()\nlxml.sax.saxify(tree, ha... | [
2,
2,
1,
0
] | [] | [] | [
"dom",
"html_parsing",
"lxml",
"python"
] | stackoverflow_0007876287_dom_html_parsing_lxml_python.txt |
Q:
Retrieving raw XML for items with feedparser
I'm trying to use feedparser to retrieve some specific information from feeds, but also retrieve the raw XML of each entry (ie. elements for RSS and for Atom), and I can't see how to do that. Obviously I could parse the XML by hand, but that's not very elegant, would ... | Retrieving raw XML for items with feedparser | I'm trying to use feedparser to retrieve some specific information from feeds, but also retrieve the raw XML of each entry (ie. elements for RSS and for Atom), and I can't see how to do that. Obviously I could parse the XML by hand, but that's not very elegant, would require separate support for RSS and Atom, and I i... | [
"I'm the current developer of feedparser. Currently, one of the ways you can get that information is to monkeypatch feedparser._FeedParserMixin (or edit a local copy of feedparser.py). The methods you'll want to modify are:\n\nfeedparser._FeedParserMixin.unknown_starttag\nfeedparser._FeedParserMixin.unknown_endtag\... | [
2
] | [] | [] | [
"atom_feed",
"feedparser",
"python",
"rss",
"xml"
] | stackoverflow_0007945669_atom_feed_feedparser_python_rss_xml.txt |
Q:
how to print lambda expression
I have two (many) lambdas:
myFoo = lambda x,y: x + y
mySpecFoo = lambda x: myFoo(x, 1)
I want to print resulting expression for mySpecFoo. smth like
x = var('x')
print(mySpecFoo(x))
and I want to see in output:
lambda x: x + 1
Do you know how to do this?
Thank you!
A:
This is c... | how to print lambda expression | I have two (many) lambdas:
myFoo = lambda x,y: x + y
mySpecFoo = lambda x: myFoo(x, 1)
I want to print resulting expression for mySpecFoo. smth like
x = var('x')
print(mySpecFoo(x))
and I want to see in output:
lambda x: x + 1
Do you know how to do this?
Thank you!
| [
"This is called \"symbolic evaluation\", and you need some external library to do this, for example SymPy:\n>>> import sympy\n>>> myFoo = lambda x,y: x + y\n>>> mySpecFoo = lambda x: myFoo(x, 1)\n>>> x = sympy.var(\"x\")\n>>> print mySpecFoo(x) \n1 + x\n\n"
] | [
3
] | [] | [] | [
"python"
] | stackoverflow_0008021165_python.txt |
Q:
How to convert two strings into single dictionary?
I'm trying to convert two string values into single dict like this
string1='red blue white'
string2= 'first second third'
dict={'red':first,'blue':second.'white':third}
But here i can't use loops!! Is there any other way without loop?.
Help me!!
Thank you
A:
>... | How to convert two strings into single dictionary? | I'm trying to convert two string values into single dict like this
string1='red blue white'
string2= 'first second third'
dict={'red':first,'blue':second.'white':third}
But here i can't use loops!! Is there any other way without loop?.
Help me!!
Thank you
| [
">>> string1 = 'red blue white'\n>>> string2 = 'first second third'\n>>> dict(zip(string1.split(), string2.split()))\n{'blue': 'second', 'red': 'first', 'white': 'third'}\n\n"
] | [
7
] | [] | [] | [
"dictionary",
"python",
"string"
] | stackoverflow_0008021170_dictionary_python_string.txt |
Q:
Python - ElementTree Library - Search through tree by attribute value
I've installed the ElementTree library from here: http://effbot.org/zone/element.htm
in python 2.7.
I've parsed in an xml file:
tree_a=parse('/home/user/cookies.xml')
The question that emerges now, and where I coudln't extract the information f... | Python - ElementTree Library - Search through tree by attribute value | I've installed the ElementTree library from here: http://effbot.org/zone/element.htm
in python 2.7.
I've parsed in an xml file:
tree_a=parse('/home/user/cookies.xml')
The question that emerges now, and where I coudln't extract the information from the documentation of effbot ElementTree:
How can I access a node from t... | [
"ElementTree has a limited support for XPath. While it does not support everything, some more advanced things work. You can query for attribute values with ElementTree 1.3+ (built-in in Python 2.7+ and Python 3.2+) like this:\ntree.find( './/*[@cookie_diameter=\"12\"]' )\n\nFor the full XPath support see the docume... | [
5
] | [] | [] | [
"elementtree",
"parsing",
"python",
"xml"
] | stackoverflow_0008021228_elementtree_parsing_python_xml.txt |
Q:
TDD practice: Distinguishing between genuine failures and unimplemented features
If you are in the middle of a TDD iteration, how do you know which tests fail because the existing code is genuinely incorrect and which fail because either the test itself or the features haven't been implemented yet? Please don't s... | TDD practice: Distinguishing between genuine failures and unimplemented features | If you are in the middle of a TDD iteration, how do you know which tests fail because the existing code is genuinely incorrect and which fail because either the test itself or the features haven't been implemented yet? Please don't say, "you just don't care, because you have to fix both." I'm ready to move past that ... | [
"A number of TDD tools have the idea of PENDING tests vs FAILING tests. I think unittest2 makes this distinction too.\n(I think how you do this is write:\ndef test_this_thing(self):\n pass\n\n... but this is from memory...\n[EDIT: In 2.7's unittest, or unittest2, you can mark test with the @skip, or @unittest.expe... | [
4,
2,
1,
0
] | [] | [] | [
"python",
"tdd"
] | stackoverflow_0008017514_python_tdd.txt |
Q:
python -- is there a way to access a function which is in the init method in a class?
I have the following code:
class random_walk:
#ns: number of steps
#np: number of particles
#dimension : choose between 1D or 2D
def __init__(self,ns,np,dimension=None):
self.ns=ns
self.np=np
... | python -- is there a way to access a function which is in the init method in a class? | I have the following code:
class random_walk:
#ns: number of steps
#np: number of particles
#dimension : choose between 1D or 2D
def __init__(self,ns,np,dimension=None):
self.ns=ns
self.np=np
self.dimension=dimension
if self.dimension==2:
#--- These represen... | [
"What you are trying to do; change the class signiture based on arguments passed to an instance method, doesn't make a whole lot of sense. \nWhat you should probably do is define two classes:\nclass random_walk:\n #ns: number of steps\n #np: number of particles\n #dimension : choose between 1D or 2D\n ... | [
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0008021288_python.txt |
Q:
Can I build a list, and sort it at the same time?
I'm working on a script for a piece of software, and it doesn't really give me direct access to the data I need. Instead, I need to ask for each piece of information I need, and build a list of the data I'm getting. For various reasons, I need the list to be sorted... | Can I build a list, and sort it at the same time? | I'm working on a script for a piece of software, and it doesn't really give me direct access to the data I need. Instead, I need to ask for each piece of information I need, and build a list of the data I'm getting. For various reasons, I need the list to be sorted. It's very easy to just build the list once, and then ... | [
"The short answer is: it's not worth it.\nHave a look at insertion sort. The worst-case running time is O(n^2) (average case is also quadratic). On the other hand, Python's sort (also known as Timsort) will take O(n log n) in the worst case.\nYes, it does \"seem\" cleaner to keep the list sorted as you're inserti... | [
17,
5,
3
] | [] | [] | [
"list",
"python",
"sorting"
] | stackoverflow_0008021314_list_python_sorting.txt |
Q:
Python Unicode, have unicode number in normal string, want to print unicode
Im using IDLE on windows 7. When I run the following code
uni = u"\u4E0D"
binary = uni.encode("utf-8")
print binary
It prints the unicode character with number 4E0D correctly. But here I have to hardcode the unicode number manually. Lets ... | Python Unicode, have unicode number in normal string, want to print unicode | Im using IDLE on windows 7. When I run the following code
uni = u"\u4E0D"
binary = uni.encode("utf-8")
print binary
It prints the unicode character with number 4E0D correctly. But here I have to hardcode the unicode number manually. Lets say I have a normal string format variable:
s="4E0D"
How do I convert this to th... | [
"s = '4e0d'\nc = unichr(int(s, 16))\n\n",
"Not the quickest way, but readable at least:\ns = \"4E0D\"\norig = \"\\u\" + s\nuni = orig.decode('cp1252')\n\n"
] | [
7,
0
] | [] | [] | [
"python",
"unicode"
] | stackoverflow_0008021331_python_unicode.txt |
Q:
pass view parameters when using it's url in templates
in views.py I have this:
def logout(request,key):
auth.logout(request)
return HttpResponseRedirect(reverse('airAgency.views.index',args=[key]))
in index template i wanna when user click on a link,logout view run:
<a href="{% url airAgency.views.logout %... | pass view parameters when using it's url in templates | in views.py I have this:
def logout(request,key):
auth.logout(request)
return HttpResponseRedirect(reverse('airAgency.views.index',args=[key]))
in index template i wanna when user click on a link,logout view run:
<a href="{% url airAgency.views.logout %}">logout</a>
I wanna pass key parameter to logout view,Im... | [
"Caught NoReverseMatch - usually means that the url is being called by incorrect arguments, or that something else is wrong when {% url %} tries to call the url specified. \nYou need to define url pattern for that view function to be called in urls.py. And in the url pattern specify a view function.\nurls.py\nurl(r... | [
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0008021328_django_python.txt |
Q:
Creating an instance of type(self) dynamically without calling __init__?
This is quite hard to explain. I have a class which should support the method copy_stateonly(). It should return a crippled version of the object which only contains the (copied) data members that I want. I hope this example explains it bette... | Creating an instance of type(self) dynamically without calling __init__? | This is quite hard to explain. I have a class which should support the method copy_stateonly(). It should return a crippled version of the object which only contains the (copied) data members that I want. I hope this example explains it better:
# everything inherits from this
class SuperBase:
def __init__(self):
... | [
"I'm not aware of a way to create new instances of classic classes (which is what you used in your example) without calling __init__(). New instances of new-style classes (descendants of object) can be created using\nobject.__new__(cls)\n\nwhere cls is the type of object you would like to create.\nAn alternative i... | [
8,
4,
2
] | [] | [] | [
"class",
"copy",
"python"
] | stackoverflow_0008021589_class_copy_python.txt |
Q:
Python list return statement deciphering
I have the following statement in a python routine:
return [hulls[h][i] for h, i in hull]
And I can't figure out what it does actually return.
I mean, hulls is a list of hull, so 'hulls[n]' is of type 'hull'. Additionally, hull is of type 'Point' hull is a list of points, ... | Python list return statement deciphering | I have the following statement in a python routine:
return [hulls[h][i] for h, i in hull]
And I can't figure out what it does actually return.
I mean, hulls is a list of hull, so 'hulls[n]' is of type 'hull'. Additionally, hull is of type 'Point' hull is a list of points, but
for h, i in hull?
The docs don't mention... | [
"Yes, it is list comprehension. Your return statement could be rewritten less compactly as:\nresult = []\nfor h, i in hull:\n result.append(hulls[h][i])\nreturn result\n\n",
"Hulls looks to be a two dimensional array of things. Hull is a list of pairs of ints (x,y). For each coordinate in Hull, it returns the ... | [
3,
1,
0
] | [] | [] | [
"for_loop",
"list",
"python",
"syntax"
] | stackoverflow_0008021796_for_loop_list_python_syntax.txt |
Q:
Creating a boost::python::object from a std::function
How can I construct a boost::python::object from a std::function ?
A:
Use boost::python::make_function, and provide a signature because the default one doesn't handle std::function.
For example, we want to wrap the return type of:
std::function<std::string(in... | Creating a boost::python::object from a std::function | How can I construct a boost::python::object from a std::function ?
| [
"Use boost::python::make_function, and provide a signature because the default one doesn't handle std::function.\nFor example, we want to wrap the return type of:\nstd::function<std::string(int, int)> get_string_function(const std::string& name)\n{\n return [=](int x, int y)\n {\n return name + \"(x=\"... | [
6
] | [] | [] | [
"boost",
"boost_python",
"c++",
"c++11",
"python"
] | stackoverflow_0007741455_boost_boost_python_c++_c++11_python.txt |
Q:
What's the best way to deploy a Flask app using Jython on Tomcat?
I successfully deployed the demo web app that comes with Jython. It uses modjy which is a Jython WSGI gateway. I'm now trying to hook modjy to my Flask app. I get a handler not defined error.
The full traceback is here: http://pastie.org/2810227
... | What's the best way to deploy a Flask app using Jython on Tomcat? | I successfully deployed the demo web app that comes with Jython. It uses modjy which is a Jython WSGI gateway. I'm now trying to hook modjy to my Flask app. I get a handler not defined error.
The full traceback is here: http://pastie.org/2810227
| [
"There are two different ways you can specify an application to modjy:\n\nUsing the app_import_name mechanism\nUsing a combination of app_directory/app_filename/app_callable_name\n\nFor the first method simply create a file that imports your Flask app object.\nfrom my_flask_app import app as application\n\nThen in ... | [
8
] | [] | [] | [
"flask",
"jython",
"python",
"tomcat"
] | stackoverflow_0008010517_flask_jython_python_tomcat.txt |
Q:
Are zlib.compress on Python and Deflater.deflate on Java (Android) compatible?
I am porting a Python application to Android and, at some point, this application has to communicate with a Web Service, sending it compressed data.
In order to do that it uses the next method:
def stuff(self, data):
"Convert into U... | Are zlib.compress on Python and Deflater.deflate on Java (Android) compatible? | I am porting a Python application to Android and, at some point, this application has to communicate with a Web Service, sending it compressed data.
In order to do that it uses the next method:
def stuff(self, data):
"Convert into UTF-8 and compress."
return zlib.compress(simplejson.dumps(data))
I am using the... | [
"compress and deflate are different compression algorithms so the answer is they will not be compatible. As an example of the difference here is 'a' compressed using the two algorithms via Tcl:\n% binary encode hex [zlib compress a]\n789c4b040000620062\n% binary encode hex [zlib deflate a]\n4b0400\nYour python code... | [
7,
2,
0
] | [] | [] | [
"android",
"deflate",
"java",
"python",
"zlib"
] | stackoverflow_0002424945_android_deflate_java_python_zlib.txt |
Q:
Getting Information from Google Chrome's Developer Tools
I am working on a project that wants me to get information from Google Chrome's Developer tools. More specifically, when I open up the developer tools on my target website, under the resources tab a folder is being populated called other.
This folder is pop... | Getting Information from Google Chrome's Developer Tools | I am working on a project that wants me to get information from Google Chrome's Developer tools. More specifically, when I open up the developer tools on my target website, under the resources tab a folder is being populated called other.
This folder is populating a list of URLs. I am curious if it is possible to some... | [
"The Chrome Developer Tools has two parts frontend and backend and there is an API which specifies the protocol between these parts. You can see the specification here. You can use it for writing your own app instead of standard DevTools frontend.\nAlso there is experimental debugging API for chrome extensions.\n",... | [
3,
0
] | [] | [] | [
"google_chrome_devtools",
"java",
"javascript",
"jquery",
"python"
] | stackoverflow_0008013302_google_chrome_devtools_java_javascript_jquery_python.txt |
Q:
Unicode character that doesnt work alone, Python
Ok so I have another Python Unicode problem. In IDLE windows 7,The following code:
uni = u"\u4E0D\u65E0"
binary = uni.encode("utf-8")
print binary
prints two chinese characters, 不无, the correct ones. However, if I replace the first line with
uni = u"\u65E0"
ie on... | Unicode character that doesnt work alone, Python | Ok so I have another Python Unicode problem. In IDLE windows 7,The following code:
uni = u"\u4E0D\u65E0"
binary = uni.encode("utf-8")
print binary
prints two chinese characters, 不无, the correct ones. However, if I replace the first line with
uni = u"\u65E0"
ie only the second character, it prints æ— instead. Altough... | [
"The unicode string u\"\\u4E0D\\u65E0\" consists of the two text characters 不 and 无.\nWhen a unicode string is encoded, it is converted into a sequence of bytes (not binary). Depending on what encoding is used, there may not be a one-to-one mapping of text characters to bytes. The \"utf8\" encoding, for instance, c... | [
4
] | [] | [] | [
"python",
"unicode"
] | stackoverflow_0008021548_python_unicode.txt |
Q:
Print results in Qt widget iso console
I am porting my console app to a QT gui. The app get data from a website and prints the rsult line by line in the console ( I use spyder). Each line are a few strings.
Now I want to add a gui to the app so others can use the app as well.
With QT designer I designed a nice gu... | Print results in Qt widget iso console | I am porting my console app to a QT gui. The app get data from a website and prints the rsult line by line in the console ( I use spyder). Each line are a few strings.
Now I want to add a gui to the app so others can use the app as well.
With QT designer I designed a nice gui. In a Main module I call the UI. Now I am ... | [
"I usually use QTextBrowser for a \"logging\" widget.\n\nJust create a QTextBrowser widget in your main window (i.e. self.log_widget = QTextBrowser())\nAdd it to some layout to be visible and part of the window\nLog messages to it with the append method (which accepts a string). (i.e. self.log_widget.append('Hello'... | [
1
] | [] | [] | [
"pyside",
"python",
"qt",
"widget"
] | stackoverflow_0008022035_pyside_python_qt_widget.txt |
Q:
Error printing collection.Counter instances
Counter objects are subclasses of dict so they have the method setdefault.
>>> from collections import Counter
>>> c = Counter(houses=5)
>>> print(c.setdefault.__doc__)
D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D
If I do:
>>> c.setdefault('castles')... | Error printing collection.Counter instances | Counter objects are subclasses of dict so they have the method setdefault.
>>> from collections import Counter
>>> c = Counter(houses=5)
>>> print(c.setdefault.__doc__)
D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D
If I do:
>>> c.setdefault('castles')
>>> c.keys()
dict_keys(['castles', 'houses'])
>>... | [
"The c.setdefault('castles') line directly assigns c['castles'] = None. This likely isn't what you intended.\nIf you intended to make castles show in the __repr__, use c['castles'] = 0 instead.\nFor a Counter to behave as designed, the keys can be anything you want to count and the values need to be a number. As... | [
2,
2
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0008022342_python_python_3.x.txt |
Q:
Numpy: how to assign values to individual elements of multidimensional arrays?
I'm working with 3-dimensional arrays (for the purpose of this example you can imagine they represent the RGB values at X, Y coordinates of the screen).
>>> import numpy as np
>>> a = np.floor(10 * np.random.random((2, 2, 3)))
>>> a
arr... | Numpy: how to assign values to individual elements of multidimensional arrays? | I'm working with 3-dimensional arrays (for the purpose of this example you can imagine they represent the RGB values at X, Y coordinates of the screen).
>>> import numpy as np
>>> a = np.floor(10 * np.random.random((2, 2, 3)))
>>> a
array([[[ 7., 3., 1.],
[ 9., 6., 9.]],
[[ 4., 6., 8.],
[ ... | [
">>> import numpy as np\n>>> a = np.array([[[ 7., 3., 1.],\n... [ 9., 6., 9.]],\n...\n... [[ 4., 6., 8.],\n... [ 8., 1., 1.]]])\n>>> a\narray([[[ 7., 3., 1.],\n [ 9., 6., 9.]],\n\n [[ 4., 6., 8.],\n [ 8., 1., 1.]]])\n\n>>> a[:,:,1][a[:,:,1] <; 5 ] = 9\n>>> ... | [
4,
1
] | [] | [] | [
"numpy",
"python",
"python_2.7"
] | stackoverflow_0008022337_numpy_python_python_2.7.txt |
Q:
XML Parsing: Element Tree (etree) vs. minidom
I've been using minidom to parse XML for years. Now I've suddenly learned about Element Tree. My question which is better for parsing? That is:
Which is faster?
Which uses less memory?
Do either have any O(n^2) dependencies I should worry about?
Is one being depreciat... | XML Parsing: Element Tree (etree) vs. minidom | I've been using minidom to parse XML for years. Now I've suddenly learned about Element Tree. My question which is better for parsing? That is:
Which is faster?
Which uses less memory?
Do either have any O(n^2) dependencies I should worry about?
Is one being depreciated in favor of another?
Why do we have two interfa... | [
"DOM and Sax interfaces for XML parsing are the classic ways to work with XML. Python had to provide those interfaces because they are well-known and standard.\nThe ElementTree package was intended to provide a more Pythonic interface. It is all about making things easier for the programmer.\nDepending on your bu... | [
21,
17
] | [] | [] | [
"elementtree",
"minidom",
"python",
"xml_parsing"
] | stackoverflow_0008022477_elementtree_minidom_python_xml_parsing.txt |
Q:
What does % mean and do?
This is my first question here (yay!). This may seem like a silly question but in a if statement like the one below what does % mean?
if n % i == 0:
print("hi")
A:
The '%' is the modulus operator. It's the remainder after integer division.
5/2 is 2 remainder 1. So 5%2 is 1.
I... | What does % mean and do? | This is my first question here (yay!). This may seem like a silly question but in a if statement like the one below what does % mean?
if n % i == 0:
print("hi")
| [
"The '%' is the modulus operator. It's the remainder after integer division.\n5/2 is 2 remainder 1. So 5%2 is 1.\nIn the specific case of comparing to zero, it checks divisibility. So n%i will be equal to zero if and only if n is evenly divisible by i.\n",
"In the sample you mention it’s (most likely) the modulo ... | [
6,
3,
2,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0008022564_python.txt |
Q:
How to write to log in python with nginx + uwsgi
I have a server running nginx + UWSGI + python. UWSGI is running as a daemon with the flag set: --daemonize /var/log/uwsgi.log which logs all application errors.
I've noticed that on error if I use a python print statement it will write to the log but only on an err... | How to write to log in python with nginx + uwsgi | I have a server running nginx + UWSGI + python. UWSGI is running as a daemon with the flag set: --daemonize /var/log/uwsgi.log which logs all application errors.
I've noticed that on error if I use a python print statement it will write to the log but only on an error. The standard python logging library doesn't seem t... | [
"uWSGI is a wsgi server, and as such passes a stream in the environ dict passed to the application callable it hosts, using the key wsgi.errors. If you are writing a bare wsgi app, then writing to that stream should do the job. If you are using a framework that abstracts the wsgi interface out (and by the sound o... | [
5,
4
] | [] | [] | [
"logging",
"nginx",
"python",
"uwsgi"
] | stackoverflow_0008022495_logging_nginx_python_uwsgi.txt |
Q:
Convert random characters in a string to uppercase
I'm try to append text strings randomly so that instead of just having an output like
>>>david
I will end up having something like
>>>DaViD
>>>dAviD
the code i have right now is this
import random
import string
print "Name Year"
text_file = open("names.txt", "r... | Convert random characters in a string to uppercase | I'm try to append text strings randomly so that instead of just having an output like
>>>david
I will end up having something like
>>>DaViD
>>>dAviD
the code i have right now is this
import random
import string
print "Name Year"
text_file = open("names.txt", "r")
for line in text_file:
print line.strip()+"".join... | [
"Well, your specification is actually to randomly uppercase characters, and if you were so inclined, you could achieve that with the following list comprehension:\nimport random\n\ns = \"...\"\ns = \"\".join( random.choice([k.upper(), k ]) for k in s )\n\nbut there may be nicer ways ...\n",
"you probably want to ... | [
7,
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0008018539_python.txt |
Q:
Django: correct order of these models
I have these models in my app models.py:
class A(models.Model):
#some details
pass
class B(models.Model):
a = models.ForeignKey(A, null=True, blank=True)
c = models.ForeignKey(C, null=True, blank=True)
class C(models.Model):
pass
def method(self):
... | Django: correct order of these models | I have these models in my app models.py:
class A(models.Model):
#some details
pass
class B(models.Model):
a = models.ForeignKey(A, null=True, blank=True)
c = models.ForeignKey(C, null=True, blank=True)
class C(models.Model):
pass
def method(self):
b_list = B.objects.filter(c=self)
... | [
"You can always use a string in such cases:\nclass A(models.Model):\n #some details\n pass\n\n\nclass B(models.Model):\n a = models.ForeignKey(\"A\", null=True, blank=True) # note the quotes\n c = models.ForeignKey(\"C\", null=True, blank=True) # note the quotes\n\nclass C(models.Model):\n pass\n\nIf... | [
3
] | [] | [] | [
"django",
"models",
"python"
] | stackoverflow_0008022864_django_models_python.txt |
Q:
How to prevent Python from escaping special characters when reading a regex from a text file?
I am reading a text file in Python that, among other things, contains pre-written regexes that will be used for matching later on. The text file is of the following format:
...
--> Task 2
Concatenate and print the string... | How to prevent Python from escaping special characters when reading a regex from a text file? | I am reading a text file in Python that, among other things, contains pre-written regexes that will be used for matching later on. The text file is of the following format:
...
--> Task 2
Concatenate and print the strings "Hello, " and "world!" to the screen.
--> Answer
Hello, world!
print(\"Hello,\s\"\s*+\s*\"world!\... | [
"Python regex patterns are just plain old strings. There should be no problem with storing them in a file. Perhaps when you use file.readline() you are seeing escaped characters because you are looking at the repr of the line? That should not be an issue when you actually use the pattern as a regex however:\nimport... | [
4
] | [] | [] | [
"file_io",
"python",
"python_3.x",
"regex"
] | stackoverflow_0008022898_file_io_python_python_3.x_regex.txt |
Q:
Python age verification
On my join script you have to be 13+ to join. The problem is when I check it against certain dates it only works if I do it a month back.
cur_time = datetime.datetime.utcnow() - datetime.timedelta(days=4848.12)
time_13 = str(cur_time.strftime("%Y-%m-%d"))
bmonth = self.get_argum... | Python age verification | On my join script you have to be 13+ to join. The problem is when I check it against certain dates it only works if I do it a month back.
cur_time = datetime.datetime.utcnow() - datetime.timedelta(days=4848.12)
time_13 = str(cur_time.strftime("%Y-%m-%d"))
bmonth = self.get_argument('bmonth', '')
bday = ... | [
"It's better to compare dates and date ranges rather than strings.\nAssuming you get strings for birthday parts:\nbmonth = self.get_argument('bmonth', '')\nbday = self.get_argument('bday', '')\nbyear = self.get_argument('byear', '')\n\nbd = datetime.datetime(int(byear), int(bmonth), int(bday))\nmin_age = datetime.t... | [
4
] | [] | [] | [
"datetime",
"python",
"verification"
] | stackoverflow_0008023063_datetime_python_verification.txt |
Q:
Difficulty with using virtualenv and specific Python version?
I'm trying to understand how to create an isolated python environment using an alternative version of Python other than the default (in my case this is Python 2.7). virtualenv works on my system with Python 2.7, but I can't seem to create a virtual envi... | Difficulty with using virtualenv and specific Python version? | I'm trying to understand how to create an isolated python environment using an alternative version of Python other than the default (in my case this is Python 2.7). virtualenv works on my system with Python 2.7, but I can't seem to create a virtual environment with a version of Python 3.
I tried to specify the Python v... | [
"I believe you need to install python 3.2 to the system first. You're telling the virtualenvironment to use a version of python that doesn't exist anywhere so it cannot find it. This is the \"does not exist\"\nEdit after more info was given in comment:\nvirtualenv -p /usr/local/bin/python3.2\n\n"
] | [
9
] | [] | [] | [
"python",
"virtualenv"
] | stackoverflow_0008023146_python_virtualenv.txt |
Q:
What is the easiest way of deleting all my blobstore data?
What is your best way to remove all of the blob from blobstore? I'm using Python.
I have quite a lot of blobs and I'd like to delete them all. I'm
currently doing the following:
class deleteBlobs(webapp.RequestHandler):
def get(self):
all ... | What is the easiest way of deleting all my blobstore data? | What is your best way to remove all of the blob from blobstore? I'm using Python.
I have quite a lot of blobs and I'd like to delete them all. I'm
currently doing the following:
class deleteBlobs(webapp.RequestHandler):
def get(self):
all = blobstore.BlobInfo.all();
more = (all.count()>0)
... | [
"I use this approach:\nimport datetime\nimport logging\nimport re\nimport urllib\n\nfrom google.appengine.ext import blobstore\nfrom google.appengine.ext import db\nfrom google.appengine.ext import webapp\n\nfrom google.appengine.ext.webapp import blobstore_handlers\nfrom google.appengine.ext.webapp import util\nfr... | [
7,
4
] | [] | [] | [
"blobstore",
"google_app_engine",
"python",
"task_queue"
] | stackoverflow_0007345893_blobstore_google_app_engine_python_task_queue.txt |
Q:
Why was the Python Unicode internal format implemented as described in PEP 100?
http://www.python.org/dev/peps/pep-0100/
PEP 100 states that the internal format, Python Unicode, holds UTF-16 encodings, but addresses the values as UCS-2 (or UCS-4 when compiled with flag --enable-unicode=ucs4).
Why wasn't UTF-16 ch... | Why was the Python Unicode internal format implemented as described in PEP 100? | http://www.python.org/dev/peps/pep-0100/
PEP 100 states that the internal format, Python Unicode, holds UTF-16 encodings, but addresses the values as UCS-2 (or UCS-4 when compiled with flag --enable-unicode=ucs4).
Why wasn't UTF-16 chosen (a variable length format) as opposed to UCS-2 (fixed length)?
Though the two e... | [
"Read on a little further: \"UCS-2 and UTF-16 are the same for all currently defined Unicode character points\" ... and that was true in the year 2000 when the PEP was written. The initial implementation covered only the BMP (first 64K codepoints).\n"
] | [
1
] | [] | [] | [
"encoding",
"python",
"ucs2",
"unicode",
"utf_16"
] | stackoverflow_0008023198_encoding_python_ucs2_unicode_utf_16.txt |
Q:
Read contents of
I have been trying to read the source of a website with the following:
import urllib2
from BeautifulSoup import BeautifulSoup
url = 'http://www.myurl.com/'
headers = {'User-Agent' : 'Mozilla/5.0'}
request = urllib2.Request(url,None,headers)
soup = BeautifulSoup(urllib2.urlopen(request).re... | Read contents of | I have been trying to read the source of a website with the following:
import urllib2
from BeautifulSoup import BeautifulSoup
url = 'http://www.myurl.com/'
headers = {'User-Agent' : 'Mozilla/5.0'}
request = urllib2.Request(url,None,headers)
soup = BeautifulSoup(urllib2.urlopen(request).read())
I further narrow... | [
"Please, execute the following code and post the result. I will write a regex to catch data you want to obtain.\nNota: it would be easier if you post it in my email and it won't encumber the SO memory\nsock = urllib2.urlopen(request)\nch = sock.read()\nsock.close()\n\nprint '\\n'.join(str(i) + ' ' + repr(line)\n ... | [
5,
2
] | [] | [] | [
"beautifulsoup",
"python",
"regex"
] | stackoverflow_0008020834_beautifulsoup_python_regex.txt |
Q:
re module - what is the r notation?
I am try to understand this code:
Var1 = re.compile(r"nothing is (\d+)").search
i am want to see what is the affect of the r notation right after the ( sign on the \d.
i know that \d mean to find decimal numbers (the \ mean that d has a special meaning), is that mean that witho... | re module - what is the r notation? | I am try to understand this code:
Var1 = re.compile(r"nothing is (\d+)").search
i am want to see what is the affect of the r notation right after the ( sign on the \d.
i know that \d mean to find decimal numbers (the \ mean that d has a special meaning), is that mean that without the r notation i would use \ ? if so w... | [
"It's a raw string literal. It changes backslashes to be treated literally (almost, see below). This is particularly useful when writing regular expressions as they often contain backslashes and if you use ordinary string literal you may have to escape the backslashes, making the regular expression harder to read.\... | [
6,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0008023392_python_regex.txt |
Q:
How does addition/subtraction of float numbers work in Python?
I don't understand what is going on in the following lines of code:
>>> 123456789012345678. -123456789012345677.
0.0
Shouldn't the result be 1.0?
Thanks. Cheers :)
A:
Floats only store 53 bits of information, so you are being affected by round-off.
... | How does addition/subtraction of float numbers work in Python? | I don't understand what is going on in the following lines of code:
>>> 123456789012345678. -123456789012345677.
0.0
Shouldn't the result be 1.0?
Thanks. Cheers :)
| [
"Floats only store 53 bits of information, so you are being affected by round-off.\nUse integers instead:\n>>> 123456789012345678 - 123456789012345677\n1\n\nOr use the Decimal module:\n>>> from decimal import Decimal\n>>> Decimal('123456789012345678.0') - Decimal('123456789012345677.0')\nDecimal('1.0')\n\n",
"The... | [
7,
3,
3,
1
] | [] | [] | [
"floating_point",
"python"
] | stackoverflow_0008023521_floating_point_python.txt |
Q:
How do I import other scripts?
OK, I tried looking up the question but I'm getting a lot of answers that confuse me(sorry for my ignorance). I wrote a script, and I want to import another script so that when i run it in the terminal it will be as if the second script is part of the first. How do I do this? I appre... | How do I import other scripts? | OK, I tried looking up the question but I'm getting a lot of answers that confuse me(sorry for my ignorance). I wrote a script, and I want to import another script so that when i run it in the terminal it will be as if the second script is part of the first. How do I do this? I appreciate any help.
| [
"Lets say you want a.py to use b.py. If the code in b.py is written outside of any function or class, all you need to do to run it is simply:\nimport b\n\nIf however the code is in some function, for example:\n# Code in b.py\ndef some_func():\n # Implementation\n\nThen you'll need to either:\nimport b\nb.some_fu... | [
3,
2,
0,
0
] | [] | [] | [
"file",
"import",
"python"
] | stackoverflow_0008023564_file_import_python.txt |
Q:
awk in python: How to use awk scripts in a python class?
I am trying to run an awk script using python, so I can process some data.
Is there any way to get an awk script to run in a python class without using the system class to invoke it as shell process? The framework where I run these python scripts does not al... | awk in python: How to use awk scripts in a python class? | I am trying to run an awk script using python, so I can process some data.
Is there any way to get an awk script to run in a python class without using the system class to invoke it as shell process? The framework where I run these python scripts does not allow the use of a subprocess call, so I am stuck either figurin... | [
"If you can't use the subprocess module, the best bet is to recode your AWK script in Python. To that end, the fileinput module is a great transition tool with and AWK-like feel.\n",
"Python's re module can help, or, if you can't be bothered with regular expressions and just need to do some quick field seperatio... | [
4,
1,
1
] | [] | [] | [
"awk",
"python"
] | stackoverflow_0007843497_awk_python.txt |
Q:
Search age of person in dictionary
I have a function that asks for the person their first and last name and then prints their age but i am having trouble entering the if statement, it is always skipping it.
My dictionary prints like this on the command line: {('name','subname'):19)}
l_name = raw_input("Enter last ... | Search age of person in dictionary | I have a function that asks for the person their first and last name and then prints their age but i am having trouble entering the if statement, it is always skipping it.
My dictionary prints like this on the command line: {('name','subname'):19)}
l_name = raw_input("Enter last name")
f_name = raw_input("Enter first n... | [
"Try this:\nif (l_name, f_name) in my_dict:\n\nSee it working online: ideone\n",
"You were very close. Just do the lookup using a tuple instead of using and.\nHere is the working code:\nage_dict = dict([\n (('tom', 'hanks'), 55),\n (('al', 'pacino'), 71),\n])\n\nl_name = raw_input(\"Enter last name: \")\nf... | [
3,
0
] | [] | [] | [
"python"
] | stackoverflow_0008023751_python.txt |
Q:
Favourite Open Source Google App Engine apps (Java or Python)
To learn from good examples, what are the best open source Google App Engine applications out there?
I don't care if it is Java or Python based.
Please one app per answer. Feel free to add a link to the live app (if there is) and to the project page.
A... | Favourite Open Source Google App Engine apps (Java or Python) | To learn from good examples, what are the best open source Google App Engine applications out there?
I don't care if it is Java or Python based.
Please one app per answer. Feel free to add a link to the live app (if there is) and to the project page.
| [
"Rietveld of course\n",
"I dearly love my App Engine Console. It is a mini-app, a \"plug-in\" for other applications. It gives you an AJAX Python interpreter that runs on the server—great for development and debugging. Sometimes I use cURL pointed at App Engine Console to run (authenticated) one-off remote Python... | [
13,
7,
3,
3,
2,
2,
1,
1,
1,
1,
1,
1
] | [] | [] | [
"google_app_engine",
"java",
"open_source",
"python"
] | stackoverflow_0001502820_google_app_engine_java_open_source_python.txt |
Q:
Is the 'zope' package widely used?
I want to implement my project using interface oriented programming. Since Python itself does not have native support to the Interface keyword, I am planning to leverage the zope.* package. But the zope.component package is really a huge package with lots of dependencies. Because... | Is the 'zope' package widely used? | I want to implement my project using interface oriented programming. Since Python itself does not have native support to the Interface keyword, I am planning to leverage the zope.* package. But the zope.component package is really a huge package with lots of dependencies. Because I want to keep my project slim with les... | [
"You could use zope.interface. For example, it is used by Twisted, Pyramid frameworks.\n"
] | [
4
] | [] | [] | [
"google_app_engine",
"interface",
"python",
"zope.interface"
] | stackoverflow_0008020442_google_app_engine_interface_python_zope.interface.txt |
Q:
Reading a CR2 (Raw Canon Image) header using Python
I'm trying to extract the date/time when a picture was taken from the CR2 (Canon format for raw pictures).
I know the CR2 specification, and I know I can use Python struct module to extract pieces from a binary buffer.
Briefly, the specification says that in Tag ... | Reading a CR2 (Raw Canon Image) header using Python | I'm trying to extract the date/time when a picture was taken from the CR2 (Canon format for raw pictures).
I know the CR2 specification, and I know I can use Python struct module to extract pieces from a binary buffer.
Briefly, the specification says that in Tag 0x0132 / 306 I can find an string of length 20 - the date... | [
"Have you taken into account the header which should (according to the spec) precede the IFD block you're talking about?\nI looked through the spec and it says the first IFD block follows the 16 byte header. So if we read bytes 16 and 17 (at offset 0x10 hex) we should get the number of entries in the first IFD bloc... | [
7,
6,
4
] | [] | [] | [
"binary_data",
"image_processing",
"metadata",
"python"
] | stackoverflow_0003696642_binary_data_image_processing_metadata_python.txt |
Q:
Django ModelForm: adding an alias to a field
I have a (GoogleAppEngine) Django ModelForm:
class A(db.Model):
a = db.StringProperty()
class MyAForm(djangoforms.ModelForm):
class Meta:
model = A
This creates a form which has one string field a. On my form I'd like to call this something else, say b. So I'... | Django ModelForm: adding an alias to a field | I have a (GoogleAppEngine) Django ModelForm:
class A(db.Model):
a = db.StringProperty()
class MyAForm(djangoforms.ModelForm):
class Meta:
model = A
This creates a form which has one string field a. On my form I'd like to call this something else, say b. So I'd like a form with a field called b and when the f... | [
"It's not clear what you mean when you say you want to 'call' the field something else on your form. Do you mean the label? That's easy to do :\nclass MyAForm(djangoforms.ModelForm):\n a = forms.CharField(label='b')\n class Meta:\n model = A\n\nIf you want to change the underlying HTML ID, you can do that via ... | [
5,
0,
0
] | [] | [] | [
"django",
"django_forms",
"google_app_engine",
"python"
] | stackoverflow_0002070377_django_django_forms_google_app_engine_python.txt |
Q:
Need to understand function in python
def process_filter_description(filter, images, ial):
'''Return a new list containing only items from list images that pass
the description filter (a str). ial is the related image association list.
Matching is done in a case insensitive manner.
'''
im... | Need to understand function in python | def process_filter_description(filter, images, ial):
'''Return a new list containing only items from list images that pass
the description filter (a str). ial is the related image association list.
Matching is done in a case insensitive manner.
'''
images = []
for items in ial:
Those ... | [
"Like I said in my comment, this is really vague. But I'll try to explain a little about the concept of a filter in python, specifically the filter() function.\nThe prototype of filter is: iterable <- filter(function, iterable). \niterable is something that can be iterated over. You can look up this term in the ... | [
1,
0
] | [] | [] | [
"function",
"python"
] | stackoverflow_0008023887_function_python.txt |
Q:
Google app engine suas cookies not expiring
When using suas in GAE and setting the flash_msg, for some reason the cookie does not expire. The symptom is that no mater how many times I refresh the page the flash message is always there. When I debugged with chrome I can see that the expiration the flash_msg cookies... | Google app engine suas cookies not expiring | When using suas in GAE and setting the flash_msg, for some reason the cookie does not expire. The symptom is that no mater how many times I refresh the page the flash message is always there. When I debugged with chrome I can see that the expiration the flash_msg cookies was set to session. Even more troubling I found ... | [
"Those cookies do not expire on page load. They expire when the browser closes. What you need to do is at every page load, if flash is in session, display it and then force remove it from the session (on the server side).\n"
] | [
1
] | [] | [] | [
"cookies",
"google_app_engine",
"python"
] | stackoverflow_0008022285_cookies_google_app_engine_python.txt |
Q:
Python: detect strings that share words
I have a list of single and multi-word phrases:
terms = ['Electronic rock', 'Alternative rock', 'Indie pop']
I want to detect that terms[0] and terms[1] share the word rock. Is there a Pythonic way to do this, instead of using a ton of for-loops, temporary lists, and split('... | Python: detect strings that share words | I have a list of single and multi-word phrases:
terms = ['Electronic rock', 'Alternative rock', 'Indie pop']
I want to detect that terms[0] and terms[1] share the word rock. Is there a Pythonic way to do this, instead of using a ton of for-loops, temporary lists, and split(' ')?
Basically, I'm trying to detect a half-e... | [
"You can use a dictonary to remember which words appear in which terms:\nfrom collections import defaultdict\n\nterms = ['Electronic rock', 'Alternative rock', 'Indie pop']\nd = defaultdict(list)\nfor term in terms:\n for word in term.split():\n d[word].append(term)\n\nfor k,v in d.iteritems():\n if le... | [
6,
1,
1,
1
] | [] | [] | [
"list",
"python",
"string"
] | stackoverflow_0008024218_list_python_string.txt |
Q:
List comprehension expression
I have a function which looks like that:
def roulette(self):
sum = 0
lst = []
for x in self.drinkList:
sum += x.fitness
lst.append(sum)
return lst
Can it be replaced with list comprehension expression or something more efficient than for loop?
PS: it... | List comprehension expression | I have a function which looks like that:
def roulette(self):
sum = 0
lst = []
for x in self.drinkList:
sum += x.fitness
lst.append(sum)
return lst
Can it be replaced with list comprehension expression or something more efficient than for loop?
PS: it apperars that if I do random.randr... | [
"It's actually possible to 'peek' at the list being built in a list comprehension. the outermost list has the name _[1], which of course is not a valid python identifier, so it must be accessed in another way:\ndef roulette(self):\n return [drink.fitness + (locals()['_[1]'][-1] if locals()['_[1]'] else 0) \n ... | [
4,
1,
0
] | [
"I don't know if it is more efficient, but this has a list comprehension and less lines:\ndef roulette(self):\n lst = [self.drinkList.pop(0).fitness]\n [ lst.append(x.fitness + lst[-1]) for x in self.drinkList]\n return lst\n\n.\nEdit\nAs nothing authorizes me to modify the list self.drinkList , I rewrite:... | [
-1
] | [
"list_comprehension",
"python"
] | stackoverflow_0008021454_list_comprehension_python.txt |
Q:
Extracting data from HTML
I am trying to scrape a website. I have been able to get the contents on the website into a string/file.
Now, I would like to search for a specific line that has something like:
<li><span class="abc">Key 1:</span> <span class="aom_pb">Value 1</span></li>
There is gauranteed to be on... | Extracting data from HTML | I am trying to scrape a website. I have been able to get the contents on the website into a string/file.
Now, I would like to search for a specific line that has something like:
<li><span class="abc">Key 1:</span> <span class="aom_pb">Value 1</span></li>
There is gauranteed to be only one Key 1: in the website an... | [
"Rather than use a regex, I would start by letting BeautifulSoup parse the html.\nThen, you can use the built-in find functions to search for the \"abc\" and \"aom_pb\" classes.\nimport BeautifulSoup\n\nsoup = BeautifulSoup.BeautifulSoup(downloaded_str)\nkey = soup.find('span', {'class': 'abc'}).text\nvalue = soup.... | [
5,
4,
2,
1
] | [] | [] | [
"python",
"regex",
"scrape"
] | stackoverflow_0008024529_python_regex_scrape.txt |
Q:
Comparing element order in Python lists
I am trying to write a function that returns True if the elements in lst1 appear in lst2 in the same order as they appear in lst1, but not necessarily consecutively.
For example,
test([29, 5, 100], [20, 29, 30, 50, 5, 100]) should return True.
test([25, 65, 40], [40, 25, 30,... | Comparing element order in Python lists | I am trying to write a function that returns True if the elements in lst1 appear in lst2 in the same order as they appear in lst1, but not necessarily consecutively.
For example,
test([29, 5, 100], [20, 29, 30, 50, 5, 100]) should return True.
test([25, 65, 40], [40, 25, 30, 65, 1, 100]) should return False.
Here is wh... | [
"Here is an iterative version of the method using index given by Triptych. I think this is probably the best way to do this, as index should be faster than any manual indexing or iteration:\ndef test(lst1, lst2):\n start = 0\n try:\n for item in lst1:\n start = lst2.index(item, start) + 1\n ... | [
5,
2,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0008024052_python.txt |
Q:
Exporting C data structures and a C API to Python
I have the source to a C library with a C API. I want to expose the functions and C data structures to python, so that I can use the library in my python scripts.
There are over 200+ functions and about 50 data structures, so it would be preferable if I could autom... | Exporting C data structures and a C API to Python | I have the source to a C library with a C API. I want to expose the functions and C data structures to python, so that I can use the library in my python scripts.
There are over 200+ functions and about 50 data structures, so it would be preferable if I could automate the generation of the "glue" code between C and Pyt... | [
"I can't comment on SWIG, but I can strongly recommend Cython (tutorial, wrapping C libraries). It does require writing the wrapper code by hand, but at least the wrapper code is almost Python and you'll likely need to do some input validation/transformation and class wrapping anyway, which Cython automates to a gr... | [
0,
0
] | [] | [] | [
"c",
"python",
"swig"
] | stackoverflow_0008024195_c_python_swig.txt |
Q:
Numpy : can't build a 2-D array of tuples
I've a problem with numpy's array constructor. I want to initialize an 2-D array with tuples, but it doesn't work as with integers :
>>> A = array([[0, 0], [3, 5]])
>>> print(A)
[[0 0]
[3 5]]
>>> A[1, 1] = 7
>>> print(A)
[[0 0]
[3 7]]
>>> A = array([[(0, 0), (0, 1)], [(1, ... | Numpy : can't build a 2-D array of tuples | I've a problem with numpy's array constructor. I want to initialize an 2-D array with tuples, but it doesn't work as with integers :
>>> A = array([[0, 0], [3, 5]])
>>> print(A)
[[0 0]
[3 5]]
>>> A[1, 1] = 7
>>> print(A)
[[0 0]
[3 7]]
>>> A = array([[(0, 0), (0, 1)], [(1, 0), None]], dtype=object)
>>> A[1, 1] = (2, 3)
... | [
"Your code seems to work for me (using the explicit numpy namespace). I'm using numpy v1.6.1:\nIn [8]: import numpy as np\nIn [9]: A = np.array([[(0, 0), (0, 1)], [(1, 0), None]], dtype=object)\n\nIn [10]: A[1, 1] = (2, 3)\n\nIn [11]: A.shape\nOut[11]: (2, 2)\n\nIn [12]: A\nOut[12]: \narray([[(0, 0), (0, 1)],\n ... | [
3
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0008024750_numpy_python.txt |
Q:
Insert a lot of products opencart script
I have a script in python in which I have all my products, descriptions , images, etc. Now I want to insert all this information in my Opencart theme. I try to find out how to save it all of this in the MySQl database. I know I have to use MySQLdb for python but I don't kno... | Insert a lot of products opencart script | I have a script in python in which I have all my products, descriptions , images, etc. Now I want to insert all this information in my Opencart theme. I try to find out how to save it all of this in the MySQl database. I know I have to use MySQLdb for python but I don't know in which place I have to save de name, the d... | [
"Your best option in my opinion is to use an Import/Export tool (there are free ones available like the excel tool by JNeuhoff). It's fairly easy to use once you figure out what you are doing. The best thing to do is to clear all the default data that comes with an install, create a couple of products, categories e... | [
2
] | [] | [] | [
"csv",
"module",
"mysql_python",
"opencart",
"python"
] | stackoverflow_0008024526_csv_module_mysql_python_opencart_python.txt |
Q:
Are datagrams always received completely?
Most datagram receiving functions such as c's recv or read, javas DatagramPacket class or pythons SocketServer, include the possibility to find out the amount of received data.
c:
int amount = recv(sock, buf, n, MSG_WAITALL);
java:
int amount = datagramSocket.getLength();... | Are datagrams always received completely? | Most datagram receiving functions such as c's recv or read, javas DatagramPacket class or pythons SocketServer, include the possibility to find out the amount of received data.
c:
int amount = recv(sock, buf, n, MSG_WAITALL);
java:
int amount = datagramSocket.getLength();
python:
class MyUDPHandler(socketserver.BaseR... | [
"UDP datagrams cannot be partially delivered¹; they are delivered as-is or not at all. So yes, you can be sure that the received datagram was sent exactly as you see it on the receiver's end.\nEdit to incorporate Will's comment which is the best kind of correct (i.e., technically):\n¹They can be fragmented at the I... | [
14,
4
] | [] | [] | [
"c",
"datagram",
"java",
"python",
"udp"
] | stackoverflow_0007931726_c_datagram_java_python_udp.txt |
Q:
Cython 1.1.2 and const correctness
I am experimenting with Cython to write a python extension for my C library. I have created a setup.py file - but when I try to build my pxd and pyx files, I get an error.
After some investigation, it appears that Cython cannot grok functions with const parameters. Whenever I rem... | Cython 1.1.2 and const correctness | I am experimenting with Cython to write a python extension for my C library. I have created a setup.py file - but when I try to build my pxd and pyx files, I get an error.
After some investigation, it appears that Cython cannot grok functions with const parameters. Whenever I remove the const specifier, the compilation... | [
"This is a known limitation, with workarounds documented in Cython's own documentation here.\n"
] | [
1
] | [] | [] | [
"cython",
"python",
"python_extensions"
] | stackoverflow_0008024583_cython_python_python_extensions.txt |
Q:
Django permalink from view with optional parameters
I'm trying to use one view to resolve two url patterns, by using optional parameters in the view definition.
I'm following recomendations from this post and this other question.
Here's my code for the url patterns urls.py:
urlpatterns = patterns('myapp.views',
... | Django permalink from view with optional parameters | I'm trying to use one view to resolve two url patterns, by using optional parameters in the view definition.
I'm following recomendations from this post and this other question.
Here's my code for the url patterns urls.py:
urlpatterns = patterns('myapp.views',
url(r'^(?P<slug>[\w-]+)/$', 'my_view', name='main_url')... | [
"You return a list in your get_absolute_url function, that's why you get two parameters.\nYou could just do like so:\nclass MyModel(models.Model):\n name = models.CharField(max_length=128)\n slug = models.CharField(max_length=32)\n\n @models.permalink\n def get_absolute_url(self):\n return \"/%s/... | [
0
] | [] | [] | [
"django",
"permalinks",
"python",
"url"
] | stackoverflow_0008023724_django_permalinks_python_url.txt |
Q:
What causes a list index out of range here?
I've had some problems with handling forms and getting back to basics after an upgrade I can't get the minimal example to work:
class PhotoUploadFormHandler(webapp2.RequestHandler):
def get(self):
self.response.out.write('<html><body>')
self.response... | What causes a list index out of range here? | I've had some problems with handling forms and getting back to basics after an upgrade I can't get the minimal example to work:
class PhotoUploadFormHandler(webapp2.RequestHandler):
def get(self):
self.response.out.write('<html><body>')
self.response.out.write('<form action="%s" method="POST" encty... | [
"It seems that *get_uploads* is returning an empty list. Accordingly, the [0] fails.\n"
] | [
3
] | [] | [] | [
"blob",
"forms",
"google_app_engine",
"http",
"python"
] | stackoverflow_0008025408_blob_forms_google_app_engine_http_python.txt |
Q:
Subplots with dates on the x-axis
I'm having trouble using multiple subplots with dates on the x-axis.
I'm using the matplotlib example from here. I've modified it to include another subplot (the data being plotted is the same). This is what I'm getting as output:
The ticks appear only on the second subplot. W... | Subplots with dates on the x-axis | I'm having trouble using multiple subplots with dates on the x-axis.
I'm using the matplotlib example from here. I've modified it to include another subplot (the data being plotted is the same). This is what I'm getting as output:
The ticks appear only on the second subplot. Why? How can I make them appear on both... | [
"I've found the culprit. It's the autofmt_xdate function:\n\nDate ticklabels often overlap, so it is useful to rotate them and right align them. Also, a common use case is a number of subplots with shared xaxes where the x-axis is date data. The ticklabels are often long, and it helps to rotate them on the bottom ... | [
12
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0008010549_matplotlib_python.txt |
Q:
How fast is SQLite via Python
I was just curious if anyone could tell me if using SQLite to store a dictionary (as in brute force) for use in a Python script was an efficient method. While I am relatively new to Python I do have quite a bit of experience with other programming languages and am currently working o... | How fast is SQLite via Python | I was just curious if anyone could tell me if using SQLite to store a dictionary (as in brute force) for use in a Python script was an efficient method. While I am relatively new to Python I do have quite a bit of experience with other programming languages and am currently working on a pentesting tool to use in Backt... | [
"Yes, sqlite is a reasonable choice for implementing a dictionary. For speed, use the :memory: option and make sure to create the appropriate indexes for your lookups and queries.\nFor large, persistent databases it also works well. For speed, take care to commit large transactions instead of per-key.\nThe sugges... | [
3,
1,
1
] | [] | [] | [
"data_structures",
"python",
"sqlite"
] | stackoverflow_0008025259_data_structures_python_sqlite.txt |
Q:
How do I serve CSS to Django in development?
I've been all through the documentation, and it just doesn't make sense to me. I ran collectstatic, I set up /static/ directories in both my app and my project directories, I added STATIC_URL and STATIC_ROOT to my settings.py file (but I have no idea how to know if the... | How do I serve CSS to Django in development? | I've been all through the documentation, and it just doesn't make sense to me. I ran collectstatic, I set up /static/ directories in both my app and my project directories, I added STATIC_URL and STATIC_ROOT to my settings.py file (but I have no idea how to know if they're set correctly) and {{ STATIC_URL }} still isn... | [
"Here's how mine is setup. It sounds like you might be missing the static context processor?\nSTATIC_ROOT and STATIC_URL\nIn the settings.py used in development:\nSTATIC_ROOT = ''\nSTATIC_URL = '/static/'\n\nAnd the settings.py used on my production server:\nSTATIC_URL = '//static.MYDOMAIN.com/'\nSTATIC_ROOT = '/ho... | [
6,
2,
2,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0007620307_django_python.txt |
Q:
How to fit closest point to an equation? Python
Basically I have some code for which it will find the equation of a plane and then attempt to place a 1 in a list if a point satisfies this equation of a line, otherwise a 0 is put in for the list.
Unfortunately, there has to be an increment amount, so how would you ... | How to fit closest point to an equation? Python | Basically I have some code for which it will find the equation of a plane and then attempt to place a 1 in a list if a point satisfies this equation of a line, otherwise a 0 is put in for the list.
Unfortunately, there has to be an increment amount, so how would you get a point that is closest to the equation so that a... | [
"If I'm understanding your intent correctly, you have a plane defined by three points (p0, p1, p2) and then want to evaluate whether some other point lies in that plane (or very nearly so).\nThis is most easily expressed using matrices rather than by manipulating the individual coordinate components in the code sni... | [
0,
0
] | [] | [] | [
"equation",
"increment",
"list",
"points",
"python"
] | stackoverflow_0008024166_equation_increment_list_points_python.txt |
Q:
Numpy arrays with mixed mutable and immutable values
I'm interested in the best/fastest way to do array ops (dot, outer, add, etc.) while ignoring some values in the array. I'm mostly interested in cases where some (maybe 50%-30%) of the values are ignored and are effectively zero with moderately large arrays, may... | Numpy arrays with mixed mutable and immutable values | I'm interested in the best/fastest way to do array ops (dot, outer, add, etc.) while ignoring some values in the array. I'm mostly interested in cases where some (maybe 50%-30%) of the values are ignored and are effectively zero with moderately large arrays, maybe 100,000 to 1,000,000 elements. There are a number of so... | [
"With a sparse matrix you can get improvement if the density is less than 10%. A sparse matrix may be faster, depending on whether you include the time required to build the matrix.\nimport timeit\n\nsetup=\\\n'''\nimport numpy as np\ndim=1000\nA = np.ones((dim, dim)) # the array to modify\nB = np.random.random_int... | [
1
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0008023716_numpy_python.txt |
Q:
matplotlib not changing scatter point colors if they are assigned the first time
In the following minimal example, I create 1-point scatter plot and later change color of points in loop using Collection.set_color. If I set the color(s) the first time scatter is called, set_color will not change its face color (onl... | matplotlib not changing scatter point colors if they are assigned the first time | In the following minimal example, I create 1-point scatter plot and later change color of points in loop using Collection.set_color. If I set the color(s) the first time scatter is called, set_color will not change its face color (only edge color), whereas if I don't specify it when the scatterplot is created, face col... | [
"I would say it is a bug/limitation of that matplotlib version.\nI tried the code with:\nmatplotlib 1.0.1 (ActivePython 2.6.7, win7 64bit) --> reproduced the behavior\nmatplotlib 1.1.0.dev (ActivePython 3.2.2, winXP, 32bit) --> works as expected\n\nThere is also a comment from Avaris saying he gets ex... | [
2
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0007955602_matplotlib_python.txt |
Q:
while loop printing list in python
The following code:
c=0 while c < len(demolist):
print ’demolist[’,c,’]=’,demolist[c]
c=c+1
Creates this output:
demolist[ 0 ]= life
demolist[ 1 ]= 42
demolist[ 2 ]= the universe
demolist[ 3 ]= 6
demolist[ 4 ]= and
demolist[ 5 ]= 7
demolist[ 6 ]= everything
What's up w... | while loop printing list in python | The following code:
c=0 while c < len(demolist):
print ’demolist[’,c,’]=’,demolist[c]
c=c+1
Creates this output:
demolist[ 0 ]= life
demolist[ 1 ]= 42
demolist[ 2 ]= the universe
demolist[ 3 ]= 6
demolist[ 4 ]= and
demolist[ 5 ]= 7
demolist[ 6 ]= everything
What's up with the demolist[',c,'] format that is b... | [
"The print statement receives four arguments (separated by commas):\n’demolist[’ # string\nc # integer\n’]=’ # string\ndemolist[c] # result of list access\n\nA clearer way to write that line is:\nprint 'demolist[ {0} ]= {1}'.format(c, demolist[c])\n\nSee it working on line: ideone\n\nNote: ... | [
5,
2,
1
] | [] | [] | [
"loops",
"python"
] | stackoverflow_0008026024_loops_python.txt |
Q:
Faulty cursor location during pydev interactive session in ECLIPSE
I am using the Latest Eclipse (3.7.0) with Pydev. The problem I am facing is that when I use interactive mode my cursor location is totally weird and very frustrating.
The cursor is never located after >>> and sometimes I have to press enter to bri... | Faulty cursor location during pydev interactive session in ECLIPSE | I am using the Latest Eclipse (3.7.0) with Pydev. The problem I am facing is that when I use interactive mode my cursor location is totally weird and very frustrating.
The cursor is never located after >>> and sometimes I have to press enter to bring the cursor on next line as it will be on result from last line.
But I... | [
"I think the problem is that you're running it as an external tool... The proper way to have an interactive console in PyDev would be using the interactive console that's builtin into PyDev. See: http://pydev.org/manual_adv_interactive_console.html for details on starting / using that console.\n"
] | [
0
] | [] | [] | [
"cursor",
"eclipse",
"pydev",
"python",
"ubuntu"
] | stackoverflow_0008025239_cursor_eclipse_pydev_python_ubuntu.txt |
Q:
Context specific localisation in Django
I have a Django application. Localising this into multiple languages is a simple and straightforward but one part of the site is an complex rich internet application. This part of the site allows the user to his workspace mode.
Everything remains the same but the terminolog... | Context specific localisation in Django | I have a Django application. Localising this into multiple languages is a simple and straightforward but one part of the site is an complex rich internet application. This part of the site allows the user to his workspace mode.
Everything remains the same but the terminology changes. e.g.
www.exmaple.com/myria/chemist... | [
"Short answer: you don't need it. In most cases it's better to have latin chars in URL instead of something %%-escaped.\nLong answer: DjangoCMS provides locale-dependent URL for each page. You can kludge something like:\nfrom django.utils.translations import ugettext as _\nfrom django import http\n...\ndef myria_vi... | [
0
] | [] | [] | [
"django",
"localization",
"python",
"sites"
] | stackoverflow_0007982127_django_localization_python_sites.txt |
Q:
Using rpyc to connect to database once and serve multiple queries
Trying to serve database query results to adhoc client requests, but do not want to open a connection for each individual query. I'm not sure if i'm doing it right.
Current solution is something like this on the "server" side (heavily cut down for ... | Using rpyc to connect to database once and serve multiple queries | Trying to serve database query results to adhoc client requests, but do not want to open a connection for each individual query. I'm not sure if i'm doing it right.
Current solution is something like this on the "server" side (heavily cut down for clarity):
import rpyc
from rpyc.utils.server import ThreadedServer
impo... | [
"I don't think the problem is that you're creating the connection outside of the class, that should be fine.\nI think the problem is that you are creating just one cursor and using it for a long time, which as far as I understand is not how cursors are meant to be used.\nYou can use conn.execute without manually cr... | [
1
] | [] | [] | [
"python",
"rpyc"
] | stackoverflow_0008025765_python_rpyc.txt |
Q:
mechanize could not retrieve all forms(including some generated by js)
it is a html including two forms. One of them is generated dynamic by js when the page is loaded
So, if I try to fetch them, only one form could be return, and the form generated dynamic not found.
the question is
how to fetch all forms even i... | mechanize could not retrieve all forms(including some generated by js) | it is a html including two forms. One of them is generated dynamic by js when the page is loaded
So, if I try to fetch them, only one form could be return, and the form generated dynamic not found.
the question is
how to fetch all forms even if they are generated by js.
| [
"As far as I know Mechanize does not handle javascript.\nThat means that you should either generate the form yourself - by reading the JS that creates the form, and then \"translating\" it to python, and inserting it in your script. -\nor:\nAutomate an actual browser that does understand Javascript using something ... | [
1,
1,
0
] | [] | [] | [
"forms",
"mechanize",
"perl",
"python"
] | stackoverflow_0008025379_forms_mechanize_perl_python.txt |
Q:
syncing content between two qtextedits or a qtextedit and qscintilla with undo history
I'm writing a blog editor using pyqt4. My issue is this. There is a wysiwyg editor tab and a html code editor tab. A change done in one should reflect in the other. One option is to use the setHtml and toHtml functions whene... | syncing content between two qtextedits or a qtextedit and qscintilla with undo history | I'm writing a blog editor using pyqt4. My issue is this. There is a wysiwyg editor tab and a html code editor tab. A change done in one should reflect in the other. One option is to use the setHtml and toHtml functions whenever text changes in a qtextedit. But the issue with this approach is that when I use setHtm... | [
"I did a little more research and made my question more clear in Accessing QTextHtmlImporter in PyQt4\nThat would essentially solve this issue.\n"
] | [
0
] | [] | [] | [
"pyqt4",
"python",
"qt4",
"qtextdocument",
"qtextedit"
] | stackoverflow_0007821613_pyqt4_python_qt4_qtextdocument_qtextedit.txt |
Q:
how to expose list of objects with dbus
I would like my dbus interface to have paths like this:
/org/fusegui/sites/example.com
/org/fusegui/sites/www.kernel.org
Each of the above is an object with the same methods: host(), name(), timeout(), etcetera.
How would I achieve above in python? For example if I would h... | how to expose list of objects with dbus | I would like my dbus interface to have paths like this:
/org/fusegui/sites/example.com
/org/fusegui/sites/www.kernel.org
Each of the above is an object with the same methods: host(), name(), timeout(), etcetera.
How would I achieve above in python? For example if I would have a list filled with those site objects. Ho... | [
"dbus-python: Exporting Objects\n",
"I crafted this together:\nimport gtk\nimport dbus\nimport dbus.service\nfrom dbus.mainloop.glib import DBusGMainLoop\n\nclass MyDBUSObject(dbus.service.Object):\n def __init__(self, path):\n bus_name = dbus.service.BusName('org.fusegui', bus=dbus.SessionBus())\n ... | [
0,
0
] | [] | [] | [
"dbus",
"linux",
"python"
] | stackoverflow_0008023569_dbus_linux_python.txt |
Q:
How to stop SQL replies to commands in Python Shell
I've Googled this question in a dozen different ways and can find no joy. I think I'm asking the wrong question or using the wrong words.
I'm making MySQL entries and queries from a Python script on my Linux server in a WEBPY framework. Everything works great i... | How to stop SQL replies to commands in Python Shell | I've Googled this question in a dozen different ways and can find no joy. I think I'm asking the wrong question or using the wrong words.
I'm making MySQL entries and queries from a Python script on my Linux server in a WEBPY framework. Everything works great is the good news. The bad news is that I'm filling up a l... | [
"Just set db.printing = False\n"
] | [
1
] | [] | [] | [
"mysql",
"python",
"web.py"
] | stackoverflow_0008002982_mysql_python_web.py.txt |
Q:
Python list.append as an argument
Why does the following code give 'None'? How can I resolve this?
def f1(list1):
f2(list1.append(2))
def f2(list1):
print(list1)
f1([1])
What also doesn't work:
def f1(list1):
arg1 = list1.append(2)
f2(arg1)
A:
In general, Python methods that mutate an object ... | Python list.append as an argument | Why does the following code give 'None'? How can I resolve this?
def f1(list1):
f2(list1.append(2))
def f2(list1):
print(list1)
f1([1])
What also doesn't work:
def f1(list1):
arg1 = list1.append(2)
f2(arg1)
| [
"In general, Python methods that mutate an object (such as list.append, list.extend, or list.sort) return None.\nIf you wish to print out the new list:\ndef f1(list1): \n list1.append(2)\n f2(list1)\n\n",
"It depends on what you want to do. If you want list1 to have changed after a call to f1, use\ndef f... | [
7,
6
] | [] | [] | [
"list",
"python",
"python_3.x"
] | stackoverflow_0008026660_list_python_python_3.x.txt |
Q:
Rendering multiple templates with web.py
Ive recently gotten into Webdesign in Python, I've tried multiple frameworks but web.py seems to be my favorite except for one problem. I cant seem to figure out how to make multiple pages with multiple templates....
here is my code so far:
import web
urls = (
'/', 'index... | Rendering multiple templates with web.py | Ive recently gotten into Webdesign in Python, I've tried multiple frameworks but web.py seems to be my favorite except for one problem. I cant seem to figure out how to make multiple pages with multiple templates....
here is my code so far:
import web
urls = (
'/', 'index', '/login/', 'login'
)
app = web.applicati... | [
"Try changing your url mapping:\nurls = (\n '/', 'index', \n '/login/?', 'login',\n)\n\n/login/? will work for /login and /login/ url paths. \nIt will be better if you show an exception that you get.\n"
] | [
1
] | [] | [] | [
"frameworks",
"linux",
"python",
"web.py"
] | stackoverflow_0008024511_frameworks_linux_python_web.py.txt |
Q:
authentication on python for wsgi application
I try to make simple wsgi application without any frameworks, only standard library (wsgiref). And now I looking for simple way to make authentication in my application. How I can make it?
Thanks.
A:
I wrote a very simple authentication module here: https://github.co... | authentication on python for wsgi application | I try to make simple wsgi application without any frameworks, only standard library (wsgiref). And now I looking for simple way to make authentication in my application. How I can make it?
Thanks.
| [
"I wrote a very simple authentication module here: https://github.com/comamitc/py-userauth \nIt should give you some ideas to work on if you want to write your own to handle encryption of the password, password matching, complexity checking, registration, etc. \nI would also check out Django's authentication mechan... | [
0,
0
] | [] | [] | [
"python",
"wsgi"
] | stackoverflow_0008026162_python_wsgi.txt |
Q:
wikitools parsing error
I'm using wikitools package to parse the wikipedia. I just copy this example from documentation. But its not working. When I run this code. I get following error.
Invalid JSON,trying requesting again. Can you please help me ? thanks
from wikitools import wiki
from wikitools import api
# cr... | wikitools parsing error | I'm using wikitools package to parse the wikipedia. I just copy this example from documentation. But its not working. When I run this code. I get following error.
Invalid JSON,trying requesting again. Can you please help me ? thanks
from wikitools import wiki
from wikitools import api
# create a Wiki object
site = wik... | [
"The \"http://my.wikisite.org/w/api.php\" is only an example, there is no MediaWiki under that domain. Try with \"http://en.wikipedia.org/w/api.php\" which searches in the English Wikipedia.\n"
] | [
3
] | [] | [] | [
"mediawiki",
"python"
] | stackoverflow_0008025559_mediawiki_python.txt |
Q:
Running Python file within its self
Is it possible to run another Python File from a Main Python File.
For example:
I have a file Main.py and its servers as the main directory for the following files:
Surface Area Calculator
Scientific Calculator
How would you import a Python file to them. I was hoping to do th... | Running Python file within its self | Is it possible to run another Python File from a Main Python File.
For example:
I have a file Main.py and its servers as the main directory for the following files:
Surface Area Calculator
Scientific Calculator
How would you import a Python file to them. I was hoping to do this so I can keep myself organized.
Could ... | [
"You don't need to point a Python file to them, you just need the import keyword to do that.\nSo, from your Main.py file you can do:\nfrom other_python_file import SurfaceAreaCalculator, ScientificCalculator\n\nThis way you will \"run\" other_python_file.py file within Main.py.\nIf you want to run content from a TX... | [
2
] | [] | [] | [
"python",
"scripting"
] | stackoverflow_0008026972_python_scripting.txt |
Q:
Python and PAMIE
I am having trouble navigaing a website with PAMIE. I want to invidually use it to open IE, then put in my username and password on a website. First I am trying o just navigate a site. This is what I have so Far....
from PAM30 import PAMIE
ie = PAMIE.PAMIE()
website = "http://www.python.org"
ie... | Python and PAMIE | I am having trouble navigaing a website with PAMIE. I want to invidually use it to open IE, then put in my username and password on a website. First I am trying o just navigate a site. This is what I have so Far....
from PAM30 import PAMIE
ie = PAMIE.PAMIE()
website = "http://www.python.org"
ie.navigate(website)
ie... | [
"I didn't use PAMIE, but it seems you need to write ie = PAMIE(), not ie = PAMIE.PAMIE() because PAM30.PAMIE is a class itself.\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0008027001_python.txt |
Q:
Always anonymous user when using render_to_response in django code
Im using Django 1.3.1.In my django code, i have the following template for the main page, its called main_page.html:
<html>
<head>
<title>My Site</title>
</head>
<body>
<h1>Welcome</h1>
{% if user.username %}
<p>Welcome {{ user.username }}!</p>
... | Always anonymous user when using render_to_response in django code | Im using Django 1.3.1.In my django code, i have the following template for the main page, its called main_page.html:
<html>
<head>
<title>My Site</title>
</head>
<body>
<h1>Welcome</h1>
{% if user.username %}
<p>Welcome {{ user.username }}!</p>
{% else %}
<p>Welcome anonymous user!
You need to <a href="/login/... | [
"In the template you should use {% if request.user.is_authenticated %} instead of your {% if user.username %}. That should solve your problem.\nOn the other hand, I don't know, why you're trying to explicitly add the user variable in the view. Why not using something like:\ndef main_page(request):\n return render_... | [
4,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0008027011_django_python.txt |
Q:
Linking values from two separate lists
Possible Duplicate:
Combining 2 lists in python
I have two lists with the same number of values in each
[x1,x2....xn] and [y1,y2....yn]
I would like to produce a 3rd list which takes the 1st value from the first list and links it with the first value from the second and th... | Linking values from two separate lists |
Possible Duplicate:
Combining 2 lists in python
I have two lists with the same number of values in each
[x1,x2....xn] and [y1,y2....yn]
I would like to produce a 3rd list which takes the 1st value from the first list and links it with the first value from the second and then repeats for every value
So that my outpu... | [
"Use zip(list1, list2).\n"
] | [
1
] | [] | [] | [
"list",
"python"
] | stackoverflow_0008027147_list_python.txt |
Q:
Problems with Tornado Web Server
I am using OSX 10.58 with the following versions:
curl --version
curl 7.16.4 (i386-apple-darwin9.0) libcurl/7.21.0 OpenSSL/0.9.7l zlib/1.2.3
Protocols: dict file ftp ftps http https imap imaps ldap ldaps pop3 pop3s rtsp smtp smtps telnet tftp
Features: IPv6 Largefile NTLM SSL libz... | Problems with Tornado Web Server | I am using OSX 10.58 with the following versions:
curl --version
curl 7.16.4 (i386-apple-darwin9.0) libcurl/7.21.0 OpenSSL/0.9.7l zlib/1.2.3
Protocols: dict file ftp ftps http https imap imaps ldap ldaps pop3 pop3s rtsp smtp smtps telnet tftp
Features: IPv6 Largefile NTLM SSL libz
Using /Library/Python/2.5/site-pack... | [
"It seems that you use Python 2.5, just try to use the 2.6-2.7 version of Python, it should help.\nQuote from Tornado prerequisites:\n\nOn Python 2.6 and 2.7, there are no dependencies outside the Python\n standard library, although PycURL (version 7.18.2 or higher required;\n version 7.21.1 or higher recommended... | [
0
] | [] | [] | [
"python",
"tornado",
"webserver"
] | stackoverflow_0003356014_python_tornado_webserver.txt |
Q:
Error while installing a Python lib?
I am trying to install the ahocorasick library using easy_install but am getting this error:
Searching for ahocorasick
Reading http://pypi.python.org/simple/ahocorasick/
Reading http://hkn.eecs.berkeley.edu/~dyoo/python/ahocorasick/
Best match: ahocorasick 1.0pre
Downloading ht... | Error while installing a Python lib? | I am trying to install the ahocorasick library using easy_install but am getting this error:
Searching for ahocorasick
Reading http://pypi.python.org/simple/ahocorasick/
Reading http://hkn.eecs.berkeley.edu/~dyoo/python/ahocorasick/
Best match: ahocorasick 1.0pre
Downloading https://hkn.eecs.berkeley.edu/~dyoo/python/a... | [
"Find the build dependencies for ahocorasick and install them. You're likely missing the header and development libraries, which you can't build the program without them.\n"
] | [
1
] | [] | [] | [
"compiler_errors",
"python"
] | stackoverflow_0008027065_compiler_errors_python.txt |
Q:
How to refactor an API
How do you deal with APIs that should be refactored, while not breaking the clients that use the API?
One possible solution I came across: recording refactors to the API, providing the recording to clients of the API which can then apply the refactors to their code:
https://netfiles.uiuc.edu... | How to refactor an API | How do you deal with APIs that should be refactored, while not breaking the clients that use the API?
One possible solution I came across: recording refactors to the API, providing the recording to clients of the API which can then apply the refactors to their code:
https://netfiles.uiuc.edu/dig/papers/Thesis.pdf
Does ... | [
"You could always provide a bridging layer which looks exactly like the old api, but calls on new functionality where you've made breaking changes. That way old clients can talk to your compatibility api, while new clients may use your new and improved layer.\n",
"It's rather simple, at least in theory — don't ev... | [
3,
2,
1,
0,
0,
0
] | [] | [] | [
"api",
"python",
"refactoring"
] | stackoverflow_0008022444_api_python_refactoring.txt |
Q:
Show PyGTK Window on all virtual desktops/workspaces
I am working on a timer which should after a certain time show a popup window. I want to force the user to accept the fact that the time is up.
I would like to set the window to be visible on all workspaces. I am able to set that property manually in a window ma... | Show PyGTK Window on all virtual desktops/workspaces | I am working on a timer which should after a certain time show a popup window. I want to force the user to accept the fact that the time is up.
I would like to set the window to be visible on all workspaces. I am able to set that property manually in a window manager but the application should do that.
How to ask a win... | [
"Call my_window.stick().\n"
] | [
5
] | [] | [] | [
"pygtk",
"python",
"workspace"
] | stackoverflow_0008027243_pygtk_python_workspace.txt |
Q:
python unzip -- tremendously slow?
Can somebody please explain the following mystery?
I created a binary file of size ~37[MB]. zipping it in Ubuntu -- using the terminal -- took less than 1[sec]. I then tried python: zipping it programatically (using the zipfile module) took also about 1[sec].
I then tried to unzi... | python unzip -- tremendously slow? | Can somebody please explain the following mystery?
I created a binary file of size ~37[MB]. zipping it in Ubuntu -- using the terminal -- took less than 1[sec]. I then tried python: zipping it programatically (using the zipfile module) took also about 1[sec].
I then tried to unzip the zip file I created. In Ubuntu -- u... | [
"I was struggling to unzip/decompress/extract zip files with Python as well and that \"create ZipFile object, loop through its .namelist(), read the files and write them to file system\" low-level approach didn't seem very Python. So I started to dig zipfile objects that I believe not very well documented and cover... | [
2,
0,
0
] | [] | [] | [
"linux",
"python",
"ubuntu",
"unzip",
"zip"
] | stackoverflow_0004997910_linux_python_ubuntu_unzip_zip.txt |
Q:
Python Scripts for mac, how to run a program and get value back
I am trying to build a script in python to mac OS, I need the script to run two other scripts; the only thing my scripts does is run a website, and return value 1 or 0.
I just need to get the values, in windows i am getting then from CMD with "Exit v... | Python Scripts for mac, how to run a program and get value back | I am trying to build a script in python to mac OS, I need the script to run two other scripts; the only thing my scripts does is run a website, and return value 1 or 0.
I just need to get the values, in windows i am getting then from CMD with "Exit value".
But i am new to mac, and in my job i need do it i mac.
After... | [
"import subprocess\nr = subprocess.call(['script', 'argument1', ...])\n\nNow r is the return value from your script. To write that to a file (I assume you want it as text):\nopen('statusfile.txt', 'w').write('%d\\n' % r)\n\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0008027457_python.txt |
Q:
Changing user in python
I am writing a simple script which restarts a hadoop slave. In the script, I have to do some initial changes as a root user. After that I have to change to user "hadoop" and perform set of commands. I was using os.system to run commands but I doubt whether it works well. For example:
uid=p... | Changing user in python | I am writing a simple script which restarts a hadoop slave. In the script, I have to do some initial changes as a root user. After that I have to change to user "hadoop" and perform set of commands. I was using os.system to run commands but I doubt whether it works well. For example:
uid=pwd.getpwnam('hadoop')[2]
os.s... | [
"you could use:\nos.system('sudo -u hadoop bin/hadoop-daemon.sh stop tasktracker')\n\nor if you dont have sudo, but have su\nos.system('su hadoop -c \"bin/hadoop-daemon.sh stop tasktracker\"')\n\n",
"It is a much better idea to use \"su\" than to switch the user ID using os.setuid().\nWhy?\n\n\"su\" will set up t... | [
7,
3,
1,
0
] | [] | [] | [
"hadoop",
"linux",
"os.system",
"python"
] | stackoverflow_0008025294_hadoop_linux_os.system_python.txt |
Q:
Does Python GC deal with reference-cycles like this?
Using objgraph, I found a bunch of objects like this:
Will Python's garbage collector deal with cycles like this, or will it leak?
A slightly wider view of the loop:
A:
Python's standard reference counting mechanism cannot free cycles, so the structure in you... | Does Python GC deal with reference-cycles like this? | Using objgraph, I found a bunch of objects like this:
Will Python's garbage collector deal with cycles like this, or will it leak?
A slightly wider view of the loop:
| [
"Python's standard reference counting mechanism cannot free cycles, so the structure in your example would leak.\nThe supplemental garbage collection facility, however, is enabled by default and should be able to free that structure, if none of its components are reachable from the outside anymore and they do not h... | [
28,
21,
5,
2
] | [] | [] | [
"garbage_collection",
"memory_leaks",
"objgraph",
"python"
] | stackoverflow_0008025888_garbage_collection_memory_leaks_objgraph_python.txt |
Q:
Efficient way of frequency counting of continuous words?
I have a string like this:
inputString = "this is the first sentence in this book the first sentence is really the most interesting the first sentence is always first"
and a dictionary like this:
{
'always first': 0,
'book the': 0,
'first': 0,... | Efficient way of frequency counting of continuous words? | I have a string like this:
inputString = "this is the first sentence in this book the first sentence is really the most interesting the first sentence is always first"
and a dictionary like this:
{
'always first': 0,
'book the': 0,
'first': 0,
'first sentence': 0,
'in this': 0,
'interesting t... | [
"Check out the Aho-Corasick algorithm.\n",
"When confronted with this problem, I think, \"I know, I'll use regular expressions\".\nStart off by making a list of all the patterns, sorted by decreasing length:\npatterns = sorted(counts.keys(), key=len, reverse=True)\n\nNow make that into a single massive regular ex... | [
4,
2,
2,
0,
0
] | [] | [] | [
"parsing",
"python",
"string",
"text"
] | stackoverflow_0008026963_parsing_python_string_text.txt |
Q:
ImportError: no module named Tkinter (Running python with NotePad++'s NppExec)
I'm trying to run a python file using Notepad++'s NppExec plugin. My file attempts to import Tkinter using the line "from Tkinter import * ". With NppExec, I run the following script:
python "$(FULL_CURRENT_PATH)"
or sometimes
python ... | ImportError: no module named Tkinter (Running python with NotePad++'s NppExec) | I'm trying to run a python file using Notepad++'s NppExec plugin. My file attempts to import Tkinter using the line "from Tkinter import * ". With NppExec, I run the following script:
python "$(FULL_CURRENT_PATH)"
or sometimes
python -i "$(FULL_CURRENT_PATH)"
In either case, I get the error "ImportError: No module ... | [
"The problem is simple -- the python command you are running does not have a module named Tkinter. The cause of the problem is more difficult to understand without more information. My first guess would be that NppExec is running a different version of python than you think it is running, and this version of python... | [
8
] | [] | [] | [
"importerror",
"notepad++",
"nppexec",
"python",
"tkinter"
] | stackoverflow_0008025188_importerror_notepad++_nppexec_python_tkinter.txt |
Q:
Finding duplicates in a list and returning True or False(python)
I have to write a function which returns True or False depengin on a list.
For example list_a =[1,2,3,4,4] it should return False and if list_a=[1,2,3,4] it should return True.
Can anyone help ?
A:
def has_dups(l):
return len(set(l)) < len(l)
... | Finding duplicates in a list and returning True or False(python) | I have to write a function which returns True or False depengin on a list.
For example list_a =[1,2,3,4,4] it should return False and if list_a=[1,2,3,4] it should return True.
Can anyone help ?
| [
"def has_dups(l): \n return len(set(l)) < len(l)\n\n",
"Utilize a set. Sets are sequences that have only unique elements.\ndef hasNoDuplicates ( lst ):\n return len( lst ) == len( set( lst ) )\n\n>>> hasNoDuplicates( [1,2,3,4,4] )\nFalse\n>>> hasNoDuplicates( [1,2,3,4] )\nTrue\n\n"
] | [
1,
1
] | [] | [] | [
"duplicates",
"function",
"list",
"python",
"return"
] | stackoverflow_0008027954_duplicates_function_list_python_return.txt |
Q:
What does "**" mean in python?
Simple program:
storyFormat = """
Once upon a time, deep in an ancient jungle,
there lived a {animal}. This {animal}
liked to eat {food}, but the jungle had
very little {food} to offer. One day, an
explorer found the {animal} and discovered
it... | What does "**" mean in python? | Simple program:
storyFormat = """
Once upon a time, deep in an ancient jungle,
there lived a {animal}. This {animal}
liked to eat {food}, but the jungle had
very little {food} to offer. One day, an
explorer found the {animal} and discovered
it liked {food}. The explorer took th... | [
"'**' takes a dict and extracts its contents and passes them as parameters to a function. Take this function for example:\ndef func(a=1, b=2, c=3):\n print a\n print b\n print b\n\nNow normally you could call this function like this:\nfunc(1, 2, 3)\n\nBut you can also populate a dictionary with those paramete... | [
49,
4
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0008028192_python_python_3.x.txt |
Q:
how many classes in a .PY file
I'm learning Python and WxPython. So far, I'm following the examples in AnotherTutorial, which is mainly wxPython related.
I'm trying to understand the following code:
import wx
class MyMenu(wx.Frame):
def __init__(self, parent, id, title):
wx.Frame.__init__(self, parent... | how many classes in a .PY file | I'm learning Python and WxPython. So far, I'm following the examples in AnotherTutorial, which is mainly wxPython related.
I'm trying to understand the following code:
import wx
class MyMenu(wx.Frame):
def __init__(self, parent, id, title):
wx.Frame.__init__(self, parent, id, title, wx.DefaultPosition, wx.... | [
"If you're used to Java, you know you can only have one public class per file, and it should have the same name as the file itself (sorry if this has changed; it was true when I used Java ;). This is so when javac is compiling your program it can find dependent but not-yet-compiled classes in other files.\nPython a... | [
3,
0
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0008028128_python_wxpython.txt |
Q:
How do I print a PDF file to a printer in landscape from Python?
I'm using Mac OSX but I need a platform independent method to print a pdf file.
I created a graph in Matplotlib and want to print it to my printer.
I can set the orientation of the canvas to fit a portrait layout with:
fig.set_size_inches( 8.27,11.... | How do I print a PDF file to a printer in landscape from Python? | I'm using Mac OSX but I need a platform independent method to print a pdf file.
I created a graph in Matplotlib and want to print it to my printer.
I can set the orientation of the canvas to fit a portrait layout with:
fig.set_size_inches( 8.27,11.69) # set the figure size in inches
but using:
fig.set_size_inches( 1... | [
"I have seen lpr -o landscape, but do not have enough experience with it to know if it works for all printers.\nRather than changing orientation while printing, you can do it when generating the image (if it fits with your workflow). The matplotlib savefig command allows you to specify saving in landscape orientati... | [
2
] | [] | [] | [
"matplotlib",
"pdf",
"printing",
"python"
] | stackoverflow_0008028115_matplotlib_pdf_printing_python.txt |
Q:
Setting up openId in tornado python
Hey all... I have been reading the tornado doc and came across open id mixin so I thought to myself "Wicked no horrid password system on my side" then I looked into how to implement it, the only example I came across was this
class GoogleHandler(tornado.web.RequestHandler, torna... | Setting up openId in tornado python | Hey all... I have been reading the tornado doc and came across open id mixin so I thought to myself "Wicked no horrid password system on my side" then I looked into how to implement it, the only example I came across was this
class GoogleHandler(tornado.web.RequestHandler, tornado.auth.GoogleMixin):
@tornado.web.as... | [
"This handler does not depend on other parts of application, you just set it on something like '/login/google' in url conf and place a link to this url somewhere on your website.\nUser clicks on it and gets redirected to google auth page (if it's logged out of google) or to a page asking to grant permission to acce... | [
6
] | [] | [] | [
"document",
"openid",
"python",
"tornado"
] | stackoverflow_0005452039_document_openid_python_tornado.txt |
Q:
python: conditinoally splitting a string
there are lots of questions about split in python, but I couldn't find
corresponding to my problem. I want to split a string, but need to have
different values for the splitter, depending on a condition. For the test
case, my string is "11xx22xx33xxBEGINxx44xx55xxENDxx66xx7... | python: conditinoally splitting a string | there are lots of questions about split in python, but I couldn't find
corresponding to my problem. I want to split a string, but need to have
different values for the splitter, depending on a condition. For the test
case, my string is "11xx22xx33xxBEGINxx44xx55xxENDxx66xx77". I want to
process this string in chunks, m... | [
"You can do it with a regular expression:\nmatches = re.findall('(?:^|xx)(BEGIN.*?END|.*?)(?=xx|$)', s)\n\nResult:\n['11', '22', '33', 'BEGINxx44xx55xxEND', '66', '77']\n\nSee it working online: ideone\n",
"What about splitting them all and then joining all the ones between BEGIN and END?\nssplit = mystring.split... | [
5,
1
] | [] | [] | [
"python"
] | stackoverflow_0008028359_python.txt |
Q:
Python toolkit for disk analyzer
I'm creating a Disk Analyzer in Linux. I would like to know which Python toolkit will help me with the GUI. I'm currently trying Tkinter is there something better?
A:
"Better" is subjective. I will gladly offer my opinion that there is no toolkit better than Tkinter for this task... | Python toolkit for disk analyzer | I'm creating a Disk Analyzer in Linux. I would like to know which Python toolkit will help me with the GUI. I'm currently trying Tkinter is there something better?
| [
"\"Better\" is subjective. I will gladly offer my opinion that there is no toolkit better than Tkinter for this task. This task seemingly doesn't need much eye candy or the ability to print, which are Tkinter's weak points. Tkinter is easy to use, modern, stable, and very customizable. Plus, you probably already ha... | [
1
] | [] | [] | [
"analyzer",
"diskspace",
"linux",
"python",
"tkinter"
] | stackoverflow_0008028001_analyzer_diskspace_linux_python_tkinter.txt |
Q:
How come my program can connect to a nonexistent website?
I am new to python and network programming and I am having trouble with a simple program. I am basically opening a connection to a nonexistent website and somehow it seems that the connection succeeds. Moreover, I get a 200 return code which means the http ... | How come my program can connect to a nonexistent website? | I am new to python and network programming and I am having trouble with a simple program. I am basically opening a connection to a nonexistent website and somehow it seems that the connection succeeds. Moreover, I get a 200 return code which means the http server has responded that it exists and the connection is OK. H... | [
"You might be using an ISP that fakes DNS results in order to give you a spam page helpful search page instead of an error for nonexistant names.\nWhat does a ping Nonexistentsite.com result in on the machine where you tested your Python code?\n",
"Running your code in Cygwin's Python, I get an error for Nonexist... | [
4,
0,
0
] | [] | [] | [
"http",
"ironpython",
"python"
] | stackoverflow_0008027158_http_ironpython_python.txt |
Q:
Methods in models
This is my first attempt to build a json webservice using the Tornado Framework and i have a question about the models design.
Currently i have a Model file (models.py) with all my models that represents my objects like this (this is a logical representation)
class person():
name = StringField(... | Methods in models | This is my first attempt to build a json webservice using the Tornado Framework and i have a question about the models design.
Currently i have a Model file (models.py) with all my models that represents my objects like this (this is a logical representation)
class person():
name = StringField()
age = IntField()
... | [
"In general you will like to have a common ancestor (in terms of inheritance) for all your models, where you implement common methods for all of them. Usually it will be handling of serialization/deserialization, database API abstraction, search, access control and so on. ORMs almost always provide such an ancestor... | [
0
] | [] | [] | [
"model_view_controller",
"mongoengine",
"python",
"tornado"
] | stackoverflow_0007989392_model_view_controller_mongoengine_python_tornado.txt |
Q:
conflict between OneToMany and OneToOne relationship in Django
I need to define a Meeting model which includes an organiser and a number of participants. All participants are derived from the standard User in auth module.
from django.db import models
from django.contrib.auth.models import User
class Meeting(model... | conflict between OneToMany and OneToOne relationship in Django | I need to define a Meeting model which includes an organiser and a number of participants. All participants are derived from the standard User in auth module.
from django.db import models
from django.contrib.auth.models import User
class Meeting(models.Model):
organizer=models.ForeignKey(User)
participants=mod... | [
"class Meeting(models.Model):\n organizer=models.ForeignKey(User, related_name=\"meetings_orginizer\")\n participants=models.ManyToManyField(User, related_name=\"meetings_participants\")\n\nIf you have a user object and you want to follow the relationship backwards to find either the meetings that user is an ... | [
3,
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0008028666_django_python.txt |
Q:
How do i calculate amount of identic elements in a list?
I Have a (very long) list, with this structure:
li1 = [[1.4, b][1.5, a][1.6, c][1,4, b][1.7,c][1.4, a][1.6,c]]
I want to write a loop that calculate amount of elements li1[i][0]` with identical value, and put this information in a new list, like this:
li2 ... | How do i calculate amount of identic elements in a list? | I Have a (very long) list, with this structure:
li1 = [[1.4, b][1.5, a][1.6, c][1,4, b][1.7,c][1.4, a][1.6,c]]
I want to write a loop that calculate amount of elements li1[i][0]` with identical value, and put this information in a new list, like this:
li2 = [[1.4, 3][1.5, 1][1.6, 2][1.7, 1]]
The problem for me is th... | [
"from collections import Counter\na, b, c = 'abc'\nli1 = [[1.4, b], [1.5, a], [1.6, c], [1.4, b], [1.7, c], [1.4, a], [1.6, c]]\nsorted(Counter(x[0] for x in li1).items())\n\n(map list onto this if you desperately want a list of lists.)\n",
"Since you only care about the first value of the list, the first step is... | [
3,
0,
0
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0008028566_python_python_3.x.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.