title
stringlengths 10
172
| question_id
int64 469
40.1M
| question_body
stringlengths 22
48.2k
| question_score
int64 -44
5.52k
| question_date
stringlengths 20
20
| answer_id
int64 497
40.1M
| answer_body
stringlengths 18
33.9k
| answer_score
int64 -38
8.38k
| answer_date
stringlengths 20
20
| tags
list |
|---|---|---|---|---|---|---|---|---|---|
Deleting multiple elements from a list
| 497,426
|
<p>Is it possible to delete multiple elements from a list at the same time? If I want to delete elements at index 0 and 2, and try something like del somelist[0], followed by del somelist[2], the second statement will actually delete somelist[3].</p>
<p>I suppose I could always delete the higher numbered elements first but I'm hoping there is a better way.</p>
| 78
|
2009-01-30T21:59:38Z
| 37,099,440
|
<p>For the indices 0 and 2 from listA:</p>
<pre><code>for x in (2,0): listA.pop(x)
</code></pre>
<p>For some random indices to remove from listA: </p>
<pre><code>indices=(5,3,2,7,0)
for x in sorted(indices)[::-1]: listA.pop(x)
</code></pre>
| 0
|
2016-05-08T11:43:42Z
|
[
"python",
"list"
] |
Deleting multiple elements from a list
| 497,426
|
<p>Is it possible to delete multiple elements from a list at the same time? If I want to delete elements at index 0 and 2, and try something like del somelist[0], followed by del somelist[2], the second statement will actually delete somelist[3].</p>
<p>I suppose I could always delete the higher numbered elements first but I'm hoping there is a better way.</p>
| 78
|
2009-01-30T21:59:38Z
| 37,907,748
|
<p>To generalize the comment from <a href="http://stackoverflow.com/users/56338/sth">@sth</a>. Item deletion in any class, that implements <a href="https://docs.python.org/3/library/collections.abc.html#collections.abc.MutableSequence" rel="nofollow">abc.MutableSequence</a>, and in <code>list</code> in particular, is done via <code>__delitem__</code> magic method. This method works similar to <code>__getitem__</code>, meaning it can accept either an integer or a slice. Here is an example:</p>
<pre><code>class MyList(list):
def __delitem__(self, item):
if isinstance(item, slice):
for i in range(*item.indices(len(self))):
self[i] = 'null'
else:
self[item] = 'null'
l = MyList(range(10))
print(l)
del l[5:8]
print(l)
</code></pre>
<p>This will output</p>
<pre><code>[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 1, 2, 3, 4, 'null', 'null', 'null', 8, 9]
</code></pre>
| 0
|
2016-06-19T13:28:05Z
|
[
"python",
"list"
] |
Deleting multiple elements from a list
| 497,426
|
<p>Is it possible to delete multiple elements from a list at the same time? If I want to delete elements at index 0 and 2, and try something like del somelist[0], followed by del somelist[2], the second statement will actually delete somelist[3].</p>
<p>I suppose I could always delete the higher numbered elements first but I'm hoping there is a better way.</p>
| 78
|
2009-01-30T21:59:38Z
| 39,328,831
|
<p>Importing it only for this reason might be overkill, but if you happen to be using <code>pandas</code> anyway, then the solution is simple and straightforward:</p>
<pre><code>import pandas as pd
stuff = pd.Series(['a','b','a','c','a','d'])
less_stuff = stuff[stuff != 'a'] # define any condition here
# results ['b','c','d']
</code></pre>
| 0
|
2016-09-05T10:39:38Z
|
[
"python",
"list"
] |
Django workflow when modifying models frequently?
| 497,654
|
<p>as I usually don't do the up front design of my models in Django projects I end up modifying the models a lot and thus deleting my test database every time (because "syncdb" won't ever alter the tables automatically for you). Below lies my workflow and I'd like to hear about yours. Any thoughts welcome.. </p>
<ol>
<li>Modify the model.</li>
<li>Delete the test database. (always a simple sqlite database for me.)</li>
<li>Run "syncdb".</li>
<li>Generate some test data via code.</li>
<li>goto 1.</li>
</ol>
<p>A secondary question regarding this.. In case your workflow is like above, how do you execute the 4. step? Do you generate the test data manually or is there a proper hook point in Django apps where you can inject the test-data-generating-code at server startup?\</p>
<p>TIA.</p>
| 24
|
2009-01-30T23:18:54Z
| 497,687
|
<p>Steps 2 & 3 can be done in one step:</p>
<pre><code>manage.py reset appname
</code></pre>
<p>Step 4 is most easily managed, from my understanding, by using <a href="http://www.djangoproject.com/documentation/models/fixtures/">fixtures</a></p>
| 21
|
2009-01-30T23:29:45Z
|
[
"python",
"django",
"django-models",
"workflow",
"django-syncdb"
] |
Django workflow when modifying models frequently?
| 497,654
|
<p>as I usually don't do the up front design of my models in Django projects I end up modifying the models a lot and thus deleting my test database every time (because "syncdb" won't ever alter the tables automatically for you). Below lies my workflow and I'd like to hear about yours. Any thoughts welcome.. </p>
<ol>
<li>Modify the model.</li>
<li>Delete the test database. (always a simple sqlite database for me.)</li>
<li>Run "syncdb".</li>
<li>Generate some test data via code.</li>
<li>goto 1.</li>
</ol>
<p>A secondary question regarding this.. In case your workflow is like above, how do you execute the 4. step? Do you generate the test data manually or is there a proper hook point in Django apps where you can inject the test-data-generating-code at server startup?\</p>
<p>TIA.</p>
| 24
|
2009-01-30T23:18:54Z
| 497,696
|
<p>This is a job for Django's fixtures. They are convenient because they are database independent and the test harness (and manage.py) have built-in support for them.</p>
<p>To use them:</p>
<ol>
<li>Set up your data in your app (call
it "foo") using the admin tool</li>
<li>Create a fixtures directory in your
"foo" app directory</li>
<li>Type: <code>python manage.py dumpdata --indent=4 foo > foo/fixtures/foo.json</code></li>
</ol>
<p>Now, after your syncdb stage, you just type:</p>
<pre><code> python manage.py loaddata foo.json
</code></pre>
<p>And your data will be re-created.</p>
<p>If you want them in a test case:</p>
<pre><code>class FooTests(TestCase):
fixtures = ['foo.json']
</code></pre>
<p>Note that you will have to recreate or manually update your fixtures if your schema changes drastically.</p>
<p>You can read more about fixtures in the django docs for <a href="http://docs.djangoproject.com/en/dev/topics/testing/#fixture-loading" rel="nofollow">Fixture Loading</a></p>
| 14
|
2009-01-30T23:32:02Z
|
[
"python",
"django",
"django-models",
"workflow",
"django-syncdb"
] |
Django workflow when modifying models frequently?
| 497,654
|
<p>as I usually don't do the up front design of my models in Django projects I end up modifying the models a lot and thus deleting my test database every time (because "syncdb" won't ever alter the tables automatically for you). Below lies my workflow and I'd like to hear about yours. Any thoughts welcome.. </p>
<ol>
<li>Modify the model.</li>
<li>Delete the test database. (always a simple sqlite database for me.)</li>
<li>Run "syncdb".</li>
<li>Generate some test data via code.</li>
<li>goto 1.</li>
</ol>
<p>A secondary question regarding this.. In case your workflow is like above, how do you execute the 4. step? Do you generate the test data manually or is there a proper hook point in Django apps where you can inject the test-data-generating-code at server startup?\</p>
<p>TIA.</p>
| 24
|
2009-01-30T23:18:54Z
| 498,092
|
<p>Here's what we do.</p>
<ol>
<li><p>Apps are named with a Schema version number. <code>appa_2</code>, <code>appb_1</code>, etc.</p></li>
<li><p>Minor changes don't change the number.</p></li>
<li><p>Major changes increment the number. Syncdb works. And a "data migration" script can be written.</p>
<pre><code>def migrate_appa_2_to_3():
for a in appa_2.SomeThing.objects.all():
appa_3.AnotherThing.create( a.this, a.that )
appa_3.NewThing.create( a.another, a.yetAnother )
for b in ...
</code></pre></li>
</ol>
<p>The point is that drop and recreate isn't always appropriate. It's sometimes helpful to move data form the old model to the new model without rebuilding from scratch.</p>
| 12
|
2009-01-31T02:39:00Z
|
[
"python",
"django",
"django-models",
"workflow",
"django-syncdb"
] |
Django workflow when modifying models frequently?
| 497,654
|
<p>as I usually don't do the up front design of my models in Django projects I end up modifying the models a lot and thus deleting my test database every time (because "syncdb" won't ever alter the tables automatically for you). Below lies my workflow and I'd like to hear about yours. Any thoughts welcome.. </p>
<ol>
<li>Modify the model.</li>
<li>Delete the test database. (always a simple sqlite database for me.)</li>
<li>Run "syncdb".</li>
<li>Generate some test data via code.</li>
<li>goto 1.</li>
</ol>
<p>A secondary question regarding this.. In case your workflow is like above, how do you execute the 4. step? Do you generate the test data manually or is there a proper hook point in Django apps where you can inject the test-data-generating-code at server startup?\</p>
<p>TIA.</p>
| 24
|
2009-01-30T23:18:54Z
| 498,098
|
<p>To add to Matthew's response, I often also use custom SQL to provide initial data as documented <a href="http://docs.djangoproject.com/en/dev/howto/initial-data/#providing-initial-sql-data" rel="nofollow">here</a>.</p>
<p>Django just looks for files in <code><app>/sql/<modelname>.sql</code> and runs them after creating tables during <code>syncdb</code> or <code>sqlreset</code>. I use custom SQL when I need to do something like populate my Django tables from other non-Django database tables.</p>
| 3
|
2009-01-31T02:43:29Z
|
[
"python",
"django",
"django-models",
"workflow",
"django-syncdb"
] |
Django workflow when modifying models frequently?
| 497,654
|
<p>as I usually don't do the up front design of my models in Django projects I end up modifying the models a lot and thus deleting my test database every time (because "syncdb" won't ever alter the tables automatically for you). Below lies my workflow and I'd like to hear about yours. Any thoughts welcome.. </p>
<ol>
<li>Modify the model.</li>
<li>Delete the test database. (always a simple sqlite database for me.)</li>
<li>Run "syncdb".</li>
<li>Generate some test data via code.</li>
<li>goto 1.</li>
</ol>
<p>A secondary question regarding this.. In case your workflow is like above, how do you execute the 4. step? Do you generate the test data manually or is there a proper hook point in Django apps where you can inject the test-data-generating-code at server startup?\</p>
<p>TIA.</p>
| 24
|
2009-01-30T23:18:54Z
| 498,100
|
<p>Personally my development db is for a project I'm working on right now is rather large, so I use <a href="http://code.google.com/p/dmigrations/" rel="nofollow">dmigrations</a> to create db migration scripts to modify the db (rather than wiping out the db everytime like I did in the beginning).</p>
<p>Edit: Actually, I'm using South now :-)</p>
| 1
|
2009-01-31T02:48:53Z
|
[
"python",
"django",
"django-models",
"workflow",
"django-syncdb"
] |
Django workflow when modifying models frequently?
| 497,654
|
<p>as I usually don't do the up front design of my models in Django projects I end up modifying the models a lot and thus deleting my test database every time (because "syncdb" won't ever alter the tables automatically for you). Below lies my workflow and I'd like to hear about yours. Any thoughts welcome.. </p>
<ol>
<li>Modify the model.</li>
<li>Delete the test database. (always a simple sqlite database for me.)</li>
<li>Run "syncdb".</li>
<li>Generate some test data via code.</li>
<li>goto 1.</li>
</ol>
<p>A secondary question regarding this.. In case your workflow is like above, how do you execute the 4. step? Do you generate the test data manually or is there a proper hook point in Django apps where you can inject the test-data-generating-code at server startup?\</p>
<p>TIA.</p>
| 24
|
2009-01-30T23:18:54Z
| 636,949
|
<p>South is the coolest.</p>
<p>Though good ol' reset works best when data doesn't matter. </p>
<p><a href="http://south.aeracode.org/">http://south.aeracode.org/</a></p>
| 10
|
2009-03-12T00:33:46Z
|
[
"python",
"django",
"django-models",
"workflow",
"django-syncdb"
] |
Python 3.0 `wsgiref` server not functioning
| 497,704
|
<p>I can't seem to get the <code>wsgiref</code> module to work at all under Python 3.0. It works fine under 2.5 for me, however. Even when I try the <a href="http://docs.python.org/3.0/library/wsgiref.html?highlight=wsgiref#examples" rel="nofollow">example in the docs</a>, it fails. It fails so hard that even if I have a print function above where I do: "<code>from wsgiref.simple_server import make_server</code>", it never gets printed for some reason. It doesn't thow any errors when run, and it just displays a blank page in the browser and doesn't log any sort of request.</p>
<p>Does anybody know what the problem may be? Thanks!</p>
| 1
|
2009-01-30T23:35:05Z
| 497,788
|
<p><a href="http://bugs.python.org/issue4718" rel="nofollow">issue 4718:wsgiref package totally broken</a>. sorry about that.</p>
| 2
|
2009-01-31T00:17:03Z
|
[
"python",
"python-3.x",
"wsgi",
"wsgiref"
] |
Python 3.0 `wsgiref` server not functioning
| 497,704
|
<p>I can't seem to get the <code>wsgiref</code> module to work at all under Python 3.0. It works fine under 2.5 for me, however. Even when I try the <a href="http://docs.python.org/3.0/library/wsgiref.html?highlight=wsgiref#examples" rel="nofollow">example in the docs</a>, it fails. It fails so hard that even if I have a print function above where I do: "<code>from wsgiref.simple_server import make_server</code>", it never gets printed for some reason. It doesn't thow any errors when run, and it just displays a blank page in the browser and doesn't log any sort of request.</p>
<p>Does anybody know what the problem may be? Thanks!</p>
| 1
|
2009-01-30T23:35:05Z
| 500,060
|
<p>You're in uncharted territory with WSGI on Python 3.0 I'm afraid.</p>
<p>WEB-SIG knew long ago that wsgiref was broken going into 3.0, but chose to do nothing about it. The spec hasn't been updated to cope with 3.0; pushing WSGI forwards even for the things everyone pretty-much agrees on is just agonisingly slow. It's depressing and senseless.</p>
<p>So yeah, it's easy to fix the obvious error with header unpacking in simple_server, but you'll still be running on a server that has been converted from Python 2-to-3 automatically and not really tested, with no de-jure standard to say exactly what it should do... never mind framework compatibility.</p>
<p>Python 3.0 for web scripting: needs some work.</p>
| 0
|
2009-02-01T02:43:53Z
|
[
"python",
"python-3.x",
"wsgi",
"wsgiref"
] |
IronPython vs. C# for small-scale projects
| 497,747
|
<p>I currently use Python for most of my programming projects (mainly rapid development of small programs and prototypes). I'd like to invest time in learning a language that gives me the flexibility to use various Microsoft tools and APIs whenever the opportunity arises. I'm trying to decide between IronPython and C#. Since Python is my favorite programming language (mainly because of its conciseness and clean syntax), IronPython sounds like the ideal option. Yet after reading about it a little bit I have several questions.</p>
<p>For those of you who have used IronPython, does it ever become unclear where classic Python ends and .NET begins? For example, there appears to be significant overlap in functionality between the .NET libraries and the Python standard library, so when I need to do string operations or parse XML, I'm unclear which library I'm supposed to use. Also, I'm unclear when I'm supposed to use Python versus .NET data types in my code. For example, which of the following would I be using in my code?</p>
<pre><code>d = {}
</code></pre>
<p>or </p>
<pre><code>d = System.Collections.Hashtable()
</code></pre>
<p>(By the way, it seems that if I do a lot of things like the latter I might lose some of the conciseness, which is why I favor Python in the first place.)</p>
<p>Another issue is that a number of Microsoft's developer tools, such as .NET CF and Xbox XNA, are not available in IronPython. Are there more situations where IronPython wouldn't give me the full reach of C#?</p>
| 8
|
2009-01-30T23:59:34Z
| 497,938
|
<p>I've built a large-scale application in IronPython bound with C#.</p>
<p>It's almost completely seamless. The only things missing in IronPython from the true "python" feel are the C-based libraries (gotta use .NET for those) and IDLE.</p>
<p>The language interacts with other .NET languages like a dream... Specifically if you embed the interpreter and bind variables by reference.</p>
<p>By the way, a hash in IronPython is declared:</p>
<pre><code>d = {}
</code></pre>
<p>Just be aware that it's actually an IronPython.Dict object, and not a C# dictionary. That said, the conversions often work invisibly if you pass it to a .NET class, and if you need to convert explicitly, there are built-ins that do it just fine.</p>
<p>All in all, an awesome language to use with .NET, if you have reason to.</p>
<p>Just a word of advice: Avoid the Visual Studio IronPython IDE like the plague. I found the automatic line completions screwed up on indentation, between spaces and tabs. Now -that- is a difficult-to-trace bug inserted into code.</p>
| 11
|
2009-01-31T01:15:04Z
|
[
"c#",
".net",
"python",
"ironpython"
] |
IronPython vs. C# for small-scale projects
| 497,747
|
<p>I currently use Python for most of my programming projects (mainly rapid development of small programs and prototypes). I'd like to invest time in learning a language that gives me the flexibility to use various Microsoft tools and APIs whenever the opportunity arises. I'm trying to decide between IronPython and C#. Since Python is my favorite programming language (mainly because of its conciseness and clean syntax), IronPython sounds like the ideal option. Yet after reading about it a little bit I have several questions.</p>
<p>For those of you who have used IronPython, does it ever become unclear where classic Python ends and .NET begins? For example, there appears to be significant overlap in functionality between the .NET libraries and the Python standard library, so when I need to do string operations or parse XML, I'm unclear which library I'm supposed to use. Also, I'm unclear when I'm supposed to use Python versus .NET data types in my code. For example, which of the following would I be using in my code?</p>
<pre><code>d = {}
</code></pre>
<p>or </p>
<pre><code>d = System.Collections.Hashtable()
</code></pre>
<p>(By the way, it seems that if I do a lot of things like the latter I might lose some of the conciseness, which is why I favor Python in the first place.)</p>
<p>Another issue is that a number of Microsoft's developer tools, such as .NET CF and Xbox XNA, are not available in IronPython. Are there more situations where IronPython wouldn't give me the full reach of C#?</p>
| 8
|
2009-01-30T23:59:34Z
| 498,067
|
<p>I'd suggest taking a look at <A HREF="http://boo.codehaus.org/" rel="nofollow">Boo [<a href="http://boo.codehaus.org/" rel="nofollow">http://boo.codehaus.org/</a>]</A>, a .NET-based language with a syntax inspired by Python, but which provides the full range of .NET 3.5 functionality.</p>
<p>IronPython is great for using .NET-centric libraries -- but it isn't well-suited to <em>creating</em> them due to underlying differences in how the languages do typing. As Boo does inference-based typing at compile time except where duck typing is explicitly requested (or a specific type is given by the user), it lets you build .NET-centric libraries easily usable from C# (and other languages') code, which IronPython isn't suitable for; also, as it has to do less introspection at runtime, Boo compiles to faster code.</p>
| 3
|
2009-01-31T02:17:45Z
|
[
"c#",
".net",
"python",
"ironpython"
] |
Python string.join(list) on object array rather than string array
| 497,765
|
<p>In Python, I can do:</p>
<pre><code>>>> list = ['a', 'b', 'c']
>>> ', '.join(list)
'a, b, c'
</code></pre>
<p>Is there any easy way to do the same when I have a list of objects?</p>
<pre><code>>>> class Obj:
... def __str__(self):
... return 'name'
...
>>> list = [Obj(), Obj(), Obj()]
>>> ', '.join(list)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: sequence item 0: expected string, instance found
</code></pre>
<p>Or do I have to resort to a for loop?</p>
| 134
|
2009-01-31T00:06:07Z
| 497,773
|
<p>You could use a list comprehension or a generator expression instead:</p>
<pre><code>', '.join([str(x) for x in list]) # list comprehension
', '.join(str(x) for x in list) # generator expression
</code></pre>
| 207
|
2009-01-31T00:10:58Z
|
[
"python",
"list"
] |
Python string.join(list) on object array rather than string array
| 497,765
|
<p>In Python, I can do:</p>
<pre><code>>>> list = ['a', 'b', 'c']
>>> ', '.join(list)
'a, b, c'
</code></pre>
<p>Is there any easy way to do the same when I have a list of objects?</p>
<pre><code>>>> class Obj:
... def __str__(self):
... return 'name'
...
>>> list = [Obj(), Obj(), Obj()]
>>> ', '.join(list)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: sequence item 0: expected string, instance found
</code></pre>
<p>Or do I have to resort to a for loop?</p>
| 134
|
2009-01-31T00:06:07Z
| 497,787
|
<p>The built-in string constructor will automatically call <code>obj.__str__</code>:</p>
<pre><code>''.join(map(str,list))
</code></pre>
| 49
|
2009-01-31T00:16:03Z
|
[
"python",
"list"
] |
Python element-wise tuple operations like sum
| 497,885
|
<p>Is there anyway to get tuple operations in Python to work like this:</p>
<pre><code>>>> a = (1,2,3)
>>> b = (3,2,1)
>>> a + b
(4,4,4)
</code></pre>
<p>instead of:</p>
<pre><code>>>> a = (1,2,3)
>>> b = (3,2,1)
>>> a + b
(1,2,3,3,2,1)
</code></pre>
<p>I know it works like that because the <code>__add__</code> and <code>__mul__</code> methods are defined to work like that. So the only way would be to redefine them?</p>
| 52
|
2009-01-31T00:51:48Z
| 497,894
|
<pre><code>import operator
tuple(map(operator.add, a, b))
</code></pre>
| 72
|
2009-01-31T00:55:01Z
|
[
"python",
"tuples"
] |
Python element-wise tuple operations like sum
| 497,885
|
<p>Is there anyway to get tuple operations in Python to work like this:</p>
<pre><code>>>> a = (1,2,3)
>>> b = (3,2,1)
>>> a + b
(4,4,4)
</code></pre>
<p>instead of:</p>
<pre><code>>>> a = (1,2,3)
>>> b = (3,2,1)
>>> a + b
(1,2,3,3,2,1)
</code></pre>
<p>I know it works like that because the <code>__add__</code> and <code>__mul__</code> methods are defined to work like that. So the only way would be to redefine them?</p>
| 52
|
2009-01-31T00:51:48Z
| 497,896
|
<p>Yes. But you can't redefine built-in types. You have to subclass them:</p>
<pre>
class MyTuple(tuple):
def __add__(self, other):
if len(self) != len(other):
raise ValueError("tuple lengths don't match")
return MyTuple(x + y for (x, y) in zip(self, other))
</pre>
| 3
|
2009-01-31T00:55:54Z
|
[
"python",
"tuples"
] |
Python element-wise tuple operations like sum
| 497,885
|
<p>Is there anyway to get tuple operations in Python to work like this:</p>
<pre><code>>>> a = (1,2,3)
>>> b = (3,2,1)
>>> a + b
(4,4,4)
</code></pre>
<p>instead of:</p>
<pre><code>>>> a = (1,2,3)
>>> b = (3,2,1)
>>> a + b
(1,2,3,3,2,1)
</code></pre>
<p>I know it works like that because the <code>__add__</code> and <code>__mul__</code> methods are defined to work like that. So the only way would be to redefine them?</p>
| 52
|
2009-01-31T00:51:48Z
| 497,931
|
<p>Sort of combined the first two answers, with a tweak to ironfroggy's code so that it returns a tuple:</p>
<pre><code>import operator
class stuple(tuple):
def __add__(self, other):
return self.__class__(map(operator.add, self, other))
# obviously leaving out checking lengths
>>> a = stuple([1,2,3])
>>> b = stuple([3,2,1])
>>> a + b
(4, 4, 4)
</code></pre>
<p>Note: using <code>self.__class__</code> instead of <code>stuple</code> to ease subclassing.</p>
| 18
|
2009-01-31T01:10:18Z
|
[
"python",
"tuples"
] |
Python element-wise tuple operations like sum
| 497,885
|
<p>Is there anyway to get tuple operations in Python to work like this:</p>
<pre><code>>>> a = (1,2,3)
>>> b = (3,2,1)
>>> a + b
(4,4,4)
</code></pre>
<p>instead of:</p>
<pre><code>>>> a = (1,2,3)
>>> b = (3,2,1)
>>> a + b
(1,2,3,3,2,1)
</code></pre>
<p>I know it works like that because the <code>__add__</code> and <code>__mul__</code> methods are defined to work like that. So the only way would be to redefine them?</p>
| 52
|
2009-01-31T00:51:48Z
| 498,103
|
<p>Using all built-ins..</p>
<pre><code>tuple(map(sum, zip(a, b))
</code></pre>
| 58
|
2009-01-31T02:49:16Z
|
[
"python",
"tuples"
] |
Python element-wise tuple operations like sum
| 497,885
|
<p>Is there anyway to get tuple operations in Python to work like this:</p>
<pre><code>>>> a = (1,2,3)
>>> b = (3,2,1)
>>> a + b
(4,4,4)
</code></pre>
<p>instead of:</p>
<pre><code>>>> a = (1,2,3)
>>> b = (3,2,1)
>>> a + b
(1,2,3,3,2,1)
</code></pre>
<p>I know it works like that because the <code>__add__</code> and <code>__mul__</code> methods are defined to work like that. So the only way would be to redefine them?</p>
| 52
|
2009-01-31T00:51:48Z
| 499,696
|
<pre><code>from numpy import *
a = array( [1,2,3] )
b = array( [3,2,1] )
print a + b
</code></pre>
<p>gives <code>array([4,4,4])</code>.</p>
<p>See <a href="http://www.scipy.org/Tentative_NumPy_Tutorial" rel="nofollow">http://www.scipy.org/Tentative_NumPy_Tutorial</a></p>
| 13
|
2009-01-31T22:25:06Z
|
[
"python",
"tuples"
] |
Python element-wise tuple operations like sum
| 497,885
|
<p>Is there anyway to get tuple operations in Python to work like this:</p>
<pre><code>>>> a = (1,2,3)
>>> b = (3,2,1)
>>> a + b
(4,4,4)
</code></pre>
<p>instead of:</p>
<pre><code>>>> a = (1,2,3)
>>> b = (3,2,1)
>>> a + b
(1,2,3,3,2,1)
</code></pre>
<p>I know it works like that because the <code>__add__</code> and <code>__mul__</code> methods are defined to work like that. So the only way would be to redefine them?</p>
| 52
|
2009-01-31T00:51:48Z
| 3,111,764
|
<p>simple solution without class definition that returns tuple</p>
<pre><code>import operator
tuple(map(operator.add,a,b))
</code></pre>
| 5
|
2010-06-24T16:10:24Z
|
[
"python",
"tuples"
] |
Python element-wise tuple operations like sum
| 497,885
|
<p>Is there anyway to get tuple operations in Python to work like this:</p>
<pre><code>>>> a = (1,2,3)
>>> b = (3,2,1)
>>> a + b
(4,4,4)
</code></pre>
<p>instead of:</p>
<pre><code>>>> a = (1,2,3)
>>> b = (3,2,1)
>>> a + b
(1,2,3,3,2,1)
</code></pre>
<p>I know it works like that because the <code>__add__</code> and <code>__mul__</code> methods are defined to work like that. So the only way would be to redefine them?</p>
| 52
|
2009-01-31T00:51:48Z
| 12,610,667
|
<p>All generator solution. Not sure on performance (itertools is fast, though)</p>
<pre><code>import itertools
tuple(x+y for x, y in itertools.izip(a,b))
</code></pre>
| 6
|
2012-09-26T21:25:32Z
|
[
"python",
"tuples"
] |
Python element-wise tuple operations like sum
| 497,885
|
<p>Is there anyway to get tuple operations in Python to work like this:</p>
<pre><code>>>> a = (1,2,3)
>>> b = (3,2,1)
>>> a + b
(4,4,4)
</code></pre>
<p>instead of:</p>
<pre><code>>>> a = (1,2,3)
>>> b = (3,2,1)
>>> a + b
(1,2,3,3,2,1)
</code></pre>
<p>I know it works like that because the <code>__add__</code> and <code>__mul__</code> methods are defined to work like that. So the only way would be to redefine them?</p>
| 52
|
2009-01-31T00:51:48Z
| 12,702,871
|
<p>This solution doesn't require an import:</p>
<pre><code>tuple(map(lambda x, y: x + y, tuple1, tuple2))
</code></pre>
| 23
|
2012-10-03T06:20:20Z
|
[
"python",
"tuples"
] |
Python element-wise tuple operations like sum
| 497,885
|
<p>Is there anyway to get tuple operations in Python to work like this:</p>
<pre><code>>>> a = (1,2,3)
>>> b = (3,2,1)
>>> a + b
(4,4,4)
</code></pre>
<p>instead of:</p>
<pre><code>>>> a = (1,2,3)
>>> b = (3,2,1)
>>> a + b
(1,2,3,3,2,1)
</code></pre>
<p>I know it works like that because the <code>__add__</code> and <code>__mul__</code> methods are defined to work like that. So the only way would be to redefine them?</p>
| 52
|
2009-01-31T00:51:48Z
| 34,799,008
|
<p>Generator comprehension could be used instead of map. Built-in map function is not obsolete but it's less readable for most people than list/generator/dict comprehension, so I'd recommend not to use map function in general.</p>
<pre><code>tuple(p+q for p, q in zip(a, b))
</code></pre>
| 2
|
2016-01-14T20:22:45Z
|
[
"python",
"tuples"
] |
Python element-wise tuple operations like sum
| 497,885
|
<p>Is there anyway to get tuple operations in Python to work like this:</p>
<pre><code>>>> a = (1,2,3)
>>> b = (3,2,1)
>>> a + b
(4,4,4)
</code></pre>
<p>instead of:</p>
<pre><code>>>> a = (1,2,3)
>>> b = (3,2,1)
>>> a + b
(1,2,3,3,2,1)
</code></pre>
<p>I know it works like that because the <code>__add__</code> and <code>__mul__</code> methods are defined to work like that. So the only way would be to redefine them?</p>
| 52
|
2009-01-31T00:51:48Z
| 37,780,038
|
<p>even simpler and without using map, you can do that</p>
<pre><code>>>> tuple(sum(i) for i in zip((1, 2, 3), (3, 2, 1)))
(4, 4, 4)
</code></pre>
| 0
|
2016-06-12T23:17:31Z
|
[
"python",
"tuples"
] |
How to make python gracefully fail?
| 497,952
|
<p>I was just wondering how do you make python fail in a user defined way in all possible errors. </p>
<p>For example, I'm writing a program that processes a (large) list of items, and some of the items may not be in the format I defined. If python detects an error, it currently just spits out an ugly error message and stop the whole process. However, I want it to just outputs the error to somewhere together with some context and then move on to the next item. </p>
<p>If anyone can help me with this it would be greatly appreciated!</p>
<p>Thanks a lot!</p>
<p>Jason</p>
| 13
|
2009-01-31T01:22:08Z
| 497,960
|
<p>The ugly error message means that an exception is raised. You need to catch the exception.</p>
<p>A good place to start is the <a href="http://docs.python.org/tutorial/errors.html" rel="nofollow">Python tutorial's section on exceptions.</a></p>
<p>Basically you need to wrap your code in a <code>try...except</code> block like this:</p>
<pre><code>try:
do_something_dangerous()
except SomeException:
handle_the_error()
</code></pre>
| 8
|
2009-01-31T01:26:01Z
|
[
"python"
] |
How to make python gracefully fail?
| 497,952
|
<p>I was just wondering how do you make python fail in a user defined way in all possible errors. </p>
<p>For example, I'm writing a program that processes a (large) list of items, and some of the items may not be in the format I defined. If python detects an error, it currently just spits out an ugly error message and stop the whole process. However, I want it to just outputs the error to somewhere together with some context and then move on to the next item. </p>
<p>If anyone can help me with this it would be greatly appreciated!</p>
<p>Thanks a lot!</p>
<p>Jason</p>
| 13
|
2009-01-31T01:22:08Z
| 497,964
|
<p>use <a href="http://docs.python.org/reference/compound_stmts.html#try" rel="nofollow">try... except</a> idiom</p>
<pre><code>try:
# code that possibly breaks
except RelevantError: # you need to know what kind of errors you code might produce
# show your message
</code></pre>
| 3
|
2009-01-31T01:28:28Z
|
[
"python"
] |
How to make python gracefully fail?
| 497,952
|
<p>I was just wondering how do you make python fail in a user defined way in all possible errors. </p>
<p>For example, I'm writing a program that processes a (large) list of items, and some of the items may not be in the format I defined. If python detects an error, it currently just spits out an ugly error message and stop the whole process. However, I want it to just outputs the error to somewhere together with some context and then move on to the next item. </p>
<p>If anyone can help me with this it would be greatly appreciated!</p>
<p>Thanks a lot!</p>
<p>Jason</p>
| 13
|
2009-01-31T01:22:08Z
| 497,965
|
<p>When Python runs into an error condition, it is throwing a exception. </p>
<p>The way to handle this is to catch the exception and maybe handle it. </p>
<p>You might check out the section on exceptions on the python <a href="http://docs.python.org/tutorial/errors.html" rel="nofollow">tutorial</a>.</p>
<p>You expressed an interest in catching all exceptions. This could be done by catching the Exception class. according to the documentation:</p>
<blockquote>
<p>All built-in, non-system-exiting
exceptions are derived from this
class. All user-defined exceptions
should also be derived from this class</p>
</blockquote>
| 0
|
2009-01-31T01:28:45Z
|
[
"python"
] |
How to make python gracefully fail?
| 497,952
|
<p>I was just wondering how do you make python fail in a user defined way in all possible errors. </p>
<p>For example, I'm writing a program that processes a (large) list of items, and some of the items may not be in the format I defined. If python detects an error, it currently just spits out an ugly error message and stop the whole process. However, I want it to just outputs the error to somewhere together with some context and then move on to the next item. </p>
<p>If anyone can help me with this it would be greatly appreciated!</p>
<p>Thanks a lot!</p>
<p>Jason</p>
| 13
|
2009-01-31T01:22:08Z
| 498,038
|
<p>The following are a few basic strategies I regularly use in my more-than-trivial scripts and medium-size applications.</p>
<p>Tip 1: Trap the error at every level where it makes sense to continue processing. In your case it may be in the inside the loop. You don't have to protect every single line or every single function call, but only the places where it makes a difference to survive the error.</p>
<p>Tip 2: Use the logging module to report what happened in a way that is configurable independently from how you compose the module with other modules in a larger applications. Start importing the root logger in your module, then, using it in a few different places, you may eventually figure out a more sensible logging hierarchy.</p>
<pre><code>import logging
logger = logging.getLogger()
for item in items:
try:
process(item)
except Exception, exc:
logger.warn("error while processing item: %s", exc)
</code></pre>
<p>Tip 3: define an "application exception", eventually you may want to define a hierarchy of such exception but this is better discovered when the need arise. Use such exception(s) to "bubble out" when the data you are dealing with are not what you expected or to signal inconsistent situations, while separating them from the normal standard exception arising from regular bugs or problems outside the modeled domain (IO errors etc).</p>
<pre><code>class DomainException(Exception):
"""Life is not what I expected"""
def process(item):
# There is no way that this item can be processed, so bail out quickly.
# Here you are assuming that your caller will report this error but probably
# it will be able to process the other items.
if item.foo > item.bar:
raise DomainException("bad news")
# Everybody knows that every item has more that 10 wickets, so
# the following instruction is assumed always being successful.
# But even if luck is not on our side, our caller will be able to
# cope with this situation and keep on working
item.wickets[10] *= 2
</code></pre>
<p>The main function is the outmost checkpoint: finally deal here with the possible ways your task finished. If this was not a shell script (but e.g. the processing beneath a dialog in an UI application or an operation after a POST in a web application) only the way you report the error changes (and the use of the logging method completely separates the implementation of the processing from its interface).</p>
<pre><code>def main():
try:
do_all_the_processing()
return 0
except DomainException, exc:
logger.error("I couldn't finish. The reason is: %s", exc)
return 1
except Exception, exc:
logger.error("Unexpected error: %s - %s", exc.__class__.__name__, exc)
# In this case you may want to forward a stacktrace to the developers via e-mail
return 1
except BaseException:
logger.info("user stop") # this deals with a ctrl-c
return 1
if __name__ == '__main__':
sys.exit(main())
</code></pre>
| 23
|
2009-01-31T02:01:10Z
|
[
"python"
] |
How to make python gracefully fail?
| 497,952
|
<p>I was just wondering how do you make python fail in a user defined way in all possible errors. </p>
<p>For example, I'm writing a program that processes a (large) list of items, and some of the items may not be in the format I defined. If python detects an error, it currently just spits out an ugly error message and stop the whole process. However, I want it to just outputs the error to somewhere together with some context and then move on to the next item. </p>
<p>If anyone can help me with this it would be greatly appreciated!</p>
<p>Thanks a lot!</p>
<p>Jason</p>
| 13
|
2009-01-31T01:22:08Z
| 498,046
|
<blockquote>
<p>all possible errors</p>
</blockquote>
<p>The other answers pretty much cover how to make your program gracefully fail, but I'd like to mention one thing -- You don't want to gracefully fail <em>all</em> errors. If you hide all your errors, you won't be shown those which signify that the logic of the program is wrong - namely errors you <em>want</em> to see.</p>
<p>So while it's important to catch your exceptions, make sure you know exactly which exceptions are actually being caught.</p>
| 2
|
2009-01-31T02:04:04Z
|
[
"python"
] |
How do I compile a Visual Studio project from the command-line?
| 498,106
|
<p>I'm scripting the checkout, build, distribution, test, and commit cycle for a large C++ solution that is using <a href="http://en.wikipedia.org/wiki/Monotone_%28software%29">Monotone</a>, <a href="http://en.wikipedia.org/wiki/CMake">CMake</a>, Visual Studio Express 2008, and custom tests. </p>
<p>All of the other parts seem pretty straight-forward, but I don't see how to compile the Visual Studio solution without getting the GUI. </p>
<p>The script is written in Python, but an answer that would allow me to just make a call to: os.system would do.</p>
| 76
|
2009-01-31T02:52:25Z
| 498,108
|
<p><a href="http://msdn.microsoft.com/en-us/library/ms171452.aspx" rel="nofollow">MSBuild is your friend.</a></p>
<pre><code>msbuild "C:\path to solution\project.sln"
</code></pre>
| 4
|
2009-01-31T02:55:12Z
|
[
"c++",
"python",
"visual-studio-2008",
"command-line"
] |
How do I compile a Visual Studio project from the command-line?
| 498,106
|
<p>I'm scripting the checkout, build, distribution, test, and commit cycle for a large C++ solution that is using <a href="http://en.wikipedia.org/wiki/Monotone_%28software%29">Monotone</a>, <a href="http://en.wikipedia.org/wiki/CMake">CMake</a>, Visual Studio Express 2008, and custom tests. </p>
<p>All of the other parts seem pretty straight-forward, but I don't see how to compile the Visual Studio solution without getting the GUI. </p>
<p>The script is written in Python, but an answer that would allow me to just make a call to: os.system would do.</p>
| 76
|
2009-01-31T02:52:25Z
| 498,118
|
<p>MSBuild usually works, but I've run into difficulties before. You may have better luck with</p>
<pre><code>devenv YourSolution.sln /Build
</code></pre>
| 32
|
2009-01-31T02:58:27Z
|
[
"c++",
"python",
"visual-studio-2008",
"command-line"
] |
How do I compile a Visual Studio project from the command-line?
| 498,106
|
<p>I'm scripting the checkout, build, distribution, test, and commit cycle for a large C++ solution that is using <a href="http://en.wikipedia.org/wiki/Monotone_%28software%29">Monotone</a>, <a href="http://en.wikipedia.org/wiki/CMake">CMake</a>, Visual Studio Express 2008, and custom tests. </p>
<p>All of the other parts seem pretty straight-forward, but I don't see how to compile the Visual Studio solution without getting the GUI. </p>
<p>The script is written in Python, but an answer that would allow me to just make a call to: os.system would do.</p>
| 76
|
2009-01-31T02:52:25Z
| 498,130
|
<p>I know of two ways to do it. </p>
<p><strong>Method 1</strong><br>
The first method (which I prefer) is to use <a href="http://msdn.microsoft.com/en-us/library/0k6kkbsd.aspx">msbuild</a>:</p>
<pre><code>msbuild project.sln /Flags...
</code></pre>
<p><strong>Method 2</strong><br>
You can also run:</p>
<pre><code>vcexpress project.sln /build /Flags...
</code></pre>
<p>The vcexpress option returns immediately and does not print any output. I suppose that might be what you want for a script.</p>
<p>Note that DevEnv is not distributed with Visual Studio Express 2008 (I spent a lot of time trying to figure that out when I first had a similar issue). </p>
<p>So, the end result might be:</p>
<pre><code>os.system("msbuild project.sln /p:Configuration=Debug")
</code></pre>
<p>You'll also want to make sure your environment variables are correct, as msbuild and vcexpress are not by default on the system path. Either start the Visual Studio build environment and run your script from there, or modify the paths in Python (with <a href="http://docs.python.org/library/os.html#os.putenv">os.putenv</a>).</p>
| 77
|
2009-01-31T03:04:10Z
|
[
"c++",
"python",
"visual-studio-2008",
"command-line"
] |
How do I compile a Visual Studio project from the command-line?
| 498,106
|
<p>I'm scripting the checkout, build, distribution, test, and commit cycle for a large C++ solution that is using <a href="http://en.wikipedia.org/wiki/Monotone_%28software%29">Monotone</a>, <a href="http://en.wikipedia.org/wiki/CMake">CMake</a>, Visual Studio Express 2008, and custom tests. </p>
<p>All of the other parts seem pretty straight-forward, but I don't see how to compile the Visual Studio solution without getting the GUI. </p>
<p>The script is written in Python, but an answer that would allow me to just make a call to: os.system would do.</p>
| 76
|
2009-01-31T02:52:25Z
| 17,867,663
|
<p>To be honest I have to add my 2 cents.</p>
<p>You can do it with <strong>msbuild.exe</strong>. There are many version of the <strong>msbuild.exe</strong>.</p>
<blockquote>
<p>C:\Windows\Microsoft.NET\Framework64\v2.0.50727\msbuild.exe
C:\Windows\Microsoft.NET\Framework64\v3.5\msbuild.exe
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\msbuild.exe<br>
C:\Windows\Microsoft.NET\Framework\v2.0.50727\msbuild.exe
C:\Windows\Microsoft.NET\Framework\v3.5\msbuild.exe
C:\Windows\Microsoft.NET\Framework\v4.0.30319\msbuild.exe</p>
</blockquote>
<p>Use version you need. Basically you have to use the last one.</p>
<blockquote>
<p>C:\Windows\Microsoft.NET\Framework64\v4.0.30319\msbuild.exe</p>
</blockquote>
<p>So how to do it.</p>
<ol>
<li><p>Run the <strong>COMMAND</strong> window</p></li>
<li><p>Input the path to msbuild.exe</p></li>
</ol>
<blockquote>
<p>C:\Windows\Microsoft.NET\Framework64\v4.0.30319\msbuild.exe</p>
</blockquote>
<ol>
<li>Input the path to the project solution like</li>
</ol>
<blockquote>
<p>"C:\Users\Clark.Kent\Documents\visual studio
2012\Projects\WpfApplication1\WpfApplication1.sln"</p>
</blockquote>
<ol>
<li><p>Add any flags you need after the solution path.</p></li>
<li><p>Press <strong>ENTER</strong></p></li>
</ol>
<p>Note you can get help about all possible flags like </p>
<blockquote>
<p>C:\Windows\Microsoft.NET\Framework64\v4.0.30319\msbuild.exe /help</p>
</blockquote>
| 11
|
2013-07-25T20:01:03Z
|
[
"c++",
"python",
"visual-studio-2008",
"command-line"
] |
How do I compile a Visual Studio project from the command-line?
| 498,106
|
<p>I'm scripting the checkout, build, distribution, test, and commit cycle for a large C++ solution that is using <a href="http://en.wikipedia.org/wiki/Monotone_%28software%29">Monotone</a>, <a href="http://en.wikipedia.org/wiki/CMake">CMake</a>, Visual Studio Express 2008, and custom tests. </p>
<p>All of the other parts seem pretty straight-forward, but I don't see how to compile the Visual Studio solution without getting the GUI. </p>
<p>The script is written in Python, but an answer that would allow me to just make a call to: os.system would do.</p>
| 76
|
2009-01-31T02:52:25Z
| 26,274,077
|
<p>DEVENV works well in many cases, but on a WIXPROJ to build my WIX installer, all I got is "CATASTROPHIC" error in the Out log.</p>
<p>This works:
MSBUILD /Path/PROJECT.WIXPROJ /t:Build /p:Configuration=Release</p>
| 1
|
2014-10-09T08:47:03Z
|
[
"c++",
"python",
"visual-studio-2008",
"command-line"
] |
How do I compile a Visual Studio project from the command-line?
| 498,106
|
<p>I'm scripting the checkout, build, distribution, test, and commit cycle for a large C++ solution that is using <a href="http://en.wikipedia.org/wiki/Monotone_%28software%29">Monotone</a>, <a href="http://en.wikipedia.org/wiki/CMake">CMake</a>, Visual Studio Express 2008, and custom tests. </p>
<p>All of the other parts seem pretty straight-forward, but I don't see how to compile the Visual Studio solution without getting the GUI. </p>
<p>The script is written in Python, but an answer that would allow me to just make a call to: os.system would do.</p>
| 76
|
2009-01-31T02:52:25Z
| 32,839,140
|
<p>Using <code>msbuild</code> as pointed out by others worked for me but I needed to do a bit more than just that. First of all, <code>msbuild</code> needs to have access to the compiler. This can be done by running:</p>
<pre><code>"C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\vcvarsall.bat"
</code></pre>
<p>Then <code>msbuild</code> was not in my $PATH so I had to run it via its explicit path:</p>
<pre><code>"C:\Windows\Microsoft.NET\Framework64\v4.0.30319\MSBuild.exe" myproj.sln
</code></pre>
<p>Lastly, my project was making use of some variables like <code>$(VisualStudioDir)</code>. It seems those do not get set by <code>msbuild</code> so I had to set them manually via the <code>/property</code> option:</p>
<pre><code>"C:\Windows\Microsoft.NET\Framework64\v4.0.30319\MSBuild.exe" /property:VisualStudioDir="C:\Users\Administrator\Documents\Visual Studio 2013" myproj.sln
</code></pre>
<p>That line then finally allowed me to compile my project.</p>
<p><strong>Bonus</strong>: it seems that the command line tools do not require a registration after 30 days of using them like the "free" GUI-based Visual Studio Community edition does. With the Microsoft registration requirement in place, that version is hardly free. Free-as-in-facebook if anything...</p>
| 1
|
2015-09-29T08:20:49Z
|
[
"c++",
"python",
"visual-studio-2008",
"command-line"
] |
Valid use case for django admin?
| 498,199
|
<p>I want to build a django site where a certain group of trusted users can edit their profile information. Does it make sense to have each trusted user go through the django admin interface? I'd only want them to be able to see and edit their own information (obviously). It doesn't seem like this fits the way the django people define "trust", especially the bolded bit...</p>
<p>From <a href="http://74.125.95.132/search?q=cache:fw9E1c2Oa7AJ:www.djangobook.com/en/beta/chapter18/+django+admin+use+cases&hl=en&ct=clnk&cd=2&gl=ca&client=firefox-a">The Django Book, Chapter 18</a>:</p>
<blockquote>
<p>The admin is designed to be used by
people who you, the developer, trust.
This doesnât just mean âpeople who
have been authenticated;â it means
that Django assumes that your content
editors can be trusted to do the right
thing.</p>
<p>This means that thereâs no âapprovalâ
process for editing content â if you
trust your users, nobody needs to
approve of their edits. It also means
that the permission system, while
powerful, has no support for limiting
access on a per-object basis. <strong>If you
trust someone to edit their own
stories, you trust them not to edit
anyone elseâs without permission.</strong></p>
</blockquote>
<p>Is this one of those use cases that fits with django's admin module, or is it just a specialized view for a non-trusted user?</p>
| 11
|
2009-01-31T03:56:54Z
| 498,277
|
<p>I wouldn't consider editing my personal profile on a website an administrative task. I think <a href="http://bitbucket.org/ubernostrum/django-profiles/wiki/Home" rel="nofollow">django-profiles</a> is what you are looking for. </p>
| 3
|
2009-01-31T04:43:32Z
|
[
"python",
"django",
"django-admin"
] |
Valid use case for django admin?
| 498,199
|
<p>I want to build a django site where a certain group of trusted users can edit their profile information. Does it make sense to have each trusted user go through the django admin interface? I'd only want them to be able to see and edit their own information (obviously). It doesn't seem like this fits the way the django people define "trust", especially the bolded bit...</p>
<p>From <a href="http://74.125.95.132/search?q=cache:fw9E1c2Oa7AJ:www.djangobook.com/en/beta/chapter18/+django+admin+use+cases&hl=en&ct=clnk&cd=2&gl=ca&client=firefox-a">The Django Book, Chapter 18</a>:</p>
<blockquote>
<p>The admin is designed to be used by
people who you, the developer, trust.
This doesnât just mean âpeople who
have been authenticated;â it means
that Django assumes that your content
editors can be trusted to do the right
thing.</p>
<p>This means that thereâs no âapprovalâ
process for editing content â if you
trust your users, nobody needs to
approve of their edits. It also means
that the permission system, while
powerful, has no support for limiting
access on a per-object basis. <strong>If you
trust someone to edit their own
stories, you trust them not to edit
anyone elseâs without permission.</strong></p>
</blockquote>
<p>Is this one of those use cases that fits with django's admin module, or is it just a specialized view for a non-trusted user?</p>
| 11
|
2009-01-31T03:56:54Z
| 498,288
|
<p>No, the Django admin is not suited for individual user profiles, each user would be able to see, and edit, all other user profiles. This is suited more to an administrator who has to manage all the users at once.</p>
<p>What you need to build is a user profile page. Django already has a nice login system courtesy of the django.contrib.auth module. You can easily integrate this into your pages, and its exactly what the Django admin uses to authenticate users.</p>
<p>Next you'll have to build a simple page that exposes that specific user's profile information based on their User model. This should be relatively painless as it will only require one view and one template, and the template can take advantage of ModelForms.</p>
| 17
|
2009-01-31T04:48:35Z
|
[
"python",
"django",
"django-admin"
] |
Valid use case for django admin?
| 498,199
|
<p>I want to build a django site where a certain group of trusted users can edit their profile information. Does it make sense to have each trusted user go through the django admin interface? I'd only want them to be able to see and edit their own information (obviously). It doesn't seem like this fits the way the django people define "trust", especially the bolded bit...</p>
<p>From <a href="http://74.125.95.132/search?q=cache:fw9E1c2Oa7AJ:www.djangobook.com/en/beta/chapter18/+django+admin+use+cases&hl=en&ct=clnk&cd=2&gl=ca&client=firefox-a">The Django Book, Chapter 18</a>:</p>
<blockquote>
<p>The admin is designed to be used by
people who you, the developer, trust.
This doesnât just mean âpeople who
have been authenticated;â it means
that Django assumes that your content
editors can be trusted to do the right
thing.</p>
<p>This means that thereâs no âapprovalâ
process for editing content â if you
trust your users, nobody needs to
approve of their edits. It also means
that the permission system, while
powerful, has no support for limiting
access on a per-object basis. <strong>If you
trust someone to edit their own
stories, you trust them not to edit
anyone elseâs without permission.</strong></p>
</blockquote>
<p>Is this one of those use cases that fits with django's admin module, or is it just a specialized view for a non-trusted user?</p>
| 11
|
2009-01-31T03:56:54Z
| 499,147
|
<p>Django's model for authorization is a little too simplistic. It is just checks for permission on the Model as a whole.</p>
<p>For this kind of thing, you are pretty much forced to write your own view functions that handle the additional check.</p>
<p>After you've written one or two, you'll see the pattern. Then you can think about writing your own decorator to handle this. </p>
<pre><code>def profileView( request, object_id ):
p= Profile.objects.get( id=int(object_id) )
if request.session['user'] != p.get_user():
# respond with a 401 not authorized or a helpful message
# process normally, since the session['user'] is the user for the Profile.
</code></pre>
<p>For the above to work, you'll need to enable sessions, and be sure you record the user in the session when they login successfully. You'll also need to eradicate the session when they logout. </p>
| 3
|
2009-01-31T16:50:16Z
|
[
"python",
"django",
"django-admin"
] |
Valid use case for django admin?
| 498,199
|
<p>I want to build a django site where a certain group of trusted users can edit their profile information. Does it make sense to have each trusted user go through the django admin interface? I'd only want them to be able to see and edit their own information (obviously). It doesn't seem like this fits the way the django people define "trust", especially the bolded bit...</p>
<p>From <a href="http://74.125.95.132/search?q=cache:fw9E1c2Oa7AJ:www.djangobook.com/en/beta/chapter18/+django+admin+use+cases&hl=en&ct=clnk&cd=2&gl=ca&client=firefox-a">The Django Book, Chapter 18</a>:</p>
<blockquote>
<p>The admin is designed to be used by
people who you, the developer, trust.
This doesnât just mean âpeople who
have been authenticated;â it means
that Django assumes that your content
editors can be trusted to do the right
thing.</p>
<p>This means that thereâs no âapprovalâ
process for editing content â if you
trust your users, nobody needs to
approve of their edits. It also means
that the permission system, while
powerful, has no support for limiting
access on a per-object basis. <strong>If you
trust someone to edit their own
stories, you trust them not to edit
anyone elseâs without permission.</strong></p>
</blockquote>
<p>Is this one of those use cases that fits with django's admin module, or is it just a specialized view for a non-trusted user?</p>
| 11
|
2009-01-31T03:56:54Z
| 499,310
|
<p>I would suggest you to create a Person model which contains a OneToOneField to the User model(Admin site User model.). Some what like this..</p>
<pre><code>from django.contrib.auth.models import User
class Person(models.Model):
"""The person class FKs to the User class and contains additional user information
including userImage, country, etc"""
user = models.OneToOneField(User, related_name='person_fk')
url = models.URLField(max_length=255, blank=True)
country = models.CharField(max_length=2, blank=True)
state = models.CharField(max_length=50, blank=True)
zipCode = models.IntegerField(max_length=7, blank=True, null=True)
userImage = models.ImageField(upload_to=generate_filename, blank=True, null=True)
</code></pre>
| 5
|
2009-01-31T18:40:48Z
|
[
"python",
"django",
"django-admin"
] |
Valid use case for django admin?
| 498,199
|
<p>I want to build a django site where a certain group of trusted users can edit their profile information. Does it make sense to have each trusted user go through the django admin interface? I'd only want them to be able to see and edit their own information (obviously). It doesn't seem like this fits the way the django people define "trust", especially the bolded bit...</p>
<p>From <a href="http://74.125.95.132/search?q=cache:fw9E1c2Oa7AJ:www.djangobook.com/en/beta/chapter18/+django+admin+use+cases&hl=en&ct=clnk&cd=2&gl=ca&client=firefox-a">The Django Book, Chapter 18</a>:</p>
<blockquote>
<p>The admin is designed to be used by
people who you, the developer, trust.
This doesnât just mean âpeople who
have been authenticated;â it means
that Django assumes that your content
editors can be trusted to do the right
thing.</p>
<p>This means that thereâs no âapprovalâ
process for editing content â if you
trust your users, nobody needs to
approve of their edits. It also means
that the permission system, while
powerful, has no support for limiting
access on a per-object basis. <strong>If you
trust someone to edit their own
stories, you trust them not to edit
anyone elseâs without permission.</strong></p>
</blockquote>
<p>Is this one of those use cases that fits with django's admin module, or is it just a specialized view for a non-trusted user?</p>
| 11
|
2009-01-31T03:56:54Z
| 501,398
|
<p>Just for reference, here's a <a href="http://www.djangosnippets.org/snippets/1054/" rel="nofollow">snippet</a> demonstrating how you can fairly easily achieve this effect (users can only edit their "own" objects) in the Django admin. Caveat: I wouldn't recommend doing this for user profiles, it'll be easier and more flexible to just create your own edit view using a ModelForm.</p>
| 1
|
2009-02-01T19:13:49Z
|
[
"python",
"django",
"django-admin"
] |
Valid use case for django admin?
| 498,199
|
<p>I want to build a django site where a certain group of trusted users can edit their profile information. Does it make sense to have each trusted user go through the django admin interface? I'd only want them to be able to see and edit their own information (obviously). It doesn't seem like this fits the way the django people define "trust", especially the bolded bit...</p>
<p>From <a href="http://74.125.95.132/search?q=cache:fw9E1c2Oa7AJ:www.djangobook.com/en/beta/chapter18/+django+admin+use+cases&hl=en&ct=clnk&cd=2&gl=ca&client=firefox-a">The Django Book, Chapter 18</a>:</p>
<blockquote>
<p>The admin is designed to be used by
people who you, the developer, trust.
This doesnât just mean âpeople who
have been authenticated;â it means
that Django assumes that your content
editors can be trusted to do the right
thing.</p>
<p>This means that thereâs no âapprovalâ
process for editing content â if you
trust your users, nobody needs to
approve of their edits. It also means
that the permission system, while
powerful, has no support for limiting
access on a per-object basis. <strong>If you
trust someone to edit their own
stories, you trust them not to edit
anyone elseâs without permission.</strong></p>
</blockquote>
<p>Is this one of those use cases that fits with django's admin module, or is it just a specialized view for a non-trusted user?</p>
| 11
|
2009-01-31T03:56:54Z
| 511,101
|
<p>There are a few django pluggable apps that allow row level permissions on your admin model. However, I'd be more inclined to write my own view that allows users to do it from within the application.</p>
<p>I had similar aspirations (using the admin contrib) when designing the app I'm currently working on, but decided that the admin app really is for admin use, and that regular users should be given their own pages to do the work and customisation (if required).</p>
<p>You can easily generate the CRUD views for a particular model using generic views and modelforms, and just apply style sheets for consistent look with the rest of your application.</p>
| 1
|
2009-02-04T12:15:25Z
|
[
"python",
"django",
"django-admin"
] |
Is Django a good choice for a security critical application?
| 498,630
|
<p>Is Django a good choice for a security critical application?</p>
<p>I am asking this because most of the online banking software is built using Java. Is there any real reason for this?</p>
| 22
|
2009-01-31T10:46:37Z
| 498,707
|
<p>Probably the reason behind Java is not in the in the security. I think Java is more used in large development companies and banks usually resort to them for their development needs (which probably are not only related to the web site but creep deeper in the backend).</p>
<p>So, I see no security reasons, mostly cultural ones.</p>
| 17
|
2009-01-31T11:56:17Z
|
[
"python",
"django",
"security"
] |
Is Django a good choice for a security critical application?
| 498,630
|
<p>Is Django a good choice for a security critical application?</p>
<p>I am asking this because most of the online banking software is built using Java. Is there any real reason for this?</p>
| 22
|
2009-01-31T10:46:37Z
| 498,798
|
<p>Actually, the security in Java and Python is the same. Digest-only password handling, cookies that timeout rapidly, careful deletion of sessions, multi-factor authentication. None of this is unique to a Java framework or a Python framework like Django.</p>
<p>Django, indeed, has a security backend architecture that allows you to add your own LDAP (or AD) connection, possibly changing the digest technique used. </p>
<p>Django has a Profile model where you can keep additional authentication factors.</p>
<p>Django offers a few standard decorators for view function authorization checking. Since Python is so flexible, you can trivially write your own decorator functions to layer in different or additional authentication checking.</p>
<p>Security is a number of first-class features in Django.</p>
| 30
|
2009-01-31T13:08:04Z
|
[
"python",
"django",
"security"
] |
Is Django a good choice for a security critical application?
| 498,630
|
<p>Is Django a good choice for a security critical application?</p>
<p>I am asking this because most of the online banking software is built using Java. Is there any real reason for this?</p>
| 22
|
2009-01-31T10:46:37Z
| 499,065
|
<p>Are you referring to the fact that the <em>complete</em> application is built in Java, or just the part you see in your browser? If the latter, the reason is probably because in the context of webpages, Java applets can be downloaded and run.</p>
| 0
|
2009-01-31T16:04:25Z
|
[
"python",
"django",
"security"
] |
Is Django a good choice for a security critical application?
| 498,630
|
<p>Is Django a good choice for a security critical application?</p>
<p>I am asking this because most of the online banking software is built using Java. Is there any real reason for this?</p>
| 22
|
2009-01-31T10:46:37Z
| 499,505
|
<p>You should not rely the security of the application on the framework. even though Django does come in with a pretty good number of measures against classical security issues, it can not guarantee that your application will be secure, you need much more than a programming Framework to get a security critical application.</p>
<p>I'd say yes, Django is a good choice as long as you know its powers and limitations and are aware of the security flaws of <strong>every</strong> application.</p>
| 1
|
2009-01-31T20:34:39Z
|
[
"python",
"django",
"security"
] |
Is Django a good choice for a security critical application?
| 498,630
|
<p>Is Django a good choice for a security critical application?</p>
<p>I am asking this because most of the online banking software is built using Java. Is there any real reason for this?</p>
| 22
|
2009-01-31T10:46:37Z
| 499,599
|
<p>The reasons for building banking apps in Java are not related to security, at least IMHO. They are related to:</p>
<ol>
<li>Java is the COBOL of the 21st century, so there is a lot of legacy code that would have to be rewritten and that takes time. Basically banking apps are old apps, they were built in java some ten years ago and nobody wants to throw all the old code away (which BTW is almost always a bad decision),</li>
<li>some people believe that a static typed language is somewhat "safer" than the dynamic typed language. This is, IMHO, not true (take for instance collections prior to Java 5).</li>
</ol>
| 8
|
2009-01-31T21:18:49Z
|
[
"python",
"django",
"security"
] |
Is Django a good choice for a security critical application?
| 498,630
|
<p>Is Django a good choice for a security critical application?</p>
<p>I am asking this because most of the online banking software is built using Java. Is there any real reason for this?</p>
| 22
|
2009-01-31T10:46:37Z
| 499,670
|
<p>I find your connection between Java and banking wrong ended.</p>
<p>Most Banking Software has terrible security. And much banking software is written in Java. Does ths mean Java makes it more difficult to write secure software than other languages?</p>
<p>Probably it's not Java's fault that there is so little quality security (and safety) wise in Banking software. Actually, like the other posters mention, the choice of your Language usually has very little consequences for your security - unless you select one of the few languages where only hotshot coders can write secure code in (C and PHP come to mind).</p>
<p>Many huge E-Commerce sites are written in Python, Ruby and Perl using various frameworks. And I would argue that the security requirements for merchants are much higher than the requirements of the banking industry. That is because merchants have to provide security and good user experience, while banking customers are willing to put up with unusable interfaces SecureID tokens and whatever.</p>
<p>So yes: Django is up to the task.</p>
| 4
|
2009-01-31T22:06:48Z
|
[
"python",
"django",
"security"
] |
Is Django a good choice for a security critical application?
| 498,630
|
<p>Is Django a good choice for a security critical application?</p>
<p>I am asking this because most of the online banking software is built using Java. Is there any real reason for this?</p>
| 22
|
2009-01-31T10:46:37Z
| 2,654,928
|
<p>You can build a secure application with Django just as you can with any popular Java framework. One part where Java does shine is its extensive cryptographic library.</p>
<p>For the minimal encryption tasks that are required by Django, Pythonâs cryptographic services are sufficient, however its lack of strong block ciphers make the encryption mechanism in Django insecure for data at rest.</p>
<p>Python does natively support secure hashing algorithms to include SHA1, SHA224,
SHA256, SHA384, and SHA512, however Djangoâs authentication mechanism has yet
to be updated to use anything other than SHA1, making it potentially vulnerable to cryptographic analysis.</p>
| 1
|
2010-04-16T17:18:42Z
|
[
"python",
"django",
"security"
] |
Minimal, Standalone, Distributable, cross platform web server
| 499,084
|
<p>I've been writing a fair number of smaller wsgi apps lately and am looking to find a web server that can be distributed, preconfigured to run the specific app. I know there are things like twisted and cherrypy which can serve up wsgi apps, but they seem to be missing a key piece of functionality for me, which is the ability to "pseudostream" large files using the http range header. Is there a web server available under a BSD or similar license which can be distributed as a standalone executable on any of the major platforms which is capable of both proxying to a a wsgi server (like cherrypy or the like) AND serving large files using the http range header?</p>
| 8
|
2009-01-31T16:15:33Z
| 499,225
|
<p>What's wrong with Apache + mod_wsgi? Apache is already multiplatform; it's often already installed (except in Windows).</p>
<p>You might also want to look at lighttpd, there are some blogs on configuring it to work with WSGI. See <a href="http://cleverdevil.org/computing/24/python-fastcgi-wsgi-and-lighttpd" rel="nofollow">http://cleverdevil.org/computing/24/python-fastcgi-wsgi-and-lighttpd</a>, and <a href="http://redmine.lighttpd.net/issues/show/1523" rel="nofollow">http://redmine.lighttpd.net/issues/show/1523</a> </p>
| 3
|
2009-01-31T17:42:49Z
|
[
"python",
"http",
"wsgi"
] |
Minimal, Standalone, Distributable, cross platform web server
| 499,084
|
<p>I've been writing a fair number of smaller wsgi apps lately and am looking to find a web server that can be distributed, preconfigured to run the specific app. I know there are things like twisted and cherrypy which can serve up wsgi apps, but they seem to be missing a key piece of functionality for me, which is the ability to "pseudostream" large files using the http range header. Is there a web server available under a BSD or similar license which can be distributed as a standalone executable on any of the major platforms which is capable of both proxying to a a wsgi server (like cherrypy or the like) AND serving large files using the http range header?</p>
| 8
|
2009-01-31T16:15:33Z
| 501,871
|
<p>Lighttpd has a BSD license, so you should be able to bundle it if you wanted.</p>
<p>You say its for small apps, so I guess that means, small, local, single user web interfaces being served by a small http server? If thats is the case, then any python implementation should work. Just use something like py2exe to package it (in fact, there was a question relating to packaging python programs here on SO not too long ago).</p>
<p>Update, re: range header:
The default python http server may not support the range header you want, but its pretty easy to write your own handler, or a small wsgi app to do the logic, especially if all you're doing is streaming a file. It wouldn't be too many lines:</p>
<pre><code>def stream_file(environ, start_response):
fp = open(base_dir + environ["PATH_INFO"])
fp.seek(environ["HTTP_CONTENT_RANGE"]) # just an example
start_response("200 OK", (('Content-Type', "file/type")))
return fp
</code></pre>
| 5
|
2009-02-02T00:01:34Z
|
[
"python",
"http",
"wsgi"
] |
Regular expression to extract URL from an HTML link
| 499,345
|
<p>Iâm a newbie in Python. Iâm learning regexes, but I need help here.</p>
<p>Here comes the HTML source:</p>
<pre><code><a href="http://www.ptop.se" target="_blank">http://www.ptop.se</a>
</code></pre>
<p>Iâm trying to code a tool that only prints out <code>http://ptop.se</code>. Can you help me please?</p>
| 22
|
2009-01-31T19:02:34Z
| 499,364
|
<p>Don't use regexes, use <a href="http://www.crummy.com/software/BeautifulSoup/" rel="nofollow">BeautifulSoup</a>. That, or be so crufty as to spawn it out to, say, w3m/lynx and pull back in what w3m/lynx renders. First is more elegant probably, second just worked a heck of a lot faster on some unoptimized code I wrote a while back.</p>
| 13
|
2009-01-31T19:13:16Z
|
[
"python",
"regex"
] |
Regular expression to extract URL from an HTML link
| 499,345
|
<p>Iâm a newbie in Python. Iâm learning regexes, but I need help here.</p>
<p>Here comes the HTML source:</p>
<pre><code><a href="http://www.ptop.se" target="_blank">http://www.ptop.se</a>
</code></pre>
<p>Iâm trying to code a tool that only prints out <code>http://ptop.se</code>. Can you help me please?</p>
| 22
|
2009-01-31T19:02:34Z
| 499,366
|
<p>this should work, although there might be more elegant ways.</p>
<pre><code>import re
url='<a href="http://www.ptop.se" target="_blank">http://www.ptop.se</a>'
r = re.compile('(?<=href=").*?(?=")')
r.findall(url)
</code></pre>
| 10
|
2009-01-31T19:16:03Z
|
[
"python",
"regex"
] |
Regular expression to extract URL from an HTML link
| 499,345
|
<p>Iâm a newbie in Python. Iâm learning regexes, but I need help here.</p>
<p>Here comes the HTML source:</p>
<pre><code><a href="http://www.ptop.se" target="_blank">http://www.ptop.se</a>
</code></pre>
<p>Iâm trying to code a tool that only prints out <code>http://ptop.se</code>. Can you help me please?</p>
| 22
|
2009-01-31T19:02:34Z
| 499,371
|
<p>If you're only looking for one:</p>
<pre><code>import re
match = re.search(r'href=[\'"]?([^\'" >]+)', s)
if match:
print match.group(0)
</code></pre>
<p>If you have a long string, and want every instance of the pattern in it:</p>
<pre><code>import re
urls = re.findall(r'href=[\'"]?([^\'" >]+)', s)
print ', '.join(urls)
</code></pre>
<p>Where <code>s</code> is the string that you're looking for matches in.</p>
<p><em>Quick explanation of the regexp bits:</em></p>
<blockquote>
<p><code>r'...'</code> is a "raw" string. It stops you having to worry about escaping characters quite as much as you normally would. (<code>\</code> especially -- in a raw string a <code>\</code> is just a <code>\</code>. In a regular string you'd have to do <code>\\</code> every time, and that gets <em>old</em> in regexps.)</p>
<p>"<code>href=[\'"]?</code>" says to match "href=", possibly followed by a <code>'</code> or <code>"</code>. "Possibly" because it's hard to say how horrible the HTML you're looking at is, and the quotes aren't strictly required.</p>
<p>Enclosing the next bit in "<code>()</code>" says to make it a "group", which means to split it out and return it separately to us. It's just a way to say "this is the part of the pattern I'm interested in."</p>
<p>"<code>[^\'" >]+</code>" says to match any characters that <em>aren't</em> <code>'</code>, <code>"</code>, <code>></code>, or a space. Essentially this is a list of characters that are an end to the URL. It lets us avoid trying to write a regexp that reliably matches a full URL, which can be a bit complicated.</p>
</blockquote>
<p>The suggestion in another answer to use BeautifulSoup isn't bad, but it does introduce a higher level of external requirements. Plus it doesn't help you in your stated goal of learning regexps, which I'd assume this specific html-parsing project is just a part of.</p>
<p>It's pretty easy to do:</p>
<pre><code>from BeautifulSoup import BeautifulSoup
soup = BeautifulSoup(html_to_parse)
for tag in soup.findAll('a', href=True):
print tag['href']
</code></pre>
<p>Once you've installed BeautifulSoup, anyway.</p>
| 50
|
2009-01-31T19:17:06Z
|
[
"python",
"regex"
] |
Regular expression to extract URL from an HTML link
| 499,345
|
<p>Iâm a newbie in Python. Iâm learning regexes, but I need help here.</p>
<p>Here comes the HTML source:</p>
<pre><code><a href="http://www.ptop.se" target="_blank">http://www.ptop.se</a>
</code></pre>
<p>Iâm trying to code a tool that only prints out <code>http://ptop.se</code>. Can you help me please?</p>
| 22
|
2009-01-31T19:02:34Z
| 499,400
|
<p>There's tonnes of them on <a href="http://regexlib.com/default.aspx" rel="nofollow">regexlib</a></p>
| 1
|
2009-01-31T19:34:19Z
|
[
"python",
"regex"
] |
Regular expression to extract URL from an HTML link
| 499,345
|
<p>Iâm a newbie in Python. Iâm learning regexes, but I need help here.</p>
<p>Here comes the HTML source:</p>
<pre><code><a href="http://www.ptop.se" target="_blank">http://www.ptop.se</a>
</code></pre>
<p>Iâm trying to code a tool that only prints out <code>http://ptop.se</code>. Can you help me please?</p>
| 22
|
2009-01-31T19:02:34Z
| 858,248
|
<p>Yes, there are tons of them on <a href="http://regexlib.com/" rel="nofollow">regexlib</a>. That only proves that RE's should not be used to do that. Use SGMLParser or BeautifulSoup or write a parser - but don't use RE's. The ones that seems to work are extremely compliated and still don't cover all cases.</p>
| 1
|
2009-05-13T14:22:29Z
|
[
"python",
"regex"
] |
Regular expression to extract URL from an HTML link
| 499,345
|
<p>Iâm a newbie in Python. Iâm learning regexes, but I need help here.</p>
<p>Here comes the HTML source:</p>
<pre><code><a href="http://www.ptop.se" target="_blank">http://www.ptop.se</a>
</code></pre>
<p>Iâm trying to code a tool that only prints out <code>http://ptop.se</code>. Can you help me please?</p>
| 22
|
2009-01-31T19:02:34Z
| 858,343
|
<p>Regexes are fundamentally bad at parsing HTML (see <a href="http://stackoverflow.com/questions/701166">Can you provide some examples of why it is hard to parse XML and HTML with a regex?</a> for why). What you need is an HTML parser. See <a href="http://stackoverflow.com/questions/773340">Can you provide an example of parsing HTML with your favorite parser?</a> for examples using a variety of parsers.</p>
<p>In particular you will want to look at the Python answers: <a href="http://stackoverflow.com/questions/773340/can-you-provide-an-example-of-parsing-html-with-your-favorite-parser/773565#773565">BeautifulSoup</a>, <a href="http://stackoverflow.com/questions/773340/can-you-provide-an-example-of-parsing-html-with-your-favorite-parser/773344#773344">HTMLParser</a>, and <a href="http://stackoverflow.com/questions/773340/can-you-provide-an-example-of-parsing-html-with-your-favorite-parser/774062#774062">lxml</a>.</p>
| 4
|
2009-05-13T14:38:27Z
|
[
"python",
"regex"
] |
Regular expression to extract URL from an HTML link
| 499,345
|
<p>Iâm a newbie in Python. Iâm learning regexes, but I need help here.</p>
<p>Here comes the HTML source:</p>
<pre><code><a href="http://www.ptop.se" target="_blank">http://www.ptop.se</a>
</code></pre>
<p>Iâm trying to code a tool that only prints out <code>http://ptop.se</code>. Can you help me please?</p>
| 22
|
2009-01-31T19:02:34Z
| 1,811,011
|
<p>John Gruber (who wrote Markdown, which is made of regular expressions and is used right here on Stack Overflow) had a go at producing a regular expression that recognises URLs in text:</p>
<p><a href="http://daringfireball.net/2009/11/liberal%5Fregex%5Ffor%5Fmatching%5Furls">http://daringfireball.net/2009/11/liberal_regex_for_matching_urls</a></p>
<p>If you just want to grab the URL (i.e. youâre not really trying to parse the HTML), this might be more lightweight than an HTML parser.</p>
| 8
|
2009-11-27T23:37:54Z
|
[
"python",
"regex"
] |
Regular expression to extract URL from an HTML link
| 499,345
|
<p>Iâm a newbie in Python. Iâm learning regexes, but I need help here.</p>
<p>Here comes the HTML source:</p>
<pre><code><a href="http://www.ptop.se" target="_blank">http://www.ptop.se</a>
</code></pre>
<p>Iâm trying to code a tool that only prints out <code>http://ptop.se</code>. Can you help me please?</p>
| 22
|
2009-01-31T19:02:34Z
| 37,339,086
|
<p>This works pretty well with using optional matches (prints after <code>href=</code>) and gets the link only. Tested on <a href="http://pythex.org/" rel="nofollow">http://pythex.org/</a></p>
<pre><code>(?:href=['"])([:/.A-z?<_&\s=>0-9;-]+)
</code></pre>
<p>Oputput:</p>
<blockquote>
<p>Match 1. /wiki/Main_Page</p>
<p>Match 2. /wiki/Portal:Contents</p>
<p>Match 3. /wiki/Portal:Featured_content</p>
<p>Match 4. /wiki/Portal:Current_events</p>
<p>Match 5. /wiki/Special:Random</p>
<p>Match 6. //donate.wikimedia.org/wiki/Special:FundraiserRedirector?utm_source=donate&utm_medium=sidebar&utm_campaign=C13_en.wikipedia.org&uselang=en</p>
</blockquote>
| 0
|
2016-05-20T06:07:46Z
|
[
"python",
"regex"
] |
What's the best serialization method for objects in memcached?
| 499,593
|
<p>My Python application currently uses the <a href="http://www.tummy.com/Community/software/python-memcached/">python-memcached API</a> to set and get objects in memcached. This API uses Python's native <a href="http://docs.python.org/library/pickle.html">pickle module</a> to serialize and de-serialize Python objects. <p>This API makes it simple and fast to store nested Python lists, dictionaries and tuples in memcached, and reading these objects back into the application is completely transparent -- it just works.<p>But I don't want to be limited to using Python exclusively, and if all the memcached objects are serialized with pickle, then clients written in other languages won't work.<p>Here are the cross-platform serialization options I've considered:<p></p>
<ol>
<li>XML - the main benefit is that it's human-readable, but that's not important in this application. XML also takes a lot space, and it's expensive to parse.<p></li>
<li>JSON - seems like a good cross-platform standard, but I'm not sure it retains the character of object types when read back from memcached. For example, according to <a href="http://stackoverflow.com/questions/408866/python-human-readable-object-serialization">this post</a> tuples are transformed into lists when using <a href="http://pypi.python.org/pypi/simplejson/">simplejson</a>; also, it seems like adding elements to the JSON structure could break code written to the old structure<p></li>
<li><a href="http://code.google.com/apis/protocolbuffers/docs/overview.html">Google Protocol Buffers</a> - I'm really interested in this because it seems very fast and compact -- at least 10 times smaller and faster than XML; it's not human-readable, but that's not important for this app; and it seems designed to support growing the structure without breaking old code<p></li>
</ol>
<p>Considering the priorities for this app, what's the ideal object serialization method for memcached?<p></p>
<ol>
<li>Cross-platform support (Python, Java, C#, C++, Ruby, Perl)<p></li>
<li>Handling nested data structures<p></li>
<li>Fast serialization/de-serialization<p></li>
<li>Minimum memory footprint<p></li>
<li>Flexibility to change structure without breaking old code</li>
</ol>
| 23
|
2009-01-31T21:17:24Z
| 499,678
|
<p>"Cross-platform support (Python, Java, C#, C++, Ruby, Perl)"</p>
<p>Too bad this criteria is first. The intent behind most languages is to express fundamental data structures and processing differently. That's what makes multiple languages a "problem": they're all different. </p>
<p>A single representation that's good across many languages is generally impossible. There are compromises in richness of the representation, performance or ambiguity.</p>
<p>JSON meets the remaining criteria nicely. Messages are compact and parse quickly (unlike XML). Nesting is handled nicely. Changing structure without breaking code is always iffy -- if you remove something, old code will break. If you change something that was required, old code will break. If you're adding things, however, JSON handles this also.</p>
<p>I like human-readable. It helps with a lot of debugging and trouble-shooting.</p>
<p>The subtlety of having Python tuples turn into lists isn't an interesting problem. The receiving application already knows the structure being received, and can tweak it up (if it matters.)</p>
<p><hr /></p>
<p>Edit on performance.</p>
<p>Parsing the XML and JSON documents from <a href="http://developers.de/blogs/damir_dobric/archive/2008/12/27/performance-comparison-soap-vs-json-wcf-implementation.aspx" rel="nofollow">http://developers.de/blogs/damir_dobric/archive/2008/12/27/performance-comparison-soap-vs-json-wcf-implementation.aspx</a></p>
<p>xmlParse 0.326
jsonParse 0.255</p>
<p>JSON appears to be significantly faster for the same content. I used the Python SimpleJSON and ElementTree modules in Python 2.5.2.</p>
| 2
|
2009-01-31T22:13:41Z
|
[
"python",
"serialization",
"xml-serialization",
"memcached",
"protocol-buffers"
] |
What's the best serialization method for objects in memcached?
| 499,593
|
<p>My Python application currently uses the <a href="http://www.tummy.com/Community/software/python-memcached/">python-memcached API</a> to set and get objects in memcached. This API uses Python's native <a href="http://docs.python.org/library/pickle.html">pickle module</a> to serialize and de-serialize Python objects. <p>This API makes it simple and fast to store nested Python lists, dictionaries and tuples in memcached, and reading these objects back into the application is completely transparent -- it just works.<p>But I don't want to be limited to using Python exclusively, and if all the memcached objects are serialized with pickle, then clients written in other languages won't work.<p>Here are the cross-platform serialization options I've considered:<p></p>
<ol>
<li>XML - the main benefit is that it's human-readable, but that's not important in this application. XML also takes a lot space, and it's expensive to parse.<p></li>
<li>JSON - seems like a good cross-platform standard, but I'm not sure it retains the character of object types when read back from memcached. For example, according to <a href="http://stackoverflow.com/questions/408866/python-human-readable-object-serialization">this post</a> tuples are transformed into lists when using <a href="http://pypi.python.org/pypi/simplejson/">simplejson</a>; also, it seems like adding elements to the JSON structure could break code written to the old structure<p></li>
<li><a href="http://code.google.com/apis/protocolbuffers/docs/overview.html">Google Protocol Buffers</a> - I'm really interested in this because it seems very fast and compact -- at least 10 times smaller and faster than XML; it's not human-readable, but that's not important for this app; and it seems designed to support growing the structure without breaking old code<p></li>
</ol>
<p>Considering the priorities for this app, what's the ideal object serialization method for memcached?<p></p>
<ol>
<li>Cross-platform support (Python, Java, C#, C++, Ruby, Perl)<p></li>
<li>Handling nested data structures<p></li>
<li>Fast serialization/de-serialization<p></li>
<li>Minimum memory footprint<p></li>
<li>Flexibility to change structure without breaking old code</li>
</ol>
| 23
|
2009-01-31T21:17:24Z
| 564,135
|
<p><strong>One major consideration is "do you want to have to specify each structure definition"</strong>? </p>
<p>If you are OK with that, then you could take a look at:</p>
<ol>
<li><a href="http://code.google.com/apis/protocolbuffers/docs/overview.html">Protocol Buffers - <a href="http://code.google.com/apis/protocolbuffers/docs/overview.html">http://code.google.com/apis/protocolbuffers/docs/overview.html</a></a></li>
<li><a href="http://developers.facebook.com/thrift/">Thrift - <a href="http://developers.facebook.com/thrift/">http://developers.facebook.com/thrift/</a></a> (more geared toward services)</li>
</ol>
<p>Both of these solutions require supporting files to define each data structure. </p>
<p><hr /></p>
<p>If you would prefer not to incur the developer overhead of pre-defining each structure, then take a look at:</p>
<ol>
<li>JSON (via python cjson, and native PHP json). Both are really really fast if you don't need to transmit binary content (such as images, etc...).</li>
<li>Yet Another Markup Language @ <a href="http://www.yaml.org/">http://www.yaml.org/</a>. Also really fast if you get the right library.</li>
</ol>
<p>However, I believe that both of these have had issues with transporting binary content, which is why they were ruled out for our usage. <strong>Note:</strong> YAML may have good binary support, you will have to check the client libraries -- see here: <a href="http://yaml.org/type/binary.html">http://yaml.org/type/binary.html</a></p>
<p><hr /></p>
<p>At our company, we rolled our own library (Extruct) for cross-language serialization with binary support. We currently have (decently) fast implementations in Python and PHP, although it isn't very human readable due to using base64 on all the strings (binary support). Eventually we will port them to C and use more standard encoding.</p>
<p>Dynamic languages like PHP and Python get really slow if you have too many iterations in a loop or have to look at each character. C on the other hand shines at such operations.</p>
<p>If you'd like to see the implementation of Extruct, please let me know. (contact info at <a href="http://blog.gahooa.com/">http://blog.gahooa.com/</a> under "About Me")</p>
| 6
|
2009-02-19T06:14:44Z
|
[
"python",
"serialization",
"xml-serialization",
"memcached",
"protocol-buffers"
] |
What's the best serialization method for objects in memcached?
| 499,593
|
<p>My Python application currently uses the <a href="http://www.tummy.com/Community/software/python-memcached/">python-memcached API</a> to set and get objects in memcached. This API uses Python's native <a href="http://docs.python.org/library/pickle.html">pickle module</a> to serialize and de-serialize Python objects. <p>This API makes it simple and fast to store nested Python lists, dictionaries and tuples in memcached, and reading these objects back into the application is completely transparent -- it just works.<p>But I don't want to be limited to using Python exclusively, and if all the memcached objects are serialized with pickle, then clients written in other languages won't work.<p>Here are the cross-platform serialization options I've considered:<p></p>
<ol>
<li>XML - the main benefit is that it's human-readable, but that's not important in this application. XML also takes a lot space, and it's expensive to parse.<p></li>
<li>JSON - seems like a good cross-platform standard, but I'm not sure it retains the character of object types when read back from memcached. For example, according to <a href="http://stackoverflow.com/questions/408866/python-human-readable-object-serialization">this post</a> tuples are transformed into lists when using <a href="http://pypi.python.org/pypi/simplejson/">simplejson</a>; also, it seems like adding elements to the JSON structure could break code written to the old structure<p></li>
<li><a href="http://code.google.com/apis/protocolbuffers/docs/overview.html">Google Protocol Buffers</a> - I'm really interested in this because it seems very fast and compact -- at least 10 times smaller and faster than XML; it's not human-readable, but that's not important for this app; and it seems designed to support growing the structure without breaking old code<p></li>
</ol>
<p>Considering the priorities for this app, what's the ideal object serialization method for memcached?<p></p>
<ol>
<li>Cross-platform support (Python, Java, C#, C++, Ruby, Perl)<p></li>
<li>Handling nested data structures<p></li>
<li>Fast serialization/de-serialization<p></li>
<li>Minimum memory footprint<p></li>
<li>Flexibility to change structure without breaking old code</li>
</ol>
| 23
|
2009-01-31T21:17:24Z
| 600,483
|
<p>I tried several methods and settled on compressed JSON as the best balance between speed and memory footprint. Python's native Pickle function is slightly faster, but the resulting objects can't be used with non-Python clients.</p>
<p>I'm seeing 3:1 compression so all the data fits in memcache and the app gets sub-10ms response times including page rendering.</p>
<p>Here's a comparison of JSON, Thrift, Protocol Buffers and YAML, with and without compression:</p>
<p><a href="http://bouncybouncy.net/ramblings/posts/more%5Fon%5Fjson%5Fvs%5Fthrift%5Fand%5Fprotocol%5Fbuffers/">http://bouncybouncy.net/ramblings/posts/more_on_json_vs_thrift_and_protocol_buffers/</a></p>
<p>Looks like this test got the same results I did with compressed JSON. Since I don't need to pre-define each structure, this seems like the fastest and smallest cross-platform answer.</p>
| 7
|
2009-03-01T20:47:27Z
|
[
"python",
"serialization",
"xml-serialization",
"memcached",
"protocol-buffers"
] |
What's the best serialization method for objects in memcached?
| 499,593
|
<p>My Python application currently uses the <a href="http://www.tummy.com/Community/software/python-memcached/">python-memcached API</a> to set and get objects in memcached. This API uses Python's native <a href="http://docs.python.org/library/pickle.html">pickle module</a> to serialize and de-serialize Python objects. <p>This API makes it simple and fast to store nested Python lists, dictionaries and tuples in memcached, and reading these objects back into the application is completely transparent -- it just works.<p>But I don't want to be limited to using Python exclusively, and if all the memcached objects are serialized with pickle, then clients written in other languages won't work.<p>Here are the cross-platform serialization options I've considered:<p></p>
<ol>
<li>XML - the main benefit is that it's human-readable, but that's not important in this application. XML also takes a lot space, and it's expensive to parse.<p></li>
<li>JSON - seems like a good cross-platform standard, but I'm not sure it retains the character of object types when read back from memcached. For example, according to <a href="http://stackoverflow.com/questions/408866/python-human-readable-object-serialization">this post</a> tuples are transformed into lists when using <a href="http://pypi.python.org/pypi/simplejson/">simplejson</a>; also, it seems like adding elements to the JSON structure could break code written to the old structure<p></li>
<li><a href="http://code.google.com/apis/protocolbuffers/docs/overview.html">Google Protocol Buffers</a> - I'm really interested in this because it seems very fast and compact -- at least 10 times smaller and faster than XML; it's not human-readable, but that's not important for this app; and it seems designed to support growing the structure without breaking old code<p></li>
</ol>
<p>Considering the priorities for this app, what's the ideal object serialization method for memcached?<p></p>
<ol>
<li>Cross-platform support (Python, Java, C#, C++, Ruby, Perl)<p></li>
<li>Handling nested data structures<p></li>
<li>Fast serialization/de-serialization<p></li>
<li>Minimum memory footprint<p></li>
<li>Flexibility to change structure without breaking old code</li>
</ol>
| 23
|
2009-01-31T21:17:24Z
| 3,723,223
|
<p>You might be interested into this link :</p>
<p><a href="http://kbyanc.blogspot.com/2007/07/python-serializer-benchmarks.html" rel="nofollow">http://kbyanc.blogspot.com/2007/07/python-serializer-benchmarks.html</a></p>
<p>An alternative : MessagePack seems to be the fastest serializer out there. Maybe you can give it a try.</p>
| 2
|
2010-09-16T02:07:53Z
|
[
"python",
"serialization",
"xml-serialization",
"memcached",
"protocol-buffers"
] |
What's the best serialization method for objects in memcached?
| 499,593
|
<p>My Python application currently uses the <a href="http://www.tummy.com/Community/software/python-memcached/">python-memcached API</a> to set and get objects in memcached. This API uses Python's native <a href="http://docs.python.org/library/pickle.html">pickle module</a> to serialize and de-serialize Python objects. <p>This API makes it simple and fast to store nested Python lists, dictionaries and tuples in memcached, and reading these objects back into the application is completely transparent -- it just works.<p>But I don't want to be limited to using Python exclusively, and if all the memcached objects are serialized with pickle, then clients written in other languages won't work.<p>Here are the cross-platform serialization options I've considered:<p></p>
<ol>
<li>XML - the main benefit is that it's human-readable, but that's not important in this application. XML also takes a lot space, and it's expensive to parse.<p></li>
<li>JSON - seems like a good cross-platform standard, but I'm not sure it retains the character of object types when read back from memcached. For example, according to <a href="http://stackoverflow.com/questions/408866/python-human-readable-object-serialization">this post</a> tuples are transformed into lists when using <a href="http://pypi.python.org/pypi/simplejson/">simplejson</a>; also, it seems like adding elements to the JSON structure could break code written to the old structure<p></li>
<li><a href="http://code.google.com/apis/protocolbuffers/docs/overview.html">Google Protocol Buffers</a> - I'm really interested in this because it seems very fast and compact -- at least 10 times smaller and faster than XML; it's not human-readable, but that's not important for this app; and it seems designed to support growing the structure without breaking old code<p></li>
</ol>
<p>Considering the priorities for this app, what's the ideal object serialization method for memcached?<p></p>
<ol>
<li>Cross-platform support (Python, Java, C#, C++, Ruby, Perl)<p></li>
<li>Handling nested data structures<p></li>
<li>Fast serialization/de-serialization<p></li>
<li>Minimum memory footprint<p></li>
<li>Flexibility to change structure without breaking old code</li>
</ol>
| 23
|
2009-01-31T21:17:24Z
| 9,319,326
|
<p>Hessian meets all of your requirements. There is a python library here:</p>
<p><a href="https://github.com/bgilmore/mustaine" rel="nofollow">https://github.com/bgilmore/mustaine</a></p>
<p>The official documentation for the protocol can be found here:</p>
<p><a href="http://hessian.caucho.com/" rel="nofollow">http://hessian.caucho.com/</a></p>
<p>I regularly use it in both Java and Python. It works and doesn't require writing protocol definition files. I couldn't tell you how the Python serializer performs, but the Java version is reasonably efficient:</p>
<p><a href="https://github.com/eishay/jvm-serializers/wiki/" rel="nofollow">https://github.com/eishay/jvm-serializers/wiki/</a></p>
| 1
|
2012-02-16T21:25:25Z
|
[
"python",
"serialization",
"xml-serialization",
"memcached",
"protocol-buffers"
] |
Passing JSON strings larger than 80 characters
| 499,596
|
<p>I'm having a problem passing strings that exceed 80 characters in JSON. When I pass a string that's exactly 80 characters long it works like magic. But once I add the 81st letter it craps out. I've tried looking at the json object in firebug and it seems to think the string is an array because it has an expander next to it. Clicking the expander though does nothing. I've tried searching online for caps on JSON string sizes and work arounds but am coming up empty :(. Anybody know anything about this?</p>
<p>edit:</p>
<p>It actually doesn't matter what the string is... using "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz" yields the same results.</p>
<p>Here's my code: (I'm using python)</p>
<p>result = {"test": "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz"}
self.response.out.write(simplejson.dumps(result))</p>
<p>would you happen to know the class that encodes strings properly for python? Thanks so much :)</p>
| -3
|
2009-01-31T21:18:00Z
| 499,612
|
<p>What is the 81st character? Sounds like the string isn't properly escaped, making the json decoder think it is an array. If you could post the string here, or at least the 20 or so characters around 80, I could probably tell you what is wrong. Also, if you could tell how the json string was made. In most languages you can get a class that will make proper json strings out of objects and arrays. For example, php has <a href="http://no2.php.net/manual/en/function.json-encode.php" rel="nofollow">json_encode();</a></p>
| 1
|
2009-01-31T21:23:48Z
|
[
"python",
"string",
"json",
"size",
"max"
] |
Can I use IPython in an embedded interactive Python console?
| 499,705
|
<p>I use the following snippet to drop into a Python shell mid-program. This works fine, but I only get the standard console. Is there a way to do the same but using the <a href="http://ipython.scipy.org/">IPython</a> shell?</p>
<pre><code>import code
class EmbeddedConsole(code.InteractiveConsole):
def start(self):
try:
self.interact("Debug console starting...")
except:
print("Debug console closing...")
def print_names():
print(adam)
print(bob)
adam = "I am Adam"
bob = "I am Bob"
print_names()
console = EmbeddedConsole(locals())
console.start()
print_names()
</code></pre>
| 7
|
2009-01-31T22:29:21Z
| 499,718
|
<p><a href="http://www.ifi.uio.no/~inf3330/scripting/doc/python/ipython/node9.html" rel="nofollow">Embedding IPython</a> might be interesting for you.</p>
<p>Mininum of code to run IPython in your app:</p>
<pre><code>from IPython.Shell import IPShellEmbed
ipshell = IPShellEmbed()
ipshell() # this call anywhere in your program will start IPython
</code></pre>
| 2
|
2009-01-31T22:35:29Z
|
[
"python",
"console"
] |
Can I use IPython in an embedded interactive Python console?
| 499,705
|
<p>I use the following snippet to drop into a Python shell mid-program. This works fine, but I only get the standard console. Is there a way to do the same but using the <a href="http://ipython.scipy.org/">IPython</a> shell?</p>
<pre><code>import code
class EmbeddedConsole(code.InteractiveConsole):
def start(self):
try:
self.interact("Debug console starting...")
except:
print("Debug console closing...")
def print_names():
print(adam)
print(bob)
adam = "I am Adam"
bob = "I am Bob"
print_names()
console = EmbeddedConsole(locals())
console.start()
print_names()
</code></pre>
| 7
|
2009-01-31T22:29:21Z
| 19,891,856
|
<p>The answer by f3lix is no longer valid it seems, I was able to find this however:</p>
<p>At the top of your python script:</p>
<pre><code>from IPython import embed
</code></pre>
<p>Wherever you want to spin up a console:</p>
<pre><code>embed()
</code></pre>
| 13
|
2013-11-10T16:04:12Z
|
[
"python",
"console"
] |
How do you create python methods(signature and content) in code?
| 499,964
|
<p>I've created a method that generates a new class and adds some methods into the class, but there is a strange bug, and I'm not sure what's happening:</p>
<pre><code>def make_image_form(image_fields):
''' Takes a list of image_fields to generate images '''
images = SortedDict()
for image_name in image_fields:
images[image_name] = forms.ImageField(required=False)
new_form = type('ListingImagesForm2', (forms.BaseForm,), {'base_fields' : images})
#now we add the validation methods to the class
for image_name in image_fields:
print "image name is: ", image_name
setattr(new_form, 'clean_' + image_name, lambda self: self._clean_photo(image_name))
#Add the _clean_photo method to the class
setattr(new_form, '_clean_photo', _clean_photo)
return new_form
</code></pre>
<p>This is my method, which takes a list of image_fields (I'm making a site in Django), and it creates a whole bunch of ImageField fields, and creates a class ListingImagesForm2, and assigns the image fields to the class.</p>
<p>The problem is in creating the methods, and more specifically the method content.</p>
<p>In the loop:</p>
<pre><code>for image_name in image_fields:
print "image name is: ", image_name
setattr(new_form, 'clean_' + image_name, lambda self: self._clean_photo(image_name))
</code></pre>
<p>The methods signatures are created correctly (e.g. clean_pic_1, clean_pic_2...) , but I think there is a problem in the lambda expression, as the _clean_photo method is always called with the same image name (which happens to be the last image name in the image_fields list).</p>
<p>Is there any nicer way to create dynamic method content(code), than using lambda expressions? </p>
<p>And why would my lambda expression only pass _clean_photo the last image_name in the for loop?</p>
| 3
|
2009-02-01T01:10:43Z
| 499,978
|
<p>Python code behaves like this for functions defined in scope of methods.
Use this instead:</p>
<pre><code>for image_name in image_fields:
print "image name is: ", image_name
setattr(new_form, 'clean_' + image_name,
lambda self, iname=image_name: self._clean_photo(iname))
</code></pre>
<p>The usage of default keyword argument makes Python remember it at the time of lambda function creation rather than at the time of its calling (when it would always take the last image).</p>
| 4
|
2009-02-01T01:23:47Z
|
[
"python",
"django",
"dynamic",
"methods",
"lambda"
] |
Can I log into a web application automatically using a users windows logon?
| 500,134
|
<p>On the intranet at my part time job (not IT related) there are various web applications that we use that do not require logging in explicitly. We are required to login to Windows obviously, and that then authenticates us some how.</p>
<p>I'm wondering how this is done? Without worrying about security TOO much, how would I go about authenticating a user to a web application, utilizing the windows login information? I'd be using Python (and Django). </p>
<p>Are there limitations on how this can be achieved? For instance, would a specific browser be required? Would the application and intranet backend have to be hosted at the same location or at least have to communicate? Or is it simply getting the users Windows credentials, and passing that to the authentication software of the web application?</p>
| 2
|
2009-02-01T03:37:44Z
| 500,155
|
<p>Once upon a time Internet Explorer supported NTLM authentication (similar to Basic Auth but it sent cached credentials to the server which could be verified with the domain controller). It was used to enable single-signon within an intranet where everyone was expected to be logged into the domain. I don't recall the details of it and I haven't used it for ages. It may still be an option if it fits your needs. </p>
<p>Maybe someone more familiar with it may have more details.</p>
<p>See: <a href="http://www.innovation.ch/personal/ronald/ntlm.html" rel="nofollow">NTLM Authentication Scheme for HTTP</a></p>
<p>The tricky part of using non-microsoft server framework is going to be talking with the necessary services to verify the credentials.</p>
| 2
|
2009-02-01T03:50:06Z
|
[
"python",
"authentication",
"web-applications",
"windows-authentication"
] |
Can I log into a web application automatically using a users windows logon?
| 500,134
|
<p>On the intranet at my part time job (not IT related) there are various web applications that we use that do not require logging in explicitly. We are required to login to Windows obviously, and that then authenticates us some how.</p>
<p>I'm wondering how this is done? Without worrying about security TOO much, how would I go about authenticating a user to a web application, utilizing the windows login information? I'd be using Python (and Django). </p>
<p>Are there limitations on how this can be achieved? For instance, would a specific browser be required? Would the application and intranet backend have to be hosted at the same location or at least have to communicate? Or is it simply getting the users Windows credentials, and passing that to the authentication software of the web application?</p>
| 2
|
2009-02-01T03:37:44Z
| 500,198
|
<p>From <a href="http://www.djangosnippets.org/snippets/501/" rel="nofollow">here</a>:</p>
<pre><code>-- Added to settings.py --
### ACTIVE DIRECTORY SETTINGS
# AD_DNS_NAME should set to the AD DNS name of the domain (ie; example.com)
# If you are not using the AD server as your DNS, it can also be set to
# FQDN or IP of the AD server.
AD_DNS_NAME = 'example.com'
AD_LDAP_PORT = 389
AD_SEARCH_DN = 'CN=Users,dc=example,dc=com'
# This is the NT4/Samba domain name
AD_NT4_DOMAIN = 'EXAMPLE'
AD_SEARCH_FIELDS = ['mail','givenName','sn','sAMAccountName']
AD_LDAP_URL = 'ldap://%s:%s' % (AD_DNS_NAME,AD_LDAP_PORT)
-- In the auth.py file --
from django.contrib.auth.models import User
from django.conf import settings
import ldap
class ActiveDirectoryBackend:
def authenticate(self,username=None,password=None):
if not self.is_valid(username,password):
return None
try:
user = User.objects.get(username=username)
except User.DoesNotExist:
l = ldap.initialize(settings.AD_LDAP_URL)
l.simple_bind_s(username,password)
result = l.search_ext_s(settings.AD_SEARCH_DN,ldap.SCOPE_SUBTREE,
"sAMAccountName=%s" % username,settings.AD_SEARCH_FIELDS)[0][1]
l.unbind_s()
# givenName == First Name
if result.has_key('givenName'):
first_name = result['givenName'][0]
else:
first_name = None
# sn == Last Name (Surname)
if result.has_key('sn'):
last_name = result['sn'][0]
else:
last_name = None
# mail == Email Address
if result.has_key('mail'):
email = result['mail'][0]
else:
email = None
user = User(username=username,first_name=first_name,last_name=last_name,email=email)
user.is_staff = False
user.is_superuser = False
user.set_password(password)
user.save()
return user
def get_user(self,user_id):
try:
return User.objects.get(pk=user_id)
except User.DoesNotExist:
return None
def is_valid (self,username=None,password=None):
## Disallowing null or blank string as password
## as per comment: http://www.djangosnippets.org/snippets/501/#c868
if password == None or password == '':
return False
binddn = "%s@%s" % (username,settings.AD_NT4_DOMAIN)
try:
l = ldap.initialize(settings.AD_LDAP_URL)
l.simple_bind_s(binddn,password)
l.unbind_s()
return True
except ldap.LDAPError:
return False
</code></pre>
| 1
|
2009-02-01T04:20:08Z
|
[
"python",
"authentication",
"web-applications",
"windows-authentication"
] |
Can I log into a web application automatically using a users windows logon?
| 500,134
|
<p>On the intranet at my part time job (not IT related) there are various web applications that we use that do not require logging in explicitly. We are required to login to Windows obviously, and that then authenticates us some how.</p>
<p>I'm wondering how this is done? Without worrying about security TOO much, how would I go about authenticating a user to a web application, utilizing the windows login information? I'd be using Python (and Django). </p>
<p>Are there limitations on how this can be achieved? For instance, would a specific browser be required? Would the application and intranet backend have to be hosted at the same location or at least have to communicate? Or is it simply getting the users Windows credentials, and passing that to the authentication software of the web application?</p>
| 2
|
2009-02-01T03:37:44Z
| 500,260
|
<p>To the best of my knowledge the only browser that automatically passes your login credentials is Internet Explorer. To enable this feature select "Enable Integrated Windows Authentication" in the advanced Internet options dialog under the security section. This is usually enabled by default. </p>
<p>The web server will have to have the Anonymous user permission removed from the web application and enable windows authentication option checked. Simply add the users you want to have access to the web application to the file/folder permissions. </p>
<p>I have only tried this with IIS so I'm not sure if it will work on other web servers.</p>
| 0
|
2009-02-01T05:15:19Z
|
[
"python",
"authentication",
"web-applications",
"windows-authentication"
] |
Python's timedelta: can't I just get in whatever time unit I want the value of the entire difference?
| 500,168
|
<p>I am trying to have some clever dates since a post has been made on my site ("seconds since, hours since, weeks since, etc..") and I'm using datetime.timedelta difference between utcnow and utc dated stored in the database for a post.</p>
<p>Looks like, according to the docs, I have to use the days attribute AND the seconds attribute, to get the fancy date strings I want. </p>
<p>Can't I just get in whatever time unit I want the value of the entire difference? Am I missing something? </p>
<p>It would be perfect if I could just get the entire difference in seconds.</p>
| 14
|
2009-02-01T03:59:27Z
| 500,195
|
<p>You can compute the difference in seconds.</p>
<pre><code>total_seconds = delta.days * 86400 + delta.seconds
</code></pre>
<p>No, you're no "missing something". It doesn't provide deltas in seconds. </p>
| 15
|
2009-02-01T04:17:58Z
|
[
"python",
"datetime",
"timedelta"
] |
Python's timedelta: can't I just get in whatever time unit I want the value of the entire difference?
| 500,168
|
<p>I am trying to have some clever dates since a post has been made on my site ("seconds since, hours since, weeks since, etc..") and I'm using datetime.timedelta difference between utcnow and utc dated stored in the database for a post.</p>
<p>Looks like, according to the docs, I have to use the days attribute AND the seconds attribute, to get the fancy date strings I want. </p>
<p>Can't I just get in whatever time unit I want the value of the entire difference? Am I missing something? </p>
<p>It would be perfect if I could just get the entire difference in seconds.</p>
| 14
|
2009-02-01T03:59:27Z
| 500,204
|
<blockquote>
<p>It would be perfect if I could just get the entire difference in seconds.</p>
</blockquote>
<p>Then plain-old-unix-timestamp as provided by the 'time' module may be more to your taste.</p>
<p>I personally have yet to be convinced by a lot of what's in 'datetime'.</p>
| 5
|
2009-02-01T04:24:45Z
|
[
"python",
"datetime",
"timedelta"
] |
Python's timedelta: can't I just get in whatever time unit I want the value of the entire difference?
| 500,168
|
<p>I am trying to have some clever dates since a post has been made on my site ("seconds since, hours since, weeks since, etc..") and I'm using datetime.timedelta difference between utcnow and utc dated stored in the database for a post.</p>
<p>Looks like, according to the docs, I have to use the days attribute AND the seconds attribute, to get the fancy date strings I want. </p>
<p>Can't I just get in whatever time unit I want the value of the entire difference? Am I missing something? </p>
<p>It would be perfect if I could just get the entire difference in seconds.</p>
| 14
|
2009-02-01T03:59:27Z
| 500,437
|
<p>Like <a href="#500204">bobince</a> said, you could use timestamps, like this:</p>
<pre><code># assuming ts1 and ts2 are the two datetime objects
from time import mktime
mktime(ts1.timetuple()) - mktime(ts2.timetuple())
</code></pre>
<p>Although I would think this is even uglier than just calculating the seconds from the <code>timedelta</code> object...</p>
| 5
|
2009-02-01T08:34:09Z
|
[
"python",
"datetime",
"timedelta"
] |
Python's timedelta: can't I just get in whatever time unit I want the value of the entire difference?
| 500,168
|
<p>I am trying to have some clever dates since a post has been made on my site ("seconds since, hours since, weeks since, etc..") and I'm using datetime.timedelta difference between utcnow and utc dated stored in the database for a post.</p>
<p>Looks like, according to the docs, I have to use the days attribute AND the seconds attribute, to get the fancy date strings I want. </p>
<p>Can't I just get in whatever time unit I want the value of the entire difference? Am I missing something? </p>
<p>It would be perfect if I could just get the entire difference in seconds.</p>
| 14
|
2009-02-01T03:59:27Z
| 3,471,718
|
<p>It seems that Python 2.7 has introduced a <a href="http://docs.python.org/library/datetime.html#datetime.timedelta.total_seconds">total_seconds()</a> method, which is what you were looking for, I believe!</p>
| 21
|
2010-08-12T20:22:47Z
|
[
"python",
"datetime",
"timedelta"
] |
Identifying numeric and array types in numpy
| 500,328
|
<p>Is there an existing function in numpy that will tell me if a value is either a numeric type or a numpy array? I'm writing some data-processing code which needs to handle numbers in several different representations (by "number" I mean any representation of a numeric quantity which can be manipulated using the standard arithmetic operators, +, -, *, /, **).</p>
<p>Some examples of the behavior I'm looking for</p>
<pre><code>>>> is_numeric(5)
True
>>> is_numeric(123.345)
True
>>> is_numeric('123.345')
False
>>> is_numeric(decimal.Decimal('123.345'))
True
>>> is_numeric(True)
False
>>> is_numeric([1, 2, 3])
False
>>> is_numeric([1, '2', 3])
False
>>> a = numpy.array([1, 2.3, 4.5, 6.7, 8.9])
>>> is_numeric(a)
True
>>> is_numeric(a[0])
True
>>> is_numeric(a[1])
True
>>> is_numeric(numpy.array([numpy.array([1]), numpy.array([2])])
True
>>> is_numeric(numpy.array(['1'])
False
</code></pre>
<p>If no such function exists, I know it shouldn't be hard to write one, something like </p>
<pre><code>isinstance(n, (int, float, decimal.Decimal, numpy.number, numpy.ndarray))
</code></pre>
<p>but are there other numeric types I should include in the list?</p>
| 11
|
2009-02-01T06:17:38Z
| 500,392
|
<p>Your <code>is_numeric</code> is ill-defined. See my comments to your question.</p>
<p>Other numerical types could be: <code>long</code>, <code>complex</code>, <code>fractions.Fraction</code>, <code>numpy.bool_</code>, <code>numpy.ubyte</code>, ...</p>
<p><code>operator.isNumberType()</code> returns <code>True</code> for Python numbers and <code>numpy.array</code>.</p>
<p>Since Python 2.6 you can use <code>isinstance(d, numbers.Number)</code> instead of deprecated <code>operator.isNumberType()</code>.</p>
<p>Generally it is better to check the capabilities of the object (e.g., whether you can add an integer to it) and not its type.</p>
| 0
|
2009-02-01T07:31:03Z
|
[
"python",
"numpy"
] |
Identifying numeric and array types in numpy
| 500,328
|
<p>Is there an existing function in numpy that will tell me if a value is either a numeric type or a numpy array? I'm writing some data-processing code which needs to handle numbers in several different representations (by "number" I mean any representation of a numeric quantity which can be manipulated using the standard arithmetic operators, +, -, *, /, **).</p>
<p>Some examples of the behavior I'm looking for</p>
<pre><code>>>> is_numeric(5)
True
>>> is_numeric(123.345)
True
>>> is_numeric('123.345')
False
>>> is_numeric(decimal.Decimal('123.345'))
True
>>> is_numeric(True)
False
>>> is_numeric([1, 2, 3])
False
>>> is_numeric([1, '2', 3])
False
>>> a = numpy.array([1, 2.3, 4.5, 6.7, 8.9])
>>> is_numeric(a)
True
>>> is_numeric(a[0])
True
>>> is_numeric(a[1])
True
>>> is_numeric(numpy.array([numpy.array([1]), numpy.array([2])])
True
>>> is_numeric(numpy.array(['1'])
False
</code></pre>
<p>If no such function exists, I know it shouldn't be hard to write one, something like </p>
<pre><code>isinstance(n, (int, float, decimal.Decimal, numpy.number, numpy.ndarray))
</code></pre>
<p>but are there other numeric types I should include in the list?</p>
| 11
|
2009-02-01T06:17:38Z
| 500,395
|
<p>In general, the flexible, fast, and pythonic way to handle unknown types is to just perform some operation on them and catch an exception on invalid types. </p>
<pre><code>try:
a = 5+'5'
except TypeError:
print "Oops"
</code></pre>
<p>Seems to me that this approach is easier than special-casing out some function to determine absolute type certainty.</p>
| 5
|
2009-02-01T07:34:44Z
|
[
"python",
"numpy"
] |
Identifying numeric and array types in numpy
| 500,328
|
<p>Is there an existing function in numpy that will tell me if a value is either a numeric type or a numpy array? I'm writing some data-processing code which needs to handle numbers in several different representations (by "number" I mean any representation of a numeric quantity which can be manipulated using the standard arithmetic operators, +, -, *, /, **).</p>
<p>Some examples of the behavior I'm looking for</p>
<pre><code>>>> is_numeric(5)
True
>>> is_numeric(123.345)
True
>>> is_numeric('123.345')
False
>>> is_numeric(decimal.Decimal('123.345'))
True
>>> is_numeric(True)
False
>>> is_numeric([1, 2, 3])
False
>>> is_numeric([1, '2', 3])
False
>>> a = numpy.array([1, 2.3, 4.5, 6.7, 8.9])
>>> is_numeric(a)
True
>>> is_numeric(a[0])
True
>>> is_numeric(a[1])
True
>>> is_numeric(numpy.array([numpy.array([1]), numpy.array([2])])
True
>>> is_numeric(numpy.array(['1'])
False
</code></pre>
<p>If no such function exists, I know it shouldn't be hard to write one, something like </p>
<pre><code>isinstance(n, (int, float, decimal.Decimal, numpy.number, numpy.ndarray))
</code></pre>
<p>but are there other numeric types I should include in the list?</p>
| 11
|
2009-02-01T06:17:38Z
| 500,908
|
<p>As others have answered, there could be other numeric types besides the ones you mention.
One approach would be to check explicitly for the capabilities you want, with something like</p>
<pre><code># Python 2
def is_numeric(obj):
attrs = ['__add__', '__sub__', '__mul__', '__div__', '__pow__']
return all(hasattr(obj, attr) for attr in attrs)
# Python 3
def is_numeric(obj):
attrs = ['__add__', '__sub__', '__mul__', '__truediv__', '__pow__']
return all(hasattr(obj, attr) for attr in attrs)
</code></pre>
<p>This works for all your examples except the last one, <code>numpy.array(['1'])</code>. That's because <code>numpy.ndarray</code> has the special methods for numeric operations but raises TypeError if you try to use them inappropriately with string or object arrays. You could add an explicit check for this like</p>
<pre><code> ... and not (isinstance(obj, ndarray) and obj.dtype.kind in 'OSU')
</code></pre>
<p>This may be good enough. </p>
<p>But... you can never be <em>100%</em> sure that somebody won't define another type with the same behavior, so a more foolproof way is to actually try to do a calculation and catch the exception, something like</p>
<pre><code>def is_numeric_paranoid(obj):
try:
obj+obj, obj-obj, obj*obj, obj**obj, obj/obj
except ZeroDivisionError:
return True
except Exception:
return False
else:
return True
</code></pre>
<p>but depending on how often you plan to call use it and with what arguments, this may not be practical (it can be potentially slow, e.g. with large arrays).</p>
| 16
|
2009-02-01T14:22:55Z
|
[
"python",
"numpy"
] |
Identifying numeric and array types in numpy
| 500,328
|
<p>Is there an existing function in numpy that will tell me if a value is either a numeric type or a numpy array? I'm writing some data-processing code which needs to handle numbers in several different representations (by "number" I mean any representation of a numeric quantity which can be manipulated using the standard arithmetic operators, +, -, *, /, **).</p>
<p>Some examples of the behavior I'm looking for</p>
<pre><code>>>> is_numeric(5)
True
>>> is_numeric(123.345)
True
>>> is_numeric('123.345')
False
>>> is_numeric(decimal.Decimal('123.345'))
True
>>> is_numeric(True)
False
>>> is_numeric([1, 2, 3])
False
>>> is_numeric([1, '2', 3])
False
>>> a = numpy.array([1, 2.3, 4.5, 6.7, 8.9])
>>> is_numeric(a)
True
>>> is_numeric(a[0])
True
>>> is_numeric(a[1])
True
>>> is_numeric(numpy.array([numpy.array([1]), numpy.array([2])])
True
>>> is_numeric(numpy.array(['1'])
False
</code></pre>
<p>If no such function exists, I know it shouldn't be hard to write one, something like </p>
<pre><code>isinstance(n, (int, float, decimal.Decimal, numpy.number, numpy.ndarray))
</code></pre>
<p>but are there other numeric types I should include in the list?</p>
| 11
|
2009-02-01T06:17:38Z
| 2,100,075
|
<p><code>isinstance(numpy.int32(4), numbers.Number)</code> returns <code>False</code>, so that doesn't quite work. <code>operator.isNumberType()</code> does work on all the variants of numpy numbers, however, including <code>numpy.array([1])</code>.</p>
| 0
|
2010-01-20T08:54:13Z
|
[
"python",
"numpy"
] |
Identifying numeric and array types in numpy
| 500,328
|
<p>Is there an existing function in numpy that will tell me if a value is either a numeric type or a numpy array? I'm writing some data-processing code which needs to handle numbers in several different representations (by "number" I mean any representation of a numeric quantity which can be manipulated using the standard arithmetic operators, +, -, *, /, **).</p>
<p>Some examples of the behavior I'm looking for</p>
<pre><code>>>> is_numeric(5)
True
>>> is_numeric(123.345)
True
>>> is_numeric('123.345')
False
>>> is_numeric(decimal.Decimal('123.345'))
True
>>> is_numeric(True)
False
>>> is_numeric([1, 2, 3])
False
>>> is_numeric([1, '2', 3])
False
>>> a = numpy.array([1, 2.3, 4.5, 6.7, 8.9])
>>> is_numeric(a)
True
>>> is_numeric(a[0])
True
>>> is_numeric(a[1])
True
>>> is_numeric(numpy.array([numpy.array([1]), numpy.array([2])])
True
>>> is_numeric(numpy.array(['1'])
False
</code></pre>
<p>If no such function exists, I know it shouldn't be hard to write one, something like </p>
<pre><code>isinstance(n, (int, float, decimal.Decimal, numpy.number, numpy.ndarray))
</code></pre>
<p>but are there other numeric types I should include in the list?</p>
| 11
|
2009-02-01T06:17:38Z
| 2,106,212
|
<p>Also, numpy has <code>numpy.isreal</code> and other similar functions (<code>numpy.is</code> + Tab should list them).</p>
<p>They all have their fun corner cases but one of those could be useful.</p>
| 3
|
2010-01-21T01:00:35Z
|
[
"python",
"numpy"
] |
How to vertically align Paragraphs within a Table using Reportlab?
| 500,406
|
<p>I'm using Reportlab to generate report cards. The report cards are basically one big Table object. Some of the content in the table cells needs to wrap, specifically titles and comments, and I also need to bold certain elements.</p>
<p>To accomplish both the wrapping and ability to bold, I'm using Paragraph objects within the Table. My table needs several of these elements vertically aligned to 'middle' but the Paragraph alignment and snaps my text to the bottom of the cell.</p>
<p>How can I vertically align my Paragraph within a Table cell?</p>
| 3
|
2009-02-01T07:55:43Z
| 516,531
|
<p>I have to ask: have you tried the tablestyle VALIGN:MIDDLE?</p>
<p>something like:</p>
<pre><code>t=Table(data)
t.setStyle(TableStyle([('VALIGN',(-1,-1),(-1,-1),'MIDDLE')]))
</code></pre>
<p>(more details in section 7.2 of the ReportLab user guide)</p>
<p>If that doesn't do it, then your paragraph object must be the full height of the cell, and internally aligned to the bottom.</p>
<p>Could you please post a small sample that reproduces the problem?</p>
| 8
|
2009-02-05T16:01:15Z
|
[
"python",
"pdf",
"alignment",
"reportlab"
] |
using django-rest-interface with http put
| 500,434
|
<p>I'm trying to figure out how to implement my first RESTful interface using Django and django-rest-interface. I'm having problems with the HTTP PUT requests.</p>
<p>How do I access the parameters of the PUT request?
I thought they would be in the request.POST array, as PUT is somewhat similar to POST in my understanding, but that array is always empty.</p>
<p>What am I doing wrong?</p>
<p>Thanks for the help</p>
| 9
|
2009-02-01T08:29:44Z
| 501,337
|
<p>request.POST processes form-encoded data into a dictionary, which only makes sense for web browser form submissions. There is no equivalent for PUT, as web browsers don't PUT forms; the data submitted could have any content type. You'll need to get the raw data out of request.raw_post_data, possibly check the content type, and process it however makes sense for your application.</p>
<p>More information in <a href="http://groups.google.com/group/django-developers/browse_thread/thread/771238a95ceb058e">this thread</a>.</p>
| 13
|
2009-02-01T18:41:22Z
|
[
"python",
"django"
] |
using django-rest-interface with http put
| 500,434
|
<p>I'm trying to figure out how to implement my first RESTful interface using Django and django-rest-interface. I'm having problems with the HTTP PUT requests.</p>
<p>How do I access the parameters of the PUT request?
I thought they would be in the request.POST array, as PUT is somewhat similar to POST in my understanding, but that array is always empty.</p>
<p>What am I doing wrong?</p>
<p>Thanks for the help</p>
| 9
|
2009-02-01T08:29:44Z
| 503,616
|
<p>if you figure in the dispatch of ResourceBase there are a line like:</p>
<pre><code>elif request_method == 'PUT':
load_put_and_files(request)
return target.update(request, *args, **kwargs)
</code></pre>
<p>load_put_and_files let prepare for you the request.PUT with the data y the request.method is PUT, so you dont have to worry about that...</p>
| 3
|
2009-02-02T15:32:49Z
|
[
"python",
"django"
] |
In Python - how to execute system command with no output
| 500,477
|
<p>Is there a built-in method in Python to execute a system command without displaying the output? I only want to grab the return value.</p>
<p>It is important that it be cross-platform, so just redirecting the output to /dev/null won't work on Windows, and the other way around. I know I can just check os.platform and build the redirection myself, but I'm hoping for a built-in solution.</p>
| 8
|
2009-02-01T09:20:45Z
| 500,483
|
<p>You can redirect output into temp file and delete it afterward. But there's also a method called popen that redirects output directly to your program so it won't go on screen.</p>
| 2
|
2009-02-01T09:23:58Z
|
[
"python"
] |
In Python - how to execute system command with no output
| 500,477
|
<p>Is there a built-in method in Python to execute a system command without displaying the output? I only want to grab the return value.</p>
<p>It is important that it be cross-platform, so just redirecting the output to /dev/null won't work on Windows, and the other way around. I know I can just check os.platform and build the redirection myself, but I'm hoping for a built-in solution.</p>
| 8
|
2009-02-01T09:20:45Z
| 500,512
|
<pre><code>import os
import subprocess
subprocess.call(["ls", "-l"], stdout=open(os.devnull, "w"), stderr=subprocess.STDOUT)
</code></pre>
| 17
|
2009-02-01T09:50:37Z
|
[
"python"
] |
is there an alternative way of calling next on python generators?
| 500,578
|
<p>I have a generator and I would like to know if I can use it without having to worry about StopIteration , and I would like to use it without the <strong><code>for item in generator</code></strong> . I would like to use it with a while statement for example ( or other constructs ). How could I do that ?</p>
| 3
|
2009-02-01T10:48:46Z
| 500,609
|
<p>built-in function</p>
<blockquote>
<p>next(iterator[, default])<br />
Retrieve the next item from the iterator by calling its <code> __next__()</code> method. If default is given, it is returned if the iterator is exhausted, otherwise StopIteration is raised.</p>
</blockquote>
<p>In Python 2.5 and older:</p>
<pre><code>raiseStopIteration = object()
def next(iterator, default=raiseStopIteration):
if not hasattr(iterator, 'next'):
raise TypeError("not an iterator")
try:
return iterator.next()
except StopIteration:
if default is raiseStopIteration:
raise
else:
return default
</code></pre>
| 15
|
2009-02-01T11:12:53Z
|
[
"python",
"language-features"
] |
is there an alternative way of calling next on python generators?
| 500,578
|
<p>I have a generator and I would like to know if I can use it without having to worry about StopIteration , and I would like to use it without the <strong><code>for item in generator</code></strong> . I would like to use it with a while statement for example ( or other constructs ). How could I do that ?</p>
| 3
|
2009-02-01T10:48:46Z
| 500,610
|
<p>Use this to wrap your generator:</p>
<pre><code>class GeneratorWrap(object):
def __init__(self, generator):
self.generator = generator
def __iter__(self):
return self
def next(self):
for o in self.generator:
return o
raise StopIteration # If you don't care about the iterator protocol, remove this line and the __iter__ method.
</code></pre>
<p>Use it like this:</p>
<pre><code>def example_generator():
for i in [1,2,3,4,5]:
yield i
gen = GeneratorWrap(example_generator())
print gen.next() # prints 1
print gen.next() # prints 2
</code></pre>
<p><strong>Update:</strong> Please use the answer below because it is much better than this one.</p>
| -1
|
2009-02-01T11:13:09Z
|
[
"python",
"language-features"
] |
is there an alternative way of calling next on python generators?
| 500,578
|
<p>I have a generator and I would like to know if I can use it without having to worry about StopIteration , and I would like to use it without the <strong><code>for item in generator</code></strong> . I would like to use it with a while statement for example ( or other constructs ). How could I do that ?</p>
| 3
|
2009-02-01T10:48:46Z
| 500,706
|
<p>Another options is to read all generator values at once:</p>
<pre><code>>>> alist = list(agenerator)
</code></pre>
<p>Example:</p>
<pre><code>>>> def f():
... yield 'a'
...
>>> a = list(f())
>>> a[0]
'a'
>>> len(a)
1
</code></pre>
| 1
|
2009-02-01T12:16:35Z
|
[
"python",
"language-features"
] |
How do Django model fields work?
| 500,650
|
<p>First of all,I'm not into web programming. I bumped into django and read a bit about models. I was intrigued by the following code ( from djangoproject.com ) :</p>
<pre><code>
class Person(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
def __str__(self):
# Note use of django.utils.encoding.smart_str() here because
# first_name and last_name will be unicode strings.
return smart_str('%s %s' % (self.first_name, self.last_name))
</code></pre>
<p>By my understanding of python , first_name and last_name are class variables , right ? How is that used in code ( because I guess that setting Person.first_name or Person.last_name will affect all Person instances ) ? Why is it used that way ?</p>
| 9
|
2009-02-01T11:43:27Z
| 500,678
|
<p>Yes, first_name and last_name are class variables. They define fields that will be created in a database table. There is a Person table that has first_name and last_name columns, so it makes sense for them to be at Class level at this point.</p>
<p>For more on models, see:
<a href="http://docs.djangoproject.com/en/dev/topics/db/models/" rel="nofollow">http://docs.djangoproject.com/en/dev/topics/db/models/</a></p>
<p>When it comes to accessing instances of a Person in code, you are typically doing this via Django's ORM, and at this point they essentially behave as instance variables.</p>
<p>For more on model instances, see:
<a href="http://docs.djangoproject.com/en/dev/ref/models/instances/?from=olddocs" rel="nofollow">http://docs.djangoproject.com/en/dev/ref/models/instances/?from=olddocs</a></p>
| 4
|
2009-02-01T11:57:17Z
|
[
"python",
"django",
"django-models"
] |
How do Django model fields work?
| 500,650
|
<p>First of all,I'm not into web programming. I bumped into django and read a bit about models. I was intrigued by the following code ( from djangoproject.com ) :</p>
<pre><code>
class Person(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
def __str__(self):
# Note use of django.utils.encoding.smart_str() here because
# first_name and last_name will be unicode strings.
return smart_str('%s %s' % (self.first_name, self.last_name))
</code></pre>
<p>By my understanding of python , first_name and last_name are class variables , right ? How is that used in code ( because I guess that setting Person.first_name or Person.last_name will affect all Person instances ) ? Why is it used that way ?</p>
| 9
|
2009-02-01T11:43:27Z
| 501,362
|
<p>The essence of your question is "how come these class variables (which I assign Field objects to) suddenly become instance variables (which I assign data to) in Django's ORM"? The answer to that is the magic of Python <a href="http://docs.python.org/reference/datamodel.html">metaclasses</a>.</p>
<p>A metaclass allows you to hook into and modify the process of creating a Python class (not the creation of an instance of that class, the creation of the class itself).</p>
<p>Django's Model object (and thus also your models, which are subclasses) has a <a href="http://code.djangoproject.com/browser/django/trunk/django/db/models/base.py">ModelBase metaclass</a>. It looks through all the class attributes of your model, and any that are instances of a Field subclass it moves into a fields list. That list is assigned as an attribute of the <code>_meta</code> object, which is a class attribute of the model. Thus you can always get to the actual Field objects via <code>MyModel._meta.fields</code>, or <code>MyModel._meta.get_field('field_name')</code>.</p>
<p>The <code>Model.__init__</code> method is then able to use the <code>_meta.fields</code> list to determine what instance attributes should be initialized when a model instance is created.</p>
<p>Don't be afraid to dive into the Django source code; it's a great source of education!</p>
| 19
|
2009-02-01T18:56:40Z
|
[
"python",
"django",
"django-models"
] |
How do Django model fields work?
| 500,650
|
<p>First of all,I'm not into web programming. I bumped into django and read a bit about models. I was intrigued by the following code ( from djangoproject.com ) :</p>
<pre><code>
class Person(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
def __str__(self):
# Note use of django.utils.encoding.smart_str() here because
# first_name and last_name will be unicode strings.
return smart_str('%s %s' % (self.first_name, self.last_name))
</code></pre>
<p>By my understanding of python , first_name and last_name are class variables , right ? How is that used in code ( because I guess that setting Person.first_name or Person.last_name will affect all Person instances ) ? Why is it used that way ?</p>
| 9
|
2009-02-01T11:43:27Z
| 9,619,431
|
<p>Not a real answer, but for enrichment:</p>
<pre><code>Person.first_name
</code></pre>
<p>won't work</p>
<pre><code>p = Person.objects.get(pk=x)
p.first_name
</code></pre>
<p>will work. so an object instance of person has a first and last name, but static context Person does not.</p>
<p>Also note: Django has Model Managers which are allow "Person" to do static queryset operations. (https://docs.djangoproject.com/en/dev/topics/db/managers/#managers). </p>
<p>so for example </p>
<pre><code>peoples = Person.objects.all()
</code></pre>
| 0
|
2012-03-08T14:45:43Z
|
[
"python",
"django",
"django-models"
] |
How to deploy Django with Spawning
| 500,822
|
<p>There's no much documentation on how to deploy a Django project with <a href="http://pypi.python.org/pypi/Spawning/">Spawning</a> and yet people are recommending it over apache/mod_wsgi.</p>
<p><a href="http://stackoverflow.com/questions/487224/reducing-django-memory-usage-low-hanging-fruit/487261#487261">In another similar question</a>, other SO user suggested me to open a new question specific to Spawning, so hopefully others can share their experiences too.</p>
| 5
|
2009-02-01T13:39:48Z
| 500,921
|
<p>I'd be interested in seeing whose seriously recommending Spawning over Apache and mod_python or mod_wsgi.</p>
<p>Judging by the fact that this question is now the #4 result in Google for 'django spawning' I'd say it's very much early days. :) If you're putting anything serious into production stick to Apache/mod_wsgi for now.</p>
| 3
|
2009-02-01T14:33:02Z
|
[
"python",
"django",
"deployment",
"spawning"
] |
How to deploy Django with Spawning
| 500,822
|
<p>There's no much documentation on how to deploy a Django project with <a href="http://pypi.python.org/pypi/Spawning/">Spawning</a> and yet people are recommending it over apache/mod_wsgi.</p>
<p><a href="http://stackoverflow.com/questions/487224/reducing-django-memory-usage-low-hanging-fruit/487261#487261">In another similar question</a>, other SO user suggested me to open a new question specific to Spawning, so hopefully others can share their experiences too.</p>
| 5
|
2009-02-01T13:39:48Z
| 501,542
|
<p>Eric Florenzo did some <a href="http://www.eflorenzano.com/blog/post/spawning-django/" rel="nofollow">basic testing of spawning</a>. Make sure and read all the comments as well as the main post.</p>
<p>Personally I always like investigating these kinds of solutions, but in this case I just can't even get to a benchmarking stage. There are too many important features I need in Apache (ssl client certs, run mongrel servers under fastcgi, django under wsgi, php <em>gasp</em>, static files served directly, ssl for each ip address, dozens of virtual hosts on multiple ip addresses, etc.).</p>
| 2
|
2009-02-01T20:48:59Z
|
[
"python",
"django",
"deployment",
"spawning"
] |
How to deploy Django with Spawning
| 500,822
|
<p>There's no much documentation on how to deploy a Django project with <a href="http://pypi.python.org/pypi/Spawning/">Spawning</a> and yet people are recommending it over apache/mod_wsgi.</p>
<p><a href="http://stackoverflow.com/questions/487224/reducing-django-memory-usage-low-hanging-fruit/487261#487261">In another similar question</a>, other SO user suggested me to open a new question specific to Spawning, so hopefully others can share their experiences too.</p>
| 5
|
2009-02-01T13:39:48Z
| 505,127
|
<p>cd to your django's settings.py directory.</p>
<p>Here is the command line to serve your django application</p>
<pre><code>spawn --factory=spawning.django_factory.config_factory settings --port 80
</code></pre>
| 3
|
2009-02-02T21:53:51Z
|
[
"python",
"django",
"deployment",
"spawning"
] |
How to deploy Django with Spawning
| 500,822
|
<p>There's no much documentation on how to deploy a Django project with <a href="http://pypi.python.org/pypi/Spawning/">Spawning</a> and yet people are recommending it over apache/mod_wsgi.</p>
<p><a href="http://stackoverflow.com/questions/487224/reducing-django-memory-usage-low-hanging-fruit/487261#487261">In another similar question</a>, other SO user suggested me to open a new question specific to Spawning, so hopefully others can share their experiences too.</p>
| 5
|
2009-02-01T13:39:48Z
| 11,171,962
|
<p>Yes, I could recommend you to use spawning over apache/wsgi setup.</p>
<p>Two reasons basically:
1) Memory usage (you'll save some MBs on spawning)
2) Dynamic code reloading (at no point of time, your user's will see a 404 or 500 page)</p>
<p>This comes from experience, I am running <a href="http://tunesdiary.com" rel="nofollow">http://tunesdiary.com</a> on spawning+nginx in this setup:</p>
<p>nginx handles all the incoming load which further proxy connection to spawning which is listening on a unprivileged port (means spawning is running as a different user than the web-server)
Spawning spawns 4 processes with 2 threads per process. (works for the current load).</p>
<p>As I push any code to the server, the previous requests are handled, and then the new code starts serving the new requests.</p>
<p>This has been working very good till now (I am running this from about 6 months)</p>
<p>What I've observed, django with mod wsgi + apache (which I used for some days earlier) was taking about 70MB of RAM after getting started (single process), and this setup uses 45MB per process or so.
Also, I've also had this with lighttpd + modfcgi which also consumes almost same amount of memory than spwaning.</p>
<p>(I might have miscalculated because in apache, the webserver's memory usage is also included)</p>
<p>You can rely on spawning, as far as I can say, but if if you don't really push often, it won't be of much use.</p>
| 0
|
2012-06-23T18:30:09Z
|
[
"python",
"django",
"deployment",
"spawning"
] |
Case insensitive Python regular expression without re.compile
| 500,864
|
<p>In Python, I can compile a regular expression to be case-insensitive using <code>re.compile</code>:</p>
<pre><code>>>> s = 'TeSt'
>>> casesensitive = re.compile('test')
>>> ignorecase = re.compile('test', re.IGNORECASE)
>>>
>>> print casesensitive.match(s)
None
>>> print ignorecase.match(s)
<_sre.SRE_Match object at 0x02F0B608>
</code></pre>
<p>Is there a way to do the same, but without using <code>re.compile</code>. I can't find anything like Perl's <code>i</code> suffix (e.g. <code>m/test/i</code>) in the documentation.</p>
| 132
|
2009-02-01T13:56:14Z
| 500,870
|
<p>Pass <code>re.IGNORECASE</code> to the <code>flags</code> param of <a href="https://docs.python.org/library/re.html#re.search"><code>search</code></a>, <a href="https://docs.python.org/library/re.html#re.match"><code>match</code></a>, or <a href="https://docs.python.org/library/re.html#re.sub"><code>sub</code></a>:</p>
<pre><code>re.search('test', 'TeSt', re.IGNORECASE)
re.match('test', 'TeSt', re.IGNORECASE)
re.sub('test', 'xxxx', 'Testing', flags=re.IGNORECASE)
</code></pre>
| 206
|
2009-02-01T14:01:10Z
|
[
"python",
"regex",
"case-sensitive",
"case-insensitive"
] |
Case insensitive Python regular expression without re.compile
| 500,864
|
<p>In Python, I can compile a regular expression to be case-insensitive using <code>re.compile</code>:</p>
<pre><code>>>> s = 'TeSt'
>>> casesensitive = re.compile('test')
>>> ignorecase = re.compile('test', re.IGNORECASE)
>>>
>>> print casesensitive.match(s)
None
>>> print ignorecase.match(s)
<_sre.SRE_Match object at 0x02F0B608>
</code></pre>
<p>Is there a way to do the same, but without using <code>re.compile</code>. I can't find anything like Perl's <code>i</code> suffix (e.g. <code>m/test/i</code>) in the documentation.</p>
| 132
|
2009-02-01T13:56:14Z
| 10,444,271
|
<p>You can also perform case insensitive searches using search/match without the IGNORECASE flag (tested in Python 2.7.3):</p>
<pre><code>re.search(r'(?i)test', 'TeSt').group() ## returns 'TeSt'
re.match(r'(?i)test', 'TeSt').group() ## returns 'TeSt'
</code></pre>
| 31
|
2012-05-04T07:05:38Z
|
[
"python",
"regex",
"case-sensitive",
"case-insensitive"
] |
Case insensitive Python regular expression without re.compile
| 500,864
|
<p>In Python, I can compile a regular expression to be case-insensitive using <code>re.compile</code>:</p>
<pre><code>>>> s = 'TeSt'
>>> casesensitive = re.compile('test')
>>> ignorecase = re.compile('test', re.IGNORECASE)
>>>
>>> print casesensitive.match(s)
None
>>> print ignorecase.match(s)
<_sre.SRE_Match object at 0x02F0B608>
</code></pre>
<p>Is there a way to do the same, but without using <code>re.compile</code>. I can't find anything like Perl's <code>i</code> suffix (e.g. <code>m/test/i</code>) in the documentation.</p>
| 132
|
2009-02-01T13:56:14Z
| 23,613,042
|
<p>You can also define case insensitive during the pattern compile:</p>
<pre><code>pattern = re.compile('FIle:/+(.*)', re.IGNORECASE)
</code></pre>
| 5
|
2014-05-12T15:26:30Z
|
[
"python",
"regex",
"case-sensitive",
"case-insensitive"
] |
Case insensitive Python regular expression without re.compile
| 500,864
|
<p>In Python, I can compile a regular expression to be case-insensitive using <code>re.compile</code>:</p>
<pre><code>>>> s = 'TeSt'
>>> casesensitive = re.compile('test')
>>> ignorecase = re.compile('test', re.IGNORECASE)
>>>
>>> print casesensitive.match(s)
None
>>> print ignorecase.match(s)
<_sre.SRE_Match object at 0x02F0B608>
</code></pre>
<p>Is there a way to do the same, but without using <code>re.compile</code>. I can't find anything like Perl's <code>i</code> suffix (e.g. <code>m/test/i</code>) in the documentation.</p>
| 132
|
2009-02-01T13:56:14Z
| 31,954,689
|
<p>Using sub you can specify the string you want to filter like in your example for the DOCTYPE and just replace it for whatever string you want. On the example below I am replacing everything in between the paragraph tags.</p>
<pre><code>import re
htmlstring = '''
<!DOCTYPE html>
<html>
<body>
<p>This is a paragraph.</p>
<p>This is a paragraph.</p>
<p>This is a paragraph.</p>
</body>
</html>'''
stringlist = re.findall('<p>.*</p>', htmlstring, re.IGNORECASE)
for s in stringlist:
print re.sub('<p>.*</p>','<p>new string</p>',s)
>> <p>new string</p>
>> <p>new string</p>
>> <p>new string</p>
</code></pre>
<p>Or you can use:</p>
<pre><code>stringlist = re.findall('<p>.*</p>', htmlstring, re.IGNORECASE)
for s in stringlist:
print s.replace(s, '<p>new string</p>')
</code></pre>
| -3
|
2015-08-12T01:41:16Z
|
[
"python",
"regex",
"case-sensitive",
"case-insensitive"
] |
Case insensitive Python regular expression without re.compile
| 500,864
|
<p>In Python, I can compile a regular expression to be case-insensitive using <code>re.compile</code>:</p>
<pre><code>>>> s = 'TeSt'
>>> casesensitive = re.compile('test')
>>> ignorecase = re.compile('test', re.IGNORECASE)
>>>
>>> print casesensitive.match(s)
None
>>> print ignorecase.match(s)
<_sre.SRE_Match object at 0x02F0B608>
</code></pre>
<p>Is there a way to do the same, but without using <code>re.compile</code>. I can't find anything like Perl's <code>i</code> suffix (e.g. <code>m/test/i</code>) in the documentation.</p>
| 132
|
2009-02-01T13:56:14Z
| 40,009,585
|
<pre><code>#'re.IGNORECASE' for case insensitive results short form re.I
#'re.match' returns the first match located
#'re.search' returns location of the where the match is found
#'re.compile' creates a regex object that can be used for multiple matches
s = 'TeSt'
print (re.match(s, re.I))
# OR
pattern = re.compile( r'TeSt', re.I)
result = pattern.match(s)
</code></pre>
| 0
|
2016-10-12T22:48:14Z
|
[
"python",
"regex",
"case-sensitive",
"case-insensitive"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.