Dataset Preview
Full Screen Viewer
Full Screen
The full dataset viewer is not available (click to read why). Only showing a preview of the rows.
The dataset generation failed because of a cast error
Error code: DatasetGenerationCastError Exception: DatasetGenerationCastError Message: An error occurred while generating the dataset All the data files must have the same columns, but at some point there are 1 new columns ({'Title'}) and 1 missing columns ({'ParentId'}). This happened while the csv dataset builder was generating data using hf://datasets/Leventiir/answer_train/question_train.csv (at revision 14b938557de7f70479541f4a4591f3cae1c906e5) Please either edit the data files to have matching columns, or separate them into different configurations (see docs at https://hf.co/docs/hub/datasets-manual-configuration#multiple-configurations) Traceback: Traceback (most recent call last): File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/builder.py", line 2011, in _prepare_split_single writer.write_table(table) File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/arrow_writer.py", line 585, in write_table pa_table = table_cast(pa_table, self._schema) File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/table.py", line 2302, in table_cast return cast_table_to_schema(table, schema) File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/table.py", line 2256, in cast_table_to_schema raise CastError( datasets.table.CastError: Couldn't cast Id: int64 OwnerUserId: double CreationDate: string Score: int64 Title: string Body: string -- schema metadata -- pandas: '{"index_columns": [{"kind": "range", "name": null, "start": 0, "' + 936 to {'Id': Value(dtype='int64', id=None), 'OwnerUserId': Value(dtype='float64', id=None), 'CreationDate': Value(dtype='string', id=None), 'ParentId': Value(dtype='int64', id=None), 'Score': Value(dtype='int64', id=None), 'Body': Value(dtype='string', id=None)} because column names don't match During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/src/services/worker/src/worker/job_runners/config/parquet_and_info.py", line 1321, in compute_config_parquet_and_info_response parquet_operations = convert_to_parquet(builder) File "/src/services/worker/src/worker/job_runners/config/parquet_and_info.py", line 935, in convert_to_parquet builder.download_and_prepare( File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/builder.py", line 1027, in download_and_prepare self._download_and_prepare( File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/builder.py", line 1122, in _download_and_prepare self._prepare_split(split_generator, **prepare_split_kwargs) File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/builder.py", line 1882, in _prepare_split for job_id, done, content in self._prepare_split_single( File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/builder.py", line 2013, in _prepare_split_single raise DatasetGenerationCastError.from_cast_error( datasets.exceptions.DatasetGenerationCastError: An error occurred while generating the dataset All the data files must have the same columns, but at some point there are 1 new columns ({'Title'}) and 1 missing columns ({'ParentId'}). This happened while the csv dataset builder was generating data using hf://datasets/Leventiir/answer_train/question_train.csv (at revision 14b938557de7f70479541f4a4591f3cae1c906e5) Please either edit the data files to have matching columns, or separate them into different configurations (see docs at https://hf.co/docs/hub/datasets-manual-configuration#multiple-configurations)
Need help to make the dataset viewer work? Make sure to review how to configure the dataset viewer, and open a discussion for direct support.
Id
int64 | OwnerUserId
float64 | CreationDate
string | ParentId
int64 | Score
int64 | Body
string |
---|---|---|---|---|---|
536 | 161 | 2008-08-02T18:49:07Z | 502 | 9 | <p>You can use ImageMagick's convert utility for this, see some examples in <a href="https://web.archive.org/web/20120413111338/http://studio.imagemagick.org/pipermail/magick-users/2002-May/002636.html" rel="nofollow">http://studio.imagemagick.org/pipermail/magick-users/2002-May/002636.html</a>
:</p>
<blockquote>
<pre><code>Convert taxes.pdf taxes.jpg
</code></pre>
<p>Will convert a two page PDF file into [2] jpeg files: taxes.jpg.0,
taxes.jpg.1</p>
<p>I can also convert these JPEGS to a thumbnail as follows:</p>
<pre><code>convert -size 120x120 taxes.jpg.0 -geometry 120x120 +profile '*' thumbnail.jpg
</code></pre>
<p>I can even convert the PDF directly to a jpeg thumbnail as follows:</p>
<pre><code>convert -size 120x120 taxes.pdf -geometry 120x120 +profile '*' thumbnail.jpg
</code></pre>
<p>This will result in a thumbnail.jpg.0 and thumbnail.jpg.1 for the two
pages.</p>
</blockquote>
|
538 | 156 | 2008-08-02T18:56:56Z | 535 | 23 | <p>One possibility is Hudson. It's written in Java, but there's integration with Python projects:</p>
<blockquote>
<p><a href="http://redsolo.blogspot.com/2007/11/hudson-embraces-python.html" rel="nofollow">Hudson embraces Python</a></p>
</blockquote>
<p>I've never tried it myself, however.</p>
<p>(<strong>Update</strong>, Sept. 2011: After a trademark dispute Hudson has been renamed to <a href="http://jenkins-ci.org/" rel="nofollow">Jenkins</a>.)</p>
|
541 | 157 | 2008-08-02T19:06:40Z | 535 | 20 | <p>We run <a href="http://buildbot.net/trac">Buildbot - Trac</a> at work, I haven't used it too much since my code base isn't part of the release cycle yet. But we run the tests on different environments (OSX/Linux/Win) and it sends emails --and it's written in python.</p> |
660 | 197 | 2008-08-03T12:09:18Z | 535 | 14 | <p>Second the Buildbot - Trac integration. You can find more information about the integration on the <a href="http://buildbot.net/trac/wiki/BuildbotAndTrac">Buildbot website</a>. At my previous job, we wrote and used the plugin they mention (tracbb).
What the plugin does is rewriting all of the Buildbot urls so you can use Buildbot from within Trac. (http://example.com/tracbb).</p>
<p>The really nice thing about Buildbot is that the configuration is written in Python. You can integrate your own Python code directly to the configuration. It's also very easy to write your own BuildSteps to execute specific tasks.</p>
<p>We used BuildSteps to get the source from SVN, pull the dependencies, publish test results to WebDAV, etcetera.</p>
<p>I wrote an X10 interface so we could send signals with build results. When the build failed, we switched on a red lava lamp. When the build succeeded, a green lava lamp switched on. Good times :-)</p> |
777 | 150 | 2008-08-03T18:32:27Z | 766 | 5 | <p>I don't have any experience with <a href="http://www.SiteGround.com" rel="nofollow">http://www.SiteGround.com</a> as a web host personally. </p>
<p>This is just a guess, but it's common for a shared host to support Python and MySQL with the MySQLdb module (e.g., GoDaddy does this). Try the following CGI script to see if MySQLdb is installed.</p>
<pre><code>#!/usr/bin/python<br><br>module_name = 'MySQLdb'<br>head = '''Content-Type: text/html<br><br>%s is ''' % module_name<br><br>try:<br> __import__(module_name)<br> print head + 'installed'<br>except ImportError:<br> print head + 'not installed'<br></code></pre> |
783 | 189 | 2008-08-03T18:40:09Z | 773 | 52 | <p>Can you show us your code?</p>
<p>The example on the Python docs is quite straightforward:</p>
<pre><code>groups = []
uniquekeys = []
for k, g in groupby(data, keyfunc):
groups.append(list(g)) # Store group iterator as a list
uniquekeys.append(k)
</code></pre>
<p>So in your case, data is a list of nodes, keyfunc is where the logic of your criteria function goes and then <code>groupby()</code> groups the data.</p>
<p>You must be careful to <strong>sort the data</strong> by the criteria before you call <code>groupby</code> or it won't work. <code>groupby</code> method actually just iterates through a list and whenever the key changes it creates a new group.</p>
|
802 | 1,384,652 | 2008-08-03T20:07:05Z | 766 | 4 | <p>I uploaded it and got an internal error</p>
<pre><code>Premature end of script headers<br></code></pre>
<p>After much playing around, I found that if I had</p>
<pre><code>import cgi<br>import cgitb; cgitb.enable()<br>import MySQLdb<br></code></pre>
<p>It would give me a much more useful answer and say that it was not installed, you can see it yourself -> <a href="http://woarl.com/db.py" rel="nofollow">http://woarl.com/db.py</a></p>
<p>Oddly enough, this would produce an error</p>
<pre><code>import MySQLdb<br>import cgi<br>import cgitb; cgitb.enable()<br></code></pre>
<p>I looked at some of the other files I had up there and it seems that library was one of the ones I had already tried.</p> |
1,478 | 305 | 2008-08-04T18:26:13Z | 1,476 | -1 | <p>As far as I can tell Python, up through 2.5, only supports hexadecimal & octal literals. I did find some discussions about adding binary to future versions but nothing definite.</p> |
1,479 | 269 | 2008-08-04T18:27:26Z | 1,476 | -1 | <p>I am pretty sure this is one of the things due to change in Python 3.0 with perhaps bin() to go with hex() and oct().</p>
<p>EDIT:
lbrandy's answer is correct in all cases.</p>
|
1,484 | 2,089,740 | 2008-08-04T18:34:45Z | 1,476 | 57 | <pre><code>>>> print int('01010101111',2)
687
>>> print int('11111111',2)
255
</code></pre>
<p>Another way.</p>
|
1,619 | 92 | 2008-08-04T21:54:11Z | 766 | 17 | <p>MySQLdb is what I have used before.</p>
<p>If you host is using Python version 2.5 or higher, support for sqlite3 databases is built in (sqlite allows you to have a relational database that is simply a file in your filesystem). But buyer beware, sqlite is not suited for production, so it may depend what you are trying to do with it.</p>
<p>Another option may be to call your host and complain, or change hosts. Honestly these days, any self respecting web host that supports python and mysql ought to have MySQLdb pre installed.</p> |
1,780 | 77 | 2008-08-05T01:14:30Z | 1,734 | 8 | <P>If you are looking for user facing interaction, stick with xml. It has more support, understanding, and general acceptance currently. If it's internal, I would say that protocol buffers are a great idea.</P>
<P>Maybe in a few years as more tools come out to support protocol buffers, then start looking towards that for a public facing api. Until then... <A href="http://en.wikipedia.org/wiki/JSON">JSON</A>?</P> |
1,840 | 116 | 2008-08-05T02:54:54Z | 1,829 | 8 | <p><strong>On Linux:</strong></p>
<ul>
<li>set raw mode</li>
<li>select and read the keystroke</li>
<li>restore normal settings</li>
</ul>
<pre>
import sys
import select
import termios
import tty
def getkey():
old_settings = termios.tcgetattr(sys.stdin)
tty.setraw(sys.stdin.fileno())
select.select([sys.stdin], [], [], 0)
answer = sys.stdin.read(1)
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_settings)
return answer
print """Menu
1) Say Foo
2) Say Bar"""
answer=getkey()
if "1" in answer: print "foo"
elif "2" in answer: print "bar"
</pre>
|
1,852 | 116 | 2008-08-05T03:11:55Z | 1,829 | 6 | <p><strong>On Windows:</strong></p>
<pre><code>import msvcrt
answer=msvcrt.getch()
</code></pre>
|
1,857 | 2,089,740 | 2008-08-05T03:27:03Z | 1,854 | 341 | <pre><code>>>> import os
>>> print os.name
posix
>>> import platform
>>> platform.system()
'Linux'
>>> platform.release()
'2.6.22-15-generic'
</code></pre>
<p>See: <a href="https://docs.python.org/2/library/platform.html">platform â Access to underlying platformâs identifying data</a></p>
|
1,870 | 30 | 2008-08-05T03:51:57Z | 1,829 | 2 | <p>Wow, that took forever. Ok, here's what I've ended up with </p>
<pre><code>#!C:\python25\python.exe<br>import msvcrt<br>print """Menu<br>1) Say Foo <br>2) Say Bar"""<br>while 1:<br> char = msvcrt.getch()<br> if char == chr(27): #escape<br> break<br> if char == "1":<br> print "foo"<br> break<br> if char == "2":<br> print "Bar"<br> break<br></code></pre>
<p>It fails hard using IDLE, the python...thing...that comes with python. But once I tried it in DOS (er, CMD.exe), as a real program, then it ran fine.</p>
<p>No one try it in IDLE, unless you have Task Manager handy.</p>
<p>I've already forgotten how I lived with menus that arn't super-instant responsive.</p> |
1,871 | 216 | 2008-08-05T03:57:22Z | 1,854 | 112 | <p>Dang -- lbrandy beat me to the punch, but that doesn't mean I can't provide you with the system results for Vista!</p>
<pre><code>>>> import os
>>> os.name
'nt'
>>> import platform
>>> platform.system()
'Windows'
>>> platform.release()
'Vista'
</code></pre>
|
1,879 | 116 | 2008-08-05T04:13:53Z | 1,854 | 91 | <p>For the record here's the results on Mac:</p>
<pre><code>>>> import os
>>> os.name
'posix'
>>> import platform
>>> platform.system()
'Darwin'
>>> platform.release()
'8.11.1'
</code></pre>
|
1,885 | 50 | 2008-08-05T04:28:03Z | 1,829 | 0 | <p>The reason msvcrt fails in IDLE is because IDLE is not accessing the library that runs msvcrt. Whereas when you run the program natively in cmd.exe it works nicely. For the same reason that your program blows up on Mac and Linux terminals.</p>
<p>But I guess if you're going to be using this specifically for windows, more power to ya.</p> |
2,316 | 259 | 2008-08-05T13:45:38Z | 2,311 | 14 | <p>Do you need to open the locfile in binary using <code>rb</code>?</p>
<pre><code>f = open (locfile, "rb")
</code></pre>
|
2,317 | 17 | 2008-08-05T13:45:47Z | 2,311 | 2 | <p>Well if you go under the properties of your file in Windows or a *nix environment, you will notice two sizes. One is the sector size, and one is the actual size. The sector size is the number of sectors in bytes that are used up on your hard disk. That is because two files cannot be in the same sector with most modern file systems, so if your file fills up half of the sector the whole sector is marked as filled.</p>
<p>So you might be comparing the sector file size to the actual file size on the FTP server or vice versa.</p> |
2,510 | 269 | 2008-08-05T15:59:24Z | 2,311 | 0 | <p>Small files take up a whole node on the filesystem whatever size that is.</p>
<p>My host tends to report all small files as 4kb in ftp but in a shell gives an accurate size so it might be a 'feature' common to ftp clients.</p> |
2,937 | 275 | 2008-08-05T22:34:25Z | 2,933 | 189 | <p>First you will need some GUI library with Python bindings and then (if you want) some program that will convert your python scripts into standalone executables.</p>
<p><strong>Cross-platform GUI libraries with Python bindings (Windows, Linux, Mac)</strong></p>
<p>Of course, there are many, but the most popular that I've seen in wild are:</p>
<ul>
<li><a href="http://wiki.python.org/moin/TkInter">Tkinter</a> - based on <a href="http://www.tcl.tk/">Tk GUI toolkit</a> (de-facto standard GUI library for python, free for commercial projects)</li>
<li><a href="http://www.wxpython.org/">WxPython</a> - based on <a href="http://www.wxwidgets.org/">WxWidgets</a> (very popular, free for commercial projects)</li>
<li><a href="http://www.riverbankcomputing.co.uk/news">PyQt</a> - based on <a href="http://trolltech.com/products/qt/">Qt</a> (also very popular and more stable than WxWidgets but costly license for commercial projects)</li>
</ul>
<p>Complete list is at <a href="http://wiki.python.org/moin/GuiProgramming">http://wiki.python.org/moin/GuiProgramming</a></p>
<p><strong>Single executable (Windows)</strong></p>
<ul>
<li><a href="http://www.py2exe.org/">py2exe</a> - Probably the most popular out there (<a href="http://stackoverflow.com/questions/2933/an-executable-python-app/31859#31859">PyInstaller</a> is also gaining in popularity)</li>
</ul>
<p><strong>Single executable (Linux)</strong></p>
<ul>
<li><a href="http://wiki.python.org/moin/Freeze">Freeze</a> - works the same way like py2exe but targets Linux platform</li>
</ul>
<p><strong>Single executable (Mac)</strong></p>
<ul>
<li><a href="https://pythonhosted.org/py2app/">py2app</a> - again, works like py2exe but targets Mac OS</li>
</ul>
|
2,941 | 92 | 2008-08-05T22:40:17Z | 2,933 | 0 | <p>You don't need to <em>compile</em> python for Mac/Windows/Linux. It is an interpreted language, so you simply need to have the Python interpreter installed on the system of your choice (it is available for all three platforms).</p>
<p>As for a GUI library that works cross platform, Python's <a href="http://www.tcl.tk/" rel="nofollow">Tk/Tcl</a> widget library works very well, and I believe is sufficiently cross platform.</p>
<p><a href="http://docs.python.org/lib/module-Tkinter.html" rel="nofollow">Tkinter</a> is the python interface to Tk/Tcl</p>
<p>From the python project webpage: </p>
<blockquote>
<p>Tkinter is not the only GuiProgramming
toolkit for Python. It is however the
most commonly used one, and almost the
only one that is portable between
Unix, Mac and Windows</p>
</blockquote> |
2,980 | 188 | 2008-08-06T00:29:36Z | 2,933 | 2 | <p>Since python is installed on nearly every non-Windows OS by default now, the only thing you really need to make sure of is that all of the non-standard libraries you use are installed.</p>
<p>Having said that, it is possible to build executables that include the python interpreter, and any libraries you use. This is likely to create a large executable, however.</p>
<p>MacOS X even includes support in the Xcode IDE for creating full standalone GUI apps. These can be run by any user running OS X.</p> |
4,128 | 17 | 2008-08-06T23:40:43Z | 3,976 | 0 | <p>have you tried watching the traffic between the GUI and the serial port to see if there is some kind of special command being sent across? Also just curious, Python is sending ASCII and not UTF-8 or something else right? The reason I ask is because I noticed your quote changes for the strings and in some languages that actually is the difference between ASCII and UTF-8.</p>
|
4,162 | 582 | 2008-08-07T00:19:03Z | 3,976 | 4 | <p><code>/dev/cu.xxxxx</code> is the "callout" device, it's what you use when you establish a connection to the serial device and start talking to it. <code>/dev/tty.xxxxx</code> is the "dialin" device, used for monitoring a port for incoming calls for e.g. a fax listener.</p> |
4,958 | 613 | 2008-08-07T16:50:43Z | 4,942 | 2 | <p>Focus on the shorter time needed for development/prototype and possibly easier maintenance (none of this may apply against Ruby).</p> |
4,978 | 676 | 2008-08-07T17:04:25Z | 4,942 | 11 | <p>This is one of those cases that really boil down to personal preference or situational details. If you're more comfortable and experienced with Python, then say so. Are they asking you to justify it because they're more comfortable with one of the other environments? After you're done, will the system be passed off to someone else for long-term maintenance?</p>
<p>If they ask you to use a technology or language that you're not as familiar with, then make sure they know up-front that it's going to take you longer.</p> |
5,014 | 660 | 2008-08-07T17:30:10Z | 4,942 | 3 | <p>I would consider that using python on a new project is completely dependent on what problem you are trying to solve with python. If you want someone to agree with you that you should use python, then show them how python's features apply specifically to that problem.</p>
<p>In the case of web development with python, talk about WSGI and other web libraries and frameworks you could use that would make your life easier. One note for python is that most of the frameworks for python web development can be plugged right into any current project. With ruby on rails, you're practically working in a DSL that anyone who uses your project will have to learn. If they know python, then they can figure out what you are doing with django, etc in a day.</p>
<p>I'm only talking about web development because it appears that's what you are going to be working on seeing ruby, python and PHP in the same list. The real message that's important is applying to whatever it is you like about python <em>directly</em> to some problem you are trying to solve.</p> |
5,129 | 680 | 2008-08-07T18:40:53Z | 5,102 | 12 | <p>There are two main ways of running Python on Apache. The simplest would be to use CGI and write normal Python scripts while the second is using a web framework like Django or Pylons.</p>
<p>Using CGI is straightforward. Make sure your Apache config file has a cgi-bin set up. If not, follow their documentation (<a href="http://httpd.apache.org/docs/2.0/howto/cgi.html" rel="nofollow">http://httpd.apache.org/docs/2.0/howto/cgi.html</a>). At that point all you need to do is place your Python scripts in the cgi-bin directory and the standard output will become the HTTP response. Refer to Python's documentation for further info (<a href="https://docs.python.org/library/cgi.html" rel="nofollow">https://docs.python.org/library/cgi.html</a>).</p>
<p>If you want to use a web framework you'll need to setup mod_python or FastCGI. These steps are dependent on which framework you want to use. Django provides clear instructions on how to setup mod_python and Django with Apache (<a href="http://www.djangoproject.com/documentation/modpython/" rel="nofollow">http://www.djangoproject.com/documentation/modpython/</a>)</p>
|
5,165 | 116 | 2008-08-07T19:02:57Z | 5,102 | 8 | <p>Yes, mod_python is pretty confusing to set up. Here's how I did it.</p>
<p>In httpd.conf:</p>
<pre><code>LoadModule python_module modules/mod_python.so<br><br><Directory "/serverbase/htdocs/myapp"><br> AddHandler mod_python .py<br> PythonHandler myapp<br> PythonDebug On<br></code></pre>
<p>and in your application directory:</p>
<pre><code>$ /serverbase/htdocs/myapp$ ls -l<br>total 16<br>-r-xr-xr-x 1 root sys 6484 May 21 15:54 myapp.py<br></code></pre>
<p>Repeat the configuration for each python program you wish to have running under mod_python.</p> |
5,168 | 636 | 2008-08-07T19:05:58Z | 5,102 | 5 | <p>Are you running Python on UNIX or Windows?</p>
<p>An alternative to mod_python and FastCGI is mod_wsgi. You can find out more at <a href="http://code.google.com/p/modwsgi/" rel="nofollow">modwsgi</a></p>
<p>I have built and installed this on Solaris without problems. I had previously tried mod_python but ran into problems with shared libraries as part of the build. There are <a href="http://code.google.com/p/modwsgi/wiki/InstallationInstructions" rel="nofollow">good install docs</a> available.</p>
|
5,319 | 380 | 2008-08-07T21:10:27Z | 5,313 | 8 | <p>erm.. HTML? (trying to be funny here... while we wait for real answers..)</p> |
5,320 | 216 | 2008-08-07T21:11:28Z | 5,313 | 1 | <p>The <a href="http://www.wxwidgets.org/" rel="nofollow" title="wxWidgets">wxWidgets</a> (formerly known as wxWindows) library might be what you're looking for. There's a particularly good port for Python, <a href="http://wxpython.org/" rel="nofollow" title="wxPython">wxPython</a>, as well as versions for different languages -- C#, C++, Perl and Ruby come to mind -- and for various GUIs: Win32, Mac OS X, GTK+, X11, Motif, WinCE. The library's been around for a while and is pretty solid.</p> |
5,340 | 108 | 2008-08-07T21:24:26Z | 5,313 | 3 | <P>Not sure if this is what you're looking for, but there's <A href="http://glade.gnome.org/" rel="nofollow">Glade</A> (or <A href="http://gladewin32.sourceforge.net/" rel="nofollow">Windows download</A>) which is a designer for GTK+. It generates an XML file which can then be used to build the GUI in a number of different languages.</P> |
5,343 | 25 | 2008-08-07T21:25:26Z | 5,313 | 5 | <p><a href="http://en.wikipedia.org/wiki/Qt_%28toolkit%29">Qt</a> (pronounced "cute" by its creators[1]) is a cross-platform application development framework, widely used for the development of GUI programs.</p>
<p>Qt uses <strong>C++</strong> with several non-standard extensions implemented by an additional pre-processor that generates standard C++ code before compilation. Qt can also be used in several other programming languages; bindings exist for <strong>Ada</strong> (QtAda)[4], C<strong>#</strong> (Qyoto/Kimono)[5], <strong>Java</strong> (Qt Jambi)[6], <strong>Pascal</strong>, <strong>Perl</strong>, <strong>PHP</strong> (PHP-Qt), <strong>Ruby</strong> (RubyQt), and <strong>Python</strong> (PyQt). It runs on all major platforms, and has extensive internationalization support. Non-GUI features include SQL database access, XML parsing, thread management, network support and a unified cross-platform API for file handling.</p> |
5,430 | 267 | 2008-08-07T22:32:23Z | 5,419 | 24 | <p><strong>Note:</strong> This answer is sort of outdated (from 2008). Please use the solution below with care!!</p>
<hr>
<p>Here is a page that details the problem and a solution (search the page for the text <em>Wrapping sys.stdout into an instance</em>):</p>
<p><a href="http://wiki.python.org/moin/PrintFails">PrintFails - Python Wiki</a></p>
<p>Here's a code excerpt from that page:</p>
<pre><code>$ python -c 'import sys, codecs, locale; print sys.stdout.encoding; \
sys.stdout = codecs.getwriter(locale.getpreferredencoding())(sys.stdout); \
line = u"\u0411\n"; print type(line), len(line); \
sys.stdout.write(line); print line'
UTF-8
<type 'unicode'> 2
Ð
Ð
$ python -c 'import sys, codecs, locale; print sys.stdout.encoding; \
sys.stdout = codecs.getwriter(locale.getpreferredencoding())(sys.stdout); \
line = u"\u0411\n"; print type(line), len(line); \
sys.stdout.write(line); print line' | cat
None
<type 'unicode'> 2
Ð
Ð
</code></pre>
<p>There's some more information on that page, well worth a read.</p>
|
5,435 | 429 | 2008-08-07T22:35:48Z | 5,415 | 13 | <p>You'll want the <a href="https://docs.python.org/3.4/library/struct.html" rel="nofollow">struct</a> package.</p>
|
6,125 | 309,844 | 2008-08-08T16:45:50Z | 5,966 | 3 | <p>Why not use SQLite? There is good support in Python and you can write SQL queries to get the data out. Here is the Python docs for <a href="http://docs.python.org/lib/module-sqlite3.html" rel="nofollow">sqlite3</a></p>
<hr>
<p>If you don't want to use SQLite you could do an array of dicts.</p>
<pre><code>episodes = []<br>episodes.append({'season':1, 'episode': 2, 'name':'Something'})<br>episodes.append({'season':1, 'episode': 2, 'name':'Something', 'actors':['Billy Bob', 'Sean Penn']})<br></code></pre>
<p>That way you add metadata to any record and search it very easily</p>
<pre><code>season_1 = [e for e in episodes if e['season'] == 1]<br>billy_bob = [e for e in episodes if 'actors' in e and 'Billy Bob' in e['actors']]<br><br>for episode in billy_bob:<br> print "Billy bob was in Season %s Episode %s" % (episode['season'], episode['episode'])<br></code></pre> |
6,161 | 758 | 2008-08-08T17:12:24Z | 1,734 | 10 | <p>Protocol buffers are intended to optimize communications between machines. They are really not intended for human interaction. Also, the format is binary, so it could not replace XML in that use case. </p>
<p>I would also recommend <a href="http://en.wikipedia.org/wiki/JSON">JSON</a> as being the most compact text-based format.</p> |
6,616 | 488 | 2008-08-09T04:44:41Z | 5,313 | 3 | <p><a href="http://www.mozilla.org/projects/xul/" rel="nofollow">XML User Interface Language</a>. Don't know much about it so not sure if it meets your desires. Post back with your experience if you play with it.</p> |
6,805 | 358 | 2008-08-09T15:13:14Z | 5,966 | 0 | <P>I have done something similar in the past and used an in-memory XML document as a quick and dirty hierachical database for storage. You can store each show/season/episode as an element (nested appropriately) and attributes of these things as xml attributes on the elements. Then you can use XQuery to get info back out.</P>
<P><STRONG>NOTE:</STRONG> I'm not a Python guy so I don't know what your xml support is like.</P>
<P><STRONG>NOTE 2:</STRONG> You'll want to profile this because it'll be bigger and slower than the solution you've already got. Likely enough if you are doing some high-volume processing then XML is probably not going to be your friend.</P> |
7,073 | 878 | 2008-08-10T07:10:19Z | 502 | 2 | <p>Is the PC likely to have Acrobat installed? I think Acrobat installs a shell extension so previews of the first page of a PDF document appear in Windows Explorer's thumbnail view. You can get thumbnails yourself via the IExtractImage COM API, which you'll need to wrap. <a href="http://www.vbaccelerator.com/home/net/code/libraries/shell_projects/Thumbnail_Extraction/article.asp" rel="nofollow" title="Domain Specific Development with Visual Studio DSL Tools.">VBAccelerator has an example in C#</a> that you could port to Python.</p>
|
7,090 | 13 | 2008-08-10T08:08:33Z | 502 | 25 | <p>ImageMagick delegates the PDF->bitmap conversion to GhostScript anyway, so here's a command you can use (it's based on the actual command listed by the <code>ps:alpha</code> delegate in ImageMagick, just adjusted to use JPEG as output):</p>
<pre><code>gs -q -dQUIET -dPARANOIDSAFER -dBATCH -dNOPAUSE -dNOPROMPT \
-dMaxBitmap=500000000 -dLastPage=1 -dAlignToPixels=0 -dGridFitTT=0 \
-sDEVICE=jpeg -dTextAlphaBits=4 -dGraphicsAlphaBits=4 -r72x72 \
-sOutputFile=$OUTPUT -f$INPUT
</code></pre>
<p>where <code>$OUTPUT</code> and <code>$INPUT</code> are the output and input filenames. Adjust the <code>72x72</code> to whatever resolution you need. (Obviously, strip out the backslashes if you're writing out the whole command as one line.)</p>
<p>This is good for two reasons:</p>
<ol>
<li>You don't need to have ImageMagick installed anymore. Not that I have anything against ImageMagick (I love it to bits), but I believe in simple solutions.</li>
<li>ImageMagick does a two-step conversion. First PDF->PPM, then PPM->JPEG. This way, the conversion is one-step.</li>
</ol>
<p>Other things to consider: with the files I've tested, PNG compresses better than JPEG. If you want to use PNG, change the <code>-sDEVICE=jpeg</code> to <code>-sDEVICE=png16m</code>.</p>
|
7,286 | 207 | 2008-08-10T18:45:32Z | 773 | 394 | <p>As Sebastjan said, <strong>you first have to sort your data. This is important.</strong></p>
<p>The part I didn't get is that in the example construction</p>
<pre><code>groups = []
uniquekeys = []
for k, g in groupby(data, keyfunc):
groups.append(list(g)) # Store group iterator as a list
uniquekeys.append(k)
</code></pre>
<p><code>k</code> is the current grouping key, and <code>g</code> is an iterator that you can use to iterate over the group defined by that grouping key. In other words, the <code>groupby</code> iterator itself returns iterators.</p>
<p>Here's an example of that, using clearer variable names:</p>
<pre><code>from itertools import groupby
things = [("animal", "bear"), ("animal", "duck"), ("plant", "cactus"), ("vehicle", "speed boat"), ("vehicle", "school bus")]
for key, group in groupby(things, lambda x: x[0]):
for thing in group:
print "A %s is a %s." % (thing[1], key)
print " "
</code></pre>
<p>This will give you the output:</p>
<blockquote>
<p>A bear is a animal.<br>
A duck is a animal.</p>
<p>A cactus is a plant.</p>
<p>A speed boat is a vehicle.<br>
A school bus is a vehicle.</p>
</blockquote>
<p>In this example, <code>things</code> is a list of tuples where the first item in each tuple is the group the second item belongs to. </p>
<p>The <code>groupby()</code> function takes two arguments: (1) the data to group and (2) the function to group it with. </p>
<p>Here, <code>lambda x: x[0]</code> tells <code>groupby()</code> to use the first item in each tuple as the grouping key.</p>
<p>In the above <code>for</code> statement, <code>groupby</code> returns three (key, group iterator) pairs - once for each unique key. You can use the returned iterator to iterate over each individual item in that group.</p>
<p>Here's a slightly different example with the same data, using a list comprehension:</p>
<pre><code>for key, group in groupby(things, lambda x: x[0]):
listOfThings = " and ".join([thing[1] for thing in group])
print key + "s: " + listOfThings + "."
</code></pre>
<p>This will give you the output:</p>
<blockquote>
<p>animals: bear and duck.<br>
plants: cactus.<br>
vehicles: speed boat and school bus.</p>
</blockquote>
|
7,496 | 680 | 2008-08-11T03:11:55Z | 5,313 | 0 | <p>I read a little on XML User Interface Language (XUL) and it looks really robust and well supported. The main problem for me is it's tied to the Gecko rendering engine so it's cross platform the way wxWidgets, QT and GTK+ are cross platform. Also, there Python bindings don't seem as good as those other libraries.</p>
<p>GladeXML and XRC seem like better markups</p>
|
8,020 | 985 | 2008-08-11T17:58:28Z | 5,419 | -1 | <p>The cause of your problem is <strong>NOT</strong> the Win console not willing to accept Unicode (as it does this since I guess Win2k by default). It is the default system encoding. Try this code and see what it gives you:</p>
<pre><code>import sys
sys.getdefaultencoding()
</code></pre>
<p>if it says ascii, there's your cause ;-)
You have to create a file called sitecustomize.py and put it under python path (I put it under /usr/lib/python2.5/site-packages, but that is differen on Win - it is c:\python\lib\site-packages or something), with the following contents:</p>
<pre><code>import sys
sys.setdefaultencoding('utf-8')
</code></pre>
<p>and perhaps you might want to specify the encoding in your files as well:</p>
<pre><code># -*- coding: UTF-8 -*-
import sys,time
</code></pre>
<p>Edit: more info can be found <a href="http://www.diveintopython.net/xml_processing/unicode.html" rel="nofollow">in excellent the Dive into Python book</a></p>
|
8,109 | 1,026 | 2008-08-11T19:17:41Z | 5,313 | 1 | <p>@Cristian and Antony Cramp: while XUL is a nice choice for UI development (cross-platform, open-source licensed, used in Firefox and other major software), it's certainly not language agnostic. You're tied to Gecko, with JS for scripting. There is experimental support for Python scripting, but it's only experimental, AFAIK.</p>
<p>You can define the UI in XUL+JS and use back-end components written in C++ though (there are Python and Java bridges available too).</p>
|
8,114 | 872 | 2008-08-11T19:21:14Z | 5,313 | 4 | <p>I seriously doubt you're going to find a markup language for GIU's that's <em>not</em> tied to a specific library. For such a thing to exist, there would need to be a standardized GUI markup language, with several implementations.</p>
|
8,165 | 985 | 2008-08-11T20:07:59Z | 5,966 | 0 | <p>I don't get this part here:</p>
<blockquote>
<p>This worked okay, but there was no easy way of checking if x[3][24] was supposed to exist or not (so I couldn't raise the season<em>not</em>found exception)</p>
</blockquote>
<p>There is a way to do it - called <strong>in</strong>:</p>
<pre><code>>>>x={}
>>>x[1]={}
>>>x[1][2]={}
>>>x
{1: {2: {}}}
>>> 2 in x[1]
True
>>> 3 in x[1]
False
</code></pre>
<p>what seems to be the problem with that?</p>
|
8,332 | 1,057 | 2008-08-11T23:16:33Z | 766 | 4 | <p>You could try setting up your own python installation using <a href="http://peak.telecommunity.com/DevCenter/EasyInstall#creating-a-virtual-python" rel="nofollow">Virtual Python</a>. Check out how to setup Django using it <a href="http://forums.site5.com/showthread.php?t=10236" rel="nofollow">here</a>. That was written a long time ago, but it shows how I got MySQLdb setup without having root access or anything like it. Once you've got the basics going, you can install any python library you want.</p>
|
8,699 | 207 | 2008-08-12T11:40:13Z | 8,692 | 74 | <p>The <a href="http://lxml.de/">lxml package</a> supports xpath. It seems to work pretty well, although I've had some trouble with the self:: axis. There's also <a href="http://pypi.python.org/pypi/Amara/1.1.6">Amara</a>, but I haven't used it personally.</p>
|
8,972 | 722 | 2008-08-12T15:32:05Z | 8,948 | 1 | <p><a href="http://www.dotfunk.com/projects/mp3/" rel="nofollow">This toolkit</a> may do what you need. I can't say if it's the "best", but really, if it does what you need, that's all that matters, right?</p>
<p>HTH</p>
|
8,974 | 394 | 2008-08-12T15:37:24Z | 8,948 | 6 | <p>A simple example from the book Dive Into Python works ok for me, <a href="http://www.diveintopython.org/download/diveintopython-examples-5.4.zip" rel="nofollow">this</a> is the download link, the example is fileinfo.py. Don't know if it's the best, but it can do the basic job.</p>
<p>The entire book is available online <a href="http://www.diveintopython.org/" rel="nofollow">here</a>.</p>
|
8,976 | 1,087 | 2008-08-12T15:37:59Z | 8,948 | 1 | <p>It can depend on exactly what you want to do in addition to reading the metadata. If it is just simply the bitrate / name etc. that you need, and nothing else, something lightweight is probably best.</p>
<p>If you're manipulating the mp3 past that PyMedia may be suitable.</p>
<p>There are quite a few, whatever you do get, make sure and test it out on plenty of sample media. There are a few different versions of ID3 tags in particular, so make sure it's not too out of date. </p>
<p>Personally I've used this small MP3Info class with luck. It is quite old though.</p>
<p><a href="http://www.omniscia.org/~vivake/python/MP3Info.py" rel="nofollow">http://www.omniscia.org/~vivake/python/MP3Info.py</a></p>
|
9,080 | 745 | 2008-08-12T17:55:22Z | 5,966 | 0 | <p>Bartosz/To clarify "This worked okay, but there was no easy way of checking if x[3][24] was supposed to exist or not"</p>
<p><code>x['some show'][3][24]</code> would return season 3, episode 24 of "some show". If there was no season 3, I want the pseudo-dict to raise tvdb<em>seasonnotfound, if "some show" doesn't exist, then raise tvdb</em>shownotfound</p>
<p>The current system of a series of classes, each with a <code>__getitem__</code> - Show checks <code>if self.seasons.has_key(requested_season_number)</code>, the Season class checks <code>if self.episodes.has_key(requested_episode_number)</code> and so on.</p>
<p>It works, but it there seems to be a lot of repeated code (each class is basically the same, but raises a different error)</p>
|
9,171 | 1,146 | 2008-08-12T19:34:44Z | 8,692 | 2 | <p><a href="http://pyxml.sourceforge.net" rel="nofollow" title="PyXML">PyXML</a> works well. </p>
<p>You didn't say what platform you're using, however if you're on Ubuntu you can get it with <code>sudo apt-get install python-xml</code>. I'm sure other Linux distros have it as well. </p>
<p>If you're on a Mac, xpath is already installed but not immediately accessible. You can set <code>PY_USE_XMLPLUS</code> in your environment or do it the Python way before you import xml.xpath:</p>
<pre><code>if sys.platform.startswith('darwin'):
os.environ['PY_USE_XMLPLUS'] = '1'
</code></pre>
<p>In the worst case you may have to build it yourself. This package is no longer maintained but still builds fine and works with modern 2.x Pythons. Basic docs are <a href="http://pyxml.sourceforge.net/topics/howto/section-XPath.html" rel="nofollow">here</a>.</p>
|
9,358 | 1,057 | 2008-08-13T00:44:26Z | 8,948 | 11 | <p>What you're after is the <a href="http://id3-py.sourceforge.net/">ID3</a> module. It's very simple and will give you exactly what you need. Just copy the ID3.py file into your site-packages directory and you'll be able to do something like the following:</p>
<pre><code>from ID3 import *
try:
id3info = ID3('file.mp3')
print id3info
# Change the tags
id3info['TITLE'] = "Green Eggs and Ham"
id3info['ARTIST'] = "Dr. Seuss"
for k, v in id3info.items():
print k, ":", v
except InvalidTagError, message:
print "Invalid ID3 tag:", message
</code></pre>
|
10,129 | 116 | 2008-08-13T17:56:34Z | 10,123 | 10 | <p>This will do what you want:</p>
<pre><code>signum = status & 0xff
exitstatus = (status & 0xff00) >> 8
</code></pre>
|
10,132 | 872 | 2008-08-13T17:58:27Z | 10,123 | 1 | <p>You can unpack the status using <a href="http://docs.python.org/ref/shifting.html" rel="nofollow">bit-shifting</a> and <a href="http://docs.python.org/ref/bitwise.html" rel="nofollow">masking</a> operators.</p>
<pre><code>low = status & 0x00FF
high = (status & 0xFF00) >> 8
</code></pre>
<p>I'm not a Python programmer, so I hope got the syntax correct.</p>
|
10,148 | 429 | 2008-08-13T18:14:10Z | 10,123 | 0 | <p>The folks before me've nailed it, but if you really want it on one line, you can do this:</p>
<pre><code>(signum, exitstatus) = (status & 0xFF, (status >> 8) & 0xFF)
</code></pre>
<p>EDIT: Had it backwards.</p>
|
10,213 | 99 | 2008-08-13T18:52:36Z | 10,123 | 10 | <p>To answer your general question, you can use <a href="http://en.wikipedia.org/wiki/Bit_twiddling" rel="nofollow">bit manipulation</a> techniques:</p>
<pre><code>pid, status = os.wait()
exitstatus, signum = status & 0xFF, (status & 0xFF00) >> 8
</code></pre>
<p>However, there are also <a href="http://docs.python.org/lib/os-process.html#l2h-2780" rel="nofollow">built-in functions</a> for interpreting exit status values:</p>
<pre><code>pid, status = os.wait()
exitstatus, signum = os.WEXITSTATUS( status ), os.WTERMSIG( status )
</code></pre>
<p>See also:</p>
<ul>
<li>os.WCOREDUMP()</li>
<li>os.WIFCONTINUED()</li>
<li>os.WIFSTOPPED()</li>
<li>os.WIFSIGNALED()</li>
<li>os.WIFEXITED()</li>
<li>os.WSTOPSIG()</li>
</ul>
|
10,778 | 985 | 2008-08-14T07:08:19Z | 5,966 | 5 | <p>OK, what you need is <code>classobj</code> from new module. That would allow you to construct exception classes dynamically (<code>classobj</code> takes a string as an argument for the class name). </p>
<pre><code>import new
myexc=new.classobj("ExcName",(Exception,),{})
i=myexc("This is the exc msg!")
raise i
</code></pre>
<p>this gives you:</p>
<pre><code>Traceback (most recent call last):
File "<stdin>", line 1, in <module>
__main__.ExcName: This is the exc msg!
</code></pre>
<p>remember that you can always get the class name through:</p>
<pre><code>self.__class__.__name__
</code></pre>
<p>So, after some string mangling and concatenation, you should be able to obtain appropriate exception class name and construct a class object using that name and then raise that exception.</p>
<p>P.S. - you can also raise strings, but this is deprecated.</p>
<pre><code>raise(self.__class__.__name__+"Exception")
</code></pre>
|
10,845 | 912 | 2008-08-14T09:46:21Z | 8,948 | 25 | <p>I've used <a href="https://bitbucket.org/lazka/mutagen">mutagen</a> to edit tags in media files before. The nice thing about mutagen is that it can handle other formats, such as mp4, FLAC etc. I've written several scripts with a lot of success using this API.</p>
|
10,846 | 912 | 2008-08-14T09:48:59Z | 8,692 | 7 | <p>The latest version of <a href="http://effbot.org/zone/element-xpath.htm">elementtree</a> supports XPath pretty well. Not being an XPath expert I can't say for sure if the implementation is full but it has satisfied most of my needs when working in Python. I've also use lxml and PyXML and I find etree nice because it's a standard module.</p>
<p>NOTE: I've since found lxml and for me it's definitely the best XML lib out there for Python. It does XPath nicely as well (though again perhaps not a full implementation).</p>
|
11,074 | 267 | 2008-08-14T14:04:25Z | 11,060 | 8 | <p>I started writing up a summary of my experience with my own code generator, then went back and re-read your question and found you had already touched upon the same issues yourself, focus on the execution results instead of the code layout/look.</p>
<p>Problem is, this is hard to test, the generated code might not be suited to actually run in the environment of the unit test system, and how do you encode the expected results?</p>
<p>I've found that you need to break down the code generator into smaller pieces and unit test those. Unit testing a full code generator is more like integration testing than unit testing if you ask me.</p>
|
11,128 | 414 | 2008-08-14T14:38:19Z | 11,060 | 0 | <p>Yes, results are the ONLY thing that matters. The real chore is writing a framework that allows your generated code to run independently... spend your time there.</p>
|
11,235 | 1,343 | 2008-08-14T15:46:01Z | 11,060 | 0 | <p>If you are running on *nux you might consider dumping the unittest framework in favor of a bash script or makefile. on windows you might consider building a shell app/function that runs the generator and then uses the code (as another process) and unittest that.</p>
<p>A third option would be to generate the code and then build an app from it that includes nothing but a unittest. Again you would need a shell script or whatnot to run this for each input. As to how to encode the expected behavior, it occurs to me that it could be done in much the same way as you would for the C++ code just using the generated interface rather than the C++ one.</p>
|
11,443 | 825 | 2008-08-14T18:15:42Z | 11,060 | 4 | <p>Recall that "unit testing" is only one kind of testing. You should be able to unit test the <strong>internal</strong> pieces of your code generator. What you're really looking at here is system level testing (a.k.a. regression testing). It's not just semantics... there are different mindsets, approaches, expectations, etc. It's certainly more work, but you probably need to bite the bullet and set up an end-to-end regression test suite: fixed C++ files -> SWIG interfaces -> python modules -> known output. You really want to check the known input (fixed C++ code) against expected output (what comes out of the final Python program). Checking the code generator results directly would be like diffing object files...</p>
|
12,166 | 995 | 2008-08-15T11:56:02Z | 2,933 | 13 | <p>An alternative tool to py2exe is <a href="http://pypi.python.org/pypi/bbfreeze/">bbfreeze</a> which generates executables for windows and linux. It's newer than py2exe and handles eggs quite well. I've found it magically works better without configuration for a wide variety of applications.</p>
|
12,167 | 1,344 | 2008-08-15T12:00:37Z | 2,933 | 2 | <p>I'm not sure that this is the best way to do it, but when I'm deploying Ruby GUI apps (not Python, but has the same "problem" as far as .exe's are concerned) on Windows, I just write a short launcher in C# that calls on my main script. It compiles to an executable, and I then have an application executable.</p>
|
12,609 | 1,448 | 2008-08-15T19:04:13Z | 12,592 | 45 | <p>Yes. You can do it. The <a href="https://docs.python.org/3/library/doctest.html">doctest module documentation</a> and Wikipedia has an <a href="http://en.wikipedia.org/wiki/Doctest#Example_2%3a_doctests_embedded_in_a_README.txt_file">example</a> of it.</p>
<pre><code> >>> x
Traceback (most recent call last):
...
NameError: name 'x' is not defined
</code></pre>
|
13,040 | 995 | 2008-08-16T07:57:53Z | 12,591 | 1 | <p>Can you give an example? According to the <a href="http://codespeak.net/lxml/validation.html" rel="nofollow">lxml validation docs</a>, lxml can handle DTD validation (specified in the XML doc or externally in code) and system catalogs, which covers most cases I can think of.</p>
<pre><code>f = StringIO("<!ELEMENT b EMPTY>")
dtd = etree.DTD(f)
dtd = etree.DTD(external_id = "-//OASIS//DTD DocBook XML V4.2//EN")
</code></pre>
|
13,107 | 1,531 | 2008-08-16T12:35:36Z | 1,476 | 204 | <p>For reference—<em>future</em> Python possibilities:<br />
Starting with Python 2.6 you can express binary literals using the prefix <strong>0b</strong> or <strong>0B</strong>:</p>
<pre><code>>>> 0b101111
47
</code></pre>
<p>You can also use the new <strong>bin</strong> function to get the binary representation of a number:</p>
<pre><code>>>> bin(173)
'0b10101101'
</code></pre>
<p>Development version of the documentation: <a href="http://docs.python.org/dev/whatsnew/2.6.html#pep-3127-integer-literal-support-and-syntax">What's New in Python 2.6</a></p>
|
13,399 | 242,853 | 2008-08-16T22:37:06Z | 13,396 | 0 | <p>Depends on the language and what you need to do, a "map" as it's called in many languages could be what you're looking for. I don't know C#, but according to <a href="http://blogs.msdn.com/devdev/archive/2006/06/30/652802.aspx" rel="nofollow">this</a> page, .NET 2.0 calls map "ConvertAll".</p>
<p>The meaning of "map" is pretty simple - take a list, and apply a function to each element of it, returning a new list. You may also be looking for "filter", which would give you a list of items that satisfy a predicate in another list.</p>
|
13,403 | 1,190 | 2008-08-16T22:47:53Z | 13,396 | 1 | <p>in Ruby:</p>
<pre><code>intArray.select { |x| x > 3 }.each do |x|
# do other processing
end
</code></pre>
<p>or if "other processing" is a short one-liner:</p>
<pre><code>intArray.select { |x| x > 3 }.each { |x| something_that_uses x }
</code></pre>
<p>lastly, if you want to return a new array containing the results of the processing of those elements greater than 3:</p>
<pre><code>intArray.select { |x| x > 3 }.map { |x| do_something_to x }
</code></pre>
|
13,405 | 429 | 2008-08-16T22:56:30Z | 13,396 | 2 | <p>In Python, you have <a href="http://docs.python.org/tut/node7.html#SECTION007130000000000000000" rel="nofollow" title="Human Interface Guidelines">filter and map</a>, which can so what you want:</p>
<pre><code>map(lambda x: foo(x + 1) filter(lambda x: x > 3, intArray))
</code></pre>
<p>There's also <a href="http://docs.python.org/tut/node7.html#SECTION007140000000000000000" rel="nofollow">list comprehensions</a> which can do both in one easy statement:</p>
<pre><code>[f(x + 1) for x in intArray if x > 3]
</code></pre>
|
13,406 | 960 | 2008-08-16T23:06:52Z | 13,396 | 3 | <p>In C# you can apply selective processing on anything that lives inside an IEnumerable like this: </p>
<pre><code>intArray.Where(i => i > 3).ConvertAll();
DoStuff(intArray.Where(i => i 3));
</code></pre>
<p>Etc..</p>
|
13,435 | 891 | 2008-08-17T00:44:57Z | 13,396 | 4 | <p>The increment in the original <code>foreach</code> loop will not affect the contents of the array, the only way to do this remains a <code>for</code> loop:</p>
<pre><code>for(int i = 0; i < intArray.Length; ++i)
{
if(intArray[i] > 3) ++intArray[i];
}
</code></pre>
<p>Linq is not intended to modify existing collections or sequences. It creates new sequences based on existing ones. It is possible to achieve the above code using Linq, though it is slightly against its purposes:</p>
<pre><code>var newArray1 = from i in intArray select ((i > 3) ? (i + 1) : (i));
var newArray2 = intArray.Select(i => (i > 3) ? (i + 1) : (i));
</code></pre>
<p>Using <code>where</code> (or equivalent), as shown in some of the other answers, will exclude any values less than or equal to 3 from the resulting sequence.</p>
<pre><code>var intArray = new int[] { 10, 1, 20, 2 };
var newArray = from i in intArray where i > 3 select i + 1;
// newArray == { 11, 21 }
</code></pre>
<p>There is a <code>ForEach</code> method on arrays that will allow you to use a lambda function instead of a <code>foreach</code> block, though for anything more than a method call I would stick with <code>foreach</code>.</p>
<pre><code>intArray.ForEach(i => DoSomething(i));
</code></pre>
|
13,456 | 1,554 | 2008-08-17T01:26:52Z | 13,454 | 0 | <p>You can obviously concatenate everything together:</p>
<pre><code>cleaned = stringwithslashes.replace("\\n","\n").replace("\\r","\n").replace("\\","")
</code></pre>
<p>Is that what you were after? Or were you hoping for something more terse?</p>
|
13,579 | 1,370 | 2008-08-17T10:28:00Z | 13,454 | -4 | <p>Python has a built-in escape() function analogous to PHP's addslashes, but no unescape() function (stripslashes), which in my mind is kind of ridiculous.</p>
<p>Regular expressions to the rescue (code not tested):</p>
<pre><code>p = re.compile( '\\(\\\S)')
p.sub('\1',escapedstring)
</code></pre>
<p>In theory that takes anything of the form \\(not whitespace) and returns \(same char)</p>
<p>edit: Upon further inspection, Python regular expressions are broken as all hell;</p>
<pre><code>>>> escapedstring
'This is a \\n\\n\\n test'
>>> p = re.compile( r'\\(\S)' )
>>> p.sub(r"\1",escapedstring)
'This is a nnn test'
>>> p.sub(r"\\1",escapedstring)
'This is a \\1\\1\\1 test'
>>> p.sub(r"\\\1",escapedstring)
'This is a \\n\\n\\n test'
>>> p.sub(r"\(\1)",escapedstring)
'This is a \\(n)\\(n)\\(n) test'
</code></pre>
<p>In conclusion, what the hell, Python.</p>
|
13,598 | 745 | 2008-08-17T12:15:13Z | 13,454 | 10 | <p>Not totally sure this is what you want, but..</p>
<pre><code>cleaned = stringwithslashes.decode('string_escape')
</code></pre>
|
13,608 | 893 | 2008-08-17T12:55:25Z | 13,454 | 2 | <p>It sounds like what you want could be reasonably efficiently handled through regular expressions:</p>
<pre><code>import re
def stripslashes(s):
r = re.sub(r"\\(n|r)", "\n", s)
r = re.sub(r"\\", "", r)
return r
cleaned = stripslashes(stringwithslashes)
</code></pre>
|
13,844 | 1,421 | 2008-08-17T19:01:02Z | 13,791 | 3 | <p>Well, I think you might have missed the r or miscounted the backslashes...</p>
<pre><code>"\\n" == r"\n"
>>> import re
>>> mystring = r"This is \\n a test \\r"
>>> p = re.compile( r"[\\][\\](.)" )
>>> print p.sub( r"\\\1", mystring )
This is \n a test \r
>>>
</code></pre>
<p>Which, if I understood is what was requested.</p>
<p>I suspect the more common request is this:</p>
<pre><code>>>> d = {'n':'\n', 'r':'\r', 'f':'\f'}
>>> p = re.compile(r"[\\]([nrfv])")
>>> print p.sub(lambda mo: d[mo.group(1)], mystring)
This is \
a test \
>>>
</code></pre>
<p>The interested student should also read Ken Thompson's <a href="http://cm.bell-labs.com/who/ken/trust.html" rel="nofollow" title="Cherry G80-11900">Reflections on Trusting Trust"</a>, wherein our hero uses a similar example to explain the perils of trusting compilers you haven't bootstrapped from machine code yourself.</p>
|
13,869 | 893 | 2008-08-17T19:26:33Z | 13,791 | 0 | <p>You are being tricked by Python's representation of the result string. The Python expression:</p>
<pre><code>'This is \\n a test \\r'
</code></pre>
<p>represents the string</p>
<pre><code>This is \n a test \r
</code></pre>
<p>which is I think what you wanted. Try adding 'print' in front of each of your p.sub() calls to print the actual string returned instead of a Python representation of the string.</p>
<pre><code>>>> mystring = r"This is \n a test \r"
>>> mystring
'This is \\n a test \\r'
>>> print mystring
This is \n a test \r
</code></pre>
|
13,875 | 1,421 | 2008-08-17T19:32:33Z | 13,857 | 37 | <p>It's simple: A function that references variables from a containing scope, potentially after flow-of-control has left that scope. That last bit is very useful:</p>
<pre><code>>>> def makeConstantAdder(x):
... constant = x
... def adder(y):
... return y + constant
... return adder
...
>>> f = makeConstantAdder(12)
>>> f(3)
15
>>> g = makeConstantAdder(4)
>>> g(3)
7
</code></pre>
<p>Note that 12 and 4 have "disappeared" inside f and g, respectively, this feature is what make f and g proper closures.</p>
|
13,882 | 1,370 | 2008-08-17T19:40:49Z | 13,791 | 0 | <p>The idea is that I'll read in an escaped string, and unescape it (a feature notably lacking from Python, which you shouldn't need to resort to regular expressions for in the first place). Unfortunately I'm not being tricked by the backslashes...</p>
<p>Another illustrative example:</p>
<pre><code>>>> mystring = r"This is \n ridiculous"
>>> print mystring
This is \n ridiculous
>>> p = re.compile( r"\\(\S)" )
>>> print p.sub( 'bloody', mystring )
This is bloody ridiculous
>>> print p.sub( r'\1', mystring )
This is n ridiculous
>>> print p.sub( r'\\1', mystring )
This is \1 ridiculous
>>> print p.sub( r'\\\1', mystring )
This is \n ridiculous
</code></pre>
<p>What I'd like it to print is</p>
<pre><code>This is
ridiculous
</code></pre>
|
13,902 | 1,659 | 2008-08-17T20:20:20Z | 13,857 | 6 | <p>I've never heard of transactions being used in the same context as explaining what a closure is and there really aren't any transaction semantics here.</p>
<p>It's called a closure because it "closes over" the outside variable (constant)--i.e., it's not just a function but an enclosure of the environment where the function was created. </p>
<p>In the following example, calling the closure g after changing x will also change the value of x within g, since g closes over x:</p>
<pre><code>x = 0
def f():
def g():
return x * 2
return g
closure = f()
print(closure()) # 0
x = 2
print(closure()) # 4
</code></pre>
|
13,906 | 150 | 2008-08-17T20:25:18Z | 13,857 | 13 | <p>I like <a href="http://effbot.org/zone/closure.htm">this rough, succinct definition</a>:</p>
<blockquote>
<p>A function that can refer to environments that are no longer active.</p>
</blockquote>
<p>I'd add</p>
<blockquote>
<p>A closure allows you to bind variables into a function <em>without passing them as parameters</em>.</p>
</blockquote>
<p>Decorators which accept parameters are a common use for closures. Closures are a common implementation mechanism for that sort of "function factory". I frequently choose to use closures in the <a href="http://c2.com/cgi/wiki?StrategyPattern">Strategy Pattern</a> when the strategy is modified by data at run-time.</p>
<p>In a language that allows anonymous block definition -- e.g., Ruby, C# -- closures can be used to implement (what amount to) novel new control structures. The lack of anonymous blocks is among <a href="http://ivan.truemesh.com/archives/000411.html">the limitations of closures in Python</a>.</p>
|
13,943 | 1,472 | 2008-08-17T21:36:32Z | 13,791 | 7 | <p>Isn't that what <a href="#13844">Anders' second example</a> does?</p>
<p>In 2.5 there's also a <code>string-escape</code> encoding you can apply:</p>
<pre><code>>>> mystring = r"This is \n a test \r"
>>> mystring.decode('string-escape')
'This is \n a test \r'
>>> print mystring.decode('string-escape')
This is
a test
>>>
</code></pre>
|
13,949 | 1,667 | 2008-08-17T21:46:02Z | 13,941 | 47 | <p>Have you tried :</p>
<pre><code>import sys
sys.stdout.write('\a')
sys.stdout.flush()
</code></pre>
<p>That works for me here on Mac OS 10.5</p>
<p>Actually, I think your original attempt works also with a little modification:</p>
<pre><code>print('\a')
</code></pre>
<p>(You just need the single quotes around the character sequence).</p>
|
13,958 | 1,370 | 2008-08-17T21:55:54Z | 13,791 | 0 | <p>Mark; his second example requires every escaped character thrown into an array initially, which generates a KeyError if the escape sequence happens not to be in the array. It will die on anything but the three characters provided (give \v a try), and enumerating every possible escape sequence every time you want to unescape a string (or keeping a global array) is a really bad solution. Analogous to PHP, that's using <code>preg_replace_callback()</code> with a lambda instead of <code>preg_replace()</code>, which is utterly unnecessary in this situation.</p>
<p>I'm sorry if I'm coming off as a dick about it, I'm just utterly frustrated with Python. This is supported by every other regular expression engine I've ever used, and I can't understand why this wouldn't work.</p>
<p>Thank you for responding; the <code>string.decode('string-escape')</code> function is precisely what i was looking for initially. If someone has a general solution to the regex backreference problem, feel free to post it and I'll accept that as an answer as well.</p>
|
13,959 | 1,472 | 2008-08-17T21:56:10Z | 13,941 | 4 | <p>I had to turn off the "Silence terminal bell" option in my active Terminal Profile in iTerm for <code>print('\a')</code> to work. It seemed to work fine by default in Terminal.</p>
<p>You can also use the Mac module <code>Carbon.Snd</code> to play the system beep:</p>
<pre><code>>>> import Carbon.Snd
>>> Carbon.Snd.SysBeep(1)
>>>
</code></pre>
<p>The Carbon modules don't have any documentation, so I had to use <code>help(Carbon.Snd)</code> to see what functions were available. It seems to be a direct interface onto Carbon, so the docs on Apple Developer Connection probably help.</p>
|
14,304 | 242,853 | 2008-08-18T08:06:30Z | 14,281 | 0 | <p>You could loop through the zip files, reading individual files using the zipfile module and running your regex on those, eliminating to unzip all the files at once. </p>
<p>I'm fairly certain that you can't run a regex over the zipped data, at least not meaningfully.</p>
|
14,314 | 1,404 | 2008-08-18T08:10:57Z | 14,281 | 0 | <p>To access the contents of a zip file you have to unzip it, although the zipfile package makes this fairly easy, as you can unzip each file within an archive individually.</p>
<p><a href="http://docs.python.org/lib/module-zipfile.html" rel="nofollow">Python zipfile module</a></p>
|
14,320 | 116 | 2008-08-18T08:19:06Z | 14,281 | 8 | <p>There's nothing that will automatically do what you want.</p>
<p>However, there is a python zipfile module that will make this easy to do. Here's how to iterate over the lines in the file.</p>
<pre><code>#!/usr/bin/python
import zipfile
f = zipfile.ZipFile('myfile.zip')
for subfile in f.namelist():
print subfile
data = f.read(subfile)
for line in data.split('\n'):
print line
</code></pre>
|
15,261 | 1,813 | 2008-08-18T21:35:39Z | 8,154 | 2 | <p>You might want to check MySQL's timeout variables:</p>
<pre><code>show variables like '%timeout%';
</code></pre>
<p>You're probably interested in <code>wait_timeout</code> (less likely but possible: <code>interactive_timeout</code>). On Debian and Ubuntu, the defaults are 28800 (MySQL kills connections after 8 hours), but maybe the default for your platform is different or whoever administrates the server has configured things differently.</p>
<p>AFAICT, <code>pool_recycle</code> doesn't actually keep the connections alive, it expires them on its own before MySQL kills them. I'm not familiar with pylons, but if causing the connections to intermittently do a <code>SELECT 1;</code> is an option, that will keep them alive at the cost of basically no server load and minimal network traffic. One final thought: are you somehow managing to use a connection that pylons thinks it has expired?</p>
|
15,291 | 1,797 | 2008-08-18T22:06:02Z | 4,942 | 0 | <p>I agree with mreggen. Tell them by working in Python you can get things done faster. Getting things done faster possibly means money saved by the client. In the least it means that you are working with a language you a more comfortable in, meaning faster development, debugging, and refactoring time. There will be less time spent looking up documentation on what function to use to find the length of a string, etc. </p>
|
15,296 | 1,199,387 | 2008-08-18T22:10:13Z | 4,942 | 4 | <p>It's one of the preferred languages over at Google - It's several years ahead of Ruby in terms of "maturity" (what ever that really means - but managers like that). Since it's prefered by Google you can also run it on the Google App Engine.</p>
<p>Mircosoft is also embracing Python, and will have a v2.0 of IronPython coming out shortly. They are working on a Ruby implementation as well, but the Python version is way ahead, and is actually "ready for primetime". That give you the possibility for easy integration with .NET code, as well as being able to write client side RIAs in Python when Silverlight 2 ships.</p>
|
End of preview.
No dataset card yet
- Downloads last month
- 6