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 |
|---|---|---|---|---|---|---|---|---|---|
What to do with "Unexpected indent" in python? | 1,016,814 | 60 | 2009-06-19T07:53:20Z | 7,499,004 | 8 | 2011-09-21T11:31:51Z | [
"python",
"syntax-error"
] | How do I rectify the error "unexpected indent" in python? | Run your code with the -tt option to find out if you are using tabs and spaces inconsistently |
simple update in sqlalchemy | 1,017,388 | 7 | 2009-06-19T10:58:46Z | 1,017,420 | 23 | 2009-06-19T11:10:50Z | [
"python",
"sqlalchemy"
] | UserTable is:
* id (INT)
* name (STR)
* last\_login (DATETIME)
Serving a web page request i have a **user id** in hand and I only wish to update the **last\_login** field to 'now'.
It seems to me that there are 2 ways:
1. issue a direct SQL using db\_engine (losing the mapper)
2. OR query the user first and then up... | Assuming you have a mapper UserTable in place:
```
DBSession.query(UserTable).filter_by(id = user_id).\
update({"last_login":datetime.datetime.now()}, synchronize_session=False)
```
Additional parameters in the [docs](http://www.sqlalchemy.org/docs/05/reference/orm/query.html#sqlalchemy.orm.query.Query.update). |
Is there any Ruby or Python interpreter for Lego Mindstorm? | 1,017,429 | 21 | 2009-06-19T11:15:31Z | 1,020,503 | 7 | 2009-06-19T23:43:24Z | [
"python",
"ruby",
"interpreter",
"robotics",
"lego"
] | I want to start coding in Python or Ruby. Since I own a [Lego Midstorms](http://en.wikipedia.org/wiki/Lego%5FRobotics) kit I thought it would be nice to program against it. Are there any good translators / interpeters for the Mindstorms brick? | The nxt-python and ruby-nxt projects are remote control interfaces to the NXT. They both run on a PC and remotely control the NXT via Bluetooth or USB.
If you are looking for running alternative firmware on the NXT, there are several different alternatives.
Steve Hassenplug has a webpage with a comprehensive list of a... |
PostgreSQL - how to run VACUUM from code outside transaction block? | 1,017,463 | 20 | 2009-06-19T11:26:33Z | 1,017,655 | 39 | 2009-06-19T12:18:49Z | [
"python",
"sql",
"postgresql",
"psycopg2",
"vacuum"
] | I am using Python with psycopg2 and I'm trying to run a full `VACUUM` after a daily operation which inserts several thousand rows. The problem is that when I try to run the `VACUUM` command within my code I get the following error:
```
psycopg2.InternalError: VACUUM cannot run inside a transaction block
```
How do I ... | After more searching I have discovered the isolation\_level property of the psycopg2 connection object. It turns out that changing this to `0` will move you out of a transaction block. Changing the vacuum method of the above class to the following solves it. Note that I also set the isolation level back to what it prev... |
Why isn't Python very good for functional programming? | 1,017,621 | 216 | 2009-06-19T12:12:06Z | 1,017,663 | 75 | 2009-06-19T12:20:18Z | [
"python",
"functional-programming"
] | I have always thought that functional programming can be done in Python. Thus, I was surprised that Python didn't get much of a mention in [this](http://stackoverflow.com/questions/1015606/mixing-object-oriented-and-functional-programming) question, and when it was mentioned, it normally wasn't very positive. However, ... | Guido has a good explanation of this [here](http://python-history.blogspot.com/2009/04/origins-of-pythons-functional-features.html). Here's the most relevant part:
> I have never considered Python to be
> heavily influenced by functional
> languages, no matter what people say
> or think. I was much more familiar
> wit... |
Why isn't Python very good for functional programming? | 1,017,621 | 216 | 2009-06-19T12:12:06Z | 1,017,673 | 9 | 2009-06-19T12:22:40Z | [
"python",
"functional-programming"
] | I have always thought that functional programming can be done in Python. Thus, I was surprised that Python didn't get much of a mention in [this](http://stackoverflow.com/questions/1015606/mixing-object-oriented-and-functional-programming) question, and when it was mentioned, it normally wasn't very positive. However, ... | Python is almost a functional language. It's "functional lite".
It has extra features, so it isn't pure enough for some.
It also lacks some features, so it isn't complete enough for some.
The missing features are relatively easy to write. Check out posts like [this](http://blog.sigfpe.com/2008/02/purely-functional-r... |
Why isn't Python very good for functional programming? | 1,017,621 | 216 | 2009-06-19T12:12:06Z | 1,017,682 | 37 | 2009-06-19T12:24:44Z | [
"python",
"functional-programming"
] | I have always thought that functional programming can be done in Python. Thus, I was surprised that Python didn't get much of a mention in [this](http://stackoverflow.com/questions/1015606/mixing-object-oriented-and-functional-programming) question, and when it was mentioned, it normally wasn't very positive. However, ... | Scheme doesn't have algebraic data types or pattern matching but it's certainly a functional language. Annoying things about Python from a functional programming perspective:
1. Crippled Lambdas. Since Lambdas can only contain an expression, and you can't do everything as easily in an expression context, this means th... |
Why isn't Python very good for functional programming? | 1,017,621 | 216 | 2009-06-19T12:12:06Z | 1,017,937 | 264 | 2009-06-19T13:22:56Z | [
"python",
"functional-programming"
] | I have always thought that functional programming can be done in Python. Thus, I was surprised that Python didn't get much of a mention in [this](http://stackoverflow.com/questions/1015606/mixing-object-oriented-and-functional-programming) question, and when it was mentioned, it normally wasn't very positive. However, ... | The question you reference asks which languages promote both OO and functional programming. Python does not *promote* functional programming even though it *works* fairly well.
The best argument *against* functional programming in Python is that imperative/OO use cases are carefully considered by Guido, while function... |
Why isn't Python very good for functional programming? | 1,017,621 | 216 | 2009-06-19T12:12:06Z | 1,017,986 | 14 | 2009-06-19T13:35:43Z | [
"python",
"functional-programming"
] | I have always thought that functional programming can be done in Python. Thus, I was surprised that Python didn't get much of a mention in [this](http://stackoverflow.com/questions/1015606/mixing-object-oriented-and-functional-programming) question, and when it was mentioned, it normally wasn't very positive. However, ... | I would never call Python âfunctionalâ but whenever I program in Python the code invariably ends up being almost purely functional.
Admittedly, that's mainly due to the extremely nice list comprehension. So I wouldn't necessarily suggest Python as a functional programming language but I would suggest functional pr... |
Why isn't Python very good for functional programming? | 1,017,621 | 216 | 2009-06-19T12:12:06Z | 1,018,393 | 14 | 2009-06-19T14:50:09Z | [
"python",
"functional-programming"
] | I have always thought that functional programming can be done in Python. Thus, I was surprised that Python didn't get much of a mention in [this](http://stackoverflow.com/questions/1015606/mixing-object-oriented-and-functional-programming) question, and when it was mentioned, it normally wasn't very positive. However, ... | Let me demonstrate with a piece of code taken from an answer to a "functional" [Python question](http://stackoverflow.com/questions/1016997/generate-from-generators/1017105#1017105) on SO
Python:
```
def grandKids(generation, kidsFunc, val):
layer = [val]
for i in xrange(generation):
layer = itertools.chain.f... |
Why isn't Python very good for functional programming? | 1,017,621 | 216 | 2009-06-19T12:12:06Z | 24,661,572 | 7 | 2014-07-09T18:48:46Z | [
"python",
"functional-programming"
] | I have always thought that functional programming can be done in Python. Thus, I was surprised that Python didn't get much of a mention in [this](http://stackoverflow.com/questions/1015606/mixing-object-oriented-and-functional-programming) question, and when it was mentioned, it normally wasn't very positive. However, ... | One thing that is really important for this question (and the answers) is the following:
What the hell is functional programming, and what are the most important properties of it.
I'll try to give my view of it:
Functional programming is a lot like writing math on a whiteboard. When you write equations
on a whiteboard... |
Python sys.path modification not working | 1,017,909 | 7 | 2009-06-19T13:14:52Z | 1,017,948 | 17 | 2009-06-19T13:26:14Z | [
"python",
"path"
] | I'm trying to modify the sys.path in one of my Python files in order to have some
specific libraries dirs in the modules search path (it might not be the best way
but ...). If I insert several paths in the front of sys.path my script is not taking into account those paths for future imports. If i make a whole new list ... | You really need to post some code for us to be able to help you. However, I can make an educated guess. You say that if you make a whole new list and assign it to sys.path then it works. I assume you mean that you're doing something like this
```
sys.path = ["dir1", "dir2", ...]
```
But that if you insert the paths a... |
Help me understand the difference between CLOBs and BLOBs in Oracle | 1,018,073 | 33 | 2009-06-19T13:51:38Z | 1,018,096 | 46 | 2009-06-19T13:56:25Z | [
"python",
"oracle"
] | This is mainly just a "check my understanding" type of question. Here's my understanding of CLOBs and BLOBs as they work in Oracle:
* CLOBs are for text like XML, JSON, etc. You should not assume what encoding the database will store it as (at least in an application) as it will be converted to whatever encoding the d... | `CLOB` is encoding and collation sensitive, `BLOB` is not.
When you write into a `CLOB` using, say, `CL8WIN1251`, you write a `0xC0` (which is Cyrillic letter Ð).
When you read data back using `AL16UTF16`, you get back `0x0410`, which is a `UTF16` represenation of this letter.
If you were reading from a `BLOB`, you... |
Help me understand the difference between CLOBs and BLOBs in Oracle | 1,018,073 | 33 | 2009-06-19T13:51:38Z | 1,018,102 | 9 | 2009-06-19T13:57:36Z | [
"python",
"oracle"
] | This is mainly just a "check my understanding" type of question. Here's my understanding of CLOBs and BLOBs as they work in Oracle:
* CLOBs are for text like XML, JSON, etc. You should not assume what encoding the database will store it as (at least in an application) as it will be converted to whatever encoding the d... | Your understanding is correct. Since you mention Python, think of the Python 3 distinction between strings and bytes: CLOBs and BLOBs are quite analogous, with the extra issue that the encoding of CLOBs is not under your app's control. |
Pass-through keyword arguments | 1,018,359 | 4 | 2009-06-19T14:44:33Z | 1,018,372 | 9 | 2009-06-19T14:46:01Z | [
"python"
] | I've got a class function that needs to "pass through" a particular keyword argument:
```
def createOrOpenTable(self, tableName, schema, asType=Table):
if self.tableExists(tableName):
return self.openTable(tableName, asType=asType)
else:
return self.createTable(self, tableName, schema, asType=a... | You're doing it right... Just take out the `self` in the second function call :)
```
return self.createTable(self, tableName, schema, asType=asType)
```
should be:
```
return self.createTable(tableName, schema, asType=asType)
``` |
Python and if statement | 1,018,415 | 2 | 2009-06-19T14:54:30Z | 1,018,426 | 8 | 2009-06-19T14:57:07Z | [
"python",
"if-statement"
] | I'm running a script to feed an exe file a statement like below:
```
for j in ('90.','52.62263.','26.5651.','10.8123.'):
if j == '90.':
z = ('0.')
elif j == '52.62263.':
z = ('0.', '72.', '144.', '216.', '288.')
elif j == '26.5651':
z = ('324.', '36.', '108.', '180.', '252.')
el... | `z = ('0.')` is not a tuple, therefore your `for k in z` loop will iterate over the characters "0" and ".". Add a comma to tell python you want it to be a tuple:
```
z = ('0.',)
``` |
Python logging incompatibilty between 2.5 and 2.6 | 1,018,527 | 6 | 2009-06-19T15:14:14Z | 1,019,022 | 8 | 2009-06-19T17:03:53Z | [
"python",
"logging",
"incompatibility"
] | Could you help me solve the following incompatibility issue between Python 2.5 and 2.6?
logger.conf:
```
[loggers]
keys=root,aLogger,bLogger
[handlers]
keys=consoleHandler
[formatters]
keys=
[logger_root]
level=NOTSET
handlers=consoleHandler
[logger_aLogger]
level=DEBUG
handlers=consoleHandler
propagate=0
qualnam... | This is a bug which was fixed between 2.5 and 2.6. The fileConfig() function is intended for one-off configuration and so should not be called more than once - however you choose to arrange this. The intended behaviour of fileConfig is to disable any loggers which are not explicitly mentioned in the configuration, and ... |
Speed of calculating powers (in python) | 1,019,740 | 16 | 2009-06-19T19:46:44Z | 1,019,932 | 17 | 2009-06-19T20:33:46Z | [
"python",
"algorithm",
"performance"
] | I'm curious as to why it's so much faster to multiply than to take powers in python (though from what I've read this may well be true in many other languages too). For example it's much faster to do
```
x*x
```
than
```
x**2
```
I suppose the \*\* operator is more general and can also deal with fractional powers. B... | Basically naive multiplication is O(n) with a very low constant factor. Taking the power is O(log n) with a higher constant factor (There are special cases that need to be tested... fractional exponents, negative exponents, etc) . Edit: just to be clear, that's O(n) where n is the exponent.
Of course the naive approac... |
Writing with Python's built-in .csv module | 1,020,053 | 7 | 2009-06-19T21:17:07Z | 1,020,077 | 10 | 2009-06-19T21:23:05Z | [
"python",
"file-io",
"csv",
"python-3.x"
] | [Please note that this is a different question from the already answered [How to replace a column using Pythonâs built-in .csv writer module?](http://stackoverflow.com/questions/1019200/how-to-replace-a-column-using-pythons-built-in-csv-writer-module)]
I need to do a find and replace (specific to one column of URLs)... | You cannot read and write the same file.
```
source = open("PALTemplateData.csv","rb")
reader = csv.reader(source , dialect)
target = open("AnotherFile.csv","wb")
writer = csv.writer(target , dialect)
```
The normal approach to ALL file manipulation is to create a modified COPY of the original file. Don't try to upd... |
Self Referencing Class Definition in python | 1,020,279 | 19 | 2009-06-19T22:14:40Z | 1,020,291 | 21 | 2009-06-19T22:18:31Z | [
"python"
] | is there any way to reference a class name from within the class declaration? an example follows:
```
class Plan(SiloBase):
cost = DataField(int)
start = DataField(System.DateTime)
name = DataField(str)
items = DataCollection(int)
subPlan = ReferenceField(Plan)
```
i've got a metaclass that reads ... | **Try this:**
```
class Plan(SiloBase):
cost = DataField(int)
start = DataField(System.DateTime)
name = DataField(str)
items = DataCollection(int)
Plan.subPlan = ReferenceField(Plan)
```
**OR use `__new__` like this:**
```
class Plan(SiloBase):
def __new__(cls, *args, **kwargs):
cls.cos... |
Self Referencing Class Definition in python | 1,020,279 | 19 | 2009-06-19T22:14:40Z | 1,020,431 | 8 | 2009-06-19T23:15:00Z | [
"python"
] | is there any way to reference a class name from within the class declaration? an example follows:
```
class Plan(SiloBase):
cost = DataField(int)
start = DataField(System.DateTime)
name = DataField(str)
items = DataCollection(int)
subPlan = ReferenceField(Plan)
```
i've got a metaclass that reads ... | > i've got a metaclass that reads this information and does some setup
Most frameworks that use metaclasses provide a way to resolve this. For instance, [Django](http://docs.djangoproject.com/en/1.0/ref/models/fields/#foreignkey):
```
subplan = ForeignKey('self')
```
[Google App Engine](http://code.google.com/appeng... |
How to do PGP in Python (generate keys, encrypt/decrypt) | 1,020,320 | 20 | 2009-06-19T22:28:46Z | 1,053,752 | 22 | 2009-06-27T22:12:35Z | [
"python",
"encryption",
"pgp",
"gnupg"
] | I'm making a program in Python to be distributed to windows users via an installer.
The program needs to be able to download a file every day encrypted with the user's public key and then decrypt it.
So I need to find a Python library that will let me generate public and private PGP keys, and also decrypt files encry... | You don't need `PyCrypto` or `PyMe`, fine though those packages may be - you will have all kinds of problems building under Windows. Instead, why not avoid the rabbit-holes and do what I did? Use `gnupg 1.4.9`. You don't need to do a full installation on end-user machines - just `gpg.exe` and `iconv.dll` from the distr... |
Whatâs the point of inheritance in Python? | 1,020,453 | 69 | 2009-06-19T23:28:18Z | 1,020,479 | 8 | 2009-06-19T23:34:45Z | [
"python",
"oop",
"inheritance"
] | Suppose you have the following situation
```
#include <iostream>
class Animal {
public:
virtual void speak() = 0;
};
class Dog : public Animal {
void speak() { std::cout << "woff!" <<std::endl; }
};
class Cat : public Animal {
void speak() { std::cout << "meow!" <<std::endl; }
};
void makeSpeak(Animal ... | I think the point of inheritance in Python is not to make the code compile, it is for the real reason of inheritance which is extending the class into another child class, and to override the logic in the base class. However the duck typing in Python makes the "interface" concept useless, because you can just check if ... |
Whatâs the point of inheritance in Python? | 1,020,453 | 69 | 2009-06-19T23:28:18Z | 1,020,482 | 76 | 2009-06-19T23:35:48Z | [
"python",
"oop",
"inheritance"
] | Suppose you have the following situation
```
#include <iostream>
class Animal {
public:
virtual void speak() = 0;
};
class Dog : public Animal {
void speak() { std::cout << "woff!" <<std::endl; }
};
class Cat : public Animal {
void speak() { std::cout << "meow!" <<std::endl; }
};
void makeSpeak(Animal ... | You are referring to the run-time duck-typing as "overriding" inheritance, however I believe inheritance has its own merits as a design and implementation approach, being an integral part of object oriented design. In my humble opinion, the question of whether you can achieve something otherwise is not very relevant, b... |
Whatâs the point of inheritance in Python? | 1,020,453 | 69 | 2009-06-19T23:28:18Z | 1,020,889 | 8 | 2009-06-20T03:44:11Z | [
"python",
"oop",
"inheritance"
] | Suppose you have the following situation
```
#include <iostream>
class Animal {
public:
virtual void speak() = 0;
};
class Dog : public Animal {
void speak() { std::cout << "woff!" <<std::endl; }
};
class Cat : public Animal {
void speak() { std::cout << "meow!" <<std::endl; }
};
void makeSpeak(Animal ... | Inheritance in Python is more of a convenience than anything else. I find that it's best used to provide a class with "default behavior."
Indeed, there is a significant community of Python devs who argue against using inheritance at all. Whatever you do, don't just don't overdo it. Having an overly complicated class h... |
Whatâs the point of inheritance in Python? | 1,020,453 | 69 | 2009-06-19T23:28:18Z | 1,020,966 | 10 | 2009-06-20T04:51:10Z | [
"python",
"oop",
"inheritance"
] | Suppose you have the following situation
```
#include <iostream>
class Animal {
public:
virtual void speak() = 0;
};
class Dog : public Animal {
void speak() { std::cout << "woff!" <<std::endl; }
};
class Cat : public Animal {
void speak() { std::cout << "meow!" <<std::endl; }
};
void makeSpeak(Animal ... | Inheritance in Python is all about code reuse. Factorize common functionality into a base class, and implement different functionality in the derived classes. |
Browser automation: Python + Firefox using PyXPCOM | 1,020,524 | 5 | 2009-06-19T23:50:57Z | 1,022,375 | 10 | 2009-06-20T19:42:04Z | [
"python",
"firefox",
"automation"
] | I have tried [Pamie](http://pamie.sourceforge.net/) a browser automation library for internet explorer. It interfaces IE using COM, pretty neat:
```
import PAM30
ie = PAM30.PAMIE("http://user-agent-string.info/")
ie.clickButton("Analyze my UA")
```
Now I would like to do the same thing using [PyXPCOM](https://develop... | I've used [webdriver](http://pypi.python.org/pypi/webdriver/0.5) with firefox. I was very pleased with it.
As for the code examples, [this](http://code.google.com/p/webdriver/wiki/PythonBindings) will get you started. |
Is there a better way to convert a list to a dictionary in Python with keys but no values? | 1,020,722 | 6 | 2009-06-20T01:43:49Z | 1,020,724 | 22 | 2009-06-20T01:48:05Z | [
"python",
"list",
"dictionary",
"list-comprehension"
] | I was sure that there would be a one liner to convert a list to a dictionary where the items in the list were keys and the dictionary had no values.
The only way I could find to do it was argued against.
"Using list comprehensions when the result is ignored is misleading and inefficient. A `for` loop is better"
```
... | Use `dict.fromkeys`:
```
>>> my_list = [1, 2, 3]
>>> dict.fromkeys(my_list)
{1: None, 2: None, 3: None}
```
Values default to `None`, but you can specify them as an optional argument:
```
>>> my_list = [1, 2, 3]
>>> dict.fromkeys(my_list, 0)
{1: 0, 2: 0, 3: 0}
```
From the docs:
> a.fromkeys(seq[, value]) Creates ... |
Is there a better way to convert a list to a dictionary in Python with keys but no values? | 1,020,722 | 6 | 2009-06-20T01:43:49Z | 1,020,728 | 15 | 2009-06-20T01:49:34Z | [
"python",
"list",
"dictionary",
"list-comprehension"
] | I was sure that there would be a one liner to convert a list to a dictionary where the items in the list were keys and the dictionary had no values.
The only way I could find to do it was argued against.
"Using list comprehensions when the result is ignored is misleading and inefficient. A `for` loop is better"
```
... | You could use a [set](http://docs.python.org/library/stdtypes.html#set-types-set-frozenset) instead of a dict:
```
>>> myList=['a','b','c','d']
>>> set(myList)
set(['a', 'c', 'b', 'd'])
```
This is better if you never need to store values, and are just storing an unordered collection of unique items. |
Custom authentication in google app engine (python) | 1,020,736 | 36 | 2009-06-20T01:56:48Z | 1,020,831 | 19 | 2009-06-20T03:03:14Z | [
"python",
"google-app-engine",
"authentication"
] | Does anyone know or know of somewhere I can learn how to create a custom authentication process using python and google app engine?
I don't want to use google accounts for authentication and want to be able to create my own users.
If not specifically for google app engine, any resource on how to implement authenticat... | Well django 1.0 was updated today on Google AppEngine. But you can make user authentication like anything else you just can't really use sessions because it is so massive.
There is a session utility in <http://gaeutilities.appspot.com/>
<http://gaeutilities.appspot.com/session>
<http://code.google.com/p/gaeutilities... |
Custom authentication in google app engine (python) | 1,020,736 | 36 | 2009-06-20T01:56:48Z | 1,020,836 | 8 | 2009-06-20T03:06:55Z | [
"python",
"google-app-engine",
"authentication"
] | Does anyone know or know of somewhere I can learn how to create a custom authentication process using python and google app engine?
I don't want to use google accounts for authentication and want to be able to create my own users.
If not specifically for google app engine, any resource on how to implement authenticat... | The [OpenID consumer](http://code.google.com/p/google-app-engine-samples/source/browse/#svn/trunk/openid-consumer) (part of the excellent "app engine samples" open source project) currently works (despite the warnings in its README, which is old) and would let you use OpenID for your users' logins.
django's [auth](htt... |
Custom authentication in google app engine (python) | 1,020,736 | 36 | 2009-06-20T01:56:48Z | 9,187,632 | 8 | 2012-02-08T03:51:34Z | [
"python",
"google-app-engine",
"authentication"
] | Does anyone know or know of somewhere I can learn how to create a custom authentication process using python and google app engine?
I don't want to use google accounts for authentication and want to be able to create my own users.
If not specifically for google app engine, any resource on how to implement authenticat... | I saw that this pops up in google, every time you search "Custom login in app engine" so
I decided to give an answer that has been serving me.
Here is sample application
<https://github.com/fredrikbonander/Webapp2-Sample-Applications>
This uses
1. webapp2 (already in GAE 1.6.2)
2. Jinja2 (already in GAE 1.6.2)
Webap... |
Custom authentication in google app engine (python) | 1,020,736 | 36 | 2009-06-20T01:56:48Z | 10,318,234 | 10 | 2012-04-25T14:54:34Z | [
"python",
"google-app-engine",
"authentication"
] | Does anyone know or know of somewhere I can learn how to create a custom authentication process using python and google app engine?
I don't want to use google accounts for authentication and want to be able to create my own users.
If not specifically for google app engine, any resource on how to implement authenticat... | This is a pretty out-of-the-box solution, and works pretty well:
<http://code.scotchmedia.com/engineauth/docs/index.html>
It has built-in support for Facebook, Google+, Twitter, LinkedIn, GitHub and OpenId (via Google App Engine).
you just have to redirect the user to `/auth/facebook` or `/auth/google` and so on (thi... |
Python database application frame work and tools | 1,020,775 | 7 | 2009-06-20T02:22:57Z | 1,021,313 | 9 | 2009-06-20T09:37:32Z | [
"python",
"frame"
] | I have been building business database applications such as finance, inventory and other business requirement applications. I am planning to shift to Python. What would be the tools to start with best. I would need to do master, transaction forms, processing (back end), reports and that sort of thing. The database woul... | If I were you, I would probably first look whether a web-based solution based on Django does the trick. If you need a little bit better look and feel, add jQuery to the mix. If it provides way too little functionality, go for PyQt. If you have a lot of very small applications, go for a mix of technologies. Below, you f... |
How to make a simple command-line chat in Python? | 1,020,839 | 10 | 2009-06-20T03:08:03Z | 1,023,232 | 7 | 2009-06-21T04:52:44Z | [
"python"
] | I study network programming and would like to write a simple command-line chat in Python.
I'm wondering how make receving constant along with inputing available for sending at any time.
As you see, this client can do only one job at a time:
```
from socket import *
HOST = 'localhost'
PORT = 21567
BUFSIZE = 1024
ADD... | Your question was not very coherent. However, your program does not need to be asynchronous at all to attain what you are asking for.
This is a working chat script you originally wanted with minimal changes. It uses 1 thread for receiving and 1 for sending, both using blocking sockets. It is far simpler than using asy... |
urllib2 read to Unicode | 1,020,892 | 42 | 2009-06-20T03:46:27Z | 1,020,931 | 90 | 2009-06-20T04:17:41Z | [
"python",
"unicode",
"urllib2"
] | I need to store the content of a site that can be in any language. And I need to be able to search the content for a Unicode string.
I have tried something like:
```
import urllib2
req = urllib2.urlopen('http://lenta.ru')
content = req.read()
```
The content is a byte stream, so I can search it for a Unicode string... | After the operations you performed, you'll see:
```
>>> req.headers['content-type']
'text/html; charset=windows-1251'
```
and so:
```
>>> encoding=req.headers['content-type'].split('charset=')[-1]
>>> ucontent = unicode(content, encoding)
```
`ucontent` is now a Unicode string (of 140655 characters) -- so for examp... |
urllib2 read to Unicode | 1,020,892 | 42 | 2009-06-20T03:46:27Z | 20,714,761 | 8 | 2013-12-21T02:23:33Z | [
"python",
"unicode",
"urllib2"
] | I need to store the content of a site that can be in any language. And I need to be able to search the content for a Unicode string.
I have tried something like:
```
import urllib2
req = urllib2.urlopen('http://lenta.ru')
content = req.read()
```
The content is a byte stream, so I can search it for a Unicode string... | To parse `Content-Type` http header, you could use `cgi.parse_header` function:
```
import cgi
import urllib2
r = urllib2.urlopen('http://lenta.ru')
_, params = cgi.parse_header(r.headers.get('Content-Type', ''))
encoding = params.get('charset', 'utf-8')
unicode_text = r.read().decode(encoding)
```
Another way to ge... |
How to call a property of the base class if this property is being overwritten in the derived class? | 1,021,464 | 50 | 2009-06-20T11:37:14Z | 1,021,477 | 26 | 2009-06-20T11:46:49Z | [
"python",
"inheritance",
"properties",
"overloading",
"descriptor"
] | I'm changing some classes of mine from an extensive use of getters and setters to a more pythonic use of properties.
But now I'm stuck because some of my previous getters or setters would call the corresponding method of the base class, and then perform something else. But how can this be accomplished with properties?... | [Super](http://docs.python.org/3.0/library/functions.html?highlight=super#super) should do the trick:
```
return super().bar
```
In Python 2.x you need to use the more verbose syntax:
```
return super(FooBar, self).bar
``` |
How to call a property of the base class if this property is being overwritten in the derived class? | 1,021,464 | 50 | 2009-06-20T11:37:14Z | 1,021,484 | 55 | 2009-06-20T11:51:38Z | [
"python",
"inheritance",
"properties",
"overloading",
"descriptor"
] | I'm changing some classes of mine from an extensive use of getters and setters to a more pythonic use of properties.
But now I'm stuck because some of my previous getters or setters would call the corresponding method of the base class, and then perform something else. But how can this be accomplished with properties?... | You might think you could call the base class function which is called by property:
```
class FooBar(Foo):
@property
def bar(self):
# return the same value
# as in the base class
return Foo.bar(self)
```
Though this is the most obvious thing to try I think - **it does not work because... |
Generating a 3D CAPTCHA [pic] | 1,021,721 | 11 | 2009-06-20T14:30:17Z | 1,022,263 | 32 | 2009-06-20T19:04:57Z | [
"python",
"graphics",
"captcha"
] | I would like to write a Python script that would generate a 3D [CAPTCHA](http://en.wikipedia.org/wiki/CAPTCHA) like this one:

Which graphics libraries can I use?
Source: [ocr-research.org.ua](http://ocr-research.org.ua/teabag.html) | There are many approaches. I would personally create the image in Python Imaging Library using [ImageDraw](http://www.pythonware.com/library/pil/handbook/imagedraw.htm)'s draw.text, convert to a [NumPy](http://en.wikipedia.org/wiki/NumPy) array (usint NumPy's [asarray](http://effbot.org/zone/pil-changes-116.htm)) then ... |
Best way to randomize a list of strings in Python | 1,022,141 | 64 | 2009-06-20T18:05:44Z | 1,022,145 | 13 | 2009-06-20T18:07:44Z | [
"python",
"string",
"random"
] | I receive as input a list of strings and need to return a list with these same strings but in randomized order. I must allow for duplicates - same string may appear once or more in the input and must appear the same number of times in the output.
I see several "brute force" ways of doing that (using loops, god forbid)... | Looks like this is the simplest way, if not the most truly random ([this question](https://stackoverflow.com/questions/3062741/maximal-length-of-list-to-shuffle-with-python-random-shuffle) more fully explains the limitations): <http://docs.python.org/library/random.html#random.shuffle> |
Best way to randomize a list of strings in Python | 1,022,141 | 64 | 2009-06-20T18:05:44Z | 1,022,151 | 162 | 2009-06-20T18:09:19Z | [
"python",
"string",
"random"
] | I receive as input a list of strings and need to return a list with these same strings but in randomized order. I must allow for duplicates - same string may appear once or more in the input and must appear the same number of times in the output.
I see several "brute force" ways of doing that (using loops, god forbid)... | ```
>>> import random
>>> x = [1, 2, 3, 4, 3, 4]
>>> random.shuffle(x)
>>> x
[4, 4, 3, 1, 2, 3]
>>> random.shuffle(x)
>>> x
[3, 4, 2, 1, 3, 4]
``` |
Commenting code in Notepad++ | 1,022,261 | 67 | 2009-06-20T19:03:15Z | 1,022,265 | 18 | 2009-06-20T19:05:17Z | [
"python",
"comments",
"notepad++"
] | I'm using Notepad++ as an editor to write programs in Python. It might sound daft but I looked around in the editor and could not find any means (not the manual way but something like in Emacs) to do a block comment in my code.
Since so many language settings are supported in Notepad++, I'm curious to find a way to bl... | Try Ctrl+K. |
Commenting code in Notepad++ | 1,022,261 | 67 | 2009-06-20T19:03:15Z | 1,022,270 | 90 | 2009-06-20T19:06:48Z | [
"python",
"comments",
"notepad++"
] | I'm using Notepad++ as an editor to write programs in Python. It might sound daft but I looked around in the editor and could not find any means (not the manual way but something like in Emacs) to do a block comment in my code.
Since so many language settings are supported in Notepad++, I'm curious to find a way to bl... | `CTRL`+`Q` Block comment/uncomment.
More [Notepad++ keyboard shortcuts](http://sourceforge.net/apps/mediawiki/notepad-plus/index.php?title=Keyboard_And_Mouse_Shortcuts). |
Commenting code in Notepad++ | 1,022,261 | 67 | 2009-06-20T19:03:15Z | 4,318,460 | 7 | 2010-11-30T20:49:20Z | [
"python",
"comments",
"notepad++"
] | I'm using Notepad++ as an editor to write programs in Python. It might sound daft but I looked around in the editor and could not find any means (not the manual way but something like in Emacs) to do a block comment in my code.
Since so many language settings are supported in Notepad++, I'm curious to find a way to bl... | for .sql files `Ctrl`+`K` or `Ctrl`+`Q` does not work.
to insert comments in .sql files in Notepad++ try `Ctrl`+`Shift`+`Q`
(there is no shortcut to uncomment the code block though. I have tried that on v5.8.2 ) |
Commenting code in Notepad++ | 1,022,261 | 67 | 2009-06-20T19:03:15Z | 21,064,238 | 9 | 2014-01-11T15:41:17Z | [
"python",
"comments",
"notepad++"
] | I'm using Notepad++ as an editor to write programs in Python. It might sound daft but I looked around in the editor and could not find any means (not the manual way but something like in Emacs) to do a block comment in my code.
Since so many language settings are supported in Notepad++, I'm curious to find a way to bl... | This link was exactly what I was searching for .
Let me summarize the answers for others' benefit (**for python and notepad++**)
1) **Ctrl + K** on multiple lines (i.e. selected region) allows you to ***block comment***.
Also note that pressing the combination multiple times allows you to add multiple "#"s (sometime... |
Emulating membership-test in Python: delegating __contains__ to contained-object correctly | 1,022,499 | 6 | 2009-06-20T20:39:05Z | 1,022,505 | 17 | 2009-06-20T20:42:37Z | [
"python",
"containers",
"delegation",
"emulation",
"iterable"
] | I am used to that Python allows some neat tricks to delegate functionality to other objects. One example is delegation to contained objects.
But it seams, that I don't have luck, when I want to delegate \_\_contains \_\_:
```
class A(object):
def __init__(self):
self.mydict = {}
self.__contains__ = ... | Special methods such as `__contains__` are only special when defined on the class, not on the instance (except in legacy classes in Python 2, which you should *not* use anyway).
So, do your delegation at class level:
```
class A(object):
def __init__(self):
self.mydict = {}
def __contains__(self, othe... |
Weighted slope one algorithm? (porting from Python to R) | 1,022,649 | 7 | 2009-06-20T21:53:56Z | 1,054,561 | 9 | 2009-06-28T08:57:29Z | [
"python",
"prediction",
"recommendation-engine"
] | I was reading about the [Weighted slope one algorithm](http://en.wikipedia.org/wiki/Slope%5FOne#Slope%5Fone%5Fcollaborative%5Ffiltering%5Ffor%5Frated%5Fresources) ( and more
formally [here (PDF)](http://www.daniel-lemire.com/fr/documents/publications/lemiremaclachlan%5Fsdm05.pdf)) which is supposed to take item ratings... | I used the same reference (Bryan O'Sullivan's python code) to write an R version of Slope One a while back. I'm pasting the code below in case it helps.
```
predict <- function(userprefs, data.freqs, data.diffs) {
seen <- names(userprefs)
preds <- sweep(data.diffs[ , seen, drop=FALSE], 2, userprefs, '+')
... |
What classes of applications or problems do you prefer Python to strictly OO Languages? | 1,022,971 | 4 | 2009-06-21T01:50:07Z | 1,023,110 | 10 | 2009-06-21T03:16:41Z | [
"c#",
"java",
"c++",
"python",
"programming-languages"
] | I've got a pretty strong background in C-style languages. And have worked on several different types of projects. I have just started taking a serious look at Python after reading [Programming Collective Intelligence](http://oreilly.com/catalog/9780596529321/). I understand that Python can solve any problem that C# can... | My motto is (and has long been) "Python where I can, C++ where I must" (one day I'll find opportunity to actually use Java, C#, &c &C, in a real-world project, but I haven't yet, except for a pilot project in Java 1.1, more tha ten years ago...;-) -- Javascript (with dojo) when code has to run in the client's browser, ... |
Change process priority in Python, cross-platform | 1,023,038 | 17 | 2009-06-21T02:27:19Z | 1,023,088 | 9 | 2009-06-21T03:01:50Z | [
"python"
] | I've got a Python program that does time-consuming computations. Since it uses high CPU, and I want my system to remain responsive, I'd like the program to change its priority to below-normal.
I found this:
[Set Process Priority In Windows - ActiveState](http://code.activestate.com/recipes/496767/)
But I'm looking fo... | On every Unix-like platform (including Linux and MacOsX), see `os.nice` [here](http://docs.python.org/library/os.html):
```
os.nice(increment)
Add increment to the processâs ânicenessâ. Return the new niceness. Availability: Unix.
```
Since you already have a recipe for Windows, that covers most platforms -- ca... |
Change process priority in Python, cross-platform | 1,023,038 | 17 | 2009-06-21T02:27:19Z | 1,023,269 | 24 | 2009-06-21T05:21:37Z | [
"python"
] | I've got a Python program that does time-consuming computations. Since it uses high CPU, and I want my system to remain responsive, I'd like the program to change its priority to below-normal.
I found this:
[Set Process Priority In Windows - ActiveState](http://code.activestate.com/recipes/496767/)
But I'm looking fo... | Here's the solution I'm using to set my process to below-normal priority:
**`lowpriority.py`**
```
def lowpriority():
""" Set the priority of the process to below-normal."""
import sys
try:
sys.getwindowsversion()
except:
isWindows = False
else:
isWindows = True
if is... |
Change process priority in Python, cross-platform | 1,023,038 | 17 | 2009-06-21T02:27:19Z | 6,245,096 | 12 | 2011-06-05T18:56:37Z | [
"python"
] | I've got a Python program that does time-consuming computations. Since it uses high CPU, and I want my system to remain responsive, I'd like the program to change its priority to below-normal.
I found this:
[Set Process Priority In Windows - ActiveState](http://code.activestate.com/recipes/496767/)
But I'm looking fo... | You can use [psutil](http://code.google.com/p/psutil/wiki/Documentation) module.
On POSIX platforms:
```
>>> import psutil, os
>>> p = psutil.Process(os.getpid())
>>> p.nice()
0
>>> p.nice(10) # set
>>> p.nice()
10
```
On Windows:
```
>>> p.nice(psutil.HIGH_PRIORITY_CLASS)
``` |
How to pickle a CookieJar? | 1,023,224 | 8 | 2009-06-21T04:46:07Z | 1,023,245 | 9 | 2009-06-21T05:01:30Z | [
"python",
"persistence",
"pickle",
"cookiejar",
"cookielib"
] | I have an object with a CookieJar that I want to pickle.
However as you all probably know, pickle chokes on objects that contain lock objects. And for some horrible reason, a CookieJar has a lock object.
```
from cPickle import dumps
from cookielib import CookieJar
class Person(object):
def __init__(self, name):... | Here is an attempt, by deriving a class from CookieJar, which override getstate/setstate used by pickle. I haven't used cookieJar, so don't know if it is usable but you can dump derived class
```
from cPickle import dumps
from cookielib import CookieJar
import threading
class MyCookieJar(CookieJar):
def __getstat... |
How can I have variable assertions in Perl? | 1,023,813 | 6 | 2009-06-21T12:45:21Z | 1,023,839 | 10 | 2009-06-21T12:58:04Z | [
"python",
"perl",
"debugging",
"assertions"
] | How can I check that a variable has a specific value in Perl? Is there a command to stop a script's execution to look up some of it's variables?
I wonder if I can use the Pythonic practice of inserting:
```
assert 0, (foo, bar)
```
to debug scripts in a debuger-less way? | A quick CPAN search suggests [Carp::Assert](http://search.cpan.org/perldoc?Carp::Assert). |
It is possible to match a character repetition with regex? How? | 1,023,902 | 5 | 2009-06-21T13:33:53Z | 1,023,909 | 22 | 2009-06-21T13:38:33Z | [
"python",
"regex"
] | **Question:**
Is is possible, with regex, to match a word that contains the same character in different positions?
**Condition:**
All words have the same length, you know the character positions (example the 1st, the 2nd and the 4th) of the repeated char, but you don't know what is it.
**Examples:**
using lowe... | You can use a backreference to do this:
```
(.)\1
```
This will match consecutive occurrences of any character.
---
**Edit**Â Â Â Hereâs some Python example:
```
import re
regexp = re.compile(r"(.)\1")
data = ["parrot","follia","carrot","mattia","rettoo","melone"]
for str in data:
match = re.search(regexp,... |
Is it pythonic to import inside functions? | 1,024,049 | 41 | 2009-06-21T14:41:00Z | 1,024,087 | 19 | 2009-06-21T14:53:55Z | [
"python",
"conventions"
] | [PEP 8](http://www.python.org/dev/peps/pep-0008/) says:
> * Imports are always put at the top of the file, just after any module
> comments and docstrings, and before module globals and constants.
On occation, I violate PEP 8. Some times I import stuff inside functions. As a general rule, I do this if there is an i... | There are two occasions where I violate PEP 8 in this regard:
* Circular imports: module A imports module B, but something in module B needs module A (though this is often a sign that I need to refactor the modules to eliminate the circular dependency)
* Inserting a pdb breakpoint: `import pdb; pdb.set_trace()` This i... |
Is it pythonic to import inside functions? | 1,024,049 | 41 | 2009-06-21T14:41:00Z | 1,024,139 | 11 | 2009-06-21T15:20:52Z | [
"python",
"conventions"
] | [PEP 8](http://www.python.org/dev/peps/pep-0008/) says:
> * Imports are always put at the top of the file, just after any module
> comments and docstrings, and before module globals and constants.
On occation, I violate PEP 8. Some times I import stuff inside functions. As a general rule, I do this if there is an i... | Here are the four import use cases that we use
1. `import` (and `from x import y` and `import x as y`) at the top
2. Choices for Import. At the top.
```
import settings
if setting.something:
import this as foo
else:
import that as foo
```
3. Conditional Import. Used with JSON, XML librari... |
Is it pythonic to import inside functions? | 1,024,049 | 41 | 2009-06-21T14:41:00Z | 1,025,259 | 31 | 2009-06-22T02:05:00Z | [
"python",
"conventions"
] | [PEP 8](http://www.python.org/dev/peps/pep-0008/) says:
> * Imports are always put at the top of the file, just after any module
> comments and docstrings, and before module globals and constants.
On occation, I violate PEP 8. Some times I import stuff inside functions. As a general rule, I do this if there is an i... | In the long run I think you'll appreciate having most of your imports at the top of the file, that way you can tell at a glance how complicated your module is by what it needs to import.
If I'm adding new code to an existing file I'll usually do the import where it's needed and then if the code stays I'll makes things... |
How to stop Python parse_qs from parsing single values into lists? | 1,024,143 | 22 | 2009-06-21T15:23:35Z | 1,024,164 | 21 | 2009-06-21T15:35:11Z | [
"python",
"python-2.6"
] | In python 2.6, the following code:
```
import urlparse
qsdata = "test=test&test2=test2&test2=test3"
qs = urlparse.parse_qs(qsdata)
print qs
```
Gives the following output:
```
{'test': ['test'], 'test2': ['test2', 'test3']}
```
Which means that even though there is only one value for test, it is still being parsed ... | You could fix it afterwards...
```
import urlparse
qsdata = "test=test&test2=test2&test2=test3"
qs = dict( (k, v if len(v)>1 else v[0] )
for k, v in urlparse.parse_qs(qsdata).iteritems() )
print qs
```
However, I don't think *I* would want this. If a parameter that is normally a list happens to arrive wit... |
How to stop Python parse_qs from parsing single values into lists? | 1,024,143 | 22 | 2009-06-21T15:23:35Z | 8,239,167 | 72 | 2011-11-23T08:35:34Z | [
"python",
"python-2.6"
] | In python 2.6, the following code:
```
import urlparse
qsdata = "test=test&test2=test2&test2=test3"
qs = urlparse.parse_qs(qsdata)
print qs
```
Gives the following output:
```
{'test': ['test'], 'test2': ['test2', 'test3']}
```
Which means that even though there is only one value for test, it is still being parsed ... | A sidenote for someone just wanting a simple dictionary and never needing multiple values with the same key, try:
```
dict(urlparse.parse_qsl('foo=bar&baz=qux'))
```
This will give you a nice `{'foo': 'bar', 'baz': 'qux'}`. Please note that if there *are* multiple values for the same key, you'll only get the last one... |
Can python doctest ignore some output lines? | 1,024,411 | 18 | 2009-06-21T17:54:11Z | 1,024,426 | 30 | 2009-06-21T18:03:19Z | [
"python",
"doctest"
] | I'd like to write a doctest like this:
```
"""
>>> print a.string()
foo : a
bar : b
date : <I don't care about the date output>
baz : c
"""
```
Is there any way to do this? I think it would make more sense to switch to unittest, but I'm curious whether it's possible to specify a... | With `doctest.ELLIPSIS`, you can use `...` to mean "match any string here". You can set `doctest` options with a doctest directive, to make it active for just one test case: one example in the [online docs](http://docs.python.org/library/doctest.html) is:
```
>>> print range(20) # doctest:+ELLIPSIS
[0, 1, ..., 18, 19]... |
How to fix python indentation | 1,024,435 | 185 | 2009-06-21T18:10:18Z | 1,024,463 | 37 | 2009-06-21T18:20:38Z | [
"python"
] | I have some python code that have inconsistent indentation, there is a lot of mixture of tabs and spaces to make the matter even worse even space indentation is not preserved.
The code works as expected but it's difficult to maintain.
How can I fix the indentation (like "html tidy" but for python) without breaking th... | If you're using [Vim](http://www.vim.org/), see [`:h retab`](http://vimdoc.sourceforge.net/htmldoc/change.html#:retab).
```
*:ret* *:retab*
:[range]ret[ab][!] [new_tabstop]
Replace all sequences of white-space containing a
... |
How to fix python indentation | 1,024,435 | 185 | 2009-06-21T18:10:18Z | 1,024,489 | 235 | 2009-06-21T18:36:59Z | [
"python"
] | I have some python code that have inconsistent indentation, there is a lot of mixture of tabs and spaces to make the matter even worse even space indentation is not preserved.
The code works as expected but it's difficult to maintain.
How can I fix the indentation (like "html tidy" but for python) without breaking th... | Use the `reindent.py` script that you find in the `Tools/scripts/` directory of your Python installation:
> Change Python (.py) files to use
> 4-space indents and no hard tab
> characters. Also trim excess spaces
> and tabs from ends of lines, and
> remove empty lines at the end of
> files. Also ensure the last line e... |
How to fix python indentation | 1,024,435 | 185 | 2009-06-21T18:10:18Z | 2,260,185 | 7 | 2010-02-14T04:55:29Z | [
"python"
] | I have some python code that have inconsistent indentation, there is a lot of mixture of tabs and spaces to make the matter even worse even space indentation is not preserved.
The code works as expected but it's difficult to maintain.
How can I fix the indentation (like "html tidy" but for python) without breaking th... | There is also PythonTidy (since you said you like HTMLTidy)
It can be found here: <http://pypi.python.org/pypi/PythonTidy/1.16>
It can do a lot more than just clean up tabs though. If you like that type of thing it's worth a look. |
How to fix python indentation | 1,024,435 | 185 | 2009-06-21T18:10:18Z | 26,643,477 | 21 | 2014-10-30T01:19:35Z | [
"python"
] | I have some python code that have inconsistent indentation, there is a lot of mixture of tabs and spaces to make the matter even worse even space indentation is not preserved.
The code works as expected but it's difficult to maintain.
How can I fix the indentation (like "html tidy" but for python) without breaking th... | I would reach for [autopep8](https://pypi.python.org/pypi/autopep8) to do this:
```
$ # see what changes it would make
$ autopep8 path/to/file.py --select=E101,E121 --diff
$ # make these changes
$ autopep8 path/to/file.py --select=E101,E121 --in-place
```
*Note: [E101 and E121](https://github.com/hhatto/autopep8#fea... |
Perl's AUTOLOAD in Python (__getattr__ on a module) | 1,024,455 | 14 | 2009-06-21T18:17:47Z | 1,024,468 | 10 | 2009-06-21T18:24:23Z | [
"python",
"module",
"autoload",
"getattr"
] | In the past I've used perl's AUTOLOAD facility for implementing lazy loading of symbols into a namespace, and wanted the same functionality in python.
Traditionally the closest you appear to be able to get is to use a class and a `__getattr__` class to achieve this sort of thing. However I've also tried rummaging arou... | "Lazy imports" could be built on top of the "new import hooks" specified in [PEP 302](http://www.python.org/dev/peps/pep-0302/), and now fully implemented. PEP 369 used to cover "lazy imports" as well as post-import hooks, but has since been simplified and now only covers post-import hooks; still, you might be interest... |
Add key to a dictionary in Python? | 1,024,847 | 1,201 | 2009-06-21T22:07:39Z | 1,024,850 | 60 | 2009-06-21T22:08:57Z | [
"python",
"dictionary"
] | Is it possible to add a key to a Python dictionary after it has been created? It doesn't seem to have an `.add()` method. | ```
dictionary[key] = value
``` |
Add key to a dictionary in Python? | 1,024,847 | 1,201 | 2009-06-21T22:07:39Z | 1,024,851 | 1,611 | 2009-06-21T22:09:06Z | [
"python",
"dictionary"
] | Is it possible to add a key to a Python dictionary after it has been created? It doesn't seem to have an `.add()` method. | ```
>>> d = {'key':'value'}
>>> print d
{'key': 'value'}
>>> d['mynewkey'] = 'mynewvalue'
>>> print d
{'mynewkey': 'mynewvalue', 'key': 'value'}
``` |
Add key to a dictionary in Python? | 1,024,847 | 1,201 | 2009-06-21T22:07:39Z | 1,024,852 | 95 | 2009-06-21T22:09:09Z | [
"python",
"dictionary"
] | Is it possible to add a key to a Python dictionary after it has been created? It doesn't seem to have an `.add()` method. | Yeah, it's pretty easy. Just do the following:
```
dict["key"] = "value"
``` |
Add key to a dictionary in Python? | 1,024,847 | 1,201 | 2009-06-21T22:07:39Z | 1,165,836 | 658 | 2009-07-22T14:48:17Z | [
"python",
"dictionary"
] | Is it possible to add a key to a Python dictionary after it has been created? It doesn't seem to have an `.add()` method. | ```
>>> x = {1:2}
>>> print x
{1: 2}
>>> x.update({3:4})
>>> print x
{1: 2, 3: 4}
``` |
Add key to a dictionary in Python? | 1,024,847 | 1,201 | 2009-06-21T22:07:39Z | 8,381,589 | 268 | 2011-12-05T06:07:36Z | [
"python",
"dictionary"
] | Is it possible to add a key to a Python dictionary after it has been created? It doesn't seem to have an `.add()` method. | I feel like consolidating info about Python dictionaries:
```
### Making a dictionary ###
data = {}
# OR
data = dict()
### Initially adding values ###
data = {'a':1,'b':2,'c':3}
# OR
data = dict(a=1, b=2, c=3)
### Inserting/Updating value ###
data['a']=1 # updates if 'a' exists, else adds 'a'
# OR
data.update({'... |
Add key to a dictionary in Python? | 1,024,847 | 1,201 | 2009-06-21T22:07:39Z | 8,381,704 | 12 | 2011-12-05T06:26:24Z | [
"python",
"dictionary"
] | Is it possible to add a key to a Python dictionary after it has been created? It doesn't seem to have an `.add()` method. | ```
data = {}
data['a'] = 'A'
data['b'] = 'B'
for key, value in data.iteritems():
print "%s-%s" % (key, value)
```
results in
```
a-A
b-B
``` |
Add key to a dictionary in Python? | 1,024,847 | 1,201 | 2009-06-21T22:07:39Z | 10,339,748 | 26 | 2012-04-26T19:04:33Z | [
"python",
"dictionary"
] | Is it possible to add a key to a Python dictionary after it has been created? It doesn't seem to have an `.add()` method. | If you want to add a dictionary within a dictionary you can do it this way.
Example: Add a new entry to your dictionary & sub dictionary
```
dictionary = {}
dictionary["new key"] = "some new entry" # add new dictionary entry
dictionary["dictionary_within_a_dictionary"] = {} # this is required by python
dictionary["di... |
Add key to a dictionary in Python? | 1,024,847 | 1,201 | 2009-06-21T22:07:39Z | 15,994,607 | 24 | 2013-04-14T00:58:27Z | [
"python",
"dictionary"
] | Is it possible to add a key to a Python dictionary after it has been created? It doesn't seem to have an `.add()` method. | The orthodox syntax is `d[key] = value`, but if your keyboard is missing the square bracket keys you could do:
```
d.__setitem__(key, value)
```
In fact, defining `__getitem__` and `__setitem__` methods is how you can make your own class support the square bracket syntax. See <http://www.diveintopython.net/object_ori... |
Add key to a dictionary in Python? | 1,024,847 | 1,201 | 2009-06-21T22:07:39Z | 16,750,088 | 17 | 2013-05-25T13:33:35Z | [
"python",
"dictionary"
] | Is it possible to add a key to a Python dictionary after it has been created? It doesn't seem to have an `.add()` method. | you can create one
```
class myDict(dict):
def __init__(self):
self = dict()
def add(self, key, value):
self[key] = value
## example
myd = myDict()
myd.add('apples',6)
myd.add('bananas',3)
print(myd)
```
gives
```
>>>
{'apples': 6, 'bananas': 3}
``` |
Add key to a dictionary in Python? | 1,024,847 | 1,201 | 2009-06-21T22:07:39Z | 18,294,122 | 14 | 2013-08-17T23:04:12Z | [
"python",
"dictionary"
] | Is it possible to add a key to a Python dictionary after it has been created? It doesn't seem to have an `.add()` method. | [This popular question](http://stackoverflow.com/questions/38987/how-can-i-merge-union-two-python-dictionaries-in-a-single-expression) addresses *functional* methods of merging dictionaries `a` and `b`.
Here are some of the more straightforward methods (tested in Python 3)...
```
c = dict( a, **b ) ## see also http:/... |
Add key to a dictionary in Python? | 1,024,847 | 1,201 | 2009-06-21T22:07:39Z | 27,208,535 | 42 | 2014-11-29T23:57:59Z | [
"python",
"dictionary"
] | Is it possible to add a key to a Python dictionary after it has been created? It doesn't seem to have an `.add()` method. | > # "Is it possible to add a key to a Python dictionary after it has been created? It doesn't seem to have an .add() method."
Yes it is possible, and it does have a method that implements this, but you don't want to use it directly.
To demonstrate how and how not to use it, let's create an empty dict with the dict li... |
How to use win32 API's with python? | 1,025,029 | 45 | 2009-06-21T23:37:04Z | 1,025,056 | 15 | 2009-06-21T23:51:31Z | [
"python",
"winapi",
"api"
] | How can I use win32 API in Python?
What is the best and easiest way to do it?
Can you please provide some examples? | PyWin32, as mentioned by @chaos, is probably the most popular choice; the alternative is [ctypes](http://docs.python.org/library/ctypes.html) which is part of Python's standard library. For example, `print ctypes.windll.kernel32.GetModuleHandleA(None)` will show the module-handle of the current module (EXE or DLL). A m... |
How to use win32 API's with python? | 1,025,029 | 45 | 2009-06-21T23:37:04Z | 1,025,331 | 32 | 2009-06-22T03:04:13Z | [
"python",
"winapi",
"api"
] | How can I use win32 API in Python?
What is the best and easiest way to do it?
Can you please provide some examples? | PyWin32 is the way to go - but how to use it? One approach is to begin with a concrete problem you're having and attempting to solve it. PyWin32 provides bindings for the Win32 API functions for which there are many, and you really have to pick a specific goal first.
In my Python 2.5 installation (ActiveState on Windo... |
Units conversion in Python | 1,025,145 | 11 | 2009-06-22T00:41:10Z | 1,025,173 | 8 | 2009-06-22T01:00:47Z | [
"python",
"math",
"symbolic-math",
"sympy"
] | [SymPy](http://en.wikipedia.org/wiki/SymPy) is a great tool for doing units conversions in Python:
```
>>> from sympy.physics import units
>>> 12. * units.inch / units.m
0.304800000000000
```
You can easily roll your own:
```
>>> units.BTU = 1055.05585 * units.J
>>> units.BTU
1055.05585*m**2*kg/s**2
```
However, I ... | The Unum documentation has a pretty good writeup on why this is hard:
> Unum is unable to handle reliably conversions between °Celsius and Kelvin. The issue is referred as the 'false origin problem' : the 0°Celsius is defined as 273.15 K. This is really a special and annoying case, since in general the value 0 is un... |
With Python's optparse module, how do you create an option that takes a variable number of arguments? | 1,025,214 | 10 | 2009-06-22T01:28:04Z | 1,025,230 | 9 | 2009-06-22T01:40:37Z | [
"python",
"optparse"
] | With Perl's `Getopt::Long` you can easily define command-line options that take a variable number of arguments:
```
foo.pl --files a.txt --verbose
foo.pl --files a.txt b.txt c.txt --verbose
```
Is there a way to do this directly with Python's `optparse` module? As far as I can tell, the `nargs` option att... | My mistake: just found this [Callback Example 6](http://docs.python.org/library/optparse.html#callback-example-6-variable-arguments). |
With Python's optparse module, how do you create an option that takes a variable number of arguments? | 1,025,214 | 10 | 2009-06-22T01:28:04Z | 1,025,232 | 8 | 2009-06-22T01:41:19Z | [
"python",
"optparse"
] | With Perl's `Getopt::Long` you can easily define command-line options that take a variable number of arguments:
```
foo.pl --files a.txt --verbose
foo.pl --files a.txt b.txt c.txt --verbose
```
Is there a way to do this directly with Python's `optparse` module? As far as I can tell, the `nargs` option att... | I believe `optparse` does not support what you require (not directly -- as you noticed, you can do it if you're willing to do all the extra work of a callback!-). You could also do it most simply with the third-party extension [argparse](http://code.google.com/p/argparse/), which does support variable numbers of argume... |
With Python's optparse module, how do you create an option that takes a variable number of arguments? | 1,025,214 | 10 | 2009-06-22T01:28:04Z | 2,205,552 | 20 | 2010-02-05T07:06:31Z | [
"python",
"optparse"
] | With Perl's `Getopt::Long` you can easily define command-line options that take a variable number of arguments:
```
foo.pl --files a.txt --verbose
foo.pl --files a.txt b.txt c.txt --verbose
```
Is there a way to do this directly with Python's `optparse` module? As far as I can tell, the `nargs` option att... | This took me a little while to figure out, but you can use the callback action to your options to get this done. Checkout how I grab an arbitrary number of args to the "--file" flag in this example.
```
from optparse import OptionParser,
def cb(option, opt_str, value, parser):
args=[]
for arg in parse... |
Decimal alignment formatting in Python | 1,025,379 | 5 | 2009-06-22T03:34:16Z | 1,025,528 | 7 | 2009-06-22T05:07:44Z | [
"python",
"formatting",
"numpy",
"code-golf"
] | This *should* be easy.
Here's my array (rather, a method of generating representative test arrays):
```
>>> ri = numpy.random.randint
>>> ri2 = lambda x: ''.join(ri(0,9,x).astype('S'))
>>> a = array([float(ri2(x)+ '.' + ri2(y)) for x,y in ri(1,10,(10,2))])
>>> a
array([ 7.99914000e+01, 2.08000000e+01, 3.94000000... | Sorry, but after thorough investigation I can't find any way to perform the task you require without a minimum of post-processing (to strip off the trailing zeros you don't want to see); something like:
```
import re
ut0 = re.compile(r'(\d)0+$')
thelist = [ut0.sub(r'\1', "%12f" % x) for x in a]
print '\n'.join(theli... |
sqlite version for python26 | 1,025,493 | 2 | 2009-06-22T04:49:30Z | 1,025,591 | 9 | 2009-06-22T05:36:23Z | [
"python",
"sqlite",
"python-2.6"
] | which versions of sqlite may best suite for python 2.6.2? | If your Python distribution already comes with a copy of sqlite (such as the Windows distribution, or Debian), this is the version you should use.
If you compile sqlite yourself, you should use the version that is recommended by the [sqlite authors](http://www.sqlite.org/) (currently 3.6.15). |
Cross-platform way to check admin rights in a Python script under Windows? | 1,026,431 | 11 | 2009-06-22T10:20:32Z | 1,026,626 | 26 | 2009-06-22T11:22:56Z | [
"python",
"privileges",
"admin-rights"
] | Is there any cross-platform way to check that my Python script is executed with admin rights? Unfortunately, `os.getuid()` is UNIX-only and is not available under Windows. | ```
import ctypes, os
try:
is_admin = os.getuid() == 0
except AttributeError:
is_admin = ctypes.windll.shell32.IsUserAnAdmin() != 0
print is_admin
``` |
Algorithms for named entity recognition | 1,026,925 | 19 | 2009-06-22T12:26:33Z | 1,027,336 | 13 | 2009-06-22T13:53:39Z | [
"php",
"python",
"extract",
"analysis",
"named-entity-recognition"
] | I would like to use named entity recognition (NER) to find adequate tags for texts in a database.
I know there is a Wikipedia article about this and lots of other pages describing NER, I would preferably hear something about this topic from you:
* What experiences did you make with the various algorithms?
* Which alg... | To start with check out <http://www.nltk.org/> if you plan working with python although as far as I know the code isn't "industrial strength" but it will get you started.
Check out section 7.5 from <http://nltk.googlecode.com/svn/trunk/doc/book/ch07.html> but to understand the algorithms you probably will have to read... |
How can I make sure all my Python code "compiles"? | 1,026,966 | 14 | 2009-06-22T12:36:18Z | 1,026,985 | 21 | 2009-06-22T12:39:34Z | [
"python",
"parsing",
"code-analysis"
] | My background is C and C++. I like Python a lot, but there's one aspect of it (and other interpreted languages I guess) that is really hard to work with when you're used to compiled languages.
When I've written something in Python and come to the point where I can run it, there's still no guarantee that no language-sp... | Look at [PyChecker](http://pychecker.sourceforge.net/) and [PyLint](http://www.logilab.org/857).
Here's example output from pylint, resulting from the trivial program:
```
print a
```
As you can see, it detects the undefined variable, which py\_compile won't (deliberately).
```
in foo.py:
************* Module foo
... |
How to execute a file within the python interpreter? | 1,027,714 | 132 | 2009-06-22T15:05:00Z | 1,027,730 | 101 | 2009-06-22T15:07:10Z | [
"python"
] | I'm trying to execute a file with python commands from within the interpreter.
EDIT: I'm trying to use variables and settings from that file, not to invoke a separate process. | ```
>>> execfile('filename.py')
```
See [the documentation](http://docs.python.org/library/functions.html#execfile). If you are using Python 3.0, see [this question](http://stackoverflow.com/questions/436198/what-is-an-alternative-to-execfile-in-python-3-0).
See answer by @S.Lott for an example of how you access glob... |
How to execute a file within the python interpreter? | 1,027,714 | 132 | 2009-06-22T15:05:00Z | 1,027,739 | 144 | 2009-06-22T15:08:38Z | [
"python"
] | I'm trying to execute a file with python commands from within the interpreter.
EDIT: I'm trying to use variables and settings from that file, not to invoke a separate process. | Several ways.
From the shell
```
python someFile.py
```
From inside IDLE, hit **F5**.
If you're typing interactively, try this.
```
>>> variables= {}
>>> execfile( "someFile.py", variables )
>>> print variables # globals from the someFile module
``` |
How to execute a file within the python interpreter? | 1,027,714 | 132 | 2009-06-22T15:05:00Z | 1,028,096 | 20 | 2009-06-22T16:18:11Z | [
"python"
] | I'm trying to execute a file with python commands from within the interpreter.
EDIT: I'm trying to use variables and settings from that file, not to invoke a separate process. | > I'm trying to use variables and settings from that file, not to invoke a separate process.
Well, simply importing the file with `import filename` (minus .py, needs to be in the same directory or on your `PYTHONPATH`) will run the file, making its variables, functions, classes, etc. available in the `filename.variabl... |
How to execute a file within the python interpreter? | 1,027,714 | 132 | 2009-06-22T15:05:00Z | 20,010,963 | 7 | 2013-11-15T21:31:19Z | [
"python"
] | I'm trying to execute a file with python commands from within the interpreter.
EDIT: I'm trying to use variables and settings from that file, not to invoke a separate process. | I am not an expert but this is what I noticed:
if your code is mycode.py for instance, and you type just 'import mycode', Python will execute it but it will not make all your variables available to the interpreter. I found that you should type actually 'from mycode import \*' if you want to make all variables availabl... |
How to execute a file within the python interpreter? | 1,027,714 | 132 | 2009-06-22T15:05:00Z | 31,566,843 | 21 | 2015-07-22T14:58:25Z | [
"python"
] | I'm trying to execute a file with python commands from within the interpreter.
EDIT: I'm trying to use variables and settings from that file, not to invoke a separate process. | ## Python 2 + Python 3
```
exec(open("./path/to/script.py").read(), globals())
```
This will execute a script and put all it's global variables in the interpreter's global scope (the normal behavior in most other languages).
[Python 3 `exec` Documentation](https://docs.python.org/3/library/functions.html#exec) |
Detect if X11 is available (python) | 1,027,894 | 4 | 2009-06-22T15:38:45Z | 1,027,907 | 8 | 2009-06-22T15:41:25Z | [
"python",
"user-interface"
] | Firstly, what is the best/simplest way to detect if X11 is running and available for a python script.
parent process?
session leader?
X environment variables?
other?
Secondly, I would like to have a utility (python script) to present a gui if available, otherwise use a command line backed tool.
Off the top of ... | I'd check to see if DISPLAY is set ( this is what C API X11 applications do after all ). |
Is python a stable platform for facebook development? | 1,027,990 | 7 | 2009-06-22T15:57:26Z | 1,028,027 | 13 | 2009-06-22T16:04:39Z | [
"python",
"api",
"facebook"
] | I'm trying to build my first facebook app, and it seems that the python facebook ([pyfacebook](http://code.google.com/p/pyfacebook/)) wrapper is really out of date, and the most relevant functions, like stream functions, are not implemented.
Are there any mature python frontends for facebook? If not, what's the best l... | The updated location of pyfacebook is [on github](http://github.com/sciyoshi/pyfacebook/tree/master). Plus, as [arstechnica](http://arstechnica.com/open-source/news/2009/04/how-to-using-the-new-facebook-stream-api-in-a-desktop-app.ars) well explains:
> PyFacebook is also very easy to extend
> when new Facebook API met... |
Is python a stable platform for facebook development? | 1,027,990 | 7 | 2009-06-22T15:57:26Z | 4,034,156 | 11 | 2010-10-27T14:08:22Z | [
"python",
"api",
"facebook"
] | I'm trying to build my first facebook app, and it seems that the python facebook ([pyfacebook](http://code.google.com/p/pyfacebook/)) wrapper is really out of date, and the most relevant functions, like stream functions, are not implemented.
Are there any mature python frontends for facebook? If not, what's the best l... | Facebook's own Python-SDK covers the newer Graph API now:
<http://github.com/facebook/python-sdk/> |
Conditional Django Middleware (or how to exclude the Admin System) | 1,028,019 | 13 | 2009-06-22T16:03:21Z | 3,204,374 | 24 | 2010-07-08T14:04:44Z | [
"python",
"django",
"django-admin",
"django-middleware"
] | I want to use some middleware I wrote across the whole of my site (large # of pages, so I chose not to use decorators as I wanted to use the code for all pages). Only issue is that I don't want to use the middleware for the admin code, and it seems to be active on them.
Is there any way I can configure the settings.py... | A general way would be (based on piquadrat's answer)
```
def process_request(self, request):
if request.path.startswith(reverse('admin:index')):
return None
# rest of method
```
This way if someone changes `/admin/` to `/django_admin/` you are still covered. |
Stop execution of a script called with execfile | 1,028,609 | 9 | 2009-06-22T17:58:34Z | 1,028,632 | 14 | 2009-06-22T18:04:03Z | [
"python",
"flow-control",
"execfile"
] | Is it possible to break the execution of a Python script called with the execfile function without using an if/else statement? I've tried `exit()`, but it doesn't allow `main.py` to finish.
```
# main.py
print "Main starting"
execfile("script.py")
print "This should print"
# script.py
print "Script starting"
a = Fals... | `main` can wrap the `execfile` into a `try`/`except` block: `sys.exit` raises a SystemExit exception which `main` can catch in the `except` clause in order to continue its execution normally, if desired. I.e., in `main.py`:
```
try:
execfile('whatever.py')
except SystemExit:
print "sys.exit was called but I'm proc... |
Python MySQLdb update query fails | 1,028,671 | 13 | 2009-06-22T18:14:45Z | 1,028,681 | 16 | 2009-06-22T18:17:32Z | [
"python",
"mysql"
] | Okay. I've built here a mysql query browser, like navicat. Using MySQLdb to perform queries.
Here's the weird part. When i run the query through the program(using MySQLdb), it gives me success, affected rows = 1, but when i look at it in phpmyadmin, the value hasn't changed.
so before i perform the query, i print it ... | Just a guess: Perhaps the code in Python is running within a transaction, and the transaction might need to be explicitly committed?
Edit: There's an [entry in the MySQLdb FAQ](http://mysql-python.sourceforge.net/FAQ.html#my-data-disappeared-or-won-t-go-away) that might be relevant. |
Python MySQLdb update query fails | 1,028,671 | 13 | 2009-06-22T18:14:45Z | 1,029,016 | 19 | 2009-06-22T19:33:48Z | [
"python",
"mysql"
] | Okay. I've built here a mysql query browser, like navicat. Using MySQLdb to perform queries.
Here's the weird part. When i run the query through the program(using MySQLdb), it gives me success, affected rows = 1, but when i look at it in phpmyadmin, the value hasn't changed.
so before i perform the query, i print it ... | I believe @Jason Creighton and @S.Lott are correct.
At least if the table that you're updating is on a transactional storage engine. `InnoDB` is transactional, `ISAM` is not.
You either have to call `commit()` on your connection object before closing it, or you must set the connection to autocommit mode. I am not sur... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.