Re: SOLVED! Re: Weird Stuff (Markdown, syntax highlighting and Python)

2024-05-29 Thread dn via Python-list

On 29/05/24 06:49, Gilmeh Serda via Python-list wrote:


Solved by using a different method.



Hedonist for hire... no job too easy!


This combination of sig-file and content seems sadly ironic.


How about CONTRIBUTING to the community by explaining 'the solution' to 
people who may find a similar problem - in the similar manner to the 
various members who have helped YOU, voluntarily (and despite the 
paucity of source-information and response)?


--
Regards,
=dn
--
https://mail.python.org/mailman/listinfo/python-list


Re: SOLVED! Re: Weird Stuff (Markdown, syntax highlighting and Python)

2024-05-29 Thread o1bigtenor via Python-list
On Tue, May 28, 2024 at 9:48 PM Gilmeh Serda via Python-list <
python-list@python.org> wrote:

>
> Solved by using a different method.
>
>
- - - And that was how?

TIA
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: [Solved] Re: Windows registry PermissionError

2022-05-13 Thread Mike Dewhirst

On 13/05/2022 4:37 pm, Eryk Sun wrote:

On 5/13/22, Mike Dewhirst  wrote:

On 13/05/2022 4:14 pm, Eryk Sun wrote:

Since self.connect() is always called, you should document that the
initial hkey parameter has to be one of the following predefined key
handles:

  HKEY_LOCAL_MACHINE
  HKEY_USERS

I'm targeting HKEY_CURRENT_USER so I assume HK_USERS includes that.

Using HKEY_CURRENT_USER with RegConnectRegistryW() to access a remote
registry isn't well defined and not documented as supported. If it
works at all, the API probably just opens a subkey of the remote
HKEY_USERS based on the string SID (security identifier string) of the
current user. That may fail as not found since user SIDs are unique to
machines, unless it's on a domain.

Bear in mind that the remote registry service is running on the remote
machine as SYSTEM (S-1-5-18) in the non-interactive services session.
If it literally accessed its "current user", then it would open
"HKEY_USERS\S-1-5-18".
In that case, I'll remove 'computer' as a parameter and lock it in as 
None. I'll document why and if I ever need to access a remote registry 
I'll do some research along the lines you suggest.


My case demands execution of this code via login script for end-user 
configuration after the IT department has done a bulk installation 
rollout. One of key items is ComputerName which is in HKLM and needs to 
be in HKCU for whichever user logs in. The application looks in HKCU for 
a unique Device Reference and ComputerName suffices and is attractive 
because it is also the asset number of the machine.



--
Signed email is an absolute defence against phishing. This email has
been signed with my private key. If you import my public key you can
automatically decrypt my signature and be sure it came from me. Just
ask and I'll send it to you. Your email software can handle signing.



OpenPGP_signature
Description: OpenPGP digital signature
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: [Solved] Re: Windows registry PermissionError

2022-05-12 Thread Eryk Sun
On 5/13/22, Mike Dewhirst  wrote:
> On 13/05/2022 4:14 pm, Eryk Sun wrote:
>> Since self.connect() is always called, you should document that the
>> initial hkey parameter has to be one of the following predefined key
>> handles:
>>
>>  HKEY_LOCAL_MACHINE
>>  HKEY_USERS
>
> I'm targeting HKEY_CURRENT_USER so I assume HK_USERS includes that.

Using HKEY_CURRENT_USER with RegConnectRegistryW() to access a remote
registry isn't well defined and not documented as supported. If it
works at all, the API probably just opens a subkey of the remote
HKEY_USERS based on the string SID (security identifier string) of the
current user. That may fail as not found since user SIDs are unique to
machines, unless it's on a domain.

Bear in mind that the remote registry service is running on the remote
machine as SYSTEM (S-1-5-18) in the non-interactive services session.
If it literally accessed its "current user", then it would open
"HKEY_USERS\S-1-5-18".
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: [Solved] Re: Windows registry PermissionError

2022-05-12 Thread Mike Dewhirst

On 13/05/2022 4:14 pm, Eryk Sun wrote:

Since self.connect() is always called, you should document that the
initial hkey parameter has to be one of the following predefined key
handles:

 HKEY_LOCAL_MACHINE
 HKEY_USERS


I'm targeting HKEY_CURRENT_USER so I assume HK_USERS includes that.

Thanks again Eryk

Cheers

mike


 HKEY_PERFORMANCE_DATA

WinAPI RegConnectRegistryW() only matters when the target computer is
a different machine, in which case an RPC proxy handle is returned.



--
Signed email is an absolute defence against phishing. This email has
been signed with my private key. If you import my public key you can
automatically decrypt my signature and be sure it came from me. Just
ask and I'll send it to you. Your email software can handle signing.



OpenPGP_signature
Description: OpenPGP digital signature
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: [Solved] Re: Windows registry PermissionError

2022-05-12 Thread Eryk Sun
Since self.connect() is always called, you should document that the
initial hkey parameter has to be one of the following predefined key
handles:

HKEY_LOCAL_MACHINE
HKEY_USERS
HKEY_PERFORMANCE_DATA

WinAPI RegConnectRegistryW() only matters when the target computer is
a different machine, in which case an RPC proxy handle is returned.
-- 
https://mail.python.org/mailman/listinfo/python-list


[Solved] Re: Windows registry PermissionError

2022-05-12 Thread Mike Dewhirst

Eryk

Many thanks. It is working perfectly now. See below for the reworked code.

Cheers

Mike

On 13/05/2022 1:42 pm, Eryk Sun wrote:

On 5/12/22, Mike Dewhirst  wrote:

  access=wr.KEY_ALL_ACCESS + wr.KEY_WRITE,


import winreg as wr class Registry: def __init__(self, computer=None, 
hkey=None, sub_key=None): self.computer = computer self.key = hkey 
self.sub_key = sub_key def connect(self): return 
wr.ConnectRegistry(self.computer, self.key) def select(self, 
access=None): with self.connect() as hkey: return wr.OpenKeyEx(key=hkey, 
sub_key=self.sub_key, access=access) def count(self): access = 
wr.KEY_QUERY_VALUE return wr.QueryInfoKey(self.select(access=access)) 
def query(self, vname, access=None): if access is None: access = 
wr.KEY_READ | wr.KEY_WOW64_32KEY return 
wr.QueryValueEx(self.select(access=access), vname) def setvalue(self, 
vname, value, access=None): if access is None: access = wr.KEY_SET_VALUE 
with self.select(access=access) as hkey: return wr.SetValueEx(hkey, 
vname, 0, wr.REG_SZ, value) if __name__ == "__main__": lmregistry = 
Registry( hkey=wr.HKEY_LOCAL_MACHINE, sub_key=r"SOFTWARE\XXX 
Technology\AppName", ) print(f"\n{lmregistry.sub_key}") anz = 
lmregistry.query('Country')[0] print(f"\n{anz}") db = 
lmregistry.query('Database')[0] print(f"\n{db}") devref = 
lmregistry.query('v135')[0] print(f"\n{devref}") orgid = 
lmregistry.query('v136')[0] print(f"\n{orgid}") curegistry = Registry( 
hkey=wr.HKEY_CURRENT_USER, sub_key=r"SOFTWARE\XXX Technology\AppName", ) 
print(f"\n{curegistry.sub_key}") anz = curegistry.query('Country')[0] 
print(f"\n{anz}") db = curegistry.query('Database')[0] print(f"\n{db}") 
devref = curegistry.query('v135')[0] print(f"\n{devref}") orgid = 
curegistry.query('v136')[0] print(f"\n{orgid}") 
curegistry.setvalue('Country', 'nz') curegistry.setvalue('Database', 
'2022.2') curegistry.setvalue('v135', 'Asus10') 
curegistry.setvalue('v136', orgid.replace('ALL', 'Most')) anz = 
curegistry.query('Country')[0] print(f"\n{anz}") db = 
curegistry.query('Database')[0] print(f"\n{db}") devref = 
curegistry.query('v135')[0] print(f"\n{devref}") orgid = 
curegistry.query('v136')[0] print(f"\n{orgid}")


Again, many thanks for putting so much effort into educating me.

Cheers

Mike

The access parameter is a bit mask of access rights that combine via
bitwise OR (|), not via arithmetic addition.

KEY_ALL_ACCESS (0x000F_003F) is a superset of KEY_WRITE (0x0002_0006):

 KEY_WRITE = (
 READ_CONTROL   | # 0x0002_
 KEY_SET_VALUE  | # 0x_0002
 KEY_CREATE_SUB_KEY | # 0x_0004
 )# 0x0002_0006

 KEY_ALL_ACCESS = (
 DELETE | # 0x0001_
 READ_CONTROL   | # 0x0002_
 WRITE_DAC  | # 0x0004_
 WRITE_OWNER| # 0x0008_
 KEY_QUERY_VALUE| # 0x_0001
 KEY_SET_VALUE  | # 0x_0002
 KEY_CREATE_SUB_KEY | # 0x_0004
 KEY_ENUMERATE_SUB_KEYS | # 0x_0008
 KEY_NOTIFY | # 0x_0010
 KEY_CREATE_LINK| # 0x_0020
 )# 0x000F_003F

The result of the arithmetic addition `KEY_ALL_ACCESS + KEY_WRITE` is
0x0011_0045, which is wrong and meaningless. Registry key objects do
not support SYNCHRONIZE (0x0010_) access; DELETE (0x0001_)
access isn't needed; 0x_0040 is not a supported key right;
KEY_CREATE_SUB_KEY (0x_0004) access isn't needed; and
KEY_QUERY_VALUE (0x_0001) isn't sufficient.

You should limit the requested access to the specific access rights
that are required for querying and setting values in the key:

 access=(wr.KEY_QUERY_VALUE | wr.KEY_SET_VALUE)


 def setvalue(self, vname, value):
return wr.SetValueEx(self.select(), vname, 0, 1, value)

You shouldn't hard code the value of the data type constant. Use
wr.REG_SZ instead of 1.

The return value of self.select() is a winreg PyHKEY object that wraps
the OS handle for the key object. You're relying on implicit closing
of this handle based on referencing counting. It's cleaner to use it
in a `with` statement, as you would for a file object returned by
open(). For example:

 with self.select() as hkey:
 wr.SetValueEx(hkey, vname, 0, wr.REG_SZ, value)


  lmregistry = Registry(
  hkey=wr.HKEY_LOCAL_MACHINE,
  sub_key="SOFTWARE\WOW6432Node\XXX Technology\AppName",

You really shouldn't open the "WOW6432Node" key directly. It is an
implementation detail of the WOW64 subsystem that runs 32-bit
applications on a 64-bit system. If you need to operate on the
registry keys of 32-bit applications from a native 64-bit process,
open the normal path using the access right KEY_WOW64_32KEY
(0x_0200). For example:

 hkey = wr.HKEY_LOCAL_MACHINE
 subkey = r"SOFTWARE\XXX Technology\AppName"
 access = (
 wr.KEY_QUERY_VALUE |
 wr.KEY_SET_VALUE

Re: [SOLVED] Module exists and cannot be found

2020-09-10 Thread James Moe via Python-list
On 9/8/20 10:35 PM, James Moe wrote:

> Module PyQt5 is most definitely installed. Apparently there is more to getting
> modules loaded than there used to be.
>
  Cause: Operator Error
  The python installation had become rather messy resulting in the errors I
showed. After installing python correctly, the errors disappeared and the app is
performing as expected.

  Thank you all for your replies.

-- 
James Moe
jmm-list at sohnen-moe dot com
Think.
-- 
https://mail.python.org/mailman/listinfo/python-list


[SOLVED] Re: Installing Python 3.8.3 with tkinter

2020-07-24 Thread Klaus Jantzen

On 7/22/20 12:20 PM, Klaus Jantzen wrote:

Hi,

Trying to install Python 3.8.3 with tkinter I run configure with the 
following options


./configure --enable-optimizations --with-ssl-default-suites=openssl 
--with-openssl=/usr/local --enable-loadable-sqlite-extensions 
--with-pydebug --with-tcltk-libs='-L/opt/ActiveTcl-8.6/lib/tcl8.6' 
--with-tcltk-includes='-I/opt/ActiveTcl-8.6/include'


Running Python gives the following information

Python 3.8.3 (default, Jul 22 2020, 11:52:15)
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import sqlite3
>>> import tkinter
Traceback (most recent call last):
  File "", line 1, in 
  File "/usr/local/lib/python3.8/tkinter/__init__.py", line 36, in 

    import _tkinter # If this fails your Python may not be configured 
for Tk

ModuleNotFoundError: No module named '_tkinter'
>>>

Obviously there is something wrong with my configure options.

How do that correctly?

Thanks for any help.

K.D.J.



In my post I forgot to mention that I am running PY under Debian Buster.

As suggested by Ned Deily I switched to PY 3.8.5

After some more research in the internet I found that the tcl/tk 
libraries have automaticalle been installed during the Buster installation.


For automatically including tkinter during the PY installation one needs 
also the 'tk-dev toolkit'.


With that I did not need the options 
'--with-tcltk-libs'/'--with-tcltk-includes'


After the installation of PY 3.8.5 I can import tkinter.

Thank you very much for your replies.

K.D.J.



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


Re: Solved: Re: Missing python curses functions?

2020-06-29 Thread Tony Flury via Python-list
Maybe you should raise a bug (bugs.python.org) and flag that this 
function is missing.


It could be that it can be introduced by whoever is maintaining the 
existing code.


On 20/05/2020 08:31, Alan Gauld via Python-list wrote:

On 19/05/2020 20:53, Alan Gauld via Python-list wrote:


One of the functions discussed that does not appear to have
a Python equivalent is attr_get() which gets the current
attributes.

OK, Using inch() I've written the following function:


def attr_get(win):
 """ return current window attributes.
 If a character exists at the bottom right position it will be lost!
 """
 y,x = win.getmaxyx() # how many lines in the window?
 win.insch(y-1,0,' ') # insert a space at bottom left
 ch = win.inch(y-1,0) # now read the char (including attributes)
 win.delch(y-1,0) # remove the char from window
 return ch

And it can be used like:

import curses
scr = curses.initscr()
# uncomment next line to test
# scr.attrset(curses.A_UNDERLINE)

atts = attr_get(scr)
if atts & cur.A_UNDERLINE:
 scr.addstr("Underline is on")
else:
 scr.addstr("Underline is off")

scr.refresh()
scr.getch()
curses.endwin()

Just in case its useful to anyone else...

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


Solved: Re: Missing python curses functions?

2020-05-20 Thread Alan Gauld via Python-list
On 19/05/2020 20:53, Alan Gauld via Python-list wrote:

> One of the functions discussed that does not appear to have
> a Python equivalent is attr_get() which gets the current
> attributes.

OK, Using inch() I've written the following function:


def attr_get(win):
""" return current window attributes.
If a character exists at the bottom right position it will be lost!
"""
y,x = win.getmaxyx() # how many lines in the window?
win.insch(y-1,0,' ') # insert a space at bottom left
ch = win.inch(y-1,0) # now read the char (including attributes)
win.delch(y-1,0) # remove the char from window
return ch

And it can be used like:

import curses
scr = curses.initscr()
# uncomment next line to test
# scr.attrset(curses.A_UNDERLINE)

atts = attr_get(scr)
if atts & cur.A_UNDERLINE:
scr.addstr("Underline is on")
else:
scr.addstr("Underline is off")

scr.refresh()
scr.getch()
curses.endwin()

Just in case its useful to anyone else...
-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: No module named 'gi' [SOLVED]

2020-04-13 Thread Jon Danniken

On 4/13/20 8:46 PM, Jon Danniken wrote:
Hello all, I am coming up with this error when, after installing 
Dropbox, I try to run Dropbox on my machine (kubuntu 18.04):


   SNIP 


Well it looks like I solved this issue with $pip uninstall conda.

Sometimes I just have to ask a question before my brain lets me have the 
answer.


Thanks,

Jon


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


[Solved] Re: dynamic import of dynamically created modules failes

2020-03-31 Thread Stephan Lukits



On 3/31/20 8:00 PM, Dieter Maurer wrote:

Stephan Lukits wrote at 2020-3-31 17:44 +0300:

background:

- a daemon creates package p1 (e.g. directory with __init__.py-file) and
in p1 a module m1 is created.

- Then the daemon wants to import from m1, which functions (so far all
the time).

- Then a module m2 is created in p1 and the daemon wants to import from
m2 which fails (most of the time but *not* always) with ModuleNotFoundError.

See the little test script at the end which reproduces the problem.
...

I remember a similar report (some time ago). There, caching has
been responsible. I have forgotten how to invalidate the caches.
But, you could try logic found in
`importlib._bootstrap_external.PathFinder.invalidate_caches`.


Yes, removing the entry for p1 from 'sys.path_importer_cache' seems to 
solve the problem.


Thank you.



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


Re: Suppress tooltips in Pygal charts (solved)

2019-10-12 Thread Roy Hann
Roy Hann wrote:

> Is there any way to tell Pygal not to generate references to on-line
> resources?

I can now answer my own question.

The solution was not obvious from reading the documentation but a glance
at the pygal code uncovered the answer. 

The js configuration parameter specifies where to look for JavaScript
resources. The scant documentation on js hints (wrongly) that it has
to be a URI reference with no specified scheme.

Reading the code it is clear a local file reference is allowed as the
scheme, so this works:

g=pygal.SolidGauge(half_pie=True,js=['file:///tmp/pygal-tooltips.min.js'])

The solution is to download the .js file ahead of time and store it
locally on my device.

Roy

PS: I know; /tmp is a silly place to put it. That's not the location I'm
really using.



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


Re: [SOLVED] Re: Compare zip lists where order is important

2019-08-29 Thread Peter Otten
Sayth Renshaw wrote:

> On Thursday, 29 August 2019 20:33:46 UTC+10, Peter Otten  wrote:
>> Sayth Renshaw wrote:
>> 
>> > will find the added
>> > pairs, but ignore the removed ones. Is that what you want?
>> > 
>> > Yes, I think. I want to find the changed pairs. The people that moved
>> > team numbers.
>> 
>> To find the people that moved team numbers I would tear the pairs apart.
>> Like:
>> 
>> >>> people = ["Tim","Bill","Sally","Ally","Fred","Fredricka"]
>> >>> team_number = [1,1,2,2,3,3]
>> >>> shuffle_people = ["Fredricka","Bill","Sally","Tim","Ally","Fred"]
>> >>> shuffle_team_number = [1,1,2,2,3,3]
>> >>> old = dict(zip(people, team_number))
>> >>> new = dict(zip(shuffle_people, shuffle_team_number))
>> >>> for name in old.keys() & new.keys():
>> ... old_team = old[name]
>> ... new_team = new[name]
>> ... if old_team != new_team:
>> ... print(name, "went from", old_team, "to", new_team)
>> ...
>> Tim went from 1 to 2
>> Fredricka went from 3 to 1
>> Ally went from 2 to 3
> 
> The reason I opted away from Dictionaries is if there was a team with
> people with same name. Then the keys would be the same.
> 
> So if Sally left and team 2 had one Tim move in and a new Tim start.
> shuffle_people = ["Fredricka","Bill","Tim","Tim","Ally","Fred"]
> shuffle_team_number = [1,1,2,2,3,3]
> 
> becomes
> {'Fredricka': 1, 'Bill': 1, 'Tim': 2, 'Ally': 3, 'Fred': 3}
> 
> This still appears to work but is wrong.
> 
> for name in old.keys()& new.keys():
> old_team = old[name]
> new_team = new[name]
> if old_team != new_team:
> print(name, "went from", old_team, "to", new_team)
> Ally went from 2 to 3
> Tim went from 1 to 2
> Fredricka went from 3 to 1
> 
> But I guess in reality I would use a UID and then look up the UID in a
> list or database.

It doesn't matter how you calculate the team changes; you always have to 
ensure unique players.

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


Re: [SOLVED] Re: Compare zip lists where order is important

2019-08-29 Thread Sayth Renshaw
On Thursday, 29 August 2019 20:33:46 UTC+10, Peter Otten  wrote:
> Sayth Renshaw wrote:
> 
> > will find the added
> > pairs, but ignore the removed ones. Is that what you want?
> > 
> > Yes, I think. I want to find the changed pairs. The people that moved team
> > numbers.
> 
> To find the people that moved team numbers I would tear the pairs apart. 
> Like:
> 
> >>> people = ["Tim","Bill","Sally","Ally","Fred","Fredricka"]
> >>> team_number = [1,1,2,2,3,3]
> >>> shuffle_people = ["Fredricka","Bill","Sally","Tim","Ally","Fred"]
> >>> shuffle_team_number = [1,1,2,2,3,3]
> >>> old = dict(zip(people, team_number))
> >>> new = dict(zip(shuffle_people, shuffle_team_number))
> >>> for name in old.keys() & new.keys():
> ... old_team = old[name]
> ... new_team = new[name]
> ... if old_team != new_team:
> ... print(name, "went from", old_team, "to", new_team)
> ... 
> Tim went from 1 to 2
> Fredricka went from 3 to 1
> Ally went from 2 to 3

The reason I opted away from Dictionaries is if there was a team with people 
with same name. Then the keys would be the same.

So if Sally left and team 2 had one Tim move in and a new Tim start.
shuffle_people = ["Fredricka","Bill","Tim","Tim","Ally","Fred"] 
shuffle_team_number = [1,1,2,2,3,3] 

becomes 
{'Fredricka': 1, 'Bill': 1, 'Tim': 2, 'Ally': 3, 'Fred': 3}

This still appears to work but is wrong.

for name in old.keys()& new.keys():
old_team = old[name]
new_team = new[name]
if old_team != new_team:
print(name, "went from", old_team, "to", new_team)
Ally went from 2 to 3
Tim went from 1 to 2
Fredricka went from 3 to 1

But I guess in reality I would use a UID and then look up the UID in a list or 
database.

Cheers

Sayth
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: [SOLVED] Re: Compare zip lists where order is important

2019-08-29 Thread Peter Otten
Sayth Renshaw wrote:

> will find the added
> pairs, but ignore the removed ones. Is that what you want?
> 
> Yes, I think. I want to find the changed pairs. The people that moved team
> numbers.

To find the people that moved team numbers I would tear the pairs apart. 
Like:

>>> people = ["Tim","Bill","Sally","Ally","Fred","Fredricka"]
>>> team_number = [1,1,2,2,3,3]
>>> shuffle_people = ["Fredricka","Bill","Sally","Tim","Ally","Fred"]
>>> shuffle_team_number = [1,1,2,2,3,3]
>>> old = dict(zip(people, team_number))
>>> new = dict(zip(shuffle_people, shuffle_team_number))
>>> for name in old.keys() & new.keys():
... old_team = old[name]
... new_team = new[name]
... if old_team != new_team:
... print(name, "went from", old_team, "to", new_team)
... 
Tim went from 1 to 2
Fredricka went from 3 to 1
Ally went from 2 to 3




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


Re: [SOLVED] Re: Compare zip lists where order is important

2019-08-29 Thread Sayth Renshaw
will find the added 
pairs, but ignore the removed ones. Is that what you want? 

Yes, I think. I want to find the changed pairs. The people that moved team 
numbers.

Sayth
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: [SOLVED] Re: Compare zip lists where order is important

2019-08-28 Thread Peter Otten
Sayth Renshaw wrote:

> On Thursday, 29 August 2019 14:03:44 UTC+10, Sayth Renshaw  wrote:
>> On Thursday, 29 August 2019 13:53:43 UTC+10, Sayth Renshaw  wrote:
>> > On Thursday, 29 August 2019 13:25:01 UTC+10, Sayth Renshaw  wrote:
>> > > Hi
>> > > 
>> > > Trying to find whats changed in this example. Based around work and
>> > > team reschuffles.
>> > > 
>> > > So first I created my current teams and then my shuffled teams.
>> > > 
>> > > people = ["Tim","Bill","Sally","Ally","Fred","Fredricka"]
>> > > team_number = [1,1,2,2,3,3]
>> > > 
>> > > shuffle_people = ["Fredricka","Bill","Sally","Tim","Ally","Fred"]
>> > > shuffle_team_number = [1,1,2,2,3,3]
>> > > 
>> > > Then combine.
>> > > 
>> > > teams = list(zip(people,team_number))
>> > > shuffle_teams = list(zip(shuffle_people, shuffle_team_number))
>> > > 
>> > > Then I am attempting to compare for change.
>> > > 
>> > > [i for i, j in zip(teams, shuffle_teams) if i != j]
>> > > 
>> > > #Result
>> > > [('Tim', 1), ('Ally', 2), ('Fred', 3), ('Fredricka', 3)]
>> > > 
>> > > #Expecting to see
>> > > 
>> > > [('Fredricka', 1),('Tim', 2)]
>> > > 
>> > > What's a working way to go about this?
>> > > 
>> > > Sayth
>> > 
>> > It looks like Tuples are comparing by position changes not content
>> > changes.
>> > 
>> > So this fails too
>> > 
>> > set(shuffle_teams) & set(teams)
>> > # {('Bill', 1), ('Fred', 3), ('Sally', 2)}
>> 
>> Well this works although its not clear which line is the change.
>> 
>> set(teams).symmetric_difference(set(shuffle_teams))
>> 
>> {('Ally', 2),
>>  ('Ally', 3), # This is the change Ally changed from 2 to 3
>>  ('Fredricka', 1), # However here this first line is the change.
>>  ('Fredricka', 3),
>>  ('Tim', 1),
>>  ('Tim', 2)}
>> 
>> Hints?
> 
> set(shuffle_teams).difference(set(teams))
> {('Ally', 3), ('Fredricka', 1), ('Tim', 2)}

(0) Sets use the comparison provided by their elements, there is no 
difference betwen ("Ally", 2) == ("Ally", 3) and "whatever" == 123
(1) If set operations work that means that list order is *not* important
(2) a.difference(b), which can also be written as a - b, will find the added 
pairs, but ignore the removed ones. Is that what you want?

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


[SOLVED] Re: Compare zip lists where order is important

2019-08-28 Thread Sayth Renshaw
On Thursday, 29 August 2019 14:03:44 UTC+10, Sayth Renshaw  wrote:
> On Thursday, 29 August 2019 13:53:43 UTC+10, Sayth Renshaw  wrote:
> > On Thursday, 29 August 2019 13:25:01 UTC+10, Sayth Renshaw  wrote:
> > > Hi
> > > 
> > > Trying to find whats changed in this example. Based around work and team 
> > > reschuffles.
> > > 
> > > So first I created my current teams and then my shuffled teams.
> > > 
> > > people = ["Tim","Bill","Sally","Ally","Fred","Fredricka"]
> > > team_number = [1,1,2,2,3,3]
> > > 
> > > shuffle_people = ["Fredricka","Bill","Sally","Tim","Ally","Fred"]
> > > shuffle_team_number = [1,1,2,2,3,3]
> > > 
> > > Then combine.
> > > 
> > > teams = list(zip(people,team_number))
> > > shuffle_teams = list(zip(shuffle_people, shuffle_team_number))
> > > 
> > > Then I am attempting to compare for change.
> > > 
> > > [i for i, j in zip(teams, shuffle_teams) if i != j]
> > > 
> > > #Result
> > > [('Tim', 1), ('Ally', 2), ('Fred', 3), ('Fredricka', 3)]
> > > 
> > > #Expecting to see
> > > 
> > > [('Fredricka', 1),('Tim', 2)]
> > > 
> > > What's a working way to go about this?
> > > 
> > > Sayth
> > 
> > It looks like Tuples are comparing by position changes not content changes.
> > 
> > So this fails too
> > 
> > set(shuffle_teams) & set(teams)
> > # {('Bill', 1), ('Fred', 3), ('Sally', 2)}
> 
> Well this works although its not clear which line is the change.
> 
> set(teams).symmetric_difference(set(shuffle_teams))
> 
> {('Ally', 2),
>  ('Ally', 3), # This is the change Ally changed from 2 to 3
>  ('Fredricka', 1), # However here this first line is the change.
>  ('Fredricka', 3),
>  ('Tim', 1),
>  ('Tim', 2)}
> 
> Hints?

set(shuffle_teams).difference(set(teams))
{('Ally', 3), ('Fredricka', 1), ('Tim', 2)}

Sayth
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Block Ctrl+S while running Python script at Windows console? (solved)

2019-03-18 Thread Malcolm Greene
Eryk,

> Another common culprit is quick-edit mode, in which case a stray mouse click 
> can select text, even just a single character. The console pauses while text 
> is selected.

MYSTERY SOLVED !! THANK YOU !!

Apparently, while mouse clicking between windows, I was inadvertently selecting 
a char on my console, thereby pausing the process that was running. Disabling 
Quick-Edit mode via the Properties dialog fixes this behavior.

I tried other console property setting combinations to block Ctrl+S keyboard 
behavior, but without success. Not a problem since I'm pretty sure I'm not 
typing random Ctrl+S keystrokes while working. 

Thanks again Eryk!
Malcolm
-- 
https://mail.python.org/mailman/listinfo/python-list


RE: python3.7.2 won't compile with SSL support (solved)

2019-02-21 Thread Felix Lazaro Carbonell


Incredibly:

./configure --with-ssl=/usr/include/openssl/

Made the trick!!
Although --with-ssl is not documented in ./configure --help.

Cheers,
Felix.

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


Re: [solved] C API version of str(exception) is not the same as pure python version

2019-02-10 Thread Barry Scott
On Sunday, 10 February 2019 11:59:16 GMT Barry Scott wrote:
> When I use the C API to get the str() of an execption I see this text:
> 
>   
> 
> But python reports the following for the same exception:
> 
>   TypeError: unsupported operand type(s) for +: 'int' and 'str'
> 
> What do I need to do in the C API to get the the same text for the
> exception?
> 

> PyObject *err = PyErr_Occurred();
> if( err != 0 )
> {
> PyObject *u_why = PyObject_Str( err );
> PyObject *b_why = PyUnicode_AsEncodedString( u_why, "utf-8",
> "strict" );
> int size = PyBytes_Size( b_why );
> char *why = PyBytes_AsString( b_why );
> printf("Error: %*s\n", size, why );
> return 0;
> }

Using this code fixes the problem as Stefan pointed out I had the type of the 
exception and not the value of the exception.

if( PyErr_Occurred() )
{
PyObject *type, *value, *trace;
PyErr_Fetch( &type, &value, &trace );

PyObject *u_why = PyObject_Str( value );
PyObject *b_why = PyUnicode_AsEncodedString( u_why, "utf-8", "strict" 
);
int size = PyBytes_Size( b_why );
char *why = PyBytes_AsString( b_why );
printf("Error: %*s\n", size, why );
return 0;
}



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


[SOLVED] Re: ah, progress...

2018-12-23 Thread ant
dieter wrote:

...

  thank you for your help.  :)  i finally worked through
the changes needed at last.


  my current package in testing PyPI is at:

  https://test.pypi.org/project/ngfp/

  which uses my code from:

  https://salsa.debian.org/ant-guest/gfpoken-in-python


  i ended up needing to do two things.  to get all the import
statements changed to include the package/module name and to
change all my image load statements to include the full path
as determined at runtime.

  this may not work on a non-linux or non-posix system from
the binary distribution but the source code distribution may
work ok.  if anyone wants to try it out.

  feedback is appreciated in any case.  :)


  now the next fun steps (figuring out the windows, other 
versions and then the Debian packaging for it).  since i
don't have windows or other machines to test on i don't 
know how that will go.

  cheers and thanks again,


  ant
-- 
https://mail.python.org/mailman/listinfo/python-list


Solved: pip hangs after successful operation (sandboxed environment problem)

2018-10-05 Thread Ryan Johnson
It turns out that Comodo Antivirus auto-sandboxes any program that it doesn’t 
recognize, and this included python in the C:\Users\$user\AppData\Programs 
directory.

This also affects Cygwin and MSYS2 (but not MSYS).

If you are thinking about using Comodo, disable the Auto-Containment feature. 
Alternately, you may try to add the folder locations to the white-list, but 
this didn’t work for me.

Have a nice day,
Ryan

Sent from Mail for Windows 10

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


[SOLVED] Re: Querying MariaDB from python

2018-10-02 Thread Tony van der Hoff
On 02/10/18 17:13, Larry Martell wrote:
> On Tue, Oct 2, 2018 at 12:09 PM Tony van der Hoff  
> wrote:
>>
>> On 02/10/18 16:47, Ervin Hegedüs wrote:
>>> hi,
>>>
>>> now rows will looks like this:
>>> ({'id':...,...},{'id':...,}...)
>>
>> Thanks Ervin, but:
>>
>>cursor = cnx.cursor(pymysql.cursors.DictCursor)
>> NameError: name 'pymysql' is not defined
>>
>> I have been using the mysql.connector module, which seems to be the
>> "official" python interface.
> 
> That also supports the cursordict:
> 
> https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursordict.html
> 

Great, thanks Larry, that sorts it.

-- 
Tony van der Hoff| mailto:t...@vanderhoff.org
Buckinghamshire, England |
-- 
https://mail.python.org/mailman/listinfo/python-list


[SOLVED]: problem with json.dumps / complexjson.loads in python 3.4 virtualenv

2018-09-05 Thread M. Fioretti

On 2018-09-05 08:21, dieter wrote:

"M. Fioretti"  writes:

I have an error in a python application that I installed...
... https://github.com/shaarli/python-shaarli-client/issues/33

...
Looks like the problem is immediately at the start of the response
(--> "ValueError: Expecting value: line 1 column 1 (char 0)"),
i.e. the server response is not recognizable as a JSON encoded value.


indeed, it turned out that the problem was a misconfiguration of the 
server
that prevented it from sending correct answers when contacted by that 
python application. Thanks for helping me to look in the right 
direction.


Marco
--
http://mfioretti.com
--
https://mail.python.org/mailman/listinfo/python-list


Re: Python web server weirdness SOLVED

2018-06-07 Thread Gregory Ewing

Steven D'Aprano wrote:
Never mind -- it turned out I had an "index.html" file in the directory 
which had been wget'ed from LiveJournal.


That's okay, then. The other possibility was that your computer
had been recruited into an evil botnet set up by LiveJournal
to create backup servers for their site...

--
Greg
--
https://mail.python.org/mailman/listinfo/python-list


Re: Python web server weirdness SOLVED

2018-06-07 Thread Steven D'Aprano
On Thu, 07 Jun 2018 13:32:10 +, Steven D'Aprano wrote:

[...]
> python3.5 -m http.server 8000
> 
> What I expected was a directory listing of my current directory.
> 
> What I got was Livejournal's front page.

Never mind -- it turned out I had an "index.html" file in the directory 
which had been wget'ed from LiveJournal. When I deleted that, it worked 
as expected.




-- 
Steven D'Aprano
"Ever since I learned about confirmation bias, I've been seeing
it everywhere." -- Jon Ronson

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


Re: Uploading on PyPI fail (solved)

2018-05-15 Thread Vincent Vande Vyvre

Le 15/05/18 à 12:05, Vincent Vande Vyvre a écrit :

Hi,

Trying to upgrade a package on PyPI, I get this error:

$ python3 setup.py register sdist upload
...
Submitting dist/py3exiv2-0.3.0.tar.gz to https://pypi.python.org/pypi
Upload failed (308): Redirect to Primary Domain
error: Upload failed (308): Redirect to Primary Domain

I know the site has changed but what is changed for me ?

This is the content of my .pypirc:
-
[distutils]
index-servers=
    pypi
    pypitest

[pypitest]
repository = https://test.pypi.org/legacy/
username = VinsS
password = ***

[pypi]
repository = https://upload.pypi.org/legacy/
username = VinsS
password = **
-

Note: I've tested on test.pypi.org without problems.

Thanks for all advices,

Vincent

(send at Tue, 15 May 2018 12:04:10 +0200)


Solved with $ twine upload  dist/*


...

Vincent

(send at Tue, 15 May 2018 14:34:10 +0200)


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


Re: urllib.request.urlopen fails with https - SOLVED

2018-03-16 Thread Irv Kalb
Thank you, thank you, thank you.

That fixed it (at least on my computer, I'll see if I can do that at my school).

Irv


> On Mar 15, 2018, at 7:39 PM, Ned Deily  wrote:
> 
> On 2018-03-14 18:04, Irv Kalb wrote:
>> File 
>> "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/urllib/request.py",
>>  line 1320, in do_open
>>   raise URLError(err)
>> urllib.error.URLError: > certificate verify failed (_ssl.c:749)>
> 
> If you are using Python 3.6 for macOS from a python.org installer, did
> you follow the instructions displayed in the installer ReadMe and also
> saved at:
> 
> /Applications/Python 3.6/ReadMe.rtf
> 
> to run the "Install Certificates.command" ?
> 
> Either double-click on it in the Finder or, from a shell command line, type:
> 
>   open "/Applications/Python 3.6/Install Certificates.command"
> 
> 
> Certificate verification and OpenSSL
> 
> **NEW** This variant of Python 3.6 now includes its own private copy of
> OpenSSL 1.0.2.  Unlike previous releases, the deprecated Apple-supplied
> OpenSSL libraries are no longer used.  This also means that the trust
> certificates in system and user keychains managed by the Keychain Access
> application and the security command line utility are no longer used as
> defaults by the Python ssl module.  For 3.6.0, a sample command script
> is included in /Applications/Python 3.6 to install a curated bundle of
> default root certificates from the third-party certifi package
> (https://pypi.python.org/pypi/certifi).  If you choose to use certifi,
> you should consider subscribing to the project's email update service to
> be notified when the certificate bundle is updated.
> 
> 
> -- 
> https://mail.python.org/mailman/listinfo/python-list
> 

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


Re: Re: Problem with StreamReaderWriter on 3.6.3? SOLVED

2017-10-20 Thread Peter via Python-list

Thanks MRAB, your solution works a treat.

I'm replying to the list so others can know that this solution works. 
Note that sys.stderr.detach() is only available in >= 3.1, so one might 
need to do some version checking to get it to work properly in both 
versions. It also can mess up with the buffering and therefore the order 
of the output of stderr vs stdout.


Thanks again.

Peter


On 20/10/2017 10:19 AM, MRAB wrote:

On 2017-10-19 22:46, Peter via Python-list wrote:

I came across this code in Google cpplint.py, a Python script for
linting C++ code. I was getting funny results with Python 3.6.3, but it
worked fine under 2.7.13

I've tracked the problem to an issue with StreamReaderWriter; the
traceback and error never shows under 3. The _cause_ of the error is
clear (xrange not in Py3), but I need the raised exception to show.

I'm running Python 3.6.3 32bit on Windows 10. I also get the same
results on Python 3.5.2 on Ubuntu (under WSL)

I'm not super familiar with rebinding stderr with codecs, but I'm
guessing they are doing it because of some Unicode issue they may have
been having.

I have a workaround - drop the rebinding - but it seems like there might
be an error in StreamReaderWriter.
Do other people see the same behaviour?
Is there something I'm not seeing or understanding?
Would I raise it on issue tracker?

Peter

--

import sys
import codecs

sys.stderr = codecs.StreamReaderWriter(
      sys.stderr, codecs.getreader('utf8'), codecs.getwriter('utf8'),
'replace')

# This should work fine in Py 2, but raise an exception in Py3
# But instead Py3 "swallows" the exception and it is never seen
print(xrange(1, 10))

# Although this line doesn't show in Py 3 (as the script has silently
crashed)
print("This line doesn't show in Py 3")

--

StreamReaderWriter is being passed an encoder which returns bytes 
(UTF-8), but the output stream that is being passed, to which it will 
be writing those butes, i.e. the original sys.stderr, expects str.


I'd get the underlying byte stream of stderr using .detach():

sys.stderr = codecs.StreamReaderWriter(sys.stderr.detach(), 
codecs.getreader('utf8'), codecs.getwriter('utf8'), 'replace')





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


Solved (Was: Re: [Q] days -> months)

2017-10-11 Thread Byung-Hee HWANG (황병희, 黃炳熙)
Oh never mind it, after so many trial and error, i did make months
format with success, thanks!!! 

Sincerely, Byung-Hee.

-- 
^고맙습니다 _救濟蒼生_ 감사합니다_^))//

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


Re: [SOLVED] Re: Firebird 1.5 and Python 3.4 - is this possible?

2017-08-10 Thread Ben Finney
Nagy László Zsolt  writes:

> Problem solved!

Congratulations. And thank you for reporting the succesful resolution :-)

-- 
 \  “It is clear that thought is not free if the profession of |
  `\   certain opinions makes it impossible to earn a living.” |
_o__)  —Bertrand Russell, _Free Thought and Official Propaganda_, 1928 |
Ben Finney

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


[SOLVED] Re: Firebird 1.5 and Python 3.4 - is this possible?

2017-08-09 Thread Nagy László Zsolt
To answer my own question:


- You can convert a firebird 1.5 database into 2.5 with this tool:
http://gsbelarus.com/gs/fdbconvert/fdbconvert_eng.html

- You can install firebird 2.5 instead of 1.5. Old BDE based program
will still work with it, because the Firebird 2.5 server can talk with a
1.5 client.

- The official fdb module (https://pypi.python.org/pypi/fdb right now at
version 1.7) can be used from Python 3, and it works with Firebird 2.5

Problem solved!



>   Hi!
>
> I have an old HIS program written in Delphi. It uses Firebird 1.5
> database. I need to make an interface to exchange data with other
> healthcare providers. I do not want to do this in Delphi, that is
> ancient code. It is also not an option to rewrite the whole program from
> scratch. I just need to add a service that runs in the background and
> sends/receives data.
>
> Is it possible to somehow connect and use firebird 1.5 database from
> Python 3? I have tried kinterbasdb with no luck. There are a number of
> firebird libraries out there, but none of them seems to support firebird
> 1.5.
>
> Does anyone know a library that can do this?
>
> Thanks,
>
>Laszlo
>
>
>

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


Re: Extended ASCII [solved]

2017-01-13 Thread D'Arcy Cain

On 2017-01-13 05:44 PM, Grant Edwards wrote:

On 2017-01-13, D'Arcy Cain  wrote:


Here is the failing code:

with open(sys.argv[1], encoding="latin-1") as fp:
   for ln in fp:
 print(ln)

Traceback (most recent call last):
   File "./load_iff", line 11, in 
 print(ln)
UnicodeEncodeError: 'ascii' codec can't encode character '\xe9' in
position 132: ordinal not in range(128)

I don't understand why the error says "ascii" when I told it to use
"latin-1".


That can't be the failing code, since it's failing at line 11, and
that's only 5 lines. It helps if we can tell which line generated the
error.  ;)


I didn't think that the part leading up to it was relevant.  Here it is.

#! /usr/bin/python

import sys, os

if len(sys.argv) < 2:
print("No file named", file=sys.stderr)
sys.exit(1)


I'm _guessing_ that line 11 is the print(), and it's barfing because


Of course.  That's why the error is listed right below it.


stdout is using ascii encoding, and there's no way to encode that
character in ascii so that it can be printed to an ascii output
stream.


Thank you!  I know all about that but for some reason I did not have 
PYTHONIOENCODING=utf8 set on that particular machine.  I have it set on 
every other machine I work on an never thought to check.  My Unicode 
universe is all right again.


Cheers.

--
D'Arcy J.M. Cain
System Administrator, Vex.Net
http://www.Vex.Net/ IM:da...@vex.net
VoIP: sip:da...@vex.net
--
https://mail.python.org/mailman/listinfo/python-list


Re: Append/Replace a row in a pandas DataFrame [SOLVED]

2016-04-14 Thread Peter Otten
Paulo da Silva wrote:

> Às 21:10 de 13-04-2016, Paulo da Silva escreveu:
>> Hi all.
> ...
> 
>> [6 rows x 4 columns]
>> 
>>> dft=pd.DataFrame([[1,2,3,4]],
>> index=[datetime.date(2016,1,12)],columns=df.columns)
>> 
>>> dft
>> A  B  C  D
>> 2016-01-12  1  2  3  4
>> 
>> [1 rows x 4 columns]
>> 
>>> pd.concat([df,dft])
>> Out[71]:
>> A B C D
>> 2013-01-01 00:00:00 -0.111621  1.126761 -2.420517  0.660948
>> 2013-01-02 00:00:00 -0.243397 -0.975684 -0.679209 -0.656913
>> 2013-01-03 00:00:00  0.405816  0.478353  0.621906 -0.262615
>> 2013-01-04 00:00:00 -0.380249  0.416711 -0.906286  1.828339
>> 2013-01-05 00:00:00  0.772747  0.993784  0.452746  1.665306
>> 2013-01-06 00:00:00  0.535011 -0.662874  1.504281  0.543537
>> 2016-01-12   1.00  2.00  3.00  4.00
>> 
>> [7 rows x 4 columns]
>> 
>> Why am I getting the second column?!
> I need to use for example pd.datetime instead of datetime.date. In fact
> there is no extra col but the inclusion of hour in the index.
> Still don't understand why!

It looks like handling of datetime objects is specialised

>>> pd.DataFrame([[1,2]], index=[datetime.datetime.now()], columns=["foo", 
"bar"]).index

[2016-04-14 08:51:09.192283]
Length: 1, Freq: None, Timezone: None

and assumes the "all-midnight" case to mean that no time of day was provided 
whereas date is handled like a generic object

>>> pd.DataFrame([[1,2]], index=[datetime.date.today()], columns=["foo", 
"bar"]).index
Index([2016-04-14], dtype='object')

and triggers usage of the string conversion provided by the entries.
For datetime this includes the time that you mistook for an extra column.

>>> str(datetime.datetime(2010, 12, 21))
'2010-12-21 00:00:00'
>>> str(datetime.date(2010, 12, 21))
'2010-12-21'

>> How do I do to have a row replaced instead of added if its date (index)
>> is an existent one?
> df.loc[]=
> 
> Paulo
> 


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


Re: Append/Replace a row in a pandas DataFrame [SOLVED]

2016-04-13 Thread Paulo da Silva
Às 21:10 de 13-04-2016, Paulo da Silva escreveu:
> Hi all.
...

> [6 rows x 4 columns]
> 
>> dft=pd.DataFrame([[1,2,3,4]],
> index=[datetime.date(2016,1,12)],columns=df.columns)
> 
>> dft
> A  B  C  D
> 2016-01-12  1  2  3  4
> 
> [1 rows x 4 columns]
> 
>> pd.concat([df,dft])
> Out[71]:
> A B C D
> 2013-01-01 00:00:00 -0.111621  1.126761 -2.420517  0.660948
> 2013-01-02 00:00:00 -0.243397 -0.975684 -0.679209 -0.656913
> 2013-01-03 00:00:00  0.405816  0.478353  0.621906 -0.262615
> 2013-01-04 00:00:00 -0.380249  0.416711 -0.906286  1.828339
> 2013-01-05 00:00:00  0.772747  0.993784  0.452746  1.665306
> 2013-01-06 00:00:00  0.535011 -0.662874  1.504281  0.543537
> 2016-01-12   1.00  2.00  3.00  4.00
> 
> [7 rows x 4 columns]
> 
> Why am I getting the second column?!
I need to use for example pd.datetime instead of datetime.date. In fact
there is no extra col but the inclusion of hour in the index.
Still don't understand why!

> 
> How do I do to have a row replaced instead of added if its date (index)
> is an existent one?
df.loc[]=

Paulo

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


Re: [SOLVED] There has to be a better way to split this string!

2016-02-09 Thread Chris Kaynor
On Tue, Feb 9, 2016 at 5:58 PM, Anthony Papillion 
wrote:
>
> On 02/09/2016 07:47 PM, Ben Finney wrote:
> > Anthony Papillion  writes:
> >
> >> On 02/09/2016 07:26 PM, Anthony Papillion wrote:
> >>> I am using datetime.now() to create a unique version of a filename.
> >>> […]
> >>
> >> Found the solution in strftime(). Exactly what I was looking for.
> >
> > For the task of making a unique filename, you should also consider the
> > ‘tempfile’ module in the standard library.
>
> I looked at tempfile. Unfortunately, the filename has to be both
> 'unique' and 'identifiable' to the original. So if I am using mydog.jpg
> as the source and I am adding something unique to it, it has to still
> have mydog.jpg in the filename. Tempfile, I think, doesn't allow an easy
> way to do that. So I'm just adding the exact date and time which is
> unique enough for my purposes.

Actually, it doe (untested, but I've used the feature in projects):

tempfile.TemporaryFile(prefix="mydog", suffix=".jpg")

Chris
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: [SOLVED] There has to be a better way to split this string!

2016-02-09 Thread Anthony Papillion
On 02/09/2016 07:47 PM, Ben Finney wrote:
> Anthony Papillion  writes:
> 
>> On 02/09/2016 07:26 PM, Anthony Papillion wrote:
>>> I am using datetime.now() to create a unique version of a filename.
>>> […]
>>
>> Found the solution in strftime(). Exactly what I was looking for.
> 
> For the task of making a unique filename, you should also consider the
> ‘tempfile’ module in the standard library.

I looked at tempfile. Unfortunately, the filename has to be both
'unique' and 'identifiable' to the original. So if I am using mydog.jpg
as the source and I am adding something unique to it, it has to still
have mydog.jpg in the filename. Tempfile, I think, doesn't allow an easy
way to do that. So I'm just adding the exact date and time which is
unique enough for my purposes.

Thanks for the pointer though.

Anthony


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


Re: [SOLVED] There has to be a better way to split this string!

2016-02-09 Thread Ben Finney
Anthony Papillion  writes:

> On 02/09/2016 07:26 PM, Anthony Papillion wrote:
> > I am using datetime.now() to create a unique version of a filename.
> > […]
>
> Found the solution in strftime(). Exactly what I was looking for.

For the task of making a unique filename, you should also consider the
‘tempfile’ module in the standard library.

-- 
 \   “I distrust those people who know so well what God wants them |
  `\to do to their fellows, because it always coincides with their |
_o__)  own desires.” —Susan Brownell Anthony, 1896 |
Ben Finney

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


Re: [SOLVED] There has to be a better way to split this string!

2016-02-09 Thread Anthony Papillion
On 02/09/2016 07:26 PM, Anthony Papillion wrote:
> Hello Everyone,
> 
> I am using datetime.now() to create a unique version of a filename.
> When the final file is named, it will look something like:
> 
> myfile-2015-02-09-19-08-45-4223
> 
> Notice I'm replacing all of the "."'s, " "'s, and ":"'s returned by
> datetime.now() with "-"'s. I'm doing that using the following code but
> it's freaking ugly and I KNOW there is a better way to do it. I just
> can't seem to think of it right now. Can anyone help? What is the
> "right", or at least, less ugly, way to do this task?

Found the solution in strftime(). Exactly what I was looking for.



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


Re: SSL certification fails / tweepy [SOLVED]

2016-01-14 Thread dieter
"K. Elo"  writes:
> ...
> I still wonder why openSuSE certificates are not working out-of-box
> with python. Maybe some of the packages were not correctly installed...

Certificates have a validity period -- usually, they need to be
renewed from time to time (to get a new vality period).

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


Re: SSL certification fails / tweepy [SOLVED]

2016-01-14 Thread K. Elo

Hi!


14.01.2016, 09:59, dieter wrote:

"SSL_VERIFICATION_FAILED" is an error which occurs when
an SSL ("https") connection is established. It happens when
the SSL certificate (of the server and/or client) does not contain
expected data - e.g. the certificate is no longer (or not yet) valid
or its subject does not reference the connected entity or the
certificate chain cannot be verified.

Look for Python documentation on SSL verification to learn how to
properly set up things for successful verfication. Among others,
you will need have somewhere information about trusted root certificates.



Thanks, dieter, for your reply. I have now re-installed both certificate 
packages and (open)ssl related python packages - and now it works!


I still wonder why openSuSE certificates are not working out-of-box with 
python. Maybe some of the packages were not correctly installed...


Anyway, thanks for your quick reply - the issue is now solved :)

Best,
Kimmo
--
https://mail.python.org/mailman/listinfo/python-list


Re: Accessing container's methods [solved]

2015-12-08 Thread Tony van der Hoff

Hum, sorry about the empty reply; just finger trouble!

Anyway I wasn't expecting such a great response; thanks to all.

On 07/12/15 23:47, Erik wrote:
[snip]


As you can't sensibly put the object into more than one container at a
time anyway, then you can pass the container object to the Actor object
as its "parent". It can then call its parent object for things that the
parent will know (such as, the total number of contained objects):

class Actor:
def __init__ ( self, name, id, parent ):
  self.name = name
  self.id = id
  self.parent = parent

def get_name( self ):
  txt = "I'm Actor {} Number {} of {}".\
   format(  self.name, self.id, self.parent.count_actors() )
  return txt

Then you can add a new actor with:

   self.actors.append( Actor( n, i, self ) )

Whilst I'm grateful for all the responses, this is the one that got me 
out of the hole I dug myself into.


In fact, this is precisely what I tried previously, and got:
TypeError: 'instancemethod' object has no attribute '__getitem__'

In my naivety, I concluded that this meant I couldn't use the 'self' 
pointer in this way. However, trying it with the Monty example, it 
worked fine, and I have now tracked down my error elsewhere.




Note that you are creating circular references here, too (the container
references the Actor object and the Actor object references the
container). Just another possible issue to bear in mind ...

Yes, I guess it's quite nasty, but, in the non-trivial case, I'm only 
calling for dynamic data from the parent, and not modifying it in any 
way, so I think I can get away with it. Otherwise, I'd have to pass a 
vast list of initialization data to the (many) children, and keep that 
up to date by passing it down the line to each one, just in case it's 
required, which would slow down things excessively. I know that if a 
design doesn't feel comfortable, then it's probably wrong, but I believe 
that in this case it's probably the best way forward.




Also, while I'm looking at this, you have this loop and comment:

 >def __init__( self, names ):
 >  self.actors = []
 >
 >  i = 0
 >  for n in names:
 >self.actors.append( Actor( n, i ) )
 >i += 1# here is a case for python supporting post-increment!

However, if you refactor that loop to use iterators, you don't need to
manually manipulate 'i' at all (you need to import the itertools module
first, and this is the "new" version where the container is passed in as
the parent):

 def __init__( self, names ):
   self.actors = [ Actor ( n, i, self ) for n, i in
itertools.izip(names, itertools.count()) ]

Or, if you don't like list comprehensions:

 def __init__( self, names ):
   self.actors = []
   for n, i in itertools.izip(names, itertools.count()):
 self.actors.append( Actor( n, i, self ) )


I rather liked Terry's suggestion of using enumerate.

The comment was tounge-in-cheek: Referring to an earlier thread, I'm yet 
to be convinced that Python is better for not having 
pre/post-increment/decrement operators. But, hey, I'm sure better minds 
than mine have addressed the subject ;)



(I assume you're using Python 3 because of your print statement - in
Python 3, 'itertools.izip' should just be 'zip'.)


No, Im actually stuck on Python 2.7. I don't see how you jumped to that 
conclusion from a simple print statement.


On 07/12/15 21:38, Terry Reedy wrote:
[snip]
> This is actually a case for using enumerate:
>for i, name in enumerate(names):
>
I've not come across this previously, but shall certainly use it in 
future. Thanks!


> return list(self.actors)  # or perhaps even faster
> return self.actors[:]

That doesn't seem to work:
<__main__.Actor instance at 0x7fc7478ba560>
<__main__.Actor instance at 0x7fc7478ba5a8>
<__main__.Actor instance at 0x7fc7478ba5f0>


Anyway, I'm no longer in a hole; thanks for all the excellent help. I'll 
certainly review the design of my current project, to see if it can be 
improved.


Cheers, Tony

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


Re: Unicode failure (Solved)

2015-12-06 Thread Dave Farrance
"D'Arcy J.M. Cain"  wrote:

>On Fri, 4 Dec 2015 18:28:22 -0500
>Terry Reedy  wrote:
>> Tk widgets, and hence IDLE windows, will print any character from
>> \u to \u without raising, even if the result is blank or ?.
>> Higher codepoints fail, but allowing the entire BMP is better than
>> any Windows codepage.
>
>Thanks to all.  Following up on the various posts brought me to
>information that solved my problem.  Basicall I added "export
>PYTHONIOENCODING=utf8" to my environment and "SetEnv PYTHONIOENCODING
>utf8" in my Apache config and now things are working as they should.
>
>Thanks all.

Hmmm. I hadn't seen this post before replying to the original because my
newsreader put this post in a later thread because:

(a) The subject header was changed
(b) The reference header is for a post that's not present in Usenet

That raises another question.  I'm seeing a number of broken threads
because people reply to posts that are not present in Usenet.  It's not
just my main news-server because my newreader can gather posts from
several Usenet servers and those posts are nowhere on Usenet.

Case in point:  The post by Terry Reedy quoted above, reference
. I presume that it's on the list server
even though it's not on Usenet.  Anybody know what's going on?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Unicode failure (Solved)

2015-12-05 Thread D'Arcy J.M. Cain
On Fri, 4 Dec 2015 18:28:22 -0500
Terry Reedy  wrote:
> Tk widgets, and hence IDLE windows, will print any character from
> \u to \u without raising, even if the result is blank or �.
> Higher codepoints fail, but allowing the entire BMP is better than
> any Windows codepage.

Thanks to all.  Following up on the various posts brought me to
information that solved my problem.  Basicall I added "export
PYTHONIOENCODING=utf8" to my environment and "SetEnv PYTHONIOENCODING
utf8" in my Apache config and now things are working as they should.

Thanks all.

-- 
D'Arcy J.M. Cain
Vybe Networks Inc.
http://www.VybeNetworks.com/
IM:da...@vex.net VoIP: sip:da...@vybenetworks.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Data integrity problem with sqlite3 - solved

2015-08-11 Thread Frank Millman

"Frank Millman"  wrote in message news:mqcslv$tee$1...@ger.gmane.org...


"Frank Millman"  wrote in message news:mqcmie$po9$1...@ger.gmane.org...

> Hi all
>
> I have a 'data integrity' problem with sqlite3 that I have been battling 
> with for a while. I have not got to the bottom of it yet but I do have 
> some useful info, so I thought I would post it here in the hope that 
> someone with some knowledge of the internals of the python sqlite3 
> module can throw some light on it.


Oops, I have just spotted my mistake.

There are times when I want to issue a SELECT statement with a lock, as it 
will be followed by an UPDATE and I do not want anything to change in 
between.


MS SQL Server allows you to add 'WITH (UPDLOCK)' to a SELECT statement, 
PostgreSQL allows you to add 'FOR UPDATE'.


I could not find an equivalent for sqlite3, but in my wisdom (this was 
some time ago) I decided that issuing a 'BEGIN IMMEDIATE' would do the 
trick.


I had not anticipated that this would generate an implied COMMIT first, 
but it makes sense, and this is what has bitten me. Now I must try to 
figure out a better solution.


For the record, I have figured out a better solution.

I was on the right lines with 'BEGIN IMMEDIATE', but I had overlooked the 
possibility that there could be a transaction already in progress.


Now I have changed it to -

   if not conn.in_transaction:
  cur.execute('BEGIN IMMEDIATE')

So far it seems to be working as intended.

Frank

P.S. Many thanks to the maintainers of the sqlite3 module for continuing to 
enhance it. 'in_transaction' was added in 3.2, and 'set_trace_callback' was 
added in 3.3. Without these my life would have been much more difficult.



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


Re: Data integrity problem with sqlite3 - solved

2015-08-11 Thread Frank Millman

"Frank Millman"  wrote in message news:mqcmie$po9$1...@ger.gmane.org...


Hi all

I have a 'data integrity' problem with sqlite3 that I have been battling 
with for a while. I have not got to the bottom of it yet but I do have 
some useful info, so I thought I would post it here in the hope that 
someone with some knowledge of the internals of the python sqlite3 module 
can throw some light on it.


Oops, I have just spotted my mistake.

There are times when I want to issue a SELECT statement with a lock, as it 
will be followed by an UPDATE and I do not want anything to change in 
between.


MS SQL Server allows you to add 'WITH (UPDLOCK)' to a SELECT statement, 
PostgreSQL allows you to add 'FOR UPDATE'.


I could not find an equivalent for sqlite3, but in my wisdom (this was some 
time ago) I decided that issuing a 'BEGIN IMMEDIATE' would do the trick.


I had not anticipated that this would generate an implied COMMIT first, but 
it makes sense, and this is what has bitten me. Now I must try to figure out 
a better solution.


Apologies for any wasted time.

Frank






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


Re: Improper Django Project error (solved)

2015-08-01 Thread Gary Roach

On 07/30/2015 11:15 PM, dieter wrote:

Gary Roach  writes:

Being new to Django and Python, I have two projects setup side by
side, each in it's own virtualenv wrapper.
The twr_project is running Django 1.7, python 2.7 and is set up to
duplicate the 'Tango With Rango' tutorial.
The archivedb project is running Django 1.8, python 2.7 and is my
actual project.

As this is more a "Django" (than a general "Python") question,
you might get better help in a "Django" mailing list/support forum.

Actually you are dead correct on that.



Your "subject" indicates that you likely see (somewhere)
the "Django" error message "Improper Django Project error".
Likely, you have corrupted you "Django" project setup.
Read about how "Django" projects must look like and fix your setup.
The real problem was that the settings.py files for Django 1.7 and 1.8 
have some very significant differences with the format of the TEMPLATES 
= [] tuple. So the  problem's solved --- sort of .

I am using Ninja-IDE as my IDE. I like it a lot.

At this point both projects are essentially identical with the
exception of name changes. The twr project work down to the first
template inclusion ( index.html ). The archivedb project refuses to
find the home.html template file. The system layout is exactly the
same.

I wiped the home.html file and attempted to re-install it but my IDE
gave the following error window:


Sorry, either settings file or virtualenv are missingthese are
required for Django Plugin to work in thepresent version, we are
working on fixing this.


I have virtualenv installed and active and the settings file is
present.

You should ask this question on a "Ninja-IDE" mailing list/support forum.
Ninja_IDE is just reporting an apparent problem. The real problem is 
that the browser can't find the file. A Django problem.




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


Re: Improper Django Project error (solved)

2015-07-31 Thread Gary Roach

On 07/30/2015 11:15 PM, dieter wrote:

Gary Roach  writes:

Being new to Django and Python, I have two projects setup side by
side, each in it's own virtualenv wrapper.
The twr_project is running Django 1.7, python 2.7 and is set up to
duplicate the 'Tango With Rango' tutorial.
The archivedb project is running Django 1.8, python 2.7 and is my
actual project.

As this is more a "Django" (than a general "Python") question,
you might get better help in a "Django" mailing list/support forum.

Actually you are dead correct on that.



Your "subject" indicates that you likely see (somewhere)
the "Django" error message "Improper Django Project error".
Likely, you have corrupted you "Django" project setup.
Read about how "Django" projects must look like and fix your setup.
The real problem was that the settings.py files for Django 1.7 and 1.8 
have some very significant differences with the format of the TEMPLATES 
= [] tuple. So the  problem's solved --- sort of .

I am using Ninja-IDE as my IDE. I like it a lot.

At this point both projects are essentially identical with the
exception of name changes. The twr project work down to the first
template inclusion ( index.html ). The archivedb project refuses to
find the home.html template file. The system layout is exactly the
same.

I wiped the home.html file and attempted to re-install it but my IDE
gave the following error window:


Sorry, either settings file or virtualenv are missingthese are
required for Django Plugin to work in thepresent version, we are
working on fixing this.


I have virtualenv installed and active and the settings file is
present.

You should ask this question on a "Ninja-IDE" mailing list/support forum.
Ninja_IDE is just reporting an apparent problem. The real problem is 
that the browser can't find the file. A Django problem.




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


Re: password authentication failed (SOLVED)

2015-07-24 Thread Gary Roach

On 07/22/2015 04:44 PM, Chris Angelico wrote:

On Thu, Jul 23, 2015 at 9:35 AM, Gary Roach  wrote:

At this point, I'm confused about a few things. Does the postgresql server
and my archivedb reside globally or are they inside my archivedb virtual
environment. I think globally.

Your virtual environment is a Python construct only. That's where
Python packages get installed, so if you don't activate it, you might
not be able to use psycopg2, but as you surmise, the database itself
is elsewhere on the system.


To get pgAdmin3 to work, I  have to have it set so that it logs in as gary (
no choice with this) and set group to root. Then in application > advanced
options set run as different user to root. This assumes that you are using a
KDE4 desktop and have these option by right clicking the icons.

pgAdmin3 data:
 Server Group > Server(1) > archivedb
 |_ Host name - 127.0.0.1
 |_ username - archive
 |_ connected - no
Archivedb requires a password to go deeper and takes the xx password
that is in the django settings.py file. This opens up access to archivedb
and lists archivedb > Schema(1) > public > tables(10). At this point I found
that all  of the sequences and all of the tables are owned by root. This is
probably the root (no pun intended) cause. Now what do I do about it. I'm
not sure how this came about so don't know how to fix it.

Ah, all owned by root. Okay! I've never actually tried this, but you
might be able to directly reassign a bunch of things:

http://www.postgresql.org/docs/9.4/static/sql-reassign-owned.html

Make sure you have a backup. Reassigning root in this way is quite
possibly a bad idea.

If there aren't too many tables, you could use ALTER TABLE:

http://www.postgresql.org/docs/9.4/static/sql-altertable.html

ALTER TABLE tablename OWNER TO archives;

But in theory, you shouldn't need to worry about owners at all - just
make sure permissions are all assigned. Which you have done. So it's
entirely possible none of this will change anything. :(

Worst case, you may need to do an SQL dump of the entire database,
then check the export, make sure ownership is correct, and reimport
into a brand new database. Tedious, but it's certain to fix the
problem.

ChrisA

pgAdmin3 showed two potential problems.

The first connection listed in pg_hba.conf was: local  all postgres   
radius. I removed this line so that the first line would be: local   
all  all  trust. Since all connections will be handled through Django? 
there should not be a problem with keeping loose security at this point.


The second problem was that all fo the sequence and table files in 
archivedb showed the owner to be root. I changed them all to archive - 
the user listed in Django's settings.py file.


Python manage.py migrate now works with no errors.

Thank you for your help. I found an O'Reilly book - PosgreSQL Up & 
Running, 2nd Edition, by Regina Obe and Leo Hsu that is very good. If I 
had read the book first, I would have avoided some of these problems. 
One of the things that I have found very frustrating is that most of the 
documentation is too compartmentalized. If an author is writing about 
Django they get sloppy with the database setup and visa versa. It now 
seems to me that:
 Postgresql should be set up first, the setup being completely 
disconnected from the Python / Django project
All communication with the database will pass through Django with 
the exception of admin maintenance.


Please correct me if I'm wrong.

Gary R.

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


Re: Matplotlib X-axis timezone trouble [SOLVED]

2015-07-04 Thread Peter Pearson
On Sat, 04 Jul 2015 07:29:45 +0300, Akira Li <4kir4...@gmail.com> wrote:
> Peter Pearson  writes:
>
>> The following code produces a plot with a line running from (9:30, 0) to
>> (10:30, 1), not from (8:30, 0) to (9:30, 1) as I desire.
>>
>> If I use timezone None instead of pacific, the plot is as desired, but
>> of course that doesn't solve the general problem of which this is a
>> much-reduced example.
>>
>> If I use timezone US/Central, I get the same (bad) plot.
>>
>> import matplotlib.pyplot as plt
>> import datetime
>> import pytz
>> pacific = pytz.timezone("US/Pacific")
>> fig = plt.figure()
>> plt.plot([datetime.datetime(2014, 10, 7, 8, 30, tzinfo=pacific),
>>   datetime.datetime(2014, 10, 7, 9, 30, tzinfo=pacific)],
>>  [0,1], marker="o", color="green")
>> fig.autofmt_xdate()
>> plt.show()
>>
>> Does anybody know why this shift is occurring?  Is Matplotlib
>> confused about what timezone to use in labeling the axis?  How
>> would I tell it what timezone to use (preferably explicitly in
>> the code, not in matplotlibrc)?
>>
>
> Your pytz usage is incorrect.
>
> Don't pass a pytz tzinfo object to the datetime construtor directly, use
> `.localize()` method instead. Read the note at the very beginning of
> pytz docs http://pytz.sourceforge.net/

Exactly.  Thank you.

For newcomers, the denouement of this thread is this:

 * Matplotlib had nothing to do with this problem, it was correctly
   displaying bad datetime.datetime values.

 * Python's datetime.datetime(..., tzinfo=timezone) is unreliable if
   timezone has daylight-saving time.

 * pytz's creators provide the localize() method specifically to
   remedy this problem.  If you want to create a datetime object
   that has a timezone that might have daylight-saving time,
   use localize().

-- 
To email me, substitute nowhere->runbox, invalid->com.
-- 
https://mail.python.org/mailman/listinfo/python-list


[Solved] Python.exe has stopped working

2015-06-19 Thread Alexis Dubois
Le samedi 6 juin 2015 13:40:13 UTC+2, Laura Creighton a écrit :
> In a message of Fri, 05 Jun 2015 11:15:31 +0200, Christian Gollwitzer writes:
> >Am 05.06.15 um 11:03 schrieb Alexis Dubois:
> >> Anyone else for an idea on that?
> >>
> >Well, it is a crash on exit. Looks like a memory error inside of PyQT. 
> >If you've got the time, you could run it inside of a debugger, or 
> >better, a memory checker like AppVerifier to find the culprit. These 
> >things are usually quite hard to diagnose, and unless someone has seen 
> >it here already, the fun starts now ;) Another possible reason might be 
> >mixing up DLLs from PyQT and another QT installation. You can find out 
> >by listing all loaded DLLs when the program is running, e.g. from a 
> >debugger or this tool: 
> >https://technet.microsoft.com/sysinternals/bb896653.aspx
> >
> > Christian
> >-- 
> >https://mail.python.org/mailman/listinfo/python-list
> 
> I don't have a windows machine, so I cannot do any more looking for this,
> but this may be relevant.
> http://stackoverflow.com/questions/20102419/pyqt-5-error-on-exit
> 
> Laura

Hello Everybody,
Thank you for your support and sorry for the late answer, I'm back from 
holidays.
I tried each solution but unfortunately, nothing works.
Finally, I solved my issue by adding "sip.setdestroyonexit(False)" just before 
"sys.exit(app.exec_())"
I don't really know what it does but it works well and I don't see any beside 
effect.
It seems that my issue was linked with a QtGui4.dll crash.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Problem with Android Build [SOLVED]

2014-10-22 Thread Cyd Haselton
On Tue, Oct 21, 2014 at 1:57 PM, Chris Angelico  wrote:

> On Wed, Oct 22, 2014 at 5:53 AM, Cyd Haselton  wrote:
> > I forgot to add...I also removed and/or commented out lines referencing
> > Modules/pwdmodule.o.
>
> Sounds like the normal sort of work involved in porting to a new
> platform. I've done a few of those kinds of jobs - ported Pike to
> OS/2, and to MinGW (there is an official Pike for Windows, but I
> wanted to use MinGW rather than MSVC), and there's a lot of fiddling
> around to be done!
>
> ChrisA
>

This problem is fixed. I'd previously removed Makefile commands to build
posixmodule.o because of an undeclared reference to I_PUSH.  After picking
through the source and history, I added them back in and instead added an
#ifndef __ANDROID__ around the function that used I_PUSH.

Ran a make clean...then make, and the newly built python was able to find
sysconfig and build pybuilddir.txt

Running into a different error, which I will post separate from this one.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: pyserial on freebsd 10.10 i386 [SOLVED]

2014-10-19 Thread Mark Lawrence

On 19/10/2014 16:06, Grant Edwards wrote:

On 2014-10-18, Nagy L?szl? Zsolt  wrote:


Strangely, pyserial will accept the number 0, but then it tries to open
a device that exists on Linux only...


I'm sure Chris would be happy to accept a patch fixing that problem.



Sadly to some people a patch is a thing that mends your flat tyre or 
goes over your eye.


--
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence

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


Re: pyserial on freebsd 10.10 i386 [SOLVED]

2014-10-19 Thread Grant Edwards
On 2014-10-18, Nagy L?szl? Zsolt  wrote:

> Strangely, pyserial will accept the number 0, but then it tries to open 
> a device that exists on Linux only...

I'm sure Chris would be happy to accept a patch fixing that problem.

-- 
Grant


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


Re: pyserial on freebsd 10.10 i386 [SOLVED]

2014-10-18 Thread Nagy László Zsolt
The port parameter of serial.Serial should be /dev/ttyu0 instead of 
COM1, and /dev/ttyu1 instead of COM2.


Strangely, pyserial will accept the number 0, but then it tries to open 
a device that exists on Linux only...


Anyway, problem solved.
--
https://mail.python.org/mailman/listinfo/python-list


Re: win32serviceutil: ImportError: DLL load failed: The specified module could not be found [SOLVED]

2014-05-26 Thread Nagy László Zsolt



Python 3.4 does not run any bdist_wininst postinstall scripts. Try to run 
`C:\Python34\python.exe C:\Python34\Scripts\pywin32_postinstall.py -install` 
manually from an elevated command prompt.

Christoph
C:\>C:\Python34\python.exe C:\Python34\Scripts\pywin32_postinstall.py 
-install

Copied pythoncom34.dll to C:\Python34\pythoncom34.dll
Copied pywintypes34.dll to C:\Python34\pywintypes34.dll
You do not have the permissions to install COM objects.
The sample COM objects were not registered.
-> Software\Python\PythonCore\3.4\Help[None]=None
-> Software\Python\PythonCore\3.4\Help\Pythonwin 
Reference[None]='C:\\Python34\\

Lib\\site-packages\\PyWin32.chm'
Pythonwin has been registered in context menu
Creating directory C:\Python34\Lib\site-packages\win32com\gen_py
Can't install shortcuts - 
'C:\\Users\\Laci\\AppData\\Roaming\\Microsoft\\Windows

\\Start Menu\\Programs\\Python 3.4' is not a folder
The pywin32 extensions were successfully installed.

C:\>python
Python 3.4.1 (v3.4.1:c0e311e010fc, May 18 2014, 10:45:13) [MSC v.1600 64 
bit (AM

D64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import win32service
>>>

Thanks!

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


Re: Strange syntax error, occurs only when script is executed directly [solved]

2014-04-22 Thread Andrew Cooper
On 22/04/2q014 13:26, Chris Angelico wrote:
> On Tue, Apr 22, 2014 at 10:21 PM, Antoon Pardon
>  wrote:
>> Yes that was it. I changed the first line of my script to:
>>
>> #!/opt/local/bin/python2.7
>>
>> and it now works.
> 
> Excellent! Shebangs are *extremely* specific, so you may want to
> consider using "/usr/bin/env python" to get a bit more flexibility.
> (Or "python2" or "python2.7" in place of "python", depending on how
> specific you want to be.)
> 
> ChrisA
> 

`man execve`

"The interpreter must be a valid pathname for an executable which is not
itself a script."

This is (presumably) to avoid recursive walks of the filesystem trying
to locate a valid interpreter to splat over the virtual address space of
the currently executing process.

~Andrew
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Strange syntax error, occurs only when script is executed directly [solved]

2014-04-22 Thread Andrew Cooper
On 22/04/2q014 13:26, Chris Angelico wrote:
> On Tue, Apr 22, 2014 at 10:21 PM, Antoon Pardon
>  wrote:
>> Yes that was it. I changed the first line of my script to:
>>
>> #!/opt/local/bin/python2.7
>>
>> and it now works.
> 
> Excellent! Shebangs are *extremely* specific, so you may want to
> consider using "/usr/bin/env python" to get a bit more flexibility.
> (Or "python2" or "python2.7" in place of "python", depending on how
> specific you want to be.)
> 
> ChrisA
> 

`man execve`

"The interpreter must be a valid pathname for an executable which is not
itself a script."

This is (presumably) to avoid recursive walks of the filesystem trying
to locate a valid interpreter to splat over the virtual address space of
the currently executing process.

~Andrew
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Strange syntax error, occurs only when script is executed directly [solved]

2014-04-22 Thread Chris Angelico
On Tue, Apr 22, 2014 at 11:01 PM, Antoon Pardon
 wrote:
> On 22-04-14 14:26, Chris Angelico wrote:
>
>> On Tue, Apr 22, 2014 at 10:21 PM, Antoon Pardon
>>  wrote:
>>> Yes that was it. I changed the first line of my script to:
>>>
>>> #!/opt/local/bin/python2.7
>>>
>>> and it now works.
>> Excellent! Shebangs are *extremely* specific, so you may want to
>> consider using "/usr/bin/env python" to get a bit more flexibility.
>
> The problem with that is that it doesn't work if python is not on
> the (standard) path, like in this case.

Ah! Well, that's why I said "consider using" rather than "you should use" :)

ChrisA
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Strange syntax error, occurs only when script is executed directly [solved]

2014-04-22 Thread Antoon Pardon
On 22-04-14 14:26, Chris Angelico wrote:

> On Tue, Apr 22, 2014 at 10:21 PM, Antoon Pardon
>  wrote:
>> Yes that was it. I changed the first line of my script to:
>>
>> #!/opt/local/bin/python2.7
>>
>> and it now works.
> Excellent! Shebangs are *extremely* specific, so you may want to
> consider using "/usr/bin/env python" to get a bit more flexibility.

The problem with that is that it doesn't work if python is not on
the (standard) path, like in this case.

-- 
Antoon Pardon


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


Re: Strange syntax error, occurs only when script is executed directly [solved]

2014-04-22 Thread Chris Angelico
On Tue, Apr 22, 2014 at 10:21 PM, Antoon Pardon
 wrote:
> Yes that was it. I changed the first line of my script to:
>
> #!/opt/local/bin/python2.7
>
> and it now works.

Excellent! Shebangs are *extremely* specific, so you may want to
consider using "/usr/bin/env python" to get a bit more flexibility.
(Or "python2" or "python2.7" in place of "python", depending on how
specific you want to be.)

ChrisA
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Strange syntax error, occurs only when script is executed directly [solved]

2014-04-22 Thread Antoon Pardon
On 22-04-14 14:09, Chris Angelico wrote:
> On Tue, Apr 22, 2014 at 8:29 PM, Antoon Pardon
>  wrote:
>> However if I call the script directly and want the #! line do its work I get 
>> the following error.
>>
>> # /usr/local/bin/ldapwatch /opt/local/log/openldap.log | head
>> /usr/local/bin/ldapwatch: line 3: syntax error near unexpected token `('
>> /usr/local/bin/ldapwatch: line 3: `class vslice(object):'
> That looks like bash trying to run Python code, so I'd look at
> something being wrong with the shebang processing. What's
> /opt/local/bin/python? Is it a symlink to something else? Some systems
> won't allow any such dereferencing, others (including modern Linux)
> allow a maximum of ten or thereabouts, counting one for every symlink
> or shebang'd script. If /opt/local/bin/python is a bouncer script that
> itself has a shebang, that might be your problem.
>
> ChrisA

Yes that was it. I changed the first line of my script to:

#!/opt/local/bin/python2.7

and it now works.

Thanks.
-- 
Antoon Pardon
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Problem using py-bt, py-locals, etc. during GDB debugging [solved]

2014-03-09 Thread Terry Reedy

On 3/9/2014 10:46 AM, Wesley wrote:

I hit a problem alike yours.
Cannot fix according your method.

Here is snippet:
root@localhost python]# gdb python 40290
GNU gdb (GDB) 7.7



Copyright (C) 2014 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later 
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.  Type "show copying"
and "show warranty" for details.
This GDB was configured as "x86_64-unknown-linux-gnu".
Type "show configuration" for configuration details.
For bug reporting instructions, please see:
.
Find the GDB manual and other documentation resources online at:
.
For help, type "help".
Type "apropos word" to search for commands related to "word"...
Reading symbols from python...done.
Attaching to program: /usr/local/bin/python, process 40290
Reading symbols from /lib64/ld-linux-x86-64.so.2...(no debugging symbols 
found)...done.
Loaded symbols for /lib64/ld-linux-x86-64.so.2
0x0030a98e15c3 in ?? ()


If you want people to attend to your posts and help, don't post line 
after line of irrelevant boilderplate.



(gdb) py-bt
(gdb) py-list
Unable to locate python frame
(gdb) py-locals
Unable to locate python frame
(gdb)

I use gdb 7.7, python 2.6.6 , centos 6.5 64bit
Any suggestion?


See above.

--
Terry Jan Reedy

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


Re: Problem using py-bt, py-locals, etc. during GDB debugging [solved]

2014-03-09 Thread Wesley
I hit a problem alike yours.
Cannot fix according your method.

Here is snippet:
root@localhost python]# gdb python 40290
GNU gdb (GDB) 7.7
Copyright (C) 2014 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later 
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.  Type "show copying"
and "show warranty" for details.
This GDB was configured as "x86_64-unknown-linux-gnu".
Type "show configuration" for configuration details.
For bug reporting instructions, please see:
.
Find the GDB manual and other documentation resources online at:
.
For help, type "help".
Type "apropos word" to search for commands related to "word"...
Reading symbols from python...done.
Attaching to program: /usr/local/bin/python, process 40290
Reading symbols from /lib64/ld-linux-x86-64.so.2...(no debugging symbols 
found)...done.
Loaded symbols for /lib64/ld-linux-x86-64.so.2
0x0030a98e15c3 in ?? ()
(gdb) py-bt
(gdb) py-list
Unable to locate python frame
(gdb) py-locals
Unable to locate python frame
(gdb) 

I use gdb 7.7, python 2.6.6 , centos 6.5 64bit
Any suggestion?

Thanks.
Wesley
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: random.sample with large weighted sample-sets? [SOLVED]

2014-02-16 Thread Tim Chase
On 2014-02-16 14:47, Terry Reedy wrote:
> > 2) the data has to be sorted for bisect to work  
> 
> cumulative sums are automatically sorted.

Ah, that they were *cumulative* was the key that I missed in my
understanding.  It makes sense now and works like a charm.

Thanks to all who offered a hand in this thread.

-tkc



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


Re: [Solved]Re: Help with TypeError: Can't convert 'list' object to str implicitly

2014-02-05 Thread Chris Angelico
On Thu, Feb 6, 2014 at 5:08 PM, Dave Angel  wrote:
> print('The secretWord is ' + secretWord
> print('The secretKey is ' + key

))

http://xkcd.com/859/

ChrisA
-- 
https://mail.python.org/mailman/listinfo/python-list


Re:[Solved]Re: Help with TypeError: Can't convert 'list' object to str implicitly

2014-02-05 Thread Dave Angel
 dave em  Wrote in message:
>
> 
> Fixed the error and am now onto the next issue.
> 
> Solution was to return a list (I think) and then break out the components of 
> the list and put in the variable.  Here is how we did it:
> 
> secretWord = getRandomWord(words)
> print('The secretWord is ' + str(secretWord[0]))
> print('The secretKey is ' + str(secretWord[1]))
> #Change secretWord from a list to a str
> secretWord = secretWord[1] 
> 
> 
> def getRandomWord(wordDict):
> # This function returns a random string from the passed dictionary of 
> lists of strings, and the key also.
> # First, randomly select a key from the dictionary:
> wordKey = random.choice(list(wordDict.keys()))
> print('The wordKey is ' + wordKey)
> # Second, randomly select a word from the key's list in the dictionary:
> wordIndex = random.randint(0, len(wordDict[wordKey]) - 1)
> print('The wordIndex is ' + str(wordIndex))
> print('The word is ' + wordDict[wordKey][wordIndex])
> return [wordDict[wordKey][wordIndex], wordKey]
> 

Much better is to change the name of the function to match what
 it's really doing.  But I'll leave that to you.

Make the return logic look like:

 word = [wordDict[wordKey][wordIndex]
 return word, wordKey

Then the calling logic should be:

secretWord,  key = getRandomSomethings (words)
print('The secretWord is ' + secretWord
print('The secretKey is ' + key


This way a name is not used for contradictory purposes.

-- 
DaveA

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


[Solved]Re: Help with TypeError: Can't convert 'list' object to str implicitly

2014-02-05 Thread dave em
On Wednesday, February 5, 2014 7:21:29 PM UTC-7, dave em wrote:
> Hello,
> 
> 
> 
> Background.  My 11 y/o son and I have taken on the task to learn python and 
> work our way through the http://inventwithpython.com/chapters/ book.
> 
> -  We are currently on Chapter 9 and trying to modify the hangman program.
> 
> 
> 
> - the first challenge was to modify the word list into a dictionary.  So we 
> changed our words variable into a dictionary
> 
> --  I believe we did this correctly.
> 
> 
> 
> -  But we somehow broke the game.  All of the words are only two letters and 
> the program crashes on exit with the following error.
> 
> 
> 
>  Traceback (most recent call last):
> 
>   File "/media/.../Python/hangman.py", line 155, in 
> 
> print('You have run out of guesses! \n After ' + str(len(missedLetters)) 
> + ' missed guesses and ' + str(len(correctLetters)) + ' correct guesses, the 
> word was "' + secretWord + '"')
> 
> TypeError: Can't convert 'list' object to str implicitly
> 
> 
> 
> -I can't see why this wouldn't work.  By definition isn't this the cast:
> 
> 
> 
> 1)  len(correctLetters) //returns the lengths of the variable as an int
> 
> 2)  str(len(correctLetters)) // converts the integer into a string.
> 
> 
> 
> Applicable code is here:
> 
>  # Check if player has guessed too many times and lost
> 
> if len(missedLetters) == len(HANGMANPICS) - 1:
> 
> displayBoard(HANGMANPICS, missedLetters, correctLetters, 
> secretWord)
> 
> print('You have run out of guesses! \n After ' + 
> str(len(missedLetters)) + ' missed guesses and ' + str(len(correctLetters)) + 
> ' correct guesses, the word was "' + secretWord + '"')
> 
> gameIsDone = True
> 
> 
> 
> Any help to get us past this error message is most appreciated.
> 
> 
> 
> Thanks in advance,
> 
> Dave

Fixed the error and am now onto the next issue.

Solution was to return a list (I think) and then break out the components of 
the list and put in the variable.  Here is how we did it:

secretWord = getRandomWord(words)
print('The secretWord is ' + str(secretWord[0]))
print('The secretKey is ' + str(secretWord[1]))
#Change secretWord from a list to a str
secretWord = secretWord[1] 


def getRandomWord(wordDict):
# This function returns a random string from the passed dictionary of lists 
of strings, and the key also.
# First, randomly select a key from the dictionary:
wordKey = random.choice(list(wordDict.keys()))
print('The wordKey is ' + wordKey)
# Second, randomly select a word from the key's list in the dictionary:
wordIndex = random.randint(0, len(wordDict[wordKey]) - 1)
print('The wordIndex is ' + str(wordIndex))
print('The word is ' + wordDict[wordKey][wordIndex])
return [wordDict[wordKey][wordIndex], wordKey]

Cheers,
Dave
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: unicode troubles and postgres [SOLVED]

2014-01-09 Thread Chris Angelico
On Fri, Jan 10, 2014 at 6:51 AM, Ethan Furman  wrote:
> The problem was I had created the database from template0 instead of
> template1, and 0 is SQL-ASCII while 1 is UTF8.

Ah, this is one of the traps with Postgres. This is one of the reasons
I prefer not to touch template[01] and to script the initialization of
a new database - any config changes are committed to source control as
part of that script.

ChrisA
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: unicode troubles and postgres [SOLVED]

2014-01-09 Thread Ethan Furman

On 01/09/2014 10:49 AM, Ethan Furman wrote:

So I'm working with postgres, and I get a datadump which I try to restore to my 
test system, and I get this:

ERROR:  value too long for type character varying(4)
CONTEXT:  COPY res_currency, line 32, column symbol: "руб"

"py6" sure looks like it should fit, but it don't.  Further investigation revealed that 
"py6" is made up of the bytes d1
80 d1 83 d0 b1.

Any ideas on what that means, exactly?


For the curious, it means CYRILLIC SMALL LETTER ER, CYRILLIC SMALL LETTER U, CYRILLIC CAPITAL LETTER IE WITH GRAVE in 
utf-8 format.


The problem was I had created the database from template0 instead of template1, 
and 0 is SQL-ASCII while 1 is UTF8.

--
~Ethan~
--
https://mail.python.org/mailman/listinfo/python-list


Re: Beginner python 3 unicode question [SOLVED]

2013-11-16 Thread Chris Angelico
On Sun, Nov 17, 2013 at 8:44 AM, Laszlo Nagy  wrote:
>
>>
>> So is the default utf-8 or not? Should the documentation be updated? Or do
>> we have a bug in the interactive shell?
>>
> It was my fault, sorry. The other program used os.system at some places, and
> it accidentally used python2 instead of python 3. :-(

Oh! Didn't see this post before responding. Oh well. Maybe someone
else one day will make use of the other. :)

ChrisA
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Beginner python 3 unicode question [SOLVED]

2013-11-16 Thread Laszlo Nagy




So is the default utf-8 or not? Should the documentation be updated? 
Or do we have a bug in the interactive shell?


It was my fault, sorry. The other program used os.system at some places, 
and it accidentally used python2 instead of python 3. :-(


--
This message has been scanned for viruses and
dangerous content by MailScanner, and is
believed to be clean.

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


[solved]Re: Python PDB conditional breakpoint

2013-11-06 Thread Tom P

On 06.11.2013 16:14, Tom P wrote:

ok I figured it. ID is a tuple, not a simple variable.
 The correct test is ID[0]==11005



I can't get conditional breakpoints to work. I have a variable ID and I
want to set a breakpoint which runs until ID==11005.

Here's what happens -



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


Re: sorting german characters äöü... solved

2013-10-30 Thread Ulrich Goebel

Hi,

Am 30.10.2013 19:48, schrieb Skip Montanaro:

Perhaps this? 
http://stackoverflow.com/questions/816285/where-is-pythons-best-ascii-for-this-unicode-database


There I found the module unidecode
(http://pypi.python.org/pypi/Unidecode),
and I found it very helpful. Thanks a lot!

So my function normal() now looks like this:

from unidecode import unidecode

def normal (s):
  r = s
  r = r.strip()  # take away blanks at the ends
  r = r.replace(u' ', '')# take away all other blanks
  r = unidecode(r)   # makes the main work
 # - see the docu of unidecode
  r = r.upper()  # changes all to uppercase letters
  return r

def compare (a, b):
  aa = normal(a)
  bb = normal(b)
  if aa < bb:
return -1
  elif aa == bb:
return 0
  else:
return 1

For the "normal" cases, that works quiet perfect - as I want it to do. 
For more (extreme) difficult cases there are even limits, but they are 
even wide limits, I would say. For example,

  print normal(u'-£-¥-Ć-û-á-€-Đ-ø-ț-ff-ỗ-Ể-ễ-ḯ-ę-ä-ö-ü-ß-')
gives
  -PS-Y=-C-U-A-EU-D-O-T-FF-O-E-E-I-E-A-O-U-SS-
That shows a bit of what unidecode does - and what it doesn't.


There is also a rather long-ish recent topic on a similar topic that
might be worth scanning as well.


Sorry, I didn't find that.


I've no direct/recent experience with this topic. I'm just an
interested bystander.


But even a helpful bystander. Thank You!

Ulrich

--
Ulrich Goebel
Paracelsusstr. 120, 53177 Bonn
--
https://mail.python.org/mailman/listinfo/python-list


Re: UnicodeEncodeError: SOLVED

2013-10-10 Thread Walter Hurry
On Thu, 10 Oct 2013 01:47:52 +, Steven D'Aprano wrote:

> On Wed, 09 Oct 2013 14:41:53 +, Walter Hurry wrote:
> 
>> Many thanks to those prepared to forgive my transgression in the
>> 'Goodbye' thread. I mentioned there that I was puzzled by a
>> UnicodeEncodeError, and said I would rise it as a separate thread.
>> 
>> However, via this link, I was able to resolve the issue myself:
>> 
>> http://stackoverflow.com/questions/3224268/python-unicode-encode-error
> 
> I don't know what problem you had, and what your solution was, but the
> above link doesn't solve the problem, it just throws away data until the
> problem no longer appears, and never mind if it changes the semantics of
> the XML data.
> 
> Instead of throwing away data, the right solution is likely to be, stop
> trying to deal with XML yourself, and use a proper UTF-8 compliant XML
> library.
> 
> Or if you can't do that, at least open and read the XML file using UTF-8
> in the first place. In Python 3, you can pass a codec to open. In Python
> 2, you can use codecs.open instead of the built-in open.

All true, but in *this* case, simply discarding the offending character 
was sufficient. Thanks anyway.

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


Re: UnicodeEncodeError: SOLVED

2013-10-09 Thread Steven D'Aprano
On Wed, 09 Oct 2013 14:41:53 +, Walter Hurry wrote:

> Many thanks to those prepared to forgive my transgression in the
> 'Goodbye' thread. I mentioned there that I was puzzled by a
> UnicodeEncodeError, and said I would rise it as a separate thread.
> 
> However, via this link, I was able to resolve the issue myself:
> 
> http://stackoverflow.com/questions/3224268/python-unicode-encode-error

I don't know what problem you had, and what your solution was, but the 
above link doesn't solve the problem, it just throws away data until the 
problem no longer appears, and never mind if it changes the semantics of 
the XML data.

Instead of throwing away data, the right solution is likely to be, stop 
trying to deal with XML yourself, and use a proper UTF-8 compliant XML 
library.

Or if you can't do that, at least open and read the XML file using UTF-8 
in the first place. In Python 3, you can pass a codec to open. In Python 
2, you can use codecs.open instead of the built-in open.


-- 
Steven
-- 
https://mail.python.org/mailman/listinfo/python-list


UnicodeEncodeError: SOLVED

2013-10-09 Thread Walter Hurry
Many thanks to those prepared to forgive my transgression in the 
'Goodbye' thread. I mentioned there that I was puzzled by a 
UnicodeEncodeError, and said I would rise it as a separate thread.

However, via this link, I was able to resolve the issue myself:

http://stackoverflow.com/questions/3224268/python-unicode-encode-error

Nevertheless, thanks again for the kind words.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: django admin.py error (solved)

2013-09-19 Thread Gary Roach

On 09/19/2013 11:56 AM, John Gordon wrote:

In  Gary Roach 
 writes:


On 09/19/2013 11:15 AM, John Gordon wrote:

Does /home/gary/ProgramFiles/mysite/mysite/models.py define an object
named 'membership'?

Yes. The following is the top part of the models.py file: q
 class Membership(models.Model):
  id_membership = models.IntegerField(unique=True, primary_key=True)

I see something named 'Membership', but nothing named 'membership'.
Python names are case-sensitive.

Stupid stupid stupid. Thanks. You would think that after working with 
Linux for over 10 years that I wouldn't pull such a stunt. Thanks. 
Everything now working fine.


Gary R
--
https://mail.python.org/mailman/listinfo/python-list


Re: How can I remove the first line of a multi-line string? (SOLVED)

2013-09-11 Thread Roy Smith
In article ,
 Fábio Santos  wrote:

One suggested solution:
> > > > sansfirstline = '\n'.join(fullstring.split('\n')[1:])

To which I suggested a couple of alternatives:
> > i = s.index('\n')
> > print s[i+1:]
> > [...]
> > print re.sub(r'^[^\n]*\n', '', s)


> > I'll admit, the split/slice/join solution is probably the easiest to
> > implement (and to understand when you're reading the code).  But, it
> > copies all the data twice; once when split() runs, and again when join()
> > runs.  Both the index and regex solutions should only do a single copy.
> > For huge strings, this might matter.  For a three-liner as in your
> > example, it doesn't make any difference.
> >
> 
> Is there not a limit argument to str.split? This should be trivial.
> 
> first, rest = multiline_str.split('\n', 1)

This certainly prevents the extra splitting and re-compositing of the 
additional lines.

One thing to watch out for is that split(s, 1) does *at most* 1 split.  
If the original string didn't have any newlines, you would end up with a 
single-item list and the unpack would fail.  You can get around that 
with:

rest = multiline_str.split('\n', 1)[-1]

but that's kind of cryptic.

Looking back at my solutions suggested above, s.index() fails in the 
same situation (throws ValueError).  The regex solution works fine, once 
again proving that 1970's technology is still superior to all this 
newfangled stuff.

A coworker recently introduced me to what is apparently a classic essay 
(http://www.team.net/mjb/hawg.html).  If Unix is the Hole Hawg of 
operating systems, then regexes are the Hole Hawg of string processing 
tools.  Those of us who grew up around them, appreciate their power and 
have learned how to use them without chopping off any fingers.  And we 
look on with a mix of amusement and pity at the current crop of 
programmers who play with index(), split(), startswith(), rpartition(), 
etc and think they're using real tools :-)

For the record, I have never used a Hole Hawg.  I do, however, own a 
Milwaukee 1/2" drill.  Which also comes with the screw-in handle for 
two-handed operation.  I've had that get away from me a couple of times, 
so I figure it's about my limit.  Torque is a wonderful thing until the 
thing you're drilling into weighs more than you do.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How can I remove the first line of a multi-line string? (SOLVED)

2013-09-11 Thread Terry Reedy

On 9/11/2013 8:08 AM, Fábio Santos wrote:


Is there not a limit argument to str.split? This should be trivial.


Yes, I posted an example using it the first day.

I also showed how to use iter and next with files and avoid copying.


first, rest = multiline_str.split('\n', 1)


This does not work right is there is no '\n'

Then someone pointed out
first, dummy, rest = partition('\n')
which does work with no '\n'

--
Terry Jan Reedy


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


Re: How can I remove the first line of a multi-line string? (SOLVED)

2013-09-11 Thread Fábio Santos
On 2 Sep 2013 18:13, "Roy Smith"  wrote:
>
> In article ,
>  Anthony Papillion  wrote:
>
> > On 09/02/2013 11:12 AM, Chris “Kwpolska” Warrick wrote:
> > > On Mon, Sep 2, 2013 at 6:06 PM, Anthony Papillion 
> > > wrote:
> > >> Hello Everyone,
> > >>
> > >> I have a multi-line string and I need to remove the very first line
from
> > >> it. How can I do that? I looked at StringIO but I can't seem to
figure
> > >> out how to properly use it to remove the first line. Basically, I
want
> > >> to toss the first line but keep everything else.  Can anyone put me
on
> > >> the right path? I know it is probably easy but I'm still learning
Python
> > >> and don't have all the string functions down yet.
> > >>
> > >> Thanks,
> > >> Anthony
> > >> --
> > >> http://mail.python.org/mailman/listinfo/python-list
> > >
> > > Use split() and join() methods of strings, along with slicing.  Like
this:
> > >
> > > fullstring = """foo
> > > bar
> > > baz"""
> > >
> > > sansfirstline = '\n'.join(fullstring.split('\n')[1:])
> > >
> > > The last line does this:
> > > 1. fullstring.split('\n') turns it into a list of ['foo', 'bar',
'baz']
> > > 2. the [1:] slice removes the first element, making it ['bar', 'baz']
> > > 3. Finally, '\n'.join() turns the list into a string separated by
> > > newlines ("""bar
> > > baz""")
> >
> > This, of course, worked like a charm. I really need to study the string
> > methods. In the work I'm doing they are going to come in very handy.
> > Thank you, Chris!
>
> Let me toss out a couple of other possibilities.  Not necessarily
> better, but if you're learning about strings, you might as well learn
> some other ways to do it:
>
>
> s = """foo
>
> bar
>
> baz"""
>
> print "using index..."
> i = s.index('\n')
> print s[i+1:]
>
> print "using regex..."
> import re
> print re.sub(r'^[^\n]*\n', '', s)
>
>
> I'll admit, the split/slice/join solution is probably the easiest to
> implement (and to understand when you're reading the code).  But, it
> copies all the data twice; once when split() runs, and again when join()
> runs.  Both the index and regex solutions should only do a single copy.
> For huge strings, this might matter.  For a three-liner as in your
> example, it doesn't make any difference.
>

Is there not a limit argument to str.split? This should be trivial.

first, rest = multiline_str.split('\n', 1)
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How can I remove the first line of a multi-line string? (SOLVED)

2013-09-02 Thread Roy Smith
In article ,
 Anthony Papillion  wrote:

> On 09/02/2013 11:12 AM, Chris “Kwpolska” Warrick wrote:
> > On Mon, Sep 2, 2013 at 6:06 PM, Anthony Papillion  
> > wrote:
> >> Hello Everyone,
> >>
> >> I have a multi-line string and I need to remove the very first line from
> >> it. How can I do that? I looked at StringIO but I can't seem to figure
> >> out how to properly use it to remove the first line. Basically, I want
> >> to toss the first line but keep everything else.  Can anyone put me on
> >> the right path? I know it is probably easy but I'm still learning Python
> >> and don't have all the string functions down yet.
> >>
> >> Thanks,
> >> Anthony
> >> --
> >> http://mail.python.org/mailman/listinfo/python-list
> > 
> > Use split() and join() methods of strings, along with slicing.  Like this:
> > 
> > fullstring = """foo
> > bar
> > baz"""
> > 
> > sansfirstline = '\n'.join(fullstring.split('\n')[1:])
> > 
> > The last line does this:
> > 1. fullstring.split('\n') turns it into a list of ['foo', 'bar', 'baz']
> > 2. the [1:] slice removes the first element, making it ['bar', 'baz']
> > 3. Finally, '\n'.join() turns the list into a string separated by
> > newlines ("""bar
> > baz""")
> 
> This, of course, worked like a charm. I really need to study the string
> methods. In the work I'm doing they are going to come in very handy.
> Thank you, Chris!

Let me toss out a couple of other possibilities.  Not necessarily 
better, but if you're learning about strings, you might as well learn 
some other ways to do it:


s = """foo  

 
bar 
   
 
baz"""

print "using index..."
i = s.index('\n')
print s[i+1:]

print "using regex..."
import re
print re.sub(r'^[^\n]*\n', '', s)


I'll admit, the split/slice/join solution is probably the easiest to 
implement (and to understand when you're reading the code).  But, it 
copies all the data twice; once when split() runs, and again when join() 
runs.  Both the index and regex solutions should only do a single copy.  
For huge strings, this might matter.  For a three-liner as in your 
example, it doesn't make any difference.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How can I remove the first line of a multi-line string? (SOLVED)

2013-09-02 Thread Anthony Papillion
On 09/02/2013 11:12 AM, Chris “Kwpolska” Warrick wrote:
> On Mon, Sep 2, 2013 at 6:06 PM, Anthony Papillion  wrote:
>> Hello Everyone,
>>
>> I have a multi-line string and I need to remove the very first line from
>> it. How can I do that? I looked at StringIO but I can't seem to figure
>> out how to properly use it to remove the first line. Basically, I want
>> to toss the first line but keep everything else.  Can anyone put me on
>> the right path? I know it is probably easy but I'm still learning Python
>> and don't have all the string functions down yet.
>>
>> Thanks,
>> Anthony
>> --
>> http://mail.python.org/mailman/listinfo/python-list
> 
> Use split() and join() methods of strings, along with slicing.  Like this:
> 
> fullstring = """foo
> bar
> baz"""
> 
> sansfirstline = '\n'.join(fullstring.split('\n')[1:])
> 
> The last line does this:
> 1. fullstring.split('\n') turns it into a list of ['foo', 'bar', 'baz']
> 2. the [1:] slice removes the first element, making it ['bar', 'baz']
> 3. Finally, '\n'.join() turns the list into a string separated by
> newlines ("""bar
> baz""")

This, of course, worked like a charm. I really need to study the string
methods. In the work I'm doing they are going to come in very handy.
Thank you, Chris!

Anthony


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


Re: How do I process this using Python? (SOLVED)

2013-08-31 Thread Anthony Papillion
On 08/31/2013 07:32 PM, Chris Angelico wrote:
> On Sun, Sep 1, 2013 at 10:19 AM, Anthony Papillion  
> wrote:
>> On 08/31/2013 06:48 PM, Chris Angelico wrote:
>>> On Sun, Sep 1, 2013 at 9:44 AM, Anthony Papillion  
>>> wrote:
 I'm writing a processor for Bitmessage messages and I am needing to
 parse the following returned JSON string:

 {u'inboxMessages':
>>>
>>> Does the JSON string really have those u prefixes and apostrophes?
>>> That's not valid JSON. You may be able to use ast.literal_eval() on it
>>> - I was able to with the example data - but not a JSON parser. Can you
>>> sort out your transmission end?
>>>
>>> ChrisA
>>
>> I think I remembered what the 'u' prefix is. It indicates that the data
>> following is a unicode string. So could that be valid JSON data wrapped
>> up in unicode?
> 
> No; JSON already supports Unicode. What you may have is an incorrect
> JSON encoder that uses Python's repr() to shortcut its work - but it's
> wrong JSON.
> 
> But bitmessage seems to be written in Python. Can you simply access
> the objects it's giving you, rather than going via text strings?
> 
> ChrisA

Once I looked at the data in a better structured way and saw it in the
proper type it became clear. Here is my solution:

data = json.loads(api.getAllInboxMessages())
for message in data['inboxmessages']:
print message['fromAddress']

Yep, it was that simple. Thanks for the help guys! I appreciate how fast
everyone responded.

Anthony


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


Re: Simple I/O problem can't get solved

2013-06-22 Thread Peter Otten
Chris Angelico wrote:

> On Fri, Jun 21, 2013 at 7:15 PM, Peter Otten <__pete...@web.de> wrote:
>> Combining these modifications:
>>
>> for line in f:
>> word = line.strip()
>> if is_palindrome.is_palindrome(word):
>> print word
> 
> Minor quibble: I wouldn't use the name 'word' here, unless you're
> expecting the file to consist of one-word lines (such as DICTOT.DIC
> from old PMMail). For detecting phrase/sentence palindromes, I'd keep
> the name 'line'.

Somehow it didn't occur to me that you might test anything but words.
However, if you want to check sentences (as some unused code in the original 
post suggests) I think you should not strip off the newline and leave the 
necessary cleanup to the test function:

>>> def is_palindrome(s):
... t = "".join(c for c in s.casefold() if c.isalnum())
... return t == t[::-1]
... 
>>> is_palindrome("A man, a plan, a canal - Panama!\n")
True


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


Re: Simple I/O problem can't get solved

2013-06-22 Thread Chris Angelico
On Fri, Jun 21, 2013 at 7:15 PM, Peter Otten <__pete...@web.de> wrote:
> Combining these modifications:
>
> for line in f:
> word = line.strip()
> if is_palindrome.is_palindrome(word):
> print word

Minor quibble: I wouldn't use the name 'word' here, unless you're
expecting the file to consist of one-word lines (such as DICTOT.DIC
from old PMMail). For detecting phrase/sentence palindromes, I'd keep
the name 'line'.

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


Re: Simple I/O problem can't get solved

2013-06-21 Thread nickgan . sps
Τη Παρασκευή, 21 Ιουνίου 2013 12:15:59 μ.μ. UTC+3, ο χρήστης Peter Otten έγραψε:
> nickgan@windowslive.com wrote:
> 
> 
> 
> > I have recently started to solve my first Python problems but I came
> 
> > across to this:
> 
> > Write a version of a palindrome recogniser that accepts a file name from
> 
> > the user, reads each line, and prints the line to the screen if it is a
> 
> > palindrome.(by http://www.ling.gu.se/~lager/python_exercises.html)
> 
> > 
> 
> > I think I coded it correctly but still I get no output. I do not have any
> 
> > errors I just do not get any output.
> 
> > 
> 
> > This is the code:
> 
> 
> 
> > import is_palindrome
> 
> > 
> 
> > filename = raw_input('Enter a file: ') # A text file
> 
> > f = open(filename)
> 
> > while True:
> 
> > line = f.readline()
> 
> 
> 
> The line includes the trailing newline character which breaks the symmetry:
> 
> 
> 
> >>> "abba" == "abba"[::-1]
> 
> True
> 
> >>> "abba\n" == "abba\n"[::-1]
> 
> False
> 
> 
> 
> Use
> 
> 
> 
> word = line.strip()
> 
> 
> 
> to remove all leading and trailing whitespace.
> 
> 
> 
> > if len(line) == 0:
> 
> > break
> 
> > elif is_palindrome.is_palindrome(line): 
> 
> > print line,
> 
> > f.close()
> 
> 
> 
> Note that python allows you to iterate over the lines of a file with
> 
> 
> 
> for line in f:
> 
> ...
> 
> 
> 
> Combining these modifications:
> 
> 
> 
> for line in f:
> 
> word = line.strip()
> 
> if is_palindrome.is_palindrome(word):
> 
> print word

Thank you a lot it worked!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Simple I/O problem can't get solved

2013-06-21 Thread Jussi Piitulainen
nickgan@windowslive.com writes:

> I think I coded it correctly but still I get no output. I do not
> have any errors I just do not get any output.
> 
> This is the code:
> 
> ***
> import is_palindrome
> 
> filename = raw_input('Enter a file: ') # A text file
> f = open(filename)
> while True:
>   line = f.readline()
>   if len(line) == 0:
>   break
>   elif is_palindrome.is_palindrome(line): 
>   print line,
> f.close()

There's a newline at the end of each input line. Strip that. (It might
be another sequence that means end-of-line in your system. It can
still be stripped as trailing whitespace. Strings have a method for
stripping trailing whitespace.)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Simple I/O problem can't get solved

2013-06-21 Thread Peter Otten
nickgan@windowslive.com wrote:

> I have recently started to solve my first Python problems but I came
> across to this:
> Write a version of a palindrome recogniser that accepts a file name from
> the user, reads each line, and prints the line to the screen if it is a
> palindrome.(by http://www.ling.gu.se/~lager/python_exercises.html)
> 
> I think I coded it correctly but still I get no output. I do not have any
> errors I just do not get any output.
> 
> This is the code:

> import is_palindrome
> 
> filename = raw_input('Enter a file: ') # A text file
> f = open(filename)
> while True:
> line = f.readline()

The line includes the trailing newline character which breaks the symmetry:

>>> "abba" == "abba"[::-1]
True
>>> "abba\n" == "abba\n"[::-1]
False

Use

word = line.strip()

to remove all leading and trailing whitespace.

> if len(line) == 0:
> break
> elif is_palindrome.is_palindrome(line): 
> print line,
> f.close()

Note that python allows you to iterate over the lines of a file with

for line in f:
...

Combining these modifications:

for line in f:
word = line.strip()
if is_palindrome.is_palindrome(word):
print word

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


Simple I/O problem can't get solved

2013-06-21 Thread nickgan . sps
Greetings to everybody,

I have recently started to solve my first Python problems but I came across to 
this:
Write a version of a palindrome recogniser that accepts a file name from the 
user, reads each line, and prints the line to the screen if it is a 
palindrome.(by http://www.ling.gu.se/~lager/python_exercises.html)

I think I coded it correctly but still I get no output. I do not have any 
errors I just do not get any output.

This is the code:

***
import is_palindrome

filename = raw_input('Enter a file: ') # A text file
f = open(filename)
while True:
line = f.readline()
if len(line) == 0:
break
elif is_palindrome.is_palindrome(line): 
print line,
f.close()
***

I have coded the is_palindrome module before and it works very well.
Here is this module's code:

***
def reverse(text):
return text[::-1]

def replace_all(text, dic):
for i, j in dic.iteritems():
text = text.replace(i, j)
return text

def is_palindrome(text):
return text == reverse(text)

points = {'.':'', ',':'', '!':'', ';':'', '?':'', '/':'', '\\':''}

something = raw_input('Enter text: ').lower().replace(' ', '')
replace = replace_all(something, points)
if is_palindrome(replace):
print 'Yes, it is a palindrome:', reverse(replace)
else:
print 'No, it is not a palindrome:', reverse(replace)
***

What should I do to output only the palindrome lines from the text file?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Building importable _tkinter on Windows (solved)

2013-03-10 Thread Terry Reedy

On 3/9/2013 7:41 PM, Terry Reedy wrote:

If you have tried to build _tkinter on Windows from the cpython
repository, and have 'import tkinter' work, please share your
experience, successful or not. I and another person have both failed.

> [snip]

Solution from Merlijn van Deen on core-mentorship list:
Let x be the directory containing both the repository directories, such 
as 'cpython' and the external dependency directories created by 
external.bat. Copy

x/tcl-8.5.11.0/win/Debug_VC10/tcl85g.dll
x/tk-8.5.11.0/win/Debug_VC10/tk85g.dll
to
x/cpython/PCbuild

Now, 'import tkinter', and hence idle, seem to work.

--
Terry Jan Reedy

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


Re: Problem using py-bt, py-locals, etc. during GDB debugging [solved]

2013-02-20 Thread drevicko
On Friday, December 7, 2012 11:22:12 AM UTC+11, Mark Shroyer wrote:
> On Thu, Dec 06, 2012 at 04:39:41PM -0500, Mark Shroyer wrote:
> 
> > I'm having trouble with the py-bt, py-locals, etc. GDB commands (from
> 
> > Python's python-gdb.py) while using GDB 7.4 to debug Python 2.7.3; I was
> 
> > wondering if anyone here could offer advice.
> 
> > 
> 
> > Briefly, py-bt seems to identify the python stack frames correctly, but
> 
> > shows "(unable to read python frame information)" for each, and likewise
> 
> > py-locals fails with "Unable to read information on python frame".
> 
> 
> 
> OK, I took a closer look at this and I've identified the issue; posting
> 
> my fix here in case someone else Googles this.
> 
> 
> 
> The problem in my case was that the python-gdb.py extension makes some
> 
> fragile assumptions about the format of values it receives from GDB, and
> 
> I had the line "set output-radix 16" in my .gdbinit, ultimately
> 
> resulting in the extension attempting to convert the string
> 
> representation of a hexadecimal number into an integer.
> 
> 
> 
> So there are two easy workarounds:
> 
> 
> 
>  1. set output-radix 10 in GDB, or
> 
> 
> 
>  2. Patch Python 2.7.3's python-gdb.py as follows:
> 
> 
> 
> === 8< =
> 
> 
> 
> --- python-gdb.py.orig2012-12-06 15:12:18.666760664 -0500
> 
> +++ python-gdb.py 2012-12-06 19:17:19.588356874 -0500
> 
> @@ -1074,7 +1074,11 @@
> 
>  
> 
>  
> 
>  def int_from_int(gdbval):
> 
> -return int(str(gdbval))
> 
> +int_str = str(gdbval)
> 
> +if int_str.startswith("0x"):
> 
> +return int(int_str[2:], 16)
> 
> +else:
> 
> +return int(int_str)
> 
>  
> 
>  
> 
>  def stringify(val):
> 
> 
> 
> === 8< =
> 
> 
> 
> I haven't checked to see whether this also applies to the GDB extension
> 
> for Python 3, though.

How did you track this down? I tried your fix, and tried setting the radix to 
10, but the problem persists. Perhaps something completely different is 
happening in my case ("unable to " isn't very useful debug information ;)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Eric - "No module named MainWindow" - solved

2013-02-17 Thread Phil

On 17/02/13 21:35, Vincent Vande Vyvre wrote:

Le 17/02/13 10:08, Phil a écrit :

Thank you for reading this.

I've been playing with Eric all day and I almost have a working GUI
application, but not quite. I have followed the two tutorials on the
Eric site and I'm sure that I haven't miss entered anything and so I
think the error is the result of something missing from my system or
perhaps a path error.

This is the error message:

The debugged program raised the exception unhandled ImportError
"No module named MainWindow"
File: /home/phil/main.py, Line: 4



The solution is to save the various files in their correct directories 
as mentioned in the tutorial.


--
Regards,
Phil
--
http://mail.python.org/mailman/listinfo/python-list


Re: Problem using py-bt, py-locals, etc. during GDB debugging [solved]

2012-12-06 Thread Mark Shroyer
On Thu, Dec 06, 2012 at 07:37:22PM -0500, MRAB wrote:
> On 2012-12-07 00:22, Mark Shroyer wrote:
> >
> > [...]
> >
> >   2. Patch Python 2.7.3's python-gdb.py as follows:
> >
> > === 8< =
> >
> > --- python-gdb.py.orig  2012-12-06 15:12:18.666760664 -0500
> > +++ python-gdb.py   2012-12-06 19:17:19.588356874 -0500
> > @@ -1074,7 +1074,11 @@
> >
> >
> >   def int_from_int(gdbval):
> > -return int(str(gdbval))
> > +int_str = str(gdbval)
> > +if int_str.startswith("0x"):
> > +return int(int_str[2:], 16)
> > +else:
> > +return int(int_str)
> >
> >
> >   def stringify(val):
> >
> > === 8< =
> >
> > I haven't checked to see whether this also applies to the GDB extension
> > for Python 3, though.
> >
> A shorter fix would be:
> 
> def int_from_int(gdbval):
>  return int(str(gdbval), 0)
> 
> 
> Some examples:
> 
>  >>> # Decimal
>  >>> int("12", 0)
> 12
>  >>> # Hexadecimal
>  >>> int("0x12", 0)
> 18
>  >>> # Octal
>  >>> int("012", 0)
> 10
>  >>> # Octal
>  >>> int("0o12", 0)
> 10
>  >>> # Binary
>  >>> int("0b11", 0)
> 3

Nice, I didn't know about that... thanks!

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


Re: Problem using py-bt, py-locals, etc. during GDB debugging [solved]

2012-12-06 Thread MRAB

On 2012-12-07 00:22, Mark Shroyer wrote:

On Thu, Dec 06, 2012 at 04:39:41PM -0500, Mark Shroyer wrote:

I'm having trouble with the py-bt, py-locals, etc. GDB commands (from
Python's python-gdb.py) while using GDB 7.4 to debug Python 2.7.3; I was
wondering if anyone here could offer advice.

Briefly, py-bt seems to identify the python stack frames correctly, but
shows "(unable to read python frame information)" for each, and likewise
py-locals fails with "Unable to read information on python frame".


OK, I took a closer look at this and I've identified the issue; posting
my fix here in case someone else Googles this.

The problem in my case was that the python-gdb.py extension makes some
fragile assumptions about the format of values it receives from GDB, and
I had the line "set output-radix 16" in my .gdbinit, ultimately
resulting in the extension attempting to convert the string
representation of a hexadecimal number into an integer.

So there are two easy workarounds:

  1. set output-radix 10 in GDB, or

  2. Patch Python 2.7.3's python-gdb.py as follows:

=== 8< =

--- python-gdb.py.orig  2012-12-06 15:12:18.666760664 -0500
+++ python-gdb.py   2012-12-06 19:17:19.588356874 -0500
@@ -1074,7 +1074,11 @@


  def int_from_int(gdbval):
-return int(str(gdbval))
+int_str = str(gdbval)
+if int_str.startswith("0x"):
+return int(int_str[2:], 16)
+else:
+return int(int_str)


  def stringify(val):

=== 8< =

I haven't checked to see whether this also applies to the GDB extension
for Python 3, though.


A shorter fix would be:

def int_from_int(gdbval):
return int(str(gdbval), 0)


Some examples:

>>> # Decimal
>>> int("12", 0)
12
>>> # Hexadecimal
>>> int("0x12", 0)
18
>>> # Octal
>>> int("012", 0)
10
>>> # Octal
>>> int("0o12", 0)
10
>>> # Binary
>>> int("0b11", 0)
3

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


Re: Problem using py-bt, py-locals, etc. during GDB debugging [solved]

2012-12-06 Thread Mark Shroyer
On Thu, Dec 06, 2012 at 04:39:41PM -0500, Mark Shroyer wrote:
> I'm having trouble with the py-bt, py-locals, etc. GDB commands (from
> Python's python-gdb.py) while using GDB 7.4 to debug Python 2.7.3; I was
> wondering if anyone here could offer advice.
> 
> Briefly, py-bt seems to identify the python stack frames correctly, but
> shows "(unable to read python frame information)" for each, and likewise
> py-locals fails with "Unable to read information on python frame".

OK, I took a closer look at this and I've identified the issue; posting
my fix here in case someone else Googles this.

The problem in my case was that the python-gdb.py extension makes some
fragile assumptions about the format of values it receives from GDB, and
I had the line "set output-radix 16" in my .gdbinit, ultimately
resulting in the extension attempting to convert the string
representation of a hexadecimal number into an integer.

So there are two easy workarounds:

 1. set output-radix 10 in GDB, or

 2. Patch Python 2.7.3's python-gdb.py as follows:

=== 8< =

--- python-gdb.py.orig  2012-12-06 15:12:18.666760664 -0500
+++ python-gdb.py   2012-12-06 19:17:19.588356874 -0500
@@ -1074,7 +1074,11 @@
 
 
 def int_from_int(gdbval):
-return int(str(gdbval))
+int_str = str(gdbval)
+if int_str.startswith("0x"):
+return int(int_str[2:], 16)
+else:
+return int(int_str)
 
 
 def stringify(val):

=== 8< =

I haven't checked to see whether this also applies to the GDB extension
for Python 3, though.
-- 
http://mail.python.org/mailman/listinfo/python-list


[SOLVED] Re: Making `logging.basicConfig` log to *both* `sys.stderr` and `sys.stdout`?

2012-10-24 Thread Daniel Dehennin
Daniel Dehennin  writes:

> Hello,

Hi


[...]

> I tried to setup the same for my scripts with
> "logging.config.dictConfig()" without much success, I want to limit
> output to stdout to INFO, everything bellow INFO should be sent to
> stderr instead.
>
> Any hints?

I finally find a solution for my script, I added a filter.

Regards.

#+begin_src python
class UniqLevelFilter(logging.Filter):
def __init__(self, level):
self._level = level

def filter(self, rec):
return rec.levelno == self._level

def init_logging(options):
# TODO: color stderr messages by level if sys.stderr.isatty()
# 
http://stackoverflow.com/questions/384076/how-can-i-color-python-logging-output
# 
http://plumberjack.blogspot.fr/2010/12/colorizing-logging-output-in-terminals.html
config = { 'version' : 1,
   'filters' : { 'stdout' : { '()' : '__main__.UniqLevelFilter',
  'level' : logging.INFO, },
},
   'formatters' : { 'stdout' : { 'format' : '%(message)s',
 'datefmt' : '', },
'stderr' : { 'format' : '%(message)s',
 'datefmt' : '', },
},
   'handlers' : { 'stdout' : { 'class' : 'logging.StreamHandler',
   'stream' : 'ext://sys.stdout',
   'level' : 'INFO',
   'filters' : ['stdout'],
   'formatter' : 'stdout', },
  'stderr' : { 'class' : 'logging.StreamHandler', 
   'stream' : 'ext://sys.stderr',
   'level' : 'WARNING', 
   'formatter' : 'stderr', }
},
   'root' : { 'level' : options.log_level.upper(),
  'handlers' : ['stdout', 'stderr'],
},
}

logging.config.dictConfig( config )
return logging.getLogger()

#+end_src

-- 
Daniel Dehennin
EOLE


pgppxZX1W6r9Y.pgp
Description: PGP signature
-- 
http://mail.python.org/mailman/listinfo/python-list


  1   2   3   >