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
Extending Python with C/C++
1,076,300
<p>Can anyone please give me tips on the tools or sofware to use to extend Python with C/C++? Thanks.</p>
4
2009-07-02T19:42:30Z
1,076,321
<p>The Python website itself has a great <a href="http://docs.python.org/extending/">set of examples</a>, as well as <a href="http://docs.python.org/c-api/">API documentation</a>. That's literally all I used when I needed to write C extensions.</p>
10
2009-07-02T19:46:35Z
[ "c++", "python", "c" ]
Extending Python with C/C++
1,076,300
<p>Can anyone please give me tips on the tools or sofware to use to extend Python with C/C++? Thanks.</p>
4
2009-07-02T19:42:30Z
1,076,324
<p>Yes, you need this: <a href="http://www.python.org/doc/ext/" rel="nofollow">http://www.python.org/doc/ext/</a></p> <p>And of course also a C/C++ compiler.</p> <p>If you describe what you are trying to do, and what kind of extensions you are making I'm sure people can give you more info.</p> <p>There are things like SWIG to wrap libraries, if that's what you want to do. If you just want speedups, C is often the answer, but not always, etc.</p>
2
2009-07-02T19:46:55Z
[ "c++", "python", "c" ]
Extending Python with C/C++
1,076,300
<p>Can anyone please give me tips on the tools or sofware to use to extend Python with C/C++? Thanks.</p>
4
2009-07-02T19:42:30Z
1,076,328
<p>I'll add the obligatory reference to <a href="http://www.boost.org/doc/libs/1%5F39%5F0/libs/python/doc/index.html">Boost.Python</a> for C++ stuff.</p>
13
2009-07-02T19:47:25Z
[ "c++", "python", "c" ]
Extending Python with C/C++
1,076,300
<p>Can anyone please give me tips on the tools or sofware to use to extend Python with C/C++? Thanks.</p>
4
2009-07-02T19:42:30Z
1,076,339
<p>Maybe <a href="http://github.com/felipec/libmtag-python/tree/master" rel="nofollow">this example</a> helps. I think it's simple enough :)</p>
1
2009-07-02T19:49:24Z
[ "c++", "python", "c" ]
Extending Python with C/C++
1,076,300
<p>Can anyone please give me tips on the tools or sofware to use to extend Python with C/C++? Thanks.</p>
4
2009-07-02T19:42:30Z
1,077,436
<p>There are many solutions. In general, you should avoid it if possible, as writing C extensions is tedious. Often, it is necessary to use a 3rd party library. In that case, I think the winning solution today is <a href="http://www.cython.org/" rel="nofollow">cython</a>.</p> <p>Cython is a languages which "looks like python", but can be made much faster by using optional typing. You can call directly C functions inside, and most of the reference counting (the hard problem in C extensions) is done automatically. In my experience, it is much better than boost.python, swig, or ctypes:</p> <ul> <li>boost.python only makes sense for wrapping C++ extensions IMHO. I find it too complicated, and hard to debug when something goes wrong.</li> <li>swig has quite some overhead, and does not lead to good code. It works ok for a couple of functions, but non trivial extensions often use typemaps, and the syntax get ugly quickly </li> </ul> <p>With cython, you can use python objects (list, dict, etc...) to wrap your C library. Of course, it is also very useful if you need to write your own extension just for speed reasons. In the scientific python community, I think cython has become the tool of choice when speed is needed.</p>
2
2009-07-03T01:21:25Z
[ "c++", "python", "c" ]
Extending Python with C/C++
1,076,300
<p>Can anyone please give me tips on the tools or sofware to use to extend Python with C/C++? Thanks.</p>
4
2009-07-02T19:42:30Z
1,077,488
<p>I see nobody's yet pointed out one of my favorite solutions for wrapping C++ code, <a href="http://www.riverbankcomputing.co.uk/software/sip/intro">SIP</a> (I believe it also works for wrapping C, like SWIG and unlike Boost, but I've never used it that way). It's the tool Riverbank Software developed to make PyQt, the Python interface to the wonderful Qt C++ cross-platform framework -- so it's a natural choice if your C++ code uses any Qt functionality, just like Boost Python is the natural choice if your C++ code uses Boost.</p> <p>SWIG is what we use at work (a reasonable decision when it was made 10 years ago;-) and has the theoretical advantage that it can also wrap C or C++ code for use from Java, Perl, Tcl, etc -- but if you only care about Python it's hard to see anything to make it stand out.</p> <p>If you're just wrapping an existing DLL/so, besides Cython, which other answers have pointed out (and I endorse, but -- it's changing very fast these days, so take care if you need something more stable), consider the standard function module <a href="http://docs.python.org/library/ctypes.html">ctypes</a> -- I wouldn't use it for very extensive work ("oops" errors that a C or C++ compiler would point out to you can cause runtime crashes with ctypes), but for small jobs it's great (and very handy since it comes with standard Python distributions!-).</p> <p>The good old C API ain't dead yet - just met today with Case, the great guy who's been doing most of the running lately for my good old open source project <a href="http://code.google.com/p/gmpy/">gmpy</a>, and together we decided to stick with the C API for at least the next release of gmpy -- we'll consider switching to Cython when it stabilizes, but we agreed that the switch would still be a bit premature now. (We didn't even think of any other alternative because gmpy's main point is to be as blindingly fast as we can possibly make it!-).</p>
6
2009-07-03T01:47:01Z
[ "c++", "python", "c" ]
Extending Python with C/C++
1,076,300
<p>Can anyone please give me tips on the tools or sofware to use to extend Python with C/C++? Thanks.</p>
4
2009-07-02T19:42:30Z
1,077,933
<p>I've used <a href="http://cxx.sourceforge.net/" rel="nofollow">pycxx</a> in the past and I've really enjoyed to use this lib. </p> <p>In my opinion, it is easier to use than SWIG. I can't really compare to boost.python because I've never really used boost. I think that pycxx is lighter than boost.python but I may be wrong.</p> <p>The key point with pycxx is that it is a c++ wrapper of the python c api. It is object-oriented and it hides all the difficult mechanism. It is quite intuitive for a python programmer. It is very easy to use and there is some nice examples for getting started.</p> <p>I do recommend pycxx as a first-class citizen for making python extension in c++.</p>
3
2009-07-03T05:58:45Z
[ "c++", "python", "c" ]
Replacing values in a Python list/dictionary?
1,076,536
<p>Ok, I am trying to filter a list/dictionary passed to me and "clean" it up a bit, as there are certain values in it that I need to get rid of.</p> <p>So, if it's looking like this:</p> <pre><code>"records": [{"key1": "AAA", "key2": "BBB", "key3": "CCC", "key4": "AAA"...}] </code></pre> <p>How would I quickly and easily run through it all and replace all values of "AAA" with something like "XXX"?</p> <p>Focus is on speed and resources, as these may be long lists and I don't want this process to consume too much time.</p>
19
2009-07-02T20:29:28Z
1,076,567
<pre><code>dic = root['records'][0] for i, j in dic.items(): # use iteritems in py2k if j == 'AAA': dic[i] = 'xxx' </code></pre>
9
2009-07-02T20:38:05Z
[ "python", "list", "dictionary", "replace" ]
Replacing values in a Python list/dictionary?
1,076,536
<p>Ok, I am trying to filter a list/dictionary passed to me and "clean" it up a bit, as there are certain values in it that I need to get rid of.</p> <p>So, if it's looking like this:</p> <pre><code>"records": [{"key1": "AAA", "key2": "BBB", "key3": "CCC", "key4": "AAA"...}] </code></pre> <p>How would I quickly and easily run through it all and replace all values of "AAA" with something like "XXX"?</p> <p>Focus is on speed and resources, as these may be long lists and I don't want this process to consume too much time.</p>
19
2009-07-02T20:29:28Z
1,076,577
<pre><code>DATA = {"records": [{"key1": "AAA", "key2": "BBB", "key3": "CCC", "key4": "AAA"}]} for name, datalist in DATA.iteritems(): # Or items() in Python 3.x for datadict in datalist: for key, value in datadict.items(): if value == "AAA": datadict[key] = "XXX" print (DATA) # Prints {'records': [{'key3': 'CCC', 'key2': 'BBB', 'key1': 'XXX', 'key4': 'XXX'}]} </code></pre>
26
2009-07-02T20:40:17Z
[ "python", "list", "dictionary", "replace" ]
Trouble using python PIL library to crop and save image
1,076,638
<p>Im attempting to crop a pretty high res image and save the result to make sure its completed. However I keep getting the following error regardless of how I use the save method: <code>SystemError: tile cannot extend outside image</code></p> <pre><code>from PIL import Image # size is width/height img = Image.open('0_388_image1.jpeg') box = (2407, 804, 71, 796) area = img.crop(box) area.save('cropped_0_388_image1', 'jpeg') output.close() </code></pre>
27
2009-07-02T20:54:04Z
1,076,648
<p>The box is (left, upper, right, lower) so maybe you meant (2407, 804, 2407+71, 804+796)?</p> <p><strong>Edit</strong>: All four coordinates are measured from the top/left corner, and describe the distance from that corner to the left edge, top edge, right edge and bottom edge.</p> <p>Your code should look like this, to get a 300x200 area from position 2407,804:</p> <pre><code>left = 2407 top = 804 width = 300 height = 200 box = (left, top, left+width, top+height) area = img.crop(box) </code></pre>
46
2009-07-02T20:56:50Z
[ "python", "python-imaging-library" ]
Trouble using python PIL library to crop and save image
1,076,638
<p>Im attempting to crop a pretty high res image and save the result to make sure its completed. However I keep getting the following error regardless of how I use the save method: <code>SystemError: tile cannot extend outside image</code></p> <pre><code>from PIL import Image # size is width/height img = Image.open('0_388_image1.jpeg') box = (2407, 804, 71, 796) area = img.crop(box) area.save('cropped_0_388_image1', 'jpeg') output.close() </code></pre>
27
2009-07-02T20:54:04Z
17,653,193
<p>Try this:</p> <p>it's a simple code to crop an image, and it works like a charm ;)</p> <pre><code>import Image def crop_image(input_image, output_image, start_x, start_y, width, height): """Pass input name image, output name image, x coordinate to start croping, y coordinate to start croping, width to crop, height to crop """ input_img = Image.open(input_image) box = (start_x, start_y, start_x + width, start_y + height) output_img = input_img.crop(box) output_img.save(output_image +".png") def main(): crop_image("Input.png","output", 0, 0, 1280, 399) if __name__ == '__main__': main() </code></pre> <p>In this case the Input image is 1280 x 800 px and the croped is 1280 x 399px starting at the top left corner.</p>
10
2013-07-15T11:28:06Z
[ "python", "python-imaging-library" ]
Making a variable non-inheritable in python
1,076,718
<p>Is there a way to make a variable non-inheritable in python? Like in the following example: B is a subclass of A, but I want it to have its own SIZE value.</p> <p>Could I get an Error to be raised (on __init__ or on getsize()) if B doesn't override SIZE?</p> <pre><code>class A: SIZE = 5 def getsize(self): return self.SIZE class B(A): pass </code></pre> <p><strong>Edit</strong>: ... while inheriting the getsize() method...?</p>
3
2009-07-02T21:13:36Z
1,076,737
<p>Use a double-underscore prefix:</p> <p>(Double-underscore solution deleted after Emma's clarification)</p> <p>OK, you can do it like this:</p> <pre><code>class A: SIZE = 5 def __init__(self): if self.__class__ != A: del self.SIZE def getsize(self): return self.SIZE class B(A): pass a = A() print a.getsize() # Prints 5 b = B() print b.getsize() # AttributeError: B instance has no attribute 'SIZE' </code></pre>
7
2009-07-02T21:17:31Z
[ "python", "inheritance" ]
Making a variable non-inheritable in python
1,076,718
<p>Is there a way to make a variable non-inheritable in python? Like in the following example: B is a subclass of A, but I want it to have its own SIZE value.</p> <p>Could I get an Error to be raised (on __init__ or on getsize()) if B doesn't override SIZE?</p> <pre><code>class A: SIZE = 5 def getsize(self): return self.SIZE class B(A): pass </code></pre> <p><strong>Edit</strong>: ... while inheriting the getsize() method...?</p>
3
2009-07-02T21:13:36Z
1,076,743
<p>You can always just override it like this:</p> <pre><code>class B(A): SIZE = 6 </code></pre>
0
2009-07-02T21:19:33Z
[ "python", "inheritance" ]
Making a variable non-inheritable in python
1,076,718
<p>Is there a way to make a variable non-inheritable in python? Like in the following example: B is a subclass of A, but I want it to have its own SIZE value.</p> <p>Could I get an Error to be raised (on __init__ or on getsize()) if B doesn't override SIZE?</p> <pre><code>class A: SIZE = 5 def getsize(self): return self.SIZE class B(A): pass </code></pre> <p><strong>Edit</strong>: ... while inheriting the getsize() method...?</p>
3
2009-07-02T21:13:36Z
1,076,793
<p>It sounds like what you want is a private variable. In which case this is what you need to do:</p> <pre><code>class A: __SIZE = 5 def getsize(self): return self.__SIZE def setsize(self,newsize): self.__SIZE=newsize class B(A): pass </code></pre>
0
2009-07-02T21:37:04Z
[ "python", "inheritance" ]
Making a variable non-inheritable in python
1,076,718
<p>Is there a way to make a variable non-inheritable in python? Like in the following example: B is a subclass of A, but I want it to have its own SIZE value.</p> <p>Could I get an Error to be raised (on __init__ or on getsize()) if B doesn't override SIZE?</p> <pre><code>class A: SIZE = 5 def getsize(self): return self.SIZE class B(A): pass </code></pre> <p><strong>Edit</strong>: ... while inheriting the getsize() method...?</p>
3
2009-07-02T21:13:36Z
1,076,798
<p>If you want to make <em>absolutely</em> sure that subclasses of <code>A</code> override <code>SIZE</code>, you could use a metaclass for <code>A</code> that will raise an error when a subclass does not override it (note that <code>A</code> is a new-style class here):</p> <pre><code>class ClassWithSize(type): def __init__(cls, name, bases, attrs): if 'SIZE' not in attrs: raise NotImplementedError('The "%s" class does not implement a "SIZE" attribute' % name) super(ClassWithSize, cls).__init__(name, bases, attrs) class A(object): __metaclass__ = ClassWithSize SIZE = 5 def getsize(self): return self.SIZE class B(A): SIZE = 6 class C(A): pass </code></pre> <p>When you put the above in a module and attempt to import it, an exception will be raised when the import reaches the <code>C</code> class implementation.</p>
4
2009-07-02T21:38:27Z
[ "python", "inheritance" ]
Making a variable non-inheritable in python
1,076,718
<p>Is there a way to make a variable non-inheritable in python? Like in the following example: B is a subclass of A, but I want it to have its own SIZE value.</p> <p>Could I get an Error to be raised (on __init__ or on getsize()) if B doesn't override SIZE?</p> <pre><code>class A: SIZE = 5 def getsize(self): return self.SIZE class B(A): pass </code></pre> <p><strong>Edit</strong>: ... while inheriting the getsize() method...?</p>
3
2009-07-02T21:13:36Z
1,077,095
<p>Another approach might be to get classes A and B to inherit from a third class instead of one from the other:</p> <pre><code>class X: def getsize(self): return self.SIZE class A(X): SIZE = 5 class B(X): pass a = A() print a.getsize() # Prints 5 b = B() print b.getsize() # AttributeError: B instance has no attribute 'SIZE' </code></pre>
0
2009-07-02T22:55:56Z
[ "python", "inheritance" ]
Making a variable non-inheritable in python
1,076,718
<p>Is there a way to make a variable non-inheritable in python? Like in the following example: B is a subclass of A, but I want it to have its own SIZE value.</p> <p>Could I get an Error to be raised (on __init__ or on getsize()) if B doesn't override SIZE?</p> <pre><code>class A: SIZE = 5 def getsize(self): return self.SIZE class B(A): pass </code></pre> <p><strong>Edit</strong>: ... while inheriting the getsize() method...?</p>
3
2009-07-02T21:13:36Z
1,077,309
<p>Another common idiom is to use <a href="http://docs.python.org/library/constants.html?highlight=notimplemented#NotImplemented" rel="nofollow">NotImplemented</a>. Think of it as the middle ground between metaclass enforcement and mere documentation.</p> <pre><code>class A: SIZE = NotImplemented </code></pre> <p>Now if a subclass forgets to override SIZE, the runtime errors will be immediate and obvious.</p>
0
2009-07-03T00:07:36Z
[ "python", "inheritance" ]
Making a variable non-inheritable in python
1,076,718
<p>Is there a way to make a variable non-inheritable in python? Like in the following example: B is a subclass of A, but I want it to have its own SIZE value.</p> <p>Could I get an Error to be raised (on __init__ or on getsize()) if B doesn't override SIZE?</p> <pre><code>class A: SIZE = 5 def getsize(self): return self.SIZE class B(A): pass </code></pre> <p><strong>Edit</strong>: ... while inheriting the getsize() method...?</p>
3
2009-07-02T21:13:36Z
1,077,513
<p>If metaclasses scare you (and I sympathize with that attitude!-), a descriptor could work -- you don't even have to make your custom descriptor (though that's <a href="http://users.rcn.com/python/download/Descriptor.htm" rel="nofollow">easy</a> enough), a plain good old property could work fine too:</p> <pre><code>class A(object): @property def SIZE(self): if type(self) is not A: raise AttributeError("Class %s MUST explicitly define SIZE!" % type(self).__name__) def getsize(self): return self.SIZE </code></pre> <p>Of course, this way you'll get the error only when an instance of a subclass of A which doesn't override SIZE actually tries to <em>use</em> <code>self.SIZE</code> (the metaclass approach has the advantage of giving the error earlier, when an errant subclass of A is created).</p>
1
2009-07-03T01:57:20Z
[ "python", "inheritance" ]
Making a variable non-inheritable in python
1,076,718
<p>Is there a way to make a variable non-inheritable in python? Like in the following example: B is a subclass of A, but I want it to have its own SIZE value.</p> <p>Could I get an Error to be raised (on __init__ or on getsize()) if B doesn't override SIZE?</p> <pre><code>class A: SIZE = 5 def getsize(self): return self.SIZE class B(A): pass </code></pre> <p><strong>Edit</strong>: ... while inheriting the getsize() method...?</p>
3
2009-07-02T21:13:36Z
1,077,535
<p>The only approach that I can add is to use <code>hasattr(self.__class__, 'SIZE')</code> in the implementation of <code>getsize()</code> and toss an exception if the attribute is not found. Something like:</p> <pre><code>class A: SIZE = 5 def getsize(self): klass = self.__class__ if hasattr(klass, 'SIZE') and 'SIZE' in klass.__dict__: return self.SIZE raise NotImplementedError('SIZE is not defined in ' + klass.__name__) </code></pre> <p>There is some magic still missing since the derived class could define a method named <code>SIZE</code> and <code>getsize</code> wouldn't detect it. You can probably do some <code>type(klass.SIZE)</code> magic to filter this out if you want to.</p>
1
2009-07-03T02:14:41Z
[ "python", "inheritance" ]
One liner to replicate lines coming from a file (Python)
1,076,872
<p>I have a regular list comprehension to load all lines of a file in a list</p> <pre><code>f = open('file') try: self._raw = [L.rstrip('\n') for L in f] finally: f.close() </code></pre> <p>Now I'd like to insert in the list each line 'n' times on the fly. How to do it inside the list comprehension ?</p> <p>Tnx</p>
1
2009-07-02T22:02:08Z
1,076,886
<pre><code>self._raw = [L.rstrip('\n') for L in f for _ in xrange(n)] </code></pre>
6
2009-07-02T22:05:13Z
[ "python", "list-comprehension" ]
urllib.urlopen isn't working. Is there a workaround?
1,076,958
<p>I'm getting a getaddress error and after doing some sleuthing, it looks like it might be my corporate intranet not allowing the connection (I'm assuming due to security, although it is strange that IE works but won't allow Python to open a url). Is there a safe way to get around this?</p> <p>Here's the exact error:</p> <pre><code>Traceback (most recent call last): File "&lt;pyshell#1&gt;", line 1, in &lt;module&gt; b = urllib.urlopen('http://www.google.com') File "C:\Python26\lib\urllib.py", line 87, in urlopen return opener.open(url) File "C:\Python26\lib\urllib.py", line 203, in open return getattr(self, name)(url) File "C:\Python26\lib\urllib.py", line 342, in open_http h.endheaders() File "C:\Python26\lib\httplib.py", line 868, in endheaders self._send_output() File "C:\Python26\lib\httplib.py", line 740, in _send_output self.send(msg) File "C:\Python26\lib\httplib.py", line 699, in send self.connect() File "C:\Python26\lib\httplib.py", line 683, in connect self.timeout) File "C:\Python26\lib\socket.py", line 498, in create_connection for res in getaddrinfo(host, port, 0, SOCK_STREAM): IOError: [Errno socket error] [Errno 11001] getaddrinfo failed </code></pre> <p>More info: I also get this error with urllib2.urlopen</p>
2
2009-07-02T22:25:44Z
1,076,969
<p>Check you are using the correct proxy.<br /> You can get the proxy information by using urllib.getproxies (note: getproxies does <em>not</em> work with dynamic proxy configuration, like when using PAC).</p> <p><strong>Update</strong> As per information about empty proxy list, I would suggest using an urlopener, with the proxy name and information.<br /> Some good information about how use proxies urlopeners:</p> <ol> <li><a href="http://docs.python.org/library/urllib.html#url-opener-objects" rel="nofollow">Urllib manual</a></li> <li><a href="http://www.voidspace.org.uk/python/articles/urllib2.shtml#proxies" rel="nofollow">Michael Foord's introduction to urllib</a></li> </ol>
3
2009-07-02T22:28:59Z
[ "python", "url" ]
urllib.urlopen isn't working. Is there a workaround?
1,076,958
<p>I'm getting a getaddress error and after doing some sleuthing, it looks like it might be my corporate intranet not allowing the connection (I'm assuming due to security, although it is strange that IE works but won't allow Python to open a url). Is there a safe way to get around this?</p> <p>Here's the exact error:</p> <pre><code>Traceback (most recent call last): File "&lt;pyshell#1&gt;", line 1, in &lt;module&gt; b = urllib.urlopen('http://www.google.com') File "C:\Python26\lib\urllib.py", line 87, in urlopen return opener.open(url) File "C:\Python26\lib\urllib.py", line 203, in open return getattr(self, name)(url) File "C:\Python26\lib\urllib.py", line 342, in open_http h.endheaders() File "C:\Python26\lib\httplib.py", line 868, in endheaders self._send_output() File "C:\Python26\lib\httplib.py", line 740, in _send_output self.send(msg) File "C:\Python26\lib\httplib.py", line 699, in send self.connect() File "C:\Python26\lib\httplib.py", line 683, in connect self.timeout) File "C:\Python26\lib\socket.py", line 498, in create_connection for res in getaddrinfo(host, port, 0, SOCK_STREAM): IOError: [Errno socket error] [Errno 11001] getaddrinfo failed </code></pre> <p>More info: I also get this error with urllib2.urlopen</p>
2
2009-07-02T22:25:44Z
1,077,370
<p>You probably need to fill in proxy information.</p> <pre><code>import urllib2 proxy_handler = urllib2.ProxyHandler({'http': 'http://yourcorporateproxy:12345/'}) proxy_auth_handler = urllib2.HTTPBasicAuthHandler() proxy_auth_handler.add_password('realm', 'host', 'username', 'password') opener = urllib2.build_opener(proxy_handler, proxy_auth_handler) opener.open('http://www.stackoverflow.com') </code></pre>
7
2009-07-03T00:40:01Z
[ "python", "url" ]
urllib.urlopen isn't working. Is there a workaround?
1,076,958
<p>I'm getting a getaddress error and after doing some sleuthing, it looks like it might be my corporate intranet not allowing the connection (I'm assuming due to security, although it is strange that IE works but won't allow Python to open a url). Is there a safe way to get around this?</p> <p>Here's the exact error:</p> <pre><code>Traceback (most recent call last): File "&lt;pyshell#1&gt;", line 1, in &lt;module&gt; b = urllib.urlopen('http://www.google.com') File "C:\Python26\lib\urllib.py", line 87, in urlopen return opener.open(url) File "C:\Python26\lib\urllib.py", line 203, in open return getattr(self, name)(url) File "C:\Python26\lib\urllib.py", line 342, in open_http h.endheaders() File "C:\Python26\lib\httplib.py", line 868, in endheaders self._send_output() File "C:\Python26\lib\httplib.py", line 740, in _send_output self.send(msg) File "C:\Python26\lib\httplib.py", line 699, in send self.connect() File "C:\Python26\lib\httplib.py", line 683, in connect self.timeout) File "C:\Python26\lib\socket.py", line 498, in create_connection for res in getaddrinfo(host, port, 0, SOCK_STREAM): IOError: [Errno socket error] [Errno 11001] getaddrinfo failed </code></pre> <p>More info: I also get this error with urllib2.urlopen</p>
2
2009-07-02T22:25:44Z
1,077,594
<p>Possibly this is a DNS issue, try urlopen with the IP address of the web server you're accessing, i.e.</p> <pre><code>import urllib URL="http://66.102.11.99" # www.google.com f = urllib.urlopen(URL) f.read() </code></pre> <p>If this succeeds, then it's probably a DNS issue rather than a proxy issue (but you should also check your proxy setup).</p>
2
2009-07-03T02:53:07Z
[ "python", "url" ]
urllib.urlopen isn't working. Is there a workaround?
1,076,958
<p>I'm getting a getaddress error and after doing some sleuthing, it looks like it might be my corporate intranet not allowing the connection (I'm assuming due to security, although it is strange that IE works but won't allow Python to open a url). Is there a safe way to get around this?</p> <p>Here's the exact error:</p> <pre><code>Traceback (most recent call last): File "&lt;pyshell#1&gt;", line 1, in &lt;module&gt; b = urllib.urlopen('http://www.google.com') File "C:\Python26\lib\urllib.py", line 87, in urlopen return opener.open(url) File "C:\Python26\lib\urllib.py", line 203, in open return getattr(self, name)(url) File "C:\Python26\lib\urllib.py", line 342, in open_http h.endheaders() File "C:\Python26\lib\httplib.py", line 868, in endheaders self._send_output() File "C:\Python26\lib\httplib.py", line 740, in _send_output self.send(msg) File "C:\Python26\lib\httplib.py", line 699, in send self.connect() File "C:\Python26\lib\httplib.py", line 683, in connect self.timeout) File "C:\Python26\lib\socket.py", line 498, in create_connection for res in getaddrinfo(host, port, 0, SOCK_STREAM): IOError: [Errno socket error] [Errno 11001] getaddrinfo failed </code></pre> <p>More info: I also get this error with urllib2.urlopen</p>
2
2009-07-02T22:25:44Z
1,077,784
<p>Looks like a DNS problem. </p> <p>Since you are using Windows, you can try run this command</p> <pre><code>nslookup www.google.com </code></pre> <p>To check if the web address can be resolved successfully.</p> <p>If not, it is a network setting issue</p> <p>If OK, then we have to look at possible alternative causes</p>
2
2009-07-03T04:43:49Z
[ "python", "url" ]
urllib.urlopen isn't working. Is there a workaround?
1,076,958
<p>I'm getting a getaddress error and after doing some sleuthing, it looks like it might be my corporate intranet not allowing the connection (I'm assuming due to security, although it is strange that IE works but won't allow Python to open a url). Is there a safe way to get around this?</p> <p>Here's the exact error:</p> <pre><code>Traceback (most recent call last): File "&lt;pyshell#1&gt;", line 1, in &lt;module&gt; b = urllib.urlopen('http://www.google.com') File "C:\Python26\lib\urllib.py", line 87, in urlopen return opener.open(url) File "C:\Python26\lib\urllib.py", line 203, in open return getattr(self, name)(url) File "C:\Python26\lib\urllib.py", line 342, in open_http h.endheaders() File "C:\Python26\lib\httplib.py", line 868, in endheaders self._send_output() File "C:\Python26\lib\httplib.py", line 740, in _send_output self.send(msg) File "C:\Python26\lib\httplib.py", line 699, in send self.connect() File "C:\Python26\lib\httplib.py", line 683, in connect self.timeout) File "C:\Python26\lib\socket.py", line 498, in create_connection for res in getaddrinfo(host, port, 0, SOCK_STREAM): IOError: [Errno socket error] [Errno 11001] getaddrinfo failed </code></pre> <p>More info: I also get this error with urllib2.urlopen</p>
2
2009-07-02T22:25:44Z
1,152,582
<p>I was facing the same issue. In my system the proxy configuration is through a .PAC file. So i opended that file, took out the default proxy url, for me it was <a href="http://168.219.61.250:8080/" rel="nofollow">http://168.219.61.250:8080/</a></p> <p>Following test code worked for me :</p> <pre><code>import urllib2 proxy_support = urllib2.ProxyHandler({'http': 'http://168.219.61.250:8080/'}) opener = urllib2.build_opener(proxy_support) urllib2.install_opener(opener) response = urllib2.urlopen('http://python.org/') html = response.read() print html </code></pre> <p>You might need to add some more code, if your proxy requires authentication</p> <p>Hope this helps!!</p>
2
2009-07-20T09:25:52Z
[ "python", "url" ]
python list comprehensions; compressing a list of lists?
1,077,015
<p>guys. I'm trying to find the most elegant solution to a problem and wondered if python has anything built-in for what I'm trying to do. </p> <p>What I'm doing is this. I have a list, <code>A</code>, and I have a function <code>f</code> which takes an item and returns a list. I can use a list comprehension to convert everything in <code>A</code> like so;</p> <pre><code>[f(a) for a in A] </code></pre> <p>But this return a list of lists;</p> <pre><code>[a1,a2,a3] =&gt; [[b11,b12],[b21,b22],[b31,b32]] </code></pre> <p>What I really want is to get the flattened list;</p> <pre><code>[b11,b12,b21,b22,b31,b32] </code></pre> <p>Now, other languages have it; it's traditionally called <code>flatmap</code> in functional programming languages, and .Net calls it <code>SelectMany</code>. Does python have anything similar? Is there a neat way to map a function over a list and flatten the result?</p> <p><em>The actual problem I'm trying to solve is this; starting with a list of directories, find all the subdirectories. so;</em></p> <pre><code>import os dirs = ["c:\\usr", "c:\\temp"] subs = [os.listdir(d) for d in dirs] print subs </code></pre> <p><em>currentliy gives me a list-of-lists, but I really want a list.</em></p>
35
2009-07-02T22:40:40Z
1,077,061
<p>You could try <code>itertools.chain()</code>, like this:</p> <pre><code>import itertools import os dirs = ["c:\\usr", "c:\\temp"] subs = list(itertools.chain(*[os.listdir(d) for d in dirs])) print subs </code></pre> <p><code>itertools.chain()</code> returns an iterator, hence the passing to <code>list()</code>.</p>
3
2009-07-02T22:47:52Z
[ "functional-programming", "python", "list-comprehension" ]
python list comprehensions; compressing a list of lists?
1,077,015
<p>guys. I'm trying to find the most elegant solution to a problem and wondered if python has anything built-in for what I'm trying to do. </p> <p>What I'm doing is this. I have a list, <code>A</code>, and I have a function <code>f</code> which takes an item and returns a list. I can use a list comprehension to convert everything in <code>A</code> like so;</p> <pre><code>[f(a) for a in A] </code></pre> <p>But this return a list of lists;</p> <pre><code>[a1,a2,a3] =&gt; [[b11,b12],[b21,b22],[b31,b32]] </code></pre> <p>What I really want is to get the flattened list;</p> <pre><code>[b11,b12,b21,b22,b31,b32] </code></pre> <p>Now, other languages have it; it's traditionally called <code>flatmap</code> in functional programming languages, and .Net calls it <code>SelectMany</code>. Does python have anything similar? Is there a neat way to map a function over a list and flatten the result?</p> <p><em>The actual problem I'm trying to solve is this; starting with a list of directories, find all the subdirectories. so;</em></p> <pre><code>import os dirs = ["c:\\usr", "c:\\temp"] subs = [os.listdir(d) for d in dirs] print subs </code></pre> <p><em>currentliy gives me a list-of-lists, but I really want a list.</em></p>
35
2009-07-02T22:40:40Z
1,077,067
<pre><code>subs = [] map(subs.extend, (os.listdir(d) for d in dirs)) </code></pre> <p>(but Ants's answer is better; +1 for him)</p>
5
2009-07-02T22:48:38Z
[ "functional-programming", "python", "list-comprehension" ]
python list comprehensions; compressing a list of lists?
1,077,015
<p>guys. I'm trying to find the most elegant solution to a problem and wondered if python has anything built-in for what I'm trying to do. </p> <p>What I'm doing is this. I have a list, <code>A</code>, and I have a function <code>f</code> which takes an item and returns a list. I can use a list comprehension to convert everything in <code>A</code> like so;</p> <pre><code>[f(a) for a in A] </code></pre> <p>But this return a list of lists;</p> <pre><code>[a1,a2,a3] =&gt; [[b11,b12],[b21,b22],[b31,b32]] </code></pre> <p>What I really want is to get the flattened list;</p> <pre><code>[b11,b12,b21,b22,b31,b32] </code></pre> <p>Now, other languages have it; it's traditionally called <code>flatmap</code> in functional programming languages, and .Net calls it <code>SelectMany</code>. Does python have anything similar? Is there a neat way to map a function over a list and flatten the result?</p> <p><em>The actual problem I'm trying to solve is this; starting with a list of directories, find all the subdirectories. so;</em></p> <pre><code>import os dirs = ["c:\\usr", "c:\\temp"] subs = [os.listdir(d) for d in dirs] print subs </code></pre> <p><em>currentliy gives me a list-of-lists, but I really want a list.</em></p>
35
2009-07-02T22:40:40Z
1,077,074
<p>You can find a good answer in <a href="http://docs.python.org/library/itertools.html#recipes">itertools' recipes:</a></p> <pre><code>def flatten(listOfLists): return list(chain.from_iterable(listOfLists)) </code></pre> <p>(Note: requires Python 2.6+)</p>
35
2009-07-02T22:50:47Z
[ "functional-programming", "python", "list-comprehension" ]
python list comprehensions; compressing a list of lists?
1,077,015
<p>guys. I'm trying to find the most elegant solution to a problem and wondered if python has anything built-in for what I'm trying to do. </p> <p>What I'm doing is this. I have a list, <code>A</code>, and I have a function <code>f</code> which takes an item and returns a list. I can use a list comprehension to convert everything in <code>A</code> like so;</p> <pre><code>[f(a) for a in A] </code></pre> <p>But this return a list of lists;</p> <pre><code>[a1,a2,a3] =&gt; [[b11,b12],[b21,b22],[b31,b32]] </code></pre> <p>What I really want is to get the flattened list;</p> <pre><code>[b11,b12,b21,b22,b31,b32] </code></pre> <p>Now, other languages have it; it's traditionally called <code>flatmap</code> in functional programming languages, and .Net calls it <code>SelectMany</code>. Does python have anything similar? Is there a neat way to map a function over a list and flatten the result?</p> <p><em>The actual problem I'm trying to solve is this; starting with a list of directories, find all the subdirectories. so;</em></p> <pre><code>import os dirs = ["c:\\usr", "c:\\temp"] subs = [os.listdir(d) for d in dirs] print subs </code></pre> <p><em>currentliy gives me a list-of-lists, but I really want a list.</em></p>
35
2009-07-02T22:40:40Z
1,077,081
<p>Google brought me next solution:</p> <pre><code>def flatten(l): if isinstance(l,list): return sum(map(flatten,l)) else: return l </code></pre>
3
2009-07-02T22:52:51Z
[ "functional-programming", "python", "list-comprehension" ]
python list comprehensions; compressing a list of lists?
1,077,015
<p>guys. I'm trying to find the most elegant solution to a problem and wondered if python has anything built-in for what I'm trying to do. </p> <p>What I'm doing is this. I have a list, <code>A</code>, and I have a function <code>f</code> which takes an item and returns a list. I can use a list comprehension to convert everything in <code>A</code> like so;</p> <pre><code>[f(a) for a in A] </code></pre> <p>But this return a list of lists;</p> <pre><code>[a1,a2,a3] =&gt; [[b11,b12],[b21,b22],[b31,b32]] </code></pre> <p>What I really want is to get the flattened list;</p> <pre><code>[b11,b12,b21,b22,b31,b32] </code></pre> <p>Now, other languages have it; it's traditionally called <code>flatmap</code> in functional programming languages, and .Net calls it <code>SelectMany</code>. Does python have anything similar? Is there a neat way to map a function over a list and flatten the result?</p> <p><em>The actual problem I'm trying to solve is this; starting with a list of directories, find all the subdirectories. so;</em></p> <pre><code>import os dirs = ["c:\\usr", "c:\\temp"] subs = [os.listdir(d) for d in dirs] print subs </code></pre> <p><em>currentliy gives me a list-of-lists, but I really want a list.</em></p>
35
2009-07-02T22:40:40Z
1,077,205
<p>You can have nested iterations in a single list comprehension:</p> <pre><code>[filename for path in dirs for filename in os.listdir(path)] </code></pre>
58
2009-07-02T23:32:56Z
[ "functional-programming", "python", "list-comprehension" ]
python list comprehensions; compressing a list of lists?
1,077,015
<p>guys. I'm trying to find the most elegant solution to a problem and wondered if python has anything built-in for what I'm trying to do. </p> <p>What I'm doing is this. I have a list, <code>A</code>, and I have a function <code>f</code> which takes an item and returns a list. I can use a list comprehension to convert everything in <code>A</code> like so;</p> <pre><code>[f(a) for a in A] </code></pre> <p>But this return a list of lists;</p> <pre><code>[a1,a2,a3] =&gt; [[b11,b12],[b21,b22],[b31,b32]] </code></pre> <p>What I really want is to get the flattened list;</p> <pre><code>[b11,b12,b21,b22,b31,b32] </code></pre> <p>Now, other languages have it; it's traditionally called <code>flatmap</code> in functional programming languages, and .Net calls it <code>SelectMany</code>. Does python have anything similar? Is there a neat way to map a function over a list and flatten the result?</p> <p><em>The actual problem I'm trying to solve is this; starting with a list of directories, find all the subdirectories. so;</em></p> <pre><code>import os dirs = ["c:\\usr", "c:\\temp"] subs = [os.listdir(d) for d in dirs] print subs </code></pre> <p><em>currentliy gives me a list-of-lists, but I really want a list.</em></p>
35
2009-07-02T22:40:40Z
1,077,220
<p>You could just do the straightforward:</p> <pre><code>subs = [] for d in dirs: subs.extend(os.listdir(d)) </code></pre>
11
2009-07-02T23:37:11Z
[ "functional-programming", "python", "list-comprehension" ]
python list comprehensions; compressing a list of lists?
1,077,015
<p>guys. I'm trying to find the most elegant solution to a problem and wondered if python has anything built-in for what I'm trying to do. </p> <p>What I'm doing is this. I have a list, <code>A</code>, and I have a function <code>f</code> which takes an item and returns a list. I can use a list comprehension to convert everything in <code>A</code> like so;</p> <pre><code>[f(a) for a in A] </code></pre> <p>But this return a list of lists;</p> <pre><code>[a1,a2,a3] =&gt; [[b11,b12],[b21,b22],[b31,b32]] </code></pre> <p>What I really want is to get the flattened list;</p> <pre><code>[b11,b12,b21,b22,b31,b32] </code></pre> <p>Now, other languages have it; it's traditionally called <code>flatmap</code> in functional programming languages, and .Net calls it <code>SelectMany</code>. Does python have anything similar? Is there a neat way to map a function over a list and flatten the result?</p> <p><em>The actual problem I'm trying to solve is this; starting with a list of directories, find all the subdirectories. so;</em></p> <pre><code>import os dirs = ["c:\\usr", "c:\\temp"] subs = [os.listdir(d) for d in dirs] print subs </code></pre> <p><em>currentliy gives me a list-of-lists, but I really want a list.</em></p>
35
2009-07-02T22:40:40Z
1,079,210
<p>You can concatenate lists using the normal addition operator:</p> <pre><code>&gt;&gt;&gt; [1, 2] + [3, 4] [1, 2, 3, 4] </code></pre> <p>The built-in function <code>sum</code> will add the numbers in a sequence and can optionally start from a specific value:</p> <pre><code>&gt;&gt;&gt; sum(xrange(10), 100) 145 </code></pre> <p>Combine the above to flatten a list of lists:</p> <pre><code>&gt;&gt;&gt; sum([[1, 2], [3, 4]], []) [1, 2, 3, 4] </code></pre> <p>You can now define your <code>flatmap</code>:</p> <pre><code>&gt;&gt;&gt; def flatmap(f, seq): ... return sum([f(s) for s in seq], []) ... &gt;&gt;&gt; flatmap(range, [1,2,3]) [0, 0, 1, 0, 1, 2] </code></pre> <p><strong>Edit:</strong> I just saw the critique in the comments for <a href="http://stackoverflow.com/questions/1077015/python-list-comprehensions-compressing-a-list-of-lists/1077067#1077067">another answer</a> and I guess it is correct that Python will needlessly build and garbage collect lots of smaller lists with this solution. So the best thing that can be said about it is that it is very simple and concise if you're used to functional programming :-)</p>
10
2009-07-03T12:47:57Z
[ "functional-programming", "python", "list-comprehension" ]
python list comprehensions; compressing a list of lists?
1,077,015
<p>guys. I'm trying to find the most elegant solution to a problem and wondered if python has anything built-in for what I'm trying to do. </p> <p>What I'm doing is this. I have a list, <code>A</code>, and I have a function <code>f</code> which takes an item and returns a list. I can use a list comprehension to convert everything in <code>A</code> like so;</p> <pre><code>[f(a) for a in A] </code></pre> <p>But this return a list of lists;</p> <pre><code>[a1,a2,a3] =&gt; [[b11,b12],[b21,b22],[b31,b32]] </code></pre> <p>What I really want is to get the flattened list;</p> <pre><code>[b11,b12,b21,b22,b31,b32] </code></pre> <p>Now, other languages have it; it's traditionally called <code>flatmap</code> in functional programming languages, and .Net calls it <code>SelectMany</code>. Does python have anything similar? Is there a neat way to map a function over a list and flatten the result?</p> <p><em>The actual problem I'm trying to solve is this; starting with a list of directories, find all the subdirectories. so;</em></p> <pre><code>import os dirs = ["c:\\usr", "c:\\temp"] subs = [os.listdir(d) for d in dirs] print subs </code></pre> <p><em>currentliy gives me a list-of-lists, but I really want a list.</em></p>
35
2009-07-02T22:40:40Z
2,082,107
<pre><code>&gt;&gt;&gt; listOfLists = [[1, 2],[3, 4, 5], [6]] &gt;&gt;&gt; reduce(list.__add__, listOfLists) [1, 2, 3, 4, 5, 6] </code></pre> <p>I'm guessing the itertools solution is more efficient than this, but this feel very pythonic and avoids having to import a library just for the sake of a single list operation.</p>
25
2010-01-17T18:32:30Z
[ "functional-programming", "python", "list-comprehension" ]
python list comprehensions; compressing a list of lists?
1,077,015
<p>guys. I'm trying to find the most elegant solution to a problem and wondered if python has anything built-in for what I'm trying to do. </p> <p>What I'm doing is this. I have a list, <code>A</code>, and I have a function <code>f</code> which takes an item and returns a list. I can use a list comprehension to convert everything in <code>A</code> like so;</p> <pre><code>[f(a) for a in A] </code></pre> <p>But this return a list of lists;</p> <pre><code>[a1,a2,a3] =&gt; [[b11,b12],[b21,b22],[b31,b32]] </code></pre> <p>What I really want is to get the flattened list;</p> <pre><code>[b11,b12,b21,b22,b31,b32] </code></pre> <p>Now, other languages have it; it's traditionally called <code>flatmap</code> in functional programming languages, and .Net calls it <code>SelectMany</code>. Does python have anything similar? Is there a neat way to map a function over a list and flatten the result?</p> <p><em>The actual problem I'm trying to solve is this; starting with a list of directories, find all the subdirectories. so;</em></p> <pre><code>import os dirs = ["c:\\usr", "c:\\temp"] subs = [os.listdir(d) for d in dirs] print subs </code></pre> <p><em>currentliy gives me a list-of-lists, but I really want a list.</em></p>
35
2009-07-02T22:40:40Z
13,498,063
<pre><code>import itertools x=[['b11','b12'],['b21','b22'],['b31']] y=list(itertools.chain(*x)) print y </code></pre> <p>itertools will work from python2.3 and greater</p>
4
2012-11-21T16:48:02Z
[ "functional-programming", "python", "list-comprehension" ]
python list comprehensions; compressing a list of lists?
1,077,015
<p>guys. I'm trying to find the most elegant solution to a problem and wondered if python has anything built-in for what I'm trying to do. </p> <p>What I'm doing is this. I have a list, <code>A</code>, and I have a function <code>f</code> which takes an item and returns a list. I can use a list comprehension to convert everything in <code>A</code> like so;</p> <pre><code>[f(a) for a in A] </code></pre> <p>But this return a list of lists;</p> <pre><code>[a1,a2,a3] =&gt; [[b11,b12],[b21,b22],[b31,b32]] </code></pre> <p>What I really want is to get the flattened list;</p> <pre><code>[b11,b12,b21,b22,b31,b32] </code></pre> <p>Now, other languages have it; it's traditionally called <code>flatmap</code> in functional programming languages, and .Net calls it <code>SelectMany</code>. Does python have anything similar? Is there a neat way to map a function over a list and flatten the result?</p> <p><em>The actual problem I'm trying to solve is this; starting with a list of directories, find all the subdirectories. so;</em></p> <pre><code>import os dirs = ["c:\\usr", "c:\\temp"] subs = [os.listdir(d) for d in dirs] print subs </code></pre> <p><em>currentliy gives me a list-of-lists, but I really want a list.</em></p>
35
2009-07-02T22:40:40Z
20,037,408
<p>The question proposed <code>flatmap</code>. Some implementations are proposed but they may unnecessary creating intermediate lists. Here is one implementation that's base on iterators.</p> <pre><code>def flatmap(func, *iterable): return itertools.chain.from_iterable(map(func, *iterable)) In [148]: list(flatmap(os.listdir, ['c:/mfg','c:/Intel'])) Out[148]: ['SPEC.pdf', 'W7ADD64EN006.cdr', 'W7ADD64EN006.pdf', 'ExtremeGraphics', 'Logs'] </code></pre> <p>In Python 2.x, use <code>itertools.map</code> in place of <code>map</code>.</p>
9
2013-11-17T23:07:11Z
[ "functional-programming", "python", "list-comprehension" ]
python list comprehensions; compressing a list of lists?
1,077,015
<p>guys. I'm trying to find the most elegant solution to a problem and wondered if python has anything built-in for what I'm trying to do. </p> <p>What I'm doing is this. I have a list, <code>A</code>, and I have a function <code>f</code> which takes an item and returns a list. I can use a list comprehension to convert everything in <code>A</code> like so;</p> <pre><code>[f(a) for a in A] </code></pre> <p>But this return a list of lists;</p> <pre><code>[a1,a2,a3] =&gt; [[b11,b12],[b21,b22],[b31,b32]] </code></pre> <p>What I really want is to get the flattened list;</p> <pre><code>[b11,b12,b21,b22,b31,b32] </code></pre> <p>Now, other languages have it; it's traditionally called <code>flatmap</code> in functional programming languages, and .Net calls it <code>SelectMany</code>. Does python have anything similar? Is there a neat way to map a function over a list and flatten the result?</p> <p><em>The actual problem I'm trying to solve is this; starting with a list of directories, find all the subdirectories. so;</em></p> <pre><code>import os dirs = ["c:\\usr", "c:\\temp"] subs = [os.listdir(d) for d in dirs] print subs </code></pre> <p><em>currentliy gives me a list-of-lists, but I really want a list.</em></p>
35
2009-07-02T22:40:40Z
31,489,364
<pre><code>If listA=[list1,list2,list3] flattened_list=reduce(lambda x,y:x+y,listA) </code></pre> <p>This will do.</p>
0
2015-07-18T08:39:41Z
[ "functional-programming", "python", "list-comprehension" ]
How do I store multiple values in a single attribute
1,077,227
<p>I don't know if I'm thinking of this the right way, and perhaps somebody will set me straight.</p> <p>Let's say I have a models.py that contains this:</p> <pre><code>class Order(models.Model): customer = models.foreignKey(Customer) total = models.charField(max_length=10) has_shipped = models.booleanField() class Product(models.Model): sku = models.charField(max_length=30) price = models.charField(max_length=10) </code></pre> <p>Now, obviously an order would contain products and not just a product. What would be the best way to add products to an order? The only way I can think is to add another field to 'Order' called 'products', and fill it with a CSV with a sku for each product in it. This, for obvious reasons is not ideal, but I'm not very good at this stuff yet and have no idea of what the better way is.</p> <p>(keep in mind this is pseudo code, so don't mind misspellings, etc.)</p>
1
2009-07-02T23:38:14Z
1,077,245
<p>You can create one more model which will serve as many-to-many relationship between Order and Products</p> <p>something like this</p> <pre><code>class OrderProducts(models.Model) product = models.ForeignKey(Product) order = models.ForeignKey(Order) </code></pre>
0
2009-07-02T23:45:30Z
[ "python", "django", "e-commerce" ]
How do I store multiple values in a single attribute
1,077,227
<p>I don't know if I'm thinking of this the right way, and perhaps somebody will set me straight.</p> <p>Let's say I have a models.py that contains this:</p> <pre><code>class Order(models.Model): customer = models.foreignKey(Customer) total = models.charField(max_length=10) has_shipped = models.booleanField() class Product(models.Model): sku = models.charField(max_length=30) price = models.charField(max_length=10) </code></pre> <p>Now, obviously an order would contain products and not just a product. What would be the best way to add products to an order? The only way I can think is to add another field to 'Order' called 'products', and fill it with a CSV with a sku for each product in it. This, for obvious reasons is not ideal, but I'm not very good at this stuff yet and have no idea of what the better way is.</p> <p>(keep in mind this is pseudo code, so don't mind misspellings, etc.)</p>
1
2009-07-02T23:38:14Z
1,077,253
<p>What you're after is a many to many relationship between product and order.</p> <p>Something like:</p> <pre><code>class Order(models.Model): customer = models.foreignKey(Customer) total = models.charField(max_length=10) has_shipped = models.booleanField() products = models.ManyToManyField(Product) </code></pre> <p>see the docs <a href="http://www.djangoproject.com/documentation/models/many%5Fto%5Fmany/" rel="nofollow">here</a> and <a href="http://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.ManyToManyField" rel="nofollow">here</a>.</p>
7
2009-07-02T23:48:41Z
[ "python", "django", "e-commerce" ]
How to specify time zone (UTC) when converting to Unix time? (Python)
1,077,285
<p>I have a utc timestamp in the IS8601 format and am trying to convert it to unix time. This is my console session:</p> <pre><code>In [9]: mydate Out[9]: '2009-07-17T01:21:00.000Z' In [10]: parseddate = iso8601.parse_date(mydate) In [14]: ti = time.mktime(parseddate.timetuple()) In [25]: datetime.datetime.utcfromtimestamp(ti) Out[25]: datetime.datetime(2009, 7, 17, 7, 21) In [26]: datetime.datetime.fromtimestamp(ti) Out[26]: datetime.datetime(2009, 7, 17, 2, 21) In [27]: ti Out[27]: 1247815260.0 In [28]: parseddate Out[28]: datetime.datetime(2009, 7, 17, 1, 21, tzinfo=&lt;iso8601.iso8601.Utc object at 0x01D74C70&gt;) </code></pre> <p>As you can see, I can't get the correct time back. The hour is ahead by one if i use fromtimestamp(), and it's ahead by six hours if i use utcfromtimestamp()</p> <p>Any advice?</p> <p>Thanks!</p>
5
2009-07-03T00:00:45Z
1,077,313
<p>I am just guessing, but one hour difference can be not because of time zones, but because of daylight savings on/off.</p>
0
2009-07-03T00:09:28Z
[ "python", "datetime", "iso8601", "unix-timestamp" ]
How to specify time zone (UTC) when converting to Unix time? (Python)
1,077,285
<p>I have a utc timestamp in the IS8601 format and am trying to convert it to unix time. This is my console session:</p> <pre><code>In [9]: mydate Out[9]: '2009-07-17T01:21:00.000Z' In [10]: parseddate = iso8601.parse_date(mydate) In [14]: ti = time.mktime(parseddate.timetuple()) In [25]: datetime.datetime.utcfromtimestamp(ti) Out[25]: datetime.datetime(2009, 7, 17, 7, 21) In [26]: datetime.datetime.fromtimestamp(ti) Out[26]: datetime.datetime(2009, 7, 17, 2, 21) In [27]: ti Out[27]: 1247815260.0 In [28]: parseddate Out[28]: datetime.datetime(2009, 7, 17, 1, 21, tzinfo=&lt;iso8601.iso8601.Utc object at 0x01D74C70&gt;) </code></pre> <p>As you can see, I can't get the correct time back. The hour is ahead by one if i use fromtimestamp(), and it's ahead by six hours if i use utcfromtimestamp()</p> <p>Any advice?</p> <p>Thanks!</p>
5
2009-07-03T00:00:45Z
1,077,362
<p>You can create an <code>struct_time</code> in UTC with <a href="http://docs.python.org/library/datetime.html#datetime.datetime.utctimetuple"><code>datetime.utctimetuple()</code></a> and then convert this to a unix timestamp with <a href="http://docs.python.org/library/calendar.html#calendar.timegm"><code>calendar.timegm()</code></a>:</p> <pre><code>calendar.timegm(parseddate.utctimetuple()) </code></pre> <p>This also takes care of any daylight savings time offset, because <code>utctimetuple()</code> normalizes this.</p>
12
2009-07-03T00:33:03Z
[ "python", "datetime", "iso8601", "unix-timestamp" ]
How to specify time zone (UTC) when converting to Unix time? (Python)
1,077,285
<p>I have a utc timestamp in the IS8601 format and am trying to convert it to unix time. This is my console session:</p> <pre><code>In [9]: mydate Out[9]: '2009-07-17T01:21:00.000Z' In [10]: parseddate = iso8601.parse_date(mydate) In [14]: ti = time.mktime(parseddate.timetuple()) In [25]: datetime.datetime.utcfromtimestamp(ti) Out[25]: datetime.datetime(2009, 7, 17, 7, 21) In [26]: datetime.datetime.fromtimestamp(ti) Out[26]: datetime.datetime(2009, 7, 17, 2, 21) In [27]: ti Out[27]: 1247815260.0 In [28]: parseddate Out[28]: datetime.datetime(2009, 7, 17, 1, 21, tzinfo=&lt;iso8601.iso8601.Utc object at 0x01D74C70&gt;) </code></pre> <p>As you can see, I can't get the correct time back. The hour is ahead by one if i use fromtimestamp(), and it's ahead by six hours if i use utcfromtimestamp()</p> <p>Any advice?</p> <p>Thanks!</p>
5
2009-07-03T00:00:45Z
13,423,441
<pre><code>naive_utc_dt = parseddate.replace(tzinfo=None) timestamp = (naive_utc_dt - datetime(1970, 1, 1)).total_seconds() # -&gt; 1247793660.0 </code></pre> <p>See more details in <a href="http://stackoverflow.com/a/8778548/4279">another answer to similar question</a>.</p> <p>And back:</p> <pre><code>utc_dt = datetime.utcfromtimestamp(timestamp) # -&gt; datetime.datetime(2009, 7, 17, 1, 21) </code></pre>
0
2012-11-16T19:50:49Z
[ "python", "datetime", "iso8601", "unix-timestamp" ]
Why is there no first(iterable) built-in function in Python?
1,077,307
<p>I'm wondering if there's a reason that there's no <code>first(iterable)</code> in the Python built-in functions, somewhat similar to <code>any(iterable)</code> and <code>all(iterable)</code> (it may be tucked in a stdlib module somewhere, but I don't see it in <code>itertools</code>). <code>first</code> would perform a short-circuit generator evaluation so that unnecessary (and a potentially infinite number of) operations can be avoided; i.e.</p> <pre><code>def identity(item): return item def first(iterable, predicate=identity): for item in iterable: if predicate(item): return item raise ValueError('No satisfactory value found') </code></pre> <p>This way you can express things like:</p> <pre><code>denominators = (2, 3, 4, 5) lcd = first(i for i in itertools.count(1) if all(i % denominators == 0 for denominator in denominators)) </code></pre> <p>Clearly you can't do <code>list(generator)[0]</code> in that case, since the generator doesn't terminate.</p> <p>Or if you have a bunch of regexes to match against (useful when they all have the same <code>groupdict</code> interface):</p> <pre><code>match = first(regex.match(big_text) for regex in regexes) </code></pre> <p>You save a lot of unnecessary processing by avoiding <code>list(generator)[0]</code> and short-circuiting on a positive match.</p>
54
2009-07-03T00:07:07Z
1,077,320
<p>If you have an iterator, you can just call its <code>next</code> method. Something like:</p> <pre><code>In [3]: (5*x for x in xrange(2,4)).next() Out[3]: 10 </code></pre>
39
2009-07-03T00:18:22Z
[ "python", "iterator", "generator" ]
Why is there no first(iterable) built-in function in Python?
1,077,307
<p>I'm wondering if there's a reason that there's no <code>first(iterable)</code> in the Python built-in functions, somewhat similar to <code>any(iterable)</code> and <code>all(iterable)</code> (it may be tucked in a stdlib module somewhere, but I don't see it in <code>itertools</code>). <code>first</code> would perform a short-circuit generator evaluation so that unnecessary (and a potentially infinite number of) operations can be avoided; i.e.</p> <pre><code>def identity(item): return item def first(iterable, predicate=identity): for item in iterable: if predicate(item): return item raise ValueError('No satisfactory value found') </code></pre> <p>This way you can express things like:</p> <pre><code>denominators = (2, 3, 4, 5) lcd = first(i for i in itertools.count(1) if all(i % denominators == 0 for denominator in denominators)) </code></pre> <p>Clearly you can't do <code>list(generator)[0]</code> in that case, since the generator doesn't terminate.</p> <p>Or if you have a bunch of regexes to match against (useful when they all have the same <code>groupdict</code> interface):</p> <pre><code>match = first(regex.match(big_text) for regex in regexes) </code></pre> <p>You save a lot of unnecessary processing by avoiding <code>list(generator)[0]</code> and short-circuiting on a positive match.</p>
54
2009-07-03T00:07:07Z
1,077,330
<p>Haskell makes use of what you just described, as the function <code>take</code> (or as the partial function <code>take 1</code>, technically). <a href="http://my.safaribooksonline.com/0596001673/pythoncook-CHP-17-SECT-12" rel="nofollow">Python Cookbook</a> has generator-wrappers written that perform the same functionality as <code>take</code>, <code>takeWhile</code>, and <code>drop</code> in Haskell.</p> <p>But as to why that's not a built-in, your guess is as good as mine.</p>
4
2009-07-03T00:22:29Z
[ "python", "iterator", "generator" ]
Why is there no first(iterable) built-in function in Python?
1,077,307
<p>I'm wondering if there's a reason that there's no <code>first(iterable)</code> in the Python built-in functions, somewhat similar to <code>any(iterable)</code> and <code>all(iterable)</code> (it may be tucked in a stdlib module somewhere, but I don't see it in <code>itertools</code>). <code>first</code> would perform a short-circuit generator evaluation so that unnecessary (and a potentially infinite number of) operations can be avoided; i.e.</p> <pre><code>def identity(item): return item def first(iterable, predicate=identity): for item in iterable: if predicate(item): return item raise ValueError('No satisfactory value found') </code></pre> <p>This way you can express things like:</p> <pre><code>denominators = (2, 3, 4, 5) lcd = first(i for i in itertools.count(1) if all(i % denominators == 0 for denominator in denominators)) </code></pre> <p>Clearly you can't do <code>list(generator)[0]</code> in that case, since the generator doesn't terminate.</p> <p>Or if you have a bunch of regexes to match against (useful when they all have the same <code>groupdict</code> interface):</p> <pre><code>match = first(regex.match(big_text) for regex in regexes) </code></pre> <p>You save a lot of unnecessary processing by avoiding <code>list(generator)[0]</code> and short-circuiting on a positive match.</p>
54
2009-07-03T00:07:07Z
1,077,369
<p>There's some ambiguity in your question. Your definition of <strong>first</strong> and the regex example imply that there is a boolean test. But the denominators example explicitly has an if clause; so it's only a coincidence that each integer happens to be true.</p> <p>It looks like the combination of next and itertools.ifilter will give you what you want.</p> <pre><code>match = next(itertools.ifilter(None, (regex.match(big_text) for regex in regexes))) </code></pre>
6
2009-07-03T00:38:09Z
[ "python", "iterator", "generator" ]
Why is there no first(iterable) built-in function in Python?
1,077,307
<p>I'm wondering if there's a reason that there's no <code>first(iterable)</code> in the Python built-in functions, somewhat similar to <code>any(iterable)</code> and <code>all(iterable)</code> (it may be tucked in a stdlib module somewhere, but I don't see it in <code>itertools</code>). <code>first</code> would perform a short-circuit generator evaluation so that unnecessary (and a potentially infinite number of) operations can be avoided; i.e.</p> <pre><code>def identity(item): return item def first(iterable, predicate=identity): for item in iterable: if predicate(item): return item raise ValueError('No satisfactory value found') </code></pre> <p>This way you can express things like:</p> <pre><code>denominators = (2, 3, 4, 5) lcd = first(i for i in itertools.count(1) if all(i % denominators == 0 for denominator in denominators)) </code></pre> <p>Clearly you can't do <code>list(generator)[0]</code> in that case, since the generator doesn't terminate.</p> <p>Or if you have a bunch of regexes to match against (useful when they all have the same <code>groupdict</code> interface):</p> <pre><code>match = first(regex.match(big_text) for regex in regexes) </code></pre> <p>You save a lot of unnecessary processing by avoiding <code>list(generator)[0]</code> and short-circuiting on a positive match.</p>
54
2009-07-03T00:07:07Z
16,174,249
<p>There's a <a href="https://pypi.python.org/pypi/first">Pypi package called “first”</a> that does this:</p> <pre><code>&gt;&gt;&gt; from first import first &gt;&gt;&gt; first([0, None, False, [], (), 42]) 42 </code></pre> <p>Here's how you would use to return the first odd number, for example:</p> <pre><code>&gt;&gt; first([2, 14, 7, 41, 53], key=lambda x: x % 2 == 1) 7 </code></pre> <p>If you just want to return the first element from the iterator regardless of whether is true or not, do this:</p> <pre><code>&gt;&gt;&gt; first([0, None, False, [], (), 42], key=lambda x: True) 0 </code></pre> <p>It's a very small package: it only contains this function, it has no dependencies, and it works on Python 2 and 3. It's a single file, so you don't even have to install it to use it.</p> <p>In fact, here's almost the entire source code (from version 2.0.1, by Hynek Schlawack, released under the MIT licence):</p> <pre><code>def first(iterable, default=None, key=None): if key is None: for el in iterable: if el: return el else: for el in iterable: if key(el): return el return default </code></pre>
13
2013-04-23T16:11:47Z
[ "python", "iterator", "generator" ]
Why is there no first(iterable) built-in function in Python?
1,077,307
<p>I'm wondering if there's a reason that there's no <code>first(iterable)</code> in the Python built-in functions, somewhat similar to <code>any(iterable)</code> and <code>all(iterable)</code> (it may be tucked in a stdlib module somewhere, but I don't see it in <code>itertools</code>). <code>first</code> would perform a short-circuit generator evaluation so that unnecessary (and a potentially infinite number of) operations can be avoided; i.e.</p> <pre><code>def identity(item): return item def first(iterable, predicate=identity): for item in iterable: if predicate(item): return item raise ValueError('No satisfactory value found') </code></pre> <p>This way you can express things like:</p> <pre><code>denominators = (2, 3, 4, 5) lcd = first(i for i in itertools.count(1) if all(i % denominators == 0 for denominator in denominators)) </code></pre> <p>Clearly you can't do <code>list(generator)[0]</code> in that case, since the generator doesn't terminate.</p> <p>Or if you have a bunch of regexes to match against (useful when they all have the same <code>groupdict</code> interface):</p> <pre><code>match = first(regex.match(big_text) for regex in regexes) </code></pre> <p>You save a lot of unnecessary processing by avoiding <code>list(generator)[0]</code> and short-circuiting on a positive match.</p>
54
2009-07-03T00:07:07Z
18,226,144
<p>I asked a <a href="http://stackoverflow.com/questions/18208730/shortcut-or-chain-applied-on-list">similar question</a> recently (it got marked as a duplicate of this question by now). My concern also was that I'd liked to use built-ins <em>only</em> to solve the problem of finding the first true value of a generator. My own solution then was this:</p> <pre><code>x = next((v for v in (f(x) for x in a) if v), False) </code></pre> <p>For the example of finding the first regexp match (not the first matching pattern!) this would look like this:</p> <pre><code>patterns = [ r'\d+', r'\s+', r'\w+', r'.*' ] text = 'abc' firstMatch = next( (match for match in (re.match(pattern, text) for pattern in patterns) if match), False) </code></pre> <p>It does not evaluate the predicate twice (as you would have to do if just the pattern was returned) and it does not use hacks like locals in comprehensions.</p> <p>But it has two generators nested where the logic would dictate to use just one. So a better solution would be nice.</p>
8
2013-08-14T07:58:09Z
[ "python", "iterator", "generator" ]
Why is there no first(iterable) built-in function in Python?
1,077,307
<p>I'm wondering if there's a reason that there's no <code>first(iterable)</code> in the Python built-in functions, somewhat similar to <code>any(iterable)</code> and <code>all(iterable)</code> (it may be tucked in a stdlib module somewhere, but I don't see it in <code>itertools</code>). <code>first</code> would perform a short-circuit generator evaluation so that unnecessary (and a potentially infinite number of) operations can be avoided; i.e.</p> <pre><code>def identity(item): return item def first(iterable, predicate=identity): for item in iterable: if predicate(item): return item raise ValueError('No satisfactory value found') </code></pre> <p>This way you can express things like:</p> <pre><code>denominators = (2, 3, 4, 5) lcd = first(i for i in itertools.count(1) if all(i % denominators == 0 for denominator in denominators)) </code></pre> <p>Clearly you can't do <code>list(generator)[0]</code> in that case, since the generator doesn't terminate.</p> <p>Or if you have a bunch of regexes to match against (useful when they all have the same <code>groupdict</code> interface):</p> <pre><code>match = first(regex.match(big_text) for regex in regexes) </code></pre> <p>You save a lot of unnecessary processing by avoiding <code>list(generator)[0]</code> and short-circuiting on a positive match.</p>
54
2009-07-03T00:07:07Z
18,589,970
<p>There is a "slice" iterator in itertools. It emulates the slice operations that we're familiar with in python. What you're looking for is something similar to this:</p> <pre><code>myList = [0,1,2,3,4,5] firstValue = myList[:1] </code></pre> <p>The equivalent using itertools for iterators:</p> <pre><code>from itertools import islice def MyGenFunc(): for i in range(5): yield i mygen = MyGenFunc() firstValue = islice(mygen, 0, 1) print firstValue </code></pre>
3
2013-09-03T10:30:54Z
[ "python", "iterator", "generator" ]
Why is there no first(iterable) built-in function in Python?
1,077,307
<p>I'm wondering if there's a reason that there's no <code>first(iterable)</code> in the Python built-in functions, somewhat similar to <code>any(iterable)</code> and <code>all(iterable)</code> (it may be tucked in a stdlib module somewhere, but I don't see it in <code>itertools</code>). <code>first</code> would perform a short-circuit generator evaluation so that unnecessary (and a potentially infinite number of) operations can be avoided; i.e.</p> <pre><code>def identity(item): return item def first(iterable, predicate=identity): for item in iterable: if predicate(item): return item raise ValueError('No satisfactory value found') </code></pre> <p>This way you can express things like:</p> <pre><code>denominators = (2, 3, 4, 5) lcd = first(i for i in itertools.count(1) if all(i % denominators == 0 for denominator in denominators)) </code></pre> <p>Clearly you can't do <code>list(generator)[0]</code> in that case, since the generator doesn't terminate.</p> <p>Or if you have a bunch of regexes to match against (useful when they all have the same <code>groupdict</code> interface):</p> <pre><code>match = first(regex.match(big_text) for regex in regexes) </code></pre> <p>You save a lot of unnecessary processing by avoiding <code>list(generator)[0]</code> and short-circuiting on a positive match.</p>
54
2009-07-03T00:07:07Z
36,981,241
<p>Just use star unpacking in Python 3.4 for the last elements, then you got your first element.</p> <pre><code>x = [0, 1, 2, 3] first, *rest = x print(first) print(rest) </code></pre> <p>This is supported since Python 3.5. Read the PEP: <a href="https://www.python.org/dev/peps/pep-0448/" rel="nofollow">https://www.python.org/dev/peps/pep-0448/</a></p> <p>The variable first gets the first element from the list. All other items going into the variable rest.</p> <pre><code>x = [0, 1, 2, 3] first, *middle, end = x </code></pre> <p>This code packs the 0 into first, [1, 2] into middle and 3 in end.</p> <p>Finally this works also with generators:</p> <pre><code>def gen(): yield 1 yield 2 yield 3 yield 4 first, *rest = gen() </code></pre> <p>In first 1 is stored, rest contains [2, 3, 4].</p>
-1
2016-05-02T11:22:55Z
[ "python", "iterator", "generator" ]
Python Unix time doesn't work in Javascript
1,077,393
<p>In Python, using calendar.timegm(), I get a 10 digit result for a unix timestamp. When I put this into Javscript's setTime() function, it comes up with a date in 1970. It evidently needs a unix timestamp that is 13 digits long. How can this happen? Are they both counting from the same date? </p> <p>How can I use the same unix timestamp between these two languages?</p> <p>In Python:</p> <pre><code>In [60]: parseddate.utctimetuple() Out[60]: (2009, 7, 17, 1, 21, 0, 4, 198, 0) In [61]: calendar.timegm(parseddate.utctimetuple()) Out[61]: 1247793660 </code></pre> <p>In Firebug:</p> <pre><code>&gt;&gt;&gt; var d = new Date(); d.setTime(1247793660); d.toUTCString() "Thu, 15 Jan 1970 10:36:55 GMT" </code></pre>
6
2009-07-03T00:55:59Z
1,077,401
<p>Are you possibly mixing up seconds-since-1970 with milliseconds-since-1970?</p>
2
2009-07-03T00:59:42Z
[ "javascript", "python", "datetime", "utc", "unix-timestamp" ]
Python Unix time doesn't work in Javascript
1,077,393
<p>In Python, using calendar.timegm(), I get a 10 digit result for a unix timestamp. When I put this into Javscript's setTime() function, it comes up with a date in 1970. It evidently needs a unix timestamp that is 13 digits long. How can this happen? Are they both counting from the same date? </p> <p>How can I use the same unix timestamp between these two languages?</p> <p>In Python:</p> <pre><code>In [60]: parseddate.utctimetuple() Out[60]: (2009, 7, 17, 1, 21, 0, 4, 198, 0) In [61]: calendar.timegm(parseddate.utctimetuple()) Out[61]: 1247793660 </code></pre> <p>In Firebug:</p> <pre><code>&gt;&gt;&gt; var d = new Date(); d.setTime(1247793660); d.toUTCString() "Thu, 15 Jan 1970 10:36:55 GMT" </code></pre>
6
2009-07-03T00:55:59Z
1,077,402
<p>JavaScript <a href="https://developer.mozilla.org/en/Core%5FJavaScript%5F1.5%5FReference/Global%5FObjects/Date" rel="nofollow">Date constructor</a> works with milliseconds, you should multiply the Python unix time by 1000.</p> <pre><code>var unixTimestampSeg = 1247793660; var date = new Date(unixTimestampSeg*1000); </code></pre>
1
2009-07-03T01:00:10Z
[ "javascript", "python", "datetime", "utc", "unix-timestamp" ]
Python Unix time doesn't work in Javascript
1,077,393
<p>In Python, using calendar.timegm(), I get a 10 digit result for a unix timestamp. When I put this into Javscript's setTime() function, it comes up with a date in 1970. It evidently needs a unix timestamp that is 13 digits long. How can this happen? Are they both counting from the same date? </p> <p>How can I use the same unix timestamp between these two languages?</p> <p>In Python:</p> <pre><code>In [60]: parseddate.utctimetuple() Out[60]: (2009, 7, 17, 1, 21, 0, 4, 198, 0) In [61]: calendar.timegm(parseddate.utctimetuple()) Out[61]: 1247793660 </code></pre> <p>In Firebug:</p> <pre><code>&gt;&gt;&gt; var d = new Date(); d.setTime(1247793660); d.toUTCString() "Thu, 15 Jan 1970 10:36:55 GMT" </code></pre>
6
2009-07-03T00:55:59Z
1,077,403
<p>timegm is based on Unix's <a href="http://linux.about.com/library/cmd/blcmdl3%5Fgmtime.htm">gmtime()</a> method, which return seconds since Jan 1, 1970.</p> <p>Javascripts <a href="http://www.w3schools.com/jsref/jsref%5FsetTime.asp">setTime()</a> method is milliseconds since that date. You'll need to multiply your seconds times 1000 to convert to the format expected by Javascript.</p>
11
2009-07-03T01:00:52Z
[ "javascript", "python", "datetime", "utc", "unix-timestamp" ]
Python Unix time doesn't work in Javascript
1,077,393
<p>In Python, using calendar.timegm(), I get a 10 digit result for a unix timestamp. When I put this into Javscript's setTime() function, it comes up with a date in 1970. It evidently needs a unix timestamp that is 13 digits long. How can this happen? Are they both counting from the same date? </p> <p>How can I use the same unix timestamp between these two languages?</p> <p>In Python:</p> <pre><code>In [60]: parseddate.utctimetuple() Out[60]: (2009, 7, 17, 1, 21, 0, 4, 198, 0) In [61]: calendar.timegm(parseddate.utctimetuple()) Out[61]: 1247793660 </code></pre> <p>In Firebug:</p> <pre><code>&gt;&gt;&gt; var d = new Date(); d.setTime(1247793660); d.toUTCString() "Thu, 15 Jan 1970 10:36:55 GMT" </code></pre>
6
2009-07-03T00:55:59Z
1,077,414
<p>Here are a couple of python methods I use to convert to and from javascript/datetime.</p> <pre><code>def to_datetime(js_timestamp): return datetime.datetime.fromtimestamp(js_timestamp/1000) def js_timestamp_from_datetime(dt): return 1000 * time.mktime(dt.timetuple()) </code></pre> <p>In javascript you would do:</p> <pre><code>var dt = new Date(); dt.setTime(js_timestamp); </code></pre>
8
2009-07-03T01:07:04Z
[ "javascript", "python", "datetime", "utc", "unix-timestamp" ]
Python Unicode UnicodeEncodeError
1,077,564
<p>I am having issues with trying to convert an UTF-8 string to unicode. I get the error.</p> <pre><code>UnicodeEncodeError: 'ascii' codec can't encode characters in position 73-75: ordinal not in range(128) </code></pre> <p>I tried wrapping this in a <code>try</code>/<code>except</code> block but then google was giving me a system administrator error which was one line. Can someone suggest how to catch this error and continue.</p> <p>Cheers, John.</p> <p><strong>-- FULL ERROR --</strong></p> <pre><code>Traceback (most recent call last): File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/ext/webapp/__init__.py", line 501, in __call__ handler.get(*groups) File "/Users/johnb/Sites/hurl/hurl.py", line 153, in get self.redirect(url.long_url) File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/ext/webapp/__init__.py", line 371, in redirect self.response.headers['Location'] = str(absolute_url) UnicodeEncodeError: 'ascii' codec can't encode characters in position 73-75: ordinal not in range(128) </code></pre>
1
2009-07-03T02:33:04Z
1,077,575
<p>Try this:</p> <pre><code>self.response.headers['Location'] = absolute_url.decode("utf-8") or self.response.headers['Location'] = unicode(absolute_url, "utf-8") </code></pre>
-1
2009-07-03T02:40:16Z
[ "python", "google-app-engine", "unicode", "utf-8" ]
Python Unicode UnicodeEncodeError
1,077,564
<p>I am having issues with trying to convert an UTF-8 string to unicode. I get the error.</p> <pre><code>UnicodeEncodeError: 'ascii' codec can't encode characters in position 73-75: ordinal not in range(128) </code></pre> <p>I tried wrapping this in a <code>try</code>/<code>except</code> block but then google was giving me a system administrator error which was one line. Can someone suggest how to catch this error and continue.</p> <p>Cheers, John.</p> <p><strong>-- FULL ERROR --</strong></p> <pre><code>Traceback (most recent call last): File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/ext/webapp/__init__.py", line 501, in __call__ handler.get(*groups) File "/Users/johnb/Sites/hurl/hurl.py", line 153, in get self.redirect(url.long_url) File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/ext/webapp/__init__.py", line 371, in redirect self.response.headers['Location'] = str(absolute_url) UnicodeEncodeError: 'ascii' codec can't encode characters in position 73-75: ordinal not in range(128) </code></pre>
1
2009-07-03T02:33:04Z
1,077,582
<p>Please edit that mess so that it's legible. Hint: use the "code block" (101010 thingy button).</p> <p>You say that you are "trying to convert an UTF-8 string to unicode" but <code>str(absolute_url)</code> is a strange way of going about it. Are you sure that <code>absolute_url</code> is UTF-8? Try </p> <pre><code>print type(absolute_url) print repr(absolute_url) </code></pre> <p>If it <em>is</em> UTF-8, you need <code>absolute_url.decode('utf8')</code></p>
1
2009-07-03T02:45:36Z
[ "python", "google-app-engine", "unicode", "utf-8" ]
Python Unicode UnicodeEncodeError
1,077,564
<p>I am having issues with trying to convert an UTF-8 string to unicode. I get the error.</p> <pre><code>UnicodeEncodeError: 'ascii' codec can't encode characters in position 73-75: ordinal not in range(128) </code></pre> <p>I tried wrapping this in a <code>try</code>/<code>except</code> block but then google was giving me a system administrator error which was one line. Can someone suggest how to catch this error and continue.</p> <p>Cheers, John.</p> <p><strong>-- FULL ERROR --</strong></p> <pre><code>Traceback (most recent call last): File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/ext/webapp/__init__.py", line 501, in __call__ handler.get(*groups) File "/Users/johnb/Sites/hurl/hurl.py", line 153, in get self.redirect(url.long_url) File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/ext/webapp/__init__.py", line 371, in redirect self.response.headers['Location'] = str(absolute_url) UnicodeEncodeError: 'ascii' codec can't encode characters in position 73-75: ordinal not in range(128) </code></pre>
1
2009-07-03T02:33:04Z
1,077,590
<p>The location header you are trying to set needs to be an Url, and an Url needs to be in Ascii. Since your Url is not an Ascii string you get the error. Just catching the error won't help since the Location header won't work with an invalid Url.</p> <p>When you create <code>absolute_url</code> you need to make sure it is encoded properly, best by using <a href="http://docs.python.org/library/urllib.html#urllib.quote" rel="nofollow"><code>urllib.quote</code></a> and the strings <a href="http://docs.python.org/library/stdtypes.html#str.encode" rel="nofollow"><code>encode()</code></a> method. You can try this:</p> <pre><code>self.response.headers['Location'] = urllib.quote(absolute_url.encode('utf-8')) </code></pre>
4
2009-07-03T02:51:38Z
[ "python", "google-app-engine", "unicode", "utf-8" ]
Python Unicode UnicodeEncodeError
1,077,564
<p>I am having issues with trying to convert an UTF-8 string to unicode. I get the error.</p> <pre><code>UnicodeEncodeError: 'ascii' codec can't encode characters in position 73-75: ordinal not in range(128) </code></pre> <p>I tried wrapping this in a <code>try</code>/<code>except</code> block but then google was giving me a system administrator error which was one line. Can someone suggest how to catch this error and continue.</p> <p>Cheers, John.</p> <p><strong>-- FULL ERROR --</strong></p> <pre><code>Traceback (most recent call last): File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/ext/webapp/__init__.py", line 501, in __call__ handler.get(*groups) File "/Users/johnb/Sites/hurl/hurl.py", line 153, in get self.redirect(url.long_url) File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/ext/webapp/__init__.py", line 371, in redirect self.response.headers['Location'] = str(absolute_url) UnicodeEncodeError: 'ascii' codec can't encode characters in position 73-75: ordinal not in range(128) </code></pre>
1
2009-07-03T02:33:04Z
1,077,646
<p>The correct <a href="http://www.nabble.com/Re:-Problem:-neither-urllib2.quote-nor-urllib.quote-encode-the--unicode-strings-arguments-p19823144.html">solution</a> is to do the following:</p> <pre><code>self.response.headers['Location'] = urllib.quote(absolute_url.encode("utf-8")) </code></pre>
8
2009-07-03T03:22:24Z
[ "python", "google-app-engine", "unicode", "utf-8" ]
Windows Application Programming & wxPython
1,077,649
<p>Developing a project of mine I realize I have a need for some level of persistence across sessions, for example when a user executes the application, changes some preferences and then closes the app. The next time the user executes the app, be it after a reboot or 15 minutes, I would like to be able to retain the preferences that had been changed. </p> <p>My question relates to this persistence. Whether programming an application using the win32 API or the MFC Framework .. or using the newer tools for higher level languages such as wxPython or wxRuby, how does one maintain the type of persistence I refer to? Is it done as a temporary file written to the disk? Is it saved into some registry setting? Is there some other layer it is stored in that I am unaware of?</p>
1
2009-07-03T03:24:31Z
1,077,657
<p>There are different methods to do this that have evolved over the years.</p> <p>These methods include (but not limited to):</p> <ol> <li>Registry entries.</li> <li>INI files.</li> <li>XML Files</li> <li>Simple binary/text files</li> <li>Databases</li> </ol> <p>Nowadays, most people do this kind of thing with XML files residing in the user specific AppData folders. It is your choice how you do it. For example, for simple things, databases can be overkill and for huge persisted objects, registry would not be appropriate. You have to see what you are doing and do it accordingly.</p> <p><a href="http://stackoverflow.com/questions/268424/when-and-why-should-you-store-data-in-the-windows-registry">Here is a very good discussion</a> on this topic</p>
1
2009-07-03T03:28:49Z
[ "python", "windows", "wxpython" ]
Windows Application Programming & wxPython
1,077,649
<p>Developing a project of mine I realize I have a need for some level of persistence across sessions, for example when a user executes the application, changes some preferences and then closes the app. The next time the user executes the app, be it after a reboot or 15 minutes, I would like to be able to retain the preferences that had been changed. </p> <p>My question relates to this persistence. Whether programming an application using the win32 API or the MFC Framework .. or using the newer tools for higher level languages such as wxPython or wxRuby, how does one maintain the type of persistence I refer to? Is it done as a temporary file written to the disk? Is it saved into some registry setting? Is there some other layer it is stored in that I am unaware of?</p>
1
2009-07-03T03:24:31Z
1,077,697
<p>I would advice to do it in two steps.</p> <ol> <li><p>First step is to save your prefs. as string, for that you can</p> <p>a) Use any xml lib or output xml by hand to output string and read similarly from string</p> <p>b) Just use pickle module to dump your prefs object as a string</p> <p>c) Somehow generate a string from prefs which you can read back as prefs e.g. use yaml, config , JSON etc actually JSON is a good option when simplejson makes it so easy.</p></li> <li><p>Once you have your methods to convert to and from string are ready, you just need to store it somewhere where it is persisted and you can read back next time, for that you can</p> <p>a) Use wx.Config which save to registry in windows and to other places depending on platform so you don't have to worry where it saves, you can just read back values in platform independent way. <strong>But if you wish you can just use wx.Config for directly saving reading prefs.</strong></p> <p>b) Directly save prefs. string to a file in a folder assigned by OS to your app e.g. app data folder in windows.</p></li> </ol> <p>Benefit of saving to a string and than using wx.Config to save it, is that you can easily change where data is saved in future e.g. in future if there is a need to upload prefs. you can just upload prefs. string.</p>
3
2009-07-03T03:58:40Z
[ "python", "windows", "wxpython" ]
How to open a file on app engine patch?
1,077,691
<p>I tried to read a file in a view like this:</p> <pre><code>def foo(request): f = open('foo.txt', 'r') data = f.read() return HttpResponse(data) </code></pre> <p>I tried to place the foo.txt in almost every folder in the project but it still returns</p> <blockquote> <p>[Errno 2] No such file or directory: 'foo.txt'</p> </blockquote> <p>So does anybody knows how to open a file in app engine patch? Where should i place the files i wish to open? many thanks. I'm using app-engine-patch 1.1beta1</p>
0
2009-07-03T03:54:38Z
1,077,743
<p>In App Engine, patch or otherwise, you should be able to open (read-only) any file that gets uploaded with your app's sources. Is 'foo.txt' in the same directory as the py file? Does it get uploaded (what does your app.yaml say?)?</p>
2
2009-07-03T04:19:23Z
[ "python", "django", "google-app-engine" ]
How to open a file on app engine patch?
1,077,691
<p>I tried to read a file in a view like this:</p> <pre><code>def foo(request): f = open('foo.txt', 'r') data = f.read() return HttpResponse(data) </code></pre> <p>I tried to place the foo.txt in almost every folder in the project but it still returns</p> <blockquote> <p>[Errno 2] No such file or directory: 'foo.txt'</p> </blockquote> <p>So does anybody knows how to open a file in app engine patch? Where should i place the files i wish to open? many thanks. I'm using app-engine-patch 1.1beta1</p>
0
2009-07-03T03:54:38Z
2,678,621
<p>You should try f = open('./foo.txt', 'r')</p>
0
2010-04-20T21:06:15Z
[ "python", "django", "google-app-engine" ]
How to open a file on app engine patch?
1,077,691
<p>I tried to read a file in a view like this:</p> <pre><code>def foo(request): f = open('foo.txt', 'r') data = f.read() return HttpResponse(data) </code></pre> <p>I tried to place the foo.txt in almost every folder in the project but it still returns</p> <blockquote> <p>[Errno 2] No such file or directory: 'foo.txt'</p> </blockquote> <p>So does anybody knows how to open a file in app engine patch? Where should i place the files i wish to open? many thanks. I'm using app-engine-patch 1.1beta1</p>
0
2009-07-03T03:54:38Z
3,108,688
<p>Put './' in front of your file path:</p> <pre><code>f = open('./foo.txt') </code></pre> <p>If you don't, it will still work in App Engine Launcher 1.3.4, which could be confusing, but once you upload it, you'll get an error.</p> <p>Also it seems that you shouldn't mention the file (or its dir) you want to access in app.yaml. I'm including css, js and html in my app this way.</p>
1
2010-06-24T09:29:29Z
[ "python", "django", "google-app-engine" ]
Tkinter button bind and parent deatroy
1,077,932
<p>This is my code :</p> <pre><code> print '1' from Tkinter import * print '2' class myApp: print '3' def __init__(self,parent): print '4' ## self.myparent = parent line1 print '11' self.myContainer1 = Frame(parent) print '12' self.myContainer1.pack() print '13' self.button1 = Button(self.myContainer1,text="OK",background="green") print '14' self.button1.pack(side=LEFT) print '15' self.button1.bind("&lt;Button-1&gt;",self.button1Click) print '16' self.button2 = Button(self.myContainer1,text="Cancel",background="cyan") print '17' self.button2.pack(side=RIGHT) print '18' self.button2.bind("&lt;Button-1&gt;",self.button2Click) print '19' def button1Click(self,event): print '5' if self.button1['background'] == 'green': print '20' self.button1['background'] ='tan' print '21' else: print '22' self.button1['background'] = 'yellow' print '23' def button2Click(self,event): print '6' ## self.myparent.destroy() self.parent.destroy() print '7' root = Tk() print '8' myapp = myApp(root) print '9' root.mainloop() print '10' </code></pre> <p>Error is :</p> <pre><code> &gt;&gt;&gt; ================================ RESTART ================================ &gt;&gt;&gt; 1 2 3 7 8 4 11 12 13 14 15 16 17 18 19 9 5 20 21 5 22 23 6 Exception in Tkinter callback Traceback (most recent call last): File "C:\Python26\lib\lib-tk\Tkinter.py", line 1403, in __call__ return self.func(*args) File "C:\Documents and Settings\he00044.HALEDGEWOOD\Desktop\TkinterExamples\buttonBind.py", line 56, in button2Click self.parent.destroy() AttributeError: myApp instance has no attribute 'parent' 10 &gt;&gt;&gt; </code></pre> <p>This is when i comment line1</p> <p>It may be becoz myapp is not finding parent.</p> <p>But the concept is not clear.</p> <p>Can anybody explain the concept in detail....</p>
0
2009-07-03T05:58:37Z
1,077,969
<p>Assign the incoming parameter parent to self.parent?</p> <pre><code>def __init__(self,parent): self.parent = parent </code></pre>
0
2009-07-03T06:19:03Z
[ "python", "tkinter" ]
Tkinter button bind and parent deatroy
1,077,932
<p>This is my code :</p> <pre><code> print '1' from Tkinter import * print '2' class myApp: print '3' def __init__(self,parent): print '4' ## self.myparent = parent line1 print '11' self.myContainer1 = Frame(parent) print '12' self.myContainer1.pack() print '13' self.button1 = Button(self.myContainer1,text="OK",background="green") print '14' self.button1.pack(side=LEFT) print '15' self.button1.bind("&lt;Button-1&gt;",self.button1Click) print '16' self.button2 = Button(self.myContainer1,text="Cancel",background="cyan") print '17' self.button2.pack(side=RIGHT) print '18' self.button2.bind("&lt;Button-1&gt;",self.button2Click) print '19' def button1Click(self,event): print '5' if self.button1['background'] == 'green': print '20' self.button1['background'] ='tan' print '21' else: print '22' self.button1['background'] = 'yellow' print '23' def button2Click(self,event): print '6' ## self.myparent.destroy() self.parent.destroy() print '7' root = Tk() print '8' myapp = myApp(root) print '9' root.mainloop() print '10' </code></pre> <p>Error is :</p> <pre><code> &gt;&gt;&gt; ================================ RESTART ================================ &gt;&gt;&gt; 1 2 3 7 8 4 11 12 13 14 15 16 17 18 19 9 5 20 21 5 22 23 6 Exception in Tkinter callback Traceback (most recent call last): File "C:\Python26\lib\lib-tk\Tkinter.py", line 1403, in __call__ return self.func(*args) File "C:\Documents and Settings\he00044.HALEDGEWOOD\Desktop\TkinterExamples\buttonBind.py", line 56, in button2Click self.parent.destroy() AttributeError: myApp instance has no attribute 'parent' 10 &gt;&gt;&gt; </code></pre> <p>This is when i comment line1</p> <p>It may be becoz myapp is not finding parent.</p> <p>But the concept is not clear.</p> <p>Can anybody explain the concept in detail....</p>
0
2009-07-03T05:58:37Z
1,077,987
<p>Why ever did you comment out those two lines mentioning <code>self.myparent</code> and create a new one mentioning a mysterious, never-initialized <code>self.parent</code>?! That's the start of your problem, of course -- looks like absurd, deliberate sabotage of code.</p>
2
2009-07-03T06:23:14Z
[ "python", "tkinter" ]
Tkinter button bind and parent deatroy
1,077,932
<p>This is my code :</p> <pre><code> print '1' from Tkinter import * print '2' class myApp: print '3' def __init__(self,parent): print '4' ## self.myparent = parent line1 print '11' self.myContainer1 = Frame(parent) print '12' self.myContainer1.pack() print '13' self.button1 = Button(self.myContainer1,text="OK",background="green") print '14' self.button1.pack(side=LEFT) print '15' self.button1.bind("&lt;Button-1&gt;",self.button1Click) print '16' self.button2 = Button(self.myContainer1,text="Cancel",background="cyan") print '17' self.button2.pack(side=RIGHT) print '18' self.button2.bind("&lt;Button-1&gt;",self.button2Click) print '19' def button1Click(self,event): print '5' if self.button1['background'] == 'green': print '20' self.button1['background'] ='tan' print '21' else: print '22' self.button1['background'] = 'yellow' print '23' def button2Click(self,event): print '6' ## self.myparent.destroy() self.parent.destroy() print '7' root = Tk() print '8' myapp = myApp(root) print '9' root.mainloop() print '10' </code></pre> <p>Error is :</p> <pre><code> &gt;&gt;&gt; ================================ RESTART ================================ &gt;&gt;&gt; 1 2 3 7 8 4 11 12 13 14 15 16 17 18 19 9 5 20 21 5 22 23 6 Exception in Tkinter callback Traceback (most recent call last): File "C:\Python26\lib\lib-tk\Tkinter.py", line 1403, in __call__ return self.func(*args) File "C:\Documents and Settings\he00044.HALEDGEWOOD\Desktop\TkinterExamples\buttonBind.py", line 56, in button2Click self.parent.destroy() AttributeError: myApp instance has no attribute 'parent' 10 &gt;&gt;&gt; </code></pre> <p>This is when i comment line1</p> <p>It may be becoz myapp is not finding parent.</p> <p>But the concept is not clear.</p> <p>Can anybody explain the concept in detail....</p>
0
2009-07-03T05:58:37Z
1,078,173
<p>Your question is not tkinter related, it's rather about object oriented design.</p> <p>Class <strong>myApp</strong> has <strong>__init__</strong> method (constructor, the method that executes when object of that class is created), as well as two methods for button clicks. In button2Click method, you attempt to read attribute <strong>self.parent</strong> (translating as <strong>myapp.parent</strong>), but this property is not defined.</p> <p>When you uncomment line 1, you won't get the error. This is because you are creating attribute <strong>myapp.parent</strong>, and you are assigning the Tk root widget to this attribute. This is necessary as all widgets you create have to receive their parent widget.</p>
0
2009-07-03T07:25:15Z
[ "python", "tkinter" ]
Tkinter button bind and parent deatroy
1,077,932
<p>This is my code :</p> <pre><code> print '1' from Tkinter import * print '2' class myApp: print '3' def __init__(self,parent): print '4' ## self.myparent = parent line1 print '11' self.myContainer1 = Frame(parent) print '12' self.myContainer1.pack() print '13' self.button1 = Button(self.myContainer1,text="OK",background="green") print '14' self.button1.pack(side=LEFT) print '15' self.button1.bind("&lt;Button-1&gt;",self.button1Click) print '16' self.button2 = Button(self.myContainer1,text="Cancel",background="cyan") print '17' self.button2.pack(side=RIGHT) print '18' self.button2.bind("&lt;Button-1&gt;",self.button2Click) print '19' def button1Click(self,event): print '5' if self.button1['background'] == 'green': print '20' self.button1['background'] ='tan' print '21' else: print '22' self.button1['background'] = 'yellow' print '23' def button2Click(self,event): print '6' ## self.myparent.destroy() self.parent.destroy() print '7' root = Tk() print '8' myapp = myApp(root) print '9' root.mainloop() print '10' </code></pre> <p>Error is :</p> <pre><code> &gt;&gt;&gt; ================================ RESTART ================================ &gt;&gt;&gt; 1 2 3 7 8 4 11 12 13 14 15 16 17 18 19 9 5 20 21 5 22 23 6 Exception in Tkinter callback Traceback (most recent call last): File "C:\Python26\lib\lib-tk\Tkinter.py", line 1403, in __call__ return self.func(*args) File "C:\Documents and Settings\he00044.HALEDGEWOOD\Desktop\TkinterExamples\buttonBind.py", line 56, in button2Click self.parent.destroy() AttributeError: myApp instance has no attribute 'parent' 10 &gt;&gt;&gt; </code></pre> <p>This is when i comment line1</p> <p>It may be becoz myapp is not finding parent.</p> <p>But the concept is not clear.</p> <p>Can anybody explain the concept in detail....</p>
0
2009-07-03T05:58:37Z
1,078,281
<p>The other answers so far are great. <br /> This may also help: <a href="http://www.pythonware.com/library/tkinter/introduction/" rel="nofollow">Fredrik Lundh's intro to Tkinter</a>.</p> <p>Added some comments to your code that, along with the other answers, should help get you moving again: </p> <pre><code>import Tkinter class MyApp: def __init__(self, parent): # constructor self.parent = parent # the parent here is 'root' self.myContainer1 = Tkinter.Frame(self.parent) # create Frame w/ root as parent self.myContainer1.pack() # make Frame (myContainer1) visible self.button1 = Tkinter.Button(self.myContainer1, text="OK", background="green") # add button as child of Frame self.button1.pack(side=Tkinter.LEFT) # place button1 in Frame self.button1.bind("&lt;Button-1&gt;",self.button1Click) # bind left mouse button to button1Click method self.button2 = Tkinter.Button(self.myContainer1, text="Cancel", background="cyan") self.button2.pack(side=Tkinter.RIGHT) self.button2.bind("&lt;Button-1&gt;", self.button2Click) def button1Click(self, event): if self.button1['background'] == 'green': self.button1['background'] ='tan' else: self.button1['background'] = 'yellow' def button2Click(self, event): self.parent.destroy() # the parent here is 'root', so you're ending the event loop root = Tkinter.Tk() # create root widget (a window) myapp = MyApp(root) # create instance of MyApp with root as the parent root.mainloop() # create event loop (ends when window is closed) </code></pre>
0
2009-07-03T07:58:40Z
[ "python", "tkinter" ]
Handling exceptions without try block in Python's interactive shell
1,078,054
<p>See the title of this question. I want to play with the exception raised in the last command. <code>_</code> didn't help me. Is there anything like that?</p>
2
2009-07-03T06:51:21Z
1,078,077
<p>Do this:</p> <pre><code>import sys sys.exc_info() </code></pre> <p>It will give you information about the exception. It's a tuple containing the exception type, the exception instance and a traceback object. </p>
5
2009-07-03T06:56:37Z
[ "python", "command-line", "exception-handling", "interactive-mode" ]
pymacs: General question and Installation problem
1,078,069
<p>I am trying to setup emacs for python development. </p> <p>From what I read, it is recommended to use python-mode.el rather than the default python.el from Emacs 22.3. So I embark on the new adventure.</p> <p>From what I understand, python-mode has the several dependencies, so I need to install rope, ropemode and ropemacs. Then on top of that I need to install pymacs. </p> <p><strong>Q: is it correct?</strong></p> <p>This is my new .emacs now:</p> <pre><code>(custom-set-variables ;; custom-set-variables was added by Custom. ;; If you edit it by hand, you could mess it up, so be careful. ;; Your init file should contain only one such instance. ;; If there is more than one, they won't work right. '(inhibit-startup-screen t) '(tab-width 4)) (custom-set-faces ;; custom-set-faces was added by Custom. ;; If you edit it by hand, you could mess it up, so be careful. ;; Your init file should contain only one such instance. ;; If there is more than one, they won't work right. ) (setq emacs-config-path "~/.emacs.d/") (setq base-lisp-path "~/.emacs.d/site-lisp/") (setq site-lisp-path (concat emacs-config-path "/site-lisp")) (defun add-path (p) (add-to-list 'load-path (concat base-lisp-path p))) (add-path "") (add-to-list 'load-path "~/.emacs.d") (require 'psvn) ;; python-mode ;; (setq auto-mode-alist (cons '("\\.py$" . python-mode) auto-mode-alist)) (setq interpreter-mode-alist (cons '("python" . python-mode) interpreter-mode-alist)) (autoload 'python-mode "python-mode" "Python editing mode." t) (setq pymacs-load-path '( "~/.emacs.d/site-lisp/rope" "~/.emacs.d/site-lisp/ropemode" "~/.emacs.d/site-lisp/ropemacs")) (setq interpreter-mode-alist (cons '("python" . python-mode) interpreter-mode-alist) python-mode-hook '(lambda () (progn (set-variable 'py-indent-offset 4) (set-variable 'py-smart-indentation nil) (set-variable 'indent-tabs-mode nil) ;;(highlight-beyond-fill-column) (define-key python-mode-map "\C-m" 'newline-and-indent) (pabbrev-mode) (abbrev-mode) ) ) ) ;; pymacs (autoload 'pymacs-apply "pymacs") (autoload 'pymacs-call "pymacs") (autoload 'pymacs-eval "pymacs" nil t) (autoload 'pymacs-exec "pymacs" nil t) (autoload 'pymacs-load "pymacs" nil t) ;; Search local path for emacs rope ;; ;; enable pymacs ;; (require 'pymacs) (pymacs-load "ropemacs" "rope-") </code></pre> <p>Now, when i start emacs, I got this error message:</p> <pre><code>("C:\\opt\\emacs-22.3\\bin\\emacs.exe") Loading encoded-kb...done Loading regexp-opt...done Loading easy-mmode...done Loading wid-edit...done Loading edmacro...done Loading derived...done Loading advice...done Loading cl-macs...done Loading byte-opt...done An error has occurred while loading `c:/opt/cygwin/home/akong/.emacs': File error: Cannot open load file, pymacs To ensure normal operation, you should investigate and remove the cause of the error in your initialization file. Start Emacs with the `--debug-init' option to view a complete error backtrace. For information about GNU Emacs and the GNU system, type C-h C-a. [2 times] </code></pre> <p>To make it slightly more complicated:</p> <p>For work reason I have to use python 2.4, but I have python 2.6 installed on my PC. But obviously rope does not like 2.4 so I did not run setup.py. I untar/unzip these packages and put these files under ~/.emacs.d/site-lisp. By default if python is invoked in command prompt, it is the python 2.4 executable.</p> <p><strong>Q: How can I successfully load 'pymacs'?</strong></p>
6
2009-07-03T06:55:40Z
1,078,183
<p>I have never used pymacs so far, but one thing which catches my eye when I look at your <code>.emacs</code> is that you apparently didn't add the pymacs directory to the <em>emacs</em> <code>load-path</code> but only to the <code>pymacs</code> one:</p> <pre><code>(setq pymacs-load-path '( "~/.emacs.d/site-lisp/rope" "~/.emacs.d/site-lisp/ropemode" "~/.emacs.d/site-lisp/ropemacs")) </code></pre> <p>You will probably need also something like:</p> <pre><code>(add-to-list 'load-path "~/.emacs.d/site-lisp/rope") (add-to-list 'load-path "~/.emacs.d/site-lisp/ropemode") (add-to-list 'load-path "~/.emacs.d/site-lisp/ropemacs") </code></pre> <p>(or whereever you have <code>pymacs.el</code>) so that emacs can find the lisp files. Also mentioned in the <a href="http://pymacs.progiciels-bpi.ca/pymacs.html#check-the-search-paths" rel="nofollow">pymacs documentation</a></p> <blockquote> <p>2.4 Install the Pymacs proper ... for the Emacs part ...</p> <p>This is usually done by hand now. First select some directory along the list kept in your Emacs <em>load-path</em>, for which you have write access, and copy file pymacs.el in that directory.</p> </blockquote>
1
2009-07-03T07:28:47Z
[ "python", "emacs", "rope", "pymacs" ]
pymacs: General question and Installation problem
1,078,069
<p>I am trying to setup emacs for python development. </p> <p>From what I read, it is recommended to use python-mode.el rather than the default python.el from Emacs 22.3. So I embark on the new adventure.</p> <p>From what I understand, python-mode has the several dependencies, so I need to install rope, ropemode and ropemacs. Then on top of that I need to install pymacs. </p> <p><strong>Q: is it correct?</strong></p> <p>This is my new .emacs now:</p> <pre><code>(custom-set-variables ;; custom-set-variables was added by Custom. ;; If you edit it by hand, you could mess it up, so be careful. ;; Your init file should contain only one such instance. ;; If there is more than one, they won't work right. '(inhibit-startup-screen t) '(tab-width 4)) (custom-set-faces ;; custom-set-faces was added by Custom. ;; If you edit it by hand, you could mess it up, so be careful. ;; Your init file should contain only one such instance. ;; If there is more than one, they won't work right. ) (setq emacs-config-path "~/.emacs.d/") (setq base-lisp-path "~/.emacs.d/site-lisp/") (setq site-lisp-path (concat emacs-config-path "/site-lisp")) (defun add-path (p) (add-to-list 'load-path (concat base-lisp-path p))) (add-path "") (add-to-list 'load-path "~/.emacs.d") (require 'psvn) ;; python-mode ;; (setq auto-mode-alist (cons '("\\.py$" . python-mode) auto-mode-alist)) (setq interpreter-mode-alist (cons '("python" . python-mode) interpreter-mode-alist)) (autoload 'python-mode "python-mode" "Python editing mode." t) (setq pymacs-load-path '( "~/.emacs.d/site-lisp/rope" "~/.emacs.d/site-lisp/ropemode" "~/.emacs.d/site-lisp/ropemacs")) (setq interpreter-mode-alist (cons '("python" . python-mode) interpreter-mode-alist) python-mode-hook '(lambda () (progn (set-variable 'py-indent-offset 4) (set-variable 'py-smart-indentation nil) (set-variable 'indent-tabs-mode nil) ;;(highlight-beyond-fill-column) (define-key python-mode-map "\C-m" 'newline-and-indent) (pabbrev-mode) (abbrev-mode) ) ) ) ;; pymacs (autoload 'pymacs-apply "pymacs") (autoload 'pymacs-call "pymacs") (autoload 'pymacs-eval "pymacs" nil t) (autoload 'pymacs-exec "pymacs" nil t) (autoload 'pymacs-load "pymacs" nil t) ;; Search local path for emacs rope ;; ;; enable pymacs ;; (require 'pymacs) (pymacs-load "ropemacs" "rope-") </code></pre> <p>Now, when i start emacs, I got this error message:</p> <pre><code>("C:\\opt\\emacs-22.3\\bin\\emacs.exe") Loading encoded-kb...done Loading regexp-opt...done Loading easy-mmode...done Loading wid-edit...done Loading edmacro...done Loading derived...done Loading advice...done Loading cl-macs...done Loading byte-opt...done An error has occurred while loading `c:/opt/cygwin/home/akong/.emacs': File error: Cannot open load file, pymacs To ensure normal operation, you should investigate and remove the cause of the error in your initialization file. Start Emacs with the `--debug-init' option to view a complete error backtrace. For information about GNU Emacs and the GNU system, type C-h C-a. [2 times] </code></pre> <p>To make it slightly more complicated:</p> <p>For work reason I have to use python 2.4, but I have python 2.6 installed on my PC. But obviously rope does not like 2.4 so I did not run setup.py. I untar/unzip these packages and put these files under ~/.emacs.d/site-lisp. By default if python is invoked in command prompt, it is the python 2.4 executable.</p> <p><strong>Q: How can I successfully load 'pymacs'?</strong></p>
6
2009-07-03T06:55:40Z
1,085,313
<p>It turns out I missed these two:</p> <pre><code>(add-to-list 'load-path "~/.emacs.d/site-lisp/Pymacs-0.23") </code></pre> <p>Obviously I need to load the pymac script.</p> <p>And I have set the env var PYMACS_PYTHON to python 2.6 because I am using python 2.4 as default python interpreter, for work reason.</p>
1
2009-07-06T03:38:31Z
[ "python", "emacs", "rope", "pymacs" ]
pymacs: General question and Installation problem
1,078,069
<p>I am trying to setup emacs for python development. </p> <p>From what I read, it is recommended to use python-mode.el rather than the default python.el from Emacs 22.3. So I embark on the new adventure.</p> <p>From what I understand, python-mode has the several dependencies, so I need to install rope, ropemode and ropemacs. Then on top of that I need to install pymacs. </p> <p><strong>Q: is it correct?</strong></p> <p>This is my new .emacs now:</p> <pre><code>(custom-set-variables ;; custom-set-variables was added by Custom. ;; If you edit it by hand, you could mess it up, so be careful. ;; Your init file should contain only one such instance. ;; If there is more than one, they won't work right. '(inhibit-startup-screen t) '(tab-width 4)) (custom-set-faces ;; custom-set-faces was added by Custom. ;; If you edit it by hand, you could mess it up, so be careful. ;; Your init file should contain only one such instance. ;; If there is more than one, they won't work right. ) (setq emacs-config-path "~/.emacs.d/") (setq base-lisp-path "~/.emacs.d/site-lisp/") (setq site-lisp-path (concat emacs-config-path "/site-lisp")) (defun add-path (p) (add-to-list 'load-path (concat base-lisp-path p))) (add-path "") (add-to-list 'load-path "~/.emacs.d") (require 'psvn) ;; python-mode ;; (setq auto-mode-alist (cons '("\\.py$" . python-mode) auto-mode-alist)) (setq interpreter-mode-alist (cons '("python" . python-mode) interpreter-mode-alist)) (autoload 'python-mode "python-mode" "Python editing mode." t) (setq pymacs-load-path '( "~/.emacs.d/site-lisp/rope" "~/.emacs.d/site-lisp/ropemode" "~/.emacs.d/site-lisp/ropemacs")) (setq interpreter-mode-alist (cons '("python" . python-mode) interpreter-mode-alist) python-mode-hook '(lambda () (progn (set-variable 'py-indent-offset 4) (set-variable 'py-smart-indentation nil) (set-variable 'indent-tabs-mode nil) ;;(highlight-beyond-fill-column) (define-key python-mode-map "\C-m" 'newline-and-indent) (pabbrev-mode) (abbrev-mode) ) ) ) ;; pymacs (autoload 'pymacs-apply "pymacs") (autoload 'pymacs-call "pymacs") (autoload 'pymacs-eval "pymacs" nil t) (autoload 'pymacs-exec "pymacs" nil t) (autoload 'pymacs-load "pymacs" nil t) ;; Search local path for emacs rope ;; ;; enable pymacs ;; (require 'pymacs) (pymacs-load "ropemacs" "rope-") </code></pre> <p>Now, when i start emacs, I got this error message:</p> <pre><code>("C:\\opt\\emacs-22.3\\bin\\emacs.exe") Loading encoded-kb...done Loading regexp-opt...done Loading easy-mmode...done Loading wid-edit...done Loading edmacro...done Loading derived...done Loading advice...done Loading cl-macs...done Loading byte-opt...done An error has occurred while loading `c:/opt/cygwin/home/akong/.emacs': File error: Cannot open load file, pymacs To ensure normal operation, you should investigate and remove the cause of the error in your initialization file. Start Emacs with the `--debug-init' option to view a complete error backtrace. For information about GNU Emacs and the GNU system, type C-h C-a. [2 times] </code></pre> <p>To make it slightly more complicated:</p> <p>For work reason I have to use python 2.4, but I have python 2.6 installed on my PC. But obviously rope does not like 2.4 so I did not run setup.py. I untar/unzip these packages and put these files under ~/.emacs.d/site-lisp. By default if python is invoked in command prompt, it is the python 2.4 executable.</p> <p><strong>Q: How can I successfully load 'pymacs'?</strong></p>
6
2009-07-03T06:55:40Z
3,430,210
<p>If paths are missing then this will easily be spotted in the startup log or by getting a backtrace at emacs start. If in doubt M-x load-library is the way to go.</p> <p>I too am getting company-ropemacs refusing to load with both emacs 23 and emacs 24 after latest Debian Testing updates which then means you can not save files because of rope save hooks. I would be interested to hear from anyone with it working. company-ropemacs and python in general with emacs has been a thorn for some time now. I intend to try and debug it some more later and will update this thread then.</p>
1
2010-08-07T11:20:37Z
[ "python", "emacs", "rope", "pymacs" ]
Restarting a Django application running on Apache + mod_python
1,078,166
<p>I'm running a Django app on Apache + mod_python. When I make some changes to the code, sometimes they have effect immediately, other times they don't, until I restart Apache. However I don't really want to do that since it's a production server running other stuff too. Is there some other way to force that?</p> <p>Just to make it clear, since I see some people get it wrong, I'm talking about a <em>production</em> environment. For development I'm using Django's development server, of course.</p>
8
2009-07-03T07:23:55Z
1,078,235
<p>Use a test server included in Django. (like <code>./manage.py runserver 0.0.0.0:8080</code>) It will do most things you would need during development. The only drawback is that it cannot handle simultaneous requests with multi-threading.</p> <p>I've heard that there is a trick that setting Apache's max instances to 1 so that every code change is reflected immediately--but because you said you're running other services, so this may not be your case.</p>
-1
2009-07-03T07:41:34Z
[ "python", "django", "mod-python" ]
Restarting a Django application running on Apache + mod_python
1,078,166
<p>I'm running a Django app on Apache + mod_python. When I make some changes to the code, sometimes they have effect immediately, other times they don't, until I restart Apache. However I don't really want to do that since it's a production server running other stuff too. Is there some other way to force that?</p> <p>Just to make it clear, since I see some people get it wrong, I'm talking about a <em>production</em> environment. For development I'm using Django's development server, of course.</p>
8
2009-07-03T07:23:55Z
1,078,282
<p>If possible, you should switch to mod_wsgi. This is now the <a href="http://docs.djangoproject.com/en/dev/howto/deployment/modwsgi/">recommended way</a> to serve Django anyway, and is much more efficient in terms of memory and server resources.</p> <p>In mod_wsgi, each site has a <code>.wsgi</code> file associated with it. To restart a site, just <code>touch</code> the relevant file, and only that code will be reloaded.</p>
15
2009-07-03T07:58:49Z
[ "python", "django", "mod-python" ]
Restarting a Django application running on Apache + mod_python
1,078,166
<p>I'm running a Django app on Apache + mod_python. When I make some changes to the code, sometimes they have effect immediately, other times they don't, until I restart Apache. However I don't really want to do that since it's a production server running other stuff too. Is there some other way to force that?</p> <p>Just to make it clear, since I see some people get it wrong, I'm talking about a <em>production</em> environment. For development I'm using Django's development server, of course.</p>
8
2009-07-03T07:23:55Z
1,078,289
<p>You can reduce number of connections to 1 by setting "MaxRequestsPerChild 1" in your httpd.conf file. But do it only on test server, not production.</p> <p>or </p> <p>If you don't want to kill existing connections and still restart apache you can restart it "gracefully" by performing "apache2ctl gracefully" - all existing connections will be allowed to complete.</p>
0
2009-07-03T08:01:27Z
[ "python", "django", "mod-python" ]
Restarting a Django application running on Apache + mod_python
1,078,166
<p>I'm running a Django app on Apache + mod_python. When I make some changes to the code, sometimes they have effect immediately, other times they don't, until I restart Apache. However I don't really want to do that since it's a production server running other stuff too. Is there some other way to force that?</p> <p>Just to make it clear, since I see some people get it wrong, I'm talking about a <em>production</em> environment. For development I'm using Django's development server, of course.</p>
8
2009-07-03T07:23:55Z
1,078,713
<p>As others have suggested, use mod_wsgi instead. To get the ability for automatic reloading, through touching the WSGI script file, or through a monitor that looks for code changes, you must be using daemon mode on UNIX. A slight of hand can be used to achieve same on Windows when using embedded mode. All the details can be found in:</p> <p><a href="http://code.google.com/p/modwsgi/wiki/ReloadingSourceCode" rel="nofollow">http://code.google.com/p/modwsgi/wiki/ReloadingSourceCode</a></p>
4
2009-07-03T10:07:07Z
[ "python", "django", "mod-python" ]
SharePoint via SOAP using Python
1,078,593
<p>I have been following the solution noted here - as this is exactly what I need to achieve;</p> <p><a href="http://stackoverflow.com/questions/218987/how-can-i-use-sharepoint-via-soap-from-python">http://stackoverflow.com/questions/218987/how-can-i-use-sharepoint-via-soap-from-python</a></p> <p>however when I run one of the last lines of this code I get the following error;</p> <p><code>&gt;&gt;&gt; client = SoapClient(url, {'opener' : opener})</code></p> <pre><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in ? File "build\bdist.win32\egg\suds\client.py", line 456, in __init__ AttributeError: 'str' object has no attribute 'options' </code></pre> <p>Any advice or suggestion as to how to solve this most welcome!</p>
0
2009-07-03T09:33:07Z
1,189,001
<p>According to <a href="https://fedorahosted.org/suds/browser/trunk/suds/client.py?rev=504" rel="nofollow">https://fedorahosted.org/suds/browser/trunk/suds/client.py?rev=504</a></p> <pre><code>434 class SoapClient: ... 445 """ 446 447 def __init__(self, client, method): 448 """ 449 @param client: A suds client. 450 @type client: L{Client} 451 @param method: A target method. 452 @type method: L{Method} 453 """ 454 self.client = client 455 self.method = method 456 self.options = client.options 457 self.cookiejar = CookieJar() </code></pre> <p>The first parameter of <code>SoapClient</code> is not a <code>string</code> but an object of the <code>Client</code> class. Your parameter is not an instance of the required class.</p>
1
2009-07-27T15:57:34Z
[ "python", "sharepoint", "soap", "suds" ]
Deploying a Web.py application with WSGI, several servers
1,078,599
<p>I've created a web.py application, and now that it is ready to be deployed, I want to run in not on web.py's built-in webserver. I want to be able to run it on different webservers, Apache or IIS, without having to change my application code. This is where WSGI is supposed to come in, if I understand it correctly.<br /> However, I don't understand what exacly I have to do to make my application deployable on a WSGI server? Most examples assume you are using Pylons/Django/other-framework, on which you simply run some magic command which fixes everything for you.<br /> From what I understand of the (quite brief) web.py documentation, instead of running <code>web.application(...).run()</code>, I should use <code>web.application(...).wsgifunc()</code>. And then what? </p>
6
2009-07-03T09:35:35Z
1,078,743
<p>Exactly what you need to do to host it with a specific WSGI hosting mechanism varies with the server.</p> <p>For the case of Apache/mod_wsgi and Phusion Passenger, you just need to provide a WSGI script file which contains an object called 'application'. For web.py 0.2, this is the result of calling web.wsgifunc() with appropriate arguments. For web.py 0.3, you instead use wsgifunc() member function of object returned by web.application(). For details of these see mod_wsgi documentation:</p> <p><a href="http://code.google.com/p/modwsgi/wiki/IntegrationWithWebPy">http://code.google.com/p/modwsgi/wiki/IntegrationWithWebPy</a></p> <p>If instead you are having to use FASTCGI, SCGI or AJP adapters for a server such as Lighttpd, nginx or Cherokee, then you need to use 'flup' package to provide a bridge between those language agnostic interfaces and WSGI. This involves calling a flup function with the same WSGI application object above that something like mod_wsgi or Phusion Passenger would use directly without the need for a bridge. For details of this see:</p> <p><a href="http://trac.saddi.com/flup/wiki/FlupServers">http://trac.saddi.com/flup/wiki/FlupServers</a></p> <p>Important thing is to structure your web application so that it is in its own self contained set of modules. To work with a particular server, then create a separate script file as necessary to bridge between what that server requires and your application code. Your application code should always be outside of the web server document directory and only the script file that acts as bridge would be in server document directory if appropriate.</p>
6
2009-07-03T10:18:09Z
[ "python", "wsgi", "web.py" ]
Deploying a Web.py application with WSGI, several servers
1,078,599
<p>I've created a web.py application, and now that it is ready to be deployed, I want to run in not on web.py's built-in webserver. I want to be able to run it on different webservers, Apache or IIS, without having to change my application code. This is where WSGI is supposed to come in, if I understand it correctly.<br /> However, I don't understand what exacly I have to do to make my application deployable on a WSGI server? Most examples assume you are using Pylons/Django/other-framework, on which you simply run some magic command which fixes everything for you.<br /> From what I understand of the (quite brief) web.py documentation, instead of running <code>web.application(...).run()</code>, I should use <code>web.application(...).wsgifunc()</code>. And then what? </p>
6
2009-07-03T09:35:35Z
1,245,928
<p>As of July 21 2009, there is a much fuller installation guide at <a href="http://webpy.org/install" rel="nofollow">the webpy install site</a>, that discusses <strong>flup</strong>, <strong>fastcgi</strong>, <strong>apache</strong> and more. I haven't yet <em>tried</em> it, but it seems like it's much more detailed. </p>
0
2009-08-07T17:12:58Z
[ "python", "wsgi", "web.py" ]
Deploying a Web.py application with WSGI, several servers
1,078,599
<p>I've created a web.py application, and now that it is ready to be deployed, I want to run in not on web.py's built-in webserver. I want to be able to run it on different webservers, Apache or IIS, without having to change my application code. This is where WSGI is supposed to come in, if I understand it correctly.<br /> However, I don't understand what exacly I have to do to make my application deployable on a WSGI server? Most examples assume you are using Pylons/Django/other-framework, on which you simply run some magic command which fixes everything for you.<br /> From what I understand of the (quite brief) web.py documentation, instead of running <code>web.application(...).run()</code>, I should use <code>web.application(...).wsgifunc()</code>. And then what? </p>
6
2009-07-03T09:35:35Z
1,406,572
<p>Here is an example of two hosted apps using cherrypy wsgi server:</p> <pre> #!/usr/bin/python from web import wsgiserver import web # webpy wsgi app urls = ( '/test.*', 'index' ) class index: def GET(self): web.header("content-type", "text/html") return "Hello, world1!" application = web.application(urls, globals(), autoreload=False).wsgifunc() # generic wsgi app def my_blog_app(environ, start_response): status = '200 OK' response_headers = [('Content-type','text/plain')] start_response(status, response_headers) return ['Hello world! - blog\n'] """ # single hosted app server = wsgiserver.CherryPyWSGIServer( ('0.0.0.0', 8070), application, server_name='www.cherrypy.example') """ # multiple hosted apps with WSGIPathInfoDispatcher d = wsgiserver.WSGIPathInfoDispatcher({'/test': application, '/blog': my_blog_app}) server = wsgiserver.CherryPyWSGIServer(('0.0.0.0', 8070), d) server.start() </pre>
0
2009-09-10T17:16:35Z
[ "python", "wsgi", "web.py" ]
wxPython menu doesn't display image
1,078,661
<p>I am creating a menu and assigning images to menu items, sometime first item in menu doesn't display any image, I am not able to find the reason. I have tried to make a simple stand alone example and below is the code which does demonstrates the problem on my machine. I am using windows XP, wx 2.8.7.1 (msw-unicode)'</p> <pre><code>import wx def getBmp(): bmp = wx.EmptyBitmap(16,16) return bmp class MyFrame(wx.Frame): def __init__(self): wx.Frame.__init__(self, style=wx.DEFAULT_FRAME_STYLE, parent=None) self.SetTitle("why New has no image?") menuBar = wx.MenuBar() fileMenu=wx.Menu() item = fileMenu.Append(wx.ID_NEW, "New") item.SetBitmap(getBmp()) item = fileMenu.Append(wx.ID_OPEN, "Open") item.SetBitmap(getBmp()) item = fileMenu.Append(wx.ID_SAVE, "Save") item.SetBitmap(getBmp()) menuBar.Append(fileMenu, "File") self.SetMenuBar(menuBar) app = wx.PySimpleApp() frame=MyFrame() frame.Show() app.SetTopWindow(frame) app.MainLoop() </code></pre> <p>So are you able to see the problem and what could be the reason for it?</p> <p><strong>Conclusion</strong>: Yes this is a official bug, I have created a simple Menu class to overcome this bug, using the trick given by "balpha" in selected answer</p> <p>It overrides each menu.Append method and sees if menu item with image is being added for first time, if yes creates a dummy item and deletes it later.</p> <p>This also adds feature/constraint so that instead of calling SetBitmap, you should pass bitmap as optional argument image</p> <pre><code>import wx class MockMenu(wx.Menu): """ A custom menu class in which image param can be passed to each Append method it also takes care of bug http://trac.wxwidgets.org/ticket/4011 """ def __init__(self, *args, **kwargs): wx.Menu.__init__(self, *args, **kwargs) self._count = 0 def applyBmp(self, unboundMethod, *args, **kwargs): """ there is a bug in wxPython so that it will not display first item bitmap http://trac.wxwidgets.org/ticket/4011 so we keep track and add a dummy before it and delete it after words may not work if menu has only one item """ bmp = None if 'image' in kwargs: bmp = kwargs['image'] tempitem = None # add temp item so it is first item with bmp if bmp and self._count == 1: tempitem = wx.Menu.Append(self, -1,"HACK") tempitem.SetBitmap(bmp) ret = unboundMethod(self, *args, **kwargs) if bmp: ret.SetBitmap(bmp) # delete temp item if tempitem is not None: self.Remove(tempitem.GetId()) self._lastRet = ret return ret def Append(self, *args, **kwargs): return self.applyBmp(wx.Menu.Append, *args, **kwargs) def AppendCheckItem(self, *args, **kwargs): return self.applyBmp(wx.Menu.AppendCheckItem, *args, **kwargs) def AppendMenu(self, *args, **kwargs): return self.applyBmp(wx.Menu.AppendMenu, *args, **kwargs) </code></pre>
3
2009-07-03T09:51:59Z
1,078,810
<p>This is a <a href="http://trac.wxwidgets.org/ticket/4011" rel="nofollow">confirmed bug</a> which appearently has been open for quite a while. After trying around a little bit, this workaround seems to do it:</p> <pre><code> menuBar = wx.MenuBar() fileMenu=wx.Menu() tempitem = fileMenu.Append(-1,"X") # !!! tempitem.SetBitmap(getBmp()) # !!! item = fileMenu.Append(wx.ID_NEW, "New") fileMenu.Remove(tempitem.GetId()) # !!! item.SetBitmap(getBmp()) item = fileMenu.Append(wx.ID_OPEN, "Open") item.SetBitmap(getBmp()) item = fileMenu.Append(wx.ID_SAVE, "Save") item.SetBitmap(getBmp()) menuBar.Append(fileMenu, "File") self.SetMenuBar(menuBar) </code></pre> <p>Note that the position of the fileMenu.Remove call is the earliest position that works, but you can also move it to the bottom. HTH.</p>
2
2009-07-03T10:44:28Z
[ "python", "menu", "wxpython" ]
wxPython menu doesn't display image
1,078,661
<p>I am creating a menu and assigning images to menu items, sometime first item in menu doesn't display any image, I am not able to find the reason. I have tried to make a simple stand alone example and below is the code which does demonstrates the problem on my machine. I am using windows XP, wx 2.8.7.1 (msw-unicode)'</p> <pre><code>import wx def getBmp(): bmp = wx.EmptyBitmap(16,16) return bmp class MyFrame(wx.Frame): def __init__(self): wx.Frame.__init__(self, style=wx.DEFAULT_FRAME_STYLE, parent=None) self.SetTitle("why New has no image?") menuBar = wx.MenuBar() fileMenu=wx.Menu() item = fileMenu.Append(wx.ID_NEW, "New") item.SetBitmap(getBmp()) item = fileMenu.Append(wx.ID_OPEN, "Open") item.SetBitmap(getBmp()) item = fileMenu.Append(wx.ID_SAVE, "Save") item.SetBitmap(getBmp()) menuBar.Append(fileMenu, "File") self.SetMenuBar(menuBar) app = wx.PySimpleApp() frame=MyFrame() frame.Show() app.SetTopWindow(frame) app.MainLoop() </code></pre> <p>So are you able to see the problem and what could be the reason for it?</p> <p><strong>Conclusion</strong>: Yes this is a official bug, I have created a simple Menu class to overcome this bug, using the trick given by "balpha" in selected answer</p> <p>It overrides each menu.Append method and sees if menu item with image is being added for first time, if yes creates a dummy item and deletes it later.</p> <p>This also adds feature/constraint so that instead of calling SetBitmap, you should pass bitmap as optional argument image</p> <pre><code>import wx class MockMenu(wx.Menu): """ A custom menu class in which image param can be passed to each Append method it also takes care of bug http://trac.wxwidgets.org/ticket/4011 """ def __init__(self, *args, **kwargs): wx.Menu.__init__(self, *args, **kwargs) self._count = 0 def applyBmp(self, unboundMethod, *args, **kwargs): """ there is a bug in wxPython so that it will not display first item bitmap http://trac.wxwidgets.org/ticket/4011 so we keep track and add a dummy before it and delete it after words may not work if menu has only one item """ bmp = None if 'image' in kwargs: bmp = kwargs['image'] tempitem = None # add temp item so it is first item with bmp if bmp and self._count == 1: tempitem = wx.Menu.Append(self, -1,"HACK") tempitem.SetBitmap(bmp) ret = unboundMethod(self, *args, **kwargs) if bmp: ret.SetBitmap(bmp) # delete temp item if tempitem is not None: self.Remove(tempitem.GetId()) self._lastRet = ret return ret def Append(self, *args, **kwargs): return self.applyBmp(wx.Menu.Append, *args, **kwargs) def AppendCheckItem(self, *args, **kwargs): return self.applyBmp(wx.Menu.AppendCheckItem, *args, **kwargs) def AppendMenu(self, *args, **kwargs): return self.applyBmp(wx.Menu.AppendMenu, *args, **kwargs) </code></pre>
3
2009-07-03T09:51:59Z
1,225,117
<p>This hack does not appear to be necessary if you create each menu item with wx.MenuItem(), set its bitmap, and only then append it to the menu. This causes the bitmaps to show up correctly. I'm testing with wxPython 2.8.10.1 on Windows.</p>
4
2009-08-03T23:35:16Z
[ "python", "menu", "wxpython" ]
Advanced SAX Parser in C#
1,078,902
<p>See Below is the XML Arch. I want to display it in row / column wize.</p> <p>What I need is I need to convert this xml file to Hashtable like,</p> <pre><code>{"form" : {"attrs" : { "string" : " Partners" } {"child1": { "group" : { "attrs" : { "col" : "6", "colspan":"1" } } { "child1": { "field" : { "attrs" : { "name":"name"} { "child2": { "field" : { "attrs" : { "name":"ref"} } {"child2": { "notebook" : "attrs" : {"colspan": 4} } } } &lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;form string="Partners"&gt; &lt;group col="6" colspan="4"&gt; &lt;field name="name" select="1"/&gt; &lt;field name="ref" select="1"/&gt; &lt;field name="customer" select="1"/&gt; &lt;field domain="[('domain', '=', 'partner')]" name="title"/&gt; &lt;field name="lang" select="2"/&gt; &lt;field name="supplier" select="2"/&gt; &lt;/group&gt; &lt;notebook colspan="4"&gt; &lt;page string="General"&gt; &lt;field colspan="4" mode="form,tree" name="address" nolabel="1" select="1"&gt; &lt;/field&gt; &lt;separator colspan="4" string="Categories"/&gt; &lt;field colspan="4" name="category_id" nolabel="1" select="2"/&gt; &lt;/page&gt; &lt;page string="Sales &amp;amp; Purchases"&gt; &lt;separator colspan="4" string="General Information"/&gt; &lt;field name="user_id" select="2"/&gt; &lt;field name="active" select="2"/&gt; &lt;field name="website" widget="url"/&gt; &lt;field name="date" select="2"/&gt; &lt;field name="parent_id"/&gt; &lt;newline/&gt; &lt;newline/&gt;&lt;group col="2" colspan="2" name="sale_list"&gt; &lt;separator colspan="2" string="Sales Properties"/&gt; &lt;field name="property_product_pricelist"/&gt; &lt;/group&gt;&lt;group col="2" colspan="2"&gt; &lt;separator colspan="2" string="Purchases Properties"/&gt; &lt;field name="property_product_pricelist_purchase"/&gt; &lt;/group&gt;&lt;group col="2" colspan="2"&gt; &lt;separator colspan="2" string="Stock Properties"/&gt; &lt;field name="property_stock_customer"/&gt; &lt;field name="property_stock_supplier"/&gt; &lt;/group&gt;&lt;/page&gt; &lt;page string="History"&gt; &lt;field colspan="4" name="events" nolabel="1" widget="one2many_list"/&gt; &lt;/page&gt; &lt;page string="Notes"&gt; &lt;field colspan="4" name="comment" nolabel="1"/&gt; &lt;/page&gt; &lt;page position="inside" string="Accounting"&gt; &lt;group col="2" colspan="2"&gt; &lt;separator colspan="2" string="Customer Accounting Properties"/&gt; &lt;field name="property_account_receivable"/&gt; &lt;field name="property_account_position"/&gt;&lt;field name="vat" on_change="vat_change(vat)" select="2"/&gt;&lt;field name="vat_subjected"/&gt; &lt;field name="property_payment_term"/&gt; &lt;/group&gt; &lt;group col="2" colspan="2"&gt; &lt;separator colspan="2" string="Supplier Accounting Properties"/&gt; &lt;field name="property_account_payable"/&gt; &lt;/group&gt; &lt;group col="2" colspan="2"&gt; &lt;separator colspan="2" string="Customer Credit"/&gt; &lt;field name="credit" select="2"/&gt; &lt;field name="credit_limit" select="2"/&gt; &lt;/group&gt; &lt;group col="2" colspan="2"&gt; &lt;separator colspan="2" string="Supplier Debit"/&gt; &lt;field name="debit" select="2"/&gt; &lt;/group&gt; &lt;field colspan="4" context="address=address" name="bank_ids" nolabel="1" select="2"&gt; &lt;/field&gt; &lt;/page&gt; &lt;/notebook&gt; &lt;/form&gt; </code></pre>
1
2009-07-03T11:16:22Z
1,116,506
<blockquote> <p>from xml.sax.handler import ContentHandler import xml class my_handler(ContentHandler):</p> <pre><code>def get_attr_dict(self, attrs): ret_dict = {} for name in attrs.getNames(): ret_dict[name] = attrs.getValue(name) #end for name in attrs.getNames(): return ret_dict def setDocumentLocator(self, locator): print "DOCUMEN T LOOCATOR" pass def startDocument(self): self.my_data = {} self.my_stack = [] print "SATART DUASDFASD:" def startElement(self, name, attrs): attr_dict = self.get_attr_dict(attrs) myname = name!='field' and name or attr_dict['name'] append_dict = { 'attrs' : attr_dict, 'childs' : [] } if not self.my_data: self.my_data[name] = append_dict else: last_dict = {} for x in self.my_stack: if last_dict: last_dict = isinstance(last_dict, list) and </code></pre> <p>last_dict[-1][x] or last_dict[x] else: last_dict = self.my_data[x] last_dict.append({myname : append_dict})</p> <pre><code> self.my_stack.extend([myname, 'childs']) def endElement(self, name): self.my_stack = self.my_stack[:-2] print "ENDS ELERMERE :",name def endDocument(self): print "Sfled :",self.my_data print "ENDA DAFASDFASD" </code></pre> <p>if <strong>name</strong> == '<strong>main</strong>': fp = open('Form.xml', 'r') xml.sax.parse(fp, my_handler()) fp.close()</p> <p>Finally instead of C#, it has been solved using Pyton Script, here I'm sharing the script. Thanks.</p> </blockquote>
0
2009-07-12T17:43:07Z
[ ".net", "python", "xml", "parsing", "sax" ]
I'd like to call the Windows C++ function WinHttpGetProxyForUrl from Python - can this be done?
1,078,939
<p>Microsoft provides a method as part of WinHTTP which allows a user to determine which Proxy ought to be used for any given URL. It's called <a href="http://msdn.microsoft.com/en-us/library/aa384097%28VS.85%29.aspx" rel="nofollow">WinHttpGetProxyForUrl</a>.</p> <p>Unfortunately I'm programming in python so I cannot directly access this function - I can use Win32COM to call any Microsoft service with a COM interface.</p> <p>So is there any way to get access to this function from Python? As an additional problem I'm not able to add anything other than Python to the project. That means however convenient it is impossible to add C# or C++ fixes.</p> <p>I'm running Python2.4.4 with Win32 extensions on Windows XP. </p> <p>Update 0:</p> <p>This is what I have so far:</p> <pre><code>import win32inet import pprint hinternet = win32inet.InternetOpen("foo 1.0", 0, "", "", 0) # Does not work!!! proxy = win32inet.WinHttpGetProxyForUrl( hinternet, u"http://www.foo.com", 0 ) </code></pre> <p>Obviously the last line is wrong, however I cannot see any docs or examples on the right way to do it!</p> <p>Update 1: </p> <p><a href="http://stackoverflow.com/questions/1079655/whats-the-correct-way-to-use-win32inet-winhttpgetproxyforurl">I'm going to re-ask this as a new question since it's now really about win32com</a>. </p>
1
2009-07-03T11:25:08Z
1,079,007
<p>You can use ctypes to call function in WinHttp.dll, it is the DLL which contains 'WinHttpGetProxyForUrl. ' Though to call it you will need a HINTERNET session variable, so here I am showing you the first step, it shows how you can use ctypes to call into DLL,it produces a HINTERNET which you have to pass to WinHttpGetProxyForUrl, that I will leave for you as exercise, if you feel difficulty POST the code I will try to fix it.</p> <p>Read more about ctypes @ <a href="http://docs.python.org/library/ctypes.html" rel="nofollow">http://docs.python.org/library/ctypes.html</a></p> <pre><code>import ctypes winHttp = ctypes.windll.LoadLibrary("Winhttp.dll") WINHTTP_ACCESS_TYPE_DEFAULT_PROXY=0 WINHTTP_NO_PROXY_NAME=WINHTTP_NO_PROXY_BYPASS=0 WINHTTP_FLAG_ASYNC=0x10000000 # http://msdn.microsoft.com/en-us/library/aa384098(VS.85).aspx HINTERNET = winHttp.WinHttpOpen("PyWin32", WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, WINHTTP_FLAG_ASYNC) print HINTERNET </code></pre>
1
2009-07-03T11:47:10Z
[ "c++", "python", "windows", "com" ]
I'd like to call the Windows C++ function WinHttpGetProxyForUrl from Python - can this be done?
1,078,939
<p>Microsoft provides a method as part of WinHTTP which allows a user to determine which Proxy ought to be used for any given URL. It's called <a href="http://msdn.microsoft.com/en-us/library/aa384097%28VS.85%29.aspx" rel="nofollow">WinHttpGetProxyForUrl</a>.</p> <p>Unfortunately I'm programming in python so I cannot directly access this function - I can use Win32COM to call any Microsoft service with a COM interface.</p> <p>So is there any way to get access to this function from Python? As an additional problem I'm not able to add anything other than Python to the project. That means however convenient it is impossible to add C# or C++ fixes.</p> <p>I'm running Python2.4.4 with Win32 extensions on Windows XP. </p> <p>Update 0:</p> <p>This is what I have so far:</p> <pre><code>import win32inet import pprint hinternet = win32inet.InternetOpen("foo 1.0", 0, "", "", 0) # Does not work!!! proxy = win32inet.WinHttpGetProxyForUrl( hinternet, u"http://www.foo.com", 0 ) </code></pre> <p>Obviously the last line is wrong, however I cannot see any docs or examples on the right way to do it!</p> <p>Update 1: </p> <p><a href="http://stackoverflow.com/questions/1079655/whats-the-correct-way-to-use-win32inet-winhttpgetproxyforurl">I'm going to re-ask this as a new question since it's now really about win32com</a>. </p>
1
2009-07-03T11:25:08Z
1,079,010
<p>This page at ActiveState: <a href="http://docs.activestate.com/activepython/2.5/pywin32/WINHTTP%5FAUTOPROXY%5FOPTIONS.html" rel="nofollow"><code>WINHTTP_AUTOPROXY_OPTIONS</code> Object</a> implies that <code>WinHttpGetProxyForUrl</code> is available in the win32inet module of the Win32 extensions. SourceForge is currently broken so I can't download it to verify whether it is or not.</p> <p><strong>Edit</strong> after "Update 0" in the question:</p> <p>You need to pass a <code>WINHTTP_AUTOPROXY_OPTIONS</code> and a <code>WINHTTP_PROXY_INFO</code> as documented here on MSDN: <a href="http://msdn.microsoft.com/en-us/library/aa384097%28VS.85%29.aspx" rel="nofollow">WinHttpGetProxyForUrl Function</a>.</p>
1
2009-07-03T11:47:47Z
[ "c++", "python", "windows", "com" ]
How to put Google login box inside flash in GAE?
1,079,022
<p>I am putting my old flash site into GAE. I want to use Google's user authentication too. Now, I want to put Googles login box inside the flash instead of redirecting to Google's login page. Same thing I want for forgot password.</p> <p>Is it possible to do this? How to do this?</p>
0
2009-07-03T11:50:41Z
1,353,761
<p>Of course this is possible you just need to use flash to post http request to your server and your server could communicate to flash through several ways like: xml , html, and AMF or even johnson( I am not sure).</p> <p>I recommend you use pyamf at server side to build a native support for flash at server side</p>
1
2009-08-30T12:15:11Z
[ "python", "flash", "google-app-engine", "authentication" ]
How to emulate language complement operator in .hgignore?
1,079,342
<p>I have a Python regular expression that matches a set of filenames. How to change it so that I can use it in Mercurial's .hgignore file to ignore files that do <em>not</em> match the expression?</p> <p>Full story: I have a big source tree with <code>*.ml</code> files scattered everywhere. I want to put them into a new repository. There are other, less important files which are too heavy to be included in the repository. I'm trying to find the corresponding expression for <code>.hgignore</code> file.</p> <p>1st observation: Python doesn't have regular language complement operator (AFAIK it can complement only a set of characters). (BTW, why?)</p> <p>2nd observation: The following regex in Python:</p> <pre><code>re.compile("^.*(?&lt;!\.ml)$") </code></pre> <p>works as expected: </p> <pre><code>abcabc - match abc.ml - no match x/abcabc - match x/abc.ml - no match </code></pre> <p>However, when I put exactly the same expression in the <code>.hgignore</code> file, I get this:</p> <pre><code>$ hg st --all ? abc.ml I .hgignore I abcabc I x/xabc I x/xabc.ml </code></pre> <p>According to <code>.hgignore</code> manpage, Mercurial uses just normal Python regular expressions. How is that I get different results then? How is it possible that Mercurial found a match for the <code>x/xabc.ml</code>?</p> <p>Does anybody know less ugly way around the lack of regular language complement operator?</p>
3
2009-07-03T13:22:55Z
1,079,968
<p>Through some testing, found two solutions that appear to work. The first roots to a subdirectory, and apparently this is significant. The second is brittle, because it only allows one suffix to be used. I'm running these tests on Windows XP (customized to work a bit more unixy) with Mercurial 1.2.1.</p> <p>(Comments added with <code># message</code> by me.)</p> <pre> $ hg --version Mercurial Distributed SCM (version 1.2.1) $ cat .hgignore syntax: regexp ^x/.+(?&lt;!\.ml)$ # rooted to x/ subdir #^.+[^.][^m][^l]$ $ hg status --all ? .hgignore # not affected by x/ regex ? abc.ml # not affected by x/ regex ? abcabc # not affected by x/ regex ? x\saveme.ml # versioned, is *.ml I x\abcabc # ignored, is not *.ml I x\ignoreme.txt # ignored, is not *.ml </pre> <p>And the second:</p> <pre> $ cat .hgignore syntax: regexp #^x/.+(?&lt;!\.ml)$ ^.+[^.][^m][^l]$ # brittle, can only use one suffix $ hg status --all ? abc.ml # versioned, is *.ml ? x\saveme.ml # versioned, is *.ml I .hgignore # ignored, is not *.ml I abcabc # ignored, is not *.ml I x\abcabc # ignored, is not *.ml I x\ignoreme.txt # ignored, is not *.ml </pre> <p>The second one has fully expected behavior as I understand the OP. The first only has expected behavior in the subdirectory, but is more flexible.</p>
0
2009-07-03T16:02:23Z
[ "python", "regex", "mercurial" ]
How to emulate language complement operator in .hgignore?
1,079,342
<p>I have a Python regular expression that matches a set of filenames. How to change it so that I can use it in Mercurial's .hgignore file to ignore files that do <em>not</em> match the expression?</p> <p>Full story: I have a big source tree with <code>*.ml</code> files scattered everywhere. I want to put them into a new repository. There are other, less important files which are too heavy to be included in the repository. I'm trying to find the corresponding expression for <code>.hgignore</code> file.</p> <p>1st observation: Python doesn't have regular language complement operator (AFAIK it can complement only a set of characters). (BTW, why?)</p> <p>2nd observation: The following regex in Python:</p> <pre><code>re.compile("^.*(?&lt;!\.ml)$") </code></pre> <p>works as expected: </p> <pre><code>abcabc - match abc.ml - no match x/abcabc - match x/abc.ml - no match </code></pre> <p>However, when I put exactly the same expression in the <code>.hgignore</code> file, I get this:</p> <pre><code>$ hg st --all ? abc.ml I .hgignore I abcabc I x/xabc I x/xabc.ml </code></pre> <p>According to <code>.hgignore</code> manpage, Mercurial uses just normal Python regular expressions. How is that I get different results then? How is it possible that Mercurial found a match for the <code>x/xabc.ml</code>?</p> <p>Does anybody know less ugly way around the lack of regular language complement operator?</p>
3
2009-07-03T13:22:55Z
1,080,058
<p>The problem appears specifically to be that matches in subdirectories are different to the root. Note the following:</p> <pre><code>$ hg --version Mercurial Distributed SCM (version 1.1.2) </code></pre> <p>It's an older version, but it behaves in the same way. My project has the following files:</p> <pre><code>$ find . -name 'abc*' -print ./x/abcabc ./x/abc.ml ./abcabc ./abc.ml </code></pre> <p>Here's my .hgignore:</p> <pre><code>$ cat .hgignore ^.*(?&lt;!\.ml)$ </code></pre> <p>Now, when I run <code>stat</code>:</p> <pre><code>$ hg stat ? abc.ml </code></pre> <p>So, <code>hg</code> has failed to pick up <code>x/abc.ml</code>. But is this really a problem with the regular expression? Perhaps not:</p> <pre><code>$ python Python 2.6.2 (release26-maint, Apr 19 2009, 01:56:41) [GCC 4.3.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import mercurial.ignore &gt;&gt;&gt; import os &gt;&gt;&gt; root = os.getcwd() &gt;&gt;&gt; ignorefunc = mercurial.ignore.ignore(root, ['.hgignore'], lambda msg: None) &gt;&gt;&gt; &gt;&gt;&gt; ignorefunc("abc.ml") # No match - this is correct &gt;&gt;&gt; ignorefunc("abcabc") # Match - this is correct, we want to ignore this &lt;_sre.SRE_Match object at 0xb7c765d0&gt; &gt;&gt;&gt; ignorefunc("abcabc").span() (0, 6) &gt;&gt;&gt; ignorefunc("x/abcabc").span() # Match - this is correct, we want to ignore this (0, 8) &gt;&gt;&gt; ignorefunc("x/abc.ml") # No match - this is correct! &gt;&gt;&gt; </code></pre> <p>Notice that <code>ignorefunc</code> treated <code>abcabc</code> and <code>x/abcabc</code> the same (matched - i.e. ignore) whereas <code>abc.ml</code> and <code>x/abc.ml</code> are also treated the same (no match - i.e. don't ignore).</p> <p>So, perhaps the logic error is elsewhere in Mercurial, or perhaps I'm looking at the wrong bit of Mercurial (though I'd be surprised if that were the case). Unless I've missed something, maybe a bug (rather than an RFE which Martin Geisler pointed to) needs to be filed against Mercurial.</p>
0
2009-07-03T16:32:28Z
[ "python", "regex", "mercurial" ]
How to emulate language complement operator in .hgignore?
1,079,342
<p>I have a Python regular expression that matches a set of filenames. How to change it so that I can use it in Mercurial's .hgignore file to ignore files that do <em>not</em> match the expression?</p> <p>Full story: I have a big source tree with <code>*.ml</code> files scattered everywhere. I want to put them into a new repository. There are other, less important files which are too heavy to be included in the repository. I'm trying to find the corresponding expression for <code>.hgignore</code> file.</p> <p>1st observation: Python doesn't have regular language complement operator (AFAIK it can complement only a set of characters). (BTW, why?)</p> <p>2nd observation: The following regex in Python:</p> <pre><code>re.compile("^.*(?&lt;!\.ml)$") </code></pre> <p>works as expected: </p> <pre><code>abcabc - match abc.ml - no match x/abcabc - match x/abc.ml - no match </code></pre> <p>However, when I put exactly the same expression in the <code>.hgignore</code> file, I get this:</p> <pre><code>$ hg st --all ? abc.ml I .hgignore I abcabc I x/xabc I x/xabc.ml </code></pre> <p>According to <code>.hgignore</code> manpage, Mercurial uses just normal Python regular expressions. How is that I get different results then? How is it possible that Mercurial found a match for the <code>x/xabc.ml</code>?</p> <p>Does anybody know less ugly way around the lack of regular language complement operator?</p>
3
2009-07-03T13:22:55Z
1,080,439
<p>The regexs are applied to each subdirectory component in turn as well as the file name, not the entire relative path at once. So if I have a/b/c/d in my repo, each regex will be applied to a, a/b, a/b/c as well as a/b/c/d. If any component matches, the file will be ignored. (You can tell that this is the behaviour by trying <code>^bar$</code> with bar/foo - you'll see that bar/foo is ignored.)</p> <p><code>^.*(?&lt;!\.ml)$</code> ignores x/xabc.ml because the pattern matches x (i.e. the subdirectory.)</p> <p>This means that there is no regex that will help you, because your patterns are bound to match the first subdirectory component.</p>
1
2009-07-03T18:41:12Z
[ "python", "regex", "mercurial" ]
Sphinx templating
1,079,417
<p>I am using <a href="http://sphinx.pocoo.org" rel="nofollow">sphinx</a>. I want to template it. So after reading the docs, what I am trying is, in my conf.py,</p> <p>I put a line like, </p> <pre><code>templates_path = ['_templates'] </code></pre> <p>and I created a file </p> <pre><code>_templates/page.html </code></pre> <p>But this does not override the default template provided by sphinx. What more should I do, and where does this template need to go?</p> <p><hr /></p> <p><strong>EDIT:</strong></p> <p>Directory structure from the comments:</p> <pre><code>conf.py abc.txt def.txt makefile _templates\ page.html </code></pre>
6
2009-07-03T13:42:37Z
1,079,474
<p>The documentation <a href="http://sphinx.pocoo.org/templating.html#working-the-the-builtin-templates" rel="nofollow">http://sphinx.pocoo.org/templating.html#working-the-the-builtin-templates</a> says that the template it's looking for is <code>layout.html</code>.</p> <p>Perhaps you should use that name.</p>
1
2009-07-03T13:55:31Z
[ "python", "documentation", "python-sphinx" ]
Sphinx templating
1,079,417
<p>I am using <a href="http://sphinx.pocoo.org" rel="nofollow">sphinx</a>. I want to template it. So after reading the docs, what I am trying is, in my conf.py,</p> <p>I put a line like, </p> <pre><code>templates_path = ['_templates'] </code></pre> <p>and I created a file </p> <pre><code>_templates/page.html </code></pre> <p>But this does not override the default template provided by sphinx. What more should I do, and where does this template need to go?</p> <p><hr /></p> <p><strong>EDIT:</strong></p> <p>Directory structure from the comments:</p> <pre><code>conf.py abc.txt def.txt makefile _templates\ page.html </code></pre>
6
2009-07-03T13:42:37Z
1,112,717
<p>This works for me. Perhaps you need to force a rebuild for all files with the command <code>sphinx-build -a</code>? Sphinx only compiles HTML files that it detects as having changed. Another option is to just touch all your source files with <code>touch *.rst</code>.</p>
0
2009-07-11T01:53:19Z
[ "python", "documentation", "python-sphinx" ]
Sphinx templating
1,079,417
<p>I am using <a href="http://sphinx.pocoo.org" rel="nofollow">sphinx</a>. I want to template it. So after reading the docs, what I am trying is, in my conf.py,</p> <p>I put a line like, </p> <pre><code>templates_path = ['_templates'] </code></pre> <p>and I created a file </p> <pre><code>_templates/page.html </code></pre> <p>But this does not override the default template provided by sphinx. What more should I do, and where does this template need to go?</p> <p><hr /></p> <p><strong>EDIT:</strong></p> <p>Directory structure from the comments:</p> <pre><code>conf.py abc.txt def.txt makefile _templates\ page.html </code></pre>
6
2009-07-03T13:42:37Z
1,767,202
<p>Be sure you are using the theme name as an explicit directory in your template. e.g.: </p> <p><code>{% extends "basic/layout.html" %}</code></p> <p>see: <a href="http://sphinx.pocoo.org/theming.html#templating">HTML Theming Support</a></p>
5
2009-11-19T23:06:00Z
[ "python", "documentation", "python-sphinx" ]
What's the correct way to use win32inet.WinHttpGetProxyForUrl
1,079,655
<p>I'm trying to use a feature of the Microsoft WinHttp library that has been exposed by the developers of Win32com. Unfortunately most of the library does not seem to be documented and there are no example of the correct way to use the win32inet features via the win32com library.</p> <p>This is what I have so far:</p> <pre><code>import win32inet hinternet = win32inet.InternetOpen("foo 1.0", 0, "", "", 0) # Does not work!!! proxy = win32inet.WinHttpGetProxyForUrl( hinternet, u"http://www.foo.com", 0 ) </code></pre> <p>As you can see, all I am trying to do is use the win32inet feature to find out which proxy is the appropriate one to use for a given URL, int his case foo.com.</p> <p>Can you help me correct the syntax of the last line? MSN has some <a href="http://msdn.microsoft.com/en-us/library/aa384097%28VS.85%29.aspx" rel="nofollow">good documentation for the function being wrapped</a> but the args do not seem to map the to those of the python library perfectly.</p> <p>The fixed version of this script should:</p> <ul> <li><p>Be able to look up which proxy to use for any given URL.</p></li> <li><p>It should always do exactly what Internet Explorer would do (i.e. use the same proxy)</p></li> <li><p>It should be valid on any valid Windows XP set-up. That means it should work with an explicitly configured proxy and also no proxy at all. </p></li> <li><p>It only needs to work on Windows XP 32bit with Python 2.4.4. It can use any official released version of win32com.</p></li> </ul> <p>I'm using Python2.4.4 with Win32Com on Windows XP. </p> <p>UPDATE 0:</p> <p>OR... can you give me an alternative implementation in cTypes? As long as I can make it work I'm happy!</p>
3
2009-07-03T14:41:10Z
1,092,465
<p>Unless there is a strong reason for using <code>win32inet</code> (which is messy in this area due to limitations of <code>SWIG</code>), I recommend that you use <code>ctypes</code> instead.</p>
1
2009-07-07T13:50:57Z
[ "python", "windows", "com", "32-bit", "winhttp" ]
What's the correct way to use win32inet.WinHttpGetProxyForUrl
1,079,655
<p>I'm trying to use a feature of the Microsoft WinHttp library that has been exposed by the developers of Win32com. Unfortunately most of the library does not seem to be documented and there are no example of the correct way to use the win32inet features via the win32com library.</p> <p>This is what I have so far:</p> <pre><code>import win32inet hinternet = win32inet.InternetOpen("foo 1.0", 0, "", "", 0) # Does not work!!! proxy = win32inet.WinHttpGetProxyForUrl( hinternet, u"http://www.foo.com", 0 ) </code></pre> <p>As you can see, all I am trying to do is use the win32inet feature to find out which proxy is the appropriate one to use for a given URL, int his case foo.com.</p> <p>Can you help me correct the syntax of the last line? MSN has some <a href="http://msdn.microsoft.com/en-us/library/aa384097%28VS.85%29.aspx" rel="nofollow">good documentation for the function being wrapped</a> but the args do not seem to map the to those of the python library perfectly.</p> <p>The fixed version of this script should:</p> <ul> <li><p>Be able to look up which proxy to use for any given URL.</p></li> <li><p>It should always do exactly what Internet Explorer would do (i.e. use the same proxy)</p></li> <li><p>It should be valid on any valid Windows XP set-up. That means it should work with an explicitly configured proxy and also no proxy at all. </p></li> <li><p>It only needs to work on Windows XP 32bit with Python 2.4.4. It can use any official released version of win32com.</p></li> </ul> <p>I'm using Python2.4.4 with Win32Com on Windows XP. </p> <p>UPDATE 0:</p> <p>OR... can you give me an alternative implementation in cTypes? As long as I can make it work I'm happy!</p>
3
2009-07-03T14:41:10Z
1,096,346
<p>Here is the code which creates HINTERNET session and uses that to get proxy details, using ctypes to directly access winhttp DLL. It works without any error but I have no proxy set on my machine, you may have to tweak few constants to get it right. Go thru the msdn links in code, from where I have seen the API.</p> <pre><code>import ctypes import ctypes.wintypes winHttp = ctypes.windll.LoadLibrary("Winhttp.dll") # http://msdn.microsoft.com/en-us/library/aa384098(VS.85).aspx # first get a handle to HTTP session WINHTTP_ACCESS_TYPE_DEFAULT_PROXY=0 WINHTTP_NO_PROXY_NAME=WINHTTP_NO_PROXY_BYPASS=0 WINHTTP_FLAG_ASYNC=0x10000000 HINTERNET = winHttp.WinHttpOpen("PyWin32", WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, WINHTTP_FLAG_ASYNC) print HINTERNET # now get proxy using HTTP session # http://msdn.microsoft.com/en-us/library/aa384097(VS.85).aspx """ BOOL WinHttpGetProxyForUrl( __in HINTERNET hSession, __in LPCWSTR lpcwszUrl, __in WINHTTP_AUTOPROXY_OPTIONS *pAutoProxyOptions, __out WINHTTP_PROXY_INFO *pProxyInfo ); """ # create C structure for WINHTTP_AUTOPROXY_OPTIONS #http://msdn.microsoft.com/en-us/library/aa384123(VS.85).aspx """ typedef struct { DWORD dwFlags; DWORD dwAutoDetectFlags; LPCWSTR lpszAutoConfigUrl; LPVOID lpvReserved; DWORD dwReserved; BOOL fAutoLogonIfChallenged; } WINHTTP_AUTOPROXY_OPTIONS; """ class WINHTTP_AUTOPROXY_OPTIONS(ctypes.Structure): _fields_ = [("dwFlags", ctypes.wintypes.DWORD), ("dwAutoDetectFlags", ctypes.wintypes.DWORD), ("lpszAutoConfigUrl", ctypes.wintypes.LPCWSTR), ("lpvReserved", ctypes.c_void_p ), ("dwReserved", ctypes.wintypes.DWORD), ("fAutoLogonIfChallenged",ctypes.wintypes.BOOL),] WINHTTP_AUTOPROXY_AUTO_DETECT = 0x00000001; WINHTTP_AUTO_DETECT_TYPE_DHCP = 0x00000001; WINHTTP_AUTO_DETECT_TYPE_DNS_A = 0x00000002; options = WINHTTP_AUTOPROXY_OPTIONS() options.dwFlags = WINHTTP_AUTOPROXY_AUTO_DETECT options.dwAutoDetectFlags = WINHTTP_AUTO_DETECT_TYPE_DHCP|WINHTTP_AUTO_DETECT_TYPE_DNS_A options.lpszAutoConfigUrl = 0 options.fAutoLogonIfChallenged = False # create C structure for WINHTTP_AUTOPROXY_OPTIONS # http://msdn.microsoft.com/en-us/library/aa383912(VS.85).aspx """ struct WINHTTP_PROXY_INFO { DWORD dwAccessType; LPWSTR lpszProxy; LPWSTR lpszProxyBypass; }; """ class WINHTTP_PROXY_INFO(ctypes.Structure): _fields_ = [("dwAccessType", ctypes.wintypes.DWORD), ("lpszProxy", ctypes.wintypes.LPCWSTR), ("lpszProxyBypass", ctypes.wintypes.LPCWSTR),] info = WINHTTP_PROXY_INFO() ret = winHttp.WinHttpGetProxyForUrl(HINTERNET, "http://www.google.com", ctypes.pointer(options), ctypes.pointer(info) ) print "proxy success?",ret if not ret: # some error lets see what is that? import win32api import win32con errorCode = win32api.GetLastError() print "win32 Error:",errorCode s = "" print win32api.FormatMessage(errorCode) print info.dwAccessType, info.lpszProxy, info.lpszProxyBypass </code></pre>
6
2009-07-08T06:09:28Z
[ "python", "windows", "com", "32-bit", "winhttp" ]
What's the correct way to use win32inet.WinHttpGetProxyForUrl
1,079,655
<p>I'm trying to use a feature of the Microsoft WinHttp library that has been exposed by the developers of Win32com. Unfortunately most of the library does not seem to be documented and there are no example of the correct way to use the win32inet features via the win32com library.</p> <p>This is what I have so far:</p> <pre><code>import win32inet hinternet = win32inet.InternetOpen("foo 1.0", 0, "", "", 0) # Does not work!!! proxy = win32inet.WinHttpGetProxyForUrl( hinternet, u"http://www.foo.com", 0 ) </code></pre> <p>As you can see, all I am trying to do is use the win32inet feature to find out which proxy is the appropriate one to use for a given URL, int his case foo.com.</p> <p>Can you help me correct the syntax of the last line? MSN has some <a href="http://msdn.microsoft.com/en-us/library/aa384097%28VS.85%29.aspx" rel="nofollow">good documentation for the function being wrapped</a> but the args do not seem to map the to those of the python library perfectly.</p> <p>The fixed version of this script should:</p> <ul> <li><p>Be able to look up which proxy to use for any given URL.</p></li> <li><p>It should always do exactly what Internet Explorer would do (i.e. use the same proxy)</p></li> <li><p>It should be valid on any valid Windows XP set-up. That means it should work with an explicitly configured proxy and also no proxy at all. </p></li> <li><p>It only needs to work on Windows XP 32bit with Python 2.4.4. It can use any official released version of win32com.</p></li> </ul> <p>I'm using Python2.4.4 with Win32Com on Windows XP. </p> <p>UPDATE 0:</p> <p>OR... can you give me an alternative implementation in cTypes? As long as I can make it work I'm happy!</p>
3
2009-07-03T14:41:10Z
21,117,496
<p>At least with <code>Python 2.7.6</code> and <code>Pywin 218</code> on Windows XP x86 and Windows 8 x64, it works:</p> <pre><code>import win32inet # http://msdn.microsoft.com/en-us/library/windows/desktop/aa384098(v=vs.85).aspx hinternet = win32inet.WinHttpOpen("foo", 0, "", "", 0) # http://msdn.microsoft.com/en-us/library/windows/desktop/aa384123(v=vs.85).aspx autoproxy_options = (2, 0, u"http://your-proxy-script-path", None, 0, 1) # http://msdn.microsoft.com/en-us/library/windows/desktop/aa384097(v=vs.85).aspx proxy = win32inet.WinHttpGetProxyForUrl(hinternet, u"http://www.google.com", autoproxy_options) print proxy </code></pre> <p>Worth to mention that the example uses the autoproxy option WINHTTP_AUTOPROXY_CONFIG_URL in order to pass in an explicit URL. You can use other options, for instance, if you want to autodetect using DNS or DHCP you can do:</p> <pre><code>autoproxy_options = (1, 1|2, u"", None, 0, 1) </code></pre> <p>You can find other options in the link showed above (in the code)</p>
1
2014-01-14T15:37:42Z
[ "python", "windows", "com", "32-bit", "winhttp" ]
Preventing invoking C types from Python
1,079,690
<p>What's the correct way to prevent invoking (creating an instance of) a C type from Python?</p> <p>I've considered providing a <code>tp_init</code> that raises an exception, but as I understand it that would still allow <code>__new__</code> to be called directly on the type.</p> <p>A C function returns instances of this type -- that's the only way instances of this type are intended to be created.</p> <p><strong>Edit:</strong> My intention is that users of my type will get an exception if they accidentally use it wrongly. The C code is such that calling a function on an object incorrectly created from Python would crash. I realise this is unusual: all of my C extension types so far have worked nicely when instantiated from Python. My question is whether there is a usual way to provide this restriction.</p>
2
2009-07-03T14:49:31Z
1,079,881
<p>Don't prevent them from doing it. "<a href="http://mail.python.org/pipermail/tutor/2003-October/025932.html" rel="nofollow">We're all consenting adults here</a>."</p> <p>Nobody is going to do it unless they have a reason, and if they have such a reason then you shouldn't stop them just because you didn't anticipate every possible use of your type.</p>
1
2009-07-03T15:36:27Z
[ "python", "cpython" ]
Preventing invoking C types from Python
1,079,690
<p>What's the correct way to prevent invoking (creating an instance of) a C type from Python?</p> <p>I've considered providing a <code>tp_init</code> that raises an exception, but as I understand it that would still allow <code>__new__</code> to be called directly on the type.</p> <p>A C function returns instances of this type -- that's the only way instances of this type are intended to be created.</p> <p><strong>Edit:</strong> My intention is that users of my type will get an exception if they accidentally use it wrongly. The C code is such that calling a function on an object incorrectly created from Python would crash. I realise this is unusual: all of my C extension types so far have worked nicely when instantiated from Python. My question is whether there is a usual way to provide this restriction.</p>
2
2009-07-03T14:49:31Z
1,079,981
<p>"The type is a return type of another C function - that's the only way instances of this type are intended to be created" -- that's rather confusing. I think you mean "A C function returns instances of this type -- that's the only way etc etc".</p> <p>In your documentation, warn the caller clearly against invoking the type. Don't export the type from your C extension. You can't do much about somebody who introspects the returned instances but so what? It's their data/machine/job at risk, not yours.</p> <p>[<strong>Update</strong> (I hate the UI for comments!)]</p> <p>James: "type ...just only created from C": again you are confusing the type and its instances. The type is created statically in C. Your C code contains the type and also a factory function that users are intended to call to obtain instances of the type. For some reason that you don't explain, if users obtain an instance by calling the type directly, subsequent instance.method() calls will crash (I presume that's what you mean by "calling functions on the object". Call me crazy, but <strong>isn't that a bug that you should fix?</strong></p> <p>Re "don't export": try "don't expose".</p> <p>In your C code, you will have something like this where you list out all the APIs that your module is providing, both types and functions:</p> <pre><code>static struct PyMethodDef public_functions[] = { {"EvilType", (PyCFunction) py_EvilType, ......}, /* omit above line and punters can't call it directly from Python */ {"make_evil", (PyCFunction) py_make_evil, ......}, ......, }; module = Py_InitModule4("mymodule", public_functions, module_doc, ... </code></pre>
0
2009-07-03T16:05:32Z
[ "python", "cpython" ]
Preventing invoking C types from Python
1,079,690
<p>What's the correct way to prevent invoking (creating an instance of) a C type from Python?</p> <p>I've considered providing a <code>tp_init</code> that raises an exception, but as I understand it that would still allow <code>__new__</code> to be called directly on the type.</p> <p>A C function returns instances of this type -- that's the only way instances of this type are intended to be created.</p> <p><strong>Edit:</strong> My intention is that users of my type will get an exception if they accidentally use it wrongly. The C code is such that calling a function on an object incorrectly created from Python would crash. I realise this is unusual: all of my C extension types so far have worked nicely when instantiated from Python. My question is whether there is a usual way to provide this restriction.</p>
2
2009-07-03T14:49:31Z
1,080,330
<p>There is a fantastically bulletproof way. Let people create the object, and have Python crash. That should stop them doing it pretty efficiently. ;)</p> <p>Also you can underscore the class name, to indicate that it should be internal. (At least, I assume you can create underscored classnames from C too, I haven't actually ever done it.)</p>
0
2009-07-03T17:58:57Z
[ "python", "cpython" ]
Preventing invoking C types from Python
1,079,690
<p>What's the correct way to prevent invoking (creating an instance of) a C type from Python?</p> <p>I've considered providing a <code>tp_init</code> that raises an exception, but as I understand it that would still allow <code>__new__</code> to be called directly on the type.</p> <p>A C function returns instances of this type -- that's the only way instances of this type are intended to be created.</p> <p><strong>Edit:</strong> My intention is that users of my type will get an exception if they accidentally use it wrongly. The C code is such that calling a function on an object incorrectly created from Python would crash. I realise this is unusual: all of my C extension types so far have worked nicely when instantiated from Python. My question is whether there is a usual way to provide this restriction.</p>
2
2009-07-03T14:49:31Z
1,080,514
<p>Simple: leave the tp_new slot of the type empty.</p> <pre><code>&gt;&gt;&gt; Foo() Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: cannot create 'foo.Foo' instances &gt;&gt;&gt; Foo.__new__(Foo) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: object.__new__(foo.Foo) is not safe, use foo.Foo.__new__() </code></pre> <p>If you inherit from a type other than the base object type, you will have to set tp_new to NULL after calling PyType_Ready().</p>
3
2009-07-03T19:12:16Z
[ "python", "cpython" ]
How do you extract a JAR in a UNIX filesystem with a single command and specify its target directory using the JAR command?
1,079,693
<p>I am creating a Python script within which I am executing UNIX system commands. I have a war archive named Binaries.war which is within an ear archive named Portal.ear</p> <p>The Portal ear file resides in, say /home/foo/bar/</p> <pre><code>jar xf /home/foo/bar/Portal.ear Binaries.war </code></pre> <p>Will extract the Binaries.war file out of the /home/foo/bar/Portal.ear archive into the current directory I am running the script from.</p> <p>How do you specify a target directory to be extracted to using just one command? I would like to do something like this to extract Binaries.war into the directory /home/foo/bar/baz </p> <pre><code>jar xf /home/foo/bar/Portal.ear Binaries.war [into target directory /home/foo/bar/baz] </code></pre> <p>I searched the the JAR man page for options and can't seem to find a simple way to do this. Of course I can extract the archive into my current directory and then move it using mv but I'd like to do this in one shot and not shuffle directories and files around.</p>
36
2009-07-03T14:50:06Z
1,079,726
<p>I don't think the jar tool supports this natively, but you can just unzip a JAR file with "unzip" and specify the output directory with that with the "-d" option, so something like:</p> <pre><code>$ unzip -d /home/foo/bar/baz /home/foo/bar/Portal.ear Binaries.war </code></pre>
47
2009-07-03T14:56:40Z
[ "java", "python", "linux", "unix", "jar" ]
How do you extract a JAR in a UNIX filesystem with a single command and specify its target directory using the JAR command?
1,079,693
<p>I am creating a Python script within which I am executing UNIX system commands. I have a war archive named Binaries.war which is within an ear archive named Portal.ear</p> <p>The Portal ear file resides in, say /home/foo/bar/</p> <pre><code>jar xf /home/foo/bar/Portal.ear Binaries.war </code></pre> <p>Will extract the Binaries.war file out of the /home/foo/bar/Portal.ear archive into the current directory I am running the script from.</p> <p>How do you specify a target directory to be extracted to using just one command? I would like to do something like this to extract Binaries.war into the directory /home/foo/bar/baz </p> <pre><code>jar xf /home/foo/bar/Portal.ear Binaries.war [into target directory /home/foo/bar/baz] </code></pre> <p>I searched the the JAR man page for options and can't seem to find a simple way to do this. Of course I can extract the archive into my current directory and then move it using mv but I'd like to do this in one shot and not shuffle directories and files around.</p>
36
2009-07-03T14:50:06Z
1,079,733
<p>Can't you just change working directory within the python script using <a href="http://docs.python.org/library/os.html" rel="nofollow"><code>os.chdir(target)</code></a>? I agree, I can't see any way of doing it from the jar command itself.</p> <p>If you don't want to permanently change directory, then store the current directory (using <code>os.getcwd()</code>)in a variable and change back afterwards.</p>
1
2009-07-03T14:57:56Z
[ "java", "python", "linux", "unix", "jar" ]
How do you extract a JAR in a UNIX filesystem with a single command and specify its target directory using the JAR command?
1,079,693
<p>I am creating a Python script within which I am executing UNIX system commands. I have a war archive named Binaries.war which is within an ear archive named Portal.ear</p> <p>The Portal ear file resides in, say /home/foo/bar/</p> <pre><code>jar xf /home/foo/bar/Portal.ear Binaries.war </code></pre> <p>Will extract the Binaries.war file out of the /home/foo/bar/Portal.ear archive into the current directory I am running the script from.</p> <p>How do you specify a target directory to be extracted to using just one command? I would like to do something like this to extract Binaries.war into the directory /home/foo/bar/baz </p> <pre><code>jar xf /home/foo/bar/Portal.ear Binaries.war [into target directory /home/foo/bar/baz] </code></pre> <p>I searched the the JAR man page for options and can't seem to find a simple way to do this. Of course I can extract the archive into my current directory and then move it using mv but I'd like to do this in one shot and not shuffle directories and files around.</p>
36
2009-07-03T14:50:06Z
1,079,803
<p>If your jar file already has an absolute pathname as shown, it is particularly easy:</p> <pre><code>cd /where/you/want/it; jar xf /path/to/jarfile.jar </code></pre> <p>That is, you have the shell executed by Python change directory for you and then run the extraction.</p> <p>If your jar file does not already have an absolute pathname, then you have to convert the relative name to absolute (by prefixing it with the path of the current directory) so that <code>jar</code> can find it after the change of directory.</p> <p>The only issues left to worry about are things like blanks in the path names.</p>
48
2009-07-03T15:12:40Z
[ "java", "python", "linux", "unix", "jar" ]
How do you extract a JAR in a UNIX filesystem with a single command and specify its target directory using the JAR command?
1,079,693
<p>I am creating a Python script within which I am executing UNIX system commands. I have a war archive named Binaries.war which is within an ear archive named Portal.ear</p> <p>The Portal ear file resides in, say /home/foo/bar/</p> <pre><code>jar xf /home/foo/bar/Portal.ear Binaries.war </code></pre> <p>Will extract the Binaries.war file out of the /home/foo/bar/Portal.ear archive into the current directory I am running the script from.</p> <p>How do you specify a target directory to be extracted to using just one command? I would like to do something like this to extract Binaries.war into the directory /home/foo/bar/baz </p> <pre><code>jar xf /home/foo/bar/Portal.ear Binaries.war [into target directory /home/foo/bar/baz] </code></pre> <p>I searched the the JAR man page for options and can't seem to find a simple way to do this. Of course I can extract the archive into my current directory and then move it using mv but I'd like to do this in one shot and not shuffle directories and files around.</p>
36
2009-07-03T14:50:06Z
1,121,899
<p>If this is a personal script, rather than one you're planning on distributing, it might be simpler to write a shell function for this:</p> <pre><code>function warextract { jar xf $1 $2 &amp;&amp; mv $2 $3 } </code></pre> <p>which you could then call from python like so:</p> <pre><code>warextract /home/foo/bar/Portal.ear Binaries.war /home/foo/bar/baz/ </code></pre> <p>If you really feel like it, you could use sed to parse out the filename from the path, so that you'd be able to call it with</p> <pre><code>warextract /home/foo/bar/Portal.ear /home/foo/bar/baz/Binaries.war </code></pre> <p>I'll leave that as an excercise to the reader, though.</p> <p>Of course, since this will extract the .war out into the current directory first, and then move it, it has the possibility of overwriting something with the same name where you are.</p> <p>Changing directory, extracting it, and cd-ing back is a bit cleaner, but I find myself using little one-line shell functions like this all the time when I want to reduce code clutter.</p>
1
2009-07-13T20:39:49Z
[ "java", "python", "linux", "unix", "jar" ]