content
stringlengths 85
101k
| title
stringlengths 0
150
| question
stringlengths 15
48k
| answers
list | answers_scores
list | non_answers
list | non_answers_scores
list | tags
list | name
stringlengths 35
137
|
|---|---|---|---|---|---|---|---|---|
Q:
Why subprocess.Popen doesn't work when args is sequence?
I'm having a problem with subprocess.Popen when args parameter is given as sequence.
For example:
import subprocess
maildir = "/home/support/Maildir"
This works (it prints the correct size of /home/support/Maildir dir):
size = subprocess.Popen(["du -s -b " + maildir], shell=True,
stdout=subprocess.PIPE).communicate()[0].split()[0]
print size
But, this doesn't work (try it):
size = subprocess.Popen(["du", "-s -b", maildir], shell=True,
stdout=subprocess.PIPE).communicate()[0].split()[0]
print size
What's wrong?
A:
From the documentation
On Unix, with shell=True: […] If args is a sequence, the first item specifies the
command string, and any additional items will be treated as additional arguments to
the shell itself. That is to say, Popen does the equivalent of:
Popen(['/bin/sh', '-c', args[0], args[1], ...])
Which translates in your case to:
Popen(['/bin/sh', '-c', 'du', '-s', '-b', maildir])
This means that -s, -b and maildir are interpreted as options by the shell, not by du (try it on the shell commandline!).
Since shell=True is not needed in your case anyway, you could just remove it:
size = subprocess.Popen(['du', '-s', '-b', maildir],
stdout=subprocess.PIPE).communicate()[0].split()[0]
Alternatively you could just use your orignal approach, but you don't need a list in that case. You would also have to take care of spaces in the directory name:
size = subprocess.Popen('du -s -b "%s"' % maildir, shell=True,
stdout=subprocess.PIPE).communicate()[0].split()[0]
A:
From document,
On Unix, with shell=True: If args is a
string, it specifies the command
string to execute through the shell.
If args is a sequence, the first item
specifies the command string, and any
additional items will be treated as
additional shell arguments.
So, Try
subprocess.Popen("du -s -b " + maildir, ...
or
subprocess.Popen(["du","-s","-b",maildir], ...
A:
it should be ["du", "-s", "-b", maildir]
|
Why subprocess.Popen doesn't work when args is sequence?
|
I'm having a problem with subprocess.Popen when args parameter is given as sequence.
For example:
import subprocess
maildir = "/home/support/Maildir"
This works (it prints the correct size of /home/support/Maildir dir):
size = subprocess.Popen(["du -s -b " + maildir], shell=True,
stdout=subprocess.PIPE).communicate()[0].split()[0]
print size
But, this doesn't work (try it):
size = subprocess.Popen(["du", "-s -b", maildir], shell=True,
stdout=subprocess.PIPE).communicate()[0].split()[0]
print size
What's wrong?
|
[
"From the documentation\n\nOn Unix, with shell=True: […] If args is a sequence, the first item specifies the\n command string, and any additional items will be treated as additional arguments to\n the shell itself. That is to say, Popen does the equivalent of:\nPopen(['/bin/sh', '-c', args[0], args[1], ...])\n\n\nWhich translates in your case to:\nPopen(['/bin/sh', '-c', 'du', '-s', '-b', maildir])\n\nThis means that -s, -b and maildir are interpreted as options by the shell, not by du (try it on the shell commandline!).\nSince shell=True is not needed in your case anyway, you could just remove it:\nsize = subprocess.Popen(['du', '-s', '-b', maildir],\n stdout=subprocess.PIPE).communicate()[0].split()[0]\n\nAlternatively you could just use your orignal approach, but you don't need a list in that case. You would also have to take care of spaces in the directory name:\nsize = subprocess.Popen('du -s -b \"%s\"' % maildir, shell=True,\n stdout=subprocess.PIPE).communicate()[0].split()[0]\n\n",
"From document,\n\nOn Unix, with shell=True: If args is a\n string, it specifies the command\n string to execute through the shell.\n If args is a sequence, the first item\n specifies the command string, and any\n additional items will be treated as\n additional shell arguments.\n\nSo, Try \nsubprocess.Popen(\"du -s -b \" + maildir, ...\n\nor \nsubprocess.Popen([\"du\",\"-s\",\"-b\",maildir], ...\n\n",
"it should be [\"du\", \"-s\", \"-b\", maildir]\n"
] |
[
12,
5,
1
] |
[] |
[] |
[
"python",
"subprocess"
] |
stackoverflow_0002400878_python_subprocess.txt
|
Q:
Why does this python queue code process items multiple times?
The following is a testcase I created. Why does every process print the number 1 to 5 and are the numbers not divided over the processes?
code:
#!/usr/bin/python
from subprocess import *
from Queue import Queue
from Queue import Empty
import multiprocessing
from multiprocessing import Process
def main():
r = Runner()
r.run()
class Runner(object):
processes = []
def run(self):
q = Queue()
for t in range(1,6):
q.put(t)
for pi in range(1,4):
p = Process(target=self.runFromQueue, args=(q,))
p.start()
self.processes.append(p)
for p in self.processes:
p.join()
print "Finished!"
def runFromQueue(self, q):
try:
while True:
number = q.get_nowait()
print str(number)
q.task_done()
except Empty:
pass
if __name__ == "__main__":
main()
Ouput:
$ ./test_threads.py
1
2
3
4
5
1
1
2
3
2
4
3
5
4
5
Finished!
Expected ouput:
$ ./test_threads.py
1
2
3
4
5
Finished!
A:
The Queue package is not process aware, it only works for threads. The following happens in your example:
Create Queue and fill with numbers
Fork 4 processes. This copies the memory content into each subprocess, including the filled Queue
Each process empties its copy of the queue
You have to use the Queue class provided by multiprocessing.
|
Why does this python queue code process items multiple times?
|
The following is a testcase I created. Why does every process print the number 1 to 5 and are the numbers not divided over the processes?
code:
#!/usr/bin/python
from subprocess import *
from Queue import Queue
from Queue import Empty
import multiprocessing
from multiprocessing import Process
def main():
r = Runner()
r.run()
class Runner(object):
processes = []
def run(self):
q = Queue()
for t in range(1,6):
q.put(t)
for pi in range(1,4):
p = Process(target=self.runFromQueue, args=(q,))
p.start()
self.processes.append(p)
for p in self.processes:
p.join()
print "Finished!"
def runFromQueue(self, q):
try:
while True:
number = q.get_nowait()
print str(number)
q.task_done()
except Empty:
pass
if __name__ == "__main__":
main()
Ouput:
$ ./test_threads.py
1
2
3
4
5
1
1
2
3
2
4
3
5
4
5
Finished!
Expected ouput:
$ ./test_threads.py
1
2
3
4
5
Finished!
|
[
"The Queue package is not process aware, it only works for threads. The following happens in your example:\n\nCreate Queue and fill with numbers\nFork 4 processes. This copies the memory content into each subprocess, including the filled Queue\nEach process empties its copy of the queue\n\nYou have to use the Queue class provided by multiprocessing.\n"
] |
[
8
] |
[] |
[] |
[
"multithreading",
"python",
"queue"
] |
stackoverflow_0002401117_multithreading_python_queue.txt
|
Q:
Importing Python module from Bash
I am launching a Python script from the command line (Bash) under Linux. I need to open Python, import a module, and then have lines of code interpreted. The console must then remain in Python (not quit it). How do I do that?
I have tried an alias like this one:
alias program="cd /home/myname/programs/; python; import module; line_of_code"
But this only starts python and the commands are not executed (no module import, no line of code treated).
What is the proper way of doing this, provided I need to keep Python open (not quit it) after the script is executed?
Many thanks!
A:
An easy way to do this is with the "code" module:
python -c "import code; code.interact(local=locals())"
This will drop you into an interactive shell when code.interact() is called. The local keyword argument to interact is used to prepopulate the default namespace for the interpreter that gets created; we'll use locals(), which is a builtin function that returns the local namespace as a dictionary.
Your command would look something like this:
python -c "import mymodule, code; code.interact(local=locals())"
which drops you into an interpreter that has the correct environment.
A:
use a subroutine instead of alias
callmyprogram(){
python -i -c "import time;print time.localtime()"
}
callmyprogram
A:
Example:
python -c "import time ; print 'waiting 2 sec.'; time.sleep(2); print 'finished' "
|
Importing Python module from Bash
|
I am launching a Python script from the command line (Bash) under Linux. I need to open Python, import a module, and then have lines of code interpreted. The console must then remain in Python (not quit it). How do I do that?
I have tried an alias like this one:
alias program="cd /home/myname/programs/; python; import module; line_of_code"
But this only starts python and the commands are not executed (no module import, no line of code treated).
What is the proper way of doing this, provided I need to keep Python open (not quit it) after the script is executed?
Many thanks!
|
[
"An easy way to do this is with the \"code\" module:\npython -c \"import code; code.interact(local=locals())\"\n\nThis will drop you into an interactive shell when code.interact() is called. The local keyword argument to interact is used to prepopulate the default namespace for the interpreter that gets created; we'll use locals(), which is a builtin function that returns the local namespace as a dictionary.\nYour command would look something like this:\npython -c \"import mymodule, code; code.interact(local=locals())\"\n\nwhich drops you into an interpreter that has the correct environment.\n",
"use a subroutine instead of alias\ncallmyprogram(){\n python -i -c \"import time;print time.localtime()\"\n}\ncallmyprogram\n\n",
"Example:\npython -c \"import time ; print 'waiting 2 sec.'; time.sleep(2); print 'finished' \"\n\n"
] |
[
16,
9,
3
] |
[] |
[] |
[
"alias",
"bash",
"linux",
"python"
] |
stackoverflow_0002401305_alias_bash_linux_python.txt
|
Q:
How to run python scripts on your server?
I have mod_python installed on my server, but if I want to acceses a python script - let's say httü://site.com/something.py the script doesn't run, the download box "pops up"
Any solutions?
A:
I would consider a lightweight framework such as http://werkzeug.pocoo.org/ as it isn't very practical in the modern day to have CGI-style python scripts.
And I would use mod_wsgi instead of mod_python as the latter is a bit outdated.
A:
This should be on ServerFault. By the way, mod_python is deprecated, use WSGI instead.
A:
Is mod_py configured ok?
http://www.modpython.org/live/current/doc-html/inst-apacheconfig.html
|
How to run python scripts on your server?
|
I have mod_python installed on my server, but if I want to acceses a python script - let's say httü://site.com/something.py the script doesn't run, the download box "pops up"
Any solutions?
|
[
"I would consider a lightweight framework such as http://werkzeug.pocoo.org/ as it isn't very practical in the modern day to have CGI-style python scripts.\nAnd I would use mod_wsgi instead of mod_python as the latter is a bit outdated.\n",
"This should be on ServerFault. By the way, mod_python is deprecated, use WSGI instead.\n",
"Is mod_py configured ok?\nhttp://www.modpython.org/live/current/doc-html/inst-apacheconfig.html\n"
] |
[
1,
0,
0
] |
[] |
[] |
[
"apache",
"python",
"unix"
] |
stackoverflow_0002401602_apache_python_unix.txt
|
Q:
Generator speed in python 3
I am going through a link about generators that someone posted. In the beginning he compares the two functions below. On his setup he showed a speed increase of 5% with the generator.
I'm running windows XP, python 3.1.1, and cannot seem to duplicate the results. I keep showing the "old way"(logs1) as being slightly faster when tested with the provided logs and up to 1GB of duplicated data.
Can someone help me understand whats happening differently?
Thanks!
def logs1():
wwwlog = open("big-access-log")
total = 0
for line in wwwlog:
bytestr = line.rsplit(None,1)[1]
if bytestr != '-':
total += int(bytestr)
return total
def logs2():
wwwlog = open("big-access-log")
bytecolumn = (line.rsplit(None,1)[1] for line in wwwlog)
getbytes = (int(x) for x in bytecolumn if x != '-')
return sum(getbytes)
*edit, spacing messed up in copy/paste
A:
For what it's worth, the main purpose of the speed comparison in the presentation was to point out that using generators does not introduce a huge performance overhead. Many programmers, when first seeing generators, might start wondering about the hidden costs. For example, is there all sorts of fancy magic going on behind the scenes? Is using this feature going to make my program run twice as slow?
In general that's not the case. The example is meant to show that a generator solution can run at essentially the same speed, if not slightly faster in some cases (although it depends on the situation, version of Python, etc.). If you are observing huge differences in performance between the two versions though, then that would be something worth investigating.
A:
In David Beazley's slides that you linked to, he states that all tests were run with "Python 2.5.1 on OS X 10.4.11," and you say you're running tests with Python 3.1 on Windows XP. So, realize you're doing some apples to oranges comparison. I suspect of the two variables, the Python version matters much more.
Python 3 is a different beast than Python 2. Many things have changed under the hood, (even within the Python 2 branch). This includes performance optimizations as well as performance regressions (see, for example, Beazley's own recent blog post on I/O in Python 3). For this reason, the Python Performance Tips page states explicitly,
You should always test these tips with
your application and the version of
Python you intend to use and not just
blindly accept that one method is
faster than another.
I should mention that one area that you can count on generators helping is in reducing memory consumption, rather than CPU consumption. If you have a large amount of data where you calculate or extract something from each individual piece, and you don't need the data after, generators will shine. See generator comprehension for more details.
A:
You don't have an answer after almost a half an hour. I'm posting something that makes sense to me, not necessarily the right answer. I figure that this is better than nothing after almost half an hour:
The first algorithm uses a generator. A generator functions by loading the first page of results from the list (into memory) and continually loads the successive pages (into memory) until there is nothing left to read from input.
The second algorithm uses two generators, each with an if statement for a total of two comparisons per loop as opposed to the first algorithm's one comparison.
Also the second algorithm calls the sum function at the end as opposed to the first algorithm that simply keeps adding relevant integers as it keeps encountering them.
As such, for sufficiently large inputs, the second algorithm has more comparisons and an extra function call than the first. This could possibly explain why it takes longer to finish than the first algorithm.
Hope this helps
|
Generator speed in python 3
|
I am going through a link about generators that someone posted. In the beginning he compares the two functions below. On his setup he showed a speed increase of 5% with the generator.
I'm running windows XP, python 3.1.1, and cannot seem to duplicate the results. I keep showing the "old way"(logs1) as being slightly faster when tested with the provided logs and up to 1GB of duplicated data.
Can someone help me understand whats happening differently?
Thanks!
def logs1():
wwwlog = open("big-access-log")
total = 0
for line in wwwlog:
bytestr = line.rsplit(None,1)[1]
if bytestr != '-':
total += int(bytestr)
return total
def logs2():
wwwlog = open("big-access-log")
bytecolumn = (line.rsplit(None,1)[1] for line in wwwlog)
getbytes = (int(x) for x in bytecolumn if x != '-')
return sum(getbytes)
*edit, spacing messed up in copy/paste
|
[
"For what it's worth, the main purpose of the speed comparison in the presentation was to point out that using generators does not introduce a huge performance overhead. Many programmers, when first seeing generators, might start wondering about the hidden costs. For example, is there all sorts of fancy magic going on behind the scenes? Is using this feature going to make my program run twice as slow?\nIn general that's not the case. The example is meant to show that a generator solution can run at essentially the same speed, if not slightly faster in some cases (although it depends on the situation, version of Python, etc.). If you are observing huge differences in performance between the two versions though, then that would be something worth investigating.\n",
"In David Beazley's slides that you linked to, he states that all tests were run with \"Python 2.5.1 on OS X 10.4.11,\" and you say you're running tests with Python 3.1 on Windows XP. So, realize you're doing some apples to oranges comparison. I suspect of the two variables, the Python version matters much more.\nPython 3 is a different beast than Python 2. Many things have changed under the hood, (even within the Python 2 branch). This includes performance optimizations as well as performance regressions (see, for example, Beazley's own recent blog post on I/O in Python 3). For this reason, the Python Performance Tips page states explicitly,\n\nYou should always test these tips with\n your application and the version of\n Python you intend to use and not just\n blindly accept that one method is\n faster than another.\n\nI should mention that one area that you can count on generators helping is in reducing memory consumption, rather than CPU consumption. If you have a large amount of data where you calculate or extract something from each individual piece, and you don't need the data after, generators will shine. See generator comprehension for more details.\n",
"You don't have an answer after almost a half an hour. I'm posting something that makes sense to me, not necessarily the right answer. I figure that this is better than nothing after almost half an hour:\nThe first algorithm uses a generator. A generator functions by loading the first page of results from the list (into memory) and continually loads the successive pages (into memory) until there is nothing left to read from input.\nThe second algorithm uses two generators, each with an if statement for a total of two comparisons per loop as opposed to the first algorithm's one comparison.\nAlso the second algorithm calls the sum function at the end as opposed to the first algorithm that simply keeps adding relevant integers as it keeps encountering them.\nAs such, for sufficiently large inputs, the second algorithm has more comparisons and an extra function call than the first. This could possibly explain why it takes longer to finish than the first algorithm.\nHope this helps\n"
] |
[
9,
1,
0
] |
[] |
[] |
[
"python",
"python_3.x"
] |
stackoverflow_0002399308_python_python_3.x.txt
|
Q:
Python: getting \\u00bd correctly in editor
I would like to do the following:
1) Serialize my class
2) Also manually edit the serialization dump file to remove certain objects of my class which I find unnecessary.
I am currently using python with simplejson. As you know, simplejson converts all characters to unicde. As a result, when I dump a particular object with simplejson, the unicode characters becomes something like that "\u00bd" for 好.
I am interested to manually edit the simplejson file for convenience. Anyone here know a work around for me to do this?
My requirements for this serialization format:
1) Easy to use (just dump and load - done)
2) Allows me to edit them manually without much hassle.
3) Able to display chinese character
I use vim. Does anyone know a way to conver "\u00bd" to 好 in vim?
A:
I don't know anything about simplejson or the Serialisation part of the question, but you asked about converting "\u00bd" to 好 in Vim. Here are some vim tips for working with unicode:
You'll need the correct encoding set up in vim, see:
:help 'encoding'
:help 'fileencoding'
Entering unicode characters by number is simply a case of going into insert mode, pressing Ctrl-V and then typing u followed by the four digit number (or U followed by an 8-digit number). See:
:help i_CTRL-V_digit
Also bear in mind that in order for the character to display correctly in Vim, you'll need a fixed-width font containing that character. It appears as a wide space in Envy Code R and as various boxes in Lucida Console, Consolas and Courier New.
To replace \uXXXX with unicode character XXXX (where X is any hexadecimal digit), type this when in normal mode (where <ENTER> means press the ENTER key, don't type it literally):
:%s/\\u\x\{4\}/\=eval('"' . submatch(0) . '"')/g<ENTER>
Note however that u00bd appears to be unicode character ½ (1/2 in case that character doesn't display correctly on your screen), not the 好 character you mentioned (which is u597D I think). See this unicode table. Start vim and type these characters (where <Ctrl-V> is produced by holding CTRL, pressing V, releasing V and then releasing CTRL):
i<Ctrl-V>u00bd
You should see a small character looking like 1/2, assuming your font supports that character.
A:
If you want json/simplejson to produce unicode output instead of str output with Unicode escapes then you need to pass ensure_ascii=False to dump()/dumps(), then either encode before saving or use a file-like from codecs.
|
Python: getting \\u00bd correctly in editor
|
I would like to do the following:
1) Serialize my class
2) Also manually edit the serialization dump file to remove certain objects of my class which I find unnecessary.
I am currently using python with simplejson. As you know, simplejson converts all characters to unicde. As a result, when I dump a particular object with simplejson, the unicode characters becomes something like that "\u00bd" for 好.
I am interested to manually edit the simplejson file for convenience. Anyone here know a work around for me to do this?
My requirements for this serialization format:
1) Easy to use (just dump and load - done)
2) Allows me to edit them manually without much hassle.
3) Able to display chinese character
I use vim. Does anyone know a way to conver "\u00bd" to 好 in vim?
|
[
"I don't know anything about simplejson or the Serialisation part of the question, but you asked about converting \"\\u00bd\" to 好 in Vim. Here are some vim tips for working with unicode:\n\nYou'll need the correct encoding set up in vim, see:\n:help 'encoding'\n:help 'fileencoding'\n\nEntering unicode characters by number is simply a case of going into insert mode, pressing Ctrl-V and then typing u followed by the four digit number (or U followed by an 8-digit number). See:\n:help i_CTRL-V_digit\n\nAlso bear in mind that in order for the character to display correctly in Vim, you'll need a fixed-width font containing that character. It appears as a wide space in Envy Code R and as various boxes in Lucida Console, Consolas and Courier New.\nTo replace \\uXXXX with unicode character XXXX (where X is any hexadecimal digit), type this when in normal mode (where <ENTER> means press the ENTER key, don't type it literally):\n:%s/\\\\u\\x\\{4\\}/\\=eval('\"' . submatch(0) . '\"')/g<ENTER>\n\n\nNote however that u00bd appears to be unicode character ½ (1/2 in case that character doesn't display correctly on your screen), not the 好 character you mentioned (which is u597D I think). See this unicode table. Start vim and type these characters (where <Ctrl-V> is produced by holding CTRL, pressing V, releasing V and then releasing CTRL):\n i<Ctrl-V>u00bd\n\nYou should see a small character looking like 1/2, assuming your font supports that character.\n",
"If you want json/simplejson to produce unicode output instead of str output with Unicode escapes then you need to pass ensure_ascii=False to dump()/dumps(), then either encode before saving or use a file-like from codecs.\n"
] |
[
1,
0
] |
[] |
[] |
[
"python",
"vim"
] |
stackoverflow_0002400088_python_vim.txt
|
Q:
Convert list in tuple to numpy array?
I have tuple of lists. One of these lists is a list of scores. I want to convert the list of scores to a numpy array to take advantage of the pre-built stats that scipy provides.
In this case the tuple is called 'data'
In [12]: type data[2]
-------> type(data[2])
Out[12]: <type 'list'>
In [13]: type data[2][1]
-------> type(data[2][1])
Out[13]: <type 'list'>
In [14]: type data[2][1][1]
-------> type(data[2][1][1])
Out[14]: <type 'float'>
In [15]: print data[2][1]
-------> print(data[2][1])
[16.66, 16.66, 16.66, 16.66, 5.5599999999999996, 16.699999999999999]
In [16]: print data[2][1][1]
-------> print(data[2][1][1])
16.66
Can I do this easily once I have stored the tuple?
A:
The command numpy.asarray will turn a number of pre-set iterable containers (list, tuple, etc) into a numpy array.
|
Convert list in tuple to numpy array?
|
I have tuple of lists. One of these lists is a list of scores. I want to convert the list of scores to a numpy array to take advantage of the pre-built stats that scipy provides.
In this case the tuple is called 'data'
In [12]: type data[2]
-------> type(data[2])
Out[12]: <type 'list'>
In [13]: type data[2][1]
-------> type(data[2][1])
Out[13]: <type 'list'>
In [14]: type data[2][1][1]
-------> type(data[2][1][1])
Out[14]: <type 'float'>
In [15]: print data[2][1]
-------> print(data[2][1])
[16.66, 16.66, 16.66, 16.66, 5.5599999999999996, 16.699999999999999]
In [16]: print data[2][1][1]
-------> print(data[2][1][1])
16.66
Can I do this easily once I have stored the tuple?
|
[
"The command numpy.asarray will turn a number of pre-set iterable containers (list, tuple, etc) into a numpy array.\n"
] |
[
47
] |
[] |
[] |
[
"arrays",
"numpy",
"python",
"scipy",
"tuples"
] |
stackoverflow_0002402575_arrays_numpy_python_scipy_tuples.txt
|
Q:
Python: Help with counters and writing files
Possible Duplicate:
Python: How do I create sequential file names?
I was suggested to use a separate file as a counter to give my files sequential file names, but I don't understand how I would do that. I need my file names to have sequential numbers, like file1.txt, file2.txt, file3.txt. Any help is appreciated!
Edit:
My mistake, I forgot to say that the code makes 1 file when it's executed, and needs a way to make a new separate one with a different file name.
More Edit:
I am taking a screen shot basically and trying to write it to a file, and I want to be able to take more than one without it being overwritten.
A:
More information probably is needed, but if you want to sequentially name files to avoid name clashes etc you don't necessarily need a separate file to record the current number. I'm assuming you want to write a new file from time to time, numbering to keep track of things?
So given a set of files, you want to know what the next valid file name would be.
Something like (for files in the current directory):
import os.path
def next_file_name():
num = 1
while True:
file_name = 'file%d.txt' % num
if not os.path.exists(file_name):
return file_name
num += 1
Obviously though as the number of files in the directory increases this will get slower, so it depends on how many files you expect there to be.
A:
Something like this?
n = 100
for i in range(n):
open('file' + str(i) + '.txt', 'w').close()
A:
Hypothetical example.
import os
counter_file="counter.file"
if not os.path.exists(counter_file):
open(counter_file).write("1");
else:
num=int(open(counter_file).read().strip()) #read the number
# do processing...
outfile=open("out_file_"+str(num),"w")
for line in open("file_to_process"):
# ...processing ...
outfile.write(line)
outfile.close()
num+=1 #increment
open(counter_file,"w").write(str(num))
A:
# get current filenum, or 1 to start
try:
with open('counterfile', 'r') as f:
filenum = int(f.read())
except (IOError, ValueError):
filenum = 1
# write next filenum for next run
with open('counterfile', 'w') as f:
f.write(str(filenum + 1))
filename = 'file%s.txt' % filenum
with open(filename, 'w') as f:
f.write('whatever you need\n')
# insert all processing here, write to f
In Python 2.5, you also need a first line of from __future__ import with_statement to use this code example; in Python 2.6 or better, you don't (and you could also use a more elegant formatting solution than that % operator, but that's a very minor issue).
|
Python: Help with counters and writing files
|
Possible Duplicate:
Python: How do I create sequential file names?
I was suggested to use a separate file as a counter to give my files sequential file names, but I don't understand how I would do that. I need my file names to have sequential numbers, like file1.txt, file2.txt, file3.txt. Any help is appreciated!
Edit:
My mistake, I forgot to say that the code makes 1 file when it's executed, and needs a way to make a new separate one with a different file name.
More Edit:
I am taking a screen shot basically and trying to write it to a file, and I want to be able to take more than one without it being overwritten.
|
[
"More information probably is needed, but if you want to sequentially name files to avoid name clashes etc you don't necessarily need a separate file to record the current number. I'm assuming you want to write a new file from time to time, numbering to keep track of things?\nSo given a set of files, you want to know what the next valid file name would be.\nSomething like (for files in the current directory):\n\nimport os.path\ndef next_file_name():\n num = 1\n while True:\n file_name = 'file%d.txt' % num\n if not os.path.exists(file_name):\n return file_name\n num += 1\n\nObviously though as the number of files in the directory increases this will get slower, so it depends on how many files you expect there to be.\n",
"Something like this?\nn = 100\nfor i in range(n):\n open('file' + str(i) + '.txt', 'w').close()\n\n",
"Hypothetical example.\nimport os\ncounter_file=\"counter.file\"\nif not os.path.exists(counter_file):\n open(counter_file).write(\"1\");\nelse:\n num=int(open(counter_file).read().strip()) #read the number\n# do processing...\noutfile=open(\"out_file_\"+str(num),\"w\")\nfor line in open(\"file_to_process\"):\n # ...processing ...\n outfile.write(line) \noutfile.close()\nnum+=1 #increment\nopen(counter_file,\"w\").write(str(num))\n\n",
"# get current filenum, or 1 to start\ntry:\n with open('counterfile', 'r') as f:\n filenum = int(f.read())\nexcept (IOError, ValueError):\n filenum = 1\n\n# write next filenum for next run\nwith open('counterfile', 'w') as f:\n f.write(str(filenum + 1))\n\nfilename = 'file%s.txt' % filenum\nwith open(filename, 'w') as f:\n f.write('whatever you need\\n')\n # insert all processing here, write to f\n\nIn Python 2.5, you also need a first line of from __future__ import with_statement to use this code example; in Python 2.6 or better, you don't (and you could also use a more elegant formatting solution than that % operator, but that's a very minor issue).\n"
] |
[
4,
0,
0,
0
] |
[] |
[] |
[
"filesystems",
"python"
] |
stackoverflow_0002401235_filesystems_python.txt
|
Q:
django: caching passwords for custom authentication
I am authenticating users in ldap, but this happens only once, when user is logging in. Afterwards I need to keep username and password, because before every ldap operation I need to make bind on ldap server before every operation. What is the safe way to cache this password (I can't store in the database or cookies) for as long as session persists.
A:
You may cache authentication credentials in sessions. If you are afraid that they may "leak" to disk, i.e. be cached in database, you may use memory based sessions.
With cache session engine (Using cached sessions) and memory based sessions this should be accomplished easily.
A:
solution 1:
maybe the most elegant solution would be to write your own auth-backend and share it with the community :-)
solution 2:
make use of the very good caching-api which django has build-in
|
django: caching passwords for custom authentication
|
I am authenticating users in ldap, but this happens only once, when user is logging in. Afterwards I need to keep username and password, because before every ldap operation I need to make bind on ldap server before every operation. What is the safe way to cache this password (I can't store in the database or cookies) for as long as session persists.
|
[
"You may cache authentication credentials in sessions. If you are afraid that they may \"leak\" to disk, i.e. be cached in database, you may use memory based sessions.\nWith cache session engine (Using cached sessions) and memory based sessions this should be accomplished easily. \n",
"solution 1:\nmaybe the most elegant solution would be to write your own auth-backend and share it with the community :-)\nsolution 2:\nmake use of the very good caching-api which django has build-in\n"
] |
[
2,
1
] |
[] |
[] |
[
"caching",
"django",
"ldap",
"passwords",
"python"
] |
stackoverflow_0002402694_caching_django_ldap_passwords_python.txt
|
Q:
Python instances and attributes: is this a bug or i got it totally wrong?
Suppose you have something like this:
class intlist:
def __init__(self,l = []):
self.l = l
def add(self,a):
self.l.append(a)
def appender(a):
obj = intlist()
obj.add(a)
print obj.l
if __name__ == "__main__":
for i in range(5):
appender(i)
A function creates an instance of intlist and calls on this fresh instance the method append on the instance attribute l.
How comes the output of this code is:
[0]
[0, 1]
[0, 1, 2]
[0, 1, 2, 3]
[0, 1, 2, 3, 4]
?
If i switch
obj = intlist()
with
obj = intlist(l=[])
I get the desired output
[0]
[1]
[2]
[3]
[4]
Why this happens?
Thanks
A:
Ah, you've hit one of the common Python gotchas: default values are computed once, then re-used. So, every time __init__ is called, the same list is being used.
This is the Pythonic way of doing what you want:
def __init__(self, l=None):
self.l = [] if l is None else l
For a bit more information, check out the Python docs (especially about three paragraphs after that heading).
Edit: There is a much better description in another answer.
A:
When you set the default value of l=[] in __init__, you're actually using the same list each time. Instead, you could try something like:
class intlist:
def __init__(self, l=None):
if l is None:
self.l = []
else:
self.l = l
A:
The issue is that when you are saying
def __init__(self,l = []):
You are telling Python to use the same list, [], for each invocation of the constructor. So each time obj = intlist() is called the same list is appended to.
What you should do instead is set l to a default value of None, which is a scalar (so your code will work as expected if it is used multiple times). Then, if l is None, initialize a new class member as []. Otherwise just assign the member variable to l.
A:
The behavior occurs because all calls to your __init__ method share the same default list.
Try:
class intlist:
def __init__(self, l):
self.l = l if (l is not None) else []
def add(self,a):
self.l.append(a)
EDIT: Use is not, per SilentGhost
A:
obj = intlist() calls your __init__() function which uses the same array for every instance of the class.
obj = intlist(l=[]) creates a new array for every instance.
A:
For more information I suggest reading this: http://effbot.org/zone/default-values.htm
A:
Be careful with default parameters of types like lists and dicts. Each instance of intlist gets that same list object from the default parameter.
|
Python instances and attributes: is this a bug or i got it totally wrong?
|
Suppose you have something like this:
class intlist:
def __init__(self,l = []):
self.l = l
def add(self,a):
self.l.append(a)
def appender(a):
obj = intlist()
obj.add(a)
print obj.l
if __name__ == "__main__":
for i in range(5):
appender(i)
A function creates an instance of intlist and calls on this fresh instance the method append on the instance attribute l.
How comes the output of this code is:
[0]
[0, 1]
[0, 1, 2]
[0, 1, 2, 3]
[0, 1, 2, 3, 4]
?
If i switch
obj = intlist()
with
obj = intlist(l=[])
I get the desired output
[0]
[1]
[2]
[3]
[4]
Why this happens?
Thanks
|
[
"Ah, you've hit one of the common Python gotchas: default values are computed once, then re-used. So, every time __init__ is called, the same list is being used.\nThis is the Pythonic way of doing what you want:\ndef __init__(self, l=None):\n self.l = [] if l is None else l\n\nFor a bit more information, check out the Python docs (especially about three paragraphs after that heading).\nEdit: There is a much better description in another answer.\n",
"When you set the default value of l=[] in __init__, you're actually using the same list each time. Instead, you could try something like:\nclass intlist:\n def __init__(self, l=None):\n if l is None:\n self.l = []\n else:\n self.l = l\n\n",
"The issue is that when you are saying\ndef __init__(self,l = []):\n\nYou are telling Python to use the same list, [], for each invocation of the constructor. So each time obj = intlist() is called the same list is appended to. \nWhat you should do instead is set l to a default value of None, which is a scalar (so your code will work as expected if it is used multiple times). Then, if l is None, initialize a new class member as []. Otherwise just assign the member variable to l.\n",
"The behavior occurs because all calls to your __init__ method share the same default list.\nTry:\nclass intlist:\n def __init__(self, l):\n self.l = l if (l is not None) else []\n def add(self,a):\n self.l.append(a)\n\nEDIT: Use is not, per SilentGhost\n",
"obj = intlist() calls your __init__() function which uses the same array for every instance of the class.\nobj = intlist(l=[]) creates a new array for every instance.\n",
"For more information I suggest reading this: http://effbot.org/zone/default-values.htm\n",
"Be careful with default parameters of types like lists and dicts. Each instance of intlist gets that same list object from the default parameter.\n"
] |
[
14,
4,
3,
1,
1,
1,
0
] |
[] |
[] |
[
"attributes",
"class",
"instance",
"python"
] |
stackoverflow_0002402887_attributes_class_instance_python.txt
|
Q:
GAE Task Queue oddness
I have been testing the taskqueue with mixed success. Currently I am
using the default queue, in default settings etc etc....
I have a test URL setup which inserts about 8 tasks into the queue.
With short order, all 8 are completed properly. So far so good.
The problem comes up when I re-load that URL twice under say a minute.
Now watching the task queue, all the tasks are added properly, but
only the first batch execute it seems. But the "Run in Last Minute" #
shows the right number of tasks being run....
The request logs tell a different story. They show only the first set
of 8 running, but all task creation URLs working successfully.
The oddness of this is that if I wait say a minute between the task
creation URL requests, it will work fine.
Oddly enough changing the bucket_size or execution speed does not seem
to help. Only the first batch are executed. I have also reduced the
number of requests all the way down to 2, and still found only the
first 2 execute. Any others added display the same issues as above.
Any suggestions?
Thanks
A:
When a task-queue ends in error : I believe it stays in your queue ..
Check that
|
GAE Task Queue oddness
|
I have been testing the taskqueue with mixed success. Currently I am
using the default queue, in default settings etc etc....
I have a test URL setup which inserts about 8 tasks into the queue.
With short order, all 8 are completed properly. So far so good.
The problem comes up when I re-load that URL twice under say a minute.
Now watching the task queue, all the tasks are added properly, but
only the first batch execute it seems. But the "Run in Last Minute" #
shows the right number of tasks being run....
The request logs tell a different story. They show only the first set
of 8 running, but all task creation URLs working successfully.
The oddness of this is that if I wait say a minute between the task
creation URL requests, it will work fine.
Oddly enough changing the bucket_size or execution speed does not seem
to help. Only the first batch are executed. I have also reduced the
number of requests all the way down to 2, and still found only the
first 2 execute. Any others added display the same issues as above.
Any suggestions?
Thanks
|
[
"When a task-queue ends in error : I believe it stays in your queue ..\nCheck that\n"
] |
[
0
] |
[] |
[] |
[
"google_app_engine",
"python",
"task_queue"
] |
stackoverflow_0002308050_google_app_engine_python_task_queue.txt
|
Q:
What would be the most efficient way to do this search (mysql or text)?
Suppose I have 500 rows of data, each with a paragraph of text (like this paragraph). That's it.I want to do a search that matches part of words. (%LIKE%, not FULL_TEXT)
What would be faster?
SELECT * FROM ...WHERE LIKE "%query%"; This would put load on the database server.
Select all. Then, go through each one and do .find >= 0 This would put load on the web server.
This is a website, and people will be searching frequently.
A:
This is very hard for us to determine without knowing:
the amount of text to search
the load and configuration on the database server
the load and configuration on on the webserver
etc etc ...
With that said i would conceptually definitely go for the first scenario. It should be lightening-fast when searching only 500 rows.
A:
You can use a full text search if you use myisam engine. http://dev.mysql.com/doc/refman/5.1/en/fulltext-query-expansion.html
|
What would be the most efficient way to do this search (mysql or text)?
|
Suppose I have 500 rows of data, each with a paragraph of text (like this paragraph). That's it.I want to do a search that matches part of words. (%LIKE%, not FULL_TEXT)
What would be faster?
SELECT * FROM ...WHERE LIKE "%query%"; This would put load on the database server.
Select all. Then, go through each one and do .find >= 0 This would put load on the web server.
This is a website, and people will be searching frequently.
|
[
"This is very hard for us to determine without knowing:\n\nthe amount of text to search\nthe load and configuration on the database server\nthe load and configuration on on the webserver\netc etc ...\n\nWith that said i would conceptually definitely go for the first scenario. It should be lightening-fast when searching only 500 rows.\n",
"You can use a full text search if you use myisam engine. http://dev.mysql.com/doc/refman/5.1/en/fulltext-query-expansion.html\n"
] |
[
1,
0
] |
[] |
[] |
[
"database",
"mysql",
"python",
"regex",
"search"
] |
stackoverflow_0002401508_database_mysql_python_regex_search.txt
|
Q:
Python: Get values (objects) from a dictionary of objects in which one of the object's field matches a value (or condition)
I have a python dictionary whose keys are strings and the values are objects.
For instance, an object with one string and one int
class DictItem:
def __init__(self, field1, field2):
self.field1 = str(field1)
self.field2 = int(field2)
and the dictionary:
myDict = dict()
myDict["sampleKey1"] = DictItem("test1", 1)
myDict["sampleKey2"] = DictItem("test2", 2)
myDict["sampleKey3"] = DictItem("test3", 3)
Which is the best/most efficient way to get the dictionary entries that have the "field2" field >= 2?
The idea is creating a "sub-dictionary" (a list would do too) only with the entries in which field2 >= 2 (in the example would be like):
{
"sampleKey2": {
"field1" : "test2",
"field2": 2
},
"sampleKey3": {
"field1" : "test3",
"field2": 3
}
}
Is there a better way than walking through all the dictionary elements and check for the condition? Maybe using itemgetters, and lambda functions?
Thank you!
P.S.: I am using Python2.4, just in case it's relevant
A:
To make a dict from your dict,
subdict = dict((k, v) for k, v in myDict.iteritems() if v.field2 >= 2)
A:
mySubList = [dict((k,v) for k,v in myDict.iteritems() if v.field2 >= 2)]
Documentation:
list-comprehensions, iteritems()
A:
You should keep your various records - that is "DicItem" instances - inside a list.
An generator/list expression can then filter your desired results with ease.
data = [
DictItem("test1", 1),
DictItem("test2", 2),
DictItem("test3", 3),
DictItem("test4", 4),
]
and then:
results = [item for item in data if item.field2 >= 2]
This, of course, creates a linear filter. If you need more than linear speed for some of your queries, the container object for the registers - in this case a "list" should be a specialized class able to create indexes of the data there in, much like a DBMS does with its table indexes. This can be done easily deriving a class from "list" and overriding the "append", "insert", "__getitem__", "__delitem__" and "pop" methods.
If you need this for a high profile application, I'd suggest you to take a look at some of the Object Oriented DB systems for Python out there, like ZODB and others.
A:
The idea is creating a "sub-dictionary" (a list would do too)
If you want a list you could use filter (or itertools.ifilter):
result_list = filter(lambda x: x.field2 > 2, mydict.values())
A:
'Most efficient' is going to depend on how often the dictionary contents change compared to how often you are doing the lookup.
If the dictionary changes often and you do the lookup less often then the most efficient method will be walking through iteritems and selecting the objects that match the criteria, using the code the Adam Bernier posted.
If the dictionary does not change much and you do lots of lookups then it may be faster to make one or more inverse dictionaries, e.g. one mapping the "field2" values to a list of objects that have that value.
Alternatively if you are going to be doing complex queries you could put all the data into an in-memory sqllite database and let SQL sort it out, perhaps via an ORM such as SqlAlchemy
|
Python: Get values (objects) from a dictionary of objects in which one of the object's field matches a value (or condition)
|
I have a python dictionary whose keys are strings and the values are objects.
For instance, an object with one string and one int
class DictItem:
def __init__(self, field1, field2):
self.field1 = str(field1)
self.field2 = int(field2)
and the dictionary:
myDict = dict()
myDict["sampleKey1"] = DictItem("test1", 1)
myDict["sampleKey2"] = DictItem("test2", 2)
myDict["sampleKey3"] = DictItem("test3", 3)
Which is the best/most efficient way to get the dictionary entries that have the "field2" field >= 2?
The idea is creating a "sub-dictionary" (a list would do too) only with the entries in which field2 >= 2 (in the example would be like):
{
"sampleKey2": {
"field1" : "test2",
"field2": 2
},
"sampleKey3": {
"field1" : "test3",
"field2": 3
}
}
Is there a better way than walking through all the dictionary elements and check for the condition? Maybe using itemgetters, and lambda functions?
Thank you!
P.S.: I am using Python2.4, just in case it's relevant
|
[
"To make a dict from your dict,\nsubdict = dict((k, v) for k, v in myDict.iteritems() if v.field2 >= 2)\n\n",
"mySubList = [dict((k,v) for k,v in myDict.iteritems() if v.field2 >= 2)]\n\nDocumentation:\nlist-comprehensions, iteritems()\n",
"You should keep your various records - that is \"DicItem\" instances - inside a list.\nAn generator/list expression can then filter your desired results with ease.\ndata = [\n DictItem(\"test1\", 1), \n DictItem(\"test2\", 2),\n DictItem(\"test3\", 3),\n DictItem(\"test4\", 4),\n]\n\nand then:\nresults = [item for item in data if item.field2 >= 2]\n\nThis, of course, creates a linear filter. If you need more than linear speed for some of your queries, the container object for the registers - in this case a \"list\" should be a specialized class able to create indexes of the data there in, much like a DBMS does with its table indexes. This can be done easily deriving a class from \"list\" and overriding the \"append\", \"insert\", \"__getitem__\", \"__delitem__\" and \"pop\" methods.\nIf you need this for a high profile application, I'd suggest you to take a look at some of the Object Oriented DB systems for Python out there, like ZODB and others. \n",
"The idea is creating a \"sub-dictionary\" (a list would do too)\nIf you want a list you could use filter (or itertools.ifilter):\nresult_list = filter(lambda x: x.field2 > 2, mydict.values())\n\n",
"'Most efficient' is going to depend on how often the dictionary contents change compared to how often you are doing the lookup.\nIf the dictionary changes often and you do the lookup less often then the most efficient method will be walking through iteritems and selecting the objects that match the criteria, using the code the Adam Bernier posted.\nIf the dictionary does not change much and you do lots of lookups then it may be faster to make one or more inverse dictionaries, e.g. one mapping the \"field2\" values to a list of objects that have that value.\nAlternatively if you are going to be doing complex queries you could put all the data into an in-memory sqllite database and let SQL sort it out, perhaps via an ORM such as SqlAlchemy\n"
] |
[
8,
4,
3,
2,
0
] |
[] |
[] |
[
"dictionary",
"python"
] |
stackoverflow_0002403372_dictionary_python.txt
|
Q:
Best web application language for Delphi Developers
I'm Delphi developer, and I would like to build few web applications, I know about Intraweb, but I think it's not a real tool for web development, maybe for just intranet applications
so I'm considering PHP, Python or ruby, I prefer python because it's better syntax than other( I feel it closer to Delphi), also I want to deploy the application to shared hosting, specially Linux.
so as Delphi developer, what do you choose to develop web application?
A:
Try Morfik http://www.morfik.com/
P.S.
It looked promising a few years ago, but after I digged it deeper I must admit that it's quite limited web development environment for a very basic web development.
A:
Why should an answer be different if the question was asked by a Delphi programmer, than a programmer from any other platform? Any decent language should be fun to learn, regardless of the tool you are using right now.
That said, I myself walked a way from Borland Pascal and Delphi (quite some time ago), over PHP and ASP.NET (using C#). Right now I am working almost exclusively on Ruby (and occasionally Rails) and I am perfectly happy with it. But, then again, it's matter of personal preference: I really enjoy Ruby's pure object-orientation and functional capabilities, as well as dynamical nature of a scripting language. So, it's all up to you and your personal preferences.
Although, one thing I can surely recommend is to stick with one of the major web-players, for pragmatic reasons: PHP, Python, Ruby, ASP.NET or possibly Java. I'm sorry to say that, but I don't think Pascaloid languages have any future anymore.
A:
If you feel like stretching your muscles, you could try out Seaside.
Seaside's a Smalltalk framework (so working with it will feel pretty much like working with Ruby) that lets you write your website just like you'd build a desktop application. You can split your code up into components that you can assemble much like you'd work with TComponents (programmatically, at least).
A:
I agree about Intraweb, but Delphi itself is still a good language to build websites with. You could start a CGI application or an ISAPI-extesion. You could also check out http://xxm.sf.net , it's an open-source project I started that offers a few extra's:
You can mix HTML and Delphi code into the same files (much like PHP)
These files get auto-compiled to a Delphi project so you can see the results by refreshing the web-browser (much like PHP)
You can load the library with a number of 'handlers':
there's a IInternetProtocol implementation to use with InternetExplorer directly (really handy for development
there's an ISAPI extension that loads the library (and auto-updates is, really handy for updates on live-environments)
there's a stand-alone HTTP executable or NT-Service
there's even a FireFox plugin and Apache module in the making.
A:
PHP is the best to start, but as experienced programmer you may want to look at Python, because PHP is a C style language. Python would be easier after Pascal, I think.
Take a look at examples:
On PHP: http://en.wikipedia.org/wiki/Php#Syntax
On Python: http://en.wikipedia.org/wiki/Python_(programming_language)#Syntax_and_semantics
Note, that Ruby and Python are rarely used by them selves in web-development. Usually Django and Ruby on railes frameworks are used. In PHP there are several variants. You can code from the scratch, or also use some framework.
I used to code on PHP for about five years and now started to learn Django (python based framework) and I think it's the best thing there is. Take a look: http://djangoproject.com/
A:
Only good answer - C# ;) Seriously ;)
Why? Anders Hejlsberg. He made it. It is the direct continuation of his work that started with Turbo Pascal and went over to Delphi... then Microsoft hired him and he moved from Pascal to C (core langauge) and made C#.
Read it up on http://en.wikipedia.org/wiki/Anders_Hejlsberg
If you come from Delphi, you will love it ;)
A:
PHP is a pretty simple answer.
One reason is there is both Delphi4PHP (the rather cryptic IDE licensed by Embarcadero which in my estimation is really only for Web Apps (not for doing whole site)s) and PHP4Delphi (the pretty awesome Delphi Component that lets you compile your Delphi code to PHP Extensions).
A:
I'm a long-time Delphi developer myself and had to do some web work recently, I decided to use ASP.Net with Delphi Prism and found myself right at home since I didn't have to learn a new language, just a new framework.
A:
Actually, the answer probably is ASP.NET using C#. You'll see (ex-)Borland engineering syntax that looks quite familiar coming from Delphi. To deploy on Linux have a look at the Mono project.
A:
I have done a fairly large (4-5 FTE) project based on webhub (www.href.com). I can certainly advise this if it is a webapp for internal use.
|
Best web application language for Delphi Developers
|
I'm Delphi developer, and I would like to build few web applications, I know about Intraweb, but I think it's not a real tool for web development, maybe for just intranet applications
so I'm considering PHP, Python or ruby, I prefer python because it's better syntax than other( I feel it closer to Delphi), also I want to deploy the application to shared hosting, specially Linux.
so as Delphi developer, what do you choose to develop web application?
|
[
"Try Morfik http://www.morfik.com/\nP.S.\nIt looked promising a few years ago, but after I digged it deeper I must admit that it's quite limited web development environment for a very basic web development.\n",
"Why should an answer be different if the question was asked by a Delphi programmer, than a programmer from any other platform? Any decent language should be fun to learn, regardless of the tool you are using right now.\nThat said, I myself walked a way from Borland Pascal and Delphi (quite some time ago), over PHP and ASP.NET (using C#). Right now I am working almost exclusively on Ruby (and occasionally Rails) and I am perfectly happy with it. But, then again, it's matter of personal preference: I really enjoy Ruby's pure object-orientation and functional capabilities, as well as dynamical nature of a scripting language. So, it's all up to you and your personal preferences.\nAlthough, one thing I can surely recommend is to stick with one of the major web-players, for pragmatic reasons: PHP, Python, Ruby, ASP.NET or possibly Java. I'm sorry to say that, but I don't think Pascaloid languages have any future anymore.\n",
"If you feel like stretching your muscles, you could try out Seaside.\nSeaside's a Smalltalk framework (so working with it will feel pretty much like working with Ruby) that lets you write your website just like you'd build a desktop application. You can split your code up into components that you can assemble much like you'd work with TComponents (programmatically, at least).\n",
"I agree about Intraweb, but Delphi itself is still a good language to build websites with. You could start a CGI application or an ISAPI-extesion. You could also check out http://xxm.sf.net , it's an open-source project I started that offers a few extra's:\n\nYou can mix HTML and Delphi code into the same files (much like PHP)\nThese files get auto-compiled to a Delphi project so you can see the results by refreshing the web-browser (much like PHP)\nYou can load the library with a number of 'handlers':\n\n\nthere's a IInternetProtocol implementation to use with InternetExplorer directly (really handy for development\nthere's an ISAPI extension that loads the library (and auto-updates is, really handy for updates on live-environments)\nthere's a stand-alone HTTP executable or NT-Service\nthere's even a FireFox plugin and Apache module in the making.\n\n\n",
"PHP is the best to start, but as experienced programmer you may want to look at Python, because PHP is a C style language. Python would be easier after Pascal, I think.\nTake a look at examples:\nOn PHP: http://en.wikipedia.org/wiki/Php#Syntax\nOn Python: http://en.wikipedia.org/wiki/Python_(programming_language)#Syntax_and_semantics\nNote, that Ruby and Python are rarely used by them selves in web-development. Usually Django and Ruby on railes frameworks are used. In PHP there are several variants. You can code from the scratch, or also use some framework.\nI used to code on PHP for about five years and now started to learn Django (python based framework) and I think it's the best thing there is. Take a look: http://djangoproject.com/\n",
"Only good answer - C# ;) Seriously ;)\nWhy? Anders Hejlsberg. He made it. It is the direct continuation of his work that started with Turbo Pascal and went over to Delphi... then Microsoft hired him and he moved from Pascal to C (core langauge) and made C#.\nRead it up on http://en.wikipedia.org/wiki/Anders_Hejlsberg\nIf you come from Delphi, you will love it ;)\n",
"PHP is a pretty simple answer. \nOne reason is there is both Delphi4PHP (the rather cryptic IDE licensed by Embarcadero which in my estimation is really only for Web Apps (not for doing whole site)s) and PHP4Delphi (the pretty awesome Delphi Component that lets you compile your Delphi code to PHP Extensions). \n",
"I'm a long-time Delphi developer myself and had to do some web work recently, I decided to use ASP.Net with Delphi Prism and found myself right at home since I didn't have to learn a new language, just a new framework.\n",
"Actually, the answer probably is ASP.NET using C#. You'll see (ex-)Borland engineering syntax that looks quite familiar coming from Delphi. To deploy on Linux have a look at the Mono project.\n",
"I have done a fairly large (4-5 FTE) project based on webhub (www.href.com). I can certainly advise this if it is a webapp for internal use.\n"
] |
[
7,
6,
4,
4,
2,
2,
1,
1,
0,
0
] |
[] |
[] |
[
"delphi",
"php",
"python",
"ruby"
] |
stackoverflow_0002400605_delphi_php_python_ruby.txt
|
Q:
How do I create a set of image files from a PowerPoint file file?
I'm creating a "slideshow room" web page. The user will upload a PowerPoint file that my server will use to generate a set of .jpg image files representing the slides to present in a custom "gallery viewer".
I'm an experienced Python developer but I cannot find anything useful.
How can I do that?
A:
Off the top of my head, the way I'd do it:
Use OpenOffice.org to convert the .ppt file into a PDF. (OO.o has a very rich Java API. Rich and bloody difficult to use, mind, but once you figure out how to get it to do the task you need, you're all set. Dunno if you can do anything useful with it via Python; not my language.)
Use ImageMagick to convert the PDF into .jpg files. (Though I've been told converting the PDF into a PS file before turning it into images gives better results.) (IM's command line interface is damn near a language unto itself -- though again, once you figure out how to get it to do what you want, you're all set.)
Dunno if that's the most efficient/reliable way to do it. But fundamentally, I'd be on Google trolling for open-source third party tools that do all the dirty work for me.
A:
Are you doing this on Windows? If so win32 com:
import win32com.client
Application = win32com.client.Dispatch("PowerPoint.Application")
Application.Visible = True
Presentation = Application.Presentations.Open(pathToPPT)
Presentation.Slides[1].Export("C:/path/to/jpg.jpg", "JPG", 800, 600);
etc...
A:
Apache POI and Jython. POI, even has an ImageExtractor class, but having just glanced at the Javadocs, I suspect it is incomplete.
|
How do I create a set of image files from a PowerPoint file file?
|
I'm creating a "slideshow room" web page. The user will upload a PowerPoint file that my server will use to generate a set of .jpg image files representing the slides to present in a custom "gallery viewer".
I'm an experienced Python developer but I cannot find anything useful.
How can I do that?
|
[
"Off the top of my head, the way I'd do it:\n\nUse OpenOffice.org to convert the .ppt file into a PDF. (OO.o has a very rich Java API. Rich and bloody difficult to use, mind, but once you figure out how to get it to do the task you need, you're all set. Dunno if you can do anything useful with it via Python; not my language.)\n\nUse ImageMagick to convert the PDF into .jpg files. (Though I've been told converting the PDF into a PS file before turning it into images gives better results.) (IM's command line interface is damn near a language unto itself -- though again, once you figure out how to get it to do what you want, you're all set.)\n\nDunno if that's the most efficient/reliable way to do it. But fundamentally, I'd be on Google trolling for open-source third party tools that do all the dirty work for me.\n",
"Are you doing this on Windows? If so win32 com:\nimport win32com.client\nApplication = win32com.client.Dispatch(\"PowerPoint.Application\")\nApplication.Visible = True\nPresentation = Application.Presentations.Open(pathToPPT)\nPresentation.Slides[1].Export(\"C:/path/to/jpg.jpg\", \"JPG\", 800, 600);\netc...\n\n",
"Apache POI and Jython. POI, even has an ImageExtractor class, but having just glanced at the Javadocs, I suspect it is incomplete.\n"
] |
[
4,
0,
0
] |
[] |
[] |
[
"jpeg",
"powerpoint",
"python"
] |
stackoverflow_0002403041_jpeg_powerpoint_python.txt
|
Q:
Google App Engine UI Widgets
Are there any UI widgets available to the python side of Google App Engine? I'd like something like the collapsed/expanded views of Google Groups threads. Are these type things limited to the GWT side?
A:
Why not simply use jQueryUI? It's a tested and very solid library, and will be easier to pick up than anything else at the current stage.
Cheers
A:
ToscaWidgets, in the version 2 that's currently in alpha test, is said to support App Engine (at least for the tw2.core part). I've also seen posts showing ways (a bit complicated ones, it seemed to me) to use the current ToscaWidgets on App Engine.
App Engine itself definitely does not include any such "widgets" package -- it has WSGI (a much lower-level service, which allows plugging in most Python web app frameworks at your choice), an extremely simple request/response/router "webapp" for trivially simple apps, and django (in several versions -- only 0.96 is part of the SDK download, but up to 1.1 for the actual service I believe) which uses templating, not widgets.
But the point of the GAE arrangement is that if you don't like django (which according to one estimate is used for > 80% Python web apps on the open web) you're welcome to plug in your own favorite framework, as long as it respects GAE's constraints (Python 2.5, no native code, no relational DB available, &c). For example, I like the werkzeug "non-framework" which works at the WSGI level (if I need UI I do tend to do it in Javascript, too, though usually with dojo/dijit or Google Closure rather than with jquery/jqueryUI -- App Engine could care less either way of course;-).
Despite django's near-dominance in mindshare (comparable to that of Rails in the Ruby world, I guess), Python is still fairly known as the language with more web frameworks than keywords. When Python 3 was brewing I suggested to Guido the obvious solution to that issue -- add many, many more keywords... but he didn't seem to take this suggestion all that seriously!-)
A:
There is no difference in the amount of built in widgets available to the python and java sides of app engine. Neither side has any! App Engine is primarily a back end technology. It allows you to use pretty much whatever web framework you want for your presentation layer, subject to constraints that Alex mentions.
GWT is completely unrelated to App Engine, besides being developed by Google. It is a client side toolkit, and can be used just fine with any web app as a backend, whether created in java, python or [your favorite language]. (Admittedly, you get a few bonus features if your backend is in java.)
|
Google App Engine UI Widgets
|
Are there any UI widgets available to the python side of Google App Engine? I'd like something like the collapsed/expanded views of Google Groups threads. Are these type things limited to the GWT side?
|
[
"Why not simply use jQueryUI? It's a tested and very solid library, and will be easier to pick up than anything else at the current stage.\nCheers\n",
"ToscaWidgets, in the version 2 that's currently in alpha test, is said to support App Engine (at least for the tw2.core part). I've also seen posts showing ways (a bit complicated ones, it seemed to me) to use the current ToscaWidgets on App Engine.\nApp Engine itself definitely does not include any such \"widgets\" package -- it has WSGI (a much lower-level service, which allows plugging in most Python web app frameworks at your choice), an extremely simple request/response/router \"webapp\" for trivially simple apps, and django (in several versions -- only 0.96 is part of the SDK download, but up to 1.1 for the actual service I believe) which uses templating, not widgets.\nBut the point of the GAE arrangement is that if you don't like django (which according to one estimate is used for > 80% Python web apps on the open web) you're welcome to plug in your own favorite framework, as long as it respects GAE's constraints (Python 2.5, no native code, no relational DB available, &c). For example, I like the werkzeug \"non-framework\" which works at the WSGI level (if I need UI I do tend to do it in Javascript, too, though usually with dojo/dijit or Google Closure rather than with jquery/jqueryUI -- App Engine could care less either way of course;-).\nDespite django's near-dominance in mindshare (comparable to that of Rails in the Ruby world, I guess), Python is still fairly known as the language with more web frameworks than keywords. When Python 3 was brewing I suggested to Guido the obvious solution to that issue -- add many, many more keywords... but he didn't seem to take this suggestion all that seriously!-)\n",
"There is no difference in the amount of built in widgets available to the python and java sides of app engine. Neither side has any! App Engine is primarily a back end technology. It allows you to use pretty much whatever web framework you want for your presentation layer, subject to constraints that Alex mentions.\nGWT is completely unrelated to App Engine, besides being developed by Google. It is a client side toolkit, and can be used just fine with any web app as a backend, whether created in java, python or [your favorite language]. (Admittedly, you get a few bonus features if your backend is in java.)\n"
] |
[
9,
5,
3
] |
[] |
[] |
[
"google_app_engine",
"python",
"user_interface"
] |
stackoverflow_0002402128_google_app_engine_python_user_interface.txt
|
Q:
python: Writing Application- Different modules/Licenses and impact on Proprietary application
I've written an application using wxPython and various other small modules (xlrd, xlwrt, pyserial, etc.) xlrd/xlwt i believe use a BSD license, and wxPython..
""Being a wrapper, wxPython uses the same free software licence
used by wxWidgets (wxWindows License)—which is approved by Free
Software Foundation and Open Source /n Initiative"" -wikipedia entry on wxPython
Just wondering about the implications of selling an application like this. I'm new to all this and am wondering what it means to use GPL-compatible modules, what the "free software foundation" is about, etc.
I.e., is the purpose of the free software foundation to restrict the use of 'open source', 'free-ware' code/modules from being bundled into commerical applications? Thanks.
A:
"GPL-compatible" only matters if you're writing GPLed or LGPLed code. When writing a proprietary application the biggest concern is "closed-source-incompatible", although a proprietary app does not necessarily need to be closed-source. BSD and LGPL (among others) are closed-source-compatible; GPL is not.
|
python: Writing Application- Different modules/Licenses and impact on Proprietary application
|
I've written an application using wxPython and various other small modules (xlrd, xlwrt, pyserial, etc.) xlrd/xlwt i believe use a BSD license, and wxPython..
""Being a wrapper, wxPython uses the same free software licence
used by wxWidgets (wxWindows License)—which is approved by Free
Software Foundation and Open Source /n Initiative"" -wikipedia entry on wxPython
Just wondering about the implications of selling an application like this. I'm new to all this and am wondering what it means to use GPL-compatible modules, what the "free software foundation" is about, etc.
I.e., is the purpose of the free software foundation to restrict the use of 'open source', 'free-ware' code/modules from being bundled into commerical applications? Thanks.
|
[
"\"GPL-compatible\" only matters if you're writing GPLed or LGPLed code. When writing a proprietary application the biggest concern is \"closed-source-incompatible\", although a proprietary app does not necessarily need to be closed-source. BSD and LGPL (among others) are closed-source-compatible; GPL is not.\n"
] |
[
0
] |
[] |
[] |
[
"commercial_application",
"licensing",
"python"
] |
stackoverflow_0002404637_commercial_application_licensing_python.txt
|
Q:
Does filehandle get closed automatically in Python after it goes out of scope?
If I do the following, does filehandle get closed automatically as it goes out of scope in Python:
def read_contents(file_path):
return file(file_path).read()
If it doesn't, how can I write this function to close the scope automatically?
A:
To expand on FogleBird's answer, if you do not explicitly close it then the file will be closed automatically when the file object is destroyed. In CPython this will happen as soon as there are no more references to it, e.g. if it is a local variable in a function and the function ends. However if an exception is thrown in the function and file is not explicitly closed using a with statement or a try:...finally: then a reference to the file will be kept as part of the stack trace in the traceback object and the file will not be closed, at least until the next exception is thrown.
Also IronPython and Jython use the garbage collection facilities of the .Net CLR and Java JVM respectively. These are not reference counted, so the file will remain open indefinitely until the garbage collector decides to reclaim the object's memory or the program terminates.
So in general it is important to explicitly close the file using either with: or try:...finally:.
Of course all this is holds true for any other type of object that requires explicit cleanup.
A:
It should close the file handle in the file's __del__ statement, but a better approach would be to use a with block:
def read_contents(file_path):
with open(file_path, 'r') as f:
return f.read()
See http://docs.python.org/library/stdtypes.html#file.close for more information.
|
Does filehandle get closed automatically in Python after it goes out of scope?
|
If I do the following, does filehandle get closed automatically as it goes out of scope in Python:
def read_contents(file_path):
return file(file_path).read()
If it doesn't, how can I write this function to close the scope automatically?
|
[
"To expand on FogleBird's answer, if you do not explicitly close it then the file will be closed automatically when the file object is destroyed. In CPython this will happen as soon as there are no more references to it, e.g. if it is a local variable in a function and the function ends. However if an exception is thrown in the function and file is not explicitly closed using a with statement or a try:...finally: then a reference to the file will be kept as part of the stack trace in the traceback object and the file will not be closed, at least until the next exception is thrown.\nAlso IronPython and Jython use the garbage collection facilities of the .Net CLR and Java JVM respectively. These are not reference counted, so the file will remain open indefinitely until the garbage collector decides to reclaim the object's memory or the program terminates.\nSo in general it is important to explicitly close the file using either with: or try:...finally:.\nOf course all this is holds true for any other type of object that requires explicit cleanup.\n",
"It should close the file handle in the file's __del__ statement, but a better approach would be to use a with block:\ndef read_contents(file_path):\n with open(file_path, 'r') as f:\n return f.read()\n\nSee http://docs.python.org/library/stdtypes.html#file.close for more information.\n"
] |
[
41,
21
] |
[] |
[] |
[
"file",
"python",
"scope"
] |
stackoverflow_0002404430_file_python_scope.txt
|
Q:
wanting to move up from ms access, thinking .net? visual studio?
So I wrote a project-management program for a small business using Microsoft Access 2007.
Now they've requested lots of additional features (timekeeping, privileged data tiers ...)
I personally use Linux, but the whole office uses Windows.
I'm relatively new to programming but like to teach myself using projects like this.
I'm right on the edge on this -- I can't really tell what the path of least resistance here is: do I stay in access + VBA and teach myself a dying, annoying language -- while struggling against all the limitations of Access? Or do I move to something else?
Python seems simple enough ... Whatever I use, i need to be able to offer a GUI.
screenshot so you can get the jist:
http://img707.imageshack.us/img707/9360/screenshot1fi.jpg
http://img707.imageshack.us/img707/7338/screenshotmh.jpg
--
notes:
current access project uses seperate frontend-backend for multiuser sharing over a LAN
cross compatibility with linux is not that important to me, i've been using virtualbox for a while now.
--UPDATE--
my wanderings have convinced me that i should proceed in IronPython -- however -- as I try to install the suite in both XP and 7, and fail ... I wonder if this also is something outdated ... most importantly, iv'e been reading up on it and I LOVE PYTHON 3 -- but i need to offer a GUI for Windows not sure where to start with that (including which IDE to use, etc)
A:
In an environment like that, you can't go wrong with VB/C#. Try the various VS Express editions.
If you want something that will translate to Linux a little more, Python and just about any cross-platform GUI framework(QT, or wxpython) would work.
EDIT:
Then there's the database. I would probably suggest sqlite if you want to learn something cross platform. Sticking in the Microsoft world, there's SQL server compact.
In a business environment like that, a .NET app is probably more maintainable(after you're gone, etc) then anything that's not completely Microsoft.
A:
MS Access is a desktop database application. One step up is most likely SQL Server Compact Edition (SQLCE), which operates as part of your application (as opposed to SQL Server Express or higher, which run as system services). I've used SQLCE with a great deal of success in a few applications, and Microsoft is using it in Visual Studio 2010 for the new Visual C++ IntelliSense cache because it's lightweight and performs great.
Despite what I've read on some sources, SQLCE doesn't cooperate well with the Entity Framework. It does however work great with LINQ-to-SQL and the corresponding designer. That said, my personal recommendation is you consider combining the following as your replacement:
Data: SQL Server Compact Edition
Data/Code: LINQ-to-SQL
Programming language: C#
Application framework: WPF
Personal note: WPF does have a learning curve, but it's primarily difficult for people who've worked with other frameworks (MFC, WinForms, etc.) for a long time. Pick up a good reference and you'll be productive in no time, plus you'll be skilled in a technology that people are moving towards instead of away.
A:
I would say web app (C#) with SQL Express on the back end - but this is just me
A:
WPF has a pretty steep learning curve, especially coming from Access. WinForms would be a simpler path, but it's still a leap from Access. However, both WPF and WinForms have drag-and-drop form construction, and assuming you learn enough VB.NET to convert the VBA business logic, you're more than halfway there. :)
If you implement your project in WPF, you can make it Silverlight-enabled, but that's a whole 'nother can of worms.
A:
VB and C# are certainly similar to Access, and would be good if you are looking to not move too far away.
Python is brilliant but nothing like Access. It is simply a programming language that happens to have good db libraries. The GUI libraries look pretty good as well though I have never used them. GUI design will be harder in python than C#/VB. Python is free and may be worth just experimenting with ie. build a GUI,connect to an SQLite database. You would probably get a good indication of the feasibility of using python for your purposes.
Dont stay exclusively with Access. Access is pretty good for small applications and you can do some stuff really quickly. On the other hand VBA is brutal and is severely limiting. Try both C# and python if you can.
A:
I said this in a comment, but I'll repeat it as an answer:
If you look at the future of Access, it's bright. MS is investing a lot in it. Access 2010 in conjunction with Sharepoint 2010 offers some pretty amazing benefits, and you do it all without any VBA (instead you use the new, powerful macros, which have variables, branching and error trapping). You can do this with client Access and no Sharepoint, or you can publish it to Sharepoint and the app runs in the web browser.
My surmise is that one of two things are going to happen in regard to the programming language in Access in the timeframe of the 2-3 Access versions after 2010:
VBA remains supported and all the work goes into macros. Eventually, macros become the preferred method for all programming in Access, with VBA eventually deprecated and finally eliminated. Because by that point macros are so versatile and robust, not programming language will replace VBA.
the same scenario, except that .NET is phased in as a replacement for VBA.
I would hope for #2, but it depends entirely on Microsoft's view of what Access is, i.e., primarily and end-user tool with upward extensibility (#1) or both an end-user tool and a versatile development tool with unlimited extensibility (#2).
My point is that you can stay with Access, avoid VBA for now (if you really hate it), and probably end up with a workable, stable app.
However, my reservations about macros are very strong, in that I find them very difficult to maintain because of their standalone nature. VBA code is pretty easy to navigate and understand, because it's compiled and because there's a full-featured IDE. Macros are much more compartmentalized and difficult to trace interrelationships between them and the objects they are used in. Add in the embedded macros added in A2007 and it gets even more complicated. I don't know if the Access team is addressing this or not, but for me it's a real step backward in terms of manageability, particularly if the beefing up of macros ends up causing VBA to be deprecated and then not replaced with a correspondingly powerful programming language with a good IDE.
Last of all, I've said nothing about the database engine, since Access is completely agnostic on this regard, able to use Jet/ACE to start with and then to upsize to the engine of your choice. It's a non-issue, seems to me, since your options are wide open when using Access as your front end.
A:
Based on your criteria, I would use PyGtk and Glade. Gtk is well supported on Windows and Linux, and I've gotten more done in less time with Python and GTK, than with any other language/toolkit combination.
If you are willing to rethink doing it on the web, have a look at ExtJS, which provides a lot of desktop like web controls, and they have a GUI builder.
For the database I would go with Postgresql, or SQLite. Be aware that SQLite has some severe limitations when it comes to concurrency, which might be a problem depending on your application design, and the number of users.
A:
As long as the clients don't share a database, a .NET WPF/WinForms app w/ an embedded DB sounds like it would work just fine.
You could probably even develop something that works on both Windows PCs and your Linux machine using Mono (you'd be stuck with a subset of WinForms...but for a simple business app, there's really nothing wrong with that).
A:
Have you thought about Appcelerator Titanium or something similar? You create a rich GUI using web techniques (HTML, CSS, javascript and or python) and compile that to a desktop application.
The advantage would be that you can develop on Linux, and only do the final testing & deployment on Windows.
That said, writing production software as a beginner is not easy. Especially handling errors can be difficult. Be smart and think about "What can go wrong when the user does this" all the way, and validate input.
A:
If it's only smallish, internal apps you're working on, take a look at Visual WebGUI - you get a very VB6-like development environment for web apps. I would not recommend it for large and/or public apps though.
|
wanting to move up from ms access, thinking .net? visual studio?
|
So I wrote a project-management program for a small business using Microsoft Access 2007.
Now they've requested lots of additional features (timekeeping, privileged data tiers ...)
I personally use Linux, but the whole office uses Windows.
I'm relatively new to programming but like to teach myself using projects like this.
I'm right on the edge on this -- I can't really tell what the path of least resistance here is: do I stay in access + VBA and teach myself a dying, annoying language -- while struggling against all the limitations of Access? Or do I move to something else?
Python seems simple enough ... Whatever I use, i need to be able to offer a GUI.
screenshot so you can get the jist:
http://img707.imageshack.us/img707/9360/screenshot1fi.jpg
http://img707.imageshack.us/img707/7338/screenshotmh.jpg
--
notes:
current access project uses seperate frontend-backend for multiuser sharing over a LAN
cross compatibility with linux is not that important to me, i've been using virtualbox for a while now.
--UPDATE--
my wanderings have convinced me that i should proceed in IronPython -- however -- as I try to install the suite in both XP and 7, and fail ... I wonder if this also is something outdated ... most importantly, iv'e been reading up on it and I LOVE PYTHON 3 -- but i need to offer a GUI for Windows not sure where to start with that (including which IDE to use, etc)
|
[
"In an environment like that, you can't go wrong with VB/C#. Try the various VS Express editions.\nIf you want something that will translate to Linux a little more, Python and just about any cross-platform GUI framework(QT, or wxpython) would work.\nEDIT:\nThen there's the database. I would probably suggest sqlite if you want to learn something cross platform. Sticking in the Microsoft world, there's SQL server compact. \nIn a business environment like that, a .NET app is probably more maintainable(after you're gone, etc) then anything that's not completely Microsoft.\n",
"MS Access is a desktop database application. One step up is most likely SQL Server Compact Edition (SQLCE), which operates as part of your application (as opposed to SQL Server Express or higher, which run as system services). I've used SQLCE with a great deal of success in a few applications, and Microsoft is using it in Visual Studio 2010 for the new Visual C++ IntelliSense cache because it's lightweight and performs great.\nDespite what I've read on some sources, SQLCE doesn't cooperate well with the Entity Framework. It does however work great with LINQ-to-SQL and the corresponding designer. That said, my personal recommendation is you consider combining the following as your replacement:\n\nData: SQL Server Compact Edition\nData/Code: LINQ-to-SQL\nProgramming language: C#\nApplication framework: WPF\n\n\nPersonal note: WPF does have a learning curve, but it's primarily difficult for people who've worked with other frameworks (MFC, WinForms, etc.) for a long time. Pick up a good reference and you'll be productive in no time, plus you'll be skilled in a technology that people are moving towards instead of away.\n\n\n",
"I would say web app (C#) with SQL Express on the back end - but this is just me\n",
"WPF has a pretty steep learning curve, especially coming from Access. WinForms would be a simpler path, but it's still a leap from Access. However, both WPF and WinForms have drag-and-drop form construction, and assuming you learn enough VB.NET to convert the VBA business logic, you're more than halfway there. :)\nIf you implement your project in WPF, you can make it Silverlight-enabled, but that's a whole 'nother can of worms.\n",
"VB and C# are certainly similar to Access, and would be good if you are looking to not move too far away. \nPython is brilliant but nothing like Access. It is simply a programming language that happens to have good db libraries. The GUI libraries look pretty good as well though I have never used them. GUI design will be harder in python than C#/VB. Python is free and may be worth just experimenting with ie. build a GUI,connect to an SQLite database. You would probably get a good indication of the feasibility of using python for your purposes.\nDont stay exclusively with Access. Access is pretty good for small applications and you can do some stuff really quickly. On the other hand VBA is brutal and is severely limiting. Try both C# and python if you can. \n",
"I said this in a comment, but I'll repeat it as an answer:\nIf you look at the future of Access, it's bright. MS is investing a lot in it. Access 2010 in conjunction with Sharepoint 2010 offers some pretty amazing benefits, and you do it all without any VBA (instead you use the new, powerful macros, which have variables, branching and error trapping). You can do this with client Access and no Sharepoint, or you can publish it to Sharepoint and the app runs in the web browser.\nMy surmise is that one of two things are going to happen in regard to the programming language in Access in the timeframe of the 2-3 Access versions after 2010:\n\nVBA remains supported and all the work goes into macros. Eventually, macros become the preferred method for all programming in Access, with VBA eventually deprecated and finally eliminated. Because by that point macros are so versatile and robust, not programming language will replace VBA. \nthe same scenario, except that .NET is phased in as a replacement for VBA.\n\nI would hope for #2, but it depends entirely on Microsoft's view of what Access is, i.e., primarily and end-user tool with upward extensibility (#1) or both an end-user tool and a versatile development tool with unlimited extensibility (#2).\nMy point is that you can stay with Access, avoid VBA for now (if you really hate it), and probably end up with a workable, stable app.\nHowever, my reservations about macros are very strong, in that I find them very difficult to maintain because of their standalone nature. VBA code is pretty easy to navigate and understand, because it's compiled and because there's a full-featured IDE. Macros are much more compartmentalized and difficult to trace interrelationships between them and the objects they are used in. Add in the embedded macros added in A2007 and it gets even more complicated. I don't know if the Access team is addressing this or not, but for me it's a real step backward in terms of manageability, particularly if the beefing up of macros ends up causing VBA to be deprecated and then not replaced with a correspondingly powerful programming language with a good IDE.\nLast of all, I've said nothing about the database engine, since Access is completely agnostic on this regard, able to use Jet/ACE to start with and then to upsize to the engine of your choice. It's a non-issue, seems to me, since your options are wide open when using Access as your front end.\n",
"Based on your criteria, I would use PyGtk and Glade. Gtk is well supported on Windows and Linux, and I've gotten more done in less time with Python and GTK, than with any other language/toolkit combination.\nIf you are willing to rethink doing it on the web, have a look at ExtJS, which provides a lot of desktop like web controls, and they have a GUI builder.\nFor the database I would go with Postgresql, or SQLite. Be aware that SQLite has some severe limitations when it comes to concurrency, which might be a problem depending on your application design, and the number of users.\n",
"As long as the clients don't share a database, a .NET WPF/WinForms app w/ an embedded DB sounds like it would work just fine.\nYou could probably even develop something that works on both Windows PCs and your Linux machine using Mono (you'd be stuck with a subset of WinForms...but for a simple business app, there's really nothing wrong with that).\n",
"Have you thought about Appcelerator Titanium or something similar? You create a rich GUI using web techniques (HTML, CSS, javascript and or python) and compile that to a desktop application.\nThe advantage would be that you can develop on Linux, and only do the final testing & deployment on Windows. \nThat said, writing production software as a beginner is not easy. Especially handling errors can be difficult. Be smart and think about \"What can go wrong when the user does this\" all the way, and validate input.\n",
"If it's only smallish, internal apps you're working on, take a look at Visual WebGUI - you get a very VB6-like development environment for web apps. I would not recommend it for large and/or public apps though.\n"
] |
[
5,
3,
2,
1,
1,
1,
1,
0,
0,
0
] |
[] |
[] |
[
".net",
"database",
"ms_access",
"python"
] |
stackoverflow_0002402814_.net_database_ms_access_python.txt
|
Q:
How do I watch a folder for changes and when changes are done using Python?
i need to watch a folder for incoming files. i did that with the following help:
How do I watch a file for changes?
the problem is that the files that are being moved are pretty big (10gb)
and i want to be notified when all files are done moving.
i tried comparing the size of the folder every 20 seconds but the file shows its correct size even tough windows shows that it is still moving.
i am using windows with python
i found a solution using open and waiting for an io exception.
if the file is still being moved i get errno 13.
A:
You should take a look at this link:
http://timgolden.me.uk/python/win32_how_do_i/watch_directory_for_changes.html
There you can see the comparison of the method you are speaking about (simple polling) with two other windows-specific techniques which, in my opinion, offers a really better solution to your problem!
Otherwise, if you are using linux, there's iNotify and the relative Python wrapper:
Pyinotify is a pure Python module used
for monitoring filesystems events on
Linux platforms through inotify
Here: http://trac.dbzteam.org/pyinotify
A:
If you have control over the process of importing the files, I would put a lock file when starting to copy files in, and remove it when you are done. by lock file I mean a tmp empty file, which is just there to indicate that you are coping a file. then your py script can check for the existence of the lock files.
A:
You may be able to use os.stat() to monitor the mtime of the file. However be aware that under various network conditions, the copy may stall momentarily and so the mtime is not updated for a few seconds, so you need to make allowance for this.
Another option is to try opening the file with exclusive read/write which should fail under windows if the file is still opened by the other process
A:
The most reliable method would be to write your own program to move the files.
A:
try checking for the last-modified time change instead of the filesize during your poll.
|
How do I watch a folder for changes and when changes are done using Python?
|
i need to watch a folder for incoming files. i did that with the following help:
How do I watch a file for changes?
the problem is that the files that are being moved are pretty big (10gb)
and i want to be notified when all files are done moving.
i tried comparing the size of the folder every 20 seconds but the file shows its correct size even tough windows shows that it is still moving.
i am using windows with python
i found a solution using open and waiting for an io exception.
if the file is still being moved i get errno 13.
|
[
"You should take a look at this link:\nhttp://timgolden.me.uk/python/win32_how_do_i/watch_directory_for_changes.html\nThere you can see the comparison of the method you are speaking about (simple polling) with two other windows-specific techniques which, in my opinion, offers a really better solution to your problem!\nOtherwise, if you are using linux, there's iNotify and the relative Python wrapper:\n\nPyinotify is a pure Python module used\n for monitoring filesystems events on\n Linux platforms through inotify\nHere: http://trac.dbzteam.org/pyinotify\n\n",
"If you have control over the process of importing the files, I would put a lock file when starting to copy files in, and remove it when you are done. by lock file I mean a tmp empty file, which is just there to indicate that you are coping a file. then your py script can check for the existence of the lock files.\n",
"You may be able to use os.stat() to monitor the mtime of the file. However be aware that under various network conditions, the copy may stall momentarily and so the mtime is not updated for a few seconds, so you need to make allowance for this.\nAnother option is to try opening the file with exclusive read/write which should fail under windows if the file is still opened by the other process\n",
"The most reliable method would be to write your own program to move the files.\n",
"try checking for the last-modified time change instead of the filesize during your poll.\n"
] |
[
2,
0,
0,
0,
0
] |
[] |
[] |
[
"monitoring",
"python",
"pywin32",
"watch"
] |
stackoverflow_0002404087_monitoring_python_pywin32_watch.txt
|
Q:
Vectorization of index operation for a scipy.sparse matrix
The following code runs too slowly even though everything seems to be vectorized.
from numpy import *
from scipy.sparse import *
n = 100000;
i = xrange(n); j = xrange(n);
data = ones(n);
A=csr_matrix((data,(i,j)));
x = A[i,j]
The problem seems to be that the indexing operation is implemented as a python function, and invoking A[i,j] results in the following profiling output
500033 function calls in 8.718 CPU seconds
Ordered by: internal time
ncalls tottime percall cumtime percall filename:lineno(function)
100000 7.933 0.000 8.156 0.000 csr.py:265(_get_single_element)
1 0.271 0.271 8.705 8.705 csr.py:177(__getitem__)
(...)
Namely, the python function _get_single_element gets called 100000 times which is really inefficient. Why isn't this implemented in pure C? Does anybody know of a way of getting around this limitation, and speeding up the above code?
Should I be using a different sparse matrix type?
A:
You can use A.diagonal() to retrieve the diagonal much more quickly (0.0009 seconds vs. 3.8 seconds on my machine) . However, if you want to do arbitary indexing then that is a more complicated question because you aren't using slices so much as a list of indices. The _get_single_element function is being called 100000 times because it just iterating through the iterators (i and j) that you passed to it. A slice would be A[30:60,10] or something similar to that.
Also, I would use csr_matrix(eye(n,n)) to make the same matrix that you made with iterators just for simplicity.
Update:
Ok, since your question is truly about being able to access lots of random elements quickly, I will answer your questions as best as I can.
Why isn't this implemented in pure C?
The answer is simple: no one has gotten around to it. There is still plenty of work to be done in the sparse matrix modules area of Scipy from what I have seen. One part that is implemented in C is the conversions between different sparse matrix formats.
Does anybody know of a way of getting around this limitation, and speeding up the above code?
You can try actually diving into the sparse matrix modules and trying to speed them up. I did so and was able to get the time down to less than a third of the original when trying out your code above for random accesses using csr matrices. I had to directly access _get_single_element and pare down the code significantly to do that including taking out bound checks.
However, it was faster still to use a lil_matrix (though slower to initialize the matrix), but I had to do the accessing with a list comprehension because lil matrices aren't setup for the type of indexing you are doing. Using a list comprehension for the csr_matrix still leaves the lil matrix method way ahead by the way. Ultimately, the lil matrix is faster for accessing random elements because it isn't compressed.
Using the lil_matrix in its original form runs in about a fifth of the time of the code you have listed above. If I take out some bound checks and call lil_matrix's _get1() method directly, I can bring the time down further about 7% of the original time. For clarity that's a speed-up from 3.4-3.8 seconds to about 0.261 seconds.
Lastly, I tried making my own function that directly accesses the lil matrix's data and avoids the repeated function calls. The time for this was about 0.136 seconds. This didn't take advantage of the data being sorted which is another potential optimization (in particular if you are accessing a lot of elements that are on the same rows).
If you want faster than that then you will have to write your own C code sparse matrix implementation probably.
Should I be using a different sparse matrix type?
Well, I suggest the lil matrix if your intent is to access a whole lot of elements, but it all depends on what you need to do. Do you also need to multiply matrices for instance? Just remember that changing between matrices can at least sometimes (in certain circumstances) be quite fast so don't rule out changing to a different matrix format to do different operations.
If you don't need to do actually do any algebra operations on your matrix, then maybe you should just use a defaultdict or something similar. The danger with defaultdicts is that whenever an element is asked for that isn't in the dict, it sets that item to the default and stores it so that could be problematic.
A:
I think _get_single_element is only called when the default dtype of 'object' is used. Have you tried providing a dtype, such as csr_matrix((data, (i,j)), dtype=int32)
|
Vectorization of index operation for a scipy.sparse matrix
|
The following code runs too slowly even though everything seems to be vectorized.
from numpy import *
from scipy.sparse import *
n = 100000;
i = xrange(n); j = xrange(n);
data = ones(n);
A=csr_matrix((data,(i,j)));
x = A[i,j]
The problem seems to be that the indexing operation is implemented as a python function, and invoking A[i,j] results in the following profiling output
500033 function calls in 8.718 CPU seconds
Ordered by: internal time
ncalls tottime percall cumtime percall filename:lineno(function)
100000 7.933 0.000 8.156 0.000 csr.py:265(_get_single_element)
1 0.271 0.271 8.705 8.705 csr.py:177(__getitem__)
(...)
Namely, the python function _get_single_element gets called 100000 times which is really inefficient. Why isn't this implemented in pure C? Does anybody know of a way of getting around this limitation, and speeding up the above code?
Should I be using a different sparse matrix type?
|
[
"You can use A.diagonal() to retrieve the diagonal much more quickly (0.0009 seconds vs. 3.8 seconds on my machine) . However, if you want to do arbitary indexing then that is a more complicated question because you aren't using slices so much as a list of indices. The _get_single_element function is being called 100000 times because it just iterating through the iterators (i and j) that you passed to it. A slice would be A[30:60,10] or something similar to that. \nAlso, I would use csr_matrix(eye(n,n)) to make the same matrix that you made with iterators just for simplicity.\nUpdate:\nOk, since your question is truly about being able to access lots of random elements quickly, I will answer your questions as best as I can.\n\nWhy isn't this implemented in pure C?\n\nThe answer is simple: no one has gotten around to it. There is still plenty of work to be done in the sparse matrix modules area of Scipy from what I have seen. One part that is implemented in C is the conversions between different sparse matrix formats.\n\nDoes anybody know of a way of getting around this limitation, and speeding up the above code?\n\nYou can try actually diving into the sparse matrix modules and trying to speed them up. I did so and was able to get the time down to less than a third of the original when trying out your code above for random accesses using csr matrices. I had to directly access _get_single_element and pare down the code significantly to do that including taking out bound checks. \nHowever, it was faster still to use a lil_matrix (though slower to initialize the matrix), but I had to do the accessing with a list comprehension because lil matrices aren't setup for the type of indexing you are doing. Using a list comprehension for the csr_matrix still leaves the lil matrix method way ahead by the way. Ultimately, the lil matrix is faster for accessing random elements because it isn't compressed. \nUsing the lil_matrix in its original form runs in about a fifth of the time of the code you have listed above. If I take out some bound checks and call lil_matrix's _get1() method directly, I can bring the time down further about 7% of the original time. For clarity that's a speed-up from 3.4-3.8 seconds to about 0.261 seconds. \nLastly, I tried making my own function that directly accesses the lil matrix's data and avoids the repeated function calls. The time for this was about 0.136 seconds. This didn't take advantage of the data being sorted which is another potential optimization (in particular if you are accessing a lot of elements that are on the same rows).\nIf you want faster than that then you will have to write your own C code sparse matrix implementation probably.\n\nShould I be using a different sparse matrix type?\n\nWell, I suggest the lil matrix if your intent is to access a whole lot of elements, but it all depends on what you need to do. Do you also need to multiply matrices for instance? Just remember that changing between matrices can at least sometimes (in certain circumstances) be quite fast so don't rule out changing to a different matrix format to do different operations. \nIf you don't need to do actually do any algebra operations on your matrix, then maybe you should just use a defaultdict or something similar. The danger with defaultdicts is that whenever an element is asked for that isn't in the dict, it sets that item to the default and stores it so that could be problematic.\n",
"I think _get_single_element is only called when the default dtype of 'object' is used. Have you tried providing a dtype, such as csr_matrix((data, (i,j)), dtype=int32)\n"
] |
[
7,
0
] |
[] |
[] |
[
"indexing",
"python",
"scipy",
"sparse_matrix"
] |
stackoverflow_0002404437_indexing_python_scipy_sparse_matrix.txt
|
Q:
Fastest way to convert file from latin1 to utf-8 in python
I need fastest way to convert files from latin1 to utf-8 in python. The files are large ~ 2G. ( I am moving DB data ). So far I have
import codecs
infile = codecs.open(tmpfile, 'r', encoding='latin1')
outfile = codecs.open(tmpfile1, 'w', encoding='utf-8')
for line in infile:
outfile.write(line)
infile.close()
outfile.close()
but it is still slow. The conversion takes one fourth of the whole migration time.
I could also use a linux command line utility if it is faster than native python code.
A:
I would go with iconv and a system call.
A:
You could use blocks larger than one line, and do binary I/O -- each might speed thinks up a bit (though on Linux binary I/O won't, as it's identical to text I/O):
BLOCKSIZE = 1024*1024
with open(tmpfile, 'rb') as inf:
with open(tmpfile, 'wb') as ouf:
while True:
data = inf.read(BLOCKSIZE)
if not data: break
converted = data.decode('latin1').encode('utf-8')
ouf.write(converted)
The byte-by-byte parsing implied in by-line reading, line-end conversion (not on Linux;-), and codecs.open-style encoding-decoding, should be part of what's slowing you down. This approach is also portable (like yours is), since control-characters such as \n need no translation among these codecs anyway (in any OS).
This only works for input codecs that have no multibyte characters, but `latin1' is one of those (it does not matter whether the output codec has such characters or not).
Try different block sizes to find the sweet spot performance-wise, depending on your disk, filesystem and available RAM.
Edit: changed code per @John's comment, and clarified a conditon as per @gnibbler's.
A:
If you are desperate to do it in Python (or any other language), at least do the I/O in bigger chunks than lines, and avoid the codecs overhead.
infile = open(tmpfile, 'rb')
outfile = open(tmpfile1, 'wb')
BLOCKSIZE = 65536 # experiment with size
while True:
block = infile.read(BLOCKSIZE)
if not block: break
outfile.write(block.decode('latin1').encode('utf8'))
infile.close()
outfile.close()
Otherwise, go with iconv ... I haven't look under the hood but if it doesn't special-case latin1 input I'd be surprised :-)
|
Fastest way to convert file from latin1 to utf-8 in python
|
I need fastest way to convert files from latin1 to utf-8 in python. The files are large ~ 2G. ( I am moving DB data ). So far I have
import codecs
infile = codecs.open(tmpfile, 'r', encoding='latin1')
outfile = codecs.open(tmpfile1, 'w', encoding='utf-8')
for line in infile:
outfile.write(line)
infile.close()
outfile.close()
but it is still slow. The conversion takes one fourth of the whole migration time.
I could also use a linux command line utility if it is faster than native python code.
|
[
"I would go with iconv and a system call.\n",
"You could use blocks larger than one line, and do binary I/O -- each might speed thinks up a bit (though on Linux binary I/O won't, as it's identical to text I/O):\n BLOCKSIZE = 1024*1024\n with open(tmpfile, 'rb') as inf:\n with open(tmpfile, 'wb') as ouf:\n while True:\n data = inf.read(BLOCKSIZE)\n if not data: break\n converted = data.decode('latin1').encode('utf-8')\n ouf.write(converted)\n\nThe byte-by-byte parsing implied in by-line reading, line-end conversion (not on Linux;-), and codecs.open-style encoding-decoding, should be part of what's slowing you down. This approach is also portable (like yours is), since control-characters such as \\n need no translation among these codecs anyway (in any OS).\nThis only works for input codecs that have no multibyte characters, but `latin1' is one of those (it does not matter whether the output codec has such characters or not).\nTry different block sizes to find the sweet spot performance-wise, depending on your disk, filesystem and available RAM.\nEdit: changed code per @John's comment, and clarified a conditon as per @gnibbler's.\n",
"If you are desperate to do it in Python (or any other language), at least do the I/O in bigger chunks than lines, and avoid the codecs overhead.\ninfile = open(tmpfile, 'rb')\noutfile = open(tmpfile1, 'wb')\nBLOCKSIZE = 65536 # experiment with size\nwhile True:\n block = infile.read(BLOCKSIZE)\n if not block: break\n outfile.write(block.decode('latin1').encode('utf8'))\ninfile.close()\noutfile.close()\n\nOtherwise, go with iconv ... I haven't look under the hood but if it doesn't special-case latin1 input I'd be surprised :-)\n"
] |
[
6,
4,
2
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002404855_python.txt
|
Q:
Why would memcached refuse to store data with some keys?
I use the memcache extension for python, and I have a very strange problem. Memcached refuses to store the exact same data with some keys, and succeeds in caching some others.
>>> import memcache
>>> conn = memcache.Client('121.0.0.1:11211', debug=0)
>>> conn.set('138b9c95d693760840aab85ee5591d2', 'test');
True
>>> conn.set('138b9c95d693760840aab85ee5591d3', 'test');
0
>>> conn.set('138b9c95d693760840aab85ee5591d4', 'test');
True
>>> conn.set('138b9c95d693760840aab85ee5591d5', 'test');
0
>>> conn.set('138b9c95d693760840aab85ee5591d6', 'test');
True
>>> conn.set('138b9c95d693760840aab85ee5591d7', 'test');
0
>>> conn.set('138b9c95d693760840aab85ee5591d8', 'test');
True
>>> conn.set('138b9c95d693760840aab85ee5591d9', 'test');
True
>>> conn.set('138b9c95d693760840aab85ee5591e0', 'test');
True
>>> conn.set('138b9c95d693760840aab85ee5591e1', 'test');
True
I don't really understand. I should add that I use the version 1.40 of the memcache module with memcached 1.2.8 running on Ubuntu Server 9.10. I restarted the memcached daemon, same result, with the same keys.
Thanks.
Update: I upgraded memcached to version 1.4.2, packaged on lucid repos, with the exact same result.
Update #2: The exact same commands entered on another server with a fresh ubuntu setup gives the same result, same places.
Update #3 As suggested, with a list instead of a string in the Client insantiation :
>>> import memcache
>>> conn = memcache.Client(['121.0.0.1:11211'], debug=0)
>>> conn.set('138b9c95d693760840aab85ee5591d2', 'test');
0
>>> conn.set('138b9c95d693760840aab85ee5591d3', 'test');
0
>>> conn.set('138b9c95d693760840aab85ee5591d4', 'test');
0
>>> conn.set('138b9c95d693760840aab85ee5591d5', 'test');
0
>>> conn.set('138b9c95d693760840aab85ee5591d6', 'test');
0
>>> conn.set('138b9c95d693760840aab85ee5591d7', 'test');
0
>>>
>>> conn = memcache.Client('121.0.0.1:11211', debug=0)
>>> conn.set('138b9c95d693760840aab85ee5591d2', 'test');
True
>>> conn.set('138b9c95d693760840aab85ee5591d3', 'test');
0
A:
The first param should be a list
conn = memcache.Client(['127.0.0.1:11211'], debug=0)
|
Why would memcached refuse to store data with some keys?
|
I use the memcache extension for python, and I have a very strange problem. Memcached refuses to store the exact same data with some keys, and succeeds in caching some others.
>>> import memcache
>>> conn = memcache.Client('121.0.0.1:11211', debug=0)
>>> conn.set('138b9c95d693760840aab85ee5591d2', 'test');
True
>>> conn.set('138b9c95d693760840aab85ee5591d3', 'test');
0
>>> conn.set('138b9c95d693760840aab85ee5591d4', 'test');
True
>>> conn.set('138b9c95d693760840aab85ee5591d5', 'test');
0
>>> conn.set('138b9c95d693760840aab85ee5591d6', 'test');
True
>>> conn.set('138b9c95d693760840aab85ee5591d7', 'test');
0
>>> conn.set('138b9c95d693760840aab85ee5591d8', 'test');
True
>>> conn.set('138b9c95d693760840aab85ee5591d9', 'test');
True
>>> conn.set('138b9c95d693760840aab85ee5591e0', 'test');
True
>>> conn.set('138b9c95d693760840aab85ee5591e1', 'test');
True
I don't really understand. I should add that I use the version 1.40 of the memcache module with memcached 1.2.8 running on Ubuntu Server 9.10. I restarted the memcached daemon, same result, with the same keys.
Thanks.
Update: I upgraded memcached to version 1.4.2, packaged on lucid repos, with the exact same result.
Update #2: The exact same commands entered on another server with a fresh ubuntu setup gives the same result, same places.
Update #3 As suggested, with a list instead of a string in the Client insantiation :
>>> import memcache
>>> conn = memcache.Client(['121.0.0.1:11211'], debug=0)
>>> conn.set('138b9c95d693760840aab85ee5591d2', 'test');
0
>>> conn.set('138b9c95d693760840aab85ee5591d3', 'test');
0
>>> conn.set('138b9c95d693760840aab85ee5591d4', 'test');
0
>>> conn.set('138b9c95d693760840aab85ee5591d5', 'test');
0
>>> conn.set('138b9c95d693760840aab85ee5591d6', 'test');
0
>>> conn.set('138b9c95d693760840aab85ee5591d7', 'test');
0
>>>
>>> conn = memcache.Client('121.0.0.1:11211', debug=0)
>>> conn.set('138b9c95d693760840aab85ee5591d2', 'test');
True
>>> conn.set('138b9c95d693760840aab85ee5591d3', 'test');
0
|
[
"The first param should be a list\nconn = memcache.Client(['127.0.0.1:11211'], debug=0)\n\n"
] |
[
1
] |
[] |
[] |
[
"memcached",
"python",
"ubuntu"
] |
stackoverflow_0002405621_memcached_python_ubuntu.txt
|
Q:
Python: Indexing list for element in nested list
I know what I'm looking for. I want python to tell me which list it's in.
Here's some pseudocode:
item = "a"
nested_list = [["a", "b"], ["c", "d"]]
list.index(item) #obviously this doesn't work
here I would want python to return 0 (because "a" is an element in the first sub-list in the bigger list). I don't care which sub-element it is. I don't care if there are duplicates, e.g., ["a", "b", "a"] should return the same thing as the above example.
A:
In Python 2.6 or better,
next((i for i, sublist in enumerate(nested_list) if "a" in sublist), -1)
assuming e.g. you want a -1 result if 'a' is present in none of the sublists.
Of course it can be done in older versions of Python, too, but not quite as handily, and since you don't specify which Python versions you're interested in, I think it's best to use the latest production-solid one (just edit your answer if you need to specify other, older versions of Python).
Edit: per request, let me try to explain how this work. I'm using the (new in 2.6) built-in function next, specifically I'm calling next(iterator, default): returns the next item of the iterator (and thus the first, since this is the first time we're advancing that iterator), or the default value if the iterator's finished (which means "empty" if it's finished before we ever advanced it;-). The default is clearly that -1 and gets returned if "a is present in none of the sublists", which means the same as "the iterator is empty" in this case.
Let's look at the iterator again:
(i for i, sublist in enumerate(nested_list) if "a" in sublist)
the (rounded) parentheses and for and if keywords mean this is a generator expression, also known for brevity as genexp. i (the index) and sublist (the item at that index) advance over enumerate(nested_list) -- if we didn't have enumerate here then we wouldn't be keeping track of the index, but in this case we do need it. They're only considered when the if clause is satisfied, that is, when the element you're looking for is present in the current sublist.
So this genexp produces, one at a time, each value of the index such that the sublist at that index satisfies the condition "a" in sublist. Since we're using it inside next, we only take the first such index.
The OP might be justified for thinking that a magical builtin doing all of this in three or four characters would be handier -- and so it would, for this very specific requirement, which I believe I've never met before in over ten years of use of Python; however, if every such specific requirement had its own very specialized builtin the language and builtins would grown to be larger than the tax code. Instead, Python offers many lower-level "lego bricks" and a few handy way to snap them together, to clearly (and reasonably concisely) express the solution to a combinatorially-large variety of specific requirements, like the OP's.
A:
You'll need to use a looping construct of some sort:
next((sublist for sublist in mainlist if item in sublist))
That will give you a generator for all sublists containing the item you want, and give you the first one.
A:
Iterate over the list to get each sublist. Then, check to see if the item is in the sublist:
for i in range(0,len(list)):
if whatYoureLookingFor in list[i]:
print i
A:
>>> nested_list = [["a", "b"], ["c", "d"]]
>>> item="a"
>>> for o,sublist in enumerate(nested_list):
... if item in sublist:
... print o
...
0
|
Python: Indexing list for element in nested list
|
I know what I'm looking for. I want python to tell me which list it's in.
Here's some pseudocode:
item = "a"
nested_list = [["a", "b"], ["c", "d"]]
list.index(item) #obviously this doesn't work
here I would want python to return 0 (because "a" is an element in the first sub-list in the bigger list). I don't care which sub-element it is. I don't care if there are duplicates, e.g., ["a", "b", "a"] should return the same thing as the above example.
|
[
"In Python 2.6 or better,\nnext((i for i, sublist in enumerate(nested_list) if \"a\" in sublist), -1)\n\nassuming e.g. you want a -1 result if 'a' is present in none of the sublists.\nOf course it can be done in older versions of Python, too, but not quite as handily, and since you don't specify which Python versions you're interested in, I think it's best to use the latest production-solid one (just edit your answer if you need to specify other, older versions of Python).\nEdit: per request, let me try to explain how this work. I'm using the (new in 2.6) built-in function next, specifically I'm calling next(iterator, default): returns the next item of the iterator (and thus the first, since this is the first time we're advancing that iterator), or the default value if the iterator's finished (which means \"empty\" if it's finished before we ever advanced it;-). The default is clearly that -1 and gets returned if \"a is present in none of the sublists\", which means the same as \"the iterator is empty\" in this case.\nLet's look at the iterator again:\n(i for i, sublist in enumerate(nested_list) if \"a\" in sublist)\n\nthe (rounded) parentheses and for and if keywords mean this is a generator expression, also known for brevity as genexp. i (the index) and sublist (the item at that index) advance over enumerate(nested_list) -- if we didn't have enumerate here then we wouldn't be keeping track of the index, but in this case we do need it. They're only considered when the if clause is satisfied, that is, when the element you're looking for is present in the current sublist.\nSo this genexp produces, one at a time, each value of the index such that the sublist at that index satisfies the condition \"a\" in sublist. Since we're using it inside next, we only take the first such index.\nThe OP might be justified for thinking that a magical builtin doing all of this in three or four characters would be handier -- and so it would, for this very specific requirement, which I believe I've never met before in over ten years of use of Python; however, if every such specific requirement had its own very specialized builtin the language and builtins would grown to be larger than the tax code. Instead, Python offers many lower-level \"lego bricks\" and a few handy way to snap them together, to clearly (and reasonably concisely) express the solution to a combinatorially-large variety of specific requirements, like the OP's.\n",
"You'll need to use a looping construct of some sort:\nnext((sublist for sublist in mainlist if item in sublist))\n\nThat will give you a generator for all sublists containing the item you want, and give you the first one.\n",
"Iterate over the list to get each sublist. Then, check to see if the item is in the sublist:\nfor i in range(0,len(list)):\n if whatYoureLookingFor in list[i]:\n print i\n\n",
">>> nested_list = [[\"a\", \"b\"], [\"c\", \"d\"]]\n>>> item=\"a\"\n>>> for o,sublist in enumerate(nested_list):\n... if item in sublist:\n... print o\n...\n0\n\n"
] |
[
12,
1,
0,
0
] |
[] |
[] |
[
"indexing",
"list",
"nested",
"python"
] |
stackoverflow_0002405928_indexing_list_nested_python.txt
|
Q:
Use of infix operator hack in production code (Python)
What is your opinion of using the infix operator hack in production code? Issues:
The effect this will have on speed.
The potential for a clashes with an object with these operators already defined. This seems particularly dangerous with generic code that is intended to handle objects of any type.
It is a shame that this isn't built in - it really does improve readability
A:
It will be measurably slower than more Pythonic code, fragile (e.g. in the way you suggest), and baffling to every expert Python programmer that comes upon such code for the first time.
If you want to turn Python into one of the very few languages that allow user-defined infix operators (such as Haskell), you're better off designing a way to alter the syntax dynamically for the purpose, implement it as a patch to Python's parser, and start lobbying for it -- if it improves readability as much as you say, then it shouldn't be that hard to get Guido's approval for a clean, easy-to-explain implementation (if Guido, as I suspect, should sternly reject it instead, then you may want to ponder who's a better judge of language readability: you, or the designer of one of the most readable widespread languages? but I can't channel Guido, that's the timbot's job;-).
A:
In my personal opinion this would not be a great idea in production code: the biggest problem with it is that it totally non-standard and will probably leave non-familiar readers wondering where this novel syntax has suddenly sprung from.
I think you should prefer clarity rather than succinctness in general - Python is not C!
|
Use of infix operator hack in production code (Python)
|
What is your opinion of using the infix operator hack in production code? Issues:
The effect this will have on speed.
The potential for a clashes with an object with these operators already defined. This seems particularly dangerous with generic code that is intended to handle objects of any type.
It is a shame that this isn't built in - it really does improve readability
|
[
"It will be measurably slower than more Pythonic code, fragile (e.g. in the way you suggest), and baffling to every expert Python programmer that comes upon such code for the first time.\nIf you want to turn Python into one of the very few languages that allow user-defined infix operators (such as Haskell), you're better off designing a way to alter the syntax dynamically for the purpose, implement it as a patch to Python's parser, and start lobbying for it -- if it improves readability as much as you say, then it shouldn't be that hard to get Guido's approval for a clean, easy-to-explain implementation (if Guido, as I suspect, should sternly reject it instead, then you may want to ponder who's a better judge of language readability: you, or the designer of one of the most readable widespread languages? but I can't channel Guido, that's the timbot's job;-).\n",
"In my personal opinion this would not be a great idea in production code: the biggest problem with it is that it totally non-standard and will probably leave non-familiar readers wondering where this novel syntax has suddenly sprung from.\nI think you should prefer clarity rather than succinctness in general - Python is not C!\n"
] |
[
6,
1
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002405936_python.txt
|
Q:
Processing a log to fix a malformed IP address ?.?.?.x
I would like to replace the first character 'x' with the number '7' on every line of a log file using a shell script. Example of the log file:
216.129.119.x [01/Mar/2010:00:25:20 +0100] "GET /etc/....
74.131.77.x [01/Mar/2010:00:25:37 +0100] "GET /etc/....
222.168.17.x [01/Mar/2010:00:27:10 +0100] "GET /etc/....
My humble beginnings...
#!/bin/bash
echo Starting script...
cd /Users/me/logs/
gzip -d /Users/me/logs/access.log.gz
echo Files unzipped...
echo I'm totally lost here to process the log file and save it back to hd...
exit 0
Why is the log file IP malformed like this? My web provider (1and1) has decide not to store IP address, so they have replaced the last number with the character 'x'. They told me it was a new requirement by 'law'. I personally think that is bs, but that would take us off topic.
I want to process these log files with AWstats, so I need an IP address that is not malformed. I want to replace the x with a 7, like so:
216.129.119.7 [01/Mar/2010:00:25:20 +0100] "GET /etc/....
74.131.77.7 [01/Mar/2010:00:25:37 +0100] "GET /etc/....
222.168.17.7 [01/Mar/2010:00:27:10 +0100] "GET /etc/....
Not perfect I know, but least I can process the files, and I can still gain a lot of useful information like country, number of visitors, etc. The log files are 200MB each, so I thought that a shell script is the way to go because I can do that rapidly on my Macbook Pro locally. Unfortunately, I know very little about shell scripting, and my javascript skills are not going to cut it this time. I appreciate your help.
A:
since everyone is posting their alternative solutions i'm going to post one that i think is very simple:
sed s/\.x/\.7/ input_file > output_file
replace any string ".x" by ".7"
hope it helps! :)
A:
The following perl one-liner should do the trick:
perl -p -i -e 's/\.x/\.7/' foo.log
It'll substitute the first instance of '.x' with '.7' on each line of the log file.
A:
while i don't know what's the purpose of putting "7" in every IP because that's inaccurate, nevertheless, here's an awk one-liner
$ awk '{sub(/x$/,7,$1)}1' file
216.129.119.7 [01/Mar/2010:00:25:20 +0100] "GET /etc/....
74.131.77.7 [01/Mar/2010:00:25:37 +0100] "GET /etc/....
222.168.17.7 [01/Mar/2010:00:27:10 +0100] "GET /etc/....
A:
You can use this little python script (which could probably be written in fewer lines than this):
import sys
for line in sys.stdin:
ip_number, rest = line.split(' ', 1)
ip_parts = ip_number.split('.')
ip_parts[3] = '7'
ip_number = '.'.join(ip_parts)
print ip_number, rest,
Save it as fixip.py and execute it as:
cat access.log | python fixip.py > output.txt
A:
Python (run with file to process as the first argument):
import sys
import gzip
fin = gzip.GzipFile(sys.argv[1], 'r')
fout = gzip.GzipFile(sys.argv[1] + '.new', 'w', 9)
for line in fin:
address, rest = line.split(' ', 1)
prefix, node = address.rsplit('.', 1)
fout.write('%s.7 %s' % (prefix, rest))
fin.close()
fout.close()
|
Processing a log to fix a malformed IP address ?.?.?.x
|
I would like to replace the first character 'x' with the number '7' on every line of a log file using a shell script. Example of the log file:
216.129.119.x [01/Mar/2010:00:25:20 +0100] "GET /etc/....
74.131.77.x [01/Mar/2010:00:25:37 +0100] "GET /etc/....
222.168.17.x [01/Mar/2010:00:27:10 +0100] "GET /etc/....
My humble beginnings...
#!/bin/bash
echo Starting script...
cd /Users/me/logs/
gzip -d /Users/me/logs/access.log.gz
echo Files unzipped...
echo I'm totally lost here to process the log file and save it back to hd...
exit 0
Why is the log file IP malformed like this? My web provider (1and1) has decide not to store IP address, so they have replaced the last number with the character 'x'. They told me it was a new requirement by 'law'. I personally think that is bs, but that would take us off topic.
I want to process these log files with AWstats, so I need an IP address that is not malformed. I want to replace the x with a 7, like so:
216.129.119.7 [01/Mar/2010:00:25:20 +0100] "GET /etc/....
74.131.77.7 [01/Mar/2010:00:25:37 +0100] "GET /etc/....
222.168.17.7 [01/Mar/2010:00:27:10 +0100] "GET /etc/....
Not perfect I know, but least I can process the files, and I can still gain a lot of useful information like country, number of visitors, etc. The log files are 200MB each, so I thought that a shell script is the way to go because I can do that rapidly on my Macbook Pro locally. Unfortunately, I know very little about shell scripting, and my javascript skills are not going to cut it this time. I appreciate your help.
|
[
"since everyone is posting their alternative solutions i'm going to post one that i think is very simple:\nsed s/\\.x/\\.7/ input_file > output_file\n\nreplace any string \".x\" by \".7\"\nhope it helps! :)\n",
"The following perl one-liner should do the trick:\n\nperl -p -i -e 's/\\.x/\\.7/' foo.log\n\nIt'll substitute the first instance of '.x' with '.7' on each line of the log file. \n",
"while i don't know what's the purpose of putting \"7\" in every IP because that's inaccurate, nevertheless, here's an awk one-liner\n$ awk '{sub(/x$/,7,$1)}1' file\n216.129.119.7 [01/Mar/2010:00:25:20 +0100] \"GET /etc/....\n74.131.77.7 [01/Mar/2010:00:25:37 +0100] \"GET /etc/....\n222.168.17.7 [01/Mar/2010:00:27:10 +0100] \"GET /etc/....\n\n",
"You can use this little python script (which could probably be written in fewer lines than this):\nimport sys\nfor line in sys.stdin:\n ip_number, rest = line.split(' ', 1)\n ip_parts = ip_number.split('.')\n ip_parts[3] = '7'\n ip_number = '.'.join(ip_parts)\n print ip_number, rest,\n\nSave it as fixip.py and execute it as:\ncat access.log | python fixip.py > output.txt\n\n",
"Python (run with file to process as the first argument):\nimport sys\nimport gzip\n\nfin = gzip.GzipFile(sys.argv[1], 'r')\nfout = gzip.GzipFile(sys.argv[1] + '.new', 'w', 9)\n\nfor line in fin:\n address, rest = line.split(' ', 1)\n prefix, node = address.rsplit('.', 1)\n fout.write('%s.7 %s' % (prefix, rest))\n\nfin.close()\nfout.close()\n\n"
] |
[
3,
2,
2,
0,
0
] |
[] |
[] |
[
"bash",
"perl",
"python",
"shell",
"string"
] |
stackoverflow_0002402553_bash_perl_python_shell_string.txt
|
Q:
Get the last '/' or '\\' character in Python
If I have a string that looks like either
./A/B/c.d
OR
.\A\B\c.d
How do I get just the "./A/B/" part? The direction of the slashes can be the same as they are passed.
This problem kinda boils down to: How do I get the last of a specific character in a string?
Basically, I want the path of a file without the file part of it.
A:
Normally os.path.dirname() is used for this.
A:
I believe you are looking for os.path.split. It splits the path into head and tail... tail being the file, head being the path up to the file.
A:
>>> p="./A/B/c.d"
>>> import os
>>> os.path.split(p)
('./A/B', 'c.d')
>>> os.path.split(p)[0]
'./A/B'
>>> os.path.dirname(p)
'./A/B'
>>> p.rsplit("/",1)[0]
'./A/B
|
Get the last '/' or '\\' character in Python
|
If I have a string that looks like either
./A/B/c.d
OR
.\A\B\c.d
How do I get just the "./A/B/" part? The direction of the slashes can be the same as they are passed.
This problem kinda boils down to: How do I get the last of a specific character in a string?
Basically, I want the path of a file without the file part of it.
|
[
"Normally os.path.dirname() is used for this.\n",
"I believe you are looking for os.path.split. It splits the path into head and tail... tail being the file, head being the path up to the file.\n",
">>> p=\"./A/B/c.d\"\n>>> import os\n>>> os.path.split(p)\n('./A/B', 'c.d')\n>>> os.path.split(p)[0]\n'./A/B'\n>>> os.path.dirname(p)\n'./A/B'\n>>> p.rsplit(\"/\",1)[0]\n'./A/B\n\n"
] |
[
7,
4,
2
] |
[] |
[] |
[
"python",
"string"
] |
stackoverflow_0002406032_python_string.txt
|
Q:
Detecting circular imports
I'm working with a project that contains about 30 unique modules. It wasn't designed too well, so it's common that I create circular imports when adding some new functionality to the project.
Of course, when I add the circular import, I'm unaware of it. Sometimes it's pretty obvious I've made a circular import when I get an error like AttributeError: 'module' object has no attribute 'attribute' where I clearly defined 'attribute'. But other times, the code doesn't throw exceptions because of the way it's used.
So, to my question:
Is it possible to programmatically detect when and where a circular import is occuring?
The only solution I can think of so far is to have a module importTracking that contains a dict importingModules, a function importInProgress(file), which increments importingModules[file], and throws an error if it's greater than 1, and a function importComplete(file) which decrements importingModules[file]. All other modules would look like:
import importTracking
importTracking.importInProgress(__file__)
#module code goes here.
importTracking.importComplete(__file__)
But that looks really nasty, there's got to be a better way to do it, right?
A:
To avoid having to alter every module, you could stick your import-tracking functionality in a import hook, or in a customized __import__ you could stick in the built-ins -- the latter, for once, might work better, because __import__ gets called even if the module getting imported is already in sys.modules, which is the case during circular imports.
For the implementation I'd simply use a set of the modules "in the process of being imported", something like (benjaoming edit: Inserting a working snippet derived from original):
beingimported = set()
originalimport = __import__
def newimport(modulename, *args, **kwargs):
if modulename in beingimported:
print "Importing in circles", modulename, args, kwargs
print " Import stack trace -> ", beingimported
# sys.exit(1) # Normally exiting is a bad idea.
beingimported.add(modulename)
result = originalimport(modulename, *args, **kwargs)
if modulename in beingimported:
beingimported.remove(modulename)
return result
import __builtin__
__builtin__.__import__ = newimport
A:
Not all circular imports are a problem, as you've found when an exception is not thrown.
When they are a problem, you'll get an exception the next time you try to run any of your tests. You can change the code when this happens.
I don't see any change required from this situation.
Example of when it's not a problem:
a.py
import b
a = 42
def f():
return b.b
b.py
import a
b = 42
def f():
return a.a
A:
Circular imports in Python are not like PHP includes.
Python imported modules are loaded the first time into an import "handler", and kept there for the duration of the process. This handler assigns names in the local namespace for whatever is imported from that module, for every subsequent import. A module is unique, and a reference to that module name will always point to the same loaded module, regardless of where it was imported.
So if you have a circular module import, the loading of each file will happen once, and then each module will have names relating to the other module created into its namespace.
There could of course be problems when referring to specific names within both modules (when the circular imports occur BEFORE the class/function definitions that are referenced in the imports of the opposite modules), but you'll get an error if that happens.
A:
import uses __builtin__.__import__(), so if you monkeypatch that then every import everywhere will pick up the changes. Note that a circular import is not necessarily a problem though.
|
Detecting circular imports
|
I'm working with a project that contains about 30 unique modules. It wasn't designed too well, so it's common that I create circular imports when adding some new functionality to the project.
Of course, when I add the circular import, I'm unaware of it. Sometimes it's pretty obvious I've made a circular import when I get an error like AttributeError: 'module' object has no attribute 'attribute' where I clearly defined 'attribute'. But other times, the code doesn't throw exceptions because of the way it's used.
So, to my question:
Is it possible to programmatically detect when and where a circular import is occuring?
The only solution I can think of so far is to have a module importTracking that contains a dict importingModules, a function importInProgress(file), which increments importingModules[file], and throws an error if it's greater than 1, and a function importComplete(file) which decrements importingModules[file]. All other modules would look like:
import importTracking
importTracking.importInProgress(__file__)
#module code goes here.
importTracking.importComplete(__file__)
But that looks really nasty, there's got to be a better way to do it, right?
|
[
"To avoid having to alter every module, you could stick your import-tracking functionality in a import hook, or in a customized __import__ you could stick in the built-ins -- the latter, for once, might work better, because __import__ gets called even if the module getting imported is already in sys.modules, which is the case during circular imports.\nFor the implementation I'd simply use a set of the modules \"in the process of being imported\", something like (benjaoming edit: Inserting a working snippet derived from original):\nbeingimported = set()\noriginalimport = __import__\ndef newimport(modulename, *args, **kwargs):\n if modulename in beingimported:\n print \"Importing in circles\", modulename, args, kwargs\n print \" Import stack trace -> \", beingimported\n # sys.exit(1) # Normally exiting is a bad idea.\n beingimported.add(modulename)\n result = originalimport(modulename, *args, **kwargs)\n if modulename in beingimported:\n beingimported.remove(modulename)\n return result\nimport __builtin__\n__builtin__.__import__ = newimport\n\n",
"Not all circular imports are a problem, as you've found when an exception is not thrown.\nWhen they are a problem, you'll get an exception the next time you try to run any of your tests. You can change the code when this happens.\nI don't see any change required from this situation.\nExample of when it's not a problem:\na.py\nimport b\na = 42\ndef f():\n return b.b\n\nb.py\nimport a\nb = 42\ndef f():\n return a.a\n\n",
"Circular imports in Python are not like PHP includes.\nPython imported modules are loaded the first time into an import \"handler\", and kept there for the duration of the process. This handler assigns names in the local namespace for whatever is imported from that module, for every subsequent import. A module is unique, and a reference to that module name will always point to the same loaded module, regardless of where it was imported.\nSo if you have a circular module import, the loading of each file will happen once, and then each module will have names relating to the other module created into its namespace.\nThere could of course be problems when referring to specific names within both modules (when the circular imports occur BEFORE the class/function definitions that are referenced in the imports of the opposite modules), but you'll get an error if that happens.\n",
"import uses __builtin__.__import__(), so if you monkeypatch that then every import everywhere will pick up the changes. Note that a circular import is not necessarily a problem though.\n"
] |
[
10,
1,
1,
0
] |
[] |
[] |
[
"circular_dependency",
"python"
] |
stackoverflow_0002406007_circular_dependency_python.txt
|
Q:
HTTPS post login form
Trying to find a way to send a POST HTTPS request from Python to a web page form
A:
httplib is for the job, and you may refer to the example code at the bottom of the document. and google for the httplib sample code.
|
HTTPS post login form
|
Trying to find a way to send a POST HTTPS request from Python to a web page form
|
[
"httplib is for the job, and you may refer to the example code at the bottom of the document. and google for the httplib sample code.\n"
] |
[
5
] |
[] |
[] |
[
"https",
"python"
] |
stackoverflow_0002406196_https_python.txt
|
Q:
How can I turn off registry redirection on Python?
My program is trying to create an key on the
HKLM\Software\Microsoft\Shared Tools\MSCONFIG\startupreg\test\
but instead the key is created on the
HKLM\Wow6432node\Software\Microsoft\Shared Tools\MSCONFIG\startupreg\test\
and don't work properly... Why? How can I solve it?
A:
The docs on reflection-key features in winreg are scarce (and bits and pieces are missing). You really need this patch, but until it's applied and a new micro-release of Python is made with these fixes, at least you can try the DisableReflectionKey etc route according to the docs that patch adds (here's the RST for them):
+.. function:: DisableReflectionKey(key)
+
+ Disables registry reflection for 32-bit processes running on a 64-bit
+ Operating System.
+
+ *key* is an already open key, or one of the predefined :const:`HKEY_\*`
+ constants.
+
+ Will generally raise :exc:`NotImplemented` if executed on a 32-bit
+ Operating System.
+ If the key is not on the reflection list, the function succeeds but has no
+ effect. Disabling reflection for a key does not affect reflection of any
+ subkeys.
+
+.. function:: EnableReflectionKey(key)
+
+ Restores registry reflection for the specified disabled key.
+
+ *key* is an already open key, or one of the predefined :const:`HKEY_\*`
+ constants.
+
+ Will generally raise :exc:`NotImplemented` if executed on a 32-bit
+ Operating System.
+
+ Restoring reflection for a key does not affect reflection of any subkeys.
+
+
+.. function:: QueryReflectionKey(key)
+
+ Determines the reflection state for the specified key.
+
+ *key* is an already open key, or one of the predefined :const:`HKEY_\*`
+ constants.
+
+ Returns ``True`` if reflection is disabled.
+
+ Will generally raise :exc:`NotImplemented` if executed on a 32-bit
+ Operating System.
A:
You can use:
import _winreg
_winreg.DisableReflectionKey(_winreg.HKEY_LOCAL_MACHINE)
# do stuff here
_winreg.EnableReflectionKey(_winreg.HKEY_LOCAL_MACHINE)
This only works in Python 2.6 and above however.
|
How can I turn off registry redirection on Python?
|
My program is trying to create an key on the
HKLM\Software\Microsoft\Shared Tools\MSCONFIG\startupreg\test\
but instead the key is created on the
HKLM\Wow6432node\Software\Microsoft\Shared Tools\MSCONFIG\startupreg\test\
and don't work properly... Why? How can I solve it?
|
[
"The docs on reflection-key features in winreg are scarce (and bits and pieces are missing). You really need this patch, but until it's applied and a new micro-release of Python is made with these fixes, at least you can try the DisableReflectionKey etc route according to the docs that patch adds (here's the RST for them):\n+.. function:: DisableReflectionKey(key)\n+ \n+ Disables registry reflection for 32-bit processes running on a 64-bit\n+ Operating System.\n+ \n+ *key* is an already open key, or one of the predefined :const:`HKEY_\\*`\n+ constants.\n+ \n+ Will generally raise :exc:`NotImplemented` if executed on a 32-bit\n+ Operating System.\n\n+ If the key is not on the reflection list, the function succeeds but has no\n+ effect. Disabling reflection for a key does not affect reflection of any\n+ subkeys.\n\n+\n+.. function:: EnableReflectionKey(key)\n+\n+ Restores registry reflection for the specified disabled key.\n+ \n+ *key* is an already open key, or one of the predefined :const:`HKEY_\\*`\n+ constants.\n+\n+ Will generally raise :exc:`NotImplemented` if executed on a 32-bit\n+ Operating System.\n+ \n+ Restoring reflection for a key does not affect reflection of any subkeys.\n+\n+\n+.. function:: QueryReflectionKey(key)\n+\n+ Determines the reflection state for the specified key.\n+ \n+ *key* is an already open key, or one of the predefined :const:`HKEY_\\*`\n+ constants.\n+ \n+ Returns ``True`` if reflection is disabled.\n+\n+ Will generally raise :exc:`NotImplemented` if executed on a 32-bit\n+ Operating System.\n\n",
"You can use:\nimport _winreg\n_winreg.DisableReflectionKey(_winreg.HKEY_LOCAL_MACHINE)\n# do stuff here\n_winreg.EnableReflectionKey(_winreg.HKEY_LOCAL_MACHINE)\n\nThis only works in Python 2.6 and above however.\n"
] |
[
2,
0
] |
[] |
[] |
[
"64_bit",
"python",
"registry",
"windows"
] |
stackoverflow_0002404595_64_bit_python_registry_windows.txt
|
Q:
Getting readline to block on a FIFO
I create a fifo:
mkfifo tofetch
I run this python code:
fetchlistfile = file("tofetch", "r")
while 1:
nextfetch = fetchlistfile.readline()
print nextfetch
It stalls on readline, as I would hope. I run:
echo "test" > tofetch
And my program doesn't stall anymore. It reads the line, and then continues looping forever. Why won't it stall again when there's no new data?
I also tried looking on "not fetchlistfile.closed", I wouldn't mind reopening it after every write, but Python thinks the fifo is still open.
A:
According to the documentation for readline, it returns the empty string if and only if you're at end-of-file. Closed isn't the same as end-of-file. The file object will only be closed when you call .close(). When your code reaches the end of the file, readline() keeps returning the empty string.
If you just use the file object as an iterator, Python will automatically read a line at a time and stop at end-of-file. Like this:
fetchlistfile = file("tofetch", "r")
for nextfetch in fetchlistfile:
print nextfetch
The echo "test" > tofetch command opens the named pipe, writes "test" to it, and closes it's end of the pipe. Because the writing end of the pipe is closed, the reading end sees end-of-file.
|
Getting readline to block on a FIFO
|
I create a fifo:
mkfifo tofetch
I run this python code:
fetchlistfile = file("tofetch", "r")
while 1:
nextfetch = fetchlistfile.readline()
print nextfetch
It stalls on readline, as I would hope. I run:
echo "test" > tofetch
And my program doesn't stall anymore. It reads the line, and then continues looping forever. Why won't it stall again when there's no new data?
I also tried looking on "not fetchlistfile.closed", I wouldn't mind reopening it after every write, but Python thinks the fifo is still open.
|
[
"According to the documentation for readline, it returns the empty string if and only if you're at end-of-file. Closed isn't the same as end-of-file. The file object will only be closed when you call .close(). When your code reaches the end of the file, readline() keeps returning the empty string.\nIf you just use the file object as an iterator, Python will automatically read a line at a time and stop at end-of-file. Like this:\nfetchlistfile = file(\"tofetch\", \"r\")\nfor nextfetch in fetchlistfile:\n print nextfetch\n\nThe echo \"test\" > tofetch command opens the named pipe, writes \"test\" to it, and closes it's end of the pipe. Because the writing end of the pipe is closed, the reading end sees end-of-file.\n"
] |
[
5
] |
[] |
[] |
[
"fifo",
"pipe",
"python"
] |
stackoverflow_0002406365_fifo_pipe_python.txt
|
Q:
Adding an object to another module's globals in python
I know this is very evil, but is it possible to add an object to another module's globals, something like:
#module dog.py
import cat
cat.globals.addVar('name','mittens')
and
#module cat.py
print name #mittens
A:
setattr(cat, 'name', 'mittens')
or
cat.name = 'mittens'
|
Adding an object to another module's globals in python
|
I know this is very evil, but is it possible to add an object to another module's globals, something like:
#module dog.py
import cat
cat.globals.addVar('name','mittens')
and
#module cat.py
print name #mittens
|
[
"setattr(cat, 'name', 'mittens')\n\nor\ncat.name = 'mittens'\n\n"
] |
[
2
] |
[] |
[] |
[
"global",
"python"
] |
stackoverflow_0002406586_global_python.txt
|
Q:
Why can you reference an imported module using the importing module in python
I am trying to understand why any import can be referenced using the importing module, e.g
#module master.py
import slave
and then
>>>import master
>>>print master.slave
gives
<module 'slave' from 'C:\Documents and Settings....'>
What is the purpose of the feature? I can see how it can be helpful in a package's __init__.py file, but nothing else. Is it a side effect of the fact that every import is added to the module's namespace and that the module's namespace is visible from the outside? If so, why didn't they make an exception with data imported from other modules (e.g don't show it as part of the module's namespace for other modules)?
A:
It's a side effect, but it can be used purposefully, e.g. os.py imports either posixpath or ntpath as path in order to create os.path.
|
Why can you reference an imported module using the importing module in python
|
I am trying to understand why any import can be referenced using the importing module, e.g
#module master.py
import slave
and then
>>>import master
>>>print master.slave
gives
<module 'slave' from 'C:\Documents and Settings....'>
What is the purpose of the feature? I can see how it can be helpful in a package's __init__.py file, but nothing else. Is it a side effect of the fact that every import is added to the module's namespace and that the module's namespace is visible from the outside? If so, why didn't they make an exception with data imported from other modules (e.g don't show it as part of the module's namespace for other modules)?
|
[
"It's a side effect, but it can be used purposefully, e.g. os.py imports either posixpath or ntpath as path in order to create os.path.\n"
] |
[
1
] |
[] |
[] |
[
"import",
"module",
"namespaces",
"python"
] |
stackoverflow_0002406722_import_module_namespaces_python.txt
|
Q:
Javascript equivalent of Python's iterkeys() dictionary method
In Python I can use the iterkeys() method to iterate over the keys of a dictionary. For example:
mydict = {'a': [3,5,6,43,3,6,3,],
'b': [87,65,3,45,7,8],
'c': [34,57,8,9,9,2],}
for k in mydict.iterkeys():
print k
gives me:
a
c
b
How can I do something similar in Javascript?
A:
var mydict = {
'a': [3,5,6,43,3,6,3,],
'b': [87,65,3,45,7,8],
'c': [34,57,8,9,9,2],
};
for (var key in mydict) {
alert(key);
}
A:
for(k in mydict){
alert(k)
}
|
Javascript equivalent of Python's iterkeys() dictionary method
|
In Python I can use the iterkeys() method to iterate over the keys of a dictionary. For example:
mydict = {'a': [3,5,6,43,3,6,3,],
'b': [87,65,3,45,7,8],
'c': [34,57,8,9,9,2],}
for k in mydict.iterkeys():
print k
gives me:
a
c
b
How can I do something similar in Javascript?
|
[
"var mydict = {\n 'a': [3,5,6,43,3,6,3,],\n 'b': [87,65,3,45,7,8],\n 'c': [34,57,8,9,9,2],\n};\nfor (var key in mydict) {\n alert(key);\n}\n\n",
"for(k in mydict){\n alert(k)\n}\n\n"
] |
[
4,
0
] |
[] |
[] |
[
"javascript",
"python"
] |
stackoverflow_0002406916_javascript_python.txt
|
Q:
I want to scrape a site using GAE and post the results into a Google Entity
I want to scrape this URL : https://www.xstreetsl.com/modules.php?searchSubmitImage_x=0&searchSubmitImage_y=0&SearchLocale=0&name=Marketplace&SearchKeyword=business&searchSubmitImage.x=0&searchSubmitImage.y=0&SearchLocale=0&SearchPriceMin=&SearchPriceMax=&SearchRatingMin=&SearchRatingMax=&sort=&dir=asc
Go into each of the links and extract out various pieces of information e.g. permissions, prims etc then post the results into a Entity on google app engine.
I want to know the best way to go about it?
Chris
A:
There are several nice screen scraping libraries you can use in Python.
Perhaps the easiest to knock up an advanced scraper with is scrapy. It relies on Twisted to implement the main engine but provides a very easy to use interface for implementing custom scraping code.
Otherwise you can look at doing it more manually with something like BeautifulSoup, or Mechanize which provides a "mechanical" browser implementation.
BeautifulSoup and Mechanize should both work out of the box on App Engine - it provides a wrapper around httplib and urllib that uses urlfetch as a backend. Only scrapy will be problematic, due to its use of twisted. [thanks to Nick Johnson for the update].
A:
For normalizing HTML using a pure Python library I have had better experiences with html5lib than BeautifulSoup.
However you just want to extract simply structured information, which doesn't actually require normalizing the HTML. I have a few scraping apps on Google App Engine which use my own xpath library that works with raw HTML.
Or you can use regular expressions for one off jobs.
|
I want to scrape a site using GAE and post the results into a Google Entity
|
I want to scrape this URL : https://www.xstreetsl.com/modules.php?searchSubmitImage_x=0&searchSubmitImage_y=0&SearchLocale=0&name=Marketplace&SearchKeyword=business&searchSubmitImage.x=0&searchSubmitImage.y=0&SearchLocale=0&SearchPriceMin=&SearchPriceMax=&SearchRatingMin=&SearchRatingMax=&sort=&dir=asc
Go into each of the links and extract out various pieces of information e.g. permissions, prims etc then post the results into a Entity on google app engine.
I want to know the best way to go about it?
Chris
|
[
"There are several nice screen scraping libraries you can use in Python. \nPerhaps the easiest to knock up an advanced scraper with is scrapy. It relies on Twisted to implement the main engine but provides a very easy to use interface for implementing custom scraping code.\nOtherwise you can look at doing it more manually with something like BeautifulSoup, or Mechanize which provides a \"mechanical\" browser implementation.\nBeautifulSoup and Mechanize should both work out of the box on App Engine - it provides a wrapper around httplib and urllib that uses urlfetch as a backend. Only scrapy will be problematic, due to its use of twisted. [thanks to Nick Johnson for the update].\n",
"For normalizing HTML using a pure Python library I have had better experiences with html5lib than BeautifulSoup.\nHowever you just want to extract simply structured information, which doesn't actually require normalizing the HTML. I have a few scraping apps on Google App Engine which use my own xpath library that works with raw HTML.\nOr you can use regular expressions for one off jobs.\n"
] |
[
3,
3
] |
[] |
[] |
[
"google_app_engine",
"python",
"screen_scraping"
] |
stackoverflow_0002406428_google_app_engine_python_screen_scraping.txt
|
Q:
Why does concatenating a boolean value return an integer?
In python, you can concatenate boolean values, and it would return an integer. Example:
>>> True
True
>>> True + True
2
>>> True + False
1
>>> True + True + True
3
>>> True + True + False
2
>>> False + False
0
Why? Why does this make sense?
I understand that True is often represented as 1, whereas False is represented as 0, but that still does not explain how adding two values together of the same type returns a completely different type.
A:
Because In Python, bool is the subclass/subtype of int.
>>> issubclass(bool,int)
True
Update:
From boolobject.c
/* Boolean type, a subtype of int */
/* We need to define bool_print to override int_print */
bool_print
fputs(self->ob_ival == 0 ? "False" : "True", fp);
/* We define bool_repr to return "False" or "True" */
bool_repr
...
/* We define bool_new to always return either Py_True or Py_False */
...
// Arithmetic methods -- only so we can override &, |, ^
bool_as_number
bool_and, /* nb_and */
bool_xor, /* nb_xor */
bool_or, /* nb_or */
PyBool_Type
"bool",
sizeof(PyIntObject),
(printfunc)bool_print, /* tp_print */
(reprfunc)bool_repr, /* tp_repr */
&bool_as_number, /* tp_as_number */
(reprfunc)bool_repr, /* tp_str */
&PyInt_Type, /* tp_base */
bool_new, /* tp_new */
A:
Replace "concatenate" with "add" and True/False with 1/0, as you've said, and it makes perfect sense.
To sum up True and False in a sentence: they're alternative ways to spell the integer values 1 and 0, with the single difference that str() and repr() return the strings 'True' and 'False' instead of '1' and '0'.
See also: http://www.python.org/dev/doc/maint23/whatsnew/section-bool.html
A:
True is 1
False is 0
+ is ADD
Try this:
IDLE 2.6.4
>>> True == 1
True
>>> False == 0
True
>>>
|
Why does concatenating a boolean value return an integer?
|
In python, you can concatenate boolean values, and it would return an integer. Example:
>>> True
True
>>> True + True
2
>>> True + False
1
>>> True + True + True
3
>>> True + True + False
2
>>> False + False
0
Why? Why does this make sense?
I understand that True is often represented as 1, whereas False is represented as 0, but that still does not explain how adding two values together of the same type returns a completely different type.
|
[
"Because In Python, bool is the subclass/subtype of int.\n>>> issubclass(bool,int)\nTrue\n\nUpdate:\nFrom boolobject.c\n/* Boolean type, a subtype of int */\n\n/* We need to define bool_print to override int_print */\nbool_print\n fputs(self->ob_ival == 0 ? \"False\" : \"True\", fp);\n\n/* We define bool_repr to return \"False\" or \"True\" */\nbool_repr\n ...\n\n/* We define bool_new to always return either Py_True or Py_False */\n ...\n\n// Arithmetic methods -- only so we can override &, |, ^\nbool_as_number\n bool_and, /* nb_and */\n bool_xor, /* nb_xor */\n bool_or, /* nb_or */\n\nPyBool_Type\n \"bool\",\n sizeof(PyIntObject),\n (printfunc)bool_print, /* tp_print */\n (reprfunc)bool_repr, /* tp_repr */\n &bool_as_number, /* tp_as_number */\n (reprfunc)bool_repr, /* tp_str */\n &PyInt_Type, /* tp_base */\n bool_new, /* tp_new */\n\n",
"Replace \"concatenate\" with \"add\" and True/False with 1/0, as you've said, and it makes perfect sense.\n\nTo sum up True and False in a sentence: they're alternative ways to spell the integer values 1 and 0, with the single difference that str() and repr() return the strings 'True' and 'False' instead of '1' and '0'. \n\nSee also: http://www.python.org/dev/doc/maint23/whatsnew/section-bool.html\n",
"True is 1\nFalse is 0\n+ is ADD\n\nTry this:\nIDLE 2.6.4 \n>>> True == 1\nTrue\n>>> False == 0\nTrue\n>>> \n\n"
] |
[
21,
7,
2
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002406959_python.txt
|
Q:
Preferred way of defining properties in Python: property decorator or lambda?
Which is the preferred way of defining class properties in Python and why? Is it Ok to use both in one class?
@property
def total(self):
return self.field_1 + self.field_2
or
total = property(lambda self: self.field_1 + self.field_2)
A:
For read-only properties I use the decorator, else I usually do something like this:
class Bla(object):
def sneaky():
def fget(self):
return self._sneaky
def fset(self, value):
self._sneaky = value
return locals()
sneaky = property(**sneaky())
update:
Recent versions of python enhanced the decorator approach:
class Bla(object):
@property
def elegant(self):
return self._elegant
@elegant.setter
def elegant(self, value):
self._elegant = value
A:
The decorator form is probably best in the case you've shown, where you want to turn the method into a read-only property. The second case is better when you want to provide a setter/deleter/docstring as well as the getter or if you want to add a property that has a different name to the method it derives its value from.
A:
Don't use lambdas for this. The first is acceptable for a read-only property, the second is used with real methods for more complex cases.
|
Preferred way of defining properties in Python: property decorator or lambda?
|
Which is the preferred way of defining class properties in Python and why? Is it Ok to use both in one class?
@property
def total(self):
return self.field_1 + self.field_2
or
total = property(lambda self: self.field_1 + self.field_2)
|
[
"For read-only properties I use the decorator, else I usually do something like this:\nclass Bla(object):\n def sneaky():\n def fget(self):\n return self._sneaky\n def fset(self, value):\n self._sneaky = value\n return locals()\n sneaky = property(**sneaky())\n\nupdate:\nRecent versions of python enhanced the decorator approach:\nclass Bla(object):\n @property\n def elegant(self):\n return self._elegant\n\n @elegant.setter\n def elegant(self, value):\n self._elegant = value\n\n",
"The decorator form is probably best in the case you've shown, where you want to turn the method into a read-only property. The second case is better when you want to provide a setter/deleter/docstring as well as the getter or if you want to add a property that has a different name to the method it derives its value from.\n",
"Don't use lambdas for this. The first is acceptable for a read-only property, the second is used with real methods for more complex cases.\n"
] |
[
51,
22,
5
] |
[] |
[] |
[
"decorator",
"lambda",
"properties",
"python"
] |
stackoverflow_0002406567_decorator_lambda_properties_python.txt
|
Q:
fastest calculation of largest prime factor of 512 bit number in python
i am simulating my crypto scheme in python, i am a new user to it.
p = 512 bit number and i need to calculate largest prime factor for it, i am looking for two things:
Fastest code to process this large prime factorization
Code that can take 512 bit of number as input and can handle it.
I have seen different implementations in other languages, my whole code is in python and this is last point where i am stuck. So let me know if there is any implementation in python.
Kindly explain in simple as i am new user to python
sorry for bad english.
edit (taken from OP's answer below):
#!/usr/bin/env python
def highest_prime_factor(n):
if isprime(n):
return n
for x in xrange(2,n ** 0.5 + 1):
if not n % x:
return highest_prime_factor(n/x)
def isprime(n):
for x in xrange(2,n ** 0.5 + 1):
if not n % x:
return False
return True
if __name__ == "__main__":
import time
start = time.time()
print highest_prime_factor(1238162376372637826)
print time.time() - start
The code above works (with a bit of delay) for "1238162376372637826" but
extending it to
10902610991329142436630551158108608965062811746392
57767545600484549911304430471090261099132914243663
05511581086089650628117463925776754560048454991130443047
makes python go crazy. Is there any way so that just like above, i can have it
calculated it in no time?
A:
For a Python-based solution, you might want to look at pyecm On a system with gmpy installed also, pyecm found the following factors:
101, 521, 3121, 9901, 36479, 300623, 53397071018461, 1900381976777332243781
There still is a 98 digit unfactored composite:
60252507174568243758911151187828438446814447653986842279796823262165159406500174226172705680274911
Factoring this remaining composite using ECM may not be practical.
Edit: After a few hours, the remaining factors are
6060517860310398033985611921721
and
9941808367425935774306988776021629111399536914790551022447994642391
A:
This should be a better fit then the trivial approach for large numbers (although with this kind of number crunching every pure Python implementation will take a while): Pollard Rho prime factorization.
A:
If you can install an extension, gmpy would help -- see my answer to this SO question, specifically the def prime_factors(x) function in the code I show there.
In pure Python (without any extension allowed) it's a tad harder and a lot slower, see the code here for example (but don't hold your breath while it runs on your huge numbers;-).
|
fastest calculation of largest prime factor of 512 bit number in python
|
i am simulating my crypto scheme in python, i am a new user to it.
p = 512 bit number and i need to calculate largest prime factor for it, i am looking for two things:
Fastest code to process this large prime factorization
Code that can take 512 bit of number as input and can handle it.
I have seen different implementations in other languages, my whole code is in python and this is last point where i am stuck. So let me know if there is any implementation in python.
Kindly explain in simple as i am new user to python
sorry for bad english.
edit (taken from OP's answer below):
#!/usr/bin/env python
def highest_prime_factor(n):
if isprime(n):
return n
for x in xrange(2,n ** 0.5 + 1):
if not n % x:
return highest_prime_factor(n/x)
def isprime(n):
for x in xrange(2,n ** 0.5 + 1):
if not n % x:
return False
return True
if __name__ == "__main__":
import time
start = time.time()
print highest_prime_factor(1238162376372637826)
print time.time() - start
The code above works (with a bit of delay) for "1238162376372637826" but
extending it to
10902610991329142436630551158108608965062811746392
57767545600484549911304430471090261099132914243663
05511581086089650628117463925776754560048454991130443047
makes python go crazy. Is there any way so that just like above, i can have it
calculated it in no time?
|
[
"For a Python-based solution, you might want to look at pyecm On a system with gmpy installed also, pyecm found the following factors:\n101, 521, 3121, 9901, 36479, 300623, 53397071018461, 1900381976777332243781\nThere still is a 98 digit unfactored composite:\n60252507174568243758911151187828438446814447653986842279796823262165159406500174226172705680274911\nFactoring this remaining composite using ECM may not be practical.\nEdit: After a few hours, the remaining factors are\n6060517860310398033985611921721\nand\n9941808367425935774306988776021629111399536914790551022447994642391 \n",
"This should be a better fit then the trivial approach for large numbers (although with this kind of number crunching every pure Python implementation will take a while): Pollard Rho prime factorization.\n",
"If you can install an extension, gmpy would help -- see my answer to this SO question, specifically the def prime_factors(x) function in the code I show there.\nIn pure Python (without any extension allowed) it's a tad harder and a lot slower, see the code here for example (but don't hold your breath while it runs on your huge numbers;-).\n"
] |
[
3,
2,
1
] |
[
"('''==============================================================================='''\n> ''' CALCULATE HIGHEST PRIME\n> FACTOR '''\n>\n> '''===============================================================================''')\n>\n> #!/usr/bin/env python\n> def highest_prime_factor(n):\n> if isprime(n):\n> return n\n> for x in xrange(2,n ** 0.5 + 1):\n> if not n % x:\n> return highest_prime_factor(n/x)\n> def isprime(n):\n> for x in xrange(2,n ** 0.5 + 1):\n> if not n % x:\n> return False\n> return True\n> if __name__ == \"__main__\":\n> import time\n> start = time.time()\n> print highest_prime_factor(1238162376372637826)\n> print time.time() - start\n\nthe code works with a bit of delay on the number : \"1238162376372637826\" but\nextending it to\n(109026109913291424366305511581086089650628117463925776754560048454991130443047109026109913291424366305511581086089650628117463925776754560048454991130443047)\nmakes python go crazy. Is there any way just like above, i can have it\ncalculated it in no time.\n"
] |
[
-1
] |
[
"factorization",
"primes",
"python"
] |
stackoverflow_0002403578_factorization_primes_python.txt
|
Q:
Convert mysql timestamp to epoch time in python
Convert mysql timestamp to epoch time in python - is there an easy way to do this?
A:
Why not let MySQL do the hard work?
select unix_timestamp(fieldname) from tablename;
A:
converting mysql time to epoch:
>>> import time
>>> import calendar
>>> mysql_time = "2010-01-02 03:04:05"
>>> mysql_time_struct = time.strptime(mysql_time, '%Y-%m-%d %H:%M:%S')
>>> print mysql_time_struct
(2010, 1, 2, 3, 4, 5, 5, 2, -1)
>>> mysql_time_epoch = calendar.timegm(mysql_time_struct)
>>> print mysql_time_epoch
1262401445
converting epoch to something MySQL can use:
>>> import time
>>> time_epoch = time.time()
>>> print time_epoch
1268121070.7
>>> time_struct = time.gmtime(time_epoch)
>>> print time_struct
(2010, 3, 9, 7, 51, 10, 1, 68, 0)
>>> time_formatted = time.strftime('%Y-%m-%d %H:%M:%S', time_struct)
>>> print time_formatted
2010-03-09 07:51:10
A:
If you don't want to have MySQL do the work for some reason, then you can do this in Python easily enough. When you get a datetime column back from MySQLdb, you get a Python datetime.datetime object. To convert one of these, you can use time.mktime. For example:
import time
# Connecting to database skipped (also closing connection later)
c.execute("SELECT my_datetime_field FROM my_table")
d = c.fetchone()[0]
print time.mktime(d.timetuple())
A:
I use something like the following to get seconds since the epoch (UTC) from a MySQL date (local time):
calendar.timegm(
time.gmtime(
time.mktime(
time.strptime(t,
"%Y-%m-%d %H:%M:%S"))))
More info in this question: How do I convert local time to UTC in Python?
|
Convert mysql timestamp to epoch time in python
|
Convert mysql timestamp to epoch time in python - is there an easy way to do this?
|
[
"Why not let MySQL do the hard work?\nselect unix_timestamp(fieldname) from tablename;\n\n",
"converting mysql time to epoch:\n>>> import time\n>>> import calendar\n>>> mysql_time = \"2010-01-02 03:04:05\"\n>>> mysql_time_struct = time.strptime(mysql_time, '%Y-%m-%d %H:%M:%S')\n>>> print mysql_time_struct\n(2010, 1, 2, 3, 4, 5, 5, 2, -1)\n>>> mysql_time_epoch = calendar.timegm(mysql_time_struct)\n>>> print mysql_time_epoch\n1262401445\n\nconverting epoch to something MySQL can use:\n>>> import time\n>>> time_epoch = time.time()\n>>> print time_epoch\n1268121070.7\n>>> time_struct = time.gmtime(time_epoch)\n>>> print time_struct\n(2010, 3, 9, 7, 51, 10, 1, 68, 0)\n>>> time_formatted = time.strftime('%Y-%m-%d %H:%M:%S', time_struct)\n>>> print time_formatted\n2010-03-09 07:51:10\n\n",
"If you don't want to have MySQL do the work for some reason, then you can do this in Python easily enough. When you get a datetime column back from MySQLdb, you get a Python datetime.datetime object. To convert one of these, you can use time.mktime. For example:\nimport time\n# Connecting to database skipped (also closing connection later)\nc.execute(\"SELECT my_datetime_field FROM my_table\")\nd = c.fetchone()[0]\nprint time.mktime(d.timetuple())\n\n",
"I use something like the following to get seconds since the epoch (UTC) from a MySQL date (local time):\ncalendar.timegm(\n time.gmtime(\n time.mktime(\n time.strptime(t, \n \"%Y-%m-%d %H:%M:%S\"))))\n\nMore info in this question: How do I convert local time to UTC in Python?\n"
] |
[
28,
9,
5,
1
] |
[] |
[] |
[
"mysql",
"python",
"time",
"timestamp"
] |
stackoverflow_0000115866_mysql_python_time_timestamp.txt
|
Q:
What does the term "blocking" mean in programming?
Could someone provide a layman definition and use case?
A:
"Blocking" means that the caller waits until the callee finishes its processing. For instance, a "blocking read" from a socket waits until there is data to return; a "non-blocking" read does not, it just returns an indication (usually a count) of whether there was something read.
You hear the term mostly around APIs that access resources that don't necessarily require CPU attention -- I/O, for instance. You also hear it in multi-threading: A call from Thread A to Thread B might be designed to "block" (hold up Thread A) until Thread B achieves the relevant state to process or at least accept the request. (The most obvious example there being "join", which usually means "I, Thread A, want to wait until Thread B has terminated" -- you use that when exiting a multi-threaded program.)
A:
In simple words: If you call a function that stops the program from continuing to run until the user has performed some action (or some other action that your program is not controlling), this call is called a blocking call.
|
What does the term "blocking" mean in programming?
|
Could someone provide a layman definition and use case?
|
[
"\"Blocking\" means that the caller waits until the callee finishes its processing. For instance, a \"blocking read\" from a socket waits until there is data to return; a \"non-blocking\" read does not, it just returns an indication (usually a count) of whether there was something read.\nYou hear the term mostly around APIs that access resources that don't necessarily require CPU attention -- I/O, for instance. You also hear it in multi-threading: A call from Thread A to Thread B might be designed to \"block\" (hold up Thread A) until Thread B achieves the relevant state to process or at least accept the request. (The most obvious example there being \"join\", which usually means \"I, Thread A, want to wait until Thread B has terminated\" -- you use that when exiting a multi-threaded program.)\n",
"In simple words: If you call a function that stops the program from continuing to run until the user has performed some action (or some other action that your program is not controlling), this call is called a blocking call.\n"
] |
[
34,
5
] |
[] |
[] |
[
"api",
"blocking",
"python"
] |
stackoverflow_0002407589_api_blocking_python.txt
|
Q:
Change sound output
Is there a way in windows by which I can toggle the audio output between a built-in speaker and the headphone jack using a python library.
I am thinking someone with .NET experience would be able to give me some pointers (I could use IronPython if there is a .NET library to do that).
I have no idea where to start. Any hints would help.
Thanks a lot.
A:
The device selected for output in the Control Panel is just a default, each application can choose to output through that device or select a new one. You can get a handle to the device you want to output through, and subsequently use it for playback, by using the Win32 API for multimedia (winmm.dll). Some of those functions are on this page: http://msdn.microsoft.com/en-us/library/dd743586%28VS.85%29.aspx
I'm not aware of any standard .Net assemblies that provide this functionality, but I'm admittedly in unfamiliar territory on this one.
|
Change sound output
|
Is there a way in windows by which I can toggle the audio output between a built-in speaker and the headphone jack using a python library.
I am thinking someone with .NET experience would be able to give me some pointers (I could use IronPython if there is a .NET library to do that).
I have no idea where to start. Any hints would help.
Thanks a lot.
|
[
"The device selected for output in the Control Panel is just a default, each application can choose to output through that device or select a new one. You can get a handle to the device you want to output through, and subsequently use it for playback, by using the Win32 API for multimedia (winmm.dll). Some of those functions are on this page: http://msdn.microsoft.com/en-us/library/dd743586%28VS.85%29.aspx\nI'm not aware of any standard .Net assemblies that provide this functionality, but I'm admittedly in unfamiliar territory on this one.\n"
] |
[
0
] |
[
"Please read http://alvasnet.blogspot.com/2010/01/communicate-with-aliens-on-ironpython.html article\n"
] |
[
-1
] |
[
".net",
"audio",
"python"
] |
stackoverflow_0001965155_.net_audio_python.txt
|
Q:
Creating a list of lists with consecutive numbers
I am looking for a convenient way to create a list of lists for which the lists within the list have consecutive numbers. So far I only came up with a very unsatisfying brute-typing force solution (yeah right, I just use python for a few weeks now):
block0 = []
...
block4 = []
blocks = [block0,block1,block2,block3,block4]
I appreciate any help that works with something like nrBlocks = 5.
A:
It's not clear what consecutive numbers you're talking about, but your code translates into the following idiomatic Python:
[[] for _ in range(4)] # use xrange in python-2.x
A:
Don't do it this way. Put it in blocks in the first place:
blocks = [
[ ... ],
[ ... ],
[ ... ],
[ ... ]
]
|
Creating a list of lists with consecutive numbers
|
I am looking for a convenient way to create a list of lists for which the lists within the list have consecutive numbers. So far I only came up with a very unsatisfying brute-typing force solution (yeah right, I just use python for a few weeks now):
block0 = []
...
block4 = []
blocks = [block0,block1,block2,block3,block4]
I appreciate any help that works with something like nrBlocks = 5.
|
[
"It's not clear what consecutive numbers you're talking about, but your code translates into the following idiomatic Python:\n[[] for _ in range(4)] # use xrange in python-2.x\n\n",
"Don't do it this way. Put it in blocks in the first place:\nblocks = [\n [ ... ],\n [ ... ],\n [ ... ],\n [ ... ]\n]\n\n"
] |
[
5,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002408452_python.txt
|
Q:
Why can't I find `len(list)` in Python?
I'm new to Python. I have a method that begins:
def foo(self, list):
length = len(list)
I've called len() successfully in other cases, but here I get:
TypeError: object of type 'type' has no len()
How do I convince Python that this object passed in is a list? What am I missing?
A:
Because list is the name of the list type.
Use a different name.
def foo(self, lst):
length = len(lst)
And make sure you didn't call foo like this:
Foo.foo(list)
A:
you're shadowing built-in. The value that you're passing to foo method is not a list object, but rather a list type, that doesn't have any length.
A:
Seems like you're calling type() on list which is a type itself. Don't use the name list for your lists because it is a already a built-in type. use L or mylist or whatever and it should work.
|
Why can't I find `len(list)` in Python?
|
I'm new to Python. I have a method that begins:
def foo(self, list):
length = len(list)
I've called len() successfully in other cases, but here I get:
TypeError: object of type 'type' has no len()
How do I convince Python that this object passed in is a list? What am I missing?
|
[
"Because list is the name of the list type.\nUse a different name.\ndef foo(self, lst):\n length = len(lst)\n\nAnd make sure you didn't call foo like this:\nFoo.foo(list)\n\n",
"you're shadowing built-in. The value that you're passing to foo method is not a list object, but rather a list type, that doesn't have any length.\n",
"Seems like you're calling type() on list which is a type itself. Don't use the name list for your lists because it is a already a built-in type. use L or mylist or whatever and it should work.\n"
] |
[
5,
5,
2
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002408575_python.txt
|
Q:
How can I tell if waiting on Event has timed out?
import threading
event = threading.Event()
event.set()
print event.wait(1)
None
event.clear()
print event.wait(1)
None
So it basically returns None both when condition was True and False. How can I distinguish the case of timeouting from the one with no waiting at all? Meanwile, the docs say
This method returns the internal flag
on exit, so it will always return True
except if a timeout is given and the
operation times out.
Am I missing something?
A:
Yes, you're missing next sentence in documentation which writes:
Changed in version 2.7: Previously,
the method always returned None.
A:
From the docs for threading.Event.wait:
This method returns the internal flag on exit, so it will always return True except if a timeout is given and the operation times out.
Changed in version 2.7: Previously, the method always returned None.
Which version of python are you using?
|
How can I tell if waiting on Event has timed out?
|
import threading
event = threading.Event()
event.set()
print event.wait(1)
None
event.clear()
print event.wait(1)
None
So it basically returns None both when condition was True and False. How can I distinguish the case of timeouting from the one with no waiting at all? Meanwile, the docs say
This method returns the internal flag
on exit, so it will always return True
except if a timeout is given and the
operation times out.
Am I missing something?
|
[
"Yes, you're missing next sentence in documentation which writes:\n\nChanged in version 2.7: Previously,\n the method always returned None.\n\n",
"From the docs for threading.Event.wait:\n\nThis method returns the internal flag on exit, so it will always return True except if a timeout is given and the operation times out.\nChanged in version 2.7: Previously, the method always returned None.\n\nWhich version of python are you using?\n"
] |
[
3,
2
] |
[] |
[] |
[
"events",
"multithreading",
"python"
] |
stackoverflow_0002408882_events_multithreading_python.txt
|
Q:
standalone application in python
I wanted to know how can I make standalone application in python.
Basically what I am doing right now is I have a template.tex file and my script generate the pdf by giving some input values.
So I have to make exe file for windows and same for linux.
I can use cx_freeze for creating exe file.
But my problem is most of people do not contain latex on their computer.
SO how can I make latex get install when I first run my exe.
Basically how to make make file.
Thanks
A:
You could write a installer (using NSIS or something) that does two things :
install LateX (or make sure there is an installation of latex available), potentially by calling another installer
then install your python script (which can assume latex is now available)
A:
Sounds like you need a decent installer which can check for latex and if it's not there, install it. If you were feeling really brave you could use that to download Python as well which could avoid the requirement to use py2exe or freeze.
I've used the Nullsoft Scriptable Install System before and it's relatively easy to get something working quickly on windows at least.
Given that you're developing on multiple platforms, InstallJammer might be of more use to you.
|
standalone application in python
|
I wanted to know how can I make standalone application in python.
Basically what I am doing right now is I have a template.tex file and my script generate the pdf by giving some input values.
So I have to make exe file for windows and same for linux.
I can use cx_freeze for creating exe file.
But my problem is most of people do not contain latex on their computer.
SO how can I make latex get install when I first run my exe.
Basically how to make make file.
Thanks
|
[
"You could write a installer (using NSIS or something) that does two things : \n\ninstall LateX (or make sure there is an installation of latex available), potentially by calling another installer\nthen install your python script (which can assume latex is now available)\n\n",
"Sounds like you need a decent installer which can check for latex and if it's not there, install it. If you were feeling really brave you could use that to download Python as well which could avoid the requirement to use py2exe or freeze.\nI've used the Nullsoft Scriptable Install System before and it's relatively easy to get something working quickly on windows at least.\nGiven that you're developing on multiple platforms, InstallJammer might be of more use to you.\n"
] |
[
2,
1
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002409168_python.txt
|
Q:
Google App Engine: Users API acting oddly
I think I'm using the Users API incorrectly:
class BaseHandler(webapp.RequestHandler):
user = users.get_current_user()
def header(self, title):
if self.user:
render('Views/link.html', self, {'text': 'Log out', 'href': users.create_logout_url('/')})
else:
render('Views/link.html', self, {'text': 'Log in', 'href': users.create_login_url('/')})
link.html:
<p>
<a href="{{href}}">{{text}}</a>
</p>
Sometimes it works, sometimes it doesn't. I will click the "log out" link 10 times in a row, and reload the page, and it will redirect me to the '/' page. Then, mysteriously, one of the times I'll be logged out. Logging in fails in essentially the same fashion. What's going on here?
Solved - This works:
class BaseHandler(webapp.RequestHandler):
def __init__(self):
self.user = users.get_current_user()
def header(self, title):
if self.user:
render('Views/message.html', self, {'msg': "Welcome, %s" % self.user.nickname()})
render('Views/link.html', self, {'text': 'Log out', 'href': users.create_logout_url('/')})
else:
render('Views/link.html', self, {'text': 'Log in', 'href': users.create_login_url('/')})
It looks like I can have instance variables by referring to them as self.var_name in a function, but never declaring them on a class level. Odd.
A:
You are storing the result of users.get_current_user() in the variable called user, but then your if checks the value of self.user, which is not the same variable.
Use the same variable name and all should be fine!
|
Google App Engine: Users API acting oddly
|
I think I'm using the Users API incorrectly:
class BaseHandler(webapp.RequestHandler):
user = users.get_current_user()
def header(self, title):
if self.user:
render('Views/link.html', self, {'text': 'Log out', 'href': users.create_logout_url('/')})
else:
render('Views/link.html', self, {'text': 'Log in', 'href': users.create_login_url('/')})
link.html:
<p>
<a href="{{href}}">{{text}}</a>
</p>
Sometimes it works, sometimes it doesn't. I will click the "log out" link 10 times in a row, and reload the page, and it will redirect me to the '/' page. Then, mysteriously, one of the times I'll be logged out. Logging in fails in essentially the same fashion. What's going on here?
Solved - This works:
class BaseHandler(webapp.RequestHandler):
def __init__(self):
self.user = users.get_current_user()
def header(self, title):
if self.user:
render('Views/message.html', self, {'msg': "Welcome, %s" % self.user.nickname()})
render('Views/link.html', self, {'text': 'Log out', 'href': users.create_logout_url('/')})
else:
render('Views/link.html', self, {'text': 'Log in', 'href': users.create_login_url('/')})
It looks like I can have instance variables by referring to them as self.var_name in a function, but never declaring them on a class level. Odd.
|
[
"You are storing the result of users.get_current_user() in the variable called user, but then your if checks the value of self.user, which is not the same variable.\nUse the same variable name and all should be fine!\n"
] |
[
1
] |
[] |
[] |
[
"django",
"google_app_engine",
"python"
] |
stackoverflow_0002406424_django_google_app_engine_python.txt
|
Q:
Cross-site json rpc : Python server side and Mozilla extension using Javascript client side
I am building a Mozilla extension that contacts a Python application on a remote server to send and receive data. The Python application can be called using xml-rpc from a Python console. I am attempting to design a JSON-RPC that would contact the same application. Developing the Python server side, which can be accessed using python console, has been easy. However, I am having difficulties making the Mozilla extension to connect to the Python server side.
How do I make cross site JSON rpc calls? I have googled and read about many libraries, but none of them seem to work. I am not sure if it is because of some origin policy or because my server side is not able to process the data. Any help would be appreciated.
A:
You can use http://mimic-xmlrpc.sourceforge.net/ js library, or just XMLHttpRequest. I'm just with the same problem, and i'm an absolute newby with js :(
mimic seems grat, even if i'm having problems parsing the data returned..
|
Cross-site json rpc : Python server side and Mozilla extension using Javascript client side
|
I am building a Mozilla extension that contacts a Python application on a remote server to send and receive data. The Python application can be called using xml-rpc from a Python console. I am attempting to design a JSON-RPC that would contact the same application. Developing the Python server side, which can be accessed using python console, has been easy. However, I am having difficulties making the Mozilla extension to connect to the Python server side.
How do I make cross site JSON rpc calls? I have googled and read about many libraries, but none of them seem to work. I am not sure if it is because of some origin policy or because my server side is not able to process the data. Any help would be appreciated.
|
[
"You can use http://mimic-xmlrpc.sourceforge.net/ js library, or just XMLHttpRequest. I'm just with the same problem, and i'm an absolute newby with js :(\nmimic seems grat, even if i'm having problems parsing the data returned.. \n"
] |
[
0
] |
[] |
[] |
[
"javascript",
"json",
"mozilla",
"python",
"rpc"
] |
stackoverflow_0002399516_javascript_json_mozilla_python_rpc.txt
|
Q:
python unicode implementation (using external programs: cygnative plink ssh rsync)
I have a backup applications in python that needs to work on Windows. It needs UTF compatibility (to be able to backup directories that contain UTF characters like italian accents). The problem is it uses external programs (plink, cygwin, ssh and rsync) and I can't get them working. The prototype is 32 lines long, please take a look:
# -*- coding: utf-8 -*-
import subprocess
def safestr(obj, encoding='utf-8'):
r"""Converts any given object to utf-8 encoded string.
>>> safestr('hello')
'hello'
>>> safestr(u'\u1234')
'\xe1\x88\xb4'
>>> safestr(2)
'2'
"""
if isinstance(obj, unicode):
return obj.encode("utf-8")
elif isinstance(obj, str):
return obj.encode
else:
return str(obj)
def execute(command):
pipe = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE)
out, errs = pipe.communicate()
retcode = pipe.poll()
print "OUT: " + repr(out)
print "ERRS: " + repr(errs)
print "RET: " + str(retcode)
command = u'rsync --stats -az --numeric-ids --delete --blocking-io --modify-window=2 --no-group --chmod=u=rwX,g=,o= -e \'cygnative plink -ssh -2 -batch -pw test \' "/cygdrive/c/κόσμε" vaidab@192.168.1.86:/volatile/backup/vaidab/2010-03-03.15_41_56/ --link-dest=../2010-03-03.15_00_57'.encode('utf-8')
execute(command)
Still doesn't work with nosklo's version, check the result:
python prototype_unicode_new.py
'rsync.exe --stats -az --numeric-ids --delete --blocking-io --modify-window=2 --
no-group --chmod=u=rwX,g=,o= -e "cygnative plink -ssh -2 -batch -pw test" /cygdr
ive/c/\xce\xba\xcf\x8c\xcf\x83\xce\xbc\xce\xb5 vaidab@192.168.1.86:/volatile/bac
kup/vaidab/2010-03-03.15_41_56/'
OUT: '\nNumber of files: 0\nNumber of files transferred: 0\nTotal file size: 0 b
ytes\nTotal transferred file size: 0 bytes\nLiteral data: 0 bytes\nMatched data:
0 bytes\nFile list size: 9\nFile list generation time: 0.001 seconds\nFile list
transfer time: 0.000 seconds\nTotal bytes sent: 22\nTotal bytes received: 12\n\
nsent 22 bytes received 12 bytes 68.00 bytes/sec\ntotal size is 0 speedup is
0.00\n'
ERRS: 'rsync: link_stat "/cygdrive/c/\xc3\x8e\xc2\xba\xc3\x8f\xc5\x92\xc3\x8f\xc
6\x92\xc3\x8e\xc2\xbc\xc3\x8e\xc2\xb5" failed: No such file or directory (2)\nrs
ync error: some files/attrs were not transferred (see previous errors) (code 23)
at /home/lapo/packaging/rsync-3.0.6-1/src/rsync-3.0.6/main.c(1039) [sender=3.0.
6]\n'
RET: 23
A:
Don't use shell=True. EVER. It needlessy invokes a shell to call your program.
Pass the parameters as a list instead of a string.
This example should work, provided the parameters are right and the rsync.exe is in current folder (or PATH):
# -*- coding: utf-8 -*-
import subprocess
def execute(command):
pipe = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, errs = pipe.communicate()
retcode = pipe.poll()
print "OUT: " + repr(out)
print "ERRS: " + repr(errs)
print "RET: " + str(retcode)
return out
command = ['rsync.exe', '--stats', '-az', '--numeric-ids', '--delete',
'--blocking-io', '--modify-window=2', '--no-group',
'--chmod=u=rwX,g=,o=', '-e',
'cygnative plink -ssh -2 -batch -pw test',
u'/cygdrive/c/κόσμε'.encode('utf-8'),
'vaidab@192.168.1.86:/volatile/backup/vaidab/2010-03-03.15_41_56/',
'--link-dest=../2010-03-03.15_00_57']
execute(command)
A:
A piece of code that passeth all understanding:
if isinstance(obj, unicode):
return obj.encode("utf-8")
elif isinstance(obj, str):
return obj.encode
# the above is returning a METHOD ***************************
else:
return str(obj)
What's the point of doctests if you don't run them?
|
python unicode implementation (using external programs: cygnative plink ssh rsync)
|
I have a backup applications in python that needs to work on Windows. It needs UTF compatibility (to be able to backup directories that contain UTF characters like italian accents). The problem is it uses external programs (plink, cygwin, ssh and rsync) and I can't get them working. The prototype is 32 lines long, please take a look:
# -*- coding: utf-8 -*-
import subprocess
def safestr(obj, encoding='utf-8'):
r"""Converts any given object to utf-8 encoded string.
>>> safestr('hello')
'hello'
>>> safestr(u'\u1234')
'\xe1\x88\xb4'
>>> safestr(2)
'2'
"""
if isinstance(obj, unicode):
return obj.encode("utf-8")
elif isinstance(obj, str):
return obj.encode
else:
return str(obj)
def execute(command):
pipe = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE)
out, errs = pipe.communicate()
retcode = pipe.poll()
print "OUT: " + repr(out)
print "ERRS: " + repr(errs)
print "RET: " + str(retcode)
command = u'rsync --stats -az --numeric-ids --delete --blocking-io --modify-window=2 --no-group --chmod=u=rwX,g=,o= -e \'cygnative plink -ssh -2 -batch -pw test \' "/cygdrive/c/κόσμε" vaidab@192.168.1.86:/volatile/backup/vaidab/2010-03-03.15_41_56/ --link-dest=../2010-03-03.15_00_57'.encode('utf-8')
execute(command)
Still doesn't work with nosklo's version, check the result:
python prototype_unicode_new.py
'rsync.exe --stats -az --numeric-ids --delete --blocking-io --modify-window=2 --
no-group --chmod=u=rwX,g=,o= -e "cygnative plink -ssh -2 -batch -pw test" /cygdr
ive/c/\xce\xba\xcf\x8c\xcf\x83\xce\xbc\xce\xb5 vaidab@192.168.1.86:/volatile/bac
kup/vaidab/2010-03-03.15_41_56/'
OUT: '\nNumber of files: 0\nNumber of files transferred: 0\nTotal file size: 0 b
ytes\nTotal transferred file size: 0 bytes\nLiteral data: 0 bytes\nMatched data:
0 bytes\nFile list size: 9\nFile list generation time: 0.001 seconds\nFile list
transfer time: 0.000 seconds\nTotal bytes sent: 22\nTotal bytes received: 12\n\
nsent 22 bytes received 12 bytes 68.00 bytes/sec\ntotal size is 0 speedup is
0.00\n'
ERRS: 'rsync: link_stat "/cygdrive/c/\xc3\x8e\xc2\xba\xc3\x8f\xc5\x92\xc3\x8f\xc
6\x92\xc3\x8e\xc2\xbc\xc3\x8e\xc2\xb5" failed: No such file or directory (2)\nrs
ync error: some files/attrs were not transferred (see previous errors) (code 23)
at /home/lapo/packaging/rsync-3.0.6-1/src/rsync-3.0.6/main.c(1039) [sender=3.0.
6]\n'
RET: 23
|
[
"\nDon't use shell=True. EVER. It needlessy invokes a shell to call your program.\nPass the parameters as a list instead of a string.\n\nThis example should work, provided the parameters are right and the rsync.exe is in current folder (or PATH):\n# -*- coding: utf-8 -*-\nimport subprocess\n\ndef execute(command):\n pipe = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n out, errs = pipe.communicate()\n retcode = pipe.poll()\n\n print \"OUT: \" + repr(out)\n print \"ERRS: \" + repr(errs)\n print \"RET: \" + str(retcode)\n return out\n\n\ncommand = ['rsync.exe', '--stats', '-az', '--numeric-ids', '--delete', \n '--blocking-io', '--modify-window=2', '--no-group', \n '--chmod=u=rwX,g=,o=', '-e', \n 'cygnative plink -ssh -2 -batch -pw test', \n u'/cygdrive/c/κόσμε'.encode('utf-8'), \n 'vaidab@192.168.1.86:/volatile/backup/vaidab/2010-03-03.15_41_56/', \n '--link-dest=../2010-03-03.15_00_57']\n\nexecute(command)\n\n",
"A piece of code that passeth all understanding:\nif isinstance(obj, unicode):\n return obj.encode(\"utf-8\")\nelif isinstance(obj, str):\n return obj.encode\n # the above is returning a METHOD ***************************\nelse:\n return str(obj)\n\nWhat's the point of doctests if you don't run them?\n"
] |
[
1,
0
] |
[] |
[] |
[
"cygwin",
"plink",
"python",
"rsync",
"utf_8"
] |
stackoverflow_0002408695_cygwin_plink_python_rsync_utf_8.txt
|
Q:
seleniumRC: Problems with browser starting on OS X
I am trying to start simple selenium test on OSX (just downloaded the latest version of RC), with a python client driver. But the browser can't start (it crashes).
The error which I see in console is
15:33:32.867 INFO - Preparing Firefox profile...
dyld: Library not loaded: /System/Library/Frameworks/ApplicationServices.framework/Versions/A/Frameworks/ImageIO.framework/Versions/A/Resources/libJPEG.dylib
Referenced from: /System/Library/Frameworks/ApplicationServices.framework/Versions/A/Frameworks/ImageIO.framework/Versions/A/ImageIO
Reason: Incompatible library version: ImageIO requires version 1.0.0 or later, but libJPEG.dylib provides version 0.0.0
15:33:53.620 ERROR - Failed to start new browser session, shutdown browser and clear all session data
java.lang.RuntimeException: Timed out waiting for profile to be created!
at org.openqa.selenium.server.browserlaunchers.FirefoxChromeLauncher.waitForFullProfileToBeCreated(FirefoxChromeLauncher.java:348)
at org.openqa.selenium.server.browserlaunchers.FirefoxChromeLauncher.populateCustomProfileDirectory(FirefoxChromeLauncher.java:124)
at org.openqa.selenium.server.browserlaunchers.FirefoxChromeLauncher.launch(FirefoxChromeLauncher.java:91)
at org.openqa.selenium.server.browserlaunchers.FirefoxChromeLauncher.launchRemoteSession(FirefoxChromeLauncher.java:400)
at org.openqa.selenium.server.BrowserSessionFactory.createNewRemoteSession(BrowserSessionFactory.java:372)
at org.openqa.selenium.server.BrowserSessionFactory.getNewBrowserSession(BrowserSessionFactory.java:124)
at org.openqa.selenium.server.BrowserSessionFactory.getNewBrowserSession(BrowserSessionFactory.java:86)
at org.openqa.selenium.server.SeleniumDriverResourceHandler.getNewBrowserSession(SeleniumDriverResourceHandler.java:733)
at org.openqa.selenium.server.SeleniumDriverResourceHandler.doCommand(SeleniumDriverResourceHandler.java:399)
at org.openqa.selenium.server.SeleniumDriverResourceHandler.handleCommandRequest(SeleniumDriverResourceHandler.java:370)
at org.openqa.selenium.server.SeleniumDriverResourceHandler.handle(SeleniumDriverResourceHandler.java:129)
at org.openqa.jetty.http.HttpContext.handle(HttpContext.java:1530)
at org.openqa.jetty.http.HttpContext.handle(HttpContext.java:1482)
at org.openqa.jetty.http.HttpServer.service(HttpServer.java:909)
at org.openqa.jetty.http.HttpConnection.service(HttpConnection.java:820)
at org.openqa.jetty.http.HttpConnection.handleNext(HttpConnection.java:986)
at org.openqa.jetty.http.HttpConnection.handle(HttpConnection.java:837)
at org.openqa.jetty.http.SocketListener.handleConnection(SocketListener.java:245)
at org.openqa.jetty.util.ThreadedServer.handle(ThreadedServer.java:357)
at org.openqa.jetty.util.ThreadPool$PoolThread.run(ThreadPool.java:534)
15:33:53.927 INFO - Got result: Failed to start new browser session: Error while launching browser on session null
Answering your questions
I set up profile (disabled almost all warnings)...
I see this error now
dyld: Library not loaded: /System/Library/Frameworks/ApplicationServices.framework/Versions/A/Frameworks/ImageIO.framework/Versions/A/Resources/libJPEG.dylib
Referenced from: /System/Library/Frameworks/ApplicationServices.framework/Versions/A/Frameworks/ImageIO.framework/Versions/A/ImageIO
Reason: Incompatible library version: ImageIO requires version 1.0.0 or later, but libJPEG.dylib provides version 0.0.0
16:35:54.245 INFO - Launching Firefox...
It became smaller, but looks like to be the same
A:
It appears as if ImageIO is interfering with the loading of Firefox when it is creating its new Firefox profile on creation.
Try create your own firefox profile and then start Selenium RC with the -firefoxProfileTemplate argument
java -jar selenium-server.jar -firefoxProfileTemplate </path/to/template/>
And see how that goes
|
seleniumRC: Problems with browser starting on OS X
|
I am trying to start simple selenium test on OSX (just downloaded the latest version of RC), with a python client driver. But the browser can't start (it crashes).
The error which I see in console is
15:33:32.867 INFO - Preparing Firefox profile...
dyld: Library not loaded: /System/Library/Frameworks/ApplicationServices.framework/Versions/A/Frameworks/ImageIO.framework/Versions/A/Resources/libJPEG.dylib
Referenced from: /System/Library/Frameworks/ApplicationServices.framework/Versions/A/Frameworks/ImageIO.framework/Versions/A/ImageIO
Reason: Incompatible library version: ImageIO requires version 1.0.0 or later, but libJPEG.dylib provides version 0.0.0
15:33:53.620 ERROR - Failed to start new browser session, shutdown browser and clear all session data
java.lang.RuntimeException: Timed out waiting for profile to be created!
at org.openqa.selenium.server.browserlaunchers.FirefoxChromeLauncher.waitForFullProfileToBeCreated(FirefoxChromeLauncher.java:348)
at org.openqa.selenium.server.browserlaunchers.FirefoxChromeLauncher.populateCustomProfileDirectory(FirefoxChromeLauncher.java:124)
at org.openqa.selenium.server.browserlaunchers.FirefoxChromeLauncher.launch(FirefoxChromeLauncher.java:91)
at org.openqa.selenium.server.browserlaunchers.FirefoxChromeLauncher.launchRemoteSession(FirefoxChromeLauncher.java:400)
at org.openqa.selenium.server.BrowserSessionFactory.createNewRemoteSession(BrowserSessionFactory.java:372)
at org.openqa.selenium.server.BrowserSessionFactory.getNewBrowserSession(BrowserSessionFactory.java:124)
at org.openqa.selenium.server.BrowserSessionFactory.getNewBrowserSession(BrowserSessionFactory.java:86)
at org.openqa.selenium.server.SeleniumDriverResourceHandler.getNewBrowserSession(SeleniumDriverResourceHandler.java:733)
at org.openqa.selenium.server.SeleniumDriverResourceHandler.doCommand(SeleniumDriverResourceHandler.java:399)
at org.openqa.selenium.server.SeleniumDriverResourceHandler.handleCommandRequest(SeleniumDriverResourceHandler.java:370)
at org.openqa.selenium.server.SeleniumDriverResourceHandler.handle(SeleniumDriverResourceHandler.java:129)
at org.openqa.jetty.http.HttpContext.handle(HttpContext.java:1530)
at org.openqa.jetty.http.HttpContext.handle(HttpContext.java:1482)
at org.openqa.jetty.http.HttpServer.service(HttpServer.java:909)
at org.openqa.jetty.http.HttpConnection.service(HttpConnection.java:820)
at org.openqa.jetty.http.HttpConnection.handleNext(HttpConnection.java:986)
at org.openqa.jetty.http.HttpConnection.handle(HttpConnection.java:837)
at org.openqa.jetty.http.SocketListener.handleConnection(SocketListener.java:245)
at org.openqa.jetty.util.ThreadedServer.handle(ThreadedServer.java:357)
at org.openqa.jetty.util.ThreadPool$PoolThread.run(ThreadPool.java:534)
15:33:53.927 INFO - Got result: Failed to start new browser session: Error while launching browser on session null
Answering your questions
I set up profile (disabled almost all warnings)...
I see this error now
dyld: Library not loaded: /System/Library/Frameworks/ApplicationServices.framework/Versions/A/Frameworks/ImageIO.framework/Versions/A/Resources/libJPEG.dylib
Referenced from: /System/Library/Frameworks/ApplicationServices.framework/Versions/A/Frameworks/ImageIO.framework/Versions/A/ImageIO
Reason: Incompatible library version: ImageIO requires version 1.0.0 or later, but libJPEG.dylib provides version 0.0.0
16:35:54.245 INFO - Launching Firefox...
It became smaller, but looks like to be the same
|
[
"It appears as if ImageIO is interfering with the loading of Firefox when it is creating its new Firefox profile on creation.\nTry create your own firefox profile and then start Selenium RC with the -firefoxProfileTemplate argument\njava -jar selenium-server.jar -firefoxProfileTemplate </path/to/template/>\n\nAnd see how that goes\n"
] |
[
0
] |
[] |
[] |
[
"python",
"selenium",
"selenium_rc"
] |
stackoverflow_0002409353_python_selenium_selenium_rc.txt
|
Q:
Python methods on an object - which is better?
Hopefully an easy question. If I have an object and I want to call a method on it which is the better approach, A or B?
class foo(object):
def bar():
print 'bar'
# approach A
f = foo()
f.bar()
# approach B
foo().bar()
A:
A is more readable.
So, A :)
A:
If your sole intent is to call bar() on a foo object, B is okay.
But if you actually plan to do something with the object later, you must go with A as B doesn't leave you any references to the created object.
A:
Approach B doesn't keep the object around. If method bar() returns self then you can write:
f = foo().bar()
Personally I like method A. Though I've started making setter functions that return self in order to chain them together like above - I don't think other people consider that pythonic.
|
Python methods on an object - which is better?
|
Hopefully an easy question. If I have an object and I want to call a method on it which is the better approach, A or B?
class foo(object):
def bar():
print 'bar'
# approach A
f = foo()
f.bar()
# approach B
foo().bar()
|
[
"A is more readable. \nSo, A :)\n",
"If your sole intent is to call bar() on a foo object, B is okay.\nBut if you actually plan to do something with the object later, you must go with A as B doesn't leave you any references to the created object.\n",
"Approach B doesn't keep the object around. If method bar() returns self then you can write:\n\nf = foo().bar()\n\nPersonally I like method A. Though I've started making setter functions that return self in order to chain them together like above - I don't think other people consider that pythonic.\n"
] |
[
2,
2,
1
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002409668_python.txt
|
Q:
django python - generic views and cookies
I made in my web a menu using generic_view - simple 'django.views.generic.list_detail.object_list' in urls.py file.
I would like to set a cookies each time when user chooses one of element of this list [HttpResponse.set_cookie(...)].
What is the best solution? Should I write function in views.py or have you got more simple solution?
Edit 1
This is the fragment of my urls.py:
manufacturer_dict = {
'queryset': Manufacturer.objects.all()
}
urlpatterns = patterns('',
url(r'^$', 'django.views.generic.list_detail.object_list', manufacturer_dict),
)
And template: manufacturer_list.html
<ul>
{% for object in object_list %}
<li><a href="{{object.get_absolute_url}}" title="{{object.name}}">{{object.name}}</a></li>
{% endfor %}
</ul>
I am only using generic_views.
This is list of mobile phone models. I want to remember the users mobile model in the cookie.
A:
Generic views are simple views that handle a couple of common cases, for example rendering a template when no view logic is needed. In your case, you want to add functionality to your view (i.e. setting a cookie) so you will need to write your custom view. In addition, you should not add view logic in your urls.py (the queryset call), this belongs in views.py
So the process flow could look like:
1) Show mobile phone models in template using a form.
2) When user selects phone model from dropdown menu (or something similar) send phone model to a function in views.py
3) This function receives the phone model and responds with a cookie containing the phone model.
However, I am not quite sure why you would want to store the phone model in a cookie.
|
django python - generic views and cookies
|
I made in my web a menu using generic_view - simple 'django.views.generic.list_detail.object_list' in urls.py file.
I would like to set a cookies each time when user chooses one of element of this list [HttpResponse.set_cookie(...)].
What is the best solution? Should I write function in views.py or have you got more simple solution?
Edit 1
This is the fragment of my urls.py:
manufacturer_dict = {
'queryset': Manufacturer.objects.all()
}
urlpatterns = patterns('',
url(r'^$', 'django.views.generic.list_detail.object_list', manufacturer_dict),
)
And template: manufacturer_list.html
<ul>
{% for object in object_list %}
<li><a href="{{object.get_absolute_url}}" title="{{object.name}}">{{object.name}}</a></li>
{% endfor %}
</ul>
I am only using generic_views.
This is list of mobile phone models. I want to remember the users mobile model in the cookie.
|
[
"Generic views are simple views that handle a couple of common cases, for example rendering a template when no view logic is needed. In your case, you want to add functionality to your view (i.e. setting a cookie) so you will need to write your custom view. In addition, you should not add view logic in your urls.py (the queryset call), this belongs in views.py\nSo the process flow could look like:\n1) Show mobile phone models in template using a form. \n2) When user selects phone model from dropdown menu (or something similar) send phone model to a function in views.py \n3) This function receives the phone model and responds with a cookie containing the phone model. \nHowever, I am not quite sure why you would want to store the phone model in a cookie. \n"
] |
[
1
] |
[] |
[] |
[
"django",
"django_generic_views",
"python"
] |
stackoverflow_0002408514_django_django_generic_views_python.txt
|
Q:
How do I do this regex in Python?
Suppose I have a string of text, of all characters Latin-based. With punctuation.
How do I "find" all the characters and put <strong> tags around it?
hay = The fox jumped up the tree.
needle = "umpe"
In this case, part of the word "jumped" would be highlighted.
A:
Without regex (may be a bit more verbose but also easier to understand):
hay = "The fox jumped up the tree."
needle = "umpe"
print hay.replace(needle, "<strong>%s<strong>" % needle)
EDIT after extra specification: if you want case insensitive replace (which a regular string replace can't do):
import re
hay = "The fox jUMPed up the tree."
needle = "umpe"
regex = re.compile('(%s)' % needle, re.I)
print regex.sub('<strong>\\1</strong>', hay)
A:
Using regular expressions on a simple search expression like this is overkill. However, in case you need a more complicated search, I referenced Python's re module documentation to put together the code below, which I think does what you want:
#!/usr/bin/env python
import re
haystack = "The fox jumped up the tree."
needle = "umpe"
new_text = "<strong>" + needle + "</strong>"
new_haystack = re.sub(needle, new_text, haystack)
print new_haystack
A:
Your question is not very clear. If you want to highlight the words that have needle in them you can match
\b(\w*needle\w*)\b
and replace it with
<strong>\1<strong>
A:
No regex used in this case, but will work for smaller strings.
hay = "The fox jumped up the tree."
needle = "umpe"
hay_lower = hey.lower()
found = []
curr_find = hay_lower.find(needle.lower())
found.append(curr_find)
hay_list = list(hay)
while(curr_find):
curr_find = hay_lower.find(needle.lower(), curr_find)
for found_index in found:
hay_list[found_index:found_index+len(needle)] = '<strong>%s</strong>' % needle
result = ''.join(hay_list)
A:
This should work:
pattern = r'(?P<needle>(umpe))'
pat_obj = re.compile(pattern)
new_text = pat_obj.sub(r'<strong>\g<needle></strong>', hay)
The result rendered in HTML: The fox jumped up the tree.
In the snippet above, i've used the re method 'sub' and referenced a captured group (which i called 'needle').
|
How do I do this regex in Python?
|
Suppose I have a string of text, of all characters Latin-based. With punctuation.
How do I "find" all the characters and put <strong> tags around it?
hay = The fox jumped up the tree.
needle = "umpe"
In this case, part of the word "jumped" would be highlighted.
|
[
"Without regex (may be a bit more verbose but also easier to understand):\nhay = \"The fox jumped up the tree.\"\nneedle = \"umpe\"\n\nprint hay.replace(needle, \"<strong>%s<strong>\" % needle)\n\nEDIT after extra specification: if you want case insensitive replace (which a regular string replace can't do):\nimport re\n\nhay = \"The fox jUMPed up the tree.\"\nneedle = \"umpe\"\n\nregex = re.compile('(%s)' % needle, re.I)\nprint regex.sub('<strong>\\\\1</strong>', hay)\n\n",
"Using regular expressions on a simple search expression like this is overkill. However, in case you need a more complicated search, I referenced Python's re module documentation to put together the code below, which I think does what you want:\n#!/usr/bin/env python\nimport re\nhaystack = \"The fox jumped up the tree.\"\nneedle = \"umpe\"\nnew_text = \"<strong>\" + needle + \"</strong>\"\nnew_haystack = re.sub(needle, new_text, haystack)\nprint new_haystack\n\n",
"Your question is not very clear. If you want to highlight the words that have needle in them you can match\n\\b(\\w*needle\\w*)\\b\n\nand replace it with\n<strong>\\1<strong>\n\n",
"No regex used in this case, but will work for smaller strings.\nhay = \"The fox jumped up the tree.\"\nneedle = \"umpe\"\n\nhay_lower = hey.lower()\nfound = []\ncurr_find = hay_lower.find(needle.lower())\nfound.append(curr_find)\nhay_list = list(hay)\n\nwhile(curr_find):\n curr_find = hay_lower.find(needle.lower(), curr_find)\n\nfor found_index in found:\n hay_list[found_index:found_index+len(needle)] = '<strong>%s</strong>' % needle\n\nresult = ''.join(hay_list)\n\n",
"This should work:\npattern = r'(?P<needle>(umpe))'\npat_obj = re.compile(pattern)\nnew_text = pat_obj.sub(r'<strong>\\g<needle></strong>', hay)\n\nThe result rendered in HTML: The fox jumped up the tree.\nIn the snippet above, i've used the re method 'sub' and referenced a captured group (which i called 'needle').\n"
] |
[
4,
3,
1,
1,
1
] |
[] |
[] |
[
"python",
"regex"
] |
stackoverflow_0002409636_python_regex.txt
|
Q:
Python: How expensive is to create a small list many times?
I encounter the following small annoying dilemma over and over again in Python:
Option 1:
cleaner but slower(?) if called many times since a_list get re-created for each call of do_something()
def do_something():
a_list = ["any", "think", "whatever"]
# read something from a_list
Option 2:
Uglier but more efficient (spare the a_list creation all over again)
a_list = ["any", "think", "whatever"]
def do_something():
# read something from a_list
What do you think?
A:
What's ugly about it?
Are the contents of the list always constants, as in your example? If so: recent versions of Python (since 2.4) will optimise that by evaluating the constant expression and keeping the result but only if it's a tuple. So you could change it to being a tuple. Or you could stop worrying about small things like that.
Here's a list of constants and a tuple of constants:
>>> def afunc():
... a = ['foo', 'bar', 'zot']
... b = ('oof', 'rab', 'toz')
... return
...
>>> import dis; dis.dis(afunc)
2 0 LOAD_CONST 1 ('foo')
3 LOAD_CONST 2 ('bar')
6 LOAD_CONST 3 ('zot')
9 BUILD_LIST 3
12 STORE_FAST 0 (a)
3 15 LOAD_CONST 7 (('oof', 'rab', 'toz'))
18 STORE_FAST 1 (b)
4 21 LOAD_CONST 0 (None)
24 RETURN_VALUE
>>>
A:
Never create something more than once if you don't have to. This is a simply optimization that can be done on your part and I personally do not find the second example ugly at all.
Some may argue not to worry about optimizing little things like this but I feel that something this simple to fix should be done immediately. I would hate to see your application create multiple copies of anything that it doesn't need to simply to preserve an arbitrary sense of "code beauty". :)
A:
Option 3:
def do_something(a_list = ("any", "think", "whatever")):
read something from a_list
Option 3 compared to Option 1:
Both are equally readable in my opinion (though some seem to think differently in the comments! :-) ). You could even write Option 3 like this
def do_something(
a_list = ("any", "think", "whatever")):
read something from a_list
which really minimizes the difference in terms of readability.
Unlike Option 1, however, Option 3 defines a_list only once -- at the time when do_something is defined. That's exactly what we want.
Option 3 compared to Option 2:
Avoid global variables if possible. Option 3 allows you to do that.
Also, with Option 2, over time or if other people maintain this code, the definition of a_list could get separated from def do_something. This may not be a big deal, but I think it is somewhat undesireable.
A:
if your a_list doesn't change, move it out of the function.
A:
You have some data
You have a method associated with it
You don't want to keep the data globally just for the sake of optimising the speed of the method unless you have to.
I think this is what classes are for.
class Processor:
def __init__(this):
this.data = "any thing whatever".split()
def fun(this,arg):
# do stuff with arg and list
inst = Processor()
inst.fun("skippy)
Also, if you someday want to separate out the data into a file, you can just modify the constructor to do so.
A:
Well it seems it comes down to initializing the array in the function or not:
import time
def fun1():
a = ['any', 'think', 'whatever']
sum = 0
for i in range(100):
sum += i
def fun2():
sum = 0
for i in range(100):
sum += i
def test_fun(fun, times):
start = time.time()
for i in range(times):
fun()
end=time.time()
print "Function took %s" % (end-start)
# Test
print 'warming up'
test_fun(fun1, 100)
test_fun(fun2, 100)
print 'Testing fun1'
test_fun(fun1, 100000)
print 'Testing fun2'
test_fun(fun2, 100000)
print 'Again'
print 'Testing fun1'
test_fun(fun1, 100000)
print 'Testing fun2'
test_fun(fun2, 100000)
and the results:
>python test.py
warming up
Function took 0.000604152679443
Function took 0.000600814819336
Testing fun1
Function took 0.597407817841
Testing fun2
Function took 0.580779075623
Again
Testing fun1
Function took 0.595198154449
Testing fun2
Function took 0.580571889877
Looks like there is no difference.
A:
If the list is never modified, why do you use lists at all?
Without knowing your actual requirements, I'd recommend to simply use some if-statements to get rid of the list and the "read something from list" part completely.
A:
I've worked on automated systems that process 100,000,000+ records a day, where a 1% percent performance improvement is huge.
I learned a big lesson working on that system: Faster is better, but only when you know when it's fast enough.
A 1% improvement would have been a huge reduction in total processing time, but it isn't enough to effect when we would need our next hardware upgrade. My application was so fast, that the amount of time I spent trying to milk that last 1% probably cost more than a new server would have.
In your case, you would have to call do_something tens of thousands of times before making a significant difference in performance. In some cases that would make a difference, in other it won't.
|
Python: How expensive is to create a small list many times?
|
I encounter the following small annoying dilemma over and over again in Python:
Option 1:
cleaner but slower(?) if called many times since a_list get re-created for each call of do_something()
def do_something():
a_list = ["any", "think", "whatever"]
# read something from a_list
Option 2:
Uglier but more efficient (spare the a_list creation all over again)
a_list = ["any", "think", "whatever"]
def do_something():
# read something from a_list
What do you think?
|
[
"What's ugly about it?\nAre the contents of the list always constants, as in your example? If so: recent versions of Python (since 2.4) will optimise that by evaluating the constant expression and keeping the result but only if it's a tuple. So you could change it to being a tuple. Or you could stop worrying about small things like that.\nHere's a list of constants and a tuple of constants:\n>>> def afunc():\n... a = ['foo', 'bar', 'zot']\n... b = ('oof', 'rab', 'toz')\n... return\n...\n>>> import dis; dis.dis(afunc)\n 2 0 LOAD_CONST 1 ('foo')\n 3 LOAD_CONST 2 ('bar')\n 6 LOAD_CONST 3 ('zot')\n 9 BUILD_LIST 3\n 12 STORE_FAST 0 (a)\n\n 3 15 LOAD_CONST 7 (('oof', 'rab', 'toz'))\n 18 STORE_FAST 1 (b)\n\n 4 21 LOAD_CONST 0 (None)\n 24 RETURN_VALUE\n>>>\n\n",
"Never create something more than once if you don't have to. This is a simply optimization that can be done on your part and I personally do not find the second example ugly at all.\nSome may argue not to worry about optimizing little things like this but I feel that something this simple to fix should be done immediately. I would hate to see your application create multiple copies of anything that it doesn't need to simply to preserve an arbitrary sense of \"code beauty\". :)\n",
"Option 3: \ndef do_something(a_list = (\"any\", \"think\", \"whatever\")):\n read something from a_list\n\nOption 3 compared to Option 1:\nBoth are equally readable in my opinion (though some seem to think differently in the comments! :-) ). You could even write Option 3 like this\ndef do_something(\n a_list = (\"any\", \"think\", \"whatever\")):\n read something from a_list\n\nwhich really minimizes the difference in terms of readability. \nUnlike Option 1, however, Option 3 defines a_list only once -- at the time when do_something is defined. That's exactly what we want.\nOption 3 compared to Option 2:\nAvoid global variables if possible. Option 3 allows you to do that.\nAlso, with Option 2, over time or if other people maintain this code, the definition of a_list could get separated from def do_something. This may not be a big deal, but I think it is somewhat undesireable.\n",
"if your a_list doesn't change, move it out of the function.\n",
"\nYou have some data\nYou have a method associated with it\nYou don't want to keep the data globally just for the sake of optimising the speed of the method unless you have to.\n\nI think this is what classes are for.\nclass Processor:\n def __init__(this):\n this.data = \"any thing whatever\".split()\n def fun(this,arg):\n # do stuff with arg and list\n\ninst = Processor()\ninst.fun(\"skippy)\n\nAlso, if you someday want to separate out the data into a file, you can just modify the constructor to do so.\n",
"Well it seems it comes down to initializing the array in the function or not:\nimport time\ndef fun1():\n a = ['any', 'think', 'whatever']\n sum = 0\n for i in range(100):\n sum += i\n\ndef fun2():\n sum = 0\n for i in range(100):\n sum += i\n\n\ndef test_fun(fun, times):\n start = time.time()\n for i in range(times):\n fun()\n end=time.time()\n print \"Function took %s\" % (end-start)\n\n# Test\nprint 'warming up'\ntest_fun(fun1, 100)\ntest_fun(fun2, 100)\n\nprint 'Testing fun1'\ntest_fun(fun1, 100000)\nprint 'Testing fun2'\ntest_fun(fun2, 100000)\n\nprint 'Again'\nprint 'Testing fun1'\ntest_fun(fun1, 100000)\nprint 'Testing fun2'\ntest_fun(fun2, 100000)\n\nand the results:\n>python test.py\nwarming up\nFunction took 0.000604152679443\nFunction took 0.000600814819336\nTesting fun1\nFunction took 0.597407817841\nTesting fun2\nFunction took 0.580779075623\nAgain\nTesting fun1\nFunction took 0.595198154449\nTesting fun2\nFunction took 0.580571889877\n\nLooks like there is no difference.\n",
"If the list is never modified, why do you use lists at all?\nWithout knowing your actual requirements, I'd recommend to simply use some if-statements to get rid of the list and the \"read something from list\" part completely.\n",
"I've worked on automated systems that process 100,000,000+ records a day, where a 1% percent performance improvement is huge. \nI learned a big lesson working on that system: Faster is better, but only when you know when it's fast enough.\nA 1% improvement would have been a huge reduction in total processing time, but it isn't enough to effect when we would need our next hardware upgrade. My application was so fast, that the amount of time I spent trying to milk that last 1% probably cost more than a new server would have.\nIn your case, you would have to call do_something tens of thousands of times before making a significant difference in performance. In some cases that would make a difference, in other it won't.\n"
] |
[
16,
4,
4,
3,
2,
1,
0,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002409472_python.txt
|
Q:
How to separate comma separated data from csv file?
I have opened a csv file and I want to sort each string which is comma separated and are in same line:
ex:: file :
name,sal,dept
tom,10000,it
o/p :: each string in string variable
I have a file which is already open, so I can not use "open" API, I have to use "csv.reader" which have to read one line at a time.
A:
If the file open for reading is bound to a variable name, say fin; and assuming you're using Python 2.6, and you know the file's not empty (has at least the row with headers):
import csv
rd = csv.reader(fin)
headers = next(rd)
for data in rd:
...process data and headers...
In Python 2.5, use headers = rd.next() instead of headers = next(rd).
These versions use a list of fields data, which is a completely general solution (i.e., you don't need to know in advance how many columns the file has: you'll access them as data[0], data[1], etc, and the current row has len(data) fields at each leg of the loop).
If you know the file has exactly three columns and prefer to use separate names for a variable per column, change the loop header to:
for name, sales, department in rd:
The field data as returned by the reader (just like the headers) are all strings. If you know for example that the second column is an int and want to treat it as such, start the loop with
for data in rd:
data[1] = int(data[1])
or, if you're using the named-variables variant:
for name, sales, department in rd:
sales = int(sales)
A:
I don't know if I have properly understood your question. You may want to have a look at the split function described in the Python documentation anyway.
|
How to separate comma separated data from csv file?
|
I have opened a csv file and I want to sort each string which is comma separated and are in same line:
ex:: file :
name,sal,dept
tom,10000,it
o/p :: each string in string variable
I have a file which is already open, so I can not use "open" API, I have to use "csv.reader" which have to read one line at a time.
|
[
"If the file open for reading is bound to a variable name, say fin; and assuming you're using Python 2.6, and you know the file's not empty (has at least the row with headers):\n import csv\n\n rd = csv.reader(fin)\n headers = next(rd)\n for data in rd:\n ...process data and headers...\n\nIn Python 2.5, use headers = rd.next() instead of headers = next(rd).\nThese versions use a list of fields data, which is a completely general solution (i.e., you don't need to know in advance how many columns the file has: you'll access them as data[0], data[1], etc, and the current row has len(data) fields at each leg of the loop).\nIf you know the file has exactly three columns and prefer to use separate names for a variable per column, change the loop header to:\n for name, sales, department in rd:\n\nThe field data as returned by the reader (just like the headers) are all strings. If you know for example that the second column is an int and want to treat it as such, start the loop with\n for data in rd:\n data[1] = int(data[1])\n\nor, if you're using the named-variables variant:\n for name, sales, department in rd:\n sales = int(sales)\n\n",
"I don't know if I have properly understood your question. You may want to have a look at the split function described in the Python documentation anyway.\n"
] |
[
2,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002408338_python.txt
|
Q:
Where to put the separation between a stateful object and a stateless calculation in Python?
Which of the following code snippets is the most "pythonic"? The calculation is trivial in this example but could be assumed to be complex in real life.
class A(object):
"""Freely mix state and calcs - no good I presume"""
def __init__(self, state):
self.state = state
def calc_with_state(self, x):
return (self.state + x)**2
or
class B(object):
"""Separate state from calc by a static method"""
@staticmethod
def inner_calc(u, v):
return (u + v)**2
def __init__(self, state):
self.state = state
def calc_with_state(self, x):
return B.inner_calc(self.state, x)
or
class C(object):
"""Break out the calculation in a free function"""
def __init__(self, state):
self.state = state
def calc_with_state(self, x):
return outer_calc(self.state, x)
def outer_calc(u, v):
return (u + v)**2
A:
As written, A, by a longshot. The issue, quite simply, is
Flat is better than nested.
Look: separating state from calculations is a good design principle, but it doesn't mean what you think, at least not what I can infer you think from this example. We want to make sure that state doesn't change in order to complete calculations if that state isn't going to be reinitialized on the next calculation. If state is read-only with respect to some particular calculation, there's no stylistic compulsion to redirect around it so that you don't directly read it. That is, unless the calculation and the state are sufficiently complex to need separate unit testing. Then, by all means, B or C will be preferred, but only if it is really that much easier to create values for u than to instantiate fresh instances of A.
A:
I think it depends on your particular project. Is cal_with_state only applicable to this particular class or is the method needs to be shared among many different objects? Do different classes share it?
There is nothing more or less pythonic about any of this approaches, use the one that will satisfy your project. DRY is beyond pythonicity.
A:
Factoring out the calculation, whether in a static or global method doesn't offer any benefit with regards to the state awareness. The only slight advantage is that the code explicitly shows which of the object's stateful properties are taken into account in the calculation (show at the level of the function call, rather than having to be read within the logic of the method in the class A)
There may be other advantages to introducing stateless (static, global) or instance methods:
reusability
code readability and management at large
but as said, these constructs do not help with regards to state management per-se. The A approach seems quite legitimate (and pythonic) to me. Indeed David Berger beat us to it, in reminding us that...
Flat is better than nested! .
A:
Personally I would say it depends on resusability. If the calculation is one that might be used with other objects (as it does look to be) then the third example is the most reusable. If the calculation is completely tied to the object or would never be reused then the first example. I'd say the second example is wrong in most cases.
A:
What is wrong with A? It does the calculation in one place only and does not modify the state so calc_with_state is a method that does not change state so is a 'simple' behaviour. If the state was complex it stops a large number of parameters being passed into the calculation function.
However if the calculation can be written taking the state as a parameter (as in C) then you can separate out the calculation. benefits here include being able to rues this calculation on data not in the class C and also you can use the function as data passed to C so calc_with_state can be made to call different calculation functions
I can't see B having any benefits as inner_calc does not make use of the class and so could just as well be a free function.
So I would probably write it as A first and then if wanting to reuse the calculation, make the class use different calculations or just if the code of the calculation got too big you could refactor into class C
|
Where to put the separation between a stateful object and a stateless calculation in Python?
|
Which of the following code snippets is the most "pythonic"? The calculation is trivial in this example but could be assumed to be complex in real life.
class A(object):
"""Freely mix state and calcs - no good I presume"""
def __init__(self, state):
self.state = state
def calc_with_state(self, x):
return (self.state + x)**2
or
class B(object):
"""Separate state from calc by a static method"""
@staticmethod
def inner_calc(u, v):
return (u + v)**2
def __init__(self, state):
self.state = state
def calc_with_state(self, x):
return B.inner_calc(self.state, x)
or
class C(object):
"""Break out the calculation in a free function"""
def __init__(self, state):
self.state = state
def calc_with_state(self, x):
return outer_calc(self.state, x)
def outer_calc(u, v):
return (u + v)**2
|
[
"As written, A, by a longshot. The issue, quite simply, is \n\nFlat is better than nested.\n\nLook: separating state from calculations is a good design principle, but it doesn't mean what you think, at least not what I can infer you think from this example. We want to make sure that state doesn't change in order to complete calculations if that state isn't going to be reinitialized on the next calculation. If state is read-only with respect to some particular calculation, there's no stylistic compulsion to redirect around it so that you don't directly read it. That is, unless the calculation and the state are sufficiently complex to need separate unit testing. Then, by all means, B or C will be preferred, but only if it is really that much easier to create values for u than to instantiate fresh instances of A.\n",
"I think it depends on your particular project. Is cal_with_state only applicable to this particular class or is the method needs to be shared among many different objects? Do different classes share it?\nThere is nothing more or less pythonic about any of this approaches, use the one that will satisfy your project. DRY is beyond pythonicity.\n",
"Factoring out the calculation, whether in a static or global method doesn't offer any benefit with regards to the state awareness. The only slight advantage is that the code explicitly shows which of the object's stateful properties are taken into account in the calculation (show at the level of the function call, rather than having to be read within the logic of the method in the class A)\nThere may be other advantages to introducing stateless (static, global) or instance methods:\n\nreusability\ncode readability and management at large\n\nbut as said, these constructs do not help with regards to state management per-se. The A approach seems quite legitimate (and pythonic) to me. Indeed David Berger beat us to it, in reminding us that...\nFlat is better than nested! .\n",
"Personally I would say it depends on resusability. If the calculation is one that might be used with other objects (as it does look to be) then the third example is the most reusable. If the calculation is completely tied to the object or would never be reused then the first example. I'd say the second example is wrong in most cases.\n",
"What is wrong with A? It does the calculation in one place only and does not modify the state so calc_with_state is a method that does not change state so is a 'simple' behaviour. If the state was complex it stops a large number of parameters being passed into the calculation function.\nHowever if the calculation can be written taking the state as a parameter (as in C) then you can separate out the calculation. benefits here include being able to rues this calculation on data not in the class C and also you can use the function as data passed to C so calc_with_state can be made to call different calculation functions\nI can't see B having any benefits as inner_calc does not make use of the class and so could just as well be a free function.\nSo I would probably write it as A first and then if wanting to reuse the calculation, make the class use different calculations or just if the code of the calculation got too big you could refactor into class C\n"
] |
[
6,
1,
1,
0,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002410265_python.txt
|
Q:
Python: how to switch between workspaces using Xlib?
How do I switch between my window manager's workspaces using Python with Xlib module?
This is my most promising attempt:
#!/usr/bin/python
from Xlib import X, display, error, Xatom, Xutil
import Xlib.protocol.event
screen = Xlib.display.Display().screen()
root = screen.root
def sendEvent(win, ctype, data, mask=None):
""" Send a ClientMessage event to the root """
data = (data+[0]*(5-len(data)))[:5]
ev = Xlib.protocol.event.ClientMessage(window=win, client_type=ctype, data=(32,(data)))
if not mask:
mask = (X.SubstructureRedirectMask|X.SubstructureNotifyMask)
root.send_event(ev, event_mask=mask)
# switch to desktop 2
sendEvent(root, Xlib.display.Display().intern_atom("_NET_CURRENT_DESKTOP"), [2])
The above code is shamelessly stolen from various places in the PyPanel source; unfortunately, it doesn't do anything, not even generate a warning / exception. Am I missing something here?
I'm using Python and PyGTK. Xlib seems to be the right choice for switching desktops. I don't intend to use wnck (buggy Python module) or similar, but I'd appreciate any pointers anyway.
I might add that this is my first attempt at writing a Python application using Xlib (or PyGTK).
A:
Apparently you need to work on the same Display object and then flush it at the end. Something like:
display = Xlib.display.Display()
screen = display.screen()
root = screen.root
# ...
sendEvent(root, display.intern_atom("_NET_CURRENT_DESKTOP"), [1, X.CurrentTime])
display.flush()
Credit: Idea from a very similar thread (which almost works).
P.S. By the way, the desktop number starts from 0.
|
Python: how to switch between workspaces using Xlib?
|
How do I switch between my window manager's workspaces using Python with Xlib module?
This is my most promising attempt:
#!/usr/bin/python
from Xlib import X, display, error, Xatom, Xutil
import Xlib.protocol.event
screen = Xlib.display.Display().screen()
root = screen.root
def sendEvent(win, ctype, data, mask=None):
""" Send a ClientMessage event to the root """
data = (data+[0]*(5-len(data)))[:5]
ev = Xlib.protocol.event.ClientMessage(window=win, client_type=ctype, data=(32,(data)))
if not mask:
mask = (X.SubstructureRedirectMask|X.SubstructureNotifyMask)
root.send_event(ev, event_mask=mask)
# switch to desktop 2
sendEvent(root, Xlib.display.Display().intern_atom("_NET_CURRENT_DESKTOP"), [2])
The above code is shamelessly stolen from various places in the PyPanel source; unfortunately, it doesn't do anything, not even generate a warning / exception. Am I missing something here?
I'm using Python and PyGTK. Xlib seems to be the right choice for switching desktops. I don't intend to use wnck (buggy Python module) or similar, but I'd appreciate any pointers anyway.
I might add that this is my first attempt at writing a Python application using Xlib (or PyGTK).
|
[
"Apparently you need to work on the same Display object and then flush it at the end. Something like:\ndisplay = Xlib.display.Display()\nscreen = display.screen()\nroot = screen.root\n\n# ...\n\nsendEvent(root, display.intern_atom(\"_NET_CURRENT_DESKTOP\"), [1, X.CurrentTime])\ndisplay.flush()\n\nCredit: Idea from a very similar thread (which almost works).\nP.S. By the way, the desktop number starts from 0.\n"
] |
[
5
] |
[] |
[] |
[
"pygtk",
"python",
"window",
"xlib"
] |
stackoverflow_0002405738_pygtk_python_window_xlib.txt
|
Q:
GAE db.Model getting property instead of a string value
I have a db.Model which has a string property on it, email_type. Now I've the values for type defined in a readonly class. When I save this to the datastore I get the string instead of "Register", it also raises a BadValueError. How do I get it to save as a string, not as a property.
Here's the (slimmed down) code:
class EmailTypes(object):
def __init__(self):
self.__reg = "Register"
self.__news = "NewsLetter"
@property
def Register(self):
return self.__reg
@property
def NewsLetter(self):
return self.__news
class Email(db.Model):
to = db.StringProperty()
email_type = db.StringProperty()
class Example(object)
def do_stuff(self):
e = Email()
e.to = 'phil@somedomain.com'
# This should be saving as 'Register' not a ref to the objects address
e.email_type = EmailTypes().Register
do = Example()
do.do_stuff()
A:
What happens if you change your EmailTypes class to look like this:
class EmailTypes(object):
Register = 'Register'
NewsLetter = 'NewsLetter'
and use it like:
e.email_type = EmailTypes.Register
Does that make your simplified example work?
|
GAE db.Model getting property instead of a string value
|
I have a db.Model which has a string property on it, email_type. Now I've the values for type defined in a readonly class. When I save this to the datastore I get the string instead of "Register", it also raises a BadValueError. How do I get it to save as a string, not as a property.
Here's the (slimmed down) code:
class EmailTypes(object):
def __init__(self):
self.__reg = "Register"
self.__news = "NewsLetter"
@property
def Register(self):
return self.__reg
@property
def NewsLetter(self):
return self.__news
class Email(db.Model):
to = db.StringProperty()
email_type = db.StringProperty()
class Example(object)
def do_stuff(self):
e = Email()
e.to = 'phil@somedomain.com'
# This should be saving as 'Register' not a ref to the objects address
e.email_type = EmailTypes().Register
do = Example()
do.do_stuff()
|
[
"What happens if you change your EmailTypes class to look like this:\nclass EmailTypes(object):\n Register = 'Register'\n NewsLetter = 'NewsLetter'\n\nand use it like:\ne.email_type = EmailTypes.Register\n\nDoes that make your simplified example work?\n"
] |
[
3
] |
[] |
[] |
[
"google_app_engine",
"python"
] |
stackoverflow_0002411138_google_app_engine_python.txt
|
Q:
Template extraction in python/php
Are there existing template extract libraries in either python or php? Perl has Template::Extract, but I haven't been able to find a similar implementation in either python or php.
The only thing close in python that I could find is TemplateMaker (http://code.google.com/p/templatemaker/), but that's not really a template extraction library.
A:
After digging around some more I found a solution to exactly what I was looking for. filippo posted a list of python solutions for screen scraping in this post: Options for HTML scraping? among which is a package called scrapemark ( http://arshaw.com/scrapemark/ ).
Hope this helps anyone else who is looking for the same solution.
A:
TmeplateMaker does seem to do what you need, at least according to its documentation. Instead of receiving a template as an input, it infers ("learns") if from a few documents. Then, it has the extract method to extract the data from other documents that were created with this template.
The example shows:
# Now that we have a template, let's extract some data.
>>> t.extract('<b>red and green</b>')
('red', 'green')
>>> t.extract('<b>django and stephane</b>')
('django', 'stephane')
# The extract() method is very literal. It doesn't magically trim
# whitespace, nor does it have any knowledge of markup languages such as
# HTML.
>>> t.extract('<b> spacy and <u>underlined</u></b>')
(' spacy ', '<u>underlined</u>')
# The extract() method will raise the NoMatch exception if the data
# doesn't match the template. In this example, the data doesn't have the
# leading and trailing "<b>" tags.
>>> t.extract('this and that')
Traceback (most recent call last):
...
So, to achieve the task you require, I think you should:
Give it a few documents rendered from your template - it will have no trouble inferring the template from them.
Use the inferred template to extract data from new documents.
Come to think about it, it's even more useful than Perl's Template::Extract as it doesn't expect you to provide it a clean template - it learns it on its own from sample text.
A:
Here is an interesting discussion from Adrian the author of TemplateMaker http://www.holovaty.com/writing/templatemaker/
It seems to be a lot like what I would call a wrapper induction library.
If your looking for something else that is more configurable (less for scraping) take a look at lxml.html and BeautifulSoup, also for python.
|
Template extraction in python/php
|
Are there existing template extract libraries in either python or php? Perl has Template::Extract, but I haven't been able to find a similar implementation in either python or php.
The only thing close in python that I could find is TemplateMaker (http://code.google.com/p/templatemaker/), but that's not really a template extraction library.
|
[
"After digging around some more I found a solution to exactly what I was looking for. filippo posted a list of python solutions for screen scraping in this post: Options for HTML scraping? among which is a package called scrapemark ( http://arshaw.com/scrapemark/ ).\nHope this helps anyone else who is looking for the same solution.\n",
"TmeplateMaker does seem to do what you need, at least according to its documentation. Instead of receiving a template as an input, it infers (\"learns\") if from a few documents. Then, it has the extract method to extract the data from other documents that were created with this template.\nThe example shows:\n# Now that we have a template, let's extract some data.\n>>> t.extract('<b>red and green</b>')\n('red', 'green')\n>>> t.extract('<b>django and stephane</b>')\n('django', 'stephane')\n\n# The extract() method is very literal. It doesn't magically trim\n# whitespace, nor does it have any knowledge of markup languages such as\n# HTML.\n>>> t.extract('<b> spacy and <u>underlined</u></b>')\n(' spacy ', '<u>underlined</u>')\n\n# The extract() method will raise the NoMatch exception if the data\n# doesn't match the template. In this example, the data doesn't have the\n# leading and trailing \"<b>\" tags.\n>>> t.extract('this and that')\nTraceback (most recent call last):\n...\n\nSo, to achieve the task you require, I think you should:\n\nGive it a few documents rendered from your template - it will have no trouble inferring the template from them.\nUse the inferred template to extract data from new documents.\n\nCome to think about it, it's even more useful than Perl's Template::Extract as it doesn't expect you to provide it a clean template - it learns it on its own from sample text.\n",
"Here is an interesting discussion from Adrian the author of TemplateMaker http://www.holovaty.com/writing/templatemaker/\nIt seems to be a lot like what I would call a wrapper induction library.\nIf your looking for something else that is more configurable (less for scraping) take a look at lxml.html and BeautifulSoup, also for python.\n"
] |
[
2,
1,
0
] |
[] |
[] |
[
"extract",
"php",
"python",
"templates"
] |
stackoverflow_0002152786_extract_php_python_templates.txt
|
Q:
pymssql connect function
i have this function
pymssql.connect(host="my host",user="my user",password="my pass",database="mydb")
I want to read the user and password from the user and put them there is that possible or named arguments lvalue should not be variable and if yes then how could i do that ?
i.e is it possible to call this function like:
pymssql,connect(host=varaible,...)
A:
Your question is worded... strangely. Are you having trouble with setting default arguments in a function definition?
>>> def f(arg1="hello", arg2="goodbye"):
print "arg1 is", arg1
print "arg2 is", arg2
>>> f()
arg1 is hello
arg2 is goodbye
>>> f(arg2="two")
arg1 is hello
arg2 is two
>>> f(1,2)
arg1 is 1
arg2 is 2
>>> f(arg2="foo", arg1="bar")
arg1 is bar
arg2 is foo
If that wasn't what you were looking for, did you want to prompt the user for a missing argument?
>>> def g(arg=None):
if arg is None:
arg = raw_input("What is the argument?")
print "The argument was", arg
>>> g(123)
The argument was 123
>>> g()
What is the argument? foo bar
The argument was foo bar
Using a sentinel value of None for a missing argument is the idiomatic way in Python to detect a missing argument and execute another function.
A:
To read input in from the user you can use raw_input.
To use the command line arguments of the program you have to import sys and use sys.argv
for example:
import sys
myvar = raw_input("please input a var") #prompts the user for a value
myvar2 = sys.argv[1] #gets the first argument to the program
you can then use the named args like
myfun(named=myvar, named2=myvar2)
|
pymssql connect function
|
i have this function
pymssql.connect(host="my host",user="my user",password="my pass",database="mydb")
I want to read the user and password from the user and put them there is that possible or named arguments lvalue should not be variable and if yes then how could i do that ?
i.e is it possible to call this function like:
pymssql,connect(host=varaible,...)
|
[
"Your question is worded... strangely. Are you having trouble with setting default arguments in a function definition? \n>>> def f(arg1=\"hello\", arg2=\"goodbye\"):\n print \"arg1 is\", arg1\n print \"arg2 is\", arg2\n\n\n>>> f()\narg1 is hello\narg2 is goodbye\n>>> f(arg2=\"two\")\narg1 is hello\narg2 is two\n>>> f(1,2)\narg1 is 1\narg2 is 2\n>>> f(arg2=\"foo\", arg1=\"bar\")\narg1 is bar\narg2 is foo\n\nIf that wasn't what you were looking for, did you want to prompt the user for a missing argument? \n>>> def g(arg=None):\n if arg is None:\n arg = raw_input(\"What is the argument?\")\n print \"The argument was\", arg\n\n\n>>> g(123)\nThe argument was 123\n>>> g()\nWhat is the argument? foo bar\nThe argument was foo bar\n\nUsing a sentinel value of None for a missing argument is the idiomatic way in Python to detect a missing argument and execute another function.\n",
"To read input in from the user you can use raw_input.\nTo use the command line arguments of the program you have to import sys and use sys.argv\nfor example:\nimport sys\nmyvar = raw_input(\"please input a var\") #prompts the user for a value\nmyvar2 = sys.argv[1] #gets the first argument to the program\n\nyou can then use the named args like\nmyfun(named=myvar, named2=myvar2)\n\n"
] |
[
3,
0
] |
[] |
[] |
[
"python",
"sql_server"
] |
stackoverflow_0002411203_python_sql_server.txt
|
Q:
Function to create in-memory zip file and return as http response
I am avoiding the creation of files on disk, this is what I have got so far:
def get_zip(request):
import zipfile, StringIO
i = open('picture.jpg', 'rb').read()
o = StringIO.StringIO()
zf = zipfile.ZipFile(o, mode='w')
zf.writestr('picture.jpg', i)
zf.close()
o.seek(0)
response = HttpResponse(o.read())
o.close()
response['Content-Type'] = 'application/octet-stream'
response['Content-Disposition'] = "attachment; filename=\"picture.zip\""
return response
Do you think is correct-elegant-pythonic enough? Any better way to do it?
Thanks!
A:
For StringIO you should generally use o.getvalue() to get the result. Also, if you want to add a normal file to the zip file, you can use zf.write('picture.jpg'). You don't need to manually read it.
A:
Avoiding disk files can slow your server to a crawl, but it will certainly work.
You'll exhaust memory if you serve too many of these requests concurrently.
|
Function to create in-memory zip file and return as http response
|
I am avoiding the creation of files on disk, this is what I have got so far:
def get_zip(request):
import zipfile, StringIO
i = open('picture.jpg', 'rb').read()
o = StringIO.StringIO()
zf = zipfile.ZipFile(o, mode='w')
zf.writestr('picture.jpg', i)
zf.close()
o.seek(0)
response = HttpResponse(o.read())
o.close()
response['Content-Type'] = 'application/octet-stream'
response['Content-Disposition'] = "attachment; filename=\"picture.zip\""
return response
Do you think is correct-elegant-pythonic enough? Any better way to do it?
Thanks!
|
[
"For StringIO you should generally use o.getvalue() to get the result. Also, if you want to add a normal file to the zip file, you can use zf.write('picture.jpg'). You don't need to manually read it.\n",
"Avoiding disk files can slow your server to a crawl, but it will certainly work.\nYou'll exhaust memory if you serve too many of these requests concurrently.\n"
] |
[
12,
4
] |
[] |
[] |
[
"python",
"stringio",
"zip"
] |
stackoverflow_0002411514_python_stringio_zip.txt
|
Q:
How to get an item from a set of Queues?
Say there are two empty Queues. Is there a way to get an item from the queue that gets it first?
So I have a queue of high anonymous proxies, queues of anonymous and transparent ones. Some threads may need only high anon. proxies, while others may accept both high anon. and just anon. proxies. That's why I can't put them all to a single queue.
A:
You could check both queues in turn, each time using a short timeout. That way you would most likely read from the first queue that receives data. However, this solution is prone to race conditions if you will be getting many items on a regular basis.
If that is the case, do you have a good reason for not just writing data to one queue?
A:
If I had this problem (and "polling", i.e. trying each queue alternately with short timeouts, was unacceptable -- it usually is, being very wasteful of CPU time etc), I would tackle it by designing a "multiqueue" object -- one with multiple condition variables, one per "subqueue" and an overall one. A put to any subqueue would signal that subqueue's specific condition variable as well as the overall one; a get from a specific subqueue would only wait on its specific condition variable, but there would also be a "get from any subqueue" which waits on the overall condition variable instead. (If more combinations than "get from this specific subqueue" or "get from any subqueue" need to be supported, just as many condition variables as combinations to support would be needed).
It would be much simpler to code if get and put were reduced to their bare bones (no timeouts, no no-waits, etc) and all subqueues used a single overall mutex (very small overhead wrt many mutexes, and much easier to code in a deadlock-free way;-). The subqueues could be exposed as "simplified queue-like duckies" to existing code which assumes it's dealing with a plain old queue (e.g. the multiqueue could support indexing to return proxy objects for the purpose).
With these assumptions, it wouldn't be much code, though it would be exceedingly tricky to write and inspect for correctness (alas, testing is of limited use when very subtle threading code is in play) -- I can't take the time for that right now, though I'd be glad to give it a try tonight (8 hours from now or so) if the assumptions are roughly correct and no other preferable answer has surfaced.
|
How to get an item from a set of Queues?
|
Say there are two empty Queues. Is there a way to get an item from the queue that gets it first?
So I have a queue of high anonymous proxies, queues of anonymous and transparent ones. Some threads may need only high anon. proxies, while others may accept both high anon. and just anon. proxies. That's why I can't put them all to a single queue.
|
[
"You could check both queues in turn, each time using a short timeout. That way you would most likely read from the first queue that receives data. However, this solution is prone to race conditions if you will be getting many items on a regular basis.\nIf that is the case, do you have a good reason for not just writing data to one queue?\n",
"If I had this problem (and \"polling\", i.e. trying each queue alternately with short timeouts, was unacceptable -- it usually is, being very wasteful of CPU time etc), I would tackle it by designing a \"multiqueue\" object -- one with multiple condition variables, one per \"subqueue\" and an overall one. A put to any subqueue would signal that subqueue's specific condition variable as well as the overall one; a get from a specific subqueue would only wait on its specific condition variable, but there would also be a \"get from any subqueue\" which waits on the overall condition variable instead. (If more combinations than \"get from this specific subqueue\" or \"get from any subqueue\" need to be supported, just as many condition variables as combinations to support would be needed).\nIt would be much simpler to code if get and put were reduced to their bare bones (no timeouts, no no-waits, etc) and all subqueues used a single overall mutex (very small overhead wrt many mutexes, and much easier to code in a deadlock-free way;-). The subqueues could be exposed as \"simplified queue-like duckies\" to existing code which assumes it's dealing with a plain old queue (e.g. the multiqueue could support indexing to return proxy objects for the purpose).\nWith these assumptions, it wouldn't be much code, though it would be exceedingly tricky to write and inspect for correctness (alas, testing is of limited use when very subtle threading code is in play) -- I can't take the time for that right now, though I'd be glad to give it a try tonight (8 hours from now or so) if the assumptions are roughly correct and no other preferable answer has surfaced.\n"
] |
[
0,
0
] |
[] |
[] |
[
"multithreading",
"python"
] |
stackoverflow_0002411306_multithreading_python.txt
|
Q:
Regex - Special alpha characters? - Python
I have a list of simple names such as Márquez,
because of the á (?< name >[a-zA-Z]+) doesn't seem to be working!
Help would be very much appreciated!
A:
you could use
\w+
with the unicode flag. I assume there's no risk of having digits or underscore in your names.
>>> re.findall('\w+', 'Márquez', re.U)
['Márquez']
You also seem to be missing P after the question mark: (?P< name >[a-zA-Z]+)
A:
For Python < 3 you may want to enable locale:
import locale
locale.setlocale(locale.LC_ALL, '')
And then use re.LOCALE option with your regexpes:
re.findall('\w+', 'Márquez', re.LOCALE)
Though, probably Unicode is the better way to go, though it requires decoding the data from and encoding it to your local encoding.
|
Regex - Special alpha characters? - Python
|
I have a list of simple names such as Márquez,
because of the á (?< name >[a-zA-Z]+) doesn't seem to be working!
Help would be very much appreciated!
|
[
"you could use \n\\w+\n\nwith the unicode flag. I assume there's no risk of having digits or underscore in your names.\n>>> re.findall('\\w+', 'Márquez', re.U)\n['Márquez']\n\nYou also seem to be missing P after the question mark: (?P< name >[a-zA-Z]+)\n",
"For Python < 3 you may want to enable locale:\nimport locale\nlocale.setlocale(locale.LC_ALL, '')\n\nAnd then use re.LOCALE option with your regexpes:\nre.findall('\\w+', 'Márquez', re.LOCALE)\n\nThough, probably Unicode is the better way to go, though it requires decoding the data from and encoding it to your local encoding.\n"
] |
[
3,
0
] |
[] |
[] |
[
"ascii",
"python",
"regex"
] |
stackoverflow_0002411759_ascii_python_regex.txt
|
Q:
Python Socket Send Buffer Vs. Str
I am trying to get a basic server (copied from Beginning Python) to send a str.
The error:
c.send( "XXX" )
TypeError: must be bytes or buffer, not str
It seems to work when pickling an object. All of the examples I found, seem to be able to send a string no problem.
Any help would be appreciated,
Stephen
import socket
import pickle
s = socket.socket()
host = socket.gethostname()
port = 80
s.bind((host, port))
s.listen(5)
while True:
c, addr = s.accept()
print( "Got Connection From ", addr )
data = pickle.dumps(c)
c.send( "XXX" )
#c.send(data)
c.close()
A:
It seems you try to use Python 2.x examples in Python 3 and you hit one of the main differences between those Python version.
For Python < 3 'strings' are in fact binary strings and 'unicode objects' are the right text objects (as they can contain any Unicode characters).
In Python 3 unicode strings are the 'regular strings' (str) and byte strings are separate objects.
Low level I/O can be done only with data (byte strings), not text (sequence of characters). For Python 2.x str was also the 'binary data' type. In Python 3 it is not any more and one of the special 'data' objects should be used. Objects are pickled to such byte strings. If you want to enter them manually in code use the "b" prefix (b"XXX" instead of "XXX").
A:
To add to Jacek Konieczny's answer: You can also use str.encode() to get bytes from a string. If you have the string in a variable instead of a literal, you can call encode and it will return an equivalent series of bytes.
|
Python Socket Send Buffer Vs. Str
|
I am trying to get a basic server (copied from Beginning Python) to send a str.
The error:
c.send( "XXX" )
TypeError: must be bytes or buffer, not str
It seems to work when pickling an object. All of the examples I found, seem to be able to send a string no problem.
Any help would be appreciated,
Stephen
import socket
import pickle
s = socket.socket()
host = socket.gethostname()
port = 80
s.bind((host, port))
s.listen(5)
while True:
c, addr = s.accept()
print( "Got Connection From ", addr )
data = pickle.dumps(c)
c.send( "XXX" )
#c.send(data)
c.close()
|
[
"It seems you try to use Python 2.x examples in Python 3 and you hit one of the main differences between those Python version.\nFor Python < 3 'strings' are in fact binary strings and 'unicode objects' are the right text objects (as they can contain any Unicode characters).\nIn Python 3 unicode strings are the 'regular strings' (str) and byte strings are separate objects. \nLow level I/O can be done only with data (byte strings), not text (sequence of characters). For Python 2.x str was also the 'binary data' type. In Python 3 it is not any more and one of the special 'data' objects should be used. Objects are pickled to such byte strings. If you want to enter them manually in code use the \"b\" prefix (b\"XXX\" instead of \"XXX\").\n",
"To add to Jacek Konieczny's answer: You can also use str.encode() to get bytes from a string. If you have the string in a variable instead of a literal, you can call encode and it will return an equivalent series of bytes.\n"
] |
[
22,
12
] |
[] |
[] |
[
"python",
"send",
"sockets",
"string"
] |
stackoverflow_0002411864_python_send_sockets_string.txt
|
Q:
Getting information from scripts/command line calls in C#
I've been writing a couple of apps which use C# as the Gui, but under the hood do all the work via scripts (which may be Python, Ruby etc.).
To pass information from the script back to the GUI (for example error reporting etc.) I've usually resorted to calling the script via Process and either
Redirected the input (StartInfo.RedirectStandardOutput etc) and read that
Created temporary files which the GUI monitors/reads to find out what it needs to know
Neither of these methods seems ideal (the second is simply awful imo) but I don't see any other way to do it. Maybe there isn't but I thought it worth asking before I started another app with a similar set of problem.
Thanks
A:
Using ProcessStartInfo.RedirectStandardInput, ProcessStartInfo.RedirectStandardOutput and ProcessStartInfo.RedirectStandardError (as well as Process.ExitCode) is perfectly fine, especially when your scripts rigorously follow a certain convention:
warnings and error descriptions go to stderr
in case of errors exit with a non-zero exit code (avoid the special value 259 STILL_ACTIVE)
in case of errors exit early if it makes sense to do so (avoids having the user sift through kilometric error messages, or your GUI having to accomodate kilometric error messages in e.g. a MessageBox)
all other, regular output goes to stdout (if applicable)
Your UI can then easily:
read script stdout and stderr into separate buffers until script terminates
check script exit code:
if exit code is 0 and stderr is empty, inform the user that Operation completed successfully
if exit code is 0 and stderr is non-empty, inform the user that Operation completed with warnings, allowing the user to optionally inspect the warnings from the stderr buffer
if exit code is non-0, inform the user that Operation has failed with errors, allowing the user to inspect the errors from the stderr buffer
|
Getting information from scripts/command line calls in C#
|
I've been writing a couple of apps which use C# as the Gui, but under the hood do all the work via scripts (which may be Python, Ruby etc.).
To pass information from the script back to the GUI (for example error reporting etc.) I've usually resorted to calling the script via Process and either
Redirected the input (StartInfo.RedirectStandardOutput etc) and read that
Created temporary files which the GUI monitors/reads to find out what it needs to know
Neither of these methods seems ideal (the second is simply awful imo) but I don't see any other way to do it. Maybe there isn't but I thought it worth asking before I started another app with a similar set of problem.
Thanks
|
[
"Using ProcessStartInfo.RedirectStandardInput, ProcessStartInfo.RedirectStandardOutput and ProcessStartInfo.RedirectStandardError (as well as Process.ExitCode) is perfectly fine, especially when your scripts rigorously follow a certain convention:\n\nwarnings and error descriptions go to stderr\nin case of errors exit with a non-zero exit code (avoid the special value 259 STILL_ACTIVE)\nin case of errors exit early if it makes sense to do so (avoids having the user sift through kilometric error messages, or your GUI having to accomodate kilometric error messages in e.g. a MessageBox)\nall other, regular output goes to stdout (if applicable)\n\nYour UI can then easily:\n\nread script stdout and stderr into separate buffers until script terminates\ncheck script exit code:\n\n\nif exit code is 0 and stderr is empty, inform the user that Operation completed successfully\nif exit code is 0 and stderr is non-empty, inform the user that Operation completed with warnings, allowing the user to optionally inspect the warnings from the stderr buffer\nif exit code is non-0, inform the user that Operation has failed with errors, allowing the user to inspect the errors from the stderr buffer\n\n\n"
] |
[
4
] |
[] |
[] |
[
"c#",
"python",
"ruby",
"scripting"
] |
stackoverflow_0002412141_c#_python_ruby_scripting.txt
|
Q:
List of Dicts comparision to match between lists and detect value changes in Python
I have a list of dictionaries that I get back from a web service call,
listA = [{'name':'foo', 'val':'x'},
{'name':'bar', 'val':'1'},
{'name':'alice','val':'2'}]
I need to compare the results from the previous call to the service and pull out changes. So on the next call I may get:
listB = [{'name':'foo', 'val':'y'},
{'name':'bar', 'val':'1'},
{'name':'eve','val':'z'}]
The ordering is not guaranteed and nor is the length of list. The names won't change. The actual data has several more keys, but I'm only concerned with 'val'.
I am trying to find a way to get back a list of the names that have had their values change between calls only for the names that are in both lists.
changed = ['foo'] # or [{'name':'foo'}]
A:
I'd build an auxiliary dict to store listA's information more sensibly:
auxdict = dict((d['name'], d['val']) for d in listA)
then the task becomes very easy:
changed = [d['name'] for d in listB
if d['name'] in auxdict and d['val'] != auxdict[d['name']]]
A:
First off, please turn that braindead format from your library into a real dict:
>>> listA = [{'name':'foo', 'val':'x'},{'name':'bar', 'val':'1'},{'name':'alice','val':'2'}]
>>> listB = [{'name':'foo', 'val':'y'},{'name':'bar', 'val':'1'},{'name':'eve','val':'z'}]
>>> def dicter(l):
... return dict([(i['name'],i['val']) for i in l])
...
>>> listA=dicter(listA)
>>> listA
{'foo': 'x', 'bar': '1', 'alice': '2'}
>>> listB=dicter(listB)
>>> listB
{'foo': 'y', 'bar': '1', 'eve': 'z'}
Then, this becomes relatively easy:
>>> answer = [k for k,v in listB.items() if k in listA and listA[k] != v]
>>> answer
['foo']
>>>
|
List of Dicts comparision to match between lists and detect value changes in Python
|
I have a list of dictionaries that I get back from a web service call,
listA = [{'name':'foo', 'val':'x'},
{'name':'bar', 'val':'1'},
{'name':'alice','val':'2'}]
I need to compare the results from the previous call to the service and pull out changes. So on the next call I may get:
listB = [{'name':'foo', 'val':'y'},
{'name':'bar', 'val':'1'},
{'name':'eve','val':'z'}]
The ordering is not guaranteed and nor is the length of list. The names won't change. The actual data has several more keys, but I'm only concerned with 'val'.
I am trying to find a way to get back a list of the names that have had their values change between calls only for the names that are in both lists.
changed = ['foo'] # or [{'name':'foo'}]
|
[
"I'd build an auxiliary dict to store listA's information more sensibly:\nauxdict = dict((d['name'], d['val']) for d in listA)\n\nthen the task becomes very easy:\nchanged = [d['name'] for d in listB \n if d['name'] in auxdict and d['val'] != auxdict[d['name']]]\n\n",
"First off, please turn that braindead format from your library into a real dict:\n>>> listA = [{'name':'foo', 'val':'x'},{'name':'bar', 'val':'1'},{'name':'alice','val':'2'}]\n>>> listB = [{'name':'foo', 'val':'y'},{'name':'bar', 'val':'1'},{'name':'eve','val':'z'}]\n>>> def dicter(l):\n... return dict([(i['name'],i['val']) for i in l])\n...\n>>> listA=dicter(listA)\n>>> listA\n{'foo': 'x', 'bar': '1', 'alice': '2'}\n>>> listB=dicter(listB)\n>>> listB\n{'foo': 'y', 'bar': '1', 'eve': 'z'}\n\nThen, this becomes relatively easy:\n>>> answer = [k for k,v in listB.items() if k in listA and listA[k] != v]\n>>> answer\n['foo']\n>>>\n\n"
] |
[
6,
0
] |
[] |
[] |
[
"comparison",
"dictionary",
"list",
"python"
] |
stackoverflow_0002412562_comparison_dictionary_list_python.txt
|
Q:
Python program doesn't quit when finished
I have the following script 186.py:
S=[]
study=set([524287])
tmax=10**7
D={}
DF={}
dudcount=0
callcount=0
def matchval(t1,t2):
if t1==t2:
global dudcount
dudcount+=1
else:
global callcount
callcount+=1
D.setdefault(t1,set([]))
D.setdefault(t2,set([]))
D[t1].add(t2)
if t1 in D[t2]:
DF.setdefault(t1,set([]))
DF[t1].add(t2)
DF.setdefault(t2,set([]))
DF[t2].add(t1)
for k in xrange(27):
t1=(100003 - 200003*(2*k+1) + 300007*(2*k+1)**3)%(1000000)
S.append(t1)
t2=(100003 - 200003*(2*k+2) + 300007*(2*k+2)**3)%(1000000)
S.append(t2)
matchval(t1,t2)
t1=(100003 - 200003*(55) + 300007*(55)**3)%(1000000)
S.append(t1)
t2=(S[31]+S.pop(0))%(1000000)
S.append(t2)
matchval(t1,t2)
for k in xrange(29,tmax+1):
t1=(S[31]+S.pop(0))%(1000000)
S.append(t1)
t2=(S[31]+S.pop(0))%(1000000)
S.append(t2)
matchval(t1,t2)
D.setdefault(524287,set([]))
DF.setdefault(524287,set([]))
print D[524287]
print DF[524287]
print dudcount,callcount
print "Done"
The last line prints "Done" but python doesn't exit when this happens. I type the following command:
$ time python 186.py
And get the results:
set([810528L, 582178L, 49419L, 214483L, 974071L, 651738L, 199163L, 193791L])
set([])
11 9999989
Done
But I have to ctrl+C to get the time:
real 34m18.642s
user 2m26.465s
sys 0m11.645s
After the program outputs "Done" python CPU usage is very little... but the memory usage continues to grow... I used ctrl+C once it got to 80% of my system memory (its an old system).
What is going on here? What is the program doing after Done is printed? Shouldn't it be done?
Thanks,
Dan
A:
I ran the same code on my 2 GHz dual-core laptop with 2GB RAM and it took about 1 1/2 minutes in Cygwin. The memory usage got up over 600 MB before the program quit and it took about 2-4 seconds after Done appeared for the prompt to come up and the memory to be released. However, I didn't see any memory increase after the Done appeared.
My guess is it has to do with memory management. After the Done appears, Python is working on freeing all of the memory which might take quite a while on an older machine with less RAM. I'm not sure why the memory actually increases unless there is just a delay in whatever is telling you how much memory is being used.
A:
There are no indications in what you've posted that match the described symptoms. Perhaps the indentation in the executed code is stuffed and you are really about to run another loop around the whole pile. Note that only brave people are going to bother trying to reproduce your problem when it takes 34 minutes to run. Can you reproduce this problem in a shorter time?
When you did Control-C, what did the traceback say?
In any case, I'd strongly advise not having hard-coded constants(?) all over the place e.g. 524287 .... give it a meaningful name and do meaningful_name = 524287 at the start. Or if it's really a variable, feed it in via sys.argv.
|
Python program doesn't quit when finished
|
I have the following script 186.py:
S=[]
study=set([524287])
tmax=10**7
D={}
DF={}
dudcount=0
callcount=0
def matchval(t1,t2):
if t1==t2:
global dudcount
dudcount+=1
else:
global callcount
callcount+=1
D.setdefault(t1,set([]))
D.setdefault(t2,set([]))
D[t1].add(t2)
if t1 in D[t2]:
DF.setdefault(t1,set([]))
DF[t1].add(t2)
DF.setdefault(t2,set([]))
DF[t2].add(t1)
for k in xrange(27):
t1=(100003 - 200003*(2*k+1) + 300007*(2*k+1)**3)%(1000000)
S.append(t1)
t2=(100003 - 200003*(2*k+2) + 300007*(2*k+2)**3)%(1000000)
S.append(t2)
matchval(t1,t2)
t1=(100003 - 200003*(55) + 300007*(55)**3)%(1000000)
S.append(t1)
t2=(S[31]+S.pop(0))%(1000000)
S.append(t2)
matchval(t1,t2)
for k in xrange(29,tmax+1):
t1=(S[31]+S.pop(0))%(1000000)
S.append(t1)
t2=(S[31]+S.pop(0))%(1000000)
S.append(t2)
matchval(t1,t2)
D.setdefault(524287,set([]))
DF.setdefault(524287,set([]))
print D[524287]
print DF[524287]
print dudcount,callcount
print "Done"
The last line prints "Done" but python doesn't exit when this happens. I type the following command:
$ time python 186.py
And get the results:
set([810528L, 582178L, 49419L, 214483L, 974071L, 651738L, 199163L, 193791L])
set([])
11 9999989
Done
But I have to ctrl+C to get the time:
real 34m18.642s
user 2m26.465s
sys 0m11.645s
After the program outputs "Done" python CPU usage is very little... but the memory usage continues to grow... I used ctrl+C once it got to 80% of my system memory (its an old system).
What is going on here? What is the program doing after Done is printed? Shouldn't it be done?
Thanks,
Dan
|
[
"I ran the same code on my 2 GHz dual-core laptop with 2GB RAM and it took about 1 1/2 minutes in Cygwin. The memory usage got up over 600 MB before the program quit and it took about 2-4 seconds after Done appeared for the prompt to come up and the memory to be released. However, I didn't see any memory increase after the Done appeared.\nMy guess is it has to do with memory management. After the Done appears, Python is working on freeing all of the memory which might take quite a while on an older machine with less RAM. I'm not sure why the memory actually increases unless there is just a delay in whatever is telling you how much memory is being used.\n",
"There are no indications in what you've posted that match the described symptoms. Perhaps the indentation in the executed code is stuffed and you are really about to run another loop around the whole pile. Note that only brave people are going to bother trying to reproduce your problem when it takes 34 minutes to run. Can you reproduce this problem in a shorter time?\nWhen you did Control-C, what did the traceback say?\nIn any case, I'd strongly advise not having hard-coded constants(?) all over the place e.g. 524287 .... give it a meaningful name and do meaningful_name = 524287 at the start. Or if it's really a variable, feed it in via sys.argv.\n"
] |
[
7,
0
] |
[] |
[] |
[
"linux",
"memory_leaks",
"python"
] |
stackoverflow_0002412715_linux_memory_leaks_python.txt
|
Q:
Python - file contents to nested list
I have a file in tab delimited format with trailing newline characters, e.g.,
123 abc
456 def
789 ghi
I wish to write function to convert the contents of the file into a nested list. To date I have tried:
def ls_platform_ann():
keyword = []
for line in open( "file", "r" ).readlines():
for value in line.split():
keyword.append(value)
and
def nested_list_input():
nested_list = []
for line in open("file", "r").readlines():
for entry in line.strip().split():
nested_list.append(entry)
print nested_list
.
The former creates a nested list but includes \n and \t characters. The latter does not make a nested list but rather lots of equivalent lists without \n and \t characters.
Anyone help?
Regards,
S ;-)
A:
You want the csv module.
import csv
source = "123\tabc\n456\tdef\n789\tghi"
lines = source.split("\n")
reader = csv.reader(lines, delimiter='\t')
print [word for word in [row for row in reader]]
Output:
[['123', 'abc'], ['456', 'def'], ['789', 'ghi']]
In the code above Ive put the content of the file right in there for easy testing. If youre reading from a file from disk you can do this as well (which might be considered cleaner):
import csv
reader = csv.reader(open("source.csv"), delimiter='\t')
print [word for word in [row for row in reader]]
A:
First off, have a look at the csv module, it should handle the whitespace for you. You may also want to call strip() on value/entry.
A:
Another option that doesn't involve the csv module is:
data = [[item.strip() for item in line.rstrip('\r\n').split('\t')] for line in open('input.txt')]
As a multiple line statement it would look like this:
data = []
for line in open('input.txt'):
items = line.rstrip('\r\n').split('\t') # strip new-line characters and split on column delimiter
items = [item.strip() for item in items] # strip extra whitespace off data items
data.append(items)
|
Python - file contents to nested list
|
I have a file in tab delimited format with trailing newline characters, e.g.,
123 abc
456 def
789 ghi
I wish to write function to convert the contents of the file into a nested list. To date I have tried:
def ls_platform_ann():
keyword = []
for line in open( "file", "r" ).readlines():
for value in line.split():
keyword.append(value)
and
def nested_list_input():
nested_list = []
for line in open("file", "r").readlines():
for entry in line.strip().split():
nested_list.append(entry)
print nested_list
.
The former creates a nested list but includes \n and \t characters. The latter does not make a nested list but rather lots of equivalent lists without \n and \t characters.
Anyone help?
Regards,
S ;-)
|
[
"You want the csv module.\nimport csv\n\nsource = \"123\\tabc\\n456\\tdef\\n789\\tghi\"\nlines = source.split(\"\\n\")\n\nreader = csv.reader(lines, delimiter='\\t')\n\nprint [word for word in [row for row in reader]]\n\nOutput:\n[['123', 'abc'], ['456', 'def'], ['789', 'ghi']]\n\nIn the code above Ive put the content of the file right in there for easy testing. If youre reading from a file from disk you can do this as well (which might be considered cleaner):\nimport csv\n\nreader = csv.reader(open(\"source.csv\"), delimiter='\\t')\n\nprint [word for word in [row for row in reader]]\n\n",
"First off, have a look at the csv module, it should handle the whitespace for you. You may also want to call strip() on value/entry.\n",
"Another option that doesn't involve the csv module is:\ndata = [[item.strip() for item in line.rstrip('\\r\\n').split('\\t')] for line in open('input.txt')]\n\nAs a multiple line statement it would look like this:\ndata = []\nfor line in open('input.txt'):\n items = line.rstrip('\\r\\n').split('\\t') # strip new-line characters and split on column delimiter\n items = [item.strip() for item in items] # strip extra whitespace off data items\n data.append(items)\n\n"
] |
[
8,
3,
3
] |
[] |
[] |
[
"file",
"list",
"newline",
"python",
"tabs"
] |
stackoverflow_0002410619_file_list_newline_python_tabs.txt
|
Q:
problem with editing labels in wx list control
do you guys have any idea how to edit the the labels in the second column in a wx.ListCtrl
here is the code that i used to create that list .. Note that the first column is the only editable one . how can i make the other one editable too?
self.lCUsers=wx.ListCtrl(self,style=wx.LC_EDIT_LABELS | wx.LC_REPORT |wx.LC_VRULES | wx.LC_HRULES)
self.lCUsers.SetPosition((20,40))
self.lCUsers.SetSize((300,350))
self.lCUsers.InsertColumn(0,'Users',format=wx.LIST_FORMAT_LEFT ,width=220)
self.lCUsers.InsertColumn(1,'Value',format=wx.LIST_FORMAT_LEFT,width=80)
thankx in advance
A:
You can use the TextEditMixin
import wx
from wx.lib.mixins.listctrl import TextEditMixin
class EditableTextListCtrl(wx.ListCtrl, TextEditMixin):
def __init__(self, parent, ID, pos=wx.DefaultPosition,
size=wx.DefaultSize, style=0):
wx.ListCtrl.__init__(self, parent, ID, pos, size, style)
TextEditMixin.__init__(self)
class MyDialog(wx.Dialog):
def __init__(self, parent, id, title):
wx.Dialog.__init__(self, parent, id)
listCtrl = EditableTextListCtrl(self, -1, style=wx.LC_REPORT|wx.LC_VRULES|wx.LC_HRULES, size=(300, 200))
listCtrl.InsertColumn(0, 'State')
listCtrl.InsertColumn(1, 'Capital')
listCtrl.SetColumnWidth(0, 140)
listCtrl.SetColumnWidth(1, 153)
states = ['Slovakia', 'Poland', 'Hungary']
capitals = ['Brastislava', 'Warsaw', 'Budapest']
for i in range(3):
listCtrl.InsertStringItem(0, states[i])
listCtrl.SetStringItem(0, 1, capitals[i])
class MyApp(wx.App):
def OnInit(self):
dia = MyDialog(None, -1, 'capitals.py')
dia.ShowModal()
dia.Destroy()
return True
app = MyApp(0)
app.MainLoop()
|
problem with editing labels in wx list control
|
do you guys have any idea how to edit the the labels in the second column in a wx.ListCtrl
here is the code that i used to create that list .. Note that the first column is the only editable one . how can i make the other one editable too?
self.lCUsers=wx.ListCtrl(self,style=wx.LC_EDIT_LABELS | wx.LC_REPORT |wx.LC_VRULES | wx.LC_HRULES)
self.lCUsers.SetPosition((20,40))
self.lCUsers.SetSize((300,350))
self.lCUsers.InsertColumn(0,'Users',format=wx.LIST_FORMAT_LEFT ,width=220)
self.lCUsers.InsertColumn(1,'Value',format=wx.LIST_FORMAT_LEFT,width=80)
thankx in advance
|
[
"You can use the TextEditMixin\nimport wx\nfrom wx.lib.mixins.listctrl import TextEditMixin\n\nclass EditableTextListCtrl(wx.ListCtrl, TextEditMixin):\n def __init__(self, parent, ID, pos=wx.DefaultPosition,\n size=wx.DefaultSize, style=0):\n wx.ListCtrl.__init__(self, parent, ID, pos, size, style)\n TextEditMixin.__init__(self) \n\nclass MyDialog(wx.Dialog):\n def __init__(self, parent, id, title):\n wx.Dialog.__init__(self, parent, id)\n listCtrl = EditableTextListCtrl(self, -1, style=wx.LC_REPORT|wx.LC_VRULES|wx.LC_HRULES, size=(300, 200))\n listCtrl.InsertColumn(0, 'State')\n listCtrl.InsertColumn(1, 'Capital')\n listCtrl.SetColumnWidth(0, 140)\n listCtrl.SetColumnWidth(1, 153)\n states = ['Slovakia', 'Poland', 'Hungary']\n capitals = ['Brastislava', 'Warsaw', 'Budapest']\n for i in range(3):\n listCtrl.InsertStringItem(0, states[i])\n listCtrl.SetStringItem(0, 1, capitals[i])\n\nclass MyApp(wx.App):\n def OnInit(self):\n dia = MyDialog(None, -1, 'capitals.py')\n dia.ShowModal()\n dia.Destroy()\n return True\n\napp = MyApp(0)\napp.MainLoop()\n\n"
] |
[
2
] |
[] |
[] |
[
"python",
"wxpython",
"wxwidgets"
] |
stackoverflow_0002274217_python_wxpython_wxwidgets.txt
|
Q:
Circular import issues with Django apps that have dependencies on each other
I am writing a couple of django apps which by design are coupled together. But I get circular import problems. I know it might be bad design, so please give examples of better solutions. I can't seem to find a better suited design, so if there isn't a better design, how to solve this one?
It is basically two django apps, with some models, which relate to each other cross app-wise. In short the system is an event based system. So there is an event model and a task model. These live in two different apps, Events and Tasks. When events is triggered, I need to check that certain tasks are solved or not, and when a task is solved, that can trigger some other events.
So in Events I need to store data about tasks (to check if these tasks are solved) and in Tasks I need to store data about events (which events to trigger when they are solved)
Here is some sample code from my apps:
Events app
models.py
from tasks.models import Task
class Event(models.Model):
...
tasks = models.ManyToManyField(Task, help_text=_("Tasks we need to check if are solved before triggering this event."))
...
Tasks app
models.py
from events.models import Event
class Task(models.Model):
...
events = models.ManyToManyField(Event, help_text=_("Events to trigger when this task i solved."))
...
This is causing import problems when I try to validate:
AttributeError: 'module' object has no attribute 'Event'
So how to solve this? Ive tried to use some of the django helper functions in hope that that would help, more specifically I've tried to use the django.db.models.get_app and get_model functions to import the models instead of directly importing them, but I still get problems.
Of course I could collect them into the same app, but I clearly believe they should live in separate apps, since they handle separate things. But yes they are dependent on each other. If I can't solve the import problems, any ideas on how to design this different?
I could of course use some generic relations, but that would actually make things harder to understand for other people since it doesn't specify the content type that it should relate to.
A:
Both models do not need many-to-many fields.
Do not put both sides of a many-to-many relationship in your model.
When you put in one many-to-many relationship, Django inserts the other side of the relationship for you.
http://docs.djangoproject.com/en/1.1/topics/db/queries/#many-to-many-relationships
Both ends of a many-to-many
relationship get automatic API access
to the other end. The API works just
as a "backward" one-to-many
relationship, above.
"When events is triggered, i need to check that surtain tasks are solved or not".
This means that Event can be triggered some other way and is independent of any Task.
If an Event can be triggered and that leads to Tasks, then Tasks depend on Events.
"when a task is solved, that can trigger some other events"
This means that Tasks depend on Events. Events do not depend on Tasks.
Put the many-to-many reference to Events in Tasks. Put nothing in Events, since Events can be used elsewhere, to trigger a chain of Tasks and other Events. Some client application will import Events only.
Further, you can provide many-to-many field references using a string name instead of importing the model.
|
Circular import issues with Django apps that have dependencies on each other
|
I am writing a couple of django apps which by design are coupled together. But I get circular import problems. I know it might be bad design, so please give examples of better solutions. I can't seem to find a better suited design, so if there isn't a better design, how to solve this one?
It is basically two django apps, with some models, which relate to each other cross app-wise. In short the system is an event based system. So there is an event model and a task model. These live in two different apps, Events and Tasks. When events is triggered, I need to check that certain tasks are solved or not, and when a task is solved, that can trigger some other events.
So in Events I need to store data about tasks (to check if these tasks are solved) and in Tasks I need to store data about events (which events to trigger when they are solved)
Here is some sample code from my apps:
Events app
models.py
from tasks.models import Task
class Event(models.Model):
...
tasks = models.ManyToManyField(Task, help_text=_("Tasks we need to check if are solved before triggering this event."))
...
Tasks app
models.py
from events.models import Event
class Task(models.Model):
...
events = models.ManyToManyField(Event, help_text=_("Events to trigger when this task i solved."))
...
This is causing import problems when I try to validate:
AttributeError: 'module' object has no attribute 'Event'
So how to solve this? Ive tried to use some of the django helper functions in hope that that would help, more specifically I've tried to use the django.db.models.get_app and get_model functions to import the models instead of directly importing them, but I still get problems.
Of course I could collect them into the same app, but I clearly believe they should live in separate apps, since they handle separate things. But yes they are dependent on each other. If I can't solve the import problems, any ideas on how to design this different?
I could of course use some generic relations, but that would actually make things harder to understand for other people since it doesn't specify the content type that it should relate to.
|
[
"Both models do not need many-to-many fields.\nDo not put both sides of a many-to-many relationship in your model.\nWhen you put in one many-to-many relationship, Django inserts the other side of the relationship for you. \nhttp://docs.djangoproject.com/en/1.1/topics/db/queries/#many-to-many-relationships\n\nBoth ends of a many-to-many\n relationship get automatic API access\n to the other end. The API works just\n as a \"backward\" one-to-many\n relationship, above.\n\n\"When events is triggered, i need to check that surtain tasks are solved or not\".\n\nThis means that Event can be triggered some other way and is independent of any Task.\nIf an Event can be triggered and that leads to Tasks, then Tasks depend on Events.\n\n\"when a task is solved, that can trigger some other events\"\n\nThis means that Tasks depend on Events. Events do not depend on Tasks. \n\nPut the many-to-many reference to Events in Tasks. Put nothing in Events, since Events can be used elsewhere, to trigger a chain of Tasks and other Events. Some client application will import Events only.\nFurther, you can provide many-to-many field references using a string name instead of importing the model.\n"
] |
[
7
] |
[] |
[] |
[
"design_patterns",
"django",
"import",
"python"
] |
stackoverflow_0002412995_design_patterns_django_import_python.txt
|
Q:
Mercurial Issue when updating
I am trying to do a terminal update and I keep getting this error, no matter what.
/Volumes/www/working/.hg/wlock.break
/Library/Python/2.6/site-packages/mercurial/dispatch.py:157: DeprecationWarning: use lock.release instead of del lock
return -1
Any ideas as to what this is?
Out of date versions?
I am running Snow Leopard 10.6.2 thanks
A:
What version of mercurial are you running? It looks like a lot of these (harmless warning) messages have been cleaned up according to the mercurial bug tracker.
|
Mercurial Issue when updating
|
I am trying to do a terminal update and I keep getting this error, no matter what.
/Volumes/www/working/.hg/wlock.break
/Library/Python/2.6/site-packages/mercurial/dispatch.py:157: DeprecationWarning: use lock.release instead of del lock
return -1
Any ideas as to what this is?
Out of date versions?
I am running Snow Leopard 10.6.2 thanks
|
[
"What version of mercurial are you running? It looks like a lot of these (harmless warning) messages have been cleaned up according to the mercurial bug tracker.\n"
] |
[
1
] |
[] |
[] |
[
"mercurial",
"python"
] |
stackoverflow_0002412043_mercurial_python.txt
|
Q:
Python Socket Getting Connection Reset
I created a threaded socket listener that stores newly accepted connections in a queue. The socket threads then read from the queue and respond. For some reason, when doing benchmarking with 'ab' (apache benchmark) using a concurrency of 2 or more, I always get a connection reset before it's able to complete the benchmark (this is taking place locally, so there's no external connection issue).
class server:
_ip = ''
_port = 8888
def __init__(self, ip=None, port=None):
if ip is not None:
self._ip = ip
if port is not None:
self._port = port
self.server_listener(self._ip, self._port)
def now(self):
return time.ctime(time.time())
def http_responder(self, conn, addr):
httpobj = http_builder()
httpobj.header('HTTP/1.1 200 OK')
httpobj.header('Content-Type: text/html; charset=UTF-8')
httpobj.header('Connection: close')
httpobj.body("Everything looks good")
data = httpobj.generate()
sent = conn.sendall(data)
def http_thread(self, id):
self.log("THREAD %d: Starting Up..." % id)
while True:
conn, addr = self.q.get()
ip, port = addr
self.log("THREAD %d: responding to request: %s:%s - %s" % (id, ip, port, self.now()))
self.http_responder(conn, addr)
self.q.task_done()
conn.close()
def server_listener(self, host, port):
self.q = Queue.Queue(0)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind( (host, port) )
sock.listen(5)
for i in xrange(4): #thread count
thread.start_new(self.http_thread, (i+1, ))
while True:
self.q.put(sock.accept())
sock.close()
server('', 9999)
When running the benchmark, I get totally random numbers of good requests before it errors out, usually between 4 and 500.
Edit: Took me a while to figure it out, but the problem was in sock.listen(5). Because I was using apache benchmark with a higher concurrency (5 and up) it was causing the backlog of connections to pile up, at which point the connections started getting dropped by the socket.
A:
Is there a reason why you're not using SocketServer which comes with Python? This would handle the situation a lot better. If you're looking to do HTTP stuff, the BaseHTTPServer also provides a framework for this.
|
Python Socket Getting Connection Reset
|
I created a threaded socket listener that stores newly accepted connections in a queue. The socket threads then read from the queue and respond. For some reason, when doing benchmarking with 'ab' (apache benchmark) using a concurrency of 2 or more, I always get a connection reset before it's able to complete the benchmark (this is taking place locally, so there's no external connection issue).
class server:
_ip = ''
_port = 8888
def __init__(self, ip=None, port=None):
if ip is not None:
self._ip = ip
if port is not None:
self._port = port
self.server_listener(self._ip, self._port)
def now(self):
return time.ctime(time.time())
def http_responder(self, conn, addr):
httpobj = http_builder()
httpobj.header('HTTP/1.1 200 OK')
httpobj.header('Content-Type: text/html; charset=UTF-8')
httpobj.header('Connection: close')
httpobj.body("Everything looks good")
data = httpobj.generate()
sent = conn.sendall(data)
def http_thread(self, id):
self.log("THREAD %d: Starting Up..." % id)
while True:
conn, addr = self.q.get()
ip, port = addr
self.log("THREAD %d: responding to request: %s:%s - %s" % (id, ip, port, self.now()))
self.http_responder(conn, addr)
self.q.task_done()
conn.close()
def server_listener(self, host, port):
self.q = Queue.Queue(0)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind( (host, port) )
sock.listen(5)
for i in xrange(4): #thread count
thread.start_new(self.http_thread, (i+1, ))
while True:
self.q.put(sock.accept())
sock.close()
server('', 9999)
When running the benchmark, I get totally random numbers of good requests before it errors out, usually between 4 and 500.
Edit: Took me a while to figure it out, but the problem was in sock.listen(5). Because I was using apache benchmark with a higher concurrency (5 and up) it was causing the backlog of connections to pile up, at which point the connections started getting dropped by the socket.
|
[
"Is there a reason why you're not using SocketServer which comes with Python? This would handle the situation a lot better. If you're looking to do HTTP stuff, the BaseHTTPServer also provides a framework for this. \n"
] |
[
0
] |
[] |
[] |
[
"multithreading",
"python",
"sockets"
] |
stackoverflow_0002411290_multithreading_python_sockets.txt
|
Q:
Error when using astWCS trying to create WCS object
I'm running python2.5 and trying to use the astLib library to analyse WCS information in astronomical images. I try and get the object instanciated with the following skeleton code:
from astLib import astWCS
w = astWCS.WCS('file.fits') # error here
where file.fits is a string pointing to a valid fits file.
I have tried using the alternate method of passing a pyfits header object and this fails also:
import pyfits
from astLib import astWCS
f = pyfits.open('file.fits')
header = f[0].header
f.close()
w = astWCS.WCS(header, mode='pyfits') # error here also
The error is this:
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/home/astro/phrfbf/build/lib/python2.6/site-packages/astLib/astWCS.py", line 79, in __init__
self.updateFromHeader()
File "/home/astro/phrfbf/build/lib/python2.6/site-packages/astLib/astWCS.py", line 119, in updateFromHeader
self.WCSStructure=wcs.wcsinit(cardstring)
File "/home/astro/phrfbf/build/lib/python2.6/site-packages/PyWCSTools/wcs.py", line 70, in wcsinit
return _wcs.wcsinit(*args)
TypeError: in method 'wcsinit', argument 1 of type 'char *'
When I run in ipython, I get the full error here on the pastebin
I know the astWCS module is a wrapped version of WCStools but i'd prefer to use the Python module as the rest of my code is in Python
Can anyone help with this problem?
A:
Just found out the updated version of this library has fixed the problem, thanks for everyone's help
A:
Oh sorry, I should have seen. Looking at the pastebin in more detail, the only error I can think of is that, for some reason the header has unicode in it. It can't be converted to char *, and you get the error. I tried searching for something in the header, but everything looks okay. Can you do this and post the output in another pastebin?
import pyfits
f = pyfits.open('file.fits')
header = f[0].header
f.close()
for x, i in enumerate(header.iteritems()):
if len(str(i[1])) >= 70:
print x, str(i[1])
cardlist = header.ascardlist()
cardstring = ""
for card in cardlist:
cardstring = cardstring + str(card)
print repr(cardstring)
Or, if you can check the header of your fits file for "funny" characters, getting rid of them should solve the issue.
|
Error when using astWCS trying to create WCS object
|
I'm running python2.5 and trying to use the astLib library to analyse WCS information in astronomical images. I try and get the object instanciated with the following skeleton code:
from astLib import astWCS
w = astWCS.WCS('file.fits') # error here
where file.fits is a string pointing to a valid fits file.
I have tried using the alternate method of passing a pyfits header object and this fails also:
import pyfits
from astLib import astWCS
f = pyfits.open('file.fits')
header = f[0].header
f.close()
w = astWCS.WCS(header, mode='pyfits') # error here also
The error is this:
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/home/astro/phrfbf/build/lib/python2.6/site-packages/astLib/astWCS.py", line 79, in __init__
self.updateFromHeader()
File "/home/astro/phrfbf/build/lib/python2.6/site-packages/astLib/astWCS.py", line 119, in updateFromHeader
self.WCSStructure=wcs.wcsinit(cardstring)
File "/home/astro/phrfbf/build/lib/python2.6/site-packages/PyWCSTools/wcs.py", line 70, in wcsinit
return _wcs.wcsinit(*args)
TypeError: in method 'wcsinit', argument 1 of type 'char *'
When I run in ipython, I get the full error here on the pastebin
I know the astWCS module is a wrapped version of WCStools but i'd prefer to use the Python module as the rest of my code is in Python
Can anyone help with this problem?
|
[
"Just found out the updated version of this library has fixed the problem, thanks for everyone's help\n",
"Oh sorry, I should have seen. Looking at the pastebin in more detail, the only error I can think of is that, for some reason the header has unicode in it. It can't be converted to char *, and you get the error. I tried searching for something in the header, but everything looks okay. Can you do this and post the output in another pastebin?\nimport pyfits\n\nf = pyfits.open('file.fits')\nheader = f[0].header\nf.close()\n\nfor x, i in enumerate(header.iteritems()):\n if len(str(i[1])) >= 70:\n print x, str(i[1])\n\ncardlist = header.ascardlist() \ncardstring = \"\" \nfor card in cardlist: \n cardstring = cardstring + str(card)\n\nprint repr(cardstring)\n\nOr, if you can check the header of your fits file for \"funny\" characters, getting rid of them should solve the issue.\n"
] |
[
1,
0
] |
[] |
[] |
[
"astronomy",
"fits",
"python"
] |
stackoverflow_0002048166_astronomy_fits_python.txt
|
Q:
Good ways to sort a queryset? - Django
what I'm trying to do is this:
get the 30 Authors with highest score ( Author.objects.order_by('-score')[:30] )
order the authors by last_name
Any suggestions?
A:
What about
import operator
auths = Author.objects.order_by('-score')[:30]
ordered = sorted(auths, key=operator.attrgetter('last_name'))
In Django 1.4 and newer you can order by providing multiple fields.
Reference: https://docs.djangoproject.com/en/dev/ref/models/querysets/#order-by
order_by(*fields)
By default, results returned by a QuerySet are ordered by the ordering tuple given by the ordering option in the model’s Meta. You can override this on a per-QuerySet basis by using the order_by method.
Example:
ordered_authors = Author.objects.order_by('-score', 'last_name')[:30]
The result above will be ordered by score descending, then by last_name ascending. The negative sign in front of "-score" indicates descending order. Ascending order is implied.
A:
I just wanted to illustrate that the built-in solutions (SQL-only) are not always the best ones. At first I thought that because Django's QuerySet.objects.order_by method accepts multiple arguments, you could easily chain them:
ordered_authors = Author.objects.order_by('-score', 'last_name')[:30]
But, it does not work as you would expect. Case in point, first is a list of presidents sorted by score (selecting top 5 for easier reading):
>>> auths = Author.objects.order_by('-score')[:5]
>>> for x in auths: print x
...
James Monroe (487)
Ulysses Simpson (474)
Harry Truman (471)
Benjamin Harrison (467)
Gerald Rudolph (464)
Using Alex Martelli's solution which accurately provides the top 5 people sorted by last_name:
>>> for x in sorted(auths, key=operator.attrgetter('last_name')): print x
...
Benjamin Harrison (467)
James Monroe (487)
Gerald Rudolph (464)
Ulysses Simpson (474)
Harry Truman (471)
And now the combined order_by call:
>>> myauths = Author.objects.order_by('-score', 'last_name')[:5]
>>> for x in myauths: print x
...
James Monroe (487)
Ulysses Simpson (474)
Harry Truman (471)
Benjamin Harrison (467)
Gerald Rudolph (464)
As you can see it is the same result as the first one, meaning it doesn't work as you would expect.
A:
Here's a way that allows for ties for the cut-off score.
author_count = Author.objects.count()
cut_off_score = Author.objects.order_by('-score').values_list('score')[min(30, author_count)]
top_authors = Author.objects.filter(score__gte=cut_off_score).order_by('last_name')
You may get more than 30 authors in top_authors this way and the min(30,author_count) is there incase you have fewer than 30 authors.
|
Good ways to sort a queryset? - Django
|
what I'm trying to do is this:
get the 30 Authors with highest score ( Author.objects.order_by('-score')[:30] )
order the authors by last_name
Any suggestions?
|
[
"What about\nimport operator\n\nauths = Author.objects.order_by('-score')[:30]\nordered = sorted(auths, key=operator.attrgetter('last_name'))\n\nIn Django 1.4 and newer you can order by providing multiple fields.\nReference: https://docs.djangoproject.com/en/dev/ref/models/querysets/#order-by\norder_by(*fields)\nBy default, results returned by a QuerySet are ordered by the ordering tuple given by the ordering option in the model’s Meta. You can override this on a per-QuerySet basis by using the order_by method.\nExample:\nordered_authors = Author.objects.order_by('-score', 'last_name')[:30]\n\nThe result above will be ordered by score descending, then by last_name ascending. The negative sign in front of \"-score\" indicates descending order. Ascending order is implied.\n",
"I just wanted to illustrate that the built-in solutions (SQL-only) are not always the best ones. At first I thought that because Django's QuerySet.objects.order_by method accepts multiple arguments, you could easily chain them:\nordered_authors = Author.objects.order_by('-score', 'last_name')[:30]\n\nBut, it does not work as you would expect. Case in point, first is a list of presidents sorted by score (selecting top 5 for easier reading):\n>>> auths = Author.objects.order_by('-score')[:5]\n>>> for x in auths: print x\n... \nJames Monroe (487)\nUlysses Simpson (474)\nHarry Truman (471)\nBenjamin Harrison (467)\nGerald Rudolph (464)\n\nUsing Alex Martelli's solution which accurately provides the top 5 people sorted by last_name:\n>>> for x in sorted(auths, key=operator.attrgetter('last_name')): print x\n... \nBenjamin Harrison (467)\nJames Monroe (487)\nGerald Rudolph (464)\nUlysses Simpson (474)\nHarry Truman (471)\n\nAnd now the combined order_by call:\n>>> myauths = Author.objects.order_by('-score', 'last_name')[:5]\n>>> for x in myauths: print x\n... \nJames Monroe (487)\nUlysses Simpson (474)\nHarry Truman (471)\nBenjamin Harrison (467)\nGerald Rudolph (464)\n\nAs you can see it is the same result as the first one, meaning it doesn't work as you would expect. \n",
"Here's a way that allows for ties for the cut-off score.\nauthor_count = Author.objects.count()\ncut_off_score = Author.objects.order_by('-score').values_list('score')[min(30, author_count)]\ntop_authors = Author.objects.filter(score__gte=cut_off_score).order_by('last_name')\n\nYou may get more than 30 authors in top_authors this way and the min(30,author_count) is there incase you have fewer than 30 authors.\n"
] |
[
248,
16,
6
] |
[] |
[] |
[
"django",
"django_models",
"python"
] |
stackoverflow_0002412770_django_django_models_python.txt
|
Q:
Python package with compiled code
I'm looking into releasing a python package which includes an existing fortran or C program. The fortran/C program is compiled by running
./configure
make
The python code calls the resulting binary through subprocess calls (i.e. the code is not really wrapped as such). What I would like is that when the user types
python setup.py install
the fortran/C program is first compiled using the ./configure and make commands, then I want the python module to be installed, and the binary to be installed in the python bin/ directory alongside executables that are usually installed via the scripts= option in distutils.core.setup.
First, are there any problems with doing this? And if not, what is the best way to do it via setup.py? Are there existing functions to automate the ./configure and make, since this is pretty standard? Or should I just use os.system calls? And either way, where should those commands go in setup.py? Then should I have make output the binary to e.g. scripts/ and then have scripts=['scripts/mybinary'] in the setup() function?
A:
Don't make this too complex.
Just provide them as separate items with a README that says -- basically -- what you said in the question.
Build the Fortran/C with ./configure; make; make install.
Setup Python with python setup.py install.
It doesn't appear to be rocket science. Trying to over-simplify the installation means that you must account for every OS vagary and oddness.
It's easier to trust the users to do "standard" installations so that the Fortran/C is on the system PATH, and your Python script should be configured to find them on the system PATH.
People who want to use your software are then free to reconfigure it to their own unique needs. They will anyway. Don't overpackage and force them to fight against you to reconfigure things.
A:
consider writing a python C extension as a wrapper for your C code, and a f2py extension as a wrapper for your fortran code. Then you can just use them in your python code as fast calls instead of using subprocess.
|
Python package with compiled code
|
I'm looking into releasing a python package which includes an existing fortran or C program. The fortran/C program is compiled by running
./configure
make
The python code calls the resulting binary through subprocess calls (i.e. the code is not really wrapped as such). What I would like is that when the user types
python setup.py install
the fortran/C program is first compiled using the ./configure and make commands, then I want the python module to be installed, and the binary to be installed in the python bin/ directory alongside executables that are usually installed via the scripts= option in distutils.core.setup.
First, are there any problems with doing this? And if not, what is the best way to do it via setup.py? Are there existing functions to automate the ./configure and make, since this is pretty standard? Or should I just use os.system calls? And either way, where should those commands go in setup.py? Then should I have make output the binary to e.g. scripts/ and then have scripts=['scripts/mybinary'] in the setup() function?
|
[
"Don't make this too complex.\nJust provide them as separate items with a README that says -- basically -- what you said in the question.\n\nBuild the Fortran/C with ./configure; make; make install.\nSetup Python with python setup.py install.\n\nIt doesn't appear to be rocket science. Trying to over-simplify the installation means that you must account for every OS vagary and oddness. \nIt's easier to trust the users to do \"standard\" installations so that the Fortran/C is on the system PATH, and your Python script should be configured to find them on the system PATH. \nPeople who want to use your software are then free to reconfigure it to their own unique needs. They will anyway. Don't overpackage and force them to fight against you to reconfigure things.\n",
"consider writing a python C extension as a wrapper for your C code, and a f2py extension as a wrapper for your fortran code. Then you can just use them in your python code as fast calls instead of using subprocess.\n"
] |
[
2,
0
] |
[] |
[] |
[
"package",
"python"
] |
stackoverflow_0002414045_package_python.txt
|
Q:
How do I make this sorting case insensitive?
def sortProfiles(p):
return sorted(p, key=itemgetter('first_name'))
I have a list with dictionaries. This function allows me to sort them by their first_name. However, it's case-sensitive.
A:
>>> from operator import itemgetter
>>> p = [{'fn':'bill'}, {'fn':'Bob'}, {'fn':'bobby'}]
>>> sorted(p, key=itemgetter('fn'))
[{'fn': 'Bob'}, {'fn': 'bill'}, {'fn': 'bobby'}]
>>> sorted(p, key=lambda x: x['fn'].lower())
[{'fn': 'bill'}, {'fn': 'Bob'}, {'fn': 'bobby'}]
>>>
A:
Here's a way:
return sorted(p, key=lambda x: x['first_name'].lower())
A:
It looks like you want sorted(p, key=lambda d: d['first_name'].lower()).
A:
>>> def my_itemgetter(attr):
def get_attr(obj):
return obj.get(attr, "").lower()
return get_attr
>>> a= [{"a":"dA"},{"a":"ab"},{"a":"Ac"},{"a":"aa"}]
>>> sorted(a, key=my_itemgetter("a"))
[{'a': 'aa'}, {'a': 'ab'}, {'a': 'Ac'}, {'a': 'dA'}]
A:
def sortProfiles(p):
return sorted(p, key=lambda el: el['first_name'].lower())
A:
If you dislike lambda, you can use a named function as your key-extractor, e.g:
def sortProfiles(p):
def lowerName(d):
return d['first_name'].lower()
return sorted(p, key=lowerName)
The def statement can appear just about anywhere another statement could, including in another function's body. In this case, the choice among a nested def, a lambda, or a separate def outside of sortProfiles, is mostly a matter of style, though the last of these could offer some performance gain.
|
How do I make this sorting case insensitive?
|
def sortProfiles(p):
return sorted(p, key=itemgetter('first_name'))
I have a list with dictionaries. This function allows me to sort them by their first_name. However, it's case-sensitive.
|
[
">>> from operator import itemgetter\n>>> p = [{'fn':'bill'}, {'fn':'Bob'}, {'fn':'bobby'}]\n>>> sorted(p, key=itemgetter('fn'))\n[{'fn': 'Bob'}, {'fn': 'bill'}, {'fn': 'bobby'}]\n>>> sorted(p, key=lambda x: x['fn'].lower())\n[{'fn': 'bill'}, {'fn': 'Bob'}, {'fn': 'bobby'}]\n>>>\n\n",
"Here's a way:\nreturn sorted(p, key=lambda x: x['first_name'].lower())\n\n",
"It looks like you want sorted(p, key=lambda d: d['first_name'].lower()).\n",
">>> def my_itemgetter(attr):\n def get_attr(obj):\n return obj.get(attr, \"\").lower()\n return get_attr\n\n>>> a= [{\"a\":\"dA\"},{\"a\":\"ab\"},{\"a\":\"Ac\"},{\"a\":\"aa\"}]\n>>> sorted(a, key=my_itemgetter(\"a\"))\n[{'a': 'aa'}, {'a': 'ab'}, {'a': 'Ac'}, {'a': 'dA'}]\n\n",
"def sortProfiles(p):\n return sorted(p, key=lambda el: el['first_name'].lower())\n\n",
"If you dislike lambda, you can use a named function as your key-extractor, e.g:\ndef sortProfiles(p):\n def lowerName(d):\n return d['first_name'].lower()\n return sorted(p, key=lowerName)\n\nThe def statement can appear just about anywhere another statement could, including in another function's body. In this case, the choice among a nested def, a lambda, or a separate def outside of sortProfiles, is mostly a matter of style, though the last of these could offer some performance gain.\n"
] |
[
10,
2,
1,
1,
1,
1
] |
[] |
[] |
[
"dictionary",
"list",
"python",
"sorting"
] |
stackoverflow_0002414201_dictionary_list_python_sorting.txt
|
Q:
How regex a empty string in python?
I want that find empty tags, here is a example
txt ="<lol1><><lol2>"
rgx = "<([a-zA-Z_0-9]+)>"
print re.findall(rgex, txt)
I get this
['lol1', 'lol2']
I want
['lol1', '', 'lol2']
How I can do this with regex?
A:
Use rgx = "<([a-zA-Z_0-9]*)>"
The key point is using *, which means "zero or more of the preceding", where you're using +, which means "one or more".
A:
no need regex
>>> s="txt ="<lol1><><lol2>"
>>> for i in txt.split(">"):
... if "<" in i:
... print i[i.find("<")+1:]
...
lol1
lol2
>>> [i[i.find("<")+1:] for i in txt.split(">") if "<" in i ]
['lol1', '', 'lol2']
|
How regex a empty string in python?
|
I want that find empty tags, here is a example
txt ="<lol1><><lol2>"
rgx = "<([a-zA-Z_0-9]+)>"
print re.findall(rgex, txt)
I get this
['lol1', 'lol2']
I want
['lol1', '', 'lol2']
How I can do this with regex?
|
[
"Use rgx = \"<([a-zA-Z_0-9]*)>\"\nThe key point is using *, which means \"zero or more of the preceding\", where you're using +, which means \"one or more\".\n",
"no need regex\n>>> s=\"txt =\"<lol1><><lol2>\"\n>>> for i in txt.split(\">\"):\n... if \"<\" in i:\n... print i[i.find(\"<\")+1:]\n...\nlol1\n\nlol2\n>>> [i[i.find(\"<\")+1:] for i in txt.split(\">\") if \"<\" in i ]\n['lol1', '', 'lol2']\n\n"
] |
[
8,
0
] |
[] |
[] |
[
"python",
"regex"
] |
stackoverflow_0002414472_python_regex.txt
|
Q:
Creating subtree from tree which is represented in xml - python
I have an XML (in the form of tree), I require to create sub-tree out of it.
For ex:
<a>
<b>
<c>Hello</c>
<d>
<e>Hi</e>
</a>
Subtree would be
<root>
<a>
<b>
<c>Hello</c>
</b>
</a>
<a>
<d>
<e>Hi</e>
</d>
</a>
</root>
What is the best XML library in python to do it? Any algorithm that already does this would also be helpful. Note: the XML doc won't be that big, it will easily fit in memory.
A:
ElementTree is good and simple for both "reading" and "writing".
Your first XML example (I edited your question just to add formatting so it would be readable!) is invalid, I assume missing close-tags for b and d as appear in what you call "the subtree" (which looks nothing like a subtree to me, but does look like it's intended as a rewrite of your first form).
Net of "prettyfication" issues (e.g. adding newlines and indents to make the resulting XML look pretty;-), this code should do what you're asking, if I understand you correctly:
try:
import xml.etree.cElementTree as et
import cStringIO as sio
except ImportError:
import xml.etree.ElementTree as et
import StringIO as sio
xmlin = sio.StringIO('''<a>
<b>
<c>Hello</c>
</b>
<d>
<e>Hi</e>
</d>
</a>
''')
tin = et.parse(xmlin)
top = tin.getroot()
tou = et.ElementTree(et.Element('root'))
newtop = tou.getroot()
for child in top.getchildren():
subtree = et.Element(top.tag)
subtree.append(child)
newtop.append(subtree)
import sys
tou.write(sys.stdout)
The try/except at the start tries to use the C versions of the modules on "normal" platforms where they're available, fall back to the pure-Python modules otherwise (for App Engine, Jython, IronPython, ...).
Then I build two trees -- tin, the input one, from the XML string you're given; tou, the output one, initially empty except for the root element.
All the rest is a very simple loop on all subelements of tin's root: for each, a suitable subtree is built and appended to the subelements of tou's root -- that's all there is to it.
The last two lines show the resulting tree (not pretty, due to whitespace issues, but perfectly correct in terms of XML structure;-).
|
Creating subtree from tree which is represented in xml - python
|
I have an XML (in the form of tree), I require to create sub-tree out of it.
For ex:
<a>
<b>
<c>Hello</c>
<d>
<e>Hi</e>
</a>
Subtree would be
<root>
<a>
<b>
<c>Hello</c>
</b>
</a>
<a>
<d>
<e>Hi</e>
</d>
</a>
</root>
What is the best XML library in python to do it? Any algorithm that already does this would also be helpful. Note: the XML doc won't be that big, it will easily fit in memory.
|
[
"ElementTree is good and simple for both \"reading\" and \"writing\".\nYour first XML example (I edited your question just to add formatting so it would be readable!) is invalid, I assume missing close-tags for b and d as appear in what you call \"the subtree\" (which looks nothing like a subtree to me, but does look like it's intended as a rewrite of your first form).\nNet of \"prettyfication\" issues (e.g. adding newlines and indents to make the resulting XML look pretty;-), this code should do what you're asking, if I understand you correctly:\ntry:\n import xml.etree.cElementTree as et\n import cStringIO as sio\nexcept ImportError:\n import xml.etree.ElementTree as et\n import StringIO as sio\n\nxmlin = sio.StringIO('''<a>\n <b>\n <c>Hello</c>\n </b>\n <d>\n <e>Hi</e>\n </d>\n</a>\n''')\n\ntin = et.parse(xmlin)\ntop = tin.getroot()\ntou = et.ElementTree(et.Element('root'))\nnewtop = tou.getroot()\nfor child in top.getchildren():\n subtree = et.Element(top.tag)\n subtree.append(child)\n newtop.append(subtree)\n\nimport sys\ntou.write(sys.stdout)\n\nThe try/except at the start tries to use the C versions of the modules on \"normal\" platforms where they're available, fall back to the pure-Python modules otherwise (for App Engine, Jython, IronPython, ...).\nThen I build two trees -- tin, the input one, from the XML string you're given; tou, the output one, initially empty except for the root element.\nAll the rest is a very simple loop on all subelements of tin's root: for each, a suitable subtree is built and appended to the subelements of tou's root -- that's all there is to it.\nThe last two lines show the resulting tree (not pretty, due to whitespace issues, but perfectly correct in terms of XML structure;-).\n"
] |
[
4
] |
[] |
[] |
[
"parsing",
"python",
"subtree",
"tree",
"xml"
] |
stackoverflow_0002414458_parsing_python_subtree_tree_xml.txt
|
Q:
How do I do this "order by" in Django, if I have foreign keys?
Suppose my model is this:
class Ego(models.Model):
event = models.ForeignKey(Event)
user = models.ForeignKey(User)
As you can see, this table has 2 columns, and they're both foreign keys.
How do I "order by" User.first_name?
Is this it? But it doesn't look like it.
Ego.objects.all().order_by("User.first_name")
A:
Solved.
I did this:
Ego.objects.all().select_related.order_by("auth_user.first_name")
|
How do I do this "order by" in Django, if I have foreign keys?
|
Suppose my model is this:
class Ego(models.Model):
event = models.ForeignKey(Event)
user = models.ForeignKey(User)
As you can see, this table has 2 columns, and they're both foreign keys.
How do I "order by" User.first_name?
Is this it? But it doesn't look like it.
Ego.objects.all().order_by("User.first_name")
|
[
"Solved.\nI did this:\nEgo.objects.all().select_related.order_by(\"auth_user.first_name\")\n\n"
] |
[
3
] |
[] |
[] |
[
"database",
"django",
"mysql",
"python"
] |
stackoverflow_0002414369_database_django_mysql_python.txt
|
Q:
Where is the full JID value when using xmpppy?
Where do I find the full JID value after connecting and authenticating against a Jabber server when using the xmpppy library?
I need the full JID for a subsequent Iq call to the server. Specifying the bare JID (user@domain.com) results in the following error:
If set, the 'from' attribute must be set to the user's full JID
I have read through the online API and looked at some of the source code but still cannot find it.
The full JID looks like this: user@domain.com/resource
A:
Use the non-underbar versions:
c = xmpp.client.Client(...)
# connect
jid = xmpp.JID(node=c.User, domain=c.Server, resource=c.Resource)
However, there is no need to set a from address. The server will do this for you for all of the stanzas you send.
A:
I don't see the JID being stored as such either, but in auth's sources, line 213, I see
self._User,self._Password,self._Resource=user,password,resource
where self is the instance of Client we're authenticating; so maybe you could just recover this info and build yourself a JID from that?
|
Where is the full JID value when using xmpppy?
|
Where do I find the full JID value after connecting and authenticating against a Jabber server when using the xmpppy library?
I need the full JID for a subsequent Iq call to the server. Specifying the bare JID (user@domain.com) results in the following error:
If set, the 'from' attribute must be set to the user's full JID
I have read through the online API and looked at some of the source code but still cannot find it.
The full JID looks like this: user@domain.com/resource
|
[
"Use the non-underbar versions:\nc = xmpp.client.Client(...)\n# connect\njid = xmpp.JID(node=c.User, domain=c.Server, resource=c.Resource)\n\nHowever, there is no need to set a from address. The server will do this for you for all of the stanzas you send.\n",
"I don't see the JID being stored as such either, but in auth's sources, line 213, I see\nself._User,self._Password,self._Resource=user,password,resource\n\nwhere self is the instance of Client we're authenticating; so maybe you could just recover this info and build yourself a JID from that?\n"
] |
[
2,
1
] |
[] |
[] |
[
"python",
"xmpp",
"xmpppy"
] |
stackoverflow_0002393011_python_xmpp_xmpppy.txt
|
Q:
Sort by key of dictionary inside a dictionary in Python
How to sort the following dictionary by the value of "remaining_pcs" or "discount_ratio"?
promotion_items = {
'one': {'remaining_pcs': 100, 'discount_ratio': 10},
'two': {'remaining_pcs': 200, 'discount_ratio': 20},
}
EDIT
What I mean is getting a sorted list of above dictionary, not to sort the dictionary itself.
A:
You can only sort the keys (or items or values) of a dictionary, into a separate list (as I wrote years ago in the recipe that @Andrew's quoting). E.g., to sort keys according to your stated criteria:
promotion_items = {
'one': {'remaining_pcs': 100, 'discount_ratio': 10},
'two': {'remaining_pcs': 200, 'discount_ratio': 20},
}
def bypcs(k):
return promotion_items[k]['remaining_pcs']
byrempcs = sorted(promotion_items, key=bypcs)
def bydra(k):
return promotion_items[k]['discount_ratio']
bydiscra = sorted(promotion_items, key=bydra)
A:
Please see To sort a dictionary:
Dictionaries can't be sorted -- a
mapping has no ordering! -- so, when
you feel the need to sort one, you no
doubt want to sort its keys (in a
separate list).
A:
If 'remaining_pcs' and 'discount_ratio' are the only keys in the nested dictionaries then:
result = sorted(promotion_items.iteritems(), key=lambda pair: pair[1].items())
If there could be other keys then:
def item_value(pair):
return pair[1]['remaining_pcs'], pair[1]['discount_ratio']
result = sorted(promotion_items.iteritems(), key=item_value)
|
Sort by key of dictionary inside a dictionary in Python
|
How to sort the following dictionary by the value of "remaining_pcs" or "discount_ratio"?
promotion_items = {
'one': {'remaining_pcs': 100, 'discount_ratio': 10},
'two': {'remaining_pcs': 200, 'discount_ratio': 20},
}
EDIT
What I mean is getting a sorted list of above dictionary, not to sort the dictionary itself.
|
[
"You can only sort the keys (or items or values) of a dictionary, into a separate list (as I wrote years ago in the recipe that @Andrew's quoting). E.g., to sort keys according to your stated criteria:\npromotion_items = {\n 'one': {'remaining_pcs': 100, 'discount_ratio': 10},\n 'two': {'remaining_pcs': 200, 'discount_ratio': 20},\n}\ndef bypcs(k):\n return promotion_items[k]['remaining_pcs']\nbyrempcs = sorted(promotion_items, key=bypcs)\ndef bydra(k):\n return promotion_items[k]['discount_ratio']\nbydiscra = sorted(promotion_items, key=bydra)\n\n",
"Please see To sort a dictionary:\n\nDictionaries can't be sorted -- a\n mapping has no ordering! -- so, when\n you feel the need to sort one, you no\n doubt want to sort its keys (in a\n separate list).\n\n",
"If 'remaining_pcs' and 'discount_ratio' are the only keys in the nested dictionaries then:\nresult = sorted(promotion_items.iteritems(), key=lambda pair: pair[1].items())\n\nIf there could be other keys then:\ndef item_value(pair):\n return pair[1]['remaining_pcs'], pair[1]['discount_ratio']\nresult = sorted(promotion_items.iteritems(), key=item_value)\n\n"
] |
[
5,
2,
0
] |
[] |
[] |
[
"dictionary",
"python",
"sorting"
] |
stackoverflow_0002414763_dictionary_python_sorting.txt
|
Q:
Concepts and tools required to scale up algorithms
I'd like to begin thinking about how I can scale up my algorithms that I write for data analysis so that they can be applied to arbitrarily large sets of data. I wonder what are the relevant concepts (threads, concurrency, immutable data structures, recursion) and tools (Hadoop/MapReduce, Terracota, and Eucalyptus) to make this happen, and how specifically these concepts and tools are related to each other. I have a rudimentary background in R, Python, and bash scripting and also C and Fortran programming, though I'm familiar with some basic functional programming concepts also. Do I need to change the way that I program, use a different language (Clojure, Haskell, etc.), or simply (or not so simply!) adapt something like R/Hadoop (HRIPE)... or write wrappers for Python to enable multi-threading or Hadoop access? I understand this would might involve requirements for additional hardware and I would like some basic idea of what the requirements/options available might be. My apologies for this rather large and yet vague question, but just trying to get started - thanks in advance!
A:
While languages and associated technologies/frameworks are important for scaling, they tend to pale in comparison to the importance of the algorithms, data structure, and architectures. Forget threads: the number of cores you can exploit that way is just too limited -- you want separate processes exchanging messages, so you can scale up at least to a small cluster of servers on a fast LAN (and ideally a large cluster as well!-).
Relational databases may be an exception to "technologies pale" -- they can really clamp you down when you're trying to scale up a few orders of magnitude. Is that your situation -- are you worried about mere dozens or at most hundreds of servers, or are you starting to think about thousands or myriads? In the former case, you can still stretch relational technology (e.g. by horizontal and vertical sharding) to support you -- in the latter, you're at the breaking point, or well past it, and must start thinking in terms of key/value stores.
Back to algorithms -- "data analysis" cover a wide range... most of my work for Google over the last few years falls in that range, e.g. in cluster management software, and currently in business intelligence. Do you need deterministic analysis (e.g. for accounting purposes, where you can't possibly overlook a single penny out of 8-digit figures), or can you stand some non-determinism? Most "data mining" applications fall into the second category -- you don't need total precision and determinism, just a good estimate of the range that your results can be proven to fall within, with, say, 95% probability.
This is particularly crucial if you ever need to do "real-near-time" data analysis -- near-real-time and 100% accuracy constraints on the same computation do not a happy camper make. But even in bulk/batch off-line data mining, if you can deliver results that are 95% guaranteed orders of magnitude faster than it would take for 99.99% (I don't know if data mining can ever be 100.00%!-), that may be a wonderful tradeoff.
The work I've been doing over the last few years has had a few requirements for "near-real-time" and many more requirements for off-line, "batch" analysis -- and only a very few cases where absolute accuracy is an absolute must. Gradually-refined sampling (when full guaranteed accuracy is not required), especially coupled with stratified sampling (designed closely with a domain expert!!!), has proven, over and over, to be a great approach; if you don't understand this terminology, and still want to scale up, beyond the terabytes, to exabytes and petabytes' worth of processing, you desperately need a good refresher course in Stats 201, or whatever course covers these concepts in your part of the woods (or on iTunes University, or the YouTube offerings in university channels, or blip.tv's, or whatever).
Python, R, C++, whatever, only come into play after you've mastered these algorithmic issues, the architectural issues that go with them (can you design a computation architecture to "statistically survive" the death of a couple of servers out of your myriad, recovering to within statistically significant accuracy without a lot of rework...?), and the supporting design and storage-technology choices.
A:
The main thing for scaling up to large data is to avoid situations where you're reading huge datasets into memory at once. In pythonic terms this generally means using iterators to consume the dataset in manageable pieces.
|
Concepts and tools required to scale up algorithms
|
I'd like to begin thinking about how I can scale up my algorithms that I write for data analysis so that they can be applied to arbitrarily large sets of data. I wonder what are the relevant concepts (threads, concurrency, immutable data structures, recursion) and tools (Hadoop/MapReduce, Terracota, and Eucalyptus) to make this happen, and how specifically these concepts and tools are related to each other. I have a rudimentary background in R, Python, and bash scripting and also C and Fortran programming, though I'm familiar with some basic functional programming concepts also. Do I need to change the way that I program, use a different language (Clojure, Haskell, etc.), or simply (or not so simply!) adapt something like R/Hadoop (HRIPE)... or write wrappers for Python to enable multi-threading or Hadoop access? I understand this would might involve requirements for additional hardware and I would like some basic idea of what the requirements/options available might be. My apologies for this rather large and yet vague question, but just trying to get started - thanks in advance!
|
[
"While languages and associated technologies/frameworks are important for scaling, they tend to pale in comparison to the importance of the algorithms, data structure, and architectures. Forget threads: the number of cores you can exploit that way is just too limited -- you want separate processes exchanging messages, so you can scale up at least to a small cluster of servers on a fast LAN (and ideally a large cluster as well!-).\nRelational databases may be an exception to \"technologies pale\" -- they can really clamp you down when you're trying to scale up a few orders of magnitude. Is that your situation -- are you worried about mere dozens or at most hundreds of servers, or are you starting to think about thousands or myriads? In the former case, you can still stretch relational technology (e.g. by horizontal and vertical sharding) to support you -- in the latter, you're at the breaking point, or well past it, and must start thinking in terms of key/value stores.\nBack to algorithms -- \"data analysis\" cover a wide range... most of my work for Google over the last few years falls in that range, e.g. in cluster management software, and currently in business intelligence. Do you need deterministic analysis (e.g. for accounting purposes, where you can't possibly overlook a single penny out of 8-digit figures), or can you stand some non-determinism? Most \"data mining\" applications fall into the second category -- you don't need total precision and determinism, just a good estimate of the range that your results can be proven to fall within, with, say, 95% probability.\nThis is particularly crucial if you ever need to do \"real-near-time\" data analysis -- near-real-time and 100% accuracy constraints on the same computation do not a happy camper make. But even in bulk/batch off-line data mining, if you can deliver results that are 95% guaranteed orders of magnitude faster than it would take for 99.99% (I don't know if data mining can ever be 100.00%!-), that may be a wonderful tradeoff.\nThe work I've been doing over the last few years has had a few requirements for \"near-real-time\" and many more requirements for off-line, \"batch\" analysis -- and only a very few cases where absolute accuracy is an absolute must. Gradually-refined sampling (when full guaranteed accuracy is not required), especially coupled with stratified sampling (designed closely with a domain expert!!!), has proven, over and over, to be a great approach; if you don't understand this terminology, and still want to scale up, beyond the terabytes, to exabytes and petabytes' worth of processing, you desperately need a good refresher course in Stats 201, or whatever course covers these concepts in your part of the woods (or on iTunes University, or the YouTube offerings in university channels, or blip.tv's, or whatever).\nPython, R, C++, whatever, only come into play after you've mastered these algorithmic issues, the architectural issues that go with them (can you design a computation architecture to \"statistically survive\" the death of a couple of servers out of your myriad, recovering to within statistically significant accuracy without a lot of rework...?), and the supporting design and storage-technology choices.\n",
"The main thing for scaling up to large data is to avoid situations where you're reading huge datasets into memory at once. In pythonic terms this generally means using iterators to consume the dataset in manageable pieces.\n"
] |
[
9,
3
] |
[] |
[] |
[
"concurrency",
"hadoop",
"multithreading",
"python",
"r"
] |
stackoverflow_0002414915_concurrency_hadoop_multithreading_python_r.txt
|
Q:
What is the fastest way to check whether a folder size is greater than a specific size?
What will be the fastest way to check whether a folder size is beyond a specific size say 10 MB, 1 Gb , 10 GB etc, without actually calculating the folder size. Something like quota. A Pythonic solution will be great, but standard UNIX utilities also welcome
A:
import os
from os.path import join, getsize
def getsize_limited(directory, limit):
total_size = 0
for root, dirs, files in os.walk(directory, topdown=False):
for name in files:
total_size += getsize(join(root, name))
if total_size > limit:
return limit, False
return total_size, True
Example:
size, within_limit = getsize_limited(os.getcwd(), limit=10**6)
A:
I'd have to say it's impossible. I don't believe any filesystems cache folder sizes. Whatever you do is going to have to walk the tree in some fashion or another. Using du is probably the fastest method since it's all going to be happening in C.
If you know the maximum filesize expected or supported you could perhaps optimise a little by counting the enties in each folder rather than the sizes and short-cutting in the case where there aren't enough files to meet the limit.
A:
you can use du -sb, which still have to calculate folder size .eg
threshold=1024000 #bytes
path="/your/path"
s=$(du -sb "$path")
set -- $s
size=$1
if [ "$size" -gt $threshold ];then
echo "size of $path greater than $threshold"
fi
A:
Folder size is still the total size of the folder contents.
You may try to call du -s foldername from python
|
What is the fastest way to check whether a folder size is greater than a specific size?
|
What will be the fastest way to check whether a folder size is beyond a specific size say 10 MB, 1 Gb , 10 GB etc, without actually calculating the folder size. Something like quota. A Pythonic solution will be great, but standard UNIX utilities also welcome
|
[
"import os\nfrom os.path import join, getsize\n\ndef getsize_limited(directory, limit):\n total_size = 0\n for root, dirs, files in os.walk(directory, topdown=False):\n for name in files:\n total_size += getsize(join(root, name))\n if total_size > limit:\n return limit, False\n return total_size, True\n\nExample:\nsize, within_limit = getsize_limited(os.getcwd(), limit=10**6)\n\n",
"I'd have to say it's impossible. I don't believe any filesystems cache folder sizes. Whatever you do is going to have to walk the tree in some fashion or another. Using du is probably the fastest method since it's all going to be happening in C.\nIf you know the maximum filesize expected or supported you could perhaps optimise a little by counting the enties in each folder rather than the sizes and short-cutting in the case where there aren't enough files to meet the limit.\n",
"you can use du -sb, which still have to calculate folder size .eg\nthreshold=1024000 #bytes\npath=\"/your/path\"\ns=$(du -sb \"$path\")\nset -- $s\nsize=$1\nif [ \"$size\" -gt $threshold ];then\n echo \"size of $path greater than $threshold\"\nfi\n\n",
"Folder size is still the total size of the folder contents.\nYou may try to call du -s foldername from python\n"
] |
[
4,
2,
2,
1
] |
[] |
[] |
[
"linux",
"python",
"shell"
] |
stackoverflow_0002414917_linux_python_shell.txt
|
Q:
Add directory to PYTHONPATH ( multiple drives ), for auto-complete
I have 2 hard-drives, C:\ and D:\
Django imports correctly (which is in my C drive), but my application is on my D drive. I can't move it to the C drive because of some back-up software I'm running/
I'm trying to get auto-complete to work in Komodo Edit 5 which works fine for Django, but not for my application. There are a few other reasons for wanting this as well (one of them being my rampant OCD). I have added D:\dev\projects to my PYTHONPATH and my application is a couple folders deep from there. I included a ; between variables but not at the end, and I left off the trailing slash. I'm on Win XP. Here's my exact PYTHONPATH in my settings:
C:\Python26\Lib\site-packages\django-trunk;D:\dev\projects
and here is my Python path as a list output by os.environ['PYTHONPATH'].split(os.pathsep)
['C:\\Python26\\Lib\\site-packages\\django-trunk', 'D:\\dev\\projects']
Why doesn't this work? Django runs OK for my app that is there, but I understand that Django sets an environment variable dynamically in manage.py. I don't get it. I've restarted my computer, and now I'm pulling out my hair.
A:
Have you tried adding Additional import directories in Edit/Preferences/ under Languages/Python in Komodo?
Edit: I think you can also add a .pth file in [komodo-install-dir]/lib/mozilla/python/ or C:\[PythonVersion]\Lib\site-packages\ containing all other path you might want to be available. Not sure wich way is more appropriate in your case.
|
Add directory to PYTHONPATH ( multiple drives ), for auto-complete
|
I have 2 hard-drives, C:\ and D:\
Django imports correctly (which is in my C drive), but my application is on my D drive. I can't move it to the C drive because of some back-up software I'm running/
I'm trying to get auto-complete to work in Komodo Edit 5 which works fine for Django, but not for my application. There are a few other reasons for wanting this as well (one of them being my rampant OCD). I have added D:\dev\projects to my PYTHONPATH and my application is a couple folders deep from there. I included a ; between variables but not at the end, and I left off the trailing slash. I'm on Win XP. Here's my exact PYTHONPATH in my settings:
C:\Python26\Lib\site-packages\django-trunk;D:\dev\projects
and here is my Python path as a list output by os.environ['PYTHONPATH'].split(os.pathsep)
['C:\\Python26\\Lib\\site-packages\\django-trunk', 'D:\\dev\\projects']
Why doesn't this work? Django runs OK for my app that is there, but I understand that Django sets an environment variable dynamically in manage.py. I don't get it. I've restarted my computer, and now I'm pulling out my hair.
|
[
"Have you tried adding Additional import directories in Edit/Preferences/ under Languages/Python in Komodo?\nEdit: I think you can also add a .pth file in [komodo-install-dir]/lib/mozilla/python/ or C:\\[PythonVersion]\\Lib\\site-packages\\ containing all other path you might want to be available. Not sure wich way is more appropriate in your case.\n"
] |
[
2
] |
[] |
[] |
[
"autocomplete",
"python",
"pythonpath"
] |
stackoverflow_0002415014_autocomplete_python_pythonpath.txt
|
Q:
How to install python modules and dependents easily?
Are there any easy installation tools like "perl -MCPAN -e shell;" to install python modules and its dependents???
A:
pip is the most up to date tool to do this: you use it by issuing the command
pip install <packagename>
The "old" way of doing the same is to easy_install:
easy_install <packagename>
If you have easy_install already on your system, it is advisable to run easy_install pip to upgrade to pip
Both of these install packages from the Python Package Index (pypi)
The package that provides the easy_install command is usually called python-setuptools (or something similar)
|
How to install python modules and dependents easily?
|
Are there any easy installation tools like "perl -MCPAN -e shell;" to install python modules and its dependents???
|
[
"pip is the most up to date tool to do this: you use it by issuing the command \npip install <packagename>\nThe \"old\" way of doing the same is to easy_install:\neasy_install <packagename>\n\nIf you have easy_install already on your system, it is advisable to run easy_install pip to upgrade to pip\nBoth of these install packages from the Python Package Index (pypi)\nThe package that provides the easy_install command is usually called python-setuptools (or something similar)\n"
] |
[
6
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002415166_python.txt
|
Q:
How to make script/program to make it so an application is always running?
I have a simple .exe that needs to be running continuously.
Unfortunately, sometimes it crashes unexpectedly, and there's nothing that can be done for this.
I'm thinking of like a C# program that scans the running application tree on a timer and if the process stops running it re-launches it... ? Not sure how to do that though....
Any other ideas?
A:
It's fairly easy to do that, but the "crashes unexpectedly, and there's nothing that can be done for this" sounds highly suspect to me. Perhaps you mean the program in question is from a third party, and you need to work around problems they can't/won't fix?
In any case, there's quite a bit of sample code to do exactly what you're talking about.
A:
The first solution would be to fix your EXE, so it does not crash. If you can not fix it now, you probably need to add exception handling, so you can catch the exception, and not close the EXE.
Second solution is to write simple guard programm that will start your simple .exe and will monitor specific process handle. It will restart your program when it closes.
A:
easiest way is to have you program see if an instance of itself is running and exit if it is. Set up a scheduled task to run it every couple of minutes.
class Program
{
static void Main(string[] args)
{
if (IsRunning())
{
return;
}
else
{
for (int x = 0; x < 10; x++)
{
//Do Stuff
System.Threading.Thread.Sleep(1000);
}
}
}
private static bool IsRunning()
{
Process[] P = Process.GetProcessesByName( Process.GetCurrentProcess().ProcessName ) ;
return P.Count() > 1;
}
}
A:
One trick occasionally employed by malware in days past was to have two processes that each monitor the currently running processes and restart the other process if it is terminated.
The System.Diagnostics namespace has classes which can help, particularly "Process".
For example
static Process[] Process.GetProcesses()
returns a list of all the currently running processes.
If your other process is not in this list, you just restart it with, for example
Process.Start()
A:
Your program needs to initially start your target process itself (with Process.Start), then simply wait for it to terminate (with WaitForExit on object that is returned by Process.Start()). After that whole procedure is repeated.
This way you'd be sure that you are watching the process you are interested in, and you don't need to poll process list at all.
Process.Start() and WaitForExit() usage example.
|
How to make script/program to make it so an application is always running?
|
I have a simple .exe that needs to be running continuously.
Unfortunately, sometimes it crashes unexpectedly, and there's nothing that can be done for this.
I'm thinking of like a C# program that scans the running application tree on a timer and if the process stops running it re-launches it... ? Not sure how to do that though....
Any other ideas?
|
[
"It's fairly easy to do that, but the \"crashes unexpectedly, and there's nothing that can be done for this\" sounds highly suspect to me. Perhaps you mean the program in question is from a third party, and you need to work around problems they can't/won't fix?\nIn any case, there's quite a bit of sample code to do exactly what you're talking about.\n",
"The first solution would be to fix your EXE, so it does not crash. If you can not fix it now, you probably need to add exception handling, so you can catch the exception, and not close the EXE.\nSecond solution is to write simple guard programm that will start your simple .exe and will monitor specific process handle. It will restart your program when it closes.\n",
"easiest way is to have you program see if an instance of itself is running and exit if it is. Set up a scheduled task to run it every couple of minutes.\nclass Program\n{\n static void Main(string[] args)\n {\n if (IsRunning())\n {\n return;\n }\n else\n {\n for (int x = 0; x < 10; x++)\n {\n //Do Stuff\n System.Threading.Thread.Sleep(1000);\n }\n }\n }\n\n private static bool IsRunning()\n {\n\n Process[] P = Process.GetProcessesByName( Process.GetCurrentProcess().ProcessName ) ;\n return P.Count() > 1;\n }\n}\n\n",
"One trick occasionally employed by malware in days past was to have two processes that each monitor the currently running processes and restart the other process if it is terminated.\nThe System.Diagnostics namespace has classes which can help, particularly \"Process\".\nFor example\nstatic Process[] Process.GetProcesses()\n\nreturns a list of all the currently running processes.\nIf your other process is not in this list, you just restart it with, for example\nProcess.Start()\n\n",
"Your program needs to initially start your target process itself (with Process.Start), then simply wait for it to terminate (with WaitForExit on object that is returned by Process.Start()). After that whole procedure is repeated.\nThis way you'd be sure that you are watching the process you are interested in, and you don't need to poll process list at all.\nProcess.Start() and WaitForExit() usage example.\n"
] |
[
2,
1,
0,
0,
0
] |
[] |
[] |
[
"c#",
"c++",
"python"
] |
stackoverflow_0002414616_c#_c++_python.txt
|
Q:
Suggestions required for generating this logging file structure in django project
Can anyone please suggest how to generate log files having following directory-file structure using python logging in django project.
logs/2009-03-09
/errors.log
/warnings.log
/info.log
/emails.log
/messages.log
logs/2009-03-08
/errors.log
/warnings.log
/info.log
/emails.log
/messages.log
A:
Set up FileHandler instances with Filter instances which match the criteria for those files.
Add the handlers to the root logger.
Profit ;-)
See this other answer for an example of a filter which matches a specific level. You can use that as an example to create your own custom filters for 'emails' and 'messages' logs.
Use strftime to format the paths with dates in them.
|
Suggestions required for generating this logging file structure in django project
|
Can anyone please suggest how to generate log files having following directory-file structure using python logging in django project.
logs/2009-03-09
/errors.log
/warnings.log
/info.log
/emails.log
/messages.log
logs/2009-03-08
/errors.log
/warnings.log
/info.log
/emails.log
/messages.log
|
[
"\nSet up FileHandler instances with Filter instances which match the criteria for those files.\nAdd the handlers to the root logger.\nProfit ;-)\n\nSee this other answer for an example of a filter which matches a specific level. You can use that as an example to create your own custom filters for 'emails' and 'messages' logs.\nUse strftime to format the paths with dates in them.\n"
] |
[
3
] |
[] |
[] |
[
"django",
"logging",
"python"
] |
stackoverflow_0002408800_django_logging_python.txt
|
Q:
python ConfigParser module
I have the following ini file
[Section]
value=test
When i use the ConfigParser Module :
import ConfigParser
config = ConfigParser.ConfigParser()
config.read('config.ini')
str=config.get('Section', 'value')
if str == 'test':
print 1
else :
print 0
it always print 0 could someone help
A:
try
print str
and see what the value is.
|
python ConfigParser module
|
I have the following ini file
[Section]
value=test
When i use the ConfigParser Module :
import ConfigParser
config = ConfigParser.ConfigParser()
config.read('config.ini')
str=config.get('Section', 'value')
if str == 'test':
print 1
else :
print 0
it always print 0 could someone help
|
[
"try \nprint str\n\nand see what the value is.\n"
] |
[
0
] |
[] |
[] |
[
"configparser",
"python"
] |
stackoverflow_0002415586_configparser_python.txt
|
Q:
"Broken" unicode strings encoded in UTF-8?
I have been studying unicode and its Python implementation now for two days, and I think I'm getting a glimpse of what it is about. Just to get confident, I'm asking if my assumptions for my current problems are correct.
In Django, forms give me unicode strings which I suspect to be "broken". Unicode strings in Python should be encoded in UTF-8, is that right? After entering the string "fähre" into a text field, the browser sends the string "f%c3%a4hre" in the POST request (checked via wireshark). When I retrieve the value via form.cleaned_data, I'm getting the string u'f\xa4hre' (note it is a unicode string), though. As far as I understand that, that is ISO-8859-1-encoded unicode string, which is incorrect. The correct string should be u'f\xc3\xa4hre', which would be a UTF-8-encoded unicode string. Is that a Django bug or is there something wrong with my understanding of it?
To fix the issue, I wrote a function to apply it to any text input from Django forms:
def fix_broken_unicode(s):
return unicode(s.encode(u'utf-8'), u'iso-8859-1')
which does
>>> fix_broken_unicode(u'f\xa4hre')
u'f\xc3\xa4hre'
That doesn't seem very elegant to me, but setting Django's settings.DEFAULT_CHARSET to 'utf-8' didn't help, nor did anything else. I am trying to work with unicode throughout the whole application so I won't get any weird errors later on, but it obviously does not suffice to mark all strings with u'...'.
Edit: Considering the answers from Dirk and sth, I will now save the strings to the database as they are. The real problem was that I was trying to urlencode these kinds of strings to use them as input for the Twitter API etc. In GET or POST requests, though, UTF-8 encoding is obviously expected which the standard urllib.urlencode() function does not process correctly (throws exceptions). Take a look at my solution in the pastebin and feel free to comment on it also.
A:
u'f\xa4hre'is a unicode string, not encoded as anything. The unicode codepoint 0xa4 is the character ä. It is not really important that ä would also be encoded as byte 0xa4 in ISO-8859-1.
The unicode string can contain any unicode characters without encoding them in some way. For example 轮渡 would be represented as u'\u8f6e\u6e21', which are simply two unicode codepoints. The UTF-8 encoding would be the much longer '\xe8\xbd\xae\xe6\xb8\xa1'.
So there is no need to fix the encoding, you are just seeing the internal representation of the unicode string.
A:
Not exactly: after having been decoded, the unicode string is unicode which means, it may contain characters with codes beyond 255. How the interpreter represents these depends on the platform, but usually nowadays it uses character elements with a width of at least 16 bits. ISO-8859-1 is a proper subset of unicode. Thus, the string u'f\xa4hre' is actually proper -- the \xa4 is a rendering artifact, since Python doesn't know if (and when) it is safe to include characters with codes beyond a certain range on the console.
UTF-8 is a transport encoding that is, a special way to write unicode data such, that it can be stored in "channels" with an element width of 8 bits per character/byte. In order to compute the proper "external" (or transport) encoding of a unicode string, you'd use the encode method, passing the desired representation. It returns a properly encoded byte string (as opposed to a unicode character string).
The reverse transformation is decode which takes a byte string and an encoding name and yields a unicode character string.
|
"Broken" unicode strings encoded in UTF-8?
|
I have been studying unicode and its Python implementation now for two days, and I think I'm getting a glimpse of what it is about. Just to get confident, I'm asking if my assumptions for my current problems are correct.
In Django, forms give me unicode strings which I suspect to be "broken". Unicode strings in Python should be encoded in UTF-8, is that right? After entering the string "fähre" into a text field, the browser sends the string "f%c3%a4hre" in the POST request (checked via wireshark). When I retrieve the value via form.cleaned_data, I'm getting the string u'f\xa4hre' (note it is a unicode string), though. As far as I understand that, that is ISO-8859-1-encoded unicode string, which is incorrect. The correct string should be u'f\xc3\xa4hre', which would be a UTF-8-encoded unicode string. Is that a Django bug or is there something wrong with my understanding of it?
To fix the issue, I wrote a function to apply it to any text input from Django forms:
def fix_broken_unicode(s):
return unicode(s.encode(u'utf-8'), u'iso-8859-1')
which does
>>> fix_broken_unicode(u'f\xa4hre')
u'f\xc3\xa4hre'
That doesn't seem very elegant to me, but setting Django's settings.DEFAULT_CHARSET to 'utf-8' didn't help, nor did anything else. I am trying to work with unicode throughout the whole application so I won't get any weird errors later on, but it obviously does not suffice to mark all strings with u'...'.
Edit: Considering the answers from Dirk and sth, I will now save the strings to the database as they are. The real problem was that I was trying to urlencode these kinds of strings to use them as input for the Twitter API etc. In GET or POST requests, though, UTF-8 encoding is obviously expected which the standard urllib.urlencode() function does not process correctly (throws exceptions). Take a look at my solution in the pastebin and feel free to comment on it also.
|
[
"u'f\\xa4hre'is a unicode string, not encoded as anything. The unicode codepoint 0xa4 is the character ä. It is not really important that ä would also be encoded as byte 0xa4 in ISO-8859-1.\nThe unicode string can contain any unicode characters without encoding them in some way. For example 轮渡 would be represented as u'\\u8f6e\\u6e21', which are simply two unicode codepoints. The UTF-8 encoding would be the much longer '\\xe8\\xbd\\xae\\xe6\\xb8\\xa1'.\nSo there is no need to fix the encoding, you are just seeing the internal representation of the unicode string.\n",
"Not exactly: after having been decoded, the unicode string is unicode which means, it may contain characters with codes beyond 255. How the interpreter represents these depends on the platform, but usually nowadays it uses character elements with a width of at least 16 bits. ISO-8859-1 is a proper subset of unicode. Thus, the string u'f\\xa4hre' is actually proper -- the \\xa4 is a rendering artifact, since Python doesn't know if (and when) it is safe to include characters with codes beyond a certain range on the console.\nUTF-8 is a transport encoding that is, a special way to write unicode data such, that it can be stored in \"channels\" with an element width of 8 bits per character/byte. In order to compute the proper \"external\" (or transport) encoding of a unicode string, you'd use the encode method, passing the desired representation. It returns a properly encoded byte string (as opposed to a unicode character string).\nThe reverse transformation is decode which takes a byte string and an encoding name and yields a unicode character string.\n"
] |
[
4,
1
] |
[] |
[] |
[
"django",
"python",
"unicode",
"utf_8"
] |
stackoverflow_0002415628_django_python_unicode_utf_8.txt
|
Q:
Send AT-command through bluetooth from python application
hai guyz,
how can i send AT-command through bluetooth from a python application?
OS:fedora 8
Any one please healp me with the code?
which package i need to import?
from where can i download it?
A:
To get a connection over bluetooth to your IP modem, you want to use the bluetooth
rfcomm driver:
michael@challenger:~> cat /etc/bluetooth/rfcomm.conf
rfcomm0 {
# Automatically bind the device at startup
bind yes;
# Bluetooth address of the device
device 00:1C:CC:XX:XX:XX;
# RFCOMM channel for the connection
channel 1;
# Description of the connection
comment "Blackberry";
}
This is the setup I use for mine - YMMV.
michael@challenger:~> cu -l /dev/rfcomm0
Connected.
ATI
Research in Motion BlackBerry IP Modem
OK
Once you have the rfcomm0 port, you treat the port as a standard serial port and you're good to go.
A:
I think this is better.......
import bluetooth
sockfd = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
sockfd.connect(('00:24:7E:9E:55:0D', 1)) # BT Address
sockfd.send('ATZ\r')
time.sleep(1)
sockfd.send(chr(26))
sockfd.close()
|
Send AT-command through bluetooth from python application
|
hai guyz,
how can i send AT-command through bluetooth from a python application?
OS:fedora 8
Any one please healp me with the code?
which package i need to import?
from where can i download it?
|
[
"To get a connection over bluetooth to your IP modem, you want to use the bluetooth\nrfcomm driver:\nmichael@challenger:~> cat /etc/bluetooth/rfcomm.conf \nrfcomm0 {\n # Automatically bind the device at startup\n bind yes;\n # Bluetooth address of the device\n device 00:1C:CC:XX:XX:XX;\n # RFCOMM channel for the connection\n channel 1;\n # Description of the connection\n comment \"Blackberry\";\n}\n\nThis is the setup I use for mine - YMMV.\nmichael@challenger:~> cu -l /dev/rfcomm0\nConnected.\nATI\nResearch in Motion BlackBerry IP Modem\n\nOK\n\nOnce you have the rfcomm0 port, you treat the port as a standard serial port and you're good to go.\n",
"I think this is better....... \nimport bluetooth \nsockfd = bluetooth.BluetoothSocket(bluetooth.RFCOMM) \nsockfd.connect(('00:24:7E:9E:55:0D', 1)) # BT Address \nsockfd.send('ATZ\\r') \ntime.sleep(1) \nsockfd.send(chr(26)) \nsockfd.close()\n\n"
] |
[
1,
1
] |
[] |
[] |
[
"at_command",
"fedora",
"python",
"sms"
] |
stackoverflow_0002161365_at_command_fedora_python_sms.txt
|
Q:
Error in gui programming in python using tkinter
#!/usr/bin/python
# -*- coding: iso-8859-1 -*-
import Tkinter
class simpleapp_tk(Tkinter.Tk):
def __init__(self,parent):
Tkinter.Tk.__init__(self,parent)
self.parent=parent
def initialize(self):
self.grid()
self.entry=Tkinter.Entry(self)
self.entry.grid(column=0,row=0,sticky='EW')
self.entry.bind("<Return>",self.OnPressEnter)
button=Tkinter.Button(self,test="Post it!",command=self.OnButtonClick)
button.grid(column=1,row=0)
label=Tkinter.Label(self,anchor="w",fg="white",bg="blue")
label=grid(column=0,row=1,columnspan=2,sticky='EW')
self.grid_columnconfigure(0,weight=1)
def OnButtonClick(self):
print "you clicked the button!"
def OnPressEnter(self,event):
print "you pressed enter!"
if __name__=="__main__":
app=simpleapp_tk(None)
app.title('poster')
app.mainloop()
I wrote this program so as to make a box to input text and a button, but it shows nothing apart from a window. Where is the error?
A:
The main issue was that you forgot to call app.initialize(), but you also had a couple of typos. I've pointed out where in the comments in this fixed version.
import Tkinter
class simpleapp_tk(Tkinter.Tk):
def __init__(self,parent):
Tkinter.Tk.__init__(self,parent)
self.parent=parent
def initialize(self):
self.grid()
self.entry=Tkinter.Entry(self)
self.entry.grid(column=0,row=0,sticky='EW')
self.entry.bind("<Return>",self.OnPressEnter)
button=Tkinter.Button(self,text="Post it!",command=self.OnButtonClick)
# the text keyword argument was mis-typed as 'test'
button.grid(column=1,row=0)
label=Tkinter.Label(self,anchor="w",fg="white",bg="blue")
label.grid(column=0,row=1,columnspan=2,sticky='EW')
# the . in label.grid was mis-typed as '='
self.grid_columnconfigure(0,weight=1)
def OnButtonClick(self):
print "you clicked the button!"
def OnPressEnter(self,event):
print "you pressed enter!"
if __name__=="__main__":
app=simpleapp_tk(None)
app.title('poster')
app.initialize() # you forgot this
app.mainloop()
|
Error in gui programming in python using tkinter
|
#!/usr/bin/python
# -*- coding: iso-8859-1 -*-
import Tkinter
class simpleapp_tk(Tkinter.Tk):
def __init__(self,parent):
Tkinter.Tk.__init__(self,parent)
self.parent=parent
def initialize(self):
self.grid()
self.entry=Tkinter.Entry(self)
self.entry.grid(column=0,row=0,sticky='EW')
self.entry.bind("<Return>",self.OnPressEnter)
button=Tkinter.Button(self,test="Post it!",command=self.OnButtonClick)
button.grid(column=1,row=0)
label=Tkinter.Label(self,anchor="w",fg="white",bg="blue")
label=grid(column=0,row=1,columnspan=2,sticky='EW')
self.grid_columnconfigure(0,weight=1)
def OnButtonClick(self):
print "you clicked the button!"
def OnPressEnter(self,event):
print "you pressed enter!"
if __name__=="__main__":
app=simpleapp_tk(None)
app.title('poster')
app.mainloop()
I wrote this program so as to make a box to input text and a button, but it shows nothing apart from a window. Where is the error?
|
[
"The main issue was that you forgot to call app.initialize(), but you also had a couple of typos. I've pointed out where in the comments in this fixed version.\nimport Tkinter\n\nclass simpleapp_tk(Tkinter.Tk):\n def __init__(self,parent):\n Tkinter.Tk.__init__(self,parent)\n self.parent=parent\n def initialize(self):\n self.grid()\n\n self.entry=Tkinter.Entry(self)\n self.entry.grid(column=0,row=0,sticky='EW')\n self.entry.bind(\"<Return>\",self.OnPressEnter)\n\n button=Tkinter.Button(self,text=\"Post it!\",command=self.OnButtonClick)\n # the text keyword argument was mis-typed as 'test'\n\n button.grid(column=1,row=0)\n\n label=Tkinter.Label(self,anchor=\"w\",fg=\"white\",bg=\"blue\")\n label.grid(column=0,row=1,columnspan=2,sticky='EW')\n # the . in label.grid was mis-typed as '='\n\n self.grid_columnconfigure(0,weight=1)\n\n def OnButtonClick(self):\n print \"you clicked the button!\"\n\n def OnPressEnter(self,event):\n print \"you pressed enter!\"\n\nif __name__==\"__main__\":\n app=simpleapp_tk(None)\n app.title('poster')\n app.initialize() # you forgot this\n app.mainloop()\n\n"
] |
[
4
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002415950_python.txt
|
Q:
Allow user to select a file or a folder in QFileDialog
In PyQt you can do something like the following to allow the user to select a file
filename = QtGui.QFileDialog.getOpenFileName(self, "Choose file..")
However I would like a QFileDialog to open in which the user would be able to select either a file or a directory. I'm sure I've seen this feature in PyQt applications before, but I can't seem to find any way to do it.
A:
From what I remember you need to write your own QFileDialog and set proper mode. I believe this should be QFileDialog.ExistingFile & QFileDialog.Directory.
You can try to write your own static method basing on the getExisitingDirectory (from C++ repository):
QString QFileDialog::getExistingDirectory(QWidget *parent,
const QString &caption,
const QString &dir,
Options options)
{
if (qt_filedialog_existing_directory_hook && !(options & DontUseNativeDialog))
return qt_filedialog_existing_directory_hook(parent, caption, dir, options);
QFileDialogArgs args;
args.parent = parent;
args.caption = caption;
args.directory = QFileDialogPrivate::workingDirectory(dir);
args.mode = (options & ShowDirsOnly ? DirectoryOnly : Directory);
args.options = options;
#if defined(Q_WS_WIN)
if (qt_use_native_dialogs && !(args.options & DontUseNativeDialog) && (options & ShowDirsOnly)
#if defined(Q_WS_WINCE)
&& qt_priv_ptr_valid
#endif
) {
return qt_win_get_existing_directory(args);
}
#endif
// create a qt dialog
QFileDialog dialog(args);
if (dialog.exec() == QDialog::Accepted) {
return dialog.selectedFiles().value(0);
}
return QString();
}
|
Allow user to select a file or a folder in QFileDialog
|
In PyQt you can do something like the following to allow the user to select a file
filename = QtGui.QFileDialog.getOpenFileName(self, "Choose file..")
However I would like a QFileDialog to open in which the user would be able to select either a file or a directory. I'm sure I've seen this feature in PyQt applications before, but I can't seem to find any way to do it.
|
[
"From what I remember you need to write your own QFileDialog and set proper mode. I believe this should be QFileDialog.ExistingFile & QFileDialog.Directory.\nYou can try to write your own static method basing on the getExisitingDirectory (from C++ repository):\nQString QFileDialog::getExistingDirectory(QWidget *parent,\n const QString &caption,\n const QString &dir,\n Options options)\n{\n if (qt_filedialog_existing_directory_hook && !(options & DontUseNativeDialog))\n return qt_filedialog_existing_directory_hook(parent, caption, dir, options);\n QFileDialogArgs args;\n args.parent = parent;\n args.caption = caption;\n args.directory = QFileDialogPrivate::workingDirectory(dir);\n args.mode = (options & ShowDirsOnly ? DirectoryOnly : Directory);\n args.options = options;\n\n#if defined(Q_WS_WIN)\n if (qt_use_native_dialogs && !(args.options & DontUseNativeDialog) && (options & ShowDirsOnly)\n#if defined(Q_WS_WINCE)\n && qt_priv_ptr_valid\n#endif\n ) {\n return qt_win_get_existing_directory(args);\n }\n#endif\n\n // create a qt dialog\n QFileDialog dialog(args);\n if (dialog.exec() == QDialog::Accepted) {\n return dialog.selectedFiles().value(0);\n }\n return QString();\n}\n\n"
] |
[
0
] |
[] |
[] |
[
"pyqt",
"python"
] |
stackoverflow_0002413692_pyqt_python.txt
|
Q:
SQLAlchemy with multiple primary keys does not automatically set any
I had a simple table:
class test(Base):
__tablename__ = 'test'
id = Column(Integer, primary_key=True)
title = Column(String)
def __init__(self, title):
self.title = title
When using this table, id was set automatically. I want to add another field that is unique and efficient to search, so I added the field:
id2 = Column(String, primary_key=True)
And updated the constructor:
def __init__(self, id2, title):
self.id2 = id2
self.title = title
Now, id is no longer automatically set, or rather I get the error:
IntegrityError: (IntegrityError) test.id may not be NULL u'INSERT INTO test (id2, title) VALUES (?, ?)' [u'a', u'b']
Is there a way to maintain a second primary key without removing the autoincrement behavior of the first?
A:
I have few problems here
1) What is a purpose of your hand-made __init__? If it does just what you wrote, you can omit constructor completely since SQLAlchemy machinery generates exactly the same constructor for all your models automagically. Although if you take some additional actions and thus have to override __init__ you probably want to call super-constructor:
def __init__(self, lalala, *args, **kwargs):
# do something with lalala here...
super(test, self).__init__(*args, **kwargs)
# ...or here
2) Once you have more than one field with primary_key=True you get a model with composite primary key. Composite primary keys are not generated automatically since there is ambiguity here: how should subsequent key differ from previous?
I suspect what you're trying can be achieved using unique indexed column and not using composite key:
class test(Base):
__tablename__ = 'test'
id = Column(Integer, primary_key=True)
id2 = Column(String, index=True, unique=True)
title = Column(String)
# def __init__(self) is not necessary
|
SQLAlchemy with multiple primary keys does not automatically set any
|
I had a simple table:
class test(Base):
__tablename__ = 'test'
id = Column(Integer, primary_key=True)
title = Column(String)
def __init__(self, title):
self.title = title
When using this table, id was set automatically. I want to add another field that is unique and efficient to search, so I added the field:
id2 = Column(String, primary_key=True)
And updated the constructor:
def __init__(self, id2, title):
self.id2 = id2
self.title = title
Now, id is no longer automatically set, or rather I get the error:
IntegrityError: (IntegrityError) test.id may not be NULL u'INSERT INTO test (id2, title) VALUES (?, ?)' [u'a', u'b']
Is there a way to maintain a second primary key without removing the autoincrement behavior of the first?
|
[
"I have few problems here\n1) What is a purpose of your hand-made __init__? If it does just what you wrote, you can omit constructor completely since SQLAlchemy machinery generates exactly the same constructor for all your models automagically. Although if you take some additional actions and thus have to override __init__ you probably want to call super-constructor:\ndef __init__(self, lalala, *args, **kwargs):\n # do something with lalala here...\n super(test, self).__init__(*args, **kwargs)\n # ...or here\n\n2) Once you have more than one field with primary_key=True you get a model with composite primary key. Composite primary keys are not generated automatically since there is ambiguity here: how should subsequent key differ from previous?\nI suspect what you're trying can be achieved using unique indexed column and not using composite key:\nclass test(Base):\n __tablename__ = 'test'\n id = Column(Integer, primary_key=True)\n id2 = Column(String, index=True, unique=True)\n title = Column(String)\n\n # def __init__(self) is not necessary\n\n"
] |
[
7
] |
[] |
[] |
[
"database",
"primary_key",
"python",
"sqlalchemy"
] |
stackoverflow_0002415842_database_primary_key_python_sqlalchemy.txt
|
Q:
Error while posting a Twitter message through a python app
#!/usr/bin/python
# -*- coding: iso-8859-1 -*-
import Tkinter
import twitter
class simpleapp_tk(Tkinter.Tk):
def __init__(self,parent):
Tkinter.Tk.__init__(self,parent)
self.parent = parent
self.initialize()
def initialize(self):
self.grid()
api=twitter.api()(username='-----',password='----')
self.entryVariable = Tkinter.StringVar()
self.entry = Tkinter.Entry(self,textvariable=self.entryVariable)
self.entry.grid(column=0,row=0,sticky='EW')
self.entry.bind("<Return>", self.OnPressEnter)
self.entryVariable.set(u"Enter text here.")
button = Tkinter.Button(self,text=u"POST IT !",
command=self.OnButtonClick)
button.grid(column=1,row=0)
self.labelVariable = Tkinter.StringVar()
label = Tkinter.Label(self,textvariable=self.labelVariable,
anchor="w",fg="white",bg="blue")
label.grid(column=0,row=1,columnspan=2,sticky='EW')
self.labelVariable.set(u"Hello !")
self.grid_columnconfigure(0,weight=1)
self.resizable(True,False)
self.update()
self.geometry(self.geometry())
self.entry.focus_set()
self.entry.selection_range(0, Tkinter.END)
def OnButtonClick(self):
self.labelVariable.set( self.entryVariable.get()+" (You clicked the button)" )
self.entry.focus_set()
self.entry.selection_range(0, Tkinter.END)
status=api.PostUpdate(self.entry)
def OnPressEnter(self,event):
self.labelVariable.set( self.entryVariable.get()+" (You pressed ENTER)" )
self.entry.focus_set()
self.entry.selection_range(0, Tkinter.END)
if __name__ == "__main__":
app = simpleapp_tk(None)
app.title('POSTit')
app.initialize()
app.mainloop()
the error displayed is .
AttributeError: 'module' object has no attribute 'api'
A:
The error message is clear, isn't it? The twitter module has no attribute named "api".
A quick google showed me some examples that have a ".Api()" method (capital A). Maybe that is your problem.
|
Error while posting a Twitter message through a python app
|
#!/usr/bin/python
# -*- coding: iso-8859-1 -*-
import Tkinter
import twitter
class simpleapp_tk(Tkinter.Tk):
def __init__(self,parent):
Tkinter.Tk.__init__(self,parent)
self.parent = parent
self.initialize()
def initialize(self):
self.grid()
api=twitter.api()(username='-----',password='----')
self.entryVariable = Tkinter.StringVar()
self.entry = Tkinter.Entry(self,textvariable=self.entryVariable)
self.entry.grid(column=0,row=0,sticky='EW')
self.entry.bind("<Return>", self.OnPressEnter)
self.entryVariable.set(u"Enter text here.")
button = Tkinter.Button(self,text=u"POST IT !",
command=self.OnButtonClick)
button.grid(column=1,row=0)
self.labelVariable = Tkinter.StringVar()
label = Tkinter.Label(self,textvariable=self.labelVariable,
anchor="w",fg="white",bg="blue")
label.grid(column=0,row=1,columnspan=2,sticky='EW')
self.labelVariable.set(u"Hello !")
self.grid_columnconfigure(0,weight=1)
self.resizable(True,False)
self.update()
self.geometry(self.geometry())
self.entry.focus_set()
self.entry.selection_range(0, Tkinter.END)
def OnButtonClick(self):
self.labelVariable.set( self.entryVariable.get()+" (You clicked the button)" )
self.entry.focus_set()
self.entry.selection_range(0, Tkinter.END)
status=api.PostUpdate(self.entry)
def OnPressEnter(self,event):
self.labelVariable.set( self.entryVariable.get()+" (You pressed ENTER)" )
self.entry.focus_set()
self.entry.selection_range(0, Tkinter.END)
if __name__ == "__main__":
app = simpleapp_tk(None)
app.title('POSTit')
app.initialize()
app.mainloop()
the error displayed is .
AttributeError: 'module' object has no attribute 'api'
|
[
"The error message is clear, isn't it? The twitter module has no attribute named \"api\".\nA quick google showed me some examples that have a \".Api()\" method (capital A). Maybe that is your problem.\n"
] |
[
3
] |
[] |
[] |
[
"python",
"tkinter",
"twitter"
] |
stackoverflow_0002416548_python_tkinter_twitter.txt
|
Q:
How to join the same table in sqlalchemy
I'm trying to join the same table in sqlalchemy. This is a minimial version of what I tried:
#!/usr/bin/env python
import sqlalchemy as sa
from sqlalchemy import create_engine
from sqlalchemy.orm import mapper, sessionmaker, aliased
engine = create_engine('sqlite:///:memory:', echo=True)
metadata = sa.MetaData()
device_table = sa.Table("device", metadata,
sa.Column("device_id", sa.Integer, primary_key=True),
sa.Column("name", sa.String(255), nullable=False),
sa.Column("parent_device_id", sa.Integer, sa.ForeignKey('device.device_id')),
)
class Device(object):
device_id = None
def __init__(self, name, parent_device_id=None):
self.name = name
self.parent_device_id = parent_device_id
def __repr__(self):
return "<Device(%s, '%s', %s)>" % (self.device_id,
self.name,
self.parent_device_id )
mapper(Device, device_table)
metadata.create_all(engine)
db_session = sessionmaker(bind=engine)()
parent = Device('parent')
db_session.add(parent)
db_session.commit()
child = Device('child', parent.device_id)
db_session.add(child)
db_session.commit()
ParentDevice = aliased(Device, name='parent_device')
q = db_session.query(Device, ParentDevice)\
.outerjoin(ParentDevice,
Device.parent_device_id==ParentDevice.device_id)
print list(q)
This gives me this error:
ArgumentError: Can't determine join between 'device' and 'parent_device'; tables have more than one foreign key constraint relationship between them. Please specify the 'onclause' of this join explicitly.
But I am specifying a onclause for the join. How should I be doing this?
A:
For query.[outer]join, you specify as list of joins (which is different to expression.[outer]join.) So I needed to put the 2 elements of the join, the table and the onclause in a tuple, like this:
q = db_session.query(Device, ParentDevice)\
.outerjoin(
(ParentDevice, Device.parent_device_id==ParentDevice.device_id)
)
A:
Your mapper should specificy the connection between the two items, here's an example: adjacency list relationships.
|
How to join the same table in sqlalchemy
|
I'm trying to join the same table in sqlalchemy. This is a minimial version of what I tried:
#!/usr/bin/env python
import sqlalchemy as sa
from sqlalchemy import create_engine
from sqlalchemy.orm import mapper, sessionmaker, aliased
engine = create_engine('sqlite:///:memory:', echo=True)
metadata = sa.MetaData()
device_table = sa.Table("device", metadata,
sa.Column("device_id", sa.Integer, primary_key=True),
sa.Column("name", sa.String(255), nullable=False),
sa.Column("parent_device_id", sa.Integer, sa.ForeignKey('device.device_id')),
)
class Device(object):
device_id = None
def __init__(self, name, parent_device_id=None):
self.name = name
self.parent_device_id = parent_device_id
def __repr__(self):
return "<Device(%s, '%s', %s)>" % (self.device_id,
self.name,
self.parent_device_id )
mapper(Device, device_table)
metadata.create_all(engine)
db_session = sessionmaker(bind=engine)()
parent = Device('parent')
db_session.add(parent)
db_session.commit()
child = Device('child', parent.device_id)
db_session.add(child)
db_session.commit()
ParentDevice = aliased(Device, name='parent_device')
q = db_session.query(Device, ParentDevice)\
.outerjoin(ParentDevice,
Device.parent_device_id==ParentDevice.device_id)
print list(q)
This gives me this error:
ArgumentError: Can't determine join between 'device' and 'parent_device'; tables have more than one foreign key constraint relationship between them. Please specify the 'onclause' of this join explicitly.
But I am specifying a onclause for the join. How should I be doing this?
|
[
"For query.[outer]join, you specify as list of joins (which is different to expression.[outer]join.) So I needed to put the 2 elements of the join, the table and the onclause in a tuple, like this:\nq = db_session.query(Device, ParentDevice)\\\n .outerjoin(\n (ParentDevice, Device.parent_device_id==ParentDevice.device_id)\n )\n\n",
"Your mapper should specificy the connection between the two items, here's an example: adjacency list relationships.\n"
] |
[
8,
3
] |
[] |
[] |
[
"python",
"sqlalchemy"
] |
stackoverflow_0002416454_python_sqlalchemy.txt
|
Q:
Django and "get() returned more than one Model name" error in multi-threaded program
Django's get_or_create function always cause "get() returned more than one Model name" error in a multi-threaded program.
I even tried to put get_or_create statement inside a lock.acquire() and lock.release() block but still didn't work.
The program only works when I set thread_count=1
The database is on InnoDB engine. How to fix this kind of problem?
A:
This is not caused by multithreading, but because there are more than one object in database, that satisfies your query. You must select exactly one object from the database using get, otherwise it will raise an exception.
|
Django and "get() returned more than one Model name" error in multi-threaded program
|
Django's get_or_create function always cause "get() returned more than one Model name" error in a multi-threaded program.
I even tried to put get_or_create statement inside a lock.acquire() and lock.release() block but still didn't work.
The program only works when I set thread_count=1
The database is on InnoDB engine. How to fix this kind of problem?
|
[
"This is not caused by multithreading, but because there are more than one object in database, that satisfies your query. You must select exactly one object from the database using get, otherwise it will raise an exception.\n"
] |
[
2
] |
[] |
[] |
[
"database",
"insert",
"multithreading",
"mysql",
"python"
] |
stackoverflow_0002416819_database_insert_multithreading_mysql_python.txt
|
Q:
Python __init__ issue: unbound method __init__() must be called with Bank instance as first argument (got int instance instead)
class Teller(object):
def __init__(self):
self.occupied = False
self.timeLeft = 0
self.totTime
def occupy(self, timeOcc):
self.occupied = True
self.timeLeft = timeOcc
def nextMin(self):
self.timeLeft -= 1
self.totTime += 1
if self.timeLeft == 0:
self.occupied = False
class Bank(object):
def __init__(numTellers, hoursOpen):
self.tellers = []
self.timeWaited = 0
self.clientsWaiting = []
for x in xrange(numTellers):
tempTeller = Teller.__init__()
self.tellers.append(tempTeller)
self.minutesOpen = hoursOpen * 60
def tellerOpen(self):
for x in xrange(len(self.tellers)):
if not self.tellers[x].occupied:
return x+1
return 0
def runSim(self, queueInput): #queueInput is a list of tuples (time, timeAtTeller)
simTime = self.minutesOpen
totCli = 0
timeToNext = queueInput[0][0]
timeAtNext = queueInput[0][1]
queueInput.pop(0)
self.clientsWaiting.append([timeToNext, timeAtNext])
while simTime > 0:
for person in self.clientsWaiting:
if person[0]:
person -= 1
if not self.clientsWaiting[len(self.clientsWaiting)-1][0]:
timeToNext = queueInput[0][0]
timeAtNext = queueInput[0][1]
queueInput.pop(0)
self.clientsWaiting.append([timeToNext, timeAtNext])
remove = 0
for x in xrange (len(self.clientsWaiting)-1):
if tellerOpen() and not self.clientsWaiting[x][0]:
self.tellers[tellerOpen()].occupy(self.clientsWaiting[x][0])
totCli += 1
remove += 1
elif not tellerOpen() and not self.clientsWaiting[x][0]:
self.timeWaited += 1
for x in xrange(remove):
self.clientsWaiting.pop(x)
print """The total time spent in the queue by all clients was %d minutes. The total number of clients today was %d. The average waiting time was %d mins""" % (self.timeWaited, totCli, self.timeWaited / totCli)\
if __name__ == '__main__':
inp = raw_input()
tList = inp.split('\n')
qList = []
for item in tList:
tList = item.split(' ')
qList.append((tList[0], tList[1]))
virtBank = Bank.__init__(3, 7)
bank.runSim(qList)
This results in this error:
> TypeError: unbound method __init__() must be called with Bank instance as first argument (got int instance instead)
I don't see what I've dont wrong. Any advice would be appreciated.
The only important parts, I think, are the Bank class __init__ and the call virtBank = Bank.__init__(3, 7)
A:
2 points to make here:
You shouldn't be calling __init__ directly, it's a magic method which is invoked when you construct an object like this:
virtBank = Bank(3, 7)
The instance is implicitly passed to the constructor, but it must be explicitly received, like this:
def __init__(self, numTellers, hoursOpen):
# ...
|
Python __init__ issue: unbound method __init__() must be called with Bank instance as first argument (got int instance instead)
|
class Teller(object):
def __init__(self):
self.occupied = False
self.timeLeft = 0
self.totTime
def occupy(self, timeOcc):
self.occupied = True
self.timeLeft = timeOcc
def nextMin(self):
self.timeLeft -= 1
self.totTime += 1
if self.timeLeft == 0:
self.occupied = False
class Bank(object):
def __init__(numTellers, hoursOpen):
self.tellers = []
self.timeWaited = 0
self.clientsWaiting = []
for x in xrange(numTellers):
tempTeller = Teller.__init__()
self.tellers.append(tempTeller)
self.minutesOpen = hoursOpen * 60
def tellerOpen(self):
for x in xrange(len(self.tellers)):
if not self.tellers[x].occupied:
return x+1
return 0
def runSim(self, queueInput): #queueInput is a list of tuples (time, timeAtTeller)
simTime = self.minutesOpen
totCli = 0
timeToNext = queueInput[0][0]
timeAtNext = queueInput[0][1]
queueInput.pop(0)
self.clientsWaiting.append([timeToNext, timeAtNext])
while simTime > 0:
for person in self.clientsWaiting:
if person[0]:
person -= 1
if not self.clientsWaiting[len(self.clientsWaiting)-1][0]:
timeToNext = queueInput[0][0]
timeAtNext = queueInput[0][1]
queueInput.pop(0)
self.clientsWaiting.append([timeToNext, timeAtNext])
remove = 0
for x in xrange (len(self.clientsWaiting)-1):
if tellerOpen() and not self.clientsWaiting[x][0]:
self.tellers[tellerOpen()].occupy(self.clientsWaiting[x][0])
totCli += 1
remove += 1
elif not tellerOpen() and not self.clientsWaiting[x][0]:
self.timeWaited += 1
for x in xrange(remove):
self.clientsWaiting.pop(x)
print """The total time spent in the queue by all clients was %d minutes. The total number of clients today was %d. The average waiting time was %d mins""" % (self.timeWaited, totCli, self.timeWaited / totCli)\
if __name__ == '__main__':
inp = raw_input()
tList = inp.split('\n')
qList = []
for item in tList:
tList = item.split(' ')
qList.append((tList[0], tList[1]))
virtBank = Bank.__init__(3, 7)
bank.runSim(qList)
This results in this error:
> TypeError: unbound method __init__() must be called with Bank instance as first argument (got int instance instead)
I don't see what I've dont wrong. Any advice would be appreciated.
The only important parts, I think, are the Bank class __init__ and the call virtBank = Bank.__init__(3, 7)
|
[
"2 points to make here:\n\nYou shouldn't be calling __init__ directly, it's a magic method which is invoked when you construct an object like this:\nvirtBank = Bank(3, 7)\n\nThe instance is implicitly passed to the constructor, but it must be explicitly received, like this:\ndef __init__(self, numTellers, hoursOpen):\n # ...\n\n\n"
] |
[
8
] |
[] |
[] |
[
"init",
"methods",
"python"
] |
stackoverflow_0002417192_init_methods_python.txt
|
Q:
Finding a module's directory
How can I find what directory a module has been imported from, as it needs to load a data file which is in the same directory.
edit:
combining several answers:
module_path = os.path.dirname(imp.find_module(self.__module__)[1])
got me what i wanted
A:
This would work:
yourmodule.__file__
and if you want to find the module an object was imported from:
myobject.__module__
A:
The path to the module's file is in module.__file__. You can use that with os.path.dirname to get the directory.
A:
Using the re module as an example:
>>> import re
>>> path = re.__file__
>>> print path
C:\python26\lib\re.pyc
>>> import os.path
>>> print os.path.dirname(os.path.abspath(path))
C:\python26\lib
Note that if the module is in your current working directory ("CWD"), you will get just a relative path e.g. foo.py. I make it a habit of getting the absolute path immediately just in case the CWD gets changed before the module path gets used.
A:
If you want to modules directory by specifying module_name as string i.e. without actually importing the module then use
def get_dir(module_name):
import os,imp
(file, pathname, description) = imp.find_module(module_name)
return os.path.dirname(pathname)
print get_dir('os')
output:
C:\Python26\lib
foo.py
def foo():
print 'foo'
bar.py
import foo
import os
print os.path.dirname(foo.__file__)
foo.foo()
output:
C:\Documents and Settings\xxx\My Documents
foo
|
Finding a module's directory
|
How can I find what directory a module has been imported from, as it needs to load a data file which is in the same directory.
edit:
combining several answers:
module_path = os.path.dirname(imp.find_module(self.__module__)[1])
got me what i wanted
|
[
"This would work:\nyourmodule.__file__\n\nand if you want to find the module an object was imported from:\nmyobject.__module__\n\n",
"The path to the module's file is in module.__file__. You can use that with os.path.dirname to get the directory.\n",
"Using the re module as an example:\n>>> import re\n>>> path = re.__file__\n>>> print path\nC:\\python26\\lib\\re.pyc\n>>> import os.path\n>>> print os.path.dirname(os.path.abspath(path))\nC:\\python26\\lib\n\nNote that if the module is in your current working directory (\"CWD\"), you will get just a relative path e.g. foo.py. I make it a habit of getting the absolute path immediately just in case the CWD gets changed before the module path gets used.\n",
"If you want to modules directory by specifying module_name as string i.e. without actually importing the module then use\ndef get_dir(module_name):\n import os,imp\n (file, pathname, description) = imp.find_module(module_name)\n return os.path.dirname(pathname)\n\nprint get_dir('os')\n\noutput:\nC:\\Python26\\lib\n\n\nfoo.py\ndef foo():\n print 'foo'\n\nbar.py\nimport foo\nimport os\nprint os.path.dirname(foo.__file__)\nfoo.foo()\n\noutput:\nC:\\Documents and Settings\\xxx\\My Documents\nfoo\n\n"
] |
[
1,
1,
1,
1
] |
[] |
[] |
[
"dirname",
"module",
"python"
] |
stackoverflow_0002417215_dirname_module_python.txt
|
Q:
How to convert this regular expression into Python
I want to use this regular expression in Python:
<(?:"[^"]*"['"]*|'[^']*'['"]*|[^'">])+>
(from RegEx match open tags except XHTML self-contained tags)
def removeHtmlTags(page):
p = re.compile(r'XXXX')
return p.sub('', page)
It seems that I cannot directly substitute the complex regular expression into the above function.
A:
Works fine here. You're probably having trouble because of the quotes. Just triple-quote it:
def removeHtmlTags(page):
p = re.compile(r'''<(?:"[^"]*"['"]*|'[^']*'['"]*|[^'">])+>''')
return p.sub('', page)
A:
If you need to remove HTML tags, this should do it:
import re
def removeHtmlTags(page):
pattern = re.compile(r'\<[^>]+\>', re.I)
return pattern.sub('', page)
|
How to convert this regular expression into Python
|
I want to use this regular expression in Python:
<(?:"[^"]*"['"]*|'[^']*'['"]*|[^'">])+>
(from RegEx match open tags except XHTML self-contained tags)
def removeHtmlTags(page):
p = re.compile(r'XXXX')
return p.sub('', page)
It seems that I cannot directly substitute the complex regular expression into the above function.
|
[
"Works fine here. You're probably having trouble because of the quotes. Just triple-quote it:\ndef removeHtmlTags(page):\n p = re.compile(r'''<(?:\"[^\"]*\"['\"]*|'[^']*'['\"]*|[^'\">])+>''')\n return p.sub('', page)\n\n",
"If you need to remove HTML tags, this should do it:\nimport re\n\ndef removeHtmlTags(page):\n pattern = re.compile(r'\\<[^>]+\\>', re.I)\n return pattern.sub('', page)\n\n"
] |
[
3,
0
] |
[] |
[] |
[
"python",
"regex"
] |
stackoverflow_0002417330_python_regex.txt
|
Q:
How to use lazy_gettext with Pylons and setup.py
Just a quick question. When I use the _() function provided by the Pylons i18n module, everything works just as expected.
My problem is with the lazy version of this function, lazy_gettext. When I run :
python setup.py extract_messages
I get in the POT file the strings to be translated with the _() function, but not those wuth lazy_gettext().
How may I get it to work ?
Thanks.
A:
In the modules where you use lazy_gettext(), just assign _ = lazy_gettext and use _() instead.
|
How to use lazy_gettext with Pylons and setup.py
|
Just a quick question. When I use the _() function provided by the Pylons i18n module, everything works just as expected.
My problem is with the lazy version of this function, lazy_gettext. When I run :
python setup.py extract_messages
I get in the POT file the strings to be translated with the _() function, but not those wuth lazy_gettext().
How may I get it to work ?
Thanks.
|
[
"In the modules where you use lazy_gettext(), just assign _ = lazy_gettext and use _() instead.\n"
] |
[
2
] |
[] |
[] |
[
"internationalization",
"pylons",
"python"
] |
stackoverflow_0002417479_internationalization_pylons_python.txt
|
Q:
How to check with python if a table is empty?
Using python and MySQLdb, how can I check if there are any records in a mysql table (innodb)?
A:
Just select a single row. If you get nothing back, it's empty! (Example from the MySQLdb site)
import MySQLdb
db = MySQLdb.connect(passwd="moonpie", db="thangs")
results = db.query("""SELECT * from mytable limit 1""")
if not results:
print "This table is empty!"
A:
Something like
import MySQLdb
db = MySQLdb.connect("host", "user", "password", "dbname")
cursor = db.cursor()
sql = """SELECT count(*) as tot FROM simpletable"""
cursor.execute(sql)
data = cursor.fetchone()
db.close()
print data
will print the number or records in the simpletable table.
You can then test if to see if it is bigger than zero.
|
How to check with python if a table is empty?
|
Using python and MySQLdb, how can I check if there are any records in a mysql table (innodb)?
|
[
"Just select a single row. If you get nothing back, it's empty! (Example from the MySQLdb site)\nimport MySQLdb\ndb = MySQLdb.connect(passwd=\"moonpie\", db=\"thangs\")\nresults = db.query(\"\"\"SELECT * from mytable limit 1\"\"\")\nif not results:\n print \"This table is empty!\"\n\n",
"Something like\nimport MySQLdb\ndb = MySQLdb.connect(\"host\", \"user\", \"password\", \"dbname\")\ncursor = db.cursor()\nsql = \"\"\"SELECT count(*) as tot FROM simpletable\"\"\"\ncursor.execute(sql)\ndata = cursor.fetchone()\ndb.close()\nprint data\n\nwill print the number or records in the simpletable table.\nYou can then test if to see if it is bigger than zero.\n"
] |
[
6,
2
] |
[] |
[] |
[
"mysql",
"python"
] |
stackoverflow_0002417545_mysql_python.txt
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.