Re: best way to share an instance of a class among modules?

2013-02-06 Thread c
On Feb 6, 7:03 pm, Michael Torrie  wrote:
> On 02/06/2013 03:41 PM, CM wrote:
>
> > Thank you.  But, I'm sorry, I'm not following this enough to get it to
> > work.  Shouldn't it be a little more like this:
>
> No, not exactly.
>
>
>
> > # in utilities module
> > shared_cursor =  DatabaseAccess_instance  #but how? see my question
> > below...
>
> How what?
>
> > # in importer
> > import utilities
> > self.shared_cursor = utilities.shared_cursor  ("self" is here to make
> > cursor available to all functions in importer
>
> Umm no.  For one you're using self incorrectly.  For two, it already is
> visible to all functions in the module.  You just have to refer to it as
> "utilities.shared_cursor."

I was using self correctly, I think; but I should have said that the
code in the importing module would be within a class, so self there
refers to that class.  But that's a side point.

I agree that utilities.shared_cursor is visible within the importing
module.  But the problem below remains for me...

> > My only problem, then, is I create the shared_cursor from within a
> > function within the instance of DatabaseAccess().  How then do I pass
> > it from within the function's namespace to the module's namespace so
> > that I can do that first line?
>
> Every function in a module has access to the module's global namespace.
>  And your shared_cursor is there, inside of the utilities reference,
> since utilities was imported into your module, "importer."

But the function in the module is also within a *class* so I don't
think the function does have access to the module's global namespace.
Here's the hierarchy:

-- Module namespace
 class namespace (DatabaseAccess is the name of the class)
  function namespace
  This is where the cursor is created.  How do I get it
into the module namespace?

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


Re: Is Python what I need?

2009-08-23 Thread c
> I'm interested in developing computer based, interactive programs

That is so open-ended it could mean anything.  If you give a much
more specified idea of what you are imagining creating, people could
be helpful.

> for students in a special school who have an aversion to pen and paper.


Aversion?  Why?  Is it that they have such bad penmanship that
writing
is too frustrating?  I've taught such students in college, and
suspect
(but do not know) that what would be good is to get them young and
really put in the remedial time to train their penmanship up to
sustained
legibility and speed.  Eventually society might go 100% electronic;
for now, being able to write notes on paper is very helpful, and
paper
is still such a great technology aside from renewable concerns, but
they can be greatly improved.  (I even suspect rigorous and successful
penmanship training might pay off in "general intelligence" gains)


> I've searched the net to find ready made software that will meet my
> needs but it is either written to a level much higher than these
> students can cope with or priced beyond our school budget. I came
> across a blog of someone singing the praises of Python. My question is
> therefore aimed at those that know what they are talking about (ie
> users in this group). Is Python the language I need to learn to
> develop these programs?

I agree with Dave A that writing a useful program is often far harder
than a beginner might imagine.  That said, much would depend on what
you would need the program to do.  Python, in my limited experience
as a hobbyist, strikes me as fairly easy to get started with in
programming, and yet can do a great deal, too.  So, as I said, more
details about the intended program would help people guide your
choice.

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


python 3.3 urllib.request

2012-12-07 Thread Steeve C
hello,

I have a python3 script with urllib.request which have a strange behavior,
here is the script :

+
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import urllib.request
import sys, time


url = 'http://google.com'

def make_some_stuff(page, url):
sys.stderr.write(time.strftime("%d/%m/%Y %H:%M:%S -> page from \"") +
url + "\"\n")
sys.stderr.write(str(page) + "\"\n")
return True

def get_page(url):
while 1:
try:
page = urllib.request.urlopen(url)
yield page

except urllib.error.URLError as e:
sys.stderr.write(time.strftime("%d/%m/%Y %H:%M:%S -> impossible
to access to \"") + url + "\"\n")
time.sleep(5)
continue

def main():
print('in main')
for page in get_page(url):
make_some_stuff(page, url)
time.sleep(5)

if __name__ == '__main__':
main()
+

if the computer is connected on internet (with an ethernet connection for
example) and I run this script, it works like a charme :
- urllib.request.urlopen return the page
- make_some_stuff write in stderr
- when the ethernet cable is unplug the except block handle the error while
the cable is unplug, and when the cable is pluged
back urllib.request.urlopen return the page and make_some_stuff write in
stderr

this is the normal behavior (for me, imho).

but if the computer is not connected on internet (ethernet cable unpluged)
and I run this script, the except block handle the error (normal), but when
I plug the cable, the script continue looping and urllib.request.urlopen
never return the page (so, it alway go to the except block)

What can I do to handle that ?

Thanks

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


numpy array operation

2013-01-29 Thread C. Ng
Is there a numpy operation that does the following to the array?

1 2  ==>  4 3
3 4   2 1

Thanks in advance.


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


h5py.File() gives error message

2017-10-24 Thread C W
Dear list,

The following Python code gives an error message

# Python code starts here:
import numpy as np
import h5py
train_dataset = h5py.File('datasets/train_catvnoncat.h5', "r")

# Python code ends

The error message:

train_dataset = h5py.File('train_catvnoncat.h5', "r")
Traceback (most recent call last):
  File "", line 1, in 
  File "/Users/M/anaconda/lib/python3.6/site-packages/h5py/_hl/files.py",
line 269, in __init__
fid = make_fid(name, mode, userblock_size, fapl, swmr=swmr)
  File "/Users/M/anaconda/lib/python3.6/site-packages/h5py/_hl/files.py",
line 99, in make_fid
fid = h5f.open(name, flags, fapl=fapl)
  File "h5py/_objects.pyx", line 54, in h5py._objects.with_phil.wrapper
  File "h5py/_objects.pyx", line 55, in h5py._objects.with_phil.wrapper
  File "h5py/h5f.pyx", line 78, in h5py.h5f.open
OSError: Unable to open file (unable to open file: name =
'train_catvnoncat.h5', errno = 2, error message = 'No such file or
directory', flags = 0, o_flags = 0)

My directory is correct, and the dataset folder with file is there.

Why error message? Is it h5py.File() or is it my file? Everything seems
pretty simple, what's going on?

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


Re: h5py.File() gives error message

2017-10-25 Thread C W
Oh, I was running a debug file, that's why the path is different.

The file is here,
https://www.dropbox.com/s/6jx4rzyg9xwl95m/train_catvnoncat.h5?dl=0

Is anyone able to get it working? Thank you!

On Tue, Oct 24, 2017 at 10:37 PM, Dennis Lee Bieber 
wrote:

> On Tue, 24 Oct 2017 18:02:26 -0700, Rob Gaddi
>  declaimed the following:
>
> Whoops, I may have gotten the wrong level of quoting -- my
> apologies if
> so (I did have agent fetch the original posting, but might not have had
> that active when I hit "reply")
> --
> Wulfraed Dennis Lee Bieber AF6VN
> wlfr...@ix.netcom.comHTTP://wlfraed.home.netcom.com/
>
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: h5py.File() gives error message

2017-10-25 Thread C W
wow, thanks so much! I don't know how you figured that it's HTML, but
that's awesome!

Mike

On Wed, Oct 25, 2017 at 5:20 AM, Peter Otten <__pete...@web.de> wrote:

> C W wrote:
>
> > Oh, I was running a debug file, that's why the path is different.
> >
> > The file is here,
> > https://www.dropbox.com/s/6jx4rzyg9xwl95m/train_catvnoncat.h5?dl=0
> >
> > Is anyone able to get it working? Thank you!
>
> Hm, that file seems to contain HTML and that causes an OSError here, too:
>
> $ head -n3 datasets/train_catvnoncat.h5
>
> 
> 
>
> $ python3
> Python 3.4.3 (default, Nov 17 2016, 01:08:31)
> [GCC 4.8.4] on linux
> Type "help", "copyright", "credits" or "license" for more information.
> >>> import h5py
> >>> train_dataset = h5py.File('datasets/train_catvnoncat.h5', "r")
> Traceback (most recent call last):
>   File "", line 1, in 
>   File "/usr/lib/python3/dist-packages/h5py/_hl/files.py", line 207, in
> __init__
> fid = make_fid(name, mode, userblock_size, fapl)
>   File "/usr/lib/python3/dist-packages/h5py/_hl/files.py", line 79, in
> make_fid
> fid = h5f.open(name, h5f.ACC_RDONLY, fapl=fapl)
>   File "h5f.pyx", line 71, in h5py.h5f.open (h5py/h5f.c:1806)
> OSError: unable to open file (File accessibilty: Unable to open file)
>
> It's not exactly what you see, but that may be due to differing software
> versions.
> When I replace the HTML file with its namesake found at
>
> https://github.com/lalxyy/NEU-MCM-Training-4/blob/master/cod
> e/datasets/train_catvnoncat.h5
>
> I can open it:
>
> $ file datasets/train_catvnoncat.h5
> datasets/train_catvnoncat.h5: Hierarchical Data Format (version 5) data
>
> $ python3
> Python 3.4.3 (default, Nov 17 2016, 01:08:31)
> [GCC 4.8.4] on linux
> Type "help", "copyright", "credits" or "license" for more information.
> >>> import h5py
> >>> train_dataset = h5py.File('datasets/train_catvnoncat.h5', "r")
> >>>
>
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


I have anaconda, but Pycharm can't find it

2017-11-26 Thread C W
Hello all,

I am a first time PyCharm user. I have Python 3 and Anaconda installed.
They work together on Sublime Text, but not on Pycharm.

Pycharm tells me it cannot find modules numpy, matplotlib, etc.

What should I do? I tried to set the interpreter environment, and a few
other options, none seem to work.

This is the typical solution, but it does not work
https://stackoverflow.com/questions/35623776/import-numpy-on-pycharm

Thanks,

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


Why does Jupyter Notebook searches files in folders, but PyCharm and Sublime Text does not?

2017-12-14 Thread C W
Hi all,

I am confused why Jupyter Notebook searches files in subfolder, but PyCharm
and Sublime Text 3 does not. Is there a rule?

For example,
I have a module or file called lr_utils.py in the current folder.

If I run the following line in Jupyter, it's fine.
> import lr_utils

But in PyCharm, I get the error,
ModuleNotFoundError: No module named 'lr_utils'

If I run it in Sublime Text, it's find too
> import os
> os.chdir("Users/My_name/Desktop/Python_Codes")
> import lr_utils

Why the code works in one but not the other? Thank you!
-- 
https://mail.python.org/mailman/listinfo/python-list


PEP about recommended project folder layout

2022-07-26 Thread c . buhtz

Hello,

I am not sure if I looked into the correct sources. I was looking in 
"PEP 609 – Python Packaging Authority (PyPA) Governance" [1] and the 
"PyPA specifications" [2].


My question in short: Is there an official document (e.g. a PEP) about a 
recommended layout for project folders.


Looking into the wild and past there are a lot of variations of such 
layouts. I am far away from being a pro but depending on experience in 
my own projects and what I have learned from others (e.g. in 
blog-posts/tutorials) I recommend to have the "test" folder and the 
package folder side by side on the same level in the project folder (the 
root).


my_project
|- tests
|  └ test_*.py
|- my_package
|  └ __init__.py
└-- README.md

I sometimes add to it the so called "src"-Layout where the package 
folder is one level deeper in an extra "src" folder.


my_project
|- tests
|  └ test_*.py
|- src
|  └- my_package
| └ __init__.py
└-- README.md

I don't want to discuss the pros and cons of all variations. What I need 
is an official document I can use in discussions with other maintainers. 
If there is a PEP/document against my current recommendation I am also 
fine with this. ;)


Kind
Christian

[1] -- 
[2] -- 
--
https://mail.python.org/mailman/listinfo/python-list


venv and packages with entry points

2022-09-06 Thread c . buhtz

Hello,

I try to get it onto my head how virtual environments (via venv) works 
when I have packages with "entry points".


I can define such entry points in the setup.cfg like this (full example 
[1]):


[options.entry_points]
console_scripts =
hyperorg = hyperorg.__main__:main

When I install such a package via pip the result is a shell script in 
/usr/bin/...


What happens when I install such a package with an entry point via "pip 
install ." when an virtual environment is activated?


Kind
Christian

[1] -- 


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


Re: Which architectures to support in a CI like Travis?

2022-09-19 Thread c . buhtz

Dear Mats,

thanks for the reply.

Am 19.09.2022 16:10 schrieb Mats Wichmann:

Kind of unrelated to the actual question, but if you start doing
anything serious under Travis you'll run out of free minutes rather
quickly.  My project had to just give up on it after they changed
their licensing models


I'm new to Travis and didn't noticed that piece of information. ;)
Now I am more scared that Travis asked me for my credit card data no 
matter that I choose a "free" plan.


I'm a bit shocked and still don't understand the "credit" infos on my 
Travis account.
There are "Credits" ("used 4470 of 1 credits") and "OSS only 
credits" ("0 of your 0 monthly credits").


OSS == "open source software" ?

I'm confused and thought that Travis is free for public github repos. 
Any suggestions.


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


How to get the current set LOG_MASK in Python's syslog module?

2022-09-22 Thread c . buhtz

X-Post: https://stackoverflow.com/q/73814924/4865723

Hello,

I'm aware that there is a `logging` package that is more _modern_ then 
[`syslog`](https://docs.python.org/3/library/syslog.html). But I have 
old code here to deal with that does use `syslog`. So that question is 
specific to `syslog` and not to `logging`.


I would like to get the current `LOG_MASK`, which is kind of a logging 
level. According to the docu it seems that `syslog` doesn't have a 
mechanism for that.


Does someone has an idea?

The docu also tells me that `syslog` does let pass all messages by 
default.
My point is I do manipulate via `syslog.setlogmask()` the current log 
leve. At the end I would like to set it back to its previous value.


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


Re: pip/setuptools: Entry points not visible from pkexec-root-environment

2022-12-18 Thread c . buhtz

Dear Gerard,
thank you for your reply.

Am 18.12.2022 19:45 schrieb Weatherby,Gerard:

"sudo python3 -m pip
install -e ."

You’ve already started down a problematic road. I recommend installing
root level Python packages through your system package manager. (apt
for debian, or whatever RedHat is using now).


I'm totally with you at this point.

It is clear for me that distro maintainers sometimes using different 
mechanics.
But I'm the upstream maintainer and before handing offer a release to 
the distro that thing need to run without a distro. And that is pip. I 
also know a quit old project using "make" for that.


This question is independent from distros.


I’ve never used pkexec. Generally, just use sudo.


They are two very different things. There is a strict reason why I need 
to use pkexec here.


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


Re: pip/setuptools: Entry points not visible from pkexec-root-environment

2022-12-18 Thread c . buhtz

Dear Chris,

thank you for your reply.

Am 18.12.2022 20:27 schrieb Chris Angelico:

Does it have to be in path? Can't you say
/usr/local/bin/entrypointname? Not sure what constitutes an elegant
solution here.


I asked that myself. My current solution do determine the full path of 
the entrypoint via "which entrypoint".

I also think this is to my current knowledge the best solution.
--
https://mail.python.org/mailman/listinfo/python-list


Re: pip/setuptools: Entry points not visible from pkexec-root-environment

2022-12-18 Thread c . buhtz

Am 18.12.2022 22:37 schrieb Mats Wichmann:

the which command uses your PATH, so I'm not sure you're buying
anything new there


I'm using which before entering pkexec. ;)

I'll show a demonstrator project later.
--
https://mail.python.org/mailman/listinfo/python-list


Re: pip/setuptools: Entry points not visible from pkexec-root-environment

2022-12-18 Thread c . buhtz

Dear Barry,
thanks for reply and asking back.

Am 18.12.2022 22:33 schrieb Barry:

Why are asking on this list and discuss.python.org?


To be exact I'm asking in the "Packaging" section of 
"discuss.python.org". To my knowledge that section is the official 
channel of "pypa/pip" project pointed to from there own README.md [1].
To be complete. I also asked in in context of "pypa/setuptools" [2] and 
on the debian-python mailing list.


Not all questions are exactly the same but touching the same meta topic.
"pypa/setuptools" themselfs pointed me to the fact that they are not 
responsible for generating the entry-point-scripts but "pypa/pip" is. No 
matter both have "pypa/" in their names they seem technically different. 
This has reasons but is very confusing for "developers from the outside" 
like me. There are also alternative build-tools other then "setuptools". 
That is why I asked on that python-list here, too. The later was in the 
hope to maybe be pointed to alternative solutions away from setuptools 
and/or pip.


My apologize. When I decide for a solution I will point you to a 
demonstrator repository illustrating that solution.


[1] -- 
[2] -- 
--
https://mail.python.org/mailman/listinfo/python-list


Re: pip/setuptools: Entry points not visible from pkexec-root-environment

2022-12-19 Thread c . buhtz

Dear Chris,
thanks for asking back and my apologize for being to broad in my way of 
asking (in a foreign language).


Am 19.12.2022 07:40 schrieb Chris Angelico:

Hmm, then I'm not sure what you're *losing* here. The problem, as I
understand it, is that the scripts are getting installed into
/usr/local/bin (which is on PATH at the time they're installed), but
pkexec has a restricted PATH. So if you use which before pkexec'ing,
wouldn't you find the scripts, and then be able to run them without
regard to PATH?


Absolut correct. This works.

The question is if this is a "good" or "elegant" way from the viewpoint 
of different communities/projects (e.g. Python, setuptools, pip, other 
build-systems, distros, something I forgot).


I assume that I'm not the first person with such a use case. So there 
could be solutions out there. Maybe they are standardized solutions out 
there; e.g. a magic feature of setuptools or pip I haven't noticed yet.

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


Re: What should go to stdout/stderr and why Python logging write everything to stderr?

2023-01-03 Thread c . buhtz

Am 03.01.2023 17:51 schrieb r...@zedat.fu-berlin.de:

logging.getLogger().addHandler( logging.StreamHandler( sys.stdout ))


But I don't want to make all log levels go to stdout. Just DEBUG and 
INFO. But this would be a workaround.


The main question here is why does Python deciecded to make all logs go 
to stderr?
Maybe I totally misunderstood the intention of logging.info()?! Isn't 
this the "usual applicaton output"?


If not, what messages should go into logging.info()? Can you name me 
some examples?

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


Re: subprocess equivalent for "os.execvp()"?

2023-01-09 Thread c . buhtz

Dear Eryk,

Am 08.01.2023 17:22 schrieb Eryk Sun:

Avoid using any of the `os.exec*` functions on Windows. There's no
support for replacing a Windows process image, so the `exec*()`
functions simply spawn a child process and terminate the current one.


Thanks for bringing this up.

On Python for Windows what is the appropriate way how a process can call 
itself again?


Let me give you an example [1]:
There is a project "bitcli" having two entry points

[project.scripts]
bitcli = "bitcli.__main__:main"
bitcli-root = "bitcli.__main__:run_main_as_root_via_policykit"

The first is usual.

But the second does call "bitcli" via "pkexec" to give it some root 
rights.


This application is intended to be run as user or root by the user 
himself.


def run_main_as_root_via_policykit():
cmd = ['pkexec', '--disable-internal-agent', 'bitcli']

# See https://github.com/python/cpython/issues/39569
os.execvp(cmd[0], cmd)

Is there a better way to achiev this?

[1] -- 

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


[pygettext] --package-name and --package-version unknown

2023-05-04 Thread c . buhtz

Hello,

am I right to assume that "pygettext" is part of the official Python3 
"package"? So it is OK to aks here?


I do use pygettext to handle po and pot files. In the manpage I'm not 
able to find help about this.
I would like to modify the header that pygettext does create in each 
po-file.


How can I set the "Project-Id-Version"? With "xgettext" I would use the 
arguments "--package-name" and "--package-version" for this but they are 
unknown for "pygettext".


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


Re: [pygettext] --package-name and --package-version unknown

2023-05-05 Thread c . buhtz

Thanks for the answer.

Am 05.05.2023 03:24 schrieb aapost:

pygettext is deprecated since xgettext supports python now, so using
xgettext is recommended.


If this is the official case then it should be mentioned in the python 
docs. The 3.11 docs still tell about pygettext and xgettext and don't 
recommend one of it.

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


How do you debug in Python? Coming from a Matlab and R user. I'm already aware of pdb.

2021-01-26 Thread C W
Hello everyone,

I'm a long time Matlab and R user working on data science. How do you
troubleshooting/debugging in Python?

I ran into this impossible situation to debug:
class person:
def __init__(self, id, created_at, name, attend_date, distance):
"""Create a new `person`.
"""
self._id = id
self.created_at = created_at
self.name = name
self.attend_date = attend_date
self.distance = distance

@classmethod
def get_person(self, employee):
"""Find and return a person by.
"""
return person(employee['created_at'],
employee['id'],
employee['name'],
employee['attend_date'],
employee['distance']
)

I got an error message saying id was 'str', but expecting 'int'.

In R, I use the interactive IDE with console. Wherever the error interrupts
the code, I just evaluate that line in the console. Very convenient!

If this error was in R, I would have tried:
> self._id = 123

But, I can't do that here! What do I do? Do I HAVE TO instantiate an object
first? It's not  convenient if I have 10 of these objects around. I need to
instantiate 10 objects.

I know hardcore computer scientists would tell me about Python debugger. R
also has one, but nobody ever uses it. I don't find them user-friendly!

Thanks a lot,

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


Re: How do you debug in Python? Coming from a Matlab and R user. I'm already aware of pdb.

2021-01-26 Thread C W
Thanks for your replies. My apologies for the poor indent. I'm rewriting
the code below.

class NEODatabase:
def __init__(self, id, created_at, name, attend_date, distance):
self._id = id
self.created_at = created_at
self.name = name
self.attend_date = attend_date
self.distance = distance

@classmethod
def get_person(self, employee):
return PERSONDatabase(employee['created_at'],
employee['id'],
employee['name'],
employee['attend_date'],
employee['distance'])

I have a naive question. How do I use traceback or trace the stack? In
particular, I'm using VS Code with Python interactive console.

Say, I want to print the value of employee['name']. Can I do it? My
understanding is that these classes are just "skeletons". I must create an
instance, assign values, then test?

Thanks so much,

Mike

On Tue, Jan 26, 2021 at 9:55 PM Ed Leafe  wrote:

> On Jan 26, 2021, at 18:16, Grant Edwards 
> wrote:
> >
> >> How do you troubleshooting/debugging in Python?
> >
> > Mostly I read exception trace and read the code and think about it.
> >
> > If that doesn't work, I add some print() or syslog() calls.
> >
> > If I really get stuck, I try to write as small a program as possible
> > that demonstrates the problem.
>
> I do the first two, but if I get really stuck, I use the pudb debugger (
> https://pypi.org/project/pudb/).
>
> Using that, I can see all the locals, jump to any point in the stack and
> see the locals there, or shell into ipython if I need to run some quick
> code. For me, this is much faster than trying to write an additional
> program that is close enough to the problem code to be useful.
>
> -- Ed Leafe
>
>
>
>
>
>
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How do you debug in Python? Coming from a Matlab and R user. I'm already aware of pdb.

2021-01-26 Thread C W
Hi Michael,
Here's the code again, class should be called PERSONDatabase, misspelled
earlier:
class PERSONDatabase:
   def __init__(self, id, created_at, name, attend_date, distance):
  self._id = id
  self.created_at = created_at
  self.name= name
  self.attend_date = attend_date
  self.distance = distance

   @classmethod
   def get_person(self, employee):
  return PERSONDatabase(employee['created_at'],
employee['id'],
employee['name'],
employee['attend_date'],
employee['distance'])

The PERSONDatabase class is called from main. This is the trace back I got
from the VS code:

Traceback (most recent call last):
   File "/Users/Mike/Documents/Mike/main.py", line 95, in 
  main()
   File "/Users/Mike/Documents/Mike/main.py", line 86, in main
  args = get_feed()
   File "/Users/Mike/DocumentsMike/main.py", line 32, in get_feed
  result = [PERSONatabase.get_person(raw_person) for raw_neo in
raw_objects]
   File "/Users/Mike/Documents/Mike/main.py", line 32, in 
  result = [NEODatabase.get_person(raw_person) for raw_neo in
raw_objects]
   File "/Users/Mike/Documents/Mike/database.py", line 24, in get_person
  return PERSONDatabase(person['created_at'],
KeyError: 'created_at'

Thank you very much!

On Wed, Jan 27, 2021 at 12:10 AM Michael Torrie  wrote:

> On 1/26/21 8:37 PM, C W wrote:
> > I have a naive question. How do I use traceback or trace the stack? In
> > particular, I'm using VS Code with Python interactive console.
>
> Show us the traceback here and we can help you interpret it.  Copy and
> paste it from the VS Code console.
>
> > Say, I want to print the value of employee['name']. Can I do it?
>
> Yes I would think so.
>
> > My understanding is that these classes are just "skeletons". I must
> > create an instance, assign values, then test?
>
> Can't you just do something like this?
>
> class NEODatabase:
> def __init__(self, id, created_at, name, attend_date, distance):
> self._id = id
> self.created_at = created_at
> self.name = name
> self.attend_date = attend_date
> self.distance = distance
>
> @classmethod
> def get_person(self, employee):
> print (employee['name'])
>
> return PERSONDatabase(employee['created_at'],
>   employee['id'],
>   employee['name'],
>   employee['attend_date'],
>   employee['distance'])
>
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How do you debug in Python? Coming from a Matlab and R user. I'm already aware of pdb.

2021-01-27 Thread C W
Hi Cameron,
Yes, you are correct in all above. There's a mistake in my copy paste.
Thanks for pointing that out!

On Wed, Jan 27, 2021 at 12:58 AM Cameron Simpson  wrote:

> On 27Jan2021 00:19, C W  wrote:
> >Here's the code again, class should be called PERSONDatabase,
> >misspelled
> >earlier:
> >class PERSONDatabase:
> >   def __init__(self, id, created_at, name, attend_date, distance):
> >  self._id = id
> >  self.created_at = created_at
> >  self.name= name
> >  self.attend_date = attend_date
> >  self.distance = distance
>
> Here's you're setting attributes (which is a very normal thing to do).
>
> >   @classmethod
> >   def get_person(self, employee):
> >  return PERSONDatabase(employee['created_at'],
> >employee['id'],
> >employee['name'],
> >employee['attend_date'],
> >employee['distance'])
>
> I think this "employee" is called "person" in the code the traceback
> came from. It is better when these two things match.
>
> >The PERSONDatabase class is called from main. This is the trace back I got
> >from the VS code:
> >
> >Traceback (most recent call last):
> >   File "/Users/Mike/Documents/Mike/main.py", line 95, in 
> >  main()
> >   File "/Users/Mike/Documents/Mike/main.py", line 86, in main
> >  args = get_feed()
> >   File "/Users/Mike/DocumentsMike/main.py", line 32, in get_feed
> >  result = [PERSONatabase.get_person(raw_person) for raw_neo in
> >raw_objects]
> >   File "/Users/Mike/Documents/Mike/main.py", line 32, in 
> >  result = [NEODatabase.get_person(raw_person) for raw_neo in
> >raw_objects]
> >   File "/Users/Mike/Documents/Mike/database.py", line 24, in get_person
> >  return PERSONDatabase(person['created_at'],
> >KeyError: 'created_at'
>
> Here's you're trying to index another object using a string, which seems
> to resemble the .created_at attribute in your PERSONDatabase object.
>
> I would presume from this that the "person" object at the bottom of the
> traceback is the "raw_person" called above it. But I do not see
> raw_person defined anywhere. Are you sure you didn't mean to pass
> "raw_neo" instead of "raw_person"? That would be more normal, since
> you're iterating over "raw_objects".
>
> Cheers,
> Cameron Simpson 
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How do you debug in Python? Coming from a Matlab and R user. I'm already aware of pdb.

2021-01-27 Thread C W
For learning purposes, here's the files:
https://www.dropbox.com/sh/a3iy40rcvib4uvj/AAADmlM2i6NquWC1SV0nZfnDa?dl=0

Yes, you are correct about "employee" and "person" discrepancies. For now,
the list comprehension is where I get stuck.

I'd like to know how the experts on here are approaching and debugging
this.

Bonus if no debugger or breakpoint. Just the good ol' run the function and
evaluate/print output for problems.

Thanks so much,

Mike

On Wed, Jan 27, 2021 at 10:53 AM Michael Torrie  wrote:

> On 1/26/21 10:19 PM, C W wrote:
> > Traceback (most recent call last):
> >File "/Users/Mike/Documents/Mike/main.py", line 95, in 
> >   main()
> >File "/Users/Mike/Documents/Mike/main.py", line 86, in main
> >   args = get_feed()
> >File "/Users/Mike/DocumentsMike/main.py", line 32, in get_feed
> >   result = [PERSONatabase.get_person(raw_person) for raw_neo in
> > raw_objects]
> >File "/Users/Mike/Documents/Mike/main.py", line 32, in 
> >   result = [NEODatabase.get_person(raw_person) for raw_neo in
> > raw_objects]
> >File "/Users/Mike/Documents/Mike/database.py", line 24, in get_person
> >   return PERSONDatabase(person['created_at'],
> > KeyError: 'created_at'
>
> The actual error is the last part, which is a KeyError on line 24.  A
> key error usually is from a dictionary-like object and it means the
> requested key is not found in that object.  In other words, this person
> object has no "created_at" key.  Hope that makes sense.
>
> I do not know why the code you posted refers to "employee" but the
> traceback refers to "person."
>
> In any case the trace back shows you what called what until the error
> occurred. You can trace the execution of the code simply by following
> it.  main() called get_feed() which set up a list comprehension, which
> calls get_person() which is where the error is occurring.  I'm not
> following the list comprehension stuff; I don't know why python is first
> referring to PERSONatabase and then refers to NEODatabase.
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: IDE tools to debug in Python?

2021-01-27 Thread C W
I'm not expert in Python, but I sure tried many IDEs to kick off Python
programming.

I started with PyCharm, but I had a problem with it constantly scanning the
background, even after I turned that feature off.

My favorite (I'm using now) is VS Code with Python extension, it's very
light. Recently also started background scanning, but that's generally done
in 30 seconds.

On Wed, Jan 27, 2021 at 1:51 PM Michał Jaworski  wrote:

> PyCharm has all these debugging capabilities and there is a community
> edition that you can use for free. If you earn for the living with Python
> it is worth investing in professional edition though.
>
> Michał Jaworski
>
> > Wiadomość napisana przez flaskee via Python-list 
> w dniu 27.01.2021, o godz. 19:32:
> >
> > 
> > While print() is groovy and all,
> > if anyone runs across a non-pdb python debugger (standalone or IDE-based)
> > please let me know.
> >
> > I too was blessed with IDE-based debugging (in the 90's!)
> > * where you can set break point(s);
> > * have the program stop right before a suspected failure point;
> > * check the contents of ALL variables, and choose whether to restart;
> > * or skip a few lines before restarting;
> > * or change a variable (hot, move back a few lines and restart, etc.
> > * Some, would even let you alter the code a bit before restarting.
> >
> > I too, miss this.
> >
> >
> > Hopefully I did not miss someone mentioning
> > such a python tool in the prior thread.
> >
> > Thanks!
> >
> > --
> > https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: IDE tools to debug in Python?

2021-01-27 Thread C W
I don't know exactly, but it shows as inspection on the bottom left corner.

I believe it's indexing in the background.

On Wed, Jan 27, 2021 at 3:25 PM Grant Edwards 
wrote:

> On 2021-01-27, C W  wrote:
> > I'm not expert in Python, but I sure tried many IDEs to kick off Python
> > programming.
> >
> > I started with PyCharm, but I had a problem with it constantly scanning
> the
> > background, even after I turned that feature off.
>
> What is it scanning?
>
> > My favorite (I'm using now) is VS Code with Python extension, it's very
> > light. Recently also started background scanning, but that's generally
> done
> > in 30 seconds.
>
> Same question, what is it scanning?
>
> --
> Grant
>
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: IDE tools to debug in Python?

2021-01-27 Thread C W
I meant bottom right corner, not left. opps!

On Wed, Jan 27, 2021 at 3:36 PM C W  wrote:

> I don't know exactly, but it shows as inspection on the bottom left corner.
>
> I believe it's indexing in the background.
>
> On Wed, Jan 27, 2021 at 3:25 PM Grant Edwards 
> wrote:
>
>> On 2021-01-27, C W  wrote:
>> > I'm not expert in Python, but I sure tried many IDEs to kick off Python
>> > programming.
>> >
>> > I started with PyCharm, but I had a problem with it constantly scanning
>> the
>> > background, even after I turned that feature off.
>>
>> What is it scanning?
>>
>> > My favorite (I'm using now) is VS Code with Python extension, it's very
>> > light. Recently also started background scanning, but that's generally
>> done
>> > in 30 seconds.
>>
>> Same question, what is it scanning?
>>
>> --
>> Grant
>>
>> --
>> https://mail.python.org/mailman/listinfo/python-list
>>
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How do you debug in Python? Coming from a Matlab and R user. I'm already aware of pdb.

2021-01-27 Thread C W
Great tutorial Irv, very simple with if-else example, gets the point
across.

My main takeaway from the discussion so far is that: you can't troubleshoot
Python without some kind of breakpoint or debugger.

I suppose I can't take the functional programming debugger style like C,
Matlab, or R, and apply it to a OOP language like Python.

On Wed, Jan 27, 2021 at 5:26 PM Irv Kalb  wrote:

> On Jan 26, 2021, at 5:28 PM, William Ray Wing via Python-list <
> python-list@python.org> wrote:
> >
> >
> >
> >> On Jan 26, 2021, at 2:00 PM, C W  wrote:
> >>
> >> Hello everyone,
> >>
> >> I'm a long time Matlab and R user working on data science. How do you
> >> troubleshooting/debugging in Python?
> >>
> >
> > Another approach is to run the code in an IDE.  I happen to use Wing,
> but that is a coincidence.  But almost ANY IDE will let you set a break
> point, then single-step through your code starting at the break point and
> examine the values of your variables at each step.  Sometimes this is an
> awfully big hammer for what is a head-slapping mistake.  But it has never
> failed me.
> >
> >
>
> I'm happy with the PyCharm IDE.  I created a video showing how to use the
> debugger in that environment.  It's available on YouTube here:
>
> https://www.youtube.com/watch?v=cxAOSQQwDJ4 <mailto:python-list@python.org
> >
>
> Irv
>
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Is there a way to subtract 3 from every digit of a number?

2021-02-20 Thread C W
Hello everyone,

I'm curious if there is a way take number and back each digit by 3 ?

2342 becomes 9019
8475 becomes 5142
5873 becomes 2540

The tricky part is that 2 becomes 9, not -1.

Here's my toy example and what I attempted,
> test_series = pd.Series(list(['2342', '8475', '5873']))
> test_series
02342
18475
25873
dtype: object

> test_series.str.split('')
[, 2, 3, 4, 2, ]
[, 8, 4, 7, 5, ]
[, 5, 8, 7, 3, ]
dtype: object

What a good approach to this? Is there a method or function that should be
handling this?

Thanks so much!

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


Re: Is there a way to subtract 3 from every digit of a number?

2021-02-21 Thread C W
Thanks so much everyone, I appreciate it!

Ming, your solution is awesome. More importantly, very clear explanations
on how and why. So, I appreciate that.

Thanks again, cheers!

Mike

On Sun, Feb 21, 2021 at 12:08 AM <2qdxy4rzwzuui...@potatochowder.com> wrote:

> On 2021-02-20 at 20:49:15 -0800,
> Dan Stromberg  wrote:
>
> > On Sat, Feb 20, 2021 at 7:13 PM Ming  wrote:
> >
> > > I just wrote a very short code can fulfill your needs:
> > >
> > > a = 2342
> > > b = int("".join(map(lambda x: str((int(x)-3)%10) ,list(str(a)
> > >
> > I tend to favor plenty of temporary variables with descriptive names, but
> > this is indeed short.
> >
> > Apart from that, you may find that using a generator expression is
> shorter
> > and clearer than map+lambda.  It should allow to additionally eliminate
> the
> > list conversion.
> >
> > So in the terse form you've got there, it'd be more like:
> > b =  int(''.join(str((int(x) - 3) % 10) for x in str(a))
> >
> > But in real life, I'd try to use descriptive variable names for some of
> the
> > subexpressions in that.  This makes reading and debugging simpler, which
> is
> > important because the maintenance phase of software is almost always much
> > longer and costly than the development phase.  And although you could do
> a
> > generator expression for each of the different parts of (int(x) - 3) %
> 10,
> > I kinda like having a named function for just that piece.
> >
> > So maybe:
> >   def rot_3(character):
> >   """Convert to int, subtract 3 and mod 10."""
> >   digit = int(character)
> >   assert 0 <= digit <= 9
> >   return (digit - 3) % 10
> >
> >
> >   def descriptive_minus_three_caesar(input_number):
> >   """Convert to a -3 caesar cypher on an integer."""
> >   string_number = str(input_number)
> >   rotated_digits = (rot_3(character) for character in string_number)
> >   output_string = ''.join(str(digit) for digit in rotated_digits)
> >   output_number = int(output_string)
> >   return output_number
>
> >>> descriptive_minus_three_caesar('38')
> 5
>
> The problem is underspecified, and the examples are lacking, but based
> on the phrase "each digit" and the examples that contain a 3, I'd prefer
> to see "38" become "05."
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Is there a way to subtract 3 from every digit of a number?

2021-02-21 Thread C W
I do want to follow up, if I may. In Ming's example,

a = 2342
b = int("".join(map(lambda x: str((int(x)-3)%10) ,list(str(a)

What's the best approach to apply to a dataframe column, rather than just
one value?  Here's my attempt using df[col_1''].apply(),
df['col_1'].apply(lambda:a int("".join(map(lambda x: str((int(x)-3)%10)
,list(str(a))

Thanks!

On Sun, Feb 21, 2021 at 9:12 AM C W  wrote:

> Thanks so much everyone, I appreciate it!
>
> Ming, your solution is awesome. More importantly, very clear explanations
> on how and why. So, I appreciate that.
>
> Thanks again, cheers!
>
> Mike
>
> On Sun, Feb 21, 2021 at 12:08 AM <2qdxy4rzwzuui...@potatochowder.com>
> wrote:
>
>> On 2021-02-20 at 20:49:15 -0800,
>> Dan Stromberg  wrote:
>>
>> > On Sat, Feb 20, 2021 at 7:13 PM Ming  wrote:
>> >
>> > > I just wrote a very short code can fulfill your needs:
>> > >
>> > > a = 2342
>> > > b = int("".join(map(lambda x: str((int(x)-3)%10) ,list(str(a)
>> > >
>> > I tend to favor plenty of temporary variables with descriptive names,
>> but
>> > this is indeed short.
>> >
>> > Apart from that, you may find that using a generator expression is
>> shorter
>> > and clearer than map+lambda.  It should allow to additionally eliminate
>> the
>> > list conversion.
>> >
>> > So in the terse form you've got there, it'd be more like:
>> > b =  int(''.join(str((int(x) - 3) % 10) for x in str(a))
>> >
>> > But in real life, I'd try to use descriptive variable names for some of
>> the
>> > subexpressions in that.  This makes reading and debugging simpler,
>> which is
>> > important because the maintenance phase of software is almost always
>> much
>> > longer and costly than the development phase.  And although you could
>> do a
>> > generator expression for each of the different parts of (int(x) - 3) %
>> 10,
>> > I kinda like having a named function for just that piece.
>> >
>> > So maybe:
>> >   def rot_3(character):
>> >   """Convert to int, subtract 3 and mod 10."""
>> >   digit = int(character)
>> >   assert 0 <= digit <= 9
>> >   return (digit - 3) % 10
>> >
>> >
>> >   def descriptive_minus_three_caesar(input_number):
>> >   """Convert to a -3 caesar cypher on an integer."""
>> >   string_number = str(input_number)
>> >   rotated_digits = (rot_3(character) for character in string_number)
>> >   output_string = ''.join(str(digit) for digit in rotated_digits)
>> >   output_number = int(output_string)
>> >   return output_number
>>
>> >>> descriptive_minus_three_caesar('38')
>> 5
>>
>> The problem is underspecified, and the examples are lacking, but based
>> on the phrase "each digit" and the examples that contain a 3, I'd prefer
>> to see "38" become "05."
>> --
>> https://mail.python.org/mailman/listinfo/python-list
>>
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Is there a way to subtract 3 from every digit of a number?

2021-02-21 Thread C W
I got it to work! I defined a separate function, and put it into
df['col_1'].apply().

Not the most elegant, but it worked. I'm also curious how people on this
mailing list would do it.

Cheers!

On Sun, Feb 21, 2021 at 9:21 AM C W  wrote:

> I do want to follow up, if I may. In Ming's example,
>
> a = 2342
> b = int("".join(map(lambda x: str((int(x)-3)%10) ,list(str(a)
>
> What's the best approach to apply to a dataframe column, rather than just
> one value?  Here's my attempt using df[col_1''].apply(),
> df['col_1'].apply(lambda:a int("".join(map(lambda x: str((int(x)-3)%10)
> ,list(str(a))
>
> Thanks!
>
> On Sun, Feb 21, 2021 at 9:12 AM C W  wrote:
>
>> Thanks so much everyone, I appreciate it!
>>
>> Ming, your solution is awesome. More importantly, very clear explanations
>> on how and why. So, I appreciate that.
>>
>> Thanks again, cheers!
>>
>> Mike
>>
>> On Sun, Feb 21, 2021 at 12:08 AM <2qdxy4rzwzuui...@potatochowder.com>
>> wrote:
>>
>>> On 2021-02-20 at 20:49:15 -0800,
>>> Dan Stromberg  wrote:
>>>
>>> > On Sat, Feb 20, 2021 at 7:13 PM Ming  wrote:
>>> >
>>> > > I just wrote a very short code can fulfill your needs:
>>> > >
>>> > > a = 2342
>>> > > b = int("".join(map(lambda x: str((int(x)-3)%10) ,list(str(a)
>>> > >
>>> > I tend to favor plenty of temporary variables with descriptive names,
>>> but
>>> > this is indeed short.
>>> >
>>> > Apart from that, you may find that using a generator expression is
>>> shorter
>>> > and clearer than map+lambda.  It should allow to additionally
>>> eliminate the
>>> > list conversion.
>>> >
>>> > So in the terse form you've got there, it'd be more like:
>>> > b =  int(''.join(str((int(x) - 3) % 10) for x in str(a))
>>> >
>>> > But in real life, I'd try to use descriptive variable names for some
>>> of the
>>> > subexpressions in that.  This makes reading and debugging simpler,
>>> which is
>>> > important because the maintenance phase of software is almost always
>>> much
>>> > longer and costly than the development phase.  And although you could
>>> do a
>>> > generator expression for each of the different parts of (int(x) - 3) %
>>> 10,
>>> > I kinda like having a named function for just that piece.
>>> >
>>> > So maybe:
>>> >   def rot_3(character):
>>> >   """Convert to int, subtract 3 and mod 10."""
>>> >   digit = int(character)
>>> >   assert 0 <= digit <= 9
>>> >   return (digit - 3) % 10
>>> >
>>> >
>>> >   def descriptive_minus_three_caesar(input_number):
>>> >   """Convert to a -3 caesar cypher on an integer."""
>>> >   string_number = str(input_number)
>>> >   rotated_digits = (rot_3(character) for character in
>>> string_number)
>>> >   output_string = ''.join(str(digit) for digit in rotated_digits)
>>> >   output_number = int(output_string)
>>> >   return output_number
>>>
>>> >>> descriptive_minus_three_caesar('38')
>>> 5
>>>
>>> The problem is underspecified, and the examples are lacking, but based
>>> on the phrase "each digit" and the examples that contain a 3, I'd prefer
>>> to see "38" become "05."
>>> --
>>> https://mail.python.org/mailman/listinfo/python-list
>>>
>>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Is there a way to subtract 3 from every digit of a number?

2021-02-21 Thread C W
Hey Avi,

I am a long time R user now using Python. So, this is my attempt to master
the language.

The problem for me is that I often have an idea about how things are done
in R, but not sure to what functions are available in Python.

I hope that clears up some confusion.

Cheer!

On Sun, Feb 21, 2021 at 9:44 AM Chris Angelico  wrote:

> On Mon, Feb 22, 2021 at 1:39 AM Avi Gross via Python-list
>  wrote:
> > But you just moved the goalpost by talking about using a data.frame as
> that
> > (and I assume numpy and pandas) are not very basic Python.
>
> Given that the original post mentioned a pd.Series, I don't know how
> far the goalposts actually moved :)
>
> ChrisA
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Fwd: Error message

2016-11-10 Thread Keenan C
To whom this may concern,

I am continuously receiving this error after the installation of Python
3.5.2.  The purpose of using this program is for a class I am currently
enrolled in at a University.  (I am running Windows 7 Home Premium 64-bit
paired with an i3-2100 processor and 6 gb of ram.  I don't believe the
specifications are a problems but I have listed them just in case.)
 Although this computer is not new, it has recently been factory reset.  I
have tried multiple times installing and uninstalling this program and
restarting the computer.  If you would be able to help me figure this out,
I would very much appreciate it.

Thank you,
Keenan Chu
[image: Inline image 1]
-- 
https://mail.python.org/mailman/listinfo/python-list


How to properly retrieve data using requests + bs4 from multiple pages in a site?

2016-12-01 Thread Juan C.
I'm a student and my university uses Moodle as their learning management
system (LMS). They don't have Moodle Web Services enabled and won't be
enabling it anytime soon, at least for students. The university programs
have the following structure, for example:

1. Bachelor's Degree in Computer Science (duration: 8 semesters)

1.1. Unit 01: Mathematics Fundamental (duration: 1 semester)
1.1.1. Algebra I (first 3 months)
1.1.2. Algebra II (first 3 months)
1.1.3. Calculus I (last 3 months)
1.1.4. Calculus II (last 3 months)
1.1.5. Unit Project (throughout the semester)

1.2. Unit 02: Programming (duration: 1 semester)
1.2.1. Programming Logic (first 3 months)
1.2.2. Data Modelling with UML (first 3 months)
1.2.3. Python I (last 3 months)
1.2.4. Python II (last 3 months)
1.2.5. Unit Project (throughout the semester)

Each course/project have a bunch of assignments + one final assignment.
This goes on, totalizing 8 (eight) units, which will make up for a 4-year
program. I'm building my own client-side Moodle API to be consumed by my
scripts. Currently I'm using 'requests' + 'bs4' to do the job. My code:

package moodle/

user.py

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

from .program import Program
import requests


class User:
   _AUTH_URL = 'http://lms.university.edu/moodle/login/index.php'

   def __init__(self, username, password, program_id):
  self.username = username
  self.password = password
  session = requests.session()
  session.post(self._AUTH_URL, {"username": username, "password":
password})
  self.program = Program(program_id=program_id, session=session)

   def __str__(self):
  return self.username + ':' + self.password

   def __repr__(self):
  return '' % self.username

   def __eq__(self, other):
  if isinstance(other, self):
 return self.username == other.username
  else:
 return False

==

program.py

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

from .unit import Unit
from bs4 import BeautifulSoup


class Program:
   _PATH = 'http://lms.university.edu/moodle/course/index.php?categoryid='

   def __init__(self, program_id, session):
  response = session.get(self._PATH + str(program_id))
  soup = BeautifulSoup(response.text, 'html.parser')

  self.name = soup.find('ul',
class_='breadcrumb').find_all('li')[-2].text.replace('/', '').strip()
  self.id = program_id
  self.units = [Unit(int(item['data-categoryid']), session) for item in
soup.find_all('div', {'class': 'category'})]

   def __str__(self):
  return self.name

   def __repr__(self):
  return '' % (self.name, self.id)

   def __eq__(self, other):
  if isinstance(other, self):
 return self.id == other.id
  else:
 return False

==

unit.py

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

from .course import Course
from bs4 import BeautifulSoup


class Unit:
   _PATH = 'http://lms.university.edu/moodle/course/index.php?categoryid='

   def __init__(self, unit_id, session):
  response = session.get(self._PATH + str(unit_id))
  soup = BeautifulSoup(response.text, 'html.parser')

  self.name = soup.find('ul',
class_='breadcrumb').find_all('li')[-1].text.replace('/', '').strip()
  self.id = unit_id
  self.courses = [Course(int(item['data-courseid']), session) for item
in soup.find_all('div', {'class': 'coursebox'})]

   def __str__(self):
  return self.name

   def __repr__(self):
  return '' % (self.name, self.id)

   def __eq__(self, other):
  if isinstance(other, self):
 return self.id == other.id
  else:
 return False

==

course.py

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


from .assignment import Assignment
import re
from bs4 import BeautifulSoup


class Course:
   _PATH = 'http://lms.university.edu/moodle/course/view.php?id='

   def __init__(self, course_id, session):
  response = session.get(self._PATH + str(course_id))
  soup = BeautifulSoup(response.text, 'html.parser')

  self.name = soup.find('h1').text
  self.id = course_id
  self.assignments = [Assignment(int(item['href'].split('id=')[-1]),
session) for item in
 soup.find_all('a', href=re.compile(r'http://lms
\.university\.edu/moodle/mod/assign/view.php\?id=.*'))]

   def __str__(self):
  return self.name

   def __repr__(self):
  return '' % (self.name, self.id)

   def __eq__(self, other):
  if isinstance(other, self):
 return self.id == other.id
  else:
 return False

==

assignment.py

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

from bs4 import BeautifulSoup


class Assignment:
   _PATH = 'http://lms.university.edu/moodle/mod/assign/view.php?id='

   def __init__(self, assignment_id, session):
  response = session.get(self._PATH + str(assignment_id))
  soup = BeautifulSoup(response.text, 'html.parser')

  self.name = soup.find('h2').text
  self.id = assignment_id
  self.sent = soup.find('td', {'

Re: How to properly retrieve data using requests + bs4 from multiple pages in a site?

2016-12-03 Thread Juan C.
On Thu, Dec 1, 2016 at 10:07 PM, Juan C.  wrote:
> It works, but it has a big issue: it gets all data from all
units/courses/assignments at the same time, and this isn't very useful as I
don't care about data from units from 1-2 years ago. How can I change the
logic so it just gets the data I need at a given moment? For example, I may
need to dump data for an entire unit, or just one course, or maybe even
just one assignment. How can I achieve this behavior? Another "issue", I
feel like handing my 'session' that I instantiated at user.py to program,
then unit, then course and then assignment is a poor design, how can I make
it better?
>
> Any other suggestions are welcome.

Oh, forgot to tell, I'm using Python 3.5.2 x64.
-- 
https://mail.python.org/mailman/listinfo/python-list


The right way to 'call' a class attribute inside the same class

2016-12-11 Thread Juan C.
I'm watching a Python course and was presented a topic regarding classes.
One of the examples were:

box.py

class Box:
serial = 100

def __init__(self, from_addr, to_addr):
self.from_addr = from_addr
self.to_addr = to_addr
self.serial = Box.serial
Box.serial += 1


from box import *

a = Box('19 Beech Ave. Seattle, WA 98144', '49 Carpenter Street North
Brunswick, NJ 08902')
b = Box('68 N. Church Dr. Vicksburg, MS 39180', '8 Lake Forest Road
Princeton, NJ 08540')

print(a.serial)  # print: 100
print(b.serial)  # print: 101
print(Box.serial)  # print: 102


The instructor said that the right way to call a class attribute is to use
'Class.class_attr' notation, but on the web I found examples where people
used 'self.class_attr' to call class attributes. I believe that using the
first notation is better ('Class.class_attr'), this way the code is more
explicit, but is there any rules regarding it?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: The right way to 'call' a class attribute inside the same class

2016-12-12 Thread Juan C.
On Sun, Dec 11, 2016 at 11:34 PM, Steve D'Aprano
 wrote:

> So... in summary:
>
>
> When *assigning* to an attribute:
>
> - use `self.attribute = ...` when you want an instance attribute;
>
> - use `Class.attribute = ...` when you want a class attribute in
>   the same class regardless of which subclass is being used;
>
> - use `type(self).attribute = ...` when you want a class attribute
>   in a subclass-friendly way.
>
>
> When *retrieving* an attribute:
>
> - use `self.attribute` when you want to use the normal inheritance
>   rules are get the instance attribute if it exists, otherwise a
>   class or superclass attribute;
>
> - use `type(self).attribute` when you want to skip the instance
>   and always return the class or superclass attribute.

Thanks, that seems simple enough.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: The right way to 'call' a class attribute inside the same class

2016-12-12 Thread Juan C.
On Mon, Dec 12, 2016 at 12:34 PM, Thomas 'PointedEars' Lahn
 wrote:
> First of all, the proper term for what you are doing there is _not_ “call”;
> you are _accessing_ an attribute instead.

Indeed, `accessing` seems better. I was looking for a better word but
couldn't find at the moment.

> To call something means generally in programming, and in Python, to execute
> it as a function instead: In the code above, the class object referred to by
> “Box” is called twice in order to instantiate twice (calling a class object
> in Python means to instantiate it, implicitly calling its constructor
> method, “__init__”, if any), and the global “print” function is called three
> times.

Since we are talking about Python terminology I believe that calling
`__init__` a constructor is also wrong. I've already seem some
discussions regarding it and the general consensus is that `__init__`
shouldn't be called constructor as it isn't really a constructor (like
Java/C# constructors). Some source:

- 
http://stackoverflow.com/questions/4859129/python-and-python-c-api-new-versus-init
- http://stackoverflow.com/questions/674304/pythons-use-of-new-and-init
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: The right way to 'call' a class attribute inside the same class

2016-12-12 Thread Juan C.
On Mon, Dec 12, 2016 at 6:59 PM, Thomas 'PointedEars' Lahn
 wrote:
> <https://docs.python.org/3/reference/datamodel.html?highlight=__init__#object.__init__>

Using the Python official doc link you provided, it clearly states
that `__new__` is the one called to "create a new instance of class
[...] The return value of __new__() should be the new object instance
(usually an instance of cls)." On the other hand, `__init__` is
"called after the instance has been created (by __new__()), but before
it is returned to the caller."

Here we have the same mindset regarding `__new__` vs `__init__`:

- http://python-textbok.readthedocs.io/en/1.0/Classes.html
"Note: __init__ is sometimes called the object’s constructor, because
it is used similarly to the way that constructors are used in other
languages, but that is not technically correct – it’s better to call
it the initialiser. There is a different method called __new__ which
is more analogous to a constructor, but it is hardly ever used."

- http://www.python-course.eu/python3_object_oriented_programming.php
"We want to define the attributes of an instance right after its
creation. __init__ is a method which is immediately and automatically
called after an instance has been created. [...] The __init__ method
is used to initialize an instance."

- https://en.wikipedia.org/wiki/Constructor_(object-oriented_programming)#Python
"In Python, constructors are defined by one or both of __new__ and
__init__ methods. A new instance is created by calling the class as if
it were a function, which calls the __new__ and __init__ methods. If a
constructor method is not defined in the class, the next one found in
the class's Method Resolution Order will be called."

- http://www.diveintopython3.net/iterators.html
"The __init__() method is called immediately after an instance of the
class is created. It would be tempting — but technically incorrect —
to call this the “constructor” of the class. It’s tempting, because it
looks like a C++ constructor (by convention, the __init__() method is
the first method defined for the class), acts like one (it’s the first
piece of code executed in a newly created instance of the class), and
even sounds like one. Incorrect, because the object has already been
constructed by the time the __init__() method is called, and you
already have a valid reference to the new instance of the class."


In general, the idea is simple, `__new__` constructs and `__init__`
initializes, this is what I believe in, after all the name `__init__`
already tell us that it's a *init* ialiser...
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Python constructors have particular semantics, and ‘Foo.__init__’ doesn't qualify (was: The right way to 'call' a class attribute inside the same class)

2016-12-12 Thread Juan C.
I agree with you, I'll post here the same thing I said in there for
another member:

On Mon, Dec 12, 2016 at 6:59 PM, Thomas 'PointedEars' Lahn
 wrote:
> <https://docs.python.org/3/reference/datamodel.html?highlight=__init__#object.__init__>
>

Using the Python official doc link you provided, it clearly states
that `__new__` is the one called to "create a new instance of class
[...] The return value of __new__() should be the new object instance
(usually an instance of cls)."

On the other hand, `__init__` is "called after the instance has been
created (by __new__()), but before it is returned to the caller."

Here we have the same mindset regarding `__new__` vs `__init__`:

- http://python-textbok.readthedocs.io/en/1.0/Classes.html
"Note: __init__ is sometimes called the object’s constructor, because
it is used similarly to the way that constructors are used in other
languages, but that is not technically correct – it’s better to call
it the initialiser. There is a different method called __new__ which
is more analogous to a constructor, but it is hardly ever used."

- http://www.python-course.eu/python3_object_oriented_programming.php
"We want to define the attributes of an instance right after its
creation. __init__ is a method which is immediately and automatically
called after an instance has been created. [...] The __init__ method
is used to initialize an instance."

- https://en.wikipedia.org/wiki/Constructor_(object-oriented_programming)#Python
"In Python, constructors are defined by one or both of __new__ and
__init__ methods. A new instance is created by calling the class as if
it were a function, which calls the __new__ and __init__ methods. If a
constructor method is not defined in the class, the next one found in
the class's Method Resolution Order will be called."

- http://www.diveintopython3.net/iterators.html
"The __init__() method is called immediately after an instance of the
class is created. It would be tempting — but technically incorrect —
to call this the “constructor” of the class. It’s tempting, because it
looks like a C++ constructor (by convention, the __init__() method is
the first method defined for the class), acts like one (it’s the first
piece of code executed in a newly created instance of the class), and
even sounds like one. Incorrect, because the object has already been
constructed by the time the __init__() method is called, and you
already have a valid reference to the new instance of the class."

In general, the idea is simple, `__new__` constructs and `__init__`
initializes, this is what I believe in, after all the name `__init__`
already tell us that it's a *init* ialiser...

It doesn't matter if Java, C#, Javascript,  have
different approaches, I'm programming (or at least, trying to :p) in
Python, so I'll follow what the official doc and the vast majority of
books/courses/etc say.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Choosing a Python IDE. what is your Pythonish recommendation? I do not know what to choose.

2017-01-02 Thread Juan C.
On Mon, Jan 2, 2017 at 9:38 AM, Antonio Caminero Garcia <
tonycam...@gmail.com> wrote:
> The thing with the from-the-scratch full featured IDEs (Eclipse,
IntelliJ, Pycharm) is that they look like a space craft dashboard and that
unwarranted resources consumption and the unnecessary icons. I want my IDE
to be minimalistic but powerful. My screen should be mostly “made of code”
as usually happens in Vim, Sublime or Atom. However, Pycharm is really cool
and python oriented.

I use Sublime Text for small scripts and PyCharm Professional for bigger
projects and I don't find it resource heavy and the interface is simple
enough. You can pretty much hide all menus and sidebars on PyCharm and
you'd get pure code (it also has a "Distraction Free" mode), I suggest you
to read Pycharm's official doc to know a little more about it. My advice is
to NOT overthink it. IDEs and code editor are just tools, just pick one you
like and you're done.
-- 
https://mail.python.org/mailman/listinfo/python-list


What are your opinions on .NET Core vs Python?

2017-01-28 Thread Juan C.
As you guys might know, .NET Core is up and running, promising a
"cross-platform, unified, fast, lightweight, modern and open source
experience" (source: .NET Core official site). What do you guys think about
it? Do you think it will be able to compete with and overcome Python in the
opensource medium?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: What are your opinions on .NET Core vs Python?

2017-01-30 Thread Juan C.
On Sun, Jan 29, 2017 at 1:06 AM, Juan C.  wrote:
>
> As you guys might know, .NET Core is up and running, promising a 
> "cross-platform, unified, fast, lightweight, modern and open source 
> experience" (source: .NET Core official site). What do you guys think about 
> it? Do you think it will be able to compete with and overcome Python in the 
> opensource medium?

Oh, I forgot to say, I was indeed talking about .NET Core in general,
the framework, but I also had C#/ASP .NET Core in mind. The real
comparison here would be C#/ASP .NET Core vs Python/Django,Flask. I
personally had to work with C# a few times, it's a great language, but
my main problem was that it was Windows only and most of my personal
programs run on Linux. Yes, we have Mono, but it really didn't feel
"right" to me, it seemed like a workaround, I wanted something really
"native".

Python still has my heart, but .NET Core tempts me. One great thing of
coding in C# would be no GIL.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: What library/package to use for parsing XML?

2017-01-30 Thread Juan C.
On Mon, Jan 30, 2017 at 3:58 PM, Chris Green  wrote:
> I want to parse some XML data, it's the address book data from the
> linux program osmo.  The file I want to parse is like this:-

Just like Irmen said, use the default xml.etree.ElementTree, it's
amazing and very simple to use.
-- 
https://mail.python.org/mailman/listinfo/python-list


Which part of the loop is it going through in this class frame?

2018-03-07 Thread C W
Hello,

I am new to OOP. I'm a bit confused about the following code.

class Clock(object):
def __init__(self, time):
self.time = time
def print_time(self):
time = '6:30'
print(self.time)

clock = Clock('5:30')
clock.print_time()
5:30

I set time to 6:30, but it's coming out to 5:30. I guess it's because I
passed in 5:30, so, it's replaced?

How does line-by-line execution run inside a frame? How does __init__ work?
I understand you must have __init__. Is it run before print_time(), if so,
why don't I just set self.time = '6:30' instead of self.time = time?

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


Re: Which part of the loop is it going through in this class frame?

2018-03-08 Thread C W
Thank you guys, lots of great answers, very helpful. I got it!

A follow-up question:

How did the value of "object" get passed to "time"? Obviously, they have
different names. How did Python make that connection?

Code is below for convenience.

class Clock(object):
def __init__(self, time):
self.time = time
def print_time(self):
time = '6:30'
print(self.time)

clock = Clock('5:30')
clock.print_time()
5:30


Thank you!

On Thu, Mar 8, 2018 at 6:30 AM, Steven D'Aprano <
steve+comp.lang.pyt...@pearwood.info> wrote:

> On Wed, 07 Mar 2018 16:57:51 -0500, C W wrote:
>
> > Hello,
> >
> > I am new to OOP. I'm a bit confused about the following code.
> >
> > class Clock(object):
> > def __init__(self, time):
> > self.time = time
>
> Here you set the instance attribute "self.time".
>
> > def print_time(self):
> > time = '6:30'
> > print(self.time)
>
> Here you set the local variable "time", which is completely unrelated to
> the attribute "self.time".
>
> If you are used to languages where "foo" inside a method is a short-cut
> for "self.foo" or "this.foo", Python does not do that. Local variables
> and instance attributes are distinct concepts, and Python keeps them
> distinct.
>
>
> > How does line-by-line execution run inside a frame?
>
> There isn't actually line-by-line execution as such, although it can be
> very similar. Before the interpreter runs Python code, it compiles it to
> byte-code, and then runs the byte-code. A single line of source code
> could result in any number of lines of byte code, from zero to an
> unlimited number.
>
> > How does __init__
> > work? I understand you must have __init__.
>
> You understand wrongly then :-)
>
> It is normal and common to have an __init__ method, but it is not
> compulsory. If your class doesn't need one, you don't need to write it.
>
> The __init__ method is the initialiser. Think of it as very similar to
> the constructor in some other languages, and for now the differences
> aren't important. The usual purpose of the __init__ method is to
> initialise the instance and set any attributes needed.
>
> > Is it run before print_time(),
>
> The __init__ method is called once, when the instance is first created.
> So the short answer is, yes, it will run before print_time(). But only
> once.
>
> > if so, why don't I just set self.time = '6:30' instead of
> > self.time = time?
>
> Because then every instance will be set to 6:30, instead of letting you
> set each instance to a different time.
>
>
>
> --
> Steve
>
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


How to fill in a dictionary with key and value from a string?

2018-03-30 Thread C W
Hello all,

I want to create a dictionary.

The keys are 26 lowercase letters. The values are 26 uppercase letters.

The output should look like:
{'a': 'A', 'b': 'B',...,'z':'Z' }

I know I can use string.ascii_lowercase and string.ascii_uppercase, but how
do I use it exactly?
I have tried the following to create the keys:

myDict = {}
for e in string.ascii_lowercase:
myDict[e]=0

But, how to fill in the values? Can I do myDict[0]='A', myDict[1]='B', and
so on?

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


Re: How to fill in a dictionary with key and value from a string?

2018-04-01 Thread C W
Thank you all for the response.

What if I have myDict = {'a': 'B', 'b': 'C',...,'z':'A' }? So now, the
values are shift by one position.

key:abcdefghijklmnopqrstuvwxyz
value: BCDEFGHIJKLMNOPQRSTUVWXYZA

Can I fill in a key and its corresponding value simultaneously on the fly?

Something in the following structure.

myDict = {}
for i in range(26):
   myDict[lowercase] = uppercase

Thank you!

On Sun, Apr 1, 2018 at 1:13 PM, Chris Angelico  wrote:

> On Mon, Apr 2, 2018 at 3:03 AM, Rustom Mody  wrote:
> > On Saturday, March 31, 2018 at 4:30:04 PM UTC+5:30, bartc wrote:
> >> On 30/03/2018 21:13, C W wrote:
> >> > Hello all,
> >> >
> >> > I want to create a dictionary.
> >> >
> >> > The keys are 26 lowercase letters. The values are 26 uppercase
> letters.
> >> >
> >> > The output should look like:
> >> > {'a': 'A', 'b': 'B',...,'z':'Z' }
> >>
> >> > I know I can use string.ascii_lowercase and string.ascii_uppercase,
> but how
> >> > do I use it exactly?
> >> > I have tried the following to create the keys:
> >> > myDict = {}
> >> >  for e in string.ascii_lowercase:
> >> >  myDict[e]=0
> >>
> >> If the input string S is "cat" and the desired output is {'c':'C',
> >> 'a':'A', 't':'T'}, then the loop might look like this:
> >>
> >> D = {}
> >> for c in S:
> >> D[c] = c.upper()
> >>
> >> print (D)
> >>
> >> Output:
> >>
> >> {'c': 'C', 'a': 'A', 't': 'T'}
> >
> > As does…
> >>>> {c: c.upper() for c in s}
> > {'a': 'A', 'c': 'C', 't': 'T'} : dict
> >
> > [Recent pythons; not sure when dict-comprehensions appeared]
>
> 3.0, and also backported to 2.7. So go ahead and use 'em.
>
> https://www.python.org/dev/peps/pep-0274/
>
> ChrisA
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How to fill in a dictionary with key and value from a string?

2018-04-01 Thread C W
A different but related question:

myDict = dict(zip(string.ascii_lowercase + string.ascii_uppercase,
string.ascii_lowercase + string.ascii_uppercase))
>myDict
{'A': 'A', 'B': 'B', 'C': 'C',...,'w': 'w', 'x': 'x', 'y': 'y', 'z': 'z'}

Why are the keys sorted from upper case to lower case? I asked for lower
case first, then upper case.



On Sun, Apr 1, 2018 at 8:52 PM, C W  wrote:

> Thank you all for the response.
>
> What if I have myDict = {'a': 'B', 'b': 'C',...,'z':'A' }? So now, the
> values are shift by one position.
>
> key:abcdefghijklmnopqrstuvwxyz
> value: BCDEFGHIJKLMNOPQRSTUVWXYZA
>
> Can I fill in a key and its corresponding value simultaneously on the fly?
>
> Something in the following structure.
>
> myDict = {}
> for i in range(26):
>myDict[lowercase] = uppercase
>
> Thank you!
>
> On Sun, Apr 1, 2018 at 1:13 PM, Chris Angelico  wrote:
>
>> On Mon, Apr 2, 2018 at 3:03 AM, Rustom Mody 
>> wrote:
>> > On Saturday, March 31, 2018 at 4:30:04 PM UTC+5:30, bartc wrote:
>> >> On 30/03/2018 21:13, C W wrote:
>> >> > Hello all,
>> >> >
>> >> > I want to create a dictionary.
>> >> >
>> >> > The keys are 26 lowercase letters. The values are 26 uppercase
>> letters.
>> >> >
>> >> > The output should look like:
>> >> > {'a': 'A', 'b': 'B',...,'z':'Z' }
>> >>
>> >> > I know I can use string.ascii_lowercase and string.ascii_uppercase,
>> but how
>> >> > do I use it exactly?
>> >> > I have tried the following to create the keys:
>> >> > myDict = {}
>> >> >  for e in string.ascii_lowercase:
>> >> >  myDict[e]=0
>> >>
>> >> If the input string S is "cat" and the desired output is {'c':'C',
>> >> 'a':'A', 't':'T'}, then the loop might look like this:
>> >>
>> >> D = {}
>> >> for c in S:
>> >> D[c] = c.upper()
>> >>
>> >> print (D)
>> >>
>> >> Output:
>> >>
>> >> {'c': 'C', 'a': 'A', 't': 'T'}
>> >
>> > As does…
>> >>>> {c: c.upper() for c in s}
>> > {'a': 'A', 'c': 'C', 't': 'T'} : dict
>> >
>> > [Recent pythons; not sure when dict-comprehensions appeared]
>>
>> 3.0, and also backported to 2.7. So go ahead and use 'em.
>>
>> https://www.python.org/dev/peps/pep-0274/
>>
>> ChrisA
>> --
>> https://mail.python.org/mailman/listinfo/python-list
>>
>
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How to fill in a dictionary with key and value from a string?

2018-04-01 Thread C W
I am using Python 3.6. I ran the those lines and got a sorted dictionary by
keys.

On Sun, Apr 1, 2018 at 9:38 PM, Chris Angelico  wrote:

> On Mon, Apr 2, 2018 at 11:34 AM, C W  wrote:
> > A different but related question:
> >
> > myDict = dict(zip(string.ascii_lowercase + string.ascii_uppercase,
> > string.ascii_lowercase + string.ascii_uppercase))
> >>myDict
> > {'A': 'A', 'B': 'B', 'C': 'C',...,'w': 'w', 'x': 'x', 'y': 'y', 'z': 'z'}
> >
> > Why are the keys sorted from upper case to lower case? I asked for lower
> > case first, then upper case.
> >
>
> What version of which Python interpreter are you using? Dictionaries
> aren't sorted by definition, but sometimes they do retain order.
>
> ChrisA
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How to fill in a dictionary with key and value from a string?

2018-04-01 Thread C W
Thank you Steven. I am frustrated that I can't enumerate a dictionary by
position index.

Maybe I want to shift by 2 positions, 5 positions...

I want to know/learn how to manipulate dictionary with loop and by its
position location.



On Sun, Apr 1, 2018 at 10:02 PM, Steven D'Aprano <
steve+comp.lang.pyt...@pearwood.info> wrote:

> On Sun, 01 Apr 2018 20:52:35 -0400, C W wrote:
>
> > Thank you all for the response.
> >
> > What if I have myDict = {'a': 'B', 'b': 'C',...,'z':'A' }? So now, the
> > values are shift by one position.
> >
> > key:abcdefghijklmnopqrstuvwxyz
> > value: BCDEFGHIJKLMNOPQRSTUVWXYZA
> >
> > Can I fill in a key and its corresponding value simultaneously on the
> > fly?
>
> Of course.
>
> myDict = dict(zip("abcdefghijklmnopqrstuvwxyz",
> "BCDEFGHIJKLMNOPQRSTUVWXYZA"))
>
>
>
> --
> Steve
>
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How to fill in a dictionary with key and value from a string?

2018-04-01 Thread C W
Yes, you see right through me!

I was able to conquer it, there's probably better ways:
self.myDict = dict(zip(string.ascii_lowercase + string.ascii_uppercase,
string.ascii_lowercase[shift:26] + string.ascii_lowercase[:shift] +
string.ascii_uppercase[shift:26] + string.ascii_uppercase[:shift]))

How to debug a particular chunk of code?

Everything in OOP is self.myDict, self.shift_dict. So, I must run the
entire code to test.

I just want to try myDict('hello', 4), shift_dict(4), like how you would do
in C language.

Thank you!

On Sun, Apr 1, 2018 at 11:13 PM, Steven D'Aprano <
steve+comp.lang.pyt...@pearwood.info> wrote:

> On Sun, 01 Apr 2018 22:24:31 -0400, C W wrote:
>
> > Thank you Steven. I am frustrated that I can't enumerate a dictionary by
> > position index.
>
> Why do you care about position index?
>
> > Maybe I want to shift by 2 positions, 5 positions...
>
> Sounds like you are trying to program the Caesar Shift cipher, am I right?
>
> You probably should be manipulating *strings*, not dicts. Do these
> examples help?
>
> py> import string
> py> letters = string.ascii_lowercase
> py> letters
> 'abcdefghijklmnopqrstuvwxyz'
> py> letters[1:] + letters[:1]
> 'bcdefghijklmnopqrstuvwxyza'
> py> letters[5:] + letters[:5]
> 'fghijklmnopqrstuvwxyzabcde'
> py> letters[23:] + letters[:23]
> 'xyzabcdefghijklmnopqrstuvw'
>
>
> Slice your strings into the order that you want, then put them in a dict
> for fast lookups by character.
>
>
> > I want to know/learn how to manipulate dictionary with loop and by its
> > position location.
>
> Dict entries don't have a position location except by accident, or in
> sufficiently new versions of Python, by insertion order.
>
> If you want to process dict entries in a specific order, operate on the
> dict in whichever order you want:
>
> ordered_keys = 'azbycxdwevfugthsirjqkplomn'
> for k in ordered_keys:
> print(mydict[k])
>
>
> In Python 3.7, dicts will keep their insertion order, so long as you
> don't delete any keys.
>
>
>
> --
> Steve
>
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


In numpy, why is it ok to do matrix.mean(), but not ok to do matrix.median()?

2018-05-01 Thread C W
Hello everyone,

In numpy, why is it ok to do matrix.mean(), but not ok to do
matrix.median()? To me, they are two of many summary statistics. So, why
median() is different?

Here's an example code,

import numpy as np
matrix = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

# find the mean
np.mean(matrix)  # ok
matrix.mean()  # ok

# find the median
np.median(matrixA)  # ok
matrix.median()# throws error message


Also, why have two of the same thing: np.mean(matrix) and matrix.mean()?
When to use which one?

The documentation below looks almost identical! What am I missing here?
[1] Median documentation:
https://docs.scipy.org/doc/numpy-1.14.0/reference/generated/numpy.median.html
[2] Mean documentation:
https://docs.scipy.org/doc/numpy-1.14.0/reference/generated/numpy.mean.html


Thank you so much,

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


Re: In numpy, why is it ok to do matrix.mean(), but not ok to do matrix.median()?

2018-05-01 Thread C W
It's interesting how mean() can be implemented, but median() will break
other packages.

So, the default way in numpy is to use functions, not methods?

When I first learned Python, I was told to create an object and to play
around, there are methods for that object. List has list methods, tuple has
tuple methods, etc.

Now, the default way in numpy is to use function instead of methods? I'm
confused. What happened to object-oriented programming?

Thanks,

-M




On Tue, May 1, 2018 at 3:38 PM, Thomas Jollans  wrote:

> On 01/05/18 19:57, C W wrote:
> > matrix.median()# throws error message
>
> READ error messages. At the very least, quote error messages when asking
> questions somewhere like here. There I was, wondering why the numpy docs
> didn't mention ndarray.median when you were clearly using it...
>
> Anyway,
>
> > Hello everyone,
> >
> > In numpy, why is it ok to do matrix.mean(), but not ok to do
> > matrix.median()? To me, they are two of many summary statistics. So, why
> > median() is different?
>
> First, this is how it's different: the method ndarray.median simply does
> not exist.
>
> Now, of course, most numpy functions don't have method versions, so
> there's nothing special about median here. However, as you quite rightly
> point out, median would be "a good fit".
>
> As with most things that are "a bit odd" about numpy this probably boils
> to "historical reasons".
>
> numpy mostly goes back to an earlier package called "Numeric". Numeric's
> array did not have methods like mean(). Early (anno 2005) numpy also
> incorporated features from a package called "numarray"; one of these
> features were array methods like ".mean". numarray did not have a
> .median method, though it *did* have a function numarray.mlab.median. So
> far, so good. ndarray.mean *must* exist for compatibility reasons,
> ndarray.median need not.
>
> So why not add it later? Other methods have been added, after all. Well,
> for starters, "who cares?". Most of numpy is functions; the methods are
> nice, but not that important. The other obstacle is that numpy.median is
> implemented in Python, not in C. For historical reasons™, it has to stay
> that way. They tried to change it in 2014, but that broke some other
> packages...
>
>
> >
> > Here's an example code,
> >
> > import numpy as np
> > matrix = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
> >
> > # find the mean
> > np.mean(matrix)  # ok
> > matrix.mean()  # ok
> >
> > # find the median
> > np.median(matrixA)  # ok
>
> >
> >
> > Also, why have two of the same thing: np.mean(matrix) and matrix.mean()?
> > When to use which one?
> >
> > The documentation below looks almost identical! What am I missing here?
> > [1] Median documentation:
> > https://docs.scipy.org/doc/numpy-1.14.0/reference/
> generated/numpy.median.html
> > [2] Mean documentation:
> > https://docs.scipy.org/doc/numpy-1.14.0/reference/
> generated/numpy.mean.html
> >
> >
> > Thank you so much,
> >
> > M
> >
>
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: In numpy, why is it ok to do matrix.mean(), but not ok to do matrix.median()?

2018-05-02 Thread C W
Thanks, Chris. That makes sense. The len() example is great!

On Tue, May 1, 2018 at 10:37 PM, Chris Angelico  wrote:

> On Wed, May 2, 2018 at 12:22 PM, C W  wrote:
> > It's interesting how mean() can be implemented, but median() will break
> > other packages.
> >
> > So, the default way in numpy is to use functions, not methods?
> >
> > When I first learned Python, I was told to create an object and to play
> > around, there are methods for that object. List has list methods, tuple
> has
> > tuple methods, etc.
> >
> > Now, the default way in numpy is to use function instead of methods? I'm
> > confused. What happened to object-oriented programming?
>
> Even outside of numpy, a lot of Python uses functions, not methods.
> One good reason for this is that a function can accept a wide variety
> of data types as its argument; for instance, len() accepts many
> things, not just lists. Some things are done with methods, others with
> stand-alone functions. There are design choices each way.
>
> ChrisA
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


In Pandas, can you do groupby in on two different datasets?

2018-06-09 Thread C W
Dear all,
I want find the average ratings of movies by movieId. Below is
ratings.head() of the dataset.

> ratings.head()

userId  movieId  rating   timestamp parsed_time
0   12 3.5  1112486027 2005-04-02 23:53:47
1   1   29 3.5  1112484676 2005-04-02 23:31:16
2   1   32 3.5  1112484819 2005-04-02 23:33:39
3   1   47 3.5  1112484727 2005-04-02 23:32:07
4   1   50 3.5  1112484580 2005-04-02 23:29:40


I'm trying two methods:

Method 1 (makes sense)
> ratings[['movieId', 'rating']].groupby('rating').mean()
This returns dataframe, it's the most common.

Method 2 (confusing)
> ratings.rating.groupby(ratings.movieId).mean()

movieId
13.921240
23.211977
33.151040
42.861393
53.064592
Name: rating, dtype: float64



What going on in method 2? It's calling ratings dataset twice.
First in ratings.rating, it restricts the working dataset to only rating
column.
Then, it groups by ratings.movieId, but how does it know there is movieId.
Didn't we just restrict the data to rating column only?

Thanks in advance!
-- 
https://mail.python.org/mailman/listinfo/python-list


What data types does matplotlib pyplot take?

2018-06-13 Thread C W
Hi everyone,

I'm curious what data types pyplot takes. It seems that it can take numpy
series, pandas series, and possibly pandas dataframe? How many people data
types are out there? Is that true for all functions in like hist(), bar(),
line(), etc?

Is there an official documentation that lists this?

I have seen this official documentation:
https://pandas.pydata.org/pandas-docs/stable/visualization.html

But it does not specify data types. I would appreciate it if someone can
point it out.

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


Re: Python list vs google group

2018-06-15 Thread C W
I recently posted two questions, but never got any replies. I am still
wondering if it was ever posted, or maybe the question was too trivial?

I think someone would have at least shouted if it was too trivial or
off-topic, right?

On Fri, Jun 15, 2018 at 12:03 PM, Mark Lawrence 
wrote:

> On 15/06/18 16:47, T Berger wrote:
>
>> On Friday, June 15, 2018 at 11:31:47 AM UTC-4, Alister wrote:
>>
>> it certainly seems to be the source of most SPAM
>>> as such some users of this list/newsgroup call it what you like block all
>>> posts from google groups
>>>
>>
>> But you don't think you get more replies to a question posted here than
>> emailed to the list? The forum and the email list are supposed to be
>> different access routes to the same content, but I don't find that to be
>> the case. I replied to a post via email, but my reply did not show up on
>> this forum.
>>
>> Tamara
>>
>>
> For the third and final time, just get a (semi-)decent email client/news
> reader/whatever it's called, point it at news.gmane.org and read this
> forum, hundreds of other python forums and thousands of other technical
> forums with no problems at all.  No cluttered inbox so no need to filter
> anything.  I happen to use thunderbird, there are umpteen other choices.
>
> --
> 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
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Why list.reverse() modifies the list, but name.replace() does not modify the string?

2018-09-03 Thread C W
Hello all,

I am learning the basics of Python. How do I know when a method modifies
the original object, when it does not. I have to exmaples:
Example 1:
> L = [3, 6, 1,4]
> L.reverse()
> L
[4, 1, 6, 3]
This changes the original list.

Example 2:
> name = "John Smith"
> name.replace("J", j")
> name
'John Smith'
This does not change the original string.

Why the two examples produce different results? As a beginner, I find this
confusing. How do you do it?

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


Re: Why list.reverse() modifies the list, but name.replace() does not modify the string?

2018-09-03 Thread Mike C
Yes, I forgot that strings are immutable. I can't change anything in the 
string. Silly me!

Thank you very much, I appreciate it. I guess sometimes it just take an 
outsider to take you outside the box. And all is answered. :)


From: Python-list  on behalf 
of Mark Lawrence 
Sent: Monday, September 3, 2018 2:21:36 PM
To: python-list@python.org
Subject: Re: Why list.reverse() modifies the list, but name.replace() does not 
modify the string?

On 03/09/18 18:49, C W wrote:
> Hello all,
>
> I am learning the basics of Python. How do I know when a method modifies
> the original object, when it does not. I have to exmaples:
> Example 1:
>> L = [3, 6, 1,4]
>> L.reverse()
>> L
> [4, 1, 6, 3]
> This changes the original list.

Lists are mutable, i.e. can be changed, so it makes sense to do this
change in place.

>
> Example 2:
>> name = "John Smith"
>> name.replace("J", j")
>> name
> 'John Smith'
> This does not change the original string.

Strings are immutable, i.e. cannot be changed, so you have to create a
new string.  Your call to `replace` will do just that, but as it's not
saved `name` remains the same.  You could use

name = name.replace("J", j") or

newname = name.replace("J", j") as you see fit.

>
> Why the two examples produce different results? As a beginner, I find this
> confusing. How do you do it?
>
> Thank you!
>


--
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
-- 
https://mail.python.org/mailman/listinfo/python-list


Why list.reverse() modifies the list, but name.replace() does not

2018-09-05 Thread C W
Hello all,

I am learning the basics of Python. How do I know when a method modifies the
original object, when it does not. I have to exmaples: Example 1:
> L = [3, 6, 1,4]
> L.reverse()
> L
[4, 1, 6, 3]
This changes the original list.

Example 2:
> name = "John Smith"
> name.replace("J", j")
> name
'John Smith'
This does not change the original string.

Why the two examples produce different results? As a beginner, I find this
confusing. How do you do it?

Thank you!

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


Re: Why list.reverse() modifies the list, but name.replace() does not

2018-09-05 Thread Mike C
Yes, I forgot that strings are immutable. I can't change anything in the
string. Silly me!

Thank you very much, I appreciate it. I guess sometimes it just take an
outsider to take you outside the box. And all is answered. :)


From: Python-list  on behalf
of Mark Lawrence  Sent: Monday, September 3, 2018
2:21:36 PM To: python-list@python.org
Subject: Re: Why list.reverse() modifies the list, but name.replace() does not
modify the string?

On 03/09/18 18:49, C W wrote:
> Hello all,
>
> I am learning the basics of Python. How do I know when a method modifies
> the original object, when it does not. I have to exmaples:
> Example 1:
>> L = [3, 6, 1,4]
>> L.reverse()
>> L
> [4, 1, 6, 3]
> This changes the original list.

Lists are mutable, i.e. can be changed, so it makes sense to do this change in
place.

>
> Example 2:
>> name = "John Smith"
>> name.replace("J", j")
>> name
> 'John Smith'
> This does not change the original string.

Strings are immutable, i.e. cannot be changed, so you have to create a new
string.  Your call to `replace` will do just that, but as it's not saved `name`
 remains the same.  You could use

name = name.replace("J", j") or

newname = name.replace("J", j") as you see fit.

>
> Why the two examples produce different results? As a beginner, I find this
> confusing. How do you do it?
>
> Thank you!
>


--
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

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


Re: Overwhelmed by the Simplicity of Python. Any Recommendation?

2018-11-04 Thread Mike C
Same here. Debugging in Python is annoying, I like to step through my code line 
by line, it's impossible to do it with object-oriented programming language.

Also, there's no good REPL IDE.

Spyder barely works with some basic features. PyCharm, the most popular, takes 
too long to start, and you have to setup folders and directories EVERY SINGLE 
TIME at startup.



From: Python-list  on behalf 
of songbird 
Sent: Saturday, November 3, 2018 12:45:57 PM
To: python-list@python.org
Subject: Re: Overwhelmed by the Simplicity of Python. Any Recommendation?

Rhodri James wrote:
...
> I completely agree.  I too have come from a background in C, and still
> do most of my day job in C or assembler.  It took a while before I was
> writing idiomatic Python, never mind efficient Python (arguably I still
> don't, but as Rob says, who cares?).  Don't worry about it; at some
> point you will discover that the "obvious" Python you are writing looks
> a lot like the code you are looking at now and thinking "that's really
> clever, I'll never be able to to that."

  at this stage of my own process in learning, i'm
trying to read the FAQs i can find, any tutorials,
answers to specific questions on stackoverflow on
particular topics to see if i can understand the
issues, etc.

  as for my own code, yes, it's horrible at the
moment, but to me working code is always the
final arbitor.  i much prefer simple and stepwise
refinement if speed isn't the issue i think clarity
and simplicity is more important.

  speed is only more important for large projects
that process a ton of data.

  in 3-5yrs i expect to understand more of what
the theory and more conceptual things going on as
i read more of the history and how the language
has developed.

  i won't consider myself fluent until i start
"thinking" in it and can visualise the data
structures/objects in my head and such as i
currently do for C.


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


Logistic Regression Define X and Y for Prediction

2019-11-12 Thread Mike C
Hi All,
I have the below code.
X = df.iloc[:, [4, 403]].values​
y = df.iloc[:, 404].values

Dummy Data looks like:

host  Mnemonic
12.234.13.6   start
22.22.44.67   something
23.44.44.14   begin

When I define the X and Y values for prediction in the train and test data, 
should I capture all the columns that has been "OneHotEncoded" (that is all 
columns with 0 and 1) for the X and Y values???

import numpyas np
import pandas   as pd ​
import os
import matplotlib   as mpl ​
mpl.rcParams['figure.dpi'] = 400  ​
import matplotlib.pyplotas plt ​
​
# Importing the df​
# Importing the df​
os.chdir('c:\directory\data')# Location of data files​
df = pd.read_csv('blahblahfile.csv')​
 ​
from sklearn.preprocessing import LabelEncoder​
hostip = LabelEncoder()​
mnemonic = LabelEncoder()​
df['host_encoded'] = hostip.fit_transform(df.reported_hostname)​
df['mnemonic_encoded'] = mnemonic.fit_transform(df.mnemonic)​
​
from sklearn.preprocessing import OneHotEncoder​
hostip_ohe = OneHotEncoder()​
mnemonic_ohe = OneHotEncoder()​
X = hostip_ohe.fit_transform(df.host_encoded.values.reshape(-1,1)).toarray()​
Y = 
mnemonic_ohe.fit_transform(df.mnemonic_encoded.values.reshape(-1,1)).toarray()​

## Add back X and Y into the original dataframe​
dfOneHot = pd.DataFrame(X, columns = ["host_"+str(int(i)) for i in 
range(X.shape[1])])​
df = pd.concat([df, dfOneHot], axis=1)​
​
dfOneHot = pd.DataFrame(Y, columns = ["mnemonic_encoded"+str(int(i)) for i in 
range(Y.shape[1])])​
df = pd.concat([df, dfOneHot], axis=1)​
​
​ here is where I am not sure if all "host_" and "mnemonic_encoded" 
values assigned to X and Y
​
X = df.iloc[:, [4, 403]].values​
y = df.iloc[:, 404].values​
​
​
​
# Splitting the dataset into the Training set and Test set​
from sklearn.model_selection import train_test_split​
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.25, 
random_state = 0)​
​
​
# Feature Scaling​
from sklearn.preprocessing import StandardScaler​
sc = StandardScaler()​
X_train = sc.fit_transform(X_train)​
X_test = sc.transform(X_test)​
​
# Fitting Logistic Regression to the Training set​
from sklearn.linear_model import LogisticRegression​
classifier = LogisticRegression(random_state = 0)​
classifier.fit(X_train, y_train)​
​
# Predicting the Test set results​
y_pred = classifier.predict(X_test)​
​
# Making the Confusion Matrix​
from sklearn.metrics import confusion_matrix​
cm = confusion_matrix(y_test, y_pred)​
​
# Visualising the Training set results​
from matplotlib.colors import ListedColormap​
X_set, y_set = X_train, y_train​
X1, X2 = np.meshgrid(np.arange(start = X_set[:, 0].min() - 1, stop = X_set[:, 
0].max() + 1, step = 0.01),​
 np.arange(start = X_set[:, 1].min() - 1, stop = X_set[:, 
1].max() + 1, step = 0.01))​
plt.contourf(X1, X2, classifier.predict(np.array([X1.ravel(), 
X2.ravel()]).T).reshape(X1.shape),​
 alpha = 0.75, cmap = ListedColormap(('red', 'green')))​
plt.xlim(X1.min(), X1.max())​
plt.ylim(X2.min(), X2.max())​
for i, j in enumerate(np.unique(y_set)):​
plt.scatter(X_set[y_set == j, 0], X_set[y_set == j, 1],​
c = ListedColormap(('red', 'green'))(i), label = j)​
plt.title('Logistic Regression (Training set)')​
plt.xlabel('Age')​
plt.ylabel('Estimated Salary')​
plt.legend()​
plt.show()​
​
# Visualising the Test set results​
from matplotlib.colors import ListedColormap​
X_set, y_set = X_test, y_test​
X1, X2 = np.meshgrid(np.arange(start = X_set[:, 0].min() - 1, stop = X_set[:, 
0].max() + 1, step = 0.01),​
 np.arange(start = X_set[:, 1].min() - 1, stop = X_set[:, 
1].max() + 1, step = 0.01))​
plt.contourf(X1, X2, classifier.predict(np.array([X1.ravel(), 
X2.ravel()]).T).reshape(X1.shape),​
 alpha = 0.75, cmap = ListedColormap(('red', 'green')))​
plt.xlim(X1.min(), X1.max())​
plt.ylim(X2.min(), X2.max())​
for i, j in enumerate(np.unique(y_set)):​
plt.scatter(X_set[y_set == j, 0], X_set[y_set == j, 1],​
c = ListedColormap(('red', 'green'))(i), label = j)​
plt.title('Logistic Regression (Test set)')​
plt.xlabel('Host IP')​
plt.ylabel('Mnemonic')​
plt.legend()​
plt.show()
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Logistic Regression Define X and Y for Prediction

2019-11-14 Thread Mike C
Hi Jason,

I will try it out... Nothing in the documentation tells a person.

Thanks


From: Python-list  on behalf 
of Jason Friedman 
Sent: Wednesday, November 13, 2019 7:19 PM
Cc: python-list@python.org 
Subject: Re: Logistic Regression Define X and Y for Prediction

>
>
> When I define the X and Y values for prediction in the train and test
> data, should I capture all the columns that has been "OneHotEncoded" (that
> is all columns with 0 and 1) for the X and Y values???
>

You might have better luck asking on Stackoverflow, per the Pandas
instructions: 
https://eur03.safelinks.protection.outlook.com/?url=https%3A%2F%2Fpandas.pydata.org%2Fcommunity.html&data=02%7C01%7C%7Ce4fa0935f3b0443c3b0f08d768988e72%7C84df9e7fe9f640afb435%7C1%7C0%7C637092876737703023&sdata=%2BO6zx05Szg3TeGdtusSaLU1GhXKp7PEL7beHpqg1hcQ%3D&reserved=0.
--
https://eur03.safelinks.protection.outlook.com/?url=https%3A%2F%2Fmail.python.org%2Fmailman%2Flistinfo%2Fpython-list&data=02%7C01%7C%7Ce4fa0935f3b0443c3b0f08d768988e72%7C84df9e7fe9f640afb435%7C1%7C0%7C637092876737703023&sdata=tDAC3St0kqFfN3rLqBBg9cTsykel5Hhj6MUjzFxZc7I%3D&reserved=0
-- 
https://mail.python.org/mailman/listinfo/python-list


Pandas Dataframe Numbers Comma Formatted

2020-05-09 Thread Joydeep C
I have a Pandas dataframe like below.

XY
0  1234567890
1  54321N/A
2  67890123456

I need to make these numbers comma formatted. For example, 12345 => 
12,345.

Please help.

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


Re: Pandas Dataframe Numbers Comma Formatted

2020-05-09 Thread Joydeep C
On Sat, 09 May 2020 14:42:43 +0200, Python wrote:

> Joydeep wrote:
>> I have a Pandas dataframe like below.
>> 
>>  XY
>> 0  1234567890 1  54321N/A 2  67890123456
>> 
>> I need to make these numbers comma formatted. For example, 12345 =>
>> 12,345.
> 
>  >>> value = 12345 f'{value:,}'  # >= 3.6
> '12,345'
>  >>> '{:,}'.format(value)  # >= 2.7
> '12,345'

I need all the numbers in the whole dataframe to be formatted like that, 
not one value.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Pandas Dataframe Numbers Comma Formatted

2020-05-09 Thread Joydeep C
On Sat, 09 May 2020 15:46:27 +0200, Python wrote:

> Joydeep C wrote:
>> On Sat, 09 May 2020 14:42:43 +0200, Python wrote:
>> 
>>> Joydeep wrote:
>>>> I have a Pandas dataframe like below.
>>>>
>>>>   XY
>>>> 0  1234567890 1  54321N/A 2  67890123456
>>>>
>>>> I need to make these numbers comma formatted. For example, 12345 =>
>>>> 12,345.
>>>
>>>   >>> value = 12345 f'{value:,}'  # >= 3.6
>>> '12,345'
>>>   >>> '{:,}'.format(value)  # >= 2.7
>>> '12,345'
>> 
>> I need all the numbers in the whole dataframe to be formatted like
>> that,
>> not one value.
> 
>  >>> data.applymap((lambda x: f"{x:,}") )
>  X Y
> 0  12,345  67,890.0 1  54,321   nan 2  67,890  12,345.0
>  >>> data.apply(np.vectorize((lambda x: f"{x:,}")))
>  X Y
> 0  12,345  67,890.0 1  54,321   nan 2  67,890  12,345.0

It's giving error - "Cannot specify ',' with 's'."
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Pandas Dataframe Numbers Comma Formatted

2020-05-09 Thread Joydeep C
On Sat, 09 May 2020 17:24:41 +0200, Python wrote:

> Joydeep C wrote:
>> On Sat, 09 May 2020 15:46:27 +0200, Python wrote:
>> 
>>> Joydeep C wrote:
>>>> On Sat, 09 May 2020 14:42:43 +0200, Python wrote:
>>>>
>>>>> Joydeep wrote:
>>>>>> I have a Pandas dataframe like below.
>>>>>>
>>>>>>XY
>>>>>> 0  1234567890 1  54321N/A 2  67890123456
>>>>>>
>>>>>> I need to make these numbers comma formatted. For example, 12345 =>
>>>>>> 12,345.
>>>>>
>>>>>>>> value = 12345 f'{value:,}'  # >= 3.6
>>>>> '12,345'
>>>>>>>> '{:,}'.format(value)  # >= 2.7
>>>>> '12,345'
>>>>
>>>> I need all the numbers in the whole dataframe to be formatted like
>>>> that,
>>>> not one value.
>>>
>>>   >>> data.applymap((lambda x: f"{x:,}") )
>>>   X Y
>>> 0  12,345  67,890.0 1  54,321   nan 2  67,890  12,345.0
>>>   >>> data.apply(np.vectorize((lambda x: f"{x:,}")))
>>>   X Y
>>> 0  12,345  67,890.0 1  54,321   nan 2  67,890  12,345.0
>> 
>> It's giving error - "Cannot specify ',' with 's'."
> 
> It means that you're not storing numbers in your dataframe but strings,
> which is likely not what you want here. Fix that first.

Of course, they are strings. It's "N/A", not nan.
-- 
https://mail.python.org/mailman/listinfo/python-list


Getting rid of virtual environments with a better dependency system

2020-11-11 Thread j c
Hello all,

I don't know if this suggestion is missing some point, or it's part of 
something already proposed before.

In a professional environment, we've came to a point in which most people use 
virtual environments or code environments to avoid "polluting a global 
environment".

However, I think that's a problem with the default behaviour of the module 
management in Python. A nice default behaviour would be to search for a 
requirements.txt file in the same directory as __file__, and use the newest 
version of every module that matches the constraints. If no requirements where 
given, the newest version already installed could be used. That would require a 
structure that allows multiple versions of the same module to be downloaded.

I already anticipate some problems: increased disk usage for people that are 
not using virtual environments, the possibility of breaking changes for scripts 
with no constraints over a module (so that if a different module download a 
newer version, both would be using it), and of course the hassle of a 
completely new default behaviour that would require a transition in many 
codebases. But still, I believe it would pay off in terms of time saved in 
environment installing and switching.

Also, I think it's a good step in the path to integrating pip as something 
closer to the Python core.

What's your opinion, is the effort required too big for the returns? Do you 
think other problems may arise?
-- 
https://mail.python.org/mailman/listinfo/python-list


Getting rid of virtual environments with a better dependency system

2020-11-11 Thread j c
Hello all,

I don't know if this suggestion is missing some point, or it's part of 
something already proposed.

In a professional environment, we've came to a point in which most people use 
virtual environments or conda environments to avoid "polluting a global 
environment".

However, I think that's a problem with the default behaviour of the module 
management in Python. A nice default behaviour would be to search for a 
requirements.txt file in the same directory as __file__, and use the newest 
version of every module that matches the constraints. If no requirements where 
given, the newest version already installed could be used. That would require 
allowing multiple versions of the same module to be downloaded.

I already anticipate some problems: increased disk usage for people that are 
not using virtual environments, the possibility of breaking changes for scripts 
with no constraints over a module (so that if a different module download a 
newer version, both would be using it), and of course the hassle of a 
completely new default behaviour that would require a transition in many 
codebases.

That there are other solutions to the problem, such as forcing the usage of 
semantic versioning, but that's a bit utopic. But still, I believe it would pay 
off in terms of time saved in environment installing and switching. Also, it's 
a good step in the path to integrating pip as something closer to the Python 
core.

What's your opinion, is the effort required too big for the returns? Do you 
think other problems may arise?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Getting rid of virtual environments with a better dependency system

2020-11-11 Thread j c
On Wednesday, 11 November 2020 at 12:22:24 UTC+1, Chris Angelico wrote:
> On Wed, Nov 11, 2020 at 10:06 PM j c wrote: 
> > 
> > Hello all, 
> > 
> > I don't know if this suggestion is missing some point, or it's part of 
> > something already proposed. 
> > 
> > In a professional environment, we've came to a point in which most people 
> > use virtual environments or conda environments to avoid "polluting a global 
> > environment". 
> > 
> > However, I think that's a problem with the default behaviour of the module 
> > management in Python. A nice default behaviour would be to search for a 
> > requirements.txt file in the same directory as __file__, and use the newest 
> > version of every module that matches the constraints. If no requirements 
> > where given, the newest version already installed could be used. That would 
> > require allowing multiple versions of the same module to be downloaded. 
> >
> This would stop venvs from providing the isolation that they are 
> supposed to, and instead would just create yet another way to invoke 
> dependency hell. No thank you. 
> 
> A virtual environment isn't just a way to install different versions 
> of modules. It's way WAY more than that, and if you need to have too 
> many different versions around, you have bigger problems to deal with. 
> 
> (As a simple thought experiment to prove the problem with your 
> proposal: what happens with your dependencies' dependencies, and what 
> if they conflict? At what point would that be detected?) 
> 
> ChrisA

How can this behaviour turn into dependency hell? Every dependency use the 
specified version if any, otherwise the most recent one, which also applies to 
second order dependencies. In case of conflict, the first version would be 
imported, which is currently the default behaviour. The main difference is that 
this approach would be able to generate a warning before running the script 
with no need for pipdeptree.
-- 
https://mail.python.org/mailman/listinfo/python-list


Setting a Limit to the Maximum Size of an Upload

2005-10-24 Thread Joey C.
Hello,
I'm designing a small "briefcase" program that will allow me to quickly
upload, download, and delete files in a briefcase.  The only real
things that I have left to do are to design a method for checking if
the file exists, preventing it from overwriting files from other
directories, and setting a user-configurable maximum limit on the
file's size.  The former two, I can handle by myself with no problem.
However, the I'm having a little trouble with.

thefile = params["upfile.file"]
if os.path.getsize(thefile) <= conf["upmax"]:
print "File Size Okay." #Add Functions Later...
else:
print "File Too Large." #Here, too.

CGItb reported the following error:
TypeError: coercing to Unicode: need string or buffer, instance found
  args = ('coercing to Unicode: need string or buffer, instance
found',)

This seems like an incredibly simple problem, but I just can't seem to
wrap my mind around it.  Thank you for your help.

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


Re: Setting a Limit to the Maximum Size of an Upload

2005-10-24 Thread Joey C.
Here is a basic overview of the variables included there.

params = cgi.FieldStorage()
I accidentally made a mistake when typing what the "thefile" variable
is.
thefile = params["upfile"].file
"upfile" is the CGI field that contains the file that I'm uploading.
As you can see, the if statement just compares two values,
os.path.getsize(thefile) and conf["upmax"], a variable I set that is
designated as the maximum file size allowed.

I'm assuming that this is all the information you need.  I'm sorry for
not including it earlier; I was in a bit of a rush.  ^.^

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


Re: Setting a Limit to the Maximum Size of an Upload

2005-10-25 Thread Joey C.
I'm afraid on my interpreter, this works.

>>> if os.path.getsize("C:\\Documents and Settings\\Joey\\Desktop\\file.txt") 
>>> <= 1000:
>>> print "<= 1000."

<= 1000.

No problems there, as you can see.

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


Re: Setting a Limit to the Maximum Size of an Upload

2005-10-25 Thread Joey C.
Oh, I'm sorry, I didn't understand what you meant at first.
Then I read your reply over again and noticed that you said that the
problem lied in os.path.getsize() when I tried to run it on the
contents of an open file.

I'll try the method you outlined now.

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


Re: Setting a Limit to the Maximum Size of an Upload

2005-10-27 Thread Joey C.
Yes, I see that now.  I tried your method and it seemed to work fine
until I tried printing the filesize out.

def checkfilesize(thefile):
# Check the Size of the File
  global filesize
  thefile.seek(0,2)
  filesize = thefile.tell()
  thefile.seek(0)
  print filesize
  print conf["upmax"]
  if filesize <= conf["upmax"]:
print "File Size Okay."
noupload = False
  else:
print "File is too Large."
noupload = True

Basically conf["upmax"] is a number that I extract from a configuration
file that is the maximum size of an upload.  I had tried setting
conf["upmax"] to 1 and it should have technically disallowed a 28 byte
file to pass through.  But it did, so I added two lines to print the
file size and the conf["upmax"] variable.
The file size turned out to be "0"!
thefile still is just params["upfile"].file, by the way.

Any suggestions?

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


Using win32ui.CreateFileDialog() to get the name of a file.

2005-11-19 Thread Joey C.
Hello.
I'm writing a program that creates a series of batch operations to
convert movies to be used on iPodLinux.  The programs that do the
encoding and conversions are seperate from mine and all mine does is
use os.system() to call the program.

However, it needs to get an input file and an output file.  Originally
I was using just raw input, but I got adventuresome and decided to try
win32ui.CreateFileDialog().  But this will only open or save a file and
its output will be either 1 or a failure.  How might I go about using
it to get the _file name_ of a file.
For example.
Box appears asking user to find a file they want.  They double click on
the file.  Let's call it C:\Video.avi
Then another dialog box appears asking them where to save it.  They
save it at C:\iPodVideo.avi.

Now the Python program extracts the name of these files and then uses
os.system() to run:
mencoder.exe -[parameters] C:\Video.avi -o C:\iPodVideo.avi

Note that I'm not actually inputting the contents of the file, I'm just
passing the file name along.

How might I do this?  Thanks.

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


Re: Using win32ui.CreateFileDialog() to get the name of a file.

2005-11-19 Thread Joey C.
Okay, thank you.  This worked very well.

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


python-dev Summary for 2004-10-16 through 2004-10-31

2005-01-01 Thread Brett C.
This is a summary of traffic on the `python-dev mailing list`_ from October 16, 
2004 through October 31, 2004.  It is intended to inform the wider Python 
community of on-going developments on the list.  To comment on anything 
mentioned here, just post to `comp.lang.python`_ (or email 
python-list@python.org which is a gateway to the newsgroup) with a subject line 
mentioning what you are discussing. All python-dev members are interested in 
seeing ideas discussed by the community, so don't hesitate to take a stance on 
something.  And if all of this really interests you then get involved and join 
`python-dev`_!

This is the fifty-first summary written by Brett Cannon (I *will* be caught up 
on summaries soon).

To contact me, please send email to brett at python.org ; I do not have the 
time to keep up on comp.lang.python and thus do not always catch follow-ups 
posted there.

All summaries are archived at http://www.python.org/dev/summary/ .
Please note that this summary is written using reStructuredText_ which can be 
found at http://docutils.sf.net/rst.html .  Any unfamiliar punctuation is 
probably markup for reST_ (otherwise it is probably regular expression syntax 
or a typo =); you can safely ignore it, although I suggest learning reST; it's 
simple and is accepted for `PEP markup`_ and gives some perks for the HTML 
output.  Also, because of the wonders of programs that like to reformat text, I 
cannot guarantee you will be able to run the text version of this summary 
through Docutils_ as-is unless it is from the `original text file`_.

.. _PEP Markup: http://www.python.org/peps/pep-0012.html
The in-development version of the documentation for Python can be found at
http://www.python.org/dev/doc/devel/ and should be used when looking up any
documentation on new code; otherwise use the current documentation as found at
http://docs.python.org/ .  PEPs (Python Enhancement Proposals) are located at 
http://www.python.org/peps/ .  To view files in the Python CVS online, go to 
http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/python/ .  Reported bugs and 
suggested patches can be found at the SourceForge_ project page.

The `Python Software Foundation`_ is the non-profit organization that holds the 
intellectual property for Python.  It also tries to forward the development and 
use of Python.  But the PSF_ cannot do this without donations.  You can make a 
donation at http://python.org/psf/donations.html .  Every penny helps so even a 
small donation (you can donate through PayPal or by check) helps.

.. _python-dev: http://www.python.org/dev/
.. _SourceForge: http://sourceforge.net/tracker/?group_id=5470
.. _python-dev mailing list: http://mail.python.org/mailman/listinfo/python-dev
.. _comp.lang.python: http://groups.google.com/groups?q=comp.lang.python
.. _Docutils: http://docutils.sf.net/
.. _reST:
.. _reStructuredText: http://docutils.sf.net/rst.html
.. _PSF:
.. _Python Software Foundation: http://python.org/psf/
.. contents::
.. _last summary: http://www.python.org/dev/summary/2004-10-01_2004-10-15.html
.. _original text file: 
http://www.python.org/dev/summary/2004-10-16_2004-10-31.ht

=
Summary Announcements
=
`Python 2.4`_ final is now out!
As I mentioned in the last summary my school schedule this past quarter has 
been insane.  But now I am on Winter Break and will hopefully be able to catch 
up on my Summary backlog.

.. _Python 2.4: http://www.python.org/2.4/
=
Summaries
=

Specifying main functions and calling packages with '-m'

In my opinion, the new '-m' command line option in Python 2.4 is really handy. 
 But wouldn't it be even handier if you could execute modules in a package? 
That exact question came up.  The reason this kind of thing didn't just go 
directly into 2.4 was that the semantics are not as obvious nor is it as 
simple.  `PEP 338`_ goes over all of this and also points to a recipe that 
implements it all now.

This also brought up the discussion of being able to specify a 'main' function 
to take the place of the good old ``if __name__ == "__main__"`` idiom.  Some 
liked the idea of allowing one to define a function named 'main', others 
'__main__'.  `PEP 299`_ discusses all of this.

.. _PEP 299: http://www.python.org/peps/pep-0299.html
.. _PEP 338: http://www.python.org/peps/pep-0338.html
Contributing threads:
  - `python-dev Summary for 2004-09-16 through 2004-09-30 [draft] 
`__
  - `Magic main functions 
`__
  - `Supporting packages on the command line 
`__


ConfigParser shootout begins

As mentioned in the `last summary`_, a desire for 

python-dev Summary for 2004-11-16 through 2004-11-30

2005-01-05 Thread Brett C
python-dev Summary for 2004-11-16 through 2004-11-30

This is a summary of traffic on the `python-dev mailing list`_ from November 
16, 2004 through November 30, 2004.  It is intended to inform the wider Python 
community of on-going developments on the list.  To comment on anything 
mentioned here, just post to `comp.lang.python`_ (or email 
python-list@python.org which is a gateway to the newsgroup) with a subject line 
mentioning what you are discussing. All python-dev members are interested in 
seeing ideas discussed by the community, so don't hesitate to take a stance on 
something.  And if all of this really interests you then get involved and join 
`python-dev`_!

This is the fifty-third summary written by Brett Cannon (Another quarter 
begins).
To contact me, please send email to brett at python.org ; I do not have the 
time to keep up on comp.lang.python and thus do not always catch follow-ups 
posted there.

All summaries are archived at http://www.python.org/dev/summary/ .
Please note that this summary is written using reStructuredText_ which can be 
found at http://docutils.sf.net/rst.html .  Any unfamiliar punctuation is 
probably markup for reST_ (otherwise it is probably regular expression syntax 
or a typo =); you can safely ignore it, although I suggest learning reST; it's 
simple and is accepted for `PEP markup`_ and gives some perks for the HTML 
output.  Also, because of the wonders of programs that like to reformat text, I 
cannot guarantee you will be able to run the text version of this summary 
through Docutils_ as-is unless it is from the `original text file`_.

.. _PEP Markup: http://www.python.org/peps/pep-0012.html
The in-development version of the documentation for Python can be found at
http://www.python.org/dev/doc/devel/ and should be used when looking up any
documentation on new code; otherwise use the current documentation as found at
http://docs.python.org/ .  PEPs (Python Enhancement Proposals) are located at 
http://www.python.org/peps/ .  To view files in the Python CVS online, go to 
http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/python/ .  Reported bugs and 
suggested patches can be found at the SourceForge_ project page.

The `Python Software Foundation`_ is the non-profit organization that holds the 
intellectual property for Python.  It also tries to forward the development and 
use of Python.  But the PSF_ cannot do this without donations.  You can make a 
donation at http://python.org/psf/donations.html .  Every penny helps so even a 
small donation (you can donate through PayPal or by check) helps.

.. _python-dev: http://www.python.org/dev/
.. _SourceForge: http://sourceforge.net/tracker/?group_id=5470
.. _python-dev mailing list: http://mail.python.org/mailman/listinfo/python-dev
.. _comp.lang.python: http://groups.google.com/groups?q=comp.lang.python
.. _Docutils: http://docutils.sf.net/
.. _reST:
.. _reStructuredText: http://docutils.sf.net/rst.html
.. _PSF:
.. _Python Software Foundation: http://python.org/psf/
.. contents::
.. _last summary: http://www.python.org/dev/summary/2004-11-01_2004-11-15.html
.. _original text file: 
http://www.python.org/dev/summary/2004-11-16_2004-11-30.ht

=
Summary Announcements
=
PyCon_ is coming up!  Being held March 23-25 in Washington, DC, registration is 
now open at http://www.python.org/pycon/2005/register.html for credit card 
users (you can pay by check as well; see the general info page for the conference).

.. _PyCon: http://www.python.org/pycon/2005/
=
Summaries
=
-
Would you like the source with your function?
-
Would you like all functions and classes to contain a __pycode__ attribute that 
contains a string of the code used to compile that code object?  Well, that 
very idea was proposed.  You would use a command-line switch to turn on the 
feature in order to remove the memory and any performance overhead for the 
default case of not needing this feature.

Some might ask why this is needed when inspect.getsource and its ilk exist. 
The perk is that __pycode__ would always exist while inspect.getsource is a 
best attempt but cannot guarantee it will have the source.

Beyond a suggested name change to __source__, various people have suggested 
very different uses.  Some see it as a convenient way to save interpreter work 
easily and thus not lose any nice code snippet developed interactively.  Others 
see a more programmatic use (such as AOP "advice" injection).  Both are rather 
different and led to the thread ending on the suggestion that a PEP be written 
that specifies what the intended use-case to make sure that need is properly met.

Contributing threads:
  - `__pycode__ extension 
`__

===
Skipped Threads
===
- PEP 310 

python-dev Summary for 2004-12-01 through 2004-12-15

2005-01-23 Thread Brett C.
space is cheap.

It seems that no longer listing documentation and adding a deprecation warning 
is what is needed to properly deprecate a module.  By no longer listing 
documentation new programmers will not use the code since they won't know about 
it.  And adding the warning will let old users know that they should be using 
something else.

.. _PEP 4: http://www.python.org/peps/pep-0004.html
Contributing threads:
  - `Deprecated xmllib module 
<http://mail.python.org/pipermail/python-dev/2004-December/050210.html>`__
  - `Rewriting PEP4 
<http://mail.python.org/pipermail/python-dev/2004-December/050241.html>`__

--
PR to fight the idea that Python is "slow"
--
An article_ in ACM TechNews that covered 2.4 had several mentions that Python 
was "slow" while justifying the slowness (whether it be flexibility or being 
fast enough).  Guido (rightfully) didn't love all of the "slow" mentions which 
I am sure we have all heard at some point or another.

The suggestions started to pour in on how to combat this.  The initial one was 
to have a native compiler.  The thinking was that if we compiled to a native 
executable that people psychologically would stop the association of Python 
being interpreted which is supposed to be slow.  Some people didn't love this 
idea since a native compiler is not an easy thing.  Others suggested including 
Pyrex with CPython, but didn't catch on (maintenance issue plus one might say 
Pyrex is not the most Pythonic solution).  This didn't get anywhere in the end 
beyond the idea of a SIG about the various bundling tools (py2app, py2exe, etc.).

The other idea was to just stop worrying about speed and move on stomping out 
bugs and making Python functionally more useful.  With modules in the stdlib 
being rewritten in C for performance reasons it was suggested we are putting 
out the perception that performance is important to us.  Several other people 
also suggested that we just not mention speed as a big deal in release notes 
and such.

This also tied into the idea that managers don't worry too much about speed as 
much as being able to hire a bunch of Python programmers.  This led to the 
suggestion of also emphasizing that Python is very easy to learn and thus is a 
moot point.  There are a good number of Python programmers, though; Stephan 
Deibel had some rough calculations that put the number at about 750K Python 
developers worldwide (give or take; rough middle point of two different 
calculations).

.. _article: http://gcn.com/vol1_no1/daily-updates/28026-1.html
Contributing threads:
  - `2.4 news reaches interesting places 
<http://mail.python.org/pipermail/python-dev/2004-December/050283.html>`__

===
Skipped Threads
===
- MS VC compiler versions
- Any reason why CPPFLAGS not used in compiling?
  Extension modules now compile with directories specified in the LDFLAGS 
and CPPFLAGS env vars
- adding key argument to min and max
  min and max now have a 'key' argument like list.sort
- Unicode in doctests
- SRE bug and notifications
- PyInt_FromLong returning NULL
- PyOS_InputHook enhancement proposal
- The other Py2.4 issue
- MinGW And The other Py2.4 issue
- Supporting Third Party Modules
- Python in education

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


python-dev Summary for 2004-12-16 through 2004-12-31

2005-02-02 Thread Brett C.
This is a summary of traffic on the `python-dev mailing list`_ from December 
16, 2004 through December 31, 2004.  It is intended to inform the wider Python 
community of on-going developments on the list.  To comment on anything 
mentioned here, just post to `comp.lang.python`_ (or email 
python-list@python.org which is a gateway to the newsgroup) with a subject line 
mentioning what you are discussing. All python-dev members are interested in 
seeing ideas discussed by the community, so don't hesitate to take a stance on 
something.  And if all of this really interests you then get involved and join 
`python-dev`_!

This is the fifty-fifth summary written by Brett Cannon (I have been doing this
for too long...).
To contact me, please send email to brett at python.org ; I do not have the 
time to keep up on comp.lang.python and thus do not always catch follow-ups 
posted there.

All summaries are archived at http://www.python.org/dev/summary/ .
Please note that this summary is written using reStructuredText_ which can be 
found at http://docutils.sf.net/rst.html .  Any unfamiliar punctuation is 
probably markup for reST_ (otherwise it is probably regular expression syntax 
or a typo =); you can safely ignore it, although I suggest learning reST; it's 
simple and is accepted for `PEP markup`_ and gives some perks for the HTML 
output.  Also, because of the wonders of programs that like to reformat text, I 
cannot guarantee you will be able to run the text version of this summary 
through Docutils_ as-is unless it is from the `original text file`_.

.. _PEP Markup: http://www.python.org/peps/pep-0012.html
The in-development version of the documentation for Python can be found at
http://www.python.org/dev/doc/devel/ and should be used when looking up any
documentation on new code; otherwise use the current documentation as found at
http://docs.python.org/ .  PEPs (Python Enhancement Proposals) are located at 
http://www.python.org/peps/ .  To view files in the Python CVS online, go to 
http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/python/ .  Reported bugs and 
suggested patches can be found at the SourceForge_ project page.

The `Python Software Foundation`_ is the non-profit organization that holds the 
intellectual property for Python.  It also tries to forward the development and 
use of Python.  But the PSF_ cannot do this without donations.  You can make a 
donation at http://python.org/psf/donations.html .  Every penny helps so even a 
small donation (you can donate through PayPal or by check) helps.

.. _python-dev: http://www.python.org/dev/
.. _SourceForge: http://sourceforge.net/tracker/?group_id=5470
.. _python-dev mailing list: http://mail.python.org/mailman/listinfo/python-dev
.. _comp.lang.python: http://groups.google.com/groups?q=comp.lang.python
.. _Docutils: http://docutils.sf.net/
.. _reST:
.. _reStructuredText: http://docutils.sf.net/rst.html
.. _PSF:
.. _Python Software Foundation: http://python.org/psf/
.. contents::
.. _last summary: http://www.python.org/dev/summary/2004-12-01_2004-12-15.html
.. _original text file: 
http://www.python.org/dev/summary/2004-12-16_2004-12-31.ht

=
Summary Announcements
=
You can still `register `__ for 
`PyCon`_.  The `schedule of talks`_ is now online.  Jim Hugunin is lined up to 
be the keynote speaker on the first day with Guido being the keynote on 
Thursday.  Once again PyCon looks like it is going to be great.

On a different note, as I am sure you are all aware I am still about a month 
behind in summaries.  School this quarter for me has just turned out hectic.  I 
think it is lack of motivation thanks to having finished my 14 doctoral 
applications just a little over a week ago (and no, that number is not a typo). 
 I am going to for the first time in my life come up with a very regimented 
study schedule that will hopefully allow me to fit in weekly Python time so as 
to allow me to catch up on summaries.

And this summary is not short because I wanted to finish it.  2.4 was released 
just before the time this summary covers so most stuff was on bug fixes 
discovered after the release.

.. _PyCon: http://www.pycon.org/
.. _schedule of talks: http://www.python.org/pycon/2005/schedule.html
===
Summary
===
-
PEP movements
-
I introduced a `proto-PEP 
`__ to 
the list on how one can go about changing CPython's bytecode.  It will need 
rewriting once the AST branch is merged into HEAD on CVS.  Plus I need to get a 
PEP number assigned to me.  =)

Contributing threads:
  - `proto-pep: How to change Python's bytecode 
`__


Handling versioning within a package

The suggestion of extending import syntax to support explicit ve

Calling a method using an argument

2005-02-03 Thread C Gillespie
Dear All,

I have a simple class
class hello:
def world(self):
return 'hello'
def test(self,arg):
return self.arg

When I want to do is:
>hello.test('world')
'hello'

i.e. pass the method name as an argument. How should I do this?

Thanks

Colin


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


Re: Calling a method using an argument

2005-02-04 Thread C Gillespie
Dear All,

Many thanks

Colin
"C Gillespie" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
> Dear All,
>
> I have a simple class
> class hello:
> def world(self):
> return 'hello'
> def test(self,arg):
> return self.arg
>
> When I want to do is:
> >hello.test('world')
> 'hello'
>
> i.e. pass the method name as an argument. How should I do this?
>
> Thanks
>
> Colin
>
>


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


Can we pass some arguments to system("cmdline")?

2005-06-19 Thread Didier C
Hi!
   I was wondering if we can pass some arguments to system("cmdline")?

E.g in Perl, we can do something like:

$dir="/home/cypher";

system("ls $dir");

which would instruct Perl to do an "ls /home/cypher"

But in python, doing something like

dir="/home/cypher"
system("ls dir")

would cause python to execute "ls dir" where "dir" might not exist at
all! Is there a way to reproduce the same thing in Python?

Thanks for any insights.

cheers,
Didier.

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


Python linear algebra module -- requesting comments on interface

2005-09-09 Thread C. Barnes

Hi, I'm in the process of writing a Python linear
algebra module.

The current targeted interface is:

  http://oregonstate.edu/~barnesc/temp/linalg/

The interface was originally based on Raymond
Hettinger's
Matfunc [1].  However, it has evolved so that now it
is
nearly identical to JAMA [2], the Java matrix library.

I am soliticing comments on this interface.

Please post up any criticism that you have.  Even
small
things -- if something isn't right, it's better to fix
it now than later.

I have not made source code available yet, since the
current code is missing the decompositions and doesn't
match the new interface.  I'm in the process of
rewritting the code to match the new interface.  You
can e-mail me and ask for the old code if you're
curious
or skeptical.

[1]. http://users.rcn.com/python/download/python.htm
[2]. http://math.nist.gov/javanumerics/jama/

-
Brief comparison with Numeric
-

Numeric and linalg serve different purposes.

Numeric is intended to be a general purpose array
extension.  It takes a "kitchen sink" approach,
and includes every function which could potentially
be useful for array manipulations.

Linalg is intended to handle real/complex vectors
and matrices, for scientific and 3D applications.
It has a more restricted scope.  Because it is
intended for 3D applications, it is optimized
for dimension 2, 3, 4 operations.

For the typical matrix operations, the linalg
interface is much intuitive than Numeric's.  Real
and imaginary components are always cast to
doubles, so no headaches are created if a matrix
is instantiated from a list of integers.  Unlike
Numeric, the * operator performs matrix
multiplication, A**-1 computes the matrix inverse,
A == B returns True or False, and the 2-norm and
cross product functions exist.

As previously stated, linalg is optimized for
matrix arithmetic with small matrices (size 2, 3, 4).

A (somewhat out of date) set of microbenchmarks [3]
[4]
show that linalg is roughly an order of magnitude
faster than Numeric for dimension 3 vectors and
matrices.

[3].
Microbenchmarks without psyco:
http://oregonstate.edu/~barnesc/temp/
numeric_vs_linalg_prelim-2005-09-07.pdf

[4].
Microbenchmarks with psyco:
http://oregonstate.edu/~barnesc/temp/
numeric_vs_linalg_prelim_psyco-2005-09-07.pdf



__
Do You Yahoo!?
Tired of spam?  Yahoo! Mail has the best spam protection around 
http://mail.yahoo.com 
-- 
http://mail.python.org/mailman/listinfo/python-list


Python linear algebra module -- requesting comments on interface

2005-09-14 Thread C. Barnes

Szabolcs Nagy wrote:
>nice interface, but with 3d apps i prefer cgkit's
approach, which has
>vec3, vec4, mat3, mat4 and quat types with lots of
useful functions for
>3d graphics (like mat4.looakAt(pos, target, up) or
mat3.toEulerXYZ())

>there are other libs with similar types and
functions:
>cgkit (http://cgkit.sourceforge.net/)

Thanks for the link!  I had planned on changing around
the constructors: using Matrix.zero(),
Matrix.identity(), and Matrix.random() static methods
(instead of module functions), and adding
Matrix.rotate(), Matrix.translate(), Matrix.scale()
for homogenous 4-matrices and with an optional arg
that would make a 3-matrix in special cases.  Then I
thought  I'd add affine_transform() and
homogeneous_transform() module methods, which could
transform several vectors at once if they are stored
in a matrix.

But I looked over cgkit's interface, and it is EXACTLY
what I wanted.  I guess my scientific programming
background made me think up too general of an
interface.  So I've cancelled this linear algebra
library.

If anyone needs the matrix decompositions, and you
can't find them elsewhere, you can always make your
own library.  I was planning on using the public
domain code from:

 http://math.nist.gov/javanumerics/jama/

ftp://math.nist.gov/pub/Jampack/Jampack/AboutJampack.html

 - Connelly Barnes




__ 
Yahoo! Mail - PC Magazine Editors' Choice 2005 
http://mail.yahoo.com
-- 
http://mail.python.org/mailman/listinfo/python-list


python-dev Summary for 2005-01-01 through 2005-01-15

2005-02-07 Thread Brett C
This is a summary of traffic on the `python-dev mailing list`_ from January 01, 
2005 through January 15, 2005.  It is intended to inform the wider Python 
community of on-going developments on the list.  To comment on anything 
mentioned here, just post to `comp.lang.python`_ (or email 
python-list@python.org which is a gateway to the newsgroup) with a subject line 
mentioning what you are discussing. All python-dev members are interested in 
seeing ideas discussed by the community, so don't hesitate to take a stance on 
something.  And if all of this really interests you then get involved and join 
`python-dev`_!

This is the fifty-sixth summary written by Brett Cannon (I don't want to do my
homework).
To contact me, please send email to brett at python.org ; I do not have the 
time to keep up on comp.lang.python and thus do not always catch follow-ups 
posted there.

All summaries are archived at http://www.python.org/dev/summary/ .
Please note that this summary is written using reStructuredText_ which can be 
found at http://docutils.sf.net/rst.html .  Any unfamiliar punctuation is 
probably markup for reST_ (otherwise it is probably regular expression syntax 
or a typo =); you can safely ignore it, although I suggest learning reST; it's 
simple and is accepted for `PEP markup`_ and gives some perks for the HTML 
output.  Also, because of the wonders of programs that like to reformat text, I 
cannot guarantee you will be able to run the text version of this summary 
through Docutils_ as-is unless it is from the `original text file`_.

.. _PEP Markup: http://www.python.org/peps/pep-0012.html
The in-development version of the documentation for Python can be found at
http://www.python.org/dev/doc/devel/ and should be used when looking up any
documentation on new code; otherwise use the current documentation as found at
http://docs.python.org/ .  PEPs (Python Enhancement Proposals) are located at 
http://www.python.org/peps/ .  To view files in the Python CVS online, go to 
http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/python/ .  Reported bugs and 
suggested patches can be found at the SourceForge_ project page.

The `Python Software Foundation`_ is the non-profit organization that holds the 
intellectual property for Python.  It also tries to forward the development and 
use of Python.  But the PSF_ cannot do this without donations.  You can make a 
donation at http://python.org/psf/donations.html .  Every penny helps so even a 
small donation (you can donate through PayPal or by check) helps.

.. _python-dev: http://www.python.org/dev/
.. _SourceForge: http://sourceforge.net/tracker/?group_id=5470
.. _python-dev mailing list: http://mail.python.org/mailman/listinfo/python-dev
.. _comp.lang.python: http://groups.google.com/groups?q=comp.lang.python
.. _Docutils: http://docutils.sf.net/
.. _reST:
.. _reStructuredText: http://docutils.sf.net/rst.html
.. _PSF:
.. _Python Software Foundation: http://python.org/psf/
.. contents::
.. _last summary: http://www.python.org/dev/summary/2004-12-16_2004-12-31.html
.. _original text file: 
http://www.python.org/dev/summary/2005-01-01_2005-01-15.ht

=
Summary Announcements
=
PyCon_ will be upon us come late March!  Still time to plan to go.
A warning on the thoroughness off this summary is in order.  While trying to 
delete a single thread of email I managed to accidentally delete my entire 
python-dev mailbox.  I did the best I could to retrieve the emails but it's 
possible I didn't resuscitate all of my emails, so I may have overlooked something.

.. _PyCon: http://www.pycon.org/
===
Summary
===
-
PEP movements
-
tip:: PEP updates by email are available as a topic from the `Python-checkins`_ 
mailing list.

`PEP 246`_ was a major topic of discussion during the time period covered by 
this summary.  This all stemmed from `Guido's blog`_ entries on optional type 
checking. This led to a huge discussion on many aspects of protocols, 
interfaces, and adaptation and the broadening of this author's vocabulary to 
include "Liskov violation".

"Monkey typing" also became a new term to know thanks to Phillip J. Eby's 
proto-PEP on the topic (found at 
http://peak.telecommunity.com/DevCenter/MonkeyTyping).  Stemming from the 
phrase "monkey see, monkey do", it's Phillip version of taking PEP 246 
logically farther (I think; the whole thing is more than my currently 
burned-out-on-school brain can handle right now).

.. _Python-checkins: http://mail.python.org/mailman/listinfo/python-checkins
.. _PEP 246: http://www.python.org/peps/pep-0246.html
.. _Guido's blog: http://www.artima.com/weblogs/index.jsp?blogger=guido
Contributing threads:
  - `getattr and __mro__ 
`__
  - `Son of PEP 246, redux 
`__
  - `PEP 246: lossless and stateless 


python-dev Summary for 2005-01-16 through 2005-01-31

2005-02-28 Thread Brett C
=
Summary Announcements
=
-
School sure likes to destroy my free time
-
A month late, that much closer to having this hectic quarter being over.  Sorry 
for being so delinquent with this summary but school has kept me busy and 
obviously the Real World has to take precedence over volunteer work.  Now if I 
could only get paid for doing this... =)

And if you hate the summaries being late, you could do it yourself.  This is 
not meant to be a flippant comment!  I am always willing to hand over 
development of the summaries to anyone who is willing to do a comparable job. 
If you are interested feel free to email me.  I have now made this a permanent 
offer in the header in case someone comes along later and decides they want to 
do this.

--
RSS feed now available
--
Thanks entirely to one of my predecessors, A.M. Kuchling, the python-dev 
Summaries are available as an `RSS feed`_.  The feed contains the titles of 
every summary and so will be updated with the newest summaries as soon as they 
are posted online.  A full text feed will eventually be available.

--
New format
--
I have done a thorough restructuring of the boilerplate and the Summary 
Announcements section for the Summaries.  The purpose of this is to make 
finding information in the boilerplate much easier.  It also keeps consistency 
by sectioning off everything as in the Summary section.

The other reason is for the ``contents`` directive in reST_.  This will provide 
a more thorough table of contents for the web version of the summary at the 
very top of the summaries.  This will allow people to jump directly to the 
section of the Summary they care about the most.  Obviously this perk only 
exists in the HTML version.

Lastly, the typical boilerplate for each Summary has now been moved to the 
bottom.  This was at the request of a regular reader who I would like to keep 
happy.  =)  It also seems reasonable since once you have read through it once 
chances are you are not going to read it again so might as well move it out of 
the way.

Then again I could be totally wrong about all of this and manage to alienate 
every person who reads the summaries regularly.  =)


===
Summary
===
-
Python 2.3.5 released
-
Consider how late this summary is I bet you already knew Python 2.3.5 was 
already out the door.  =)

With Python 2.4 out in the world this means there is a very high probability 
2.3.6 will never exist and this marks the end of the 2.3 branch.

Contributing threads:
  - `2.3.5 delayed til next week 
<http://mail.python.org/pipermail/python-dev/2005-January/051140.html>`__
  - `2.3 BRANCH FREEZE imminent! 
<http://mail.python.org/pipermail/python-dev/2005-January/051277.html>`__
  - `RELEASED Python 2.3.5, release candidate 1 
<http://mail.python.org/pipermail/python-dev/2005-January/051304.html>`__

--
Making magic type conversion methods act like __str__
--
Walter DÃrwald discovered that when you subclass 'unicode' and call unicode() 
on an instance of the subclass it will not call the implementation of 
__unicode__ of the subclass but instead will call unicode.__unicode__ .  When 
in the same scenario with strings, though, str() calls the subclass' __str__ 
method.  Turns out 'int' and 'float' act like 'unicode' while 'complex' acts 
like 'str'.

So who is right?  Docs say 'str' is wrong, but this is mainly an artifact of 
pre-2.2 inability to subclass types.  Turns out 'str' is acting properly. 
`Patch #1109424`_ implements the proper semantics and will eventually go in for 
2.5 (won't touch 2.4 since it is a semantic change).

.. _Patch #1109424: http://www.python.org/sf/1109424
Contributing threads:
  - `__str__ vs. __unicode__ 
<http://mail.python.org/pipermail/python-dev/2005-January/051175.html>`__

-
Speeding up function calls to C API functions
-
Neal Norwitz posted the patch found at http://www.python.org/sf/1107887 to help 
with function calls to C code.  The idea is to expand the family of values used 
in PyMethodDef.ml_flags for argument types to include specifying the number of 
minimum and maximum number of arguments.  This can provide a speedup by 
allowing the eval loop to unpack everything in the C stack and skip packing 
arguments in a tuple.

But not everyone was sure it was worth the extra need to specify all of this 
for functions.  Regardless of that and any other objections this would be more 
of a Python 3000 thing.

Which also led to a quick shift in topic to how Python 3.0 will be d

OK, time to retire (was: Re: python-dev Summary for 2005-01-16 through 2005-01-31)

2005-03-01 Thread Brett C.
Steve Holden wrote:
Michele Simionato wrote [on c.l.py]:
Brett Cannon:
[... python-dev summary ... boilerplate change ...]
+1 for this idea. The summary looks much better now :)
Keep the good work going,
Sorry, but i have to disagree. I hope you won't take this reply 
personally, Michele, since it's directed to all c.l.py readers, as well 
as (particularly) at Python users who [unlike you] are mostly take and 
rather less give. Although this is inherently the nature of open source, 
in certain cases this can be taken too far.

[SNIP]
Now, the reason for this specific rant is this: I can tell a cry for 
help when I see one. Brett has done a magnificent job of providing 
python-dev summaries since Andrew decided he'd had enough, and he is to 
be congratulated for it. I managed to offload another bunch of work on 
him (moderation of various troublesome PyCon mailing lists), but at 
least I was able to recompense him by letting him into PyCon for nothing.

[SNIP]
But frankly, I think it's time someone else stood up and said "Brett, 
you've done a magnificent job. Hesitant though I am about replacing you, 
I would like to volunteer for the task, because only when you are free 
from the burden of writing the python-dev summaries will we see what 
else you are capable of". Since I am at best an intermittent reader of 
python-dev I can say this without fear of having to stand up myself.

[SNIP]
[I am going to use this to reply to both Steve and Martin]
As Steve mentioned above, he can spot a cry for help when he sees one.  I think 
the problem is that I am a total sucker when it comes to the Python community 
and python-dev.

Anyone who has been on the python-dev list for as long as I have been a 
participant has most likely seen my almost yearly "thank you" emails I send the 
list (which there will probably be another one of once I choose where I am 
going to pursue my doctorate; I have acceptances but I am still waiting to here 
back from 9 more schools).  Usually it is just me gushing to python-dev, 
thanking the list for how Python has gotten me where I am today.  And that 
statement is completely sincere; python-dev has sculpted me into the programmer 
that I am (does this mean I can blame python-dev for my own buggy code?  =). 
And for that I will be eternally grateful to all of the wonderful people I have 
gotten to work with and know on this list.

It has also made me want to help people to get involved on python-dev in hopes 
others would benefit from python-dev the same way I have.  Granted, python-dev 
tends not to attract people like I was when I started getting involved (a 
philosophy degree and 4 CS courses does not equal a good programmer by default 
 =), but I have always hoped that through my efforts some other people could 
come to enjoy hacking on Python, learn some things, and advance the language.

But I think the big problem is that the Summaries have become a "gift" in the 
truest sense of the word.  I lost all personal benefit from the Summaries over 
a year ago.  Initially I learned a ton from all of the reading I was doing and 
the research required to understand what the heck people were talking about. 
But I have graduated from "The School of Hard Knocks".  At this point I do the 
Summaries entirely altruistically, giving back what I can to the community in a 
way that I know benefits many people which happens to have zero benefit to me now.

The Summaries consume what little free time I do have for Python which is 
unfortunate.  I have always hoped I would get to the point in my programming 
abilities that I would be a larger asset to python-dev as a programmer than as 
a writer.  I would like to think I have reached that point finally after my 
over two and a half years on the list (I can't believe I first posted to the 
list on June 17, 2002!).

So, to make sure I don't squander what time I do have for Python waiting for a 
possible replacement that might never come, I have decided that I am going to 
stop doing the python-dev Summaries after PyCon; the Summary covering the last 
half of March 2005 will be it for me.  Hopefully I will be more valuable as an 
active participant on python-dev again instead of as a passive listener who 
just happens to chime in on occasion and squash a simple bug when I am 
procrastinating from doing my homework.

This has been a long time coming and I needed a swift kick in the ass to 
finally get me to stop.  I thank you, Steve, for giving me that kick like the 
English gentleman you are.  =)

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


Re: [Python-Dev] Re: OK, time to retire

2005-03-02 Thread Brett C.
[taking python-dev off of the Cc: list]
Scott David Daniels wrote:
Brett C. wrote:
I have decided that I am going to stop doing the python-dev Summaries
 > after PyCon; the Summary covering the last half of March 2005 will be
 > it for me.
I (as well as most, I'd guess) have enjoyed your voice in the summaries.
Thanks for a great series of summaries.  Perhaps your final summary
could be a personal view of PyCon for those of us unable to get there.
If people want that, sure, be happy to cover PyCon.  Anybody else like that 
idea?  Or do the various bloggers who attend do a good enough job of coverage?

If you make no more contribution to Python than you have so far, you
will have done us a great service.
=)  Thanks.  Glad I have been able to help.
-Brett
--
http://mail.python.org/mailman/listinfo/python-list


python-dev Summary for 2005-02-01 through 2005-02-14

2005-03-06 Thread Brett C.
hemselves.
Guido `reiterated the rules`_ for str() (used by 'print') and
repr(). Since both complex.__str__ and complex.__repr__
pass the eval() test, he pronounced it fine.
.. _reiterated the rules: 
http://mail.python.org/pipermail/python-dev/2005-February/051390.html

Contributing threads:
  - `complex I/O problem 
<http://mail.python.org/pipermail/python-dev/2005-February/051388.html>`__

-
2.3.5 and 2.4.1 release plans
-
note: written by Steve Bethard
Anthony Baxter, Alex Martelli and Tim Peters squelched a bug where
deepcopy failed on instances of types that lacked an ``__mro__``
attribute.
The patch was pretty straight-forward (use inspect.getmro instead
of cls.__mro__), but coming up with a test case was hard --
creating a Python object that doesn't have an __mro__ takes some
complicated C code like that of Zope's ExtensionClass.  Fortunately,
John Lenton's c.l.py_ suggestion to simply raise an AttributeError for
__mro__ in __getattribute__ properly tickled the bug, and 2.3.5
was cleared for release.
Contributing Threads:
- `2.3.5 and 2.4.1 release plans 
<http://mail.python.org/pipermail/python-dev/2005-February/thread.html>`__

-
Clarification sought about including a multidimensional array object into 
Python core
-
note: written by Steve Bethard

Travis Oliphant and others looked into the issues of including an
array object (like that of Numeric or numarray) in Python core.
Guido seemed hesitant, concerned that as Numeric_ and numarray_ continue
to co-exist, the array object wouldn't be the "best of breed" (one of
the requirements for inclusion in Python core).  Travis explained that
most of the disagreements are over ufunc objects, not the basic array
object itself, so it wouldn't be unreasonable to include the array
object without the ufunc object if necessary.  There was also some
suggestion that, at least for basic arithmetic operations, Numeric and
numarray mostly agree, so a stripped-down ufunc object for these
operations might also be inclusion-worthy.
In an aside that grew decidedly un-aside-ish, Paul F. Dubois, Guido
and David Ascher explained why matrix should not inherit from
arrayobject -- this would complicate __new__ and cause confusion when
mixed operands (arrays and matrices) are given to a binary op like
multiplication.
.. _Numeric: http://numeric.scipy.org/
.. _numarray: http://www.stsci.edu/resources/software_hardware/numarray
Contributing Threads:
  - `Clarification sought about including a multidimensional array object into 
Python core 
<http://mail.python.org/pipermail/python-dev/2005-February/051474.html>`__
  - `Numeric life as I see it 
<http://mail.python.org/pipermail/python-dev/2005-February/051493.html>`__

--
More licensing issues - redistribution
--
note:: written by Tony Meyer
As most people know, one of the major changes between the Windows builds of
Python 2.3 and 2.4 is that 2.4 is built with VC7, rather than VC6.  One of
the consequences of this change is that 2.4 links with the Microsoft DLL
msvcr71.dll, which only some people have, rather than msvcr.dll, which
pretty much all Windows users have.
The Windows Python 2.4 distribution installs msvcr71.dll, so it's there when
needed.  However, those building frozen applications (e.g. with py2exe) need
to ensure that their users have msvcr71.dll.
After going through the EULA's for both the commercial and free-to-use
Microsoft compilers, it seems that redistributing mscvr71.dll is acceptable,
if the re-distributor owns a copy of the commercial (not free) compiler,
includes an EULA agreement in one of various forms (e.g. 'click-wrap'), and
follows various other minor conditions (note that just about every message
in this thread contains "IANAL, but").
This leaves those without VC7 unable to redistribute msvcr71.dll, unless, as
some suggested, distributing a frozen Python application can be considered
as redistributing Python (and the various other minor conditions are
followed).
In an interesting twist, it appears that the official Windows Python 2.4
distribution is in breach of the EULA, as a 'click-wrap' license is
required, and is not present.  This element of the thread died without
reaching a conclusion, however.
If you *are* a lawyer (with expertise in this area), and would like to
comment, then please do!
Contributing threads:
   - `Is msvcr71.dll re-redistributable? 
<http://mail.python.org/pipermail/python-dev/2005-February/051393.html>`__

--
Avoiding signs in memory addresses
--
note:: written by Tony Meyer
Troels Walsted Hansen pointed out t

python-dev Summary for 2005-02-15 through 2005-02-28

2005-03-07 Thread Brett C.
[The HTML version of this Summary is available at
http://www.python.org/dev/summary/2005-02-15_2005-02-28.html]

=
Summary Announcements
=

Status of the candidates

It looks like all three candidates for taking over the Summaries (Tony Meyer, 
Steven Bethard, and Tim Lesher) have agreed to actually do the Summaries 
together.  SO no break in the Summaries and I don't have to agonize over 
choosing a successor.

---
PyCon Looms
---
PyCon_ is coming soon!
.. _PyCon: http://www.pycon.org/
=
Summaries
=
-
PEP movements
-
`PEP 309`_ is now final since the 'functional' module has now been checked into 
Python.

.. _PEP 309: http://www.python.org/peps/pep-0309.html
Contributing threads:
  - `PEP 309 enhancements 
<http://mail.python.org/pipermail/python-dev/2005-February/051785.html>`__
  - `PEP 309 
<http://mail.python.org/pipermail/python-dev/2005-February/051789.html>`__

--
Indices for slices other objects with __int__ not okay
--
Travis Oliphant asked if it would be possible to patch slicing so that any 
object that defines __int__ could be used.

Guido didn't like this idea, though.  Float, for instance, has __int__ defined. 
 Guido admitted he "unfortunately copied a design mistake from C here".  He 
said he might add a __trunc__ magic method in Python 3000 for objects that 
really can't be viewed as an int but are willing to have data loss to give one.

Contributing threads:
  - `Fixing _PyEval_SliceIndex so that integer-like objects can be used 
<http://mail.python.org/pipermail/python-dev/2005-February/051669.html>`__
  - `Fix _PyEval_SliceIndex (Take two) 
<http://mail.python.org/pipermail/python-dev/2005-February/051672.html>`__

----
Why can't ``class C(): pass`` be acceptable?

No reason.  =)  So as of Python 2.5 it is acceptable to have empty parentheses 
for class definitions.  It does create a classic class and not a new-style one.

Contributing threads:
  - `Requesting that a class be a new-style class 
<http://mail.python.org/pipermail/python-dev/2005-February/051691.html>`__

--
What basestring is truly meant for
--
What is basestring for?  According to Guido it is purely for unicode and str to 
inherit from to help with checks in code where either type is acceptable.  It 
is *not* meant to be used as a base class for any other classes.

Contributing threads:
  - `UserString 
<http://mail.python.org/pipermail/python-dev/2005-February/051710.html>`__

--
Quickly opening an SF bug/patch in Firefox/Thunderbird
--
Martin v. LÃwis posted a way to use the DictionarySearch_ plug-in for Mozilla 
to launch a browser with the highlighted patch/bug #.  See the email for the 
thread on how to get it to work.

.. _DictionarySearch: 
http://dictionarysearch.mozdev.org/download.php/http://downloads.mozdev.org/dictionarysearch/dictionarysearch_0.8.xpi

Contributing threads:
  - `Quick access to Python bug reports in Thunderbird 
<http://mail.python.org/pipermail/python-dev/2005-February/051804.html>`__


Optimizing ``x in [1, 2, 3]``

Raymond Hettinger has been trying to teach the peepholer some new tricks to 
optimize ``x in [1, 2, 3]`` and the like into a faster operation.  Initially he 
got it to change the list to a tuple.  He then tried turning the list into a 
frozenset, but that had the unforeseen issue of breaking semantics since it 
then required the object being checked for to be hashable.

So Raymond suggested introducing a SearchSet that tried the comparison as a 
frozenset first, and upon failure of hashing, to old way of just looking at 
each item in the list.

But this seemed like overkill since most lists would be small; probably usually 
under 4 items.  But Fredrik Lundh suggested expanding it to ``x == 1 or x == 2 
or x == 3``.  This seemed like a performance boost when the items of the list 
were lists since the COMPARE_OP opcode special-cases comparing ints.  But for 
other instances it probably isn't worth it unless more special-casing is done 
in the opcodes.

Contributing threads:
  - `Prospective Peephole Transformation 
<http://mail.python.org/pipermail/python-dev/2005-February/051651.html>`__

--
A DupStore opcode?
--
Raymond Hettinger suggested a new opcode called DupStore that would replace 
load;store opcode pairs.  Guido questioned if this was leading down a road of 
adding too much extra code for

Ptyon 2.3.5 probably coming in January; get your bugs/patches reported!

2004-12-05 Thread Brett C.
Anthony Baxter, our ever-diligent release manager, mentioned this past week 
that Python 2.3.5 will most likely come to fruition some time in January (this 
is not guaranteed date).  This means that in order to have enough time to 
proper evaluate new patches and bugs they must be reported **now**!  A one 
month lead time is necessary to properly look at, test, and commit patches, let 
alone coming up with solutions to any reported bugs.

Please realize, though, that reporting a bug or submitting a patch now does not 
guarantee that it will committed in time!  The free time of the development 
team is limited.  If you want to help a bug or patch along to make it easier to 
be evaluated and thus raise its chances of being dealt with please see the 
"Helping Out" section of the 'Intro to Development' essay at 
http://www.python.org/dev/dev_intro.html .

As always, both bugs and patches should be reported to Python's SourceForge 
tracker at http://sourceforge.net/bugs/?group_id=5470 and 
http://sourceforge.net/patch/?group_id=5470, respectively.

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


spawn or fork

2004-12-08 Thread C Gillespie
Dear All,

I have a function
def printHello():
fp = open('file','w')
fp.write('hello')
fp.close()

I would like to call that function using spawn or fork. My questions are:

1. Which should I use
2. How do I call that function if it is defined in the same file.

Many thanks

Colin


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


  1   2   3   4   5   6   7   8   9   10   >