title
stringlengths
12
150
question_id
int64
469
40.1M
question_score
int64
2
5.52k
question_date
stringdate
2008-08-02 15:11:16
2016-10-18 06:16:31
answer_id
int64
536
40.1M
answer_score
int64
7
8.38k
answer_date
stringdate
2008-08-02 18:49:07
2016-10-18 06:19:33
tags
listlengths
1
5
question_body_md
stringlengths
15
30.2k
answer_body_md
stringlengths
11
27.8k
Interpreted vs. Compiled vs. Late-Binding
2,881,526
13
2010-05-21T11:15:54Z
2,881,565
9
2010-05-21T11:22:25Z
[ "java", "python", "late-binding", "compiled", "interpreted" ]
Python is compiled into an intermediate bytecode(pyc) and then executed. So, there is a compilation followed by interpretation. However, long-time Python users say that Python is a "late-binding" language and that it should`nt be referred to as an interpreted language. 1. How would Python be different from another int...
> How would Python be different from another interpreted language? That involves hair-splitting. Interpreted languages and "managed code" languages like C# and virtual machine languages (like Java) form a weird continuum. There are folks who will say that **all** languages are "interpreted" -- even machine language. A...
Interpreted vs. Compiled vs. Late-Binding
2,881,526
13
2010-05-21T11:15:54Z
2,881,574
7
2010-05-21T11:24:29Z
[ "java", "python", "late-binding", "compiled", "interpreted" ]
Python is compiled into an intermediate bytecode(pyc) and then executed. So, there is a compilation followed by interpretation. However, long-time Python users say that Python is a "late-binding" language and that it should`nt be referred to as an interpreted language. 1. How would Python be different from another int...
Late binding is a very different concept to interpretation. Strictly speaking, an interpreted language is executed directly from source. It doesn't go through a byte-code compilation stage. The confusion arises because the python program *is* an interpreter, but it interprets the byte-code, so it is Python's byte-code...
Spawning a thread in python
2,882,308
14
2010-05-21T13:11:11Z
2,883,627
18
2010-05-21T16:01:32Z
[ "python" ]
I have a series of 'tasks' that I would like to run in separate threads. The tasks are to be performed by separate modules. Each containing the business logic for processing their tasks. Given a tuple of tasks, I would like to be able to spawn a new thread for each module as follows. ``` from foobar import alice, bob...
Instead of switch-case, why not use a proper polymorphism? For example, here what you can do with duck typing in Python: In, say, `alice.py`: ``` def do_stuff(data): print 'alice does stuff with %s' % data ``` In, say, `bob.py`: ``` def do_stuff(data): print 'bob does stuff with %s' % data ``` Then in your...
Running the same code for get(self) as post(self)
2,882,915
5
2010-05-21T14:26:00Z
2,883,169
11
2010-05-21T14:59:15Z
[ "python", "google-app-engine" ]
Its been mentioned in other answers about getting the same code running for both the `def get(self)` and the `def post(self)` for any given request. I was wondering what techniques people use, I was thinking of: ``` class ListSubs(webapp.RequestHandler): def get(self): self._run() def post(self): ...
I would suggest both theoretical and practical reasons why the approach you're using (refactoring out the common code to a separate method and calling it from both post and get methods) is superior to the apparently-simpler alternative of just having one of those two methods call the other. From a theoretical viewpoin...
Calling MATLAB functions from python
2,883,189
39
2010-05-21T15:01:23Z
2,885,122
21
2010-05-21T19:50:34Z
[ "python", "matlab", "visual-c++" ]
Is it possible to run MATLAB functions from within Python? I search the internet, I could only find PyMat. The bad thing is the compiled version only supports Python2.2 and I am using 2.6. So I tried to download the source code, so I can compile it for myself. But I cannot compile it, VC++ express seems not to have the...
PyMat looks like it's been abandoned. I'm assuming you are on windows so you could always do the simplest approach and use Matlab's COM interface: ``` >>> import win32com.client >>> h = win32com.client.Dispatch('matlab.application') >>> h.Execute ("plot([0 18], [7 23])") >>> h.Execute ("1+1") u'\nans =\n\n 2\n\n'...
Calling MATLAB functions from python
2,883,189
39
2010-05-21T15:01:23Z
3,451,672
28
2010-08-10T17:25:22Z
[ "python", "matlab", "visual-c++" ]
Is it possible to run MATLAB functions from within Python? I search the internet, I could only find PyMat. The bad thing is the compiled version only supports Python2.2 and I am using 2.6. So I tried to download the source code, so I can compile it for myself. But I cannot compile it, VC++ express seems not to have the...
Another option is [`Mlabwrap`](http://mlabwrap.sourceforge.net/): > Mlabwrap is a high-level python to Matlab® bridge that lets Matlab look like a normal python library. It works well with numpy arrays. An example from the home page: ``` >>> from mlabwrap import mlab; from numpy import * >>> xx = arange(-2*pi, 2*pi...
Calling MATLAB functions from python
2,883,189
39
2010-05-21T15:01:23Z
11,467,714
9
2012-07-13T09:27:24Z
[ "python", "matlab", "visual-c++" ]
Is it possible to run MATLAB functions from within Python? I search the internet, I could only find PyMat. The bad thing is the compiled version only supports Python2.2 and I am using 2.6. So I tried to download the source code, so I can compile it for myself. But I cannot compile it, VC++ express seems not to have the...
There is a python-matlab bridge which is unique in the sense that Matlab runs in the background so you don't have the startup cost each time you call a Matlab function. <https://github.com/jaderberg/python-matlab-bridge> it's as easy as downloading and the following code: ``` from pymatbridge import Matlab mlab = Mat...
Calling MATLAB functions from python
2,883,189
39
2010-05-21T15:01:23Z
23,762,412
23
2014-05-20T14:21:41Z
[ "python", "matlab", "visual-c++" ]
Is it possible to run MATLAB functions from within Python? I search the internet, I could only find PyMat. The bad thing is the compiled version only supports Python2.2 and I am using 2.6. So I tried to download the source code, so I can compile it for myself. But I cannot compile it, VC++ express seems not to have the...
I know this is an old question and has been answered. But I was looking for the same thing (for the Mac) and found that there are quite a few options with different methods of interacting with matlab and different levels of maturity. Here's what I found: ## pymat A low level interface to Matlab using the matlab engin...
How can I freeze a dual-mode (GUI and console) application using cx_Freeze?
2,883,205
6
2010-05-21T15:02:47Z
3,237,924
13
2010-07-13T14:02:19Z
[ "python", "wxpython", "cx-freeze" ]
I've developed a Python application that runs both in the GUI mode and the console mode. If any arguments are specified, it runs in a console mode else it runs in the GUI mode. I've managed to freeze this using cx\_Freeze. I had some problems hiding the black console window that would pop up with wxPython and so I mod...
I found this bit on [this](http://sebsauvage.net/python/snyppets/) page: > Tip for the console-less version: If > you try to print anything, you will > get a nasty error window, because > stdout and stderr do not exist (and > the cx\_freeze Win32gui.exe stub will > display an error Window). This is a > pain when you w...
Why is i++++++++i valid in python?
2,883,920
16
2010-05-21T16:45:03Z
2,883,944
28
2010-05-21T16:49:49Z
[ "python" ]
I "accidentally" came across this weird but valid syntax ``` i=3 print i+++i #outputs 6 print i+++++i #outputs 6 print i+-+i #outputs 0 print i+--+i #outputs 6 ``` (for every even no: of minus symbol, it outputs 6 else 0, why?) Does this do anything useful? **Update (Don't take it the wrong way..I love python)**: O...
Since Python doesn't have C-style ++ or -- operators, one is left to assume that you're negating or positivating(?) the value on the left. E.g. what would you expect `i + +5` to be? ``` i=3 print i + +(+i) #outputs 6 print i + +(+(+(+i))) #outputs 6 print i + -(+i) #outputs 0 print i + -(-(+i)) #outputs 6 ``` Notabl...
Django select max id
2,884,509
14
2010-05-21T18:19:00Z
2,884,803
26
2010-05-21T19:01:42Z
[ "python", "django" ]
given a standard model (called Image) with an autoset 'id', how do I get the max id? So far I've tried: ``` max_id = Image.objects.all().aggregate(Max('id')) ``` but I get a 'id\_\_max' Key error. Trying ``` max_id = Image.objects.order_by('id')[0].id ``` gives a 'argument 2 to map() must support iteration' excep...
Just order by reverse id, and take the top one. ``` Image.objects.all().order_by("-id")[0] ```
Django select max id
2,884,509
14
2010-05-21T18:19:00Z
15,082,690
40
2013-02-26T06:22:02Z
[ "python", "django" ]
given a standard model (called Image) with an autoset 'id', how do I get the max id? So far I've tried: ``` max_id = Image.objects.all().aggregate(Max('id')) ``` but I get a 'id\_\_max' Key error. Trying ``` max_id = Image.objects.order_by('id')[0].id ``` gives a 'argument 2 to map() must support iteration' excep...
In current version of django (1.4) it is even more readable `Image.objects.latest('id').id`
Using Python's ConfigParser to read a file without section name
2,885,190
51
2010-05-21T20:01:34Z
2,885,753
28
2010-05-21T21:37:02Z
[ "python", "parsing", "configuration-files" ]
I am using ConfigParser to read the runtime configuration of a script. I would like to have the flexibility of not providing a section name (there are scripts which are simple enough; they don't need a 'section'). ConfigParser will throw the `NoSectionError` exception, and will not accept the file. How can I make Con...
Alex Martelli [provided a solution](http://stackoverflow.com/questions/2819696/module-to-use-when-parsing-properties-file-in-python/2819788#2819788) for using `ConfigParser` to parse `.properties` files (which are apparently section-less config files). [His solution](http://stackoverflow.com/a/25493615/3462319) is a f...
Using Python's ConfigParser to read a file without section name
2,885,190
51
2010-05-21T20:01:34Z
7,918,193
8
2011-10-27T15:18:07Z
[ "python", "parsing", "configuration-files" ]
I am using ConfigParser to read the runtime configuration of a script. I would like to have the flexibility of not providing a section name (there are scripts which are simple enough; they don't need a 'section'). ConfigParser will throw the `NoSectionError` exception, and will not accept the file. How can I make Con...
You can use the ConfigObj library to do that simply : <http://www.voidspace.org.uk/python/configobj.html> Updated: Find latest code [here](https://pypi.python.org/pypi/configobj/). If you are under Debian/Ubuntu, you can install this module using your package manager : ``` apt-get install python-configobj ``` An ex...
Using Python's ConfigParser to read a file without section name
2,885,190
51
2010-05-21T20:01:34Z
10,746,467
27
2012-05-24T23:01:45Z
[ "python", "parsing", "configuration-files" ]
I am using ConfigParser to read the runtime configuration of a script. I would like to have the flexibility of not providing a section name (there are scripts which are simple enough; they don't need a 'section'). ConfigParser will throw the `NoSectionError` exception, and will not accept the file. How can I make Con...
Enlightened by [this answer by jterrace](http://stackoverflow.com/a/7472878), I come up with this solution: 1. Read entire file into a string 2. Prefix with a default section name 3. Use StringIO to mimic a file-like object ``` ini_str = '[root]\n' + open(ini_path, 'r').read() ini_fp = StringIO.StringIO(ini_str) conf...
Using Python's ConfigParser to read a file without section name
2,885,190
51
2010-05-21T20:01:34Z
26,859,985
18
2014-11-11T07:47:50Z
[ "python", "parsing", "configuration-files" ]
I am using ConfigParser to read the runtime configuration of a script. I would like to have the flexibility of not providing a section name (there are scripts which are simple enough; they don't need a 'section'). ConfigParser will throw the `NoSectionError` exception, and will not accept the file. How can I make Con...
You can do this with a single additional line of code. (Two lines if you count `import` statements.) In python 3, use [`itertools.chain()`](https://docs.python.org/3/library/itertools.html#itertools.chain) to simulate a section header for [`read_file()`](https://docs.python.org/3/library/configparser.html#configparser...
C++ Structure within itself?
2,885,502
8
2010-05-21T20:54:29Z
2,885,510
19
2010-05-21T20:56:04Z
[ "c++", "python", "c", "huffman-coding" ]
I've been trying to port this code to python, but there is something I do not quite understand in C++ (I do know a bit of C++ but this is beyond me): ``` typedef struct huffnode_s { struct huffnode_s *zero; struct huffnode_s *one; unsigned char val; float freq; } huffnode_t; ``` What I don't get is ho...
`huffnode_s` isn't within itself, only *pointers* to `huffnode_s` are in there. Since a pointer is of known size, it's no problem.
C++ Structure within itself?
2,885,502
8
2010-05-21T20:54:29Z
2,885,527
11
2010-05-21T20:58:22Z
[ "c++", "python", "c", "huffman-coding" ]
I've been trying to port this code to python, but there is something I do not quite understand in C++ (I do know a bit of C++ but this is beyond me): ``` typedef struct huffnode_s { struct huffnode_s *zero; struct huffnode_s *one; unsigned char val; float freq; } huffnode_t; ``` What I don't get is ho...
This. ``` class Huffnode(object): def __init__(self, zero, one, val, freq): """zero and one are Huffnode's, val is a 'char' and freq is a float.""" self.zero = zero self.one = one self.val = val self.freq = freq ``` You can then refactor your various C functions to be metho...
Adding custom fields to users in django
2,886,987
13
2010-05-22T04:49:18Z
2,887,048
16
2010-05-22T05:21:18Z
[ "python", "django" ]
I am using the create\_user() function that Django provides to create my users. Also I want to store additional information about the users. So I tried following the instructions given at <http://docs.djangoproject.com/en/dev/topics/auth/#storing-additional-information-about-users> but I cannot get it to work for me....
I am not aware of a step by step(though I am sure a solid google would produce something). But here is a quick go at it. 1) Create a `UserProfile` model to hold the extra information and put it in your `models.py`. It could look something like this: ``` class UserProfile(models.Model): #required by the auth model...
Adding custom fields to users in django
2,886,987
13
2010-05-22T04:49:18Z
34,427,137
7
2015-12-23T01:21:19Z
[ "python", "django" ]
I am using the create\_user() function that Django provides to create my users. Also I want to store additional information about the users. So I tried following the instructions given at <http://docs.djangoproject.com/en/dev/topics/auth/#storing-additional-information-about-users> but I cannot get it to work for me....
The [recommended way](https://docs.djangoproject.com/en/1.9/topics/auth/customizing/#extending-the-existing-user-model) is to create a new model and give it a `OneToOneField()` with the built-in `User` model like so: ``` class Student(models.Model): user = models.OneToOneField(User) college = models.CharField(...
Python: How can I override one module in a package with a modified version that lives outside the package?
2,887,041
9
2010-05-22T05:19:59Z
2,887,888
9
2010-05-22T11:32:00Z
[ "python", "django" ]
I would like to update one module in a python package with my own version of the module, with the following conditions: * I want my updated module to live outside of the original package (either because I don't have access to the package source, or because I want to keep my local modifications in a separate repo, etc)...
Just set the entry in sys.modules before anything else imports it: ``` import sys import myreplacement sys.modules["original"] = myreplacement ``` Then, when someone does "import original", they'll get your version instead. If you want to replace a submodule, you can do it like this: ``` import sys import thepackag...
Importing a CSV file into a sqlite3 database table using Python
2,887,878
43
2010-05-22T11:25:58Z
2,887,897
9
2010-05-22T11:34:41Z
[ "python", "database", "sqlite", "csv", "sqlite3" ]
I have a CSV file and I want to bulk-import this file into my sqlite3 database using Python. the command is ".import .....". but it seems that it cannot work like this. Can anyone give me an example of how to do it in sqlite3? I am using windows just in case. Thanks
The `.import` command is a feature of the sqlite3 command-line tool. To do it in Python, you should simply load the data using whatever facilities Python has, such as the [csv module](http://docs.python.org/library/csv.html), and inserting the data as per usual. This way, you also have control over what types are inse...
Importing a CSV file into a sqlite3 database table using Python
2,887,878
43
2010-05-22T11:25:58Z
2,888,042
71
2010-05-22T12:20:04Z
[ "python", "database", "sqlite", "csv", "sqlite3" ]
I have a CSV file and I want to bulk-import this file into my sqlite3 database using Python. the command is ".import .....". but it seems that it cannot work like this. Can anyone give me an example of how to do it in sqlite3? I am using windows just in case. Thanks
``` import csv, sqlite3 con = sqlite3.connect(":memory:") cur = con.cursor() cur.execute("CREATE TABLE t (col1, col2);") # use your column names here with open('data.csv','rb') as fin: # `with` statement available in 2.5+ # csv.DictReader uses first line in file for column headings by default dr = csv.DictRea...
Importing a CSV file into a sqlite3 database table using Python
2,887,878
43
2010-05-22T11:25:58Z
12,432,311
7
2012-09-14T21:37:11Z
[ "python", "database", "sqlite", "csv", "sqlite3" ]
I have a CSV file and I want to bulk-import this file into my sqlite3 database using Python. the command is ".import .....". but it seems that it cannot work like this. Can anyone give me an example of how to do it in sqlite3? I am using windows just in case. Thanks
Many thanks for bernie's [answer](http://stackoverflow.com/a/2888042/12892)! Had to tweak it a bit - here's what worked for me: ``` import csv, sqlite3 conn = sqlite3.connect("pcfc.sl3") curs = conn.cursor() curs.execute("CREATE TABLE PCFC (id INTEGER PRIMARY KEY, type INTEGER, term TEXT, definition TEXT);") reader = ...
Importing a CSV file into a sqlite3 database table using Python
2,887,878
43
2010-05-22T11:25:58Z
28,802,613
20
2015-03-02T04:14:26Z
[ "python", "database", "sqlite", "csv", "sqlite3" ]
I have a CSV file and I want to bulk-import this file into my sqlite3 database using Python. the command is ".import .....". but it seems that it cannot work like this. Can anyone give me an example of how to do it in sqlite3? I am using windows just in case. Thanks
Creating an sqlite connection to a file on disk is left as an exercise for the reader ... but there is now a two-liner made possible by the pandas library ``` df = pandas.read_csv(csvfile) df.to_sql(table_name, conn, if_exists='append', index=False) ```
Getting two characters from string in python
2,888,281
2
2010-05-22T13:38:19Z
2,888,285
8
2010-05-22T13:40:26Z
[ "python", "loops", "for-loop", "character" ]
how to get in python from string not one character, but two? I have: ``` long_str = 'abcd' for c in long_str: print c ``` and it gives me like ``` a b c d ``` but i need to get ``` ab cd ``` I'm new in python.. is there any way?
You can use slice notation. `long_str[x:y]` will give you characters in the range `[x, y)` (where x is included and y is not). ``` >>> for i in range(0, len(long_str) - 1, 2): ... print long_str[i:i+2] ... ab cd ``` Here I am using the three-argument range operator to denote start, end, and step (see <http://docs....
Selenium Webdriver python bindings
2,888,773
3
2010-05-22T16:01:47Z
6,602,337
7
2011-07-06T20:12:03Z
[ "python", "binding", "webdriver" ]
I can't make python bindings for webdriver workable. [Here is](http://code.google.com/p/selenium/wiki/PythonBindings?redir=1) tutorial for installing. > ``` > easy_install webdriver > ``` Won't find webdriver package so I have to install it manually from sources. I've downloaded source from trunk, set **WEBDRIVER** a...
the latest selenium (which includes webdriver) bindings should be [pip](http://www.pip-installer.org) installable: ``` pip install selenium ```
Creating collaborative whiteboard drawing application
2,889,363
6
2010-05-22T18:56:09Z
2,889,781
10
2010-05-22T21:12:09Z
[ "python", "wxpython", "twisted", "paint", "whiteboard" ]
I have my own drawing program in place, with a variety of "drawing tools" such as Pen, Eraser, Rectangle, Circle, Select, Text etc. It's made with Python and wxPython. Each tool mentioned above is a class, which all have polymorphic methods, such as left\_down(), mouse\_motion(), hit\_test() etc. The program manages a...
**Making any real-time collaborative tool/game boils down to efficiently synchronizing changes on a minimal shared data structure between clients.** Network bandwidth is the bottleneck. Send only information absolutely needed to synchronize the shared data. You are on the right track by storing shapes instead of indivi...
How to force PyYAML to load strings as unicode objects?
2,890,146
19
2010-05-22T23:27:31Z
2,967,461
18
2010-06-03T15:35:50Z
[ "python", "python-2.x", "pyyaml" ]
The PyYAML package loads unmarked strings as either unicode or str objects, depending on their content. I would like to use unicode objects throughout my program (and, unfortunately, can't switch to Python 3 just yet). Is there an easy way to force PyYAML to always strings load unicode objects? I do not want to clutt...
Here's a version which overrides the PyYAML handling of strings by always outputting `unicode`. In reality, this is probably the identical result of the other response I posted except shorter (i.e. you still need to make sure that strings in custom classes are converted to `unicode` or passed `unicode` strings yourself...
Load Pymacs & Ropemacs only when opening a Python file?
2,890,199
4
2010-05-22T23:54:01Z
2,953,084
9
2010-06-01T20:28:18Z
[ "python", "emacs", "ropemacs", "pymacs" ]
I use **Pymacs** to load **ropemacs** and **rope** with the following lines in my **.emacs** file as described [here](http://www.enigmacurry.com/2009/01/21/autocompleteel-python-code-completion-in-emacs/). ``` (autoload 'pymacs-load "pymacs" nil t) (pymacs-load "ropemacs" "rope-") ``` It however slows down the start-...
In my **.emacs** I have: ``` (autoload 'python-mode "my-python-setup" "" t) ``` And in a separate file **my-python-setup.el** I keep: ``` (require 'python) (add-to-list 'auto-mode-alist '("\\.py\\'" . python-mode)) ;; Initialize Pymacs (autoload 'pymacs-apply "pymacs") (autoload 'pymacs-call "pymacs") (autoload 'pym...
In Ruby or Python can the very concept of Class be rewritten?
2,890,229
9
2010-05-23T00:06:10Z
2,890,252
8
2010-05-23T00:16:21Z
[ "python", "ruby", "class", "metaprogramming", "ontology" ]
first time at stack overflow. I'm looking into using some of the metaprogramming features provided by Ruby or Python, but first I need to know the extent to which they will allow me to extend the language. The main thing I need to be able to do is to rewrite the concept of *Class*. This doesn't mean that I want to rew...
Sounds like [duck typing](http://en.wikipedia.org/wiki/Duck_typing#In_Python) to me. Just declare the methods you want and remember that it's easier to ask forgiveness than permission: ``` try: poodle.wear() except (AttributeError, TypeError): pass ```
In Ruby or Python can the very concept of Class be rewritten?
2,890,229
9
2010-05-23T00:06:10Z
2,890,303
7
2010-05-23T00:42:03Z
[ "python", "ruby", "class", "metaprogramming", "ontology" ]
first time at stack overflow. I'm looking into using some of the metaprogramming features provided by Ruby or Python, but first I need to know the extent to which they will allow me to extend the language. The main thing I need to be able to do is to rewrite the concept of *Class*. This doesn't mean that I want to rew...
I agree with Samir that it just sounds like duck typing. You don't need to care what 'type' an object really 'is' you only need bother with what an object can 'do'. This is true in both Ruby and Python. However if you really are checking the types of classes and you really do need to have a `Poodle` object optionally ...
Number of lines in csv.DictReader
2,890,549
16
2010-05-23T03:03:07Z
2,890,569
17
2010-05-23T03:13:07Z
[ "python", "iterator", "python-3.x" ]
I have a csv DictReader object (using Python 3.1), but I would like to know the number of lines/rows contained in the reader **before** I iterate through it. Something like as follows... ``` myreader = csv.DictReader(open('myFile.csv', newline='')) totalrows = ? rowcount = 0 for row in myreader: rowcount +=1 ...
``` rows = list(myreader) totalrows = len(rows) for i, row in enumerate(rows): print("Row %d/%d" % (i+1, totalrows)) ```
Number of lines in csv.DictReader
2,890,549
16
2010-05-23T03:03:07Z
2,891,061
12
2010-05-23T08:17:32Z
[ "python", "iterator", "python-3.x" ]
I have a csv DictReader object (using Python 3.1), but I would like to know the number of lines/rows contained in the reader **before** I iterate through it. Something like as follows... ``` myreader = csv.DictReader(open('myFile.csv', newline='')) totalrows = ? rowcount = 0 for row in myreader: rowcount +=1 ...
You only need to open the file once: ``` import csv f = open('myFile.csv', 'rb') countrdr = csv.DictReader(f) totalrows = 0 for row in countrdr: totalrows += 1 f.seek(0) # You may not have to do this, I didn't check to see if DictReader did myreader = csv.DictReader(f) for row in myreader: do_work ``` No mat...
How to join two wav files using python?
2,890,703
12
2010-05-23T04:57:25Z
2,900,266
27
2010-05-24T20:57:37Z
[ "python", "audio", "wav" ]
I am using python programming language,I want to join to wav file one at the end of other wav file? I have a Question in the forum which suggest how to merge two wav file i.e add the contents of one wav file at certain offset,but i want to join two wav file at the end of each other... And also i had a prob playing the...
Python ships with the [wave](http://docs.python.org/library/wave.html) module that will do what you need. The example below works when the details of the files (mono or stereo, frame rates, etc) are the same: ``` import wave infiles = ["sound_1.wav", "sound_2.wav"] outfile = "sounds.wav" data= [] for infile in infil...
Extract IP address from an html string (python)
2,890,896
17
2010-05-23T06:57:25Z
2,890,905
31
2010-05-23T07:02:50Z
[ "python", "regex", "string" ]
My Friends, I really want to extract a simple IP address from a string (actually an one-line html) using Python. But it turns out that 2 hours passed I still couldn't come up with a good solution. ``` >>> s = "<html><head><title>Current IP Check</title></head><body>Current IP Address: 165.91.15.131</body></html>" ```...
Remove your capturing group: ``` ip = re.findall( r'[0-9]+(?:\.[0-9]+){3}', s ) ``` Result: ``` ['165.91.15.131'] ``` Notes: * If you are parsing HTML it might be a good idea to look at [BeautifulSoup](http://www.crummy.com/software/BeautifulSoup/). * Your regular expression matches some invalid IP addresses such ...
Extract IP address from an html string (python)
2,890,896
17
2010-05-23T06:57:25Z
2,890,922
7
2010-05-23T07:11:32Z
[ "python", "regex", "string" ]
My Friends, I really want to extract a simple IP address from a string (actually an one-line html) using Python. But it turns out that 2 hours passed I still couldn't come up with a good solution. ``` >>> s = "<html><head><title>Current IP Check</title></head><body>Current IP Address: 165.91.15.131</body></html>" ```...
You can use the following regex to capture only valid IP addresses ``` re.findall(r'\b25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?\.25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?\.25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?\.25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?\b',s) ``` returns ``` ['165', '91', '15', '131'] ```
list exported functions from dll with ctypes
2,891,493
25
2010-05-23T11:22:12Z
2,892,131
9
2010-05-23T14:37:45Z
[ "python", "dll", "shared-libraries", "ctypes" ]
Is there any way to know which functions are exported from the `dll` through python foreign function library `ctypes`? And if possible to know details about the exported functions through c`types`. If yes, could someone provide a snippet of code?
I don't think ctypes offers this functionality. On Windows with visual studio: ``` DUMPBIN -EXPORTS XXX.DLL ``` Or for mingw on windows: ``` objdump -p XXX.dll ```
Pretty-printing of numpy.array
2,891,790
155
2010-05-23T12:54:29Z
2,891,805
242
2010-05-23T12:59:36Z
[ "python", "numpy", "pretty-print" ]
I'm curious, whether there is any way to print formatted numpy.arrays, e.g., in the way similar to this: ``` x = 1.23456 print '%.3f' % x ``` If I want to print the numpy.array of floats, it prints several decimals, often in 'scientific' format, which is rather hard to read even for low-dimensional arrays. However, n...
You can use `set_printoptions` to set the precision of the output: ``` import numpy as np x=np.random.random(10) print(x) # [ 0.07837821 0.48002108 0.41274116 0.82993414 0.77610352 0.1023732 # 0.51303098 0.4617183 0.33487207 0.71162095] np.set_printoptions(precision=3) print(x) # [ 0.078 0.48 0.413 0.8...
Pretty-printing of numpy.array
2,891,790
155
2010-05-23T12:54:29Z
18,287,838
22
2013-08-17T10:37:56Z
[ "python", "numpy", "pretty-print" ]
I'm curious, whether there is any way to print formatted numpy.arrays, e.g., in the way similar to this: ``` x = 1.23456 print '%.3f' % x ``` If I want to print the numpy.array of floats, it prints several decimals, often in 'scientific' format, which is rather hard to read even for low-dimensional arrays. However, n...
Unutbu gave a really complete answer (they got a +1 from me too), but here is a lo-tech alternative: ``` >>> x=np.random.randn(5) >>> x array([ 0.25276524, 2.28334499, -1.88221637, 0.69949927, 1.0285625 ]) >>> ['{:.2f}'.format(i) for i in x] ['0.25', '2.28', '-1.88', '0.70', '1.03'] ``` As a function (using the `f...
Pretty-printing of numpy.array
2,891,790
155
2010-05-23T12:54:29Z
30,630,098
15
2015-06-03T20:31:58Z
[ "python", "numpy", "pretty-print" ]
I'm curious, whether there is any way to print formatted numpy.arrays, e.g., in the way similar to this: ``` x = 1.23456 print '%.3f' % x ``` If I want to print the numpy.array of floats, it prints several decimals, often in 'scientific' format, which is rather hard to read even for low-dimensional arrays. However, n...
You can get a subset of the `np.set_printoptions` functionality from the `np.array_str` command, which applies only to a single print statement. <http://docs.scipy.org/doc/numpy/reference/generated/numpy.array_str.html> For example: ``` In [27]: x = np.array([[1.1, 0.9, 1e-6]]*3) In [28]: print x [[ 1.10000000e+00...
Longest common substring from more than two strings - Python
2,892,931
44
2010-05-23T18:37:39Z
2,894,073
41
2010-05-24T00:12:40Z
[ "python", "string", "longest-substring" ]
I'm looking for a python library for finding the longest common substring from a set of python strings. I'have read that it exist to way to solve this problem : - one using suffix trees - the other using dynamic programming. The method implemented is not important. Otherwise, it is important to have a implementation ...
These paired functions will find the longest common string in any arbitrary array of strings: ``` def long_substr(data): substr = '' if len(data) > 1 and len(data[0]) > 0: for i in range(len(data[0])): for j in range(len(data[0])-i+1): if j > len(substr) and is_substr(data[0...
verbose_name for a model's method
2,892,999
14
2010-05-23T18:55:15Z
2,893,021
15
2010-05-23T19:02:52Z
[ "python", "django", "django-models", "django-admin" ]
How can I set a verbose\_name for a model's method, so that it might be displayed in the admin's change\_view form? example: ``` class Article(models.Model): title = models.CharField(max_length=64) created_date = models.DateTimeField(....) def created_weekday(self): return self.created_date.strfti...
[list\_display](http://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.list_display) ``` created_weekday.short_description = 'Foo' ```
404 not found in telnet, works fine in browser
2,893,063
4
2010-05-23T19:15:19Z
2,893,077
10
2010-05-23T19:20:10Z
[ "python", "c", "http", "telnet" ]
i am having a very irritating problem, when i open a url ( <http://celebs.widewallpapers.net/md/a/adriana-lima/1440/Adriana-Lima-1440x900-002.jpg> ) in browser, it works fine.. but when i try to access it by telnet on bash, i get 404 not found!! my exact terminal: $ telnet celebs.widewallpapers.net 80 HEAD /md/a/adr...
You aren't passing a host header. As per HTTP/1.1 you need to tell the web server which virtual host you are expecting to talk to. And 99% of servers today will only talk HTTP/1.1 even if you specify HTTP/1.0 in the request. ``` jb@apto % telnet celebs.widewallpapers.net 80 ... HEAD /md/a/adriana-lima/1440/Adriana-Lim...
AppEngine BlobStore upload failing with a request that works in the Development Environment
2,893,268
5
2010-05-23T20:14:40Z
2,926,550
11
2010-05-28T03:53:23Z
[ "python", "google-app-engine" ]
I have an AppEngine application that uses the blobstore to store user-provided image data. When I upload images to that application from a form in Chrome it works fine. When I try to upload an image from an Android application it fails. Both methods work fine if I am running against the development server, but the Andr...
Turns out the problem was this line: ``` Content-Disposition: form-data; name="img";filename="PhotoHunt.jpg" ``` It should read like this: ``` Content-Disposition: form-data; name="img"; filename="PhotoHunt.jpg" ``` The parser for form-data on the production servers is more strict than the one in the development en...
Advice on translating code from very unrelated languages (in this case Scheme to Python)?
2,893,313
5
2010-05-23T20:29:44Z
2,893,338
7
2010-05-23T20:33:20Z
[ "python", "scheme", "code-translation" ]
Reasoning: I'm trying to convert a large library from Scheme to Python Are there any good strategies for doing this kind of conversion? Specifically cross-paradigm in this case since Python is more OO and Scheme is Functional. Totally subjective so I'm making it community wiki
I would treat the original language implementation almost like a requirements specification, and write up a design based on it (most importantly including detailed interface definitions, both for the external interfaces and for those between modules within the library). Then I would implement from that design. What I ...
Building a balanced binary search tree
2,893,318
9
2010-05-23T20:30:45Z
2,893,354
7
2010-05-23T20:37:08Z
[ "c#", "python", "binary-tree" ]
Is there a method to build a balanced binary search tree? Example: ``` 1 2 3 4 5 6 7 8 9 5 / \ 3 etc / \ 2 4 / 1 ``` I'm thinking there is a method to do this, without using the more complex self-balancing trees. Otherwise I can do it on my own, but someone probably have done this al...
For each subtree: * Find the middle element of the subtree and put that at the top of the tree. * Find all the elements before the middle element and use this algorithm recursively to get the left subtree. * Find all the elements after the middle element and use this algorithm recursively to get the right subtree. If...
How can I order fields in Django ModelForm?
2,893,471
27
2010-05-23T21:11:19Z
2,925,366
45
2010-05-27T22:09:19Z
[ "python", "django-forms", "order" ]
I have an 'order' Model: ``` class Order(models.Model): date_time=models.DateTimeField() # other stuff ``` And I'm using Django ModelForm class to render a form, but I want to display date and time widgets separately. I've came up with this: ``` class Form(forms.ModelForm): class Meta: model =...
You can use fields = [ ..., 'date', 'time', ... ] on Meta class of your form. See: <http://docs.djangoproject.com/en/dev/topics/forms/modelforms/#changing-the-order-of-fields>
Printing to STDOUT and log file while removing ANSI color codes
2,893,650
6
2010-05-23T22:00:24Z
2,893,767
8
2010-05-23T22:33:05Z
[ "python", "logging", "stdout", "ansi-colors" ]
I have the following functions for colorizing my screen messages: ``` def error(string): return '\033[31;1m' + string + '\033[0m' def standout(string): return '\033[34;1m' + string + '\033[0m' ``` I use them as follows: ``` print error('There was a problem with the program') print "This is normal " + stando...
The `sys.stdout.isatty` function might be able to help: ``` from sys import stdout def error(string, is_tty=stdout.isatty()): return ('\033[31;1m' + string + '\033[0m') if is_tty else string def standout(string, is_tty=stdout.isatty()): return ('\033[34;1m' + string + '\033[0m') if is_tty else string ``` Th...
Where to use a pyc file
2,893,686
10
2010-05-23T22:09:10Z
2,893,714
9
2010-05-23T22:16:18Z
[ "python" ]
I want to know what a pyc file(python bytecode) is. I want to know all the details. I want to know about how pyc files interface with the compiler. Is it a replacement for exe? Does it need to be run by python? Is it as portable as the .py file is? Where should I use this?
Python bytecode requires Python to run, cannot be ran standalone without Python, and is specific to a particular `x.y` release of Python. It should be portable across platforms for the same version. There is not a common reason for you to use it; Python uses it to optimize out parsing of your .py file on repeated impor...
Where to use a pyc file
2,893,686
10
2010-05-23T22:09:10Z
2,893,739
14
2010-05-23T22:22:32Z
[ "python" ]
I want to know what a pyc file(python bytecode) is. I want to know all the details. I want to know about how pyc files interface with the compiler. Is it a replacement for exe? Does it need to be run by python? Is it as portable as the .py file is? Where should I use this?
To supplement Mike Graham's answer there are some interesting comments [here](http://www.network-theory.co.uk/docs/pytut/CompiledPythonfiles.html) giving some information on pyc files. Most interestingly I suspect for you is the line: > A program doesn't run any faster when it is read from a ‘.pyc’ or ‘.pyo’ f...
for x in y, type iteration in python. Can I find out what iteration I'm currently on?
2,894,323
8
2010-05-24T01:34:05Z
2,894,326
21
2010-05-24T01:34:56Z
[ "python", "iteration" ]
I have a question about the loop construct in Python in the form of: `for x in y:` In my case y is a line read from a file and x is separate characters. I would like to put a space after every pair of characters in the output, like this: `aa bb cc dd` etc. So, I would like to know the current iteration. Is it possible,...
``` for i,x in enumerate(y): .... ```
send activate-email with django-registration
2,894,802
6
2010-05-24T04:53:08Z
2,905,763
9
2010-05-25T14:48:43Z
[ "python", "django", "django-registration" ]
I am curious if there's a way to send activated email with username, password by using django-registration. First I thought about modifying registration form but I need some example.
[django-registration](https://bitbucket.org/ubernostrum/django-registration/) uses the following code, internally, to handle sending emails: ``` send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, [self.user.email]) ``` If you want to work, you will have to specify the value DEFAULT\_FROM\_EMAIL in your settings...
Check for a valid domain name in a string?
2,894,902
4
2010-05-24T05:23:08Z
2,894,918
8
2010-05-24T05:27:31Z
[ "python", "regex", "api", "domain-name" ]
I am using python and would like a simple api or regex to check for a domain name's validity. By validity I am the syntactical validity and not whether the domain name actually exists on the Internet or not.
Any domain name is (syntactically) valid if it's a dot-separated list of identifiers, each no longer than 63 characters, and made up of letters, digits and dashes (no underscores). So: ``` r'[a-zA-Z\d-]{,63}(\.[a-zA-Z\d-]{,63})*' ``` would be a start. Of course, these days some non-Ascii characters may be allowed (a...
which inotify event signals the completion of a large file operation?
2,895,187
3
2010-05-24T06:36:06Z
2,895,230
9
2010-05-24T06:45:11Z
[ "python", "inotify", "pyinotify" ]
for large files or slow connections, copying files may take some time. using pyinotify, i have been watching for the IN\_CREATE event code. but this seems to occur at the *start* of a file transfer. i need to know when a file is completely copied - it aint much use if it's only half there. when a file transfer is *fi...
`IN_CLOSE` *probably* means the write is complete. This isn't for sure since some applications are bad actors and open and close files constantly while working with them, but if you know the app you're dealing with (file transfer, etc.) and understand its' behaviour, you're probably fine. (Note, this doesn't mean the t...
Python del() built-in can't be used in assignment?
2,895,629
5
2010-05-24T08:12:22Z
2,895,655
8
2010-05-24T08:17:52Z
[ "python", "built-in" ]
I noticed a problem when I was trying to use del in a lambda to thin out a list of threads to just those running: ``` map(lambda x: del(x) if not x.isAlive() else x, self.threads) ``` Ignore for a second that this doesn't do anything, I'm just fooling around with map, reduce, and lambda. This fails with a syntax err...
The limitation is that [`del` is a *statement*](http://docs.python.org/reference/simple_stmts.html#the-del-statement) and not an *expression*. It doesn't "return a value" because statements don't return values in Python. The `lambda` form only allows you to mention expressions (because there is an implicit `return` be...
Python del() built-in can't be used in assignment?
2,895,629
5
2010-05-24T08:12:22Z
2,895,677
9
2010-05-24T08:24:23Z
[ "python", "built-in" ]
I noticed a problem when I was trying to use del in a lambda to thin out a list of threads to just those running: ``` map(lambda x: del(x) if not x.isAlive() else x, self.threads) ``` Ignore for a second that this doesn't do anything, I'm just fooling around with map, reduce, and lambda. This fails with a syntax err...
Two problems. The first one is more subtle so I'll explain that first. The issue is that del removes a variable binding. Passing it a value will not serve your purpose. Here's an illustration ``` >>> a = 5 >>> del(a) >>> a Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'a' i...
How to calculate cointegrations of two lists?
2,895,992
7
2010-05-24T09:39:09Z
2,896,371
7
2010-05-24T10:53:17Z
[ "python", "statistics", "scipy" ]
Thank you in advance for your help! I have two lists with some stocks prices, example: ``` a = [10.23, 11.65, 12.36, 12.96] b = [5.23, 6.10, 8.3, 4.98] ``` I can calculate the **correlation** of these two lists, with: ``` import scipy.stats scipy.stats.pearsonr(a, b)[0] ``` But, I didn't found a method to calcul...
I don't believe a cointegration test has been implemented for scipy. You may be better off [using `rpy2`](http://rpy.sourceforge.net/rpy2.html) to interface Python with R. R provides cointegration tests in the [`urca` package](http://cran.r-project.org/web/packages/urca/index.html). For example: ``` import rpy2.robje...
Fitting a gamma distribution with (python) Scipy
2,896,179
14
2010-05-24T10:18:19Z
2,896,284
27
2010-05-24T10:38:29Z
[ "python", "scipy", "distribution", "gamma-distribution" ]
Can anyone help me out in fitting a gamma distribution in python? Well, I've got some data : X and Y coordinates, and I want to find the gamma parameters that fit this distribution... In the [Scipy doc](http://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.gamma.html#scipy.stats.gamma), it turns out that a fi...
Generate some gamma data: ``` import scipy.stats as stats alpha = 5 loc = 100.5 beta = 22 data = stats.gamma.rvs(alpha, loc=loc, scale=beta, size=10000) print(data) # [ 202.36035683 297.23906376 249.53831795 ..., 271.85204096 180.75026301 # 364.60240242] ``` Here we fit the data to the gamma distributio...
How to prevent my site page to be loaded via 3rd party site frame of iFrame
2,896,623
54
2010-05-24T11:32:53Z
2,896,705
70
2010-05-24T11:46:30Z
[ "php", "python", "iframe", "http-headers", "frame" ]
How can I find out that my page is embedded as a frame to other site during page loading? I guess referrer request header can't help me here? Thanks.
You cannot check it from the server's side, but you can use javascript to detect it after the page has loaded. Compare `top` and `self`, if they're not identical, you are in a frame. Additionally, some modern browsers respect the `X-FRAME-OPTIONS` header, that can have two values: * DENY – prevents the page from be...
How to prevent my site page to be loaded via 3rd party site frame of iFrame
2,896,623
54
2010-05-24T11:32:53Z
2,896,882
29
2010-05-24T12:17:04Z
[ "php", "python", "iframe", "http-headers", "frame" ]
How can I find out that my page is embedded as a frame to other site during page loading? I guess referrer request header can't help me here? Thanks.
Stackoverflow includes some JS to test it (`master.js`). This is the relevant part of it: ``` if(top!=self){ top.location.replace(document.location); alert("For security reasons, framing is not allowed; click OK to remove the frames.") } ``` But keep in mind that JS can be disabled.
How to prevent my site page to be loaded via 3rd party site frame of iFrame
2,896,623
54
2010-05-24T11:32:53Z
20,493,279
7
2013-12-10T11:28:53Z
[ "php", "python", "iframe", "http-headers", "frame" ]
How can I find out that my page is embedded as a frame to other site during page loading? I guess referrer request header can't help me here? Thanks.
you can prevent loading you page in an iframe with javascript ``` <script type="text/javascript"> if ( window.self !== window.top ) { window.top.location.href=window.location.href; } </script> ``` this code change address of container of your page's iframe to your page address and force container to show your pag...
How to prevent my site page to be loaded via 3rd party site frame of iFrame
2,896,623
54
2010-05-24T11:32:53Z
25,353,933
13
2014-08-17T21:44:50Z
[ "php", "python", "iframe", "http-headers", "frame" ]
How can I find out that my page is embedded as a frame to other site during page loading? I guess referrer request header can't help me here? Thanks.
For [modern browsers](http://caniuse.com/contentsecuritypolicy "CSP browser support"), you can use CSP (Content Security Policy), which is a standard. The following header will prevent the document from loading in a frame anywhere: ``` Content-Security-Policy: frame-ancestors 'none' ``` (IE 11 needs the `X-` prefix, ...
Removing Item From List - during iteration - what's wrong with this idiom?
2,896,752
13
2010-05-24T11:54:40Z
2,896,797
7
2010-05-24T12:01:30Z
[ "python", "list", "loops" ]
As an experiment, I did this: ``` letters=['a','b','c','d','e','f','g','h','i','j','k','l'] for i in letters: letters.remove(i) print letters ``` The last print shows that not all items were removed ? (every other was). ``` IDLE 2.6.2 >>> ================================ RESTART ===========================...
You cannot iterate over a list and mutate it at the same time, instead iterate over a slice: ``` letters=['a','b','c','d','e','f','g','h','i','j','k','l'] for i in letters[:]: # note the [:] creates a slice letters.remove(i) print letters ``` That said, for a simple operation such as this, you should simply use:...
Removing Item From List - during iteration - what's wrong with this idiom?
2,896,752
13
2010-05-24T11:54:40Z
2,897,058
24
2010-05-24T12:48:50Z
[ "python", "list", "loops" ]
As an experiment, I did this: ``` letters=['a','b','c','d','e','f','g','h','i','j','k','l'] for i in letters: letters.remove(i) print letters ``` The last print shows that not all items were removed ? (every other was). ``` IDLE 2.6.2 >>> ================================ RESTART ===========================...
Some answers explain why this happens and some explain what you should've done. I'll shamelessly put the pieces together. --- ### What's the reason for this? Because the Python language is designed to handle this use case differently. [The documentation makes it clear:](http://docs.python.org/tutorial/controlflow.ht...
How can I unit test django messages?
2,897,609
47
2010-05-24T14:15:05Z
4,934,325
16
2011-02-08T14:35:57Z
[ "python", "django", "unit-testing", "django-testing" ]
In my django application, I'm trying to write a unit test that performs an action and then checks the messages in the response. As far as I can tell, there is no nice way of doing this. I'm using the CookieStorage storage method, and I'd like to do something similar to the following: ``` response = self.client.p...
This works for me (displays all messages): ``` print [m.message for m in list(response.context['messages'])] ``` Also here are a couple of utility methods I have in a test class inherited from Django's TestCase. If you'd prefer to have them as functions, remove the `self` arguments and replace `self.fail()`'s with a ...
How can I unit test django messages?
2,897,609
47
2010-05-24T14:15:05Z
14,909,727
26
2013-02-16T11:26:03Z
[ "python", "django", "unit-testing", "django-testing" ]
In my django application, I'm trying to write a unit test that performs an action and then checks the messages in the response. As far as I can tell, there is no nice way of doing this. I'm using the CookieStorage storage method, and I'd like to do something similar to the following: ``` response = self.client.p...
I found a really easy approach: ``` r = self.client.post('/foo/') m = list(r.context['messages']) self.assertEqual(len(m), 1) self.assertEqual(str(m[0]), 'my message') ``` (I use session based backend for messages)
Confusion Matrix with number of classified/misclassified instances on it (Python/Matplotlib)
2,897,826
8
2010-05-24T14:48:11Z
2,901,740
8
2010-05-25T03:10:34Z
[ "python", "matplotlib", "confusion-matrix" ]
I am plotting a confusion matrix with matplotlib with the following code: ``` from numpy import * import matplotlib.pyplot as plt from pylab import * conf_arr = [[33,2,0,0,0,0,0,0,0,1,3], [3,31,0,0,0,0,0,0,0,0,0], [0,4,41,0,0,0,0,0,0,0,1], [0,1,0,30,0,6,0,0,0,0,1], [0,0,0,0,38,10,0,0,0,0,0], [0,0,0,3,1,39,0,0,0,0,4],...
You can use [**text**](http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.text) to put arbitrary text in your plot. For example, inserting the following lines into your code will write the numbers (note the first and last lines are from your code to show you where to insert my lines): ``` res = ax...
Hashing in SHA512 using a salt? - Python
2,898,685
26
2010-05-24T16:58:28Z
2,898,780
46
2010-05-24T17:09:22Z
[ "python", "salt", "sha", "hashlib", "saltedhash" ]
I have been looking through ths hashlib documentation but haven't found anything talking about using **salt** when **hashing** data. Help would be great.
Samir's answer is correct but somewhat cryptic. Basically, the salt is just a randomly derived bit of data that you prefix or postfix your data with to dramatically increase the complexity of a dictionary attack on your hashed value. So given a salt `s` and data `d` you'd just do the following to generate a salted hash...
Hashing in SHA512 using a salt? - Python
2,898,685
26
2010-05-24T16:58:28Z
2,898,801
10
2010-05-24T17:11:44Z
[ "python", "salt", "sha", "hashlib", "saltedhash" ]
I have been looking through ths hashlib documentation but haven't found anything talking about using **salt** when **hashing** data. Help would be great.
Just add the salt to your sensitive data: ``` >>> import hashlib >>> m = hashlib.sha512() >>> m.update('salt') >>> m.update('sensitive data') >>> m.hexdigest() '70197a4d3a5cd29b62d4239007b1c5c3c0009d42d190308fd855fc459b107f40a03bd427cb6d87de18911f21ae9fdfc24dadb0163741559719669c7668d7d587' >>> n = hashlib.sha512() >>>...
Find value within a range in lookup table
2,899,129
3
2010-05-24T18:05:38Z
2,899,190
11
2010-05-24T18:14:44Z
[ "python", "table", "lookup" ]
I have the simplest problem to implement, but so far I have not been able to get my head around a solution in Python. I have built a table that looks similar to this one: ``` 501 - ASIA 1262 - EUROPE 3389 - LATAM 5409 - US ``` I will test a certain value to see if it falls within these ranges, `389 -> ASIA, 1300 -> ...
You could use the bisect module. Instead of linear search, that would use binary search, which would hopefully be faster: ``` import bisect places = [ (501, 'ASIA'), (1262, 'EUROPE'), (3389, 'LATAM'), (5409, 'US'), ] places.sort() # list must be sorted for to_find in (389, 1300, 5400): pos = bise...
Can I use python to create flash like browser games?
2,899,907
7
2010-05-24T20:03:26Z
3,322,826
10
2010-07-23T22:22:44Z
[ "python" ]
is it possible to use python to create flash like browser games? (Actually I want to use it for an economic simulation, but it amounts to the same as a browser game) Davoud
The answer would be yes, assuming you consider this a good example of what you want to do: <http://pyjs.org/examples/Space.html> This browser-based version of Asteroids was created using Pyjamas, which enables you to write the code in python in one place, and have it run either on the browser, or on the desktop: <ht...
changing file extension in python
2,900,035
12
2010-05-24T20:19:14Z
2,900,068
18
2010-05-24T20:23:44Z
[ "python", "cgi", "rename" ]
Suppose from index.py, i have post file #####.fasta to display file. I want to change ####.fasta file extension to ####.aln in display file. How can i do it? I am working right now on python cgi. Thanks for listening
[`os.path.splitext()`](http://docs.python.org/library/os.path.html#os.path.splitext), [`os.rename()`](http://docs.python.org/library/os.html#os.rename) for example: ``` # renamee is the file getting renamed, pre is the part of file name before extension and ext is current extension pre, ext = os.path.splitext(renamee...
changing file extension in python
2,900,035
12
2010-05-24T20:19:14Z
7,363,015
31
2011-09-09T14:14:59Z
[ "python", "cgi", "rename" ]
Suppose from index.py, i have post file #####.fasta to display file. I want to change ####.fasta file extension to ####.aln in display file. How can i do it? I am working right now on python cgi. Thanks for listening
``` import os thisFile = "mysequence.fasta" base = os.path.splitext(thisFile)[0] os.rename(thisFile, base + ".aln") ``` Where thisFile = the absolute path of the file you are changing
Django 1.2 Equivalent of QuerySet.query.as_sql()
2,900,057
10
2010-05-24T20:22:36Z
2,900,079
11
2010-05-24T20:25:26Z
[ "python", "django", "django-queryset" ]
In Django 1.1 I was able to produce the SQL used by a `QuerySet` with this notation: ``` QuerySet.query.as_sql() ``` In Django 1.2, this raises as `AttributeError`. Anyone know the Django 1.2 equivalent of that method? Thanks
In Django 1.1, `QuerySet.query` returned a `BaseQuery` object, now it returns a `Query` objects. The query object has a `__str__` method defined that returns the SQL.
Counting positive elements in a list with Python list comprehensions
2,900,084
21
2010-05-24T20:26:22Z
2,900,105
13
2010-05-24T20:30:08Z
[ "python", "list", "list-comprehension" ]
I have a list of integers and I need to count how many of them are > 0. I'm currently doing it with a list comprehension that looks like this: ``` sum([1 for x in frequencies if x > 0]) ``` It seems like a decent comprehension but I don't really like the "1"; it seems like a bit of a magic number. Is there a more P...
A slightly more Pythonic way would be to use a generator instead: ``` sum(1 for x in frequencies if x > 0) ``` This avoids generating the whole list before calling `sum()`.
Counting positive elements in a list with Python list comprehensions
2,900,084
21
2010-05-24T20:26:22Z
2,900,111
44
2010-05-24T20:30:45Z
[ "python", "list", "list-comprehension" ]
I have a list of integers and I need to count how many of them are > 0. I'm currently doing it with a list comprehension that looks like this: ``` sum([1 for x in frequencies if x > 0]) ``` It seems like a decent comprehension but I don't really like the "1"; it seems like a bit of a magic number. Is there a more P...
If you want to reduce the amount of memory, you can avoid generating a temporary list by using a generator: ``` sum(x > 0 for x in frequencies) ``` This works because `bool` is a subclass of `int`: ``` >>> isinstance(True,int) True ``` and `True`'s value is 1: ``` >>> True==1 True ``` However, as Joe Golton point...
The "correct" way to define an exception in Python without PyLint complaining
2,901,000
16
2010-05-24T23:17:46Z
2,901,111
23
2010-05-24T23:43:51Z
[ "python", "exception" ]
I'm trying to define my own (very simple) exception class in Python 2.6, but no matter how I do it I get some warning. First, the simplest way: ``` class MyException(Exception): pass ``` This works, but prints out a warning at runtime: [DeprecationWarning: BaseException.message has been deprecated as of Python 2...
When you call `super`, you need the subclass/derived class as the first argument, not the main/base class. From the Python online documentation: ``` class C(B): def method(self, arg): super(C, self).method(arg) ``` So your exception would be defined as follows: ``` class MyException(Exception): def ...
Temporary PYTHONPATH in Windows
2,901,404
4
2010-05-25T01:17:17Z
2,901,456
7
2010-05-25T01:36:29Z
[ "python", "windows", "command-line" ]
How do I set, temporarily, the PYTHONPATH environment variable just before executing a Python script? In \*nix, I can do this: ``` $ PYTHONPATH='.' python scripts/doit.py ``` In Windows, this syntax does not work, of course. What is the equivalent, though?
To set and restore an environment variable on Windows' command line requires an unfortunately "somewhat torturous" approach...: ``` SET SAVE=%PYTHONPATH% SET PYTHONPATH=. python scripts/doit.py SET PYTHONPATH=%SAVE% ``` You could use a little auxiliary Python script to make it less painful, e.g. ``` import os import...
Integer array in Python
2,901,847
3
2010-05-25T03:39:35Z
2,901,892
11
2010-05-25T03:52:29Z
[ "python" ]
How I can define array of integer numbers in Python code Say if this code is ok. or no ``` pos = [int] len = 99 for i in range (0,99): pos[i]=7 ```
Why not just: ``` pos = [7] * 99 ``` This is the most pythonic, in my opinion.
django sync db question
2,902,800
2
2010-05-25T07:34:17Z
2,902,836
7
2010-05-25T07:40:33Z
[ "python", "django", "django-models" ]
In django models say this model exist in details/models.py ``` class OccDetails(models.Model): title = models.CharField(max_length = 255) occ = models.ForeignKey(Occ) ``` So when sync db is made the following fields get created and later to this of two more fields are added and sync db is made the ...
> [syncdb](http://docs.djangoproject.com/en/dev/ref/django-admin/#syncdb) creates the database tables for all apps in INSTALLED\_APPS whose tables have not already been created. > > **Syncdb will not alter existing tables** > `syncdb` will only create tables for models which have not yet been installed. It will never...
Internationalizing a Python 2.6 application via Babel
2,903,232
7
2010-05-25T08:55:48Z
2,903,728
7
2010-05-25T10:16:46Z
[ "python", "internationalization", "translation", "gettext", "babel" ]
We're evaluating Babel 0.9.5 [1] under Windows for use with Python 2.6 and have the following questions that we we've been unable to answer through reading the documentation or googling. 1) I would like to use an \_ like abbreviation for ungettext. Is there a concencus on whether one should use n\_ or N\_ for this? n...
By default `pybabel extract` recognizes the following keywords: `_`, `gettext`, `ngettext`, `ugettext`, `ungettext`, `dgettext`, `dngettext`,`N_`. Use [`-k` option](http://babel.edgewall.org/wiki/Documentation/0.9/cmdline.html#extract) to add others. `N_` is often used for [NULL-translations](http://docs.python.org/lib...
Why are Python exceptions named "Error"?
2,903,827
43
2010-05-25T10:36:40Z
2,903,946
52
2010-05-25T10:58:28Z
[ "java", "python", "exception" ]
Why are Python exceptions named "Error" (e.g. `ZeroDivisionError`, `NameError`, `TypeError`) and not "Exception" (e.g. `ZeroDivisionException`, `NameException`, `TypeException`). I come from a Java background and started to learn Python recently, as such this is confusing because in Java there is a distinction between...
1. You don't name each class with 'Class' in name and each variable with '\_variable' in name. The same name you don't name exception using the word 'Exception'. The name should tell something about the meaning of the object. 'Error' is the meaning of most of the exceptions. 2. Not all Exceptions are Errors. `SystemExi...
Why are Python exceptions named "Error"?
2,903,827
43
2010-05-25T10:36:40Z
2,903,973
7
2010-05-25T11:04:02Z
[ "java", "python", "exception" ]
Why are Python exceptions named "Error" (e.g. `ZeroDivisionError`, `NameError`, `TypeError`) and not "Exception" (e.g. `ZeroDivisionException`, `NameException`, `TypeException`). I come from a Java background and started to learn Python recently, as such this is confusing because in Java there is a distinction between...
Python is fairly similar to Java in this respect. But Python's Exception should be compared to Java's Throwable. As Throwables come in all kinds of flavors - Error, RuntimeException and (checked) Exception - so do Python's (though no checked exceptions). As for the language, an Error is exceptional, so that inheritan...
Why are Python exceptions named "Error"?
2,903,827
43
2010-05-25T10:36:40Z
2,906,861
29
2010-05-25T17:20:42Z
[ "java", "python", "exception" ]
Why are Python exceptions named "Error" (e.g. `ZeroDivisionError`, `NameError`, `TypeError`) and not "Exception" (e.g. `ZeroDivisionException`, `NameException`, `TypeException`). I come from a Java background and started to learn Python recently, as such this is confusing because in Java there is a distinction between...
I believe this convention comes from [PEP 8 - Style Guide for Python Code](https://www.python.org/dev/peps/pep-0008/#exception-names): > ### Exception Names > > Because exceptions should be classes, the class naming convention > applies here. However, you should use the suffix "Error" on your > exception names (if the...
First parameter of os.exec*
2,904,171
5
2010-05-25T11:41:51Z
2,904,263
11
2010-05-25T11:52:58Z
[ "python", "exec", "command-line-arguments" ]
From the python docs: > The various exec\*() functions take a > list of arguments for the new program > loaded into the process. In each case, > the first of these arguments is passed > to the new program as its own name > rather than as an argument a user may > have typed on a command line. For the > C programmer, th...
UNIX, where all these `exec` things come from, separated the program executable file from the program name, so that your process could have any arbitrary name. The first argument is the *program* that will run. This must exist. The next argument is what your process running the program will be *called,* what will be i...
globals and locals in python exec()
2,904,274
29
2010-05-25T11:54:21Z
2,906,198
15
2010-05-25T15:41:46Z
[ "python", "scope" ]
I'm trying to run a piece of python code using exec. ``` my_code = """ class A(object): pass print 'locals: %s' % locals() print 'A: %s' % A class B(object): a_ref = A """ global_env = {} local_env = {} my_code_AST = compile(my_code, "My Code", "exec") exec(my_code_AST, global_env, local_env) print local_env `...
Well, I believe it's either an implementation bug or an undocumented design decision. The crux of the issue is that a name-binding operation in the module-scope should bind to a global variable. The way it is achieved is that when in the module level, globals() IS locals() (try that one out in the interpreter), so when...
What the heck kind of timestamp is this: 1267488000000
2,904,847
5
2010-05-25T13:05:25Z
2,904,872
15
2010-05-25T13:08:01Z
[ "python", "datetime" ]
And how do I convert it to a datetime.datetime instance in python? It's the output from the New York State Senate's API: <http://open.nysenate.gov/legislation/>.
It looks like Unix time, but with milliseconds instead of seconds? ``` >>> import time >>> time.gmtime(1267488000000 / 1000) time.struct_time(tm_year=2010, tm_mon=3, tm_mday=2, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=1, tm_yday=61, tm_isdst=0) ``` March 2nd, 2010? And if you want a `datetime` object: ``` >>> import ...
Perfom python unit tests via a web interface
2,904,997
7
2010-05-25T13:24:53Z
2,905,671
8
2010-05-25T14:40:06Z
[ "python", "unit-testing" ]
Is it possible to perform unittest tests via a web interface...and if so how? **EDIT**: For now I want the results...for the tests I want them to be automated...possibly every time I make a change to the code. Sorry I forgot to make this more clear
EDIT: This answer is outdated at this point: * Use [Jenkins](http://jenkins-ci.org/) instead of Hudson (same thing, new name). * Use [django-jenkins](https://sites.google.com/site/kmmbvnr/home/django-jenkins-tutorial) instead of xmlrunner.py. The link to django-jenkins goes to a nice tutorial on how to use Jenkins w...
Emacs: pass arguments to inferior Python shell during buffer evaluation
2,905,575
6
2010-05-25T14:27:11Z
2,906,371
7
2010-05-25T16:07:49Z
[ "python", "emacs", "ide" ]
recently I started using Emacs as a Python IDE, and it not quite intuitive... The problem I am struggling with right now is how to pass command line arguments to the inferior python shell when the buffer is evaluated with C-c C-c. Thanks for help.
This doesn't appear to be easily possible; the inferior process managed by the `python.el` module is designed to persist across many invocations of `python-send-buffer` (and friends). One solution I've found is to write your own function that sets `sys.argv` programmatically from within the inferior process: ``` (defu...
Creating Threads in python
2,905,965
59
2010-05-25T15:15:01Z
2,906,014
115
2010-05-25T15:20:56Z
[ "python", "multithreading" ]
I have a script and I want one function to run at the same time as the other. Example code I have looked at: ``` import threading def MyThread ( threading.thread ): doing something........ def MyThread2 ( threading.thread ): doing something........ MyThread().start() MyThread2().start() ``` I am having tro...
You don't need to use a subclass of `Thread` to make this work - take a look at the simple example I'm posting below to see how: ``` from threading import Thread from time import sleep def threaded_function(arg): for i in range(arg): print "running" sleep(1) if __name__ == "__main__": thread...
Creating Threads in python
2,905,965
59
2010-05-25T15:15:01Z
2,906,135
20
2010-05-25T15:35:30Z
[ "python", "multithreading" ]
I have a script and I want one function to run at the same time as the other. Example code I have looked at: ``` import threading def MyThread ( threading.thread ): doing something........ def MyThread2 ( threading.thread ): doing something........ MyThread().start() MyThread2().start() ``` I am having tro...
There are a few problems with your code: ``` def MyThread ( threading.thread ): ``` * You can't subclass with a function; only with a class * If you were going to use a subclass you'd want threading.Thread, not threading.thread If you really want to do this with only functions, you have two options: With threading:...
Converting a list to a string
2,906,092
26
2010-05-25T15:29:33Z
2,906,133
9
2010-05-25T15:35:19Z
[ "python" ]
I have extracted some data from a file and want to write it to a second file. But my program is returning the error: ``` sequence item 1: expected string, list found ``` This appears to be happening because `write()` wants a string but it is receiving a list. So, with respect to this code, how can I convert the list...
``` ''.join(buffer) ```
Converting a list to a string
2,906,092
26
2010-05-25T15:29:33Z
2,906,148
32
2010-05-25T15:36:37Z
[ "python" ]
I have extracted some data from a file and want to write it to a second file. But my program is returning the error: ``` sequence item 1: expected string, list found ``` This appears to be happening because `write()` wants a string but it is receiving a list. So, with respect to this code, how can I convert the list...
Try [`str.join`](http://docs.python.org/library/stdtypes.html#str.join): ``` file2.write(' '.join(buffer)) ``` Documentation says: > Return a string which is the concatenation of the strings in the iterable iterable. The separator between elements is the string providing this method.
What is the difference between "a is b" and "id(a) == id(b)" in Python?
2,906,177
27
2010-05-25T15:39:52Z
2,906,209
47
2010-05-25T15:44:42Z
[ "python", "identity" ]
The [`id()`](http://docs.python.org/library/functions.html#id) inbuilt function gives... > an integer (or long integer) which is guaranteed to be unique and constant for this object during its lifetime. The [`is`](http://docs.python.org/library/stdtypes.html#comparisons) operator, instead, gives... > object identity...
``` >>> b.test is a.test False >>> a.test is a.test False ``` Methods are created on-the-fly each time you look them up. The function object (which is always the same object) implements the [descriptor protocol](http://www.python.org/download/releases/2.2.3/descrintro/) and its `__get__` creates the bound method objec...
Why is Django testrunner not finding the tests I created?
2,906,285
3
2010-05-25T15:55:54Z
2,906,698
7
2010-05-25T16:55:03Z
[ "python", "django" ]
I had been trying to add tests to a project I'm working on. The tests are in forum/tests/ When I run manage.py test it doesn't find any of the tests I created, on the tests in Django 1.2 I started with all my tests in their own package but have simplified down to just being in my tests.py file. The current tests.py ...
As noted in the comment, Django 1.6 introduced backwards-incompatibility with **[discovery of tests in any test module](https://docs.djangoproject.com/en/dev/releases/1.6/#discovery-of-tests-in-any-test-module)**. Before Django 1.6, one would have to do the following: Create file named `__init__.py` in ``` forum/tes...
Embedding a scripting engine in C++
2,907,087
3
2010-05-25T17:47:35Z
2,907,217
7
2010-05-25T18:02:22Z
[ "javascript", "c++", "python", "scripting", "embedding" ]
I'm researching how to best extend a C++ application with scripting capability, and I am looking at either Python or JavaScript. User-defined scripts will need the ability to access the application's data model. Have any of you had experiences with embedding these scripting engines? What are some potential pitfalls?
Lua is also a great candidate for embedding in programs. Its very self contained, and even the native cross-language call system isn't bad. For JavaScript, your best bet right now is to look at V8 (from Google), which is easy enough to work with.
Python's Equivalent of "public static void main"
2,907,637
13
2010-05-25T19:00:56Z
2,907,655
21
2010-05-25T19:02:48Z
[ "java", "python" ]
What is Python's equivalent of "public static void main(String[] args) { ... }"? I remember having used it in the past and then forgot. What I'm basically trying to remember is a function which I think included some underscores (\_\_)... thx
``` #!/usr/bin/env python import sys def main(args): print args if __name__ == '__main__': main(sys.argv) ``` *edit*: emulate a `void` return.
Python's Equivalent of "public static void main"
2,907,637
13
2010-05-25T19:00:56Z
2,907,664
10
2010-05-25T19:03:32Z
[ "java", "python" ]
What is Python's equivalent of "public static void main(String[] args) { ... }"? I remember having used it in the past and then forgot. What I'm basically trying to remember is a function which I think included some underscores (\_\_)... thx
``` if __name__ == "__main__": ....do your thing ```
Python's Equivalent of "public static void main"
2,907,637
13
2010-05-25T19:00:56Z
2,908,674
9
2010-05-25T21:30:29Z
[ "java", "python" ]
What is Python's equivalent of "public static void main(String[] args) { ... }"? I remember having used it in the past and then forgot. What I'm basically trying to remember is a function which I think included some underscores (\_\_)... thx
This is a commonly-used idiom, but it is NOT equivalent to Java's `public static void main(String args[])`. *All* Python modules execute from top to bottom *all* statements at the module's scope. For most imported modules, these statements are usually limited to class and method definitions, which set up values in the ...