Question about extending the interperter

2005-05-09 Thread Eli
Hi,
I've followed the Python docs about extending the Python interperter
and created an extension library.
I've added my functions like this:

static PyMethodDef pmylib_methods[] = {
{"foo", pmylib_foo, METH_VARARGS, "foo() doc string"},
...
}
static PyObject *pmylib_foo(PyObject *self, PyObject *args)
{
...
char *p;
if (!PyArg_ParseTuple(args, "s", &p))
...
}

And that's works fine.
The problem for me is that the pointer "p" in the last function points
to the arguments:
If a user caller foo("123") - p points to '123'.
What I need is to point it to the whole string received - 'foo
("123")'.

Is there a way I can do this?

Thanks in advance,
Eli

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


Re: Question about extending the interperter

2005-05-10 Thread Eli
Thanks for the answer; I should better explain my problem.

My organization already has a DOS command line tool which I would like
to transffer to Python.
Every function this DOS command line too can execute has a definition
entry in an array:
 {"function name", function address, other info... },
Which means if 'function name' was enetered by the user the command
line tool will call 'function address'. Note that this is a *big*
array.

Now I'm trying to pass the above enteries to Python's interperter
extension:
One way would be going over all of my enteries and add Python calls
like that:

static PyMethodDef pmylib_methods[] = {
{"function name 1", pmylib_1, METH_VARARGS, "..."},
{"function name 2", pmylib_2, METH_VARARGS, "..."},
etc
...
}
The only problem I need to preprocess the input first (initialize
strtok).
So a solution would be creating 'function 1' which preprocess the input
and calls the original function 1, than do so for any other function.
This works, but there are *lots* of such enteries and I'm trying a
general way of doing so.
If I would have the full line the user enetered I could make all of the
extensions to call a general function which will call the original
functions (it can do so because it has the function address as a
parameter).
If I could get the full line the user has entered that would be great,
if that's possible.

Hope I've explained it correctly...
cheers,
Eli

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


Re: Question about extending the interperter

2005-05-15 Thread Eli
I've tried that and it worked. I've used Python to generate wrapper and
it seems ok- I'm yet testing it, so far so good.

thanks,
Elie

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


Re: Question about extending the interperter

2005-05-15 Thread Eli
Thanks for your answer, I've tried the way Fredrik suggested which
pointed out to a solution.

cheers

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


Calling PySys_WriteStdout from embedded Python

2005-05-16 Thread Eli
Hello all,
I'm embedding Python in my C application. The application makes several
calls to PySys_WriteStdout from the main thread and so far it's ok.
A problem occurs when I'm creating another thread (in Windows with
CreateThread) and trying to call PySys_WriteStdout from there; at the
first try it crashed.

I've added some locking calls and now the code looks like this (from
the thread):
PyEval_AcquireLock();
PyThreadState *interp = Py_NewInterpreter();
PyThreadState_Swap(interp);

PySys_WriteStdout("write somthing...");

PyEval_ReleaseThread(interp);
PyEval_ReleaseLock();

Well the code does not crash now, but it doesn't display anything in
Python's console. If I call PySys_WriteStdout from the main thread it
does display alright.

Any ideas how I can get PySys_WriteStdout to work within a thread?
tnanks,
Eli

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


check whether a value is scalar

2006-04-22 Thread Eli
Hi,

I want to check whether a value is a scalar. A scalar can be:
- None (null)
- string
- number (integer, float)
- boolean
How can I validate a value is one of these types?

I care about the value only, and not its class methods.
An object is not a scalar, since it's not a simple value.
An array might be considered as scalar.
The issue is I want to keep a set of values to share among several
applications in different languages, and only scalar values can be
shared. Since objects are not the same in all languages, it's possible
to share only simple values.

-thanks

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


Re: check whether a value is scalar

2006-04-22 Thread Eli
Python treats integers as objects, but as I mentioned that I do care
about the value only, and not its object methods. I mean that it's not
possible to share objects among application in different programming
languages, but it's possible to share the scalar values among them.
Strings, booleans, integeres, floats, null are types that most
programming languages use. Arrays are also commonly used, but each
programming language defines and uses it differently, so it's more
problematic to treat it as scalar (for example python uses dictionaries
while other langs uses regular arrays only).

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


subplot function in matplotlib

2008-04-15 Thread eli
Does anyone know a workaround to plotting beyond 9 subplots in
matplotlib? It would be nice to have 20 plots under the subplot
function for example (poster).

Cheers,

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


Re: subplot function in matplotlib

2008-04-16 Thread eli
On Apr 16, 8:27 am, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
> eli wrote:
> > Does anyone know a workaround to plotting beyond 9 subplots in
> > matplotlib? It would be nice to have 20 plots under the subplot
> > function for example (poster).
>
> Is there such a limitation? I thought that was only for the condensed
> sublpot-specification-form (where you give e.g. 133 instead of 1,3,3)
>
> Diez


Didn't see that part. Now it's fixed. Thanks!

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


accuracy issues with numpy arrays?

2008-04-29 Thread eli
Hi,

I'm writing a quick script to import a fits (astronomy) image that has
very low values for each pixel. Mostly on the order of 10^-9. I have
written a python script that attempts to take low values and put them
in integer format. I basically do this by taking the mean of the 1000
lowest pixel values, excluding zeros, and dividing the rest of the
image by that mean. Unfortunately, when I try this in practice, *all*
of the values in the image are being treated as zeros. But, if I doFor
example, I take the pixel that I know has the highest value and do

x = scipy.ndimage.maximum(image)
print x
1.7400700016878545e-05

The script is below. Thanks for the help.

Eli



import pyfits as p
import scipy as s
import scipy.ndimage as nd
import numpy as n


def flux2int(name):
d  = p.getdata(name)
x,y = n.shape(d)
l = x*y
arr1= n.array(d.reshape(x*y,1))
temp = n.unique(arr1[0]) # This is where the bug starts. All values
are treated as zeros. Hence only one value remains, zero.
arr1= arr1.sort()
arr1= n.array(arr1)
arr1= n.array(arr1[s.where(arr1 >= temp)])

val = n.mean(arr1[0:1000])

d   = d*(1.0/val)
d   = d.round()
p.writeto(name[0,]+'fixed.fits',d,h)
--
http://mail.python.org/mailman/listinfo/python-list


Re: [Python-Dev] [RELEASED] Python 3.3.0

2012-09-29 Thread Eli Bendersky
On Sat, Sep 29, 2012 at 5:18 AM, Georg Brandl  wrote:
> On behalf of the Python development team, I'm delighted to announce the
> Python 3.3.0 final release.
>

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


Else statement executing when it shouldnt

2013-01-20 Thread eli m
an else statement is running when it shouldnt be. It is on the last line. 
Whenever i am in the math or game function, when i type in main, it goes back 
to the start of the program, but it also says not a valid function. I am 
stumped!
Here is my code:
#Cmd 
#Created By Eli M.
#import modules
import random
import math
gtn = 0
print ("Type in help for a list of cmd functions")
#initiate main loop
cmd = 0
while cmd == 0:
#ask for input on function
function = raw_input("Type in a function:")
#start math loop
if function == "math":
run = 0
while run == 0:
#ask for math operation
type = raw_input("What math operation do you want to use?")
if type == "multiplication":
x = raw_input("Type in your first number:")
y = raw_input("Multiply your first number by:")
try:
ans = int(x) * int(y)
print (ans)
try:
ans = float(x) * float(y)
print (ans)
except ValueError, err:
print ("Not a valid number")
except OverflowError, err:
print ("Number too large")
#division math function
if type == "division":
x = raw_input("Type in your first number:")
y = raw_input("Divide your first number by:")
try:
ans = float(x) / float(y)
print (ans)
except ZeroDivisionError, err:
print ("Can't divide by zero")
except ValueError, err:
print ("Not a valid number")
except OverflowError, err:
print ("Number too large")
#subtraction math function
if type == "subtraction":
x = raw_input("Type in your first number:")
y = raw_input("Subtract your first number by:")
try:
ans = float(x) - float(y)
print (ans)
except ValueError, err:
print ("Not a valid number")
#addition math function
if type == "addition":
x = raw_input("Type in your first number:")
y = raw_input("Add your first number by:")
try:
ans = float(x) + float(y)
print (ans)
except ValueError, err:
try:
ans = int(x) + int(y)
print (ans)
except ValueError, err:
print ("Not a valid number")
except OverflowError, err:
print ("Number too large")
#square root math function
if type == "square root":
x = raw_input("Type in your number:")
try:
y = float(x)
z = math.sqrt(y)
print (z)
except ValueError, err:
print ("Not a valid number")
except OverflowError, err:
print ("Number too large")

#to the power of... math function
if type == "power":
x = raw_input("Type in your number:")
y = raw_input("Multiply your first number by the power of:")
try:
ans = float(x) ** float(y)
print (ans)
except OverflowError, err:
print ("Number too large")
except ValueError, err:
print ("Not a valid number")
#break the math loop
if type == "main":
run = 1
#absolute value math function
if type == "absolute value":
try:
x = float(raw_input("Type in your number:"))
y = math.fabs(x)
print (y)
except ValueError, err:
print ("Not a valid number")
if function == "random number":
try:
x = int(raw_input("Minimum number:"))
y = int(raw_input("Maximum number:"))
num = random.randint(x, y)
print (num)
except ValueError, err:
print ("Not a valid number")
if function == "games":
games = 0

Re: Else statement executing when it shouldnt

2013-01-20 Thread eli m
On Sunday, January 20, 2013 8:54:13 PM UTC-8, René Klačan wrote:
> You have to break while loop not to execute else branch
> 
> 
> Rene
> 
> 
> 
Can you explain in more detail please.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Else statement executing when it shouldnt

2013-01-20 Thread eli m

> 
> 
> 
> Your else is lined up with while, not with if.
> 
> 
> 
>   -m
> 
> 
> 
> 
> 
> -- 
> 
> Lark's Tongue Guide to Python: http://lightbird.net/larks/
> 
> 
> 
> When a friend succeeds, I die a little.  Gore Vidal
Its lined up. It got messed up when i copied the code into the post.

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


Re: Else statement executing when it shouldnt

2013-01-20 Thread eli m
On Sunday, January 20, 2013 8:40:47 PM UTC-8, eli m wrote:
hint: Use the comments in the code to find out where my error is.
> 
> Here is my code:
> 
> #Cmd 
> 
> #Created By Eli M.
> 
> #import modules
> 
> import random
> 
> import math
> 
> gtn = 0
> 
> print ("Type in help for a list of cmd functions")
> 
> #initiate main loop
> 
> cmd = 0
> 
> while cmd == 0:
> 
> #ask for input on function
> 
> function = raw_input("Type in a function:")
> 
> #start math loop
> 
> if function == "math":
> 
> run = 0
> 
> while run == 0:
> 
> #ask for math operation
> 
> type = raw_input("What math operation do you want to use?")
> 
> if type == "multiplication":
> 
> x = raw_input("Type in your first number:")
> 
> y = raw_input("Multiply your first number by:")
> 
> try:
> 
> ans = int(x) * int(y)
> 
> print (ans)
> 
> try:
> 
> ans = float(x) * float(y)
> 
> print (ans)
> 
> except ValueError, err:
> 
> print ("Not a valid number")
> 
> except OverflowError, err:
> 
> print ("Number too large")
> 
> #division math function
> 
> if type == "division":
> 
> x = raw_input("Type in your first number:")
> 
> y = raw_input("Divide your first number by:")
> 
> try:
> 
> ans = float(x) / float(y)
> 
> print (ans)
> 
> except ZeroDivisionError, err:
> 
> print ("Can't divide by zero")
> 
> except ValueError, err:
> 
> print ("Not a valid number")
> 
> except OverflowError, err:
> 
> print ("Number too large")
> 
> #subtraction math function
> 
> if type == "subtraction":
> 
> x = raw_input("Type in your first number:")
> 
> y = raw_input("Subtract your first number by:")
> 
> try:
> 
> ans = float(x) - float(y)
> 
> print (ans)
> 
> except ValueError, err:
> 
> print ("Not a valid number")
> 
> #addition math function
> 
> if type == "addition":
> 
> x = raw_input("Type in your first number:")
> 
> y = raw_input("Add your first number by:")
> 
> try:
> 
> ans = float(x) + float(y)
> 
> print (ans)
> 
> except ValueError, err:
> 
> try:
> 
> ans = int(x) + int(y)
> 
> print (ans)
> 
> except ValueError, err:
> 
> print ("Not a valid number")
> 
> except OverflowError, err:
> 
> print ("Number too large")
> 
> #square root math function
> 
> if type == "square root":
> 
> x = raw_input("Type in your number:")
> 
> try:
> 
> y = float(x)
> 
> z = math.sqrt(y)
> 
> print (z)
> 
> except ValueError, err:
> 
> print ("Not a valid number")
> 
> except OverflowError, err:
> 
> print ("Number too large")
> 
> 
> 
> #to the power of... math function
> 
> if type == "power":
> 
> x = raw_input("Type in your number:")
> 
> y = raw_input("Multiply your first number by the power 
> of:")
> 
> try:
> 
> ans = float(x) ** float(y)
> 
> print (ans)
> 
> except OverflowError, err:
> 
> print ("Number too large")
> 
> except ValueError, err:
> 
&

Re: Else statement executing when it shouldnt

2013-01-20 Thread eli m
On Sunday, January 20, 2013 8:52:12 PM UTC-8, Chris Angelico wrote:
> On Mon, Jan 21, 2013 at 3:40 PM, eli m  wrote:
> 
> > an else statement is running when it shouldnt be. It is on the last line. 
> > Whenever i am in the math or game function, when i type in main, it goes 
> > back to the start of the program, but it also says not a valid function. I 
> > am stumped!
> 
> 
> 
> Check your indentation levels. I see a few things here that look odd:
> 
> 
> 
> > if function == "help":
> 
> > while helpfunc == 0:
> 
> > if helpmain == "main":
> 
> > else:
> 
> 
> 
> What is the else meant to bind to? The innermost if? The 'if function
> 
> == "help"'? It's currently binding to the while.
> 
> 
> 
> Recommendation: Break this up! Your main loop is huge! It's way too
> 
> easy to get lost in it. And while you're at it, consider unifying some
> 
> of the similar blocks of code. The solution to both issues is simple:
> 
> Use functions. Have you been taught about them yet?
> 
> 
> 
> Also, side tip: Be honest about homework. I'm fairly sure that's what
> 
> this is. :)
> 
> 
> 
> ChrisA

Its not homework. It is a personal project.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Else statement executing when it shouldnt

2013-01-21 Thread eli m
On Sunday, January 20, 2013 9:56:59 PM UTC-8, alex23 wrote:
> On Jan 21, 2:40 pm, eli m  wrote:
> 
> > an else statement is running when it shouldnt be. It is
> 
> > on the last line. Whenever i am in the math or game
> 
> > function, when i type in main, it goes back to the start
> 
> > of the program, but it also says not a valid function.
> 
> > I am stumped!
> 
> 
> 
> Here is your code with the irrelevancy stripped away:
> 
> 
> 
> function = raw_input("Type in a function:")
> 
> #start math loop
> 
> if function == "math":
> 
> #math code
> 
> if function == "random number":
> 
> #random code
> 
> if function == "games":
> 
> #games code
> 
> if function == "help":
> 
> #help code
> 
> else:
> 
> print ("Not a valid function")
> 
> 
> 
> Say you enter 'math'. It passes the first condition, so runs the math
> 
> code.
> 
> It then fails on the next 3 conditions, the last of which has an else,
> 
> so if you type _anything_ other than 'help', you'll see "Not a valid
> 
> function".
> 
> 
> 
> Easy answer, use `elif` ("else if") instead of else for the subsequent
> 
> tests:
> 
> 
> 
> if function == "math":
> 
> #math code
> 
> elif function == "random number":
> 
> #random code
> 
> elif function == "games":
> 
> #games code
> 
> elif function == "help":
> 
> #help code
> 
> else:
> 
> print ("Not a valid function")
> 
> 
> 
> Better answer: read up on real functions, and look into dictionary
> 
> dispatch:
> 
> 
> 
> def f_math():
> 
>#math code
> 
> 
> 
> def f_random_number():
> 
>#random code
> 
> 
> 
> 
> 
> 
> 
> function_dispatcher = {
> 
> 'math': f_math,
> 
> 'random number': f_random_number,
> 
> 
> 
> }
> 
> 
> 
>while cmd == 0:
> 
>function_name = raw_input("Type in a function:")
> 
>if function_name in function_dispatcher:
> 
>function_dispatcher[function_name]()
> 
>else:
> 
>print("Not a valid function")
> 
> 
> 
> To have your functions break out of the loop, use a `global` variable
> 
> or pass a context object into each function to allow them to set
> 
> `cmd`.

Thank you, that solved my problem. Sorry for my posts, i am a noob and this is 
my first time posting on here.
-- 
http://mail.python.org/mailman/listinfo/python-list


stopping a thread with _Thread__stop

2011-08-05 Thread Eli Bendersky
This recipe: 
http://code.activestate.com/recipes/576780-timeout-for-nearly-any-callable/

Claims that a Python thread can be stopped by executing the private
method "Thread._Thread__stop". I don't think this is true, since
_Thread__stop doesn't really stop or kill the thread. In conformance
to theory, the "timelimited" method this recipe defines leaves a
thread running in the background if the function it's given is
long-running (or infinite). Is there something I'm missing?

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


Calling super() in __init__ of a metaclass

2011-08-06 Thread Eli Bendersky
Consider this standard metaclass definition:

class MyMetaclass(type):
def __init__(cls, name, bases, dct):
super(MyMetaclass, cls).__init__(name, bases, dct)
# do meta-stuff

class Foo(object):
__metaclass__ = MyMetaclass

The call "super(MyMetaclass, cls)" should returns the parent of
MyMetaclass here. But the 'cls' passed into this __init__ is *not*
MyMetaclass, but rather the created class - i.e. Foo. So how does
"super" get to the parent of MyMetaclass using this information? The
documentation of "super" says:

If the second argument is a type, issubclass(type2, type) must be
true (this is useful for classmethods).

Yes, 'cls' is a type (it's "class Foo"), but no, it's not a subclass
of MyMetaclass, so this doesn't help.

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


Re: Calling super() in __init__ of a metaclass

2011-08-06 Thread Eli Bendersky
On Sat, Aug 6, 2011 at 11:04, Chris Rebert  wrote:
> On Sat, Aug 6, 2011 at 12:34 AM, Eli Bendersky  wrote:
>> Consider this standard metaclass definition:
>>
>> class MyMetaclass(type):
>>    def __init__(cls, name, bases, dct):
>>        super(MyMetaclass, cls).__init__(name, bases, dct)
>>        # do meta-stuff
>>
>> class Foo(object):
>>    __metaclass__ = MyMetaclass
>>
>> The call "super(MyMetaclass, cls)" should returns the parent of
>> MyMetaclass here. But the 'cls' passed into this __init__ is *not*
>> MyMetaclass, but rather the created class - i.e. Foo.
>
> ...which is an instance of the first argument to super(), which is how
> super is typically invoked. Remember: a class is an instance of its
> metaclass.
>
> Perhaps if you rename `cls` to `self` and then re-read your snippet,
> you'll have a flash of sudden understanding. Calling the parameter
> `cls` is merely convention.
>
>> So how does
>> "super" get to the parent of MyMetaclass using this information? The
>> documentation of "super" says:
>>
>>    If the second argument is a type, issubclass(type2, type) must be
>> true (this is useful for classmethods).
>>
>> Yes, 'cls' is a type (it's "class Foo"), but no, it's not a subclass
>> of MyMetaclass, so this doesn't help.
>
> The typical form of super(), mentioned earlier in the documentation,
> is being used here:
>
>    super(type, obj) -> bound super object; requires isinstance(obj, type)
>
> `type` here is the metaclass, `obj` here is the class. By definition,
> a class is an *instance* of its metaclass, so the precondition is
> satisfied.

Thanks, Chris. This clarifies things.

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


Re: Python enabled gdb on Windows and relocation

2011-05-14 Thread Eli Zaretskii
> Date: Sat, 14 May 2011 11:09:13 +0200
> From: Ruben Van Boxem 
> Cc: [email protected], [email protected]
> 
> 1. Check hardcoded path; my suggestion would be " executable>/../lib/python27"
> 2. If this fails to find the necessary files/scripts, find it like you
> described above in Linux, without PYTHONPATH set.
> 3. Check PYTHONPATH.
> 
> I would think only number one would change, and perhaps be only
> enabled with a special configure option. Nothing else would have to
> change, and Windows users would rejoice :)

The problem, I think, is that it's not so easy on Unix to get the
place where the GDB executable leaves.  There isn't a system call to
do that (similar to what Windows gives you).

So I think on Posix platforms, number 2 would be used most of the
time.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: [python-cffi] Fwd: Re: Progress migrating cffi and pycparser to libclang

2018-01-06 Thread Eli Bendersky
On Fri, Jan 5, 2018 at 1:15 AM, Etienne Robillard 
wrote:

> Forwarding  this thread to the CFFI developers...
>
> Re Paul: Thanks for your feedback.
>
> My intended audience are developers who can use hg to fetch/build source
> code without pip.
>
> Best regards,
>
> Etienne
>

I'd like to understand the requirements here better, from the point of view
of pycparser. What are you trying to accomplish?

One of the issues with parsing "original" headers (with #defines and
#includes and all that jazz) is that you have to match the compilation
environment very precisely. When a compiler compiles a large project it
could set dozens of -Ds, as well as -Is pointing to directories with
additional headers. This is usually specified in Makefiles or something
similar. Clang and libclang deal with this by having the concept of a
compilation database which remembers for each file what the exact flags to
compile it are (https://clang.llvm.org/docs/JSONCompilationDatabase.html)

To make this *really* work for CFFI you'd have to take all of this into
account -- do you really want to deal with this on the CFFI level?

Eli








>
>  Message transféré 
> Sujet : Re: Progress migrating cffi and pycparser to libclang
> Date : Thu, 4 Jan 2018 21:25:27 +
> De : Paul Moore  
> Pour : Etienne Robillard  
> Copie à : Python  
>
> On 4 January 2018 at 21:02, Etienne Robillard  
>  wrote:
> >> As a fork/extension for cffi, I have no particular opinion (I'm
> >> unlikely to ever use it). But the advantage of pycparser is that it's
> >> cross-platform and pure Python, so I doubt this will be acceptable for
> >> inclusion into CFFI itself.
> >
> > CFFI/pycparser definitely need to be patched to support parsing standard C
> > directives like #define and #include in the ffi.cdef() function.
> >
> > The easiest solution is to migrate the internal parsing code to libclang, a
> > state-of-the art C/C++ compiler based on LLVM.
>
> I would strongly object to adding a dependency to cffi that couldn't
> be automatically installed by pip as part of standard dependency
> resolution (i.e., a PyPI hosted Python project with wheels available
> for all common platforms - Linux, Mac OS and Windows). But ultimately
> if you're proposing this as a change to cffi, you should be getting
> the opinions of the cffi devs, not just asking on this list. (I notice
> you have posted to the cffi mailing list, but haven't had any response
> yet).
>
> Paul
>
>
> --
> -- python-cffi: To unsubscribe from this group, send email to
> [email protected]. For more options, visit this
> group at https://groups.google.com/d/forum/python-cffi?hl=en
> ---
> You received this message because you are subscribed to the Google Groups
> "python-cffi" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to [email protected].
> For more options, visit https://groups.google.com/d/optout.
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Different names for Unicode codepoint

2016-04-21 Thread Eli Zaretskii
> From: Lele Gaifax 
> Date: Thu, 21 Apr 2016 21:04:32 +0200
> Cc: [email protected]
> 
> is there a particular reason for the slightly different names that Emacs
> (version 25.0.92) and Python (version 3.6.0a0) give to a single Unicode 
> entity?

They don't.

> Just to mention one codepoint, ⋖ is called "LESS THAN WITH DOT" accordingly to
> Emacs' C-x 8 RET TAB menu, while in Python:
> 
> >>> import unicodedata
> >>> unicodedata.name('⋖')
> 'LESS-THAN WITH DOT'
> >>> print("\N{LESS THAN WITH DOT}")
>   File "", line 1
> SyntaxError: (unicode error) ...: unknown Unicode character name

Emacs shows both the "Name" and the "Old Name" properties of
characters as completion candidates, while Python evidently supports
only "Name".  If you type "C-x 8 RET LESS TAB", then you will see
among the completion candidates both "LESS THAN WITH DOT" and
"LESS-THAN WITH DOT".  The former is the "old name" of this character,
according to the Unicode Character Database (which is where Emacs
obtains the names and other properties of characters).
-- 
https://mail.python.org/mailman/listinfo/python-list


nested escape chars in a shell command

2005-10-18 Thread Eli Criffield
I'm try run an ssh command in pexpect and I'm having trouble getting
everything escaped to do what i want.

Here's a striped down script showing what i want to do.

--
#!/usr/bin/env python
import pexpect
import sys
if len(sys.argv) < 3:
print "ssh.py host command"
sys.exit(1)

host = sys.argv[1]
command = sys.argv[2]

child = pexpect.spawn('''sh -x -c "stty -echo ; ssh -t -o
'StrictHostKeyChecking no' %s '%s' |awk '{print \"%s:\"$0}' "
'''%(host,command,host), timeout=30)

child.setlog(sys.stdout)
child.expect(pexpect.EOF)
--

The problem in the pexpect.spawn line, It doesn't like the \"%s:\" part
of the awk command. This is necessary so i can see what server the
command is running on, In the full script the command will be running
on about 100 servers at a time.
It parses out into:
+ stty -echo
+ ssh -t -o 'StrictHostKeyChecking no' testserver date
+ awk '{print testserver:$0}'
It totally strips out the "

The stty -echo is required because part of what the program does is it
tries to remember any passwords that are asked for, So you can run a
command like "su -c id" and it will remember roots password for the
next
server and try that. -echo keeps the root password from being echoed to
the screen.

The second problem with the command is while "su -c id" works (taking
out the awk part) running any command with more then one word after the
-c in su fails, It strips out the '
like so:
./sshexpect testserver "su -c 'ls -l /root'"
+ stty -echo
+ ssh -t -o 'StrictHostKeyChecking no' testserver 'su -c ls' -l /root
su: user /root does not exist

I have tried every combination of escaping i can think of can i can't
get either problem solved.

Any ideas?

Eli

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


Re: Web based applications are possible with wxPython?

2005-10-18 Thread Eli Criffield
http://www.nomachine.com/companion_screenshots.php

While not exacly what your talking about, its about as close as i can
think of. This allows you to run any X applications inside a web
browser.

Eli

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


Re: nested escape chars in a shell command

2005-10-20 Thread Eli Criffield
I can't seem to get that to work either.

child =
pexpect.spawn('/bin/sh',args=['-c','/usr/bin/ssh','-t','-o','StrictHostKeyChecking
no',host,command,'|','awk','{print %s:$0}'%host], timeout=30)

Complains its getting the wrong arguments to ssh.

Eli

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


Re: Web based applications are possible with wxPython?

2005-10-25 Thread Eli Criffield
not quite but close, NX is a compression protical for the X protical,
so its a lot more like a java X client then a java VNC client.

Eli

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


Pick random choice from variables

2013-02-10 Thread eli m
How do i make something with python that will ask the user for input, and then 
use the random.choice function to select a random choice from what the user 
entered.
-- 
http://mail.python.org/mailman/listinfo/python-list


How would you do this?

2013-02-14 Thread eli m
I want to make a guess the number game (Which i have), but i want to make the 
computer play the game against itself. How would i do this?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How would you do this?

2013-02-14 Thread eli m
On Thursday, February 14, 2013 4:09:37 PM UTC-8, Oscar Benjamin wrote:
> On 14 February 2013 23:34, eli m  wrote:
> 
> > I want to make a guess the number game (Which i have), but i want to make 
> > the computer play the game against itself. How would i do this?
> 
> 
> 
> Your question would make more sense if you would show your program and
> 
> also explain how you would like the output to look when the computer
> 
> played itself.
> 
> 
> 
> 
> 
> Oscar
This is my code:

#Guess the number game
import random
run = 0
while run == 0:
print ("I am thinking of a number between 1 and 100")
num = random.randint(1, 100)
num = int(num)
guesses = 0
guessestaken = 0
while guesses == 0:
try:
guess = raw_input("Your guess:")
guess = int(guess)
guessestaken = (guessestaken) + 1
guessestaken = int(guessestaken)
if guess == (num):
print 'Correct! It took you', int(guessestaken), 'guesses!'
playagain = raw_input("Do you want to play again?")
if playagain == "yes":
guesses = 1
if playagain == "no":
run = 1
if guess > num:
print ("My number is lower")
if guess < num:
print ("My number is higher")
except TypeError, err:
print ("Not a valid number")

I would like it to show the computer guessing the numbers. 

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


Small program ideas

2013-02-15 Thread eli m
Any small program ideas? I would prefer to stick to command line ones. Thanks.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Small program ideas

2013-02-15 Thread eli m
On Friday, February 15, 2013 7:52:57 PM UTC-8, Mitya Sirenef wrote:
> On 02/15/2013 10:22 PM, eli m wrote:
> 
> > Any small program ideas? I would prefer to stick to command line ones. 
> > Thanks.
> 
> 
> 
> How about these two:
> 
> 
> 
>   - simulation of a street crossing with green/red lights allowing cars 
> 
> and pedestrians to pass in one direction then another
> 
> 
> 
>   - simulation of an elevator in a building: buttons on each floor to 
> 
> call the elevator, buttons inside to go to a particular floor,
> 
> multiple floors can be selected at the same time, creating a queue 
> 
> of floors to go to.
> 
> 
> 
>   -m
> 
> 
> 
> -- 
> 
> Lark's Tongue Guide to Python: http://lightbird.net/larks/

Could i make these text and not visual? That is what i am trying to do.
-- 
http://mail.python.org/mailman/listinfo/python-list


Import Question

2013-02-20 Thread eli m
How long does it take for the program to import something? I am asking this 
because i have like 7 imports at the beginning of my program and i am thinking 
thats the reason why it is slow to start up. Thanks in advance.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Small program ideas

2013-02-25 Thread eli m
On Friday, February 15, 2013 7:22:41 PM UTC-8, eli m wrote:
> Any small program ideas? I would prefer to stick to command line ones. Thanks.

Thank you guys for the suggestions. Any more?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Small program ideas

2013-02-26 Thread eli m
On Monday, February 25, 2013 10:15:24 PM UTC-8, Dave Angel wrote:
> On 02/25/2013 10:48 PM, eli m wrote:
> 
> > On Friday, February 15, 2013 7:22:41 PM UTC-8, eli m wrote:
> 
> >> Any small program ideas? I would prefer to stick to command line ones. 
> >> Thanks.
> 
> >
> 
> > Thank you guys for the suggestions. Any more?
> 
> >
> 
> 
> 
> There are all kinds of things you could do.  First, consider something 
> 
> that might be useful.
> 
> 
> 
> 1) checksum all the files in a directory tree, using various checksum 
> 
> algorithms.
> 
> 
> 
> 2) Convert one kind of file to another.
> 
> 
> 
> 3) Calculate time between two dates
> 
> 
> 
> 4) Write some part of a backup system.  For example, copy files from a 
> 
> directory tree into a specified directory, stopping when the size totals 
> 
> N.N gig, and keeping track of which files have been so processed, so 
> 
> that after burning that directory to DVD, you can repeat the process. 
> 
> As a bonus, add a utility & datafile to the top of that directory, so 
> 
> that the DVD can be self-checking.
> 
> 
> 
> Then try something interesting:
> 
> 
> 
> 1) find the nth prime, for example the 1000th prime
> 
> 
> 
> 2) Find all perfect numbers under a trillion
> 
> 
> 
> 3) solve the puzzles on http://projecteuler.net
> 
> 
> 
> 4) Build a spell checker, using a combination of a standard 
> 
> dictionary-list and custom entries.  Bonus question - Make it smart 
> 
> enough to only spell-check comments and literal strings, when applied to 
> 
> files with an extension of .py
> 
> 
> 
> 
> 
> -- 
> 
> DaveA

How hard would it be to change one file to another and would it be a 
small-medium sized program?

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


Re: Small program ideas

2013-02-26 Thread eli m
On Tuesday, February 26, 2013 4:22:10 PM UTC-8, Joshua Landau wrote:
> On 26 February 2013 22:47, eli m  wrote:
> 
> 
> 
> 
> 
> How hard would it be to change one file to another and would it be a 
> small-medium sized program?
> 
> 
> How do you want to change it? Like rename a file (os.rename)?

I want to change the file type.
-- 
http://mail.python.org/mailman/listinfo/python-list


Display video in tkinter?

2013-02-27 Thread eli m
Is there a way to display video (an avi) in tkinter without having to download 
other modules? If not then are there any other options? 
-- 
http://mail.python.org/mailman/listinfo/python-list


How would you do this?

2013-02-27 Thread eli m
How would you find the slope, y intercept, and slope-intercept form equation 
for a line in python?
-- 
http://mail.python.org/mailman/listinfo/python-list


Store a variable permanently

2013-02-28 Thread eli m
So i have a variable called funds that i want to store the value of even after 
the program is exited. My funds variable holds the total value of funds i have. 
I add a certain number of funds each time i run the program by entering how 
much i want to add. How would i store the funds variable to keep its value?
-- 
http://mail.python.org/mailman/listinfo/python-list


Input wont work with if statement if it has a space

2013-03-05 Thread eli m
Hi guys, i have a program like this: (A lot of code is not included)
run = 0
while run == 0:
   raw_input("Type in a function:")
   if function == "Example":
  print ("Hello World!")
   else:
  print ("blah blah blah")

The problem is that whenever i type in example with a space after it then it 
prints the else statement.

My question is, how do i get it to except input with spaces?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Input wont work with if statement if it has a space

2013-03-05 Thread eli m
On Tuesday, March 5, 2013 3:31:13 PM UTC-8, eli m wrote:
> Hi guys, i have a program like this: (A lot of code is not included)
> 
> run = 0
> 
> while run == 0:
> 
>raw_input("Type in a function:")
> 
>if function == "Example":
> 
>   print ("Hello World!")
> 
>else:
> 
>   print ("blah blah blah")
> 
> 
> 
> The problem is that whenever i type in example with a space after it then it 
> prints the else statement.
> 
> 
> 
> My question is, how do i get it to except input with spaces?

oops i meant function = raw_input("Type in a function:")
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Input wont work with if statement if it has a space

2013-03-05 Thread eli m
On Tuesday, March 5, 2013 3:47:31 PM UTC-8, emile wrote:
> On 03/05/2013 03:33 PM, eli m wrote:
> 
> > On Tuesday, March 5, 2013 3:31:13 PM UTC-8, eli m wrote:
> 
> >> Hi guys, i have a program like this: (A lot of code is not included)
> 
> >>
> 
> >> run = 0
> 
> >>
> 
> >> while run == 0:
> 
> >>
> 
> >> function = raw_input("Type in a function:")
> 
> >>
> 
> >> if function == "Example":
> 
> 
> 
> whenever function isn't _exactly_ "Example" the else clause executes.
> 
> 
> 
> If you want to catch forms of example you might try:
> 
> 
> 
>  if function.strip().upper() == "EXAMPLE":
> 
> 
> 
> Emile
> 
> 
> 
> 
> 
> 
> 
> 
> 
> >>
> 
> >>print ("Hello World!")
> 
> >>
> 
> >> else:
> 
> >>
> 
> >>print ("blah blah blah")
> 
> >>
> 
> >>
> 
> >>
> 
> >> The problem is that whenever i type in example with a space after it then 
> >> it prints the else statement.
> 
> >>
> 
> >>
> 
> >>
> 
> >> My question is, how do i get it to except input with spaces?
> 
> >
> 
> > oops i meant function = raw_input("Type in a function:")
> 
> >

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


Insert comma in number?

2013-03-06 Thread eli m
I have a python program that accepts input and calculates the factorial of that 
number, and i want to know if i can make it so commas get inserted in the 
number.
For example: instead of 1000 it would say 1,000
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Small program ideas

2013-03-18 Thread eli m
Any other ideas?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problem this random seed()

2013-03-18 Thread eli m
On Monday, March 18, 2013 6:57:30 PM UTC-7, NZach wrote:
> Hello everyone,
> 
> 
> 
> i am using the MMK.py example from a SimPy tutorial, which can be found here: 
> http://heather.cs.ucdavis.edu/~matloff/156/PLN/DESimIntro.pdf
> 
> 
> 
> I have made very little changes to the code and i have upload it here:
> 
> http://codeviewer.org/view/code:30d3
> 
> 
> 
> The problem is that i am executing  the main() function in lines 83 and 90, 
> but 
> 
> i do not receive the  same result, although the random seed is used in the G 
> 
> class.
> 
> 
> 
> Any idea please, how can i solve it ?
> 
> 
> 
> 
> 
> Thanks,
> 
> 
> 
> Nicholas.

What errors did it show?
-- 
http://mail.python.org/mailman/listinfo/python-list


Video tutorial for making a guess the number game in python

2013-05-04 Thread eli m
I made a video tutorial for making a guess the number game in python. You can 
check it out here: http://www.youtube.com/watch?v=0WSQb-7wMJQ
-- 
http://mail.python.org/mailman/listinfo/python-list


tab compleation input

2006-11-13 Thread Eli Criffield

Here is what i want to do. I have a question in my program, and i want
to do tab completion for the valid answers.

Say i have :
--snip--
validanswers = [ 'yes', 'no', 'maybe', 'tuesday', 'never' ]

#and i ask

sys.stdout.write("Answer the Question: ")
answer = sys.stdin.readline().rstrip()
if answer not in valid answers:
  print "Wrong!"
--snip--

But what i want is when i enter the answer i can hit tab and it'll
complete one of the validanswers
I know i can do tab complete with readline and 'raw_input('> ')' but
that's only to execute python commands right?

Eli

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


Re: tab compleation input

2006-11-13 Thread Eli Criffield

Not sure what your trying to do, but it doesn't work. :)
valid doesn't exsist,  and if you make vaid =
sys.stdin.readline().rstrip(), then answer doesn't exsist.

Either way, it doesn't take the tab tell after you hit enter, Not
really what i was getting at. What i want is like a bash shell prompt.
>From a bash shell prompt try ls  , like that. (readline does
that for bash, but i don't know how to get readline to do anything but
python commands in python).

Eli

[EMAIL PROTECTED] wrote:
> On a gui on this would be a little bit easier but it's a completley
> diffrent realm when doing it in the console. It makes it a little more
> difficult when using stdin.readline() because you can only read line by
> line. Here is my implmentation.
>
> import sys
>
> validanswers = [ 'yes', 'no', 'maybe', 'tuesday', 'never' ]
> while True:
> sys.stdout.write("Answer the Question: ")
> answer = sys.stdin.readline().rstrip()
> for valid in validanswers:
> if valid.startswith(answer.strip("\t")):
> answer = valid
> else:
> print "Invalid Answer: Please enter a valid answer"
> continue
> break
> print "You have answered, ", answer
>
> I'm at school and wasn't able to test it, but it looks like it should
> work.
>
> Eli Criffield wrote:
> > Here is what i want to do. I have a question in my program, and i want
> > to do tab completion for the valid answers.
> >
> > Say i have :
> > --snip--
> > validanswers = [ 'yes', 'no', 'maybe', 'tuesday', 'never' ]
> >
> > #and i ask
> >
> > sys.stdout.write("Answer the Question: ")
> > answer = sys.stdin.readline().rstrip()
> > if answer not in valid answers:
> >   print "Wrong!"
> > --snip--
> >
> > But what i want is when i enter the answer i can hit tab and it'll
> > complete one of the validanswers
> > I know i can do tab complete with readline and 'raw_input('> ')' but
> > that's only to execute python commands right?
> > 
> > Eli

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


Re: tab compleation input

2006-11-13 Thread Eli Criffield

#Thanks for the link from Fredrik Lundh

#from http://effbot.org/librarybook/readline.htm
#You do it like this,

class Completer:
def __init__(self, words):
self.words = words
self.prefix = None
def complete(self, prefix, index):
if prefix != self.prefix:
self.matching_words = [
w for w in self.words if w.startswith(prefix)
]
self.prefix = prefix
try:
return self.matching_words[index]
except IndexError:
return None

import readline

# a set of more or less interesting words
validanswers = [ 'yes', 'no', 'maybe', 'tuesday', 'never' ]

completer = Completer(validanswers)

readline.parse_and_bind("tab: complete")
readline.set_completer(completer.complete)

# try it out!
while 1:
answer = raw_input("Answer the Question: ")
if answer not in validanswers:
   print "Wrong!"
else:
   print "Your answer is",answer



Fredrik Lundh wrote:
> Eli Criffield wrote:
>
> > Not sure what your trying to do, but it doesn't work. :)
> > valid doesn't exsist
>
> it's assigned to by the for-in loop, and is only used inside it.
>
> > Either way, it doesn't take the tab tell after you hit enter, Not
> > really what i was getting at. What i want is like a bash shell prompt.
>
> you can use the "readline" module with a custom completer class.  see
> the second example on this page:
> 
>  http://effbot.org/librarybook/readline.htm
> 
> 

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


Re: recursively removing files and directories

2007-04-09 Thread Eli Criffield
On Apr 9, 1:44 pm, "bahoo" <[EMAIL PROTECTED]> wrote:
> Hi,
>
> I found a message on Jan 16, 2006 regarding the same topic, except
> that I wanted to remove only certain files that satisfy the format
> "ABC_XXX_XXX.dat", but not the other files.  Once the files are
> removed, if a folder becomes empty, I want to remove the folder as
> well.
>
> The solution to the Jan 16 2006 message required many lines of python
> code.  I was wondering if there is a simpler solution to my problem at
> hand, perhaps by using more specialized functions?
>
> Thanks!
> bahoo

Something like

import os
import re

def processFiles(args,dir,fileList):
for thisFile in fileList:
   if re.match(r'REGEXPATTERN',thisFile):
os.unlink("%s%s"dir,thisFile)

os.path.walk("/",processFiles,None)

But thats just off the top of my head, so that mite not be exact.

Eli Criffield

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


Re: recursively removing files and directories

2007-04-09 Thread Eli Criffield
Forgot the rmdir

import os
import re

def processFiles(args,dir,fileList):
for thisFile in fileList:
   if re.match(r'REGEXPATTERN',thisFile):
os.unlink("%s%s"dir,thisFile)
os.rmdir(dir)

os.path.walk("/",processFiles,None)



Eli Criffield

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


XML-RPC SSL and client side certs?

2007-04-10 Thread Eli Criffield

Does anyone have an example setup of a XML-RPC sever using client side
certs for authentication?

And instead of having a list of certs allowed to connect, I'd like to
allow any cert signed by my CA.

It doesn't seem like it would be to hard to do and I'll probably spend
some time setting it up here soon, but would be interested if anyone
else has already written a solution like this or has used one (in
python of course).

Eli Criffield

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


Re: Xah's Edu Corner: Criticism vs Constructive Criticism

2006-04-26 Thread Eli Gottlieb
Xah Lee wrote:
> Criticism versus Constructive Criticism
> 
> Xah Lee, 2003-01
> 
> A lot intelligent people are rather confused about criticism,
> especially in our “free-speech” free-for-all internet age. When
> they say “constructive criticisms are welcome” they mostly mean
> “bitching and complaints not welcome”. Rarely do people actually
> mean that “criticism without suggestion of possible solutions are not
> welcome” or “impolite criticism not welcome”.
> 
> Such discernment is important. Wanton bitching as internet-using geeks
> are used to is not criticism is any form.
> 
> People can be respected and make a living out of criticisms, called
> critics, but not bitching. And when one really value opinions, you
> often want criticism without qualifications. Just be happy that
> valuable criticisms may come to you free from the experts in the
> public. The instant you qualify what kind of feedback are welcome, your
> feedback is compromised. (this is particularly so for political or
> controversial subjects)
> 
> One easy way for many of the unix geeks to understand this is the
> cryptology industry.
> 
> If one really desires valuable criticisms that is polite or with
> solutions or “constructive” (whatever that means), one usually have
> to pay.
> 
> This post is archived at:
> http://xahlee.org/UnixResource_dir/writ/criticism.html
> 
>Xah
>[EMAIL PROTECTED]
>  ∑ http://xahlee.org/
> 
Oh, God, not another one.

-- 
The science of economics is the cleverest proof of free will yet 
constructed.
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Tabs versus Spaces in Source Code

2006-05-14 Thread Eli Gottlieb
Actually, spaces are better for indenting code.  The exact amount of 
space taken up by one space character will always (or at least tend to 
be) the same, while every combination of keyboard driver, operating 
system, text editor, content/file format, and character encoding all 
change precisely what the tab key does.

There's no use in typing "tab" for indentation when my text editor will 
simply convert it to three spaces, or worse, autoindent and mix tabs 
with spaces so that I have no idea how many actual whitespace characters 
of what kinds are really taking up all that whitespace.  I admit it 
doesn't usually matter, but then you go back to try and make your code 
prettier and find yourself asking "WTF?"

Undoubtedly adding the second spark to the holy war,
Eli

-- 
The science of economics is the cleverest proof of free will yet 
constructed.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Software Needs Philosophers

2006-05-23 Thread Eli Gottlieb
John D Salt wrote:
> <[EMAIL PROTECTED]> wrote in news:[EMAIL PROTECTED]:
> 
> [Snips]
> 
>>Wrong. We live in a paradise of ideas and possibilities well beyond the
>>wildest dreams of only 20 years ago.
> 
> 
> What exciting new ideas exist in software that are both important and 
> cannot be traced back to 1986 or earlier?
> 
> I'd like to believe that there are some, but I can't think of any at the 
> moment.
> 
> All the best,
> 
> John.
I correct: We live in a paradise where we finally have to processing 
power to realize all those ideas that were too inefficient 20 years ago.

-- 
The science of economics is the cleverest proof of free will yet 
constructed.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: John Bokma harassment

2006-05-24 Thread Eli Gottlieb
Tim N. van der Leeuw wrote:
> [EMAIL PROTECTED] wrote:
> 
>>I agree there are limits to you right to free speech, but I believe Xah
>>Lee is not crossing
>>any boundaries. If he starts taking over newspapers and TV stations be
>>sure to notify me,
>>I might revise my position.
>>Immanuel
> 
> 
> Perhaps he's not crossing boundaries of free speech, but he's
> repeatedly crossing boundaries on usenet nettiquette, even though
> repeatedly he's being asked not to do so. (Extensive crossposting to
> various usenetgroups / mailing lists, for instance).
> 
> If he would just post his stuff on a blog and find a why to get people
> to visit hist blog, without crossposting to 10 usenest groups for each
> post he makes to his blog, then nobody would mind him expressing his
> opinions, and those interested could discuss them wildly on the blog.
> 
> But I've repeatedly seen people telling him not to crosspost his essays
> to so many newsgroups, yet he continues doing it.
> If that's enough to quit his subscription with his ISP I don't know,
> but since I've stopped following threads originated by him I don't know
> what other grounds there would be.
> 
> Cheers,
> 
> --Tim
> 
Who reads blogs?  They're well known for housing crackpots far worse 
than Xah, and I estimate he doesn't want to associate himself with that 
sort.

-- 
The science of economics is the cleverest proof of free will yet 
constructed.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: John Bokma harassment

2006-05-24 Thread Eli Gottlieb
[EMAIL PROTECTED] wrote:
> John Bokma wrote:
> 
>>"Ant" <[EMAIL PROTECTED]> wrote:
>>
>>
>>>I have no particular affinity for Xah's views, but what does get up my
>>>nose is usenet Nazism.
>>
>>That's because you're clueless.
>>
>>--
>>John   MexIT: http://johnbokma.com/mexit/
>>   personal page:   http://johnbokma.com/
>>Experienced programmer available: http://castleamber.com/
>>Happy Customers: http://castleamber.com/testimonials.html
> 
> 
> Time for a game!
> 
> Both johnbokma.com and castleamber.com are hosted by seagull.net.  Here
> is a link to their TOS:
> 
> http://www.seagull.net/tos.html
> 
> Who can come up with the most violations that John is committing on
> this thread? I count 4.
> 
Let's not drop to his level.
-- 
The science of economics is the cleverest proof of free will yet 
constructed.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Sorting dicts inside dicts

2010-07-03 Thread Eli Bendersky
On Sat, Jul 3, 2010 at 03:34, MRAB  wrote:

> abhijeet thatte wrote:
>
>> Hi,
>> I have a huge dict structure like below:
>>
>> /*{'module':{'reg_dict_0':{'name':'abc','reg_addr':'2004'},'reg_dict_1':{'name':'xyz','reg_addr':'2002'},'reg_dict_2':{'name':'pqr','reg_addr':'2008'}}*/
>>
>> Module dict and reg_dicts contain many elements than shown.
>> I want to sort this 'module' dictionary as per 'reg_addr' element in every
>> 'reg_dict'.
>> There is no relation between 'reg_dict' suffix and address. So, reg_dict_0
>> can contain reg_address = 2000/72 (any number)
>> I do not want output in a list format as the actual dict size is huge
>> which I want to use based on key value pair.
>>
>> So, I want output as :
>>
>>
>> /*{'module':{'reg_dict_1':{'name':'xyz','reg_addr':'2002'},'reg_dict_0':{'name':'abc','reg_addr':'2004'},'reg_dict_2':{'name':'pqr','reg_addr':'2008'}}*/
>> /*
>> */
>>
>> Is it possible to sort the things? What I guess is Python stores dicts in
>> a tree like structure but I am forcing it to store the way I want. Is it
>> possible  to do something like that.
>>
>>  Python dicts are implemented as hash tables, not trees, for speed, and
> they are unordered.
>
> If the order matters then you should use an ordered dict instead. You
> should be able to find an implementation of one.
>
> The easiest way to find such an implementation is in the standard library
of Python, starting with Python 3.1 (collections.OrderedDict)

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


Re: ipython problem in opening a file

2010-07-09 Thread Eli Bendersky
> One of the many things I tried, is as below.
>
> *
>
>
> f=open('od.txt','w')
> ---
> IOError                                   Traceback (most recent call
> last)
>
> C:\Windows\system32\ in ()
>
> IOError: [Errno 13] Permission denied: 'od.txt'
>
>

It appears that your ipython runs in C:\Windows\system32
You can find it out for sure by executing "os.getcwd()" after
importing the "os" module.

You may not have permissions in C:\Windows\system32, which is why the
error is printed.

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


Re: ipython problem in opening a file

2010-07-09 Thread Eli Bendersky
On Fri, Jul 9, 2010 at 16:07, Youngung Jeong  wrote:
> Thank you for your kindness.
> I found you're right. It's running in that folder.
> What should I do for making this work?
> Could you please tell me a bit more...
>
> Youngung

You can change the "current directory" ipython executes in, by either
executing it directly (from the command line) in the directory of your
choice, or calling the os.chdir function with the path of your choice.

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


Re: Hello

2010-07-10 Thread Eli Bendersky
On Fri, Jul 9, 2010 at 19:31, Dani Valverde  wrote:

> Hello!
> I am new to python and pretty new to programming (I have some expertise wit
> R statistical programming language). I am just starting, so my questions may
> be a little bit stupid. Can anyone suggest a good editor for python?
> Cheers!
>

Hi Dani,

Don't be shy to ask beginner questions. However, you will do well to first
read a few FAQs.

Start here: http://www.python.org/doc/faq/
Part of it is also available in spanish, for your convenience:
http://www.python.org/doc/faq/es/general/
The Python wiki (http://wiki.python.org/moin/FrontPage) is also useful. For
example, it has a rather comprehensive page about editors:
http://wiki.python.org/moin/PythonEditors

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


Re: Basic Information about Python

2010-07-30 Thread Eli Bendersky
On Fri, Jul 30, 2010 at 16:55, Durga D  wrote:

> Hi JM,
>
>   Thanks alot for your prompt response.
>
>   If I include into windows setup, what will be setup size (assume
> before include 10 MB)? i mean, python supporting dlls/libs size for
> python exe.
>

IIRC, the size of a simple "hello world" script packed with py2exe or
PyInstaller is around 2-3 MB. If you use large GUI libraries (like PyQt or
wxPython) it goes up to 6-10MB, and so on (more libraries -> larger .exe)

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


co_firstlineno on decorated functions

2010-08-01 Thread Eli Bendersky
Hello,

I've been tinkering with __code__.co_firstlineno for testing the trace.py
module (Python Issue 9315), and ran into an interesting problem. Consider
this code:


def dummydecorator(f):
return f

def foo(a):
return a

@dummydecorator
def bar(a):
return a


if __name__ == "__main__":
print foo.__code__.co_firstlineno
print bar.__code__.co_firstlineno


The first print out correctly specifies the line "def foo" is in. However,
the second one points to the line with "@dummydecorator" instead of "def
bar". [Python 2.6]

The side-effects of this behavior can be easily seen in the output of
modules like trace and profile. Would you say it's normal, or could this be
considered a bug?

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


Re: parsing a c project

2010-08-04 Thread Eli Bendersky
On Wed, Aug 4, 2010 at 14:33, Aitor Garcia wrote:

> Hi,
>
> I need to know the memory locations of all variables in a C project
> including
> variables allocated inside structs.
>


Aitor, try the pycparser project (http://code.google.com/p/pycparser/) -
it's a complete ISO C parser in pure Python. It has been used for tasks
similar to this one (parsing of struct/union declarations for various
purposes).

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


Re: Python library for Sequence Matching/Comparison

2010-08-07 Thread Eli Bendersky
On Sat, Aug 7, 2010 at 12:32, Sohail  wrote:

> Hi,
>
> Is there any sequence matching library in (apart from difflib) to
> compare sequences of natural text?
>
> thanks
> --
> http://mail.python.org/mailman/listinfo/python-list
>

Are you aware of NLTK? It has a lot of sub-libraries for almost anything you
might need with processing natural text.

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


Re: Bit fields in python?

2010-09-07 Thread Eli Bendersky
>
>
> I'm trying to rewrite a c program in python & encountered several problems.
> I have some data structures in my c program like below:
>
> typedef struct
> {
> unsigned short size;
>
> unsigned short reserved:8;
> unsigned short var_a1:2;
> unsigned short var_a2:2;
> unsigned short var_a3:2;
> unsigned short var_a4:2;
>
> unsigned int var_a5;
> }structa;
>
>  typedef struct
>  {
> unsigned short size;
>
> unsigned char reserved:4;
> unsigned char var_b1:1;
> unsigned char var_b2:1;
> unsigned char var_b3:1;
> unsigned char var_b4:1;
>
> structa var_structa;
> }structb;
>
> I tried to code the above in python but only got this far:
>
> class StructA(object):
> def __init__(self, size=0)
> self.size = size
>
> class StructB(object):
> def __init__(self, size=0)
>
> Any equivalent for c data structures & bit fields in python? And how do I
> define var_structa (in structb) in python?
>
>

Bitfields are most commonly used for extreme space optimization - i.e.
shoving several variables and flags with carefully limited ranges into a
single work. In Python you rarely work this way (where such an optimization
is warranted, Python isn't the best tool for the job). However, as in your
use case, it is sometimes needed in Python in order to communicate with
other devices over the network or some other link.

In my work with Python and embedded devices I've found the construct library
(http://construct.wikispaces.com/) very useful. It allows to you very easily
define complex formats for frames/messages on the bit and byte level. The
idea is to use construct to encode and decode messages being sent to an
embedded device. It works great.

If you have further questions about this approach, feel free to ask.

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


Re: Bit fields in python?

2010-09-14 Thread Eli Bendersky
>  Hi,
>
> I'm trying to use the construct library, but encountered a problem. May I
> know how do I implement the following using the construct library?
>
> typedef struct
> {
> unsigned short size;
> .
> .
> }CodecInfo;
>
> typedef struct
> {
> unsigned short size;
> CodecInfo mastercodec;
> CodecInfo slavecodec;
> }StatusInfo;
>
> StatusInfo t;
> printf("%hu %hu\n", t.mastercodec.size,t.slavecodec.size);
>
> Not sure how to include 2 copies of the CodecInfo Struct into StatusInfo
> Struct & be able to access CodecInfo's fields like the example above:
>
> CodecInfo = Struct("CodecInfo",
> .
> .
> .
> )
>
> StatusInfo = Struct("StatusInfo",
> CodecInfo,
> CodecInfo
> )
>
> Status = StatusInfo.parse(buf)
>
>
You can just nest Struct objects. Here's one implementation of what you're
looking for:

from construct import *

def make_codec_info(name):
return Struct(name,  ULInt16('size'))

StatusInfo = Struct('StatusInfo',
ULInt16('size'),
make_codec_info('mastercodec'),
make_codec_info('slavecodec'),
)

c = StatusInfo.parse('\x12\x13\x01\x02\x03\x04')

print c

P.S. It is covered in the first part of construct's tutorial (
http://construct.wikispaces.com/tut-basics). The tutorial is a pretty good
starting point for using construct.

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


-ffast-math

2022-09-07 Thread Eli the Bearded
https://twitter.com/moyix/status/1567167774039973888

Brendan Dolan-Gavitt @moyix

New blog post is live! In which I download 4 TB of Python packages
containing native x86-64 libraries and see how many of them use
-ffast-math, potentially altering floating point behavior in any
program unlucky enough to load them!


https://moyix.blogspot.com/2022/09/someones-been-messing-with-my-subnormals.html

8:08 AM - Sep 6, 2022

It's quite an adventure, a longish read but fun.

Elijah
--
TL;DR: two dependencies using same misguided makefile cause most issues
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Find the path of a shell command

2022-10-13 Thread Eli the Bearded
In comp.lang.python, jkn   wrote:
> On Wednesday, October 12, 2022 at 6:12:23 AM UTC+1, jak wrote:
>> I'm afraid you will have to look for the command in every path listed in 
>> the PATH environment variable.
> erm, or try 'which rm' ?

It is so hilarious seeing the responses to this thread. Hint: what do
you think the `which` program does?

$ touch /var/tmp/rm
$ chmod 755 /var/tmp/rm
$ env -i PATH=/etc:/usr:/lib:/var/tmp:/tmp /usr/bin/which rm
/var/tmp/rm
$ mv /var/tmp/rm /tmp/ 
$ env -i PATH=/etc:/usr:/lib:/var/tmp:/tmp /usr/bin/which rm
/tmp/rm
$ 

Elijah
--
/usr/bin/busybox rm /tmp/rm
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Application window geometry specifier

2021-01-12 Thread Eli the Bearded
In comp.lang.python, Rich Shepard   wrote:
>> Keep in mind that if you target Linux, the "modern" window server
>> (Wayland) will not allow user code to decide the positioning and size of
> I suspect that Slackware will continue with X11.

Even with traditional X11, geometry is "preferred" size and position[*],
not a requirement. Window managers have always been able to override
that if desired, and tiling window managers make that override a
feature. There might not be a tiling window manager in Slack's standard
packages, but there sure are in Slackbuilds.

Elijah
--
[*] See GEOMETRY SPECIFICATIONS in "man X"
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: why sqrt is not a built-in function?

2021-01-14 Thread Eli the Bearded
In comp.lang.python, Skip Montanaro   wrote:
> Finally, should have never considered it, I think you might want to
> study the output of
> 
> import this
> 
> Think on the second and last lines in particular.

   >>> import this
   The Zen of Python, by Tim Peters

   Beautiful is better than ugly.
   Explicit is better than implicit.
   Simple is better than complex.
   Complex is better than complicated.
   Flat is better than nested.
   Sparse is better than dense.
   Readability counts.
   Special cases aren't special enough to break the rules.
   Although practicality beats purity.
   Errors should never pass silently.
   Unless explicitly silenced.
   In the face of ambiguity, refuse the temptation to guess.
   There should be one-- and preferably only one --obvious way to do it.
   Although that way may not be obvious at first unless you're Dutch.
   Now is better than never.
   Although never is often better than *right* now.
   If the implementation is hard to explain, it's a bad idea.
   If the implementation is easy to explain, it may be a good idea.
   Namespaces are one honking great idea -- let's do more of those!
   >>> 

"There should be one-- and preferably only one --obvious way to do it."

Meanwhile, Alan Gauld pointed out:

  AG> because pow() is a builtin function and
  AG> root = pow(x,0.5)
  AG> is the same as
  AG> root = math.sqrt(x)

Plus the ** operation ("root = x ** 0.5"), that's now three ways.

Elijah
--
python user, not python advocate
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Exploring terminfo

2021-01-14 Thread Eli the Bearded
In comp.lang.python, Barry Scott   wrote:
> Alan Gauld via Python-list  wrote:
>> I've written a short program that is supposed to
>> - *clear the screen*,
>> - read some input
>> - display the result in a message *highlighted in bold*.
>> - get input to end the program
> It seems that curses does not allow you to mix raw stdin/stdout with its 
> calls.

This sounds very plausable. In C, in curses one uses printw() not
printf().

> If all you want is simple things like bold and clear I'd just use the
> ANSI escape sequences directly.
> 
> Are there any terminals that do not understand ANSI escape sequences
> these days?

Probably, I hear tales of people using odd set-ups from time to time.
But that could just be the circles I hang out in.

When I've wanted to do simple things like bold and clear, I've used the
tput(1) tool. You can capture stdout from the tool and use the output
over and over. Typically I've done this in shell scripts:

#!/bin/sh
bold=$(tput smso)   # set mode stand out
nobold=$(tput rmso) # remove mode stand out
clear=$(tput clear) # clear screen
home=$(tput home)   # home, without clear

for word in Ten Nine Eight Seven Six Five Four Three Two One; do
   echo "${clear}${bold}${word}${nobold} ..."
   sleep 1
done
echo "${home}Nothing happens."
exit

Elijah
--
adapting to python left as an excercise for the reader
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: why sqrt is not a built-in function?

2021-01-14 Thread Eli the Bearded
In comp.lang.python, Ethan Furman   wrote:
> On 1/14/21 11:06 AM, Eli the Bearded wrote:
>> "There should be one-- and preferably only one --obvious way to do it."
>> Plus the ** operation ("root = x ** 0.5"), that's now three ways.
> Yes, but which of those is obvious?

If it's up to me, the ** one.

Elijah
--
using a syntax with "^" instead of "**" would be okay, too
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: why sqrt is not a built-in function?

2021-01-15 Thread Eli the Bearded
In comp.lang.python, Chris Angelico   wrote:
> Michael F. Stemper  wrote:
>> On 15/01/2021 14.01, Stefan Ram wrote:
>>> __import__( "math" ).sqrt( 4 )
>> I had no idea that syntax existed, and find it completely at odds
>> with The Zen of Python. I'm torn between forgetting that I ever saw
>> it and using it for some evilly-obfuscated code.
> I recommend option #2. It is incredibly good fun. For added bonus
> obscurity, don't import a module directly; import it from some
> unrelated module, such as "from ast import sys" or "from base64 import
> re".

Is there an Obfuscated Python contest, like there is with C? I know the
C ones are often quite interesting, like the 2020 entry that implements
tic-tac-toe in "Turing complete" sub-language of printf() format strings.
(Carlini, http://www.ioccc.org/years.html#2020 )

Elijah
--
with the complexity of fitting the 200k format into a 2k source file
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Exploring terminfo

2021-01-19 Thread Eli the Bearded
In comp.lang.python, Greg Ewing   wrote:
> On 18/01/21 3:34 am, Alan Gauld wrote:
>> The problem is terminfo is not really part of curses.
>> Curses is built on top of terminfo.
> As far as I can tell from the man pages, terminfo itself
> is just a file format. The only programmatic interfaces I
> can find for it *are* part of curses:

Putting my Unix hat on, curses is a "friendly" library around creating
text-windowed applications. Programs like mutt use curses rather than
raw terminal operations, programs like vi use raw terminal operations.
Either curses or raw terminal operations will (should) consult a
terminal capabilities database to figure out what can be done and how to
do it. The two competing database formats for that are termcap and
terminfo, where terminfo is the newer, better one.

Termcap used a single large text file for all terminals types.
Terminfo uses a directory tree full of small files, one per type.

I'm pretty sure both include the ability to say something along the
lines of "start with this one terminal, and then change these bits".
So that starts to get complicated without a library. Or maybe I'm wrong,
and vi uses curses. I'm not really sure how vi reads the term info files.

Okay, checking the source to the only vi I have lying around[*], it uses
a few curses calls, apparently only these:

int tgetent(char *bp, const char *name);
int tgetflag(char *id);
int tgetnum(char *id);
char *tgetstr(char *id, char **area);
char *tgoto(const char *cap, int col, int row);
int tputs(const char *str, int affcnt, int (*putc)(int));

My local manpage calles this set the "direct curses interface to the
terminfo capability database" whereas things I think of as "curses"
programs use calls like:

WINDOW *initscr(void);
int cbreak(void);
int start_color(void);
int noecho(void);
int move(int y, int x);
int attr_set(attr_t attrs, short pair, void *opts);
int getch(void);
int addch(const chtype ch);
int printw(const char *fmt, ...);

The vi method relies on the programmer knowing what attributes are
wanted and how to use them, and how to use alternatives when the
first choices aren't provided. The curses method relies on the programmer
knowing which of a hundred different library functions to use for any
given output. :^)

[*] It's ex-1.1, an "heirloom" source package that has possibly been
brushed up just enough to compile on a modern system. ex-1.1 is by
most reckoning, the first vi. It won't start in vi mode though, you
need to run ex, then begin the visual mode. It is recongizable as vi
to me, but a somewhat different experience.

Elijah
--
has modified C curses programs, but not written one from scratch
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: A 35mm film camera represented in Python object

2021-03-17 Thread Eli the Bearded
In comp.lang.python,
D.M. Procida  wrote:
> Hi everyone, I've created  -
> a representation of a Canonet G-III QL17 in Python.
> 
> There's also documentation: .

This is interesting. Some feedback.

> It's a pure Python model of the physical sub-systems of a camera and
> their interactions. So far it's at a fairly high level - I haven't yet
> got down to the level of individual springs and levers yet.

There's a wealth of specifics for that camera above individual springs
and levers. Notably how the light meter performs with different
batteries and how it works with other films. This much is clear from
just a few minutes research on the Canonet G-III QL17 (what a mouthful
of a name).

I'm guessing you plan to deal light meter quirks because of the battery
voltage setting. I see you don't even attempt to tackle ISO outside of
supported range (and I have no idea how the camera itself deals with
that). Is the camera sensing the ISO from the film roll (so won't work
with hand rolled film cartridges)? Is there a setting on the camera to
manually specify that? (I don't think so.)

> You can do things like advance the film, release the shutter, meter the
> scene with the built-in light meter (if the camera has a battery of
> course) and even spoil your film if you make the mistake of opening the
> back in daylight.

Film spoilage isn't boolean in real life. If I rewind most, but not all
of the way, before I open the back, I've only ruined a few frames. If I
open it in a lightproof camera bag, I can take the roll out without
rewinding.

(I've done such things with pin hole cameras.)

> But you can also do things that you shouldn't do, like opening the back
> of the camera in daylight with a partially-exposed roll of film inside -
> which will spoil the film::
> 
> >>> c.back.open()
> Opening back
> Resetting frame counter to 0
> 'Film is ruined'

If luminosity is set to zero, that could emulate the lightproof bag.
Frame by frame "film is ruined" might be a better choice for boolean.

On this camera, there's no manual double exposure setting, right? So
partial rewind would be the way to do that. But I can make double
exposures with this code:

>>> c.shutter.trip()
Shutter openening for 1/128 seconds
Shutter closes
Shutter uncocked
'Tripped'
>>> c.shutter.cock()
Cocking shutter
Cocked
'Cocked'
>>> c.shutter_speed = 1/512
>>> c.shutter.trip()
Shutter openening for 1/512 seconds
Shutter closes
Shutter uncocked
'Tripped'
>>>

In general, I never used simple cameras with light meters. Advanced SLR
or dumb cameras. My personal favorite film camera is a Universal Mercury
II, a half frame 35mm from mid 1940s with hot and cold shoes (intended
for flash and film meter attachments), bulb to 1/1000 shutter range,
mechanical exposure calculator on the back, and a dial for reminding you
what film you have in it.

Does a camera like the one you have modelled that actively stop you from
using a ISO/shutter speed/F-stop that will vastly over- or under- expose
things? Or is it just a warning light in the viewfinder?

Certainly my c.shutter.trip() calls give me no advice from the meter.

A useful thing your camera-as-code model could provide, but doesn't, is
some measure of how exposed each frame is. This will be a function of
film speed, iris setting, cumulative exposure time from zero or more
shutter openings, and scene luminosity. (You could extend this to
include opened back over exposure conditions.)

Elijah
--
can see how this might get integrated with an image generation tool
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: A 35mm film camera represented in Python object

2021-03-17 Thread Eli the Bearded
In comp.lang.python,
D.M. Procida  wrote:
> Eli the Bearded <*@eli.users.panix.com> wrote:
>> I see you don't even attempt to tackle ISO outside of
>> supported range (and I have no idea how the camera itself deals with
>> that). Is the camera sensing the ISO from the film roll (so won't work
>> with hand rolled film cartridges)? Is there a setting on the camera to
>> manually specify that? (I don't think so.)
> The camera's film speed setting (it's old enough that it's ASA rather
> than ISO) is set manually. If you try to set an illegal value, there's a
> setter decorator that raises a NonExistentFilmSpeed exception.

I can see what the code does, I'm asking what the camera does and do you
plan to work that into your code? Maybe it only works for ISO 1600 in
manual mode, but works.

> I have to add a button and winder lever to the camera object itself, I'm
> doing those things bit by bit.

Gotcha.

> Yes, it would be fun to allow it to "take a picture" of an image file,
> and process the result. Or ultimately built into a web application using
> somehting like https://anvil.works and have take a real picture with a
> user's webcam.

Yes, that sounds like good future work.

Elijah
--
bring light into the dark box
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: A 35mm film camera represented in Python object

2021-04-01 Thread Eli the Bearded
In comp.lang.python, Richard Damon   wrote:
> On 4/1/21 6:41 PM, [email protected] wrote:
>> Richard Damon  wrote:
>>> If you keep track of the positions as a floating point number, the
>>> precision will be more than you could actually measure it.
>> I won't disagree with Richard, although I will give you a general
>> warning about floating point rounding issues:  if you do, in fact, end
>> up with your first solution and lots and lots (millions?  billions?
>> more?) of discrete calculations, be aware that what looks like a lot of
>> precision in the beginning may not be all that precise (or accurate) in
>> the end.

I'm having a hard time figuring where the floating point rounding issues
enter in. My reading is that instead of N discrete steps (level 12 is 
1% moved, lever 12 is 2% moved, lever 12 is 3% moved and makes contact
to cam 3, lever 12 is 4% moved and cam 3 is 5% moved; or what not) using
floating points lever 12 could move 0.0 to > 1, and cam 3 start moving
at lever 12 => 0.04.

>> Also, doesn't the overall motion of the camera as a whole also depend on
>> external factors, such as whether/how it's mounted or handheld, the
>> nature of the "ground" (e.g., soft wet sand vs. hard concrete
>> vs. someone standing on a boat in the water), an experienced
>> photographer "squeezing" the shutter release vs. a newbie "pressing the
>> button"?  I can think of plenty of variables; I guess it depends on what
>> you're trying to model and how accurate you intend to be (or not to be).

I suspect very little of the motion of parts *inside* the camera see
meaningful changes from that. The motion of the camera relative to the
scene is meaningful for how motion blurred a shot will be. But the
springs and levers that move as the shutter release button is pushed
will be basically only moving relative to the camera, and not much
changed by tripod or handheld.

> Actually, I would contend that due to all the factors that you can't
> take into account accurately makes the use of floating point more
> applicable. Yes, you need to realize that just because the value has
> many digits, you KNOW that is only an approximation, and you process
> accordingly, knowing you just has an approximation.

All of the parts of the camera were built with some engineering
tolerance. Using a precision in code that exceeds that tolerance fails
to accurately model the camera.

> The real question comes, what is the purpose of the simulation? You can
> NEVER simulate everything, and some parts of 'simulating' requires
> actual hardware to interact with. Sometimes the real thing is the best
> simulation available.

The purpose was stated in the original post: model a particular camera in
software from the point of view of someone who has done repair work. If
lever 12 is bent, and only touches cam 3 after 15% (or => 0.15) motion
that changes the way the camera works. I believe those sorts of things
are meant to be visible in this model.

Elijah
--
would use floating point, or fixed point as if floating
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: python text://protocol client?

2021-04-09 Thread Eli the Bearded
In comp.lang.python, Petite Abeille   wrote:
> Would you know of any python text://protocol client? Or server?

The whole thing was started (judging by git commits) about a month ago.

https://github.com/textprotocol?tab=overview&from=2021-03-01&to=2021-03-31

March 7: First repository

I suspect no one has cared to reimplement it any language since then.

> Thanks in advance.
> 
> [1] https://textprotocol.org

I have read that and I don't understand what one does with this
protocol or why.

> [2] https://github.com/textprotocol/public
> [3] https://github.com/textprotocol/publictext

The Lua code is not long, under 2k LOC. Why don't you just study it and
create your own python version if you care?

Elijah
--
has not been given enough reason to care to read the code
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: basic auth request

2021-08-25 Thread Eli the Bearded
In comp.lang.python, Jon Ribbens   wrote:
> Another attempt at combatting this problem is DNS CAA records,
> which are a way of politely asking all CAs in the world except the
> ones you choose "please don't issue a certificate for my domain".
> By definition someone who had hacked a CA would pay no attention
> to that request, of course.

Yeah, but it works for the case of forgotten hostnames, a rare but
real attack. Basically it works like this:

$COMPANY puts out a lot of things on different IP addresses from
a shared public(ish) pool like AWS and assigns different names
to them. Later $COMPANY discontinues one or more of those things,
terminates the host, and lets the IP address rejoin the public(ish)
pool.

$ATTACKER notices the domain name pointing to an unused IP address
and works to acquire it for their own server. $ATTACKER then gets
a cert for that domain, since they can easily prove ownership of
the server through http content challenges. $ATTACKER now has a
host in $COMPANY's name to launch phishing attacks.

This probably has some clever infosec name that I don't know.

Elijah
--
or a clever infosec name now forgotten

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


Re: basic auth request

2021-08-25 Thread Eli the Bearded
In comp.lang.python, Jon Ribbens   wrote:
> On 2021-08-25, Eli the Bearded <*@eli.users.panix.com> wrote:
>> $COMPANY puts out a lot of things on different IP addresses from
>> a shared public(ish) pool like AWS and assigns different names
>> to them. Later $COMPANY discontinues one or more of those things,
>> terminates the host, and lets the IP address rejoin the public(ish)
>> pool.
>>
>> $ATTACKER notices the domain name pointing to an unused IP address
>> and works to acquire it for their own server. $ATTACKER then gets
>> a cert for that domain, since they can easily prove ownership of
>> the server through http content challenges. $ATTACKER now has a
>> host in $COMPANY's name to launch phishing attacks.
> How does CAA help with this? Unless the domain owner knows in advance
> that they're going to forget about the hostname and prepares for it
> by setting a CAA record that denies all CAs, the attacker will simply
> get a certificate from one of the permitted CAs - since, as you point
> out, they genuinely own and control the relevant IP address.

I believe the way it helps is by limiting to a CA that will insist
all cert requests come through the right channel, not some random
one off somewhere. This doesn't prevent issues, but does raise the
complexity on an already niche attack.

It does aid in knocking out the easy random one-offs from Let's Encrypt.

Elijah
--
using LE for all his personal sites these days
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: basic auth request

2021-08-25 Thread Eli the Bearded
In comp.lang.python, Barry   wrote:
> It is possible to sign an ip address in a certificate, but that is not
> often done.

It's bad practice. I've never seen one in the wild.

> Getting to reuse the IP address that example.com was using will not help
> the attacker unless they can make a cert that signs the dns  name.
> And that means they hacked the CA which is a big problem.

You misunderstand the attack. Some web searching suggests the term is
"dangling DNS record".

Big co Acme Example, with example.com, has a website for the regular
public on www.example.com, gets mail at mail.example.com, serves
DNS from ns1., ns2. and ns3.example.com. The IT staff watch those
domaines very carefully. 

One day marketing says, "We've got a big CES show this year, let's
make a website for the press at ces.example.com." They tell execs
the execs tell the IT guys the IT guys say "Okay, what does it point
to?" and Marketing gives them the IP address of the blog site they
just rented. IT sets up an A record. IT does not watch _that_
carefully. Two years later Marketing stops paying the bill on the
blog site, and ces.example.com has a "dangling" DNS record, it
exists but no longer points to a valid resource.

Attacker gets the IP address that points to (maybe they churn
through a bunch of temporary accounts until they do) and now with
the right IP to match ces.example.com they go off to get a SSL
cert for that.

$500 bug bounty write up here for someone who found a dangling
record, but didn't churn for the record to exploit it:

https://gist.github.com/TheBinitGhimire/9ebcd27086a11df1d7ec925e5f604e03

Another variant of this, which probably doesn't get you an SSL
cert, is a dangling CNAME. These can be easier to get. If
ces.example.com was a CNAME to cesdemosite2017.com then when
cesdemosite2017.com expires, it's trivial to re-register it and
squat "as" ces.example.com.

The most insidious version is a DNS delegation. If ces.example.com is an
NS record (unlikely for a marketing site, but plausible for some other
scenarios) and it goes to ns1.parternership.net, when parternership.net
expires the attacker can grab that, create a new ns1.parternership.net
and give themselves finan.ces.example.com then start spitting out bogus
bills with it.

The CAA record adds a smidgen more protection against those attacks.
(I don't think that's what it is designed for, but a good defense
works against more than just the original attack method.)

I also found this in my search, which is exactly the sort of threat
CAA was meant to handle:

https://en.wikipedia.org/wiki/Comodo_Cybersecurity#Dangling_markup_injection_vulnerability
On 25 July 2016, Matthew Bryant showed that Comodo's website is
vulnerable to dangling markup injection attacks and can send emails
to system administrators from Comodo's servers to approve a wildcard
certificate issue request which can be used to issue arbitrary
wildcard certificates via Comodo's 30-Day PositiveSSL product.

Bugs in automated systems that give out arbitrary certs are not
common, but very very nasty.

Elijah
--
DNS: the cause of, and solution to, all our Internet problems
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: XML Considered Harmful

2021-09-21 Thread Eli the Bearded
In comp.lang.python, Michael F. Stemper  wrote:
> I've heard of JSON, but never done anything with it.

You probably have used it inadvertantly on a regular basis over the
past few years. Websites live on it.

> How does CSV handle hierarchical data? For instance, I have
> generators[1], each of which has a name, a fuel and one or more
> incremental heat rate curves. Each fuel has a name, UOM, heat content,
> and price. Each incremental cost curve has a name, and a series of
> ordered pairs (representing a piecewise linear curve).
> 
> Can CSV files model this sort of situation?

Can a string of ones and zeros encode the sounds of Bach, the images
of his sheet music, the details to reproduce his bust in melted plastic
extruded from nozzle under the control of machines?

Yes, CSV files can model that. But it would not be my first choice of
data format. (Neither would JSON.) I'd probably use XML.

I rather suspect that all (many) of those genomes that end up in
Microsoft Excel files get there via a CSV export from a command line
tool. Once you can model life in CSV, everything seems possible.

> [1] The kind made of tons of iron and copper, filled with oil, and
> rotating at 1800 rpm.

Those are rather hard to model in CSV, too, but I'm sure it could be
done.

Elijah
--
for bonus round, use punched holes in paper to encode the ones and zeros
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: XML Considered Harmful

2021-09-23 Thread Eli the Bearded
In comp.lang.python, Christian Gollwitzer   wrote:
> Am 22.09.21 um 16:52 schrieb Michael F. Stemper:
>> On 21/09/2021 19.30, Eli the Bearded wrote:
>>> Yes, CSV files can model that. But it would not be my first choice of
>>> data format. (Neither would JSON.) I'd probably use XML.
>> Okay. 'Go not to the elves for counsel, for they will say both no
>> and yes.' (I'm not actually surprised to find differences of opinion.)

Well, I have a recommendation with my answer.

> It's the same as saying "CSV supports images". Of course it doesn't, its 
> a textfile, but you could encode a JPEG as base64 and then put this 
> string into the cell of a CSV table. That definitely isn't what a sane 
> person would understand as "support".

I'd use one of the netpbm formats instead of JPEG. PBM for one bit
bitmaps, PGM for one channel (typically grayscale), PPM for three
channel RGB, and PAM for anything else (two channel gray plus alpha,
CMYK, RGBA, HSV, YCbCr, and more exotic formats). JPEG is tricky to
map to CSV since it is a three channel format (YCbCr), where the
channels are typically not at the same resolution. Usually Y is full
size and the Cb and Cr channels are one quarter size ("4:2:0 chroma
subsampling"). The unequal size of the channels does not lend itself
to CSV, but I can't say it's impossible.

But maybe you meant the whole JFIF or Exif JPEG file format base64
encoded with no attempt to understand the image. That sort of thing
is common in JSON, and I've seen it in YAML, too. It wouldn't surprise
me if people do that in CSV or XML, but I have so far avoided seeing
that. I used that method for sticking a tiny PNG in a CSS file just
earlier this month. The whole PNG was smaller than the typical headers
of an HTTP/1.1 request and response, so I figured "don't make it a
separate file".

Elijah
--
can at this point recegnize a bunch of "magic numbers" in base64


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


Re: XML Considered Harmful

2021-09-25 Thread Eli the Bearded
In comp.lang.python, Chris Angelico   wrote:
> Eli the Bearded <*@eli.users.panix.com> wrote:
>> I'd use one of the netpbm formats instead of JPEG. PBM for one bit
>> bitmaps, PGM for one channel (typically grayscale), PPM for three
>> channel RGB, and PAM for anything else (two channel gray plus alpha,
>> CMYK, RGBA, HSV, YCbCr, and more exotic formats). JPEG is tricky to
>> map to CSV since it is a three channel format (YCbCr), where the
>> channels are typically not at the same resolution. Usually Y is full
>> size and the Cb and Cr channels are one quarter size ("4:2:0 chroma
>> subsampling"). The unequal size of the channels does not lend itself
>> to CSV, but I can't say it's impossible.
> Examine prior art, and I truly do mean art, from Matt Parker:
> https://www.youtube.com/watch?v=UBX2QQHlQ_I

His spreadsheet is a PPM file, not a JPEG. You can tell because all of
the cells are the same size.

He also ignores vector graphics when considering digital images. Often
they are rendered in what he calls "spreadsheets" but not always. I have
a Vectrex, for example.

Elijah
--
then there's typewriter art with non-square "pixels"
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: The task is to invent names for things

2021-10-27 Thread Eli the Bearded
In comp.lang.python, Peter J. Holzer  wrote:
 ^^

> On 2021-10-27 12:41:56 +0200, Karsten Hilbert wrote:
>> In that situation, is it preferable to choose a nonsensical
>> name over a mediocre one ?
> I don't know. A mediocre name conveys at least some information, and
> that seems to be better than none. On the other hand it might be just
> enough to lead the reader astray which wouldn't happen with a
> non-sensical name.

C is named as a pun on the earlier B, which was derived from BCPL, the
Barely Complete Programming Language. Unix is a pun on Multix, Linux
a personalization of Unix. sed is a portmanteaux of "stream editor".
AWK is named for the authors' initials. Perl started out as an
initialism (Practical Extraction and Report Language, I think), which
the manpage used to lead with. Ruby is named as a play on Perl, it's a
different four letter gem, and Ruby has obvious Perl influence.

But "Python"? What's Python named for? Hint, it's a pretty "non-sensical
name" for a computer language.

> But since perfect names are hard to find, using nonsensical instead of
> mediocre names would mean choosing nonsensical names most of the time.
> So I'll stick with mediocre names if in doubt.

The choice of a non-sensical is perfectly fine _when_ it's a major
component. Kafka, Python, Java, Rust. Those are all non-sensically named,
in that the name doesn't fit what it is, by pun, initials, or reference.
Someone just liked the name and applied it to thing being build. The
designer of Kafka liked the author. Guido liked Monty Python. Java is
named for coffee. Rust is named for a fungus. 

Those all work. But if you are writing a new web framework and you name
your method to log stuff to a remote server "Britney" because you were
listening the singer, that's not perfectly fine, even you want to make
"Oops, I did it again" jokes about your logged errors.

Where naming has a great importance to understanding, it needs to be
done carefully. Mediocre names work, but can be confusing. For the
remote logging example, there's probably not a lot of difficulty with
mediocre. If you're doing something with a multiple of things, do you
call it a "pod", "cluster", "group", "set", etc? You can pick one but
then when you have multiples of multiples, you'll want to pick another
and if you do it wrong it will confuse people. A Kubernetes "cluster"
will run replica "sets" of "pods" (each of which have one or more
"containers", but "containers" is a word that predates Kubernetes).

If your framework runs "sets" of "clusters" that reversal of heirarchy
ends up being more likely to confuse. Or look at the mess that AWS has
for Elasticache Redis: you can have a "cluster" that provides redundancy
in case something fails. Or you can run in "cluster mode" which shards
the data across multiple independent nodes. If you want redundancy
in "cluster mode" you can can have groups of replicas.

Redis no replication or sharding:   Node

Redis non-cluster mode cluster: Node Replica-Node1 ...

Redis cluster mode cluster no replicaion:
Shard-1-Primary-Node
Shard-2-Primary-Node
...

Redis cluster mode cluster with replicas:
Shard-1-Primary-Node Shard-1-Replica-Node-1 ...
Shard-2-Primary-Node Shard-2-Replica-Node-1 ...
...

Maybe this is Redis's fault or maybe it's AWS's, I don't know the
history of these names, I've only used it on AWS. But whoever did the
naming did a "mediocre" job to come up with something that's called a
"Redis cluster-mode enabled cluster".

https://aws.amazon.com/blogs/database/work-with-cluster-mode-on-amazon-elasticache-for-redis/

Elijah
--
naming is hard, unless it's easy
-- 
https://mail.python.org/mailman/listinfo/python-list


news to me today: RIP Aahz

2021-11-18 Thread Eli the Bearded
Aahz, co-author of Python for Dummies with Stef Maruch, recently passed
away.

Tiny death notice (with name typo) from the wilds of the Internet:

http://file770.com/pixel-scroll-10-15-21-i-know-what-pixel-you-scrolled-last-summer/

(12) AAHZ MARUCH (1967-2021). [Item by James Davis Nicoll.] Python
programmer, whose fannish activities date back at least as far as
classic USENET (alt.poly and other groups), died October 14
following several years of ill health. Survived by partner Steph
Maruch.

Editor's postscript: Alan Prince Winston earlier this year described
him as "an unstoppable-seeming guy" who "became a contra and square
dance caller and choreographer despite really severe hearing
impairment."

I met Aahz once. He always wanted to be a mononym person, and used his
partner's surname only reluctantly.

Elijah
--
Aahz's rule6 website seems to be held by a squatter now

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


need help understanding: converting text to binary

2019-04-22 Thread Eli the Bearded
Here's some code I wrote today:

-- cut here 8< --
HEXCHARS = (b'0', b'1', b'2', b'3', b'4', b'5', b'6', b'7', b'8', b'9',
b'A', b'B', b'C', b'D', b'E', b'F',
b'a', b'b', b'c', b'd', b'e', b'f')


# decode a single hex digit
def hord(c):
c = ord(c)
if c >= ord(b'a'):
return c - ord(b'a') + 10
elif c >= ord(b'A'):
return c - ord(b'a') + 10
else:
return c - ord(b'0')


# decode quoted printable, specifically the MIME-encoded words
# variant which is slightly different than the body text variant
def decodeqp(v):
out = b''
state = '' # used for =XY decoding
for c in list(bytes(v,'ascii')):
c = bytes((c,))

if c == b'=':
if state == '':
state = '='
else:
raise ValueError
continue

   if c == b'_':   # underscore is space only for MIME words
if state == '':
out += b' '
else:
raise ValueError
continue

if c in HEXCHARS:
if state == '':
out += c
elif state == '=':
state = hord(c)
else:
state *= 16
state += hord(c)
out += bytes((state,))
state = ''
continue

if state == '':
out += c
else:
raise ValueError
continue

if state != '':
raise ValueError

return out
-- >8 cut here --

It works, in the sense that

 print(decodeqp("=21_yes"))

will output

 b'! yes'

But the bytes() thing is really confusing me. Most of this is translated
from C code I wrote some time ago. I'm new to python and did spend some
time reading:

https://docs.python.org/3/library/stdtypes.html#bytes-objects

Why does "bytes((integertype,))" work? I'll freely admit to stealing
that trick from /usr/lib/python3.5/quopri.py on my system. (Why am I not
using quopri? Well, (a) I want to learn, (b) it decodes to a file
not a variable, (c) I want different error handling.)

Is there a more python-esque way to convert what should be plain ascii
into a binary "bytes" object? In the use case I'm working towards the
charset will not be ascii or UTF-8 all of the time, and the charset
isn't the responsibility of the python code. Think "decode this if
charset matches user-specified value, then output in that same charset;
otherwise do nothing."

Elijah
--
has yet to warm up to this language
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: need help understanding: converting text to binary

2019-04-23 Thread Eli the Bearded
In comp.lang.python, Chris Angelico   wrote:
> Have you checked to see if Python can already do this? You mention

I'm sure there's a library already. I'm trying to mix library usage with
my own code to get practice writing in python. In this case, I want code
to deal with MIME encoding in email headers. I turned to a library for
the base64 part and translated C code I once wrote for the
quoted-printable part. I was struck by how complicated it seems to be to
generate binary blobs in python, which makes me think I'm not getting
something.

>> Is there a more python-esque way to convert what should be plain ascii
> What does "plain ASCII" actually mean, though?

ASCII encoded binary data. ASCII is code points that fit in 7-bits
comprising the characters found on a typical 1970s US oriented
typewriter plus a few control characters.

>> into a binary "bytes" object? In the use case I'm working towards the
>> charset will not be ascii or UTF-8 all of the time, and the charset
>> isn't the responsibility of the python code. Think "decode this if
>> charset matches user-specified value, then output in that same charset;
>> otherwise do nothing."
> I'm not sure what this means,

If the terminal expects this encoding, then decode the ASCII transport
encoding and show the raw stream. If the terminal doesn't expect this
encoding, do not decode. Python should be treating it as a a binary
stream, and doesn't need to understand the encoding itself.

> but I would strongly recommend just
> encoding and decoding regardless. Use text internally and bytes at the
> outside.

That feels entirely wrong. I don't know what b'\x9A' means without
knowing the character set and character encoding. If the encoding is a
multibyte one, b'\x9A' doesn't mean anything on its own. That's why I
want to treat it as binary.

Elijah
--
thinking of an array of "unsigned char" not of characters
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: need help understanding: converting text to binary

2019-04-23 Thread Eli the Bearded
In comp.lang.python, Paul Rubin   wrote:
> Eli the Bearded <*@eli.users.panix.com> writes:
>> # decode a single hex digit
>> def hord(c): ...
> 
>def hord(c): return int(c, 16)

That's a good method, thanks.

> > # decode quoted printable, specifically the MIME-encoded words
> > # variant which is slightly different than the body text variant
> > def decodeqp(v): ...
> 
> I think this is supposed to mean:
> 
> from itertools import islice
> 
> def getbytes(v):
> cs = iter(bytes(v,'ascii'))
> for c in cs:
> if c == ord('='):
> h1,h2 = islice(cs,2)
> yield int(chr(h1)+chr(h2), 16)
> else: yield c
> 
> def decodeqp(v):
> return bytes(getbytes(v))
> 
> print (decodeqp('=21_yes'))  # prints "b'!_yes'"

But that's not the output my sample produced.

  def getbytes(v):
  cs = iter(bytes(v,'ascii'))
  for c in cs:
  if c == ord('='):
  h1,h2 = islice(cs,2)
  yield int(chr(h1)+chr(h2), 16)
  elif c == ord('_'):
  yield ord(' ')
  else: yield c

That's certainly a lot cleaner that what I had.

Elijah
--
and shorter than the one in /usr/lib/python3.5/quopri.py
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: need help understanding: converting text to binary

2019-04-23 Thread Eli the Bearded
In comp.lang.python, Cameron Simpson   wrote:
> On 23Apr2019 20:35, Eli the Bearded <*@eli.users.panix.com> wrote:
>> That feels entirely wrong. I don't know what b'\x9A' means without
>> knowing the character set and character encoding. If the encoding is a
>> multibyte one, b'\x9A' doesn't mean anything on its own. That's why I
>> want to treat it as binary.
> If you don't know the encoding then you don't know you're looking at a 
> hex digit. OTOH, if the binary data contain ASCII data then you do know 
> the encoding: it is ASCII.

Hmmm. Maybe I'm not making myself clear. ASCII "=9a" should decode to
b'\x9A' and it is that binary byte for which I don't know the meaning
and why I don't want to use "text internallly" for as suggested
upthread.

> If that is mixed with other data then you need to know where it 
> starts/stops in order to pull it out to be decoded. The overall data may 
> be a mix, but the bit you're pulling out is encoded text, which you 
> could decode.

I do want to decode it, and possibly compare it for an exact match. And
because there are different possible encodings of the same source data
(consider the trivial case of "=9A" versus "=9a", I don't want to just
keep it in raw form).

Elijah
--
not to mention QP versus b64
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Generating generations of files

2019-04-29 Thread Eli the Bearded
In comp.lang.python, Peter J. Holzer  wrote:
> On 2019-04-29 20:12:28 -, Grant Edwards wrote:
>> Well, the FILES-11 filesystem on VAX/VMS did that automatically, but
>> that's probably not too helpful.
> Until this is finished you could use something like this:
> 
> #!/usr/bin/python3
> 
> import os
> 
> def open11(file, mode, **kwargs):
> if "w" in mode:
> try:
> oldfile = os.readlink(file)
> basename, version = oldfile.split(";")
> except FileNotFoundError:
> basename = os.path.basename(file)
> version = 0
> newfile = basename + ";" + str(int(version) + 1)
> os.unlink(file)
> os.symlink(newfile, file)
> return open(file, mode, **kwargs)
> 
> 
> if __name__ == "__main__":
> with open11("foo", "w") as f:
> f.write("test1")
> 
> with open11("foo", "w") as f:
> f.write("test2")
> 
> with open11("foo", "w") as f:
> f.write("test3")
> 
> :-)

Noted.

> (WARNING: I haven't really tested this)

No foo:

Traceback (most recent call last):
  File "versioned-open", line 21, in 
with open11("foo", "w") as f:
  File "versioned-open", line 15, in open11
os.unlink(file)
FileNotFoundError: [Errno 2] No such file or directory: 'foo'

There is a foo, but it's not a symlink:

Traceback (most recent call last):
  File "versioned-open", line 21, in 
with open11("foo", "w") as f:
  File "versioned-open", line 9, in open11
oldfile = os.readlink(file)
OSError: [Errno 22] Invalid argument: 'foo'

Parse error on version string:

Traceback (most recent call last):
  File "versioned-open", line 21, in 
with open11("foo", "w") as f:
  File "versioned-open", line 10, in open11
basename, version = oldfile.split(";")
ValueError: not enough values to unpack (expected 2, got 1)

etc (there are several possible parse errors: no semicolon, multiple
semicolons, invalid literal for int()).

That said, I do think it makes a reasonable suggestion for the stated
versioning requirement.

Elijah
--
bet a FAT filesystem would produce a different error
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Generating generations of files

2019-04-29 Thread Eli the Bearded
In comp.lang.python, DL Neil   wrote:
> On 30/04/19 10:59 AM, Chris Angelico wrote:
>>> bet a FAT filesystem would produce a different error
>> Probably it'd raise BadFileSystemError or something. Which is a
> Fortunately, it runs on a Linux 'compute server'.

I mount FAT under Linux all the time.

Elijah
--
but generally for sneakernet reasons
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Conway's game of Life, just because.

2019-05-07 Thread Eli the Bearded
In comp.lang.python, Paul Rubin   wrote:

Thanks for posting this. I'm learning python and am very familiar with
this "game".

> #!/usr/bin/python3
> from itertools import chain
> 
> def adjacents(cell):# generate coordinates of cell neighbors
> x, y = cell # a cell is just an x,y coordinate pair
> return ((x+i,y+j) for i in [-1,0,1] for j in [-1,0,1] if i or j)

This line confuses me. How do you expect "if i or j" to work there?

>>> for pair in adjacents((0,0)):
...print(pair)
...
(-1, -1)
(-1, 0)
(-1, 1)
(0, -1)
(0, 1)
(1, -1)
(1, 0)
(1, 1)
>>> def neighboring(cell):
... x, y = cell
... return ((x+i,y+j) for i in [-1,0,1] for j in [-1,0,1])
... 
>>> 
>>> for pair in neighboring((0,0)):
...print(pair)
... 
(-1, -1)
(-1, 0)
(-1, 1)
(0, -1)
(0, 0)
(0, 1)
(1, -1)
(1, 0)
(1, 1)
>>>

Elijah
--
is the torus game board unintentional?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Conway's game of Life, just because.

2019-05-07 Thread Eli the Bearded
In comp.lang.python, MRAB   wrote:
> I've never seen a version of Conway's Game of Life where the board 
> doesn't wrap around.

The one I wrote in vi macros doesn't. It's a design choice you can make.

(Thanks for the explainations everyone.)

Elijah
--
the vi macro one is included in the vim macros directory
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: convert .py to Android ?

2019-05-14 Thread Eli the Bearded
In comp.lang.python, Ben Finney   wrote:
> "Steve"  writes:
>> I have a working .py program
>> that I want to get into my Android Moto G phone.
> To my knowledge, an Android app must be implemented, at some level, in
> Java and specifically linked to Android Java libraries. That's a hard
> limitation of the Android platform.
> 
> That implies that any Python program will need to be written at least
> with partial awareness that it is not going to run in a native Python
> VM, but instead get compiled to somehow run in a Java Android environment.

If it doesn't have a GUI, the easy solution is put Termux on the phone,
run "pkg install python" (or python2), then install 'curl' or 'ssh' (for
scp) to transfer the program over. I use Termux scripts on my phone for
image preprocessing (namely strip exif and downscale) prior to using my
photos on the open web.

Elijah
--
also uses Termux as an ssh client
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Proper shebang for python3

2019-07-22 Thread Eli the Bearded
In comp.lang.python, Tim Daneliuk   wrote:
> On 7/20/19 1:20 PM, Chris Angelico wrote:
> > On Sun, Jul 21, 2019 at 4:13 AM Michael Speer  wrote:
> >> You may want to use `#!/usr/bin/env python3` instead.

I no longer have one to verify, but I recall Solaris boxen used /bin/env
not /usr/bin/env.

> So, no, do NOT encode the hard location - ever.  Always use env to
> discover the one that the user has specified. 

But wait, you just hard coded the location of env...

>The only exception is
> /bin/sh which - for a variety of reasons - can reliably counted upon.

B! Fully half of my work porting trn4 to my cellphone was fixing all
the places that ancient build system believed /bin/sh was the name of
sh. In that environment (Termux shell on an Android phone) the location
is /data/data/com.termux/files/usr/bin/sh (and env is also in
/data/data/com.termux/files/usr/bin hahaha).

Even on more traditional environments -cough-Solaris-cough- /bin/sh may
exist but be so ancient as to break things that work elsewhere. "^" as
a synonym for "|", is a noteworthy gotcha.

Figuring out where things are on the user's path is a laudable goal, but
do it only at install time, not run time, for consistent runs.

Elijah
--
pathological edge cases -r- us
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Hermetic environments

2019-07-24 Thread Eli the Bearded
In comp.lang.python, DL Neil   wrote:
> Is Python going 'the right way' with virtual environments?
...
> Am I 'getting away with it', perhaps because my work-pattern doesn't 
> touch some 'gotcha' or show-stopper?
> 
> Why, if so much of 'the rest of the world' is utilising "containers", 
> both for mobility and for growth, is the Python eco-system following its 
> own path?

I'm going to speculate that even inside containers, some people will use
multiple virtual environments. It could be that the app and the
monitoring for that app are developed by different branches of the
company and have different requirements.

But I think a lot of the use of virtual environments is in dev
environments where a developer wants to have multiple closed settings
for doing work. On the dev branch, newer versions of things can be
tested, but a production environment can be retained for hotfixes to
deployed code.

Or because the different microservices being used are each at different
update levels and need their own environments.

> Is there something about dev (and ops) using Python venvs which is a 
> significant advantage over a language-independent (even better: an 
> OpSys-independent) container?

I'm not a big fan of language-dependent virtual environments because
they only capture the needs of a particular language. Very often code
works with things that are outside of that language, even if it is only
system libraries.

Elijah
--
interested in hearing other voices on this
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Proper shebang for python3

2019-07-25 Thread Eli the Bearded
In comp.lang.python, Thomas 'PointedEars' Lahn   wrote:
> Michael Torrie wrote:
>> On 7/24/19 4:20 PM, Cameron Simpson wrote:
>>> That is some progress, hooray. Then there's just sbin -> bin to go.
>> I suppose in the olden days sbin was for static binaries, […]
> No, “sbin” is short for “*system* binaries” which in general only the 
> superuser should be able to execute.

I think Michael is confusing "sbin" with the statically linked utilities
some systems (particularly older ones, but also FreeBSD in /rescue/)
have for repairing the system when things start to go bad. You'd want
a shell (sh is great), a basic editor (eg, eg), and a smattering of
other tools, akin to the ones listed as "must be in /sbin" in your
linuxfoundation link.

But more than a few utilities in /sbin are useful for non-superusers.
Eg ip or ifconfig for informational purposes like identifying current
IP address and getting MAC.

> Which is why the above is a Very Bad Idea[tm].

Why? Programs that can *only* be usefully run by a privileged user
or in a system context (eg halt or getty) already *must* prevent non
privileged use. So why would it be a Very Bad Idea[tm] to have them in
a common directory like /bin/?

(Feel free to crosspost and set follow-ups to another group if you like.
But I would suggest *not* a Linux group, since this is something general
to all Unix-likes.)

> 

Elijah
--
uses both netbsd and linux regularly
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: [OT(?)] Ubuntu 18 vim now defaults to 4-space tabs

2019-09-09 Thread Eli the Bearded
In comp.lang.python, Tobiah   wrote:
> We upgraded a server to 18.04 and now when I start typing

Your subject missed a critical word: vim. There are a lot of editors in
Ubuntu, and probably they don't all do that.

> This is more of a vim question perhaps, but I'm already
> subscribed here and I figured someone would know what
> to do.

Run vim. Then ':set' to see what's set different than default. Then,
if it is tabstop you want to know about, ':verbose set tabstop?' will
tell you where that setting was last altered.

I'm not seeing tabstops changed on my Ubuntu 18.04, but I may have vim
installed with different packages. I prefer vim configured in a closer to
vi-compatible way than defaults.

Elijah
--
expects `ed` and `nano` still work the same
-- 
https://mail.python.org/mailman/listinfo/python-list


  1   2   >