title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
How get hours:minutes
1,784,952
<p>I have a script here (not my own) which calculates the length of a movie in my satreceiver. It displays the length in <strong>minutes:seconds</strong></p> <p>I want to have that in <strong>hours:minutes</strong></p> <p>What changes do I have to make?</p> <p>This is the peace of script concerned:</p> <pre><code>i...
1
2009-11-23T18:11:07Z
33,964,397
<p>You can use timedelta</p> <pre><code>from datetime import timedelta str(timedelta(minutes=100)) # "1:40:00" </code></pre>
1
2015-11-27T20:23:17Z
[ "python", "time", "formatting" ]
Managing *args variance in calls to functions
1,784,971
<p>Have a method with the following signature:</p> <pre><code>def foo(self, bar, *uks): return other_method(..., uks) </code></pre> <p>Normally this is called as:</p> <pre><code>instance.foo(1234, a, b, c, d) </code></pre> <p>However in some cases I need to do something like this:</p> <pre><code>p = [a, b, c, ...
3
2009-11-23T18:13:22Z
1,784,992
<p>Python supports <a href="http://docs.python.org/tutorial/controlflow.html#unpacking-argument-lists" rel="nofollow">unpacking of argument lists</a> to handle exactly this situation. The two following calls are equivalent:</p> <p>Regular call:</p> <pre><code>instance.foo(1234, a, b, c, d) </code></pre> <p>Argument...
3
2009-11-23T18:17:06Z
[ "python" ]
Managing *args variance in calls to functions
1,784,971
<p>Have a method with the following signature:</p> <pre><code>def foo(self, bar, *uks): return other_method(..., uks) </code></pre> <p>Normally this is called as:</p> <pre><code>instance.foo(1234, a, b, c, d) </code></pre> <p>However in some cases I need to do something like this:</p> <pre><code>p = [a, b, c, ...
3
2009-11-23T18:13:22Z
1,784,993
<pre><code>p = [a, b, c, d] instance.foo(1234, *p) </code></pre> <p>The <code>*p</code> form is the crucial part here -- it means "expand sequence <code>p</code> into separate positional arguments".</p>
2
2009-11-23T18:17:22Z
[ "python" ]
Managing *args variance in calls to functions
1,784,971
<p>Have a method with the following signature:</p> <pre><code>def foo(self, bar, *uks): return other_method(..., uks) </code></pre> <p>Normally this is called as:</p> <pre><code>instance.foo(1234, a, b, c, d) </code></pre> <p>However in some cases I need to do something like this:</p> <pre><code>p = [a, b, c, ...
3
2009-11-23T18:13:22Z
1,785,214
<p>I think the answers you have here are correct. Here's a fully fleshed out example:</p> <pre><code>class MyObject(object): def foo(self, bar, *uks): return self.other_method(1, uks) def other_method(self, x, uks): print "uks is %r" % (uks,) # sample data... a, b, c, d = 'a', 'b', 'c', 'd' ...
1
2009-11-23T18:56:30Z
[ "python" ]
Tuples in Dicts
1,784,973
<p>Is it possible in python to add a tuple as a value in a dictionary?<br> And if it is,how can we add a new value, then? And how can we remove and change it?</p>
1
2009-11-23T18:13:52Z
1,784,978
<pre><code>&gt;&gt;&gt; a = {'tuple': (23, 32)} &gt;&gt;&gt; a {'tuple': (23, 32)} &gt;&gt;&gt; a['tuple'] = (42, 24) &gt;&gt;&gt; a {'tuple': (42, 24)} &gt;&gt;&gt; del a['tuple'] &gt;&gt;&gt; a {} </code></pre> <p>if you meant to use tuples as keys you could do:</p> <pre><code>&gt;&gt;&gt; b = {(23, 32): 'tuple as ...
12
2009-11-23T18:15:00Z
[ "python", "dictionary", "tuples" ]
Tuples in Dicts
1,784,973
<p>Is it possible in python to add a tuple as a value in a dictionary?<br> And if it is,how can we add a new value, then? And how can we remove and change it?</p>
1
2009-11-23T18:13:52Z
1,785,004
<p>You can't change a tuple itself. You have to replace it by a different tuple.</p> <p>When you use a list, you could also add values to it (changing the list itself) without need to replace it:</p> <pre><code>&gt;&gt; a = {'list': (23, 32)} &gt;&gt; a {'list': [23, 32]} &gt;&gt; a['list'].append(99) &gt;&gt; a {'li...
1
2009-11-23T18:18:47Z
[ "python", "dictionary", "tuples" ]
Tuples in Dicts
1,784,973
<p>Is it possible in python to add a tuple as a value in a dictionary?<br> And if it is,how can we add a new value, then? And how can we remove and change it?</p>
1
2009-11-23T18:13:52Z
1,785,006
<p>Since tuples are <em>immutable</em>, you cannot add a value to the tuple. What you <em>can</em> do, is construct a new tuple from the current tuple and an extra value. The <code>+=</code> operator does this for you, provided the left argument is a variable (or in this case a dictionary value):</p> <pre><code>&gt;&g...
1
2009-11-23T18:19:10Z
[ "python", "dictionary", "tuples" ]
Tuples in Dicts
1,784,973
<p>Is it possible in python to add a tuple as a value in a dictionary?<br> And if it is,how can we add a new value, then? And how can we remove and change it?</p>
1
2009-11-23T18:13:52Z
1,785,210
<pre><code>t1=('name','date') t2=('x','y') # "Number" is a String key! d1={"Number":t1} # Update the value of "Number" d1["Number"] = t2 # Use a tuple as key, and another tuple as value d1[t1] = t2 # Obtain values (getters) # Can throw a KeyError if "Number" not a key foo = d1["Number"] # Does not throw a key erro...
1
2009-11-23T18:55:26Z
[ "python", "dictionary", "tuples" ]
term by term division in python (division termino a termino en python )
1,785,005
<p><strong>hello all,</strong> need to define a function that can be divided term by term matrix or in the worst cases, between arrays of lists so you get the result in a third matrix,</p> <p>thanks for any response</p>
3
2009-11-23T18:18:48Z
1,785,047
<p>Unless I'm misunderstanding, this is where <a href="http://numpy.scipy.org/"><code>numpy</code></a> can be put to good use:</p> <pre><code>&gt;&gt;&gt; from numpy import * &gt;&gt;&gt; a = array([[1,2,3],[4,5,6],[7,8,9]]) &gt;&gt;&gt; b = array([[0.5] * 3, [0.5] * 3, [0.5] * 3]) &gt;&gt;&gt; a / b array([[ 2., 4...
7
2009-11-23T18:26:30Z
[ "python" ]
Convert \r text to \n so readlines() works as intended
1,785,233
<p>In Python, you can read a file and load its lines into a list by using</p> <pre><code>f = open('file.txt','r') lines = f.readlines() </code></pre> <p>Each individual line is delimited by <code>\n</code> but if the contents of a line have <code>\r</code> then it is not treated as a new line. I need to convert all <...
11
2009-11-23T18:58:13Z
1,785,275
<pre><code>f = open('file.txt','rU') </code></pre> <p>This opens the file with Python's <a href="http://docs.python.org/library/functions.html#open">universal newline support</a> and <code>\r</code> is treated as an end-of-line.</p>
31
2009-11-23T19:04:42Z
[ "python", "readline" ]
Convert \r text to \n so readlines() works as intended
1,785,233
<p>In Python, you can read a file and load its lines into a list by using</p> <pre><code>f = open('file.txt','r') lines = f.readlines() </code></pre> <p>Each individual line is delimited by <code>\n</code> but if the contents of a line have <code>\r</code> then it is not treated as a new line. I need to convert all <...
11
2009-11-23T18:58:13Z
1,785,348
<p>If it's a concern, open in binary format and convert with this code:</p> <pre><code>from __future__ import with_statement with open(filename, "rb") as f: s = f.read().replace('\r\n', '\n').replace('\r', '\n') lines = s.split('\n') </code></pre>
1
2009-11-23T19:18:01Z
[ "python", "readline" ]
Filtering mousePressEvent with installEventFilter
1,785,251
<p>I am having problem filtering the <code>"mousePressEvent"</code> with <code>installEventFilter</code></p> <p><code>MyTestxEdit</code> is a widget that holds <code>QTextEdit</code> I want that all the events of <code>QTextEdit</code> will be handle by <code>MyTestxEdit</code> I have used the <code>installEventFilter...
2
2009-11-23T19:00:30Z
1,785,307
<p>Try to install the filter on the <code>QTextEdit's</code> viewport instead of the <code>QTextEdit</code> itself...</p> <p>I don't know python but something like:</p> <pre><code>self.__qTextEdit.viewport().installEventFilter(self) </code></pre> <p>I hope it helps!</p> <p>You should do something like:</p> <pre><c...
5
2009-11-23T19:11:02Z
[ "python", "qt" ]
Piping Cygwin into a Python program
1,785,265
<p>As a i'm new to the whole Piping thing and Python I had recently encountered a problem trying to pipe Cygwin's stdin &amp; stdout into a python program usin Python's subprocess moudle. for example I took a simple program:</p> <pre><code>cygwin = subprocess.Popen('PathToCygwin',shell=False,stdin=subprocess.PIPE,stdo...
0
2009-11-23T19:03:18Z
1,785,346
<p>Well, your literal code won't work. You are passing a string with the value 'PathToCygwin' and that isn't going to do anything. I assume that you are passing a better string than that, but you didn't show us what.</p> <p>I think your PathToCygwin is probably the problem. If you don't get the path right, it won't...
2
2009-11-23T19:17:57Z
[ "python", "cygwin", "pipe", "subprocess" ]
How do I build the 32-bit pypy JIT in 64-bit Linux?
1,785,428
<p>Pypy's JIT will compile on 64-bit Linux ever since it grew 64-bit support, but what if I wanted to compile a 32-bit version? How should I cross-compile a 32-bit JITting pypy on that machine?</p>
4
2009-11-23T19:32:16Z
1,791,637
<p>You could try compiling it in a chroot.</p>
2
2009-11-24T17:29:37Z
[ "python", "pypy" ]
When should I use uuid.uuid1() vs. uuid.uuid4() in python?
1,785,503
<p>I understand the differences between the two from the <a href="http://docs.python.org/2/library/uuid.html">docs.</a></p> <p><code>uuid1()</code>:<br> Generate a UUID from a host ID, sequence number, and the current time</p> <p><code>uuid4()</code>:<br> Generate a random UUID.</p> <p>So <code>uuid1</code> uses mac...
121
2009-11-23T19:48:24Z
1,785,592
<p><code>uuid1()</code> is guaranteed to not produce any collisions (under the assumption you do not create too many of them at the same time). I wouldn't use it if it's important that there's no connection between the <code>uuid</code> and the computer, as the mac address gets used to make it unique across computers.<...
150
2009-11-23T20:05:41Z
[ "python", "uuid" ]
When should I use uuid.uuid1() vs. uuid.uuid4() in python?
1,785,503
<p>I understand the differences between the two from the <a href="http://docs.python.org/2/library/uuid.html">docs.</a></p> <p><code>uuid1()</code>:<br> Generate a UUID from a host ID, sequence number, and the current time</p> <p><code>uuid4()</code>:<br> Generate a random UUID.</p> <p>So <code>uuid1</code> uses mac...
121
2009-11-23T19:48:24Z
1,785,670
<p>One instance when you may consider <code>uuid1()</code> rather than <code>uuid4()</code> is <strong>when UUIDs are produced on separate machines</strong>, for example when multiple online transactions are process on several machines for scaling purposes.</p> <p>In such a situation, the risks of having collisions du...
21
2009-11-23T20:18:20Z
[ "python", "uuid" ]
When should I use uuid.uuid1() vs. uuid.uuid4() in python?
1,785,503
<p>I understand the differences between the two from the <a href="http://docs.python.org/2/library/uuid.html">docs.</a></p> <p><code>uuid1()</code>:<br> Generate a UUID from a host ID, sequence number, and the current time</p> <p><code>uuid4()</code>:<br> Generate a random UUID.</p> <p>So <code>uuid1</code> uses mac...
121
2009-11-23T19:48:24Z
24,271,230
<p>One thing to note when using <code>uuid1</code>, if you use the default call (without giving <code>clock_seq</code> parameter) you have a chance of running into collisions: you have only 14 bit of randomness (generating 18 entries within 100ns gives you roughly 1% chance of a collision see birthday paradox/attack). ...
4
2014-06-17T18:49:50Z
[ "python", "uuid" ]
When should I use uuid.uuid1() vs. uuid.uuid4() in python?
1,785,503
<p>I understand the differences between the two from the <a href="http://docs.python.org/2/library/uuid.html">docs.</a></p> <p><code>uuid1()</code>:<br> Generate a UUID from a host ID, sequence number, and the current time</p> <p><code>uuid4()</code>:<br> Generate a random UUID.</p> <p>So <code>uuid1</code> uses mac...
121
2009-11-23T19:48:24Z
34,391,851
<p>My team just ran into trouble using UUID1 for a database upgrade script where we generated ~120k UUIDs within a couple of minutes. The UUID collision led to violation of a primary key constraint.</p> <p>We've upgraded 100s of servers but on our Amazon EC2 instances we ran into this issue a few times. I suspect poor...
7
2015-12-21T08:51:22Z
[ "python", "uuid" ]
C lib with Python bindings where both want to render
1,785,604
<p>I'm sketching on some fluid dynamics in Python. After a while, I'm looking for a bit more speed, so I rewrote the actual logic in C and put up some Python bindings (using <strong>SWIG</strong>).</p> <p>My problem now is that I don't how to render it in a good way. The logic is run pixel by pixel so pixels are what ...
0
2009-11-23T20:06:39Z
1,787,720
<p>Have you tried something like the following to get <code>SDL_Surface*</code> from python object?</p> <pre><code>PySurfaceObject *obj; SDL_Surface *surf; if (!PyArg_ParseTuple(args, 'O!', &amp;PySurface_Type, &amp;obj) { return NULL; # or other action for error } surf = PySurface_AsSurface(obj); </code></pre>
0
2009-11-24T04:10:31Z
[ "python", "c", "sdl", "swig", "pygame" ]
Python Webdriver doesn't wait until the page is downloaded in Firefox when used with proxy
1,785,607
<p>when I set the Firefox proxy with python webdriver, it doesn't wait until the page is fully downloaded, this doesn't happen when I don't set one. How can I change this behavior? Or how can I check that the page download is over?</p>
1
2009-11-23T20:06:54Z
1,790,122
<p>The simplest thing to do is to poll the page looking for an element you know will be present once the download is complete. The Java webdriver bindings offer a "Wait" class for just this purpose, though there isn't (yet) an analogue for this in the python bindings.</p>
1
2009-11-24T13:36:54Z
[ "python", "firefox", "proxy", "webdriver" ]
GAE Image Posting to Datastore through Django Form
1,785,637
<p>I'm working on a little side project that involves posting an avatar to a users profile page, seems straight forward enough. I'm following the instructions from the "<a href="http://code.google.com/appengine/docs/python/images/usingimages.html" rel="nofollow">Using the Images Python API</a>" on the GAE web site. </p...
0
2009-11-23T20:12:43Z
1,786,944
<p>In your image serving code, you're writing out a redirect, with the 'URL' for the redirect being the image data - eg, you're redirecting users to "%PNG...". You need to write out the response data directly.</p> <p>Besides that, what is HttpResponseRedirect? It's not part of the webapp framework.</p> <p>Also, have ...
1
2009-11-24T00:01:58Z
[ "python", "django", "google-app-engine", "gae-datastore" ]
GAE Image Posting to Datastore through Django Form
1,785,637
<p>I'm working on a little side project that involves posting an avatar to a users profile page, seems straight forward enough. I'm following the instructions from the "<a href="http://code.google.com/appengine/docs/python/images/usingimages.html" rel="nofollow">Using the Images Python API</a>" on the GAE web site. </p...
0
2009-11-23T20:12:43Z
1,793,746
<p>The following line won't work in Django 0.96, which is the default version on GAE:</p> <pre><code>img = self.request.FILES['file'].read() </code></pre> <p>I was the one who posted a similar question before (I think this is the thread you're referring to: <a href="http://stackoverflow.com/questions/1616890/storing-...
0
2009-11-24T23:41:14Z
[ "python", "django", "google-app-engine", "gae-datastore" ]
GAE Image Posting to Datastore through Django Form
1,785,637
<p>I'm working on a little side project that involves posting an avatar to a users profile page, seems straight forward enough. I'm following the instructions from the "<a href="http://code.google.com/appengine/docs/python/images/usingimages.html" rel="nofollow">Using the Images Python API</a>" on the GAE web site. </p...
0
2009-11-23T20:12:43Z
1,818,690
<p>Here's my code:</p> <pre><code> if 'image' in request.FILES: imageFile = request.FILES['image'] #in forms.py: image = forms.FileField(required=False) fileSize = imageFile.size fileType = imageFile.content_type filename = imageFile.name cPhoto ...
0
2009-11-30T09:14:17Z
[ "python", "django", "google-app-engine", "gae-datastore" ]
Nested Lambdas in Python
1,785,826
<p>I'm a beginning python programmer, and I'd like someone to clarify the following behavior.</p> <p>I have the following code:</p> <pre><code>env = lambda id: -1 def add(id, val, myenv): return lambda x: val if x == id else myenv(id) test_env = add("a", 1, env) test_env_2 = add("b", 2, test_env) </code></pre> ...
3
2009-11-23T20:46:30Z
1,785,920
<p>I think you just confused <code>myenv(id)</code> with <code>myenv(x)</code>. Change it and you'll get the desired output.</p>
5
2009-11-23T20:59:23Z
[ "python", "functional-programming", "lambda", "nested", "closures" ]
Efficient way of calling set of functions in Python
1,785,867
<p>I have a set of functions:</p> <pre><code>functions=set(...) </code></pre> <p>All the functions need one parameter x.</p> <p>What is the most efficient way in python of doing something similar to:</p> <pre><code>for function in functions: function(x) </code></pre>
0
2009-11-23T20:52:01Z
1,785,882
<p>If you need the output, a list comprehension would work.</p> <pre><code>[func(x) for func in functions] </code></pre>
1
2009-11-23T20:53:48Z
[ "python", "iteration" ]
Efficient way of calling set of functions in Python
1,785,867
<p>I have a set of functions:</p> <pre><code>functions=set(...) </code></pre> <p>All the functions need one parameter x.</p> <p>What is the most efficient way in python of doing something similar to:</p> <pre><code>for function in functions: function(x) </code></pre>
0
2009-11-23T20:52:01Z
1,785,901
<p>I'm somewhat doubtful of how much of an impact this will have on the total running time of your program, but I guess you could do something like this:</p> <pre><code>[func(x) for func in functions] </code></pre> <p>The downside is that you will create a new list that you immediatly toss away, but it should be slig...
0
2009-11-23T20:56:49Z
[ "python", "iteration" ]
Efficient way of calling set of functions in Python
1,785,867
<p>I have a set of functions:</p> <pre><code>functions=set(...) </code></pre> <p>All the functions need one parameter x.</p> <p>What is the most efficient way in python of doing something similar to:</p> <pre><code>for function in functions: function(x) </code></pre>
0
2009-11-23T20:52:01Z
1,785,905
<p>The code you give,</p> <pre><code>for function in functions: function(x) </code></pre> <p>...does not appear to do anything with the result of calling <code>function(x)</code>. If that is indeed so, meaning that these functions are called for their side-effects, then there is no more pythonic alternative. <em>...
7
2009-11-23T20:57:14Z
[ "python", "iteration" ]
Efficient way of calling set of functions in Python
1,785,867
<p>I have a set of functions:</p> <pre><code>functions=set(...) </code></pre> <p>All the functions need one parameter x.</p> <p>What is the most efficient way in python of doing something similar to:</p> <pre><code>for function in functions: function(x) </code></pre>
0
2009-11-23T20:52:01Z
1,786,082
<p>Edit: I redid the test using timeit</p> <p>My new test code:</p> <pre><code>import timeit def func(i): return i; a = b = c = d = e = f = func functions = [a, b, c, d, e, f] timer = timeit.Timer("[f(2) for f in functions]", "from __main__ import functions") print (timer.repeat()) timer = timeit.Timer("map(...
0
2009-11-23T21:23:39Z
[ "python", "iteration" ]
How to install EasyGUI on Mac OS X 10.6 (Snow Leopard)?
1,785,987
<p>I would like to install <a href="http://easygui.sourceforge.net/" rel="nofollow">EasyGUI</a> on Mac OS X 10.6, but am running into trouble. Has anyone successfully done this? If so, what explicit set of steps did you follow?</p> <p>Thank you.</p>
1
2009-11-23T21:09:26Z
1,786,226
<p>It's hard to know what <strong><em>running into trouble</em></strong> means but, nonetheless, something like this <em>seems</em> to work on 10.6:</p> <pre><code>mkdir test_easygui cd test_easygui curl http://easygui.sourceforge.net/current_version/easygui_v0.93.tar.gz | tar xz /usr/bin/python2.6 easygui.py </code><...
2
2009-11-23T21:44:59Z
[ "python", "osx", "easygui" ]
Creation of PyTuple in C++ module crashes
1,786,070
<p>Having some trouble with this code. Trying to return a tuple of tuples (coordinates) from a C++ module Im writing. It looks right to me, the <code>dirty</code> list contains two <code>Coord</code>s so <code>len</code> is 2, the <code>x</code> and <code>y</code> values of the items in the list are <code>0,0</code> an...
0
2009-11-23T21:22:47Z
1,786,136
<p>The arguments to <code>PyTuple_Pack</code>, after the first one, must be <code>PyObject</code> pointers.</p> <p>You might want instead</p> <pre><code>Py_BuildValue("(ii)", (*i).x, (*i).y) </code></pre> <p>...assuming the coordinates are actually of type <code>int</code>.</p>
1
2009-11-23T21:32:08Z
[ "python", "python-c-api" ]
Knowing if any key is pressed, wxPython
1,786,194
<p>I have a timer, and need to know if any of the keys is pressed on any cycle. How do I do it?</p>
0
2009-11-23T21:41:12Z
1,786,212
<p>Try:</p> <pre><code>import sys c = sys.stdin.read(1) </code></pre>
0
2009-11-23T21:43:12Z
[ "python", "wxpython" ]
Knowing if any key is pressed, wxPython
1,786,194
<p>I have a timer, and need to know if any of the keys is pressed on any cycle. How do I do it?</p>
0
2009-11-23T21:41:12Z
1,786,223
<p>If you are using Linux it's found in the <code>curses</code> module, if you use Windows it's in the <code>msvcrt</code> module. I found following article really helpful in describing this topic - <a href="http://www.freenetpages.co.uk/hp/alan.gauld/tutevent.htm" rel="nofollow">Event Driven Programming</a></p>
1
2009-11-23T21:44:14Z
[ "python", "wxpython" ]
Knowing if any key is pressed, wxPython
1,786,194
<p>I have a timer, and need to know if any of the keys is pressed on any cycle. How do I do it?</p>
0
2009-11-23T21:41:12Z
1,794,260
<p>If you are using Windows, Use <a href="http://sourceforge.net/apps/mediawiki/pyhook/index.php?title=Main%5FPage" rel="nofollow">PyHook</a> If you like to know system wide key press events.</p> <pre><code>import pythoncom, pyHook def OnKeyboardEvent(event): print 'Ascii:', event.Ascii, chr(event.Ascii) pri...
0
2009-11-25T02:17:46Z
[ "python", "wxpython" ]
is there a Java equivalent of Python's defaultdict?
1,786,206
<p>In Python, the defaultdict class provides a convenient way to create a mapping from key -> [list of values], in the following example,</p> <pre><code>from collections import defaultdict d = defaultdict(list) d[1].append(2) d[1].append(3) # d is now {1: [2, 3]} </code></pre> <p>Is there an equivalent to this in Jav...
25
2009-11-23T21:42:18Z
1,786,228
<p>You can use <a href="https://commons.apache.org/proper/commons-collections/apidocs/org/apache/commons/collections4/MultiMap.html" rel="nofollow"><code>MultiMap</code></a> from <a href="https://commons.apache.org/" rel="nofollow">Apache Commons</a>.</p>
5
2009-11-23T21:45:15Z
[ "java", "python", "hashmap" ]
is there a Java equivalent of Python's defaultdict?
1,786,206
<p>In Python, the defaultdict class provides a convenient way to create a mapping from key -> [list of values], in the following example,</p> <pre><code>from collections import defaultdict d = defaultdict(list) d[1].append(2) d[1].append(3) # d is now {1: [2, 3]} </code></pre> <p>Is there an equivalent to this in Jav...
25
2009-11-23T21:42:18Z
1,786,345
<p>in addition to apache collections, check also <a href="http://google-collections.googlecode.com/svn/trunk/javadoc/com/google/common/collect/Multimap.html">google collections</a>:</p> <blockquote> <p>A collection similar to a Map, but which may associate multiple values with a single key. If you call put(K, V) twi...
7
2009-11-23T22:00:23Z
[ "java", "python", "hashmap" ]
is there a Java equivalent of Python's defaultdict?
1,786,206
<p>In Python, the defaultdict class provides a convenient way to create a mapping from key -> [list of values], in the following example,</p> <pre><code>from collections import defaultdict d = defaultdict(list) d[1].append(2) d[1].append(3) # d is now {1: [2, 3]} </code></pre> <p>Is there an equivalent to this in Jav...
25
2009-11-23T21:42:18Z
1,786,358
<p>Using just the Java runtime library you could use a <code>HashMap</code> and add an <code>ArrayList</code> to hold your values when the key does not exist yet or add the value to the list when the key does exist.</p>
1
2009-11-23T22:03:06Z
[ "java", "python", "hashmap" ]
is there a Java equivalent of Python's defaultdict?
1,786,206
<p>In Python, the defaultdict class provides a convenient way to create a mapping from key -> [list of values], in the following example,</p> <pre><code>from collections import defaultdict d = defaultdict(list) d[1].append(2) d[1].append(3) # d is now {1: [2, 3]} </code></pre> <p>Is there an equivalent to this in Jav...
25
2009-11-23T21:42:18Z
1,812,263
<p>There is nothing that gives the behaviour of default dict out of the box. However creating your own default dict in Java would not be that difficult.</p> <pre><code>import java.util.ArrayList; import java.util.HashMap; import java.util.List; public class DefaultDict&lt;K, V&gt; extends HashMap&lt;K, V&gt; { C...
15
2009-11-28T11:08:10Z
[ "java", "python", "hashmap" ]
is there a Java equivalent of Python's defaultdict?
1,786,206
<p>In Python, the defaultdict class provides a convenient way to create a mapping from key -> [list of values], in the following example,</p> <pre><code>from collections import defaultdict d = defaultdict(list) d[1].append(2) d[1].append(3) # d is now {1: [2, 3]} </code></pre> <p>Is there an equivalent to this in Jav...
25
2009-11-23T21:42:18Z
20,661,841
<p>The solution from @tendayi-mawushe did not work for me with Primitive types (e.g. <code>InstantiationException Integer</code>), here is one implementation that works with Integer, Double, Float. I often use Maps with these and added static constructors for conveninence </p> <pre><code>import java.util.HashMap; impo...
1
2013-12-18T15:17:39Z
[ "java", "python", "hashmap" ]
is there a Java equivalent of Python's defaultdict?
1,786,206
<p>In Python, the defaultdict class provides a convenient way to create a mapping from key -> [list of values], in the following example,</p> <pre><code>from collections import defaultdict d = defaultdict(list) d[1].append(2) d[1].append(3) # d is now {1: [2, 3]} </code></pre> <p>Is there an equivalent to this in Jav...
25
2009-11-23T21:42:18Z
30,968,796
<p>In most common cases where you want a <code>defaultdict</code>, you'll be even happier with a properly designed Multimap or Multiset, which is what you're really looking for. A Multimap is a key -> collection mapping (default is an empty collection) and a Multiset is a key -> int mapping (default is zero).</p> <p>...
1
2015-06-21T20:04:28Z
[ "java", "python", "hashmap" ]
is there a Java equivalent of Python's defaultdict?
1,786,206
<p>In Python, the defaultdict class provides a convenient way to create a mapping from key -> [list of values], in the following example,</p> <pre><code>from collections import defaultdict d = defaultdict(list) d[1].append(2) d[1].append(3) # d is now {1: [2, 3]} </code></pre> <p>Is there an equivalent to this in Jav...
25
2009-11-23T21:42:18Z
39,190,927
<p>I wrote the library <a href="https://github.com/guavaberry/guavaberry" rel="nofollow">Guavaberry</a> containing such data structure: <a href="https://github.com/guavaberry/guavaberry/wiki/Collections" rel="nofollow">DefaultHashMap</a>.</p> <p>It is highly tested and documented. You can find it and integrate it pre...
0
2016-08-28T11:46:54Z
[ "java", "python", "hashmap" ]
Parsing XML in Python using ElementTree example
1,786,476
<p>I'm having a hard time finding a good, basic example of how to parse XML in python using Element Tree. From what I can find, this appears to be the easiest library to use for parsing XML. Here is a sample of the XML I'm working with:</p> <pre><code>&lt;timeSeriesResponse&gt; &lt;queryInfo&gt; &lt;locati...
48
2009-11-23T22:24:01Z
1,786,583
<p>So I have ElementTree 1.2.6 on my box now, and ran the following code against the XML chunk you posted: </p> <pre><code>import elementtree.ElementTree as ET tree = ET.parse("test.xml") doc = tree.getroot() thingy = doc.find('timeSeries') print thingy.attrib </code></pre> <p>and got the following back:</p> <pre>...
34
2009-11-23T22:42:34Z
[ "python", "xml", "elementtree" ]
Parsing XML in Python using ElementTree example
1,786,476
<p>I'm having a hard time finding a good, basic example of how to parse XML in python using Element Tree. From what I can find, this appears to be the easiest library to use for parsing XML. Here is a sample of the XML I'm working with:</p> <pre><code>&lt;timeSeriesResponse&gt; &lt;queryInfo&gt; &lt;locati...
48
2009-11-23T22:24:01Z
1,786,786
<p>If I understand your question correctly:</p> <pre><code>for elem in doc.findall('timeSeries/values/value'): print elem.get('dateTime'), elem.text </code></pre> <p>or if you prefer (and if there is only one occurrence of <code>timeSeries/values</code>:</p> <pre><code>values = doc.find('timeSeries/values') for ...
14
2009-11-23T23:27:32Z
[ "python", "xml", "elementtree" ]
Python - Simple algorithmic task on lists (standard question for a job-interview)
1,786,504
<p>There are 2 input lists L and M, for example:</p> <pre><code>L = ['a', 'ab', 'bba'] M = ['baa', 'aa', 'bb'] </code></pre> <p>How to obtain 2 non-empty output lists U and V such that: <code>''.join(U) == ''.join(V)) is True</code>, and every element of U is in L, and every element of V is in M?</p> <p>For e...
3
2009-11-23T22:28:31Z
1,786,534
<p>What are you looking for -- all (the countable infinity of) possible solutions? The "shortest" (by some measure) <strong>non-empty</strong> solution, or the set of equal-shortest ones, or...?</p> <p>Because, if <strong>any</strong> solution will do, setting U and V both to [] meets all the stated conditions, and i...
9
2009-11-23T22:33:44Z
[ "python", "algorithm" ]
Python - Simple algorithmic task on lists (standard question for a job-interview)
1,786,504
<p>There are 2 input lists L and M, for example:</p> <pre><code>L = ['a', 'ab', 'bba'] M = ['baa', 'aa', 'bb'] </code></pre> <p>How to obtain 2 non-empty output lists U and V such that: <code>''.join(U) == ''.join(V)) is True</code>, and every element of U is in L, and every element of V is in M?</p> <p>For e...
3
2009-11-23T22:28:31Z
1,787,196
<p>This is my try! I think it finds all the solutions.</p> <pre><code>from itertools import product m = 5 # top limit of elements in output lists sumsets = lambda s1, s2: s1 | s2 for u in reduce(sumsets, [set(product(L, repeat=i)) for i in range(1, m+1)]): for v in reduce(sumsets, [set(product(M, repeat=i)) f...
4
2009-11-24T01:13:07Z
[ "python", "algorithm" ]
Python - Simple algorithmic task on lists (standard question for a job-interview)
1,786,504
<p>There are 2 input lists L and M, for example:</p> <pre><code>L = ['a', 'ab', 'bba'] M = ['baa', 'aa', 'bb'] </code></pre> <p>How to obtain 2 non-empty output lists U and V such that: <code>''.join(U) == ''.join(V)) is True</code>, and every element of U is in L, and every element of V is in M?</p> <p>For e...
3
2009-11-23T22:28:31Z
1,787,475
<p>This is known as the <a href="http://en.wikipedia.org/wiki/Post%5Fcorrespondence%5Fproblem" rel="nofollow">Post Correspondence Problem</a> and it's undecidable as others have said.</p>
1
2009-11-24T02:47:13Z
[ "python", "algorithm" ]
How different are the semantics between Python and JavaScript?
1,786,522
<p>Both these languages seem extremely similar to me. Although Python supports actual classes instead of being prototype-based, in Python classes are not all that different from functions that generate objects containing values and functions, just as you'd do in JavaScript. On the other hand, JavaScript only supports...
12
2009-11-23T22:30:41Z
1,786,550
<p>In Python, whitespace is part of the language. In Javascript, braces define code blocks and spaces are ignored. Furthermore, Python has bindings for the Java API, .net, and other cool fancy libraries. Javascript is pretty limited in the library department when compared to Python, but it has some neat windowing libra...
1
2009-11-23T22:36:27Z
[ "javascript", "python", "semantics" ]
How different are the semantics between Python and JavaScript?
1,786,522
<p>Both these languages seem extremely similar to me. Although Python supports actual classes instead of being prototype-based, in Python classes are not all that different from functions that generate objects containing values and functions, just as you'd do in JavaScript. On the other hand, JavaScript only supports...
12
2009-11-23T22:30:41Z
1,786,573
<p>Being a JavaScript developer and done some Python stuff (thanks to Google App Engine) I would say that the two major differences between JavaScript and Python would be</p> <ul> <li><p>Formatting. JavaScript doesn't care about the looks of your code (think of all the code minimizers and what the resulting looks like...
2
2009-11-23T22:40:32Z
[ "javascript", "python", "semantics" ]
How different are the semantics between Python and JavaScript?
1,786,522
<p>Both these languages seem extremely similar to me. Although Python supports actual classes instead of being prototype-based, in Python classes are not all that different from functions that generate objects containing values and functions, just as you'd do in JavaScript. On the other hand, JavaScript only supports...
12
2009-11-23T22:30:41Z
1,786,584
<ol> <li>Classical inheritance in Python, Prototypal inheritance in ECMAScript</li> <li>ECMAScript is a braces and semicolons language while Python is white-space and indent/block based</li> <li>No <code>var</code> keyword in Python, implicit globals in ECMAScript, both are lexically scoped</li> <li>Closures in Python ...
19
2009-11-23T22:42:43Z
[ "javascript", "python", "semantics" ]
How different are the semantics between Python and JavaScript?
1,786,522
<p>Both these languages seem extremely similar to me. Although Python supports actual classes instead of being prototype-based, in Python classes are not all that different from functions that generate objects containing values and functions, just as you'd do in JavaScript. On the other hand, JavaScript only supports...
12
2009-11-23T22:30:41Z
1,786,635
<p><strong>Typing</strong>: Javascript and Python are both <em>dynamically</em> typed, whereas javascript is <em>weakly</em>, python <em>strongly</em> typed.</p>
3
2009-11-23T22:53:06Z
[ "javascript", "python", "semantics" ]
How different are the semantics between Python and JavaScript?
1,786,522
<p>Both these languages seem extremely similar to me. Although Python supports actual classes instead of being prototype-based, in Python classes are not all that different from functions that generate objects containing values and functions, just as you'd do in JavaScript. On the other hand, JavaScript only supports...
12
2009-11-23T22:30:41Z
1,786,753
<p>In python, "self" is explicitly passed to a member function, and is not a special keyword or anything. In javascript, "this" is dynamically scoped. you can fiddle with the scope of a member function by calling apply() on it.</p>
4
2009-11-23T23:19:03Z
[ "javascript", "python", "semantics" ]
How different are the semantics between Python and JavaScript?
1,786,522
<p>Both these languages seem extremely similar to me. Although Python supports actual classes instead of being prototype-based, in Python classes are not all that different from functions that generate objects containing values and functions, just as you'd do in JavaScript. On the other hand, JavaScript only supports...
12
2009-11-23T22:30:41Z
1,787,630
<p>I'll add a few I haven't seen mentioned yet:</p> <ul> <li>JavaScript supports object-literal notation. Python doesn't exactly work the same way, but Python dictionaries are similar to JavaScript associative arrays. </li> <li><p>JavaScript objects/arrays support that cool feature where you don't need to quote (sin...
2
2009-11-24T03:42:05Z
[ "javascript", "python", "semantics" ]
Django cache_page checking
1,786,543
<p>How can I confirm my Django views are being cached when I use the cache_page decorator like so:</p> <pre><code>@cache_page(60) def my_view(request): </code></pre> <p>Ideally I would like to output cache hit/miss messages in the console so I can confirm my view is being cached for 60 seconds etc.</p> <p>Many thank...
5
2009-11-23T22:35:38Z
1,786,936
<p>Depending on the cache middleware you are using, you could inspect the <code>process_request</code> method of that class and find some line like these (taken from <code>django/middleware/cache.py</code>)</p> <pre><code>131 response = cache.get(cache_key, None) 132 if response is None: 133 ... ... loggi...
1
2009-11-23T23:59:53Z
[ "python", "django", "caching" ]
Django cache_page checking
1,786,543
<p>How can I confirm my Django views are being cached when I use the cache_page decorator like so:</p> <pre><code>@cache_page(60) def my_view(request): </code></pre> <p>Ideally I would like to output cache hit/miss messages in the console so I can confirm my view is being cached for 60 seconds etc.</p> <p>Many thank...
5
2009-11-23T22:35:38Z
1,791,399
<p>you <em>could</em> grab a copy of <code>django-debug-toolbar</code> (<a href="http://github.com/robhudson/django-debug-toolbar">http://github.com/robhudson/django-debug-toolbar</a>) and watch the queries: if the page is not being pulled from the cache, <code>django-debug-toolbar</code> should display all of the quer...
5
2009-11-24T16:56:13Z
[ "python", "django", "caching" ]
Where does Python's pydoc help function get its content?
1,787,056
<p>I have a lot of callable objects and they all have the <code>__doc__</code> string correctly filled out, but running help on them produces the help for their class instead of help based on <code>__doc__</code>.</p> <p>I want to change it so that running help on them produces customized help that looks essentially l...
9
2009-11-24T00:28:15Z
1,787,418
<p>I'm not very clear about what your question is exactly. My understanding is that you have a class and a function defined in it and you want to know where Python gets the help text for that function from.</p> <p>Python gets the help text from the doc strings provided in that class/method.</p> <p>If you have a class...
2
2009-11-24T02:30:58Z
[ "python", "introspection", "pydoc" ]
Where does Python's pydoc help function get its content?
1,787,056
<p>I have a lot of callable objects and they all have the <code>__doc__</code> string correctly filled out, but running help on them produces the help for their class instead of help based on <code>__doc__</code>.</p> <p>I want to change it so that running help on them produces customized help that looks essentially l...
9
2009-11-24T00:28:15Z
1,789,495
<p>The <code>help</code> function (implemented in the <code>pydoc</code> module) isn't prepared to find per-instance docstrings. I took a quick look through the module to see if there was a way to provide explicit help, but there doesn't seem to be. It uses the <code>inspect</code> module to determine what kind of th...
4
2009-11-24T11:30:41Z
[ "python", "introspection", "pydoc" ]
what is the true difference between lemmatization vs stemming?
1,787,110
<p>When do I use each ?</p> <p>Also...is the NLTK lemmatization dependent upon Parts of Speech? Wouldn't it be more accurate if it was?</p>
30
2009-11-24T00:48:11Z
1,787,121
<p>Short and dense: <a href="http://nlp.stanford.edu/IR-book/html/htmledition/stemming-and-lemmatization-1.html">http://nlp.stanford.edu/IR-book/html/htmledition/stemming-and-lemmatization-1.html</a></p> <blockquote> <p>The goal of both stemming and lemmatization is to reduce inflectional forms and sometimes derivat...
44
2009-11-24T00:52:12Z
[ "python", "nlp", "nltk", "lemmatization" ]
what is the true difference between lemmatization vs stemming?
1,787,110
<p>When do I use each ?</p> <p>Also...is the NLTK lemmatization dependent upon Parts of Speech? Wouldn't it be more accurate if it was?</p>
30
2009-11-24T00:48:11Z
1,787,129
<p>ianacl<br> but i think Stemming is a rough hack people use to get all the different forms of the same word down to a base form which need not be a legit word on its own<br> Something like the Porter Stemmer can uses simple regexes to eliminate common word suffixes</p> <p>Lemmatization brings a word down to its actu...
1
2009-11-24T00:54:18Z
[ "python", "nlp", "nltk", "lemmatization" ]
what is the true difference between lemmatization vs stemming?
1,787,110
<p>When do I use each ?</p> <p>Also...is the NLTK lemmatization dependent upon Parts of Speech? Wouldn't it be more accurate if it was?</p>
30
2009-11-24T00:48:11Z
1,787,709
<p>As MYYN pointed out, stemming is the process of removing inflectional and sometimes derivational affixes to a base form that all of the original words are probably related to. Lemmatization is concerned with obtaining the single word that allows you to group together a bunch of inflected forms. This is harder than...
8
2009-11-24T04:07:18Z
[ "python", "nlp", "nltk", "lemmatization" ]
what is the true difference between lemmatization vs stemming?
1,787,110
<p>When do I use each ?</p> <p>Also...is the NLTK lemmatization dependent upon Parts of Speech? Wouldn't it be more accurate if it was?</p>
30
2009-11-24T00:48:11Z
5,605,064
<p>The purpose of both stemming and lemmatization is to reduce morphological variation. This is in contrast to the the more general "term conflation" procedures, which may also address lexico-semantic, syntactic, or orthographic variations. </p> <p>The real difference between stemming and lemmatization is threefold:</...
8
2011-04-09T12:37:15Z
[ "python", "nlp", "nltk", "lemmatization" ]
what is the true difference between lemmatization vs stemming?
1,787,110
<p>When do I use each ?</p> <p>Also...is the NLTK lemmatization dependent upon Parts of Speech? Wouldn't it be more accurate if it was?</p>
30
2009-11-24T00:48:11Z
31,247,216
<blockquote> <p><strong>Lemmatisation</strong> is closely related to <strong>stemming</strong>. The difference is that a stemmer operates on a single word without knowledge of the context, and therefore cannot discriminate between words which have different meanings depending on part of speech. However, stemmer...
7
2015-07-06T13:31:35Z
[ "python", "nlp", "nltk", "lemmatization" ]
what is the true difference between lemmatization vs stemming?
1,787,110
<p>When do I use each ?</p> <p>Also...is the NLTK lemmatization dependent upon Parts of Speech? Wouldn't it be more accurate if it was?</p>
30
2009-11-24T00:48:11Z
33,300,859
<p>An example-driven explanation on the differenes between lemmatization and stemming:</p> <p><strong>Lemmatization</strong> handles <strong>matching “car” to “cars” along with matching “car” to “automobile”.</strong> </p> <p><strong>Stemming</strong> handles <strong>matching “car” to “cars”<...
1
2015-10-23T11:07:23Z
[ "python", "nlp", "nltk", "lemmatization" ]
what is the true difference between lemmatization vs stemming?
1,787,110
<p>When do I use each ?</p> <p>Also...is the NLTK lemmatization dependent upon Parts of Speech? Wouldn't it be more accurate if it was?</p>
30
2009-11-24T00:48:11Z
33,704,691
<p>There are two aspects to show their differences:</p> <ol> <li><p>A <strong>stemmer</strong> will return the stem of a word, which needn't be identical to the morphological root of the word. It usually sufficient that related words map to the same stem,even if the stem is not in itself a valid root, while in <strong...
2
2015-11-14T03:05:05Z
[ "python", "nlp", "nltk", "lemmatization" ]
How to call ssh by subprocess module so that it uses SSH_ASKPASS variable
1,787,288
<p>I am writing a GUI which uses SSH commands. I tried to use the subprocess module to call ssh and set the SSH_ASKPASS environment variable so that my application can pop up a window asking for the SSH password. However I cannot make ssh read the password using the given SSH_ASKPASS command: it always prompts it in th...
8
2009-11-24T01:45:36Z
1,788,266
<p>Your problem is that SSH detects your TTY and talks to it directly (as is clearly stated in the man-page). You can try and run ssh without a terminal - the man page suggests it might be necessary to redirect <code>stdin</code> to <code>/dev/null</code> for ssh to think it has no terminal.</p> <p>You can also use <a...
4
2009-11-24T06:39:26Z
[ "python", "ssh", "subprocess" ]
How to call ssh by subprocess module so that it uses SSH_ASKPASS variable
1,787,288
<p>I am writing a GUI which uses SSH commands. I tried to use the subprocess module to call ssh and set the SSH_ASKPASS environment variable so that my application can pop up a window asking for the SSH password. However I cannot make ssh read the password using the given SSH_ASKPASS command: it always prompts it in th...
8
2009-11-24T01:45:36Z
1,793,567
<p>SSH uses the SSH_ASKPASS variable only if the process is really detached from TTY (stdin redirecting and setting environment variables is not enough). To detach a process from console it should fork and call os.setsid(). So the first solution I found was:</p> <pre><code># Detach process pid = os.fork() if pid == 0:...
15
2009-11-24T23:05:30Z
[ "python", "ssh", "subprocess" ]
How to call ssh by subprocess module so that it uses SSH_ASKPASS variable
1,787,288
<p>I am writing a GUI which uses SSH commands. I tried to use the subprocess module to call ssh and set the SSH_ASKPASS environment variable so that my application can pop up a window asking for the SSH password. However I cannot make ssh read the password using the given SSH_ASKPASS command: it always prompts it in th...
8
2009-11-24T01:45:36Z
12,820,215
<p>If you want a quick and dirty way of doing it for your own personal usage, you could enable passwordless login between these two machines by doing this in your terminal:</p> <pre><code>ssh-keygen -t rsa # generate a keypair (if you haven't done this already) ssh-copy-id user@other_machine # copy your public key to ...
1
2012-10-10T13:13:25Z
[ "python", "ssh", "subprocess" ]
How do I limit the number of active threads in python?
1,787,397
<p>Am new to python and making some headway with <code>threading</code> - am doing some music file conversion and want to be able to utilize the multiple cores on my machine (one active conversion thread per core). </p> <pre><code>class EncodeThread(threading.Thread): # this is hacked together a bit, but should g...
7
2009-11-24T02:24:12Z
1,787,444
<p>If you're using the default "cpython" version then this won't help you, because only one thread can execute at a time; look up <a href="http://google.com/search?q=global+interpreter+lock" rel="nofollow">Global Interpreter Lock</a>. Instead, I'd suggest looking at the <code>multiprocessing</code> <a href="http://doc...
1
2009-11-24T02:38:16Z
[ "python", "multithreading" ]
How do I limit the number of active threads in python?
1,787,397
<p>Am new to python and making some headway with <code>threading</code> - am doing some music file conversion and want to be able to utilize the multiple cores on my machine (one active conversion thread per core). </p> <pre><code>class EncodeThread(threading.Thread): # this is hacked together a bit, but should g...
7
2009-11-24T02:24:12Z
1,787,445
<p>I am not an expert in this, but I have read something about "Lock"s. <a href="http://effbot.org/zone/thread-synchronization.htm" rel="nofollow">This article</a> might help you out</p> <p>Hope this helps</p>
0
2009-11-24T02:38:31Z
[ "python", "multithreading" ]
How do I limit the number of active threads in python?
1,787,397
<p>Am new to python and making some headway with <code>threading</code> - am doing some music file conversion and want to be able to utilize the multiple cores on my machine (one active conversion thread per core). </p> <pre><code>class EncodeThread(threading.Thread): # this is hacked together a bit, but should g...
7
2009-11-24T02:24:12Z
1,787,448
<p>It looks to me that what you want is a pool of some sort, and in that pool you would like the have n threads where n == the number of processors on your system. You would then have another thread whose only job was to feed jobs into a queue which the worker threads could pick up and process as they became free (so ...
1
2009-11-24T02:39:17Z
[ "python", "multithreading" ]
How do I limit the number of active threads in python?
1,787,397
<p>Am new to python and making some headway with <code>threading</code> - am doing some music file conversion and want to be able to utilize the multiple cores on my machine (one active conversion thread per core). </p> <pre><code>class EncodeThread(threading.Thread): # this is hacked together a bit, but should g...
7
2009-11-24T02:24:12Z
1,787,526
<p>"Each of my threads is using <code>subprocess.Popen</code> to run a separate command line [process]".</p> <p>Why have a bunch of threads manage a bunch of processes? That's exactly what an OS does that for you. Why micro-manage what the OS already manages?</p> <p>Rather than fool around with threads overseeing...
4
2009-11-24T03:06:20Z
[ "python", "multithreading" ]
How do I limit the number of active threads in python?
1,787,397
<p>Am new to python and making some headway with <code>threading</code> - am doing some music file conversion and want to be able to utilize the multiple cores on my machine (one active conversion thread per core). </p> <pre><code>class EncodeThread(threading.Thread): # this is hacked together a bit, but should g...
7
2009-11-24T02:24:12Z
1,789,127
<p>Short answer: don't use threads.</p> <p>For a working example, you can look at something I've recently tossed together at work. It's a little wrapper around <code>ssh</code> which runs a configurable number of <code>Popen()</code> subprocesses. I've posted it at: <a href="http://bitbucket.org/jimd/classh/" rel="n...
1
2009-11-24T10:14:07Z
[ "python", "multithreading" ]
How do I limit the number of active threads in python?
1,787,397
<p>Am new to python and making some headway with <code>threading</code> - am doing some music file conversion and want to be able to utilize the multiple cores on my machine (one active conversion thread per core). </p> <pre><code>class EncodeThread(threading.Thread): # this is hacked together a bit, but should g...
7
2009-11-24T02:24:12Z
5,991,741
<p>If you want to limit the number of parallel threads, use a <a href="http://docs.python.org/library/threading.html#semaphore-objects">semaphore</a>:</p> <pre><code>threadLimiter = threading.BoundedSemaphore(maximumNumberOfThreads) class EncodeThread(threading.Thread): def run(self): threadLimiter.acqui...
26
2011-05-13T12:22:13Z
[ "python", "multithreading" ]
How to print out encoded Asian characters(gb2312) on command prompt?
1,787,497
<p>I am working for a company that uses the Python programming language version 3.1 as a causal work now. And I've encountered this problem: how to print out some encoded Asian characters(Chinese, Japanese, Korean) on command prompt?</p> <p>Done a bit research and tried, but got no luck:</p> <pre><code>import sys imp...
1
2009-11-24T02:57:25Z
1,787,784
<p>If you open the cmd window yourself, type the following command before running test.py: mode con cp select=936</p> <p>If your Python program starts by some other means, you'll have to make it open its console window with the correct code page.</p>
0
2009-11-24T04:27:57Z
[ "python", "windows", "python-3.x", "command-prompt" ]
How to print out encoded Asian characters(gb2312) on command prompt?
1,787,497
<p>I am working for a company that uses the Python programming language version 3.1 as a causal work now. And I've encountered this problem: how to print out some encoded Asian characters(Chinese, Japanese, Korean) on command prompt?</p> <p>Done a bit research and tried, but got no luck:</p> <pre><code>import sys imp...
1
2009-11-24T02:57:25Z
1,787,827
<blockquote> <p>I cannot change the default encoding from UTF-8 to anything else</p> </blockquote> <p>I don't think UTF-8 is being used as the default encoding for your console:</p> <blockquote> <p>File "C:\tools\Python31\lib\encodings\cp437.py"</p> </blockquote> <p>cp437 is the old DOS terminal code page, which...
1
2009-11-24T04:40:50Z
[ "python", "windows", "python-3.x", "command-prompt" ]
How to print out encoded Asian characters(gb2312) on command prompt?
1,787,497
<p>I am working for a company that uses the Python programming language version 3.1 as a causal work now. And I've encountered this problem: how to print out some encoded Asian characters(Chinese, Japanese, Korean) on command prompt?</p> <p>Done a bit research and tried, but got no luck:</p> <pre><code>import sys imp...
1
2009-11-24T02:57:25Z
15,632,882
<p>I have solved this problem. When I am programming a dict, I encounter this problem.</p> <pre><code>#coding=utf-8 import codecs import sys # import imp # imp.reload(sys) # sys.setdefaultencoding('utf8') dictFileName = 'abstract.dict' print(sys.getdefaultencoding()) print(sys.stdout.encoding) def readDict(): ...
2
2013-03-26T08:56:43Z
[ "python", "windows", "python-3.x", "command-prompt" ]
Python nested lists and recursion problem
1,787,576
<p>I'm trying to process a first order logic formula represented as nested lists and strings in python so that that its in disjunctive normal form, </p> <p>i.e ['&amp;', ['|', 'a', 'b'], ['|', 'c', 'd']] </p> <p>turns into </p> <p>['|' ['&amp;', ['&amp;', 'a', 'c'], ['&amp;', 'b', 'c']], ['&amp;', ['&amp;', 'a', 'd'...
1
2009-11-24T03:24:00Z
1,788,590
<p>I didn't really try to understand your solution, sorry. I think it is way too difficult to read and probably the approach is too cumbersome.</p> <p>If you have a DNF, all you need to do is find all combinations of atoms, taking one out of each sublist. This pretty much boils down to <a href="http://stackoverflow.co...
0
2009-11-24T08:12:18Z
[ "python", "logic" ]
Python nested lists and recursion problem
1,787,576
<p>I'm trying to process a first order logic formula represented as nested lists and strings in python so that that its in disjunctive normal form, </p> <p>i.e ['&amp;', ['|', 'a', 'b'], ['|', 'c', 'd']] </p> <p>turns into </p> <p>['|' ['&amp;', ['&amp;', 'a', 'c'], ['&amp;', 'b', 'c']], ['&amp;', ['&amp;', 'a', 'd'...
1
2009-11-24T03:24:00Z
1,802,564
<p>Okay, here is an actual solution that seems to work.</p> <p>I do not understand your code, and I hadn't heard of DNF, so I started out by studying the problem some more.</p> <p>The <a href="http://en.wikipedia.org/wiki/Disjunctive_normal_form" rel="nofollow">Wikipedia page on DNF</a> was very helpful. It included...
1
2009-11-26T09:26:05Z
[ "python", "logic" ]
Python and .NET integration
1,787,755
<p>I'm currently looking at python because I really like the text parsing capabilities and the nltk library, but traditionally I am a .Net/C# programmer. I don't think IronPython is an integration point for me because I am using NLTK and presumably would need a port of that library to the CLR. I've looked a little at...
7
2009-11-24T04:21:28Z
1,787,793
<p>Just an Idea</p> <p>How about running Python behind as a server, and connect it from .NET with socket?</p> <p>Since NLTK loading take time and better load it in advance anyway.</p>
0
2009-11-24T04:32:18Z
[ "python", ".net", "nlp", "nltk", "python.net" ]
Python and .NET integration
1,787,755
<p>I'm currently looking at python because I really like the text parsing capabilities and the nltk library, but traditionally I am a .Net/C# programmer. I don't think IronPython is an integration point for me because I am using NLTK and presumably would need a port of that library to the CLR. I've looked a little at...
7
2009-11-24T04:21:28Z
1,787,804
<p>I don't know why you have a problem with IronPython. you can still use any and all nltk calls there.</p> <p>To answer your question about porting a Python class into C#: try <a href="http://www.py2exe.org" rel="nofollow">compiling your python code into an EXE</a>. This creates a DLL with all your python classes in ...
5
2009-11-24T04:34:09Z
[ "python", ".net", "nlp", "nltk", "python.net" ]
Python and .NET integration
1,787,755
<p>I'm currently looking at python because I really like the text parsing capabilities and the nltk library, but traditionally I am a .Net/C# programmer. I don't think IronPython is an integration point for me because I am using NLTK and presumably would need a port of that library to the CLR. I've looked a little at...
7
2009-11-24T04:21:28Z
1,788,172
<p>NLTK is pure-python and thus can be made to run on IronPython easily. A search turned up <a href="http://ironpython.codeplex.com/WorkItem/View.aspx?WorkItemId=24357">this ticket</a> - all one has to do is install a couple of extra Python libraries that don't come by default with IronPython.</p> <p>This is probably ...
7
2009-11-24T06:18:44Z
[ "python", ".net", "nlp", "nltk", "python.net" ]
Catching update errors on MySQLdb
1,788,000
<p>I have a function that updates a MySQL table from a CSV file. The MySQL table contains the client account number -- this is what I use to compare with the CSV file. At some point, some of the queries will fail because the account number being compared from the CSV file has not been added yet.</p> <p>How do I get th...
0
2009-11-24T05:30:51Z
1,788,026
<p>An update query returns the number of rows affected. Checking the <code>Cursor.rowcount</code> after you made am execute will give that number. If it is not 1, that that update row failed.</p>
1
2009-11-24T05:37:14Z
[ "python", "mysql" ]
How to read data from file and display in QEditText box in QT
1,788,062
<p>i would like to read a line of data from text file and display that data in Text Edit box</p>
0
2009-11-24T05:45:14Z
1,788,074
<p>You may interest to look at this tutorial </p> <p><a href="http://doc.trolltech.com/4.5/help-simpletextviewer.html" rel="nofollow">Simple Text Viewer Example</a></p>
0
2009-11-24T05:49:11Z
[ "c++", "python", "linux", "ubuntu", "qt4" ]
How to read data from file and display in QEditText box in QT
1,788,062
<p>i would like to read a line of data from text file and display that data in Text Edit box</p>
0
2009-11-24T05:45:14Z
1,788,212
<p>It's quite simple, actually:</p> <pre><code>import sys from PyQt4.QtCore import * from PyQt4.QtGui import * FILENAME = 'textedit_example.py' class Form(QDialog): def __init__(self, parent=None): super(Form, self).__init__(parent) self.edit = QTextEdit() layout = QVBoxLayout() ...
2
2009-11-24T06:26:24Z
[ "c++", "python", "linux", "ubuntu", "qt4" ]
Using contexts in rdflib
1,788,063
<p>I am having trouble finding a clear, sensible example of usage of context with rdflib. ConjunctiveGraph does not accept contexts, and Graph is deprecated. How am I supposed to create and operate on different contexts within the same global ConjunctiveGraph ?</p>
5
2009-11-24T05:45:43Z
1,788,129
<p>Yes. This is the code</p> <pre><code>import rdflib from rdflib.Graph import Graph conj=rdflib.ConjunctiveGraph() NS=rdflib.Namespace("http://example.com/#") NS_CTX=rdflib.Namespace("http://example.com/context/#") alice=NS.alice bob=NS.bob charlie=NS.charlie pizza=NS.pizza meat=NS.meat chocolate=NS.chocolate lo...
9
2009-11-24T06:06:22Z
[ "python", "rdf", "rdflib" ]
appengine: how to use validator in Class:Property?
1,788,119
<p>described in <a href="http://code.google.com/intl/en/appengine/docs/python/datastore/propertyclass.html#Property" rel="nofollow">http://code.google.com/intl/en/appengine/docs/python/datastore/propertyclass.html#Property</a></p> <p>but there is no example code.</p> <p>i code sth like:</p> <pre><code>class Model(db...
0
2009-11-24T06:03:46Z
1,788,314
<pre><code>class Model(db.Model): def clean_email(value): if ... email = db.EmailProperty(validator=clean_email) </code></pre> <p>use a argument. and the argument itself is the value of email in this case.</p>
2
2009-11-24T06:55:03Z
[ "python", "google-app-engine", "validation" ]
appengine: how to use validator in Class:Property?
1,788,119
<p>described in <a href="http://code.google.com/intl/en/appengine/docs/python/datastore/propertyclass.html#Property" rel="nofollow">http://code.google.com/intl/en/appengine/docs/python/datastore/propertyclass.html#Property</a></p> <p>but there is no example code.</p> <p>i code sth like:</p> <pre><code>class Model(db...
0
2009-11-24T06:03:46Z
1,789,206
<p>You need to either define the method before the property, as joetsuihk demonstrates, or define it as a function, outside the class. I would recommend the latter, as there's no reason for the validator to be associated with the class.</p>
1
2009-11-24T10:30:25Z
[ "python", "google-app-engine", "validation" ]
How to determine if data is valid tar file without a file?
1,788,236
<p>My upload form expects a tar file and I want to check whether the uploaded data is valid. The <a href="http://docs.python.org/library/tarfile.html" rel="nofollow">tarfile</a> module supports <a href="https://docs.python.org/2/library/tarfile.html#tarfile.is_tarfile" rel="nofollow"><code>is_tarfile()</code></a>, but ...
6
2009-11-24T06:31:08Z
1,788,261
<p>The tar file format is <a href="http://en.wikipedia.org/wiki/Tar%5F%28file%5Fformat%29" rel="nofollow">here</a> on Wikipedia.</p> <p>I suspect your best bet would be to check that the header checksum for the first file is valid. You may also want to check the file name for sanity but that may not be reliable, depen...
4
2009-11-24T06:37:45Z
[ "python", "tar", "tarfile" ]
How to determine if data is valid tar file without a file?
1,788,236
<p>My upload form expects a tar file and I want to check whether the uploaded data is valid. The <a href="http://docs.python.org/library/tarfile.html" rel="nofollow">tarfile</a> module supports <a href="https://docs.python.org/2/library/tarfile.html#tarfile.is_tarfile" rel="nofollow"><code>is_tarfile()</code></a>, but ...
6
2009-11-24T06:31:08Z
1,788,318
<p>The class TarFile accepts a fileobj object. I guess you can pass any partial download entity you get from your web framework.</p> <pre><code>__init__(self, name=None, mode='r', fileobj=None) </code></pre> <p>Adding to paxdiablo post: tar is a very difficult and complex file format, despite its apparent simplicity....
3
2009-11-24T06:56:18Z
[ "python", "tar", "tarfile" ]
How to determine if data is valid tar file without a file?
1,788,236
<p>My upload form expects a tar file and I want to check whether the uploaded data is valid. The <a href="http://docs.python.org/library/tarfile.html" rel="nofollow">tarfile</a> module supports <a href="https://docs.python.org/2/library/tarfile.html#tarfile.is_tarfile" rel="nofollow"><code>is_tarfile()</code></a>, but ...
6
2009-11-24T06:31:08Z
1,788,326
<p>The <code>open</code> method of <code>tarfile</code> takes a file-like object in its <code>fileObj</code> argument. This can be a <code>StringIO</code> instance</p>
3
2009-11-24T06:57:25Z
[ "python", "tar", "tarfile" ]
How to determine if data is valid tar file without a file?
1,788,236
<p>My upload form expects a tar file and I want to check whether the uploaded data is valid. The <a href="http://docs.python.org/library/tarfile.html" rel="nofollow">tarfile</a> module supports <a href="https://docs.python.org/2/library/tarfile.html#tarfile.is_tarfile" rel="nofollow"><code>is_tarfile()</code></a>, but ...
6
2009-11-24T06:31:08Z
1,788,363
<p>Say your uploaded data is contained in string <code>data</code>.</p> <pre><code>from tarfile import TarFile, TarError from StringIO import StringIO sio = StringIO(data) try: tf = TarFile(fileobj=sio) # process the file.... except TarError: print "Not a tar file" </code></pre> <p>There are additional c...
3
2009-11-24T07:08:50Z
[ "python", "tar", "tarfile" ]
django unprintable templatesyntaxerror object caused by urlconf?
1,788,245
<p>I'm trying to get a django project set up, and I seem to be having trouble with my urlconf. I'm not sure what the deal is, and the error below isn't entirely helpful to me. I don't think it really has anything to do with template rendering, actually, because I stepped through the execution path until just before t...
0
2009-11-24T06:33:25Z
1,788,336
<p>Make sure each of your .py files is syntactically correct. Run <code>python manage.py shell</code> and then <code>import</code> each of your modules and make sure it loads with no errors. Since syntax errors are runtime errors in python, mistakes sometimes show up at odd times and in odd places.</p>
1
2009-11-24T07:01:18Z
[ "python", "django", "google-app-engine" ]
django unprintable templatesyntaxerror object caused by urlconf?
1,788,245
<p>I'm trying to get a django project set up, and I seem to be having trouble with my urlconf. I'm not sure what the deal is, and the error below isn't entirely helpful to me. I don't think it really has anything to do with template rendering, actually, because I stepped through the execution path until just before t...
0
2009-11-24T06:33:25Z
1,795,618
<p>Here's another suggestion which could come in handy in the future.</p> <p>The stack trace printed in the web interface isn't always optimal for a number of possible reasons. However, you can also get a stack trace out to the console which might give you information that was omitted on the web page.</p> <p>The easi...
0
2009-11-25T09:12:02Z
[ "python", "django", "google-app-engine" ]
django unprintable templatesyntaxerror object caused by urlconf?
1,788,245
<p>I'm trying to get a django project set up, and I seem to be having trouble with my urlconf. I'm not sure what the deal is, and the error below isn't entirely helpful to me. I don't think it really has anything to do with template rendering, actually, because I stepped through the execution path until just before t...
0
2009-11-24T06:33:25Z
1,996,644
<p>looks like the problem is because of a NoReverseMatch exception being thrown because my templates contain a {% url ... %} block that doesn't resolve. From the django site: Note that if the URL you're reversing doesn't exist, you'll get an NoReverseMatch exception raised, which will cause your site to display an erro...
0
2010-01-03T22:45:38Z
[ "python", "django", "google-app-engine" ]
Django: Serving admin media files
1,788,274
<p>I am trying to serve static files from another domain (sub domain of current domain). To serve all media files I used this settings:</p> <blockquote> <p>MEDIA_URL = '<a href="http://media.bud-inform.co.ua/" rel="nofollow">http://media.bud-inform.co.ua/</a>'</p> </blockquote> <p>So when in template I used </p> ...
4
2009-11-24T06:41:37Z
1,788,302
<p><code>MEDIA_URL</code> and <code>ADMIN_MEDIA_PREFIX</code> are two different things. One is the location of <em>your</em> media files, while the other is the location of the django admin system's media files.</p> <p>You have to make sure that the <code>ADMIN_MEDIA_PREFIX</code> points to somewhere where you're <str...
2
2009-11-24T06:50:12Z
[ "python", "django", "django-admin" ]
Java to Python RSA
1,788,421
<p>I'm trying to encrypt a string from Java to Python, using the library Bouncy Castle J2ME on the client side and Python M2Crypto on the other.</p> <p>Everything is pretty good, I can decrypt it properly, but the padding is the issue.</p> <p>The M2Crypto lib gives me (as far as I can tell) only these Padding schemes...
2
2009-11-24T07:23:18Z
1,789,100
<p>I'm not familiar with Bouncy Castle but I guess you somehow use <a href="http://www.bouncycastle.org/docs/docs1.6/org/bouncycastle/crypto/engines/RSAEngine.html" rel="nofollow"><code>RSAEngine</code></a> which implements <a href="http://www.bouncycastle.org/docs/docs1.6/org/bouncycastle/crypto/AsymmetricBlockCipher....
1
2009-11-24T10:07:55Z
[ "java", "python", "rsa", "bouncycastle", "m2crypto" ]
Java to Python RSA
1,788,421
<p>I'm trying to encrypt a string from Java to Python, using the library Bouncy Castle J2ME on the client side and Python M2Crypto on the other.</p> <p>Everything is pretty good, I can decrypt it properly, but the padding is the issue.</p> <p>The M2Crypto lib gives me (as far as I can tell) only these Padding schemes...
2
2009-11-24T07:23:18Z
4,762,242
<p>Bouncy castle provides padding. If you want for example to make an RSA with PKCS1 padding you have to do this:</p> <pre><code>public static PKCS1Encoding create_rsa_public(RSAKeyParameters PublicKey){ RSAEngine engine=new RSAEngine(); PKCS1Encoding encrypto=new PKCS1Encoding(engine); encrypto.init(true,...
1
2011-01-21T18:09:25Z
[ "java", "python", "rsa", "bouncycastle", "m2crypto" ]
How to have a URL like this in Django?
1,788,432
<p>How can I have URLs like <code>example.com/category/catename-operation/</code> in Django?</p> <p>Also in some cases the user enters a space separated category, how can I handle that? E.g if the user enters the category as "my home", then the URL for this category will become <code>example.com/my home/</code> which...
2
2009-11-24T07:25:37Z
1,788,452
<p><code>http://example.com/my%20home/</code> is a valid URL where space character is escaped and Django will do all escaping/unescaping for you.</p>
3
2009-11-24T07:32:48Z
[ "python", "django" ]
How to have a URL like this in Django?
1,788,432
<p>How can I have URLs like <code>example.com/category/catename-operation/</code> in Django?</p> <p>Also in some cases the user enters a space separated category, how can I handle that? E.g if the user enters the category as "my home", then the URL for this category will become <code>example.com/my home/</code> which...
2
2009-11-24T07:25:37Z
1,788,459
<p>You could consider adding a URL-friendly name to your category and using that in the URL instead.</p> <p>As another example you could have <code>example.com/tv/</code> and have the category called "Televisions."</p>
0
2009-11-24T07:34:19Z
[ "python", "django" ]
How to have a URL like this in Django?
1,788,432
<p>How can I have URLs like <code>example.com/category/catename-operation/</code> in Django?</p> <p>Also in some cases the user enters a space separated category, how can I handle that? E.g if the user enters the category as "my home", then the URL for this category will become <code>example.com/my home/</code> which...
2
2009-11-24T07:25:37Z
1,788,715
<blockquote> <p>How can I handle these things?</p> </blockquote> <p>If you want to handle this thing, to obtain my-url, then use the form field clean method to return the valid url. Thats what it is meant for.</p>
0
2009-11-24T08:40:26Z
[ "python", "django" ]
How to have a URL like this in Django?
1,788,432
<p>How can I have URLs like <code>example.com/category/catename-operation/</code> in Django?</p> <p>Also in some cases the user enters a space separated category, how can I handle that? E.g if the user enters the category as "my home", then the URL for this category will become <code>example.com/my home/</code> which...
2
2009-11-24T07:25:37Z
1,790,175
<p>If you want to keep your URLs pretty, for example when a user enters "my category" you could have "my-category" instead of "my%20category" in the URL. I suggest you look into SlugField (<a href="http://docs.djangoproject.com/en/dev/ref/models/fields/#slugfield">http://docs.djangoproject.com/en/dev/ref/models/fields/...
6
2009-11-24T13:48:56Z
[ "python", "django" ]
How to have a URL like this in Django?
1,788,432
<p>How can I have URLs like <code>example.com/category/catename-operation/</code> in Django?</p> <p>Also in some cases the user enters a space separated category, how can I handle that? E.g if the user enters the category as "my home", then the URL for this category will become <code>example.com/my home/</code> which...
2
2009-11-24T07:25:37Z
1,791,523
<p>You can use the slugify template tag within your views to deal with spaces and such like so:</p> <pre><code>from django.template.defaultfilters import slugify slugify("This is a slug!") # Will return u'this-is-a-slug' </code></pre>
1
2009-11-24T17:11:14Z
[ "python", "django" ]