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
How can I create a key using RSA/ECB/PKCS1Padding in python?
2,855,326
2
2010-05-18T07:44:23Z
2,856,628
7
2010-05-18T11:11:26Z
[ "python", "encryption", "rsa" ]
I am struggling to find any method of using RSA in ECB mode with PKCS1 padding in python. I've looked into pyCrypto, but they don't have PKCS1 padding in the master branch (but do in a patch). Nevertheless I found RSA with PKCS1 in the M2Crypto package, but I'm not sure if I can choose ECB mode...
Chaining mode such as ECB makes no sense for RSA, unless you are doing it wrong. ECB is for block ciphers: the input data is split into equal-size blocks, and each block is encrypted separately. This induces some weaknesses so ECB mode is best avoided for block ciphers. RSA is not a block cipher. In particular, RSA n...
ropemacs USAGE tutorial
2,855,378
79
2010-05-18T07:52:19Z
2,855,895
63
2010-05-18T09:21:00Z
[ "python", "emacs", "ide", "autocomplete" ]
There are many sites with instructions on *installing* ropemacs, but so far I couldn't find any with instructions on how to *use* it after it's already installed. I have it installed, or at least it seems so, Emacs has "Rope" menu in it's top menu bar. Now what? So far I could use only "Show documentation" (C-c d by de...
Well, you first need to select your project root folder. Quite simply, this is the folder at the top level of your project, or the current folder if you're dealing with a single file. Once you've selected the root folder, then other options will work, such as code assist, showing documentation, jumping to other symbols...
ropemacs USAGE tutorial
2,855,378
79
2010-05-18T07:52:19Z
2,858,148
10
2010-05-18T14:27:12Z
[ "python", "emacs", "ide", "autocomplete" ]
There are many sites with instructions on *installing* ropemacs, but so far I couldn't find any with instructions on how to *use* it after it's already installed. I have it installed, or at least it seems so, Emacs has "Rope" menu in it's top menu bar. Now what? So far I could use only "Show documentation" (C-c d by de...
You can set the root folder with `rope-open-project` . Once you've set the root project a `.ropeproject` dir will be created. Inside it, a config.py file has hooks where you can run (python) code once the project is set. The `project_opened(project):` function is a good place to run code. I usually activate the virtua...
ropemacs USAGE tutorial
2,855,378
79
2010-05-18T07:52:19Z
3,866,199
13
2010-10-05T17:38:43Z
[ "python", "emacs", "ide", "autocomplete" ]
There are many sites with instructions on *installing* ropemacs, but so far I couldn't find any with instructions on how to *use* it after it's already installed. I have it installed, or at least it seems so, Emacs has "Rope" menu in it's top menu bar. Now what? So far I could use only "Show documentation" (C-c d by de...
The best usage information I've found is a readme in the ropemacs source, here: <https://github.com/python-rope/ropemacs>
Show escaped string as Unicode in Python
2,855,661
9
2010-05-18T08:37:04Z
2,858,469
8
2010-05-18T15:01:51Z
[ "python", "unicode", "escaping" ]
i have just known Python for few days. Unicode seems to be a problem with Python. i have a text file stores a text string like this ``` '\u0110\xe8n \u0111\u1ecf n\xfat giao th\xf4ng Ng\xe3 t\u01b0 L\xe1ng H\u1ea1' ``` i can read the file and print the string out but it displays incorrectly. How can i print it out t...
``` >>> x=r'\u0110\xe8n \u0111\u1ecf n\xfat giao th\xf4ng Ng\xe3 t\u01b0 L\xe1ng H\u1ea1' >>> u=unicode(x, 'unicode-escape') >>> print u Đèn đỏ nút giao thông Ngã tư Láng Hạ ``` This works in a Mac, where Terminal.App correctly makes `sys.stdout.encoding` be set to `utf-8`. If your platform doesn't set tha...
How does Python's website generate its online documentation?
2,856,847
10
2010-05-18T11:41:41Z
2,857,216
9
2010-05-18T12:30:30Z
[ "python", "directory", "python-sphinx", "restructuredtext" ]
> Created using Sphinx 0.6.5. I know Python's documentation uses `reStructuredText`, but it has different sections like `http://docs.python.org/whatsnew/2.6.html` and `http://docs.python.org/tutorial/index.html`. How do you do this in reStructuredText? Do you run `rst2html` in a bunch of directories, keeping its stru...
The Python documentation uses reST for its *markup*, but it generates the HTML using `sphinx`, not `rst2html` directly. The `sphinx` tool is what converts all the individual `.rst` files into multiple `.html` files. To see how the Python docs are generated, see <http://svn.python.org/projects/python/trunk/Doc/Makefile>
How can I create a GUI on top of a Python APP so it can do either GUI or CLI?
2,857,634
2
2010-05-18T13:24:38Z
2,857,700
10
2010-05-18T13:33:54Z
[ "python", "xml", "user-interface", "gtk", "glade" ]
I am trying to write an app in python to control a motor using serial. This all works in a CLI situation fine and is generally stable. but I was wondering how simple it was to add a GUI on top of this code base? I assume there will be more code, but is there a simple way of detecting something like GTK, so it only app...
> is there a simple way of detecting something like GTK, so it only applied the code when GTK was present? First, break your app into 3 separate modules. 1. The actual work: `foo_core.py`. 2. A CLI module that imports `foo_core`. Call it `foo_cli.py`. 3. A GUI module that imports `foo_core`. Call it `foo_gui.pyw`. T...
Why does the "is" keyword have a different behavior when there is a dot in the string?
2,858,603
56
2010-05-18T15:18:56Z
2,858,669
87
2010-05-18T15:26:49Z
[ "python", "identity", "equality" ]
Consider this code: ``` >>> x = "google" >>> x is "google" True >>> x = "google.com" >>> x is "google.com" False >>> ``` Why is it like that? To make sure the above is correct, I have just tested on Python 2.5.4, 2.6.5, 2.7b2, Python 3.1 on windows and Python 2.7b1 on Linux. It looks like there is consistency acros...
`is` verifies object identity, and any implementation of Python, when it meets literal of immutable types, is perfectly free to *either* make a new object of that immutable type, *or* seek through existing objects of that type to see if some of them could be reused (by adding a new reference to the same underlying obje...
Why does the "is" keyword have a different behavior when there is a dot in the string?
2,858,603
56
2010-05-18T15:18:56Z
2,858,680
15
2010-05-18T15:27:59Z
[ "python", "identity", "equality" ]
Consider this code: ``` >>> x = "google" >>> x is "google" True >>> x = "google.com" >>> x is "google.com" False >>> ``` Why is it like that? To make sure the above is correct, I have just tested on Python 2.5.4, 2.6.5, 2.7b2, Python 3.1 on windows and Python 2.7b1 on Linux. It looks like there is consistency acros...
"is" is an identity test. Python has some caching behavior for small integers and (apparently) strings. "is" is best used for singleton testing (ex. `None`). ``` >>> x = "google" >>> x is "google" True >>> id(x) 32553984L >>> id("google") 32553984L >>> x = "google.com" >>> x is "google.com" False >>> id(x) 32649320L >...
python: equivalent to Javascript "||" to override non-truthful value
2,858,723
4
2010-05-18T15:33:16Z
2,858,752
10
2010-05-18T15:37:00Z
[ "python" ]
In Javascript I can do this: ``` function A(x) { return x || 3; } ``` This returns 3 if x is a "non-truthful" value like 0, null, false, and it returns x otherwise. This is useful for empty arguments, e.g. I can do `A()` and it will evaluate as 3. Does Python have an equivalent? I guess I could make one out of the t...
You can use `or` to do the same thing but you have to be careful because some unexpected things can be considered `False` in that arrangement. Just make sure you want this behavior if you choose to do it that way: ``` >>> "" or 1 1 >>> " " or 1 ' ' >>> 0 or 1 1 >>> 10 or 1 10 >>> ['a', 'b', 'c'] or 1 ['a', 'b', 'c'] >...
Execute a BASH command in Python-- in the same process
2,858,920
3
2010-05-18T15:57:43Z
2,859,098
10
2010-05-18T16:20:32Z
[ "python", "bash", "db2", "subprocess" ]
I need to execute the command `. /home/db2v95/sqllib/db2profile` before I can `import ibm_db_dbi` in Python 2.6. Executing it before I enter Python works: ``` baldurb@gigur:~$ . /home/db2v95/sqllib/db2profile baldurb@gigur:~$ python Python 2.6.4 (r264:75706, Dec 7 2009, 18:45:15) [GCC 4.4.1] on linux2 Type "help", ...
You are calling a '.' shell command. This command means 'execute this shell file in current process'. You cannot execute shell file in Python process as Python is not a shell script interpreter. The `/home/b2v95/sqllib/db2profile` probably sets some shell environment variables. If you read it using `system()` function...
Is multi-level polymorphism possible in SQLAlchemy?
2,859,339
6
2010-05-18T16:53:56Z
2,859,787
9
2010-05-18T18:06:35Z
[ "python", "sqlalchemy" ]
Is it possible to have multi-level polymorphism in SQLAlchemy? Here's an example: ``` class Entity(Base): __tablename__ = 'entities' id = Column(Integer, primary_key=True) created_at = Column(DateTime, default=datetime.utcnow, nullable=False) entity_type = Column(Unicode(20), nullable=False) __mapp...
[Yes](http://www.sqlalchemy.org/docs/reference/ext/declarative.html#inheritance-configuration). The problem with your code is that you're making Image a type of file, when you must aim for the head of the tree, making Image a type of Entity. Example: ``` from sqlalchemy import (Table, Column, Integer, String, create_...
converting python list of strings to their type
2,859,674
8
2010-05-18T17:47:12Z
2,859,689
19
2010-05-18T17:49:26Z
[ "python", "numpy", "scipy" ]
given a list of python strings, how can I automatically convert them to their correct type? Meaning, if I have: ``` ["hello", "3", "3.64", "-1"] ``` I'd like this to be converted to the list ``` ["hello", 3, 3.64, -1] ``` where the first element is a stirng, the second an int, the third a float and the fourth an in...
``` import ast L = ["hello", "3", "3.64", "-1"] def tryeval(val): try: val = ast.literal_eval(val) except ValueError: pass return val print [tryeval(x) for x in L] ```
converting python list of strings to their type
2,859,674
8
2010-05-18T17:47:12Z
2,859,738
7
2010-05-18T17:59:49Z
[ "python", "numpy", "scipy" ]
given a list of python strings, how can I automatically convert them to their correct type? Meaning, if I have: ``` ["hello", "3", "3.64", "-1"] ``` I'd like this to be converted to the list ``` ["hello", 3, 3.64, -1] ``` where the first element is a stirng, the second an int, the third a float and the fourth an in...
Without using evaluation: ``` def convert(val): constructors = [int, float, str] for c in constructors: try: return c(val) except ValueError: pass ```
Creating an interface and swappable implementations in python
2,860,106
7
2010-05-18T18:50:56Z
2,860,419
7
2010-05-18T19:29:00Z
[ "python", "oop" ]
Would it be possible to create a class interface in python and various implementations of the interface. Example: I want to create a class for pop3 access (and all methods etc.). If I go with a commercial component, I want to wrap it to adhere to a contract. In the future, if I want to use another component or code m...
For people coming from a strongly typed language background, Python does not need a class interface. You can simulate it using a base class. ``` class BaseAccess: def open(arg): raise NotImplementedError() class Pop3Access(BaseAccess): def open(arg): ... class AlternateAccess(BaseAccess): def open(arg)...
How do I get the parent directory in Python?
2,860,153
140
2010-05-18T18:55:41Z
2,860,174
8
2010-05-18T18:58:25Z
[ "python" ]
Could someone tell me how to get the parent directory of a path in Python in a cross platform way. E.g. ``` C:\Program Files ---> C:\ ``` and ``` C:\ ---> C:\ ``` If the directory doesn't have a parent directory, it returns the directory itself. The question might seem simple but I couldn't dig it up through Google...
``` os.path.abspath(os.path.join(somepath, '..')) ``` Observe: ``` import posixpath import ntpath print ntpath.abspath(ntpath.join('C:\\', '..')) print ntpath.abspath(ntpath.join('C:\\foo', '..')) print posixpath.abspath(posixpath.join('/', '..')) print posixpath.abspath(posixpath.join('/home', '..')) ```
How do I get the parent directory in Python?
2,860,153
140
2010-05-18T18:55:41Z
2,860,179
13
2010-05-18T18:58:46Z
[ "python" ]
Could someone tell me how to get the parent directory of a path in Python in a cross platform way. E.g. ``` C:\Program Files ---> C:\ ``` and ``` C:\ ---> C:\ ``` If the directory doesn't have a parent directory, it returns the directory itself. The question might seem simple but I couldn't dig it up through Google...
``` os.path.split(os.path.abspath(mydir))[0] ```
How do I get the parent directory in Python?
2,860,153
140
2010-05-18T18:55:41Z
2,860,193
174
2010-05-18T19:00:05Z
[ "python" ]
Could someone tell me how to get the parent directory of a path in Python in a cross platform way. E.g. ``` C:\Program Files ---> C:\ ``` and ``` C:\ ---> C:\ ``` If the directory doesn't have a parent directory, it returns the directory itself. The question might seem simple but I couldn't dig it up through Google...
Try this: ``` import os.path print os.path.abspath(os.path.join(yourpath, os.pardir)) ``` where `yourpath` is the path you want the parent for.
How do I get the parent directory in Python?
2,860,153
140
2010-05-18T18:55:41Z
2,860,200
10
2010-05-18T19:00:59Z
[ "python" ]
Could someone tell me how to get the parent directory of a path in Python in a cross platform way. E.g. ``` C:\Program Files ---> C:\ ``` and ``` C:\ ---> C:\ ``` If the directory doesn't have a parent directory, it returns the directory itself. The question might seem simple but I couldn't dig it up through Google...
``` import os p = os.path.abspath('..') ``` C:\Program Files ---> C:\\ C:\ ---> C:\\
How do I get the parent directory in Python?
2,860,153
140
2010-05-18T18:55:41Z
2,860,321
183
2010-05-18T19:14:32Z
[ "python" ]
Could someone tell me how to get the parent directory of a path in Python in a cross platform way. E.g. ``` C:\Program Files ---> C:\ ``` and ``` C:\ ---> C:\ ``` If the directory doesn't have a parent directory, it returns the directory itself. The question might seem simple but I couldn't dig it up through Google...
Using `os.path.dirname`: ``` >>> os.path.dirname(r'C:\Program Files') 'C:\\' >>> os.path.dirname('C:\\') 'C:\\' >>> ```
How do I get the parent directory in Python?
2,860,153
140
2010-05-18T18:55:41Z
29,137,365
28
2015-03-19T04:44:27Z
[ "python" ]
Could someone tell me how to get the parent directory of a path in Python in a cross platform way. E.g. ``` C:\Program Files ---> C:\ ``` and ``` C:\ ---> C:\ ``` If the directory doesn't have a parent directory, it returns the directory itself. The question might seem simple but I couldn't dig it up through Google...
In Python 3.4+ ``` from pathlib import Path Path('C:\Program Files').parent ``` [doc page](https://docs.python.org/3.4/library/pathlib.html#pathlib.PurePath.parent) --- **Additional Info** The new pathlib library brings together and simplifies using paths and common file operations. Here are some examples from the...
Can Python's set absence of ordering be considered random order?
2,860,339
12
2010-05-18T19:17:24Z
2,860,350
24
2010-05-18T19:19:24Z
[ "python", "random", "set", "order", "shuffle" ]
I'd like to know if the absence of element ordering of the Python's built-in `set` structure is "random enough". For instance, taking the iterator of a set, can it be considered a shuffled view of its elements? (If it matters, I'm running Python 2.6.5 on a Windows host.)
No, it is *not* random. It is "arbitrarily ordered", which means that you cannot depend on it being either ordered or random.
How to access __init__.py variables from deeper parts of a package
2,860,482
8
2010-05-18T19:36:27Z
2,860,631
12
2010-05-18T19:55:57Z
[ "python" ]
I apologize for yet another `__init__.py` question. I have the following package structure: ``` +contrib +--__init__.py | +database +--__init__.py | +--connection.py ``` In the top-level `__init__.py` I define: `USER='me'`. If I `import contrib` from the command line, then I can access `contr...
Adding `import contrib` to `connection.py` is the way to go. Yes, the `contrib` module is already imported (you can find out from `sys.modules`). The problem is there is no reference to the module from your code in connection.py. Doing another import will give you the reference. You do not need to worry about additiona...
Send HTML e-mail in App Engine / Python?
2,860,614
21
2010-05-18T19:54:15Z
2,860,958
43
2010-05-18T20:36:02Z
[ "python", "google-app-engine", "email" ]
Can you please give me a simple, and straightforward python example of sending an HTML e-mail using App Engine? Plaintext is straightforward, but I'm having difficulties with HTML tags.
I haven't tested this, so please forgive any little bugs. It's based on an example from the Google documentation: <http://code.google.com/appengine/docs/python/mail/sendingmail.html> ``` from google.appengine.api import mail message = mail.EmailMessage(sender="Example.com Support <support@example.com>", ...
Upgrade package without upgrading dependencies using pip?
2,861,183
25
2010-05-18T21:10:05Z
2,880,884
31
2010-05-21T09:22:29Z
[ "python", "virtualenv", "pip" ]
I'm using pip and virtualenv for my python application. I would like to upgrade to a new version of the application without touching the dependencies. When I use `pip install -U`, it tries to upgrade all the packages, and even uninstalls and re-installs the same version of a dependency package when there isn't a new ve...
I just tried on my virtualenv project and `pip install -U --no-deps mypackage` seems to work just fine. It just download mypackage and nothing else. What's your set up like?
How do I convert this Python punctuation-stripping function to JavaScript?
2,861,528
2
2010-05-18T22:13:42Z
2,861,540
12
2010-05-18T22:17:44Z
[ "javascript", "python" ]
Please can anyone translate this python code into javascript. ``` # def strip_punctuation(s): # for c in ',.":;!%$': # while s.find(c) is not -1: # s.replace(c, '') ```
``` function strip_punctuation(s) { return s.replace(/[,.":;!%$]/g, ""); } ```
How to determine subprocess.Popen() failed when shell=True
2,861,548
6
2010-05-18T22:19:12Z
2,861,589
13
2010-05-18T22:27:32Z
[ "python", "subprocess", "popen" ]
Windows version of Python 2.6.4: Is there any way to determine if subprocess.Popen() fails when using shell=True? Popen() successfully fails when shell=False ``` >>> import subprocess >>> p = subprocess.Popen( 'Nonsense.application', shell=False ) Traceback (most recent call last): File ">>> pyshell#258", line 1, i...
`returncode` will work, although it will be `None` until you've called `p.poll()`. [`poll()`](http://docs.python.org/library/subprocess.html#popen-objects) itself will return the error code, so you can just do ``` if a.poll() != 0: print ":(" ```
How do I subtract two dates in Django/Python?
2,861,770
26
2010-05-18T23:03:34Z
2,861,851
27
2010-05-18T23:19:37Z
[ "python", "django", "datetime", "date", "time" ]
I'm working on a little fitness tracker in order to teach myself Django. I want to graph my weight over time, so I've decided to use the Python Google Charts Wrapper. Google charts require that you convert your date into a x coordinate. To do this I want to take the number of days in my dataset by subtracting the first...
Django `datetime` objects are just regular [Python `datetime` objects](http://docs.python.org/library/datetime#datetime-objects). When you subtract one `datetime` from another you get a [`timedelta`](http://docs.python.org/library/datetime#timedelta-objects) object. If you are looking to subtract a length of time from...
How do I subtract two dates in Django/Python?
2,861,770
26
2010-05-18T23:03:34Z
2,861,860
43
2010-05-18T23:22:36Z
[ "python", "django", "datetime", "date", "time" ]
I'm working on a little fitness tracker in order to teach myself Django. I want to graph my weight over time, so I've decided to use the Python Google Charts Wrapper. Google charts require that you convert your date into a x coordinate. To do this I want to take the number of days in my dataset by subtracting the first...
You can just subtract the dates directly, which will yield a `datetime.timedelta` object: ``` dt = weight_now.weight_date - weight_then.weight_date ``` A `timedelta` object has fields for days, seconds, and microseconds. From there, you can just do the appropriate math. For example: ``` hours = dt.seconds / 60 / 60 ...
Queue remote calls to a Python Twisted perspective broker?
2,861,858
11
2010-05-18T23:22:21Z
2,862,440
28
2010-05-19T02:16:26Z
[ "python", "asynchronous", "twisted" ]
The strength of Twisted (for python) is its asynchronous framework (I think). I've written an image processing server that takes requests via Perspective Broker. It works great as long as I feed it less than a couple hundred images at a time. However, sometimes it gets spiked with hundreds of images at virtually the sa...
One ready-made option that might help with this is `twisted.internet.defer.DeferredSemaphore`. This is the asynchronous version of the normal (counting) semaphore you might already know if you've done much threaded programming. A (counting) semaphore is a lot like a mutex (a lock). But where a mutex can only be acquir...
How do I get the Math equation of Python Algorithm?
2,861,996
5
2010-05-18T23:58:07Z
2,861,998
15
2010-05-19T00:00:05Z
[ "python", "algorithm", "math" ]
ok so I am feeling a little stupid for not knowing this, but a coworker asked so I am asking here: I have written a python algorithm that solves his problem. given x > 0 add all numbers together from 1 to x. ``` def intsum(x): if x > 0: return x + intsum(x - 1) else: return 0 intsum(10) 55 ``` first what...
This is recursion, though for some reason you're labeling it like it's factorial. In any case, the sum from 1 to n is also simply: `n * ( n + 1 ) / 2` (You can special case it for negative values if you like.)
How do I get the Math equation of Python Algorithm?
2,861,996
5
2010-05-18T23:58:07Z
2,862,037
8
2010-05-19T00:09:38Z
[ "python", "algorithm", "math" ]
ok so I am feeling a little stupid for not knowing this, but a coworker asked so I am asking here: I have written a python algorithm that solves his problem. given x > 0 add all numbers together from 1 to x. ``` def intsum(x): if x > 0: return x + intsum(x - 1) else: return 0 intsum(10) 55 ``` first what...
Transforming recursively-defined sequences of integers into ones that can be expressed in a closed form is a fascinating part of discrete mathematics -- I heartily recommend **Concrete Mathematics: A Foundation for Computer Science**, by Ronald Graham, Donald Knuth, and Oren Patashnik (see. e.g. the [wikipedia](http://...
Python 2.6, 3 abstract base class misunderstanding
2,862,153
7
2010-05-19T00:46:08Z
2,862,419
14
2010-05-19T02:07:20Z
[ "python", "abstract-class" ]
I'm not seeing what I expect when I use ABCMeta and abstractmethod. This works fine in python3: ``` from abc import ABCMeta, abstractmethod class Super(metaclass=ABCMeta): @abstractmethod def method(self): pass a = Super() TypeError: Can't instantiate abstract class Super ... ``` And in 2.6: ``` c...
With `Super` build as in your working snippets, what you're calling when you do `Super()` is: ``` >>> Super.__init__ <slot wrapper '__init__' of 'object' objects> ``` If `Super` inherits from `list`, call it `Superlist`: ``` >>> Superlist.__init__ <slot wrapper '__init__' of 'list' objects> ``` Now, abstract base c...
Easiest way to rename a model using Django/South?
2,862,979
136
2010-05-19T05:02:33Z
2,899,145
128
2010-05-24T18:07:53Z
[ "python", "django", "model", "rename", "django-south" ]
I've been hunting for an answer to this on South's site, Google, and SO, but couldn't find a simple way to do this. I want to rename a Django model using South. Say you have the following: ``` class Foo(models.Model): name = models.CharField() class FooTwo(models.Model): name = models.CharField() foo = m...
To answer your first question, the simple model/table rename is pretty straightforward. Run the command: ``` ./manage.py schemamigration yourapp rename_foo_to_bar --empty ``` (Update 2: try `--auto` instead of `--empty` to avoid the warning below. Thanks to @KFB for the tip.) If you're using an older version of sout...
Easiest way to rename a model using Django/South?
2,862,979
136
2010-05-19T05:02:33Z
12,361,162
64
2012-09-11T00:21:58Z
[ "python", "django", "model", "rename", "django-south" ]
I've been hunting for an answer to this on South's site, Google, and SO, but couldn't find a simple way to do this. I want to rename a Django model using South. Say you have the following: ``` class Foo(models.Model): name = models.CharField() class FooTwo(models.Model): name = models.CharField() foo = m...
Make the changes in `models.py` and then run ``` ./manage.py schemamigration --auto myapp ``` When you inspect the migration file, you'll see that it deletes a table and creates a new one ``` class Migration(SchemaMigration): def forwards(self, orm): # Deleting model 'Foo' ...
Python: avoiding fraction simplification
2,863,270
3
2010-05-19T06:15:27Z
2,863,289
9
2010-05-19T06:19:30Z
[ "python", "music", "fractions" ]
I'm working on a music app' in Python and would like to use the fractions module to handle time signatures amongst other things. My problem is that fractions get simplified, i.e.: ``` >>> from fractions import Fraction >>> x = Fraction(4, 4) >>> x Fraction(1, 1) ``` However, it is important from a musical point of vi...
Yes: make a custom class for it. Musical time signatures are not fractions, so it doesn't make sense to represent them with a math class.
Creating self-referential tables with polymorphism in SQLALchemy
2,863,336
4
2010-05-19T06:31:09Z
2,863,398
9
2010-05-19T06:46:44Z
[ "python", "sqlalchemy" ]
I'm trying to create a db structure in which I have many types of content entities, of which one, a Comment, can be attached to any other. Consider the following: ``` from datetime import datetime from sqlalchemy import create_engine from sqlalchemy import Column, ForeignKey from sqlalchemy import Unicode, Integer, D...
Try to supplement your `Comment.__mapper_args__` to: ``` __mapper_args__ = { 'polymorphic_identity': 'comment', 'inherit_condition': (id == Entity.id), } ``` P.S. I haven't understand what you need `_idref` relationship for? If you want to use a comment somewhere where `Entity` is expected you could just pass...
Are classes in Python in different files?
2,864,366
9
2010-05-19T09:47:35Z
2,864,387
15
2010-05-19T09:50:19Z
[ "python", "class", "naming-conventions" ]
Much like Java (or php), I'm use to seperating the classes to files. Is it the same deal in Python? plus, how should I name the file? Lowercase like classname.py or the same like ClassName.py? Do I need to do something special if I want to create an object from this class or does the fact that it's in the same...
In Python, one file is called a [**module**](http://docs.python.org/tutorial/modules.html). A module can consist of **multiple** classes or functions. As Python is **not** an OO language only, it does not make sense do have a rule that says, one file should only contain one class. One file (module) should contain cla...
Common elements comparison between 2 lists
2,864,842
18
2010-05-19T10:57:01Z
2,864,863
42
2010-05-19T11:00:02Z
[ "python", "list" ]
``` def common_elements(list1, list2): """ Return a list containing the elements which are in both list1 and list2 >>> common_elements([1,2,3,4,5,6], [3,5,7,9]) [3, 5] >>> common_elements(['this','this','n','that'],['this','not','that','that']) ['this', 'that'] """ for element in list1:...
``` >>> list1 = [1,2,3,4,5,6] >>> list2 = [3, 5, 7, 9] >>> list(set(list1).intersection(list2)) [3, 5] ```
Common elements comparison between 2 lists
2,864,842
18
2010-05-19T10:57:01Z
2,864,867
8
2010-05-19T11:00:53Z
[ "python", "list" ]
``` def common_elements(list1, list2): """ Return a list containing the elements which are in both list1 and list2 >>> common_elements([1,2,3,4,5,6], [3,5,7,9]) [3, 5] >>> common_elements(['this','this','n','that'],['this','not','that','that']) ['this', 'that'] """ for element in list1:...
use set intersections, set(list1) & set(list2) ``` >>> def common_elements(list1, list2): ... return list(set(list1) & set(list2)) ... >>> >>> common_elements([1,2,3,4,5,6], [3,5,7,9]) [3, 5] >>> >>> common_elements(['this','this','n','that'],['this','not','that','that']) ['this', 'that'] >>> >>> ``` Note that re...
Common elements comparison between 2 lists
2,864,842
18
2010-05-19T10:57:01Z
2,865,033
14
2010-05-19T11:30:24Z
[ "python", "list" ]
``` def common_elements(list1, list2): """ Return a list containing the elements which are in both list1 and list2 >>> common_elements([1,2,3,4,5,6], [3,5,7,9]) [3, 5] >>> common_elements(['this','this','n','that'],['this','not','that','that']) ['this', 'that'] """ for element in list1:...
The solutions suggested by [S.Mark](http://stackoverflow.com/questions/2864842/common-elements-comparison-between-2-lists/2864867#2864867) and [SilentGhost](http://stackoverflow.com/questions/2864842/common-elements-comparison-between-2-lists/2864863#2864863) generally tell you how it should be done in a Pythonic way, ...
removing elements incrementally from a list
2,864,854
3
2010-05-19T10:59:16Z
2,864,906
9
2010-05-19T11:07:53Z
[ "python", "list" ]
I've a list of float numbers and I would like to delete incrementally a set of elements in a given range of indexes, sth. like: ``` for j in range(beginIndex, endIndex+1): print ("remove [%d] => val: %g" % (j, myList[j])) del myList[j] ``` However, since I'm iterating over the same list, the indexes (range) are...
Do you really need to remove them incrementaly? If not, you can do it like this: ``` del myList[beginIndex:endIndex+1] ```
In Python, how to find all the files under a directory, including the files in subdirectories?
2,865,278
3
2010-05-19T12:08:53Z
2,865,328
10
2010-05-19T12:15:53Z
[ "python", "list", "file" ]
Is there any built in functions to find all the files under a particular directory including files under subdirectories ? I have tried this code, but not working...may be the logic itself is wrong... ``` def fun(mydir): lis=glob.glob(mydir) length=len(lis) l,i=0,0 if len(lis): while(l+i<length)...
There is no built-in function, but using [`os.walk`](http://docs.python.org/library/os.html#os.walk) it's trivial to construct it: ``` import os def recursive_file_gen(mydir): for root, dirs, files in os.walk(mydir): for file in files: yield os.path.join(root, file) ``` **ETA**: the `os.walk` ...
How to unescape special characters from BeautifulSoup output?
2,865,295
4
2010-05-19T12:12:03Z
2,871,104
8
2010-05-20T04:55:58Z
[ "python", "utf-8", "character-encoding", "special-characters", "beautifulsoup" ]
I am facing issues with the special characters like ° and ® which represent the degree Fahrenheit sign and the registered sign, when i print the string the contains the special characters, it gives output like this: ``` Preheat oven to 350&deg; F Welcome to Lorem Ipsum Inc&reg; ``` Is there a way I can output the ex...
``` $ python -c'from BeautifulSoup import BeautifulSoup > print BeautifulSoup("""<html>Preheat oven to 350&deg; F > Welcome to Lorem Ipsum Inc&reg;""", > convertEntities=BeautifulSoup.HTML_ENTITIES).contents[0].string' Preheat oven to 350° F Welcome to Lorem Ipsum Inc® ```
How can I time a code segment for testing performance with Pythons timeit?
2,866,380
53
2010-05-19T14:24:46Z
2,866,456
89
2010-05-19T14:32:35Z
[ "python", "testing", "timeit", "database-tuning" ]
I've a python script which works just as it should but I need to write the time for the execution. I've googled that I should use [`timeit`](https://docs.python.org/2/library/timeit.html) but I can't seem to get it to work. My Python script looks like this: ``` import sys import getopt import timeit import random imp...
you can use time.time ot time.clock before and after the block you want to time ``` import time t0 = time.time() code_block t1 = time.time() total = t1-t0 ``` this method is not as exact as timeit (it does not average several runs) but it is straighforward. time.time() (in windows and linux) and time.clock(in linu...
How can I time a code segment for testing performance with Pythons timeit?
2,866,380
53
2010-05-19T14:24:46Z
2,866,460
23
2010-05-19T14:33:06Z
[ "python", "testing", "timeit", "database-tuning" ]
I've a python script which works just as it should but I need to write the time for the execution. I've googled that I should use [`timeit`](https://docs.python.org/2/library/timeit.html) but I can't seem to get it to work. My Python script looks like this: ``` import sys import getopt import timeit import random imp...
Quite apart from the timing, this code you show is simply incorrect: you execute 100 connections (completely ignoring all but the last one), and then when you do the first execute call you pass it a local variable `query_stmt` which you only initialize *after* the execute call. First, make your code correct, without w...
How can I time a code segment for testing performance with Pythons timeit?
2,866,380
53
2010-05-19T14:24:46Z
22,135,117
13
2014-03-02T23:26:59Z
[ "python", "testing", "timeit", "database-tuning" ]
I've a python script which works just as it should but I need to write the time for the execution. I've googled that I should use [`timeit`](https://docs.python.org/2/library/timeit.html) but I can't seem to get it to work. My Python script looks like this: ``` import sys import getopt import timeit import random imp...
If you are profiling your code and can use IPython, it has the magic function `%timeit`. `%%timeit` operates on cells. ``` In [2]: %timeit cos(3.14) 10000000 loops, best of 3: 160 ns per loop In [3]: %%timeit ...: cos(3.14) ...: x = 2 + 3 ...: 10000000 loops, best of 3: 196 ns per loop ```
How to delete files with a Python script from a FTP server which are older than 7 days?
2,867,217
7
2010-05-19T15:57:32Z
3,114,477
8
2010-06-24T22:51:07Z
[ "python", "file", "ftp", "delete-file" ]
I would like to write a Python script which allows me to delete files from a FTP Server after they have reached a certain age. I prepared the scipt below but it throws the error message: `WindowsError: [Error 3] The system cannot find the path specified: '/test123/*.*'` Do someone have an idea how to resolve this issu...
OK. Assuming your FTP server supports the `MLSD` command, make a module with the following code (this is code from a script I use to sync a remote FTP site with a local directory): ## module code ``` # for python ≥ 2.6 import sys, os, time, ftplib import collections FTPDir= collections.namedtuple("FTPDir", "name si...
Why does Python sometimes upgrade a string to unicode and sometimes not?
2,867,773
2
2010-05-19T17:10:06Z
2,867,813
10
2010-05-19T17:15:44Z
[ "python", "unicode" ]
I'm confused. Consider this code working the way I expect: ``` >>> foo = u'Émilie and Juañ are turncoats.' >>> bar = "foo is %s" % foo >>> bar u'foo is \xc3\x89milie and Jua\xc3\xb1 are turncoats.' ``` And this code not at all working the way I expect: ``` >>> try: ... raise Exception(foo) ... except Exception...
The [Python Language Reference](http://docs.python.org/library/stdtypes.html#string-formatting) has the answer: > If `format` is a Unicode object, or if any of the objects being converted using the `%s` conversion are Unicode objects, the result will also be a Unicode object. ``` foo = u'Émilie and Juañ are turncoa...
Reading from CSVs in Python repeatedly?
2,868,354
16
2010-05-19T18:42:10Z
2,868,455
17
2010-05-19T18:51:16Z
[ "python", "csv" ]
I'm trying to check the value of extracted data against a csv I already have. It will only loop through the rows of the CSV once, I can only check one value of feed.items(). Is there a value I need to reset somewhere? Is there a better/more efficient way to do this? Thanks. ``` orig = csv.reader(open("googlel.csv", "r...
You can "reset" the CSV iterator by resetting the read position of the file object. ``` data = open("googlel.csv", "rb") orig = csv.reader(data, delimiter = ';') goodrows = [] for feed in gotfeeds: for link,comments in feed.items(): data.seek(0) for row in orig: print link if...
How do I name a variable with acronym?
2,869,251
2
2010-05-19T20:46:03Z
2,869,389
10
2010-05-19T21:00:53Z
[ "python", "naming-conventions" ]
For example in Java for Data Transfer Object I use as: ``` ExampleDTO exampleDTO = new ExampleDTO(); ``` So, if I am following PEP 8 (lower\_case\_with\_underscores), what naming convention should I use for similar in Python?
The style most agreeing with PEP-8 would probably be... `example_dto = ExampleDTO()`
In Python, how to I create a datetime with X hours?
2,869,407
2
2010-05-19T21:03:15Z
2,869,441
8
2010-05-19T21:08:44Z
[ "python", "datetime", "time" ]
How do I create the datetime that is 24 hours before NOW()? 48 before NOW()? X hours or days before now??
``` from datetime import datetime, timedelta def hours_ago(hours): return datetime.today() - timedelta(hours=hours) def days_ago(days): return datetime.today() - timedelta(days=days) ```
How do I count the highest key in a python dictionary? (very pythonic way?) EDIT: make a list
2,869,586
2
2010-05-19T21:33:38Z
2,869,634
10
2010-05-19T21:40:09Z
[ "python", "dictionary" ]
d = {'apple':9,'oranges':3,'grapes':22} How do I return the largest key/value? Edit: How do I make a list that has this sorted by largest to lowest value?
``` >>> d = {'apple':9,'oranges':3,'grapes':22} >>> v, k = max((v, k) for k, v in d.items()) >>> k 'grapes' >>> v 22 ``` **Edit**: To sort them: ``` >>> items = sorted(((v, k) for k, v in d.items()), reverse=True) >>> items [(22, 'grapes'), (9, 'apple'), (3, 'oranges')] ```
django-admin.py startproject mysite not working well on windows 7
2,870,262
9
2010-05-20T00:05:15Z
3,237,555
14
2010-07-13T13:22:58Z
[ "python", "django" ]
I'm learning django and I did successfully start a site on Windows XP by following the tutorial. However, on Windows 7 when I issued: ``` django-admin.py startproject mysite ``` python.exe was started and a window appeared to ask me to choose either python.exe or other program to open a file.... Did I do anything w...
That's already been reported to the django, see <http://bugs.python.org/issue7936> And these's an solution: open regedit and find python.exe like this "C:\Python26\python.exe" "%1" change it to "C:\Python26\python.exe" "%1" %\*
django-admin.py startproject mysite not working well on windows 7
2,870,262
9
2010-05-20T00:05:15Z
5,815,788
8
2011-04-28T08:29:27Z
[ "python", "django" ]
I'm learning django and I did successfully start a site on Windows XP by following the tutorial. However, on Windows 7 when I issued: ``` django-admin.py startproject mysite ``` python.exe was started and a window appeared to ask me to choose either python.exe or other program to open a file.... Did I do anything w...
I had the same error when I ran `django-admin.py` on the command prompt. I couldn't create a projects. I tried to run *Regedit* by using Find to Search python.exe and then adding `%%` but it was not sufficient. I then added the necessary Path to the *System PATH* as shown below. **Open:** *Control Panel* -> *Syst...
django-admin.py startproject mysite not working well on windows 7
2,870,262
9
2010-05-20T00:05:15Z
15,261,516
13
2013-03-07T01:36:43Z
[ "python", "django" ]
I'm learning django and I did successfully start a site on Windows XP by following the tutorial. However, on Windows 7 when I issued: ``` django-admin.py startproject mysite ``` python.exe was started and a window appeared to ask me to choose either python.exe or other program to open a file.... Did I do anything w...
This is what worked for me: I already had c:\python27 and c:\python27\Scripts in PATH. 1. Copy django-admin.py and django-admin-script.py from c:\python27\Scripts to your desired folder 2. with cmd go to that folder and run > django-admin startproject mysite Note that if I doesn't type `python` windows just opens the...
Python readability hints for a Java programmer
2,870,292
9
2010-05-20T00:13:29Z
2,870,297
8
2010-05-20T00:16:29Z
[ "java", "python", "conventions", "readability" ]
I'm a java programmer, but now entering the "realm of python" for some stuff for which Python works better. I'm quite sure a good portion of my code would look weird for a Python programmer (e.g. using parenthesis on every if). I know each language has its own conventions and set of "habits". So, from a readability st...
There's no simple answer to that question. It takes time for your code to be ["Pythonic"](http://faassen.n--tree.net/blog/view/weblog/2005/08/06/0). Don't try and recreate Java idioms in Python. It will just take time to learn Python idioms. Take a look at [Code Like a Pythonista: Idiomatic Python](http://python.net/~...
python histogram one-liner
2,870,466
42
2010-05-20T01:15:39Z
2,870,517
72
2010-05-20T01:33:21Z
[ "python", "histogram", "reduce", "counting" ]
There are many ways to write a Python program that computes a histogram. By histogram, I mean a function that counts the occurrence of objects in an `iterable` and outputs the counts in a dictionary. For example: ``` >>> L = 'abracadabra' >>> histogram(L) {'a': 5, 'b': 2, 'c': 1, 'd': 1, 'r': 2} ``` One way to write...
Python 3.x does have `reduce`, you just have to do a `from functools import reduce`. It also has "dict comprehensions", which have exactly the syntax in your example. Python 2.7 and 3.x also have a [Counter](http://docs.python.org/py3k/library/collections.html#counter-objects) class which does exactly what you want: ...
What are your "must-have" Python Packages for Finance?
2,870,661
13
2010-05-20T02:28:49Z
2,887,314
7
2010-05-22T07:35:19Z
[ "python", "finance", "scientific-computing" ]
With the recent [SEC proposal](http://www.sec.gov/rules/proposed/2010/33-9117.pdf) requiring that most Asset-Backed Securities issuers file a python computer program to document the flow of funds (or waterfall) provisions of the transaction, I thought it timely to ask what you thought the "Must-Have" Python Packages fo...
<http://code.google.com/p/pandas/> is also developed with a quantitative finance background. I guess then the usual suspects: * numpy * scipy * rpy * matplotlib * ... For my quant-development I usual start with pythonxy (http://www.pythonxy.com/) as a basis. In the past I used also some python bindings for quantlib...
How to convert an HTML table to an array in python
2,870,667
10
2010-05-20T02:29:58Z
2,870,688
17
2010-05-20T02:39:02Z
[ "python", "html" ]
I have an html document, and I want to pull the tables out of this document and return them as arrays. I'm picturing 2 functions, one that finds all the html tables in a document, and a second one that turns html tables into 2-dimensional arrays. Something like this: ``` htmltables = get_tables(htmldocument) for tabl...
Use [BeautifulSoup](http://www.crummy.com/software/BeautifulSoup/) (I recommend `3.0.8`). Finding all tables is trivial: ``` import BeautifulSoup def get_tables(htmldoc): soup = BeautifulSoup.BeautifulSoup(htmldoc) return soup.findAll('table') ``` However, in Python, an [array](http://docs.python.org/library...
Python raw strings and trailing backslash
2,870,730
22
2010-05-20T02:53:42Z
2,870,738
17
2010-05-20T02:57:28Z
[ "python", "windows", "escaping" ]
I ran across something once upon a time and wondered if it was a Python "bug" or at least a misfeature. I'm curious if anyone knows of any justifications for this behavior. I thought of it just now reading "Code Like a Pythonista," which has been enjoyable so far. I'm only familiar with the 2.x line of Python. Raw str...
It's a [FAQ](http://docs.python.org/faq/design.html#why-can-t-raw-strings-r-strings-end-with-a-backslash). And in response to "you really want your string to end with a backslash. There's no way to do that in a 'raw' string.": the FAQ shows how to workaround it. ``` >>> r'ab\c' '\\' == 'ab\\c\\' True >>> ```
Efficient way in Python to add an element to a comma-separated string
2,871,030
2
2010-05-20T04:34:35Z
2,871,056
8
2010-05-20T04:42:56Z
[ "python", "string", "pylons" ]
I'm looking for the most efficient way to add an element to a comma-separated string while maintaining alphabetical order for the words: For example: ``` string = 'Apples, Bananas, Grapes, Oranges' addition = 'Cherries' result = 'Apples, Bananas, Cherries, Grapes, Oranges' ``` Also, a way to do this but while mainta...
For the first case: ``` alist = string.split(', ') result = ', '.join(sorted(alist + [addition])) ``` For the second case: ``` alist = string.split(', ') result = ', '.join(sorted(alist + [addition], key=lambda s: s.split(':', 1)[1])) ``` If you have many thousands of items in the list, th...
how to create english language dictionary application with python (django)?
2,871,809
10
2010-05-20T07:39:11Z
2,874,343
8
2010-05-20T13:53:46Z
[ "python", "django", "dictionary" ]
I would like to create an online dictionary application by using python (or with django). It will be similar to <http://dictionary.reference.com/>. PS: the dictionary is not stored in a database. it's stored in a text file or gunzip file. Free english dictionary files can be downloaded from this URL: dicts.info/dicti...
You might want to check out <http://www.nltk.org/> You could get lots of words and their definitions without having to worry about the implementation details of a database. If you're new to all this stuff, at the very least it would be useful to get you up and going, and then when you've got a working version, start pu...
Inserting newline character after every 76 characters in a base64 string
2,871,933
5
2010-05-20T08:01:04Z
2,871,950
7
2010-05-20T08:03:30Z
[ "python", "base64" ]
I am trying to convert bitmap images into a base64 string before inserting it into database as binary blobs. The base64 string needs to be encoded in such a way that their is a new line character after every 76 characters. What is the best pythonic way of doing this?
``` '\n'.join(s[pos:pos+76] for pos in xrange(0, len(s), 76)) ```
Inserting newline character after every 76 characters in a base64 string
2,871,933
5
2010-05-20T08:01:04Z
18,540,152
7
2013-08-30T19:26:11Z
[ "python", "base64" ]
I am trying to convert bitmap images into a base64 string before inserting it into database as binary blobs. The base64 string needs to be encoded in such a way that their is a new line character after every 76 characters. What is the best pythonic way of doing this?
``` import base64 base64.encodestring(s) ``` <http://docs.python.org/library/base64.html> > Encode the string s, which can contain arbitrary binary data, and return a string containing one or more lines of base64-encoded data. encodestring() returns a string containing one or more lines of base64-encoded data always ...
How can I make Perl and Python print each line of the program being executed?
2,872,089
36
2010-05-20T08:28:13Z
2,872,117
42
2010-05-20T08:32:13Z
[ "python", "bash", "perl", "debugging", "trace" ]
I know that `bash -x script.sh` will execute script printing each line before actual execution. How to make Perl and Python interpreters do the same?
[Devel::Trace](http://search.cpan.org/~mjd/Devel-Trace-0.10/Trace.pm) is the Perl analogue, the [trace module](http://docs.python.org/library/trace.html) is Python's.
How to read a file byte by byte in Python and how to print a bytelist as a binary?
2,872,381
15
2010-05-20T09:14:57Z
2,872,393
20
2010-05-20T09:16:52Z
[ "python", "file-io", "byte" ]
I'm trying to read a file byte by byte, but I'm not sure how to do that. I'm trying to do it like that: ``` file = open(filename, 'rb') while 1: byte = file.read(8) # Do something... ``` So does that make the variable byte to contain 8 next bits at the beginning of every loop? It doesn't matter what those bytes...
To read one byte: ``` file.read(1) ``` 8 bits is one byte.
How to read a file byte by byte in Python and how to print a bytelist as a binary?
2,872,381
15
2010-05-20T09:14:57Z
2,872,397
11
2010-05-20T09:17:28Z
[ "python", "file-io", "byte" ]
I'm trying to read a file byte by byte, but I'm not sure how to do that. I'm trying to do it like that: ``` file = open(filename, 'rb') while 1: byte = file.read(8) # Do something... ``` So does that make the variable byte to contain 8 next bits at the beginning of every loop? It doesn't matter what those bytes...
The code you've shown will read 8 *bytes*. You could use ``` with open(filename, 'rb') as f: while 1: byte_s = f.read(1) if not byte_s: break byte = byte_s[0] ... ```
How to read a file byte by byte in Python and how to print a bytelist as a binary?
2,872,381
15
2010-05-20T09:14:57Z
2,874,748
13
2010-05-20T14:37:33Z
[ "python", "file-io", "byte" ]
I'm trying to read a file byte by byte, but I'm not sure how to do that. I'm trying to do it like that: ``` file = open(filename, 'rb') while 1: byte = file.read(8) # Do something... ``` So does that make the variable byte to contain 8 next bits at the beginning of every loop? It doesn't matter what those bytes...
To answer the second part of your question, to convert to binary you can use a [format string](http://docs.python.org/library/string.html#string.Formatter.format) and the [`ord`](http://docs.python.org/library/functions.html#ord) function: ``` >>> byte = 'a' >>> '{0:08b}'.format(ord(byte)) '01100001' ``` Note that th...
Python truncate a long string
2,872,512
89
2010-05-20T09:37:03Z
2,872,519
167
2010-05-20T09:38:05Z
[ "python" ]
How does one truncate a string to 75 characters in Python? This is how it is done in JavaScript: ``` var data="saddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddsaddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddsaddddddddddddddddddddddddddddddddddddd...
``` info = (data[:75] + '..') if len(data) > 75 else data ```
Python truncate a long string
2,872,512
89
2010-05-20T09:37:03Z
2,872,552
7
2010-05-20T09:44:08Z
[ "python" ]
How does one truncate a string to 75 characters in Python? This is how it is done in JavaScript: ``` var data="saddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddsaddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddsaddddddddddddddddddddddddddddddddddddd...
You could use this one-liner: ``` data = (data[:75] + '..') if len(data) > 75 else data ```
Python truncate a long string
2,872,512
89
2010-05-20T09:37:03Z
2,873,335
34
2010-05-20T11:48:37Z
[ "python" ]
How does one truncate a string to 75 characters in Python? This is how it is done in JavaScript: ``` var data="saddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddsaddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddsaddddddddddddddddddddddddddddddddddddd...
Even more concise: ``` data = data[:75] ``` If it is less than 75 characters there will be no change.
Python truncate a long string
2,872,512
89
2010-05-20T09:37:03Z
2,873,416
71
2010-05-20T11:58:46Z
[ "python" ]
How does one truncate a string to 75 characters in Python? This is how it is done in JavaScript: ``` var data="saddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddsaddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddsaddddddddddddddddddddddddddddddddddddd...
Even shorter : ``` info = data[:75] + (data[75:] and '..') ```
Python truncate a long string
2,872,512
89
2010-05-20T09:37:03Z
34,993,870
8
2016-01-25T13:30:08Z
[ "python" ]
How does one truncate a string to 75 characters in Python? This is how it is done in JavaScript: ``` var data="saddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddsaddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddsaddddddddddddddddddddddddddddddddddddd...
For a Django solution (which has not been mentioned in the question): ``` from django.utils.text import Truncator value = Truncator(value).chars(75) ``` Have a look at Truncator's source code to appreciate the problem: <https://github.com/django/django/blob/master/django/utils/text.py#L66> Concerning truncation with...
how can I put a process in background using django?
2,872,605
5
2010-05-20T09:52:30Z
2,872,940
15
2010-05-20T10:41:10Z
[ "python", "django", "process", "system" ]
I tried os.system, os.spwanl, etc.. but it doesn't work well I need to execute some background process from django application.
Try to use [celery](http://ask.github.com/celery/getting-started/introduction.html). It was originally created for this purpose and also supports scheduling tasks.
Is there a better way to write this URL Manipulation in Python?
2,873,438
9
2010-05-20T12:01:33Z
2,873,495
10
2010-05-20T12:09:18Z
[ "python", "url", "parsing" ]
I'm curious if there's a simpler way to remove a particular parameter from a url. What I came up with is the following. This seems a bit verbose. Libraries to use or a more pythonic version appreciated. ``` parsed = urlparse(url) if parsed.query != "": params = dict([s.split("=") for s in parsed.query.split("&")])...
Use [`urlparse.parse_qsl()`](http://docs.python.org/2/library/urlparse.html#urlparse.parse_qsl) to crack the query string. You can filter this in one go: ``` params = [(k,v) for (k,v) in parse_qsl(parsed.query) if k != 'page'] ```
Is there a better way to write this URL Manipulation in Python?
2,873,438
9
2010-05-20T12:01:33Z
2,878,051
7
2010-05-20T21:36:45Z
[ "python", "url", "parsing" ]
I'm curious if there's a simpler way to remove a particular parameter from a url. What I came up with is the following. This seems a bit verbose. Libraries to use or a more pythonic version appreciated. ``` parsed = urlparse(url) if parsed.query != "": params = dict([s.split("=") for s in parsed.query.split("&")])...
I've created a small helper class to represent a url in a structured way: ``` import cgi, urllib, urlparse class Url(object): def __init__(self, url): """Construct from a string.""" self.scheme, self.netloc, self.path, self.params, self.query, self.fragment = urlparse.urlparse(url) self.ar...
Why subtract a value from itself (x - x) in Python?
2,875,024
13
2010-05-20T15:06:45Z
2,875,083
14
2010-05-20T15:12:15Z
[ "python", "numpy", "type-conversion" ]
In NumPy functions, there are often initial lines that do checking of variable types, forcing them to be certain types, etc. Can someone explain the point of these lines in [scipy.signal.square](http://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.square.html)? What does subtracting a value from itself do? ...
I believe that this will make the final w and t have the same type. For example, if you start with float and int, you will end up with both being float arrays which is better for subsequent operations.
list python package dependencies without loading them?
2,875,232
20
2010-05-20T15:27:44Z
2,875,570
24
2010-05-20T15:59:45Z
[ "python", "dependencies", "packaging" ]
Say that python package A requires B, C and D; is there a way to list A → B C D without loading them ? `Requires` in the metadata (`yolk -M A`) are often incomplete, grr. One can download A.tar / A.egg, then look through A/setup.py, but some of those are pretty gory. (I'd have thought that getting at least first-l...
[Snakefood](http://furius.ca/snakefood/) ``` sfood -fuq package.py | sfood-target-files ``` will list the dependencies. ``` `-f` tells sfood to follow dependencies recursively `-u` tells sfood to ignore unused imports `-q` tells sfood to be quiet about debugging information ``` To filter out modules from the standa...
list python package dependencies without loading them?
2,875,232
20
2010-05-20T15:27:44Z
2,876,185
9
2010-05-20T17:18:20Z
[ "python", "dependencies", "packaging" ]
Say that python package A requires B, C and D; is there a way to list A → B C D without loading them ? `Requires` in the metadata (`yolk -M A`) are often incomplete, grr. One can download A.tar / A.egg, then look through A/setup.py, but some of those are pretty gory. (I'd have thought that getting at least first-l...
[modulefinder](http://docs.python.org/library/modulefinder.html) from the standard lib > New in version 2.3. > > This module provides a ModuleFinder > class that can be used to determine > the set of modules imported by a > script. modulefinder.py can also be > run as a script, giving the filename > of a Python script...
Does urllib or urllib2 in Python 2.5 support https?
2,875,402
2
2010-05-20T15:43:35Z
2,875,611
8
2010-05-20T16:04:09Z
[ "python", "https", "urllib2", "urllib", "python-2.5" ]
Thanks for the help in advance. I am puzzled that the same code works for python 2.6 but not 2.5. Here is the code ``` import cgi, urllib, urlparse, urllib2 url='https://graph.facebook.com' req=urllib2.Request(url=url) p=urllib2.urlopen(req) response = cgi.parse_qs(p.read()) ``` And here is the exception I got ``` ...
Most likely you're 2.5 version as been compiled without ssl support. Try this : ``` >>> import socket >>> socket.ssl <function ssl at 0xb7ce602c> ``` to check if ssl is present (ie, you don't catch an AttributeError)
cx_Freeze and PYC/PYD files
2,875,530
3
2010-05-20T15:55:17Z
2,875,948
7
2010-05-20T16:45:46Z
[ "python", "cx-freeze" ]
I'm using cx\_Freeze to freeze my python program. On running cx\_Freeze, a bunch of PYD files are created, a whole bunch of PYC files are put into a archive named library.zip and a few DLL files are there too. Could someone tell me the difference between the PYC and the PYD files? What's the reason for the PYD files n...
Disclaimer: I haven't used cx\_Freeze in awhile...... .PYD files are DLL machine-code files that contain specific python-required functions. .PYC files are .py files that have been compiled into bytecode. so PYDs are machine code and PYCs are bytecode Now as for why the PYDs aren't in the .zip....I'd imagine it's b...
Bundle a Python app as a single file to support add-ons or extensions?
2,876,967
7
2010-05-20T19:04:51Z
2,971,344
7
2010-06-04T03:35:32Z
[ "python", "py2exe", "software-distribution", "py2app", "pyinstaller" ]
There are several utilities — all with different procedures, limitations, and target operating systems — for getting a Python package and all of its dependencies and turning them into a single binary program that is easy to ship to customers: * <http://wiki.python.org/moin/Freeze> * <http://www.pyinstaller.org/> *...
You should be able to have a plugins directory that your application scans at runtime (or later) to import the code in question. Here's an example that should work with regular .py or .pyc code that even works with plugins stored inside zip files (so users could just drop someplugin.zip in the 'plugins' directory and h...
Python new-style classes and __subclasses__ function
2,877,110
10
2010-05-20T19:28:30Z
2,877,433
23
2010-05-20T20:11:25Z
[ "python" ]
Can somebody explain to me why this works (in Python 2.5) : ``` class Foo(object): pass class Bar(Foo): pass print(Foo.__subclasses__()) ``` but this doesn't : ``` class Foo(): pass class Bar(Foo): pass print(Foo.__subclasses__()) ``` The latter returns "AttributeError: class Foo has no attribut...
``` class Foo(object): pass ``` The class above is a "new-style" class because it inherits from the **object** class. New-style classes provide a lot of extra framework that "old-style" classes do not have. One particular attribute of a new-style class is to be able to determine the subclasses of the class with th...
Parameters for find function
2,877,114
8
2010-05-20T19:29:07Z
2,877,302
17
2010-05-20T19:52:08Z
[ "python", "find", "beautifulsoup" ]
I'm using beautiful soup (in Python). I have such hidden input object: ``` <input type="hidden" name="form_build_id" id="form-531f740522f8c290ead9b88f3da026d2" value="form-531f740522f8c290ead9b88f3da026d2" /> ``` I need in id/value. Here is my code: ``` mainPageData = cookieOpener.open('http://page.com').read() so...
Try using the [alternative `attrs` keyword](http://www.crummy.com/software/BeautifulSoup/documentation.html#arg-attrs): ``` areaId = soupHandler.find('input', attrs={'name':'form_build_id', 'type':'hidden'}) ``` > You can't use a keyword argument > called name because the Beautiful Soup > search methods already defin...
Python, store a dict in a database
2,877,410
12
2010-05-20T20:07:39Z
2,877,479
13
2010-05-20T20:18:48Z
[ "python", "string", "dictionary" ]
What's the best way to store and retrieve a python dict in a database?
If you are not specifically interested into using a traditionally SQL database, such as MySQL, you could look into unstructured document databases where documents naturally map to python dictionaries, for example [MongoDB](http://www.mongodb.org/). The MongoDB [python bindings](http://api.mongodb.org/python/1.6%2B/inde...
Sort a list of dicts by dict values
2,878,084
10
2010-05-20T21:44:20Z
2,878,123
12
2010-05-20T21:51:55Z
[ "python", "sorting", "dictionary" ]
I have a list of dictionaries: ``` [{'title':'New York Times', 'title_url':'New_York_Times','id':4}, {'title':'USA Today','title_url':'USA_Today','id':6}, {'title':'Apple News','title_url':'Apple_News','id':2}] ``` I'd like to sort it by the title, so elements with A go before Z: ``` [{'title':'Apple News','title_...
``` l.sort(key=lambda x:x['title']) ``` To sort with multiple keys, assuming all in ascending order: ``` l.sort(key=lambda x:(x['title'], x['title_url'], x['id'])) ```
Sort a list of dicts by dict values
2,878,084
10
2010-05-20T21:44:20Z
2,878,183
14
2010-05-20T22:03:05Z
[ "python", "sorting", "dictionary" ]
I have a list of dictionaries: ``` [{'title':'New York Times', 'title_url':'New_York_Times','id':4}, {'title':'USA Today','title_url':'USA_Today','id':6}, {'title':'Apple News','title_url':'Apple_News','id':2}] ``` I'd like to sort it by the title, so elements with A go before Z: ``` [{'title':'Apple News','title_...
The hypoallergenic alternative for those who sneeze when approached by lambdas: ``` import operator L.sort(key=operator.itemgetter('title','title_url','id')) ```
How to delete old image when update ImageField?
2,878,490
11
2010-05-20T23:03:39Z
2,879,558
10
2010-05-21T04:25:10Z
[ "python", "django", "django-models" ]
I'm using Django to create a stock photo site, I have a ImageField in my model, the problem is that when the user update the image field, the original image file isn't deleted from the hard disk. how can I make to delete those images after an update? Thanks!
You'll have to delete the old image manually. The absolute path to the image is stored in your\_image\_field.name. So you'd do something like: ``` os.remove(your_image_field.name) ``` But, as a convenience, you can use the associated FieldFile object, which gives easy access to the underlying file, as well as provid...
How to delete old image when update ImageField?
2,878,490
11
2010-05-20T23:03:39Z
12,058,684
7
2012-08-21T15:53:22Z
[ "python", "django", "django-models" ]
I'm using Django to create a stock photo site, I have a ImageField in my model, the problem is that when the user update the image field, the original image file isn't deleted from the hard disk. how can I make to delete those images after an update? Thanks!
Use [django-cleanup](https://github.com/un1t/django-cleanup) ``` pip install django-cleanup ``` settings.py ``` INSTALLED_APPS = ( ... 'django_cleanup', # should go after your apps ) ```
Python OOP and lists
2,878,499
2
2010-05-20T23:04:37Z
2,878,540
8
2010-05-20T23:14:08Z
[ "python", "class-variables" ]
I'm new to Python and it's OOP stuff and can't get it to work. Here's my code: ``` class Tree: root = None; data = []; def __init__(self, equation): self.root = equation; def appendLeft(self, data): self.data.insert(0, data); def appendRight(self, data): self.data.append...
The problem is that you've declared `data` as a class variable, so all instances of the class share the same list. Instead, put `self.data = []` in your `__init__`. Also, get rid of all those semicolons. They are unnecessary and clutter up your code.
Replacing backslashes in Python strings
2,878,549
2
2010-05-20T23:15:40Z
2,878,588
7
2010-05-20T23:25:26Z
[ "python", "string", "replace", "backslash" ]
I have some code to encrypt some strings in Python. Encrypted text is used as a parameter in some urls, but after encrypting, there comes backslashes in string and I cannot use single backslash in urllib2.urlopen. I cannot replace single backslash with double. For example: ``` print cipherText '\t3-@\xab7+\xc7\x93H...
probably what you are seeing is not a real "backslash character", but it is the string representation of a non printable (or non-ascii) character. For example `\t` is Tab, not a backslash and `t`. You should build your url with ``` "http://awebsite.me/main?%s" % (urllib.urlencode({'param': cipherText})) ```
Make OS open directory in Python
2,878,712
4
2010-05-20T23:57:48Z
2,878,744
9
2010-05-21T00:06:32Z
[ "python" ]
I am writing a program in Python, and want to get it to make the OS open the current working directory, making for instance Windows open explorer.exe and navigating to the wanted directory. Any ideas on how to do this? The directory is already given by os.getcwd. Cross platform methods preferred :)
There is [os.startfile](http://docs.python.org/library/os.html#os.startfile), but it's only available under windows: ``` import os os.startfile('C:/') # opens explorer at C:\ drive ``` [Here](http://docs.python.org/library/os.html#os.startfile) someone (credits to Eric\_Dexter@msn.com apparently) posted an alternativ...
Python- Convert a mixed number to a float
2,878,727
2
2010-05-21T00:02:28Z
2,878,743
8
2010-05-21T00:06:12Z
[ "python", "numbers", "mixed" ]
I want to make a function that converts mixed numbers and fractions (as strings) to floats. Here's some examples: ``` '1 1/2' -> 1.5 '11/2' -> 5.5 '7/8' -> 0.875 '3' -> 3 '7.7' -> 7.7 ``` I'm currently using this function, but I think it could be improved. It also doesn't handle numbers that are already in decimal re...
2.6 has the [`fractions`](http://docs.python.org/library/fractions.html) module. Just split the string on whitespace, feed the chunks to `fractions.Fraction()`, call `float()` against the result, and add them all up.
Python base classes share attributes?
2,879,494
5
2010-05-21T04:06:03Z
2,879,512
12
2010-05-21T04:11:19Z
[ "python" ]
Code in test.py: ``` class Base(object): def __init__(self, l=[]): self.l = l def add(self, num): self.l.append(num) def remove(self, num): self.l.remove(num) class Derived(Base): def __init__(self, l=[]): super(Derived, self).__init__(l) ``` Python shell session: `...
You're making a common Python newcomer mistake. See my answer here: <http://stackoverflow.com/questions/2681243/how-should-i-declare-default-values-for-instance-variables-in-python/2681507#2681507> Briefly explained, Python interprets the class definitions only **once**. That means everything declared in the `__init_...
How can I hide the console window when freezing wxPython applications with cxFreeze?
2,880,316
27
2010-05-21T07:37:44Z
2,882,079
15
2010-05-21T12:40:55Z
[ "python", "wxpython", "cx-freeze" ]
I'm developing a Python application using wxPython and freezing it using cxFreeze. All seems to be going fine apart from this following bit: When I run the executable created by cxFreeze, a blank console window pops up. I don't want to show it. Is there any way I could hide it? It doesn't seem to be documented on the...
This worked to some extent but it has issues. My program runs in both a console mode and a GUI mode. When run from the console with a `--console` argument it runs in a console mode. When I followed the procedure below, this doesn't work anymore and my program is only a GUI app then. The following source code comes fro...
How can I hide the console window when freezing wxPython applications with cxFreeze?
2,880,316
27
2010-05-21T07:37:44Z
6,310,295
18
2011-06-10T17:58:06Z
[ "python", "wxpython", "cx-freeze" ]
I'm developing a Python application using wxPython and freezing it using cxFreeze. All seems to be going fine apart from this following bit: When I run the executable created by cxFreeze, a blank console window pops up. I don't want to show it. Is there any way I could hide it? It doesn't seem to be documented on the...
For Windows: You have to use a line like this (use file folders and names as appropriate) ``` C:/Python/Scripts/cxfreeze C:/Python/Code/yourprogram.py --base-name=Win32GUI --target-dir C:/Python/Dist ``` By adding the `--base-name=Win32GUI` option, the console window will not appear.
Time difference in seconds (as a floating point)
2,880,713
8
2010-05-21T08:55:52Z
2,880,735
12
2010-05-21T08:58:56Z
[ "python", "datetime", "floating-point" ]
``` >>> from datetime import datetime >>> t1 = datetime.now() >>> t2 = datetime.now() >>> delta = t2 - t1 >>> delta.seconds 7 >>> delta.microseconds 631000 ``` Is there any way to get that as 7.631000 ? I can use time module, but I also need that t1 and t2 variables as DateTime objects. So if there is an easy way to d...
`combined = delta.seconds + delta.microseconds/1E6`
Time difference in seconds (as a floating point)
2,880,713
8
2010-05-21T08:55:52Z
24,260,054
12
2014-06-17T09:21:33Z
[ "python", "datetime", "floating-point" ]
``` >>> from datetime import datetime >>> t1 = datetime.now() >>> t2 = datetime.now() >>> delta = t2 - t1 >>> delta.seconds 7 >>> delta.microseconds 631000 ``` Is there any way to get that as 7.631000 ? I can use time module, but I also need that t1 and t2 variables as DateTime objects. So if there is an easy way to d...
for newer version of Python (2.6 does not have it, but 2.7 does), you can also use the method `total_seconds`: ``` from datetime import datetime t1 = datetime.now() t2 = datetime.now() delta = t2 - t1 delta.total_seconds() ```
Python daylight savings time
2,881,025
21
2010-05-21T09:45:15Z
2,881,048
36
2010-05-21T09:48:41Z
[ "python", "time", "dst" ]
How do I check if daylight saving time is in effect?
You can use [`time.localtime`](http://docs.python.org/library/time.html#time.localtime) and look at the `tm_isdst` flag in the return value. ``` >>> import time >>> time.localtime() (2010, 5, 21, 21, 48, 51, 4, 141, 0) >>> _.tm_isdst 0 ``` Using `time.localtime()`, you can ask the same question for any arbitrary time...