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:
File Manipulation: Scripting Question
I have a script which connects to database and gets all records which statisfy the query. These record results are files present on a server, so now I have a text file which has all file names in it.
I want a script which would know:
What is the size of each file in the output.txt file?
What is the total size of all the files present in that text file?
Update:
I would like to know how can I achieve my task using Perl programming language, any inputs would be highly appreciated.
Note: I do not have any specific language constraint, it could be either Perl or Python scripting language which I can run from the Unix prompt. Currently I am using the bash shell and have sh and py script. How can this be done?
My scripts:
#!/usr/bin/ksh
export ORACLE_HOME=database specific details
export PATH=$ORACLE_HOME/bin:path information
sqlplus database server information<<EOF
SET HEADING OFF
SET ECHO OFF
SET PAGESIZE 0
SET LINESIZE 1000
SPOOL output.txt
select * from my table_name;
SPOOL OFF
EOF
I know du -h would be the command which I should be using but I am not sure how should my script be, I have tried something in python. I am totally new to Python and it's my first time effort.
Here it is:
import os
folderpath='folder_path'
file=open('output file which has all listing of query result','r')
for line in file:
filename=line.strip()
filename=filename.replace(' ', '\ ')
fullpath=folderpath+filename
# print (fullpath)
os.system('du -h '+fullpath)
File names in the output text file for example are like: 007_009_Bond Is Here_009_Yippie.doc
Any guidance would be highly appreciated.
Update:
How can I move all the files which are present in output.txt file to some other folder location using Perl ?
After doing step1, how can I delete all the files which are present in output.txt file ?
Any suggestions would be highly appreciated.
A:
Eyeballing, you can make YOUR script work this way:
1) Delete the line filename=filename.replace(' ', '\ ') Escaping is more complicated than that, and you should just quote the full path or use a Python library to escape it based on the specific OS;
2) You are probably missing a delimiter between the path and the file name;
3) You need single quotes around the full path in the call to os.system.
This works for me:
#!/usr/bin/python
import os
folderpath='/Users/andrew/bin'
file=open('ft.txt','r')
for line in file:
filename=line.strip()
fullpath=folderpath+"/"+filename
os.system('du -h '+"'"+fullpath+"'")
The file "ft.txt" has file names with no path and the path part is '/Users/andrew/bin'. Some of the files have names that would need to be escaped, but that is taken care of with the single quotes around the file name.
That will run du -h on each file in the .txt file, but does not give you the total. This is fairly easy in Perl or Python.
Here is a Python script (based on yours) to do that:
#!/usr/bin/python
import os
folderpath='/Users/andrew/bin/testdir'
file=open('/Users/andrew/bin/testdir/ft.txt','r')
blocks=0
i=0
template='%d total files in %d blocks using %d KB\n'
for line in file:
i+=1
filename=line.strip()
fullpath=folderpath+"/"+filename
if(os.path.exists(fullpath)):
info=os.stat(fullpath)
blocks+=info.st_blocks
print `info.st_blocks`+"\t"+fullpath
else:
print '"'+fullpath+"'"+" not found"
print `blocks`+"\tTotal"
print " "+template % (i,blocks,blocks*512/1024)
Notice that you do not have to quote or escape the file name this time; Python does it for you. This calculates file sizes using allocation blocks; the same way that du does it. If I run du -ahc against the same files that I have listed in ft.txt I get the same number (well kinda; du reports it as 25M and I get the report as 24324 KB) but it reports the same number of blocks. (Side note: "blocks" are always assumed to be 512 bytes under Unix even though the actual block size on larger disc is always larger.)
Finally, you may want to consider making your script so that it can read a command line group of files rather than hard coding the file and the path in the script. Consider:
#!/usr/bin/python
import os, sys
total_blocks=0
total_files=0
template='%d total files in %d blocks using %d KB\n'
print
for arg in sys.argv[1:]:
print "processing: "+arg
blocks=0
i=0
file=open(arg,'r')
for line in file:
abspath=os.path.abspath(arg)
folderpath=os.path.dirname(abspath)
i+=1
filename=line.strip()
fullpath=folderpath+"/"+filename
if(os.path.exists(fullpath)):
info=os.stat(fullpath)
blocks+=info.st_blocks
print `info.st_blocks`+"\t"+fullpath
else:
print '"'+fullpath+"'"+" not found"
print "\t"+template % (i,blocks,blocks*512/1024)
total_blocks+=blocks
total_files+=i
print template % (total_files,total_blocks,total_blocks*512/1024)
You can then execute the script (after chmod +x [script_name].py) by ./script.py ft.txt and it will then use the path to the command line file as the assumed path to the files "ft.txt". You can process multiple files as well.
A:
In perl, the -s filetest operator is probaby what you want.
use strict;
use warnings;
use File::Copy;
my $folderpath = 'the_path';
my $destination = 'path/to/destination/directory';
open my $IN, '<', 'path/to/infile';
my $total;
while (<$IN>) {
chomp;
my $size = -s "$folderpath/$_";
print "$_ => $size\n";
$total += $size;
move("$folderpath/$_", "$destination/$_") or die "Error when moving: $!";
}
print "Total => $total\n";
Note that -s gives size in bytes not blocks like du.
On further investigation, perl's -s is equivalent to du -b. You should probably read the man pages on your specific du to make sure that you are actually measuring what you intend to measure.
If you really want the du values, change the assignment to $size above to:
my ($size) = split(' ', `du "$folderpath/$_"`);
A:
You can do it in your shell script itself.
You have all the files names in your spooled file output.txt, all you have to add at the end of existing script is:
< output.txt du -h
It will give size of each file and also a total at the end.
A:
You can use the Python skeleton that you've sketched out and add os.path.getsize(fullpath) to get the size of individual file.
For example, if you wanted a dictionary with the file name and size you could:
dict((f, os.path.getsize(f)) for f in file)
Keep in mind that the result from os.path.getsize(...) is in bytes so you'll have to convert it to get other units if you want.
In general os.path is a key module for manipulating files and paths.
| File Manipulation: Scripting Question | I have a script which connects to database and gets all records which statisfy the query. These record results are files present on a server, so now I have a text file which has all file names in it.
I want a script which would know:
What is the size of each file in the output.txt file?
What is the total size of all the files present in that text file?
Update:
I would like to know how can I achieve my task using Perl programming language, any inputs would be highly appreciated.
Note: I do not have any specific language constraint, it could be either Perl or Python scripting language which I can run from the Unix prompt. Currently I am using the bash shell and have sh and py script. How can this be done?
My scripts:
#!/usr/bin/ksh
export ORACLE_HOME=database specific details
export PATH=$ORACLE_HOME/bin:path information
sqlplus database server information<<EOF
SET HEADING OFF
SET ECHO OFF
SET PAGESIZE 0
SET LINESIZE 1000
SPOOL output.txt
select * from my table_name;
SPOOL OFF
EOF
I know du -h would be the command which I should be using but I am not sure how should my script be, I have tried something in python. I am totally new to Python and it's my first time effort.
Here it is:
import os
folderpath='folder_path'
file=open('output file which has all listing of query result','r')
for line in file:
filename=line.strip()
filename=filename.replace(' ', '\ ')
fullpath=folderpath+filename
# print (fullpath)
os.system('du -h '+fullpath)
File names in the output text file for example are like: 007_009_Bond Is Here_009_Yippie.doc
Any guidance would be highly appreciated.
Update:
How can I move all the files which are present in output.txt file to some other folder location using Perl ?
After doing step1, how can I delete all the files which are present in output.txt file ?
Any suggestions would be highly appreciated.
| [
"Eyeballing, you can make YOUR script work this way:\n1) Delete the line filename=filename.replace(' ', '\\ ') Escaping is more complicated than that, and you should just quote the full path or use a Python library to escape it based on the specific OS;\n2) You are probably missing a delimiter between the path and ... | [
1,
1,
0,
0
] | [] | [] | [
"file",
"perl",
"python",
"scripting",
"unix"
] | stackoverflow_0003746552_file_perl_python_scripting_unix.txt |
Q:
'from sqlite3 import dbapi2 as sqlite3' vs 'import sqlite3'?
When I see the examples for pysqlite, there are two use cases for the SQLite library.
from sqlite3 import dbapi2 as sqlite3
and
import sqlite3
Why there are two ways to support the sqlite3 api? What's the difference between the two? Are they the same? In normal use, which would be preferred.
ADDED
I knew that they are different in terms of namespace, and I wanted ask if they are the same in terms of usage, I mean, do they have the same API set?
A:
They are the same. In the Lib/ directory of my Python installation (v2.6), the sqlite3 package contains a __init__.py file with this:
from dbapi2 import *
Which means that the two ways of importing are absolutely identical.
That said, I definitely recommend just using import sqlite3 - as this is the documented approach.
A:
They are not the same.
In the first case, you are importing the dbapi2 symbol from the sqlite3 module into the current namespace.
In the last case, you just import the sqlite3 module in the namespace.
The difference is that in the first case you can directly use dbapi2 (aliased as sqlite3) class, which in the latter case, you would have to reference to sqlite3.dbapi2 all the time you want to reference it.
See for more information the python documentation
| 'from sqlite3 import dbapi2 as sqlite3' vs 'import sqlite3'? | When I see the examples for pysqlite, there are two use cases for the SQLite library.
from sqlite3 import dbapi2 as sqlite3
and
import sqlite3
Why there are two ways to support the sqlite3 api? What's the difference between the two? Are they the same? In normal use, which would be preferred.
ADDED
I knew that they are different in terms of namespace, and I wanted ask if they are the same in terms of usage, I mean, do they have the same API set?
| [
"They are the same. In the Lib/ directory of my Python installation (v2.6), the sqlite3 package contains a __init__.py file with this:\nfrom dbapi2 import *\n\nWhich means that the two ways of importing are absolutely identical.\nThat said, I definitely recommend just using import sqlite3 - as this is the documente... | [
8,
2
] | [] | [] | [
"pysqlite",
"python"
] | stackoverflow_0003754080_pysqlite_python.txt |
Q:
Help converting Python app to C#
Everyone,
here is a link to a small python app:
http://en.wikipedia.org/wiki/File:Beta-skeleton.svg
I think I've correctly converted it. (Source at bottom of post)
But, the Math.Acos always returns NaN. Is there a difference between the python version of acos and Math.Acos?
private Random rnd = new Random();
private double scale = 5;
private double radius = 10;
private double beta1 = 1.1;
private double beta2 = 0.9;
private double theta1;
private double theta2;
private Point[] points = new Point[10];
public MainWindow()
{
InitializeComponent();
for (int i = 0; i < 100; i++ )
{
points[i] = new Point((rnd.NextDouble() * scale),
(rnd.NextDouble() * scale));
}
theta1 = Math.Asin(1/beta1);
theta2 = Math.PI - Math.Asin(beta2);
}
private double Dot(Point p, Point q, Point r)
{
var pr = new Point();
var qr = new Point();
//(p[0]-r[0])
pr.X = p.X-r.X;
//(p[1]-r[1])
pr.Y = p.Y-r.Y;
//(q[0]-r[0])
qr.X = q.X-r.X;
//(q[1]-r[1])
qr.Y = q.Y-r.Y;
return (pr.X*qr.X) + (pr.Y*qr.Y);
}
private double Sharp(Point p,Point q)
{
double theta = 0;
foreach(var pnt in points)
{
if(pnt!=p && pnt!=q)
{
var dotpq = Dot(p, q, pnt);
double t = Math.Acos(dotpq);
double u = Math.Pow((dotpq * dotpq), 0.5);
var tempVal = t/u;
theta = Math.Max(theta, tempVal);
}
}
return theta;
}
private void DrawPoint(Point p)
{
var e = new Ellipse
{
Width = radius/2,
Height = radius/2,
Stroke = Brushes.Red,
Visibility = Visibility.Visible
};
Canvas.SetTop(e, p.Y + radius);
Canvas.SetLeft(e, p.X + radius);
MyCanvas.Children.Add(e);
}
private void DrawEdge1(Point p,Point q)
{
var l = new Line
{
X1 = p.X,
Y1 = p.Y,
X2 = q.X,
Y2 = q.Y,
Stroke = Brushes.Black,
Width = 1,
Visibility = Visibility.Visible
};
MyCanvas.Children.Add(l);
}
private void DrawEdge2(Point p,Point q)
{
var l = new Line
{
X1 = p.X,
Y1 = p.Y,
X2 = q.X,
Y2 = q.Y,
Stroke = Brushes.Blue,
Width = 1,
Visibility = Visibility.Visible
};
MyCanvas.Children.Add(l);
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
foreach (var p in points)
{
foreach (var q in points)
{
var theta = Sharp(p, q);
if(theta < theta1) DrawEdge1(p, q);
else if(theta < theta2) DrawEdge2(p, q);
}
}
}
A:
What you need to do to get the angle from the dot product is to take away the lengths before you acos.
What python has:
prq = acos(dot(p,q,r) / (dot(p,p,r)*dot(q,q,r))**0.5)
What you're doing is not dividing in the Acos, but dividing after.
so:
int r = pnt;
int ppr = Dot(p,p,r);
int qqr = Dot(q,q,r);
int pqr = Dot(p,q,r);
double u = Math.Acos(pqr / Math.Sqrt(ppr * qqr));
Of course change the variables, I was just trying to keep it similar to the python to help you understand :)
A:
I think it's due to your translation of the Python expression (dot(p,q,r) / (dot(p,p,r) * dot(q,q,r)) **0.5). Exponentiation in Python has one of the lowest operators precedency-wise, so the square-root is being taken of the subterm dot(p,q,r) / (dot(p,p,r) * dot(q,q,r)). In your C# version, when calculating the value of the double 'u', you're only taking the square-root of the product of the last two terms, i.e. the (dotpq * dotpq).
A:
The question really is what is the value of dotpq when the function gets called. It has to be a double value between -1 and 1 as stated in the docs.
| Help converting Python app to C# | Everyone,
here is a link to a small python app:
http://en.wikipedia.org/wiki/File:Beta-skeleton.svg
I think I've correctly converted it. (Source at bottom of post)
But, the Math.Acos always returns NaN. Is there a difference between the python version of acos and Math.Acos?
private Random rnd = new Random();
private double scale = 5;
private double radius = 10;
private double beta1 = 1.1;
private double beta2 = 0.9;
private double theta1;
private double theta2;
private Point[] points = new Point[10];
public MainWindow()
{
InitializeComponent();
for (int i = 0; i < 100; i++ )
{
points[i] = new Point((rnd.NextDouble() * scale),
(rnd.NextDouble() * scale));
}
theta1 = Math.Asin(1/beta1);
theta2 = Math.PI - Math.Asin(beta2);
}
private double Dot(Point p, Point q, Point r)
{
var pr = new Point();
var qr = new Point();
//(p[0]-r[0])
pr.X = p.X-r.X;
//(p[1]-r[1])
pr.Y = p.Y-r.Y;
//(q[0]-r[0])
qr.X = q.X-r.X;
//(q[1]-r[1])
qr.Y = q.Y-r.Y;
return (pr.X*qr.X) + (pr.Y*qr.Y);
}
private double Sharp(Point p,Point q)
{
double theta = 0;
foreach(var pnt in points)
{
if(pnt!=p && pnt!=q)
{
var dotpq = Dot(p, q, pnt);
double t = Math.Acos(dotpq);
double u = Math.Pow((dotpq * dotpq), 0.5);
var tempVal = t/u;
theta = Math.Max(theta, tempVal);
}
}
return theta;
}
private void DrawPoint(Point p)
{
var e = new Ellipse
{
Width = radius/2,
Height = radius/2,
Stroke = Brushes.Red,
Visibility = Visibility.Visible
};
Canvas.SetTop(e, p.Y + radius);
Canvas.SetLeft(e, p.X + radius);
MyCanvas.Children.Add(e);
}
private void DrawEdge1(Point p,Point q)
{
var l = new Line
{
X1 = p.X,
Y1 = p.Y,
X2 = q.X,
Y2 = q.Y,
Stroke = Brushes.Black,
Width = 1,
Visibility = Visibility.Visible
};
MyCanvas.Children.Add(l);
}
private void DrawEdge2(Point p,Point q)
{
var l = new Line
{
X1 = p.X,
Y1 = p.Y,
X2 = q.X,
Y2 = q.Y,
Stroke = Brushes.Blue,
Width = 1,
Visibility = Visibility.Visible
};
MyCanvas.Children.Add(l);
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
foreach (var p in points)
{
foreach (var q in points)
{
var theta = Sharp(p, q);
if(theta < theta1) DrawEdge1(p, q);
else if(theta < theta2) DrawEdge2(p, q);
}
}
}
| [
"What you need to do to get the angle from the dot product is to take away the lengths before you acos.\nWhat python has:\nprq = acos(dot(p,q,r) / (dot(p,p,r)*dot(q,q,r))**0.5)\n\nWhat you're doing is not dividing in the Acos, but dividing after.\nso:\nint r = pnt;\nint ppr = Dot(p,p,r);\nint qqr = Dot(q,q,r);\nint... | [
3,
2,
0
] | [] | [] | [
"c#",
"math",
"python"
] | stackoverflow_0003753925_c#_math_python.txt |
Q:
Ruby To Python Syntax Confusion
I'm trying to convert someone's Ruby code into my Python code. The originally developer is no longer with us and I don't know Ruby. Most of his code is easy enough to follow, but some of the following syntax is tripping me up.
Example:
myTable = ''
myTable << [ 0, 1, 0, 0, 0, 300].pack('vvvvvv')
myTable [40, 4] = [41310005 - 5].pack('V')
1) Am I correct to assume that after the 2nd line, myTable is going to hold an array of 6 values specified in the []'s? And is that .pack() similar to Python's struct.pack ?
2) After the third line, is the value on the right going to be stored at position 40 in the array and be 4 bytes long? Is the -5 in the []'s just him being fun or does that hold some special significance?
A:
You're wrong about the second line, though strangely you're right that it's similar to struct.pack. myTable is a string. Array#pack() returns a string of the packed data (much like struct.pack), and String#<< appends a string to the receiving string. The third line sets 4 bytes at index 40 to be the result of [41310000].pack('V').
A:
Take a look at the documentation for Array#pack. It converts an array into the string representation of a binary sequence. v is the directive for "Short, little-endian byte order", and V is "Long, little-endian byte order".
The << acts as concatenation when sent to a String object. Since the string is empty before that point, though, myTable could have been immediately initialized to [0, 1, 0, 0, 0, 300].pack('vvvvvv') instead.
String#[m,n]= replaces the substring from index m to m+n.
A:
No, myTable is a string (it was assigned a string literal). The << operator on strings (and arrays) is the append operator, so you're appending a string to a string. The pack method returns a string, in this case a string of "Short, little-endian byte order." It'll be a string of 6 short integers, not converted to ASCII in any way, just dumped into the string.
Then, part of this string of integers in their native format is being replaced by another value from pack, this turn returning a "Long, little-endian byte order." It's being replaced into the location in the string 40 bytes in, and 4 bytes long.
This is some pretty funky code. Just know that myTable is a string, and that pack is returning numbers in native format.
| Ruby To Python Syntax Confusion | I'm trying to convert someone's Ruby code into my Python code. The originally developer is no longer with us and I don't know Ruby. Most of his code is easy enough to follow, but some of the following syntax is tripping me up.
Example:
myTable = ''
myTable << [ 0, 1, 0, 0, 0, 300].pack('vvvvvv')
myTable [40, 4] = [41310005 - 5].pack('V')
1) Am I correct to assume that after the 2nd line, myTable is going to hold an array of 6 values specified in the []'s? And is that .pack() similar to Python's struct.pack ?
2) After the third line, is the value on the right going to be stored at position 40 in the array and be 4 bytes long? Is the -5 in the []'s just him being fun or does that hold some special significance?
| [
"You're wrong about the second line, though strangely you're right that it's similar to struct.pack. myTable is a string. Array#pack() returns a string of the packed data (much like struct.pack), and String#<< appends a string to the receiving string. The third line sets 4 bytes at index 40 to be the result of [413... | [
3,
2,
1
] | [] | [] | [
"python",
"ruby",
"syntax"
] | stackoverflow_0003754450_python_ruby_syntax.txt |
Q:
Execute external application and send some key events to it
I wasn't able to find a solution for Python.
I am abelt o launch the application (using subprocess.Popen or subprocess.call), but I can't find a way to do the other part:
I want to send a serie of keys (kind of macro) to the application I just opened. Like:
Tab
Tab
Enter
Tab
Tab
Delete
...
Is there a way to do this that is Mac and PC compatible ? Or, in case not, only PC ?
Thanks for your help,
Basil
PS. I know there are some application to automate some keys event, but I want to make my own.
A:
Under windows you could use the venerable SendKeys to do this. There's a few implementations floating around. One, using the win32 extentions or two, there's even a couple ready-to-use modules available
A:
Run the subprocess.Popen() command with the argument stdin=subprocess.PIPE then use the Popen object's stdin file to write data to the process's standard input stream. For some of the commands you mentioned, standard string escapes are available (like '\t' for TAB). However, if you need a more comprehensive keyset, you'll need to break out an old ASCII table and piece together the strings via the chr() function.
p = subprocess.Popen(['bash',], stdin=subprocess.PIPE)
p.stdin.write('echo "Hello\t\t\tWorld"\n')
A:
Thanks for answering. I tried using the subprocess.Popen(), but it seems that it doesn't work. Sending the '\t' string does not work... It simply does nothing... Notice that the application is not python based (it's an installation application - basically, they are auto-extracting zip files (.exe) and I have hundreds of them...)
I'll try the other idea with some windows modules... but I really would prefer using something Mac and PC compatible...
| Execute external application and send some key events to it | I wasn't able to find a solution for Python.
I am abelt o launch the application (using subprocess.Popen or subprocess.call), but I can't find a way to do the other part:
I want to send a serie of keys (kind of macro) to the application I just opened. Like:
Tab
Tab
Enter
Tab
Tab
Delete
...
Is there a way to do this that is Mac and PC compatible ? Or, in case not, only PC ?
Thanks for your help,
Basil
PS. I know there are some application to automate some keys event, but I want to make my own.
| [
"Under windows you could use the venerable SendKeys to do this. There's a few implementations floating around. One, using the win32 extentions or two, there's even a couple ready-to-use modules available\n",
"Run the subprocess.Popen() command with the argument stdin=subprocess.PIPE then use the Popen object's ... | [
2,
1,
0
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0003684594_python_wxpython.txt |
Q:
The open/close function of SQLite implementation
I'm trying to come up with SQLiteDB object, and following is the open/close code for it.
Does this work without problem? Am I missing something important?
For close(), I use con.close() and cursor.close(), but I'm wondering if cursor.close() is necessary.
class SQLiteDB(object):
def __init__(self, dbFile, connect = True):
self.dbFile = dbFile
self.con = None
self.cursor = None
if connect:
self.open()
def __del__(self):
if self.con:
self.close()
def open(self):
self.con = sqlite3.connect(self.dbFile)
self.cursor = self.connector.cursor()
return self.con, self.cursor
def close(self):
self.con.close()
self.cursor.close()
self.cursor = None
self.con = None
A:
What happens on Cursor.close() depends on the underlying database implementation. For SQLite it might currently work without closing, but for other implementations or a future SQLite version it might not, so I would recommend to close the Cursor object. You can find further information on Cursor.close() in PEP 249.
Also, there seems to be a typo in your code:
self.connector = sqlite3.connect(self.dbFile)
should probably be
self.con = sqlite3.connect(self.dbFile)
Otherwise your code looks fine to me. Happy coding :) .
| The open/close function of SQLite implementation | I'm trying to come up with SQLiteDB object, and following is the open/close code for it.
Does this work without problem? Am I missing something important?
For close(), I use con.close() and cursor.close(), but I'm wondering if cursor.close() is necessary.
class SQLiteDB(object):
def __init__(self, dbFile, connect = True):
self.dbFile = dbFile
self.con = None
self.cursor = None
if connect:
self.open()
def __del__(self):
if self.con:
self.close()
def open(self):
self.con = sqlite3.connect(self.dbFile)
self.cursor = self.connector.cursor()
return self.con, self.cursor
def close(self):
self.con.close()
self.cursor.close()
self.cursor = None
self.con = None
| [
"What happens on Cursor.close() depends on the underlying database implementation. For SQLite it might currently work without closing, but for other implementations or a future SQLite version it might not, so I would recommend to close the Cursor object. You can find further information on Cursor.close() in PEP 249... | [
1
] | [] | [] | [
"pysqlite",
"python"
] | stackoverflow_0003754151_pysqlite_python.txt |
Q:
How can we use ms office communicator client exposed APIs in python, is that possible?
I want to use ms office communicator client apis, and i wan to use those in python is it possible to do ?
A:
>>> import win32com.client
>>> msg = win32com.client.Dispatch('Communicator.UIAutomation')
>>> msg.InstantMessage('user@domain.com')
A:
There is an JSON API to access all office communicator functions via "office communicator web access". You can download a description for that API. But nobody has implemented a module yet. The API is quiet complex.
A:
I don't know very well Ms Office communicator but if it exposes a COM interface, you shoudl be able to access it through the Mark Hammond python bindings for COM http://starship.python.net/crew/skippy/
Otherwise, if it exposes a .NET API you should be able to access it with IronPython
I hope it helps
| How can we use ms office communicator client exposed APIs in python, is that possible? | I want to use ms office communicator client apis, and i wan to use those in python is it possible to do ?
| [
"\n>>> import win32com.client\n>>> msg = win32com.client.Dispatch('Communicator.UIAutomation')\n>>> msg.InstantMessage('user@domain.com')\n\n\n",
"There is an JSON API to access all office communicator functions via \"office communicator web access\". You can download a description for that API. But nobody has im... | [
2,
1,
0
] | [] | [] | [
"api",
"office_communicator",
"python"
] | stackoverflow_0002286790_api_office_communicator_python.txt |
Q:
shopify xml request from GAE python
I'm trying to make requests to the shopify.com API over GAE python
the url i have to request is not formed in the usual format.
it is composed like http://apikey:password@hostname/admin/resource.xml
with urllib I can request it but i cant set the headers for an xml request so it doesn't work.
urllib2, httplib... are having problems with the ':'.
I get either a 'nodename nor servname provided, or not known' or a 'nonnumeric port' because it expects a port number after the semicolon.
any help?
A:
Look into how to do HTTP Basic authentication in Python. See especially the section on Doing it Properly.
| shopify xml request from GAE python | I'm trying to make requests to the shopify.com API over GAE python
the url i have to request is not formed in the usual format.
it is composed like http://apikey:password@hostname/admin/resource.xml
with urllib I can request it but i cant set the headers for an xml request so it doesn't work.
urllib2, httplib... are having problems with the ':'.
I get either a 'nodename nor servname provided, or not known' or a 'nonnumeric port' because it expects a port number after the semicolon.
any help?
| [
"Look into how to do HTTP Basic authentication in Python. See especially the section on Doing it Properly.\n"
] | [
2
] | [] | [] | [
"google_app_engine",
"python",
"xml"
] | stackoverflow_0003753951_google_app_engine_python_xml.txt |
Q:
How to copy directory permissions
I'm curious how to copy the permission from directory to another.
Any idea?
Thanks
A:
shutil.copymode should help you out. From the documentation:
shutil.copymode(src, dst)
Copy the permission bits from src to dst. The file contents, owner, and group are unaffected. src and dst are path names given as strings.
I tested this in Ubuntu Jaunty using Python 2.6.2 and it worked for me.
A:
Since you mentionned python, I assume you are looking for
shutil.copymode(src, dst)
See the documentation on shutil
A:
Try cp -a from_dir to_dir. It will maintain the permissions from the first directory.
| How to copy directory permissions | I'm curious how to copy the permission from directory to another.
Any idea?
Thanks
| [
"shutil.copymode should help you out. From the documentation:\n\nshutil.copymode(src, dst)\nCopy the permission bits from src to dst. The file contents, owner, and group are unaffected. src and dst are path names given as strings.\n\nI tested this in Ubuntu Jaunty using Python 2.6.2 and it worked for me.\n",
"Sin... | [
5,
2,
1
] | [] | [] | [
"permissions",
"python"
] | stackoverflow_0003754848_permissions_python.txt |
Q:
Scheduling a time in the future to send an email in Java or Python
I'm writing an application and I'd like it to somehow schedule an email to be sent at a later date (likely an hour after it is run). The programming language will be Python or Java.
Any open-source tools available for that purpose?
EDIT: I forgot to mention it's to be run after a test run, so the application will already be down and I believe the Quartz solution wouldn't work. Would this be possible?
Ideally, I'd like to hear that SMTP protocol has some hidden stuff that allows this, and would just require adding some flag to the message and email providers would interpret as to having to send them later.
A:
Quartz Scheduler can be user for this kind of asynchronous jobs.
A:
Quartz is a great Java library for functions that you want to run at a certain time, after a certain time interval, etc.
There is also the Timer class in the JDK.
A:
If you are to use Java, try Quartz, an open source job scheduling framework.
A:
You can build the actual email to send, using JavaMail (with attachments and all), save it to disk, and then delegate a "mail foo@bar.com < textfilefromjavamail" to the Linux batch system.
There is an "at" command which will most likely do exactly what you want.
A:
I don't think standard SMTP protocol has such a feature, so if you want to be platform-independent, you will have to search for another solution.
How about writing your message to a queue (local database, for example) with a timestamp and then have some program watching it periodically and send pending emails out?
Is the delay an exact timedelta or is it "1-2 hours later"? If it is the latter, than you can have an hourly job (cronjob starting every hour or a background job sleeping for an hour), which would then send out the emails.
A:
Answer 1:
In Python, use threading.Timer to schedule in the future; use smtplib to send an email. No external library needed.
Answer 2:
Sounds like you want the sending program to quit rather than having it wait in the background. You may use cron for this. Alternative just use the unix command sleep and mail:
$ { sleep 3600; echo "hello world" | mail -s the-subject destination-email; } &
P.S. I don't believe SMTP have anything for you in this case. You are really looking for an MTA that has scheduling feature. Though I'm not familiar with it to make a recommendation.
| Scheduling a time in the future to send an email in Java or Python | I'm writing an application and I'd like it to somehow schedule an email to be sent at a later date (likely an hour after it is run). The programming language will be Python or Java.
Any open-source tools available for that purpose?
EDIT: I forgot to mention it's to be run after a test run, so the application will already be down and I believe the Quartz solution wouldn't work. Would this be possible?
Ideally, I'd like to hear that SMTP protocol has some hidden stuff that allows this, and would just require adding some flag to the message and email providers would interpret as to having to send them later.
| [
"Quartz Scheduler can be user for this kind of asynchronous jobs.\n",
"Quartz is a great Java library for functions that you want to run at a certain time, after a certain time interval, etc.\nThere is also the Timer class in the JDK.\n",
"If you are to use Java, try Quartz, an open source job scheduling framew... | [
7,
3,
2,
2,
1,
1
] | [] | [] | [
"email",
"java",
"python",
"scheduling"
] | stackoverflow_0003753982_email_java_python_scheduling.txt |
Q:
How to use a generator to iterate over a tree's leafs
The problem:
I have a trie and I want to return the information stored in it. Some leaves have information (set as value > 0) and some leaves do not. I would like to return only those leaves that have a value.
As in all trie's number of leaves on each node is variable, and the key to each value is actually made up of the path necessary to reach each leaf.
I am trying to use a generator to traverse the tree postorder, but I cannot get it to work. What am I doing wrong?
My module:
class Node():
'''Each leaf in the trie is a Node() class'''
def __init__(self):
self.children = {}
self.value = 0
class Trie():
'''The Trie() holds all nodes and can return a list of their values'''
def __init__(self):
self.root = Node()
def add(self, key, value):
'''Store a "value" in a position "key"'''
node = self.root
for digit in key:
number = digit
if number not in node.children:
node.children[number] = Node()
node = node.children[number]
node.value = value
def __iter__(self):
return self.postorder(self.root)
def postorder(self, node):
if node:
for child in node.children.values():
self.postorder(child)
# Do my printing / job related stuff here
if node.value > 0:
yield node.value
Example use:
>>trie = Trie()
>>trie.add('foo', 3)
>>trie.add('foobar', 5)
>>trie.add('fobaz', 23)
>>for key in trie:
>>....print key
>>
3
5
23
I know that the example given is simple and can be solved using any other data structure. However, it is important for this program to use a trie as it is very beneficial for the data access patterns.
Thanks for the help!
Note: I have omitted newlines in the code block to be able to copy-paste with greater ease.
A:
Change
self.postorder(child)
to
for n in self.postorder(child):
yield n
seems to make it work.
P.S. It is very helpful for you to left out the blank lines for ease of cut & paste :)
| How to use a generator to iterate over a tree's leafs | The problem:
I have a trie and I want to return the information stored in it. Some leaves have information (set as value > 0) and some leaves do not. I would like to return only those leaves that have a value.
As in all trie's number of leaves on each node is variable, and the key to each value is actually made up of the path necessary to reach each leaf.
I am trying to use a generator to traverse the tree postorder, but I cannot get it to work. What am I doing wrong?
My module:
class Node():
'''Each leaf in the trie is a Node() class'''
def __init__(self):
self.children = {}
self.value = 0
class Trie():
'''The Trie() holds all nodes and can return a list of their values'''
def __init__(self):
self.root = Node()
def add(self, key, value):
'''Store a "value" in a position "key"'''
node = self.root
for digit in key:
number = digit
if number not in node.children:
node.children[number] = Node()
node = node.children[number]
node.value = value
def __iter__(self):
return self.postorder(self.root)
def postorder(self, node):
if node:
for child in node.children.values():
self.postorder(child)
# Do my printing / job related stuff here
if node.value > 0:
yield node.value
Example use:
>>trie = Trie()
>>trie.add('foo', 3)
>>trie.add('foobar', 5)
>>trie.add('fobaz', 23)
>>for key in trie:
>>....print key
>>
3
5
23
I know that the example given is simple and can be solved using any other data structure. However, it is important for this program to use a trie as it is very beneficial for the data access patterns.
Thanks for the help!
Note: I have omitted newlines in the code block to be able to copy-paste with greater ease.
| [
"Change \nself.postorder(child)\n\nto\nfor n in self.postorder(child):\n yield n\n\nseems to make it work.\nP.S. It is very helpful for you to left out the blank lines for ease of cut & paste :)\n"
] | [
2
] | [] | [] | [
"generator",
"python",
"tree"
] | stackoverflow_0003755242_generator_python_tree.txt |
Q:
Python or SQL Logistic Regression
Given time-series data, I want to find the best fitting logarithmic curve. What are good libraries for doing this in either Python or SQL?
Edit: Specifically, what I'm looking for is a library that can fit data resembling a sigmoid function, with upper and lower horizontal asymptotes.
A:
If your data were categorical, then you could use a logistic regression to fit the probabilities of belonging to a class (classification).
However, I understand you are trying to fit the data to a sigmoid curve, which means you just want to minimize the mean squared error of the fit.
I would redirect you to the SciPy function called scipy.optimize.leastsq: it is used to perform least squares fits.
| Python or SQL Logistic Regression | Given time-series data, I want to find the best fitting logarithmic curve. What are good libraries for doing this in either Python or SQL?
Edit: Specifically, what I'm looking for is a library that can fit data resembling a sigmoid function, with upper and lower horizontal asymptotes.
| [
"If your data were categorical, then you could use a logistic regression to fit the probabilities of belonging to a class (classification).\nHowever, I understand you are trying to fit the data to a sigmoid curve, which means you just want to minimize the mean squared error of the fit.\nI would redirect you to the ... | [
3
] | [] | [] | [
"machine_learning",
"math",
"python",
"regression",
"sql"
] | stackoverflow_0003754051_machine_learning_math_python_regression_sql.txt |
Q:
Django newbie question regarding defining an object with subobjects from models for use in templates
I am somewhat new to Django and have searched for some simple examples of creating objects with subobjects in views so that in templates I can have nested for loops.
Here is my models.py for this application...
from django.db import models
from django import forms
class Market(models.Model):
name = models.CharField('Market name', max_length=150)
state = models.CharField('State', max_length=2)
def __unicode__(self):
return self.name
class Location(models.Model):
name = models.CharField('Location name', max_length=150)
address1 = models.CharField('Address 1', max_length=200)
address2 = models.CharField('Address 2', max_length=200,blank=True)
city = models.CharField('City', max_length=100)
state = models.CharField('State', max_length=2)
zip_code = models.CharField('ZIP', max_length=10)
phone = models.CharField('Phone', max_length=20)
hours = models.TextField('Hours of operation', max_length=255)
quote_text = models.TextField('Customer quote', max_length=500)
quote_by = models.CharField('Customer name', max_length=30)
yelp_url = models.URLField('Yelp URL', max_length=300,blank=True)
image_store = models.ImageField('Storefront image', upload_to='images/locations', max_length=300,blank=True)
image_staff = models.ImageField('Staff image', upload_to='images/locations', max_length=300,blank=True)
market = models.ForeignKey(Market, verbose_name='Regional market', null=True)
def __unicode__(self):
return self.name
Markets data may look as follows...
id = 1
state = 'MO'
name = 'St. Louis - Central'
id = 2
state = 'MO'
name = 'St. Louis - West'
id = 3
state = 'IL'
name = 'Chicago - South'
id = 4
state = 'IL'
name = 'Chicago - North'
In my views.py I'd like to create an object with a list/array of grouped Market states (distinct) in descending order, each with a subarray of the individual Market names in that State in order to complete a nested forloop in the template.
The templating language in Django is really cool in how it prevents a ton of logic from residing betwixt the html, which I like. But I am still wrapping my head around both Python syntax and the need to create all objects exactly the way they need to iterate in the template.
Here's what views.py looks like ...
def locations_landing(request):
marketList = Market.objects.values('state').order_by('-state').distinct()
return render_to_response('locations.html', locals())
How to return an object so that my template can perform the following nested looping...
{% for st in stateList.all %}
<h4>{{ st.state }}</h4>
{% for mkt in stateList.marketList.all %}
<p>* <a href="#">{{ mkt.name }}</a></p>
{% endfor %}
{% endfor %}
This would result in the following rendered in html based on my data samples above...
<h4>MO</h4>
<p>* St. Louis - Central</p>
<p>* St. Louis - West</p>
<h4>IL</h4>
<p>* Chicago - South</p>
<p>* Chicago - North</p>
BTW, there are no errors in any of the .PY code samples above, all is well, I just need some guidance on creating the object correctly in the view so the template does it's thing.
A:
I don't see a need to use distinct here. By representing the states as separate model and using relations you would gain much more flexibility.
I suggest you create a third State model and use a ForeignKey to relate the models together so that each Market has a one to many relation to single State, i guess you also want Location model related to the Market model.
class State(models.Model):
name = models.CharField('State name', max_length=150)
class Market(models.Model):
name = models.CharField('Market name', max_length=150)
state = models.ForeignKeyField(State)
class Location(models.Model):
state = models.ForeignKeyField(Market)
...
In your view, all you need to do is take all the states and pass them into the template:
def locations_landing(request):
state_list = State.objects.all()
return render_to_response('locations.html', {'state_list':state_list})
And finally, in your template, iterate over the state list and use a backward relation queryset to get all the markets in that state:
{% for state in state_list %}
<h4>{{ state }}</h4>
{% for market in state.market_set.all %}
<p>* <a href="#">{{ market }}</a></p>
{% for location in market.location_set.all %}
<p> {{ location }} </p>
{% endfor %}
{% endfor %}
{% endfor %}
| Django newbie question regarding defining an object with subobjects from models for use in templates | I am somewhat new to Django and have searched for some simple examples of creating objects with subobjects in views so that in templates I can have nested for loops.
Here is my models.py for this application...
from django.db import models
from django import forms
class Market(models.Model):
name = models.CharField('Market name', max_length=150)
state = models.CharField('State', max_length=2)
def __unicode__(self):
return self.name
class Location(models.Model):
name = models.CharField('Location name', max_length=150)
address1 = models.CharField('Address 1', max_length=200)
address2 = models.CharField('Address 2', max_length=200,blank=True)
city = models.CharField('City', max_length=100)
state = models.CharField('State', max_length=2)
zip_code = models.CharField('ZIP', max_length=10)
phone = models.CharField('Phone', max_length=20)
hours = models.TextField('Hours of operation', max_length=255)
quote_text = models.TextField('Customer quote', max_length=500)
quote_by = models.CharField('Customer name', max_length=30)
yelp_url = models.URLField('Yelp URL', max_length=300,blank=True)
image_store = models.ImageField('Storefront image', upload_to='images/locations', max_length=300,blank=True)
image_staff = models.ImageField('Staff image', upload_to='images/locations', max_length=300,blank=True)
market = models.ForeignKey(Market, verbose_name='Regional market', null=True)
def __unicode__(self):
return self.name
Markets data may look as follows...
id = 1
state = 'MO'
name = 'St. Louis - Central'
id = 2
state = 'MO'
name = 'St. Louis - West'
id = 3
state = 'IL'
name = 'Chicago - South'
id = 4
state = 'IL'
name = 'Chicago - North'
In my views.py I'd like to create an object with a list/array of grouped Market states (distinct) in descending order, each with a subarray of the individual Market names in that State in order to complete a nested forloop in the template.
The templating language in Django is really cool in how it prevents a ton of logic from residing betwixt the html, which I like. But I am still wrapping my head around both Python syntax and the need to create all objects exactly the way they need to iterate in the template.
Here's what views.py looks like ...
def locations_landing(request):
marketList = Market.objects.values('state').order_by('-state').distinct()
return render_to_response('locations.html', locals())
How to return an object so that my template can perform the following nested looping...
{% for st in stateList.all %}
<h4>{{ st.state }}</h4>
{% for mkt in stateList.marketList.all %}
<p>* <a href="#">{{ mkt.name }}</a></p>
{% endfor %}
{% endfor %}
This would result in the following rendered in html based on my data samples above...
<h4>MO</h4>
<p>* St. Louis - Central</p>
<p>* St. Louis - West</p>
<h4>IL</h4>
<p>* Chicago - South</p>
<p>* Chicago - North</p>
BTW, there are no errors in any of the .PY code samples above, all is well, I just need some guidance on creating the object correctly in the view so the template does it's thing.
| [
"I don't see a need to use distinct here. By representing the states as separate model and using relations you would gain much more flexibility.\nI suggest you create a third State model and use a ForeignKey to relate the models together so that each Market has a one to many relation to single State, i guess you al... | [
2
] | [] | [] | [
"django",
"models",
"python",
"templates",
"views"
] | stackoverflow_0003755164_django_models_python_templates_views.txt |
Q:
Using Relative Paths To Log Files In Pylons' development.ini
I am working on a Pylons app that runs on top of Apache with mod_wsgi. I would like to send logging messages that my app generates to files in my app's directory, instead of to Apache's logs. Further, I would like to specify the location of logfiles via a relative path so that it'll be easier to deploy my app on other people's servers. Right now I can log to files, but only via a fragile absolute path.
Here is the relevant part of my development.ini file:
# Logging configuration
[loggers]
keys = root, routes, myapp, sqlalchemy, debugging-logger
[handlers]
keys = console, debugging-logger-file
[formatters]
keys = generic
[logger_debugging-logger]
level = DEBUG
handlers = debugging-logger-file
qualname = myapp.controllers.logging-test-controller.debugging-logger
[handler_debugging-logger-file]
class = FileHandler
args = ('/var/pylons/myapp/logs/myapp-debugging-errors.log', 'a')
level = DEBUG
formatter = generic
Although the .ini helpfully advises using %(here)s to refer to the current path, using %(here)s in the "args = ('foo')" line of the error handler does not behave the way that I expect it to. The syntax of this ini file is documented on the Paste Deploy site, but does not specify how %(here)s can be used in relation to quoted strings.
What syntax should I use in the "args = ('foo')" line to specify the current path?
A:
The problem is that Paste Deploy creates one ConfigParser object to store the 'here' tag in it's set of defaults, and logging.config.fileConfig() is never passed that set of defaults. Therefore, when fileConfig() reads the .ini file, it doesn't have access to the 'here' tag, and the ConfigParser's interpolation can't find it.
You could do something like this:
[DEFAULT]
my_log_dir = '/var/pylons/myapp/logs'
...
[handler_debugging-logger-file]
args = (%(my_log_dir)s + '/myapp-debugging-errors.log', 'a')
Not exactly what you're looking for, but a tiny bit more configurable.
Another possibility is:
args = (os.getcwd() + '/myapp-debugging-errors.log', 'a')
(This works because 'os' is a valid variable in the logging module's namespace when it calls eval() on the args value. But this is an implementation detail of the logging package that may not be reliable long term.) But this most likely won't give you what you want-- it will most likely use the Apache process's working directory.
You could even set an environment variable outside the program, and use it like:
args = (os.environ['MY_LOG_DIR'] + '/myapp-debugging-errors.log', 'a')
And yet another possibility is overriding the behavior of some of the functions or class methods in the logging module or paste package.
Hope those give you some ideas.
A:
Configuration files for Paste Deploy allow a 'here' tag to indicate directory where configuration file is. You can then work relative to that.
| Using Relative Paths To Log Files In Pylons' development.ini | I am working on a Pylons app that runs on top of Apache with mod_wsgi. I would like to send logging messages that my app generates to files in my app's directory, instead of to Apache's logs. Further, I would like to specify the location of logfiles via a relative path so that it'll be easier to deploy my app on other people's servers. Right now I can log to files, but only via a fragile absolute path.
Here is the relevant part of my development.ini file:
# Logging configuration
[loggers]
keys = root, routes, myapp, sqlalchemy, debugging-logger
[handlers]
keys = console, debugging-logger-file
[formatters]
keys = generic
[logger_debugging-logger]
level = DEBUG
handlers = debugging-logger-file
qualname = myapp.controllers.logging-test-controller.debugging-logger
[handler_debugging-logger-file]
class = FileHandler
args = ('/var/pylons/myapp/logs/myapp-debugging-errors.log', 'a')
level = DEBUG
formatter = generic
Although the .ini helpfully advises using %(here)s to refer to the current path, using %(here)s in the "args = ('foo')" line of the error handler does not behave the way that I expect it to. The syntax of this ini file is documented on the Paste Deploy site, but does not specify how %(here)s can be used in relation to quoted strings.
What syntax should I use in the "args = ('foo')" line to specify the current path?
| [
"The problem is that Paste Deploy creates one ConfigParser object to store the 'here' tag in it's set of defaults, and logging.config.fileConfig() is never passed that set of defaults. Therefore, when fileConfig() reads the .ini file, it doesn't have access to the 'here' tag, and the ConfigParser's interpolation ca... | [
8,
0
] | [] | [] | [
"logging",
"mod_wsgi",
"pylons",
"python"
] | stackoverflow_0003752982_logging_mod_wsgi_pylons_python.txt |
Q:
Does IronPython .net based DLL need to be deployed with Python Standard Library if it uses the Standard Library?
If I reference the Python Standard Library using IronPython do I have to deploy any Python related libraries or runtimes along with my .net dll? Or, can I just deploy the dll?
A:
you need to deploy the python libraries you're referencing along with your dll. it wont be included statically in there for you.
| Does IronPython .net based DLL need to be deployed with Python Standard Library if it uses the Standard Library? | If I reference the Python Standard Library using IronPython do I have to deploy any Python related libraries or runtimes along with my .net dll? Or, can I just deploy the dll?
| [
"you need to deploy the python libraries you're referencing along with your dll. it wont be included statically in there for you.\n"
] | [
3
] | [] | [] | [
".net",
"ironpython",
"python"
] | stackoverflow_0003755493_.net_ironpython_python.txt |
Q:
Sharing data between nodes (app servers) in cloud
I'm building a Python/Pylons webapp that has been served by single server so far, now I want to investigate how it would scale among several servers with some kind of load balancer in front.
The main concern is server-side state, of course. It includes user session data, user uploaded data (pictures and the like), and cache. I want app servers to share cache, so one server doesn't have to do extra work if other has already done it. Scaling is probably not going to be an issue anytime soon, but this seems like a big architectural decision so better get it semi-right at the beginning.
For sessions, I could use cookie-based sessions: http://beaker.groovie.org/sessions.html#cookie-based
For user uploaded data and cache (both currently stored on local filesystem) I need a different approach and I'm not sure which one would be the best fit. Some of the options I've considered:
Distributed filesystem
Amazon S3 in particular, since I'm targeting Amazon as cloud provider. However, I'd like to avoid my code becoming overly vendor-specific, so changing cloud provider later is feasible.
[distributed] key-value store, would require to rewrite/abstract-out parts of my code that assume all data goes on filesystem
Somehow avoid sharing data at all, load balancer could be very clever to direct requests to nodes that have neccessary user data / cache locally. Wait, this is called sharding, right?
Network-accessible filesystem, NFS in particular: NFS directory exported on one (possibly dedicated) node, all others mounting it. Possible problems I can think of:
Bandwidth to NFS host could become a bottleneck
Race conditions when several clients try to access same files at the same time
I'm currently considering going with NFS--it seems to be the easiest solution that could possibly work. But then again, maybe there are more caveats that I'm not aware of, making this a short-sighted decision? What is your experience, what forms of data storage and sharing you have used for apps that hosted in cloud and are expected to scale horizontally?
A:
caching is easily accomplished using standard memecached - which can be distributed over multiple servers.
NFS sounds like a bad idea since you'll need to implement your own locking mechanism to avoid race conditions.
I would go for one of the distributed no-sql solutions like cassandra.
A:
I'd strongly recommend that you look at a distributed key/value store rather than NFS.
I'd probably use redis rather than cassandra since you are currently on one system and want to scale up to 2 systems. Cassandra while cool, is designed for systems with more writes than reads, and works best when you have 3 or more nodes.
Redis on the other hand works very well with a single node deamon, essentially like memcached but with fallible persistence.
Redis is trivially easy to use under python, it is very performant, so until you are doing millions of requests you shouldn't need to worry about sharding or scaling the Redis itself, but it's failover that is likely to be the biggest issue. I've not deployed it personally, so I'm not sure how effective / easy it is to recover all the data if it ever fails and you fail over to another one. If you think that's likely then I'd investigate it.
If you want to store more complex data structures, I'd look into MongoDB or one of it's equivalents.
| Sharing data between nodes (app servers) in cloud | I'm building a Python/Pylons webapp that has been served by single server so far, now I want to investigate how it would scale among several servers with some kind of load balancer in front.
The main concern is server-side state, of course. It includes user session data, user uploaded data (pictures and the like), and cache. I want app servers to share cache, so one server doesn't have to do extra work if other has already done it. Scaling is probably not going to be an issue anytime soon, but this seems like a big architectural decision so better get it semi-right at the beginning.
For sessions, I could use cookie-based sessions: http://beaker.groovie.org/sessions.html#cookie-based
For user uploaded data and cache (both currently stored on local filesystem) I need a different approach and I'm not sure which one would be the best fit. Some of the options I've considered:
Distributed filesystem
Amazon S3 in particular, since I'm targeting Amazon as cloud provider. However, I'd like to avoid my code becoming overly vendor-specific, so changing cloud provider later is feasible.
[distributed] key-value store, would require to rewrite/abstract-out parts of my code that assume all data goes on filesystem
Somehow avoid sharing data at all, load balancer could be very clever to direct requests to nodes that have neccessary user data / cache locally. Wait, this is called sharding, right?
Network-accessible filesystem, NFS in particular: NFS directory exported on one (possibly dedicated) node, all others mounting it. Possible problems I can think of:
Bandwidth to NFS host could become a bottleneck
Race conditions when several clients try to access same files at the same time
I'm currently considering going with NFS--it seems to be the easiest solution that could possibly work. But then again, maybe there are more caveats that I'm not aware of, making this a short-sighted decision? What is your experience, what forms of data storage and sharing you have used for apps that hosted in cloud and are expected to scale horizontally?
| [
"caching is easily accomplished using standard memecached - which can be distributed over multiple servers.\nNFS sounds like a bad idea since you'll need to implement your own locking mechanism to avoid race conditions.\nI would go for one of the distributed no-sql solutions like cassandra.\n",
"I'd strongly reco... | [
1,
1
] | [] | [] | [
"architecture",
"cloud",
"python",
"scaling"
] | stackoverflow_0003440521_architecture_cloud_python_scaling.txt |
Q:
importing modules' files into submodules
i have a module with many files, which i import in themselves for sharing of functionality
myModule/
-myFile1.py
-myFile2.py
-mySubmodule/
--myFile3.py
i can do import myFile2, inside of myFile1, but how can i do a import myFile2 in myFile3 without referencing the base module? i dont want to reference myModule, because i am working on a branch so the name is going to change.
A:
You're asking about relative imports. See this question
Within myFile3, you want:
from .. import myFile2
| importing modules' files into submodules | i have a module with many files, which i import in themselves for sharing of functionality
myModule/
-myFile1.py
-myFile2.py
-mySubmodule/
--myFile3.py
i can do import myFile2, inside of myFile1, but how can i do a import myFile2 in myFile3 without referencing the base module? i dont want to reference myModule, because i am working on a branch so the name is going to change.
| [
"You're asking about relative imports. See this question\nWithin myFile3, you want:\nfrom .. import myFile2\n\n"
] | [
0
] | [] | [] | [
"import",
"module",
"python"
] | stackoverflow_0003755330_import_module_python.txt |
Q:
Trying to use my subnet address in python code
I'm trying to get my ip subnet address (192.168.1.xxx) into my python code. I'm running linux/osx. How do I do this/ What is the best way to do this?
A:
The easiest way to to this in my experience is to use two third party packages:
python-netifaces: Portable network interface information
python-netaddr: Pythonic manipulation of IPv4, IPv6, CIDR, EUI and MAC network addresses
So install those modules and then it's as easy as this:
import netifaces
import netaddr
import socket
from pprint import pformat
ifaces = netifaces.interfaces()
# => ['lo', 'eth0', 'eth1']
myiface = 'eth0'
addrs = netifaces.ifaddresses(myiface)
# {2: [{'addr': '192.168.1.150',
# 'broadcast': '192.168.1.255',
# 'netmask': '255.255.255.0'}],
# 10: [{'addr': 'fe80::21a:4bff:fe54:a246%eth0',
# 'netmask': 'ffff:ffff:ffff:ffff::'}],
# 17: [{'addr': '00:1a:4b:54:a2:46', 'broadcast': 'ff:ff:ff:ff:ff:ff'}]}
# Get ipv4 stuff
ipinfo = addrs[socket.AF_INET][0]
address = ipinfo['addr']
netmask = ipinfo['netmask']
# Create ip object and get
cidr = netaddr.IPNetwork('%s/%s' % (address, netmask))
# => IPNetwork('192.168.1.150/24')
network = cidr.network
# => IPAddress('192.168.1.0')
print 'Network info for %s:' % myiface
print '--'
print 'address:', address
print 'netmask:', netmask
print ' cidr:', cidr
print 'network:', network
And this outputs:
Network info for eth0:
--
address: 192.168.1.150
netmask: 255.255.255.0
cidr: 192.168.1.150/24
network: 192.168.1.0
This was done using Linux. With OSX the interface names are different but the method is the same.
| Trying to use my subnet address in python code | I'm trying to get my ip subnet address (192.168.1.xxx) into my python code. I'm running linux/osx. How do I do this/ What is the best way to do this?
| [
"The easiest way to to this in my experience is to use two third party packages:\n\npython-netifaces: Portable network interface information\npython-netaddr: Pythonic manipulation of IPv4, IPv6, CIDR, EUI and MAC network addresses\n\nSo install those modules and then it's as easy as this:\nimport netifaces\nimport ... | [
9
] | [] | [] | [
"linux",
"networking",
"python"
] | stackoverflow_0003755863_linux_networking_python.txt |
Q:
Form.save(commit=False) behaving differently in Django 1.2.3?
Prior to today, I've been using Django 1.1. To ensure I'm keeping up with the times, I decided to update my Django environment to use Django 1.2.3. Unfortunately, I've encountered an issue.
The following code did not raise a ValueError in 1.1:
instance = FormClass(
request.POST,
instance=existing_instance
).save(commit=False)
However, now that I've upgraded, it raises a ValueError each time. I have a SSN field that I'm submitting as part of my Form and I strip out the dashes prior to doing an instance.save() call. Unfortunately, the ValueError occurs because Django thinks my SSN value is too long (it's expecting 9 characters and it's receiving 11 -- 123-45-6789).
I've looked through the Django docs and I couldn't find anything relating to this change. Any idea what's going on? I've always thought the purpose of the "commit=False" parameter was to allow pre-processing of data before saving the information.
Am I missing something?
A:
According to the 1.2 docs on the save() method, "If you call save() with commit=False, then it will return an object that hasn't yet been saved to the database." So I'm not sure why there would have been a change in functionality, but it's possible that in 1.1 validation/check code ran only when an object was saved to the database, and in 1.2 it happens earlier (before the object is saved).
In any case, if you're cleaning data that is being entered in a form, you should probably be cleaning it in the FormClass:
def clean_ssn(self):
data = re.sub(r'[^0-9]','',self.cleaned_data['ssn'])
#validation code here
return data
That should at least fix the problem...
| Form.save(commit=False) behaving differently in Django 1.2.3? | Prior to today, I've been using Django 1.1. To ensure I'm keeping up with the times, I decided to update my Django environment to use Django 1.2.3. Unfortunately, I've encountered an issue.
The following code did not raise a ValueError in 1.1:
instance = FormClass(
request.POST,
instance=existing_instance
).save(commit=False)
However, now that I've upgraded, it raises a ValueError each time. I have a SSN field that I'm submitting as part of my Form and I strip out the dashes prior to doing an instance.save() call. Unfortunately, the ValueError occurs because Django thinks my SSN value is too long (it's expecting 9 characters and it's receiving 11 -- 123-45-6789).
I've looked through the Django docs and I couldn't find anything relating to this change. Any idea what's going on? I've always thought the purpose of the "commit=False" parameter was to allow pre-processing of data before saving the information.
Am I missing something?
| [
"According to the 1.2 docs on the save() method, \"If you call save() with commit=False, then it will return an object that hasn't yet been saved to the database.\" So I'm not sure why there would have been a change in functionality, but it's possible that in 1.1 validation/check code ran only when an object was sa... | [
3
] | [] | [] | [
"django",
"django_forms",
"pre_commit",
"python"
] | stackoverflow_0003755738_django_django_forms_pre_commit_python.txt |
Q:
How would I write some values/strings in particular columns of a file in python
I have some values that I want to write in a text file with the constraint that each value has to go to a particular column of each line.
For example, lets say that I have values = [a, b, c, d] and I want to write them in a line so that a is going to be written in the 10th column of the line, b on the 25th, c on the 34th, and d on the 48th column.
How would I do this in python?
Does python have something like column.insert(10, a)? It would make my life way easier.
I appreciate your hep.
A:
In this case, I'd think you'd just use the padding functions with python's string formatting syntax.
Something like "%10d%15d%9d%14d"%values will place the right-most digit of a,b,c,d on the columns you listed.
If you want to have the left-most digits placed there, then you could use: "%<15d%<9d%<14d%d"%values, and prepend 10 spaces.
EDIT: For some reason I'm having trouble with the above syntax... so I used the newstyle formatting syntax like so:
" "*9 + "{:<14}{:<9}{:<14}{}".format(*values)
This should print, for values=[20,30,403,50]:
......... <-- from " "*9
20............ <-- {:<14}
30....... <-- {:<9}
403........... <-- {:<14}
50 <-- {}
----=----1----=----2----=----3----=----4----=----5 <-- guide
20 30 403 50 <-- Actual output, all together
A:
class ColumnWriter(object):
def __init__(self, columns):
columns = (-1, ) + tuple(columns)
widths = (c2 - c1 for c1, c2 in zip(columns, columns[1:]))
format_codes = ("{" + str(i) + ":>" + str(width) +"}"
for i, width in enumerate(widths))
self.format_string = ''.join(format_codes)
def get_row(self, values):
return self.format_string.format(*values)
cw = ColumnWriter((1, 20, 21))
print cw.get_row((1, 2, 3))
print cw.get_row((1, 'a', 'a'))
if you need the columns to vary from row to row, then you can do one liners.
import itertools
for columns in itertools.combinations(range(10), 3):
print ColumnWriter(columns).get_row(('.','.','.'))
It slacks on the error checking. It needs to check that columns is sorted and that len(values) == len(columns).
It has problems with the value being longer than the area being allocated to hold it but I'm not sure what to do about this. Currently if that occurs, it overwrites the previous column. example:
print ColumnWriter((1, 2, 3)).get_row((1, 1, 'aa'))
If you had an iterable of rows that you wanted to write to a file, you could do something like this
rows = [(1, 3, 4), ('a', 'b', 4), ['foo', 'ten', 'mongoose']]
format = ColumnWriter((20, 30, 50)).get_row
with open(filename, 'w') as fout:
fout.write("\n".join(format(row) for row in rows))
| How would I write some values/strings in particular columns of a file in python | I have some values that I want to write in a text file with the constraint that each value has to go to a particular column of each line.
For example, lets say that I have values = [a, b, c, d] and I want to write them in a line so that a is going to be written in the 10th column of the line, b on the 25th, c on the 34th, and d on the 48th column.
How would I do this in python?
Does python have something like column.insert(10, a)? It would make my life way easier.
I appreciate your hep.
| [
"In this case, I'd think you'd just use the padding functions with python's string formatting syntax.\nSomething like \"%10d%15d%9d%14d\"%values will place the right-most digit of a,b,c,d on the columns you listed.\nIf you want to have the left-most digits placed there, then you could use: \"%<15d%<9d%<14d%d\"%valu... | [
3,
1
] | [
"You can use the mmap module to memory-map a file.\nhttp://docs.python.org/library/mmap.html\nWith mmap you can do something like this:\nfh = file('your_file', 'wb')\nmap = mmap.mmap(fh.fileno(), <length of the file you want to create>)\nmap[10] = a\nmap[25] = b\n\nNot sure if that is what you're looking for, but i... | [
-1
] | [
"file",
"file_io",
"python"
] | stackoverflow_0003756097_file_file_io_python.txt |
Q:
How to declare a method that takes an instance as an argument in Python?
I know it is probably a stupid question, but I am new to OOP in Python and if I declare a function def myFunction( b) and pass an instance of an object to it, I get TypeError: expected string or buffer.
To be more specific, I have a following code that I use to parse a summary molecular formula and make an object out of it.
class SummaryFormula:
def __init__( self, summaryFormula):
self.atoms = {}
for atom in re.finditer( "([A-Z][a-z]{0,2})(\d*)", summaryFormula):
symbol = atom.group(1)
count = atom.group(2)
def extend( self, b):
# these are the two dictionaries of both molecules
originalFormula = self.atoms.copy()
self.atoms.clear()
addAtoms = SummaryFormula( b)
# and here both dictionaries are merged
for atom in addAtoms.atoms.keys():
if atom in originalFormula.keys():
self.atoms[ atom] = originalFormula[ atom]
self.atoms[ atom] += addAtoms.atoms[ atom]
else:
pass
for atom in originalFormula.keys():
if atom not in self.atoms.keys():
self.atoms[ atom] = originalFormula[ atom]
#this is what works now
test = SummaryFormula( "H2CFe2")
test.extend("H5C5") #result is a molecule H7C6Fe2
#this is what I want instead
test = SummaryFormula( "H2CFe2")
toExtend = SummaryFormula( "H5C5")
test.extend( toExtend)
Thank you, Tomas
A:
Firstly, the program needs to include the re module.
Secondly, you have a typo at line 4:
for atom in re.finditer( "([A-Z][a-z]{0,2})(\d*)", SummaryFormula):
should read
for atom in re.finditer( "([A-Z][a-z]{0,2})(\d*)", summaryFormula):
i.e. lower-case s in summaryFormula.
SummaryFormula refers to the name of the class while summaryFormula refers to the second parameter (after self) of the __init__ method.
Third, the line addAtoms = SummaryFormula(b) is passing an instance of SummaryFormula as argument b (assigned in top-level part of script test.extend(toExtend).
The fixed program should look like:
import re
class SummaryFormula:
def __init__(self, summaryFormula):
self.atoms = {}
for atom in re.finditer("([A-Z][a-z]{0,2})(\d*)", summaryFormula):
symbol = atom.group(1)
count = atom.group(2)
def extend( self, b):
# these are the two dictionaries of both molecules
originalFormula = self.atoms.copy()
self.atoms.clear()
# PASS AN APPROPRIATE VALUE HERE!
addAtoms = SummaryFormula("SOME STRING")
# and here both dictionaries are merged
for atom in addAtoms.atoms.keys():
if atom in originalFormula.keys():
self.atoms[ atom] = originalFormula[ atom]
self.atoms[ atom] += addAtoms.atoms[ atom]
else:
pass
for atom in originalFormula.keys():
if atom not in self.atoms.keys():
self.atoms[ atom] = originalFormula[ atom]
#this is what works now
test = SummaryFormula("H2CFe2")
test.extend("H5C5") #result is a molecule H7C6Fe2
#this is what I want instead
test = SummaryFormula("H2CFe2")
toExtend = SummaryFormula("H5C5")
test.extend(toExtend)
with "SOME STRING" replaced by the intended string literal or string variable reference. I don't know the exact intention of the program so I'll leave it up to somebody else to determine what this program should be passing to the constructor of SummaryFormula at this point.
Hope that helps!
A:
Richard Cook is correct. There is another problem, however: In extend, you say:
addAtoms = SummaryFormula( b)
Thus, a SummaryFormula instance is passed into the __init__ method of SummaryFormula. Here (modulo the typo mentioned before), this object is given to re.finditer:
for atom in re.finditer( "([A-Z][a-z]{0,2})(\d*)", summaryFormula)
The function re.finditer expects a string; it doesn't know what to do with a SummaryFormula instance.
There are a few ways to fix this. The immediately simplest is to check whether you already have a SummaryFormula instance before trying to create one:
if isinstance(b, SummaryFormula):
addAtoms = b
else if isinstance(b, str):
addAtoms = SummaryFormula(b)
else:
raise TypeError("Expected a SummaryFormula or equivalent string.")
A:
In short you can pass any object to a function, including instances of classes you created.
More generally, everything in Python is an object. This is a key concept in Python so if you're new to the language spend some time getting familiar as it will help your write code which is more concise and pythonic.
The error you get isn't from passing a class instance object, but rather is generated somewhere (see other answers as they seem to be onto it) else in your code by another function or operation which is expecting a string, or string-like object to operate on. For example you can generate a similar error by doing:
>>> a = 2
>>> open(a, 'r')
TypeError: coercing to Unicode: need string or buffer, int found
Here the error occurs because the file opening function open is expecting a string rather than an integer.
| How to declare a method that takes an instance as an argument in Python? | I know it is probably a stupid question, but I am new to OOP in Python and if I declare a function def myFunction( b) and pass an instance of an object to it, I get TypeError: expected string or buffer.
To be more specific, I have a following code that I use to parse a summary molecular formula and make an object out of it.
class SummaryFormula:
def __init__( self, summaryFormula):
self.atoms = {}
for atom in re.finditer( "([A-Z][a-z]{0,2})(\d*)", summaryFormula):
symbol = atom.group(1)
count = atom.group(2)
def extend( self, b):
# these are the two dictionaries of both molecules
originalFormula = self.atoms.copy()
self.atoms.clear()
addAtoms = SummaryFormula( b)
# and here both dictionaries are merged
for atom in addAtoms.atoms.keys():
if atom in originalFormula.keys():
self.atoms[ atom] = originalFormula[ atom]
self.atoms[ atom] += addAtoms.atoms[ atom]
else:
pass
for atom in originalFormula.keys():
if atom not in self.atoms.keys():
self.atoms[ atom] = originalFormula[ atom]
#this is what works now
test = SummaryFormula( "H2CFe2")
test.extend("H5C5") #result is a molecule H7C6Fe2
#this is what I want instead
test = SummaryFormula( "H2CFe2")
toExtend = SummaryFormula( "H5C5")
test.extend( toExtend)
Thank you, Tomas
| [
"Firstly, the program needs to include the re module.\nSecondly, you have a typo at line 4:\nfor atom in re.finditer( \"([A-Z][a-z]{0,2})(\\d*)\", SummaryFormula):\n\nshould read\nfor atom in re.finditer( \"([A-Z][a-z]{0,2})(\\d*)\", summaryFormula):\n\ni.e. lower-case s in summaryFormula.\nSummaryFormula refers to... | [
1,
1,
1
] | [] | [] | [
"object",
"python"
] | stackoverflow_0003755948_object_python.txt |
Q:
Do I have to manually create the combined folder when using Python's Minimatic module?
I'm using the Python library Minimatic found at this site: Minimatic
What this essentially does is it minifies and combines all your css and js files into one file. When deploying my Pylons web application on the server, does this mean I have to manually create the combined folders? So if I have the the directory as such:
/public
|
|--/combined
|
|-/js
|-/css
|
|--/css
|--/js
In /public/css and /public/js, this is where I store all my regular uncompressed css and js. In /public/combined/js and /public/combined/css, that's where I specify the combined property for JS and CSS files in my python code. Do I need to manually create the combined directories in my server or will Minimatic create them for me?
Thanks
-Mark
A:
Yes, Minimatic will, as of this writing, create the directories for you. I found this out by reading the source code on GitHub - lines 149 to 166 or so have your answer.
| Do I have to manually create the combined folder when using Python's Minimatic module? | I'm using the Python library Minimatic found at this site: Minimatic
What this essentially does is it minifies and combines all your css and js files into one file. When deploying my Pylons web application on the server, does this mean I have to manually create the combined folders? So if I have the the directory as such:
/public
|
|--/combined
|
|-/js
|-/css
|
|--/css
|--/js
In /public/css and /public/js, this is where I store all my regular uncompressed css and js. In /public/combined/js and /public/combined/css, that's where I specify the combined property for JS and CSS files in my python code. Do I need to manually create the combined directories in my server or will Minimatic create them for me?
Thanks
-Mark
| [
"Yes, Minimatic will, as of this writing, create the directories for you. I found this out by reading the source code on GitHub - lines 149 to 166 or so have your answer. \n"
] | [
0
] | [] | [] | [
"pylons",
"python"
] | stackoverflow_0003714407_pylons_python.txt |
Q:
Unable to load profile in django
I am trying to add additional fields to the default User model. I had a look around the internet and done something like this:
Made a new model named UserProfile with the following in /UserProfile/models.py:
from django.db import models
from django.contrib.auth.models import User
class UserProfile(models.Model):
# This is the only required field
user = models.ForeignKey(User, unique=True)
# The rest is completely up to you...
favorite_band = models.CharField(max_length=100, blank=True)
favorite_cheese = models.CharField(max_length=100, blank=True)
lucky_number = models.IntegerField()
And added:
AUTH_PROFILE_MODULE = "newSite.userprofile"
To the settings, I also added "UserProfile" to the INSTALLED_APPS as to run sqlall.
The only problem is when I try the following in the shell:
>>> from django.contrib.auth.models import User
>>> user = User.objects.get(username = "user01")
>>> user.get_profile()
I get the following error:
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "C:\Python27\lib\site-packages\django\contrib\auth\models.py", line 367,in get_profile
raise SiteProfileNotAvailable('Unable to load the profile '
SiteProfileNotAvailable: Unable to load the profile model, check AUTH_PROFILE_MODULE in your project settings
Any help to solve this problem is appreciated!
A:
If you really did create an app caled UserProfile and put the models.py there, then you should put
AUTH_PROFILE_MODULE = "userprofile.userprofile"
into your settings.py file instead.
You should make your UserProfile folder lowercase: userprofile
| Unable to load profile in django | I am trying to add additional fields to the default User model. I had a look around the internet and done something like this:
Made a new model named UserProfile with the following in /UserProfile/models.py:
from django.db import models
from django.contrib.auth.models import User
class UserProfile(models.Model):
# This is the only required field
user = models.ForeignKey(User, unique=True)
# The rest is completely up to you...
favorite_band = models.CharField(max_length=100, blank=True)
favorite_cheese = models.CharField(max_length=100, blank=True)
lucky_number = models.IntegerField()
And added:
AUTH_PROFILE_MODULE = "newSite.userprofile"
To the settings, I also added "UserProfile" to the INSTALLED_APPS as to run sqlall.
The only problem is when I try the following in the shell:
>>> from django.contrib.auth.models import User
>>> user = User.objects.get(username = "user01")
>>> user.get_profile()
I get the following error:
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "C:\Python27\lib\site-packages\django\contrib\auth\models.py", line 367,in get_profile
raise SiteProfileNotAvailable('Unable to load the profile '
SiteProfileNotAvailable: Unable to load the profile model, check AUTH_PROFILE_MODULE in your project settings
Any help to solve this problem is appreciated!
| [
"If you really did create an app caled UserProfile and put the models.py there, then you should put\nAUTH_PROFILE_MODULE = \"userprofile.userprofile\"\n\ninto your settings.py file instead.\nYou should make your UserProfile folder lowercase: userprofile\n"
] | [
4
] | [] | [] | [
"django",
"python"
] | stackoverflow_0003756449_django_python.txt |
Q:
Timing/Recording input() in Python 3.1
I am a beginner at using Python,
I am trying to request input from the user via stdin as a string, but record the time it takes for the user to enter the input, so that it may be played back later.
For example:
"It could take me 10 seconds to type this sentence"
and then if I played that sentence back it would take the same amount of time to redisplay it...
Any basic ideas on which modules to use for timing / input? For output, I am just going to store all the recorded values and times in a dictionary object and read from them. (Seems to be the best way...)
Any guidance or help would be appreciated. I am not a beginner programmer, but just very new to Python, so don't feel like you have to write anything out for me.
Thanks!
A:
The input built-in function is fine for the input itself, and standard Python library module time probably the best way to measure time for your purposes. A simple function you can write easily puts them together:
import time
def timed_input(prompt):
start = time.time()
s = input(prompt)
return s, time.time() - start
This function requires a prompt string as the only argument and returns a tuple with two items: the string the user typed, then a floating-point number with the seconds (and fraction thereof) the user took to type (plus some miniscule overhead for the time the system took to show the user the prompt, but that's really a tiny fraction of a second).
So, you call it as, e.g.:
s, thetime = timed_input('Type now: ')
then you do whatever you want with string s and float thetime (it's not clear to me how you plan to structure the dictionary you want to store them in, but that's a completely different question than the one I've been answering at length, of course!-).
| Timing/Recording input() in Python 3.1 | I am a beginner at using Python,
I am trying to request input from the user via stdin as a string, but record the time it takes for the user to enter the input, so that it may be played back later.
For example:
"It could take me 10 seconds to type this sentence"
and then if I played that sentence back it would take the same amount of time to redisplay it...
Any basic ideas on which modules to use for timing / input? For output, I am just going to store all the recorded values and times in a dictionary object and read from them. (Seems to be the best way...)
Any guidance or help would be appreciated. I am not a beginner programmer, but just very new to Python, so don't feel like you have to write anything out for me.
Thanks!
| [
"The input built-in function is fine for the input itself, and standard Python library module time probably the best way to measure time for your purposes. A simple function you can write easily puts them together:\nimport time\n\ndef timed_input(prompt):\n start = time.time()\n s = input(prompt)\n return... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0003756278_python.txt |
Q:
Implementing Server Push
Read about Server push here.
I want to push data to client from my web application in real time.
I was looking at TCP sockets as one of the options.
For HTTP I found a variety of frameworks for Java, PHP, Python and others over here.
However I don't know whether any of these support Push.
What options and frameworks would you
suggest for implementing Server push?
What language would you advocate for implementing the same and why?
A:
How about Orbited, it's very good and being used by Echowaves
A:
I'm using Orbited right now, it's great!
If you are doing chat or subscription type stuff use stompservice and orbited.
If you are doing 1 to 1 client mapping use TCPSocket.
I can give you some code examples if you want.
A:
Comet is the protocol you want. What Comet implementation is best, is a harder call.
If you're OK with Java (or, I guess, Jython), or .NET (where IronPython's a possibility), I suspect (not having extensively tried them all!-) that stream hub must be a major contender. It'a typical "freemium" product -- you can get a free ("as in free beer";-) version, or you can try the pricey Web Edition, or the even-pricier Enterprise Edition; feature comparison is here (e.g., free edition: no https, no more than 10 concurrent users, no .NET).
A:
Ok, I'm using ASP.NET with PokeIn comet ajax library on my project. Also, I tried Atmosphere under JAVA.. My last choice was PokeIn.. Because, only server push support is not solving the problems. You will need some kind of client to server object serialization and object life time management. PokeIn covered all these needs for me.
A:
What about Ajax Push Engine?
A:
I'm personally biased, but I like WebSync, for IIS/.NET. It integrates with IIS, so no other server software necessary, just a dll to add to your project.
A:
I believe xmpp implementation is one which is being use by a lot of big companies but the common thing is to use a comet server as well.
a lot of implementation in python for thoses you can google around.
A:
Have you tried StreamHub Push Server?
| Implementing Server Push | Read about Server push here.
I want to push data to client from my web application in real time.
I was looking at TCP sockets as one of the options.
For HTTP I found a variety of frameworks for Java, PHP, Python and others over here.
However I don't know whether any of these support Push.
What options and frameworks would you
suggest for implementing Server push?
What language would you advocate for implementing the same and why?
| [
"How about Orbited, it's very good and being used by Echowaves\n",
"I'm using Orbited right now, it's great!\nIf you are doing chat or subscription type stuff use stompservice and orbited.\nIf you are doing 1 to 1 client mapping use TCPSocket.\nI can give you some code examples if you want.\n",
"Comet is the pr... | [
3,
3,
3,
3,
2,
2,
1,
0
] | [] | [] | [
"java",
"php",
"python",
"ruby",
"server_push"
] | stackoverflow_0001425048_java_php_python_ruby_server_push.txt |
Q:
Python multiprocessing : progress report from processes
I have some tasks in an application that are CPU bound and I want to use the multiprocessing module to use the multi-cores processors.
I take a big task (a video file analysis) and I split it into several smaller tasks which are put in a queue and done by worker processes.
What I want to know is how to report progress to the main process from these worker processes. For example I need them to send "I am at 1000ms of my analysis of file 1". What is the best way to do such progress reports ?
A:
I would recommend a multiprocessing.Queue: nothing easier than for the worker processes to post their updates (presumably as tuples with the various aspect of their progress updates) there, while the main process just wait for such messages and when they come updates the GUI (or textual UI;-) to keep the user appraised of progress.
| Python multiprocessing : progress report from processes | I have some tasks in an application that are CPU bound and I want to use the multiprocessing module to use the multi-cores processors.
I take a big task (a video file analysis) and I split it into several smaller tasks which are put in a queue and done by worker processes.
What I want to know is how to report progress to the main process from these worker processes. For example I need them to send "I am at 1000ms of my analysis of file 1". What is the best way to do such progress reports ?
| [
"I would recommend a multiprocessing.Queue: nothing easier than for the worker processes to post their updates (presumably as tuples with the various aspect of their progress updates) there, while the main process just wait for such messages and when they come updates the GUI (or textual UI;-) to keep the user appr... | [
14
] | [] | [] | [
"multiprocessing",
"python"
] | stackoverflow_0003756533_multiprocessing_python.txt |
Q:
Deep copy of a derived python object
I have an object in python that is derived from QtGui.QGraphicsPixmapItem with a few basic attributes and methods. After calling deepcopy on a reference to this object, I get an error saying that underlying C/C++ object has been deleted when I try to use the copy. I had received this error before, and it occured when I didn't call the base class' constructor in __init__ so I assume this error is because the QtGui.QGraphicsPixmapItem is not being copied.
How do I go about specifying this? All I know is that there is a __deepcopy__ method for this purpose.
A:
QGraphicsPixmapItem is not copyable. It inherits QGraphicsItem which is declared using the Q_DISABLE_COPY macro which is the same mechanism used for QObjects to disable copying. The documentation explains it a bit better.
| Deep copy of a derived python object | I have an object in python that is derived from QtGui.QGraphicsPixmapItem with a few basic attributes and methods. After calling deepcopy on a reference to this object, I get an error saying that underlying C/C++ object has been deleted when I try to use the copy. I had received this error before, and it occured when I didn't call the base class' constructor in __init__ so I assume this error is because the QtGui.QGraphicsPixmapItem is not being copied.
How do I go about specifying this? All I know is that there is a __deepcopy__ method for this purpose.
| [
"QGraphicsPixmapItem is not copyable. It inherits QGraphicsItem which is declared using the Q_DISABLE_COPY macro which is the same mechanism used for QObjects to disable copying. The documentation explains it a bit better.\n"
] | [
4
] | [] | [] | [
"deep_copy",
"derived_class",
"object",
"pyqt",
"python"
] | stackoverflow_0003705994_deep_copy_derived_class_object_pyqt_python.txt |
Q:
python regex retrieve only one group
I have juste a little experience with the regex, and now I have a little problem.
I must retrieve the strings between the .
So here is a sample :
Categories: <a href="/car/2/page1.html">2</a>, <a href="/car/nissan/">nissan</a>,<a href="/car/all/page1.html">all</a>
And this is my little regex:
re.findall("""<a href=".*">.*</a>""",string)
Well, it works , but I just want the strings between the , not the href,
so how could I do this ?
thanks.
A:
Use parentheses to form a capturing group:
'<a href=".*">(.*)</a>'
You also probably want to use a non-greedy quantifier to avoid matching far more than you intended.
'<a href=".*?">(.*?)</a>'
Result:
['2', 'nissan', 'all']
Or even better, consider using an HTML parser, such as BeautifulSoup.
A:
Regex is never a good idea for parsing HTML. There are too many edge cases that make crafting a robust regular expression difficult. Consider the following perfectly browser-viewable links:
< a href="/car/all/page1.html">all</a>
<a href="/car/all/page1.html">all</a>
<a href= "/car/all/page1.html">all</a>
<a id="foo" href="/car/all/page1.html">all</a>
<a
href="/car/all/page1.html">all</a>
All of which will not be matched by the given regular expression. I highly recommend an HTML parser, such as Beautiful Soup or lxml. Here's an lxml example:
from lxml import etree
html = """
Categories: <a href="/car/2/page1.html">2</a>, <a href="/car/nissan/">nissan</a>,<a href="/car/all/page1.html">all</a>
"""
doc = etree.HTML(html)
result = doc.xpath('//a[@href]/text()')
Result:
['2', 'nissan', 'all']
no matter if the HTML is different or even somewhat malformed.
| python regex retrieve only one group | I have juste a little experience with the regex, and now I have a little problem.
I must retrieve the strings between the .
So here is a sample :
Categories: <a href="/car/2/page1.html">2</a>, <a href="/car/nissan/">nissan</a>,<a href="/car/all/page1.html">all</a>
And this is my little regex:
re.findall("""<a href=".*">.*</a>""",string)
Well, it works , but I just want the strings between the , not the href,
so how could I do this ?
thanks.
| [
"Use parentheses to form a capturing group:\n'<a href=\".*\">(.*)</a>'\n\nYou also probably want to use a non-greedy quantifier to avoid matching far more than you intended.\n'<a href=\".*?\">(.*?)</a>'\n\nResult:\n['2', 'nissan', 'all']\n\nOr even better, consider using an HTML parser, such as BeautifulSoup.\n",
... | [
2,
1
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0003756429_python_regex.txt |
Q:
Google app engine key value error
I am writing a google app engine app and I have this key value error upon requests coming in
from the backtrace I just access and cause the key error
self.request.headers
entire code snippet is here, I just forward the headers unmodified
response = fetch( "%s%s?%s" % (
self.getApiServer() ,
self.request.path.replace("/twitter/", ""),
self.request.query_string
),
self.request.body,
method,
self.request.headers,
)
and get method handling the request calling proxy()
# handle http get
def get(self, *args):
parameters = self.convertParameters(self.request.query_string)
# self.prepareHeader("GET", parameters)
self.request.query_string = "&".join("%s=%s" % (quote(key) , quote(value)) for key, value in parameters.items())
self.proxy(GET, *args)
def convertParameters(self, source):
parameters = {}
for pairs in source.split("&"):
item = pairs.split("=")
if len(item) == 2:
parameters[item[0]] = unquote(item[1])
return parameters
the error back trace:
'CONTENT_TYPE'
Traceback (most recent call last):
File "/base/python_runtime/python_lib/versions/1/google/appengine/ext/webapp/__init__.py", line 513, in __call__
handler.post(*groups)
File "/base/data/home/apps/waytosing/1.342850593213842824/com/blogspot/zizon/twitter/RestApiProxy.py", line 67, in post
self.proxy(POST, *args)
File "/base/data/home/apps/waytosing/1.342850593213842824/com/blogspot/zizon/twitter/RestApiProxy.py", line 47, in proxy
self.request.headers,
File "/base/python_runtime/python_lib/versions/1/google/appengine/api/urlfetch.py", line 240, in fetch
allow_truncated, follow_redirects)
File "/base/python_runtime/python_lib/versions/1/google/appengine/api/urlfetch.py", line 280, in make_fetch_call
for key, value in headers.iteritems():
File "/base/python_runtime/python_dist/lib/python2.5/UserDict.py", line 106, in iteritems
yield (k, self[k])
File "/base/python_runtime/python_lib/versions/1/webob/datastruct.py", line 40, in __getitem__
return self.environ[self._trans_name(item)]
KeyError: 'CONTENT_TYPE'
Any idea why it happens or is this a known bug?
A:
This looks weird. The docs mention that response "Headers objects do not raise an error when you try to get or delete a key that isn't in the wrapped header list. Getting a nonexistent header just returns None". It's not clear from the request documentation if request.headers are also objects of this class, but even they were regular dictionaries, iteritems seems to be misbehaving. So this might be a bug.
It might be worth inspecting self.request.headers, before calling fetch, and see 1) its actual type, 2) its keys, and 3) if trying to get self.request.headers['CONTENT_TYPE'] raises an error then.
But, if you simply want to solve your problem and move forward, you can try to bypass it like:
if 'CONTENT_TYPE' not in self.request.headers:
self.request.headers['CONTENT_TYPE'] = None
(I'm suggesting setting it to None, because that's what a response Header object should return on non-existing keys)
A:
Here's my observation about this problem:
When the content-type is application/x-www-form-urlencoded and POST data is empty (e.g. jquery.ajax GET, twitter's favorite and retweet API...), the content-type is dropped by Google appengine.
You can add:
self.request.headers.update({'content-type':'application/x-www-form-urlencoded'})
before urlfetch.
A:
Edit: indeed, looking at the error more carefully, it doesn't seem to be related to convertParameters, as the OP points out in the comments. I'm retiring this answer.
I'm not entirely sure what you mean by "just forward the headers unmodified", but have you taken a look at self.request.query_string before and after you call convertParameters? More to the point, you're leaving out any (valid) GET parameters of the form "key=" (that is, keys with empty values).
Maybe your original query_string had a value like "CONTENT_TYPE=", and your convertParameters is stripping it out.
A:
Known issue http://code.google.com/p/googleappengine/issues/detail?id=3427 and potential workarounds here http://code.google.com/p/googleappengine/issues/detail?id=2040
| Google app engine key value error | I am writing a google app engine app and I have this key value error upon requests coming in
from the backtrace I just access and cause the key error
self.request.headers
entire code snippet is here, I just forward the headers unmodified
response = fetch( "%s%s?%s" % (
self.getApiServer() ,
self.request.path.replace("/twitter/", ""),
self.request.query_string
),
self.request.body,
method,
self.request.headers,
)
and get method handling the request calling proxy()
# handle http get
def get(self, *args):
parameters = self.convertParameters(self.request.query_string)
# self.prepareHeader("GET", parameters)
self.request.query_string = "&".join("%s=%s" % (quote(key) , quote(value)) for key, value in parameters.items())
self.proxy(GET, *args)
def convertParameters(self, source):
parameters = {}
for pairs in source.split("&"):
item = pairs.split("=")
if len(item) == 2:
parameters[item[0]] = unquote(item[1])
return parameters
the error back trace:
'CONTENT_TYPE'
Traceback (most recent call last):
File "/base/python_runtime/python_lib/versions/1/google/appengine/ext/webapp/__init__.py", line 513, in __call__
handler.post(*groups)
File "/base/data/home/apps/waytosing/1.342850593213842824/com/blogspot/zizon/twitter/RestApiProxy.py", line 67, in post
self.proxy(POST, *args)
File "/base/data/home/apps/waytosing/1.342850593213842824/com/blogspot/zizon/twitter/RestApiProxy.py", line 47, in proxy
self.request.headers,
File "/base/python_runtime/python_lib/versions/1/google/appengine/api/urlfetch.py", line 240, in fetch
allow_truncated, follow_redirects)
File "/base/python_runtime/python_lib/versions/1/google/appengine/api/urlfetch.py", line 280, in make_fetch_call
for key, value in headers.iteritems():
File "/base/python_runtime/python_dist/lib/python2.5/UserDict.py", line 106, in iteritems
yield (k, self[k])
File "/base/python_runtime/python_lib/versions/1/webob/datastruct.py", line 40, in __getitem__
return self.environ[self._trans_name(item)]
KeyError: 'CONTENT_TYPE'
Any idea why it happens or is this a known bug?
| [
"This looks weird. The docs mention that response \"Headers objects do not raise an error when you try to get or delete a key that isn't in the wrapped header list. Getting a nonexistent header just returns None\". It's not clear from the request documentation if request.headers are also objects of this class, but ... | [
2,
1,
0,
0
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0003094418_google_app_engine_python.txt |
Q:
How to create a rollback button in django with MySQLdb?
I want to create a rollback button in my django project using MySQLdb. I have tried to use commit() and rollback() with InnoDB as database engine, rollback() seems not work because the database was updated even though rollback() was put after commit(). Here is some related lines in python code:
def update(request):
if 'weight' in request.GET and request.GET['weight']:
weight = request.GET['weight']
else:
return HttpResponseRedirect('/clamplift/')
if 'realtag' in request.GET and request.GET['realtag']:
realtag = request.GET['realtag']
else:
return HttpResponseRedirect('/clamplift/')
conn = MySQLdb.Connect(host="localhost", user="root", passwd="", db="scale")
cur = conn.cursor()
cur.execute("UPDATE `scale`.`scale_stock` SET `current_weight` = %s WHERE `scale_stock`.`paper_roll_id` = %s", (weight,realtag))
conn.commit()
conn.rollback() # I test rollback() function here.
cur.close()
conn.close()
return HttpResponseRedirect('/clamplift/')
Actually I want one button for update data to database and another button to rollback like providing undo function.
Please give me any idea. Thank you very much.
A:
I have no experience with MySQLdb directly, but most of the time, the rollback method is only good during a transaction. That is, if a transaction is still open, then rollback will undo everything that has happened since the start of the transaction. So when you call commit, you are ending the transaction and can no longer meaningfully call rollback.
In response to question in comments:
Add a datetime field to the model to track revisions. Create another model with the same fields as the original model and a foreign key into to original model's table. When an update occurs to the original model, copy the old values into the new table, set the datetime to NOW and set the foreign key in the revisions table to point at the row being edited before performing the update. You can then provide a list of previous states to revert to by selecting all of the revisions for the row in question and letting the user select based on datetime. Of course you can also provide the user that made the edit as well or other specific information that you think will be useful to the users of your app.
| How to create a rollback button in django with MySQLdb? | I want to create a rollback button in my django project using MySQLdb. I have tried to use commit() and rollback() with InnoDB as database engine, rollback() seems not work because the database was updated even though rollback() was put after commit(). Here is some related lines in python code:
def update(request):
if 'weight' in request.GET and request.GET['weight']:
weight = request.GET['weight']
else:
return HttpResponseRedirect('/clamplift/')
if 'realtag' in request.GET and request.GET['realtag']:
realtag = request.GET['realtag']
else:
return HttpResponseRedirect('/clamplift/')
conn = MySQLdb.Connect(host="localhost", user="root", passwd="", db="scale")
cur = conn.cursor()
cur.execute("UPDATE `scale`.`scale_stock` SET `current_weight` = %s WHERE `scale_stock`.`paper_roll_id` = %s", (weight,realtag))
conn.commit()
conn.rollback() # I test rollback() function here.
cur.close()
conn.close()
return HttpResponseRedirect('/clamplift/')
Actually I want one button for update data to database and another button to rollback like providing undo function.
Please give me any idea. Thank you very much.
| [
"I have no experience with MySQLdb directly, but most of the time, the rollback method is only good during a transaction. That is, if a transaction is still open, then rollback will undo everything that has happened since the start of the transaction. So when you call commit, you are ending the transaction and can ... | [
1
] | [] | [] | [
"django",
"mysql",
"python"
] | stackoverflow_0003757266_django_mysql_python.txt |
Q:
running PIL on 64bit
Is there any way of running PIL(Python Imaging Library) on a 64bit OS?
it is windows 7 64bit
A:
PIL-1.1.7.win-amd64-py2.x installers are available at http://www.lfd.uci.edu/~gohlke/pythonlibs/#pil
| running PIL on 64bit | Is there any way of running PIL(Python Imaging Library) on a 64bit OS?
it is windows 7 64bit
| [
"PIL-1.1.7.win-amd64-py2.x installers are available at http://www.lfd.uci.edu/~gohlke/pythonlibs/#pil\n"
] | [
23
] | [] | [] | [
"64_bit",
"python",
"python_imaging_library"
] | stackoverflow_0003754574_64_bit_python_python_imaging_library.txt |
Q:
findString program python
I have an assignment said that to create a findString function that accept 2 string which are 'target' and 'query', and that returns
a
list
of
all
indices
in
target
where
query
appears.
If
target
does
not
contain
query,
return
an
empty
list.
For example:
findString(‘attaggtttattgg’,’gg’)
return:
[4,12]
I dont know how to start off with this function writing at all. Please help me everyone. Thank you so much!!!
A:
since an answer has already been given:
def find_matches(strng, substrng):
substrg_len = len(substr)
return [i for i in range(len(strg) + 1 - substrg_len)
if strg[i:i+substrg_len] == substrg]
A:
def find_string(search, needle):
start = -1
results = []
while start + 1< len(search):
start = search.find(needle, start +1)
if start == -1:
break
results.append(start )
return results
A:
Here are a couple of hints to get you started.
target.find(query) will return the index of query in target. If query is not found, it will return -1.
A string can be sliced. target[pos:] will give you a substring of target starting from pos.
A:
This may require some error handling:
def find_allPatterns(strVal, strSub):
listPos = []
strTemp = strVal
while True:
try:
posInStr = strTemp.index(strSub)
except ValueError:
posInStr = None
if posInStr:
listPos.append(posInStr)
subpos = posInStr + len(strSub)
strTemp = strTemp[subpos:]
else:
break
return listPos
print find_allPatterns('attaggtttattgg', 'gg')
Output:
[4, 6]
| findString program python | I have an assignment said that to create a findString function that accept 2 string which are 'target' and 'query', and that returns
a
list
of
all
indices
in
target
where
query
appears.
If
target
does
not
contain
query,
return
an
empty
list.
For example:
findString(‘attaggtttattgg’,’gg’)
return:
[4,12]
I dont know how to start off with this function writing at all. Please help me everyone. Thank you so much!!!
| [
"since an answer has already been given:\ndef find_matches(strng, substrng):\n substrg_len = len(substr)\n return [i for i in range(len(strg) + 1 - substrg_len) \n if strg[i:i+substrg_len] == substrg]\n\n",
"\ndef find_string(search, needle):\n start = -1\n results = []\nwhile start + 1... | [
1,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0003757326_python.txt |
Q:
Python programming
My assignment ask to make a function call readFasta that
accepts
one
argument:
the
name
of
a
fasta
format
file
(fn)
containing
one
or
more
sequences.
The
function
should
read
the
file
and
return
a
dictionary
where
the
keys
are
the
fasta
headers
and
the
values
are
the
corresponding
sequences
from
file
fn
converted
to
strings.
Make
sure
that
you
don’t
include
any
new
lines
or
other
white space
characters
in
the
sequences
in
the
dictionary.
For ex, if afile.fa looks like:
>one
atctac
>two
gggaccttgg
>three
gacattac
then the a.readFasta(f) returns:
[‘one’ : ‘atctac’,
‘two’ : ‘gggaccttgg’,
‘three’: ‘gacattac’]
If have tried to write some codes but as I am totally newbie in programming, it didnt work out very much for me. Can everyone please help me. Thank you so much. Here are my codes:
import gzip
def readFasta(fn):
if fn.endswith('.gz'):
fh = gzip.gzipfile(fn)
else:
fh = open(fn,'r')
d = {}
while 1:
line = fh.readline()
if not line:
fh.close()
break
vals = line.rstrip().split('\t')
number = vals[0]
sequence = vals[1]
if d.has_key(number):
lst = d[number]
if gene not in lst:
# this test may not be necessary
lst.append(sequence)
else:
d[number] = [sequence]
return d
Here is what I got in my afile.txt
one atctac
two gggaccttgg
three gacattac
A:
your post is slightly confusing. I assume that you want it to return a dict. in that case, you would write it as {'one': 'actg', 'two': 'aaccttgg' }. if you correctly presented the file format, then this function should do the trick.
import gzip
def read_fasta(filename):
with gzip.open(filename) as f:
return dict(line.split() for line in f)
| Python programming | My assignment ask to make a function call readFasta that
accepts
one
argument:
the
name
of
a
fasta
format
file
(fn)
containing
one
or
more
sequences.
The
function
should
read
the
file
and
return
a
dictionary
where
the
keys
are
the
fasta
headers
and
the
values
are
the
corresponding
sequences
from
file
fn
converted
to
strings.
Make
sure
that
you
don’t
include
any
new
lines
or
other
white space
characters
in
the
sequences
in
the
dictionary.
For ex, if afile.fa looks like:
>one
atctac
>two
gggaccttgg
>three
gacattac
then the a.readFasta(f) returns:
[‘one’ : ‘atctac’,
‘two’ : ‘gggaccttgg’,
‘three’: ‘gacattac’]
If have tried to write some codes but as I am totally newbie in programming, it didnt work out very much for me. Can everyone please help me. Thank you so much. Here are my codes:
import gzip
def readFasta(fn):
if fn.endswith('.gz'):
fh = gzip.gzipfile(fn)
else:
fh = open(fn,'r')
d = {}
while 1:
line = fh.readline()
if not line:
fh.close()
break
vals = line.rstrip().split('\t')
number = vals[0]
sequence = vals[1]
if d.has_key(number):
lst = d[number]
if gene not in lst:
# this test may not be necessary
lst.append(sequence)
else:
d[number] = [sequence]
return d
Here is what I got in my afile.txt
one atctac
two gggaccttgg
three gacattac
| [
"your post is slightly confusing. I assume that you want it to return a dict. in that case, you would write it as {'one': 'actg', 'two': 'aaccttgg' }. if you correctly presented the file format, then this function should do the trick.\nimport gzip\n\ndef read_fasta(filename):\n with gzip.open(filename) as f:\n ... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0003757480_python.txt |
Q:
How to replace digits in string?
Ok say I have a string in python:
str="martin added 1 new photo to the <a href=''>martins photos</a> album."
the string contains a lot more css/html in real world use
What is the fastest way to change the 1 ('1 new photo') to say '2 new photos'. of course later the '1' may say '12'.
Note, I don't know what the number is, so doing a replace is not acceptable.
I also need to change 'photo' to 'photos' but I can just do a .replace(...).
Unless there is a neater, easier solution to modify both?
A:
Update
Never mind. From the comments it is evident that the OP's requirement is more complicated than it appears in the question. I don't think it can be solved by my answer.
Original Answer
You can convert the string to a template and store it. Use placeholders for the variables.
template = """%(user)s added %(count)s new %(l_object)s to the
<a href='%(url)s'>%(text)s</a> album."""
options = dict(user = "Martin", count = 1, l_object = 'photo',
url = url, text = "Martin's album")
print template % options
This expects the object of the sentence to be pluralized externally. If you want this logic (or more complex conditions) in your template(s) you should look at a templating engine such as Jinja or Cheetah.
A:
since you're not parsing html, just use an regular expression
import re
exp = "{0} added ([0-9]*) new photo".format(name)
number = int(re.findall(exp, strng)[0])
This assumes that you will always pass it a string with the number in it. If not, you'll get an IndexError.
I would store the number and the format string though, in addition to the formatted string. when the number changes, remake the format string and replace your stored copy of it. This will be much mo'bettah' then trying to parse a string to get the count.
In response to your question about the html mattering, I don't think so. You are not trying to extract information that the html is encoding so you are not parsing html with regular expressions. This is just a string as far as that concern goes.
A:
It sounds like this is what you want (although why is another question :^)
import re
def add_photos(s,n):
def helper(m):
num = int(m.group(1)) + n
plural = '' if num == 1 else 's'
return 'added %d new photo%s' % (num,plural)
return re.sub(r'added (\d+) new photo(s?)',helper,s)
s = "martin added 0 new photos to the <a href=''>martins photos</a> album."
s = add_photos(s,1)
print s
s = add_photos(s,5)
print s
s = add_photos(s,7)
print s
Output
martin added 1 new photo to the <a href=''>martins photos</a> album.
martin added 6 new photos to the <a href=''>martins photos</a> album.
martin added 13 new photos to the <a href=''>martins photos</a> album.
| How to replace digits in string? | Ok say I have a string in python:
str="martin added 1 new photo to the <a href=''>martins photos</a> album."
the string contains a lot more css/html in real world use
What is the fastest way to change the 1 ('1 new photo') to say '2 new photos'. of course later the '1' may say '12'.
Note, I don't know what the number is, so doing a replace is not acceptable.
I also need to change 'photo' to 'photos' but I can just do a .replace(...).
Unless there is a neater, easier solution to modify both?
| [
"Update\nNever mind. From the comments it is evident that the OP's requirement is more complicated than it appears in the question. I don't think it can be solved by my answer.\nOriginal Answer\nYou can convert the string to a template and store it. Use placeholders for the variables.\ntemplate = \"\"\"%(user)s add... | [
3,
2,
2
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0003757738_python_regex.txt |
Q:
How would I go about reading bittorrent pieces?
I'm currently developing a torrent metainfo management library for Ruby.
I'm having trouble reading the pieces from the files. I just don't understand how I'm supposed to go about it. I know I'm supposed to SHA1 digest piece length bytes of a file once (or read piece length bytes multiple times, or what?)
I'm counting on your help.
Pseudo / Python / Ruby / PHP code preferred.
Thanks in advance.
A:
C#
// Open the file
using (var file = File.Open(...))
{
// Move to the relevant place in the file where the piece begins
file.Seek(piece * pieceLength, SeekOrigin.Begin);
// Attempt to read up to pieceLength bytes from the file into a buffer
byte[] buffer = new byte[pieceLength];
int totalRead = 0;
while (totalRead < pieceLength)
{
var read = stream.Read(buffer, totalRead, pieceLength-totalRead);
if (read == 0)
{
// the piece is smaller than the pieceLength,
// because it’s the last in the file
Array.Resize(ref buffer, totalRead);
break;
}
totalRead += read;
}
// If you want the raw data for the piece:
return buffer;
// If you want the SHA1 hashsum:
return SHA1.Create().ComputeHash(buffer);
}
| How would I go about reading bittorrent pieces? | I'm currently developing a torrent metainfo management library for Ruby.
I'm having trouble reading the pieces from the files. I just don't understand how I'm supposed to go about it. I know I'm supposed to SHA1 digest piece length bytes of a file once (or read piece length bytes multiple times, or what?)
I'm counting on your help.
Pseudo / Python / Ruby / PHP code preferred.
Thanks in advance.
| [
"C#\n// Open the file\nusing (var file = File.Open(...))\n{\n // Move to the relevant place in the file where the piece begins\n file.Seek(piece * pieceLength, SeekOrigin.Begin);\n\n // Attempt to read up to pieceLength bytes from the file into a buffer\n byte[] buffer = new byte[pieceLength];\n int ... | [
1
] | [
"Please taker a look at this distribution here:\nhttp://prdownload.berlios.de/torrentparse/TorrentParse.GTK.0.21.zip\nWritten in PHP, it contains an Encoder and Decoder and the in's and out I believe!\n"
] | [
-1
] | [
"c#",
"php",
"pseudocode",
"python",
"ruby"
] | stackoverflow_0003757965_c#_php_pseudocode_python_ruby.txt |
Q:
How to specify argument type in a dynamically typed language, i.e. Python?
Is there any such equivalent of Java
String myMethod (MyClass argument) {...}
in Python?
Thank you, Tomas
A:
No. (And more stuff to round this up to 15 characters...)
A:
No, there is not.
In fact, checking types is considered "un-Pythonic", because an object of any type that looks enough like the expected type should be treated equally.
A:
Python 3.x has function annotations where you can declare argument and return types:
def myMethod(argument: MyClass) -> str:
...
But currently Python does nothing with them, they serve as documentation only.
A:
I just want to say that I'm in full agreement that type checking is evil. But python is also incredibly flexible and I'm in the mood to be evil. This code will take effect at runtime and not compile time. You could do something similar for return type. Something like this could be useful for debugging and, because it's a decorator, it's easy enough to remove.
For it to be useful for debugging you would have to have a situation where two types had all the same attributes that were getting accessed but with different semantics. So that's a pretty limited case. Other than that, you're about to get a typerror anyways when this code runs. The good news is that this is almost never a problem. I really don't know why people from statically typed languages make such a big deal over it.
def types(*args, **kwargs):
arg_types = args
kwarg_types = kwargs
def decorator(f):
def func(*args, **kwargs):
for arg, arg_type in zip(args, arg_types):
if not isinstance(arg, arg_type):
raise TypeError("Wrong type suckah")
for kw, arg in kwargs.items():
if not isinstance(arg, kwarg_types[kw]):
raise TypeError("this is a bad error message")
return f(*args, **kwargs)
return func
return decorator
@types(int, str, bool, flag=bool)
def demo(i, strng, flag=False):
print i, strng, flag
demo(1, "foo", True)
try:
demo("foo", "bar", flag="foobar")
except TypeError:
print "busted on posargs"
try:
demo(1, "foo", flag=2)
except TypeError:
print "busted on keyargs"
try:
demo(1, "foo", 3)
except TypeError:
print "no use sneaking it through"
A:
No.
In Python, it's the program's
responsibility to use built-in
functions like isinstance() and
issubclass() to test variable types
and correct usage. Python tries to
stay out of your way while giving you
all you need to implement strong type
checking.
from Why is Python a dynamic language and also a strongly typed language. Also
In a dynamically typed language, a
variable is simply a value bound to a
name; the value has a type -- like
"integer" or "string" or "list" -- but
the variable itself doesn't. You could
have a variable which, right now,
holds a number, and later assign a
string to it if you need it to change.
Further, isinstance() and issubclass() can be used to do type-checking. If you want to make sure that argument is of MyClass type, you can have a check inside the function. You can even type-cast the value of the argument (if you have a constructor accepting such value) and assign it to my_object.
| How to specify argument type in a dynamically typed language, i.e. Python? | Is there any such equivalent of Java
String myMethod (MyClass argument) {...}
in Python?
Thank you, Tomas
| [
"No. (And more stuff to round this up to 15 characters...)\n",
"No, there is not.\nIn fact, checking types is considered \"un-Pythonic\", because an object of any type that looks enough like the expected type should be treated equally.\n",
"Python 3.x has function annotations where you can declare argument and ... | [
13,
12,
8,
4,
1
] | [] | [] | [
"dynamic",
"java",
"python",
"static"
] | stackoverflow_0003753364_dynamic_java_python_static.txt |
Q:
counting records of files on directory with python
I have wxpython application that run over a list of files on some directory and proccess the files line by line
I need to build a progress bar that show the status how records already done with wx.gauge control
I need to count the number of the records before i use the wx.guage in order to build the progress bar ,
is this the way to do this and if yes what is the best method to count the number of lines of all the files on some directory with pyhon ?
A:
I think you could do 2 progress bars, one for files, and second for line in just read file. This will be similar to copy progress in TotalCommander.
If you want one progress bar you could just count file sizes using os.path.getsize(path) and then show how many bytes have you processed/bytes total.
| counting records of files on directory with python | I have wxpython application that run over a list of files on some directory and proccess the files line by line
I need to build a progress bar that show the status how records already done with wx.gauge control
I need to count the number of the records before i use the wx.guage in order to build the progress bar ,
is this the way to do this and if yes what is the best method to count the number of lines of all the files on some directory with pyhon ?
| [
"I think you could do 2 progress bars, one for files, and second for line in just read file. This will be similar to copy progress in TotalCommander.\nIf you want one progress bar you could just count file sizes using os.path.getsize(path) and then show how many bytes have you processed/bytes total.\n"
] | [
1
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0003758468_python_wxpython.txt |
Q:
What languages would be a good replacement for Java?
I may be posting a premature question, and maybe I'm just freaking out for no reason, but the way Oracle is handling Java is not very promising. I am a nerd who fell in love with Java from the first sight, and use it all the time in my personal/freelance projects but now I am thinking of a replacement.
I am fluent in C#/VB.NET too but I am looking for something more like:
Open Source
Compiled
Cross-Platform
Object Oriented
Large standard library
Extensive documentation
Web development is a major plus
I was thinking about a compromise: Python/Django for web development (or PHP), and Qt for thick client development. Anyone with better thoughts?
A:
Not so long ago, I decided to explore away from the JVM. I set foot on python, and even though i'm nowhere near the expert/ guru level, I dont regret it. Didn't choose C# (considered it) because I consider it to be more of the same. I alredy know (and like a lot) C++, so python seemed like something new, which is what I was looking for.
It fullfils many of your requirements. Particularly, i'm decided not to learn PHP, so the web frameworks in python came in great.
Not to mention, Python has a large community (also see here), always eager to help and teach, which I consider to be very important.
Just my two cents.
A:
Might be worth loking at the other JVM languages - Clojure and Scala are the two I personally think are most promising.
Yes you are on the JVM, but you're pretty independent from Java the langauage and don't have to use any Sun/Oracle implementations if you don't want to.
Having said that - I think that you are worrying a little too much about Java, too many players (including Oracle!) have too much invested to let it go too far off course.
A:
Try Scala. It looks extremely elegant and promising. Being object oriented and sharing a lot with java in a very concise manner.
A:
Everything you said points to C#, except for the Open Source point.
To fix that, there's Mono.
A:
You could try D. My one-sentence description of why it's an awesome language is that its generic programming/compile-time introspection/template metaprogramming facilities are good enough to give you almost flexibility of a duck-typed language, while its execution speed and static type checking rival or exceed C++ and C#.
I think it meets your requirements quite well.
Open source: The frontend to the reference DMD implementation is open source (the back end isn't due to restrictions beyond the author's control). Work is underway to glue the reference frontend to open source backends such as LLVM (LDC) and GCC (GDC). In the case of D1 (the older version of the language) the LLVM port is fairly mature.
Compiled: D is meant to be compiled to native machine code, i.e. raw, inscrutable hexadecimal numbers.
Cross-platform: The reference DMD compiler supports x86 Windows, Linux, Mac OS X and FreeBSD. GDC and LDC will likely support a lot more CPU architectures.
Object oriented: D isn't a "pure" OO language in the Ruby sense of everything being an object, or in the Java sense of not supporting any other paradigm. It does, however, fully support Java-style OO as a subset of the language, along with procedural and functional style programming.
Large standard library: D1 has Tango, which qualifies. D2 has Phobos, which is not "large" yet by modern standards but is larger than C or C++'s standard lib. However, recently there has been a large interest in contributing and Andrei Alexandrescu (its main designer) has accepted several new contributors, including myself.
Extensive documentation: The standard library and language are reasonably well documented at the Digital Mars website. There's also Andrei Alexandrescu's book "The D Programming Language".
Web development: This is an admitted weakness. D doesn't (yet) have a good web framework, though its native unicode support and excellent generic programming support should make writing one relatively easy.
A:
I too would like another Java-like technology to come along. Lately I've been doing Flex/Actionscript. While I really enjoy it, Actionscript technology seriously lacks the elegance that Java has. Adobe can write some good cross platform APIs, but they just don't have the head capital to build elegant languages and compilers. I've also tried Ruby, but the VM for Ruby is really bad. I've gone back to Java after my flirtation with other technologies and I think it's because the language is good enough, but the JVM is by far the best out there.
So do you want to stay with the JVM or do you really want to the leave the JVM altogether? Staying on the JVM there are lots of options: JRuby, Scala, Groovy, Javascript, Clojure are the big players. However, there are tons of great languages that can take advantage of the JVM's features.
Leaving the JVM there are still good options like python, ruby, and erlang. But you give up some of the nice features of the JVM like performance (big one), and the ability to drop down to a nice language like Java if you need speed. Those others mean using C or nothing at all.
I finally stopped worrying about Java's future. Sun did all it could to screw it up and it still turned out pretty darn good. I think Opensource has a lot more influence over Java's success than Oracle or Sun could ever have had.
A:
I can't post comments yet, so I'm posting an answer related to the Python discussion. Though Python isn't compiled to machine code, there is a Python-to-C compiler called Cython, which can compile nearly all valid Python -- closures are finally (!) in the latest development release. It's have a big impact on some parts of the Python commmunity, e.g., I was at Euroscipy recently, and over half the talks mentioned Cython.
A:
I personally don't like PHP, but it does meet all of your requirements. It doesn't officially support compilation but there is the Hip Hop project which compiles PHP to C code. Facebook is currently heading up this project.
That said, I highly discourage you from using it :)
A:
C# is the only thing that will meet your needs and not feel hopelessly archaic, or frustrate with limited library. For open source/non-windows, use mono. It's a good, mature implementation of most of what's important in the CLR.
Some things (WPF, WCF, etc) are "missing" from mono, but these aren't so much part of the platform as they are windows-specific proprietary toolkits. Some of them are being implemented slowly in mono, some aren't. Coming from java you won't miss them because you're looking for a platform and good standard libraries to build upon, not a gui toolkit or whiz-bang communication framework.
As far as a platform to build stuff with that's "like" java and offers similar levels of functionality, C# + CLR is the clearest option.
A:
Using also Cython you get the best of the two worlds , the ability to code in python , the ability to code in C and C++ and of course compile your code and the ability to use both python a c/c++ libraries out of the box. And if you dont like C++ syntax , cython syntax is python syntax and more.
link text
| What languages would be a good replacement for Java? | I may be posting a premature question, and maybe I'm just freaking out for no reason, but the way Oracle is handling Java is not very promising. I am a nerd who fell in love with Java from the first sight, and use it all the time in my personal/freelance projects but now I am thinking of a replacement.
I am fluent in C#/VB.NET too but I am looking for something more like:
Open Source
Compiled
Cross-Platform
Object Oriented
Large standard library
Extensive documentation
Web development is a major plus
I was thinking about a compromise: Python/Django for web development (or PHP), and Qt for thick client development. Anyone with better thoughts?
| [
"Not so long ago, I decided to explore away from the JVM. I set foot on python, and even though i'm nowhere near the expert/ guru level, I dont regret it. Didn't choose C# (considered it) because I consider it to be more of the same. I alredy know (and like a lot) C++, so python seemed like something new, which is ... | [
15,
6,
3,
2,
2,
1,
1,
0,
0,
0
] | [] | [] | [
"java",
"programming_languages",
"python",
"qt",
"replace"
] | stackoverflow_0003506252_java_programming_languages_python_qt_replace.txt |
Q:
Assign class methods from YAML file
In short,I've written an application that parses text files in specified formats from different email feeds. Currently, there are two formats allowed by users in order to correctly upload information. I've also included a simple YAML file that allows people with non-programming backgrounds (ie sysadmins) to define the basics parsing parameters such as delimiters for each different email feed.
As it turns out, users are going to require a lot more formats than the ones I've defined. As in entirely-different-parsing-algorithm format.
Since it would be difficult for someone not familiar with the source to constantly add/update parsing methods, my idea is to allow the admin to define custom methods in the YAML file like so:
parser: !!python/name:modules.custom.parser
That way the admin can define their own parsing method called, for example, modules.custom.parser without having to dig through source code.
Am I playing with fire allowing the admin to dynamically upload their own custom methods?
A:
I don't think the idea of having "executable config files" is a bad one, but I think having a mix of YAML and Python code could be confusing. Perhaps instead you could go the route of Xen, SCons, hellanzb, etc. and have your "config file" just be a Python script?
| Assign class methods from YAML file | In short,I've written an application that parses text files in specified formats from different email feeds. Currently, there are two formats allowed by users in order to correctly upload information. I've also included a simple YAML file that allows people with non-programming backgrounds (ie sysadmins) to define the basics parsing parameters such as delimiters for each different email feed.
As it turns out, users are going to require a lot more formats than the ones I've defined. As in entirely-different-parsing-algorithm format.
Since it would be difficult for someone not familiar with the source to constantly add/update parsing methods, my idea is to allow the admin to define custom methods in the YAML file like so:
parser: !!python/name:modules.custom.parser
That way the admin can define their own parsing method called, for example, modules.custom.parser without having to dig through source code.
Am I playing with fire allowing the admin to dynamically upload their own custom methods?
| [
"I don't think the idea of having \"executable config files\" is a bad one, but I think having a mix of YAML and Python code could be confusing. Perhaps instead you could go the route of Xen, SCons, hellanzb, etc. and have your \"config file\" just be a Python script?\n"
] | [
1
] | [] | [] | [
"class_design",
"python",
"yaml"
] | stackoverflow_0003755386_class_design_python_yaml.txt |
Q:
Problem when Serving static files in Django
I have my css file in
/var/www/media/static/style.css
and added
(r'^media/(?P<path>.*)$', 'django.views.static.serve',{'document_root': '/var/www/media/static'}),
to my urls but when I go to http://localhost:8000/media/style.css I get: "Page not found: /media/style.css" what is wrong?
A:
Have you updated your settings.MEDIA_ROOT (the filesystem path) and settings.MEDIA_URL (the URL for static assets) to reflect the setup of your project?
A:
Check the logging output to see what's actually been requested - I've found that to be particularly helpful in diagnosing these issues.
A:
The problem has to do with the actual choice of Path: '/media' was taken by admin I changed it to '/static' that works now.
| Problem when Serving static files in Django | I have my css file in
/var/www/media/static/style.css
and added
(r'^media/(?P<path>.*)$', 'django.views.static.serve',{'document_root': '/var/www/media/static'}),
to my urls but when I go to http://localhost:8000/media/style.css I get: "Page not found: /media/style.css" what is wrong?
| [
"Have you updated your settings.MEDIA_ROOT (the filesystem path) and settings.MEDIA_URL (the URL for static assets) to reflect the setup of your project?\n",
"Check the logging output to see what's actually been requested - I've found that to be particularly helpful in diagnosing these issues.\n",
"The problem ... | [
0,
0,
0
] | [] | [] | [
"django",
"python",
"static"
] | stackoverflow_0003746586_django_python_static.txt |
Q:
What encoding looks exactly like ASCII but has NULL bytes before each byte?
I have a string that looks and behaves as follows (Python code provided). WTF?! What encoding is it in?
s = u'\x00Q\x00u\x00i\x00c\x00k'
>>> print s
Quick
>>>
>>> s == 'Quick'
False
>>>
>>> import re
>>> re.search('Quick', s)
>>>
>>> import chardet
>>> chardet.detect(s)
/usr/lib/pymodules/python2.6/chardet/universaldetector.py:69: UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal
if aBuf[:3] == '\xEF\xBB\xBF':
/usr/lib/pymodules/python2.6/chardet/universaldetector.py:72: UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal
elif aBuf[:4] == '\xFF\xFE\x00\x00':
/usr/lib/pymodules/python2.6/chardet/universaldetector.py:75: UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal
elif aBuf[:4] == '\x00\x00\xFE\xFF':
/usr/lib/pymodules/python2.6/chardet/universaldetector.py:78: UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal
elif aBuf[:4] == '\xFE\xFF\x00\x00':
/usr/lib/pymodules/python2.6/chardet/universaldetector.py:81: UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal
elif aBuf[:4] == '\x00\x00\xFF\xFE':
/usr/lib/pymodules/python2.6/chardet/universaldetector.py:84: UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal
elif aBuf[:2] == '\xFF\xFE':
/usr/lib/pymodules/python2.6/chardet/universaldetector.py:87: UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal
elif aBuf[:2] == '\xFE\xFF':
{'confidence': 1.0, 'encoding': 'ascii'}
>>>
>>> chardet.detect(s)
{'confidence': 1.0, 'encoding': 'ascii'}
>>>
A:
UTF-16 big endian
A:
You have UTF-16BE without a BOM. As documented, chardet doesn't grok UTF-nnxE without a BOM.
>>> s = '\x00Q\x00u\x00i\x00c\x00k' #### Note: dropping the spurious `u` prefix
>>> s.decode('utf_16be')
u'Quick'
>>>
chardet is also not smart enough to raise a DontBeSilly exception if you feed it unicode :-)
| What encoding looks exactly like ASCII but has NULL bytes before each byte? | I have a string that looks and behaves as follows (Python code provided). WTF?! What encoding is it in?
s = u'\x00Q\x00u\x00i\x00c\x00k'
>>> print s
Quick
>>>
>>> s == 'Quick'
False
>>>
>>> import re
>>> re.search('Quick', s)
>>>
>>> import chardet
>>> chardet.detect(s)
/usr/lib/pymodules/python2.6/chardet/universaldetector.py:69: UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal
if aBuf[:3] == '\xEF\xBB\xBF':
/usr/lib/pymodules/python2.6/chardet/universaldetector.py:72: UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal
elif aBuf[:4] == '\xFF\xFE\x00\x00':
/usr/lib/pymodules/python2.6/chardet/universaldetector.py:75: UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal
elif aBuf[:4] == '\x00\x00\xFE\xFF':
/usr/lib/pymodules/python2.6/chardet/universaldetector.py:78: UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal
elif aBuf[:4] == '\xFE\xFF\x00\x00':
/usr/lib/pymodules/python2.6/chardet/universaldetector.py:81: UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal
elif aBuf[:4] == '\x00\x00\xFF\xFE':
/usr/lib/pymodules/python2.6/chardet/universaldetector.py:84: UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal
elif aBuf[:2] == '\xFF\xFE':
/usr/lib/pymodules/python2.6/chardet/universaldetector.py:87: UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal
elif aBuf[:2] == '\xFE\xFF':
{'confidence': 1.0, 'encoding': 'ascii'}
>>>
>>> chardet.detect(s)
{'confidence': 1.0, 'encoding': 'ascii'}
>>>
| [
"UTF-16 big endian\n",
"You have UTF-16BE without a BOM. As documented, chardet doesn't grok UTF-nnxE without a BOM.\n>>> s = '\\x00Q\\x00u\\x00i\\x00c\\x00k' #### Note: dropping the spurious `u` prefix\n>>> s.decode('utf_16be')\nu'Quick'\n>>>\n\nchardet is also not smart enough to raise a DontBeSilly exception i... | [
8,
2
] | [] | [] | [
"character_encoding",
"python"
] | stackoverflow_0003759189_character_encoding_python.txt |
Q:
creating xml tree from a textfile with Python
I need to avoid creating double branches in an xml tree when parsing a text file. Let's say the textfile is as follows (the order of lines is random):
branch1:branch11:message11
branch1:branch12:message12
branch2:branch21:message21
branch2:branch22:message22
So the resulting xml tree should have a root with two branches. Both of those branches have two subbranches. The Python code I use to parse this textfile is as follows:
import string
fh = open ('xmlbasic.txt', 'r')
allLines = fh.readlines()
fh.close()
import xml.etree.ElementTree as ET
root = ET.Element('root')
for line in allLines:
tempv = line.split(':')
branch1 = ET.SubElement(root, tempv[0])
branch2 = ET.SubElement(branch1, tempv[1])
branch2.text = tempv[2]
tree = ET.ElementTree(root)
tree.write('xmlbasictree.xml')
The problem with this code is, that a branch in xml tree is created with each line from the textfile.
Any suggestions how to avoid creating another branch in xml tree if a branch with this name exists already?
A:
with open("xmlbasic.txt") as lines_file:
lines = lines_file.read()
import xml.etree.ElementTree as ET
root = ET.Element('root')
for line in lines:
head, subhead, tail = line.split(":")
head_branch = root.find(head)
if not head_branch:
head_branch = ET.SubElement(root, head)
subhead_branch = head_branch.find(subhead)
if not subhead_branch:
subhead_branch = ET.SubElement(branch1, subhead)
subhead_branch.text = tail
tree = ET.ElementTree(root)
ET.dump(tree)
The logic is simple -- you already stated it in your question! You merely need to check whether a branch already exists in the tree before creating it.
Note that this is likely inefficient, since you are searching up to the entire tree for each line. This is because ElementTree is not designed for uniqueness.
If you require speed (which you may not, especially for smallish trees!), a more efficient way would be to use a defaultdict to store the tree structure before converting it to an ElementTree.
import collections
import xml.etree.ElementTree as ET
with open("xmlbasic.txt") as lines_file:
lines = lines_file.read()
root_dict = collections.defaultdict( dict )
for line in lines:
head, subhead, tail = line.split(":")
root_dict[head][subhead] = tail
root = ET.Element('root')
for head, branch in root_dict.items():
head_element = ET.SubElement(root, head)
for subhead, tail in branch.items():
ET.SubElement(head_element,subhead).text = tail
tree = ET.ElementTree(root)
ET.dump(tree)
A:
something along these lines? You keep the level of the branches to be reused in a dict.
b1map = {}
for line in allLines:
tempv = line.split(':')
branch1 = b1map.get(tempv[0])
if branch1 is None:
branch1 = b1map[tempv[0]] = ET.SubElement(root, tempv[0])
branch2 = ET.SubElement(branch1, tempv[1])
branch2.text = tempv[2]
| creating xml tree from a textfile with Python | I need to avoid creating double branches in an xml tree when parsing a text file. Let's say the textfile is as follows (the order of lines is random):
branch1:branch11:message11
branch1:branch12:message12
branch2:branch21:message21
branch2:branch22:message22
So the resulting xml tree should have a root with two branches. Both of those branches have two subbranches. The Python code I use to parse this textfile is as follows:
import string
fh = open ('xmlbasic.txt', 'r')
allLines = fh.readlines()
fh.close()
import xml.etree.ElementTree as ET
root = ET.Element('root')
for line in allLines:
tempv = line.split(':')
branch1 = ET.SubElement(root, tempv[0])
branch2 = ET.SubElement(branch1, tempv[1])
branch2.text = tempv[2]
tree = ET.ElementTree(root)
tree.write('xmlbasictree.xml')
The problem with this code is, that a branch in xml tree is created with each line from the textfile.
Any suggestions how to avoid creating another branch in xml tree if a branch with this name exists already?
| [
"with open(\"xmlbasic.txt\") as lines_file:\n lines = lines_file.read()\n\nimport xml.etree.ElementTree as ET\n\nroot = ET.Element('root')\n\nfor line in lines:\n head, subhead, tail = line.split(\":\")\n\n head_branch = root.find(head)\n if not head_branch:\n head_branch = ET.SubElement(root, he... | [
1,
0
] | [] | [] | [
"elementtree",
"python",
"xml"
] | stackoverflow_0003759200_elementtree_python_xml.txt |
Q:
How to use delete() method in Google App Engine Python's request handler
In GAE Python, I could use
class MyRequestHandler(webapp.RequestHandler):
def get(self):
pass #Do Something...
def post(self):
pass #Do Something...
To handle GET and POST request. But how can I handle DELETE and PUT? I see delete() and put() in API documentation, but I don't know how to write a form to simulate DELETE and PUT.
I know in Rails, I can use post method with a hidden field in form to simulate the requests like this:
<input type="hidden" name="_method" value="delete" />
and Rails handles the dirty works automatically.
Is there any similar way to do it in GAE python?
I searched this in Google, but no luck.
Thanks.
A:
You can use the request method which accepts all the methods like get,post,delete and put.
Then you can check it for the request type accordingly.
Check this:
http://gdata-python-client.googlecode.com/svn/trunk/pydocs/gdata.urlfetch.html
<form method="post" action="">
<input type="hidden" name="_method" value="put" />
<input type="text" name="name" value="" />
<input type="submit" value="Save" />
</form>
def post(self):
method= self.request.get("_method")
if method == 'put':
#call put() function as required
you can go through this as well for the put specification.
http://code.google.com/appengine/docs/python/tools/webapp/requesthandlerclass.html#RequestHandler_put
A:
The HTML specification doesn't allow a form to use the DELETE method, and you probably can't get a browser to send an HTTP DELETE request with a form. The delete() method of a RequestHandler subclass would generally be used for a RESTful web application with a client that knows how to send DELETE requests, rather than using ordinary HTML forms. (For a browser-based client, you can send DELETE requests in javascript using XMLHttpRequest.)
A:
You can implement this simulation yourself of course, In pseudo code (I'm not familiar with GAE specifics):
def post(self):
if request.get('_method', '') == 'delete':
return self.post()
If you want to truely test PUT and DELETE you will have to find a way to actually use these methods in stead of simulating them. You can use curl for this, for example, i.e.
$ curl -X DELETE url
$ curl -T file url # for PUT
See the curl documentation / manpage for more information.
A:
First, you need to create a new RequestHandler subclass :
from google.appengine.ext import webapp
class RESTfulHandler(webapp.RequestHandler):
def post(self, *args):
method = self.request.get('_method')
if method == "put":
self.put(*args)
elif method == "delete":
self.delete(*args)
else:
self.error(405) # Method not allowed
Then your handler will inherit from it :
class MyHandler(RESTfulHandler):
def get(self):
...
def delete(self):
...
def put(self):
...
def post(self):
...
Here is another example using the X-HTTP-Method-Override header used by most JavaScript libraries :
http://github.com/sork/webapp-handlers/blob/master/restful.py
| How to use delete() method in Google App Engine Python's request handler | In GAE Python, I could use
class MyRequestHandler(webapp.RequestHandler):
def get(self):
pass #Do Something...
def post(self):
pass #Do Something...
To handle GET and POST request. But how can I handle DELETE and PUT? I see delete() and put() in API documentation, but I don't know how to write a form to simulate DELETE and PUT.
I know in Rails, I can use post method with a hidden field in form to simulate the requests like this:
<input type="hidden" name="_method" value="delete" />
and Rails handles the dirty works automatically.
Is there any similar way to do it in GAE python?
I searched this in Google, but no luck.
Thanks.
| [
"You can use the request method which accepts all the methods like get,post,delete and put.\nThen you can check it for the request type accordingly.\nCheck this:\nhttp://gdata-python-client.googlecode.com/svn/trunk/pydocs/gdata.urlfetch.html\n<form method=\"post\" action=\"\">\n <input type=\"hidden\" name=\"_metho... | [
6,
4,
0,
0
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0003740823_google_app_engine_python.txt |
Q:
Django string in unicode pattern
Django when i send the following string from an ajax submit i get the following string in unicode.How to decode this
$.post("/records/save_t/",snddata,
function(data){
if(data == 0 ){
}
},"json");
In django
def save_t(request):
if request.method == 'GET':
qd = request.GET
elif request.method == 'POST':
qd = request.POST
map_str = qd.getlist('map_str')
logging.debug(map_str)
Output is [u'##1##@1//##2##@1//']. How can I convert this to a string? str(map_str) did not work.
Also how to get the values in the pattern
str = map_str.split("//")
for s in map_str.split("//"):
...
...
A:
Why do you think you need to convert it to a string? What's wrong with it as Unicode? It should be perfectly usable as it is.
In any case, what you have is a list containing a single unicode string (because you've used getlist, which always unsurprisingly returns a list). Is the actual problem just that you want to get the actual data out of the list? Then use map_str[0] (of course, map_str is a bad name, because it's not a string but a list).
Or, don't use getlist, but a simple get to get a string rather than a list.
| Django string in unicode pattern | Django when i send the following string from an ajax submit i get the following string in unicode.How to decode this
$.post("/records/save_t/",snddata,
function(data){
if(data == 0 ){
}
},"json");
In django
def save_t(request):
if request.method == 'GET':
qd = request.GET
elif request.method == 'POST':
qd = request.POST
map_str = qd.getlist('map_str')
logging.debug(map_str)
Output is [u'##1##@1//##2##@1//']. How can I convert this to a string? str(map_str) did not work.
Also how to get the values in the pattern
str = map_str.split("//")
for s in map_str.split("//"):
...
...
| [
"Why do you think you need to convert it to a string? What's wrong with it as Unicode? It should be perfectly usable as it is.\nIn any case, what you have is a list containing a single unicode string (because you've used getlist, which always unsurprisingly returns a list). Is the actual problem just that you want ... | [
0
] | [] | [] | [
"django",
"django_models",
"django_views",
"python"
] | stackoverflow_0003759598_django_django_models_django_views_python.txt |
Q:
is it possible to have keyname and an id for an entity in Appengine?
I'm building a facebook app, and my users table's keyName is set to the Uid of the facebook user. I found this to be efficient because I can use db.Key.from_path() to efficiently query the datastore for a particular user instead of doing a query (where uid = x, limit = 1). This is actually my first time using key names.
But when I did this in the sdk, the key().id() is set to None. Is there a way have an id as well?
I'd like an id for use as a primary key is because it's shorter and an integer which makes it faster when I'm storing users in a listProperty (i.e a seperate Buddies entity with a list of friends the user has in the app).
I hope this makes sense :)
thanks a ton!
A:
No. An entity's Key is composed of the application ID, the Kind, the path of the parent entity (if any) and either a key name or an auto-generated ID. It's not possible to have both. The entire Key is the "primary key".
| is it possible to have keyname and an id for an entity in Appengine? | I'm building a facebook app, and my users table's keyName is set to the Uid of the facebook user. I found this to be efficient because I can use db.Key.from_path() to efficiently query the datastore for a particular user instead of doing a query (where uid = x, limit = 1). This is actually my first time using key names.
But when I did this in the sdk, the key().id() is set to None. Is there a way have an id as well?
I'd like an id for use as a primary key is because it's shorter and an integer which makes it faster when I'm storing users in a listProperty (i.e a seperate Buddies entity with a list of friends the user has in the app).
I hope this makes sense :)
thanks a ton!
| [
"No. An entity's Key is composed of the application ID, the Kind, the path of the parent entity (if any) and either a key name or an auto-generated ID. It's not possible to have both. The entire Key is the \"primary key\".\n"
] | [
2
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0003759021_google_app_engine_python.txt |
Q:
What are the downsides of using Python instead of Objective-C?
I know some Python and I'm really impressed by the language's ease of use. From what I've seen of Objective-C it looks a lot less pretty, but it seems to be the lingua franca for Mac OS X development (which means it has better documentation).
I'm thinking about starting Mac development - will using PyObjC+Python make me a second class citizen?
A:
Yes.
For one thing, as you note, all the documentation is written for Objective-C, which is a very different language.
One difference is method name. In Objective-C, when you send a message to (Python would say “call a method of”) an object, the method name (selector) and arguments are mixed:
NSURL *URL = /*…*/;
NSError *error = nil;
QTMovie *movie = [QTMovie movieWithURL:URL
error:&error];
This isn't possible in Python. Python's keyword arguments don't count as part of the method name, so if you did this:
movie = QTMovie.movieWithURL(URL, error = ???)
you would get an exception, because the QTMovie class has no method named movieWithURL; the message in the Objective-C example uses the selector movieWithURL:error:. movieWithURL: and movieWithURL would be two other selectors.
There's no way they can change this, because Python's keyword arguments aren't ordered. Suppose you have a hypothetical three-argument method:
foo = Foo.foo(fred, bar=bar, baz=baz)
Now, this calls foo:bar:baz:, right?
Not so fast. Foo may also have a method named foo:baz:bar:. Because Python's keyword arguments aren't ordered, you may actually be calling that method. Likewise, if you tried to call foo:baz:bar:, you may actually end up calling foo:bar:baz:. In reality, this case is unlikely, but if it ever happens, you would be unable to reliably call either method.
So, in PyObjC, you would need to call the method like this:
movie = QTMovie.movieWithURL_error_(URL, ???)
You may be wondering about the ???. C doesn't allow multiple return values, so, in Objective-C, the error: argument takes a pointer to a pointer variable, and the method will store an object in that variable (this is called return-by-reference). Python doesn't have pointers, so the way the bridge handles arguments like this is that you pass None, and the method will (appear to) return a tuple. So the correct example is:
movie, error = QTMovie.movieWithURL_error_(URL, None)
You can see how even a simple example deviates from what documentation might show you in Objective-C.
There are other issues, such as the GIL. Cocoa apps are only going to get more concurrent, and you're going to want in on this, especially with tempting classes like NSOperation lying around. And the GIL is a serious liability, especially on multi-core machines. I say this as a Python guy myself (when not writing for Cocoa). As David Beazley demonstrates in that video, it's a cold, hard fact; there's no denying it.
So, if I were going to switch away from Objective-C for my apps, I would take up MacRuby. Unlike with PyObjC and RubyCocoa, messages to Cocoa objects don't cross the language bridge; it's a from-the-ground-up Ruby implementation in Cocoa, with language extensions to better support writing Cocoa code in it.
But that's too far ahead of you. You're just getting started. Start with Objective-C. Better to avoid all impedance mismatches between the language you're using and the one the documentation is written for by keeping them the same language.
Plus, you'll find some bugs (such as messages to deceased objects) harder to diagnose without knowledge of how Objective-C works. You will write these bugs as a new Cocoa programmer, regardless of which language you're writing the code in.
So, learn C, then learn Objective-C. A working knowledge of both shouldn't take more than a few weeks, and at the end of it, you'll be better prepared for everything else.
I won't go into how I learned C; suffice to say that I do not recommend the way I did it. I've heard that this book is good, but I've never owned nor read it. I do have this book, and can confirm that it's good, but it's also not Mac-specific; skip the chapter on how to compile the code, and use Xcode instead.
As for Objective-C: The Hillegass book is the most popular, but I didn't use it. (I have skimmed it, and it looks good.) I read Apple's document on the language, then jumped right in to writing small Cocoa apps. I read some of the guides, with mixed results. There is a Currency Converter tutorial, but it didn't help me at all, and doesn't quite reflect a modern Cocoa app. (Modern apps still use outlets and actions, but also Bindings, and a realistic Currency Converter would be almost entirely a couple of Bindings.)
A:
This really says it all:
As the maintainer of PyObjC for nearly
15 years, I will say it bluntly. Use
Objective-C. You will need to know
Objective-C to really understand Cocoa
anyway and PyObjC is just going to add
a layer of bugs & issues that are
alien to 99% of Cocoa programmers.
a comment in an answer to this question. This question is also interesting.
A:
DO NOT ATTEMPT to avoid learning objective-C if you're going to write apps for the Mac. The purpose of PyObjC and the other language bindings is to let you re-use existing libraries in your apps, not to let you avoid learning the native tools.
A:
Second class citizen seems a bit strong. The Objective-C API's are available from Python as well, should you need them, and that's mostly if you want to make Cocoa apps. But then they are restricted to OS X anyway. Personally, I have no interest in building apps that isn't cross-platform, but that's me. That also means I haven't actually done this, so I don't know how tricky it is, but there was an article in the Python Magazine not long ago, and it didn't look that horrible.
The major drawback of Python is execution time, and that mainly comes from it being a dynamic language. This can be solved with Cython and C-extensions, etc, but then you get a mix of Python + ObjectiveC API's + Cython which can be daunting.
So it depends a lot of what kinds of applications you are going to make. Something uniquely OSX-ish that makes no sense anywhere else? ObjectiveC is probably the ticket. Cross-platform servers, well then Python rocks! Something else? Then it depends.
A:
This is something I've been wondering myself, and although I hope someone comes by with more experience, from what I know you will not be seriously constrained by Python itself. Along with Java and GCC, Python is an excellent way to write native cross-platform applications. Once you get the hang of it you should be able to map example code in Objective C to your Python code.
Since you have access to all libraries and events, everything that you can do in Objective C will be there in Python. Of course, the more OS X-only calls and functions you use, the less easy it will be to port to another platform, but that's beside the point. Usually graphics programming and working with device drivers is somewhat of a limiting factor - but in both cases I'm finding evidence of good support and community libraries (search for Python and Quartz, Lightblue, libhid, PyUSB, for some examples).
The decisive factor for me would be: what is the level of tooling and IDE support that is needed. Apple provides some great software for building new software, but then again with something like Pydev you've got a great place to write Python code too! http://pydev.org/
So give it a try, I'm sure you won't regret it, and there will be a supportive community to draw on for help and insipiration.
A:
You're going to need Objective-C: that's what all the tutorials, documentation, sample code, and everything is written in. In addition to a wilder variety of people being able to help you.
So learn ObjC first. If, on your second or third project, or a year down the road, you start a project that needs a Python module (like, say, Twisted, or SQLAlchemy. But a SERIOUS need like foundation of your app need, where the extra boost your app gets makes everything worth it), then you can write a PyObjC app and get a lot of the speed benefits of that language, with your background in Cocoa.
A:
Just as an extra option, consider that wxPython can produce some pretty good applications on Mac as well as on Linux and Windows. For the most part you can get native appearance but maintain portability with little or no attention to platform-specific issues.
In other words, PyObjC + Python is not the only way to do Mac development with Python.
A:
No you dont need to know Objective C you dont need to use PyObjC , and you wont be a second class citizent.
Unless you want to do something extremely specific to the MAC platform , coding in Objective C or using PyObjC is a really bad idea.
The reason is obvious, once you go the objc route you say a big "goodbye" to other platforms. Its that simple.
Apple does not want you to code for other platforms the same way Microsoft does not want you to code for other platforms. And that is why more and more developers are turning to open source languages like, python, java, ruby etc. Because you dont care what Apple and Microsot , you only care about an App that is the most useful and most easy to develop. And making your App available only for MAC will make it less useful and obviously developing in Objective C is way more difficult.
Python has more than enough libraries to accomodate you , hundrends of them , readily available for the mac platform. I for instance develope a new application in pygame, no its not a game, if I have done the same thing in ObjC or PyObj I would have to rewrite the code for windows and linux. While with pygame my code works exactly the same in windows and linux even though my main platform is macos.
Thats the appeal of most python libraries , they are cross platform. WxPython is another example, someone mentioned that "it does not exactly look natively" , do you want this to stop you from making your application available for windows and linux. Why limit yourself only on the MAC platform ? Do you think the average user will care how natively your app will look. Even macos apps do not look native , many of them introduce their own "eye candy" gui. Not that you cant make WxPython look 100% native, the way you code is always importnat.
Objc makes sense when you intend to develop for Iphone OS , as Apple thought it a great idea to exclude python (and not only python), even though they were forced to include javascript (or else websurfing would have being a nightmare on iphoneos) . Pyjamas, can make python available for iphone os as well (with no hacks or jailbroken phones), but with the obvious limitations since it translates python code to javascript, but still its a valid solution till Apple decide that excluding python from iphone os is a really bad idea.
link text
There is no harm done in studying Objective C though. You can always use the native libraries via pyobjc.
But to be absolutely sincere with you, If my app reaches a dead end with the python libraries ( a very unlikely scenario) I would rather wrap an existing cross platform C/C++ Libraries with Cython than go the objective c pyobjc route and detroy the cross platform ability of my app. The last thing I would be using is anything platoform specifc.
Now if you dont care about other platforms at all, then I guess Objective C can be a valid choice. It certainly looks ugly as hell, but I have heard that it gets much better the more you use it and there are many people that prefer it over C/C++.
| What are the downsides of using Python instead of Objective-C? | I know some Python and I'm really impressed by the language's ease of use. From what I've seen of Objective-C it looks a lot less pretty, but it seems to be the lingua franca for Mac OS X development (which means it has better documentation).
I'm thinking about starting Mac development - will using PyObjC+Python make me a second class citizen?
| [
"Yes.\nFor one thing, as you note, all the documentation is written for Objective-C, which is a very different language.\nOne difference is method name. In Objective-C, when you send a message to (Python would say “call a method of”) an object, the method name (selector) and arguments are mixed:\nNSURL *URL = /*…*/... | [
37,
18,
3,
2,
0,
0,
0,
0
] | [] | [] | [
"cocoa",
"macos",
"pyobjc",
"python"
] | stackoverflow_0002175573_cocoa_macos_pyobjc_python.txt |
Q:
Python: get path to file in sister directory?
I have a file structure like this:
data
mydata.xls
scripts
myscript.py
From within myscript.py, how can I get the filepath of mydata.xls?
I need to pass it to xlrd:
book = xlrd.open_workbook(filename)
and relative filepaths like '../data/mydata.xls' don't seem to work.
A:
You can use os.path.abspath(<relpath>) to get an absolute path from a relative one.
vinko@parrot:~/p/f$ more a.py
import os
print os.path.abspath('../g/a')
vinko@parrot:~/p/f$ python a.py
/home/vinko/p/g/a
The dir structure:
vinko@parrot:~/p$ tree
.
|-- f
| `-- a.py
`-- g
`-- a
2 directories, 2 files
A:
If you want to made it independent from your current directory try
os.path.join(os.path.dirname(__file__), '../data/mydata.xls')
The special variable __file__ contains a relative path to the script in which it's used. Keep in mind that __file__ is undefined when using the REPL interpreter.
A:
import os
directory = os.path.dirname(os.getcwd())
final = os.path.join(directory, 'data', 'mydata.xls')
or simply
os.path.abspath('../data/mydata.xls')
| Python: get path to file in sister directory? | I have a file structure like this:
data
mydata.xls
scripts
myscript.py
From within myscript.py, how can I get the filepath of mydata.xls?
I need to pass it to xlrd:
book = xlrd.open_workbook(filename)
and relative filepaths like '../data/mydata.xls' don't seem to work.
| [
"You can use os.path.abspath(<relpath>) to get an absolute path from a relative one.\nvinko@parrot:~/p/f$ more a.py\nimport os\nprint os.path.abspath('../g/a')\n\nvinko@parrot:~/p/f$ python a.py\n/home/vinko/p/g/a\n\nThe dir structure:\nvinko@parrot:~/p$ tree\n.\n|-- f\n| `-- a.py\n`-- g\n `-- a\n\n2 directori... | [
10,
9,
4
] | [
"From you comments, it seems that book = xlrd.open_workbook(filename) doesn't like relative path. You can create a path relative to the current file __file__ and then take the absolute path that will remove the relative portions (..)\nimport os\n\nfilename = os.path.join(os.path.dirname(__file__), '../data/mydata.x... | [
-1
] | [
"python"
] | stackoverflow_0003758866_python.txt |
Q:
python string pattern matching
new_str="@@2@@*##1"
new_str1="@@3@@*##5##7"
How to split the above string in python
for val in new_str.split("@@*"):
logging.debug("=======")
logging.debug(val[2:]) // will give
for st in val.split("@@*"):
//how to get the values after ## in new_str and new_str1
A:
I don't understand the question.
Are you trying to split a string by a delimiter? Then use split:
>>> a = "@@2@@*##1"
>>> b = "@@3@@*##5##7"
>>>
>>> a.split("@@*")
['@@2', '##1']
>>> b.split("@@*")
['@@3', '##5##7']
Are you trying to strip extraneous characters from a string? Then use strip:
>>> c = b.split("@@*")[1]
>>> c
'##5##7'
>>> c.strip("#")
'5##7'
Are you trying to remove all the hashes (#) from a string? Then use replace:
>>> c.replace("#","")
'57'
Are you trying to find all the characters after "##"? Then use rsplit with its optional argument to split only once:
>>> a.rsplit("##",1)
['@@2@@*', '1']
| python string pattern matching | new_str="@@2@@*##1"
new_str1="@@3@@*##5##7"
How to split the above string in python
for val in new_str.split("@@*"):
logging.debug("=======")
logging.debug(val[2:]) // will give
for st in val.split("@@*"):
//how to get the values after ## in new_str and new_str1
| [
"I don't understand the question.\nAre you trying to split a string by a delimiter? Then use split:\n>>> a = \"@@2@@*##1\"\n>>> b = \"@@3@@*##5##7\"\n>>>\n>>> a.split(\"@@*\")\n['@@2', '##1']\n>>> b.split(\"@@*\")\n['@@3', '##5##7']\n\nAre you trying to strip extraneous characters from a string? Then use strip:\n>>... | [
4
] | [] | [] | [
"python"
] | stackoverflow_0003760075_python.txt |
Q:
What is the equivalent of Ruby require?
I am coming to Python from Ruby.
What is the equivalent statement of require in Python?
A:
The import statement.
Maybe it's advisable you follow a Python tutorial where much of the basics are explained
| What is the equivalent of Ruby require? | I am coming to Python from Ruby.
What is the equivalent statement of require in Python?
| [
"The import statement.\nMaybe it's advisable you follow a Python tutorial where much of the basics are explained\n"
] | [
5
] | [] | [] | [
"equivalent",
"python",
"require"
] | stackoverflow_0003760247_equivalent_python_require.txt |
Q:
allow_none in twisted XML-RPC server
I am building xml rpc service using twisted and I would like to use None just as it can be done in standard python lib. How can I pass allow_none to the twisted version of xmlrpc server?
EDIT
In [28]: sock = rpc.ServerProxy('http://localhost:7080',allow_none=True)
In [29]: sock
Out[29]: <ServerProxy for localhost:7080/RPC2>
In [30]: sock.list_reports()
Out[30]: ['example']
In [31]: sock.run_report('example')
---------------------------------------------------------------------------
Fault Traceback (most recent call last)
reports/<ipython console> in <module>()
/usr/lib/python2.6/xmlrpclib.pyc in __call__(self, *args)
1197 return _Method(self.__send, "%s.%s" % (self.__name, name))
1198 def __call__(self, *args):
-> 1199 return self.__send(self.__name, args)
1200
1201 ##
/usr/lib/python2.6/xmlrpclib.pyc in __request(self, methodname, params)
1487 self.__handler,
1488 request,
-> 1489 verbose=self.__verbose
1490 )
1491
/usr/lib/python2.6/xmlrpclib.pyc in request(self, host, handler, request_body, verbose)
1251 sock = None
1252
-> 1253 return self._parse_response(h.getfile(), sock)
1254
1255 ##
/usr/lib/python2.6/xmlrpclib.pyc in _parse_response(self, file, sock)
1390 p.close()
1391
-> 1392 return u.close()
1393
1394 ##
/usr/lib/python2.6/xmlrpclib.pyc in close(self)
836 raise ResponseError()
837 if self._type == "fault":
--> 838 raise Fault(**self._stack[0])
839 return tuple(self._stack)
840
Fault: <Fault 8002: "Can't serialize output: cannot marshal None unless allow_none is enabled">
A:
XMLRPC accepts allowNone as an argument to its initializer. So, pass True when instantiating your resources if you want to support None.
from twisted.web.xmlrpc import XMLRPC
resource = XMLRPC(allowNone=True)
A:
I think it should be specified on client side...
when you create the proxy from your xmlrpc client - you may pass the keyword argument allow_none = True for python xmlrpclib module like below...
In [184]: import xmlrpclib as rpc
In [185]: sock = rpc.ServerProxy('http://localhost/xmlrpc/object',allow_none=True)
EDIT:
from twisted.web.xmlrpc import Proxy
proxy = Proxy('http://localhost/xmlrpc', allowNone=True)
| allow_none in twisted XML-RPC server | I am building xml rpc service using twisted and I would like to use None just as it can be done in standard python lib. How can I pass allow_none to the twisted version of xmlrpc server?
EDIT
In [28]: sock = rpc.ServerProxy('http://localhost:7080',allow_none=True)
In [29]: sock
Out[29]: <ServerProxy for localhost:7080/RPC2>
In [30]: sock.list_reports()
Out[30]: ['example']
In [31]: sock.run_report('example')
---------------------------------------------------------------------------
Fault Traceback (most recent call last)
reports/<ipython console> in <module>()
/usr/lib/python2.6/xmlrpclib.pyc in __call__(self, *args)
1197 return _Method(self.__send, "%s.%s" % (self.__name, name))
1198 def __call__(self, *args):
-> 1199 return self.__send(self.__name, args)
1200
1201 ##
/usr/lib/python2.6/xmlrpclib.pyc in __request(self, methodname, params)
1487 self.__handler,
1488 request,
-> 1489 verbose=self.__verbose
1490 )
1491
/usr/lib/python2.6/xmlrpclib.pyc in request(self, host, handler, request_body, verbose)
1251 sock = None
1252
-> 1253 return self._parse_response(h.getfile(), sock)
1254
1255 ##
/usr/lib/python2.6/xmlrpclib.pyc in _parse_response(self, file, sock)
1390 p.close()
1391
-> 1392 return u.close()
1393
1394 ##
/usr/lib/python2.6/xmlrpclib.pyc in close(self)
836 raise ResponseError()
837 if self._type == "fault":
--> 838 raise Fault(**self._stack[0])
839 return tuple(self._stack)
840
Fault: <Fault 8002: "Can't serialize output: cannot marshal None unless allow_none is enabled">
| [
"XMLRPC accepts allowNone as an argument to its initializer. So, pass True when instantiating your resources if you want to support None.\nfrom twisted.web.xmlrpc import XMLRPC\nresource = XMLRPC(allowNone=True)\n\n",
"I think it should be specified on client side...\nwhen you create the proxy from your xmlrpc c... | [
8,
0
] | [] | [] | [
"python",
"twisted",
"xml_rpc"
] | stackoverflow_0003760043_python_twisted_xml_rpc.txt |
Q:
What are the WordPress analogs\clones that would run under Google App Engine?
So I want it to run on free google app engine version, I want it to be more or less structured like WP (meaning end user experience). I need clean readable source so I could change it as I wish.
If there are no such alike WP ones than some other Blog Engine would work for me.
What are the WordPress analogs\clones that would run under Google App Engine?
A:
Roller is a good Java-based blog engine. I'm not sure if it works with GAE but I can't see why it wouldn't.
| What are the WordPress analogs\clones that would run under Google App Engine? | So I want it to run on free google app engine version, I want it to be more or less structured like WP (meaning end user experience). I need clean readable source so I could change it as I wish.
If there are no such alike WP ones than some other Blog Engine would work for me.
What are the WordPress analogs\clones that would run under Google App Engine?
| [
"Roller is a good Java-based blog engine. I'm not sure if it works with GAE but I can't see why it wouldn't.\n"
] | [
1
] | [] | [] | [
"blogs",
"google_app_engine",
"java",
"python",
"wordpress"
] | stackoverflow_0003760384_blogs_google_app_engine_java_python_wordpress.txt |
Q:
Setting window style in PyQT/PySide?
I've been looking for how to do this and I've found places where the subject comes up, but none of the suggestions actually work for me, even though they seem to work out okay for the questioner (they don't even list what to import). I ran across self.setWindowFlags(Qt.FramelessWindowHint) but it doesn't seem to work regardless of the import I try (QtGui.FramelessWindowHint, QtCore.FramelessWindowHint, etc.).
Any ideas?
A:
u need to import QtCore
so the code will look like this :
self.setWindowFlags(QtCore.Qt.FramelessWindowHint)
whenever you see Qt.something put in mind that they are talking about the Qt class inside QtCore module .
hope this helps
| Setting window style in PyQT/PySide? | I've been looking for how to do this and I've found places where the subject comes up, but none of the suggestions actually work for me, even though they seem to work out okay for the questioner (they don't even list what to import). I ran across self.setWindowFlags(Qt.FramelessWindowHint) but it doesn't seem to work regardless of the import I try (QtGui.FramelessWindowHint, QtCore.FramelessWindowHint, etc.).
Any ideas?
| [
"u need to import QtCore\n\n\nso the code will look like this : \n self.setWindowFlags(QtCore.Qt.FramelessWindowHint) \nwhenever you see Qt.something put in mind that they are talking about the Qt class inside QtCore module .\nhope this helps \n"
] | [
13
] | [] | [] | [
"pyqt",
"pyside",
"python"
] | stackoverflow_0003758648_pyqt_pyside_python.txt |
Q:
Converting domain names to idn in python
I have a long list of domain names which I need to generate some reports on. The list contains some IDN domains, and although I know how to convert them in python on the command line:
>>> domain = u"pfarmerü.com"
>>> domain
u'pfarmer\xfc.com'
>>> domain.encode("idna")
'xn--pfarmer-t2a.com'
>>>
I'm struggling to get it to work with a small script reading data from the text file.
#!/usr/bin/python
import sys
infile = open(sys.argv[1])
for line in infile:
print line,
domain = unicode(line.strip())
print type(domain)
print "IDN:", domain.encode("idna")
print
I get the following output:
$ ./idn.py ./test
pfarmer.com
<type 'unicode'>
IDN: pfarmer.com
pfarmerü.com
Traceback (most recent call last):
File "./idn.py", line 9, in <module>
domain = unicode(line.strip())
UnicodeDecodeError: 'ascii' codec can't decode byte 0xfc in position 7: ordinal not in range(128)
I have also tried:
#!/usr/bin/python
import sys
import codecs
infile = codecs.open(sys.argv[1], "r", "utf8")
for line in infile:
print line,
domain = line.strip()
print type(domain)
print "IDN:", domain.encode("idna")
print
Which gave me:
$ ./idn.py ./test
Traceback (most recent call last):
File "./idn.py", line 8, in <module>
for line in infile:
File "/usr/lib/python2.6/codecs.py", line 679, in next
return self.reader.next()
File "/usr/lib/python2.6/codecs.py", line 610, in next
line = self.readline()
File "/usr/lib/python2.6/codecs.py", line 525, in readline
data = self.read(readsize, firstline=True)
File "/usr/lib/python2.6/codecs.py", line 472, in read
newchars, decodedbytes = self.decode(data, self.errors)
UnicodeDecodeError: 'utf8' codec can't decode bytes in position 0-5: unsupported Unicode code range
Here is my test data file:
pfarmer.com
pfarmerü.com
I'm very aware of my need to understand unicode now.
Thanks,
Peter
A:
you need to know in which encoding you file was saved. This would be something like 'utf-8' (which is NOT Unicode) or 'iso-8859-1' or 'cp1252' or alike.
Then you can do (assuming 'utf-8'):
infile = open(sys.argv[1])
for line in infile:
print line,
domain = line.strip().decode('utf-8')
print type(domain)
print "IDN:", domain.encode("idna")
print
Convert encoded strings to unicode with decode. Convert unicode to string with encode. If you try to encode something which is already encoded, python tries to decode first, with the default codec 'ascii' which fails for non-ASCII-values.
A:
Your first example is fine, except that:
domain = unicode(line.strip())
you have to specify a particular encoding here: unicode(line.strip(), 'utf-8'). Otherwise you get the default encoding which for safety is 7-bit ASCII, hence the error. Alternatively you can spell it line.strip().decode('utf-8') as in knitti's example; there is no difference in behaviour between the two syntaxes.
However judging by the error “can't decode byte 0xfc”, I think you haven't actually saved your test file as UTF-8. Presumably this is why the second example, that also looks OK in principle, fails.
Instead it's ISO-8859-1 or the very similar Windows code page 1252. If it's come from a text editor on a Western Windows box it will certainly be the latter; Linux machines use UTF-8 by default instead nowadays. Either make sure to save your file as UTF-8, or read the file using the encoding 'cp1252' instead.
| Converting domain names to idn in python | I have a long list of domain names which I need to generate some reports on. The list contains some IDN domains, and although I know how to convert them in python on the command line:
>>> domain = u"pfarmerü.com"
>>> domain
u'pfarmer\xfc.com'
>>> domain.encode("idna")
'xn--pfarmer-t2a.com'
>>>
I'm struggling to get it to work with a small script reading data from the text file.
#!/usr/bin/python
import sys
infile = open(sys.argv[1])
for line in infile:
print line,
domain = unicode(line.strip())
print type(domain)
print "IDN:", domain.encode("idna")
print
I get the following output:
$ ./idn.py ./test
pfarmer.com
<type 'unicode'>
IDN: pfarmer.com
pfarmerü.com
Traceback (most recent call last):
File "./idn.py", line 9, in <module>
domain = unicode(line.strip())
UnicodeDecodeError: 'ascii' codec can't decode byte 0xfc in position 7: ordinal not in range(128)
I have also tried:
#!/usr/bin/python
import sys
import codecs
infile = codecs.open(sys.argv[1], "r", "utf8")
for line in infile:
print line,
domain = line.strip()
print type(domain)
print "IDN:", domain.encode("idna")
print
Which gave me:
$ ./idn.py ./test
Traceback (most recent call last):
File "./idn.py", line 8, in <module>
for line in infile:
File "/usr/lib/python2.6/codecs.py", line 679, in next
return self.reader.next()
File "/usr/lib/python2.6/codecs.py", line 610, in next
line = self.readline()
File "/usr/lib/python2.6/codecs.py", line 525, in readline
data = self.read(readsize, firstline=True)
File "/usr/lib/python2.6/codecs.py", line 472, in read
newchars, decodedbytes = self.decode(data, self.errors)
UnicodeDecodeError: 'utf8' codec can't decode bytes in position 0-5: unsupported Unicode code range
Here is my test data file:
pfarmer.com
pfarmerü.com
I'm very aware of my need to understand unicode now.
Thanks,
Peter
| [
"you need to know in which encoding you file was saved. This would be something like 'utf-8' (which is NOT Unicode) or 'iso-8859-1' or 'cp1252' or alike.\nThen you can do (assuming 'utf-8'):\n\ninfile = open(sys.argv[1])\n\nfor line in infile:\n print line,\n domain = line.strip().decode('utf-8')\n print t... | [
22,
2
] | [] | [] | [
"python",
"unicode"
] | stackoverflow_0003760338_python_unicode.txt |
Q:
How to order by ancestor/parent Google App Engine query?
I would like to order entities by ancestor, GQL reference only mentions properties in ordering. Do I have to store a parent as a property to involve it in the ordering?
I trying to achieve something like this:
Foo.all().ancestor(bar).order('ancestor').order('-value').fetch(100)
EDIT:
I have something like this:
bar
├ spam
│ ├ foo2 (value = 2)
│ └ foo7
└ egs
├ foo6
└ foo5
And I'd like to get: [foo5, foo6, foo2, foo7]. I guess what I really want I to group them by ancestor, and then order them by value property.
A:
Ordering by key will sort first by ancestors, then by the id or name of the entity. If you want to sort by ancestor but not by id/name of the entity itself then yes, you'll need to include an explicit 'ancestor' SelfReferenceProperty to sort on.
| How to order by ancestor/parent Google App Engine query? | I would like to order entities by ancestor, GQL reference only mentions properties in ordering. Do I have to store a parent as a property to involve it in the ordering?
I trying to achieve something like this:
Foo.all().ancestor(bar).order('ancestor').order('-value').fetch(100)
EDIT:
I have something like this:
bar
├ spam
│ ├ foo2 (value = 2)
│ └ foo7
└ egs
├ foo6
└ foo5
And I'd like to get: [foo5, foo6, foo2, foo7]. I guess what I really want I to group them by ancestor, and then order them by value property.
| [
"Ordering by key will sort first by ancestors, then by the id or name of the entity. If you want to sort by ancestor but not by id/name of the entity itself then yes, you'll need to include an explicit 'ancestor' SelfReferenceProperty to sort on.\n"
] | [
4
] | [] | [] | [
"google_app_engine",
"google_cloud_datastore",
"python"
] | stackoverflow_0003759713_google_app_engine_google_cloud_datastore_python.txt |
Q:
Java oneliner for list cleanup
Is there a construct in java that does something like this(here implemented in python):
[] = [item for item in oldList if item.getInt() > 5]
Today I'm using something like:
ItemType newList = new ArrayList();
for( ItemType item : oldList ) {
if( item.getInt > 5) {
newList.add(item);
}
}
And to me the first way looks a bit smarter.
A:
Java 7 might or might not implement closures and hence support functionality like this, but currently it doesn't, so on the Java VM you have the options to do it in Groovy, Scala or Clojure (possible others, too), but in java you can only get close to that by using helpers like Guava's Collections2.filter().
JDK 7 sample code:
findItemsLargerThan(List<Integer> l, int what){
return filter(boolean(Integer x) { x > what }, l);
}
findItemsLargerThan(Arrays.asList(1,2,5,6,9), 5)
Groovy sample code:
Arrays.asList(1,2,5,6,9).findAll{ it > 5}
Guava Sample Code:
Collections2.filter(Arrays.asList(1, 2, 5, 6, 9),
new Predicate<Integer>(){
@Override
public boolean apply(final Integer input){
return input.intValue() > 5;
}
}
);
Scala sample code (thanks Bolo):
Array(1, 2, 5, 6, 9) filter (x => x > 5)
A:
You can give a look at lambdaj. There is a select method you can use with a hamcrest condition.
A:
Nothing is impossible (-:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class ListCleaner {
public static void main(String[] args) {
final List<Integer> oldList = Arrays.asList(new Integer[] { 23, 4, 5,
657 });
System.out.println(oldList);
List<Integer> newList = new ArrayList<Integer>() {
{
for (Integer element : oldList) {
if (element > 5) {
this.add(element);
}
}
}
};
System.out.println(newList);
}
}
The only constraint is that the oldList has to be final.
A:
It can be done in pure Java, but you need to write a support class Filter for the following code to run successfully:
List<Integer> oldList = Arrays.asList(new Integer[] { 1, 2, 5, 6, 9 });
List<Integer> newList = new Filter<Integer>(oldList) {
{
findAll(it > 5);
}
}.values();
System.out.println(newList); // [6, 9]
In case you wonder why this code compiles take a look at Hidden features of Java: Double brace initialization. This creates an anonymous instance of the class Filter that contains the it variable and provides the method findAll().
The Filter class itself has the one drawback that a new instance is created for each list element to evaluate the boolean condition at findAll():
public abstract class Filter<T> {
protected List<T> values = new ArrayList<T>();
protected T it;
public Filter(List<T> values) {
if (values != null) {
this.values.addAll(values);
}
if (values.isEmpty()) {
throw new RuntimeException("Not for empty collections!");
}
it = values.iterator().next();
// instance initializer gets executed here, calls findAll
}
protected void findAll(boolean b) throws Throwable {
// exit condition for future calls
if (values.size() > 1) {
// only repeat for each entry, if values has multiple entries
Iterator<T> iterator = values.iterator();
while (iterator.hasNext()) {
// don't evalute again for the first entry
if (!b) {
iterator.next();
iterator.remove();
b = true;
} else {
// for each other entry create an argument with one element
List<T> next = new ArrayList<T>();
next.add(iterator.next());
// get constructor of anonymous class
Constructor<?> constructor = this.getClass().getDeclaredConstructors()[0];
// invoke constructor and thus execute instance initializer again
Filter<T> filtered = (Filter<T>) constructor.newInstance(new Object[] { null, next });
// if values is empty, the condition didn't match and the element can be removed
if (filtered.values.isEmpty()) {
iterator.remove();
}
}
}
} else {
// one element can be checked directly
if (!b) {
values.clear();
}
}
}
public List<T> values() {
return values;
}
}
But as instance creation is rather cheap these days and the Filter class is usable for all Objects, it may be worth including in your Utils package.
Greetz,
GHad
A:
No, this kind of dynamic language construct is not supported in Java yet :-) So you have to live with your option 2
| Java oneliner for list cleanup | Is there a construct in java that does something like this(here implemented in python):
[] = [item for item in oldList if item.getInt() > 5]
Today I'm using something like:
ItemType newList = new ArrayList();
for( ItemType item : oldList ) {
if( item.getInt > 5) {
newList.add(item);
}
}
And to me the first way looks a bit smarter.
| [
"Java 7 might or might not implement closures and hence support functionality like this, but currently it doesn't, so on the Java VM you have the options to do it in Groovy, Scala or Clojure (possible others, too), but in java you can only get close to that by using helpers like Guava's Collections2.filter().\nJDK ... | [
5,
3,
1,
1,
0
] | [] | [] | [
"closures",
"collections",
"java",
"python"
] | stackoverflow_0003760120_closures_collections_java_python.txt |
Q:
How to stay under GAE quotas? Algorithm design
I have a function in my app that uses a lot of resources, and takes time to execute.
This is normal and control, however I often get errors due to GAE limit of 30 secs/request.
My function takes the argument and returns several results one after the other, decreasing the size of the argument (a unicode string)
Summary:
def my_function(arg):
while arg!=u''
#do_stuff
#get result
#arg=new_argument(arg,result)
As the process costs resources, I thought I could split it and enqueue it:
def my_function(arg):
if arg==u''
#stop
else:
do_stuff
get_result
enqueue(my_function(new_argument))
However I'm worried to fall under the API queue limit of 100k calls as I might have a lot of iterations.
I was thinking of redirecting request one to another, which would executes them in a row, but then I have no way to control resource usage:
def my_function(arg):
if arg==u''
#stop
else:
do_stuff
get_result
return redirect('/my_function_url',args=(new_argument))
I don't know if there's a beter way to do it?
A:
I would suggest that you use the Task Queue API, which is perfectly suited to this kind of problems.
Be aware that if you enable billing on your application, you automatically get much larger free quotas : the Task Queue API calls daily limit increases to 20,000,000.
You can set your max daily budget as low as $1 but you won't likely have to pay anything.
| How to stay under GAE quotas? Algorithm design | I have a function in my app that uses a lot of resources, and takes time to execute.
This is normal and control, however I often get errors due to GAE limit of 30 secs/request.
My function takes the argument and returns several results one after the other, decreasing the size of the argument (a unicode string)
Summary:
def my_function(arg):
while arg!=u''
#do_stuff
#get result
#arg=new_argument(arg,result)
As the process costs resources, I thought I could split it and enqueue it:
def my_function(arg):
if arg==u''
#stop
else:
do_stuff
get_result
enqueue(my_function(new_argument))
However I'm worried to fall under the API queue limit of 100k calls as I might have a lot of iterations.
I was thinking of redirecting request one to another, which would executes them in a row, but then I have no way to control resource usage:
def my_function(arg):
if arg==u''
#stop
else:
do_stuff
get_result
return redirect('/my_function_url',args=(new_argument))
I don't know if there's a beter way to do it?
| [
"I would suggest that you use the Task Queue API, which is perfectly suited to this kind of problems.\nBe aware that if you enable billing on your application, you automatically get much larger free quotas : the Task Queue API calls daily limit increases to 20,000,000.\nYou can set your max daily budget as low as $... | [
1
] | [] | [] | [
"algorithm",
"google_app_engine",
"python"
] | stackoverflow_0003759637_algorithm_google_app_engine_python.txt |
Q:
Create one keybord shortcut for 2 objects in PyQt
How can i create for "Ctrl+C" bindings for 2 objects: self.table, self.editor
I have:
shortcut = QtGui.QShortcut(QtGui.QKeySequence("Ctrl+C"), self.table, None, self.copyTable)
shortcut2 = QtGui.QShortcut(QtGui.QKeySequence("Ctrl+C"), self.editor, None, self.copyText)
This works, but is toogled. If i have focus on self.editor and for the first time i press "Ctrl+C it does self.copyTable, the second time is does self.copyText.
What am i doing wrong? :P
I did find a workaround where i create a QAction which checks which object has focus and triggers the wanted action. But i would rather have it per object.
Edit (a working example):
shortcut = QtGui.QShortcut(QtGui.QKeySequence("Ctrl+C"), self, self.copytoclipbord)
shortcut.setContext(QtCore.Qt.WidgetShortcut)
A:
You have to set the correct context for short cuts: by default they are window-"global", you probably want them to be widget-"local". See setShortcutContext.
A:
i did that already here and it worked fine ^_^. very simple idea .
just make one shortcut and one slot.
QtGui.QShortcut(QtGui.QKeySequence("Ctrl+C"), self, None, self.copyFunction)
and inside copyFunction check the focus , like so :
def copyFunction(self):
if self.table.hasFocus:
self.copyTable()
elif self.editor.hasFocus:
self.copyEditor()
| Create one keybord shortcut for 2 objects in PyQt | How can i create for "Ctrl+C" bindings for 2 objects: self.table, self.editor
I have:
shortcut = QtGui.QShortcut(QtGui.QKeySequence("Ctrl+C"), self.table, None, self.copyTable)
shortcut2 = QtGui.QShortcut(QtGui.QKeySequence("Ctrl+C"), self.editor, None, self.copyText)
This works, but is toogled. If i have focus on self.editor and for the first time i press "Ctrl+C it does self.copyTable, the second time is does self.copyText.
What am i doing wrong? :P
I did find a workaround where i create a QAction which checks which object has focus and triggers the wanted action. But i would rather have it per object.
Edit (a working example):
shortcut = QtGui.QShortcut(QtGui.QKeySequence("Ctrl+C"), self, self.copytoclipbord)
shortcut.setContext(QtCore.Qt.WidgetShortcut)
| [
"You have to set the correct context for short cuts: by default they are window-\"global\", you probably want them to be widget-\"local\". See setShortcutContext.\n",
"i did that already here and it worked fine ^_^. very simple idea .\n\njust make one shortcut and one slot.\n\nQtGui.QShortcut(QtGui.QKeySequence(... | [
3,
3
] | [] | [] | [
"pyqt",
"python"
] | stackoverflow_0003724697_pyqt_python.txt |
Q:
Python not recognising directories os.path.isdir()
I have the following Python code to remove files in a directory.
For some reason my .svn directories are not being recognised as directories.
And I get the following output:
.svn not a dir
Any ideas would be appreciated.
def rmfiles(path, pattern):
pattern = re.compile(pattern)
for each in os.listdir(path):
if os.path.isdir(each) != True:
print(each + " not a dir")
if pattern.search(each):
name = os.path.join(path, each)
os.remove(name)
A:
You need to create the full path name before checking:
if not os.path.isdir(os.path.join(path, each)):
...
A:
You will need to os.path.join the path you invoke listdir on with the found file/directory, i.e.
for each in os.listdir(path):
if os.path.isdir(os.path.join(path, each)):
....
If you don't create an absolute path this way you will be testing against your current working directory in stead, which probably dioesn't have the svn directory.
Also, don't explicitly compare boolean values. Let if handle it as a boolean expression (some functions may return non True/False truth values, i.e. None or an instance)
A:
You could also switch to the target directory instead of constructing an absolute path.
def rmfiles(path, pattern):
pattern = re.compile(pattern)
oldpath = os.getcwd() # <--
os.chdir(path) # <--
try:
for each in os.listdir('.'):
if os.path.isdir(each) != True:
print(each + " not a dir")
if pattern.search(each):
name = os.path.join(path, each)
os.remove(name)
finally:
os.chdir(oldpath) # <--
| Python not recognising directories os.path.isdir() | I have the following Python code to remove files in a directory.
For some reason my .svn directories are not being recognised as directories.
And I get the following output:
.svn not a dir
Any ideas would be appreciated.
def rmfiles(path, pattern):
pattern = re.compile(pattern)
for each in os.listdir(path):
if os.path.isdir(each) != True:
print(each + " not a dir")
if pattern.search(each):
name = os.path.join(path, each)
os.remove(name)
| [
"You need to create the full path name before checking:\nif not os.path.isdir(os.path.join(path, each)):\n ...\n\n",
"You will need to os.path.join the path you invoke listdir on with the found file/directory, i.e.\nfor each in os.listdir(path):\n if os.path.isdir(os.path.join(path, each)):\n ....\n\nI... | [
59,
3,
0
] | [] | [] | [
"directory",
"file_io",
"path",
"python"
] | stackoverflow_0003761473_directory_file_io_path_python.txt |
Q:
How to Compare 2 very large matrices using Python
I have an interesting problem.
I have a very large (larger than 300MB, more than 10,000,000 lines/rows in the file) CSV file with time series data points inside. Every month I get a new CSV file that is almost the same as the previous file, except for a few new lines have been added and/or removed and perhaps a couple of lines have been modified.
I want to use Python to compare the 2 files and identify which lines have been added, removed and modified.
The issue is that the file is very large, so I need a solution that can handle the large file size and execute efficiently within a reasonable time, the faster the better.
Example of what a file and its new file might look like:
Old file
A,2008-01-01,23
A,2008-02-01,45
B,2008-01-01,56
B,2008-02-01,60
C,2008-01-01,3
C,2008-02-01,7
C,2008-03-01,9
etc...
New file
A,2008-01-01,23
A,2008-02-01,45
A,2008-03-01,67 (added)
B,2008-01-01,56
B,2008-03-01,33 (removed and added)
C,2008-01-01,3
C,2008-02-01,7
C,2008-03-01,22 (modified)
etc...
Basically the 2 files can be seen as matrices that need to be compared, and I have begun thinking of using PyTable. Any ideas on how to solve this problem would be greatly appreciated.
A:
Like this.
Step 1. Sort.
Step 2. Read each file, doing line-by-line comparison. Write differences to another file.
You can easily write this yourself. Or you can use difflib. http://docs.python.org/library/difflib.html
Note that the general solution is quite slow as it searches for matching lines near a difference. Writing your own solution can run faster because you know things about how the files are supposed to match. You can optimize that "resynch-after-a-diff" algorithm.
And 10,000,000 lines hardly matters. It's not that big. Two 300Mb files easily fit into memory.
A:
This is a little bit of a naive implementation but will deal with unsorted data:
import csv
file1_dict = {}
file2_dict = {}
with open('file1.csv') as handle:
for row in csv.reader(handle):
file1_dict[tuple(row[:2])] = row[2:]
with open('file2.csv') as handle:
for row in csv.reader(handle):
file2_dict[tuple(row[:2])] = row[2:]
with open('outfile.csv', 'w') as handle:
writer = csv.writer(handle)
for key, val in file1_dict.iteritems():
if key in file2_dict:
#deal with keys that are in both
if file2_dict[key] == val:
writer.writerow(key+val+('Same',))
else:
writer.writerow(key+file2_dict[key]+('Modified',))
file2_dict.pop(key)
else:
writer.writerow(key+val+('Removed',))
#deal with added keys!
for key, val in file2_dict.iteritems():
writer.writerow(key+val+('Added',))
You probably won't be able to "drop in" this solution but it should get you ~95% of the way there. @S.Lott is right, 2 300mb files will easily fit in memory ... if your files get into the 1-2gb range then this may have to be modified with the assumption of sorted data.
Something like this is close ... although you may have to change the comparisons around for the added a modified to make sense:
#assumming both files are sorted by columns 1 and 2
import datetime
from itertools import imap
def str2date(in):
return datetime.date(*map(int,in.split('-')))
def convert_tups(row):
key = (row[0], str2date(row[1]))
val = tuple(row[2:])
return key, val
with open('file1.csv') as handle1:
with open('file2.csv') as handle2:
with open('outfile.csv', 'w') as outhandle:
writer = csv.writer(outhandle)
gen1 = imap(convert_tups, csv.reader(handle1))
gen2 = imap(convert_tups, csv.reader(handle2))
gen2key, gen2val = gen2.next()
for gen1key, gen1val in gen1:
if gen1key == gen2key and gen1val == gen2val:
writer.writerow(gen1key+gen1val+('Same',))
gen2key, gen2val = gen2.next()
elif gen1key == gen2key and gen1val != gen2val:
writer.writerow(gen2key+gen2val+('Modified',))
gen2key, gen2val = gen2.next()
elif gen1key > gen2key:
while gen1key>gen2key:
writer.writerow(gen2key+gen2val+('Added',))
gen2key, gen2val = gen2.next()
else:
writer.writerow(gen1key+gen1val+('Removed',))
| How to Compare 2 very large matrices using Python | I have an interesting problem.
I have a very large (larger than 300MB, more than 10,000,000 lines/rows in the file) CSV file with time series data points inside. Every month I get a new CSV file that is almost the same as the previous file, except for a few new lines have been added and/or removed and perhaps a couple of lines have been modified.
I want to use Python to compare the 2 files and identify which lines have been added, removed and modified.
The issue is that the file is very large, so I need a solution that can handle the large file size and execute efficiently within a reasonable time, the faster the better.
Example of what a file and its new file might look like:
Old file
A,2008-01-01,23
A,2008-02-01,45
B,2008-01-01,56
B,2008-02-01,60
C,2008-01-01,3
C,2008-02-01,7
C,2008-03-01,9
etc...
New file
A,2008-01-01,23
A,2008-02-01,45
A,2008-03-01,67 (added)
B,2008-01-01,56
B,2008-03-01,33 (removed and added)
C,2008-01-01,3
C,2008-02-01,7
C,2008-03-01,22 (modified)
etc...
Basically the 2 files can be seen as matrices that need to be compared, and I have begun thinking of using PyTable. Any ideas on how to solve this problem would be greatly appreciated.
| [
"Like this.\nStep 1. Sort. \nStep 2. Read each file, doing line-by-line comparison. Write differences to another file.\nYou can easily write this yourself. Or you can use difflib. http://docs.python.org/library/difflib.html\nNote that the general solution is quite slow as it searches for matching lines near a... | [
4,
1
] | [] | [] | [
"data_structures",
"django",
"matrix",
"python"
] | stackoverflow_0003760615_data_structures_django_matrix_python.txt |
Q:
Problem Accessing WSDL-Service with python suds raises TypeNotFound: ArrayOfint
Type not found: '(ArrayOfint, http://schemas.microsoft.com/2003/10/Serialization/Arrays, )'
is what suds resolver raises.
In ...2003/10/Serialization/Arrays ArrayOfInt is defined, so I guess linux' case sensitivity is the problem.
Any Idea how I can get around that?
from suds.client import Client
c = Client("https://developer-api.affili.net/V2.0/Logon.svc?wsdl")
used to return
Type not found: '(ArrayOfint, http://schemas.microsoft.com/2003/10/Serialization/Arrays, )'
now since a few days I don't even get there anymore but instead I get a
TypeNotFound: Type not found: '(Logon, http://affilinet.framework.webservices/types, )'
A:
Sounds like you have a broken WSDL. This is where you'll need to use the ImportDoctor provided by SUDS. You need use this to help the Client constructor use the ArrayOfint type found at http://schemas.microsoft.com/2003/10/Serialization/Arrays.
I have done this in the past with other services but without seeing your WSDL or your code, this is only my best guess as to how you may fix it because I can't test it myself:
from suds.client import Client
from suds.xsd.doctor import Import, ImportDoctor
# Obviously I made this up
wsdl_url = 'http://whatever/path/to/wsdl'
# Fix missing types with ImportDoctor
schema_url = 'http://schemas.microsoft.com/2003/10/Serialization/Arrays'
schema_import = Import(schema_url)
schema_doctor = ImportDoctor(schema_import)
# Pass doctor to Client
client = Client(url=wsdl_url, doctor=schema_doctor)
One thing worth noting is that the URL http://schemas.microsoft.com/2003/10/Serialization/Arrays is not even valid (it returns a 404), so I am really not sure that is the right URL. Although I am confident that I am at least steering you in the right direction.
Edit in response to your recent comment (2010-10-05):
Using the URL you provided of https://developer-api.affili.net/V2.0/Logon.svc?wsdl I was able to successfully create a client. I had to use an ImportDoctor because it raised the following error:
TypeNotFound: Type not found: '(Logon, http://affilinet.framework.webservices/types, )'
So I used the following code and was able to get a successful client object:
from suds.client import Client
from suds.xsd.doctor import Import, ImportDoctor
wsdl_url = 'https://developer-api.affili.net/V2.0/Logon.svc?wsdl'
schema_url = 'http://affilinet.framework.webservices/types'
schema_import = Import(schema_url)
schema_doctor = ImportDoctor(schema_import)
client = Client(url=wsdl_url, doctor=schema_doctor)
Printing the client object displays this:
Suds ( https://fedorahosted.org/suds/ ) version: 0.3.9 GA build: R659-20100219
Service ( Authentication ) tns="http://affilinet.framework.webservices/Svc"
Prefixes (5)
ns0 = "http://affilinet.framework.webservices/types"
ns1 = "http://schemas.datacontract.org/2004/07/Microsoft.Practices.EnterpriseLibrary.Validation.Integration.WCF"
ns2 = "http://schemas.microsoft.com/2003/10/Serialization/"
ns3 = "http://schemas.microsoft.com/2003/10/Serialization/Arrays"
ns4 = "http://www.microsoft.com/practices/EnterpriseLibrary/2007/01/wcf/validation"
Ports (1):
(DefaultEndpointLogon)
Methods (2):
GetIdentifierExpiration(xs:string CredentialToken, )
Logon(xs:string Username, xs:string Password, ns0:WebServiceTypes WebServiceType, ns0:TokenDeveloperDetails DeveloperSettings, ns0:TokenApplicationDetails ApplicationSettings, )
Types (12):
ns3:ArrayOfKeyValueOfstringstring
ns1:ArrayOfValidationDetail
ns0:Logon
ns0:TokenApplicationDetails
ns0:TokenDeveloperDetails
ns1:ValidationDetail
ns4:ValidationFault
ns0:WebServiceTypes
ns0:affilinetWebserviceFault
ns2:char
ns2:duration
ns2:guid
Before you can use client.service.Logon() you're going to have to satisfy the type signature required by that method. You'll have to create various type objects using client.factory.create() (e.g. client.factory.create('ns0:WebServiceTypes')) and pass those objects along with your username/password.
| Problem Accessing WSDL-Service with python suds raises TypeNotFound: ArrayOfint | Type not found: '(ArrayOfint, http://schemas.microsoft.com/2003/10/Serialization/Arrays, )'
is what suds resolver raises.
In ...2003/10/Serialization/Arrays ArrayOfInt is defined, so I guess linux' case sensitivity is the problem.
Any Idea how I can get around that?
from suds.client import Client
c = Client("https://developer-api.affili.net/V2.0/Logon.svc?wsdl")
used to return
Type not found: '(ArrayOfint, http://schemas.microsoft.com/2003/10/Serialization/Arrays, )'
now since a few days I don't even get there anymore but instead I get a
TypeNotFound: Type not found: '(Logon, http://affilinet.framework.webservices/types, )'
| [
"Sounds like you have a broken WSDL. This is where you'll need to use the ImportDoctor provided by SUDS. You need use this to help the Client constructor use the ArrayOfint type found at http://schemas.microsoft.com/2003/10/Serialization/Arrays. \nI have done this in the past with other services but without seein... | [
6
] | [] | [] | [
"python",
"suds",
"wsdl"
] | stackoverflow_0003760427_python_suds_wsdl.txt |
Q:
Python Music Library?
I'm looking at writing a little drum machine in Python for fun. I've googled some and found the python pages on music and basic audio as well as a StackOverflow question on generating audio files, but what I'm looking for is a decent library for music creation. Has anyone on here tried to do something like this before? If so, what was your solution? What, either of the ones I've found, or something I haven't found, would be a decent library for audio manipulation?
Minimally, I'd like to be able to do something similar to Audacity's scope within python, but if anyone knows of a library that can do more... I'm all ears.
A:
Take a close look at cSounds. There are Python bindings allow you to do pretty flexible digital synthesis. There are some pretty complete packages available, too.
See http://www.csounds.com/node/188 for a package.
See http://www.csounds.com/journal/issue6/pythonOpcodes.html for information on Python scripting within cSounds.
A:
I had to do this years ago. I used pymedia. I am not sure if it is still around any way here is some test code I wrote when I was playing with it. It is about 3 years old though.
Edit: The sample code plays an MP3 file
import pymedia
import time
demuxer = pymedia.muxer.Demuxer('mp3') #this thing decodes the multipart file i call it a demucker
f = open(r"path to \song.mp3", 'rb')
spot = f.read()
frames = demuxer.parse(spot)
print 'read it has %i frames' % len(frames)
decoder = pymedia.audio.acodec.Decoder(demuxer.streams[0]) #this thing does the actual decoding
frame = decoder.decode(spot)
print dir(frame)
#sys.exit(1)
sound = pymedia.audio.sound
print frame.bitrate, frame.sample_rate
song = sound.Output( frame.sample_rate, frame.channels, 16 ) #this thing handles playing the song
while len(spot) > 0:
try:
if frame: song.play(frame.data)
spot = f.read(512)
frame = decoder.decode(spot)
except:
pass
while song.isPlaying(): time.sleep(.05)
print 'well done'
A:
There is a variety of Python music software, you can find a catalog here.
If you scroll down the linked page, you find a section on Music Programming in Python describing several music creation packages including MusicKit and PySndObj.
A:
Also check out http://code.google.com/p/pyo/
A:
In addition to what has been mentioned previously, I wrote a simple Python audio editor.
http://code.google.com/p/yaalp/source/browse/#svn/trunk
See main.py.
It also has audio manipulation and some effects.
Code's GPL, so this could be a starting point for you.
| Python Music Library? | I'm looking at writing a little drum machine in Python for fun. I've googled some and found the python pages on music and basic audio as well as a StackOverflow question on generating audio files, but what I'm looking for is a decent library for music creation. Has anyone on here tried to do something like this before? If so, what was your solution? What, either of the ones I've found, or something I haven't found, would be a decent library for audio manipulation?
Minimally, I'd like to be able to do something similar to Audacity's scope within python, but if anyone knows of a library that can do more... I'm all ears.
| [
"Take a close look at cSounds. There are Python bindings allow you to do pretty flexible digital synthesis. There are some pretty complete packages available, too. \nSee http://www.csounds.com/node/188 for a package.\nSee http://www.csounds.com/journal/issue6/pythonOpcodes.html for information on Python scriptin... | [
14,
8,
4,
3,
2
] | [] | [] | [
"audio",
"python"
] | stackoverflow_0000108848_audio_python.txt |
Q:
Using PayPal with AppEngine (Python)
I'm looking to use Google AppEngine (Python). The Tipfy framework looks very good. How do I add PayPal and/or Google Web Payments into my app.
Is there a simple extension or similar that I can drop in?
A:
Here's the blog entry where they introduce the PayPal X toolkit for GAE/J:
Wednesday, June 30, 2010
PayPal introduces PayPal X Platform Toolkit for Google App Engine
http://googleappengine.blogspot.com/2010/06/paypal-introduces-paypal-x-platform.html
In that article it says that they are working on the Python version.
If you have the flexibility you could wait for this official support, otherwise check one of the older stackoverflow topics on this issue where they discuss unofficial solutions.
| Using PayPal with AppEngine (Python) | I'm looking to use Google AppEngine (Python). The Tipfy framework looks very good. How do I add PayPal and/or Google Web Payments into my app.
Is there a simple extension or similar that I can drop in?
| [
"Here's the blog entry where they introduce the PayPal X toolkit for GAE/J:\nWednesday, June 30, 2010\nPayPal introduces PayPal X Platform Toolkit for Google App Engine\nhttp://googleappengine.blogspot.com/2010/06/paypal-introduces-paypal-x-platform.html\nIn that article it says that they are working on the Python ... | [
2
] | [] | [] | [
"google_app_engine",
"paypal_ipn",
"python",
"tipfy"
] | stackoverflow_0003758827_google_app_engine_paypal_ipn_python_tipfy.txt |
Q:
Wrap std::vector of std::vectors, C++ SWIG Python
I want to wrap a C++ vector of vectors to Python code by using SWIG.
Is it possible to wrap this type of vector of vectors?
std::vector<std::vector<MyClass*>>;
In the interface file MyApplication.i I added these lines:
%include "std_vector.i"
%{
#include <vector>
%}
namespace std {
%template(VectorOfStructVector) vector<vector<MyClass*>>;
}
But, I'm getting an Error when SWIG is executed. I'm able to wrap this type (using reference to the vector):
std::vector<std::vector<MyClass*>*>;
But, it's not working properly, I cannot access the items. That's why I'm interested in this type (without the reference):
std::vector<std::vector<MyClass*>>;
Any ideas?
A:
Is it a C++ parsing issue?
std::vector<std::vector<MyClass*> >;
---Important space---------------^
| Wrap std::vector of std::vectors, C++ SWIG Python | I want to wrap a C++ vector of vectors to Python code by using SWIG.
Is it possible to wrap this type of vector of vectors?
std::vector<std::vector<MyClass*>>;
In the interface file MyApplication.i I added these lines:
%include "std_vector.i"
%{
#include <vector>
%}
namespace std {
%template(VectorOfStructVector) vector<vector<MyClass*>>;
}
But, I'm getting an Error when SWIG is executed. I'm able to wrap this type (using reference to the vector):
std::vector<std::vector<MyClass*>*>;
But, it's not working properly, I cannot access the items. That's why I'm interested in this type (without the reference):
std::vector<std::vector<MyClass*>>;
Any ideas?
| [
"Is it a C++ parsing issue?\n std::vector<std::vector<MyClass*> >;\n ---Important space---------------^\n\n"
] | [
4
] | [] | [] | [
"c++",
"python",
"swig",
"vector"
] | stackoverflow_0003761861_c++_python_swig_vector.txt |
Q:
Passing data from a virtual printer to python
I am trying to make a thing where in other applications you can print to a certain printer and python will get the data. How would I go about making this? It would have to work in all applications, so it would appear as a normal printer, and work on Linux and Windows, even if I have to rewrite it for both.
So to recap: One opens a program and hits the print button. It brings up the printer dialogue and they select the python printer, like any other printer. After they accept, the python program which loaded the module (this will probably be a module) gets the data that the other application printed.
A:
Most Linux distros (and OS X) and use CUPS to do printing these days. A CUPS backends for a specific printer is ultimately just an executable, which you can make do anything you want. The CUPS project provides filter/backend API documentation. There also exists at least one open-source CUPS virtual printer in the form of CUPS-PDF, which might make for a useful example to consult.
On the Windows side I'm afraid I can't help you.
| Passing data from a virtual printer to python | I am trying to make a thing where in other applications you can print to a certain printer and python will get the data. How would I go about making this? It would have to work in all applications, so it would appear as a normal printer, and work on Linux and Windows, even if I have to rewrite it for both.
So to recap: One opens a program and hits the print button. It brings up the printer dialogue and they select the python printer, like any other printer. After they accept, the python program which loaded the module (this will probably be a module) gets the data that the other application printed.
| [
"Most Linux distros (and OS X) and use CUPS to do printing these days. A CUPS backends for a specific printer is ultimately just an executable, which you can make do anything you want. The CUPS project provides filter/backend API documentation. There also exists at least one open-source CUPS virtual printer in th... | [
2
] | [] | [] | [
"printing",
"python",
"virtual"
] | stackoverflow_0003761865_printing_python_virtual.txt |
Q:
Understanding python variable scope within class
I am trying to define a variable in a class that then can be accessed/changed from functions within that class.
For example:
class MyFunctions():
def __init__( self):
self.listOfItems = []
def displayList( self):
"""Prints all items in listOfItems)"""
for item in self.listOfItems:
print item
def addToList(self):
"""Updates all mlb scores, and places results in a variable."""
self.listOfItems.append("test")
f = MyFunctions()
f.addToList
f.displayList
This should output all of the items in the list for me, but instead it displays nothing. I am assuming this is occuring because I did not setup the scope of the variables correctly. I want to be able to access and change listOfItems from within all of the functions in MyFuctions.
I have been trying to figure this out for a few hours now, so any help would be greatly appreciated.
A:
f.addToList and f.displayList do not invoke the methods addToList and displayList respectively. They simply evaluate to the method (bound to the object f in this case) themselves. Add parentheses to invoke the methods as in the corrected version of the program:
class MyFunctions():
def __init__( self):
self.listOfItems = []
def displayList( self):
"""Prints all items in listOfItems)"""
for item in self.listOfItems:
print item
def addToList(self):
"""Updates all mlb scores, and places results in a variable."""
self.listOfItems.append("test")
f = MyFunctions()
f.addToList()
f.displayList()
This is in contrast to Ruby which does not require parentheses for method invocation (except to eliminate ambiguity in certain cases).
It is instructive to add the following to the end of your program:
print type(f.addToList)
This will output something like the following:
<type 'instancemethod'>
demonstrating that this is a method reference and not a method invocation.
| Understanding python variable scope within class | I am trying to define a variable in a class that then can be accessed/changed from functions within that class.
For example:
class MyFunctions():
def __init__( self):
self.listOfItems = []
def displayList( self):
"""Prints all items in listOfItems)"""
for item in self.listOfItems:
print item
def addToList(self):
"""Updates all mlb scores, and places results in a variable."""
self.listOfItems.append("test")
f = MyFunctions()
f.addToList
f.displayList
This should output all of the items in the list for me, but instead it displays nothing. I am assuming this is occuring because I did not setup the scope of the variables correctly. I want to be able to access and change listOfItems from within all of the functions in MyFuctions.
I have been trying to figure this out for a few hours now, so any help would be greatly appreciated.
| [
"f.addToList and f.displayList do not invoke the methods addToList and displayList respectively. They simply evaluate to the method (bound to the object f in this case) themselves. Add parentheses to invoke the methods as in the corrected version of the program:\nclass MyFunctions():\n def __init__( self):\n ... | [
6
] | [] | [] | [
"call",
"methods",
"python",
"syntax"
] | stackoverflow_0003762197_call_methods_python_syntax.txt |
Q:
Checking Version of Python Interpreter Upon Execution of Script With Invalid Syntax
I have a Python script that uses Python version 2.6 syntax (Except error as value:) which version 2.5 complains about. So in my script I have included some code to check for the Python interpreter version before proceeding so that the user doesn't get hit with a nasty error, however, no matter where I place that code, it doesn't work. Once it hits the strange syntax it throws the syntax error, disregarding any attempts of mine of version checking.
I know I could simply place a try/except block over the area that the SyntaxError occurs and generate the message there but I am wondering if there is a more "elegant" way. As I am not very keen on placing try/except blocks all over my code to address the version issue. I looked into using an __ init__.py file, but the user won't be importing/using my code as a package, so I don't think that route will work, unless I am missing something...
Here is my version checking code:
import sys
def isPythonVersion(version):
if float(sys.version[:3]) >= version:
return True
else:
return False
if not isPythonVersion(2.6):
print "You are running Python version", sys.version[:3], ", version 2.6 or 2.7 is required. Please update. Aborting..."
exit()
A:
Create a wrapper script that checks the version and calls your real script -- this gives you a chance to check the version before the interpreter tries to syntax-check the real script.
A:
Something like this in beginning of code?
import sys
if sys.version_info<(2,6):
raise SystemExit('Sorry, this code need Python 2.6 or higher')
A:
In sys.version_info you will find the version information stored in a tuple:
sys.version_info
(2, 6, 6, 'final', 0)
Now you can compare:
def isPythonVersion(version):
return version >= sys.version_info[0] + sys.version_info[1] / 10.
A:
If speed is not a priority, you can avoid this problem entirely by using sys.exc_info to grab the details of the last exception.
| Checking Version of Python Interpreter Upon Execution of Script With Invalid Syntax | I have a Python script that uses Python version 2.6 syntax (Except error as value:) which version 2.5 complains about. So in my script I have included some code to check for the Python interpreter version before proceeding so that the user doesn't get hit with a nasty error, however, no matter where I place that code, it doesn't work. Once it hits the strange syntax it throws the syntax error, disregarding any attempts of mine of version checking.
I know I could simply place a try/except block over the area that the SyntaxError occurs and generate the message there but I am wondering if there is a more "elegant" way. As I am not very keen on placing try/except blocks all over my code to address the version issue. I looked into using an __ init__.py file, but the user won't be importing/using my code as a package, so I don't think that route will work, unless I am missing something...
Here is my version checking code:
import sys
def isPythonVersion(version):
if float(sys.version[:3]) >= version:
return True
else:
return False
if not isPythonVersion(2.6):
print "You are running Python version", sys.version[:3], ", version 2.6 or 2.7 is required. Please update. Aborting..."
exit()
| [
"Create a wrapper script that checks the version and calls your real script -- this gives you a chance to check the version before the interpreter tries to syntax-check the real script.\n",
"Something like this in beginning of code?\nimport sys\nif sys.version_info<(2,6):\n raise SystemExit('Sorry, this code n... | [
15,
15,
9,
1
] | [] | [] | [
"interpreter",
"python"
] | stackoverflow_0003760098_interpreter_python.txt |
Q:
SWIG - Problem with namespaces
I'm having trouble getting the following simple example to work with SWIG 1.3.40 (and I also tried 1.3.31). The Foo structure comes through as a Python module as long as I don't wrap it in a namespace, but as soon as I do I get a compilation error in the generated test_wrap.c.
test.h:
#ifndef __TEST_H__
#define __TEST_H__
#define USE_NS 1
#if USE_NS
namespace ns {
#endif
struct Foo {
float a;
float b;
float func();
};
#if USE_NS
}
#endif
#endif
test.cpp
#include "test.h"
#if USE_NS
namespace ns {
#endif
float Foo::func()
{
return a;
}
#if USE_NS
}
#endif
test.i
%module test
%{
#include "test.h"
%}
%include "test.h"
I run the following commands for building a bundle on OSX 10.6.3:
swig -python test.i
g++ -c -m64 -fPIC test.cpp
g++ -c -m64 -fPIC -I/usr/local/include -I/opt/local/include -I/opt/local/Library/Frameworks/Python.framework/Headers test_wrap.c
g++ -o _test.so -bundle -flat_namespace -undefined suppress test_wrap.o test.o -L/usr/local/lib -L/opt/local/lib -lpython2.6
This works, but only if I take out the namespace. I though SWIG handled namespaces automatically in simple cases like this. What am I doing wrong?
This is the error that I get - it looks like SWIG references a 'ns' and a 'namespace' symbol which are undefined.
test_wrap.c: In function ‘int Swig_var_ns_set(PyObject*)’:
test_wrap.c:2721: error: expected primary-expression before ‘=’ token
test_wrap.c:2721: error: expected primary-expression before ‘namespace’
test_wrap.c:2721: error: expected `)' before ‘namespace’
test_wrap.c:2721: error: expected `)' before ‘;’ token
test_wrap.c: In function ‘PyObject* Swig_var_ns_get()’:
test_wrap.c:2733: error: expected primary-expression before ‘void’
test_wrap.c:2733: error: expected `)' before ‘void’
A:
In your test.i file, add a "using namespace ns" line after the #include. Without that, your swig wrapper code won't know to look for Foo in the "ns" namespace.
| SWIG - Problem with namespaces | I'm having trouble getting the following simple example to work with SWIG 1.3.40 (and I also tried 1.3.31). The Foo structure comes through as a Python module as long as I don't wrap it in a namespace, but as soon as I do I get a compilation error in the generated test_wrap.c.
test.h:
#ifndef __TEST_H__
#define __TEST_H__
#define USE_NS 1
#if USE_NS
namespace ns {
#endif
struct Foo {
float a;
float b;
float func();
};
#if USE_NS
}
#endif
#endif
test.cpp
#include "test.h"
#if USE_NS
namespace ns {
#endif
float Foo::func()
{
return a;
}
#if USE_NS
}
#endif
test.i
%module test
%{
#include "test.h"
%}
%include "test.h"
I run the following commands for building a bundle on OSX 10.6.3:
swig -python test.i
g++ -c -m64 -fPIC test.cpp
g++ -c -m64 -fPIC -I/usr/local/include -I/opt/local/include -I/opt/local/Library/Frameworks/Python.framework/Headers test_wrap.c
g++ -o _test.so -bundle -flat_namespace -undefined suppress test_wrap.o test.o -L/usr/local/lib -L/opt/local/lib -lpython2.6
This works, but only if I take out the namespace. I though SWIG handled namespaces automatically in simple cases like this. What am I doing wrong?
This is the error that I get - it looks like SWIG references a 'ns' and a 'namespace' symbol which are undefined.
test_wrap.c: In function ‘int Swig_var_ns_set(PyObject*)’:
test_wrap.c:2721: error: expected primary-expression before ‘=’ token
test_wrap.c:2721: error: expected primary-expression before ‘namespace’
test_wrap.c:2721: error: expected `)' before ‘namespace’
test_wrap.c:2721: error: expected `)' before ‘;’ token
test_wrap.c: In function ‘PyObject* Swig_var_ns_get()’:
test_wrap.c:2733: error: expected primary-expression before ‘void’
test_wrap.c:2733: error: expected `)' before ‘void’
| [
"In your test.i file, add a \"using namespace ns\" line after the #include. Without that, your swig wrapper code won't know to look for Foo in the \"ns\" namespace.\n"
] | [
18
] | [] | [] | [
"c++",
"macos",
"namespaces",
"python",
"swig"
] | stackoverflow_0003696084_c++_macos_namespaces_python_swig.txt |
Q:
How's Python GUI development today (Sep/2010)?
Last time I saw, GUIs in Python were extremely ugly, how's it today?
(saw some beautiful images on google images, but I don't know if are really Python's)
A:
Python 2.7 and 3.0 ships with the themed tk ("ttk") widgets which look much better than previous versions of Tk (though, honestly, any competent GUI developer can make even older Tk look good). Don't let the people who don't know much about Tk sway you from using it, it's still a very viable toolkit for many, many tasks. You won't be creating a Photoshop clone with it, but how many people write those kinds of apps anyway?
I've been using wxPython for the past year and would still choose Tkinter over it for most tasks. Tkinter is much simpler and in many respects more powerful. The only advantage wxWidgets has is that it has more built-in widgets, but I find many of them a bit buggy and hard to use. For most apps that most people will write, Tkinter is still an excellent choice.
Some screenshots of themed widgets are available here:
http://code.google.com/p/python-ttk/wiki/Screenshots
Here's a screenshot of a Tkinter app that uses the themed widgets on the Mac:
http://www.codebykevin.com/phynchronicity-running.png
A:
Tk is sill is the default GUI toolkit for Python, but it has a theme support from Python 2.7/3.1. It is not as ugly as before.
However, you can use some nice alternatives which still look better (IMHO) and have more functionalities :
wxPython : maybe the most used, cross platform and all, your applications will look the same as native.
PyQt or soon PySide : bindings for the Nokia Qt open source framework. There is more than just a GUI toolkit.
PyGTK : bindings for the GTK+ libraries
Here is more info : http://wiki.python.org/moin/GuiProgramming
A:
Python has bindings for Tk, Qt, GTK, wx, and many more. There's no reason it should be any uglier than another language. You're probably thinking of a gui made with Tk, which has a reputation of being ugly. It's not specific to python, but it might be more common because it's very simple and ships with python by default.
See Gui Programming on the python wiki for more info.
A:
I Think the latest Tkinter version offers native look for Macos. WxPython and QT offers native look for macos,windows and linux. GTK is abit ugly and prone to crashes on mac cause of the X11 implentation there.
Of course you could build your own GUI , that something I am trying to do with pygame.Let me clarify , I am not making a GUI library just GUI for my own application. I am making the graphics in the 3d app Blender.
My vote for Generic GUI goes to wxPython, tried it, looks great, easy to use and works like a charm across platforms. You will also find tons of info about it. Integrates well with opengl so if you want to do extreme guis on it , it can do them.
| How's Python GUI development today (Sep/2010)? | Last time I saw, GUIs in Python were extremely ugly, how's it today?
(saw some beautiful images on google images, but I don't know if are really Python's)
| [
"Python 2.7 and 3.0 ships with the themed tk (\"ttk\") widgets which look much better than previous versions of Tk (though, honestly, any competent GUI developer can make even older Tk look good). Don't let the people who don't know much about Tk sway you from using it, it's still a very viable toolkit for many, ma... | [
7,
2,
1,
1
] | [] | [] | [
"python",
"user_interface"
] | stackoverflow_0003760714_python_user_interface.txt |
Q:
How do I find out the Python, Django versions and path that a Django site is running?
I currently have multiple Django sites running from one Apache server through WSGI and each site has their own virtualenv with possibly slight Python and Django version difference. For each site, I want to display the Python and Django version it is using as well as from which path it's pulling the Python binaries from.
For each Django site, I can do:
import sys
sys.version
but I'm not sure if it's showing the Python that the site is using or the system's Python. Any help on that?
A:
but I'm not sure if it's showing the Python that the site is using or the system's Python. Any help on that?
Nope.
However, if you want to know something about your Django app, do this.
Use logging. Write to sys.stderr that's usually routed to errors_log by mod_wsgi. Or look inside the request for the wsgi.errors file.
Update your top-level urls.py to write a startup message, including sys.version to your log.
A:
To find out which Python is being used, log the value of sys.executable. It should contain the path to the interpreter being used.
A:
This is a bit more than what you asked for, but we have a similar situation where different directories are (possibly) using different Python/Django code. We use following to build an easy to look at list (at least for me) of Python & Django versions plus all modules and where they were loaded from. It has sometimes helped save what little there is left of my hair. Modify to taste.
import sys, re, os
import django
def ModuleList():
ret = []
# The double call to dirname() is because this file is in our utils/
# directory, which is one level down from the top of the project.
dir_project = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
project_name = os.path.basename(dir_project)
for k,v in sys.modules.items():
x = str(v)
if 'built-in' in x:
ret.append((k, 'built-in'))
continue
m = re.search(r"^.*?'(?P<module>.*?)' from '(?P<file>.*?)'.*$", x)
if m:
d = m.groupdict()
f = d['file']
# You can skip all of the re.sub()'s if you want raw paths
f = re.sub(r'/usr/.*?/lib/python[.0-9]*/site-packages/django/', 'system django >> ', f)
f = re.sub(r'/usr/.*?/lib/python[.0-9]*/site-packages/', 'site-packages >> ', f)
f = re.sub(r'/usr/.*?/lib/python[.0-9]*/', 'system python >> ', f)
f = re.sub(dir_project+'.*python/', 'local python >> ', f)
f = re.sub(dir_project+'.*django/', 'local django >> ', f)
f = re.sub(dir_project+r'(/\.\./)?', project_name + ' >> ', f)
ret.append((d['module'], f))
ret.sort( lambda a,b: cmp(a[0].lower(), b[0].lower()) )
ret.insert(0, ('Python version', sys.version) )
ret.insert(0, ('Django version', django.get_version()) )
return ret
# ModuleList
| How do I find out the Python, Django versions and path that a Django site is running? | I currently have multiple Django sites running from one Apache server through WSGI and each site has their own virtualenv with possibly slight Python and Django version difference. For each site, I want to display the Python and Django version it is using as well as from which path it's pulling the Python binaries from.
For each Django site, I can do:
import sys
sys.version
but I'm not sure if it's showing the Python that the site is using or the system's Python. Any help on that?
| [
"\nbut I'm not sure if it's showing the Python that the site is using or the system's Python. Any help on that?\n\nNope.\nHowever, if you want to know something about your Django app, do this.\n\nUse logging. Write to sys.stderr that's usually routed to errors_log by mod_wsgi. Or look inside the request for the w... | [
0,
0,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0003761681_django_python.txt |
Q:
Python daemon will not run in the background on Ubuntu
My Python daemon runs fine in the foreground of my Ubuntu system using this command in the terminal:
python /opt/my-daemon.py foreground
However when I try to call the daemon using the "start" command it fails, why?
python /opt/my-daemon.py start
This is how I call the command in the /etc/rc.local file:
python /opt/my-daemon.py start &
Herewith the code:
1.daemon.py
#!/usr/bin/env python
import sys, os, time, atexit
from signal import SIGTERM
class Daemon:
"""
A generic daemon class.
Usage: subclass the Daemon class and override the run() method
"""
def __init__(self, pidfile,
stdin='/dev/null',stdout='/dev/null',stderr='/dev/null'):
self.stdin = stdin
self.stdout = stdout
self.stderr = stderr
self.pidfile = pidfile
def daemonize(self):
"""
Do the UNIX double-fork magic. See Richard Stevens' "Advanced
Programming in the UNIX Environment" for details (ISBN 0201563177)
http://www.erlenstar.demon.co.uk/unix/faq_2.html#SEC16
"""
try:
pid = os.fork()
if pid > 0:
# exit first parent
sys.exit(0)
except OSError, e:
sys.stderr.write("fork #1 failed: %d (%s)\n" % (e.errno,
e.strerror))
sys.exit(1)
# Decouple from parent environment
os.chdir("/")
os.setsid()
os.umask(0)
# Do second fork
try:
pid = os.fork()
if pid > 0:
# Exit from second parent
sys.exit(0)
except OSError, e:
sys.stderr.write("fork #2 failed: %d (%s)\n" % (e.errno, e.strerror))
sys.exit(1)
# Redirect standard file descriptors
sys.stdout.flush()
sys.stderr.flush()
si = file(self.stdin, 'r')
so = file(self.stdout, 'a+')
se = file(self.stderr, 'a+', 0)
os.dup2(si.fileno(), sys.stdin.fileno())
os.dup2(so.fileno(), sys.stdout.fileno())
os.dup2(se.fileno(), sys.stderr.fileno())
# Write pidfile
atexit.register(self.delpid)
pid = str(os.getpid())
file(self.pidfile,'w+').write("%s\n" % pid)
def delpid(self):
os.remove(self.pidfile)
def start(self):
"""
Start the daemon
"""
# Check for a pidfile to see if the daemon already runs
try:
pf = file(self.pidfile,'r')
pid = int(pf.read().strip())
pf.close()
except IOError:
pid = None
if pid:
message = "pidfile %s already exist. Daemon already running?\n"
sys.stderr.write(message % self.pidfile)
sys.exit(1)
# Start the daemon
self.daemonize()
self.run()
def stop(self):
"""
Stop the daemon
"""
# Get the pid from the pidfile
try:
pf = file(self.pidfile,'r')
pid = int(pf.read().strip())
pf.close()
except IOError:
pid = None
if not pid:
message = "pidfile %s does not exist. Daemon not running?\n"
sys.stderr.write(message % self.pidfile)
return # not an error in a restart
# Try killing the daemon process
try:
while 1:
os.kill(pid, SIGTERM)
time.sleep(0.1)
except OSError, err:
err = str(err)
if err.find("No such process") > 0:
if os.path.exists(self.pidfile):
os.remove(self.pidfile)
else:
print str(err)
sys.exit(1)
def restart(self):
"""
Restart the daemon
"""
self.stop()
self.start()
def run(self):
"""
You should override this method when you subclass Daemon. It will be called after the process has been
daemonized by start() or restart().
"""
2.my-daemon.py
import sys, time
from daemon import Daemon
import MySQLdb #MySQL libraries
#Database parameters
config = {"host":"localhost",...}
try:
conn = MySQLdb.connect(config['host'],...
class MyDaemon(Daemon):
def run(self):
while True:
time.sleep(2)
#{Do processes, connect to the database, etc....}
...
if __name__ == "__main__":
daemon = MyDaemon('/tmp/daemon-example.pid')
if len(sys.argv) == 2:
if 'start' == sys.argv[1]:
daemon.start()
elif 'stop' == sys.argv[1]:
daemon.stop()
elif 'restart' == sys.argv[1]:
daemon.restart()
elif 'foreground' == sys.argv[1]: #This runs the daemon in the foreground
daemon.run()
else:
print "Unknown command"
sys.exit(2)
sys.exit(0)
else:
print "usage: %s start|foreground|stop|restart" % sys.argv[0]
sys.exit(2)
A:
SOLVED. I was under the impression that the foreground and the start parameter was two different things. It turns out I just needed to do the following.
def run(self):
while True:
time.sleep(2)
to
def start(self):
while True:
time.sleep(2)
I then removed the foreground parameter, because I can run the script from the terminal using the start command to see the output in the foreground.
python /opt/my-daemon.py start
Also, in rc.local I start the script as follows:
python /opt/my-daemon.py start &
This hides the daemon process and executes the script on startup regardless of the user who logs in :)
A:
Instead of using daemon.py, you may want to consider leveraging Ubuntu's Upstart system which provides an easy way to set up a respawning daemon. From the same link, it features:
* Services may be respawned if they die unexpectedly
* Supervision and respawning of daemons which separate from their parent process
If you are using Ubuntu9.10 or later, take a look at /etc/init/cron.conf as an example. For earlier versions of Ubuntu, I believe the upstart scripts are located in /etc/event.d/.
For an explanation of Upstart keywords, see here.
A:
You may try this http://gunslingerc0de.wordpress.com/2010/03/02/forking-daemon-process-in-unix/
| Python daemon will not run in the background on Ubuntu | My Python daemon runs fine in the foreground of my Ubuntu system using this command in the terminal:
python /opt/my-daemon.py foreground
However when I try to call the daemon using the "start" command it fails, why?
python /opt/my-daemon.py start
This is how I call the command in the /etc/rc.local file:
python /opt/my-daemon.py start &
Herewith the code:
1.daemon.py
#!/usr/bin/env python
import sys, os, time, atexit
from signal import SIGTERM
class Daemon:
"""
A generic daemon class.
Usage: subclass the Daemon class and override the run() method
"""
def __init__(self, pidfile,
stdin='/dev/null',stdout='/dev/null',stderr='/dev/null'):
self.stdin = stdin
self.stdout = stdout
self.stderr = stderr
self.pidfile = pidfile
def daemonize(self):
"""
Do the UNIX double-fork magic. See Richard Stevens' "Advanced
Programming in the UNIX Environment" for details (ISBN 0201563177)
http://www.erlenstar.demon.co.uk/unix/faq_2.html#SEC16
"""
try:
pid = os.fork()
if pid > 0:
# exit first parent
sys.exit(0)
except OSError, e:
sys.stderr.write("fork #1 failed: %d (%s)\n" % (e.errno,
e.strerror))
sys.exit(1)
# Decouple from parent environment
os.chdir("/")
os.setsid()
os.umask(0)
# Do second fork
try:
pid = os.fork()
if pid > 0:
# Exit from second parent
sys.exit(0)
except OSError, e:
sys.stderr.write("fork #2 failed: %d (%s)\n" % (e.errno, e.strerror))
sys.exit(1)
# Redirect standard file descriptors
sys.stdout.flush()
sys.stderr.flush()
si = file(self.stdin, 'r')
so = file(self.stdout, 'a+')
se = file(self.stderr, 'a+', 0)
os.dup2(si.fileno(), sys.stdin.fileno())
os.dup2(so.fileno(), sys.stdout.fileno())
os.dup2(se.fileno(), sys.stderr.fileno())
# Write pidfile
atexit.register(self.delpid)
pid = str(os.getpid())
file(self.pidfile,'w+').write("%s\n" % pid)
def delpid(self):
os.remove(self.pidfile)
def start(self):
"""
Start the daemon
"""
# Check for a pidfile to see if the daemon already runs
try:
pf = file(self.pidfile,'r')
pid = int(pf.read().strip())
pf.close()
except IOError:
pid = None
if pid:
message = "pidfile %s already exist. Daemon already running?\n"
sys.stderr.write(message % self.pidfile)
sys.exit(1)
# Start the daemon
self.daemonize()
self.run()
def stop(self):
"""
Stop the daemon
"""
# Get the pid from the pidfile
try:
pf = file(self.pidfile,'r')
pid = int(pf.read().strip())
pf.close()
except IOError:
pid = None
if not pid:
message = "pidfile %s does not exist. Daemon not running?\n"
sys.stderr.write(message % self.pidfile)
return # not an error in a restart
# Try killing the daemon process
try:
while 1:
os.kill(pid, SIGTERM)
time.sleep(0.1)
except OSError, err:
err = str(err)
if err.find("No such process") > 0:
if os.path.exists(self.pidfile):
os.remove(self.pidfile)
else:
print str(err)
sys.exit(1)
def restart(self):
"""
Restart the daemon
"""
self.stop()
self.start()
def run(self):
"""
You should override this method when you subclass Daemon. It will be called after the process has been
daemonized by start() or restart().
"""
2.my-daemon.py
import sys, time
from daemon import Daemon
import MySQLdb #MySQL libraries
#Database parameters
config = {"host":"localhost",...}
try:
conn = MySQLdb.connect(config['host'],...
class MyDaemon(Daemon):
def run(self):
while True:
time.sleep(2)
#{Do processes, connect to the database, etc....}
...
if __name__ == "__main__":
daemon = MyDaemon('/tmp/daemon-example.pid')
if len(sys.argv) == 2:
if 'start' == sys.argv[1]:
daemon.start()
elif 'stop' == sys.argv[1]:
daemon.stop()
elif 'restart' == sys.argv[1]:
daemon.restart()
elif 'foreground' == sys.argv[1]: #This runs the daemon in the foreground
daemon.run()
else:
print "Unknown command"
sys.exit(2)
sys.exit(0)
else:
print "usage: %s start|foreground|stop|restart" % sys.argv[0]
sys.exit(2)
| [
"SOLVED. I was under the impression that the foreground and the start parameter was two different things. It turns out I just needed to do the following.\ndef run(self):\n while True:\n time.sleep(2)\n\nto \ndef start(self):\n while True:\n time.sleep(2)\n\nI then removed the foreground paramete... | [
1,
0,
0
] | [] | [] | [
"daemon",
"linux",
"python",
"ubuntu_10.04",
"unix"
] | stackoverflow_0003449066_daemon_linux_python_ubuntu_10.04_unix.txt |
Q:
python line editing telnet server
I am creating a server in python (what it is doing is irrelevant), but I would like it to accept telnet connections and provide a command line interface with line editing capabilities (tabcompletion, emacs/vi-mode, etc) and history per session. I have successfully created the telnet session, disabled line mode and enabled server echo.
My initial thoughts were using readline but the python readline module seems to only work for a single session on stdin; and examining the underlying readline library that seems to be the way it works.
What I would like to do however is to create an instance (call it state if you like) for each client, and as characters (bytes) are received feed to the state. Once a complete line has been generated it would pass it to the server which may parse it.
So my question is if there is a library which handles this kind of thing, even a c-library would be sufficient.
EDIT: To clarify, I've got a fully functional server already, but I want the telnet interface as an add on to reconfigure, get information, etc.
A:
It sounds like you've got the TELNET part sorted, and now you want to provide features commonly found in shells like BASH, KSH etc. I've not tried it myself, but have a look as shython: "a versatile shell having features of both bash and python".
A:
Perhaps the cmd library could be of interest/help?
A:
You need telnetlib http://docs.python.org/library/telnetlib.html?highlight=telnet#module-telnetlib
| python line editing telnet server | I am creating a server in python (what it is doing is irrelevant), but I would like it to accept telnet connections and provide a command line interface with line editing capabilities (tabcompletion, emacs/vi-mode, etc) and history per session. I have successfully created the telnet session, disabled line mode and enabled server echo.
My initial thoughts were using readline but the python readline module seems to only work for a single session on stdin; and examining the underlying readline library that seems to be the way it works.
What I would like to do however is to create an instance (call it state if you like) for each client, and as characters (bytes) are received feed to the state. Once a complete line has been generated it would pass it to the server which may parse it.
So my question is if there is a library which handles this kind of thing, even a c-library would be sufficient.
EDIT: To clarify, I've got a fully functional server already, but I want the telnet interface as an add on to reconfigure, get information, etc.
| [
"It sounds like you've got the TELNET part sorted, and now you want to provide features commonly found in shells like BASH, KSH etc. I've not tried it myself, but have a look as shython: \"a versatile shell having features of both bash and python\".\n",
"Perhaps the cmd library could be of interest/help?\n",
"Y... | [
2,
1,
0
] | [] | [] | [
"libreadline",
"python",
"sockets",
"telnet"
] | stackoverflow_0003412832_libreadline_python_sockets_telnet.txt |
Q:
Python vs. C++ for an application that does sparse linear algebra
I'm writing an application where quite a bit of the computational time will be devoted to performing basic linear algebra operations (add, multiply, multiply by vector, multiply by scalar, etc.) on sparse matrices and vectors. Up to this point, we've built a prototype using C++ and the Boost matrix library.
I'm considering switching to Python, to ease of coding the application itself, since it seems the Boost library (the easy C++ linear algebra library) isn't particularly fast anyway. This is a research/proof of concept application, so some reduction of run time speed is acceptable (as I assume C++ will almost always outperform Python) so long as coding time is also significantly decreased.
Basically, I'm looking for general advice from people who have used these libraries before. But specifically:
1) I've found scipy.sparse and and pySparse. Are these (or other libraries) recommended?
2) What libraries beyond Boost are recommended for C++? I've seen a variety of libraries with C interfaces, but again I'm looking to do something with low complexity, if I can get relatively good performance.
3) Ultimately, will Python be somewhat comparable to C++ in terms of run time speed for the linear algebra operations? I will need to do many, many linear algebra operations and if the slowdown is significant then I probably shouldn't even try to make this switch.
Thank you in advance for any help and previous experience you can relate.
A:
My advice is to fully test the algorithm in Python before translating it into any other language (otherwise you run the risk of optimizing prematurely a bad algorithm). Once you have clearly defined the best interface for your problems, you can factor it out to external code.
Let me explain.
Suppose your final algorithm consists of taking a bunch of numbers in (row, column, value) format and, say, computing the SVD of the corresponding sparse matrix. Then you can leave the entire interface to Python:
class Problem(object):
def __init__(self, values):
self.values = values
def solve(self):
return external_svd(self.values)
where external_svd is the Python wrapper to a Fortran/C/C++ subroutine which efficiently computes the svd given a matrix in the format (row, column, value), or whatever floats your boat.
Again, first try to use numpy and scipy, and any other standard Python tool. Only then, after you've profiled your code, should you write the actual wrapper external_svd.
If you go this route, you will have a module which is user friendly (the user interacts with Python, not with Fotran/C/C++) and, most importantly, you will be able to use different back-ends: external_svd_lapack, external_svd_paradiso, external_svd_gsl, etc. (one for each back-end you choose).
As for sparse linear algebra libraries, check the Intel Math Kernel Library, the PARADISO sparse solver, the Harwell Subroutine Library (HSL) called "MA27". I've used them successfully to solve very sparse, very large problems (check the page of the nonlinear optimization solver IPOPT to see what I mean)
A:
As llasram says, many libs in python are written in C/C++ so python should run at an acceptable speed.
On C++ you can also test gsl (gnu scientific library) but I believe that the routines of linear algebra will be the same as Boost (the two libraries are using BLAS for that). For sparse linear algebra, you should take a look at SBLAS but I never used it.
Here's a short general "pros and cons" that I see :
C++ :
Will force you to keep a well-structured program
Can be quite easily wrapped for high level languages (like python) to ensure fast-testing (look at the python c api or at swig).
Python :
easy to debug but can easily lead to badly-structured programs
can very easily import data for tests
there are some very reliable libraries like scipy/numpy (by the way, scipy also uses BLAS for linear algebra)
managed code
I personnaly use gsl for matrix manipulation and I wrap my C++ libraries into Python libs to test easily with data. On my mind, it's a way of combining the pros of the two languages.
A:
2) Looks like you are looking for Eigen.
3) I would guess that if you are doing sparse linear algebra, rather sooner than later you will want every bit of speed-up you can get so I'd just stick with C++. I don't see a point in using Python for this unless quickly testing a prototype, which you have already done in C++ anyways.
A:
I don't have directly applicable experience, but the scipy/numpy operations are almost all implemented in C. As long as most of what you need to do is expressed in terms of scipy/numpy functions, then your code shouldn't be much slower than equivalent C/C++.
A:
Speed nowdays its no longer an issue for python since ctypes and cython emerged. Whats brilliant about cython is that your write python code and it generates c code without requiring from you to know a single line of c and then compiles to a library or you could even create a stanalone. Ctypes also is similar though abit slower. From the tests I have conducted cython code is as fast as c code and that make sense since cython code is translated to c code. Ctypes is abit slower.
So in the end its a question of profiling , see what is slow in python and move it to cython, or you could wrap your existing c libraries for python with cython. Its quite easy to achieve c speeds this way.
So I will recommend not to waste the effort you invested creating these c libraries , wrap them with cython and do the rest with python. Or you could do all of it with cython if you wish as cython is python bar some limitations. And even allows you to mix c code as well. So you could do part of it in c and part of it python/cython. Depending what makes you feel more comfortable.
Numpy ans SciPy could be used as well for saving more time and providing ready to use solutions to your problems / needs.You should certainly check them out. Numpy has even has weaver a tool that let you inline c code inside your python code, just like you can inline assembly code inside your c code. But i think you would prefer to use cython . Remember because cython is both c and python at the same time it allows you to use directly c and python libraries.
| Python vs. C++ for an application that does sparse linear algebra | I'm writing an application where quite a bit of the computational time will be devoted to performing basic linear algebra operations (add, multiply, multiply by vector, multiply by scalar, etc.) on sparse matrices and vectors. Up to this point, we've built a prototype using C++ and the Boost matrix library.
I'm considering switching to Python, to ease of coding the application itself, since it seems the Boost library (the easy C++ linear algebra library) isn't particularly fast anyway. This is a research/proof of concept application, so some reduction of run time speed is acceptable (as I assume C++ will almost always outperform Python) so long as coding time is also significantly decreased.
Basically, I'm looking for general advice from people who have used these libraries before. But specifically:
1) I've found scipy.sparse and and pySparse. Are these (or other libraries) recommended?
2) What libraries beyond Boost are recommended for C++? I've seen a variety of libraries with C interfaces, but again I'm looking to do something with low complexity, if I can get relatively good performance.
3) Ultimately, will Python be somewhat comparable to C++ in terms of run time speed for the linear algebra operations? I will need to do many, many linear algebra operations and if the slowdown is significant then I probably shouldn't even try to make this switch.
Thank you in advance for any help and previous experience you can relate.
| [
"My advice is to fully test the algorithm in Python before translating it into any other language (otherwise you run the risk of optimizing prematurely a bad algorithm). Once you have clearly defined the best interface for your problems, you can factor it out to external code.\nLet me explain.\nSuppose your final a... | [
7,
4,
4,
2,
1
] | [] | [] | [
"c++",
"linear_algebra",
"python"
] | stackoverflow_0003761994_c++_linear_algebra_python.txt |
Q:
Python: subprocess with different working directory
I have a python script that is under this directory:
work/project/test/a.py
Inside a.py, I use subprocess.POPEN to launch the process from another directory,
work/to_launch/file1.pl, file2.py, file3.py, ...
Python Code:
subprocess.POPEN("usr/bin/perl ../to_launch/file1.pl")
and under work/project/, I type the following
[user@machine project]python test/a.py,
error "file2.py, 'No such file or directory'"
How can I add work/to_launch/, so that these dependent files file2.py can be found?
A:
Your code does not work, because the relative path is seen relatively to your current location (one level above the test/a.py).
In sys.path[0] you have the path of your currently running script.
Use os.path.join(os.path.abspath(sys.path[0]), relPathToLaunch) with relPathToLaunch = '../to_launch/file1.pl' to get the absolute path to your file1.pl and run perl with it.
EDIT: if you want to launch file1.pl from its directory and then return back, just remember your current working directory and then switch back:
origWD = os.getcwd() # remember our original working directory
os.chdir(os.path.join(os.path.abspath(sys.path[0]), relPathToLaunch))
subprocess.POPEN("usr/bin/perl ./file1.pl")
[...]
os.chdir(origWD) # get back to our original working directory
A:
Use paths relative to the script, not the current working directory
os.path.join(os.path.dirname(__file__), '../../to_launch/file1.pl)
See also my answer to Python: get path to file in sister directory?
A:
You could use this code to set the current directory:
import os
os.chdir("/path/to/your/files")
| Python: subprocess with different working directory | I have a python script that is under this directory:
work/project/test/a.py
Inside a.py, I use subprocess.POPEN to launch the process from another directory,
work/to_launch/file1.pl, file2.py, file3.py, ...
Python Code:
subprocess.POPEN("usr/bin/perl ../to_launch/file1.pl")
and under work/project/, I type the following
[user@machine project]python test/a.py,
error "file2.py, 'No such file or directory'"
How can I add work/to_launch/, so that these dependent files file2.py can be found?
| [
"Your code does not work, because the relative path is seen relatively to your current location (one level above the test/a.py).\nIn sys.path[0] you have the path of your currently running script.\nUse os.path.join(os.path.abspath(sys.path[0]), relPathToLaunch) with relPathToLaunch = '../to_launch/file1.pl' to get ... | [
17,
3,
0
] | [] | [] | [
"python",
"subprocess",
"working_directory"
] | stackoverflow_0003762468_python_subprocess_working_directory.txt |
Q:
How to connect to internet & load html using python/urllib in ubuntu?
I am new to programming, i had some problem with the code..
Here i have posted the code below.
Actually after running the program its shows some error...
ERROR:
It shows some traceback error
import urllib
proxies = {'http' : 'http://proxy:80'}
urlopener = urllib.FancyURLopener(proxies)
htmlpage = urlopener.open('http://www.google.com')
data = htmlpage.readlines()
print data
A:
You need indent your python and replace readlines() with read()
import urllib
proxies = {'http' : 'http://proxy:80'}
urlopener = urllib.FancyURLopener(proxies)
htmlpage = urlopener.open('http://www.google.com')
data = htmlpage.read()
print data
| How to connect to internet & load html using python/urllib in ubuntu? | I am new to programming, i had some problem with the code..
Here i have posted the code below.
Actually after running the program its shows some error...
ERROR:
It shows some traceback error
import urllib
proxies = {'http' : 'http://proxy:80'}
urlopener = urllib.FancyURLopener(proxies)
htmlpage = urlopener.open('http://www.google.com')
data = htmlpage.readlines()
print data
| [
"You need indent your python and replace readlines() with read()\nimport urllib \nproxies = {'http' : 'http://proxy:80'} \nurlopener = urllib.FancyURLopener(proxies) \nhtmlpage = urlopener.open('http://www.google.com') \ndata = htmlpage.read() \nprint data\n\n"
] | [
1
] | [] | [] | [
"python",
"urllib"
] | stackoverflow_0003509284_python_urllib.txt |
Q:
examples of common middleware people use in pylons?
Just trying to get a feel for what common middleware people use in pylons?
Is middleware just the main pipeline for the request and response object?
i.e. would it be possbile to create a very simple middleware that outputs 'hello world' to the screen?
A:
The default middleware is the pipeline, as you guessed. However, my impression is that after that, "common middleware" is slightly oxymoronic, especially for a loosely coupled framework like Pylons. The framework's setup suggests "here is the basic middleware - and here's where to put middleware that you write yourself to satisfy your individual needs." I could be talking through my hat, but that's how it feels to me - when I've thought "should that be middleware?" about modules of mine, the answer has always so far turned out to be "nope, I can just put that in a controller." So - be aware of scope and don't boot things to a middleware layer if you can gracefully keep them closer to the context where you need them.
Further: The WSGI wiki has a list of middleware that may also go some ways towards answering your question.
| examples of common middleware people use in pylons? | Just trying to get a feel for what common middleware people use in pylons?
Is middleware just the main pipeline for the request and response object?
i.e. would it be possbile to create a very simple middleware that outputs 'hello world' to the screen?
| [
"The default middleware is the pipeline, as you guessed. However, my impression is that after that, \"common middleware\" is slightly oxymoronic, especially for a loosely coupled framework like Pylons. The framework's setup suggests \"here is the basic middleware - and here's where to put middleware that you write... | [
1
] | [] | [] | [
"middleware",
"pylons",
"python"
] | stackoverflow_0003709385_middleware_pylons_python.txt |
Q:
login_form_seq ? in python
can some one give me example and explain how to use login_form_seq in python and login_form_data .. and this simple example but i don't know really how to deal with that !!
login_form_seq = [
('log', sys.argv[2]),
('pwd', word),
('rememberme', 'forever'),
('wp-submit', 'Login >>'),
('redirect_to', 'wp-admin/')]
z=0
login_form_data = urllib.urlencode(login_form_seq)
if z != 0:
print " I love you Hamoud!"
else:
opener = urllib2.build_opener()
try:
site = opener.open(host, login_form_data).read()
except(urllib2.URLError), msg:
print msg
site = ""
pass
Please explain as well or don't explain and don't forget an example.
A:
You may try this...
import sys, urllib, urllib2
word = "YOUR WORD"
login_form_seq = {
'log', sys.argv[2],
'pwd', word,
'rememberme', 'forever',
'wp-submit', 'Login >>',
'redirect_to', 'wp-admin/'
}
z=0
login_form_data = urllib.urlencode(login_form_seq)
if z != 0:
print " I love you Hamoud!"
else:
opener = urllib2.build_opener()
try:
site = opener.open(host, login_form_data).read()
finally:
print site
except urllib2.URLError, msg:
print msg
site = ""
pass
| login_form_seq ? in python | can some one give me example and explain how to use login_form_seq in python and login_form_data .. and this simple example but i don't know really how to deal with that !!
login_form_seq = [
('log', sys.argv[2]),
('pwd', word),
('rememberme', 'forever'),
('wp-submit', 'Login >>'),
('redirect_to', 'wp-admin/')]
z=0
login_form_data = urllib.urlencode(login_form_seq)
if z != 0:
print " I love you Hamoud!"
else:
opener = urllib2.build_opener()
try:
site = opener.open(host, login_form_data).read()
except(urllib2.URLError), msg:
print msg
site = ""
pass
Please explain as well or don't explain and don't forget an example.
| [
"You may try this...\nimport sys, urllib, urllib2\nword = \"YOUR WORD\"\n login_form_seq = { \n 'log', sys.argv[2],\n 'pwd', word,\n 'rememberme', 'forever',\n 'wp-submit', 'Login >>',\n 'redirect_to', 'wp-admin/'\n }\n z=0\n login_form_data = urllib.urlencode(... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0003595189_python.txt |
Q:
Finding maximum value in a dictionary containing mixed items in Python
I have a dictionary with either a integer or a tuple of integers as value. How do I find the maximum integer present in dicts' values?
Example:
x1 = {0:2, 2:1, 3:(1, 2), 20:3}
should return 3
and
x2 = {0:2, 2:1, 3:(1, 5), 20:3}
should return 5
A:
A one-liner:
max(max(v) if isinstance(v, collections.Iterable) else v for v in d.itervalues())
Needs at least Python 2.6 due to collections.Iterable ABC.
A:
max(max(k,max(v) if isinstance(v,collections.Iterable) else v) for k,v in x1.items())
The other one-liner does not take account of the keys.
This is icky because it is not the designed use of a dictionary: the keys are meant to be keys, not themselves stores of data. I think you should reconsider your data structure.
EDIT: The above was nonsense. Thanks to @SilentGhost for pointing it out.
A:
This is my version of one liner not needing 2.6:
x1 = {0:2, 2:1, 3:(1, 2), 20:3}
x2 = {0:2, 2:1, 3:(1, 5), 20:3}
print max(max(values) if hasattr(values,'__iter__') else values for values in x1.values())
print max(max(values) if hasattr(values,'__iter__') else values for values in x2.values())
Output:
3
5
HOWEVER I strongly suggest to go to origin of these values and change the storing of integers to singleton tuples.Then you can use cleaner code:
x1 = {0:(2,), 2:(1,), 3:(1, 2), 20:(3,)}
x2 = {0:(2,), 2:(1,), 3:(1, 5), 20:(3,)}
for x in (x1,x2):
print max(max(values) for values in x.values())
A:
You could try this aproach:
create a set for storing integers
loop through the values of the dictionary
add integer values to set
add each integer value of tuple values to set
find max of set
Something like this:
def maxofdict(x):
s = set()
for v in x.values():
if hasattr(v, '__len__'):
s.update(v)
else:
s.add(v)
return max(s)
A:
You need a generic flatten() function. The Python standard library oddly enough doesn't provide one -- not even in itertools -- but googling around should get you an implementation. If you don't mind being potentially backwards incompatible, you can import a "private" implementation from tkinter:
from _tkinter import _flatten as flatten
def mixed_max(d):
return max(flatten(d.items()))
mixed_max({0: 2, 2: 1, 3: (1,2), 4: 0}) # => 4
mixed_max({0: 2, 2: 1, 3: (1,5), 4: 0}) # => 5
A:
Assuming the correct result for x1 = 4;
def maxOfMixedDict(x):
max = 0
for key, value in x.items():
if(key > max):
max = key
try:
for v2 in value:
if(v2 > max):
max = v2
except TypeError, e:
pass
return max
| Finding maximum value in a dictionary containing mixed items in Python | I have a dictionary with either a integer or a tuple of integers as value. How do I find the maximum integer present in dicts' values?
Example:
x1 = {0:2, 2:1, 3:(1, 2), 20:3}
should return 3
and
x2 = {0:2, 2:1, 3:(1, 5), 20:3}
should return 5
| [
"A one-liner:\nmax(max(v) if isinstance(v, collections.Iterable) else v for v in d.itervalues())\n\nNeeds at least Python 2.6 due to collections.Iterable ABC.\n",
"max(max(k,max(v) if isinstance(v,collections.Iterable) else v) for k,v in x1.items())\n\nThe other one-liner does not take account of the keys.\nThis ... | [
3,
1,
1,
0,
0,
0
] | [] | [] | [
"max",
"python"
] | stackoverflow_0003761124_max_python.txt |
Q:
How can I get all the attributes of a HTML tag?
How can I get all the attributes of a HTML tag?
listinp = soup('input')
for input in listinp:
# get all attr on this tag in dict
A:
Use attrs:
for tag in listinp:
print dict(tag.attrs)
A:
use pretiffy() in BeautifulSoup
import urllib2, BeautifulSoup
opener = urllib2.build_opener()
host = "http://google.com"
site = opener.open(host)
html = site.read()
soup = BeautifulSoup(html)
print soup.pretiffy()
| How can I get all the attributes of a HTML tag? | How can I get all the attributes of a HTML tag?
listinp = soup('input')
for input in listinp:
# get all attr on this tag in dict
| [
"Use attrs:\nfor tag in listinp:\n print dict(tag.attrs)\n\n",
"use pretiffy() in BeautifulSoup\nimport urllib2, BeautifulSoup\nopener = urllib2.build_opener()\nhost = \"http://google.com\"\nsite = opener.open(host)\nhtml = site.read()\nsoup = BeautifulSoup(html)\nprint soup.pretiffy()\n\n"
] | [
2,
0
] | [] | [] | [
"beautifulsoup",
"python"
] | stackoverflow_0003543197_beautifulsoup_python.txt |
Q:
Python, parse html form
how I can get input from html forms on other sites?
I want it to return a dictionary such as:
form = [('name' = 'somename', 'type' = 'text', 'value':''},{' name' = 'somename', 'type' = 'submit', 'value': ' submit ').
Sorry for my English.
A:
you probably wont be able to retrieve form data from other users on other sites. If you wish to use a script to send data to a form, mechanize is one tool that makes this quite easy.
A:
Yeah mechanize is sweet !
import mechanize
# Browser
br = mechanize.Browser()
br.set_handle_equiv(True)
br.set_handle_gzip(True)
br.set_handle_redirect(True)
br.set_handle_referer(True)
br.set_handle_robots(False)
br.set_handle_refresh(mechanize._http.HTTPRefreshProcessor(), max_time=1)
br.addheaders = [('User-agent', 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1')]
# we inspect the all form element in the http://stackoverflow.com
br.open('http://stackoverflow.com')
for form in br.forms():
print form
A:
Look at mechanize, lxml.html and BeatifulSoup.
| Python, parse html form | how I can get input from html forms on other sites?
I want it to return a dictionary such as:
form = [('name' = 'somename', 'type' = 'text', 'value':''},{' name' = 'somename', 'type' = 'submit', 'value': ' submit ').
Sorry for my English.
| [
"you probably wont be able to retrieve form data from other users on other sites. If you wish to use a script to send data to a form, mechanize is one tool that makes this quite easy.\n",
"Yeah mechanize is sweet !\nimport mechanize\n\n# Browser\nbr = mechanize.Browser()\nbr.set_handle_equiv(True)\nbr.set_handle_... | [
3,
2,
1
] | [] | [] | [
"forms",
"html",
"python"
] | stackoverflow_0003541098_forms_html_python.txt |
Q:
Why does python think this is a local variable?
I have a global variable I called Y_VAL which is initialized to a value of 2.
I then have a function, called f() (for brevity), which uses Y_VAL.
def f():
y = Y_VAL
Y_VAL += 2
However, when trying to run my code, python gives the error message:
UnboundLocalError: local variable 'Y_VAL' referenced before assignment
If I remove the last line Y_VAL += 2 it works fine.
Why does python think that Y_VAL is a local variable?
A:
You're missing the line global Y_VAL inside the function.
When Y_VAL occurs on the right-hand-side of an assignment, it's no problem because the local scope is searched first, then the global scope is searched. However, on the left-hand-side, you can only assign to a global that way when you've explicitly declared global Y_VAL.
From the docs:
It would be impossible to assign to a global variable without global, although free variables may refer to globals without being declared global.
A:
This is just how Python works: Assignment always binds the left-hand side name in the closest surrounding name space. Inside of a function the closest namespace is the local namespace of the function.
In order to assign to a global variable, you have to declare it global. But avoid global by all means. Global variables are almost always bad design, and thus the use of the global keyword is a strong hint, that you are making design mistakes.
A:
I ran to the same issue as you and as many others like you, before realising it needs the global statement. I then decided to move everything to object orientation and have piece of mind. Call me insane but I just dont trust myself with the global statement and its not difficult to come against a problem of local scope that is a pain to debug.
So I would advice collect all your "global" variables put them in a class inside an init(self) and not only you wont have to worry about local scope but you will have your code much better organised. Its not a freak of luck that most programmer out there prefer OOP.
| Why does python think this is a local variable? | I have a global variable I called Y_VAL which is initialized to a value of 2.
I then have a function, called f() (for brevity), which uses Y_VAL.
def f():
y = Y_VAL
Y_VAL += 2
However, when trying to run my code, python gives the error message:
UnboundLocalError: local variable 'Y_VAL' referenced before assignment
If I remove the last line Y_VAL += 2 it works fine.
Why does python think that Y_VAL is a local variable?
| [
"You're missing the line global Y_VAL inside the function.\nWhen Y_VAL occurs on the right-hand-side of an assignment, it's no problem because the local scope is searched first, then the global scope is searched. However, on the left-hand-side, you can only assign to a global that way when you've explicitly declar... | [
15,
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0003241930_python.txt |
Q:
Is there a way to run a python script that is inside a zip file from bash?
I know there is a way to import modules which are in a zip file with python. I created kind of custom python package library in a zip file.
I would like to put as well my "task" script in this package, those are using the library. Then, with bash, I would like to call the desired script in the zip file without extracting the zip.
The goal is to have only one zip to move in a specified folder when I want to run my scripts.
A:
I finally found a way to do this. If I create a zip file, I must create __main__.py at the root of the zip. Thus, it is possible to launch the script inside the main and call if from bash with the following command :
python myArchive.zip
This command will run the __main__.py file! :)
Then I can create .command file to launch the script with proper parameters.
You can also put some code in the __main__.py file to give you more flexibility if you need to pass arguments for example.
ex: python __main__.py buildProject
The reference documentation is here: https://docs.python.org/2/library/runpy.html
A:
Have a look at zipimport. It should work directly from the install. You might have to do some work to make the pythonpath point to your zip file/directory.
This module adds the ability to import
Python modules (*.py, *.py[co]) and
packages from ZIP-format archives. It
is usually not needed to use the
zipimport module explicitly; it is
automatically used by the built-in
import mechanism for sys.path items
that are paths to ZIP archives.that are paths to ZIP archives.
| Is there a way to run a python script that is inside a zip file from bash? | I know there is a way to import modules which are in a zip file with python. I created kind of custom python package library in a zip file.
I would like to put as well my "task" script in this package, those are using the library. Then, with bash, I would like to call the desired script in the zip file without extracting the zip.
The goal is to have only one zip to move in a specified folder when I want to run my scripts.
| [
"I finally found a way to do this. If I create a zip file, I must create __main__.py at the root of the zip. Thus, it is possible to launch the script inside the main and call if from bash with the following command :\npython myArchive.zip\nThis command will run the __main__.py file! :)\nThen I can create .command ... | [
18,
3
] | [] | [] | [
"bash",
"macos",
"python",
"python_module",
"zip"
] | stackoverflow_0003760970_bash_macos_python_python_module_zip.txt |
Q:
Returning all characters before the first underscore
Using re in Python, I would like to return all of the characters in a string that precede the first appearance of an underscore. In addition, I would like the string that is being returned to be in all uppercase and without any non-alpanumeric characters.
For example:
AG.av08_binloop_v6 = AGAV08
TL.av1_binloopv2 = TLAV1
I am pretty sure I know how to return a string in all uppercase using string.upper() but I'm sure there are several ways to remove the . efficiently. Any help would be greatly appreciated. I am still learning regular expressions slowly but surely. Each tip gets added to my notes for future use.
To further clarify, my above examples aren't the actual strings. The actual string would look like:
AG.av08_binloop_v6
With my desired output looking like:
AGAV08
And the next example would be the same. String:
TL.av1_binloopv2
Desired output:
TLAV1
Again, thanks all for the help!
A:
Even without re:
text.split('_', 1)[0].replace('.', '').upper()
A:
Try this:
re.sub("[^A-Z\d]", "", re.search("^[^_]*", str).group(0).upper())
A:
Since everyone is giving their favorite implementation, here's mine that doesn't use re:
>>> for s in ('AG.av08_binloop_v6', 'TL.av1_binloopv2'):
... print ''.join(c for c in s.split('_',1)[0] if c.isalnum()).upper()
...
AGAV08
TLAV1
I put .upper() on the outside of the generator so it is only called once.
A:
You don't have to use re for this. Simple string operations would be enough based on your requirements:
tests = """
AG.av08_binloop_v6 = AGAV08
TL.av1_binloopv2 = TLAV1
"""
for t in tests.splitlines():
print t[:t.find('_')].replace('.', '').upper()
# Returns:
# AGAV08
# TLAV1
Or if you absolutely must use re:
import re
pat = r'([a-zA-Z0-9.]+)_.*'
pat_re = re.compile(pat)
for t in tests.splitlines():
print re.sub(r'\.', '', pat_re.findall(t)[0]).upper()
# Returns:
# AGAV08
# TLAV1
A:
He, just for fun, another option to get text before the first underscore is:
before_underscore, sep, after_underscore = str.partition('_')
So all in one line could be:
re.sub("[^A-Z\d]", "", str.partition('_')[0].upper())
A:
import re
re.sub("[^A-Z\d]", "", yourstr.split('_',1)[0].upper())
| Returning all characters before the first underscore | Using re in Python, I would like to return all of the characters in a string that precede the first appearance of an underscore. In addition, I would like the string that is being returned to be in all uppercase and without any non-alpanumeric characters.
For example:
AG.av08_binloop_v6 = AGAV08
TL.av1_binloopv2 = TLAV1
I am pretty sure I know how to return a string in all uppercase using string.upper() but I'm sure there are several ways to remove the . efficiently. Any help would be greatly appreciated. I am still learning regular expressions slowly but surely. Each tip gets added to my notes for future use.
To further clarify, my above examples aren't the actual strings. The actual string would look like:
AG.av08_binloop_v6
With my desired output looking like:
AGAV08
And the next example would be the same. String:
TL.av1_binloopv2
Desired output:
TLAV1
Again, thanks all for the help!
| [
"Even without re:\ntext.split('_', 1)[0].replace('.', '').upper()\n\n",
"Try this:\nre.sub(\"[^A-Z\\d]\", \"\", re.search(\"^[^_]*\", str).group(0).upper())\n\n",
"Since everyone is giving their favorite implementation, here's mine that doesn't use re:\n>>> for s in ('AG.av08_binloop_v6', 'TL.av1_binloopv2'):\n... | [
22,
7,
3,
2,
2,
1
] | [] | [] | [
"python",
"regex",
"string"
] | stackoverflow_0003762420_python_regex_string.txt |
Q:
how to create hyperlink in piechart
I want to do a pie chart in matplotlib.
This pie chart will be a representation of two variables: male and female.
That's easy to do :)
What I would like to do next, I'm not even sure if it's possible to do with matplotlib, I would like to make these two variables clickable so if I click on male, I would see another page with information about this, same thing with female.
Image map isn't a solution since this variables may change in the future.
Anyone has any idea how to do this? If it's possible with matplotlib or what program would you recommend.
Thank you!
A:
While it's not really in a workably stable state yet, have a look at the html5 canvas backend for matplotlib. It looks interesting, anyway, and will probably be the best way to do this sort of thing (interactive webpage with a matplotlib plot) in the future.
In the meantime, as @Mark suggested, it's not too hard to dynamically generate an imagemap for the wedges of a pie plot.
Here's a rough example, that I'm sure you could adapt to whatever web framework you're using.
import matplotlib.pyplot as plt
def main():
# Make an example pie plot
fig = plt.figure()
ax = fig.add_subplot(111)
labels = ['Beans', 'Squash', 'Corn']
wedges, plt_labels = ax.pie([20, 40, 60], labels=labels)
ax.axis('equal')
make_image_map(fig, wedges, labels, 'temp.html')
def make_image_map(fig, wedges, labels, html_filename):
"""Makes an example static html page with a image map of a pie chart.."""
#-- Save the figure as an image and get image size ------------------------
# Be sure to explictly set the dpi when saving the figure
im_filename = 'temp.png'
fig.savefig(im_filename, dpi=fig.dpi)
# Get figure size...
_, _, fig_width, fig_height = fig.bbox.bounds
#-- Get the coordinates of each wedge as a string of x1,y2,x2,y2... -------
coords = []
for wedge in wedges:
xy = wedge.get_verts()
# Transform to pixel coords
xy = fig.get_transform().transform(xy)
# Format into coord string and convert to <0,0> in top left...
xy = ', '.join(['%0.2f,%0.2f' % (x, fig_height - y) for x, y in xy])
coords.append(xy)
#-- Build web page --------------------------------------------------------
header = """
<html>
<body>
<img src="{0}" alt="Pie Chart" usemap="#pie_map" width="{1}" height="{2}" />
""".format(im_filename, fig_width, fig_height)
# Make the image map
map = '<map name="pie_map">\n'
for label, xy in zip(labels, coords):
href = 'http://images.google.com/images?q={0}'.format(label)
area = '<area shape="poly" coords="{0}" href="{1}" alt="{2}" />'
area = area.format(xy, href, label)
map += ' ' + area + '\n'
map += '</map>\n'
footer = """
</body>
</html>"""
# Write to a file...
with file(html_filename, 'w') as outfile:
outfile.write(header + map + footer)
if __name__ == '__main__':
main()
Edit: I just realized that you might not be referring to embedding the plot into a web page... (I assumed that you were from the "display another page" bit in your question.) If you want more of a desktop app, without having to mess with a "full" gui toolkit, you can do something like this:
import matplotlib.pyplot as plt
def main():
# Make an example pie plot
fig = plt.figure()
ax = fig.add_subplot(111)
labels = ['Beans', 'Squash', 'Corn']
wedges, plt_labels = ax.pie([20, 40, 60], labels=labels)
ax.axis('equal')
make_picker(fig, wedges)
plt.show()
def make_picker(fig, wedges):
import webbrowser
def on_pick(event):
wedge = event.artist
label = wedge.get_label()
webbrowser.open('http://images.google.com/images?q={0}'.format(label))
# Make wedges selectable
for wedge in wedges:
wedge.set_picker(True)
fig.canvas.mpl_connect('pick_event', on_pick)
if __name__ == '__main__':
main()
Which opens a browser window for a google image search of whatever the wedge is labeled as...
A:
You can do this with an imagemap or HTML element overlay controlled by JavaScript/jQuery.
Essentially, send your chart data to the page along with the chart image, and use JS to create the elements with the links according to the specification of the data.
It's a bit harder than the bar graphs I've done this to before, but should work fine.
| how to create hyperlink in piechart | I want to do a pie chart in matplotlib.
This pie chart will be a representation of two variables: male and female.
That's easy to do :)
What I would like to do next, I'm not even sure if it's possible to do with matplotlib, I would like to make these two variables clickable so if I click on male, I would see another page with information about this, same thing with female.
Image map isn't a solution since this variables may change in the future.
Anyone has any idea how to do this? If it's possible with matplotlib or what program would you recommend.
Thank you!
| [
"While it's not really in a workably stable state yet, have a look at the html5 canvas backend for matplotlib. It looks interesting, anyway, and will probably be the best way to do this sort of thing (interactive webpage with a matplotlib plot) in the future.\nIn the meantime, as @Mark suggested, it's not too hard... | [
5,
1
] | [] | [] | [
"hyperlink",
"javascript",
"jquery",
"matplotlib",
"python"
] | stackoverflow_0003758658_hyperlink_javascript_jquery_matplotlib_python.txt |
Q:
Using reverse operators in Python
I have never handled reverse operators before. I just finished learning about them so wanted to try them out. But for some reason, it is not working. Here is the code:
>>> class Subtract(object):
def __init__(self, number):
self.number = number
def __rsub__(self, other):
return self.number - other.number
>>> x = Subtract(5)
>>> y = Subtract(10)
>>> x - y # FAILS!
Traceback (most recent call last):
File "<pyshell#8>", line 1, in <module>
x - y
TypeError: unsupported operand type(s) for -: 'Subtract' and 'Subtract'
>>> x.__rsub__(y) # WORKS!
-5
If I change __rsub__ to __sub__, it works.
What am I doing wrong? Also what is the purpose of these reverse operators?
A:
__rsub__() will only be called if the operands are of different types; when they're of the same type it's assumed that if __sub__ isn't present they can't be subtracted.
Also note that your logic is reversed in any case; you're returning self - other instead of other - self
A:
The point of these methods is to allow this:
class MyNumber(object):
def __init__(self, x):
self.x = x
print 10 - MyNumber(9) # fails because 10.__sub__(MyNumber(9)) is unknown
class MyFixedNumber(MyNumber):
def __rsub__(self, other):
return MyNumber( other - self.x )
print 10 - MyFixedNumber(9) # MyFixedNumber(9).__rsub__(10) is defined
Very rarely useful though, usually you just use things of the same type and the direct __sub__
A:
From Python's Data model at http://docs.python.org/reference/datamodel.html :
These methods are called to implement
the binary arithmetic operations (+,
-, *, /, %, divmod(), pow(), **, <<, >>, &, ^, |) with reflected (swapped) operands. These functions are only
called if the left operand does not
support the corresponding operation
and the operands are of different
types. [2] For instance, to evaluate
the expression x - y, where y is an
instance of a class that has an
__rsub__() method, y.__rsub__(x) is called if x.__sub__(y) returns
NotImplemented.
However - both objects must not be of the same class - that means, that even if you put a __sub__ method returning NotImplemented on your example above, you will still get the same error: Python just assumes your Subtract class can't subtract from "Subtract" iobjects, no matter the order.
However, this works:
class Sub1(object):
number = 5
def __sub__(self, other):
return NotImplemented
class Sub2(object):
number = 2
def __rsub__(self, other):
return other.number - self.number
a = Sub1()
b = Sub2()
print a - b
A:
The methods with reflected operands are provided so that your class can implement an operator when the left operand is a primitive or something else that isn't under your control:
These functions are only called if the left operand does not support the corresponding operation and the operands are of different types.
Since they're both of the same type, it's cowardly refusing and you should implement the __sub__ method.
| Using reverse operators in Python | I have never handled reverse operators before. I just finished learning about them so wanted to try them out. But for some reason, it is not working. Here is the code:
>>> class Subtract(object):
def __init__(self, number):
self.number = number
def __rsub__(self, other):
return self.number - other.number
>>> x = Subtract(5)
>>> y = Subtract(10)
>>> x - y # FAILS!
Traceback (most recent call last):
File "<pyshell#8>", line 1, in <module>
x - y
TypeError: unsupported operand type(s) for -: 'Subtract' and 'Subtract'
>>> x.__rsub__(y) # WORKS!
-5
If I change __rsub__ to __sub__, it works.
What am I doing wrong? Also what is the purpose of these reverse operators?
| [
"__rsub__() will only be called if the operands are of different types; when they're of the same type it's assumed that if __sub__ isn't present they can't be subtracted.\nAlso note that your logic is reversed in any case; you're returning self - other instead of other - self\n",
"The point of these methods is to... | [
6,
5,
4,
3
] | [] | [] | [
"operators",
"python"
] | stackoverflow_0003763683_operators_python.txt |
Q:
Python cProfile: how to filter out specific calls from the profiling data?
I've started profiling a script which has many sleep(n) statements. All in all, I get over 99% of the run time spent sleeping. Nevertheless, it occasionally runs into performance problems during the time that it does real work but the relevant, interesting profiling data becomes very difficult to identify when e.g. using kcachegrind.
Is there a way I can blacklist certain calls/functions from being profiled?
Alternatively, how can I filter out such call with post-processing of the profiling data file?
I'm using the profilestats decorator ( http://pypi.python.org/pypi/profilestats ).
Thanks
A:
You need more than just excluding samples during sleep(). You need the remaining samples to tell you something useful. That would be stack sampling, on wall-clock time, summarizing percent at the line-of-code level. Zoom is a good tool for this kind of sampling, and I would hope it's not too hard to ignore samples that contain a particular function.
| Python cProfile: how to filter out specific calls from the profiling data? | I've started profiling a script which has many sleep(n) statements. All in all, I get over 99% of the run time spent sleeping. Nevertheless, it occasionally runs into performance problems during the time that it does real work but the relevant, interesting profiling data becomes very difficult to identify when e.g. using kcachegrind.
Is there a way I can blacklist certain calls/functions from being profiled?
Alternatively, how can I filter out such call with post-processing of the profiling data file?
I'm using the profilestats decorator ( http://pypi.python.org/pypi/profilestats ).
Thanks
| [
"You need more than just excluding samples during sleep(). You need the remaining samples to tell you something useful. That would be stack sampling, on wall-clock time, summarizing percent at the line-of-code level. Zoom is a good tool for this kind of sampling, and I would hope it's not too hard to ignore samples... | [
2
] | [] | [] | [
"cprofile",
"kcachegrind",
"profiling",
"python"
] | stackoverflow_0003761671_cprofile_kcachegrind_profiling_python.txt |
Q:
How do you handle timezones for data processing?
curious how people have solved this problem...
I have a series of jobs that run overnight that roll up reports based on that day's data for customers. They're now asking for timezone support.
One of the reports is.. you had x number of orders last night, however last night could be different depending on timezone. What is the best way to organize or process the data so timezones are taking into account to make that job easier?
thanks
A:
It is good practice to represent all the dates in the UTC time zone. This timezone has no confusing daylight savings time. Then the customer in the US/Pacific timezone can ask for a report on orders between 2010-09-20T00:00-700 to 2010-09-21T00:00-700 (using ISO 8601 format). The input layer of your program should convert both the customer dates and the stored order dates to seconds since the epoch in UTC and then go from there.
A:
In my app, I save the local time plus the offset to UTC. This way, I can still compare the values (by converting them to universal time) in the code but when I display it on the screen, users will see the times they expect ("Yeah, I did that at 9:30 yesterday"). With a switch, they can show the timezone or switch to universal time or display all times in local time.
A:
In my experience with this, we've rolled the data up into hourly (or fifteen minute) buckets during the nightly run. Then you can have the user requests grab the relevant buckets based on the time zone they are using for their report.
| How do you handle timezones for data processing? | curious how people have solved this problem...
I have a series of jobs that run overnight that roll up reports based on that day's data for customers. They're now asking for timezone support.
One of the reports is.. you had x number of orders last night, however last night could be different depending on timezone. What is the best way to organize or process the data so timezones are taking into account to make that job easier?
thanks
| [
"It is good practice to represent all the dates in the UTC time zone. This timezone has no confusing daylight savings time. Then the customer in the US/Pacific timezone can ask for a report on orders between 2010-09-20T00:00-700 to 2010-09-21T00:00-700 (using ISO 8601 format). The input layer of your program should... | [
3,
1,
0
] | [] | [] | [
"data_processing",
"java",
"python",
"timezone"
] | stackoverflow_0003761655_data_processing_java_python_timezone.txt |
Q:
How to add the binary of a int with the binary of a string
Basically i want to be able to get a 32bit int and attach its binary to the binary of a string.
E.g.
(IM going to use 8bit instead of 32bit)
i want
255 + hi
11111111 + 0110100001101001 = 111111110110100001101001
So the int holds its binary value,i dont care how it comes out i just want it to be able to send the data over a socket.
(This is all over websockets and the new sec-websocket-key's to stop hacking, if anyone just knows how to do the websocket handshake that would be just as nice)
Thankyou ! I have been trying on this for days and im not one to come to this type of website to get the answer
EDIT
Ive been ask to give more info so her is the full deal. I have connected to the user of a stream port, he has sent me headers now i need to reply to to complete the connection. The import data is
Sec-WebSocket-Key1: 4 @1 46546xW%0l 1 5"Random string following rules"(i will call this sk1)
Sec-WebSocket-Key2: 12998 5 Y3 1 .P00 "Random string following rules"(i will call this sk2)
^n:ds[4U "Random string following rules"(i will call this sk3)
1) int1 = compress the numbers into sk1 and divid them by the amount of spaces in sk1
2) int2 = compress the numbers into sk2 and divid them by the amount of spaces in sk2
3) fullapend = Add append the bytes of int2 to int1 then append the bytes in sk3
4) Finally MD5 digest fullapend
5) Send the final result to the host along with some other headers and if they match up the connection holds open
That is everything that needs to happen and i have not got a clue how to do it
Finished !
Well basic both answers was right and i would like to apologise if i seemed a bit rude, i didnt know the \x was a (something) meaning binary. but that worked a treat. Once i have the finished function to connect send etc... i will post it on here and else where for anyone else thats stuck, again thankyou !
A:
Something like
struct.pack("!i%ds" % len(your_string), your_int, your_string)
should do pretty much what you want !
A:
Is this what you're looking for? Don't know whether you're after a hexdigest or a digest, and I couldn't tell where the keys started and stopped, which is a shame as they are whitespace sensitive.
Also in your update you said "compress" numbers when I think you meant "concatenate". I think the resulting keys are supposed to be bigendian, which is what I've done.
>>> import struct
>>> def processKey(data):
... num = int("".join([x for x in data if x.isdigit()]))
... spaces = data.count(' ')
... return num / spaces
...
>>> key1 = '4 @1 46546xW%0l 1 5'
>>> key2 = '12998 5 Y3 1 .P00 '
>>> sk1 = processKey(key1)
>>> sk2 = processKey(key2)
>>> sk1
1036636503L
>>> sk2
259970620
>>> sk3 = "^n:ds[4U"
>>> fullappend = struct.pack('>ii%ds' % len(sk3),sk1,sk2,sk3)
>>> fullappend
'=\xc9\xd1W\x0f~\xd6<^n:ds[4U'
>>> len(fullappend)
16
>>> from hashlib import md5
>>> md5(fullappend).hexdigest()
'fd028b6b39ceb8e37f09b8e45556bbc4'
>>> md5(fullappend).digest()
'\xfd\x02\x8bk9\xce\xb8\xe3\x7f\t\xb8\xe4UV\xbb\xc4'
| How to add the binary of a int with the binary of a string | Basically i want to be able to get a 32bit int and attach its binary to the binary of a string.
E.g.
(IM going to use 8bit instead of 32bit)
i want
255 + hi
11111111 + 0110100001101001 = 111111110110100001101001
So the int holds its binary value,i dont care how it comes out i just want it to be able to send the data over a socket.
(This is all over websockets and the new sec-websocket-key's to stop hacking, if anyone just knows how to do the websocket handshake that would be just as nice)
Thankyou ! I have been trying on this for days and im not one to come to this type of website to get the answer
EDIT
Ive been ask to give more info so her is the full deal. I have connected to the user of a stream port, he has sent me headers now i need to reply to to complete the connection. The import data is
Sec-WebSocket-Key1: 4 @1 46546xW%0l 1 5"Random string following rules"(i will call this sk1)
Sec-WebSocket-Key2: 12998 5 Y3 1 .P00 "Random string following rules"(i will call this sk2)
^n:ds[4U "Random string following rules"(i will call this sk3)
1) int1 = compress the numbers into sk1 and divid them by the amount of spaces in sk1
2) int2 = compress the numbers into sk2 and divid them by the amount of spaces in sk2
3) fullapend = Add append the bytes of int2 to int1 then append the bytes in sk3
4) Finally MD5 digest fullapend
5) Send the final result to the host along with some other headers and if they match up the connection holds open
That is everything that needs to happen and i have not got a clue how to do it
Finished !
Well basic both answers was right and i would like to apologise if i seemed a bit rude, i didnt know the \x was a (something) meaning binary. but that worked a treat. Once i have the finished function to connect send etc... i will post it on here and else where for anyone else thats stuck, again thankyou !
| [
"Something like \nstruct.pack(\"!i%ds\" % len(your_string), your_int, your_string)\n\nshould do pretty much what you want !\n",
"Is this what you're looking for? Don't know whether you're after a hexdigest or a digest, and I couldn't tell where the keys started and stopped, which is a shame as they are whitespace... | [
3,
2
] | [] | [] | [
"python",
"websocket"
] | stackoverflow_0003761871_python_websocket.txt |
Q:
Calling Tcl procedures with Function pointers as argument from Python
Is it possible to call Tcl procedures that have function pointers (or callback functions) from Python?
I am using Tkinter to call Tcl procedures from Python.
Python Snippet :
proc callbackFunc():
print "I am in callbackFunc"
cb = callbackFunc
Tkinter.Tk.call('tclproc::RetrieveInfo', cb)
Tcl Snippet :
proc tclproc::RetrieveInfo() { callback } {
eval $callback
}
Note I cannot modify Tcl code as its an external library to my application.
//Hemanth
A:
Yes, and your pseudocode is pretty close. You have to register your python code with the Tcl interpreter. This will create a tcl command that will call your python code. You then reference this new tcl command whenever you pass it to a Tcl procedure that expects a procedure name. It goes something like this:
import Tkinter
root=Tkinter.Tk()
# create a python callback function
def callbackFunc():
print "I am in callbackFunc"
# register the callback as a Tcl command. What gets returned
# must be used when calling the function from Tcl
cb = root.register(callbackFunc)
# call a tcl command ('eval', for demonstration purposes)
# that calls our python callback:
root.call('eval',cb)
A tiny bit of documentation is here:
http://epydoc.sourceforge.net/stdlib/Tkinter.Misc-class.html#register
| Calling Tcl procedures with Function pointers as argument from Python | Is it possible to call Tcl procedures that have function pointers (or callback functions) from Python?
I am using Tkinter to call Tcl procedures from Python.
Python Snippet :
proc callbackFunc():
print "I am in callbackFunc"
cb = callbackFunc
Tkinter.Tk.call('tclproc::RetrieveInfo', cb)
Tcl Snippet :
proc tclproc::RetrieveInfo() { callback } {
eval $callback
}
Note I cannot modify Tcl code as its an external library to my application.
//Hemanth
| [
"Yes, and your pseudocode is pretty close. You have to register your python code with the Tcl interpreter. This will create a tcl command that will call your python code. You then reference this new tcl command whenever you pass it to a Tcl procedure that expects a procedure name. It goes something like this:\nimpo... | [
7
] | [] | [] | [
"python",
"tcl",
"tkinter"
] | stackoverflow_0003763904_python_tcl_tkinter.txt |
Q:
Using pydbgr with Emacs
Has anyone used Pydbgr with Emacs and if so would they mind sharing their .emacs configuration plus any associated elisp sources required.
The installation instructions can be found at:
http://code.google.com/p/pydbgr/wiki/Tutorial#Installation
Pydbgr looks like a really useful extension to the capabilities of pdb, especially its support for multi-threaded debug and the promise of conducting this within Emacs, but I cannot find any elisp source allowing for easy integration in the Emacs environment.
A:
see http://github.com/rocky/emacs-dbgr which supports a number of debuggers, pydbgr being one of them.
| Using pydbgr with Emacs | Has anyone used Pydbgr with Emacs and if so would they mind sharing their .emacs configuration plus any associated elisp sources required.
The installation instructions can be found at:
http://code.google.com/p/pydbgr/wiki/Tutorial#Installation
Pydbgr looks like a really useful extension to the capabilities of pdb, especially its support for multi-threaded debug and the promise of conducting this within Emacs, but I cannot find any elisp source allowing for easy integration in the Emacs environment.
| [
"see http://github.com/rocky/emacs-dbgr which supports a number of debuggers, pydbgr being one of them.\n"
] | [
1
] | [] | [] | [
"debugging",
"dot_emacs",
"elisp",
"emacs",
"python"
] | stackoverflow_0003764575_debugging_dot_emacs_elisp_emacs_python.txt |
Q:
upload docs and web pages using drag and drop interface using python desktop app
i have desktop interface in python which uses drag and drop and where users can login. right now if i drop a file it will be stored in local directory. now what i want is, i want to upload user dropeed file to remote web server. can anybody help me in direction ? i have been exploring python's ftp library's and everything i can find. anybody suggest me some good option to do the same ?
i also need to track user who uploaded file so if you can help me figuring out best option then it will be great help. tell me best way to achieve this. i am not sure ftp is the only option i have or not.
and thanks for reading this much.
have a good day.
A:
In order to avoid reinventing the wheel, I recommend using FTP. With that being said, you'll need, of course, to have an FTP server.
By using FTP, this entirely avoids the creation of a proprietary file transferring server and client system. That would entail massive amounts of coding of sockets – perhaps even the confusing and convoluted use of Asynchronous Socketing if you plan on allowing more than one user to connect at a time – a user database, etc.
As you are already aware, python is compatible with FTP servers. More information is available from the online Python Documentation.
As for the tracking of which user uploads which file, I'd recommend creating a file with some sort of prefix. For example, if you have the user-uploaded file names.txt, make python upload a sister file _names.txt inside which will be the name of the user who uploaded the file.
(Have python hide these files in the GUI so that they're abstracted from the end user.)
There are loads more options available, like creating an XML file in each working directory that will serve as the database for each file and user pair in the directory. The creation of an SQLite database is also an option.
| upload docs and web pages using drag and drop interface using python desktop app | i have desktop interface in python which uses drag and drop and where users can login. right now if i drop a file it will be stored in local directory. now what i want is, i want to upload user dropeed file to remote web server. can anybody help me in direction ? i have been exploring python's ftp library's and everything i can find. anybody suggest me some good option to do the same ?
i also need to track user who uploaded file so if you can help me figuring out best option then it will be great help. tell me best way to achieve this. i am not sure ftp is the only option i have or not.
and thanks for reading this much.
have a good day.
| [
"In order to avoid reinventing the wheel, I recommend using FTP. With that being said, you'll need, of course, to have an FTP server.\nBy using FTP, this entirely avoids the creation of a proprietary file transferring server and client system. That would entail massive amounts of coding of sockets – perhaps even th... | [
1
] | [] | [] | [
"desktop",
"desktop_application",
"python"
] | stackoverflow_0003763783_desktop_desktop_application_python.txt |
Q:
Adding Readline Functionality Without Recompiling Python
I recently upgraded to Ubuntu 10.04 LTS and refreshed my Python environment. I installed Python 2.7 from source. Unfortunately, I didn't notice that Setup.dist has the readline line commented out by default - by default, there is no readline support installed. I'm now using the Python interpreter as a REPL enough that the constant ^[[A and ^[[D are very obnoxious.
Can I add readline support quickly, or do I have to actually recompile Python again? It seems like the sort of thing where there should be a quick, sane way to do it, but I don't know such a way.
A:
There's a standalone gnureadline package available, you can install it using setuptools
$ easy_install readline
You might also consider using ipython instead.
| Adding Readline Functionality Without Recompiling Python | I recently upgraded to Ubuntu 10.04 LTS and refreshed my Python environment. I installed Python 2.7 from source. Unfortunately, I didn't notice that Setup.dist has the readline line commented out by default - by default, there is no readline support installed. I'm now using the Python interpreter as a REPL enough that the constant ^[[A and ^[[D are very obnoxious.
Can I add readline support quickly, or do I have to actually recompile Python again? It seems like the sort of thing where there should be a quick, sane way to do it, but I don't know such a way.
| [
"There's a standalone gnureadline package available, you can install it using setuptools\n$ easy_install readline\n\nYou might also consider using ipython instead.\n"
] | [
12
] | [] | [] | [
"python",
"readline"
] | stackoverflow_0003764730_python_readline.txt |
Q:
When __repr__() is called?
print OBJECT calls OBJECT.__str__(), then when OBJECT.__repr__() is called? I see that print OBJECT calls OBJECT.__repr__() when OBJECT.__str__() doesn't exist, but I expect that's not the only way to call __repr__().
A:
repr(obj)
calls
obj.__repr__
the purpose of __repr__ is that it provides a 'formal' representation of the object that is supposed to be a expression that can be evaled to create the object. that is,
obj == eval(repr(obj))
should, but does not always in practice, yield True
I was asked in the comments for an example of when obj != eval(repr(obj)).
class BrokenRepr(object):
def __repr__(self):
return "not likely"
here's another one:
>>> con = sqlite3.connect(':memory:')
>>> repr(con)
'<sqlite3.Connection object at 0xb773b520>'
>>>
A:
Not only does __repr__() get called when you use repr(), but also in the following cases:
You type obj in the shell and press enter
You ever print an object in a dictionary/tuple/list. E.g.: print [u'test'] does not print ['test']
A:
repr(obj) calls obj.__repr__.
This is intended to clearly describe an object, specially for debugging purposes. More info in the docs
A:
In python 2.x, `obj` will end up calling obj.__repr__(). It's shorthand for repr().
| When __repr__() is called? | print OBJECT calls OBJECT.__str__(), then when OBJECT.__repr__() is called? I see that print OBJECT calls OBJECT.__repr__() when OBJECT.__str__() doesn't exist, but I expect that's not the only way to call __repr__().
| [
"repr(obj)\n\ncalls\nobj.__repr__\n\nthe purpose of __repr__ is that it provides a 'formal' representation of the object that is supposed to be a expression that can be evaled to create the object. that is,\nobj == eval(repr(obj))\n\nshould, but does not always in practice, yield True\nI was asked in the comments f... | [
27,
10,
3,
1
] | [] | [] | [
"python"
] | stackoverflow_0003764360_python.txt |
Q:
Designing my domain model around one 3rd-party library
I'm working on a poker analysis tool with the following use case:
User create Strategy class with one method: input GameState, output PokerAction
User runs Analysis script, which launches a PokerGame between various Strategy subclasses (i.e. various strategies)
PokerGame generates random deck
PokerGame sends GameState to Strategy
Strategy sends PokerAction to PokerGame
PokerGame updates GameState
When the game is done (managed by PokerGame), send GameResult to Analysis script
User reviews output of Analysis script
There's a third-party library that performs all of the PokerGame functionality. It doesn't match at all with my own modeling of the domain in some areas (e.g. card values, etc.) but performs much of the "hard-to-code" functionality that I need (i.e. the non-trivial steps 4 - 7).
General design question
When faced with a library like this (eliminates a lot of hard coding, but might constrain future design choices in related projects), do you tend to mold the rest of your project to the library? Do you refactor the key library to conform to your domain model? Or is it something else?
Thanks,
Mike
A:
If I really felt my domain model better suited me going forward, I would try to create an abstraction layer to map between the 3rd party library and my own model. This would allow me to take advantage of the library now while providing me with the flexibility to replace it in the future with another 3rd party library or one I created.
Take a look a this list of design patterns, especially the Adapter Pattern.
A:
I would not couple my project tightly to the library, but instead try to abstract functionality and couple both using one or more objects in between. The mediator and/or facade pattern come to my mind here.
| Designing my domain model around one 3rd-party library | I'm working on a poker analysis tool with the following use case:
User create Strategy class with one method: input GameState, output PokerAction
User runs Analysis script, which launches a PokerGame between various Strategy subclasses (i.e. various strategies)
PokerGame generates random deck
PokerGame sends GameState to Strategy
Strategy sends PokerAction to PokerGame
PokerGame updates GameState
When the game is done (managed by PokerGame), send GameResult to Analysis script
User reviews output of Analysis script
There's a third-party library that performs all of the PokerGame functionality. It doesn't match at all with my own modeling of the domain in some areas (e.g. card values, etc.) but performs much of the "hard-to-code" functionality that I need (i.e. the non-trivial steps 4 - 7).
General design question
When faced with a library like this (eliminates a lot of hard coding, but might constrain future design choices in related projects), do you tend to mold the rest of your project to the library? Do you refactor the key library to conform to your domain model? Or is it something else?
Thanks,
Mike
| [
"If I really felt my domain model better suited me going forward, I would try to create an abstraction layer to map between the 3rd party library and my own model. This would allow me to take advantage of the library now while providing me with the flexibility to replace it in the future with another 3rd party lib... | [
2,
1
] | [] | [] | [
"oop",
"python"
] | stackoverflow_0003764851_oop_python.txt |
Q:
Python: What does the use of [] mean here?
What is the difference in these two statements in python?
var = foo.bar
and
var = [foo.bar]
I think it is making var into a list containing foo.bar but I am unsure. Also if this is the behavior and foo.bar is already a list what do you get in each case?
For example: if foo.bar = [1, 2] would I get this?
var = foo.bar #[1, 2]
and
var = [foo.bar] #[[1,2]] where [1,2] is the first element in a multidimensional list
A:
[] is an empty list.
[foo.bar] is creating a new list ([]) with foo.bar as the first item in the list, which can then be referenced by its index:
var = [foo.bar]
var[0] == foo.bar # returns True
So your guess that your assignment of foo.bar = [1,2] is exactly right.
If you haven't already, I recommend playing around with this kind of thing in the Python interactive interpreter. It makes it pretty easy:
>>> []
[]
>>> foobar = [1,2]
>>> foobar
[1, 2]
>>> [foobar]
[[1, 2]]
A:
Yes, it's making a list containing one element, foo.bar.
If foo.bar is [1,2], you indeed get [[1,2]].
For instance,
>> a=[]
>> a.append([1,2])
>> a[0]
[1,2]
>> b=[[1,2]]
>> b[0]
[1,2]
To elaborate a bit more on that exact example,
>> class Foos:
>> bar=[1,2]
>> foo=Foos()
>> foo.bar
[1,2]
>> a=[foo.bar]
>> a
[[1,2]]
>> a[0]
[1,2]
A:
I think it is making var into a list containing foo.bar but I am unsure. Also if this is the behavior and foo.bar is already a list what do you get in each case?
Yes, it creates a new list.
If foo.bar is already a list, it will simply become a list, containing one list.
h[1] >>> l = [1, 2]
h[1] >>> [l]
[[1, 2]]
h[3] >>> l[l][0]
[1, 2]
A:
That pretty much means it's an array/list of stuff with foo.bar being the first item in the list/array.
| Python: What does the use of [] mean here? | What is the difference in these two statements in python?
var = foo.bar
and
var = [foo.bar]
I think it is making var into a list containing foo.bar but I am unsure. Also if this is the behavior and foo.bar is already a list what do you get in each case?
For example: if foo.bar = [1, 2] would I get this?
var = foo.bar #[1, 2]
and
var = [foo.bar] #[[1,2]] where [1,2] is the first element in a multidimensional list
| [
"[] is an empty list. \n[foo.bar] is creating a new list ([]) with foo.bar as the first item in the list, which can then be referenced by its index:\nvar = [foo.bar]\nvar[0] == foo.bar # returns True \n\nSo your guess that your assignment of foo.bar = [1,2] is exactly right.\nIf you haven't already, I recommend pla... | [
14,
3,
1,
0
] | [] | [] | [
"brackets",
"list",
"python",
"syntax",
"variable_assignment"
] | stackoverflow_0003764858_brackets_list_python_syntax_variable_assignment.txt |
Q:
python 2.6.x theading / signals /atexit fail on some versions?
I've seen a lot of questions related to this... but my code works on python 2.6.2 and fails to work on python 2.6.5. Am I wrong in thinking that the whole atexit "functions registered via this module are not called when the program is killed by a signal" thing shouldn't count here because I'm catching the signal and then exiting cleanly? What's going on here? Whats the proper way to do this?
import atexit, sys, signal, time, threading
terminate = False
threads = []
def test_loop():
while True:
if terminate:
print('stopping thread')
break
else:
print('looping')
time.sleep(1)
@atexit.register
def shutdown():
global terminate
print('shutdown detected')
terminate = True
for thread in threads:
thread.join()
def close_handler(signum, frame):
print('caught signal')
sys.exit(0)
def run():
global threads
thread = threading.Thread(target=test_loop)
thread.start()
threads.append(thread)
while True:
time.sleep(2)
print('main')
signal.signal(signal.SIGINT, close_handler)
if __name__ == "__main__":
run()
python 2.6.2:
$ python halp.py
looping
looping
looping
main
looping
main
looping
looping
looping
main
looping
^Ccaught signal
shutdown detected
stopping thread
python 2.6.5:
$ python halp.py
looping
looping
looping
main
looping
looping
main
looping
looping
main
^Ccaught signal
looping
looping
looping
looping
...
looping
looping
Killed <- kill -9 process at this point
The main thread on 2.6.5 appears to never execute the atexit functions.
A:
The root difference here is actually unrelated to both signals and atexit, but rather a change in the behavior of sys.exit.
Before around 2.6.5, sys.exit (more accurately, SystemExit being caught at the top level) would cause the interpreter to exit; if threads were still running, they'd be terminated, just as with POSIX threads.
Around 2.6.5, the behavior changed: the effect of sys.exit is now essentially the same as returning from the main function of the program. When you do that--in both versions--the interpreter waits for all threads to be joined before exiting.
The relevant change is that Py_Finalize now calls wait_for_thread_shutdown() near the top, where it didn't before.
This behavioral change seems incorrect, primarily because it no longer functions as documented, which is simply: "Exit from Python." The practical effect is no longer to exit from Python, but simply to exit the thread. (As a side note, sys.exit has never exited Python when called from another thread, but that obscure divergance from documented behavior doesn't justify a much bigger one.)
I can see the appeal of the new behavior: rather than two ways to exit the main thread ("exit and wait for threads" and "exit immediately"), there's only one, as sys.exit is essentially identical to simply returning from the top function. However, it's a breaking change and diverges from documented behavior, which far outweighs that.
Because of this change, after sys.exit from the signal handler above, the interpreter sits around waiting for threads to exit and then runs atexit handlers after they do. Since it's the handler itself that tells the threads to exit, the result is a deadlock.
A:
Exiting due to a signal is not the same as exiting from within a signal handler. Catching a signal and exiting with sys.exit is a clean exit, not an exit due to a signal handler. So, yes, I agree that it should run atexit handlers here--at least in principle.
However, there's something tricky about signal handlers: they're completely asynchronous. They can interrupt the program flow at any time, between any VM opcode. Take this code, for example. (Treat this as the same form as your code above; I've omitted code for brevity.)
import threading
lock = threading.Lock()
def test_loop():
while not terminate:
print('looping')
with lock:
print "Executing synchronized operation"
time.sleep(1)
print('stopping thread')
def run():
while True:
time.sleep(2)
with lock:
print "Executing another synchronized operation"
print('main')
There's a serious problem here: a signal (eg. ^C) may be received while run() is holding lock. If that happens, your signal handler will be run with the lock still held. It'll then wait for test_loop to exit, and if that thread is waiting for the lock, you'll deadlock.
This is a whole category of problems, and it's why a lot of APIs say not to call them from within signal handlers. Instead, you should set a flag to tell the main thread to shut down at an appropriate time.
do_shutdown = False
def close_handler(signum, frame):
global do_shutdown
do_shutdown = True
print('caught signal')
def run():
while not do_shutdown:
...
My preference is to avoid exiting the program with sys.exit entirely and to explicitly do cleanup at the main exit point (eg. the end of run()), but you can use atexit here if you want.
A:
I'm not sure if this was entirely changed, but this is how I have my atexit done in 2.6.5
atexit.register(goodbye)
def goodbye():
print "\nStopping..."
| python 2.6.x theading / signals /atexit fail on some versions? | I've seen a lot of questions related to this... but my code works on python 2.6.2 and fails to work on python 2.6.5. Am I wrong in thinking that the whole atexit "functions registered via this module are not called when the program is killed by a signal" thing shouldn't count here because I'm catching the signal and then exiting cleanly? What's going on here? Whats the proper way to do this?
import atexit, sys, signal, time, threading
terminate = False
threads = []
def test_loop():
while True:
if terminate:
print('stopping thread')
break
else:
print('looping')
time.sleep(1)
@atexit.register
def shutdown():
global terminate
print('shutdown detected')
terminate = True
for thread in threads:
thread.join()
def close_handler(signum, frame):
print('caught signal')
sys.exit(0)
def run():
global threads
thread = threading.Thread(target=test_loop)
thread.start()
threads.append(thread)
while True:
time.sleep(2)
print('main')
signal.signal(signal.SIGINT, close_handler)
if __name__ == "__main__":
run()
python 2.6.2:
$ python halp.py
looping
looping
looping
main
looping
main
looping
looping
looping
main
looping
^Ccaught signal
shutdown detected
stopping thread
python 2.6.5:
$ python halp.py
looping
looping
looping
main
looping
looping
main
looping
looping
main
^Ccaught signal
looping
looping
looping
looping
...
looping
looping
Killed <- kill -9 process at this point
The main thread on 2.6.5 appears to never execute the atexit functions.
| [
"The root difference here is actually unrelated to both signals and atexit, but rather a change in the behavior of sys.exit.\nBefore around 2.6.5, sys.exit (more accurately, SystemExit being caught at the top level) would cause the interpreter to exit; if threads were still running, they'd be terminated, just as wi... | [
8,
3,
0
] | [] | [] | [
"atexit",
"multithreading",
"python",
"signals"
] | stackoverflow_0003713360_atexit_multithreading_python_signals.txt |
Q:
Is there a way to tell if I'm using recursion in Python?
I'm writing a function to traverse the user's file system and create a tree representing that directory (the tree is really a TreeView widget in Tkinter, but that's functionally a tree).
The best way I can think of doing this is recursion. However, one of my cases in the function requires me to know if it is the "original" function call, in which case the files have no parent node, or if it is a "recursive" function call, i.e. a call that has been made by the function itself, so that I can give those files an appropriate parent node.
Is there any way in Python to ask a function, "hey, are you recursive?" or "hey, where were you called from?"
A:
Pretty much the same as in every other language - in your case, you pass a reference to the parent and check if it is None. If so, you create a proper parent node.
A:
one of my cases in the function requires me to know if it is the "original" function call, in which case the files have no parent node
This seems like a strange case of too much work for the specific function. You have to construct the tree - why do you need to know where it's attached? Why not just construct the nodes you're responsible for and return them?
def make_tree(path):
return [
make_tree(os.path.join(path, element))
for element in get_elements(path)]
And walk the tree again when you receive it?
If you really want to integrate it, just pass the parent:
def make_tree(path, parent_node = None):
new_node = Node(...)
for ....:
make_tree(path+..., new_node)
if parent_node is not None:
parent_node.add(new_node)
else:
.....
A:
It should be easy and common, to include a reference to the parent or some level information along with the call to the recursion.
One other way (which I wouldn't prefer, though) is to use pythons inspect module, which lets you inspect e.g. the call stack. An example:
#!/usr/bin/env python
import inspect
def whocalled():
return inspect.stack()[2][3]
def fib(n):
print n, whocalled()
if n < 2:
return n
return fib(n - 1) + fib(n - 2)
if __name__ == '__main__':
fib(4)
Would print:
4 <module>
3 fib
2 fib
1 fib
0 fib
1 fib
2 fib
1 fib
0 fib
A:
You can access the memory stack through the inspectmodule.
import inspect
def whoami():
'''Returns the function name of the caller.'''
return inspect.stack()[1][3] #Stack data for the name of the function
def caller():
'''Returns the caller of a function.'''
return inspect.stack()[2][3] #Stack data for the name of whatever calls this
caller = caller()
You'll get an index out of range error if you attempt to call it from __main__.
when the caller of the function != whoami() -> no longer recursing.
A:
I really wonder why you make this so complicated. You can simply split the function in a recursive and a not recursive part! Here is a simple example:
def countdown(n):
" original function "
print "Ok, start the countdown (not recursive)"
msg = "We are at"
def recursive( x ):
" recursive part "
if x >= 0:
print msg, x, "(recursive)"
return recursive(x-1)
return recursive(n)
countdown(10)
In reality you don't even need many arguments to the recursive function because it is a closure and can use anything you defined in it's namespace.
| Is there a way to tell if I'm using recursion in Python? | I'm writing a function to traverse the user's file system and create a tree representing that directory (the tree is really a TreeView widget in Tkinter, but that's functionally a tree).
The best way I can think of doing this is recursion. However, one of my cases in the function requires me to know if it is the "original" function call, in which case the files have no parent node, or if it is a "recursive" function call, i.e. a call that has been made by the function itself, so that I can give those files an appropriate parent node.
Is there any way in Python to ask a function, "hey, are you recursive?" or "hey, where were you called from?"
| [
"Pretty much the same as in every other language - in your case, you pass a reference to the parent and check if it is None. If so, you create a proper parent node.\n",
"\none of my cases in the function requires me to know if it is the \"original\" function call, in which case the files have no parent node\n\nTh... | [
7,
4,
1,
1,
1
] | [] | [] | [
"functional_programming",
"python",
"recursion",
"traversal",
"tree"
] | stackoverflow_0003764879_functional_programming_python_recursion_traversal_tree.txt |
Q:
How to use subqueries in SQLAlchemy to produce a moving average?
My problem is that I want to retrieve both a list of measurements along with a moving average of those measurements. I can do that with this SQL statement (postgresql interval syntax):
SELECT time, value,
(
SELECT AVG(t2.value)
FROM measurements t2
WHERE t2.time BETWEEN t1.time - interval '5 days' AND t1.time
) moving_average
FROM measurements t1
ORDER BY t1.time;
I want to have the SQLAlchemy code to produce a similar statement to this effect. I currently have this Python code:
moving_average_days = # configureable value, defaulting to 5
t1 = Measurements.alias('t1')
t2 = Measurements.alias('t2')
query = select([t1.c.time, t1.c.value, select([func.avg(t2.c.value)], t2.c.time.between(t1.c.time - datetime.timedelta(moving_average_days), t1.c.time))],
t1.c.time > (datetime.datetime.utcnow() - datetime.timedelta(ndays))). \
order_by(Measurements.c.time)
That however, generates this SQL:
SELECT t1.time, t1.value, avg_1
FROM measurements AS t1,
(
SELECT avg(t2.value) AS avg_1
FROM measurements AS t2
WHERE t2.time BETWEEN t1.time - %(time_1)s AND t1.time
)
WHERE t1.time > %(time_2)s
ORDER BY t1.time;
That SQL has the subquery as part of the FROM clause where it cannot have scalar access to the column values of the top-level values, i.e. it causes PostgreSQL to spit out this error:
ERROR: subquery in FROM cannot refer to other relations of same query level
LINE 6: WHERE t2.time BETWEEN t1.time - interval '5 days' AN...
What I would thus like to know is: how do I get SQLAlchemy to move the subquery to the SELECT clause?
Alternatively another way to get a moving average (without performing a query for each (time,value) pair) would be an option.
A:
Right, apparently what I needed was the use of a so-called scalar select. With the use of those I get this python code, which actually works as I want it to (generates the equivalent SQL to that of the first in my question which was my goal):
moving_average_days = # configurable value, defaulting to 5
ndays = # configurable value, defaulting to 90
t1 = Measurements.alias('t1') ######
t2 = Measurements.alias('t2')
query = select([t1.c.time, t1.c.value,
select([func.avg(t2.c.value)],
t2.c.time.between(t1.c.time - datetime.timedelta(moving_average_days), t1.c.time)).label('moving_average')],
t1.c.time > (datetime.datetime.utcnow() - datetime.timedelta(ndays))). \
order_by(t1.c.time)
This gives this SQL:
SELECT t1.time, t1.value,
(
SELECT avg(t2.value) AS avg_1
FROM measurements AS t2
WHERE t2.time BETWEEN t1.time - :time_1 AND t1.time
) AS moving_average
FROM measurements AS t1
WHERE t1.time > :time_2 ORDER BY t1.time;
| How to use subqueries in SQLAlchemy to produce a moving average? | My problem is that I want to retrieve both a list of measurements along with a moving average of those measurements. I can do that with this SQL statement (postgresql interval syntax):
SELECT time, value,
(
SELECT AVG(t2.value)
FROM measurements t2
WHERE t2.time BETWEEN t1.time - interval '5 days' AND t1.time
) moving_average
FROM measurements t1
ORDER BY t1.time;
I want to have the SQLAlchemy code to produce a similar statement to this effect. I currently have this Python code:
moving_average_days = # configureable value, defaulting to 5
t1 = Measurements.alias('t1')
t2 = Measurements.alias('t2')
query = select([t1.c.time, t1.c.value, select([func.avg(t2.c.value)], t2.c.time.between(t1.c.time - datetime.timedelta(moving_average_days), t1.c.time))],
t1.c.time > (datetime.datetime.utcnow() - datetime.timedelta(ndays))). \
order_by(Measurements.c.time)
That however, generates this SQL:
SELECT t1.time, t1.value, avg_1
FROM measurements AS t1,
(
SELECT avg(t2.value) AS avg_1
FROM measurements AS t2
WHERE t2.time BETWEEN t1.time - %(time_1)s AND t1.time
)
WHERE t1.time > %(time_2)s
ORDER BY t1.time;
That SQL has the subquery as part of the FROM clause where it cannot have scalar access to the column values of the top-level values, i.e. it causes PostgreSQL to spit out this error:
ERROR: subquery in FROM cannot refer to other relations of same query level
LINE 6: WHERE t2.time BETWEEN t1.time - interval '5 days' AN...
What I would thus like to know is: how do I get SQLAlchemy to move the subquery to the SELECT clause?
Alternatively another way to get a moving average (without performing a query for each (time,value) pair) would be an option.
| [
"Right, apparently what I needed was the use of a so-called scalar select. With the use of those I get this python code, which actually works as I want it to (generates the equivalent SQL to that of the first in my question which was my goal):\nmoving_average_days = # configurable value, defaulting to 5\nndays = # ... | [
5
] | [] | [] | [
"postgresql",
"python",
"sqlalchemy",
"subquery"
] | stackoverflow_0003764358_postgresql_python_sqlalchemy_subquery.txt |
Q:
Python Array with String Indices
Is it possible to use strings as indices in an array in python?
For example:
myArray = []
myArray["john"] = "johns value"
myArray["jeff"] = "jeffs value"
print myArray["john"]
A:
What you want is called an associative array. In python these are called dictionaries.
Dictionaries are sometimes found in other languages as “associative memories” or “associative arrays”. Unlike sequences, which are indexed by a range of numbers, dictionaries are indexed by keys, which can be any immutable type; strings and numbers can always be keys.
myDict = {}
myDict["john"] = "johns value"
myDict["jeff"] = "jeffs value"
Alternative way to create the above dict:
myDict = {"john": "johns value", "jeff": "jeffs value"}
Accessing values:
print(myDict["jeff"]) # => "jeffs value"
Getting the keys (in Python v2):
print(myDict.keys()) # => ["john", "jeff"]
In Python 3, you'll get a dict_keys, which is a view and a bit more efficient (see views docs and PEP 3106 for details).
print(myDict.keys()) # => dict_keys(['john', 'jeff'])
If you want to learn about python dictionary internals, I recommend this ~25 min video presentation: https://www.youtube.com/watch?v=C4Kc8xzcA68. It's called the "The Mighty Dictionary".
A:
Even better, try an OrderedDict (assuming you want something like a list). Closer to a list than a regular dict since the keys have an order just like list elements have an order. With a regular dict, the keys have an arbitrary order.
Note that this is available in Python 3 and 2.7. If you want to use with an earlier version of Python you can find installable modules to do that.
| Python Array with String Indices | Is it possible to use strings as indices in an array in python?
For example:
myArray = []
myArray["john"] = "johns value"
myArray["jeff"] = "jeffs value"
print myArray["john"]
| [
"What you want is called an associative array. In python these are called dictionaries.\n\nDictionaries are sometimes found in other languages as “associative memories” or “associative arrays”. Unlike sequences, which are indexed by a range of numbers, dictionaries are indexed by keys, which can be any immutable ty... | [
176,
5
] | [] | [] | [
"arrays",
"dictionary",
"list",
"python"
] | stackoverflow_0003765533_arrays_dictionary_list_python.txt |
Q:
Running python on a Windows machine vs Linux
I am interested in learning python but my Linux skills suck. I would like to develop a medium to large scale web application using python and django but afraid the software may not work well on a windows box. Is there a performance difference in running python on Linux vs Windows? Is there anything that I should watch out for when developing the application. Also, I am aware that it is very easy integrating C++ libraries with python. Is this statement still true is the code is on a windows box?
A:
Don't tell anybody this, but I've run python/django on windows. It works all right and the performance hit isn't any worse than you would expect from windows. I used MySQL and it installed without a problem. I had to grope around to find out how to manage it (no good ol' sudo /etc/init.d/mysql restart but i eventually found a graphical interface to do what I needed.
A:
but afraid the software may not work well on a windows box.
Your software will work. The Windows OS may not work as you hope. But that's Windows, not Python.
We develop 100% on Windows. We completely test: Unit test, integration test and user acceptance test on Windows. 100%.
We deploy for production 0% on Windows, 100% on Linux.
We have a few (less than 6) differences in the unit tests that are Windows-specific.
The application has no changes. It works with Apache or not. It works with SQLite or MySQL.
A:
I've been working Py on both Windows and Linux. I favor Linux because of several things:
virtualenvs - once you start working with virtualenvs, there is no turning back.
SHELL - CMD is very frustrating when executing python/management commands in django. Also, you should add python.exe every time :).
ipython works better on Linux.
GeoDjango doesn't work on Vista/7 last time i checked. I spent 3 days trying to set it up. Just for comparison, i set GeoDjango-able development environment in 20 minutes in Linux.
Linux is free :)
Although there is no visible performance impact or incompatibility when working python cross-platform, the benefits of Linux for python development outweigh Windows by a lot. It's a lot more comfortable and definitely will boost your productivity.
...
IMHO Linux is the smart choice for Python development.
A:
Python program is very easily portable. Most of the time your code will work on any platform that have the appropriate version of python.
One point to be aware of though, is file path handling. Linux, Windows, Macs, etc uses different path schemes, so you shouldn't be handling them as strings; instead use os.path functions to join, split, etc.
There is ultimately some slight performance difference with regard to timing, threading, processing, I/O, but they're nothing to worry about.
Integrating Python and C++ is easy; the only problem is in the C++ side, i.e. you will have to recompile the C++ code.
A:
Shouldn't be a problem. Some people even host Python+Django on Windows.
A:
Which software are you affraid will not work on windows, the actual web app or your development enviroment. If you mean the IDE, then I wouldn't worry about that there are very good python IDEs for windows, as for the webapp that's another discussion all together
The statement that "it is very easy integrating C++ libs with python" is not accurate, there are many ways of doing it and they are not all easy, I have personally only tried SWIG, but there are many other alternatives (for example Boost.Python), whoever I wouldn't believe it is as easy to get up and running with some of these tools on a windows enviromeny with out something like mingw or cygwin as at least SWIG is built with *nix in mind
| Running python on a Windows machine vs Linux | I am interested in learning python but my Linux skills suck. I would like to develop a medium to large scale web application using python and django but afraid the software may not work well on a windows box. Is there a performance difference in running python on Linux vs Windows? Is there anything that I should watch out for when developing the application. Also, I am aware that it is very easy integrating C++ libraries with python. Is this statement still true is the code is on a windows box?
| [
"Don't tell anybody this, but I've run python/django on windows. It works all right and the performance hit isn't any worse than you would expect from windows. I used MySQL and it installed without a problem. I had to grope around to find out how to manage it (no good ol' sudo /etc/init.d/mysql restart but i eventu... | [
16,
14,
9,
1,
1,
1
] | [] | [] | [
"python",
"windows"
] | stackoverflow_0003765178_python_windows.txt |
Q:
Use of cycle in django
I have a webpage where I am looping,and using cycle inside the loop.
{% for o in something %}
{% for c in o %}
<div class="{% cycle 'white' 'black'%}"></div>
{% endfor %}
Now, this means everytime inside the loop, first div tag gets white.But,what I want is to alternate between white and black i.e. start with white, then next time when inside the loop start the first div tag with black.Is it possible to achieve here?
A:
There is an accept bug open about this issue. You may want to try the proposed change to see if it works for you.
If you do not want to try it, or it does not work, give this a shot:
{% cycle 'white' 'black' as divcolors %}
{% for o in something %}
{% for c in o %}
<div class="{% cycle divcolors %}"></div>
{% endfor %}
{% endfor %}
As I understand it, the cycle would start at white, and then loop through the values each time inside the loop (meaning you won't restart at white every time).
A:
Something like this might work (untested):
{% for o in something %}
{% for c in o %}
{% ifchanged forloop.parent.counter %}
<div class="{% cycle 'white' 'black' %}"></div>
{% else %}
<div class="{% cycle 'black' 'white' %}"></div>
{% endifchanged %}
{% endfor %}
{% endfor %}
| Use of cycle in django | I have a webpage where I am looping,and using cycle inside the loop.
{% for o in something %}
{% for c in o %}
<div class="{% cycle 'white' 'black'%}"></div>
{% endfor %}
Now, this means everytime inside the loop, first div tag gets white.But,what I want is to alternate between white and black i.e. start with white, then next time when inside the loop start the first div tag with black.Is it possible to achieve here?
| [
"There is an accept bug open about this issue. You may want to try the proposed change to see if it works for you.\nIf you do not want to try it, or it does not work, give this a shot:\n{% cycle 'white' 'black' as divcolors %}\n{% for o in something %}\n {% for c in o %}\n <div class=\"{% cycle divcolors ... | [
4,
0
] | [] | [] | [
"django",
"django_templates",
"python"
] | stackoverflow_0000861855_django_django_templates_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.