static, class and instance methods

2016-10-05 Thread ast

Hello,

In a class there are three possible types of methods,
the static methods, the class methods and the
instance methods

* Class methods are decorated, eg:

@classmethod
def func(cls, a, b):
...

I read that the decorator tranforms 'func' as a descriptor,
and when this descriptor is read, it provided a new
function 'func' where the 1st parameter cls is already filled 
with the class. That's ok for me.



* For instance methods, there is no decorator:

def funct2(self, a, b):
...

self is automatically filled with the instance when we call
funct2 from an instance and not filled if funct2 is called from
a class.
But there is no decorator, why ? Is python doing the conversion
of funct2 to a descriptor itself, behind the scene ?


* static methods are decorated too

@staticmethod
def funct3(a, b):
...

The 1st argument is not supposed to be automatically filled
So what the decorator used for ? 
Just to distinguish funct3 from an instance method ?


regards




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


Re: Assignment versus binding

2016-10-05 Thread Rustom Mody
On Thursday, October 6, 2016 at 11:31:13 AM UTC+5:30, Chris Angelico wrote:
> On Thu, Oct 6, 2016 at 3:57 PM, Gregory Ewing wrote:
> > Chris Angelico wrote:
> >>
> >> Hence my
> >> query about how variadic functions and automatic currying work - how
> >> does it know whether to curry or run?
> >
> >
> > Calling it "automatic" was probably a bad choice of words.
> > I don't mean to imply that Haskell goes around currying
> > things behind your back when you don't want it to.
> 
> No no, I never meant it like that. Automatic currying can be a huge
> boon, but also a stringent limitation.
> 
> > The Haskell definition
> >
> > f x y z = x + y + z
> >
> > is equivalent to the Python definition
> >
> > f = lambda x: lambda y: lambda z: x + y + z
> >
> > To call it, you write
> >
> > f 1 2 3
> 
> Right, and that's fine as long as the function takes a fixed number of
> arguments.
> 
> > For a variable number of arguments, you could use a list
> > instead of a tuple, but again you would need to explicitly
> > construct the list when calling.
> 
> In other words, it still has to take a fixed number of arguments.
> Effectively, variadic functions are _impossible_, so instead you use
> argument packaging.
> 
> That's not necessarily a bad thing. Not all language features need to
> be everywhere. Python has named arguments, and that's great; other
> high level languages generally do the same sort of thing with an
> options mapping. For example, here's how Pike lets you create a
> subprocess:
> 
> // Process.Process(command_line, options);
> Process.Process("ffmpeg -i file.blk file.mkv", ([
> "cwd": "/path/whatever",
> "uid": 1000, "gid": 1000,
> "timeout": 15,
> ]));
> 
> command_line is either a string (which will be split according to
> shell rules) or an array of strings (already split); options is a
> mapping. Here's Python's version of that:
> 
> # subprocess.run(args, *, **kwargs)
> subprocess.run("ffmpeg -i file.blk file.mkv",
> cwd="/path/whatever",
> # uid and gid not supported, but you get the idea
> timeout=15,
> )
> 
> args is either a string or a list of strings, and options are provided
> via keyword arguments. (Interestingly, though Python and Pike offer a
> lot of options as you create a subprocess, there are actually very few
> that are common. Weird.) This is not a problem. And if variadic
> functions are a problem to Haskell, so be it. They don't exist. That
> does at least answer my question about "how does Haskell handle
> variadic functions and currying" - and, importantly, it answers the
> question that comes up periodically of "why can't Python do automatic
> currying".
> 
> > I hope you can see from this that there's no confusion over
> > "whether to curry or run". It all depends on how you define
> > the function.
> 
> Yeah. No confusion because it does fit into the simple structure that
> I described as also working for Python.
> 
> There's one other consideration. With Python functions, you often want
> to run a function for its side effects and ignore its return value.
> With automatic currying, you'd get no error doing that with
> insufficient arguments, you'd just be dropping the curried egg - erm,
> I mean, function - on the ground. It'd be a subtlety like this:
> 
> print("Heading")
> print("===")
> print
> print("First line of data")
> print("Second line of data")
> 
> In Py2, this prints a blank line underneath the heading. In Py3, it
> merely evaluates the print function, then drops it. This can currently
> happen only with the zero argument case, but if you accept
> insufficient arguments to mean curry, it could happen any time. That's
> somewhat unideal.
> 
> ChrisA

It is fair to say that Haskell's variadic function support is poorer than C's
[Collecting into a list fails for different types
 Collecting into a tuple fails because (t1,t2) and (t1,t2,t3) are incompatible
types. There's some heavy artillery called type families round this whose
messiness puts haskell squarely into C++ camp] 

Python's variadicity is better than any other language (I know) (Common Lisp??)
[Except for mutable-default gotcha]
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Assignment versus binding

2016-10-05 Thread Chris Angelico
On Thu, Oct 6, 2016 at 3:57 PM, Gregory Ewing
 wrote:
> Chris Angelico wrote:
>>
>> Hence my
>> query about how variadic functions and automatic currying work - how
>> does it know whether to curry or run?
>
>
> Calling it "automatic" was probably a bad choice of words.
> I don't mean to imply that Haskell goes around currying
> things behind your back when you don't want it to.

No no, I never meant it like that. Automatic currying can be a huge
boon, but also a stringent limitation.

> The Haskell definition
>
> f x y z = x + y + z
>
> is equivalent to the Python definition
>
> f = lambda x: lambda y: lambda z: x + y + z
>
> To call it, you write
>
> f 1 2 3

Right, and that's fine as long as the function takes a fixed number of
arguments.

> For a variable number of arguments, you could use a list
> instead of a tuple, but again you would need to explicitly
> construct the list when calling.

In other words, it still has to take a fixed number of arguments.
Effectively, variadic functions are _impossible_, so instead you use
argument packaging.

That's not necessarily a bad thing. Not all language features need to
be everywhere. Python has named arguments, and that's great; other
high level languages generally do the same sort of thing with an
options mapping. For example, here's how Pike lets you create a
subprocess:

// Process.Process(command_line, options);
Process.Process("ffmpeg -i file.blk file.mkv", ([
"cwd": "/path/whatever",
"uid": 1000, "gid": 1000,
"timeout": 15,
]));

command_line is either a string (which will be split according to
shell rules) or an array of strings (already split); options is a
mapping. Here's Python's version of that:

# subprocess.run(args, *, **kwargs)
subprocess.run("ffmpeg -i file.blk file.mkv",
cwd="/path/whatever",
# uid and gid not supported, but you get the idea
timeout=15,
)

args is either a string or a list of strings, and options are provided
via keyword arguments. (Interestingly, though Python and Pike offer a
lot of options as you create a subprocess, there are actually very few
that are common. Weird.) This is not a problem. And if variadic
functions are a problem to Haskell, so be it. They don't exist. That
does at least answer my question about "how does Haskell handle
variadic functions and currying" - and, importantly, it answers the
question that comes up periodically of "why can't Python do automatic
currying".

> I hope you can see from this that there's no confusion over
> "whether to curry or run". It all depends on how you define
> the function.

Yeah. No confusion because it does fit into the simple structure that
I described as also working for Python.

There's one other consideration. With Python functions, you often want
to run a function for its side effects and ignore its return value.
With automatic currying, you'd get no error doing that with
insufficient arguments, you'd just be dropping the curried egg - erm,
I mean, function - on the ground. It'd be a subtlety like this:

print("Heading")
print("===")
print
print("First line of data")
print("Second line of data")

In Py2, this prints a blank line underneath the heading. In Py3, it
merely evaluates the print function, then drops it. This can currently
happen only with the zero argument case, but if you accept
insufficient arguments to mean curry, it could happen any time. That's
somewhat unideal.

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


Re: Python 3.5 amd64 and win32service

2016-10-05 Thread Nagy László Zsolt

>
> The MWE I provided is so simple. By now, It should be obvious what is
> missing from it. :-(
>
>
The problem is NOT with my code. I just installed a new virtual machine,
and installed python3.5 amd64 + pypiwin32 on it. On that machine, the
test service works perfectly!

So it is with my machine. My machine has Python2.7 32bit, Python 3.5
32bit and Python 3.5 64bit installed. Can this be the problem? But how?

What to do next?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Python 3.5 amd64 and win32service

2016-10-05 Thread Nagy László Zsolt



> On Wed, Oct 5, 2016 at 7:43 AM, Nagy László Zsolt  
> wrote:
>> It did not help. I still get the same error message (service did not
>> respond in time).
> Can you run the service executable directly? From the command line
> check `sc qc TestService`. Run the BINARY_PATH_NAME executable, e.g.
>
> for /f "tokens=1* delims=: " %i in (
> 'sc qc TestService ^| findstr BINARY_PATH_NAME') do @%j
>
> output:
>
> C - Python Service Manager
> Options:
>  -register - register the EXE - this should generally not be necessary.
>  -debug servicename [parms] - debug the Python service.
>
> NOTE: You do not start the service using this program - start the
> service using Control Panel, or 'net start service_name'
All of the commands below were executed in cmd.exe running in elevated
mode (as administrator):

c:\Users\Laci\Python\Projects\gateway>service_test.py install
Installing service TestService
Service installed

c:\Users\Laci\Python\Projects\gateway>sc qc TestService
[SC] QueryServiceConfig SUCCESS

SERVICE_NAME: TestService
TYPE   : 10  WIN32_OWN_PROCESS
START_TYPE : 3   DEMAND_START
ERROR_CONTROL  : 1   NORMAL
BINARY_PATH_NAME   :
"C:\Users\Laci\AppData\Local\Programs\Python\Python35\lib\site-packages\win32\PythonService.exe"
LOAD_ORDER_GROUP   :
TAG: 0
DISPLAY_NAME   : Test Service
DEPENDENCIES   :
SERVICE_START_NAME : LocalSystem



It seems to be the correct executable:

c:\Users\Laci\Python\Projects\gateway>py -3
Python 3.5.2 (v3.5.2:4def2a2901a5, Jun 25 2016, 22:18:55) [MSC v.1900 64
bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.executable
'C:\\Users\\Laci\\AppData\\Local\\Programs\\Python\\Python35\\python.exe'

The service starts to fail in any way:

* service_test.py start
* net start testservice
* from the services.msc with the start button

The error message suggest that the service does not respont to the start
request.

The MWE I provided is so simple. By now, It should be obvious what is
missing from it. :-(


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


Re: I am comfused about the name behavior of Python in recursion

2016-10-05 Thread Gregory Ewing

38016226...@gmail.com wrote:

def rec(a):
a+=1
if a<10:
rec(a)
print(a)

rec(0) gives me 101 normally.Why it works? Because of the stack memory 
management?


Yes. There isn't just one 'a' here, there's a different one
each time rec is called.


Thank you

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


Re: Assignment versus binding

2016-10-05 Thread Gregory Ewing

Chris Angelico wrote:

Hence my
query about how variadic functions and automatic currying work - how
does it know whether to curry or run?


Calling it "automatic" was probably a bad choice of words.
I don't mean to imply that Haskell goes around currying
things behind your back when you don't want it to.

Rather, Haskell provides a very concise syntax for
defining and using curried functions -- so concise that
it's easier to use it than not, so it tends to get used
by default even when currying isn't strictly necessary.

The Haskell definition

f x y z = x + y + z

is equivalent to the Python definition

f = lambda x: lambda y: lambda z: x + y + z

To call it, you write

f 1 2 3

Function application associates to the left, so that's
equivalent to

((f 1) 2) 3)

or in Python,

f(1)(2)(3)

If you don't want currying, there are various options.
For example, you could define it to take a tuple:

f (x, y, z) = x + y + z

which is equivalent to the Python

def f(args):
  x, y, z = args
  return x + y + z

Then you would call it as

f (1, 2, 3)

i.e. construct a tuple of values and then pass it as the
single argument.

For a variable number of arguments, you could use a list
instead of a tuple, but again you would need to explicitly
construct the list when calling.

I hope you can see from this that there's no confusion over
"whether to curry or run". It all depends on how you define
the function.

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


Re: Assignment versus binding

2016-10-05 Thread Rustom Mody
On Thursday, October 6, 2016 at 1:06:07 AM UTC+5:30, BartC wrote:
> On 05/10/2016 14:43, Rustom Mody wrote:
> > On Wednesday, October 5, 2016 at 7:05:02 PM UTC+5:30, BartC wrote:
> 
> >> That's the one it can't find. Actually it can't seem to import any
> >> standard libraries, so the implementation must be screwed up.
> >>
> >> Or is it because I downloaded the Minimal** rather Full version? The
> >> minimal version is already 1.7GB! Can it really be that big and yet not
> >> include such basic stuff? If so, what on earth is taking up all the
> >> space! (The full version was 10-15% bigger.)
> >>
> >> (**
> >> https://downloads.haskell.org/~platform/8.0.1/HaskellPlatform-8.0.1-minimal-x86_64-setup-a.exe)
> >
> > Minimal means only compiler: NO libraries except what the compiler needs to 
> > compile.
> > Almost certainly wrong for a beginner’s testing the waters.
> >
> > You should probably download haskell-platform (full)
> 
> (I've downloaded the full version. Now I have 25,000 files in 2200MB. 
> And it still doesn't work.

We are now crossing the fuzzy OT boundary! Wont persist too much
on list about this. Just a few comments:

Many noobs (to programming/Python/computers/life!) appear out here with
similar questions — it doesn’t work!!! I would guess most of them feel similar
to you. I would like to believe that most of them get out of their difficulty 
with the help of more experienced responders out here.

Likewise Haskell. Go to haskell-cafe or haskell-beginners mailing-lists
and you should cross this roadblock easily enough
https://mail.haskell.org/mailman/listinfo/haskell-cafe
https://mail.haskell.org/mailman/listinfo/beginners

You can write to me also — off-list! Just that I dont consider myself a
haskell expert. Still less a haskell-on-windows expert

For now I will only reiterate haskell-platform without System.* does not
seem reasonable. You took a wrong turning somewhere.

Is haskell large? Yes!
Should it be? OT discussion, relevance of which asymptotically vanishes
thanks to Moore’s law
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: I am comfused about the name behavior of Python in recursion

2016-10-05 Thread Ben Finney
38016226...@gmail.com writes:

> Google told me Python name is a label attaching to the object.

Well, “Google told me” has no necessary bearing on whether it's true :-)
so that's not a good citation to give.

If you need to know what Python terminology means, the Python
documentation is better.

https://docs.python.org/3/glossary.html>

so, I don't think “name” has a technical meaning for Python.

Rather, Python has an assignment operation, which binds a name (or some
other reference) to an object.

> But in this recursive function,the name 'a' will point to different number 
> object.
>
> def rec(a):
>   a+=1
>   if a<10:
>   rec(a)
>   print(a)
>
> rec(0) gives me 101 normally.

Yes. What would you expect instead, and why?

Maybe you think the *name* is passed around. That doesn't happen; in
Python, names are not tractable in that way.

By referencing the name ‘a’, you immediately have the object referred to
by that name. You don't have the name itself, and when you pass that
object, the name you happened to use does not come with it.

-- 
 \ “Science is a way of trying not to fool yourself. The first |
  `\ principle is that you must not fool yourself, and you are the |
_o__)   easiest person to fool.” —Richard P. Feynman, 1964 |
Ben Finney

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


Re: Python and ssh for remote login

2016-10-05 Thread Michael Torrie
On 10/05/2016 11:46 AM, Noah wrote:
> Hello folk,
> 
> I would like to use a python script to ssh into a server using a username
> and password and perhaps ass port.
> 
> Any ideas on how to script that.

If paramiko doesn't fit your needs, traditionally this sort of work was
done with the pexpect module for drying a TTY. There is a submodule of
pexpect called pxssh for automating things.

http://pexpect.readthedocs.io/en/stable/api/pxssh.html

Note that pexpect uses your normal ssh binary.  Paramiko is a complete
implementation of the ssh protocol in python.  Both modules are useful
and fill certain needs.
-- 
https://mail.python.org/mailman/listinfo/python-list


I am comfused about the name behavior of Python in recursion

2016-10-05 Thread 380162267qq
Google told me Python name is a label attaching to the object.
But in this recursive function,the name 'a' will point to different number 
object.

def rec(a):
a+=1
if a<10:
rec(a)
print(a)

rec(0) gives me 101 normally.Why it works? Because of the stack memory 
management?

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


Re: User Interface Suggestions? (newbie)

2016-10-05 Thread Beverly Howard
Thanks guys...

I'm getting overwhelmed with good info, so, I am going to disappear
for a while and will comeback with questions when I get far enough to
ask them.

Again, thanks!

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


Re: Assignment versus binding

2016-10-05 Thread Chris Angelico
On Thu, Oct 6, 2016 at 9:45 AM, BartC  wrote:
> On 05/10/2016 22:34, Chris Angelico wrote:
>>
>> On Thu, Oct 6, 2016 at 6:35 AM, BartC  wrote:
>>>
>>> This is exactly why I persist with my own language implementations. My
>>> current one is only 1/5000th the size but standard libraries are
>>> included!)
>>
>>
>> Yes, it has all the standard library that *you* expect. Does it have
>> what some random person on the internet will expect? Here are a few
>> examples from the standard library of Python:
>>
>> * Unicode character names and categories
>> * Date/time manipulation
>> * Arbitrary-precision rationals
>> * Statistical functions
>> * zlib (zip/gzip) compression and decompression
>> * sqlite3 databasing
>> * BSD sockets
>> * Various internet protocols  (HTTP, FTP, SMTP, IMAP)
>>
>> And that's not even counting the stuff that, if it were proposed
>> today, would probably be pushed to PyPI. Standard libraries tend to be
>> fairly large because they're catering to a lot of people's needs. Mind
>> you, two gig is still a lot, I'm not denying that; but you're saying
>> that yours is half a meg, and I doubt that a full-featured language of
>> today can exist inside a floppy disk.
>
>
> No, it doesn't have all that. But believe me, even with all those things,
> and even if it worked, a 2GB language implementation is *MASSIVE*, not just
> a lot.

Yeah - I agreed with you on that. 2GB+ is huge. But if you try to keep
your language ubertiny, you're going to have a _lot_ of people
complaining that your stdlib doesn't have .

> Even Python, not exactly small, is only 2.5% the size (for 3.4 and
> presumably including all the libraries in your list).

Right. I didn't calculate the percentages, but my cpython/Lib
directory is something like 40MB. You could shrink that down a ton by
eliminating the tests and zipping the rest up, without losing primary
functionality, but it'd still be a good solid bit - about 5MB.

> As to what it consists of, well it doesn't include any How-To videos which
> would account for much of it. But it does seem to have MSYS (ie. half a Unix
> system, 200MB); Mingw (a gcc C compiler, 350MB); docs (180MB); and a library
> (1300MB, but looking at it much of it seems to be useless junk).
>
>> (Also, does your implementation compile directly to machine code, or
>> does it depend on something else? It's easy to make something small if
>> it depends on another compiler/interpreter.)
>
> The language in question is interpreted. It depends on a
> compiler/interpreter which is currently a 300KB executable but could end up
> a bit bigger. The most basic libraries are another 60KB (which will probably
> end up inside the executable). The only dependencies are what is already
> present in an OS (msvcrt.dll for example).

Ignoring OS-provided deps is perfectly fine. But if, for instance,
your program emits C code, then it depends on a C compiler, which adds
to the effective download.

> Small languages are perfectly viable: the JIT version of Lua, for example,
> is only about 225KB, and is very fast.
>
> If I wanted to send you program.lua, and you didn't have Lua, I only need to
> add luajit.exe and lus51.dll (for Windows). With my system, it would be
> program.q and r.exe, even for multi-module apps.

See above about how restricted the stdib is. Lua, on its own, is not a
full-featured language for writing general-purpose applications. It's
designed to be embedded in something else, and it's great at that, but
it doesn't have all the features of a modern apps language. You could
write an Ook interpreter in a handful of bytes of code, but it's not
what you would write an app in. Since you're talking about Windows, I
grabbed file sizes for Windows installers; for Pike, the .msi file is
a 24MB download, and Python clocks in variously at 18MB (32-bit
2.7.12) up to 28MB (64-bit 3.5.2 full installation). Those kinds of
figures are pretty reasonable for full-featured language interpreters.
You get enough for it to actually be usable as-is, but you're not
getting a full C dev environment.

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


Re: Assignment versus binding

2016-10-05 Thread BartC

On 05/10/2016 22:34, Chris Angelico wrote:

On Thu, Oct 6, 2016 at 6:35 AM, BartC  wrote:

This is exactly why I persist with my own language implementations. My
current one is only 1/5000th the size but standard libraries are included!)


Yes, it has all the standard library that *you* expect. Does it have
what some random person on the internet will expect? Here are a few
examples from the standard library of Python:

* Unicode character names and categories
* Date/time manipulation
* Arbitrary-precision rationals
* Statistical functions
* zlib (zip/gzip) compression and decompression
* sqlite3 databasing
* BSD sockets
* Various internet protocols  (HTTP, FTP, SMTP, IMAP)

And that's not even counting the stuff that, if it were proposed
today, would probably be pushed to PyPI. Standard libraries tend to be
fairly large because they're catering to a lot of people's needs. Mind
you, two gig is still a lot, I'm not denying that; but you're saying
that yours is half a meg, and I doubt that a full-featured language of
today can exist inside a floppy disk.


No, it doesn't have all that. But believe me, even with all those 
things, and even if it worked, a 2GB language implementation is 
*MASSIVE*, not just a lot.


Even Python, not exactly small, is only 2.5% the size (for 3.4 and 
presumably including all the libraries in your list).


As to what it consists of, well it doesn't include any How-To videos 
which would account for much of it. But it does seem to have MSYS (ie. 
half a Unix system, 200MB); Mingw (a gcc C compiler, 350MB); docs 
(180MB); and a library (1300MB, but looking at it much of it seems to be 
useless junk).


> (Also, does your implementation compile directly to machine code, or
> does it depend on something else? It's easy to make something small if
> it depends on another compiler/interpreter.)

The language in question is interpreted. It depends on a 
compiler/interpreter which is currently a 300KB executable but could end 
up a bit bigger. The most basic libraries are another 60KB (which will 
probably end up inside the executable). The only dependencies are what 
is already present in an OS (msvcrt.dll for example).


Small languages are perfectly viable: the JIT version of Lua, for 
example, is only about 225KB, and is very fast.


If I wanted to send you program.lua, and you didn't have Lua, I only 
need to add luajit.exe and lus51.dll (for Windows). With my system, it 
would be program.q and r.exe, even for multi-module apps.


What would I need for program.hs? (I already know of some solutions for 
program.py; that's not so straightforward either. But Python 
installations are more common.)


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


Re: working with ctypes and complex data structures

2016-10-05 Thread eryk sun
On Wed, Oct 5, 2016 at 9:03 PM, Michael Felt  wrote:
>
>> +80  args = (1, "name", None), (2, "buff", None), (1, "size",
>> 0), (1, "count", 1)
>
> error #1. paramater type 2 (the buffer might be where data is being put, but
> for the call, the pointer is INPUT)

An output parameter (type 2) has ctypes implicitly create the buffer
and insert it in the argument list. It gets returned as the call's
result. Here's a contrived example:

class Buf(ctypes.Structure):
_fields_ = (('value', ctypes.c_char * 100),)

LP_Buf = ctypes.POINTER(Buf)

proto = ctypes.CFUNCTYPE(ctypes.c_int,
LP_Buf, ctypes.c_char_p, ctypes.c_int)
flags = ((2, 'buf'), (1, 'fmt'), (1, 'arg', 42))
sprintf = proto(('sprintf', ctypes.CDLL(None)), flags)

>>> r = sprintf(b'The answer is %d.')
>>> r.value
b'The answer is 42.'

This works best when combined with an errcheck function. This lets you
see the actual arguments that were passed in the call and the original
result:

def errcheck(result, func, args):
print('result:', result)
print('args:', args)
return args

sprintf.errcheck = errcheck

>>> r = sprintf(b'The answer is %d.')
result: 17
args: (<__main__.Buf object at 0x7fede840bb70>, b'The answer is %d.', 42)

When the errcheck function returns "args", this tells ctypes to
continue with its normal post-processing, so instead of the actual 17
result, it returns the "buf" output parameter:

>>> r.value
b'The answer is 42.'

Notice that I declared the output parameter's type as a pointer type,
but ctypes is smart enough to create a Buf instance for me instead of
just a pointer. Also, because the argument type is a pointer type, its
from_param method implicitly passes the Buf instance by reference.

> class perfstat_xxx:
> def init(self):
> # AIX member in an archive
> _perflib = ctypes.CDLL("libperfstat.a(shr_64.o)")
> _fn_xxx = _perflib.xxx
> # ALL AIX perfstat routines have 4 arguments:
> # (name, buff, sizeof_buff, count)
> # the buff is a pointer to where the information will be stored
> _fn = CFUNCTYPE(c_int, c_void_p, POINTER(xxx_t), c_int, c_int)
> _args = ((1, "name", None), (1, "buff", None), (1, "size", 0),
>  (1, "count", 1))
> _xxx = _fn(("xxx", _fn_xxx), _args)

You should really do this work at the class or module level. Every
time this init() method is called, you're needlessly incrementing the
reference count on the "libperfstat.a(shr_64.o)" shared library and
needlessly creating and instantiating the function pointer type.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: User Interface Suggestions? (newbie)

2016-10-05 Thread Akira Li
Beverly Howard  writes:

>...snip...
> A primary question would be, "What are options for building a display
> that would update displayed values without scrolling?"

To rewrite only the last character, you could use '\b':

  import os
  import itertools
  import time
  for c in map(str.encode, itertools.cycle('\-/|')):
  os.write(1, b'\b'+c)
  time.sleep(.3)

To rewrite only the last line, you could use '\r':

  for i in range(1, 101):
  time.sleep(.1)
  print('\r{:4.0%}'.format(i/100), flush=True, end='')

To control the full screen in the terminal e.g., to change the position,
you could use *blessings* module [1]:

  from blessings import Terminal  # $ pip install blessings

  line = 'Line in the middle of the terminal.'
  term = Terminal()
  with term.hidden_cursor(), term.fullscreen():
  x = (term.width - len(line)) // 2
  y = (term.height - 1) // 2
  with term.location(x, y):
  print(term.bold_white_on_black(line))
  
  with term.location(0, term.height - 1):
  input('press  to exit..')
  
For interactive command-line applications from a simple prompt to full
screen terminal applications, you could use *prompt_toolkit* module [2].

> My first goal is to build a program that would interface with a
> Raspberry Pi to control a heating process.
>

For flexibility, you could split your program into a server and a client
that controls it (text, GUI, web).

To control the Raspberry Pi from your mobile device, you could try Kivy
[3] or just create something quick in Pythonista 3 on iOS [4].  To create
a GUI on desktop, you could try Tkinter, Gtk, Qt frameworks [5,6].

For the web part on the server, you could try *flask*, *bottle* modules
[7], to return json data to a client using http protocol:

  from bottle import route # $ pip install bottle

  @route('/data')
  def data():
  return dict(data=[1,2,3])

On the (text/GUI) client in Python:

  import requests # $ pip install requests

  data = requests.get('https://your.server.example.com/data').json()

Or in the browser using jQuery [8]:

  $.getJSON('https://your.server.example.com/data', function(data) {
  //use data here
  });

To make the interaction more responsive, you could use WebSocket protocol e.g., 
via
Flask-SocketIO on the server [9].

[1]: https://pypi.python.org/pypi/blessings/
[2]: https://python-prompt-toolkit.readthedocs.io/
[3]: https://kivy.org
[4]: http://omz-software.com/pythonista/
[5]: http://www.tkdocs.com/tutorial/onepage.html
[6]: http://doc.qt.io/qt-4.8/gallery-gtk.html
[7]: http://bottlepy.org/docs/stable/
[8]: http://api.jquery.com/jquery.getjson/
[9]: https://flask-socketio.readthedocs.io

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


Re: Assignment versus binding

2016-10-05 Thread Gregory Ewing

BartC wrote:
This is exactly why I persist with my own language implementations. My 
current one is only 1/5000th the size but standard libraries are included!)


You might like to try a different Haskell implementation,
such as Hugs:

https://wiki.haskell.org/Hugs

According to the web page, it comes with most of the same
libraries as ghc. It's based on an older version of the
Haskell standard, though, so I'm not sure if it's up to
date with modern practice regarding monads, etc.

Hugs is what I used last time I messed around with functional
programming, and it seemed to work very nicely. I don't
remember exactly how big it was, but it certainly wasn't
measured in gigabytes! That's just ridiculous.

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


Re: User Interface Suggestions? (newbie)

2016-10-05 Thread Brendan Abel
You should look into using PyQt or PySide.  They are python bindings for
the very popular Qt GUI framework.



On Wed, Oct 5, 2016 at 2:33 PM, Beverly Howard  wrote:

> >> if it is a pi controlling the system I would tend towards controlling it
> from a web page via the network. to keep it updating would require AJAX
> style programming of the web page. <<
>
> Thanks.  I am interested in eventually doing that, but it seems that
> learning how to do it on a local console first would be to my advantage...
> especially during initial testing stages.
>
> fwiw, this project is to transfer (actually re-create) a basic program
> that I wrote for a Tandy Model 100 portable back in the early 80's to
> control ceramic kilns which get to over 2,000 degrees F.
>
> Worked perfectly until a few years ago when there were no longer any Tandy
> Model 100s available at any cost ;-)  (In case anyone is interested in
> fossilized projects, see http://bevhoward.com/kiln/KilnCtrl.htm)
>
> Thanks again for the response and pointers,
> Beverly Howard
>
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: User Interface Suggestions? (newbie)

2016-10-05 Thread Beverly Howard
I _think_ I see what I need... 

window.move(new_y, new_x)
Move cursor to (new_y, new_x)

...even if not, I now know it's there somewhere.

Thanks for the specific links... they are very valuable.

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


Re: User Interface Suggestions? (newbie)

2016-10-05 Thread Beverly Howard
>> I would recommend the 'curses' library: <<

Great!  Thanks!

I'll be back... I'm sure.

Beverly Howard

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


Re: User Interface Suggestions? (newbie)

2016-10-05 Thread Beverly Howard
>> if it is a pi controlling the system I would tend towards controlling it
from a web page via the network. to keep it updating would require AJAX
style programming of the web page. <<

Thanks.  I am interested in eventually doing that, but it seems that learning 
how to do it on a local console first would be to my advantage... especially 
during initial testing stages.

fwiw, this project is to transfer (actually re-create) a basic program that I 
wrote for a Tandy Model 100 portable back in the early 80's to control ceramic 
kilns which get to over 2,000 degrees F.

Worked perfectly until a few years ago when there were no longer any Tandy 
Model 100s available at any cost ;-)  (In case anyone is interested in 
fossilized projects, see http://bevhoward.com/kiln/KilnCtrl.htm)

Thanks again for the response and pointers,
Beverly Howard

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


Re: Assignment versus binding

2016-10-05 Thread Chris Angelico
On Thu, Oct 6, 2016 at 6:35 AM, BartC  wrote:
> This is exactly why I persist with my own language implementations. My
> current one is only 1/5000th the size but standard libraries are included!)

Yes, it has all the standard library that *you* expect. Does it have
what some random person on the internet will expect? Here are a few
examples from the standard library of Python:

* Unicode character names and categories
* Date/time manipulation
* Arbitrary-precision rationals
* Statistical functions
* zlib (zip/gzip) compression and decompression
* sqlite3 databasing
* BSD sockets
* Various internet protocols  (HTTP, FTP, SMTP, IMAP)

And that's not even counting the stuff that, if it were proposed
today, would probably be pushed to PyPI. Standard libraries tend to be
fairly large because they're catering to a lot of people's needs. Mind
you, two gig is still a lot, I'm not denying that; but you're saying
that yours is half a meg, and I doubt that a full-featured language of
today can exist inside a floppy disk.

(Also, does your implementation compile directly to machine code, or
does it depend on something else? It's easy to make something small if
it depends on another compiler/interpreter.)

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


Re: User Interface Suggestions? (newbie)

2016-10-05 Thread Chris Angelico
On Thu, Oct 6, 2016 at 8:19 AM, Beverly Howard  wrote:
> Thanks for the responses... appreciated.
>
>>> print("value value data data data", end="\r") <<
>
> That makes sense, but it also seems to suggest that there is no other way to 
> position the cursor prior to printing.
>
> For example, if that line is halfway down the screen, is there any way to 
> position the cursor two lines above it?
>
> fwiw, I am open to creating functions if there are positioning options, both 
> to meet the need, but, more importantly, to learn.

What I showed you was the very simplest way of doing things. If you
want to move the cursor around, I would recommend the 'curses'
library:

https://docs.python.org/3/library/curses.html
https://docs.python.org/3/howto/curses.html

There are other ways, too; with more info on what you're trying to
accomplish, we could better advise. It might be that a GUI will serve
you well, particularly if you have several pieces of information that
you want to update.

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


Re: User Interface Suggestions? (newbie)

2016-10-05 Thread Beverly Howard
Thanks for the responses... appreciated.

>> print("value value data data data", end="\r") <<

That makes sense, but it also seems to suggest that there is no other way to 
position the cursor prior to printing.

For example, if that line is halfway down the screen, is there any way to 
position the cursor two lines above it?

fwiw, I am open to creating functions if there are positioning options, both to 
meet the need, but, more importantly, to learn.

Beverly Howard

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


Re: working with ctypes and complex data structures

2016-10-05 Thread Michael Felt

Never said thank you - so, thanks!

What I need to do was add the .v at the end so I was accessing the value 
of the structure.


Unlilke Linux, AIX - for reasons unknown to all, they have the time_t 
definition that is specific to the ABI size, at least for these 
performance libraries that probably originated before 64-bit was a 
concern. So my guess is that the dual size in the struct, depending on 
the application size (not the kernel) is to maintain compatibility with 
32-bit applications that had been built against/on a 32-bit kernel.


So, lucky for me it did not work intiallly - because it made me pause 
and understand better what I had written.


And now the real thankyou for the detail you shared!

M


On 03-Oct-16 17:53, eryk sun wrote:

On Mon, Oct 3, 2016 at 2:35 PM, Michael Felt  wrote:

On 02-Oct-16 23:44, eryk sun wrote:

   On Sun, Oct 2, 2016 at 5:50 PM, Michael Felt 
wrote:


b) what I am not understanding - as the basic documentation shows
FOO.value as the way to set/get the value of a _field_

You may be surprised when accessing simple-type fields such as c_int
and c_char_p. These simple types have getter and setter functions that
get called automatically whenever the type is used as a function
result, array index, or struct field. For example:

OK - so lucky me - it "does not work" like earlier examples because I am
referencing, generally, c_ulonglong - and these do not have a automatic
getter/setter function? If not, how do I go about making one (preferably
without needing to right a "method" for each and every _field_ in a class.

No, c_ulonglong is a simple (fundamental) type, which behaves just
like other simple types such as c_int or c_char_p.

On platform's with a 64-bit long, c_ulonglong is an alias for c_ulong
(i.e. type "L"). On the other hand, on 64-bit Windows, c_ulonglong is
an unsigned quad word (i.e. type "Q").

All simple types subclass ctypes._SimpleCData and define a `_type_`
code such as "c" for c_char. On 64-bit Linux the simple types are
defined as follows:

 ?: c_bool
 c: c_char
 z: c_char_p
 u: c_wchar
 Z: c_wchar_p
 P: c_void_p

 b: c_int8, c_byte
 B: c_uint8, c_ubyte
 h: c_int16, c_short
 H: c_uint16, c_ushort
 i: c_int32, c_int
 I: c_uint32, c_uint
 l: c_int64, c_long, c_longlong, c_ssize_t
 L: c_uint64, c_ulong, c_ulonglong, c_size_t

 f: c_float
 d: c_double
 g: c_longdouble

For convenience, simple types are automatically converted when
accessed as a function result, struct field, or array index. As I
mentioned previously, the only way around this behavior is to use a
subclass. A subclass doesn't get automatically converted because it
might define custom methods and attributes that need to be preserved.


I'd alias the type instead of defining a struct, e.g. `time_t =
c_long`. This preserves automatic conversion of the simple type.

The reason for the not using alias is because a) I was trying to be more
inline with the text of the include file. I will have to check the sizeof
c_long (i.e., sizeof(long) in both 32 and 64-bit modes

I don't follow. Currently you wrap a c_int or c_long in a struct when
you could just use those types directly. You have to check the pointer
size, but then it's up to you what assumptions to make about the
target platform's integer sizes. Currently on a 64-bit system you're
assuming a Unix-style LP64 data model [1], in which a long is 64-bit.
That should be fine if you're writing Unix-specific code that doesn't
care about LLP64 Windows systems.

Wrapping the type in a struct provides more type safety, but if I
wanted that I'd create my own simple subclass. For example, assuming
time_t should be a signed integer that's the same size as a pointer:

 class time_t(ctypes._SimpleCData):
 if ctypes.sizeof(ctypes.c_void_p) == ctypes.sizeof(ctypes.c_longlong):
 _type_ = ctypes.c_longlong._type_
 elif ctypes.sizeof(ctypes.c_void_p) == ctypes.sizeof(ctypes.c_long):
 _type_ = ctypes.c_long._type_
 elif ctypes.sizeof(ctypes.c_void_p) == ctypes.sizeof(ctypes.c_int):
 _type_ = ctypes.c_int._type_
 # else raise AttributeError for missing _type_

[1]: https://en.wikipedia.org/wiki/64-bit_computing#64-bit_data_models


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


Re: working with ctypes and complex data structures

2016-10-05 Thread Michael Felt



On 05-Oct-16 22:29, Emile van Sebille wrote:
Thanks for the reply!

After a shirt coffeebreak - back into the fray - and I found the following:


+76  class cpu_total:
   +77  def __init__(self):
   +78  __perfstat__ = CDLL("libperfstat.a(shr_64.o)")
   +79  prototype = CFUNCTYPE(c_int, c_void_p, c_void_p, c_int,
c_int)

error #2 - see below

+80  args = (1, "name", None), (2, "buff", None), (1, "size",
0), (1, "count", 1)
error #1. paramater type 2 (the buffer might be where data is being put, 
but for the call, the pointer is INPUT)

+81  cpu_total = prototype(("perfstat_cpu_total",
__perfstat__), args)
   +82
   +83  buff = perfstat_cpu_total_t()
   +84  cpu_total(buff=buff, size=sizeof(buff))
   +85 
The error #2 is #2, because only after I corrected the inputs did I get 
Type Exceptions. I had hoped that c_void_p was a "typeless" type, mainly 
the right size, but the ctypes interface is more particular when you use 
the CFUNCTYPE() - so now I have my boilerplate for what I hope
can be a tutorial for interfacing - by hand - with complex functions, 
i.e., using one class as the data aka typedef defintion, and a second 
class to work

on it.

In template form:

class perfstat_xxx_t:
_fields_ = ( ... )

class perfstat_xxx:
def init(self):
_perflib = ctypes.CDLL("libperfstat.a(shr_64.o)") # AIX member 
in an archive

_fn_xxx = _perflib.xxx
# ALL AIX perfstat routines have 4 arguments: (name, buff, 
sizeof_buff, count)

# the buff is a pointer to where the information will be stored
_fn = CFUNCTYPE(c_int, c_void_p, POINTER(xxx_t), c_int, c_int)
_args = (1, "name", None), (1, "buff", None), (1, "size", 0), 
(1, "count", 1)

_xxx = _fn(("xxx", _fn_xxx), _args)

_buff = perfstat_cpu_total_t()
_xxx(buff=_buff, size=sizeof(_buff))
self._v = _buff

So, the next question/test will be to move the _fields_ into the 
"second" class definition. I just need to find what "self" attribute 
that is.


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


Re: working with ctypes and complex data structures

2016-10-05 Thread Emile van Sebille

On 10/05/2016 01:06 PM, Michael Felt wrote:



On 02-Oct-16 19:50, Michael Felt wrote:

I am trying to understand the documentation re: ctypes and interfacing
with existing libraries.

I am reading the documentation, and also other sites that have largely
just copied the documentation - as well as the "free chapter" at
O'Reilly (Python Cookbook).


Using O'Reilly and the standard documentation I now have these two
excerpts. The second def works, the first does not.

Someone helping me understand what I am not reading properly in this bit
of documentation - is much appreciated.


from  ctypes  import  c_int,  WINFUNCTYPE,  windll
from  ctypes.wintypes  import  HWND,  LPCSTR,  UINT
prototype  =  WINFUNCTYPE(c_int,  HWND,  LPCSTR,  LPCSTR,  UINT)
paramflags  =  (1,  "hwnd",  0),  (1,  "text",  "Hi"),  (1,
"caption",  None),  (1,  "flags",  0)
MessageBox  =  prototype(("MessageBoxA",  windll.user32),  paramflags)



The MessageBox foreign function can now be called in these ways:






MessageBox()
MessageBox(text="Spam, spam, spam")
MessageBox(flags=2,  text="foo bar")



Note that MessageBox() may give two arguments.

My code: note both def init() are meant to do the same thing, just
different call syntax.

   +76  class cpu_total:
   +77  def __init__(self):
   +78  __perfstat__ = CDLL("libperfstat.a(shr_64.o)")
   +79  prototype = CFUNCTYPE(c_int, c_void_p, c_void_p, c_int,
c_int)
   +80  args = (1, "name", None), (2, "buff", None), (1, "size",
0), (1, "count", 1)
   +81  cpu_total = prototype(("perfstat_cpu_total",
__perfstat__), args)
   +82
   +83  buff = perfstat_cpu_total_t()
   +84  cpu_total(buff=buff, size=sizeof(buff))
   +85
   +86  class perfstat_cpu_total:
   +87  def __init__(self):
   +88  __perfstat__ = CDLL("libperfstat.a(shr_64.o)")
   +89  cpu_total = __perfstat__.perfstat_cpu_total
   +90
   +91  _perfstat_cpu_total = perfstat_cpu_total_t()
   +92  ret = cpu_total(None,
   +93  byref(_perfstat_cpu_total),
   +94  sizeof(perfstat_cpu_total_t), 1)
   +95  self.boot = _perfstat_cpu_total.lbolt.v / 100
   +96  self.ncpus = _perfstat_cpu_total.ncpus
   +97  self._v = _perfstat_cpu_total


When I call the second I can print values and even call functions,
reload the _v, etc..

The first class fails with this message:

a = cpu_total()
Traceback (most recent call last):
  File "", line 135, in 
  File "", line 84, in __init__
TypeError: call takes exactly 1 arguments (2 given)

Thanks for your attention.


the line it's objecting to is:

>+84  cpu_total(buff=buff, size=sizeof(buff))

because the expectation is defined as:

>+77  def __init__(self):

HTH,

Emile

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


Re: Problem with install of Python 3.5.2 on Windows Vista

2016-10-05 Thread eryk sun
On Wed, Oct 5, 2016 at 7:18 PM, Mike Adams  wrote:
> The install seemed to be going well up to near the end when I got the msg 
> 'Python
> has stopped working', I clicked the button then I got the msg 'Setup was 
> successful'.
> I then clicked 'IDLE' and it says it can't find 
> 'api-msi-win-crt-runtime-11-1-0.dll'.  I
> checked Python Tracker and saw that there was a similar issue with Python 
> 3.5.0
> which has been fixed.  So, what do I need to do now to correct this problem?

Make sure your OS is up to date via Windows Update. Microsoft is
supposed to be distributing the Universal CRT as an OS component for
Vista SP2. If you're up to date and the system still can't find CRT
DLLs, then try manually installing the CRT update. It's available for
download here:

https://support.microsoft.com/en-us/kb/3118401
-- 
https://mail.python.org/mailman/listinfo/python-list


python and dos files question

2016-10-05 Thread Xristos Xristoou
hello

some programs allow to export tools to dos .bat files for running from command 
line.
my question is how can i do to running .bat files and how can i do to define 
some variables from the .bat file before the running.

for example i want to define 4 variable and run this .bat file with the python
variables can be strings paths,images and text.

.bat file like this :

@ECHO OFF

REM SET program1=C:\program1\Modules
REM SET PATH=%PATH%;C:\program1

REM Tool: Tool1

program1_cmd tool1 0 -variable1=NULL -variable2=NULL -variable3=NULL 
-variable4=NULL -

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


Re: working with ctypes and complex data structures

2016-10-05 Thread Michael Felt



On 02-Oct-16 19:50, Michael Felt wrote:
I am trying to understand the documentation re: ctypes and interfacing 
with existing libraries.


I am reading the documentation, and also other sites that have largely 
just copied the documentation - as well as the "free chapter" at 
O'Reilly (Python Cookbook).


Using O'Reilly and the standard documentation I now have these two 
excerpts. The second def works, the first does not.


Someone helping me understand what I am not reading properly in this bit 
of documentation - is much appreciated.



from  ctypes  import  c_int,  WINFUNCTYPE,  windll
from  ctypes.wintypes  import  HWND,  LPCSTR,  UINT
prototype  =  WINFUNCTYPE(c_int,  HWND,  LPCSTR,  LPCSTR,  UINT)
paramflags  =  (1,  "hwnd",  0),  (1,  "text",  "Hi"),  (1,  "caption",  None),  (1,  
"flags",  0)
MessageBox  =  prototype(("MessageBoxA",  windll.user32),  paramflags)



The MessageBox foreign function can now be called in these ways:






MessageBox()
MessageBox(text="Spam, spam, spam")
MessageBox(flags=2,  text="foo bar")



Note that MessageBox() may give two arguments.

My code: note both def init() are meant to do the same thing, just different 
call syntax.

   +76  class cpu_total:
   +77  def __init__(self):
   +78  __perfstat__ = CDLL("libperfstat.a(shr_64.o)")
   +79  prototype = CFUNCTYPE(c_int, c_void_p, c_void_p, c_int, c_int)
   +80  args = (1, "name", None), (2, "buff", None), (1, "size", 0), (1, 
"count", 1)
   +81  cpu_total = prototype(("perfstat_cpu_total", __perfstat__), 
args)
   +82
   +83  buff = perfstat_cpu_total_t()
   +84  cpu_total(buff=buff, size=sizeof(buff))
   +85
   +86  class perfstat_cpu_total:
   +87  def __init__(self):
   +88  __perfstat__ = CDLL("libperfstat.a(shr_64.o)")
   +89  cpu_total = __perfstat__.perfstat_cpu_total
   +90
   +91  _perfstat_cpu_total = perfstat_cpu_total_t()
   +92  ret = cpu_total(None,
   +93  byref(_perfstat_cpu_total),
   +94  sizeof(perfstat_cpu_total_t), 1)
   +95  self.boot = _perfstat_cpu_total.lbolt.v / 100
   +96  self.ncpus = _perfstat_cpu_total.ncpus
   +97  self._v = _perfstat_cpu_total


When I call the second I can print values and even call functions, reload the 
_v, etc..

The first class fails with this message:

a = cpu_total()
Traceback (most recent call last):
  File "", line 135, in 
  File "", line 84, in __init__
TypeError: call takes exactly 1 arguments (2 given)

Thanks for your attention.


 



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


Problem with install of Python 3.5.2 on Windows Vista

2016-10-05 Thread Mike Adams
The install seemed to be going well up to near the end when I got the msg 
'Python has stopped working', I clicked the button then I got the msg 'Setup 
was successful'.  I then clicked 'IDLE' and it says it can't find 
'api-msi-win-crt-runtime-11-1-0.dll'.  I checked Python Tracker and saw that 
there was a similar issue with Python 3.5.0 which has been fixed.  So, what do 
I need to do now to correct this problem?
-- 
https://mail.python.org/mailman/listinfo/python-list


Code complexity analysis of Python code (was: Quick way to calculate lines of code/comments in a collection of Python scripts?)

2016-10-05 Thread Ben Finney
Malcolm Greene  writes:

> Looking for a quick way to calculate lines of code/comments in a
> collection of Python scripts. This isn't a LOC per day per developer
> type analysis - I'm looking for a metric to quickly judge the complexity
> of a set of scripts I'm inheriting.

Prospector http://prospector.landscape.io/> is a static analysis
tool for Python code.

Its documentation promises to do what you're asking, please let us know
how it works for you.

-- 
 \  “[Entrenched media corporations will] maintain the status quo, |
  `\   or die trying. Either is better than actually WORKING for a |
_o__)  living.” —ringsnake.livejournal.com, 2007-11-12 |
Ben Finney

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


Re: rocket simulation game with just using tkinter

2016-10-05 Thread Irmen de Jong
On 5-10-2016 2:43, Dennis Lee Bieber wrote:
>   Or do what I once did with the Lunar Lander game on my college
> computer... Target accuracy: Excellent... Landing gear? somewhere on the
> other side of the moon. My vertical velocity was sub-inches per second --
> the horizontal velocity was in multi-feet per second.

My lander game takes the magnitude of the velocity into account and not the 
direction,
so you will still crash when going down a pixel per second but strafing like 
mad :)


>   I also used to crash with more fuel than I started with... Game didn't
> do a sign check on "lbs of fuel to burn", so -10lbs @ 180deg had the same
> effect as 10lbs @ 0deg, but gained fuel.

I forgot to add a fuel gauge! My rocket can fly for all eternity if you manage 
to keep
it in the air :P

The first rocket landing game I ever came across must have been a text only 
version
running on my commodore 64 where it was only printing your current altitude and 
velocity
and fuel level, and then stopped to ask for input. I think it asked for values 
for how
long to burn the engine and for how many seconds. Then it recomputed everything 
and
stopped again for input until you landed safely or crashed...
It must have been a short BASIC listing I copied over from a magazine or 
something.


Irmen

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


Re: Assignment versus binding

2016-10-05 Thread BartC

On 05/10/2016 14:43, Rustom Mody wrote:

On Wednesday, October 5, 2016 at 7:05:02 PM UTC+5:30, BartC wrote:



That's the one it can't find. Actually it can't seem to import any
standard libraries, so the implementation must be screwed up.

Or is it because I downloaded the Minimal** rather Full version? The
minimal version is already 1.7GB! Can it really be that big and yet not
include such basic stuff? If so, what on earth is taking up all the
space! (The full version was 10-15% bigger.)

(**
https://downloads.haskell.org/~platform/8.0.1/HaskellPlatform-8.0.1-minimal-x86_64-setup-a.exe)


Minimal means only compiler: NO libraries except what the compiler needs to 
compile.
Almost certainly wrong for a beginner’s testing the waters.

You should probably download haskell-platform (full)


(I've downloaded the full version. Now I have 25,000 files in 2200MB. 
And it still doesn't work.


This is exactly why I persist with my own language implementations. My 
current one is only 1/5000th the size but standard libraries are included!)


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


Re: Passing Variable to Function

2016-10-05 Thread alister
On Wed, 05 Oct 2016 19:17:33 +, John McKenzie wrote:

> Hello, all.
> 
>  I have a function that takes three arguments, arguments to express an
>  RGB
> colour. The function controls an LED light strip (a Blinkytape).
> 
>  Sometimes I might need to be change what colour is sent to the
>  function,
> so I set a variable with the idea that I can change just the variable
> later if I need to instead of changing a bunch of different lines.
> 
> So I have variables along the lines of this:
> 
> colour ="255, 0, 0"
> colour2 ="100, 0, 0"
> 
> 
> My function, written by the Blinkytape people:
> 
> 
> def changeColor(r, g, b):
>  serialPorts = glob.glob("/dev/ttyACM0*")
>  port = serialPorts[0]
> 
>  if not port:
>  sys.exit("Could not locate a BlinkyTape.")
> 
>  print "BlinkyTape found at: %s" % port
> 
>  bt = BlinkyTape.BlinkyTape(port)
>  bt.displayColor(r, g, b)
>  time.sleep(.1)  # Give the serial driver some time to actually send
> the data
>  bt.close()
> 
> 
>  Later, I have conditional statements like:
> 
> 
> if latitude > maxNetural and latitude < NorthLine:
> changeColor(colour)
> elif latitude > NorthLine:
> changeColor(colour2)
> 
> 
> 
> (There is a GPS device connected, there are variables defined based on
> latitude earlier in the script.)
> 
>  I get an error stating that changeColor takes three arguments and I am
> just giving it one (either "colour1" or "colour2").
> 
> 
>  Is there a way to format the "colour" variable so that the changeColor
> function takes it as the three numbers it is meant to be defined as?
> 
> 
> Entire script:
> http://hastebin.com/qaqotusozo.py
> 
> 
>  Thanks.

use a list & pythons parameter expansion options (I am sure the experts 
here will be able to provide the correct name)

colour1=[100,0,255]

def set_colour(r,g,b):



set_colour(*colour1)



-- 
Come live with me and be my love,
And we will some new pleasures prove
Of golden sands and crystal brooks
With silken lines, and silver hooks.
There's nothing that I wouldn't do
If you would be my POSSLQ.

You live with me, and I with you,
And you will be my POSSLQ.
I'll be your friend and so much more;
That's what a POSSLQ is for.

And everything we will confess;
Yes, even to the IRS.
Some day on what we both may earn,
Perhaps we'll file a joint return.
You'll share my pad, my taxes, joint;
You'll share my life - up to a point!
And that you'll be so glad to do,
Because you'll be my POSSLQ.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Passing Variable to Function

2016-10-05 Thread Brendan Abel
Define your colors as actual number variables instead of a string

color = (255,0,0)
color2 = (0,0,255)

Then use argument expansion to pass them in as separate arguments to the
function

colorFunction(*color)

Brendan

On Wed, Oct 5, 2016 at 12:17 PM, John McKenzie 
wrote:

>
>  Hello, all.
>
>  I have a function that takes three arguments, arguments to express an RGB
> colour. The function controls an LED light strip (a Blinkytape).
>
>  Sometimes I might need to be change what colour is sent to the function,
> so I set a variable with the idea that I can change just the variable
> later if I need to instead of changing a bunch of different lines.
>
> So I have variables along the lines of this:
>
> colour ="255, 0, 0"
> colour2 ="100, 0, 0"
>
>
> My function, written by the Blinkytape people:
>
>
> def changeColor(r, g, b):
>  serialPorts = glob.glob("/dev/ttyACM0*")
>  port = serialPorts[0]
>
>  if not port:
>  sys.exit("Could not locate a BlinkyTape.")
>
>  print "BlinkyTape found at: %s" % port
>
>  bt = BlinkyTape.BlinkyTape(port)
>  bt.displayColor(r, g, b)
>  time.sleep(.1)  # Give the serial driver some time to actually send
> the data
>  bt.close()
>
>
>  Later, I have conditional statements like:
>
>
> if latitude > maxNetural and latitude < NorthLine:
> changeColor(colour)
> elif latitude > NorthLine:
> changeColor(colour2)
>
>
>
> (There is a GPS device connected, there are variables defined based on
> latitude earlier in the script.)
>
>  I get an error stating that changeColor takes three arguments and I am
> just giving it one (either "colour1" or "colour2").
>
>
>  Is there a way to format the "colour" variable so that the changeColor
> function takes it as the three numbers it is meant to be defined as?
>
>
> Entire script:
> http://hastebin.com/qaqotusozo.py
>
>
>  Thanks.
>
>
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Passing Variable to Function

2016-10-05 Thread John McKenzie

 Hello, all.

 I have a function that takes three arguments, arguments to express an RGB 
colour. The function controls an LED light strip (a Blinkytape).

 Sometimes I might need to be change what colour is sent to the function, 
so I set a variable with the idea that I can change just the variable 
later if I need to instead of changing a bunch of different lines.

So I have variables along the lines of this:

colour ="255, 0, 0"
colour2 ="100, 0, 0"


My function, written by the Blinkytape people:


def changeColor(r, g, b):
 serialPorts = glob.glob("/dev/ttyACM0*")
 port = serialPorts[0]

 if not port:
 sys.exit("Could not locate a BlinkyTape.")

 print "BlinkyTape found at: %s" % port

 bt = BlinkyTape.BlinkyTape(port)
 bt.displayColor(r, g, b)
 time.sleep(.1)  # Give the serial driver some time to actually send 
the data
 bt.close()


 Later, I have conditional statements like:


if latitude > maxNetural and latitude < NorthLine:
changeColor(colour)
elif latitude > NorthLine:
changeColor(colour2)



(There is a GPS device connected, there are variables defined based on 
latitude earlier in the script.)

 I get an error stating that changeColor takes three arguments and I am 
just giving it one (either "colour1" or "colour2").


 Is there a way to format the "colour" variable so that the changeColor 
function takes it as the three numbers it is meant to be defined as?


Entire script:
http://hastebin.com/qaqotusozo.py


 Thanks.


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


Re: Python and ssh for remote login

2016-10-05 Thread Noah
On 5 Oct 2016 22:02, "Ethan Furman"  wrote:
>
> On 10/05/2016 10:46 AM, Noah wrote:
>
>> I would like to use a python script to ssh into a server using a username
>> and password [...]
>
>
> I've written a module called scription to help with scripts; it supports
giving passwords to programs like ssh.
>

Hi Ethan and for writting this script.

> Here's an example from one of my utility scripts:
>
> -- 8< ---
> #!/usr/local/bin/python
>
> from getpass import getpass
> from antipathy import Path
> from scription import Command, Execute, Main, OPTION, REQUIRED
>
> ...
>
> @Command(
> repo=('repository to pull [default: all]', OPTION),
> path=('base path to search', OPTION, 'p', Path),
> )
> def pull(repo, *path):
> '''
> retrieve remote change sets
> '''
> password = getpass('[mercurial] password: ')
> target = repo
> for repo in workhorse(*path):
> if target and repo.filename != target:
> continue
> history = Execute(('hg', 'pull'), cwd=repo, password=password,
pty=True)
>
> -- 8< 
>
> and in use:
>
> ==
>
> $ hgc --help
> Available commands/options in hgc
>incoming  displays changesets in remote repo not present locally
>list  displays all repos
>log-date  displays all log entries for matching date
>outgoing  displays changesets in remote repo not present locally
>parentdisplays parent of active branch
>pull  retrieve remote change sets
>push  send local changesets to remote repo
>statusdisplay status for each repo
>updateupdate active files to latest version
>
> $ hgc pull
> [mercurial] password:
>
> ...
> ===
>
> It's available via pip.  Feedback welcome.  :)
>

I will pip it too and try it out and give some feedback based on my use
case.

Thanks a lot.

> --
> ~Ethan~
> --

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


Re: Python and ssh for remote login

2016-10-05 Thread Ethan Furman

On 10/05/2016 10:46 AM, Noah wrote:


I would like to use a python script to ssh into a server using a username
and password [...]


I've written a module called scription to help with scripts; it supports giving 
passwords to programs like ssh.

Here's an example from one of my utility scripts:

-- 8< ---
#!/usr/local/bin/python

from getpass import getpass
from antipathy import Path
from scription import Command, Execute, Main, OPTION, REQUIRED

...

@Command(
repo=('repository to pull [default: all]', OPTION),
path=('base path to search', OPTION, 'p', Path),
)
def pull(repo, *path):
'''
retrieve remote change sets
'''
password = getpass('[mercurial] password: ')
target = repo
for repo in workhorse(*path):
if target and repo.filename != target:
continue
history = Execute(('hg', 'pull'), cwd=repo, password=password, pty=True)

-- 8< 

and in use:

==

$ hgc --help
Available commands/options in hgc
   incoming  displays changesets in remote repo not present locally
   list  displays all repos
   log-date  displays all log entries for matching date
   outgoing  displays changesets in remote repo not present locally
   parentdisplays parent of active branch
   pull  retrieve remote change sets
   push  send local changesets to remote repo
   statusdisplay status for each repo
   updateupdate active files to latest version

$ hgc pull
[mercurial] password:

...
===

It's available via pip.  Feedback welcome.  :)

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


Re: Python and ssh for remote login

2016-10-05 Thread Noah
Hi Rob

Thank you for your email.

I am guessing that is some module. Ok i will pip it and see how it goes.

Noah

On 5 Oct 2016 21:32, "Rob Gaddi"  wrote:

> Noah wrote:
>
> > Hello folk,
> >
> > I would like to use a python script to ssh into a server using a username
> > and password and perhaps ass port.
> >
> > Any ideas on how to script that.
> >
> > Thanks
> >
> > Noah
>
> paramiko
>
> --
> Rob Gaddi, Highland Technology -- www.highlandtechnology.com
> Email address domain is currently out of order.  See above to fix.
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Python and ssh for remote login

2016-10-05 Thread Rob Gaddi
Noah wrote:

> Hello folk,
>
> I would like to use a python script to ssh into a server using a username
> and password and perhaps ass port.
>
> Any ideas on how to script that.
>
> Thanks
>
> Noah

paramiko

-- 
Rob Gaddi, Highland Technology -- www.highlandtechnology.com
Email address domain is currently out of order.  See above to fix.
-- 
https://mail.python.org/mailman/listinfo/python-list


Python and ssh for remote login

2016-10-05 Thread Noah
Hello folk,

I would like to use a python script to ssh into a server using a username
and password and perhaps ass port.

Any ideas on how to script that.

Thanks

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


Re: Quick way to calculate lines of code/comments in a collection of Python scripts?

2016-10-05 Thread Chris Angelico
On Thu, Oct 6, 2016 at 4:56 AM, Malcolm Greene  wrote:
> Looking for a quick way to calculate lines of code/comments in a
> collection of Python scripts. This isn't a LOC per day per developer
> type analysis - I'm looking for a metric to quickly judge the complexity
> of a set of scripts I'm inheriting.

Post the code to GitHub, then click on the file. Up the top, you'll
see something like this:

https://github.com/Rosuav/LetMeKnow/blob/master/letmeknow.py
231 lines (212 sloc)

The first figure is the raw line count. The second is, in theory at
least, the number of lines of "actual code".

Cheating? Totally. Effective? Yup.

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


Quick way to calculate lines of code/comments in a collection of Python scripts?

2016-10-05 Thread Malcolm Greene
Looking for a quick way to calculate lines of code/comments in a
collection of Python scripts. This isn't a LOC per day per developer
type analysis - I'm looking for a metric to quickly judge the complexity
of a set of scripts I'm inheriting.

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


Has any one automated the vmware-vra setup using python?

2016-10-05 Thread Robert Clove

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


Re: I can't run python on my computer

2016-10-05 Thread MRAB

On 2016-10-05 15:19, Camille Benoit via Python-list wrote:

Hi,it has been about a week since the last time I was able to use Python. Most of the 
time, the interpreter doesn't show up and when it does and I am trying to run a program 
it displayed the following message: "IDLE's subprocess didn't make connection. 
Either IDLE can't start a subprocess or personal firewall software is blocking the 
connection."  Can you please help me with this. It'd be a huge help.

Thank you very much.


There are plenty of answers on StackOverflow, e.g.:

Can't run Python via IDLE from Explorer [2013] - IDLE's subprocess 
didn't make connection

http://stackoverflow.com/questions/15888186/cant-run-python-via-idle-from-explorer-2013-idles-subprocess-didnt-make-c

Python error - IDLE's subprocess didn't make connection. Either IDLE 
can't start or personal firewall software is blocking connection

http://stackoverflow.com/questions/29567051/python-error-idles-subprocess-didnt-make-connection-either-idle-cant-start


It might be caused by trying to run a program whose name is the same as 
one of Python's standard modules, so that when Python tries to use the 
module, it gets your program instead.


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


Re: Python -Simplebool

2016-10-05 Thread MRAB

On 2016-10-05 16:01, priya@gmail.com wrote:

Hi,
   I am new to Python and I am learning it. Need some help. I downloaded 
SimpleBool (https://github.com/lujunyan1118/SimpleBool) for simulating Boolean 
models. SimpleBool works in Python. I downloaded the Canopy and executed 
Boolmutation.py file. Below is the Boolmutation.py file


[snip]


After running this file, I got the following 
error:/home/JPJ/Priya_Ph.D/simple_bool/simplebool/SimpleBool-master/BoolMutation.py 
in ()
383 para=ParaParser(sys.argv[1])
384 except:
--> 385 para=ParaParser('mutation.in')
386 simu_mutation(para)

/home/JPJ/Priya_Ph.D/simple_bool/simplebool/SimpleBool-master/BoolMutation.py 
in ParaParser(ParaFile)
254 }  # define parameters
255
--> 256 for each_line in open(ParaFile).readlines():
257 para_name = each_line.split('=')[0].strip()
258 para_value = each_line.split('=')[1].strip()

IOError: [Errno 2] No such file or directory: 'mutation.in'


I can't understand, the problem here. Should I specify anything in the 
Boolmutation.py file. Any help would be appreciated

The traceback says what the problem is: """No such file or directory: 
'mutation.in'""".


You haven't given it the path to the input file on the command line, so 
it's defaulting to 'mutation.in', which it can't find or doesn't exist.


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


Re: Looking for the best way to make this

2016-10-05 Thread mr . marydavid
Here is another example 
http://www.codetwo.com/media/images/exchange-sync-screencast-5.jpg 
-- 
https://mail.python.org/mailman/listinfo/python-list


Looking for the best way to make this

2016-10-05 Thread mr . marydavid
http://www.qualicode.com/EN/images/ScheduleGrid.png

looking to add schedule like that to my software trying with Qt but not sure 
how to .

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


Re: Python -Simplebool

2016-10-05 Thread Joel Goldstick
Welcome,

Please, format your code.  That's a lot of code, and it doesn't run as
presented.  Use text mode in your email program (or whatever you use
to post here), and make sure the indentation is correct.

On Wed, Oct 5, 2016 at 11:01 AM,   wrote:
> Hi,
>I am new to Python and I am learning it. Need some help. I downloaded 
> SimpleBool (https://github.com/lujunyan1118/SimpleBool) for simulating 
> Boolean models. SimpleBool works in Python. I downloaded the Canopy and 
> executed Boolmutation.py file. Below is the Boolmutation.py file
>
>
> #!/bin/env python
> '''
> SimpleBool is a python package for dynamic simulations of boolean network
> Copyright (C) 2013 Junyan Lu
>
> This program is free software: you can redistribute it and/or modify
> it under the terms of the GNU General Public License as published by
> the Free Software Foundation, either version 3 of the License, or
> (at your option) any later version.
>
> This program is distributed in the hope that it will be useful,
> but WITHOUT ANY WARRANTY; without even the implied warranty of
> MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
> GNU General Public License for more details.
>
> You should have received a copy of the GNU General Public License
> along with this program. If not, see .
> '''
> from __future__ import division
> import random
> import sys
>
> class Model:
> def __init__(self,INPUT,mut_nodes=[]):
> random.seed()
> self.KEEP={}
> self.INITIAL={}
> self.REG_NODES=[]
> self.TRUTH_TAB=[]
> self.MAPPING={}
> self.INPUT={}
> self.FINAL={}
> def GetNodes(expression):
> '''convert one line of expression to a node list'''
> nodes = []
> other = ['=', 'and', 'or', 'not'] # remove operator signs
> for node in expression.split():
> node=node.strip('*() ')
> if node not in other:
> nodes.append(node) # remove * ( ) from the node name
> return nodes
> def IterState(expression, keep):
> '''Iterate all the state of input node and output all the inital state and 
> the value of the target node,
> used to construct truth table.
> Return a list of tuples, the first tuple contain the index of target node and 
> its regulators,
> the rest of the tuple contain all the possible state of the target node and 
> its regulators,
> the first element in the tuple is the state of target'''
> nodes = GetNodes(expression)
> record = [] # to store results
> all_regulator = nodes[1:] # all regulator of the target
> target_node = nodes[0]
> record.append(tuple([target_node] + all_regulator)) # record the target node 
> and free regulator
> bool_func = expression.split('=')[1].strip()
> total_ini = 2 ** len(all_regulator) # n nodes have 2**n combinations
> for node in set(all_regulator) & set(keep.keys()):
> vars()[node] = keep[node] # set the value of keeped nodes
> for index in xrange(total_ini):
> state = bin(index)[2:].zfill(len(all_regulator)) # conver a interger to a 
> boolean string with specified length
> for i in range(len(all_regulator)):
> vars()[all_regulator[i]] = int(state[i]) # set the node variable to logical 
> state, if it is not keeped
> if target_node not in keep:
> target_val = int(eval(bool_func)) # caculate the target node's value, kept 
> nodes are considered implicitly
> else: # if the node value has been keeped by hand, than used that value 
> iregulate of the state of its regulators
> target_val = int(keep[target_node])
> record.append(tuple([target_val] + [int(n) for n in state]))
> return record
>
> def ConstructTruthTab(booltext, keep):
> '''Construct the truth table that contain all the possibile input state and 
> output state for each node'''
> all_result = []
> all_nodes = set([]) # all nodes in boolean rule file
> target_nodes = set([]) # nodes have regulators in boolean rule file
> RegNodes = [] # a list contain regulator of each node as a tuple. The tuple 
> index in the list is the target node index
> TruthTab = [] # a list of dictionary contain the truth table for each node. 
> The sequence is in consist with node sequence in mapping
> for line in booltext.split('\n'):
> if line != '' and line[0] != '#':
> line_nodes = GetNodes(line)
> target_nodes = target_nodes | set([line_nodes[0]])
> all_nodes = all_nodes | set(line_nodes)
> if line_nodes[0] not in keep.keys():
> try:
> all_result.append(IterState(line, keep))
> except:
> print "Expressing error of boolean function"
> print line
> else: #if the node has been kept
> all_result.append([(line_nodes[0], line_nodes[0]), (1, 1), (0, 0)])
> unmapped = all_nodes - target_nodes # find the node that do not have 
> regulator, and not specified in the keep list
> for unmapped_id in unmapped:
> all_result.append([(unmapped_id, unmapped_id), (1, 1), (0, 0)]) # if the node 
> do not have any regulate node, then it regulate by itself
> sorted_all = sorted(all_result, key=lambda x:x[0][0])
> mappings = dict(zip([node[0][0] for node in sorted_all], 
> range(len(sorted_all
> # generate list of regulators for each node and the truth table

I can't run python on my computer

2016-10-05 Thread Camille Benoit via Python-list
Hi,it has been about a week since the last time I was able to use Python. Most 
of the time, the interpreter doesn't show up and when it does and I am trying 
to run a program it displayed the following message: "IDLE's subprocess didn't 
make connection. Either IDLE can't start a subprocess or personal firewall 
software is blocking the connection."  Can you please help me with this. It'd 
be a huge help.

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


Python -Simplebool

2016-10-05 Thread priya . bmg
Hi,
   I am new to Python and I am learning it. Need some help. I downloaded 
SimpleBool (https://github.com/lujunyan1118/SimpleBool) for simulating Boolean 
models. SimpleBool works in Python. I downloaded the Canopy and executed 
Boolmutation.py file. Below is the Boolmutation.py file 


#!/bin/env python
'''
SimpleBool is a python package for dynamic simulations of boolean network
Copyright (C) 2013 Junyan Lu

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program. If not, see .
'''
from __future__ import division
import random
import sys

class Model:
def __init__(self,INPUT,mut_nodes=[]):
random.seed()
self.KEEP={}
self.INITIAL={}
self.REG_NODES=[]
self.TRUTH_TAB=[]
self.MAPPING={}
self.INPUT={}
self.FINAL={}
def GetNodes(expression):
'''convert one line of expression to a node list'''
nodes = []
other = ['=', 'and', 'or', 'not'] # remove operator signs
for node in expression.split():
node=node.strip('*() ')
if node not in other:
nodes.append(node) # remove * ( ) from the node name
return nodes
def IterState(expression, keep):
'''Iterate all the state of input node and output all the inital state and the 
value of the target node,
used to construct truth table.
Return a list of tuples, the first tuple contain the index of target node and 
its regulators,
the rest of the tuple contain all the possible state of the target node and its 
regulators,
the first element in the tuple is the state of target'''
nodes = GetNodes(expression)
record = [] # to store results
all_regulator = nodes[1:] # all regulator of the target
target_node = nodes[0]
record.append(tuple([target_node] + all_regulator)) # record the target node 
and free regulator
bool_func = expression.split('=')[1].strip()
total_ini = 2 ** len(all_regulator) # n nodes have 2**n combinations
for node in set(all_regulator) & set(keep.keys()):
vars()[node] = keep[node] # set the value of keeped nodes
for index in xrange(total_ini):
state = bin(index)[2:].zfill(len(all_regulator)) # conver a interger to a 
boolean string with specified length
for i in range(len(all_regulator)):
vars()[all_regulator[i]] = int(state[i]) # set the node variable to logical 
state, if it is not keeped
if target_node not in keep:
target_val = int(eval(bool_func)) # caculate the target node's value, kept 
nodes are considered implicitly
else: # if the node value has been keeped by hand, than used that value 
iregulate of the state of its regulators
target_val = int(keep[target_node])
record.append(tuple([target_val] + [int(n) for n in state]))
return record

def ConstructTruthTab(booltext, keep):
'''Construct the truth table that contain all the possibile input state and 
output state for each node'''
all_result = []
all_nodes = set([]) # all nodes in boolean rule file
target_nodes = set([]) # nodes have regulators in boolean rule file
RegNodes = [] # a list contain regulator of each node as a tuple. The tuple 
index in the list is the target node index
TruthTab = [] # a list of dictionary contain the truth table for each node. The 
sequence is in consist with node sequence in mapping
for line in booltext.split('\n'):
if line != '' and line[0] != '#':
line_nodes = GetNodes(line)
target_nodes = target_nodes | set([line_nodes[0]])
all_nodes = all_nodes | set(line_nodes)
if line_nodes[0] not in keep.keys():
try:
all_result.append(IterState(line, keep))
except:
print "Expressing error of boolean function"
print line
else: #if the node has been kept
all_result.append([(line_nodes[0], line_nodes[0]), (1, 1), (0, 0)])
unmapped = all_nodes - target_nodes # find the node that do not have regulator, 
and not specified in the keep list
for unmapped_id in unmapped:
all_result.append([(unmapped_id, unmapped_id), (1, 1), (0, 0)]) # if the node 
do not have any regulate node, then it regulate by itself
sorted_all = sorted(all_result, key=lambda x:x[0][0])
mappings = dict(zip([node[0][0] for node in sorted_all], 
range(len(sorted_all
# generate list of regulators for each node and the truth table, sorted as the 
mappings
for each_node in sorted_all:
state_dic = {}
regulators = tuple([mappings[node] for node in each_node[0][1:]])
RegNodes.append(regulators)
for each_state in each_node[1:]:
state_dic[each_state[1:]] = each_state[0]
TruthTab.append(state_dic)
return RegNodes, TruthTab, mappings #
self.INPUT=INPUT
for on_nodes in INPUT['ini_on']:
self.INITIAL[on_nodes] = True
for off_nodes in INPUT['ini_off']:
self.INITIAL[off_nodes] = False

for on_nodes in IN

Re: Assignment versus binding

2016-10-05 Thread Ben Bacarisse
BartC  writes:

> On 05/10/2016 11:03, Ben Bacarisse wrote:
>> Gregory Ewing  writes:
>>
>>> Steve D'Aprano wrote:
>>>
 And (shamelessly using Python syntax) if I have a function:

 def spam(x):
 print(x)
 print(x+1)

 spam(time.sleep(60) or 1)
>>>
>>> You can't write that in Haskell, because Haskell's
>>> equivalent of print() is not a function (or at least
>>> it's not a function that ever returns), and neither
>>> is sleep().
>>
>> I suppose it all depends on what "that" is exactly.  Here is the closest
>> match I could come up with:
>>
>> import Control.Concurrent
>>
>> spam io = do x <- io;
>>  print x;
>>  print (x+1)
>>
>> main = spam (do threadDelay (2*10^6); return 1)
>>
>> It matches the Python in that the delay happens once.  To get the
>> behaviour being hinted at (two delays) you need to re-bind the IO
>> action:
>>
>> spam io = do x <- io;
>>  print x;
>>  x <- io;
>>  print (x+1)
>
> (I downloaded Haskell (ghc) yesterday to try this out. First problem
> was that I couldn't figure out how to do two things one after another
> (apparently you need 'do').
>
> And when I tried to use a random number function in an expression to
> see if it was evaluated once or twice, apparently my installation
> doesn't have any form of random() (despite being a monstrous 1700MB
> with 20,000 files).

I'm not sure what is installed by default.  The place to look is the
module System.Random:

$ ghci
GHCi, version 7.10.3: http://www.haskell.org/ghc/  :? for help
Prelude> import System.Random
Prelude System.Random> getStdRandom random
-4343223433618198958

If this does not work "out of the box" you need to use something like
cabal to install System.Random.

> Not an easy language..)

Not an easy language to get started with, for sure.  It is very
different to the languages that most people have got used to.  I image
that people who learn it first have a different view (in more ways than
one!).

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


Re: User Interface Suggestions? (newbie)

2016-10-05 Thread Chris Angelico
On Thu, Oct 6, 2016 at 12:10 AM, Beverly Howard  wrote:
> I'm new to Python, but have three decades of experience with FoxPro and VFP 
> plus I started programming in Basic and still comfortable with that.
>
> I have spent some time with Python and am now fairly familiar with the syntax 
> and functions, but building a user interface has me stopped.
>
> A primary question would be, "What are options for building a display that 
> would update displayed values without scrolling?"
>
> My first goal is to build a program that would interface with a Raspberry Pi 
> to control a heating process.
>

Good question to ask, and thank you for declaring your background.
Also, welcome!

In Python, the simplest and cleanest way to build a user interface is
the console. You'd use something like this:

print("value value data data data", end="\r")

That'll print out whatever you want, and then move the cursor to the
beginning of the line, so the next output will be on the same line.
This is the technique I use in LetMeKnow [1] to create a spinning
display; when the event changes, it writes a newline (and thus
advances to the next line of output), but otherwise, it overwrites
each line with the next.

Other good user interfaces include web browsers (build your app in a
mix of Python and HTML, so a button click sends a request to a server)
and classic GUIs (Python includes one GUI library by default, and you
can pick up others from PyPI). But I'd recommend giving the end="\r"
technique a try first; based on your "without scrolling" comment, I'm
guessing you've already tried the console and found it almost, but not
quite, what you want, so this would be a very small change.

Hope that helps! Happy to clarify further if you have questions.

ChrisA

[1] https://github.com/Rosuav/LetMeKnow/blob/master/letmeknow.py#L175
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: User Interface Suggestions? (newbie)

2016-10-05 Thread alister
On Wed, 05 Oct 2016 06:10:05 -0700, Beverly Howard wrote:

> I'm new to Python, but have three decades of experience with FoxPro and
> VFP plus I started programming in Basic and still comfortable with that.
> 
> I have spent some time with Python and am now fairly familiar with the
> syntax and functions, but building a user interface has me stopped.
> 
> A primary question would be, "What are options for building a display
> that would update displayed values without scrolling?"
> 
> My first goal is to build a program that would interface with a
> Raspberry Pi to control a heating process.
> 
> Thanks in advance,
> Beverly Howard

if it is a pi controlling the system I would tend towards controlling it 
from a wb page via the network. to keep it updating would require AJAX 
style programming of the web page.

if you have a monitor keyboard etc.. attached to the pi & want to use it 
directly there are a number of GUI tool-kits available
tkinter being in the std library but possibly also the most limited 



-- 
"Innovation, innovate, and the concept of doing what everyone else did 20
 years ago are registered trademarks of Microsoft Corporation. Other
 buzzwords, euphemisms, and blatant lies are trademarks of their 
respective
 owners."

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


Re: Assignment versus binding

2016-10-05 Thread Rustom Mody
On Wednesday, October 5, 2016 at 7:05:02 PM UTC+5:30, BartC wrote:
> On 05/10/2016 14:13, Rustom Mody wrote:
> > On Wednesday, October 5, 2016 at 4:24:01 PM UTC+5:30, BartC wrote:
> >> On 05/10/2016 11:03, Ben Bacarisse wrote:
> 
> >>> spam io = do x <- io;
> >>>  print x;
> >>>  x <- io;
> >>>  print (x+1)
> >>
> >> (I downloaded Haskell (ghc) yesterday to try this out. First problem was
> >> that I couldn't figure out how to do two things one after another
> >> (apparently you need 'do').
> >>
> >> And when I tried to use a random number function in an expression to see
> >> if it was evaluated once or twice, apparently my installation doesn't
> >> have any form of random() (despite being a monstrous 1700MB with 20,000
> >> files).
> >
> > In general this may be true.
> > In general you need to use cabal or stack in haskell-world like you use
> > pip in python world to get what stuff you need
> >
> > However for Random it seems to be part of System:
> > https://hackage.haskell.org/package/random-1.1/docs/System-Random.html
> >
> >
> > Here’s a session just blindly following
> > https://www.schoolofhaskell.com/school/starting-with-haskell/libraries-and-frameworks/randoms
> >
> > $ ghci
> > GHCi, version 7.10.3: http://www.haskell.org/ghc/  :? for help
> > Prelude> import System.Random
> 
> That's the one it can't find. Actually it can't seem to import any 
> standard libraries, so the implementation must be screwed up.
> 
> Or is it because I downloaded the Minimal** rather Full version? The 
> minimal version is already 1.7GB! Can it really be that big and yet not 
> include such basic stuff? If so, what on earth is taking up all the 
> space! (The full version was 10-15% bigger.)
> 
> (** 
> https://downloads.haskell.org/~platform/8.0.1/HaskellPlatform-8.0.1-minimal-x86_64-setup-a.exe)

Minimal means only compiler: NO libraries except what the compiler needs to 
compile.
Almost certainly wrong for a beginner’s testing the waters.

You should probably download haskell-platform (full)

[Disclaimer: Dont know too much about haskell on windows]
-- 
https://mail.python.org/mailman/listinfo/python-list


any json data validation library recommendation?

2016-10-05 Thread Maciej Dziardziel
Hi

I'm writing json data validation tool in a language other than python,
but knowing that there is plenty of good tools for it,
I am looking for inspiration here.

I am aware of json schema standard, but on its own its
rather verbose and I'd rather have models defined in code
(directly or via some DSL).
Can anyone recommend library that provides
good API for declaring data schemas, so I could see how it could be done?

(Doing it is not a problem. Doing it in a way that's convenient for users,
readable and generates good error messages is something I care about).

Thanks
-- 
Maciej Dziardziel
fied...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Assignment versus binding

2016-10-05 Thread Chris Angelico
On Thu, Oct 6, 2016 at 12:13 AM, Gregory Ewing
 wrote:
> Chris Angelico wrote:
>>
>> How do you handle variadic functions?
>
>
> All functions in Haskell take exactly one argument, so
> there isn't really any such thing as a variadic function.
> The argument can be a list, however, so you can get the
> same effect.

That basically just means you always pack and unpack *args. If you're
talking about currying a function - particularly *automatic* currying
- functions have to take multiple arguments, and in a naive
implementation, a fixed number. Something like:

def auto_curry(f):
@functools.wraps(f)
def curry_or_run(*args):
if len(args) >= f.__code__.co_argcount:
 return f(*args)
return functools.partial(curry_or_run, *args)
return curry_or_run

@auto_curry
def f(a, b, c):
return a + b * c

print(f(1)(2, 3))
print(f(1, 2)(3))
print(f(1, 2, 3))
print(f(1)(2)(3))

That works fine as long as you can probe the function for co_argcount.
(And as long as you don't have keyword arguments, but they're a bit of
a Python peculiarity so I doubt that'll get in the way.) Hence my
query about how variadic functions and automatic currying work - how
does it know whether to curry or run?

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


Re: Assignment versus binding

2016-10-05 Thread BartC

On 05/10/2016 14:13, Rustom Mody wrote:

On Wednesday, October 5, 2016 at 4:24:01 PM UTC+5:30, BartC wrote:

On 05/10/2016 11:03, Ben Bacarisse wrote:



spam io = do x <- io;
 print x;
 x <- io;
 print (x+1)


(I downloaded Haskell (ghc) yesterday to try this out. First problem was
that I couldn't figure out how to do two things one after another
(apparently you need 'do').

And when I tried to use a random number function in an expression to see
if it was evaluated once or twice, apparently my installation doesn't
have any form of random() (despite being a monstrous 1700MB with 20,000
files).


In general this may be true.
In general you need to use cabal or stack in haskell-world like you use
pip in python world to get what stuff you need

However for Random it seems to be part of System:
https://hackage.haskell.org/package/random-1.1/docs/System-Random.html


Here’s a session just blindly following
https://www.schoolofhaskell.com/school/starting-with-haskell/libraries-and-frameworks/randoms

$ ghci
GHCi, version 7.10.3: http://www.haskell.org/ghc/  :? for help
Prelude> import System.Random


That's the one it can't find. Actually it can't seem to import any 
standard libraries, so the implementation must be screwed up.


Or is it because I downloaded the Minimal** rather Full version? The 
minimal version is already 1.7GB! Can it really be that big and yet not 
include such basic stuff? If so, what on earth is taking up all the 
space! (The full version was 10-15% bigger.)


(** 
https://downloads.haskell.org/~platform/8.0.1/HaskellPlatform-8.0.1-minimal-x86_64-setup-a.exe)


--
Bartc

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


Re: Assignment versus binding

2016-10-05 Thread Gregory Ewing

Chris Angelico wrote:

So how do you handle something that, by its nature, has BOTH side
effects and a return value?


A Pascal purist would probably say that you should make
it a procedure, and use var parameters to pass back
any results.

In the case of something like the unix write() call, this
may actually make more sense anyway, because in Pascal
you can't just ignore the return value of a function
if you don't want it. Passing a result parameter that
you don't use is probably less obtrusive to read than
assigning to a variable that you don't use.

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


Re: Assignment versus binding

2016-10-05 Thread Rustom Mody
On Wednesday, October 5, 2016 at 4:24:01 PM UTC+5:30, BartC wrote:
> On 05/10/2016 11:03, Ben Bacarisse wrote:
> > Gregory Ewing  writes:
> >
> >> Steve D'Aprano wrote:
> >>
> >>> And (shamelessly using Python syntax) if I have a function:
> >>>
> >>> def spam(x):
> >>> print(x)
> >>> print(x+1)
> >>>
> >>> spam(time.sleep(60) or 1)
> >>
> >> You can't write that in Haskell, because Haskell's
> >> equivalent of print() is not a function (or at least
> >> it's not a function that ever returns), and neither
> >> is sleep().
> >
> > I suppose it all depends on what "that" is exactly.  Here is the closest
> > match I could come up with:
> >
> > import Control.Concurrent
> >
> > spam io = do x <- io;
> >  print x;
> >  print (x+1)
> >
> > main = spam (do threadDelay (2*10^6); return 1)
> >
> > It matches the Python in that the delay happens once.  To get the
> > behaviour being hinted at (two delays) you need to re-bind the IO
> > action:
> >
> > spam io = do x <- io;
> >  print x;
> >  x <- io;
> >  print (x+1)
> 
> (I downloaded Haskell (ghc) yesterday to try this out. First problem was 
> that I couldn't figure out how to do two things one after another 
> (apparently you need 'do').
> 
> And when I tried to use a random number function in an expression to see 
> if it was evaluated once or twice, apparently my installation doesn't 
> have any form of random() (despite being a monstrous 1700MB with 20,000 
> files).

In general this may be true.
In general you need to use cabal or stack in haskell-world like you use
pip in python world to get what stuff you need

However for Random it seems to be part of System:
https://hackage.haskell.org/package/random-1.1/docs/System-Random.html


Here’s a session just blindly following
https://www.schoolofhaskell.com/school/starting-with-haskell/libraries-and-frameworks/randoms

$ ghci 
GHCi, version 7.10.3: http://www.haskell.org/ghc/  :? for help
Prelude> import System.Random
Prelude System.Random> import Control.Monad (replicateM)
Prelude System.Random Control.Monad> let main = replicateM 10 (randomIO :: IO 
Float) >>= print
Prelude System.Random Control.Monad> main
[0.57468385,0.84545535,0.1624645,0.8491243,0.48347688,2.9622138e-2,0.70125,0.9189069,0.5903369,0.26639372]

Small modif from the link above:
I changed
main = replicateM...
to
let main = replicateM...

for reasons quite related to this whole long thread! viz.
= ie definitions goes into haskell files
At the repl one can only write expressions
let wangles around that

> 
> Not an easy language..)

I am not going to argue that!
Every language (that Ive ever used) has oddities that tripped me up.
Once these initial hurdles are crossed is it hard or easy is a real
but different question.
-- 
https://mail.python.org/mailman/listinfo/python-list


User Interface Suggestions? (newbie)

2016-10-05 Thread Beverly Howard
I'm new to Python, but have three decades of experience with FoxPro and VFP 
plus I started programming in Basic and still comfortable with that.

I have spent some time with Python and am now fairly familiar with the syntax 
and functions, but building a user interface has me stopped.

A primary question would be, "What are options for building a display that 
would update displayed values without scrolling?"

My first goal is to build a program that would interface with a Raspberry Pi to 
control a heating process.

Thanks in advance,
Beverly Howard
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Assignment versus binding

2016-10-05 Thread Gregory Ewing

Chris Angelico wrote:

How do you handle variadic functions?


All functions in Haskell take exactly one argument, so
there isn't really any such thing as a variadic function.
The argument can be a list, however, so you can get the
same effect.

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


Re: Assignment versus binding

2016-10-05 Thread Rustom Mody
On Wednesday, October 5, 2016 at 12:21:35 PM UTC+5:30, Chris Angelico wrote:
> On Wed, Oct 5, 2016 at 5:19 PM, Rustom Mody  wrote:
> > Its ironical:
> > - Function in Fortran was meant to emulate math-functions
> > - C took the same thing and did a ‘small little syntax elision’ viz
> > conflating function and subprogram (procedure in Pascal speak) all under
> > the heading of function. In Pascal it was certainly a publicised intent
> > to sharply distinguish functions — no side-effects — from procedures — no 
> > return value.
> > - Finally this abuse of notation (and notions) has become such a norm 
> > (normal!)
> > that people are surprised to find non-abusive languages!
> 
> So how do you handle something that, by its nature, has BOTH side
> effects and a return value? For instance, writing to a socket has
> three results:
> 
> 1) Data is sent to the socket (side effect), possibly with consequent
> changes to visible state
> 2) Status return saying how much was written
> 3) Possible error return in the event of failure.

Not sure I understand your question.
Analogy: Take Linux syscalls

In C you do
#include 
And then do (say)
n = read(fd,buffer,bufsize);

In assembly you do (something like!)
mov eax, 1   # read's number
mov ebx, fd
mov ecx, buffer
mov edx, bufsize
int 0x80
mov n, eax

You could argue that they are identical
Or they are completely different... unrelated

Truth is somewhere in between; someone who knows this world would 
be able to deduce one from the other.
OTOH its hard to deny the fact that the assembly is far from the C.

Likewise here.
You cant use effectful things and say thats a function
But you can get any effects you want:
https://hackage.haskell.org/package/network-2.6.3.1/docs/Network-Socket.html

starts with this para:

| The Network.Socket module is for when you want full control over sockets. 
| Essentially the entire C socket API is exposed through this module; in 
| general the operations follow the behaviour of the C functions of the same 
| name (consult your favourite Unix networking book).

One could simulate something like this even in python by saying that
- socket is a None returning function (procedure)
- it takes a list of len 3 say arg
- which is mutated on return to contain (size, buffer, errorstate)

No its not pythonic
Its not haskellic either

Just saying that world-effects does not imply or follow from impure functions
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Python 3.5 amd64 and win32service

2016-10-05 Thread eryk sun
On Wed, Oct 5, 2016 at 7:43 AM, Nagy László Zsolt  wrote:
> It did not help. I still get the same error message (service did not
> respond in time).

Can you run the service executable directly? From the command line
check `sc qc TestService`. Run the BINARY_PATH_NAME executable, e.g.

for /f "tokens=1* delims=: " %i in (
'sc qc TestService ^| findstr BINARY_PATH_NAME') do @%j

output:

C - Python Service Manager
Options:
 -register - register the EXE - this should generally not be necessary.
 -debug servicename [parms] - debug the Python service.

NOTE: You do not start the service using this program - start the
service using Control Panel, or 'net start service_name'
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Assignment versus binding

2016-10-05 Thread BartC

On 05/10/2016 11:03, Ben Bacarisse wrote:

Gregory Ewing  writes:


Steve D'Aprano wrote:


And (shamelessly using Python syntax) if I have a function:

def spam(x):
print(x)
print(x+1)

spam(time.sleep(60) or 1)


You can't write that in Haskell, because Haskell's
equivalent of print() is not a function (or at least
it's not a function that ever returns), and neither
is sleep().


I suppose it all depends on what "that" is exactly.  Here is the closest
match I could come up with:

import Control.Concurrent

spam io = do x <- io;
 print x;
 print (x+1)

main = spam (do threadDelay (2*10^6); return 1)

It matches the Python in that the delay happens once.  To get the
behaviour being hinted at (two delays) you need to re-bind the IO
action:

spam io = do x <- io;
 print x;
 x <- io;
 print (x+1)


(I downloaded Haskell (ghc) yesterday to try this out. First problem was 
that I couldn't figure out how to do two things one after another 
(apparently you need 'do').


And when I tried to use a random number function in an expression to see 
if it was evaluated once or twice, apparently my installation doesn't 
have any form of random() (despite being a monstrous 1700MB with 20,000 
files).


Not an easy language..)

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


Re: Assignment versus binding

2016-10-05 Thread Ben Bacarisse
Gregory Ewing  writes:

> Steve D'Aprano wrote:
>
>> And (shamelessly using Python syntax) if I have a function:
>>
>> def spam(x):
>> print(x)
>> print(x+1)
>>
>> spam(time.sleep(60) or 1)
>
> You can't write that in Haskell, because Haskell's
> equivalent of print() is not a function (or at least
> it's not a function that ever returns), and neither
> is sleep().

I suppose it all depends on what "that" is exactly.  Here is the closest
match I could come up with:

import Control.Concurrent

spam io = do x <- io;
 print x;
 print (x+1)

main = spam (do threadDelay (2*10^6); return 1)

It matches the Python in that the delay happens once.  To get the
behaviour being hinted at (two delays) you need to re-bind the IO
action:

spam io = do x <- io;
 print x;
 x <- io;
 print (x+1)


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


Re: 'str' object has no attribute 'intersection' and unhashable set

2016-10-05 Thread meInvent bbird
after change to frozenset , 

it seems can classify into 7 repeated group

but, in real data

this consecutive lines can be also a group
but i can not find this,
actually i do not understand how the function works
is there any algorithm tutorials or books or external library that
can have a better result for finding repeated lines as group in grouping 
application

1,[(1, 0, 1)]
1,[(1, 0, 1)]
1,[(1, 0, 1)]
1,[(1, 0, 1)]


real data
1,[(1, 0, 1)]
1,[]
1,[(-1, 1, -2), (2, -1/2, 1)]
0,[(1, 0, 0)]
1,[(1, 0, 1)]
1,[]
1,[]
0,[{a: 0}, {b: -1/c, a: 0}, {c: 1, b: -1, a: 0}, {c: -1, b: 1, a: 0}]
0,[(1/2 + sqrt(5)/2, -sqrt(5)/2 + 1/2, -1/2 + sqrt(5)/2), (-sqrt(5)/2 + 1/2, 
1/2 + sqrt(5)/2, -sqrt(5)/2 - 1/2)]
0,[(1, 0, 0)]
1,[(1, 0, 1)]
1,[(1, 0, 1)]
1,[(1, 0, 1)]
1,[(1, 0, 1)]
1,[]
1,[]
0,[(1/2 + sqrt(5)/2, -sqrt(5)/2 + 1/2, -1/2 + sqrt(5)/2), (-sqrt(5)/2 + 1/2, 
1/2 + sqrt(5)/2, -sqrt(5)/2 - 1/2)]
0,[(1, 0, 0)]
1,[]
1,[(-1, 1, -2), (2, -1/2, 1)]
0,[(1, 0, 0)]
1,[(1, 0, 1)]
1,[(1, 0, 1)]
1,[]
1,[(-1, 1, -2), (2, -1/2, 1)]
0,[(-1, -1, 1), (1, 1, -1)]
1,[]
0,[(1/2 + sqrt(5)/2, -sqrt(5)/2 + 1/2, -1/2 + sqrt(5)/2), (-sqrt(5)/2 + 1/2, 
1/2 + sqrt(5)/2, -sqrt(5)/2 - 1/2)]
0,[(-1, -1, 1), (1, 1, -1)]
1,[]
0,[(1/2 + sqrt(5)/2, -sqrt(5)/2 + 1/2, -1/2 + sqrt(5)/2), (-sqrt(5)/2 + 1/2, 
1/2 + sqrt(5)/2, -sqrt(5)/2 - 1/2)]
0,[(-1, -1, 1), (1, 1, -1)]
1,[(-1, 1, -2), (2, -1/2, 1)]
0,[(-1, -1, 1), (1, 1, -1)]
1,[(-1, 1, -2), (2, -1/2, 1)]
0,[(1, 0, 0)]
1,[]
1,[(-1, 1, -2), (2, -1/2, 1)]
0,[(-1, -1, 1), (1, 1, -1)]
1,[]
0,[(1/2 + sqrt(5)/2, -sqrt(5)/2 + 1/2, -1/2 + sqrt(5)/2), (-sqrt(5)/2 + 1/2, 
1/2 + sqrt(5)/2, -sqrt(5)/2 - 1/2)]
0,[(1, 0, 0)]
1,[(1, 0, 1)]
1,[]

def consolidate(sets):
# http://rosettacode.org/wiki/Set_consolidation#Python:_Iterative
setlist = [s for s in sets if s]
for i, s1 in enumerate(setlist):
if s1:
for s2 in setlist[i+1:]:
intersection = s1.intersection(s2)
if intersection:
s2.update(s1)
s1.clear()
s1 = s2
return [s for s in setlist if s]

def wrapper(seqs):
consolidated = consolidate(map(set, seqs))
groupmap = {x: i for i,seq in enumerate(consolidated) for x in seq}
output = {}
for seq in seqs:
target = output.setdefault(groupmap[seq[0]], [])
target.append(seq)
return list(output.values())

with open("testing1.txt", "r") as myfile:
content = myfile.readlines()
gr = [['']]
for ii in range(0,500):
try:
gr = [[frozenset(content[ii].split())]] + gr
except:
print "error" + str(content[ii])
groups = wrapper(gr)
for i, group in enumerate(wrapper(gr)):
print('g{}:'.format(i), group)
print("\n")




On Wednesday, October 5, 2016 at 3:40:25 PM UTC+8, dieter wrote:
> meInvent bbird  writes:
> ... not looking at the details ...
> 
> "'str' object has not attribute 'intersection'": apparently,
> something is really a string (an 'str') while you expect it to be a set.
> 
> "unhashable set": maybe, you try to put a set into another set (or a dict;
> or somewhere else where hashability is necessary). A "set" itself is
> unhashable (like many mutable standard data types); you may consider to use
> "frozenset" in those cases (of course, a "frozenset" is immutable, i.e.
> cannot be changed after creation).

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


Re: Python 3.5 amd64 and win32service

2016-10-05 Thread Nagy László Zsolt

>> But again, that is not related to the question. Why does it not work?
>> What is missing?
> If you mean why running the service doesn't work, it should once you
> run the post-install script that copies pywintypes35.dll to the
> Windows System32 directory. This DLL is required by PythonService.exe.
> It fails to start without it. After running the post-install script,
> run `where pywintypes35.dll` to verify that it was copied correctly.
It did not help. I still get the same error message (service did not
respond in time).

By the way, running the aforementioned post install script raised this
error:

C:\Users\User\appdata\Local\programs\Python\Python35\Scripts>pywin32_postinstall.py
-install
Traceback (most recent call last):
  File
"C:\Users\User\appdata\Local\programs\Python\Python35\Scripts\pywin32_postinstall.py",
line 6, in 
import winreg as winreg
ImportError: No module named winreg

In addition to the replacements, I had to do "py -3
pywin32_postinstall.py -install". The package developer should add
"#!/usr/bin/python3" to the beginning of that post install script, so
that py.exe can select the right interpreter automatically.

In my opinion, the pypiwin32 and pywin32 packages are both broken. I say
this because I cannot just "install the package". The pywin32 installer
throws a cryptic error message. Pypiwin32:  I have to edit source code
files and figure out command lines that are not documented. Not hard to
do for me, but still...


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


Re: 'str' object has no attribute 'intersection' and unhashable set

2016-10-05 Thread dieter
meInvent bbird  writes:
... not looking at the details ...

"'str' object has not attribute 'intersection'": apparently,
something is really a string (an 'str') while you expect it to be a set.

"unhashable set": maybe, you try to put a set into another set (or a dict;
or somewhere else where hashability is necessary). A "set" itself is
unhashable (like many mutable standard data types); you may consider to use
"frozenset" in those cases (of course, a "frozenset" is immutable, i.e.
cannot be changed after creation).

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


Re: Assignment versus binding

2016-10-05 Thread dieter
Rustom Mody  writes:

> On Tuesday, October 4, 2016 at 12:47:58 PM UTC+5:30, dieter wrote:
> ...
>> On the other hand, one can model Python variables as bindings
>> where language constructs (assignments) allow to change the binding.
>> 
>> Thus, at an appropriate level of abstraction, you can say that
>> "binding" and "assignment" are mostly equivalent.
>
> Thats a bizarre statement -- Are not the contents of the scope and the shape 
> of the scope different things?

An interesting view.

Apparently, you identify "binding" and "scope" (or more precisely its shape).
And in this view, the binding is changed by language construct introducing
"variables".

My view is a bit different. I identify "binding" with the map
from variables to values, i.e. the environment in which expressions
are evaluated. This is more the "scope's content".

I am not sure which view is more correct.

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


Re: Assignment versus binding

2016-10-05 Thread Paul Rubin
Anuradha Laxminarayan  writes:
> it Would be great to stay within the Python world if I could cover
> the key computational monadic ideas without the rest of Haskell.

It's useful to write some Python things in monadic style, but monads
make the most sense as type operators, which don't map onto Python that
well.  
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: 'str' object has no attribute 'intersection' and unhashable set (Reposting On Python-List Prohibited)

2016-10-05 Thread Ho Yeung Lee
i do not understand, 

how to solve this frozonset ?


Lawrence D’Oliveiro於 2016年10月5日星期三 UTC+8下午2時24分13秒寫道:
> On Wednesday, October 5, 2016 at 2:35:25 PM UTC+13, meInvent bbird wrote:
> > it return unhashable type 'set'
> 
> This is what “frozenset” is for--it’s the immutable counterpart of “set”.
> 
> Data-typing supersymmetry, anybody?

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


Re: Assignment versus binding

2016-10-05 Thread Anuradha Laxminarayan
On Wednesday, 5 October 2016 11:47:17 UTC+5:30, Gregory Ewing  wrote:
> Chris Angelico wrote:
> > Seriously though... this ties in with the other issues about *purely*
> > functional languages being rather impractical, and the purity
> > generally being sullied some by things like monads (which I still
> > don't understand, despite the explanations in another thread).
> 
> If you'd like to understand better, I could put together
> an example that illustrates the basic idea behind monads
> using Python. It's really not that hard; it only seems
> hard because it's traditionally presented in a very
> abstract and mathematical way.

That will be very helpful.
I am preparing material for an Algorithms and Data Structures course using
Python. I would like to demonstrate paradigm shifts in models of computation.
Earlier I had thought of using Haskell together with Python for some of this,
but it Would be great to stay within the Python world if I could cover the key 
computational monadic ideas without the rest of Haskell.

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