Tkinter on dual screen

2005-02-01 Thread nik
hello,

i am writing an app which is running on a dual screen setup on windows
and OS X. is anyone doing this using Tkinter? are there problems with
it?

i know Tk() takes a "screenname" argument which specifies the screen.
but i am not sure about how well Tkinter copes with having two Tk
objects and i could not find any documentation as to what the screens
are called.

- what are the screen names for screen 1 / 2 on windows / linux / OS X?
- is there a Tk command that can check for multiple screens? ideally i
would like something like
names = getScreenNames()
that tells me how many screens there are and what they are called. then
i could write my app so that it runs on any OS and with any number of
screens. all the examples i have seen so far rely on a
platform-specific name which seems to come out of nowhere...
- are you running dual screen Tkinter and is it working? what are the
pitfalls?

thanks for any help!

nik

-- 
http://mail.python.org/mailman/listinfo/python-list


read 9 bytes

2007-06-10 Thread nik
Hi,

I need to read a 9 byte response from a device on the serial port.
>From reading the pySerial documentation it appears that I can only
read in characters at a time.

If I do: serialport.read(4)
I would get 8 bytes, and if I did
serialport.read(5)
I think the port will block until a time out, since there

Is there a trick to read 9 bytes off of a serial port?

Thanks,
Nik

-- 
http://mail.python.org/mailman/listinfo/python-list


save class

2007-06-13 Thread nik
Hi,

I would like to create a class and then save it for re-use later. I
have tried to use pickle, but am not sure if that is right. I am
sorry, but I am new to python.

Basically, I have a class, Map. I want to be able to create new maps:
MapA, MapB... that have Map as the base class.

start with-
class Map:
pass

and then get a different class

class MapA(Map):
pass

that can be saved in a .py file for re-use

so far I thought that -
cls = new.classobj('MapA', (Map, ), {})
file = open('somefile', mode='w')
pickle.dump(cls, file)

-might work, but it didn't can anybody point me in the right
direction? I know that classes must get saved from the interactive
console, so I would think that it would be a standard thing to do.

Thank you,
Nik

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: save class

2007-06-13 Thread nik
On Jun 13, 6:48 pm, "Gabriel Genellina" <[EMAIL PROTECTED]>
wrote:
> En Wed, 13 Jun 2007 22:20:16 -0300, nik <[EMAIL PROTECTED]> escribió:
>
> > I would like to create a class and then save it for re-use later. I
> > have tried to usepickle, but am not sure if that is right. I am
> > sorry, but I am new to python.
>
> Do you want to save the *source*code* of your class, or do you want to
> save created *instances* -objects- of your classes to retrieve them later
> (like a database)?
>
> > Basically, I have a class, Map. I want to be able to create new maps:
> > MapA, MapB... that have Map as the base class.
>
> > start with-
> > class Map:
> > pass
>
> > and then get a different class
>
> > class MapA(Map):
> > pass
>
> > that can be saved in a .py file for re-use
>
> You just create the .py file with any text editor, containing the source
> code for all your classes.
>
> > so far I thought that -
> > cls = new.classobj('MapA', (Map, ), {})
> > file = open('somefile', mode='w')
> >pickle.dump(cls, file)
>
> > -might work, but it didn't can anybody point me in the right
> > direction? I know that classes must get saved from the interactive
> > console, so I would think that it would be a standard thing to do.
>
> This would try to save the *class* definition, which is usually not
> required because they reside on your source files.
> If this is actually what you really want to do, try to explain us exactly
> why do you think so. Chances are that there is another solution for this.
>
> --
> Gabriel Genellina

Thanks for the response.

It would seem that I want to actually save the source code for the
class. I know that I could of course open up an editor and just make
it, but my ideal would be to have the base class, Map, be able to make
the sub-classes. I don't want the class definition. What I want is an
actual class that I could later import and use somewhere else. I am
planning to have each one of these map objects contain a different
dictionary and then be able to import the map into the application,
but have certain methods defined in the Map super-class to draw data
out of the specific map's specific dictionary. I hope that makes
sense.

Something like,
class Map:
     dict = {}
 def DoSomething(self):
 pass

 def MakeNewMapSubClass(self, newclassname):
 """ make a new file, newclassname.py that contains a new
class
 newclassname(Map) that inherits from base-class Map.

Thanks,
Nik

-- 
http://mail.python.org/mailman/listinfo/python-list

Re: save class

2007-06-14 Thread nik
On Jun 13, 10:04 pm, Josiah Carlson <[EMAIL PROTECTED]>
wrote:
> Gabriel Genellina wrote:
> > En Wed, 13 Jun 2007 23:11:22 -0300, nik <[EMAIL PROTECTED]> escribió:
> >> It would seem that I want to actually save the source code for the
> >> class. I know that I could of course open up an editor and just make
> >> it, but my ideal would be to have the base class, Map, be able to make
> >> the sub-classes. I don't want the class definition. What I want is an
> >> actual class that I could later import and use somewhere else. I am
> >> planning to have each one of these map objects contain a different
> >> dictionary and then be able to import the map into the application,
> >> but have certain methods defined in the Map super-class to draw data
> >> out of the specific map's specific dictionary. I hope that makes
> >> sense.
>
> >> Something like,
> >> class Map:
> >>  dict = {}
> >>  def DoSomething(self):
> >>  pass
>
> >>  def MakeNewMapSubClass(self, newclassname):
> >>  """ make a new file, newclassname.py that contains a new
> >> class
> >>  newclassname(Map) that inherits from base-class Map.
>
> > And are you sure you actually need different subclasses? Will you
> > construct them several instances of each subclass? From the above
> > description I feel you want just different Map *instances*, each with
> > its own dict, not different *subclasses*.
>
> What you said, and that his solution sounds like a Java approach to the
> problem (subclass an abstract base class that calls specific methods on
> the subclass to "do the right thing").
>
> To offer the OP source he can use...
>
> class Map:
>  def __init__(self):
>  self.dict = {}
>  def DoSomething(self):
>  #do something with self.dict
>
> Every instance gets a new dictionary.  Now, if he actually wants to
> change the behavior of the DoSomething method, of course then it would
> make sense to subclass Map.
>
>   - Josiah

I am hoping to change the self.dict for each subclass. I realize that
I could save self.dict to file and then load in different dicts each
time I get a new instance of class. But I want to be able to make
subclasses of map that each have different self.dict. Then when I need
to use them, just import the module and use the specific dict, instead
of having to keep track of a separate dictionary file. I am new to
this, but I thought that this would be a regular thing to do in
python, because people must make classes in the interactive console
and then export them somehow for later use.

Thank you for your responses.

-- 
http://mail.python.org/mailman/listinfo/python-list

serial readline thread IO Error (9, 'Bad file descriptor')

2007-06-19 Thread nik
Hi,
How can I close a thread that is waiting on a file/port down
gracefully, and not have an IO error pop up?

I am having trouble closing a thread that is listening to the serial
port. I have a thread that calls uses a pySerial serial port and calls
readline() without a timeout, which is blocking. When I am shutting
down the application I close the serial port, which causes the IO
error: (9, 'Bad file descriptor'). It makes sense that we would get
this error, because it is trying to read off of a closed 'file'. Is
there a better way to close this thread and port down?

Thanks,
Nik

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: save class

2007-06-19 Thread nik
Thank you for all the responses. In light of what you've told me I
have gone back to storing my specific dictionaries in text files and
then reading them in to the class.

Thank you,
Nik


-- 
http://mail.python.org/mailman/listinfo/python-list


VB frontend to Python COM backend

2007-07-05 Thread nik
I have a VB6 application that I would like to attach to a python
communications application.

I have come across several discussions on using VB with a Python COM
back-end, but no starting point. I haven't had anymore luck with
google at finding out what this method is called and where to find
more information or examples on it. I would really appreciate it if
someone could point me in the right direction for using python objects
from VB.

Thank you,
Nik

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: VB frontend to Python COM backend

2007-07-06 Thread nik
Thank you for the lead. That is exactly what I was wishing for.

Thank you,
Nik

-- 
http://mail.python.org/mailman/listinfo/python-list


subprocess popen trouble

2007-07-10 Thread nik
I am having trouble using subprocess popen and stdin/stdout

I have the following simple test application written in C++, that just
echoes back the stdin. It works fine running from the command line:

#include 
#include 

int main (int argc, char * const argv[]) {
int currenttemp = 0;
int settemp = 0;
char* str;

while(currenttemp < 500){
gets(str);
sscanf(str, ">%d", &settemp);
currenttemp = settemp;
printf("<%d\n", currenttemp++);
}
return 0;
}

##
Then I have the following python code. A listener thread that waits
for the output of test and the main part that creates the subprocess
Popen object, passes it to the thread and then sends user input to the
subprocess test.


import subprocess
import os, sys
from threading import *
import time

class TempXListen(Thread):
""" thread to listen for incomming
messages and put them onto a
shared queue, no time lost processing incoming lines
"""
def __init__(self, channel):
""" connect internal response queue
to external queue
"""
Thread.__init__(self)
self.setDaemon(True)
self._channel = channel
self.start()

def run(self):
""" listening loop
reads line off of input source
puts the line into the response Q shared with parent
thread
sets event that parent is waiting for to indicate Q has at
least 1 element
"""
while 1:
try:
response = self._channel.stdout.readline() #
read input line
print response
except Exception, e:
print 'Listener Exception: ' + str(e)


print "Temp Monitor Test"
tempx = subprocess.Popen('/Users/engineeringadmin/Documents/test/build/
Debug/test', \
 bufsize=1, stdin=subprocess.PIPE,
stdout=subprocess.PIPE, \
 stderr=subprocess.PIPE)

print tempx.stderr.readline()

listener = TempXListen(tempx)
while 1:
data = sys.stdin.readline()
if data != '':
data = '>' + data + '\n'
tempx.stdin.write(data)
print data
time.sleep(1)


###
When I run it this is the output:

Temp Monitor Test
warning: this program uses gets(), which is unsafe.

45
>45


The subprocess is opened, because the warning is coming off of the
test applications stderr, but nothing else seems to go in or out. I've
been looking at a lot of examples and a lot of different postings, and
can't see any mistakes in my use of subprocess. I would really
appreciate it if somebody could see where I am going wrong.

Thank you,
Nik

-- 
http://mail.python.org/mailman/listinfo/python-list


interactive graphical script builder

2007-07-11 Thread nik
Hi,

I am looking for an interactive graphical script builder for python.
Basically, something like the os X automator. I have made a group of
methods that some non-programmers need to combine into a script. I
don't need a python IDE necessarially, but more of a sequence builder.
I am imagining a tool that could show graphical representations of my
different commands and then string them together in a single "script."
I've done a lot of googling, and the closest things that I can find
are apple automator or labview, but before I go through the process of
making one of those interact with python I would like to know if
anybody already knows of something like them that is more tuned to
python.

Thanks,
Nik

-- 
http://mail.python.org/mailman/listinfo/python-list


ScrolledText?

2007-05-01 Thread nik
I've been trying to get the scrollbar and text box always going to the
last line and have been completely unsuccessful.

I've tried, ScrolledText, text.see, and text.yview_pickplace without
success

for instance this was the last setup:

 self.text = ScrolledText(master, relief=RIDGE)
 self.text.grid(column=1, row=2, columnspan=10,\
rowspan=5, pady=10, sticky=NSEW)

with this text entry:

 self.text.insert(END, ins)
 self.text.yview_pickplace("end")

Can anybody please tell me what I might be doing wrong, or an example
that works, so that I can see what's going wrong.

Thanks,
Nik

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ScrolledText?

2007-05-01 Thread nik
Thank you, but I am not sure.
What is wx in this case?

I should have mentioned that I am using Tkinter, am pretty new to
python
and had previously tried just a plain text box with a scrollbar
without success.
The scrollbar always works manually, nothing I've tried yet has
scrolled down automatically.

Thanks

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ScrolledText?

2007-05-02 Thread nik
Great thank you for the help, we got it working.

-- 
http://mail.python.org/mailman/listinfo/python-list


tracking/ordering log files

2007-10-23 Thread nik
Hi,

I heard that there was a utility for keeping files and specifically
log files organized, but haven't been able to find anything but the
logging class. The logging class seems to help create the content of a
log file, but unless I am missing something, it doesn't keep track of
multiple log files.

What I am looking for is some utility that allows me to create a log
file, say test.log, when the program runs. Then the next time it runs
it will see that test.log already exists and will create test.log.1 or
something similiar. Ideally it would also be able to throw out log
files that are older than a certain date or sequence, so if we got to
creating the 10th file it would delete the first one and so on.

I am sorry for the ambiguois question, but I was told this existed,
can't find it and would like to know if I'm on a wild goose chase and
should just put something together myself.

Thank you,
Nik

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: tracking/ordering log files

2007-10-23 Thread nik
On Oct 23, 11:46 am, nik <[EMAIL PROTECTED]> wrote:
> Hi,
>
> I heard that there was a utility for keeping files and specifically
> log files organized, but haven't been able to find anything but the
> logging class. The logging class seems to help create the content of a
> log file, but unless I am missing something, it doesn't keep track of
> multiple log files.
>
> What I am looking for is some utility that allows me to create a log
> file, say test.log, when the program runs. Then the next time it runs
> it will see that test.log already exists and will create test.log.1 or
> something similiar. Ideally it would also be able to throw out log
> files that are older than a certain date or sequence, so if we got to
> creating the 10th file it would delete the first one and so on.
>
> I am sorry for the ambiguois question, but I was told this existed,
> can't find it and would like to know if I'm on a wild goose chase and
> should just put something together myself.
>
> Thank you,
> Nik


I think it is called "logfile rotation" and see some links about
log4py, but no description of what that is.
thanks

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: tracking/ordering log files

2007-11-16 Thread nik
OK, that's it,
so to do what I want I am using:
self.logger = logging.getLogger('debuglog')
hdlr = logging.handlers.RotatingFileHandler(debugfilename,
'a', 0, 5)
hdlr.doRollover()
formatter = logging.Formatter('%(asctime)s %
(levelname)s:%(message)s')
hdlr.setFormatter(formatter)
self.logger.addHandler(hdlr)


Thanks for your help
-- 
http://mail.python.org/mailman/listinfo/python-list


ISO with timezone

2008-01-28 Thread nik
Hi,

How does one express the time in ISO format with the timezone
designator?

what I want is -MM-DDThh:mm:ss.sTZD

>From the documentation I see:
>>> from datetime import tzinfo, timedelta, datetime
>>> class TZ(tzinfo):
... def utcoffset(self, dt): return timedelta(minutes=-399)
...
>>> datetime(2002, 12, 25, tzinfo=TZ()).isoformat(' ')
'2002-12-25 00:00:00-06:39'

and I've also figured out:
>>>datetime.datetime.fromtimestamp(time.time()).isoformat()[:-3]
'2008-01-23T11:22:54.130'

But can't figure out how to fit them together.

Thank you,
Nik
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ISO with timezone

2008-01-29 Thread nik
On Jan 29, 10:56 am, nik <[EMAIL PROTECTED]> wrote:
> Thanks,
> that does help and now I have:
>
> >>> from datetime import datetime, tzinfo, timedelta
> >>> import time
> >>> class TZ(tzinfo):
>
> ...def utcoffset(self,dt): return timedelta(seconds=time.timezone)
> ...>>> print datetime(2008,2,29,15,30,11,tzinfo=TZ()).isoformat()
>
> 2008-02-29T15:30:11+8:00
>
> But what I want to know now it how to get the actual time into the
> expression instead of typing the 2008,2,29,15
> So something like: >>> print
> datetime(time.gmtime(),tzinfo=TZ()).isoformat(), but that doesn't
> work.
>
> I realize that I could do:
>
> >>> t = time.localtime()
> >>> print datetime(t[0],t[1],t[2],t[3],t[4],t[5],tzinfo=TZ()).isoformat()
>
> but I imagine there might be a cleaner way of doing this.
>
> Thanks,
> Nik
>
> On Jan 28, 9:10 pm, "Nicholas F. Fabry" <[EMAIL PROTECTED]>
> wrote:
>
> > Hello, nik.
>
> > On Jan 28, 2008, at 21:03, nik wrote:
>
> > > Hi,
>
> > > How does one express the time in ISO format with the timezone
> > > designator?
>
> > > what I want is -MM-DDThh:mm:ss.sTZD
>
> > >> From the documentation I see:
> > >>>> from datetime import tzinfo, timedelta, datetime
> > >>>> class TZ(tzinfo):
> > > ... def utcoffset(self, dt): return timedelta(minutes=-399)
> > > ...
> > >>>> datetime(2002, 12, 25, tzinfo=TZ()).isoformat(' ')
> > > '2002-12-25 00:00:00-06:39'
>
> > > and I've also figured out:
> > >>>> datetime.datetime.fromtimestamp(time.time()).isoformat()[:-3]
> > > '2008-01-23T11:22:54.130'
>
> > > But can't figure out how to fit them together.
>
> > There is nothing there to 'fit together' - in the first example given,
> > the datetime object has no time component specified, so it fills in
> > default vaules of zero.  The following should make this clear:
>
> >  >>> your_time = datetime(2008, 2, 29, 15, 30, 11, tzinfo=TZ())
> >  >>> print your_time
> > 2008-02-29 15:30:11-05:00
> >  >>> print your_time.isoformat('T')
> > 2008-02-29T15:30:11-05:00
>
> > If you wish to append the NAME of the tzinfo object instead of its
> > offset, that requires a bit more playing around (along with a properly
> > defined tzinfo object - check out dateutil or pytz for a concrete
> > implementation of tzinfo subclasses (i.e. timezones)), but the
> > following would work:
>
> >  >>> print your_time.strftime('%Y-%m-%dT%H:%M:%S %Z')
> > 2008-02-29T15:30:11 EST
>
> > For details on how the .strftime method works, see Python Standard
> > Library, Section 14.2.
>
> > I hope this helps!
>
> > Nick Fabry
>
> > > Thank you,
> > > Nik
> > > --
> > >http://mail.python.org/mailman/listinfo/python-list

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ISO with timezone

2008-01-29 Thread nik
Thanks,
that does help and now I have:

>>> from datetime import datetime, tzinfo, timedelta
>>> import time
>>> class TZ(tzinfo):
...def utcoffset(self,dt): return timedelta(seconds=time.timezone)
...
>>> print datetime(2008,2,29,15,30,11,tzinfo=TZ()).isoformat()
2008-02-29T15:30:11+8:00


But what I want to know now it how to get the actual time into the
expression instead of typing the 2008,2,29,15
So something like: >>> print
datetime(time.gmtime(),tzinfo=TZ()).isoformat(), but that doesn't
work.

I realize that I could do:
>>> t = time.gmtime()
>>> print datetime(t[0],t[1],t[2],t[3],t[4],t[5],tzinfo=TZ()).isoformat()

but I imagine there might be a cleaner way of doing this.

Thanks,
Nik


On Jan 28, 9:10 pm, "Nicholas F. Fabry" <[EMAIL PROTECTED]>
wrote:
> Hello, nik.
>
> On Jan 28, 2008, at 21:03, nik wrote:
>
>
>
> > Hi,
>
> > How does one express the time in ISO format with the timezone
> > designator?
>
> > what I want is -MM-DDThh:mm:ss.sTZD
>
> >> From the documentation I see:
> >>>> from datetime import tzinfo, timedelta, datetime
> >>>> class TZ(tzinfo):
> > ... def utcoffset(self, dt): return timedelta(minutes=-399)
> > ...
> >>>> datetime(2002, 12, 25, tzinfo=TZ()).isoformat(' ')
> > '2002-12-25 00:00:00-06:39'
>
> > and I've also figured out:
> >>>> datetime.datetime.fromtimestamp(time.time()).isoformat()[:-3]
> > '2008-01-23T11:22:54.130'
>
> > But can't figure out how to fit them together.
>
> There is nothing there to 'fit together' - in the first example given,
> the datetime object has no time component specified, so it fills in
> default vaules of zero.  The following should make this clear:
>
>  >>> your_time = datetime(2008, 2, 29, 15, 30, 11, tzinfo=TZ())
>  >>> print your_time
> 2008-02-29 15:30:11-05:00
>  >>> print your_time.isoformat('T')
> 2008-02-29T15:30:11-05:00
>
> If you wish to append the NAME of the tzinfo object instead of its
> offset, that requires a bit more playing around (along with a properly
> defined tzinfo object - check out dateutil or pytz for a concrete
> implementation of tzinfo subclasses (i.e. timezones)), but the
> following would work:
>
>  >>> print your_time.strftime('%Y-%m-%dT%H:%M:%S %Z')
> 2008-02-29T15:30:11 EST
>
> For details on how the .strftime method works, see Python Standard
> Library, Section 14.2.
>
> I hope this helps!
>
> Nick Fabry
>
> > Thank you,
> > Nik
> > --
> >http://mail.python.org/mailman/listinfo/python-list

>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Trying to set a cookie within a python script

2010-08-03 Thread Nik Gr

 Στις 3/8/2010 10:39 πμ, ο/η Chris Rebert έγραψε:

Please tell me the difference between 3 things.

a) Asking Notepad++(my editor) to save all my python scripts as UTF-8
without BOM.

That affects what encoding the text file comprising the source code
itself is in.


What does this practically mean? Perhaps you mean that it affects the 
way this file will be stored in the hard disk?


For example is it different to say to Notapad++ to save it as 'Asci'i 
and different to save it as 'UTF-8 without BOM'?


What should i use? My script only containes python code(english) and 
greek chars inside print statemetns.



b) Using this line '# -*- coding: utf-8 -*-' Isn't this line supposed
to tell browser that the contents of this python script as in UTF-8
and to handle it as such?

This tells Python what encoding the text file comprising the source
code itself is in.


What practically does this mean?

What difference does it have with (a) ?


c) print ''' Content-Type: text/html; charset=UTF-8 /n'''

This tells the web browser what encoding the HTML you're sending it is
in. Said HTML is output by your Python script and must match the
encoding you specify in (c).
When a python script runs it produces html output or only after the 
python's output to the Web Server the html output is produced?

--
http://mail.python.org/mailman/listinfo/python-list


Re: String substitution VS proper mysql escaping

2010-08-18 Thread Nik Gr

 Στις 18/8/2010 7:31 πμ, ο/η Cameron Simpson έγραψε:

On 17Aug2010 20:15, Νίκος  wrote:
| ===
| cursor.execute( ''' SELECT host, hits, date FROM visitors WHERE page =
| '%s' ORDER BY date DESC ''' % (page) )
| ===
|
| Someone told me NOT to do string substitution ("%") on SQL statements
| and to let MySQLdb do it
| for me, with proper escaping like the following
|
| ===
| cursor.execute('''SELECT host, hits, date FROM visitors WHERE page=%s
| ORDER BY date DESC''', (page,))
| ===
|
| The difference is that if some external source can control "page",
| and
| they put in a value like
| 100 ; DELETE FROM visitors; SELECT * FROM visitors
| i will be losing my database table data.

That other difference is that the mysql dialect support knows how to
correctly escape a string for insertion into an SQL statement. You may
not, or may forget to pre-escape the string, etc. Using the MySQLdb
stuff do it for you is reliable and robust.


Can you please tell me what escaping means by giving me an example of 
what is escaped and whats isn't?


Also hwo can i delete my data for testing purposes as?

http://webville.gr/index.html?page="100 ; DELETE FROM visitors; SELECT * 
FROM visitors"


I get an error...

| a) I wanted to ask what is proper escaping mean and why after variable
| page syntax has a comma

Because this:

   (page)

means the same thing as:

   page

i.e. the argument to the "%" operator is just the string in page.

This:

   (page,)

is a _tuple_ containing a single element, the page variable.
A bit like:

   [page]

which is a list containing a single element. The trailing comma is
needed to tell python you want to use a tuple, not the bare string.

The "%" operator has special knowledge that is it is passed as string instead
of a list or tuple or other sequence then it should act _as_ _if_ it had been
passed a single element tuple containing the string.

%s and %d is behaving the same due to % expecting a string instead of an 
integer?



Otherwise, because a string _is_ a sequence the "%" might want to treat
the string "foo" as the sequence:

   ("f", "o", "o")
cursor.execute('''SELECT host, hits, date FROM visitors WHERE page=%s 
ORDER BY date DESC''',  page)


But it alss might treat it an entity, i mean since 'page' is a variable 
containing a string why not just 'page' as it is expecting 'page' variable to 
give its value when asked?



Run these three loops to see the difference:

   for s in "foo":
 print s
   for s in ("foo"):
 print s
   for s in ("foo",):
 print s

Cheers,

>>> for s in "nikos":
print s


n
i
k
o
s

# this handles the string "nikos" as a series of chars right?

>>> for s in ("nikos"):
print s


n
i
k
o
s

# this handles the string "nikos" as a series of chars too but what si 
the difference with the above in htis with the parentheses? is "nikos" 
is handles still as string here?


>>> for s in ("nikos",):
print s


nikos

# Here yes it handles "nikos" as the 1st item of a tuple

nikos
>>> for s in ["nikos"]:
print s


nikos

# Here? why is it behaving fifferent than the above ("nikos") and is 
proccessign it all chars in one?


>>> for s in ["nikos",]:
print s


nikos

# Here it handles "nikos" as the 1st item of a list right?

--
http://mail.python.org/mailman/listinfo/python-list


Re: String substitution VS proper mysql escaping

2010-08-19 Thread Nik Gr

 Στις 19/8/2010 2:32 μμ, ο/η Tim Chase έγραψε:
So Python needs a way to express that you *explicitly* mean "this is 
one of those rare one-element tuples, not an order of operations 
prioritization":


  (1,) + (2,)
to return "(1,2)"
Yes i can see the difference now!! I just had to look at the big picture 
here! There is no other way of seperating this for that.



You can also prefix any of them with "r" such as

  file_path = r"c:\path\to\file.txt"
  file_path = r'c:\path\to\file.txt
  file_path = r"""c:\path\to\file.txt"""
  file_path = r'''c:\path\to\file.txt''' 


'r' is to avoid escaping backslashes only or other special charcaters as 
well?


As for the string i noticed that if i'am to mix single quotes and double 
quotes(any number of them not just always pairs)
and backslashes and other special stuff in them then i'm best off using 
3-sinlge-quotes like


name='''My name is "Nikos" and i'am from Thessaloniki\Greece'''

The above example can only be written by using 3-single quoting right? 
Not by pairs of single or double quotes, correct?


And i dont have to use the 'r' in fornt of it too.

===

Also if you please comment on my mysql string substitution example i've 
posted in my previous post just to make it work.

I want it to be able to delete my data but it fails when i try to

http://webville.gr/index.html?page="100 ; DELETE FROM visitors; SELECT * 
FROM visitors" 



please try it yourself, i dont mind lossign the data i just want to see 
if this mysql in jection can actually work.


Thank you.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: String substitution VS proper mysql escaping

2010-08-19 Thread Nik Gr

 Στις 19/8/2010 2:32 μμ, ο/η Tim Chase έγραψε:

  (1,) + (2,)

to return "(1,2)" 
This is actually joining two single element tuples (1,)  and (2, ) to a 
new bigger tuple of two elements, correct?

--
http://mail.python.org/mailman/listinfo/python-list


Re: String substitution VS proper mysql escaping

2010-08-19 Thread Nik Gr

 Στις 19/8/2010 6:58 μμ, ο/η Tim Chase έγραψε:
It can be written as a non-3-quote string, you just have to escape the 
inner quotes (single & double) and the backslash to be seen:


  name = 'My name is "Nikos" and I\'m from Thessaloniki\\Greece'
  name = "My name is \"Nikos\" and I'm from Thessaloniki\\Greece"



So if i enclose the string in double quotes the inner double quotes have 
to be escaped while
if i enclose the string in single quotes the inner single quotes have to 
be escaped.


But in 3-single-quoting thing became easier since i don't have to escape 
all kind of quotes right? just the backslashes.



And i dont have to use the 'r' in fornt of it too.


Using the 'r' in front would make it much more challenging, because it 
would prevent the backslashes from being seen as escaping. :)


So the best way to write the above assignment statement would be:

name = r'''My name is "Nikos" and I'm from Thessaloniki\Greece'''

It cannot get any easier that that can it? :)

''' ''' helps avoid escaping all kind of quotes!
'r' avoid escaping backslashes!

=
Why does the page variable which is actually a string needs to be a 
tuple or a list and not just as a string which is what it actually is?

I have a strong desire to use it like this:

cursor.execute( '''SELECT hits FROM counters WHERE page = %s''' , page )

opposed to tuple. Would i might facing a problem? Of what? MySQLdb 
instead of give the whole value to the placeholder to give just a single 
char?
Also do i need 3-single-quoting here as well or it can be written qith 
signle/double quotes?

What appleis to  strings apply to mysql queries as well?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: String substitution VS proper mysql escaping

2010-08-19 Thread Nik Gr

 Στις 20/8/2010 8:22 πμ, ο/η Cameron Simpson έγραψε:

[...snip...]
| Why does the page variable which is actually a string needs to be a
| tuple or a list and not just as a string which is what it actually
| is?

With regard to the "%" operator, it considers the string on the left to
be a format string with multiple %blah things in it to replace. The
thing on the right is a sequence of items to place into the format
string.


I didn't undersatnd.


So the thing on the right is_supposed_  to
| I have a strong desire to use it like this:
| cursor.execute( '''SELECT hits FROM counters WHERE page = %s''' , page )
| opposed to tuple.

Hmm. This isn't the python "%" format operator at all.
This is the database API's .execute() method.
If it expects its second argument to be a sequence of parameters
(which is does) then you need to supply a sequence of parameters.
It is that simple!

In you usage above you're supplying "page" instead of "(page,)".
The latter matches the .execute() method's requirements.

I don't follow either.
--
http://mail.python.org/mailman/listinfo/python-list


Streaming Webcam over network

2009-06-30 Thread Nik Martelaro
Hi eveyone,
I am working on a project that requires streaming video from a webcam over
LAN and displaying the live video on the remote computer. Basically, I am
creating a specialized video chat client. I can get really nice video
locally using VideoCapture and Pygame, however have only been able to send
pixel data and recreate a single image at the other end. Does anyone know of
a good video streaming module or any other way of doing this in Python?

Thanks for any help!
-- 
http://mail.python.org/mailman/listinfo/python-list


[OS X 10.5] hitting TAB inserts ./ in interactive mode ?

2010-09-17 Thread Nik Krumm
Hi all,

Thanks for your help. I installed python 2.7 on my Mac OS X 10.5.8
machine:


nik$ python
Python 2.7 (r27:82508, Jul  3 2010, 21:12:11)
[GCC 4.0.1 (Apple Inc. build 5493)] on darwin
Type "help", "copyright", "credits" or "license" for more information.

and now, when I hit TAB or paste in a code snippet with tabs in them,
the interpreter tries to autocomplete a path, or inserts "./" if the
line is blank (just as readline would in the shell environment). It
does *not* try to autocomplete function (as readline would in python--
importing readline does turn on this functionality). And it does *not*
insert a tab, as I would like it to!

If i start my old python 2.5 which came with the OS, this is not a
problem.

I've tried setting a PYTHONIOENCODING, but that doesn't seem to be
doing the job.

Any ideas? Thanks in advance.
~Nik
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: hitting TAB inserts ./ in interactive mode ?

2010-09-20 Thread Nik Krumm
On Sep 18, 11:28 am, Ned Deily  wrote:
> In article ,
>  Lawrence D'Oliveiro  wrote:
>
> > In message , Ned Deily
> > wrote:
> > >     try:
> > >         importreadline
> > >     except ImportError:
> > >         print("Modulereadlinenot available.")
> > >     else:
> > >         import rlcompleter
> > >        readline.parse_and_bind("tab: complete")
>
> > > Note the print() form which works with either Python 2 or 3.
> > You should be writing diagnostics to stderr, not stdout.
>
> In general, sure.   Statements in a PYTHONSTARTUP file, like here, are
> only executed in interactive mode and it isn't likely that someone is
> going to be redirecting stdout or stderr; that would kind of defeat the
> purpose ofreadlinecompletion functions which is what this is all
> about.  But, if you feel strongly about it, I'm sure a contributed patch
> to improve the rlcompleter documentation would be welcome.
>
> --
>  Ned Deily,
>  n...@acm.org

Hi, Thanks for the replies.

The issue isn't with readline. The readline module or rlcompleter
module are both available, and loading them has no effect on the
behavior of tab:


>>> import readline
[Now i hit tab...]
>>> ./
  File "", line 1
./
^
SyntaxError: invalid syntax

[Hit tab twice...]
>>> ./
./.bash_history ./.bash_profile ./.bash_profile.pysave  
./.CFUserTextEncoding   ./.cups ./.dropbox
./.DS_Store ./.fontconfig   ./.ipython  
./.lesshst  ./.ssh  ./.subversion
./.Trash./.Xauthority   ./
Desktop   ./Documents ./
Downloads ./inputrc
./Library   ./Movies./
Music ./Pictures  ./
Public./python
./Sites
>>> ./

>>> import rlcompleter
>>> pri[TAB]--> completes
>>> if testvar:
... [one TAB: nothing], [two TABs: "Display all 179 possibilities y/
n?"] (Note: here i need it to insert a tab, just as it should!)

So this ostensibly makes it very hard to write or paste any code into
the command line!

any further ideas? Thanks again
~N
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problem checking an existing browser cookie

2010-08-29 Thread Nik the Greek
On 30 Αύγ, 04:51, MRAB  wrote:
> On 30/08/2010 02:14, Νίκος wrote:
>
>
>
>
>
>
>
>
>
> > On 29 Αύγ, 21:44, MRAB  wrote:
> >> On 29/08/2010 06:34, Νίκος wrote:
>
> >>> On 28 Αύγ, 23:15, MRAB    wrote:
>  On 28/08/2010 20:37, Íßêïò wrote:
>
> > On 22 Áýã, 10:27, Íßêïò      wrote:
> >> On 16 Áýã, 14:31, Peter Otten<__pete...@web.de>      wrote:
>
> >>> Íßêïò wrote:
>  # initializecookie
>  cookie=Cookie.SimpleCookie()
>  cookie.load( os.environ.get('HTTP_COOKIE', '') )
>  mycookie =cookie.get('visitor')
>
>  if ( mycookie and mycookie.value != 'nikos' ) or re.search( r'(cyta|
>  yandex|13448|spider|crawl)', host ) is None:
>         blabla...
>  
>
>  I checked and Chrome has acookienames visitor with a value ofnikos
>  within.
>  So, i have to ask why the if fails?
>
> >>> Maybe it's because != != ==
>
> >> Iwant ti if code block to be executed only if the browsercookienames
> >> visitor fetched doesnt cotnain the vbalue of 'nikos'
>
> >> Is there somethign wrong with the way i wrote it?
>
> > Please do help me with this too becaus eif i dont solve this my
> > website keeps count my each visit like iam a guest visitor!
>
>  Print out mycookie, repr(mycookie.value) (unless mycookie is None) and
>  repr(host). Then follow the code yourself to see whether the condition
>  is True.
>
> >>> print mycookie outputs 'None'
>
> >>> Thts weird because i check with the browser and the cookie is there!
>
> >> Just because you can see it doesn't mean your code can.
>
> >>> print repr(host) outputs '78-236-176.adsl.cyta.gr'
>
> >>> repr(mycookie.value) (unless mycookie is None)
>
> >>> and also
>
> >>> print mycookie.value gives an error too. Maybe there is not a value
> >>> method?
>
> >> If mycookie is None, then it's not surprising that doesn't have 'value'.
>
> >> In summary, mycookie is None, so:
>
> >>       mycookie and mycookie.value != 'nikos'
>
> >> is false (actually None, which is treated as false).
>
> >> host == '78-236-176.adsl.cyta.gr', so:
>
> >>       re.search(r'(cyta|yandex|13448|spider|crawl)', host)
>
> >> finds 'cyta' and the search returns a match.
>
> >> false or false == false
>
> >> blabla... isn't executed.
>
> > Lets forget the 2nd or argument, ill put it off
>
> > so we have this now
>
> > if ( mycookie and mycookie.value != 'nikos' ):
> >      #do stuff as long as there ins't a cookie names visitor with a
> > value of nikos in the broswer
>
> > What does it mean practically that the mycookie equals to None?
> > That mycookie doesnt exist?
>
> > How should i write this if block to mkake sure it checks whether or
> > not the cookie exists?
>
> Under what conditions do you want to execute the block?
>
> This:
>
>      mycookie and mycookie.value != 'nikos'
>
> will be true if:
>
>      there _is_ a cookie, but its value isn't 'nikos'
>
> I think that you want is to execute the block if someone else is
> visiting. Correct?

Yes that exactyl right!

To make sure a cookie is set i have a script names koukos.py
containing this:

==
#!/usr/bin/python
# -*- coding: utf-8 -*-

import cgitb; cgitb.enable()
import cgi, os, Cookie


# initialize cookie
cookie = Cookie.SimpleCookie()
cookie.load( os.environ.get('HTTP_COOKIE', '') )
mycookie = cookie.get('visitor')

htmlBody = []

# if visitor cookie does exist
if ( mycookie and mycookie.value == 'nikos' ):
htmlBody.append('ΑΠΟ ΤΗΝ ΕΠΟΜΕΝΗ ΕΠΙΣΚΕΨΗ ΣΟΥ ΘΑ ΣΕ ΥΠΟΛΟΓΙΖΩ ΩΣ
ΕΠΙΣΚΕΠΤΗ ΑΥΞΑΝΟΝΤΑΣ ΤΟΝ ΜΕΤΡΗΤΗ!')
cookie['visitor'] = 'nikos'
cookie['visitor']['expires'] = -1  #this cookie will expire
now
else:
htmlBody.append('ΑΠΟ ΔΩ ΚΑΙ ΣΤΟ ΕΞΗΣ ΔΕΝ ΣΕ ΕΙΔΑ, ΔΕΝ ΣΕ ΞΕΡΩ, ΔΕΝ
ΣΕ ΑΚΟΥΣΑ! ΘΑ ΕΙΣΑΙ ΠΛΕΟΝ Ο ΑΟΡΑΤΟΣ ΕΠΙΣΚΕΠΤΗΣ!!')
cookie['visitor'] = 'nikos'
cookie['visitor']['expires'] = 60*60*24*30*12

htmlBody.insert(0, 'Content-type: text/html; charset=UTF-8\n')

print(cookie)
print('\n'.join(htmlBody))
=

Which i seicth on and off according to my desire if i want to be
counted or not!

> How do you know when it _is_ you? There'll be a cookie which says it's
> you?
>
> If so, then you want to execute the block if there isn't any cookie, or
> if there's a cookie but it doesn't say it's you:
>
>      not mycookie or mycookie.value != 'nikos'

i tried this as you suggested:

if ( not mycookie or mycookie.value != 'nikos' ) or re.search( r'(msn|
yandex|13448|spider|crawl)', host ) is None:

but the counter keeps increasing although the cookie named visitor on
my browser exist and also has the valuie of 'nikos'.

Why it keeps increasing? Doesn't the if code "sees" that the cookie
with a value of "nikos" is present!?!!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: String substitution VS proper mysql escaping

2010-08-29 Thread Nik the Greek
On 30 Αύγ, 05:04, MRAB  wrote:

when iam trying to pass a tuple to the execute methos should i pass it
like this?

cursor.execute(''' SELECT hits FROM counters WHERE page = %s and
date = %s and host = %s ''' % (page, date, host) )


or like

tuple = (page, host, date)

cursor.execute(''' SELECT hits FROM counters WHERE page = %s and
date = %s and host = %s ''' % (tuple) )


Or is it the same thing?

> > =
> > I'm asking this to see why
>
> > cursor.execute(''' SELECT hits FROM counters WHERE page = '%s' and
> > date = '%s' and host = '%s' ''' % (page, date, host) )
>
> > does work, while same thign qithout the quotes
>
> > cursor.execute(''' SELECT hits FROM counters WHERE page = %s and date
> > = %s and host = %s ''' % (page, date, host) )
>
> > doesn't. Dont know why but quotes somehopw confuse me both in strings
> > and sql_queries as well when it comes to substitutions.
>
> Don't quote the placeholders yourself. Let the method do it.

No, iam taking substitution here not mysql escaping.

Cursor.execute(''' SELECT hits FROM counters WHERE page = '%s' and
date = '%s' and host = '%s' ''' % (page, date, host) )

As it is above it works , with double quotes still works but if i
leave it unquoted it doesn't.

This is because without sigle or double quotes the the method doesn't
know where a value begins and here it ends? That why it needs quoting?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problem checking an existing browser cookie

2010-08-29 Thread Nik the Greek
On 30 Αύγ, 05:43, MRAB  wrote:
> On 30/08/2010 03:07, Nik the Greek wrote:
>
>
>
>
>
>
>
>
>
> > On 30 Αύγ, 04:51, MRAB  wrote:
> >> On 30/08/2010 02:14, Νίκος wrote:
>
> >>> On 29 Αύγ, 21:44, MRAB    wrote:
> >>>> On 29/08/2010 06:34, Νίκος wrote:
>
> >>>>> On 28 Αύγ, 23:15, MRAB      wrote:
> >>>>>> On 28/08/2010 20:37, Íßêïò wrote:
>
> >>>>>>> On 22 Áýã, 10:27, Íßêïò        wrote:
> >>>>>>>> On 16 Áýã, 14:31, Peter Otten<__pete...@web.de>        wrote:
>
> >>>>>>>>> Íßêïò wrote:
> >>>>>>>>>> # initializecookie
> >>>>>>>>>> cookie=Cookie.SimpleCookie()
> >>>>>>>>>> cookie.load( os.environ.get('HTTP_COOKIE', '') )
> >>>>>>>>>> mycookie =cookie.get('visitor')
>
> >>>>>>>>>> if ( mycookie and mycookie.value != 'nikos' ) or re.search( 
> >>>>>>>>>> r'(cyta|
> >>>>>>>>>> yandex|13448|spider|crawl)', host ) is None:
> >>>>>>>>>>         blabla...
> >>>>>>>>>> 
>
> >>>>>>>>>> I checked and Chrome has acookienames visitor with a value ofnikos
> >>>>>>>>>> within.
> >>>>>>>>>> So, i have to ask why the if fails?
>
> >>>>>>>>> Maybe it's because != != ==
>
> >>>>>>>> Iwant ti if code block to be executed only if the browsercookienames
> >>>>>>>> visitor fetched doesnt cotnain the vbalue of 'nikos'
>
> >>>>>>>> Is there somethign wrong with the way i wrote it?
>
> >>>>>>> Please do help me with this too becaus eif i dont solve this my
> >>>>>>> website keeps count my each visit like iam a guest visitor!
>
> >>>>>> Print out mycookie, repr(mycookie.value) (unless mycookie is None) and
> >>>>>> repr(host). Then follow the code yourself to see whether the condition
> >>>>>> is True.
>
> >>>>> print mycookie outputs 'None'
>
> >>>>> Thts weird because i check with the browser and the cookie is there!
>
> >>>> Just because you can see it doesn't mean your code can.
>
> >>>>> print repr(host) outputs '78-236-176.adsl.cyta.gr'
>
> >>>>> repr(mycookie.value) (unless mycookie is None)
>
> >>>>> and also
>
> >>>>> print mycookie.value gives an error too. Maybe there is not a value
> >>>>> method?
>
> >>>> If mycookie is None, then it's not surprising that doesn't have 'value'.
>
> >>>> In summary, mycookie is None, so:
>
> >>>>        mycookie and mycookie.value != 'nikos'
>
> >>>> is false (actually None, which is treated as false).
>
> >>>> host == '78-236-176.adsl.cyta.gr', so:
>
> >>>>        re.search(r'(cyta|yandex|13448|spider|crawl)', host)
>
> >>>> finds 'cyta' and the search returns a match.
>
> >>>> false or false == false
>
> >>>> blabla... isn't executed.
>
> >>> Lets forget the 2nd or argument, ill put it off
>
> >>> so we have this now
>
> >>> if ( mycookie and mycookie.value != 'nikos' ):
> >>>       #do stuff as long as there ins't a cookie names visitor with a
> >>> value of nikos in the broswer
>
> >>> What does it mean practically that the mycookie equals to None?
> >>> That mycookie doesnt exist?
>
> >>> How should i write this if block to mkake sure it checks whether or
> >>> not the cookie exists?
>
> >> Under what conditions do you want to execute the block?
>
> >> This:
>
> >>       mycookie and mycookie.value != 'nikos'
>
> >> will be true if:
>
> >>       there _is_ a cookie, but its value isn't 'nikos'
>
> >> I think that you want is to execute the block if someone else is
> >> visiting. Correct?
>
> > Yes that exactyl right!
>
> > To make sure a cookie is set i have a script names koukos.py
> > conta

Re: String substitution VS proper mysql escaping

2010-08-29 Thread Nik the Greek
On 30 Αύγ, 05:48, MRAB  wrote:
> On 30/08/2010 03:33, Nik the Greek wrote:
>
>
>
>
>
>
>
> > On 30 Αύγ, 05:04, MRAB  wrote:
>
> > when iam trying to pass a tuple to the execute methos should i pass it
> > like this?
>
> > cursor.execute(''' SELECT hits FROM counters WHERE page = %s and
> > date = %s and host = %s ''' % (page, date, host) )
>
> > or like
>
> > tuple = (page, host, date)
>
> > cursor.execute(''' SELECT hits FROM counters WHERE page = %s and
> > date = %s and host = %s ''' % (tuple) )
>
> > Or is it the same thing?
>
> 'tuple' is the name of a built-in. Don't use it.
>
> The first example is clearer.


ok a_tuple = (page, hist, host)

cursor.execute(''' SELECT hits FROM counters WHERE page = %s and
date = %s and host = %s ''' , a_tuple )

would that syntax be correct? No need to enclose the tuple name inside
parenthesis here right?


> >>> =
> >>> I'm asking this to see why
>
> >>> cursor.execute(''' SELECT hits FROM counters WHERE page = '%s' and
> >>> date = '%s' and host = '%s' ''' % (page, date, host) )
>
> >>> does work, while same thign qithout the quotes
>
> >>> cursor.execute(''' SELECT hits FROM counters WHERE page = %s and date
> >>> = %s and host = %s ''' % (page, date, host) )
>
> >>> doesn't. Dont know why but quotes somehopw confuse me both in strings
> >>> and sql_queries as well when it comes to substitutions.
>
> >> Don't quote the placeholders yourself. Let the method do it.
>
> > No, iam taking substitution here not mysql escaping.
>
> > Cursor.execute(''' SELECT hits FROM counters WHERE page = '%s' and
> > date = '%s' and host = '%s' ''' % (page, date, host) )
>
> > As it is above it works , with double quotes still works but if i
> > leave it unquoted it doesn't.
>
> > This is because without sigle or double quotes the the method doesn't
> > know where a value begins and here it ends? That why it needs quoting?
>
> Let the method do the substitution:
>
> cursor.execute(''' SELECT hits FROM counters WHERE page = %s and date =
> %s and host = %s ''', (page, date, host) )
>
> This is the best way.

Yes i will i just asked to know if i were to substitute what might be
the problem so to understand why i need the quoting.

why not like that?

> cursor.execute(''' SELECT hits FROM counters WHERE page = %s and date =
> %s and host = %s ''' % (page, date, host) )

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problem checking an existing browser cookie

2010-08-29 Thread Nik the Greek
On 30 Αύγ, 06:12, MRAB  wrote:

> This part:
>
>      ( not mycookie or mycookie.value != 'nikos' )
>
> is false but this part:
>
>      re.search( r'(msn|yandex|13448|spider|crawl)', host ) is None
>
> is true because host doesn't contain any of those substrings.

So, the if code does executed because one of the condition is true?

How should i write it?

I cannot think clearly on this at all.

I just wan to tell it to get executed  ONLY IF

the cookie values is not 'nikos'

or ( don't knwo if i have to use and or 'or' here)

host does not contain any of the substrings.

What am i doign wrong?!

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problem checking an existing browser cookie

2010-08-30 Thread Nik the Greek
On 30 Αύγ, 06:12, MRAB  wrote:
> On 30/08/2010 03:55, Nik the Greek wrote:
>
>
>
>
>
>
>
>
>
> > On 30 Αύγ, 05:43, MRAB  wrote:
> >> On 30/08/2010 03:07, Nik the Greek wrote:
>
> >>> On 30 Αύγ, 04:51, MRAB    wrote:
> >>>> On 30/08/2010 02:14, Νίκος wrote:
>
> >>>>> On 29 Αύγ, 21:44, MRAB      wrote:
> >>>>>> On 29/08/2010 06:34, Νίκος wrote:
>
> >>>>>>> On 28 Αύγ, 23:15, MRAB        wrote:
> >>>>>>>> On 28/08/2010 20:37, Íßêïò wrote:
>
> >>>>>>>>> On 22 Áýã, 10:27, Íßêïò          wrote:
> >>>>>>>>>> On 16 Áýã, 14:31, Peter Otten<__pete...@web.de>          wrote:
>
> >>>>>>>>>>> Íßêïò wrote:
> >>>>>>>>>>>> # initializecookie
> >>>>>>>>>>>> cookie=Cookie.SimpleCookie()
> >>>>>>>>>>>> cookie.load( os.environ.get('HTTP_COOKIE', '') )
> >>>>>>>>>>>> mycookie =cookie.get('visitor')
>
> >>>>>>>>>>>> if ( mycookie and mycookie.value != 'nikos' ) or re.search( 
> >>>>>>>>>>>> r'(cyta|
> >>>>>>>>>>>> yandex|13448|spider|crawl)', host ) is None:
> >>>>>>>>>>>>          blabla...
> >>>>>>>>>>>> 
>
> >>>>>>>>>>>> I checked and Chrome has acookienames visitor with a value 
> >>>>>>>>>>>> ofnikos
> >>>>>>>>>>>> within.
> >>>>>>>>>>>> So, i have to ask why the if fails?
>
> >>>>>>>>>>> Maybe it's because != != ==
>
> >>>>>>>>>> Iwant ti if code block to be executed only if the 
> >>>>>>>>>> browsercookienames
> >>>>>>>>>> visitor fetched doesnt cotnain the vbalue of 'nikos'
>
> >>>>>>>>>> Is there somethign wrong with the way i wrote it?
>
> >>>>>>>>> Please do help me with this too becaus eif i dont solve this my
> >>>>>>>>> website keeps count my each visit like iam a guest visitor!
>
> >>>>>>>> Print out mycookie, repr(mycookie.value) (unless mycookie is None) 
> >>>>>>>> and
> >>>>>>>> repr(host). Then follow the code yourself to see whether the 
> >>>>>>>> condition
> >>>>>>>> is True.
>
> >>>>>>> print mycookie outputs 'None'
>
> >>>>>>> Thts weird because i check with the browser and the cookie is there!
>
> >>>>>> Just because you can see it doesn't mean your code can.
>
> >>>>>>> print repr(host) outputs '78-236-176.adsl.cyta.gr'
>
> >>>>>>> repr(mycookie.value) (unless mycookie is None)
>
> >>>>>>> and also
>
> >>>>>>> print mycookie.value gives an error too. Maybe there is not a value
> >>>>>>> method?
>
> >>>>>> If mycookie is None, then it's not surprising that doesn't have 
> >>>>>> 'value'.
>
> >>>>>> In summary, mycookie is None, so:
>
> >>>>>>         mycookie and mycookie.value != 'nikos'
>
> >>>>>> is false (actually None, which is treated as false).
>
> >>>>>> host == '78-236-176.adsl.cyta.gr', so:
>
> >>>>>>         re.search(r'(cyta|yandex|13448|spider|crawl)', host)
>
> >>>>>> finds 'cyta' and the search returns a match.
>
> >>>>>> false or false == false
>
> >>>>>> blabla... isn't executed.
>
> >>>>> Lets forget the 2nd or argument, ill put it off
>
> >>>>> so we have this now
>
> >>>>> if ( mycookie and mycookie.value != 'nikos' ):
> >>>>>        #do stuff as long as there ins't a cookie names visitor with a
> >>>>> value of nikos in the broswer
>
> >>>>> What does it mean practically that the my

Re: Problem checking an existing browser cookie

2010-08-30 Thread Nik the Greek
On 30 Αύγ, 11:01, Nik the Greek  wrote:
> On 30 Αύγ, 06:12, MRAB  wrote:
>
>
>
>
>
>
>
>
>
> > On 30/08/2010 03:55, Nik the Greek wrote:
>
> > > On 30 Αύγ, 05:43, MRAB  wrote:
> > >> On 30/08/2010 03:07, Nik the Greek wrote:
>
> > >>> On 30 Αύγ, 04:51, MRAB    wrote:
> > >>>> On 30/08/2010 02:14, Νίκος wrote:
>
> > >>>>> On 29 Αύγ, 21:44, MRAB      wrote:
> > >>>>>> On 29/08/2010 06:34, Νίκος wrote:
>
> > >>>>>>> On 28 Αύγ, 23:15, MRAB        wrote:
> > >>>>>>>> On 28/08/2010 20:37, Íßêïò wrote:
>
> > >>>>>>>>> On 22 Áýã, 10:27, Íßêïò          wrote:
> > >>>>>>>>>> On 16 Áýã, 14:31, Peter Otten<__pete...@web.de>          wrote:
>
> > >>>>>>>>>>> Íßêïò wrote:
> > >>>>>>>>>>>> # initializecookie
> > >>>>>>>>>>>> cookie=Cookie.SimpleCookie()
> > >>>>>>>>>>>> cookie.load( os.environ.get('HTTP_COOKIE', '') )
> > >>>>>>>>>>>> mycookie =cookie.get('visitor')
>
> > >>>>>>>>>>>> if ( mycookie and mycookie.value != 'nikos' ) or re.search( 
> > >>>>>>>>>>>> r'(cyta|
> > >>>>>>>>>>>> yandex|13448|spider|crawl)', host ) is None:
> > >>>>>>>>>>>>          blabla...
> > >>>>>>>>>>>> 
>
> > >>>>>>>>>>>> I checked and Chrome has acookienames visitor with a value 
> > >>>>>>>>>>>> ofnikos
> > >>>>>>>>>>>> within.
> > >>>>>>>>>>>> So, i have to ask why the if fails?
>
> > >>>>>>>>>>> Maybe it's because != != ==
>
> > >>>>>>>>>> Iwant ti if code block to be executed only if the 
> > >>>>>>>>>> browsercookienames
> > >>>>>>>>>> visitor fetched doesnt cotnain the vbalue of 'nikos'
>
> > >>>>>>>>>> Is there somethign wrong with the way i wrote it?
>
> > >>>>>>>>> Please do help me with this too becaus eif i dont solve this my
> > >>>>>>>>> website keeps count my each visit like iam a guest visitor!
>
> > >>>>>>>> Print out mycookie, repr(mycookie.value) (unless mycookie is None) 
> > >>>>>>>> and
> > >>>>>>>> repr(host). Then follow the code yourself to see whether the 
> > >>>>>>>> condition
> > >>>>>>>> is True.
>
> > >>>>>>> print mycookie outputs 'None'
>
> > >>>>>>> Thts weird because i check with the browser and the cookie is there!
>
> > >>>>>> Just because you can see it doesn't mean your code can.
>
> > >>>>>>> print repr(host) outputs '78-236-176.adsl.cyta.gr'
>
> > >>>>>>> repr(mycookie.value) (unless mycookie is None)
>
> > >>>>>>> and also
>
> > >>>>>>> print mycookie.value gives an error too. Maybe there is not a value
> > >>>>>>> method?
>
> > >>>>>> If mycookie is None, then it's not surprising that doesn't have 
> > >>>>>> 'value'.
>
> > >>>>>> In summary, mycookie is None, so:
>
> > >>>>>>         mycookie and mycookie.value != 'nikos'
>
> > >>>>>> is false (actually None, which is treated as false).
>
> > >>>>>> host == '78-236-176.adsl.cyta.gr', so:
>
> > >>>>>>         re.search(r'(cyta|yandex|13448|spider|crawl)', host)
>
> > >>>>>> finds 'cyta' and the search returns a match.
>
> > >>>>>> false or false == false
>
> > >>>>>> blabla... isn't executed.
>
> > >>>>> Lets forget the 2nd or argument, ill put it off
>
> > >>>>>

Re: String substitution VS proper mysql escaping

2010-08-30 Thread Nik the Greek
On 30 Αύγ, 11:11, Gregory Ewing  wrote:
> Nik the Greek wrote:
> > Yes i will i just asked to know if i were to substitute what might be
> > the problem so to understand why i need the quoting.
>
> Because if you use % to build a query string, the result must
> be syntactically valid SQL. The values that you substitute
> into the placeholders must end up looking like SQL literals.
> That means string values need to be in quotes, and probably
> dates as well, although numbers don't.
>
> When you use the execute method's own parameter substitution
> mechanism, things are different. It's not a textual replacement,
> and you don't put quotes around the placeholders. There's no
> particular reason for that, it's just the way it's defined
> to work.
>
> --
> Greg

cursor.execute(''' SELECT hits FROM counters WHERE page = %s and
date = %s and host = %s ''' , a_tuple )

and

cursor.execute(''' SELECT hits FROM counters WHERE page = %s and
date = %s and host = %s ''' , (a_tuple) )

are both syntactically correct right?

buw what about

cursor.execute(''' SELECT hits FROM counters WHERE page = %s and
date = %s and host = %s ''' , (a_tuple,) )
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problem checking an existing browser cookie

2010-08-30 Thread Nik the Greek
On 30 Αύγ, 19:41, MRAB  wrote:
> On 30/08/2010 04:33, Nik the Greek wrote:
>
>
>
>
>
>
>
> > On 30 Αύγ, 06:12, MRAB  wrote:
>
> >> This part:
>
> >>       ( not mycookie or mycookie.value != 'nikos' )
>
> >> is false but this part:
>
> >>       re.search( r'(msn|yandex|13448|spider|crawl)', host ) is None
>
> >> is true because host doesn't contain any of those substrings.
>
> > So, the if code does executed because one of the condition is true?
>
> > How should i write it?
>
> > I cannot think clearly on this at all.
>
> > I just wan to tell it to get executed  ONLY IF
>
> > the cookie values is not 'nikos'
>
> > or ( don't knwo if i have to use and or 'or' here)
>
> > host does not contain any of the substrings.
>
> > What am i doign wrong?!
>
> It might be clearer if you reverse the condition and say:
>
>      me_visiting = ...
>      if not me_visiting:
>          ...

I don't understand what are you trying to say

Please provide a full example.

You mean i should try it like this?

unless ( visitor and visitor.value == 'nikos' ) or re.search( r'(msn|
yandex|13448|spider|crawl)', host ) not None:

But isnt it the same thing like the if?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problem checking an existing browser cookie

2010-08-30 Thread Nik the Greek
On 30 Αύγ, 19:21, Peter Otten <__pete...@web.de> wrote:
> Nik the Greek wrote:
> >> Perhpas its doenst get loaded like that?
>
> >> # initialize cookie
> >> cookie = SimpleCookie()
> >> cookie.load( os.environ.get('HTTP_COOKIE', '') )
> >> mycookie = cookie.get('visitor')
>
> > Please someone else has an idea on how this to work?
>
> Add a print statement to verify that HTTP_COOKIE does indeed have a visitor.
> Or use the stuff below as a template.
>
> Here is a minimal script to set the visitor:
>
> #!/usr/bin/env python
> import cgitb
> cgitb.enable()
>
> import cgi
> import Cookie
> import os
> import sys
>
> form = cgi.FieldStorage()
> name = form.getfirst("name", "Unknown")
>
> cookie = Cookie.SimpleCookie()
> cookie["visitor"] = name
>
> sys.stdout.write(cookie.output())
> sys.stdout.write("\r\nContent-type: text/plain\r\n\r\n")
> print "Hello, your new name is", name
>
> Invoke it with the equivalent of
>
> http://localhost:8000/cgi-bin/set_visitor.py?name=Nikos
>
> for your website. Then proceed with a small script to show the visitor's
> name:
>
> #!/usr/bin/env python
> import cgitb
> cgitb.enable()
>
> import cgi
> import Cookie
> import os
> import sys
>
> cookie = Cookie.SimpleCookie()
> cookie.load(os.environ.get("HTTP_COOKIE"))
>
> visitor = cookie.get("visitor")
> if visitor is None:
>     visitor_name = "Unknown"
> else:
>     visitor_name = visitor.value
>
> sys.stdout.write("Content-type: text/plain\r\n\r\n")
> print "Hello,", visitor_name
> print
> print
> print "HTTP_COOKIE=%r" % os.environ.get("HTTP_COOKIE")
>
> which you can invoke with the equivalent of
>
> http://localhost:8000/cgi-bin/show_visitor.py
>
> With some luck you should see your name and can proceed to adapt your script
> accordingly.
>
> Peter

The cookie is set tyo the browser with the code i provided few posts
back

The problem is that i for soemreason cant check correctly its
existance.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problem checking an existing browser cookie

2010-08-30 Thread Nik the Greek
On 30 Αύγ, 19:41, MRAB  wrote:
> On 30/08/2010 04:33, Nik the Greek wrote:
>
>
>
>
>
>
>
> > On 30 Αύγ, 06:12, MRAB  wrote:
>
> >> This part:
>
> >>       ( not mycookie or mycookie.value != 'nikos' )
>
> >> is false but this part:
>
> >>       re.search( r'(msn|yandex|13448|spider|crawl)', host ) is None
>
> >> is true because host doesn't contain any of those substrings.
>
> > So, the if code does executed because one of the condition is true?
>
> > How should i write it?
>
> > I cannot think clearly on this at all.
>
> > I just wan to tell it to get executed  ONLY IF
>
> > the cookie values is not 'nikos'
>
> > or ( don't knwo if i have to use and or 'or' here)
>
> > host does not contain any of the substrings.
>
> > What am i doign wrong?!
>
> It might be clearer if you reverse the condition and say:
>
>      me_visiting = ...
>      if not me_visiting:
>          ...


# initialize cookie
cookie = SimpleCookie()
cookie.load( os.environ.get('HTTP_COOKIE', '') )
visitor = cookie.get('visitor')

This statement

if (visitor.value != 'nikos') and re.search( r'(msn|yandex|13448|
spider|crawl)', host ) is None:

produces the following error:

 /home/webville/public_html/cgi-bin/counter.py
   93 # do not increment the counter if a Cookie is set to the
visitors browser already
   94 #
=
   95 if (visitor.value != 'nikos') and re.search( r'(msn|yandex|13448|
spider|crawl)', host ) is None:
   96
   97 print visitor
visitor = None, visitor.value undefined, re = , re.search = , host =
'178-128-217.dynamic.cyta.gr', builtin None = None

Why visitor.value is undefined?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problem checking an existing browser cookie

2010-08-30 Thread Nik the Greek
On 30 Αύγ, 20:53, MRAB  wrote:

> > Why visitor.value is undefined?
>
> Because visitor is None. It's not seeing any cookie.

WHY NOT?!

THE COOKIE _DOES_EXIST !!!

What am i missing here?!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problem checking an existing browser cookie

2010-08-31 Thread Nik the Greek
On 30 Αύγ, 20:48, Rami Chowdhury 
wrote:
> On Mon, Aug 30, 2010 at 23:36, Nik the Greek  
> wrote:
>
>
>
>
>
>
>
>
>
> > # initialize cookie
> > cookie = SimpleCookie()
> > cookie.load( os.environ.get('HTTP_COOKIE', '') )
> > visitor = cookie.get('visitor')
>
> > This statement
>
> > if (visitor.value != 'nikos') and re.search( r'(msn|yandex|13448|
> > spider|crawl)', host ) is None:
>
> > produces the following error:
>
> >  /home/webville/public_html/cgi-bin/counter.py
> >   93 # do not increment the counter if a Cookie is set to the
> > visitors browser already
> >   94 #
> > === 
> > ==
> >   95 if (visitor.value != 'nikos') and re.search( r'(msn|yandex|13448|
> > spider|crawl)', host ) is None:
> >   96
> >   97         print visitor
> > visitor = None, visitor.value undefined, re =  > lib64/python2.4/re.pyc'>, re.search = , host =
> > '178-128-217.dynamic.cyta.gr', builtin None = None
>
> > Why visitor.value is undefined?
>
> Because, as the traceback tells you, visitor is None. As you said, the
> cookie is not recognized. Try inserting the following line at the top
> of your script:
>
> print "Content-type:text/html\r\n\r\n", os.environ.get('HTTP_COOKIE',
> 'NO COOKIE DATA')
>
> That should give you the value of the cookie, which might help you
> debug why it is not being loaded.
>
> --
> Rami Chowdhury
> "Never assume malice when stupidity will suffice." -- Hanlon's Razor
> 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD)

Unfortunately it produces an Internal Server Error :(
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problem checking an existing browser cookie

2010-08-31 Thread Nik the Greek
On 30 Αύγ, 20:50, MRAB  wrote:
> On 30/08/2010 18:16, Nik the Greek wrote:
>
>
>
>
>
>
>
>
>
> > On 30 Αύγ, 19:41, MRAB  wrote:
> >> On 30/08/2010 04:33, Nik the Greek wrote:
>
> >>> On 30 Αύγ, 06:12, MRAB    wrote:
>
> >>>> This part:
>
> >>>>        ( not mycookie or mycookie.value != 'nikos' )
>
> >>>> is false but this part:
>
> >>>>        re.search( r'(msn|yandex|13448|spider|crawl)', host ) is None
>
> >>>> is true because host doesn't contain any of those substrings.
>
> >>> So, the if code does executed because one of the condition is true?
>
> >>> How should i write it?
>
> >>> I cannot think clearly on this at all.
>
> >>> I just wan to tell it to get executed  ONLY IF
>
> >>> the cookie values is not 'nikos'
>
> >>> or ( don't knwo if i have to use and or 'or' here)
>
> >>> host does not contain any of the substrings.
>
> >>> What am i doign wrong?!
>
> >> It might be clearer if you reverse the condition and say:
>
> >>       me_visiting = ...
> >>       if not me_visiting:
> >>           ...
>
> > I don't understand what are you trying to say
>
> > Please provide a full example.
>
> > You mean i should try it like this?
>
> > unless ( visitor and visitor.value == 'nikos' ) or re.search( r'(msn|
> > yandex|13448|spider|crawl)', host ) not None:
>
> > But isnt it the same thing like the if?
>
> My point is that the logic might be clearer to you if you think first
> about how you know when you _are_ the visitor.

Well my idea was to set a cookie on my browser with the name visitor
and a value of "nikos" and then check each time that cooki. if value
is "nikos" then dont count!

I could also pass an extra url string like http://webville.gr?show=nikos
and check that but i dont like the idea very much of giving an extra
string each time i want to visit my webpage.
So form the 2 solution mentioned the 1st one is better but cant come
into action for some reason.

Aprt form those too solution i cant think of anyhting else that would
identify me and filter me out of the actual guest of my website.

I'm all ears if you can think of something else.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problem checking an existing browser cookie

2010-09-01 Thread Nik the Greek
On 31 Αύγ, 11:07, Nik the Greek  wrote:
> On 30 Αύγ, 20:50, MRAB  wrote:
>
>
>
>
>
>
>
>
>
> > On 30/08/2010 18:16, Nik the Greek wrote:
>
> > > On 30 Αύγ, 19:41, MRAB  wrote:
> > >> On 30/08/2010 04:33, Nik the Greek wrote:
>
> > >>> On 30 Αύγ, 06:12, MRAB    wrote:
>
> > >>>> This part:
>
> > >>>>        ( not mycookie or mycookie.value != 'nikos' )
>
> > >>>> is false but this part:
>
> > >>>>        re.search( r'(msn|yandex|13448|spider|crawl)', host ) is None
>
> > >>>> is true because host doesn't contain any of those substrings.
>
> > >>> So, the if code does executed because one of the condition is true?
>
> > >>> How should i write it?
>
> > >>> I cannot think clearly on this at all.
>
> > >>> I just wan to tell it to get executed  ONLY IF
>
> > >>> the cookie values is not 'nikos'
>
> > >>> or ( don't knwo if i have to use and or 'or' here)
>
> > >>> host does not contain any of the substrings.
>
> > >>> What am i doign wrong?!
>
> > >> It might be clearer if you reverse the condition and say:
>
> > >>       me_visiting = ...
> > >>       if not me_visiting:
> > >>           ...
>
> > > I don't understand what are you trying to say
>
> > > Please provide a full example.
>
> > > You mean i should try it like this?
>
> > > unless ( visitor and visitor.value == 'nikos' ) or re.search( r'(msn|
> > > yandex|13448|spider|crawl)', host ) not None:
>
> > > But isnt it the same thing like the if?
>
> > My point is that the logic might be clearer to you if you think first
> > about how you know when you _are_ the visitor.
>
> Well my idea was to set a cookie on my browser with the name visitor
> and a value of "nikos" and then check each time that cooki. if value
> is "nikos" then dont count!
>
> I could also pass an extra url string likehttp://webville.gr?show=nikos
> and check that but i dont like the idea very much of giving an extra
> string each time i want to visit my webpage.
> So form the 2 solution mentioned the 1st one is better but cant come
> into action for some reason.
>
> Aprt form those too solution i cant think of anyhting else that would
> identify me and filter me out of the actual guest of my website.
>
> I'm all ears if you can think of something else.

Is there any other way for the webpage to identify me and filter me
out except checking a cookie or attach an extra url string to the
address bar?
-- 
http://mail.python.org/mailman/listinfo/python-list