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
listlengths
1
5
how to get the function declaration or definitions using regex
943,391
<p>I want to get only function prototypes like</p> <pre><code>int my_func(char, int, float) void my_func1(void) my_func2() </code></pre> <p>from C files using regex and python.</p> <p>Here is my regex format: <code>".*\(.*|[\r\n]\)\n"</code></p>
4
2009-06-03T06:45:13Z
943,429
<p>This is a convenient script I wrote for such tasks but it wont give the function types. It's only for function names and the argument list.</p> <pre><code># Exctract routine signatures from a C++ module import re def loadtxt(filename): "Load text file into a string. I let FILE exceptions to pass." f = open...
6
2009-06-03T06:58:45Z
[ "python", "regex" ]
how to get the function declaration or definitions using regex
943,391
<p>I want to get only function prototypes like</p> <pre><code>int my_func(char, int, float) void my_func1(void) my_func2() </code></pre> <p>from C files using regex and python.</p> <p>Here is my regex format: <code>".*\(.*|[\r\n]\)\n"</code></p>
4
2009-06-03T06:45:13Z
943,486
<p>See if your C compiler has an option to output a file of just the prototypes of what it is compiling. For gcc, it's -aux-info FILENAME</p>
2
2009-06-03T07:23:46Z
[ "python", "regex" ]
how to get the function declaration or definitions using regex
943,391
<p>I want to get only function prototypes like</p> <pre><code>int my_func(char, int, float) void my_func1(void) my_func2() </code></pre> <p>from C files using regex and python.</p> <p>Here is my regex format: <code>".*\(.*|[\r\n]\)\n"</code></p>
4
2009-06-03T06:45:13Z
943,520
<p>I think regex isn't best solution in your case. There are many traps like comments, text in string etc., but if your function prototypes share common style:</p> <pre><code>type fun_name(args); </code></pre> <p>then <code>\w+ \w+\(.*\);</code> should work in most cases:</p> <pre><code>mn&gt; egrep "\w+ \w+\(.*\);"...
0
2009-06-03T07:40:44Z
[ "python", "regex" ]
how to get the function declaration or definitions using regex
943,391
<p>I want to get only function prototypes like</p> <pre><code>int my_func(char, int, float) void my_func1(void) my_func2() </code></pre> <p>from C files using regex and python.</p> <p>Here is my regex format: <code>".*\(.*|[\r\n]\)\n"</code></p>
4
2009-06-03T06:45:13Z
943,870
<p>I think this one should do the work:</p> <pre><code>r"^\s*[\w_][\w\d_]*\s*.*\s*[\w_][\w\d_]*\s*\(.*\)\s*$" </code></pre> <p>which will be expanded into:</p> <pre><code>string begin: ^ any number of whitespaces (including none): \s* return type: - start with letter or _: [\w_] - continue with...
1
2009-06-03T09:44:56Z
[ "python", "regex" ]
how to get the function declaration or definitions using regex
943,391
<p>I want to get only function prototypes like</p> <pre><code>int my_func(char, int, float) void my_func1(void) my_func2() </code></pre> <p>from C files using regex and python.</p> <p>Here is my regex format: <code>".*\(.*|[\r\n]\)\n"</code></p>
4
2009-06-03T06:45:13Z
944,421
<p>There are LOTS of pitfalls trying to "parse" C code (or extract some information at least) with just regular expressions, I will definitely borrow a C for your favourite parser generator (say Bison or whatever alternative there is for Python, there are C grammar as examples everywhere) and add the actions in the cor...
1
2009-06-03T12:20:31Z
[ "python", "regex" ]
how to get the function declaration or definitions using regex
943,391
<p>I want to get only function prototypes like</p> <pre><code>int my_func(char, int, float) void my_func1(void) my_func2() </code></pre> <p>from C files using regex and python.</p> <p>Here is my regex format: <code>".*\(.*|[\r\n]\)\n"</code></p>
4
2009-06-03T06:45:13Z
33,208,691
<p>The regular expression below consider also the definition of destructor or const functions:</p> <pre><code>^\s*\~{0,1}[\w_][\w\d_]*\s*.*\s*[\w_][\w\d_]*\s*\(.*\)\s*(const){0,1}$ </code></pre>
0
2015-10-19T07:19:21Z
[ "python", "regex" ]
how to get the function declaration or definitions using regex
943,391
<p>I want to get only function prototypes like</p> <pre><code>int my_func(char, int, float) void my_func1(void) my_func2() </code></pre> <p>from C files using regex and python.</p> <p>Here is my regex format: <code>".*\(.*|[\r\n]\)\n"</code></p>
4
2009-06-03T06:45:13Z
36,995,949
<p>I built on Nick Dandoulakis's <a href="http://stackoverflow.com/a/943429/724752">answer</a> for a similar use case. I wanted to find the definition of the <code>socket</code> function in glibc. This finds a bunch of functions with "socket" in the name but <code>socket</code> was not found, highlighting what many oth...
0
2016-05-03T05:02:17Z
[ "python", "regex" ]
Python: Getting file modification times with greater resolution than a second
943,503
<p><code>os.path.getmtime()</code> and <code>os.stat()</code> seem to return values in whole seconds only.</p> <p>Is this the greatest resolution possible on either a Windows or OSX file system, or is there a way of getting greater resolution on file times?</p>
3
2009-06-03T07:32:36Z
943,532
<p><a href="http://docs.python.org/library/os.html#os.stat" rel="nofollow">The documentation for os.stat()</a> has a note that says:</p> <blockquote> <p>The exact meaning and resolution of the st_atime, st_mtime, and st_ctime members depends on the operating system and the file system. For example, on Window...
3
2009-06-03T07:44:30Z
[ "python", "windows", "osx", "filesystems", "timestamp" ]
Python: Getting file modification times with greater resolution than a second
943,503
<p><code>os.path.getmtime()</code> and <code>os.stat()</code> seem to return values in whole seconds only.</p> <p>Is this the greatest resolution possible on either a Windows or OSX file system, or is there a way of getting greater resolution on file times?</p>
3
2009-06-03T07:32:36Z
943,537
<p>HFS+ (used by OS X) has a date resolution of <a href="http://en.wikipedia.org/wiki/HFS%5FPlus" rel="nofollow">one second</a>.</p>
3
2009-06-03T07:46:47Z
[ "python", "windows", "osx", "filesystems", "timestamp" ]
Python: Getting file modification times with greater resolution than a second
943,503
<p><code>os.path.getmtime()</code> and <code>os.stat()</code> seem to return values in whole seconds only.</p> <p>Is this the greatest resolution possible on either a Windows or OSX file system, or is there a way of getting greater resolution on file times?</p>
3
2009-06-03T07:32:36Z
943,563
<p>As documented in <a href="http://docs.python.org/library/os" rel="nofollow">the Python <code>os</code> module</a>, it is a portable interface to OS-specific functionality. Depending on what platform you're running on, you will get different behaviour.</p> <p>Specifically, the modification time returned by <code>sta...
1
2009-06-03T07:55:03Z
[ "python", "windows", "osx", "filesystems", "timestamp" ]
String manipulation in Cython
943,809
<p>I have code that does some very CPU-intensive string manipulations and I was looking for ways to improve performance.</p> <p>(EDIT: I'm doing stuff like finding longest common substring, running lots of regular expressions which might be better expressed as state machines in c, stripping comments from HTML, stuff l...
19
2009-06-03T09:19:23Z
944,512
<p>I voted up the 'profile it' answer, but wanted to add this: where possible the best optimisation you can make is to use Python standard libraries or built-in functions to perform the tasks you want. These are typically implemented in C and will provide performance broadly equivalent to any extension, including exten...
9
2009-06-03T12:41:38Z
[ "python", "string", "cython" ]
String manipulation in Cython
943,809
<p>I have code that does some very CPU-intensive string manipulations and I was looking for ways to improve performance.</p> <p>(EDIT: I'm doing stuff like finding longest common substring, running lots of regular expressions which might be better expressed as state machines in c, stripping comments from HTML, stuff l...
19
2009-06-03T09:19:23Z
1,560,811
<p>This is a very interesting issue. Cython at its core is a tool to integrate python with C data types. It doesn't supply any functionality to assist in dealing with strings, probably because there isn't as much demand for that as there is for specific Numpy functionality.</p> <p>Having said that, you could well use ...
4
2009-10-13T15:02:17Z
[ "python", "string", "cython" ]
String manipulation in Cython
943,809
<p>I have code that does some very CPU-intensive string manipulations and I was looking for ways to improve performance.</p> <p>(EDIT: I'm doing stuff like finding longest common substring, running lots of regular expressions which might be better expressed as state machines in c, stripping comments from HTML, stuff l...
19
2009-06-03T09:19:23Z
1,803,176
<p>Just for completeness, what I ended up doing is just write (some of) the string manipulation code in C.</p> <p>As it turns out, it's <a href="http://en.wikibooks.org/wiki/Python%5FProgramming/Extending%5Fwith%5FC">ridiculously easy</a> to get started writing c extensions to python. Unicode strings are just arrays o...
5
2009-11-26T11:36:11Z
[ "python", "string", "cython" ]
String manipulation in Cython
943,809
<p>I have code that does some very CPU-intensive string manipulations and I was looking for ways to improve performance.</p> <p>(EDIT: I'm doing stuff like finding longest common substring, running lots of regular expressions which might be better expressed as state machines in c, stripping comments from HTML, stuff l...
19
2009-06-03T09:19:23Z
1,806,183
<p>"Ridiculously easy" is a very relative term. "Getting started" is just that. Writing robust extensions in C requires very careful attention to things like reference counting, memory allocation/freeing, and error handling. Cython does much of that for you.</p> <p>A non-unicode string in Cython is either a Python str...
7
2009-11-26T23:57:05Z
[ "python", "string", "cython" ]
String manipulation in Cython
943,809
<p>I have code that does some very CPU-intensive string manipulations and I was looking for ways to improve performance.</p> <p>(EDIT: I'm doing stuff like finding longest common substring, running lots of regular expressions which might be better expressed as state machines in c, stripping comments from HTML, stuff l...
19
2009-06-03T09:19:23Z
5,687,072
<p>Note that Cython actually has support for CPython's Py_UNICODE type, so, for example, you can directly iterate over unicode strings or compare characters at C speed. See</p> <p><a href="http://docs.cython.org/src/tutorial/strings.html" rel="nofollow">http://docs.cython.org/src/tutorial/strings.html</a></p>
3
2011-04-16T14:15:20Z
[ "python", "string", "cython" ]
String manipulation in Cython
943,809
<p>I have code that does some very CPU-intensive string manipulations and I was looking for ways to improve performance.</p> <p>(EDIT: I'm doing stuff like finding longest common substring, running lots of regular expressions which might be better expressed as state machines in c, stripping comments from HTML, stuff l...
19
2009-06-03T09:19:23Z
9,335,037
<p>I've been recently introduced to Cython and have had great success wrapping large C and C++ libraries for use in significant projects. Some of the generated Python extensions are in fact already running in our production environment. So, first off, Cython is, imo, definitely a good choice.</p> <p>That being said,...
2
2012-02-17T20:37:35Z
[ "python", "string", "cython" ]
Connect to a running instance of Visual Studio 2003 using COM, build and read output
943,863
<p>For Visual Studio 6.0, I can connect to a running instance like:</p> <pre><code>o = GetActiveObject("MSDev.Application") </code></pre> <ul> <li>What prog ID do I use for Visual Studio 2003?</li> <li>How do I execute a 'Build Solution' once I have the COM object that references the VS2003 instance?</li> <li>How do ...
1
2009-06-03T09:43:16Z
944,009
<p>After a bit of research (mainly looking at EnvDTE docs), I found the solution to this myself:</p> <p>To build current solution (code in Python):</p> <pre><code>def build_active_solution(progid="VisualStudio.DTE.7.1"): from win32com.client import GetActiveObject dte = GetActiveObject(progid) sb = dte.So...
2
2009-06-03T10:19:43Z
[ "python", "visual-studio", "com" ]
pygtk gui freezes with pyjack thread
944,161
<p>I have a program that records audio from firewire device (FA-66) with Jack connection. The interface is created with pygtk and the recording with py-jack (<a href="http://sourceforge.net/projects/py-jack/" rel="nofollow">http://sourceforge.net/projects/py-jack/</a>). The recording is done in a different thread becau...
0
2009-06-03T11:06:56Z
945,377
<p>You misunderstand how threads work. </p> <p>Threads don't help you in this case. </p> <blockquote> <p><em>"Then when one sample is recorded, it will be analyzed and the results are shown in the GUI. At the same time the next sample is already being recorded."</em></p> </blockquote> <p><strong>WRONG</stron...
2
2009-06-03T15:20:15Z
[ "python", "multithreading", "pygtk" ]
Method that gets called on module deletion in Python
944,336
<p>Is there a method that I can add to my module, which will get called when destructing the class?</p> <p>We have a simple class which has only static member functions and needs to clean up the database connection when unloading the module.</p> <p>Was hoping there would be a <code>__del__</code> method either for mo...
4
2009-06-03T12:00:03Z
944,354
<p>Use the del method:</p> <pre><code>class Foo: def __init__(self): print "constructor called." def __del__(self): print "destructor called." </code></pre>
-1
2009-06-03T12:04:26Z
[ "python", "destructor", "shutdown" ]
Method that gets called on module deletion in Python
944,336
<p>Is there a method that I can add to my module, which will get called when destructing the class?</p> <p>We have a simple class which has only static member functions and needs to clean up the database connection when unloading the module.</p> <p>Was hoping there would be a <code>__del__</code> method either for mo...
4
2009-06-03T12:00:03Z
944,358
<p>The class destructor method you're looking for is <code>__del__</code>. There are some nuances to when it's called, and to how exceptions and subclassing should be handled in <code>__del__</code>, so be sure to read the <a href="http://docs.python.org/reference/datamodel.html#special-method-names" rel="nofollow">off...
0
2009-06-03T12:05:17Z
[ "python", "destructor", "shutdown" ]
Method that gets called on module deletion in Python
944,336
<p>Is there a method that I can add to my module, which will get called when destructing the class?</p> <p>We have a simple class which has only static member functions and needs to clean up the database connection when unloading the module.</p> <p>Was hoping there would be a <code>__del__</code> method either for mo...
4
2009-06-03T12:00:03Z
944,359
<p>When destructing which class? I though you said module?</p> <p>Your module lives until the interpreter stops. you can add something to run at that time using the "atexit" module:</p> <pre><code>import atexit atexit.register(myfunction) </code></pre> <p><hr /></p> <p>EDIT: Based on your comments.</p> <p>Since yo...
16
2009-06-03T12:05:17Z
[ "python", "destructor", "shutdown" ]
Method that gets called on module deletion in Python
944,336
<p>Is there a method that I can add to my module, which will get called when destructing the class?</p> <p>We have a simple class which has only static member functions and needs to clean up the database connection when unloading the module.</p> <p>Was hoping there would be a <code>__del__</code> method either for mo...
4
2009-06-03T12:00:03Z
15,322,774
<p>Tested using bpython...</p> <pre><code>&gt;&gt;&gt; import atexit &gt;&gt;&gt; class Test( object ): ... @staticmethod ... def __cleanup__(): ... print("cleanup") ... atexit.register(Test.__cleanup__) ... Traceback (most recent call last): File "&lt;input&gt;", line 1, in &lt;module&gt; Fil...
0
2013-03-10T13:30:32Z
[ "python", "destructor", "shutdown" ]
copy worksheet from one spreadsheet to another
944,419
<p>Is it possible to copy spreadsheets with gdata API or worksheets from one spreadsheet to other? For now i copy all cells from one worksheet to another. One cell per request. It is too slow. I read about "cell batch processing" and write this code:</p> <pre> <code> src_key = 'rFQqEnFWuR6qoU2HEfdVuTw'; dst_key = 'rPC...
1
2009-06-03T12:20:22Z
1,615,889
<p>You probably should be using a <a href="http://code.google.com/apis/spreadsheets/data/1.0/developers%5Fguide%5Fpython.html#cellsQueryExample" rel="nofollow">cell range query</a> to get a whole row at a time, then <a href="http://code.google.com/apis/spreadsheets/data/1.0/developers%5Fguide%5Fpython.html#addRow" rel=...
1
2009-10-23T21:05:02Z
[ "python", "gdata-api", "google-docs", "gdata" ]
Execution of a OS command from a Python daemon
944,501
<p>I've got a daemon.py with a callback. How should I make the handler function execute a OS command?</p>
0
2009-06-03T12:39:03Z
944,508
<p>when i learned Python some time ago, I used:</p> <pre><code>import os os.system('ls -lt') </code></pre> <p>but it seems like in Python 3.x, the recommended use is <a href="http://docs.python.org/library/commands.html" rel="nofollow">commands</a> or <a href="http://docs.python.org/library/os.html#os.popen" rel="nof...
-2
2009-06-03T12:40:34Z
[ "python", "bash", "operating-system", "command", "handler" ]
Efficient way of creating recursive paths Python
944,536
<p>Hi I need a simple function to create a path in Python where the parent may or may not exist. </p> <p>From python documentation os.makedirs will fail if one of the parents exists.</p> <p>I have written the below method as which works by makes as many sub directories as necessary.</p> <p>Does this look efficient?...
13
2009-06-03T12:46:07Z
944,561
<blockquote> <p>"From python documentation <code>os.makedirs</code> will fail if one of the parents exists."</p> </blockquote> <p>No, <a href="http://docs.python.org/library/os.html#os.makedirs"><code>os.makedirs</code></a> will fail if the directory itself already exists. It won't fail if just any of the parent dir...
42
2009-06-03T12:50:37Z
[ "python", "path", "operating-system" ]
Efficient way of creating recursive paths Python
944,536
<p>Hi I need a simple function to create a path in Python where the parent may or may not exist. </p> <p>From python documentation os.makedirs will fail if one of the parents exists.</p> <p>I have written the below method as which works by makes as many sub directories as necessary.</p> <p>Does this look efficient?...
13
2009-06-03T12:46:07Z
7,016,628
<p>Rough draft:</p> <pre><code>import os class Path(str): """ A helper class that allows easy contactenation of path components, creation of directory trees, amongst other things. """ @property def isdir(self): return os.path.isdir(self) @property def isfile(self): ...
4
2011-08-10T19:30:17Z
[ "python", "path", "operating-system" ]
Efficient way of creating recursive paths Python
944,536
<p>Hi I need a simple function to create a path in Python where the parent may or may not exist. </p> <p>From python documentation os.makedirs will fail if one of the parents exists.</p> <p>I have written the below method as which works by makes as many sub directories as necessary.</p> <p>Does this look efficient?...
13
2009-06-03T12:46:07Z
13,183,555
<p>Try this code, it checks if path exists till n sub directory level, and create directory if not exists.</p> <pre><code>def pathtodir(path): if not os.path.exists(path): l=[] p = "/" l = path.split("/") i = 1 while i &lt; len(l): p = p + l[i] + "/" i = i + 1 if not os.path...
2
2012-11-01T18:46:58Z
[ "python", "path", "operating-system" ]
Efficient way of creating recursive paths Python
944,536
<p>Hi I need a simple function to create a path in Python where the parent may or may not exist. </p> <p>From python documentation os.makedirs will fail if one of the parents exists.</p> <p>I have written the below method as which works by makes as many sub directories as necessary.</p> <p>Does this look efficient?...
13
2009-06-03T12:46:07Z
21,349,806
<p>Here's my take, which lets the system libraries do all the path-wrangling. Any errors other than the directory already existing are propagated.</p> <pre><code>import os, errno def ensure_dir(dirname): """ Ensure that a named directory exists; if it does not, attempt to create it. """ try: ...
12
2014-01-25T11:15:18Z
[ "python", "path", "operating-system" ]
Efficient way of creating recursive paths Python
944,536
<p>Hi I need a simple function to create a path in Python where the parent may or may not exist. </p> <p>From python documentation os.makedirs will fail if one of the parents exists.</p> <p>I have written the below method as which works by makes as many sub directories as necessary.</p> <p>Does this look efficient?...
13
2009-06-03T12:46:07Z
24,973,246
<p>I found this question while researching a way to make simple directory trees inside of a project directory.</p> <p>I am somewhat new to Python, and I struggle when data structures get too complex, i.e. nested. It is much easier on my brain's mental mapping to keep track of small lists of iterables, so I came up wit...
1
2014-07-26T16:42:28Z
[ "python", "path", "operating-system" ]
Efficient way of creating recursive paths Python
944,536
<p>Hi I need a simple function to create a path in Python where the parent may or may not exist. </p> <p>From python documentation os.makedirs will fail if one of the parents exists.</p> <p>I have written the below method as which works by makes as many sub directories as necessary.</p> <p>Does this look efficient?...
13
2009-06-03T12:46:07Z
29,508,062
<p>With python ( >=3.4.1 ) there is exist_ok parameter for os.makedirs.</p> <blockquote> <p>If exist_ok is False (the default), an OSError is raised if the target directory already exists.</p> </blockquote> <p>So if you use like exist_ok=True there won't be any problem for Recursive directory creation.</p> <bloc...
2
2015-04-08T07:04:39Z
[ "python", "path", "operating-system" ]
Efficient way of creating recursive paths Python
944,536
<p>Hi I need a simple function to create a path in Python where the parent may or may not exist. </p> <p>From python documentation os.makedirs will fail if one of the parents exists.</p> <p>I have written the below method as which works by makes as many sub directories as necessary.</p> <p>Does this look efficient?...
13
2009-06-03T12:46:07Z
38,077,347
<p><a href="https://gist.github.com/samuelsh/b837f8ab8b33c344f01128568dd12019" rel="nofollow">This code</a> will generate directory tree with given depth and width, using recursive function call:</p> <pre><code>#!/usr/bin/python2.6 import sys import os def build_dir_tree(base, depth, width): print("Call #%d" % d...
0
2016-06-28T13:15:55Z
[ "python", "path", "operating-system" ]
Best practice for Python Assert
944,592
<ol> <li><p>Is there a performance or code maintenance issue with using <code>assert</code> as part of the standard code instead of using it just for debugging purposes?</p> <p>Is</p> <pre><code>assert x &gt;= 0, 'x is less than zero' </code></pre> <p>better or worse than </p> <pre><code>if x &lt; 0: raise Exce...
291
2009-06-03T12:57:16Z
944,660
<p>To be able to automatically throw an error when x become less than zero throughout the function. You can use <a href="http://docs.python.org/reference/datamodel.html#implementing-descriptors">class descriptors</a>. Here is an example:</p> <pre><code>class LessThanZeroException(Exception): pass class variable(o...
102
2009-06-03T13:12:18Z
[ "python", "assert", "raise" ]
Best practice for Python Assert
944,592
<ol> <li><p>Is there a performance or code maintenance issue with using <code>assert</code> as part of the standard code instead of using it just for debugging purposes?</p> <p>Is</p> <pre><code>assert x &gt;= 0, 'x is less than zero' </code></pre> <p>better or worse than </p> <pre><code>if x &lt; 0: raise Exce...
291
2009-06-03T12:57:16Z
944,661
<p>The only thing that's really wrong with this approach is that it's hard to make a very descriptive exception using assert statements. If you're looking for the simpler syntax, remember you <em>can</em> also do something like this:</p> <pre><code>class XLessThanZeroException(Exception): pass def CheckX(x): ...
13
2009-06-03T13:12:25Z
[ "python", "assert", "raise" ]
Best practice for Python Assert
944,592
<ol> <li><p>Is there a performance or code maintenance issue with using <code>assert</code> as part of the standard code instead of using it just for debugging purposes?</p> <p>Is</p> <pre><code>assert x &gt;= 0, 'x is less than zero' </code></pre> <p>better or worse than </p> <pre><code>if x &lt; 0: raise Exce...
291
2009-06-03T12:57:16Z
945,135
<p>Asserts should be used to test conditions that <em>should never happen</em>. The purpose is to crash early in the case of a corrupt program state.</p> <p>Exceptions should be used for errors that can conceivably happen, and you should almost always create your own Exception classes.</p> <p><hr /></p> <p>For exam...
509
2009-06-03T14:34:29Z
[ "python", "assert", "raise" ]
Best practice for Python Assert
944,592
<ol> <li><p>Is there a performance or code maintenance issue with using <code>assert</code> as part of the standard code instead of using it just for debugging purposes?</p> <p>Is</p> <pre><code>assert x &gt;= 0, 'x is less than zero' </code></pre> <p>better or worse than </p> <pre><code>if x &lt; 0: raise Exce...
291
2009-06-03T12:57:16Z
1,838,411
<p><strong>"assert" statements are removed when the compilation is optimized</strong>. So, yes, there are both performance and functional differences.</p> <blockquote> <p>The current code generator emits no code for an assert statement when optimization is requested at compile time. - <a href="http://docs.python.or...
242
2009-12-03T08:15:24Z
[ "python", "assert", "raise" ]
Best practice for Python Assert
944,592
<ol> <li><p>Is there a performance or code maintenance issue with using <code>assert</code> as part of the standard code instead of using it just for debugging purposes?</p> <p>Is</p> <pre><code>assert x &gt;= 0, 'x is less than zero' </code></pre> <p>better or worse than </p> <pre><code>if x &lt; 0: raise Exce...
291
2009-06-03T12:57:16Z
1,839,402
<p>In addition to the other answers, asserts themselves throw exceptions, but only AssertionErrors. From a utilitarian standpoint, assertions aren't suitable for when you need fine grain control over which exceptions you catch.</p>
14
2009-12-03T11:37:29Z
[ "python", "assert", "raise" ]
Best practice for Python Assert
944,592
<ol> <li><p>Is there a performance or code maintenance issue with using <code>assert</code> as part of the standard code instead of using it just for debugging purposes?</p> <p>Is</p> <pre><code>assert x &gt;= 0, 'x is less than zero' </code></pre> <p>better or worse than </p> <pre><code>if x &lt; 0: raise Exce...
291
2009-06-03T12:57:16Z
7,759,918
<p>There's a framework called JBoss <a href="http://www.jboss.org/drools" rel="nofollow">Drools</a> for java that does runtime monitoring to assert business rules, which answers the second part of your question. However, I am unsure if there is such a framework for python. </p>
2
2011-10-13T20:15:01Z
[ "python", "assert", "raise" ]
Best practice for Python Assert
944,592
<ol> <li><p>Is there a performance or code maintenance issue with using <code>assert</code> as part of the standard code instead of using it just for debugging purposes?</p> <p>Is</p> <pre><code>assert x &gt;= 0, 'x is less than zero' </code></pre> <p>better or worse than </p> <pre><code>if x &lt; 0: raise Exce...
291
2009-06-03T12:57:16Z
15,237,844
<p>As has been said previously, assertions should be used when your code SHOULD NOT ever reach a point, meaning there is a bug there. Probably the most useful reason I can see to use an assertion is an invariant/pre/postcondition. These are something that must be true at the start or end of each iteration of a loop or ...
5
2013-03-06T02:22:48Z
[ "python", "assert", "raise" ]
Best practice for Python Assert
944,592
<ol> <li><p>Is there a performance or code maintenance issue with using <code>assert</code> as part of the standard code instead of using it just for debugging purposes?</p> <p>Is</p> <pre><code>assert x &gt;= 0, 'x is less than zero' </code></pre> <p>better or worse than </p> <pre><code>if x &lt; 0: raise Exce...
291
2009-06-03T12:57:16Z
18,980,471
<p>Assume you work on 200,000 lines of code with four colleagues Alice, Bernd, Carl, and Daphne. They call your code, you call their code.</p> <p>Then <code>assert</code> has <strong>four roles</strong>:</p> <ol> <li><p><strong>Inform Alice, Bernd, Carl, and Daphne what your code expects.</strong><br> Assume you have...
76
2013-09-24T11:33:18Z
[ "python", "assert", "raise" ]
Best practice for Python Assert
944,592
<ol> <li><p>Is there a performance or code maintenance issue with using <code>assert</code> as part of the standard code instead of using it just for debugging purposes?</p> <p>Is</p> <pre><code>assert x &gt;= 0, 'x is less than zero' </code></pre> <p>better or worse than </p> <pre><code>if x &lt; 0: raise Exce...
291
2009-06-03T12:57:16Z
18,980,730
<p>As for "<em>Is there a performance issue</em>?":<br></p> <ul> <li><p>Please remember to <em>"make it work first before you make it work fast"</em>.<br> Very few percent of any program are usually relevant for its speed. You can always kick out or simplify an <code>assert</code> if it ever proves to be a performance...
2
2013-09-24T11:45:09Z
[ "python", "assert", "raise" ]
Best practice for Python Assert
944,592
<ol> <li><p>Is there a performance or code maintenance issue with using <code>assert</code> as part of the standard code instead of using it just for debugging purposes?</p> <p>Is</p> <pre><code>assert x &gt;= 0, 'x is less than zero' </code></pre> <p>better or worse than </p> <pre><code>if x &lt; 0: raise Exce...
291
2009-06-03T12:57:16Z
29,521,626
<p>In IDE's such as PTVS, PyCharm, Wing <code>assert isinstance()</code> statements can be used to enable code completion for some unclear objects.</p>
3
2015-04-08T17:40:32Z
[ "python", "assert", "raise" ]
Best practice for Python Assert
944,592
<ol> <li><p>Is there a performance or code maintenance issue with using <code>assert</code> as part of the standard code instead of using it just for debugging purposes?</p> <p>Is</p> <pre><code>assert x &gt;= 0, 'x is less than zero' </code></pre> <p>better or worse than </p> <pre><code>if x &lt; 0: raise Exce...
291
2009-06-03T12:57:16Z
40,084,762
<p>An Assert is to check -<br/> <strong>1. the valid condition,<br/> 2. the valid statement,<br/> 3. true logic;<br/></strong> of source code. Instead of failing the whole project it gives an alarm that something is not appropriate in your source file.</p> <p>In example 1, since variable 'str' is not nul. So no any...
0
2016-10-17T11:04:16Z
[ "python", "assert", "raise" ]
How to check for NaN in python?
944,700
<p><code>float('nan')</code> results in a thingy simply called nan. But how do I check for it? Should be very easy, but i cannot find it.</p>
300
2009-06-03T13:19:54Z
944,712
<p>The usual way to test for a NaN is to see if it's equal to itself:</p> <pre><code>def isNaN(num): return num != num </code></pre>
106
2009-06-03T13:22:05Z
[ "python", "math" ]
How to check for NaN in python?
944,700
<p><code>float('nan')</code> results in a thingy simply called nan. But how do I check for it? Should be very easy, but i cannot find it.</p>
300
2009-06-03T13:19:54Z
944,733
<p><a href="http://docs.python.org/library/math.html#math.isnan">math.isnan()</a></p> <blockquote> <p>Checks if the float x is a NaN (not a number). NaNs are part of the IEEE 754 standards. Operation like but not limited to inf * 0, inf / inf or any operation involving a NaN, e.g. nan * 1, return a NaN.</p> <p>...
407
2009-06-03T13:24:37Z
[ "python", "math" ]
How to check for NaN in python?
944,700
<p><code>float('nan')</code> results in a thingy simply called nan. But how do I check for it? Should be very easy, but i cannot find it.</p>
300
2009-06-03T13:19:54Z
944,734
<p><a href="http://docs.python.org/library/math.html#math.isnan">math.isnan()</a></p> <p>or compare the number to itself. NaN is always != NaN, otherwise (e.g. if it <em>is</em> a number) the comparison should succeed.</p>
12
2009-06-03T13:24:51Z
[ "python", "math" ]
How to check for NaN in python?
944,700
<p><code>float('nan')</code> results in a thingy simply called nan. But how do I check for it? Should be very easy, but i cannot find it.</p>
300
2009-06-03T13:19:54Z
944,756
<p><code>numpy.isnan(float)</code> tells you if it's <code>NaN</code> or not in Python 2.5.</p>
42
2009-06-03T13:28:31Z
[ "python", "math" ]
How to check for NaN in python?
944,700
<p><code>float('nan')</code> results in a thingy simply called nan. But how do I check for it? Should be very easy, but i cannot find it.</p>
300
2009-06-03T13:19:54Z
2,138,383
<p>Another method if you're stuck on &lt;2.6, you don't have numpy, and you don't have IEEE 754 support:</p> <pre><code>def isNaN(x): return str(x) == str(1e400*0) </code></pre>
9
2010-01-26T09:10:53Z
[ "python", "math" ]
How to check for NaN in python?
944,700
<p><code>float('nan')</code> results in a thingy simply called nan. But how do I check for it? Should be very easy, but i cannot find it.</p>
300
2009-06-03T13:19:54Z
3,060,088
<p>With python &lt; 2.6 I ended up with</p> <pre><code>def isNaN(x): return str(float(x)).lower() == 'nan' </code></pre> <p>This works for me with python 2.5.1 on a Solaris 5.9 box and with python 2.6.5 on Ubuntu 10 </p>
9
2010-06-17T08:35:39Z
[ "python", "math" ]
How to check for NaN in python?
944,700
<p><code>float('nan')</code> results in a thingy simply called nan. But how do I check for it? Should be very easy, but i cannot find it.</p>
300
2009-06-03T13:19:54Z
11,334,997
<p>Well I entered this post, because i've had some issues with the function:</p> <pre><code>math.isnan() </code></pre> <p>There are problem when you run this code:</p> <pre><code>a = "hello" math.isnan(a) </code></pre> <p>It raises exception. My solution for that is to make another check:</p> <pre><code>def is_nan...
5
2012-07-04T20:15:28Z
[ "python", "math" ]
How to check for NaN in python?
944,700
<p><code>float('nan')</code> results in a thingy simply called nan. But how do I check for it? Should be very easy, but i cannot find it.</p>
300
2009-06-03T13:19:54Z
12,588,878
<p>I actually just ran into this, but for me it was checking for nan, -inf, or inf. I just used</p> <pre><code>if float('-inf') &lt; float(num) &lt; float('inf'): </code></pre> <p>This is true for numbers, false for nan and both inf, and will raise an exception for things like strings or other types (which is probabl...
19
2012-09-25T18:22:03Z
[ "python", "math" ]
How to check for NaN in python?
944,700
<p><code>float('nan')</code> results in a thingy simply called nan. But how do I check for it? Should be very easy, but i cannot find it.</p>
300
2009-06-03T13:19:54Z
37,985,974
<p>I am receiving the data from a web-service that sends <code>NaN</code> as a string <code>'Nan'</code>. But there could be other sorts of string in my data as well, so a simple <code>float(value)</code> could throw an exception. I used the following variant of the accepted answer:</p> <pre><code>def isnan(value): ...
0
2016-06-23T08:22:33Z
[ "python", "math" ]
How to extract nested tables from HTML?
944,860
<p>I have an HTML file (encoded in utf-8). I open it with <code>codecs.open()</code>. The file architecture is:</p> <pre><code>&lt;html&gt; // header &lt;body&gt; // some text &lt;table&gt; // some rows with cells here // some cells contains tables &lt;/table&gt; // maybe some text here &lt;table&gt;...
4
2009-06-03T13:48:39Z
944,968
<p>Try <a href="http://www.crummy.com/software/BeautifulSoup/" rel="nofollow">beautiful soup</a></p> <p>In principle you need to use a real parser (which Beaut. Soup is), regex cannot deal with nested elements, for computer sciencey reasons (finite state machines can't parse context-free grammars, IIRC)</p>
4
2009-06-03T14:07:04Z
[ "python", "html", "html-table", "extract" ]
How to extract nested tables from HTML?
944,860
<p>I have an HTML file (encoded in utf-8). I open it with <code>codecs.open()</code>. The file architecture is:</p> <pre><code>&lt;html&gt; // header &lt;body&gt; // some text &lt;table&gt; // some rows with cells here // some cells contains tables &lt;/table&gt; // maybe some text here &lt;table&gt;...
4
2009-06-03T13:48:39Z
945,011
<p>If the HTML is well-formed you can parse it into a DOM tree and use XPath to extract the table you want. I usually use <a href="http://codespeak.net/lxml/index.html" rel="nofollow">lxml</a> for parsing XML, and <a href="http://codespeak.net/lxml/parsing.html" rel="nofollow">it can parse HTML as well</a>.</p> <p>The...
2
2009-06-03T14:13:23Z
[ "python", "html", "html-table", "extract" ]
How to extract nested tables from HTML?
944,860
<p>I have an HTML file (encoded in utf-8). I open it with <code>codecs.open()</code>. The file architecture is:</p> <pre><code>&lt;html&gt; // header &lt;body&gt; // some text &lt;table&gt; // some rows with cells here // some cells contains tables &lt;/table&gt; // maybe some text here &lt;table&gt;...
4
2009-06-03T13:48:39Z
945,097
<p>You may like <a href="http://codespeak.net/lxml/" rel="nofollow">lxml</a>. I'm not sure I really understood what you want to do with that structure, but maybe this example will help...</p> <pre><code>import lxml.html def process_row(row): for cell in row.xpath('./td'): inner_tables = cell.xpath('./table...
3
2009-06-03T14:29:27Z
[ "python", "html", "html-table", "extract" ]
Numpy: Should I use newaxis or None?
944,863
<p>In numpy one can use the 'newaxis' object in the slicing syntax to create an axis of length one, e.g.:</p> <pre><code>import numpy as np print np.zeros((3,5))[:,np.newaxis,:].shape # shape will be (3,1,5) </code></pre> <p>The <a href="http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#numpy.newaxis">do...
57
2009-06-03T13:48:45Z
945,313
<p><code>None</code> is allowed because <code>numpy.newaxis</code> is merely an alias for <code>None</code>.</p> <pre><code>In [1]: import numpy In [2]: numpy.newaxis is None Out[2]: True </code></pre> <p>The authors probably chose it because they needed a convenient constant, and <code>None</code> was available.</p...
65
2009-06-03T15:05:52Z
[ "python", "numpy" ]
Publish feeds using Django
945,001
<p>I'm publishing a feed from a Django application.</p> <p>I subclassed django.contrib.syndication.feeds.Feed, everything works fine, except the date that doesn't get published on the feed.</p> <p>Here's the method I've created on my Feed class</p> <pre> def item_pubdate(self, item): return item.date </pre> <p>...
0
2009-06-03T14:12:40Z
945,016
<p>This is how mine is setup, and it is working.</p> <pre><code>class AllFeed(Feed): def item_pubdate(self, item): return item.date </code></pre>
0
2009-06-03T14:14:57Z
[ "python", "django", "rss" ]
Publish feeds using Django
945,001
<p>I'm publishing a feed from a Django application.</p> <p>I subclassed django.contrib.syndication.feeds.Feed, everything works fine, except the date that doesn't get published on the feed.</p> <p>Here's the method I've created on my Feed class</p> <pre> def item_pubdate(self, item): return item.date </pre> <p>...
0
2009-06-03T14:12:40Z
1,095,528
<p>I've been banging my head against this one for a while. It seems that the django rss system need a "datetime" object instead of just the date (since it wants a time zone, and the date object doesn't have a time, let alone a time zone...)</p> <p>I might be wrong though, but it's something that I've found via the err...
0
2009-07-08T00:23:18Z
[ "python", "django", "rss" ]
Publish feeds using Django
945,001
<p>I'm publishing a feed from a Django application.</p> <p>I subclassed django.contrib.syndication.feeds.Feed, everything works fine, except the date that doesn't get published on the feed.</p> <p>Here's the method I've created on my Feed class</p> <pre> def item_pubdate(self, item): return item.date </pre> <p>...
0
2009-06-03T14:12:40Z
1,169,884
<p>According to the <a href="http://docs.djangoproject.com/en/dev/ref/contrib/syndication/#feed-class-reference" rel="nofollow">Feed Class Reference</a> in the Django documentation, the item_pubdate field is supposed to return a datetime.datetime object. If item.date is just a DateField and not a DateTimeField, that m...
3
2009-07-23T06:06:30Z
[ "python", "django", "rss" ]
DBus interface properties
945,007
<p>How do I get the list of available DBus interface properties?</p> <p>I am writing a script that would be tracking specific type of usb devices connections. A way to distinguish the connections to be tracked from all usb connections I guess is to check the properties of signals' interfaces DBus is sending on a usb c...
4
2009-06-03T14:13:14Z
989,948
<p>First of all, check hal documentation and sources, they are always your friend.</p> <pre><code>import dbus bus = dbus.SystemBus() dev = bus.get_object("org.freedesktop.Hal", u'/org/freedesktop/Hal/devices/computer_logicaldev_input') iface = dbus.Interface(dev, 'org.freedesktop.Hal.Device') props = iface.GetAllPrope...
3
2009-06-13T04:06:51Z
[ "python", "properties", "interface", "dbus" ]
DBus interface properties
945,007
<p>How do I get the list of available DBus interface properties?</p> <p>I am writing a script that would be tracking specific type of usb devices connections. A way to distinguish the connections to be tracked from all usb connections I guess is to check the properties of signals' interfaces DBus is sending on a usb c...
4
2009-06-03T14:13:14Z
1,993,780
<p>In general, you can use the <a href="http://dbus.freedesktop.org/doc/dbus-specification.html#standard-interfaces-properties" rel="nofollow"><code>GetAll</code></a> method on the <code>org.freedesktop.DBus.Properties</code> interface.</p>
1
2010-01-03T02:48:43Z
[ "python", "properties", "interface", "dbus" ]
DBus interface properties
945,007
<p>How do I get the list of available DBus interface properties?</p> <p>I am writing a script that would be tracking specific type of usb devices connections. A way to distinguish the connections to be tracked from all usb connections I guess is to check the properties of signals' interfaces DBus is sending on a usb c...
4
2009-06-03T14:13:14Z
24,126,305
<p>I recently encountered the same issue (not with Hal specifically). I'm not sure if this holds universally but it can (at least very often) be retrieved via the <code>org.freedesktop.DBus.Properties</code> interface (as @daf suggested).</p> <pre><code>bus = dbus.SystemBus() device = bus.get_object(...) your_interf...
0
2014-06-09T18:15:06Z
[ "python", "properties", "interface", "dbus" ]
How can I script the creation of a movie from a set of images?
945,250
<p>I managed to get a set of images loaded using Python. </p> <p>I'd like my script to take this series of images (in whatever format I need them), and create a video from them. The big limit in all this is that I am looking for something easy and simple to install. Ideally, using the standard OS X installation proced...
8
2009-06-03T14:54:29Z
945,389
<p>Do you have to use python? There are other tools that are created just for these purposes. For example, to use <a href="http://electron.mit.edu/~gsteele/ffmpeg/" rel="nofollow">ffmpeg or mencoder</a>.</p>
4
2009-06-03T15:22:45Z
[ "python", "osx", "video" ]
How can I script the creation of a movie from a set of images?
945,250
<p>I managed to get a set of images loaded using Python. </p> <p>I'd like my script to take this series of images (in whatever format I need them), and create a video from them. The big limit in all this is that I am looking for something easy and simple to install. Ideally, using the standard OS X installation proced...
8
2009-06-03T14:54:29Z
945,570
<p>You may use OpenCV. And it can be installed on Mac. Also, it has a <a href="http://opencv.willowgarage.com/wiki/PythonInterface">python interface</a>.</p> <p>I have slightly modified a program taken from <a href="http://morphm.ensmp.fr/wiki/morphee-admin/How%5Fto%5Fuse%5FMorph-M%5Fwith%5FOpenCV%5F">here</a>, but do...
8
2009-06-03T16:00:47Z
[ "python", "osx", "video" ]
How can I script the creation of a movie from a set of images?
945,250
<p>I managed to get a set of images loaded using Python. </p> <p>I'd like my script to take this series of images (in whatever format I need them), and create a video from them. The big limit in all this is that I am looking for something easy and simple to install. Ideally, using the standard OS X installation proced...
8
2009-06-03T14:54:29Z
945,829
<p>If you're not averse to using the command-line, there's the <code>convert</code> command from the ImageMagick package. It's available for Mac, Linux, Windows. See <a href="http://www.imagemagick.org/script/index.php">http://www.imagemagick.org/script/index.php</a>.</p> <p>It supports a huge number of image formats ...
19
2009-06-03T16:53:53Z
[ "python", "osx", "video" ]
Why doesn't anyone care about this MySQLdb bug? is it a bug?
945,482
<p>TL;DR: I've supplied a patch for a bug I found and I've got 0 feedback on it. I'm wondering if it's a bug at all. This is not a rant. Please read this and if you may be affected by it check the fix.</p> <p>I have found and reported this MySQLdb bug some weeks ago (edit: 6 weeks ago), sent a patch, posted it on a co...
10
2009-06-03T15:41:34Z
945,519
<blockquote> <p>Why doesn’t anyone care about this MySQLdb bug?</p> </blockquote> <p>bugs can take a while to prioritize, research, verify the problem, find a fix, test the fix, make sure the fix fix does not break anything else. I would suggest you deploy a work around, since it could take some time for this f...
7
2009-06-03T15:48:58Z
[ "python", "deadlock", "mysql" ]
is there a multiple format specifier in Python?
945,972
<p>I have a data table 44 columns wide that I need to write to file. I don't want to write:</p> <pre><code>outfile.write("%i,%f,%f,$f ... )\n" % (i, a,b,c ...)) </code></pre> <p>In Fortran you can specify multiple format specifiers easily:</p> <pre><code>write (*,"(3f8.3)") a,b,c </code></pre> <p>Is there a simila...
7
2009-06-03T17:18:53Z
945,988
<p>Are you asking about</p> <pre><code>format= "%i" + ",%f"*len(row) + "\n" outfile.write( format % ([i]+row)) </code></pre>
3
2009-06-03T17:21:14Z
[ "python" ]
is there a multiple format specifier in Python?
945,972
<p>I have a data table 44 columns wide that I need to write to file. I don't want to write:</p> <pre><code>outfile.write("%i,%f,%f,$f ... )\n" % (i, a,b,c ...)) </code></pre> <p>In Fortran you can specify multiple format specifiers easily:</p> <pre><code>write (*,"(3f8.3)") a,b,c </code></pre> <p>Is there a simila...
7
2009-06-03T17:18:53Z
945,994
<pre><code>&gt;&gt;&gt; "%d " * 3 '%d %d %d ' &gt;&gt;&gt; "%d " * 3 % (1,2,3) '1 2 3 ' </code></pre>
20
2009-06-03T17:21:59Z
[ "python" ]
is there a multiple format specifier in Python?
945,972
<p>I have a data table 44 columns wide that I need to write to file. I don't want to write:</p> <pre><code>outfile.write("%i,%f,%f,$f ... )\n" % (i, a,b,c ...)) </code></pre> <p>In Fortran you can specify multiple format specifiers easily:</p> <pre><code>write (*,"(3f8.3)") a,b,c </code></pre> <p>Is there a simila...
7
2009-06-03T17:18:53Z
946,026
<p>Is not exactly the same, but you can try something like this:</p> <pre><code>values=[1,2.1,3,4,5] #you can use variables instead of values of course outfile.write(",".join(["%f" % value for value in values])); </code></pre>
0
2009-06-03T17:28:19Z
[ "python" ]
is there a multiple format specifier in Python?
945,972
<p>I have a data table 44 columns wide that I need to write to file. I don't want to write:</p> <pre><code>outfile.write("%i,%f,%f,$f ... )\n" % (i, a,b,c ...)) </code></pre> <p>In Fortran you can specify multiple format specifiers easily:</p> <pre><code>write (*,"(3f8.3)") a,b,c </code></pre> <p>Is there a simila...
7
2009-06-03T17:18:53Z
947,192
<p>Note that I think it'd be much better to do something like:</p> <pre><code>outfile.write(", ".join(map(str, row))) </code></pre> <p>...which isn't what you asked for, but is better in a couple of ways.</p>
0
2009-06-03T20:55:26Z
[ "python" ]
Equivalent Javascript Functions for Python's urllib.quote() and urllib.unquote()
946,170
<p>Are there any equivalent Javascript functions for Python's <a href="http://docs.python.org/library/urllib.html#urllib.quote"><code>urllib.quote()</code></a> and <a href="http://docs.python.org/library/urllib.html#urllib.unquote"><code>urllib.unquote()</code></a>?</p> <p>The closest I've come across are <a href="htt...
22
2009-06-03T17:51:28Z
946,380
<p>OK, I think I'm going to go with a hybrid custom set of functions:</p> <p>Encode: Use encodeURIComponent(), then put slashes back in.<br> Decode: Decode any %hex values found.</p> <p>Here's a more complete variant of what I ended up using (it handles Unicode properly, too):</p> <pre><code>function quoteUrl(url, s...
5
2009-06-03T18:30:19Z
[ "javascript", "python", "url", "encoding" ]
Equivalent Javascript Functions for Python's urllib.quote() and urllib.unquote()
946,170
<p>Are there any equivalent Javascript functions for Python's <a href="http://docs.python.org/library/urllib.html#urllib.quote"><code>urllib.quote()</code></a> and <a href="http://docs.python.org/library/urllib.html#urllib.unquote"><code>urllib.unquote()</code></a>?</p> <p>The closest I've come across are <a href="htt...
22
2009-06-03T17:51:28Z
946,656
<p>Try a regex. Something like this:</p> <pre><code>mystring.replace(/[\xFF-\xFFFF]/g, "%" + "$&amp;".charCodeAt(0)); </code></pre> <p>That will replace any character above ordinal 255 with its corresponding %HEX representation.</p>
1
2009-06-03T19:26:24Z
[ "javascript", "python", "url", "encoding" ]
Equivalent Javascript Functions for Python's urllib.quote() and urllib.unquote()
946,170
<p>Are there any equivalent Javascript functions for Python's <a href="http://docs.python.org/library/urllib.html#urllib.quote"><code>urllib.quote()</code></a> and <a href="http://docs.python.org/library/urllib.html#urllib.unquote"><code>urllib.unquote()</code></a>?</p> <p>The closest I've come across are <a href="htt...
22
2009-06-03T17:51:28Z
2,947,168
<p>Python: <code>urllib.quote</code></p> <p>Javascript:<code>unescape</code></p> <p>I haven't done extensive testing but for my purposes it works most of the time. I guess you have some specific characters that don't work. Maybe if I use some Asian text or something it will break :)</p> <p>This came up when I google...
1
2010-06-01T03:47:21Z
[ "javascript", "python", "url", "encoding" ]
Equivalent Javascript Functions for Python's urllib.quote() and urllib.unquote()
946,170
<p>Are there any equivalent Javascript functions for Python's <a href="http://docs.python.org/library/urllib.html#urllib.quote"><code>urllib.quote()</code></a> and <a href="http://docs.python.org/library/urllib.html#urllib.unquote"><code>urllib.unquote()</code></a>?</p> <p>The closest I've come across are <a href="htt...
22
2009-06-03T17:51:28Z
6,618,858
<p>For the record:</p> <pre><code>JavaScript | Python ----------------------------------- encodeURI(str) | urllib.quote(str, safe='~@#$&amp;()*!+=:;,.?/\''); ----------------------------------- encodeURIComponent(str) | urllib.quote(str, safe='~()*!.\'') </code></pre>
44
2011-07-08T00:58:30Z
[ "javascript", "python", "url", "encoding" ]
Equivalent Javascript Functions for Python's urllib.quote() and urllib.unquote()
946,170
<p>Are there any equivalent Javascript functions for Python's <a href="http://docs.python.org/library/urllib.html#urllib.quote"><code>urllib.quote()</code></a> and <a href="http://docs.python.org/library/urllib.html#urllib.unquote"><code>urllib.unquote()</code></a>?</p> <p>The closest I've come across are <a href="htt...
22
2009-06-03T17:51:28Z
35,343,767
<p>The requests library is a bit more popular if you don't mind the extra dependency</p> <pre><code>from requests.utils import quote quote(str) </code></pre>
1
2016-02-11T15:44:50Z
[ "javascript", "python", "url", "encoding" ]
Using Python's list index() method on a list of tuples or objects?
946,860
<p>Python's list type has an index() method that takes one parameter and returns the index of the first item in the list matching the parameter. For instance:</p> <pre><code>&gt;&gt;&gt; some_list = ["apple", "pear", "banana", "grape"] &gt;&gt;&gt; some_list.index("pear") 1 &gt;&gt;&gt; some_list.index("grape") 3 </c...
34
2009-06-03T20:01:51Z
946,906
<p>How about this?</p> <pre><code>&gt;&gt;&gt; tuple_list = [("pineapple", 5), ("cherry", 7), ("kumquat", 3), ("plum", 11)] &gt;&gt;&gt; [x for x, y in enumerate(tuple_list) if y[1] == 7] [1] &gt;&gt;&gt; [x for x, y in enumerate(tuple_list) if y[0] == 'kumquat'] [2] </code></pre> <p>As pointed out in the comments, t...
47
2009-06-03T20:07:23Z
[ "python", "list", "tuples", "reverse-lookup" ]
Using Python's list index() method on a list of tuples or objects?
946,860
<p>Python's list type has an index() method that takes one parameter and returns the index of the first item in the list matching the parameter. For instance:</p> <pre><code>&gt;&gt;&gt; some_list = ["apple", "pear", "banana", "grape"] &gt;&gt;&gt; some_list.index("pear") 1 &gt;&gt;&gt; some_list.index("grape") 3 </c...
34
2009-06-03T20:01:51Z
946,940
<p>One possibility is to use the <a href="http://docs.python.org/library/operator.html#operator.itemgetter">itemgetter</a> function from the <code>operator</code> module:</p> <pre><code>import operator f = operator.itemgetter(0) print map(f, tuple_list).index("cherry") # yields 1 </code></pre> <p>The call to <code>i...
8
2009-06-03T20:12:28Z
[ "python", "list", "tuples", "reverse-lookup" ]
Using Python's list index() method on a list of tuples or objects?
946,860
<p>Python's list type has an index() method that takes one parameter and returns the index of the first item in the list matching the parameter. For instance:</p> <pre><code>&gt;&gt;&gt; some_list = ["apple", "pear", "banana", "grape"] &gt;&gt;&gt; some_list.index("pear") 1 &gt;&gt;&gt; some_list.index("grape") 3 </c...
34
2009-06-03T20:01:51Z
947,166
<p>You can do this with a list comprehension and index()</p> <pre><code>tuple_list = [("pineapple", 5), ("cherry", 7), ("kumquat", 3), ("plum", 11)] [x[0] for x in tuple_list].index("kumquat") 2 [x[1] for x in tuple_list].index(7) 1 </code></pre>
4
2009-06-03T20:50:48Z
[ "python", "list", "tuples", "reverse-lookup" ]
Using Python's list index() method on a list of tuples or objects?
946,860
<p>Python's list type has an index() method that takes one parameter and returns the index of the first item in the list matching the parameter. For instance:</p> <pre><code>&gt;&gt;&gt; some_list = ["apple", "pear", "banana", "grape"] &gt;&gt;&gt; some_list.index("pear") 1 &gt;&gt;&gt; some_list.index("grape") 3 </c...
34
2009-06-03T20:01:51Z
947,184
<p>Those list comprehensions are messy after a while.</p> <h3>I like this Pythonic approach:</h3> <pre><code>from operator import itemgetter def collect(l, index): return map(itemgetter(index), l) # And now you can write this: collect(tuple_list,0).index("cherry") # = 1 collect(tuple_list,1).index("3") ...
24
2009-06-03T20:54:10Z
[ "python", "list", "tuples", "reverse-lookup" ]
Using Python's list index() method on a list of tuples or objects?
946,860
<p>Python's list type has an index() method that takes one parameter and returns the index of the first item in the list matching the parameter. For instance:</p> <pre><code>&gt;&gt;&gt; some_list = ["apple", "pear", "banana", "grape"] &gt;&gt;&gt; some_list.index("pear") 1 &gt;&gt;&gt; some_list.index("grape") 3 </c...
34
2009-06-03T20:01:51Z
6,850,520
<p>I would place this as a comment to Triptych, but I can't comment yet due to lack of rating:</p> <p>Using the enumerator method to match on sub-indices in a list of tuples. e.g.</p> <pre><code>li = [(1,2,3,4), (11,22,33,44), (111,222,333,444), ('a','b','c','d'), ('aa','bb','cc','dd'), ('aaa','bbb','ccc','dd...
2
2011-07-27T20:02:43Z
[ "python", "list", "tuples", "reverse-lookup" ]
Using Python's list index() method on a list of tuples or objects?
946,860
<p>Python's list type has an index() method that takes one parameter and returns the index of the first item in the list matching the parameter. For instance:</p> <pre><code>&gt;&gt;&gt; some_list = ["apple", "pear", "banana", "grape"] &gt;&gt;&gt; some_list.index("pear") 1 &gt;&gt;&gt; some_list.index("grape") 3 </c...
34
2009-06-03T20:01:51Z
11,106,344
<p>ok, it might be a mistake in <code>vals(j)</code>, the correction is:</p> <pre><code>def getIndex(li,indices,vals): for pos,k in enumerate(lista): match = True for i in indices: if k[i] != vals[indices.index(i)]: match = False break if(match): return pos </code></...
1
2012-06-19T17:38:27Z
[ "python", "list", "tuples", "reverse-lookup" ]
Using Python's list index() method on a list of tuples or objects?
946,860
<p>Python's list type has an index() method that takes one parameter and returns the index of the first item in the list matching the parameter. For instance:</p> <pre><code>&gt;&gt;&gt; some_list = ["apple", "pear", "banana", "grape"] &gt;&gt;&gt; some_list.index("pear") 1 &gt;&gt;&gt; some_list.index("grape") 3 </c...
34
2009-06-03T20:01:51Z
12,919,542
<pre><code>tuple_list = [("pineapple", 5), ("cherry", 7), ("kumquat", 3), ("plum", 11)] def eachtuple(tupple, pos1, val): for e in tupple: if e == val: return True for e in tuple_list: if eachtuple(e, 1, 7) is True: print tuple_list.index(e) for e in tuple_list: if eachtuple(e...
1
2012-10-16T16:44:44Z
[ "python", "list", "tuples", "reverse-lookup" ]
Using Python's list index() method on a list of tuples or objects?
946,860
<p>Python's list type has an index() method that takes one parameter and returns the index of the first item in the list matching the parameter. For instance:</p> <pre><code>&gt;&gt;&gt; some_list = ["apple", "pear", "banana", "grape"] &gt;&gt;&gt; some_list.index("pear") 1 &gt;&gt;&gt; some_list.index("grape") 3 </c...
34
2009-06-03T20:01:51Z
14,364,040
<pre><code>z = list(zip(*tuple_list)) z[1][z[0].index('persimon')] </code></pre>
0
2013-01-16T17:19:20Z
[ "python", "list", "tuples", "reverse-lookup" ]
Using Python's list index() method on a list of tuples or objects?
946,860
<p>Python's list type has an index() method that takes one parameter and returns the index of the first item in the list matching the parameter. For instance:</p> <pre><code>&gt;&gt;&gt; some_list = ["apple", "pear", "banana", "grape"] &gt;&gt;&gt; some_list.index("pear") 1 &gt;&gt;&gt; some_list.index("grape") 3 </c...
34
2009-06-03T20:01:51Z
35,446,495
<p>Inspired by <a href="http://stackoverflow.com/questions/35446421/finding-a-specific-value-from-list-of-dictionary-in-python#35446432">this question</a>, I found this quite elegant:</p> <pre><code>&gt;&gt;&gt; tuple_list = [("pineapple", 5), ("cherry", 7), ("kumquat", 3), ("plum", 11)] &gt;&gt;&gt; next(i for i, t i...
1
2016-02-17T01:49:51Z
[ "python", "list", "tuples", "reverse-lookup" ]
Using Python's list index() method on a list of tuples or objects?
946,860
<p>Python's list type has an index() method that takes one parameter and returns the index of the first item in the list matching the parameter. For instance:</p> <pre><code>&gt;&gt;&gt; some_list = ["apple", "pear", "banana", "grape"] &gt;&gt;&gt; some_list.index("pear") 1 &gt;&gt;&gt; some_list.index("grape") 3 </c...
34
2009-06-03T20:01:51Z
37,022,206
<p>No body suggest lambdas?</p> <p>Y try this and works. I come to this post searching answer. I don't found that I like, but I feel a insingth :P</p> <pre><code> l #[['rana', 1, 1], ['pato', 1, 1], ['perro', 1, 1]] map(lambda x:x[0], l).index("pato") #1 </code></pre> <p>Edit to add examples: </p> <pre><c...
0
2016-05-04T08:21:41Z
[ "python", "list", "tuples", "reverse-lookup" ]
How to execute a process remotely using python
946,946
<p>I want to connect too and execute a process on a remote server using python. I want to be able to get the return code and stderr(if any) of the process. Has anyone ever done anything like this before. I have done it with ssh, but I want to do it from python script.</p> <p>Cheers.</p>
19
2009-06-03T20:12:56Z
946,962
<p>Well, you can call ssh from python...</p> <pre><code>import subprocess ret = subprocess.call(["ssh", "user@host", "program"]); # or, with stderr: prog = subprocess.Popen(["ssh", "user@host", "program"], stderr=subprocess.PIPE) errdata = prog.communicate()[1] </code></pre>
16
2009-06-03T20:15:42Z
[ "python", "ssh" ]
How to execute a process remotely using python
946,946
<p>I want to connect too and execute a process on a remote server using python. I want to be able to get the return code and stderr(if any) of the process. Has anyone ever done anything like this before. I have done it with ssh, but I want to do it from python script.</p> <p>Cheers.</p>
19
2009-06-03T20:12:56Z
8,798,354
<p>Use the <a href="http://pypi.python.org/pypi/paramiko/">ssh module called paramiko</a> which was created for this purpose instead of using <code>subprocess</code>. Here's an example below:</p> <pre><code>from paramiko import SSHClient client = SSHClient() client.load_system_host_keys() client.connect("hostname", us...
29
2012-01-10T03:55:15Z
[ "python", "ssh" ]
How to execute a process remotely using python
946,946
<p>I want to connect too and execute a process on a remote server using python. I want to be able to get the return code and stderr(if any) of the process. Has anyone ever done anything like this before. I have done it with ssh, but I want to do it from python script.</p> <p>Cheers.</p>
19
2009-06-03T20:12:56Z
12,491,631
<p>Maybe if you want to wrap the nuts and bolts of the ssh calls you could use <a href="http://docs.fabfile.org" rel="nofollow">Fabric</a> This library is geared towards deployment and server management, but it could also be useful for these kind of problems.</p> <p>Also have a look at <a href="http://docs.celeryproje...
3
2012-09-19T09:09:26Z
[ "python", "ssh" ]
Get file creation time with Python on Mac
946,967
<p>Python's os.path.getctime on the Mac (and under Unix in general) does not give the date when a file was created but "the time of the last change" (according to the docs at least). On the other hand in the Finder I can see the real file creation time so this information is kept by HFS+.</p> <p>Do you have any sugges...
7
2009-06-03T20:16:51Z
946,985
<p>ctime differs on the platform: <em>On some systems (like Unix) is the time of the last metadata change, and, on others (like Windows), is the creation time</em>. That's because Unices usually don't preserve the "original" creation time.</p> <p>That said you can access all information that the OS provides with the <...
1
2009-06-03T20:20:03Z
[ "python", "osx" ]
Get file creation time with Python on Mac
946,967
<p>Python's os.path.getctime on the Mac (and under Unix in general) does not give the date when a file was created but "the time of the last change" (according to the docs at least). On the other hand in the Finder I can see the real file creation time so this information is kept by HFS+.</p> <p>Do you have any sugges...
7
2009-06-03T20:16:51Z
947,239
<p>Use the <a href="https://docs.python.org/3/library/os.html#os.stat_result.st_birthtime" rel="nofollow"><strong><code>st_birthtime</code></strong></a> property on the result of a call to <a href="https://docs.python.org/3/library/os.html#os.stat" rel="nofollow"><code>os.stat()</code></a> (or <code>fstat</code>/<code>...
14
2009-06-03T21:02:52Z
[ "python", "osx" ]
using pyodbc on linux to insert unicode or utf-8 chars in a nvarchar mssql field
947,077
<p>I am using <strong>Ubuntu 9.04</strong></p> <p>I have installed the following package versions:</p> <pre><code>unixodbc and unixodbc-dev: 2.2.11-16build3 tdsodbc: 0.82-4 libsybdb5: 0.82-4 freetds-common and freetds-dev: 0.82-4 </code></pre> <p>I have configured <code>/etc/unixodbc.ini</code> like this:</p> <pre>...
21
2009-06-03T20:35:24Z
953,881
<p>I use UCS-2 to interact with SQL Server, not UTF-8.</p> <p>Correction: I changed the .freetds.conf entry so that the client uses UTF-8</p> <pre><code> tds version = 8.0 client charset = UTF-8 text size = 32768 </code></pre> <p>Now, bind values work fine for UTF-8 encoded strings. The driver converts tr...
1
2009-06-05T01:28:17Z
[ "python", "sql-server", "unicode", "utf-8", "pyodbc" ]
using pyodbc on linux to insert unicode or utf-8 chars in a nvarchar mssql field
947,077
<p>I am using <strong>Ubuntu 9.04</strong></p> <p>I have installed the following package versions:</p> <pre><code>unixodbc and unixodbc-dev: 2.2.11-16build3 tdsodbc: 0.82-4 libsybdb5: 0.82-4 freetds-common and freetds-dev: 0.82-4 </code></pre> <p>I have configured <code>/etc/unixodbc.ini</code> like this:</p> <pre>...
21
2009-06-03T20:35:24Z
964,825
<p>I can remember having this kind of stupid problems using odbc drivers, even if that time it was a java+oracle combination.</p> <p>The core thing is that odbc driver apparently encodes the query string when sending it to the DB. Even if the field is Unicode, and if you provide Unicode, in some cases it does not seem...
20
2009-06-08T13:06:21Z
[ "python", "sql-server", "unicode", "utf-8", "pyodbc" ]
using pyodbc on linux to insert unicode or utf-8 chars in a nvarchar mssql field
947,077
<p>I am using <strong>Ubuntu 9.04</strong></p> <p>I have installed the following package versions:</p> <pre><code>unixodbc and unixodbc-dev: 2.2.11-16build3 tdsodbc: 0.82-4 libsybdb5: 0.82-4 freetds-common and freetds-dev: 0.82-4 </code></pre> <p>I have configured <code>/etc/unixodbc.ini</code> like this:</p> <pre>...
21
2009-06-03T20:35:24Z
994,431
<p>Are you sure it's INSERT that's causing problem not reading? There's a bug open on pyodbc <a href="http://code.google.com/p/pyodbc/issues/detail?id=13" rel="nofollow">Problem fetching NTEXT and NVARCHAR data</a>.</p>
0
2009-06-15T03:50:11Z
[ "python", "sql-server", "unicode", "utf-8", "pyodbc" ]
using pyodbc on linux to insert unicode or utf-8 chars in a nvarchar mssql field
947,077
<p>I am using <strong>Ubuntu 9.04</strong></p> <p>I have installed the following package versions:</p> <pre><code>unixodbc and unixodbc-dev: 2.2.11-16build3 tdsodbc: 0.82-4 libsybdb5: 0.82-4 freetds-common and freetds-dev: 0.82-4 </code></pre> <p>I have configured <code>/etc/unixodbc.ini</code> like this:</p> <pre>...
21
2009-06-03T20:35:24Z
7,929,603
<p>I had the same problem when trying to bind unicode parameter: '[HY004] [FreeTDS][SQL Server]Invalid data type (0) (SQLBindParameter)'</p> <p>I solved it by upgrading freetds to version 0.91. </p> <p>I use pyodbc 2.1.11. I had to apply <a href="http://code.google.com/p/pyodbc/issues/attachmentText?id=170&amp;aid=17...
1
2011-10-28T12:59:48Z
[ "python", "sql-server", "unicode", "utf-8", "pyodbc" ]
Custom simple Python HTTP server not serving css files
947,372
<p>I had found written in python, a very simple http server, it's do_get method looks like this:</p> <pre><code>def do_GET(self): try: self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers(); filepath = self.path print...
4
2009-06-03T21:31:32Z
947,442
<p>You're explicitly serving all files as <code>Content-type: text/html</code>, where you need to serve CSS files as <code>Content-type: text/css</code>. See <a href="http://css-discuss.incutio.com/?page=MozillaCssMimeType">this page on the CSS-Discuss Wiki</a> for details. Web servers usually have a lookup table to ...
9
2009-06-03T21:44:24Z
[ "python", "css", "http" ]
Custom simple Python HTTP server not serving css files
947,372
<p>I had found written in python, a very simple http server, it's do_get method looks like this:</p> <pre><code>def do_GET(self): try: self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers(); filepath = self.path print...
4
2009-06-03T21:31:32Z
947,443
<p>it seems to be returning the html mimetype for all files:</p> <pre><code>self.send_header('Content-type', 'text/html') </code></pre> <p>Also, it seems to be pretty bad. Why are you interested in this sucky server? Look at cherrypy or paste for good python implementations of HTTP server and a good code to study.</p...
5
2009-06-03T21:44:47Z
[ "python", "css", "http" ]
Custom simple Python HTTP server not serving css files
947,372
<p>I had found written in python, a very simple http server, it's do_get method looks like this:</p> <pre><code>def do_GET(self): try: self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers(); filepath = self.path print...
4
2009-06-03T21:31:32Z
947,592
<p>See <a href="http://hg.python.org/cpython/file/3481c6f36e55/Lib/SimpleHTTPServer.py" rel="nofollow"><code>SimpleHTTPServer.py</code></a> in the standard library for a safer, saner implementation that you can customize if you need.</p>
2
2009-06-03T22:28:02Z
[ "python", "css", "http" ]
How to I reload global vars on every page refresh in DJango
947,436
<p>Here is my problem. DJango continues to store all the global objects after the first run of a script. For instance, an object you instantiate in views.py globally will be there until you restart the app server. This is fine unless your object is tied to some outside resource that may time out. Now the way I was ...
0
2009-06-03T21:43:37Z
947,486
<p>Simple: Don't use global objects. If you want an object inside the view, instantiate it inside the view, not as global. That way it will be collected after the view ends.</p>
6
2009-06-03T21:56:42Z
[ "python", "django" ]
Strip all non-numeric characters (except for ".") from a string in Python
947,776
<p>I've got a pretty good working snippit of code, but I was wondering if anyone has any better suggestions on how to do this:</p> <pre><code>val = ''.join([c for c in val if c in '1234567890.']) </code></pre> <p>What would you do?</p>
37
2009-06-03T23:12:00Z
947,789
<pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; non_decimal = re.compile(r'[^\d.]+') &gt;&gt;&gt; non_decimal.sub('', '12.34fe4e') '12.344' </code></pre>
80
2009-06-03T23:14:46Z
[ "python" ]
Strip all non-numeric characters (except for ".") from a string in Python
947,776
<p>I've got a pretty good working snippit of code, but I was wondering if anyone has any better suggestions on how to do this:</p> <pre><code>val = ''.join([c for c in val if c in '1234567890.']) </code></pre> <p>What would you do?</p>
37
2009-06-03T23:12:00Z
947,868
<p>Here's some sample code:</p> <pre><code>$ cat a.py a = '27893jkasnf8u2qrtq2ntkjh8934yt8.298222rwagasjkijw' for i in xrange(1000000): ''.join([c for c in a if c in '1234567890.']) </code></pre> <hr> <pre><code>$ cat b.py import re non_decimal = re.compile(r'[^\d.]+') a = '27893jkasnf8u2qrtq2ntkjh8934yt8.2982...
13
2009-06-03T23:44:12Z
[ "python" ]
Strip all non-numeric characters (except for ".") from a string in Python
947,776
<p>I've got a pretty good working snippit of code, but I was wondering if anyone has any better suggestions on how to do this:</p> <pre><code>val = ''.join([c for c in val if c in '1234567890.']) </code></pre> <p>What would you do?</p>
37
2009-06-03T23:12:00Z
948,855
<p>Another 'pythonic' approach</p> <p><code>filter( lambda x: x in '0123456789.', s )</code></p> <p>but regex is faster.</p>
10
2009-06-04T06:24:02Z
[ "python" ]