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
listlengths
1
5
FIFO (named pipe) messaging obstacles
927,233
<p>I plan to use Unix named pipes (mkfifo) for simple multi-process messaging. A message would be just a single line of text.</p> <p>Would you discourage me from that? What obstacles should I expect?</p> <p>I have noticed these limitations:</p> <ol> <li>A sender cannot continue until the message is received.</li> <l...
1
2009-05-29T17:35:45Z
927,371
<p>The blocking, both on the sender side and the receiver side, can be worked around via non-blocking I/O.</p> <p>Further limitations of FIFOs:</p> <ul> <li>Only one client at a time.</li> <li>After the client closes the FIFO, the server need to re-open its endpoint.</li> <li>Unidirectional.</li> </ul> <p>I would us...
3
2009-05-29T18:11:45Z
[ "python", "linux", "unix", "pipe", "named-pipes" ]
how to parse windows inf files for python?
927,279
<p>please help me. example inf file : </p> <pre><code>;============================================================================= ; ; Copyright (c) Intel Corporation (2002). ; ; INTEL MAKES NO WARRANTY OF ANY KIND REGARDING THE CODE. THIS CODE IS ; LICENSED ON AN "AS IS" BASIS AND INTEL WILL NOT PROVIDE ANY SUPPOR...
3
2009-05-29T17:52:31Z
927,306
<p>You may try the built-in ConfigParser</p> <p><a href="http://docs.python.org/library/configparser.html">http://docs.python.org/library/configparser.html</a></p> <p>As well as ConfigObj</p> <p><a href="http://code.google.com/p/configobj/">http://code.google.com/p/configobj/</a></p> <p>Both claim to be able to han...
10
2009-05-29T17:57:35Z
[ "python", "windows", "parsing", "file", "drivers" ]
Parsing HTTP User-Agent string
927,552
<p>What is the best method to parse a User-Agent string in Python to reliably detect</p> <ol> <li>Browser</li> <li>Browser version</li> <li>OS</li> </ol> <p>Or perhaps any helper library that does it</p>
45
2009-05-29T18:53:46Z
927,710
<p>However if you wish to parse all this on the Python side you can use the XML/INI files provided at <a href="http://browsers.garykeith.com/downloads.asp" rel="nofollow">http://browsers.garykeith.com/downloads.asp</a> to do lookups on the user agent. This is the same file that is used in php's get_browser() function.<...
2
2009-05-29T19:25:27Z
[ "python", "http", "http-headers", "user-agent" ]
Parsing HTTP User-Agent string
927,552
<p>What is the best method to parse a User-Agent string in Python to reliably detect</p> <ol> <li>Browser</li> <li>Browser version</li> <li>OS</li> </ol> <p>Or perhaps any helper library that does it</p>
45
2009-05-29T18:53:46Z
929,077
<p>Th <a href="http://www.djangosnippets.org/snippets/267/" rel="nofollow">Browser Cap Parser</a> should work. It may be a bit slow though..</p>
3
2009-05-30T05:28:49Z
[ "python", "http", "http-headers", "user-agent" ]
Parsing HTTP User-Agent string
927,552
<p>What is the best method to parse a User-Agent string in Python to reliably detect</p> <ol> <li>Browser</li> <li>Browser version</li> <li>OS</li> </ol> <p>Or perhaps any helper library that does it</p>
45
2009-05-29T18:53:46Z
1,151,956
<p>Answering my own question ;)</p> <p>Finally I decided to go by suggestion#1 i.e. write your own. And I am happy with the outcome. Please feel free to use/modify/send me patch etc.</p> <p>It's here -> <a href="http://pypi.python.org/pypi/httpagentparser">http://pypi.python.org/pypi/httpagentparser</a></p>
63
2009-07-20T06:24:40Z
[ "python", "http", "http-headers", "user-agent" ]
Parsing HTTP User-Agent string
927,552
<p>What is the best method to parse a User-Agent string in Python to reliably detect</p> <ol> <li>Browser</li> <li>Browser version</li> <li>OS</li> </ol> <p>Or perhaps any helper library that does it</p>
45
2009-05-29T18:53:46Z
1,339,838
<p><a href="http://user-agent-string.info/download/UASparser-for-Python">UASparser for Python</a> by Hicro Kee. Auto updated datafile and cache from remote server with version checking.</p>
10
2009-08-27T09:10:50Z
[ "python", "http", "http-headers", "user-agent" ]
Parsing HTTP User-Agent string
927,552
<p>What is the best method to parse a User-Agent string in Python to reliably detect</p> <ol> <li>Browser</li> <li>Browser version</li> <li>OS</li> </ol> <p>Or perhaps any helper library that does it</p>
45
2009-05-29T18:53:46Z
10,109,978
<p>Having run these suggestions against <a href="http://www.useragentstring.com/pages/Firefox/">the full corpus of Firefox User Agents</a>, I've found that the version-number parsing for comparison is quite poor. </p> <p>If that's what you need, I suggest that you take a look at <a href="https://github.com/dinomite/ua...
6
2012-04-11T16:25:00Z
[ "python", "http", "http-headers", "user-agent" ]
Parsing HTTP User-Agent string
927,552
<p>What is the best method to parse a User-Agent string in Python to reliably detect</p> <ol> <li>Browser</li> <li>Browser version</li> <li>OS</li> </ol> <p>Or perhaps any helper library that does it</p>
45
2009-05-29T18:53:46Z
11,148,234
<p>Werkzeug has user-agent parsing built-in.</p> <p><a href="http://werkzeug.pocoo.org/docs/0.10/utils/#module-werkzeug.useragents">http://werkzeug.pocoo.org/docs/0.10/utils/#module-werkzeug.useragents</a></p>
8
2012-06-21T23:25:03Z
[ "python", "http", "http-headers", "user-agent" ]
Parsing HTTP User-Agent string
927,552
<p>What is the best method to parse a User-Agent string in Python to reliably detect</p> <ol> <li>Browser</li> <li>Browser version</li> <li>OS</li> </ol> <p>Or perhaps any helper library that does it</p>
45
2009-05-29T18:53:46Z
27,642,188
<p>The other responses to this question are rather old now. I believe the new standard in Browser User Agent parsing is Browserscope's <a href="https://github.com/ua-parser/uap-python/">user agent parser</a>. </p> <ul> <li><a href="https://pypi.python.org/pypi/ua-parser">UA Parser pypi package</a> </li> <li><a href="h...
5
2014-12-24T21:08:03Z
[ "python", "http", "http-headers", "user-agent" ]
str.startswith() not working as I intended
927,584
<p>I'm trying to test for a /t or a space character and I can't understand why this bit of code won't work. What I am doing is reading in a file, counting the loc for the file, and then recording the names of each function present within the file along with their individual lines of code. The bit of code below is where...
1
2009-05-29T19:00:37Z
927,599
<p><code>\s</code> is only whitespace to the <code>re</code> package when doing pattern matching.</p> <p>For <code>startswith</code>, an ordinary method of ordinary strings, <code>\s</code> is nothing special. Not a pattern, just characters.</p>
8
2009-05-29T19:03:30Z
[ "python", "string", "python-3.x" ]
str.startswith() not working as I intended
927,584
<p>I'm trying to test for a /t or a space character and I can't understand why this bit of code won't work. What I am doing is reading in a file, counting the loc for the file, and then recording the names of each function present within the file along with their individual lines of code. The bit of code below is where...
1
2009-05-29T19:00:37Z
927,606
<p>You string literals aren't what you think they are. You can specify a space or TAB like so:</p> <pre><code>space = ' ' tab = '\t' </code></pre>
2
2009-05-29T19:05:08Z
[ "python", "string", "python-3.x" ]
str.startswith() not working as I intended
927,584
<p>I'm trying to test for a /t or a space character and I can't understand why this bit of code won't work. What I am doing is reading in a file, counting the loc for the file, and then recording the names of each function present within the file along with their individual lines of code. The bit of code below is where...
1
2009-05-29T19:00:37Z
928,150
<p>Your question has already been answered and this is slightly off-topic, but...</p> <p>If you want to parse code, it is often easier and less error-prone to use a parser. If your code is Python code, Python comes with a couple of parsers (<a href="http://docs.python.org/library/tokenize.html" rel="nofollow">tokenize...
3
2009-05-29T21:04:44Z
[ "python", "string", "python-3.x" ]
how to override the verbose name of a superclass model field in django
927,729
<p>Let's say that I have a model Foo that inherits from SuperFoo:</p> <pre><code>class SuperFoo(models.Model): name = models.CharField('name of SuperFoo instance', max_length=50) ... class Foo(SuperFoo): ... # do something that changes verbose_name of name field of SuperFoo </code></pre> <p>In class Foo,...
23
2009-05-29T19:30:57Z
928,030
<p>Your best bet would be setting/changing the label in the form itself. Referring to the <code>name</code> field of the <code>Foo</code> model (eg. by looking it up in <code>Foo._meta.fields</code>) will actually give you a reference to the <code>name</code> field of <code>SuperFoo</code>, so changing its <code>verbos...
4
2009-05-29T20:39:38Z
[ "python", "django", "inheritance", "django-models" ]
how to override the verbose name of a superclass model field in django
927,729
<p>Let's say that I have a model Foo that inherits from SuperFoo:</p> <pre><code>class SuperFoo(models.Model): name = models.CharField('name of SuperFoo instance', max_length=50) ... class Foo(SuperFoo): ... # do something that changes verbose_name of name field of SuperFoo </code></pre> <p>In class Foo,...
23
2009-05-29T19:30:57Z
928,774
<p>A simple hack I have used is:</p> <pre><code>class SuperFoo(models.Model): name = models.CharField('name of SuperFoo instance', max_length=50) ... class Foo(SuperFoo): ... # do something that changes verbose_name of name field of SuperFoo Foo._meta.get_field('name').verbose_name = 'Whatever' </code></p...
45
2009-05-30T02:02:46Z
[ "python", "django", "inheritance", "django-models" ]
how to override the verbose name of a superclass model field in django
927,729
<p>Let's say that I have a model Foo that inherits from SuperFoo:</p> <pre><code>class SuperFoo(models.Model): name = models.CharField('name of SuperFoo instance', max_length=50) ... class Foo(SuperFoo): ... # do something that changes verbose_name of name field of SuperFoo </code></pre> <p>In class Foo,...
23
2009-05-29T19:30:57Z
6,426,278
<p>Have a look at how Django-CMS does this, they override the <code>db_table</code> field in the models inheriting from <code>CMSPlugin</code>. The basics (which I also use for my own stuff) boil down to:</p> <pre><code>class SuperFooMetaClass(ModelBase): def __new__(cls, name, bases, attrs): new_class = s...
5
2011-06-21T13:43:24Z
[ "python", "django", "inheritance", "django-models" ]
how to override the verbose name of a superclass model field in django
927,729
<p>Let's say that I have a model Foo that inherits from SuperFoo:</p> <pre><code>class SuperFoo(models.Model): name = models.CharField('name of SuperFoo instance', max_length=50) ... class Foo(SuperFoo): ... # do something that changes verbose_name of name field of SuperFoo </code></pre> <p>In class Foo,...
23
2009-05-29T19:30:57Z
24,475,838
<p>Bearing in mind the caveat that modifying Foo._meta.fields will affect the superclass too - and therefore is only really useful if the superclass is abstract, I've wrapped the answer @Gerry gave up as a reusable class decorator:</p> <pre><code>def modify_fields(**kwargs): def wrap(cls): for field, prop_...
5
2014-06-29T11:54:04Z
[ "python", "django", "inheritance", "django-models" ]
Really odd (mod)_python problem
927,759
<p>this one is hard to explain!</p> <p>I am writing a python application to be ran through mod_python. At each request, the returned output differs, even though the logic is 'fixed'.</p> <p>I have two classes, <code>classA</code> and <code>classB</code>. Such that:</p> <pre><code>class ClassA: def page(self, req...
2
2009-05-29T19:38:24Z
927,769
<p>I don't really know, but constructors aren't supposed to return anything, so remove the <code>return None</code>. Even if they could return stuff, <code>None</code> is automatically returned if a function doesn't return anything by itself.</p> <p>And I think you need a <code>self</code> argument in MethodB.</p> <p...
1
2009-05-29T19:41:07Z
[ "python", "debugging", "mod-python" ]
Really odd (mod)_python problem
927,759
<p>this one is hard to explain!</p> <p>I am writing a python application to be ran through mod_python. At each request, the returned output differs, even though the logic is 'fixed'.</p> <p>I have two classes, <code>classA</code> and <code>classB</code>. Such that:</p> <pre><code>class ClassA: def page(self, req...
2
2009-05-29T19:38:24Z
927,925
<p>I've seen similar behaviour with mod_python before. Usually it is because apache is running multiple threads and one of them is running an older version of the code. When you refresh the page chances are the thread with the older code is serving the page. I usually fix this by stoping apache and then restarting it a...
4
2009-05-29T20:16:55Z
[ "python", "debugging", "mod-python" ]
How to get the owner and group of a folder with Python on a Linux machine?
927,866
<p>How can I get the owner and group IDs of a directory using Python under Linux?</p>
6
2009-05-29T20:04:54Z
927,886
<p>I tend to use <a href="http://docs.python.org/library/os.html#files-and-directories" rel="nofollow">os.stat</a>:</p> <blockquote> <p>Perform a stat system call on the given path. The return value is an object whose attributes correspond to the members of the stat structure, namely: st_mode (protection bits), <cod...
0
2009-05-29T20:09:52Z
[ "python", "linux", "folder", "group", "owner" ]
How to get the owner and group of a folder with Python on a Linux machine?
927,866
<p>How can I get the owner and group IDs of a directory using Python under Linux?</p>
6
2009-05-29T20:04:54Z
927,888
<p>Use the <code>os.stat</code> function.</p>
0
2009-05-29T20:10:30Z
[ "python", "linux", "folder", "group", "owner" ]
How to get the owner and group of a folder with Python on a Linux machine?
927,866
<p>How can I get the owner and group IDs of a directory using Python under Linux?</p>
6
2009-05-29T20:04:54Z
927,890
<p>Use <a href="http://docs.python.org/library/os.html#os.stat"><code>os.stat()</code></a> to get the uid and gid of the file. Then, use <a href="http://docs.python.org/library/pwd.html#pwd.getpwuid"><code>pwd.getpwuid()</code></a> and <a href="http://docs.python.org/library/grp.html#grp.getgrgid"><code>grp.getgrgid()<...
22
2009-05-29T20:10:40Z
[ "python", "linux", "folder", "group", "owner" ]
How to get the owner and group of a folder with Python on a Linux machine?
927,866
<p>How can I get the owner and group IDs of a directory using Python under Linux?</p>
6
2009-05-29T20:04:54Z
927,902
<p>Use <a href="http://docs.python.org/3.0/library/os.html#os.stat" rel="nofollow">os.stat</a>:</p> <pre><code>&gt;&gt;&gt; s = os.stat('.') &gt;&gt;&gt; s.st_uid 1000 &gt;&gt;&gt; s.st_gid 1000 </code></pre> <p><code>st_uid</code> is the user id of the owner, <code>st_gid</code> is the group id. See the linked docum...
0
2009-05-29T20:13:19Z
[ "python", "linux", "folder", "group", "owner" ]
How to get the owner and group of a folder with Python on a Linux machine?
927,866
<p>How can I get the owner and group IDs of a directory using Python under Linux?</p>
6
2009-05-29T20:04:54Z
36,546,321
<p>Since Python 3.4.4, the <code>Path</code> class of <code>pathlib</code> module provides a nice syntax for this:</p> <pre><code>from pathlib import Path whatever = Path("relative/or/absolute/path/to_whatever") if whatever.exists(): print("Owner: %s" % whatever.owner()) print("Group: %s" % whatever.group()) <...
1
2016-04-11T10:38:07Z
[ "python", "linux", "folder", "group", "owner" ]
Python Class Inheritance issue
927,985
<p>I'm playing with Python Class inheritance and ran into a problem where the inherited <code>__init__</code> is not being executed if called from the sub-class (code below) the result I get from Active Python is:</p> <p><hr /></p> <pre><code>&gt;&gt;&gt; start Tom Sneed Sue Ann Traceback (most recent call last): F...
16
2009-05-29T20:28:23Z
927,996
<p>Employee has to explicitly invoke the parent's __init__ (not init):</p> <pre><code> class Employee(Person): def __init__(self): Person.__init__(self) self.empnum = 'abc123' </code></pre>
5
2009-05-29T20:31:04Z
[ "python", "class", "inheritance" ]
Python Class Inheritance issue
927,985
<p>I'm playing with Python Class inheritance and ran into a problem where the inherited <code>__init__</code> is not being executed if called from the sub-class (code below) the result I get from Active Python is:</p> <p><hr /></p> <pre><code>&gt;&gt;&gt; start Tom Sneed Sue Ann Traceback (most recent call last): F...
16
2009-05-29T20:28:23Z
928,004
<p>You should explicitely call the superclass' init function:</p> <pre><code>class Employee(Person): def __init__(self): Person.__init__(self) self.empnum = "abc123" </code></pre>
9
2009-05-29T20:32:36Z
[ "python", "class", "inheritance" ]
Python Class Inheritance issue
927,985
<p>I'm playing with Python Class inheritance and ran into a problem where the inherited <code>__init__</code> is not being executed if called from the sub-class (code below) the result I get from Active Python is:</p> <p><hr /></p> <pre><code>&gt;&gt;&gt; start Tom Sneed Sue Ann Traceback (most recent call last): F...
16
2009-05-29T20:28:23Z
928,013
<p>Three things:</p> <ol> <li>You need to explicitly call the constructor. It isn't called for you automatically like in C++</li> <li>Use a new-style class inherited from object</li> <li>With a new-style class, use the super() method available</li> </ol> <p>This will look like:</p> <pre><code>class Person(object): ...
25
2009-05-29T20:34:37Z
[ "python", "class", "inheritance" ]
Python Class Inheritance issue
927,985
<p>I'm playing with Python Class inheritance and ran into a problem where the inherited <code>__init__</code> is not being executed if called from the sub-class (code below) the result I get from Active Python is:</p> <p><hr /></p> <pre><code>&gt;&gt;&gt; start Tom Sneed Sue Ann Traceback (most recent call last): F...
16
2009-05-29T20:28:23Z
4,147,739
<p>Instead of <code>super(class, instance)</code> pattern why not just use <code>super(instance)</code> as the class is always <code>instance.__class__</code>?</p> <p>Are there specific cases where it would not be <code>instance.__class__</code>?</p>
2
2010-11-10T18:25:50Z
[ "python", "class", "inheritance" ]
Formatting the output of a key from a dictionary
928,330
<p>I have a dictionary which store a string as the key, and an integer as the value. In my output I would like to have the key displayed as a string without parenthesis or commas. How would I do this?</p> <pre><code>for f_name,f_loc in dict_func.items(): print ('Function names:\n\n\t{0} -- {1} lines of code\n'...
1
2009-05-29T21:55:29Z
928,340
<p>I expect you have a problem with your parsing code. The lines as written should work as expected.</p>
2
2009-05-29T21:58:06Z
[ "python", "string", "dictionary", "python-3.x" ]
Formatting the output of a key from a dictionary
928,330
<p>I have a dictionary which store a string as the key, and an integer as the value. In my output I would like to have the key displayed as a string without parenthesis or commas. How would I do this?</p> <pre><code>for f_name,f_loc in dict_func.items(): print ('Function names:\n\n\t{0} -- {1} lines of code\n'...
1
2009-05-29T21:55:29Z
928,342
<p>I don't have Python 3 so I can't test this, but the output of f_name makes it look like it is a tuple with one element in it. So you would change <code>.format(f_name, f_loc)</code> to <code>.format(f_name[0], f_loc)</code></p> <p><strong>EDIT</strong>:</p> <p>In response to your edit, try using <a href="http://do...
4
2009-05-29T21:58:14Z
[ "python", "string", "dictionary", "python-3.x" ]
Formatting the output of a key from a dictionary
928,330
<p>I have a dictionary which store a string as the key, and an integer as the value. In my output I would like to have the key displayed as a string without parenthesis or commas. How would I do this?</p> <pre><code>for f_name,f_loc in dict_func.items(): print ('Function names:\n\n\t{0} -- {1} lines of code\n'...
1
2009-05-29T21:55:29Z
928,352
<p>To elaborate on <a href="http://stackoverflow.com/questions/928330/formatting-the-output-of-a-key-from-a-dictionary/928340#928340">Peter's answer</a>, It looks to me like you're assigning a one-item <a href="http://docs.python.org/library/stdtypes.html#sequence-types-str-unicode-list-tuple-buffer-xrange" rel="nofoll...
3
2009-05-29T22:00:23Z
[ "python", "string", "dictionary", "python-3.x" ]
Formatting the output of a key from a dictionary
928,330
<p>I have a dictionary which store a string as the key, and an integer as the value. In my output I would like to have the key displayed as a string without parenthesis or commas. How would I do this?</p> <pre><code>for f_name,f_loc in dict_func.items(): print ('Function names:\n\n\t{0} -- {1} lines of code\n'...
1
2009-05-29T21:55:29Z
928,391
<p>Since the key is some type of tuple, you may want to join the different elements before printing. We can't really tell what the significance of the key is from the snippet shown.</p> <p>So you could do something like such:</p> <pre><code>.format(", ".join(f_name), f_loc) </code></pre>
1
2009-05-29T22:17:34Z
[ "python", "string", "dictionary", "python-3.x" ]
Tkinter: Changing a variable within a function
928,520
<p>I know this kind of question gets asked all the time but either i've been unable to come across the answer i need, or i've been unable to understand it when i did.</p> <p>I want to be able to do something like:</p> <pre><code>spam = StringVar() spam.set(aValue) class MyScale(Scale): def __init__(self,var,*args...
1
2009-05-29T23:17:34Z
928,554
<p>Let's look at this method function</p> <pre><code> def getValue(self,event): ## spam gets changed to the new value set ## by the user manipulating the scale var.set(self.get) </code></pre> <p>The <code>var.set(self.get)</code> line has exactly two local variables available:</p> <ul> <l...
1
2009-05-29T23:37:13Z
[ "python", "tkinter" ]
Tkinter: Changing a variable within a function
928,520
<p>I know this kind of question gets asked all the time but either i've been unable to come across the answer i need, or i've been unable to understand it when i did.</p> <p>I want to be able to do something like:</p> <pre><code>spam = StringVar() spam.set(aValue) class MyScale(Scale): def __init__(self,var,*args...
1
2009-05-29T23:17:34Z
929,100
<p>Please give this a shot.</p> <p>Lots of example code out there generously uses globals, like your "var" variable.</p> <p>I have used your var argument to act as a pointer back to the original spam object; assigned to self.var_pointer within the MyScale class.</p> <p>The code below will change the value of 'spam' ...
2
2009-05-30T05:45:14Z
[ "python", "tkinter" ]
How do I access the name of the class of an Object in Python?
928,806
<p>The title says it mostly.</p> <p>If I have an object in Python and want to access the name of the class it is instantiated from is there a standard way to do this?</p>
1
2009-05-30T02:21:11Z
928,810
<pre><code>obj.__class__.__name__ </code></pre>
19
2009-05-30T02:23:00Z
[ "python" ]
Python File Read + Write
928,918
<p>I am working on porting over a database from a custom MSSQL CMS to MYSQL - Wordpress. I am using Python to read a txt file with <code>\t</code> delineated columns and one row per line.</p> <p>I am trying to write a Python script that will read this file (fread) and [eventually] create a MYSSQL ready .sql file with ...
4
2009-05-30T03:21:24Z
928,927
<p>What you probably want is something like this: <code>data=line.split("\t")</code><br/>It'll give you a nice sequence object to work with.<br/> (By the way, no need for semicolons in Python. There's one here: <code>print line;</code>)<br/><br/>As Dave pointed out, this might leave a newline in there. Call strip() on ...
0
2009-05-30T03:25:16Z
[ "python", "file" ]
Python File Read + Write
928,918
<p>I am working on porting over a database from a custom MSSQL CMS to MYSQL - Wordpress. I am using Python to read a txt file with <code>\t</code> delineated columns and one row per line.</p> <p>I am trying to write a Python script that will read this file (fread) and [eventually] create a MYSSQL ready .sql file with ...
4
2009-05-30T03:21:24Z
928,937
<p>The Python Standard Library has a module for <a href="http://docs.python.org/library/csv.html" rel="nofollow">CSV (comma separated value) file reading and writing</a> that can be made to work on tab separated files like your one. It's probably overkill for this task.</p>
0
2009-05-30T03:32:11Z
[ "python", "file" ]
Python File Read + Write
928,918
<p>I am working on porting over a database from a custom MSSQL CMS to MYSQL - Wordpress. I am using Python to read a txt file with <code>\t</code> delineated columns and one row per line.</p> <p>I am trying to write a Python script that will read this file (fread) and [eventually] create a MYSSQL ready .sql file with ...
4
2009-05-30T03:21:24Z
928,943
<p>Although this is easily doable, it does become easier with the <a href="http://docs.python.org/library/csv.html">csv</a> module.</p> <pre><code>&gt;&gt;&gt; import csv &gt;&gt;&gt; reader = csv.reader(open('C:/www/stackoverflow.txt'), delimiter='\t') &gt;&gt;&gt; for row in reader: ... print row ... ['1', 'John...
9
2009-05-30T03:38:16Z
[ "python", "file" ]
Python File Read + Write
928,918
<p>I am working on porting over a database from a custom MSSQL CMS to MYSQL - Wordpress. I am using Python to read a txt file with <code>\t</code> delineated columns and one row per line.</p> <p>I am trying to write a Python script that will read this file (fread) and [eventually] create a MYSSQL ready .sql file with ...
4
2009-05-30T03:21:24Z
928,953
<p>Knowing the exact number of columns helps self document your code:</p> <pre><code>fwrite = open("d:/icm_db/wp_sql/wp.users.sql","w") for line in open("d:/icm_db/users.txt"): name, title, login, location = line.strip().split("\t") # Double up on those single quotes to avoid nasty SQL! safe_name = name.replac...
1
2009-05-30T03:48:39Z
[ "python", "file" ]
Python File Read + Write
928,918
<p>I am working on porting over a database from a custom MSSQL CMS to MYSQL - Wordpress. I am using Python to read a txt file with <code>\t</code> delineated columns and one row per line.</p> <p>I am trying to write a Python script that will read this file (fread) and [eventually] create a MYSSQL ready .sql file with ...
4
2009-05-30T03:21:24Z
928,973
<pre><code>fwrite = open('/home/lyrae/Desktop/E/wp.users.sql','a') fread = open('/home/lyrae/Desktop/E/users.txt','r') for line in fread: line = line.split("\t") fwrite.write("insert into wp_users ( ID, user_login, user_name ) values (%s, '%s', '%s')\n" % (line[0], line[1], line[2])) fread.close() fwrite.clos...
0
2009-05-30T04:08:45Z
[ "python", "file" ]
Looping over a Python / IronPython Object Methods
928,990
<p>What is the proper way to loop over a Python object's methods and call them?</p> <p>Given the object:</p> <pre><code>class SomeTest(): def something1(self): print "something 1" def something2(self): print "something 2" </code></pre>
3
2009-05-30T04:24:46Z
928,997
<h3>Edit</h3> <p>Daniel, you are wrong.</p> <p><a href="http://docs.python.org/reference/datamodel.html" rel="nofollow">http://docs.python.org/reference/datamodel.html</a></p> <blockquote> <p>User-defined methods</p> <p>A user-defined <strong>method</strong> object <strong>combines a class, a class instance</...
-1
2009-05-30T04:30:56Z
[ "python", "reflection", "ironpython", "introspection", "python-datamodel" ]
Looping over a Python / IronPython Object Methods
928,990
<p>What is the proper way to loop over a Python object's methods and call them?</p> <p>Given the object:</p> <pre><code>class SomeTest(): def something1(self): print "something 1" def something2(self): print "something 2" </code></pre>
3
2009-05-30T04:24:46Z
1,191,333
<p>Methods vs. functions and other types of callables...</p> <p>(To address the issue in the comments in Unknown's post.)</p> <p>First, it should be noted that, in addition to user-defined methods, there are built-in methods, and a built-in method is, as the doc at <a href="http://docs.python.org/reference/datamodel....
3
2009-07-28T00:21:36Z
[ "python", "reflection", "ironpython", "introspection", "python-datamodel" ]
Looping over a Python / IronPython Object Methods
928,990
<p>What is the proper way to loop over a Python object's methods and call them?</p> <p>Given the object:</p> <pre><code>class SomeTest(): def something1(self): print "something 1" def something2(self): print "something 2" </code></pre>
3
2009-05-30T04:24:46Z
1,447,529
<p>You can use the inspect module to get class (or instance) members:</p> <pre><code>&gt;&gt;&gt; class C(object): ... a = 'blah' ... def b(self): ... pass ... ... &gt;&gt;&gt; c = C() &gt;&gt;&gt; inspect.getmembers(c, inspect.ismethod) [('b', &lt;bound method C.b of &lt;__main__.C object at 0x10...
7
2009-09-19T02:17:33Z
[ "python", "reflection", "ironpython", "introspection", "python-datamodel" ]
Looping over a Python / IronPython Object Methods
928,990
<p>What is the proper way to loop over a Python object's methods and call them?</p> <p>Given the object:</p> <pre><code>class SomeTest(): def something1(self): print "something 1" def something2(self): print "something 2" </code></pre>
3
2009-05-30T04:24:46Z
3,911,435
<p>This code snippet will call anything it will find in <code>obj</code> and store results in mapping, where key is attribute name — <code>dict((k, v()) for (k, v) in obj.__dict__.iteritems() if k.startswith('something'))</code></p>
0
2010-10-12T03:13:23Z
[ "python", "reflection", "ironpython", "introspection", "python-datamodel" ]
How do I access the child classes of an object in django without knowing the name of the child class?
929,029
<p>In Django, when you have a parent class and multiple child classes that inherit from it you would normally access a child through parentclass.childclass1_set or parentclass.childclass2_set, but what if I don't know the name of the specific child class I want?</p> <p>Is there a way to get the related objects in the ...
63
2009-05-30T04:52:56Z
929,073
<p>You can achieve this looking for all the fields in the parent that are an instance of django.db.models.fields.related.RelatedManager. From your example it seems that the child classes you are talking about are not subclasses. Right?</p>
0
2009-05-30T05:23:19Z
[ "python", "django", "many-to-many" ]
How do I access the child classes of an object in django without knowing the name of the child class?
929,029
<p>In Django, when you have a parent class and multiple child classes that inherit from it you would normally access a child through parentclass.childclass1_set or parentclass.childclass2_set, but what if I don't know the name of the specific child class I want?</p> <p>Is there a way to get the related objects in the ...
63
2009-05-30T04:52:56Z
929,128
<p>In Python, given a ("new-style") class X, you can get its (direct) subclasses with <code>X.__subclasses__()</code>, which returns a list of class objects. (If you want "further descendants", you'll also have to call <code>__subclasses__</code> on each of the direct subclasses, etc etc -- if you need help on how to d...
15
2009-05-30T06:02:24Z
[ "python", "django", "many-to-many" ]
How do I access the child classes of an object in django without knowing the name of the child class?
929,029
<p>In Django, when you have a parent class and multiple child classes that inherit from it you would normally access a child through parentclass.childclass1_set or parentclass.childclass2_set, but what if I don't know the name of the specific child class I want?</p> <p>Is there a way to get the related objects in the ...
63
2009-05-30T04:52:56Z
929,982
<p>(<strong>Update</strong>: For Django 1.2 and newer, which can follow select_related queries across reverse OneToOneField relations (and thus down inheritance hierarchies), there's a better technique available which doesn't require the added <code>real_type</code> field on the parent model. It's available as <a href=...
74
2009-05-30T15:47:56Z
[ "python", "django", "many-to-many" ]
How do I access the child classes of an object in django without knowing the name of the child class?
929,029
<p>In Django, when you have a parent class and multiple child classes that inherit from it you would normally access a child through parentclass.childclass1_set or parentclass.childclass2_set, but what if I don't know the name of the specific child class I want?</p> <p>Is there a way to get the related objects in the ...
63
2009-05-30T04:52:56Z
930,709
<p>Carl's solution is a good one, here's one way to do it manually if there are multiple related child classes:</p> <pre><code>def get_children(self): rel_objs = self._meta.get_all_related_objects() return [getattr(self, x.get_accessor_name()) for x in rel_objs if x.model != type(self)] </code></pre> <p>It us...
4
2009-05-30T22:01:08Z
[ "python", "django", "many-to-many" ]
How do I access the child classes of an object in django without knowing the name of the child class?
929,029
<p>In Django, when you have a parent class and multiple child classes that inherit from it you would normally access a child through parentclass.childclass1_set or parentclass.childclass2_set, but what if I don't know the name of the specific child class I want?</p> <p>Is there a way to get the related objects in the ...
63
2009-05-30T04:52:56Z
972,789
<p>It turns out that what I really needed was this:</p> <p><a href="http://www.djangosnippets.org/snippets/1034/">Model inheritance with content type and inheritance-aware manager</a></p> <p>That has worked perfectly for me. Thanks to everyone else, though. I learned a lot just reading your answers!</p>
5
2009-06-09T22:20:31Z
[ "python", "django", "many-to-many" ]
How do I access the child classes of an object in django without knowing the name of the child class?
929,029
<p>In Django, when you have a parent class and multiple child classes that inherit from it you would normally access a child through parentclass.childclass1_set or parentclass.childclass2_set, but what if I don't know the name of the specific child class I want?</p> <p>Is there a way to get the related objects in the ...
63
2009-05-30T04:52:56Z
12,425,895
<p>An alternative approach using proxies can be found in <a href="http://anthony-tresontani.github.com/Python/2012/09/11/django-polymorphism/" rel="nofollow">this blog post</a>. Like the other solutions, it has its benefits and liabilities, which are very well put in the end of the post.</p>
0
2012-09-14T13:47:42Z
[ "python", "django", "many-to-many" ]
How do I access the child classes of an object in django without knowing the name of the child class?
929,029
<p>In Django, when you have a parent class and multiple child classes that inherit from it you would normally access a child through parentclass.childclass1_set or parentclass.childclass2_set, but what if I don't know the name of the specific child class I want?</p> <p>Is there a way to get the related objects in the ...
63
2009-05-30T04:52:56Z
12,608,181
<p>Here's my solution, again it uses <code>_meta</code> so isn't guaranteed to be stable.</p> <pre><code>class Animal(models.model): name = models.CharField() number_legs = models.IntegerField() ... def get_child_animal(self): child_animal = None for r in self._meta.get_all_related_obj...
1
2012-09-26T18:32:38Z
[ "python", "django", "many-to-many" ]
How do I access the child classes of an object in django without knowing the name of the child class?
929,029
<p>In Django, when you have a parent class and multiple child classes that inherit from it you would normally access a child through parentclass.childclass1_set or parentclass.childclass2_set, but what if I don't know the name of the specific child class I want?</p> <p>Is there a way to get the related objects in the ...
63
2009-05-30T04:52:56Z
16,658,889
<p>You can use <a href="https://github.com/chrisglass/django_polymorphic" rel="nofollow">django-polymorphic</a> for that.</p>
1
2013-05-20T21:43:09Z
[ "python", "django", "many-to-many" ]
Eclipse + AppEngine =? autocomplete
929,095
<p>I was doing some beginner AppEngine dev on a Windows box and installed Eclipse for that. I liked the autocompletion I got with the objects and functions.</p> <p>I moved my dev environment over to my Macbook, and installed Eclipse Ganymede. I installed the AppEngine SDK and Eclipse plug in. However, when I am typ...
0
2009-05-30T05:41:17Z
930,606
<ol> <li>Do you have any form of 'Java Proposals' checked in Java->Editor->Content Assist->Advanced (see below)?</li> <li>Do you have any messages in your error log?</li> </ol> <p><img src="http://img26.imageshack.us/img26/2663/completionpreferences.png" alt="Preferences" /></p>
0
2009-05-30T21:00:38Z
[ "python", "eclipse", "google-app-engine" ]
Eclipse + AppEngine =? autocomplete
929,095
<p>I was doing some beginner AppEngine dev on a Windows box and installed Eclipse for that. I liked the autocompletion I got with the objects and functions.</p> <p>I moved my dev environment over to my Macbook, and installed Eclipse Ganymede. I installed the AppEngine SDK and Eclipse plug in. However, when I am typ...
0
2009-05-30T05:41:17Z
932,259
<p>The App Engine plugin for eclipse is for the Java SDK, not for the Python one. I don't know eclipse very well, but I suspect what you're missing is simply the path to the App Engine SDK included in eclipse's pythonpath configuration. Find somewhere to add that, and it'll be able to find the SDK classes and offer aut...
2
2009-05-31T15:33:55Z
[ "python", "eclipse", "google-app-engine" ]
Eclipse + AppEngine =? autocomplete
929,095
<p>I was doing some beginner AppEngine dev on a Windows box and installed Eclipse for that. I liked the autocompletion I got with the objects and functions.</p> <p>I moved my dev environment over to my Macbook, and installed Eclipse Ganymede. I installed the AppEngine SDK and Eclipse plug in. However, when I am typ...
0
2009-05-30T05:41:17Z
945,606
<p>To have Eclipse auto-complete your Python code you need to install Pydev into Eclipse.</p> <p>It's a free plug-in and is available here: <a href="http://aptana.com/python" rel="nofollow">http://aptana.com/python</a></p> <p>The URL to use when updating Eclipse: <a href="http://pydev.sourceforge.net/updates/" rel="n...
0
2009-06-03T16:09:02Z
[ "python", "eclipse", "google-app-engine" ]
Eclipse + AppEngine =? autocomplete
929,095
<p>I was doing some beginner AppEngine dev on a Windows box and installed Eclipse for that. I liked the autocompletion I got with the objects and functions.</p> <p>I moved my dev environment over to my Macbook, and installed Eclipse Ganymede. I installed the AppEngine SDK and Eclipse plug in. However, when I am typ...
0
2009-05-30T05:41:17Z
961,360
<p>I found the answer from a poster on the Google App Engine forum. I will blog the experience later, but this one gets a FAIL for GOOG. You need to click on the download link for "Linux/Other" to get the ZIP file with the right files. You can then point your PYTHONPATH at the directory on your local machine.</p> <...
0
2009-06-07T06:57:52Z
[ "python", "eclipse", "google-app-engine" ]
Eclipse + AppEngine =? autocomplete
929,095
<p>I was doing some beginner AppEngine dev on a Windows box and installed Eclipse for that. I liked the autocompletion I got with the objects and functions.</p> <p>I moved my dev environment over to my Macbook, and installed Eclipse Ganymede. I installed the AppEngine SDK and Eclipse plug in. However, when I am typ...
0
2009-05-30T05:41:17Z
13,116,061
<ol> <li>Add library <a href="http://stackoverflow.com/questions/7756981/pydev-project-for-google-app-engine-not-finding-webapp2">PyDev project for Google App Engine not finding webapp2</a></li> <li>Create pydev GAE project now <a href="http://www.mkyong.com/google-app-engine/google-app-engine-python-hello-world-exampl...
1
2012-10-29T04:57:51Z
[ "python", "eclipse", "google-app-engine" ]
Convert a number range to another range, maintaining ratio
929,103
<p>I'm trying to convert one range of numbers to another, maintaining ratio. Maths is not my strong point.</p> <p>I have an image file where point values may range from -16000.00 to 16000.00 though the typical range may be much less. What I want to do is compress these values into the integer range 0-100, where 0 is t...
135
2009-05-30T05:48:22Z
929,104
<p>That's a simple linear conversion.</p> <pre><code>new_value = ( (old_value - old_min) / (old_max - old_min) ) * (new_max - new_min) + new_min </code></pre> <p>So converting 10000 on the scale of -16000 to 16000 to a new scale of 0 to 100 yields:</p> <pre><code>old_value = 10000 old_min = -16000 old_max = 16000 ne...
39
2009-05-30T05:50:45Z
[ "python", "math" ]
Convert a number range to another range, maintaining ratio
929,103
<p>I'm trying to convert one range of numbers to another, maintaining ratio. Maths is not my strong point.</p> <p>I have an image file where point values may range from -16000.00 to 16000.00 though the typical range may be much less. What I want to do is compress these values into the integer range 0-100, where 0 is t...
135
2009-05-30T05:48:22Z
929,107
<pre><code>NewValue = (((OldValue - OldMin) * (NewMax - NewMin)) / (OldMax - OldMin)) + NewMin </code></pre> <p>Or a little more readable: </p> <pre><code>OldRange = (OldMax - OldMin) NewRange = (NewMax - NewMin) NewValue = (((OldValue - OldMin) * NewRange) / OldRange) + NewMin </code></pre> <p>Or if you want t...
244
2009-05-30T05:52:21Z
[ "python", "math" ]
Convert a number range to another range, maintaining ratio
929,103
<p>I'm trying to convert one range of numbers to another, maintaining ratio. Maths is not my strong point.</p> <p>I have an image file where point values may range from -16000.00 to 16000.00 though the typical range may be much less. What I want to do is compress these values into the integer range 0-100, where 0 is t...
135
2009-05-30T05:48:22Z
11,405,720
<p>There is a condition, when all of the values that you are checking are the same, where @jerryjvl's code would return NaN.</p> <pre><code>if (OldMin != OldMax &amp;&amp; NewMin != NewMax): return (((OldValue - OldMin) * (NewMax - NewMin)) / (OldMax - OldMin)) + NewMin else: return (NewMax + NewMin) / 2 </cod...
8
2012-07-10T02:11:52Z
[ "python", "math" ]
Convert a number range to another range, maintaining ratio
929,103
<p>I'm trying to convert one range of numbers to another, maintaining ratio. Maths is not my strong point.</p> <p>I have an image file where point values may range from -16000.00 to 16000.00 though the typical range may be much less. What I want to do is compress these values into the integer range 0-100, where 0 is t...
135
2009-05-30T05:48:22Z
15,537,393
<p>Actually there are some cases that above answers would break. Such as wrongly input value, wrongly input range, negative input/output ranges.</p> <pre><code>def remap( x, oMin, oMax, nMin, nMax ): #range check if oMin == oMax: print "Warning: Zero input range" return None if nMin == nM...
13
2013-03-21T00:32:53Z
[ "python", "math" ]
Convert a number range to another range, maintaining ratio
929,103
<p>I'm trying to convert one range of numbers to another, maintaining ratio. Maths is not my strong point.</p> <p>I have an image file where point values may range from -16000.00 to 16000.00 though the typical range may be much less. What I want to do is compress these values into the integer range 0-100, where 0 is t...
135
2009-05-30T05:48:22Z
24,658,800
<p>I used this solution in a problem I was solving in js, so I thought I would share the translation. Thanks for the explanation and solution.</p> <pre><code>function remap( x, oMin, oMax, nMin, nMax ){ //range check if (oMin == oMax){ console.log("Warning: Zero input range"); return None; }; if (nMin == nMax...
2
2014-07-09T16:14:08Z
[ "python", "math" ]
Convert a number range to another range, maintaining ratio
929,103
<p>I'm trying to convert one range of numbers to another, maintaining ratio. Maths is not my strong point.</p> <p>I have an image file where point values may range from -16000.00 to 16000.00 though the typical range may be much less. What I want to do is compress these values into the integer range 0-100, where 0 is t...
135
2009-05-30T05:48:22Z
27,137,732
<p>C++ Variant</p> <p>I found PenguinTD's Solution usefull, so i ported it to C++ if anyone needs it:</p> <blockquote> <p>float remap(float x, float oMin, float oMax, float nMin, float nMax ){</p> <pre><code>//range check if( oMin == oMax) { //std::cout&lt;&lt; "Warning: Zero input range"; return -1; } ...
1
2014-11-25T22:11:12Z
[ "python", "math" ]
Convert a number range to another range, maintaining ratio
929,103
<p>I'm trying to convert one range of numbers to another, maintaining ratio. Maths is not my strong point.</p> <p>I have an image file where point values may range from -16000.00 to 16000.00 though the typical range may be much less. What I want to do is compress these values into the integer range 0-100, where 0 is t...
135
2009-05-30T05:48:22Z
27,497,644
<p>In the listing provided by PenguinTD, I do not understand why the ranges are reversed, it works without having to reverse the ranges. Linear range conversion is based upon the linear equation <code>Y=Xm+n</code>, where <code>m</code> and <code>n</code> are derived from the given ranges. Rather than refer to the rang...
2
2014-12-16T04:40:26Z
[ "python", "math" ]
Convert a number range to another range, maintaining ratio
929,103
<p>I'm trying to convert one range of numbers to another, maintaining ratio. Maths is not my strong point.</p> <p>I have an image file where point values may range from -16000.00 to 16000.00 though the typical range may be much less. What I want to do is compress these values into the integer range 0-100, where 0 is t...
135
2009-05-30T05:48:22Z
29,505,969
<p><strong>Short-cut/simplified proposal</strong> </p> <pre><code> NewRange/OldRange = Handy multiplicand or HM Convert OldValue in OldRange to NewValue in NewRange = (OldValue - OldMin x HM) + NewMin </code></pre> <p>wayne</p>
-1
2015-04-08T04:30:54Z
[ "python", "math" ]
Convert a number range to another range, maintaining ratio
929,103
<p>I'm trying to convert one range of numbers to another, maintaining ratio. Maths is not my strong point.</p> <p>I have an image file where point values may range from -16000.00 to 16000.00 though the typical range may be much less. What I want to do is compress these values into the integer range 0-100, where 0 is t...
135
2009-05-30T05:48:22Z
36,244,586
<p>PHP Port</p> <p>Found PenguinTD's solution helpful so I ported it to PHP. Help yourself!</p> <pre><code>/** * ===================================== * Remap Range * ===================================== * - Convert one range to another. (including value) * * @param int $intValue The va...
2
2016-03-27T06:37:22Z
[ "python", "math" ]
str.startswith() not working as I intended
929,169
<p>I can't see why this won't work. I am performing lstrip() on the string being passed to the function, and trying to see if it starts with """. For some reason, it gets caught in an infinite loop</p> <pre><code>def find_comment(infile, line): line_t = line.lstrip() if not line_t.startswith('"""') and not li...
-1
2009-05-30T06:27:38Z
929,177
<pre><code>not line_t.startswith('"""') or not line_t.startswith('#') </code></pre> <p>This expression evaluates to True no matter what string line_t denotes. Do you want 'and' instead of 'or'? Your question isn't clear to me.</p>
1
2009-05-30T06:32:59Z
[ "python", "string", "python-3.x" ]
str.startswith() not working as I intended
929,169
<p>I can't see why this won't work. I am performing lstrip() on the string being passed to the function, and trying to see if it starts with """. For some reason, it gets caught in an infinite loop</p> <pre><code>def find_comment(infile, line): line_t = line.lstrip() if not line_t.startswith('"""') and not li...
-1
2009-05-30T06:27:38Z
929,185
<pre><code>if not line_t.startswith('"""') or not line_t.startswith('#'): </code></pre> <p>This <code>if</code> will always be satisfied -- either the line doesn't start with <code>"""</code>, or it doesn't start with <code>#</code> (or both). You probably meant to use <code>and</code> where you used <code>or</code>....
1
2009-05-30T06:37:58Z
[ "python", "string", "python-3.x" ]
str.startswith() not working as I intended
929,169
<p>I can't see why this won't work. I am performing lstrip() on the string being passed to the function, and trying to see if it starts with """. For some reason, it gets caught in an infinite loop</p> <pre><code>def find_comment(infile, line): line_t = line.lstrip() if not line_t.startswith('"""') and not li...
-1
2009-05-30T06:27:38Z
929,200
<p><code>while True</code> is an infinite loop. You need to <code>break</code> once you're done.</p>
2
2009-05-30T06:49:50Z
[ "python", "string", "python-3.x" ]
str.startswith() not working as I intended
929,169
<p>I can't see why this won't work. I am performing lstrip() on the string being passed to the function, and trying to see if it starts with """. For some reason, it gets caught in an infinite loop</p> <pre><code>def find_comment(infile, line): line_t = line.lstrip() if not line_t.startswith('"""') and not li...
-1
2009-05-30T06:27:38Z
929,208
<p>You haven't provided and exit path from the recursive loop. A return statement should do the trick.</p> <pre><code> (...) while True: if line.rstrip().endswith('"""'): line = infile.readline() return find_comment(infile, line) else: line = infile.readline()...
3
2009-05-30T06:57:19Z
[ "python", "string", "python-3.x" ]
str.startswith() not working as I intended
929,169
<p>I can't see why this won't work. I am performing lstrip() on the string being passed to the function, and trying to see if it starts with """. For some reason, it gets caught in an infinite loop</p> <pre><code>def find_comment(infile, line): line_t = line.lstrip() if not line_t.startswith('"""') and not li...
-1
2009-05-30T06:27:38Z
929,213
<p>As long as lines start or end with a comment, the code below should work.</p> <p>However, keep in mind that the docstrings can start or end in the middle of a line of code.</p> <p>Also, you'll need to code for triple single-quotes as well as docstrings assigned to variables which aren't really comments.</p> <p>Do...
1
2009-05-30T07:01:10Z
[ "python", "string", "python-3.x" ]
Is there a Python module/recipe (not numpy) for 2d arrays for small games
929,274
<p>I am writing some small games in Python with Pygame &amp; Pyglet as hobby projects.</p> <p>A class for 2D array would be very handy. I use py2exe to send the games to relatives/friends and numpy is just too big and most of it's features are unnecessary for my requirements.</p> <p>Could you suggest a Python module...
1
2009-05-30T07:46:36Z
929,332
<p>The simplest approach would just be to use nested lists:</p> <pre><code>&gt;&gt;&gt; matrix = [[0] * num_cols] * num_rows &gt;&gt;&gt; matrix[i][j] = 'value' # row i, column j, value 'value' &gt;&gt;&gt; print repr(matrix[i][j]) 'value' </code></pre> <p>Alternatively, if you’re going to be dealing with sparse ma...
3
2009-05-30T08:30:11Z
[ "python", "arrays", "multidimensional-array" ]
Is there a Python module/recipe (not numpy) for 2d arrays for small games
929,274
<p>I am writing some small games in Python with Pygame &amp; Pyglet as hobby projects.</p> <p>A class for 2D array would be very handy. I use py2exe to send the games to relatives/friends and numpy is just too big and most of it's features are unnecessary for my requirements.</p> <p>Could you suggest a Python module...
1
2009-05-30T07:46:36Z
929,376
<p>How about using a defaultdict?</p> <pre><code>&gt;&gt;&gt; import collections &gt;&gt;&gt; Matrix = lambda: collections.defaultdict(int) &gt;&gt;&gt; m = Matrix() &gt;&gt;&gt; m[3,2] = 6 &gt;&gt;&gt; print m[3,4] # deliberate typo :-) 0 &gt;&gt;&gt; m[3,2] += 4 &gt;&gt;&gt; print m[3,2] 10 &gt;&gt;&gt; print m de...
6
2009-05-30T08:48:39Z
[ "python", "arrays", "multidimensional-array" ]
Is there a Python module/recipe (not numpy) for 2d arrays for small games
929,274
<p>I am writing some small games in Python with Pygame &amp; Pyglet as hobby projects.</p> <p>A class for 2D array would be very handy. I use py2exe to send the games to relatives/friends and numpy is just too big and most of it's features are unnecessary for my requirements.</p> <p>Could you suggest a Python module...
1
2009-05-30T07:46:36Z
930,212
<p>Maybe <a href="http://code.google.com/p/pyeuclid/" rel="nofollow">pyeuclid</a> matches your needs -- (dated but usable) formatted docs are <a href="http://partiallydisassembled.net/euclid/" rel="nofollow">here</a>, up-to-date docs in ReST format are in <a href="http://code.google.com/p/pyeuclid/source/browse/trunk/e...
2
2009-05-30T17:53:32Z
[ "python", "arrays", "multidimensional-array" ]
Is there a Python module/recipe (not numpy) for 2d arrays for small games
929,274
<p>I am writing some small games in Python with Pygame &amp; Pyglet as hobby projects.</p> <p>A class for 2D array would be very handy. I use py2exe to send the games to relatives/friends and numpy is just too big and most of it's features are unnecessary for my requirements.</p> <p>Could you suggest a Python module...
1
2009-05-30T07:46:36Z
1,243,930
<p>I wrote the class. Don't know if it is a good or redundant but... Posted it here <a href="http://bitbucket.org/pieceofpeace/container2d/" rel="nofollow">http://bitbucket.org/pieceofpeace/container2d/</a></p>
0
2009-08-07T09:56:58Z
[ "python", "arrays", "multidimensional-array" ]
Django ORM Query to limit for the specific key instance
929,468
<p>Projectfundingdetail has a foreign key to project.</p> <p>The following query gives me the list of all projects that have <em>any</em> projectfundingdetail under 1000. How do I limit it to latest projectfundingdetail only.</p> <pre><code>projects_list.filter(projectfundingdetail__budget__lte=1000).distinct() </cod...
1
2009-05-30T09:59:51Z
930,180
<p>This query is harder than it looks at first glance. AFAIK the Django ORM does not provide any way to generate efficient SQL for this query, because the efficient SQL requires a correlated subquery. (I'd love to be corrected on this!) You can generate some ugly SQL with this query:</p> <pre><code>Projectfundingdet...
2
2009-05-30T17:38:58Z
[ "python", "django", "orm", "django-models", "django-orm" ]
Why doesn't inspect.getsource return the whole class source?
929,472
<p>I have this code in my <code>forms.py</code>:</p> <pre><code>from django import forms from formfieldset.forms import FieldsetMixin class ContactForm(forms.Form, FieldsetMixin): full_name = forms.CharField(max_length=120) email = forms.EmailField() website = forms.URLField() message = forms.CharFie...
0
2009-05-30T10:01:19Z
929,524
<p><strong>edit: revised based on comments:</strong></p> <p>Inside <code>inspect.getsource(forms.ContactForm)</code> the method <code>BlockFinder.tokeneater()</code> is used to determine where the <code>ContactForm</code> block stops. Besides others, it checks for <code>tokenize.DEDENT</code>, which it finds right bef...
1
2009-05-30T10:47:17Z
[ "python", "inspect", "code-inspection" ]
Why doesn't inspect.getsource return the whole class source?
929,472
<p>I have this code in my <code>forms.py</code>:</p> <pre><code>from django import forms from formfieldset.forms import FieldsetMixin class ContactForm(forms.Form, FieldsetMixin): full_name = forms.CharField(max_length=120) email = forms.EmailField() website = forms.URLField() message = forms.CharFie...
0
2009-05-30T10:01:19Z
929,618
<p>Works for me. I don't have "from formfieldset.forms import FieldsetMixin" in my code. Maybe that is causing an issue..</p>
0
2009-05-30T11:54:59Z
[ "python", "inspect", "code-inspection" ]
Why does assigning to my global variables not work in Python?
929,777
<p>I'm having terrible trouble trying to understand python scoping rules.</p> <p>With the following script:</p> <pre><code>a = 7 def printA(): print "Value of a is %d" % (a) def setA(value): a = value print "Inside setA, a is now %d" %(a) print "Before setA" printA() setA(42) print "After setA" printA...
34
2009-05-30T14:09:18Z
929,783
<p>Global variables are special. If you try to assign to a variable <code>a = value</code> inside of a function, it creates a new local variable inside the function, even if there is a global variable with the same name. To instead access the global variable, add a <a href="http://docs.python.org/reference/simple%5Fs...
78
2009-05-30T14:12:14Z
[ "python", "global-variables", "scope" ]
Why does assigning to my global variables not work in Python?
929,777
<p>I'm having terrible trouble trying to understand python scoping rules.</p> <p>With the following script:</p> <pre><code>a = 7 def printA(): print "Value of a is %d" % (a) def setA(value): a = value print "Inside setA, a is now %d" %(a) print "Before setA" printA() setA(42) print "After setA" printA...
34
2009-05-30T14:09:18Z
929,793
<p>The trick to understanding this is that when you assign to a variable, using =, you also declare it as a local variable. So instead of changing the value of the global variable a, setA(value) actually sets a local variable (which happens to be called a) to the value passed in.</p> <p>This becomes more obvious if yo...
10
2009-05-30T14:17:00Z
[ "python", "global-variables", "scope" ]
Why does assigning to my global variables not work in Python?
929,777
<p>I'm having terrible trouble trying to understand python scoping rules.</p> <p>With the following script:</p> <pre><code>a = 7 def printA(): print "Value of a is %d" % (a) def setA(value): a = value print "Inside setA, a is now %d" %(a) print "Before setA" printA() setA(42) print "After setA" printA...
34
2009-05-30T14:09:18Z
930,768
<p>Python does not have a concept of variables as other languages. You have objects which are "somewhere" and you have references to these objects. = is used to assign these objects to references in the <em>current</em> namespace.</p> <p>You create a name a in the namespace of the setA function which refers to the obj...
1
2009-05-30T22:26:57Z
[ "python", "global-variables", "scope" ]
Why does assigning to my global variables not work in Python?
929,777
<p>I'm having terrible trouble trying to understand python scoping rules.</p> <p>With the following script:</p> <pre><code>a = 7 def printA(): print "Value of a is %d" % (a) def setA(value): a = value print "Inside setA, a is now %d" %(a) print "Before setA" printA() setA(42) print "After setA" printA...
34
2009-05-30T14:09:18Z
2,076,921
<p>inside the function,<em>a</em> is treated as a local variable,you need to define <br></p> <blockquote> <p>global a </p> </blockquote> <p>inside the function</p>
1
2010-01-16T10:03:30Z
[ "python", "global-variables", "scope" ]
Runtime directory of Python
929,841
<p>How do I find out the current runtime directory from within a Python script?</p>
1
2009-05-30T14:45:12Z
929,849
<p>Use <a href="http://docs.python.org/library/os.html#os.getcwd" rel="nofollow"><code>os.getcwd</code></a>. This will tell you the <em>current working directory</em>. If you create a new file with</p> <pre><code>fp = open('a.txt', 'w') </code></pre> <p>then <code>a.txt</code> will be created in the current working d...
6
2009-05-30T14:48:33Z
[ "python", "working-directory" ]
Runtime directory of Python
929,841
<p>How do I find out the current runtime directory from within a Python script?</p>
1
2009-05-30T14:45:12Z
6,064,915
<p>This is working for me.</p> <pre><code>os.path.dirname(__file__) </code></pre>
0
2011-05-19T21:08:57Z
[ "python", "working-directory" ]
Runtime directory of Python
929,841
<p>How do I find out the current runtime directory from within a Python script?</p>
1
2009-05-30T14:45:12Z
13,082,959
<p><code>os.getcwd()</code> will change when u use <code>os.chdir</code></p> <p>If you need a fixed path to your python file, use:</p> <pre><code>module_path = os.path.dirname(__file__) </code></pre>
0
2012-10-26T07:54:12Z
[ "python", "working-directory" ]
Two simple questions about python
929,887
<p>I have 2 simple questions about python:</p> <p>1.How to get number of lines of a file in python?</p> <p>2.How to locate the position in a file object to the last line easily?</p>
2
2009-05-30T15:05:14Z
929,899
<p>lines are just data delimited by the newline char <code>'\n'</code>.</p> <p>1) Since lines are variable length, you have to read the entire file to know where the newline chars are, so you can count how many lines:</p> <pre><code>count = 0 for line in open('myfile'): count += 1 print count, line # it will be t...
8
2009-05-30T15:11:00Z
[ "python", "file" ]
Two simple questions about python
929,887
<p>I have 2 simple questions about python:</p> <p>1.How to get number of lines of a file in python?</p> <p>2.How to locate the position in a file object to the last line easily?</p>
2
2009-05-30T15:05:14Z
929,905
<p>The only way to count lines [that I know of] is to read all lines, like this:</p> <pre><code>count = 0 for line in open("file.txt"): count = count + 1 </code></pre> <p>After the loop, <code>count</code> will have the number of lines read.</p>
1
2009-05-30T15:13:26Z
[ "python", "file" ]
Two simple questions about python
929,887
<p>I have 2 simple questions about python:</p> <p>1.How to get number of lines of a file in python?</p> <p>2.How to locate the position in a file object to the last line easily?</p>
2
2009-05-30T15:05:14Z
929,907
<p>Answer to the first question (beware of poor performance on large files when using this method):</p> <pre><code>f = open("myfile.txt").readlines() print len(f) - 1 </code></pre> <p>Answer to the second question:</p> <pre><code>f = open("myfile.txt").read() print f.rfind("\n") </code></pre> <p>P.S. Yes I do under...
0
2009-05-30T15:14:07Z
[ "python", "file" ]
Two simple questions about python
929,887
<p>I have 2 simple questions about python:</p> <p>1.How to get number of lines of a file in python?</p> <p>2.How to locate the position in a file object to the last line easily?</p>
2
2009-05-30T15:05:14Z
929,922
<p>For small files that fit memory, how about using <a href="http://docs.python.org/library/string.html#string.count" rel="nofollow"><code>str.count()</code></a> for getting the number of lines of a file:</p> <pre><code>line_count = open("myfile.txt").read().count('\n') </code></pre>
2
2009-05-30T15:20:49Z
[ "python", "file" ]
Two simple questions about python
929,887
<p>I have 2 simple questions about python:</p> <p>1.How to get number of lines of a file in python?</p> <p>2.How to locate the position in a file object to the last line easily?</p>
2
2009-05-30T15:05:14Z
929,924
<p>Let's not forget</p> <pre><code>f = open("myfile.txt") lines = f.readlines() numlines = len(lines) lastline = lines[-1] </code></pre> <p>NOTE: this reads the whole file in memory as a list. Keep that in mind in the case that the file is very large.</p>
7
2009-05-30T15:21:11Z
[ "python", "file" ]
Two simple questions about python
929,887
<p>I have 2 simple questions about python:</p> <p>1.How to get number of lines of a file in python?</p> <p>2.How to locate the position in a file object to the last line easily?</p>
2
2009-05-30T15:05:14Z
929,970
<p>The <em>easiest</em> way is simply to read the file into memory. eg:</p> <pre><code>f = open('filename.txt') lines = f.readlines() num_lines = len(lines) last_line = lines[-1] </code></pre> <p>However for big files, this may use up a lot of memory, as the whole file is loaded into RAM. An alternative is to itera...
5
2009-05-30T15:42:56Z
[ "python", "file" ]
Two simple questions about python
929,887
<p>I have 2 simple questions about python:</p> <p>1.How to get number of lines of a file in python?</p> <p>2.How to locate the position in a file object to the last line easily?</p>
2
2009-05-30T15:05:14Z
930,010
<p>I'd like too add to the other solutions that some of them (those who look for <code>\n</code>) will not work with files with OS 9-style line endings (<code>\r</code> only), and that they may contain an extra blank line at the end because lots of text editors append it for some curious reasons, so you might or might ...
2
2009-05-30T15:56:49Z
[ "python", "file" ]
Two simple questions about python
929,887
<p>I have 2 simple questions about python:</p> <p>1.How to get number of lines of a file in python?</p> <p>2.How to locate the position in a file object to the last line easily?</p>
2
2009-05-30T15:05:14Z
930,229
<p>For the first question there're already a few good ones, I'll suggest @Brian's one as the best (most pythonic, line ending character proof and memory efficient):</p> <pre><code>f = open('filename.txt') num_lines = sum(1 for line in f) </code></pre> <p>For the second one, I like @nosklo's one, but modified to be mo...
0
2009-05-30T18:04:33Z
[ "python", "file" ]
Equivalent for Python's lambda functions in Java?
929,988
<p>Can someone please tell me if there is an equivalent for Python's lambda functions in Java?</p>
21
2009-05-30T15:49:17Z
930,003
<p>One idea is based on a generic <code>public interface Lambda&lt;T&gt;</code> -- see <a href="http://www.javalobby.org/java/forums/t75427.html">http://www.javalobby.org/java/forums/t75427.html</a> .</p>
6
2009-05-30T15:53:55Z
[ "java", "python", "function", "lambda" ]
Equivalent for Python's lambda functions in Java?
929,988
<p>Can someone please tell me if there is an equivalent for Python's lambda functions in Java?</p>
21
2009-05-30T15:49:17Z
930,012
<p>I don't think there is an exact equivalent, however there are anonymous classes that are about as close as you can get. But still pretty different. Joel Spolsky wrote an article about how the students taught only Java are missing out on these beauties of functional style programming: <a href="http://www.joelonsoft...
9
2009-05-30T15:57:01Z
[ "java", "python", "function", "lambda" ]
Equivalent for Python's lambda functions in Java?
929,988
<p>Can someone please tell me if there is an equivalent for Python's lambda functions in Java?</p>
21
2009-05-30T15:49:17Z
930,019
<p>Unfortunately, there are no lambdas in Java. However, you can get <em>almost</em> the same effect (in a really ugly way) with anonymous classes:</p> <pre><code>interface MyLambda { void theFunc(); // here we define the interface for the function } public class Something { static void execute(MyLambda l) { ...
28
2009-05-30T15:58:12Z
[ "java", "python", "function", "lambda" ]
Equivalent for Python's lambda functions in Java?
929,988
<p>Can someone please tell me if there is an equivalent for Python's lambda functions in Java?</p>
21
2009-05-30T15:49:17Z
3,050,232
<p>Somewhat similarly to Zifre's, you could create an interface thus</p> <pre><code>public interface myLambda&lt;In, Out&gt; { Out call(In i); } </code></pre> <p>to enable you to write, say</p> <pre><code>Function&lt;MyObj, Boolean&gt; func = new Function&lt;MyObj, Boolean&gt;() { public Boolean callFor(myOb...
1
2010-06-16T01:52:18Z
[ "java", "python", "function", "lambda" ]
Equivalent for Python's lambda functions in Java?
929,988
<p>Can someone please tell me if there is an equivalent for Python's lambda functions in Java?</p>
21
2009-05-30T15:49:17Z
28,942,165
<p>Yes,</p> <p>Lambda expressions are introduced in java from java8.</p> <p>Basic syntax for lambda expressions are:</p> <pre><code>(parameters)-&gt; { statements; } </code></pre> <p>Example</p> <pre><code>(String s)-&gt; { System.out.println(s); } </code></pre> <p>Check this link:</p> <p><a href="http://docs....
0
2015-03-09T12:36:06Z
[ "java", "python", "function", "lambda" ]
Python String Cleanup + Manipulation (Accented Characters)
930,303
<p>I have a database full of names like:</p> <pre><code>John Smith Scott J. Holmes Dr. Kaplan Ray's Dog Levi's Adrian O'Brien Perry Sean Smyre Carie Burchfield-Thompson Björn Árnason </code></pre> <p>There are a few foreign names with accents in them that need to be converted to strings with non-acc...
5
2009-05-30T18:36:16Z
930,316
<p>Take a look at this link [redacted]</p> <p>Here is the code from the page</p> <pre><code>def latin1_to_ascii (unicrap): """This replaces UNICODE Latin-1 characters with something equivalent in 7-bit ASCII. All characters in the standard 7-bit ASCII range are preserved. In the 8th bit range all the Lati...
12
2009-05-30T18:47:38Z
[ "python", "regex", "unicode", "string" ]
Python String Cleanup + Manipulation (Accented Characters)
930,303
<p>I have a database full of names like:</p> <pre><code>John Smith Scott J. Holmes Dr. Kaplan Ray's Dog Levi's Adrian O'Brien Perry Sean Smyre Carie Burchfield-Thompson Björn Árnason </code></pre> <p>There are a few foreign names with accents in them that need to be converted to strings with non-acc...
5
2009-05-30T18:36:16Z
930,324
<p>I would do something like this</p> <pre><code># coding=utf-8 def alnum_dot(name, replace={}): import re for k, v in replace.items(): name = name.replace(k, v) return re.sub("[^a-z.]", "", name.strip().lower()) print alnum_dot(u"Frédrik Holmström", { u"ö":"o", " ":"." }) </code></pre>...
1
2009-05-30T18:51:11Z
[ "python", "regex", "unicode", "string" ]
Python String Cleanup + Manipulation (Accented Characters)
930,303
<p>I have a database full of names like:</p> <pre><code>John Smith Scott J. Holmes Dr. Kaplan Ray's Dog Levi's Adrian O'Brien Perry Sean Smyre Carie Burchfield-Thompson Björn Árnason </code></pre> <p>There are a few foreign names with accents in them that need to be converted to strings with non-acc...
5
2009-05-30T18:36:16Z
930,331
<p>The translate method allows you to delete characters. You can use that to delete arbitrary characters.</p> <pre><code>Fullname.translate(None,"'-\"") </code></pre> <p>If you want to delete whole classes of characters, you might want to use the re module.</p> <pre><code>re.sub('[^a-z0-9 ]', '', Fullname.strip().lo...
1
2009-05-30T18:53:34Z
[ "python", "regex", "unicode", "string" ]