Re: Need help please

2023-04-10 Thread Thomas Passin

On 4/10/2023 9:59 AM, Jack Gilbert wrote:

I D/L 3.11.3, I can see it in CMD

running W10 64bit

I have IDL on my desktop,

HOW do I get 3.11.3 on my desktop?


If you mean "How can I create a shortcut to Python 3.11.3 on my desktop 
that opens an interactive Python session", here is one way:


1. Find where your Python 3.11.3 program has been installed.  On the 
command line in a console, type:


py -c "import sys; print(sys.executable)"

You will get a response like this:

C:\Users\tom\AppData\Local\Programs\Python\Python311\python.exe

NOTE:  If the "py" command is not on your computer or does not open 
Python 3.11, then open a python 3.11 session and type the same commands:


import sys
print(sys.executable)

2. Open the Windows file browser ("Windows Explorer") and navigate to 
that directory.  On my computer this is


C:\Users\tom\AppData\Local\Programs\Python\Python311

3. Press and hold both the CTRL and SHIFT keys down at the same time, 
and with the mouse drag the icon for "python.exe" to a blank space on 
the desktop.  This will not drag the program itself but will create a 
shortcut and drag that.


4. Test the new shortcut by double-clicking on it and seeing that a new 
console window opens with the Python interpreter running in it.


If you do not like the size, shape, or font of this new console, change 
them by clicking on the icon in the upper left, then selecting 
"Properties", and making changes in the dialog box that opens.  The new 
choices will be used whenever you use this shortcut again.


5. The new shortcut will probably be named "python.ex".  I suggest that 
you rename it to "Python 3.11".  This way you can create other python 
shortcuts without having their names conflict.

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


Re: Need help please

2023-04-10 Thread Sravan Kumar Chitikesi
use where cmd to find out the path of the binary and create a shortcut to
that file on desktop

Regards,
*Sravan Chitikesi*
AWS Solutions Architect - Associate


On Mon, Apr 10, 2023 at 10:03 AM Jack Gilbert <00jhen...@gmail.com> wrote:

> I D/L 3.11.3, I can see it in CMD
>
> running W10 64bit
>
> I have IDL on my desktop,
>
> HOW do I get 3.11.3 on my desktop?
>
> Thanks
>
> Jack g
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Need help please

2023-04-10 Thread Jack Gilbert
I D/L 3.11.3, I can see it in CMD

running W10 64bit

I have IDL on my desktop,

HOW do I get 3.11.3 on my desktop?

Thanks

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


Re: Need help with custom string formatter

2022-11-05 Thread MRAB

On 2022-11-05 11:07, Stefan Ram wrote:

Robert Latest  writes:

result += ' ' *( length - len( result ))

Nice, I didn't know that one could multiply strings by negative numbers without
error.


   Thanks, but today I thought that maybe there might
   be a solution for getting a field of a fixed length
   that is even shorter. It uses Python's string
   formatting, here in the form of an "f" string.

   main.py

def f( result, length ):
 # get a field with the given length from the string "result"
 # - as used in postings from october
 result = result[ :length ]
 result += ' ' *( length - len( result ))


That can be done more compactly as:

 result = result[ : length].ljust(length)


 return result


[snip]


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


Re: need help

2022-10-24 Thread Peter J. Holzer
On 2022-10-24 01:02:24 +, rbowman wrote:
> On Mon, 24 Oct 2022 10:02:10 +1100, Cameron Simpson wrote:
> > I'd say GMail are rudely dropping traffic to port 2525. Maybe try just
> > 25,
> > the normal SMTP port?
> 
> 2525 is an alternative to 587, the standard TLS port.

Port 587 is not the standard TLS port. Port 587 is the standard mail
submission port (i.e., a MUA should use port 587 when sending mail; MTAs
should use port 25 when relaying mails to other MTAs).

Traffic on both port 25 and 587 starts in plain text. The server can
indicate that it supports TLS and the client can then send a STARTTLS
command to start a TLS session.

If you want to start the connection with TLS, you can (usually) use port
465. Like 587, this is only intended for mail submission, not mail
transport.

hp

-- 
   _  | Peter J. Holzer| Story must make more sense than reality.
|_|_) ||
| |   | h...@hjp.at |-- Charles Stross, "Creative writing
__/   | http://www.hjp.at/ |   challenge!"


signature.asc
Description: PGP signature
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: need help

2022-10-23 Thread Cameron Simpson

On 24Oct2022 01:02, rbowman  wrote:

On Mon, 24 Oct 2022 10:02:10 +1100, Cameron Simpson wrote:
I'd say GMail are rudely dropping traffic to port 2525. Maybe try 
just 25, the normal SMTP port?


2525 is an alternative to 587, the standard TLS port.


Yah. My point was more focussed on GMail's shoddy firewall practices not 
returning connection refused.



25  and 587 work.


Good to know. Thanks!
Cameron Simpson 
--
https://mail.python.org/mailman/listinfo/python-list


Re: need help

2022-10-23 Thread rbowman
On Mon, 24 Oct 2022 10:02:10 +1100, Cameron Simpson wrote:


> I'd say GMail are rudely dropping traffic to port 2525. Maybe try just
> 25,
> the normal SMTP port?

2525 is an alternative to 587, the standard TLS port. 25  and 587 work.

telnet smtp.gmail.com 587
Trying 2607:f8b0:4023:1004::6d...
Connected to smtp.gmail.com.
Escape character is '^]'.
220 smtp.gmail.com ESMTP s6-20020a056870ea8600b0010bf07976c9sm13154711oap.
41 - gsmtp
EHLO
501-5.5.4 Empty HELO/EHLO argument not allowed, closing connection.
501 5.5.4  https://support.google.com/mail/?p=helo 
s6-20020a056870ea8600b0010bf07976c9sm13154711oap.41 - gsmtp
Connection closed by foreign host.


The EHLO needs a domain.  Port 25 is the same. 
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: need help

2022-10-23 Thread Cameron Simpson
Please try to choose more descriptive subject lines (eg "problem with 
sock.connect" or similar). That you want help is almost implicit, and 
what the whole list is for.


Anyway, to your problem:

On 23Oct2022 10:19, Shuaib Akhtar  wrote:

  How to fix Traceback (most recent call last):
    File "C:\Program
  
Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.2288.0_x64__qbz5n2kfra8p0\lib\socket.py",
  line 833, in create_connection
      sock.connect(sa)
  TimeoutError: [WinError 10060] A connection attempt failed because 
  the connected party did not properly respond after a period of time, or

  established connection failed because connected host has failed to respond


This usually means that either the host address is legal but incorrect 
(there's no host/server listening with that address) or that the port is 
incorrect and some firewall is _discarding_ your traffic because of the 
wrong port instead of returning a nice "connection refused", which is 
usually instant.


Fortunately you've listed your call:

    File "C:\Users\i9shu\Downloads\python email bot\email bot.py", 
  line 25,

  in 
      server = smtplib.SMTP('smtp.gmail.com',2525)


So, I'll try that by hand here:

% telnet smtp.gmail.com 2525
Trying 142.250.4.108...
telnet: connect to address 142.250.4.108: Operation timed out
Trying 2404:6800:4003:c0f::6d...
telnet: connect to address 2404:6800:4003:c0f::6d: No route to host
telnet: Unable to connect to remote host
%

I'd say GMail are rudely dropping traffic to port 2525. Maybe try just 
25, the normal SMTP port?


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


need help

2022-10-23 Thread Shuaib Akhtar
   How to fix Traceback (most recent call last):

     File "C:\Program
   
Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.2288.0_x64__qbz5n2kfra8p0\lib\socket.py",
   line 833, in create_connection

       sock.connect(sa)

   TimeoutError: [WinError 10060] A connection attempt failed because the
   connected party did not properly respond after a period of time, or
   established connection failed because connected host has failed to respond

    

   During handling of the above exception, another exception occurred:

    

   Traceback (most recent call last):

     File "C:\Users\i9shu\Downloads\python email bot\email bot.py", line 25,
   in 

       server = smtplib.SMTP('smtp.gmail.com',2525)

     File "C:\Program
   
Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.2288.0_x64__qbz5n2kfra8p0\lib\smtplib.py",
   line 255, in __init__

       (code, msg) = self.connect(host, port)

     File "C:\Program
   
Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.2288.0_x64__qbz5n2kfra8p0\lib\smtplib.py",
   line 341, in connect

       self.sock = self._get_socket(host, port, self.timeout)

     File "C:\Program
   
Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.2288.0_x64__qbz5n2kfra8p0\lib\smtplib.py",
   line 312, in _get_socket

       return socket.create_connection((host, port), timeout,

     File "C:\Program
   
Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.2288.0_x64__qbz5n2kfra8p0\lib\socket.py",
   line 833, in create_connection

       sock.connect(sa)

   KeyboardInterrupt

    

   Process finished with exit code -1073741510 (0xC13A: interrupted by
   Ctrl+C)

   eorr

    

   Sent from [1]Mail for Windows

    

References

   Visible links
   1. https://go.microsoft.com/fwlink/?LinkId=550986
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Need help with custom string formatter

2022-10-22 Thread Robert Latest via Python-list
Cameron Simpson wrote:
> Stefan's code implements it's own format_field and falls back to the 
> original format_field(). That's standard subclassing practice, and worth 
> doing reflexively more of the time - it avoids _knowing_ that 
> format_field() just calls format().
>
> So I'd take Stefan's statement above to imply that calling format() 
> directly should work.

Yup, makes sense.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Need help with custom string formatter

2022-10-21 Thread Cameron Simpson

On 21Oct2022 16:55, Stefan Ram  wrote:

 I was not aware of "isdigit".


There's also "isdecimal" and "isnumeric". They all have subtly different 
meanings :-)


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


Re: Need help with custom string formatter

2022-10-21 Thread Cameron Simpson

On 21Oct2022 16:55, Stefan Ram  wrote:

Robert Latest  writes:

return super().format_field( value, format_string )

Why do you prefer super().format_field() over plain format()? The doc says:
"format_field() simply calls format()." So I figured I might do the same.


 I am not aware of any reason not to call "format" directly.


Stefan's code implements it's own format_field and falls back to the 
original format_field(). That's standard subclassing practice, and worth 
doing reflexively more of the time - it avoids _knowing_ that 
format_field() just calls format().


So I'd take Stefan's statement above to imply that calling format() 
directly should work.


My own habit would be to stick with the original, if only for semantic 
reasons. Supposing you switched from subclassing Formatter to some other 
class which itself subclasses Formatter. (Yes, that is probably 
something you will never do.) Bypassing the call to 
super().format_field(...) prevents shoehorning some custom format_fields 
from the changed superclass. Which you'd then need to debug.


That's all.

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


Re: Need help with custom string formatter

2022-10-21 Thread Robert Latest via Python-list
Stefan Ram wrote:

[the solution]

thanks, right on the spot. I had already figured out that format_field() is the
one method I need, and thanks for the str.translate method. I knew that raking
seven RE's across the same string HAD to be stupid.

Have a nice weekend!

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


Need help with custom string formatter

2022-10-21 Thread Robert Latest via Python-list
Hi all,

I would like to modify the standard str.format() in a way that when the
input field is of type str, there is some character replacement, and the
string gets padded or truncated to the given field width. Basically like
this:

fmt = MagicString('<{s:6}>')
print(fmt.format(s='Äußerst'))

Output:


I've written a function fix_format() which, given a string and a field width,
does just that. However, I find myself unable to implement a Formatter that
uses this function in the intened way. See the example below, I hope I
sprinkled it with enough comments to make my intents clear.  Thanks for any
enlightenment. The interesting part starts somewhere in the middle.

### Self contained example
import re
from string import Formatter

_replacements = [(re.compile(rx), repl) for rx, repl in (\
('Ä', 'Ae'),
('ä', 'ae'),
('Ö', 'Oe'),
('ö', 'oe'),
('Ü', 'Ue'),
('ü', 'ue'),
('ß', 'ss'))]

def fix_format(text, width):

# Seven regex passes seems awfully inefficient. I can't think of a
# better way. Besides the point though.
for rx, repl in _replacements:
text = re.sub(rx, repl, text)

# return truncated / padded version of string
return text[:width] + ' ' * max(0, width - len(text))

class Obj():
"""I'm just an object with some attributes"""
def __init__(self, **kw):
self.__dict__.update(kw)

o = Obj(x="I am X, and I'm too long",
y="ÄÖÜ Ich bin auch zu lang")
z = 'Pad me!'

format_spec = '<{o.x:6}>\n<{o.y:6}>\n<{z:10}>'

# Standard string formatting
print('Standard string formatting:')
print(format_spec.format(o=o, z=z))

# Demonstrate fix_format()
print('\nWanted output:')
print('<' + fix_format(o.x, 6) + '>')
print('<' + fix_format(o.y, 6) + '>')
print('<' + fix_format(z, 10) + '>')

# This is where my struggle begins. #

class MagicString(Formatter):
def __init__(self, format_spec):
self.spec = format_spec
super().__init__()

def format(self, **kw):
return(self.vformat(self.spec, [], kw))

def get_field(self, name, a, kw):
# Compound fields have a dot:
obj_name, _, key = name.partition('.')
obj = getattr(kw[obj_name], key) if key else kw[obj_name]
if isinstance(obj, str):
# Here I would like to call fix_format(), but I don't know where
# to get the field width.
print('get_field(): <' + obj + '>')
else:
# Here I'd like to use the "native" formatter of whatever type
# the field is.
pass
return obj, key

def get_value(self, key, a, kw):
'''I don't understand what this method is for, it never gets called'''
raise NotImplementedError

fmt = MagicString(format_spec)
print('\nReal output:')
print(fmt.format(o=o, z=z))

# Weirdly, somewhere on the way the standard formatting kicks in, too, as
# the 'Pad me!' string does get padded (which must be some postprocessing,
# as the string is still unpadded when passed into get_field())

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


Re: Need help with custom string formatter

2022-10-21 Thread Robert Latest via Python-list


Hi Stefan, 

I have now implemented a version of this, works nicely. I have a few minor
questions / remarks:

>   result += ' ' *( length - len( result ))

Nice, I didn't know that one could multiply strings by negative numbers without
error.

> def __init__( self ):
> super().__init__()

Isn't this a no-op? Probably a leftover from my stuff.

> def format_field( self, value, format_string ):
> if re.match( r'\d+', format_string )and type( value )== str:

Why do you prefer re.match(r'\d+', x) over x.isdigit()?

> return super().format_field( value, format_string )

Why do you prefer super().format_field() over plain format()? The doc says:
"format_field() simply calls format()." So I figured I might do the same.

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


Re: Need help in blockchain coding.

2022-06-11 Thread Mats Wichmann
On 6/11/22 15:29, dn wrote:
> On 12/06/2022 02.51, Ayesha Tassaduq wrote:
>> I am a beginner in python I want to transfer generated hash to a local 
>> database. I try it with socket programming but I fail. can anyone please 
>> help me ow I can do this?
> 
> Where is the database?
> Where is the socket?
> What are the (full) error messages?

Indeed... what you've posted, with the exception that we don't see what
these two _df values are:

t1 = Time_sensitive_df
...
t3 = normal_df

looks basically workable for what it is.

Guessing at your intent here - presumably you want your chain to be
persistent and not be created from scratch each time you go to access
it. You *could* use a database for this, and there are lots of Python
technologies for talking to databases, but there's none of that in your
code so we can't comment on it.

For early experiments you could just use a text file.  Then you need to
code a way to load the existing chain from the file into your working
copy, if the file exists, rather than instantiating a copy of
Blockchain, which will always start over:

def __init__( self ):
self.chain = [ ]
self.generate_genesis_block()

since the chain itself is a list, perhaps you could dump that list to a
json file, and reload it into self.chain if the json file is found to
exist, instead of doing the initial-setup?

Apologies if I have completely misunderstood what you are seeking...
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Need help in blockchain coding.

2022-06-11 Thread dn
On 12/06/2022 02.51, Ayesha Tassaduq wrote:
> I am a beginner in python I want to transfer generated hash to a local 
> database. I try it with socket programming but I fail. can anyone please help 
> me ow I can do this?

Where is the database?
Where is the socket?
What are the (full) error messages?


> class Block:
> def __init__( self, previous_block_hash, transaction_list ):
> self.previous_block_hash = previous_block_hash
> self.transaction_list = transaction_list
> 
> self.block_data = f"{' - '.join(transaction_list)} - 
> {previous_block_hash}"
> self.block_hash = hashlib.sha256(self.block_data.encode()).hexdigest()
> 
> 
> class Blockchain:
> def __init__( self ):
> self.chain = [ ]
> self.generate_genesis_block()
> 
> def generate_genesis_block( self ):
> self.chain.append(Block("0", [ 'Genesis Block' ]))
> 
> def create_block_from_transaction( self, transaction_list ):
> previous_block_hash = self.last_block.block_hash
> self.chain.append(Block(previous_block_hash, transaction_list))
> 
> def display_chain( self ):
> for i in range(len(self.chain)):
> print(f"Hash {i + 1}: {self.chain [ i ].block_hash}\n")
> 
> @property
> def last_block( self ):
> return self.chain [ -1 ]
> 
> 
> **t1 = Time_sensitive_df
> t2 = "abcdefghijklmnopqrstuvwxyz"
> t3 = normal_df
> myblockchain = Blockchain()
> myblockchain.create_block_from_transaction(t1)
> myblockchain.create_block_from_transaction(t2)
> myblockchain.create_block_from_transaction(t3)
> myblockchain.display_chain()**

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


Need help in blockchain coding.

2022-06-11 Thread Ayesha Tassaduq
I am a beginner in python I want to transfer generated hash to a local 
database. I try it with socket programming but I fail. can anyone please help 
me ow I can do this?

class Block:
def __init__( self, previous_block_hash, transaction_list ):
self.previous_block_hash = previous_block_hash
self.transaction_list = transaction_list

self.block_data = f"{' - '.join(transaction_list)} - 
{previous_block_hash}"
self.block_hash = hashlib.sha256(self.block_data.encode()).hexdigest()


class Blockchain:
def __init__( self ):
self.chain = [ ]
self.generate_genesis_block()

def generate_genesis_block( self ):
self.chain.append(Block("0", [ 'Genesis Block' ]))

def create_block_from_transaction( self, transaction_list ):
previous_block_hash = self.last_block.block_hash
self.chain.append(Block(previous_block_hash, transaction_list))

def display_chain( self ):
for i in range(len(self.chain)):
print(f"Hash {i + 1}: {self.chain [ i ].block_hash}\n")

@property
def last_block( self ):
return self.chain [ -1 ]


**t1 = Time_sensitive_df
t2 = "abcdefghijklmnopqrstuvwxyz"
t3 = normal_df
myblockchain = Blockchain()
myblockchain.create_block_from_transaction(t1)
myblockchain.create_block_from_transaction(t2)
myblockchain.create_block_from_transaction(t3)
myblockchain.display_chain()**
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: need help with a translation issue

2021-04-17 Thread dn via Python-list
Longer response:

NB I've not used the system and only quickly reviewed
https://py-googletrans.readthedocs.io/_/downloads/en/documentation/pdf/

NBB I am treating you (and/or other interested-readers) as something of
a 'beginner'. No insult is intended should I appear to be 'talking down'.



On 18/04/2021 10.56, Quentin Bock wrote:
> I'm trying to take the user input and let them change the target language
> or dest
> code:
> 
> from deep_translator import GoogleTranslator
> import googletrans
> import sys
> 
> language_list = googletrans.LANGUAGES
> print(language_list)


Why print this? Should this output be labelled, or otherwise explained
to the user?

Looking at what is output (yourself), is it a list or a dictionary? When
using it, is the code referring to a list or list of dictionary keys
(country-codes), should it be looking at the country-names, or even both?
(I'm not sure of your intent)


> feedback = input("Would you like to translate a sentence of your own?
> (yes/no)")
> 
> if feedback == 'no':
> sys.exit()

When reviewing code: if the same lines are (basically) repeated, is this
(often) a recommendation to employ a function?

Given that the user has kicked-off the program[me], is it necessary to
ask if (s)he wants to translate some text? Will anyone reply "no" at
this point?

Thus, (instead of asking) could we reasonably set "feedback" to "yes"?

That said, what if the user replies "YES" (or some less logical
combination of the same letters)?


> while feedback == 'yes':

Some might suggest that "feedback" should be a boolean value, thus:

while feedback:


> user_choice = input ("Enter a language (the abbreviation or correctly
> spelled name of the language): ").lower()

So, the acceptable response is either the code or the name of the language?


> user_sentence = input("Enter a sentence you want translated: ")
> 
> user_translation = GoogleTranslator(source='en',
> target=user_choice).translate(user_sentence)

Yet (according to the docs), the "target" value should be a
language-code, eg 'fr' rather than 'french'.
(remember: I've not used the library, so you're the expert...)


> print(user_translation)

Some would suggest that if "user_translation" is defined on one line and
only ever used on the following, the two lines should be conflated.

(some of us don't agree, especially if it makes testing more awkward)


> feedback = input ("Would you like to translate a sentence of your own?
> (yes/no)")
> 
> if feedback == 'no':
> sys.exit()

A UX (User Experience) consideration:
If the user has a series of translations to be made, will (s)he want to
keep repeating the same language/code? Could you code the input
statement to have a default value on the second and ensuing times
through the loop? In this mode, if the user hits Enter without entering
any text-data, the code could 'remember' the language and save
manual-effort.


A thought about design:
This code consists of a loop which has two purposes
1 translate some text
2 continue looping or stop

A useful guide (and testing aid) is "SRP" (the Single Responsibility
Principle) which has a more-technical definition, but let's stick to its
name. Each routine should have only a single task to perform (and should
do it well). Let's consider the first 'purpose':

def translate():
user_choice = input ("Enter...): ").lower()
user_sentence = input("Enter a sentence you want translated: ")
user_translation = GoogleTranslator(source='en',
target=user_choice).translate(user_sentence)

Applying SRP again, we might debate that last line, because it is not
(easily) possible to distinguish between an error at class
instantiation-time (eg "target" is not an acceptable language-code), and
an error at translation-time.

Let's go the next step and separate-out the input functionality. How
about a function like:

def translate( target_language_code, english_text ):
translator = GoogleTranslator( source='en',
   target=target_language_code
 )
return translator.translate( english_text )

Why?

There is virtue in what appears to be extra, even unnecessary, coding
effort!

This is very easily tested - and can be (even more easily) automatically
tested:

def test_translator( ... ):
assert translate( "fr", "hello" ) == "bonjour"
assert translate( "de", "thank you" ) == "danke schön"
... test for error using non-existent language-code
... test for error using non-English text


I'll leave you to work-out how to encapsulate the inputs into a function
- especially if you plan to implement the default-value idea/service to
users. (!)


The second purpose, after extracting the above, leaves us with a
"control loop" (in real-time systems it is termed an "event loop"), and
pretty-much the code as-is (after any amendments per comments-above).

while feedback:
print( translate() )
feedback = input ("Would you like to translate a 

Re: need help with a translation issue

2021-04-17 Thread Chris Angelico
On Sun, Apr 18, 2021 at 9:58 AM dn via Python-list
 wrote:
> Alternately, what's there to stop some nefarious/stupid user (like me!)
> entering "gobbledegook" and complaining that the program fails?

"What is the French for fiddle-de-dee?" -- the Red Queen, to Alice

(Incidentally, Google attempts to translate it as "violon-de-dee", and
declares that the input was indeed in English, disagreeing quite
firmly with Alice on both points.)

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


Re: need help with a translation issue

2021-04-17 Thread MRAB

On 2021-04-17 23:56, Quentin Bock wrote:

I'm trying to take the user input and let them change the target language
or dest
code:

from deep_translator import GoogleTranslator
import googletrans
import sys

language_list = googletrans.LANGUAGES
print(language_list)

feedback = input("Would you like to translate a sentence of your own?
(yes/no)")

if feedback == 'no':
 sys.exit()

while feedback == 'yes':

 user_choice = input ("Enter a language (the abbreviation or correctly
spelled name of the language): ").lower()

 user_sentence = input("Enter a sentence you want translated: ")

 user_translation = GoogleTranslator(source='en',
target=user_choice).translate(user_sentence)

 print(user_translation)

 feedback = input ("Would you like to translate a sentence of your own?
(yes/no)")

 if feedback == 'no':
 sys.exit()
when ran, this will bring an error saying that your inputted language is
not supported
why is this?


All I can say is that it works for me!
--
https://mail.python.org/mailman/listinfo/python-list


Re: need help with a translation issue

2021-04-17 Thread dn via Python-list
On 18/04/2021 10.56, Quentin Bock wrote:
> I'm trying to take the user input and let them change the target language
> or dest
> code:
> 
...

> language_list = googletrans.LANGUAGES
> print(language_list)
...

> user_choice = input ("Enter a language (the abbreviation or correctly
> spelled name of the language): ").lower()
...

> user_translation = GoogleTranslator(source='en',
> target=user_choice).translate(user_sentence)

Where is the "user_choice" related back to "language_list"?

Alternately, what's there to stop some nefarious/stupid user (like me!)
entering "gobbledegook" and complaining that the program fails?
-- 
-- 
Regards,
=dn
-- 
https://mail.python.org/mailman/listinfo/python-list


need help with a translation issue

2021-04-17 Thread Quentin Bock
I'm trying to take the user input and let them change the target language
or dest
code:

from deep_translator import GoogleTranslator
import googletrans
import sys

language_list = googletrans.LANGUAGES
print(language_list)

feedback = input("Would you like to translate a sentence of your own?
(yes/no)")

if feedback == 'no':
sys.exit()

while feedback == 'yes':

user_choice = input ("Enter a language (the abbreviation or correctly
spelled name of the language): ").lower()

user_sentence = input("Enter a sentence you want translated: ")

user_translation = GoogleTranslator(source='en',
target=user_choice).translate(user_sentence)

print(user_translation)

feedback = input ("Would you like to translate a sentence of your own?
(yes/no)")

if feedback == 'no':
sys.exit()
when ran, this will bring an error saying that your inputted language is
not supported
why is this?
-- 
https://mail.python.org/mailman/listinfo/python-list


need help with a ctypes project for PyPI

2021-02-03 Thread Simon Zhang
Hi,

I have created a ctypes project as in the following link's first answer:
https://stackoverflow.com/questions/42585210/extending-setuptools-extension-to-use-cmake-in-setup-py

Since my machine's gcc is too high version or something, I used the docker
image located here:
https://quay.io/repository/pypa/manylinux2014_x86_64
to compile the copied .whl file. I ran auditwheel repair on my whl file
then copied it back to my local machine without complaints.

I'm not sure I understand the subsequent process I need to do with PyPI.

If I copy the manylinux2014 wheel back to my local machine  (into the dist
folder) and run the command:

python3 -m twine upload --repository testpypi dist/*

following the instructions from:
https://packaging.python.org/tutorials/packaging-projects/

when I pip3 install spamplusplus (this is the name I gave my test project)
https://test.pypi.org/project/spamplusplus/

I get that the CMakeLists.txt file is not existent. I used the same
setup.py file given in the link:
https://stackoverflow.com/questions/42585210/extending-setuptools-extension-to-use-cmake-in-setup-py

However I get the error that CMakeLists.txt file is not being uploaded?

 cmake /tmp/pip-build-6ff9ifuu/spamplusplus
-DCMAKE_LIBRARY_OUTPUT_DIRECTORY=/tmp/pip-build-6ff9ifuu/spamplusplus/build/lib.linux-x86_64-3.6/spamplusplus
-DCMAKE_BUILD_TYPE=Release
  CMake Error: The source directory
"/tmp/pip-build-6ff9ifuu/spamplusplus" does not appear to contain
CMakeLists.txt.

I think this is something basic involving paths but could be more involved.

Can anyone help!!

Thanks,

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


Re: Python 2 to Python 3 .so library incompatibility - need help

2020-12-17 Thread Michał Jaworski
I've looked into the details of the deb package that Cameron mentioned. It
may be the one that you Chris uss because it does indeed include a
pyscand.so file. Quick question to you Chris: the utilities
you've mentioned are the code that you've written yourself or utilities
from /usr/libexec/okimfputl that are shipped with the "driver package". In
the deb package I've found following files:
/usr/libexec/okimfputl/imgfilecv.py
/usr/libexec/okimfputl/pushconfig.py
/usr/libexec/okimfputl/pushass.py
/usr/libexec/okimfputl/mfpcfgfile.py
...

If that's the latter, I wouldn't even try to port that to Python 3. First,
it would be clearly against the licence agreement. Second, that would
probably result in total mess and take more time that it takes to earn for
a new printer. If you really want to keep the printer (I wouldn't) I would
do the following: upgrade your system, install Python 2.7 straight from
sources in a separate location (e.g. /opt/oki-python?) and modify all
shebang lines of the OKI python utilities from utilities to use that python
location instead of "/usr/bin/env python" or "/usr/bin/python". That would
make it totally independent of your system installation. The last thing
would be probably installing pygtk in that "isolated" python installation
as OKI utilities clearly rely on this. You could use venv for that or just
simply make sure that gtk for python2 is in that python's library path.
Whatever more convenient: you won't be using that python installation for
anything else than supporting the driver.

To be honest, what I would really do is to buy a new printer from a vendor
that is known to be supporting their hardware for long term on the system
you use. Printer vendors sucks. In the end, they always stop producing
printing supplies you need and render your hardware useless. I have a combo
that I can't refill with toner anymore which has used photoconductor drum
that I can't replace anymore. I keep it around because it has a working
scanner and haven't buyed a new printer because this one "almost works".

Cheers,
Michał

śr., 16 gru 2020 o 23:48 Cameron Simpson  napisał(a):

> On 16Dec2020 21:59, Chris Green  wrote:
> >Cameron Simpson  wrote:
> >> On 16Dec2020 18:51, Chris Green  wrote:
> >> >The specific problem that finally prevented me from managing to get it
> >> >to work was a (Linux) .so file that had been built for Python 2 and,
> >> >as I don't have the source, I can't build for Python 3.
> >>
> >> ChrisA I think suggested keeping a Python 2.7 install around for this.
> >>
> >Not possible really as there are other python conflicts that start
> >appearing if one tries to retain the libraries needed.
>
> Runtime python issues like you missing symbol error, or package conflict
> issues?
>
> i.e. can you keep the OKI stuff sitting around along with Python 2
> install without having trouble with the PPA?
>
> >> >I need to have another go at fixing this as otherwise the code that
> >> >I need to manage my printer will stop working as I update my Ubuntu
> >> >systems.
>
> I'm leaning towards ChrisA's JSON suggestion at this point (absent newer
> driver software). Keep a small Python 2 programme around which uses the
> printer driver in whatever _basic_ ways you need, and _invoke that_ from
> your modern Python 3 code as an external command, passing/receiving the
> necessary information in JSON form as input.output, or on its command
> line if that is more convenient.
>
> >> Have you considered keeping a legacy VM around as well? I have a few VMs
> >> sitting here I use for some legacy software.
> >>
> >That's not a lot of use.  The programs that I want to run (by
> >converting to Python 3) are utility programs for my printer, they
> >install with a handy 'app' in my toolbar.  Having them in a VM
> >wouldn't really do much good! :-)
>
> Fair enough. It seemed cumbersome to me too, but it is a viable way to
> keep something legacy around, particularly if that legacy thing requires
> a legacy OS.
>
> >I still have python 2.  The issue is that the programs need modules
> >which come from a PPA to support Python GTK, these conflict with
> >ongoing updates to Python.  The PPA works OK in Ubuntu 20.04 but
> >prevents some updates in 20.10.  I expect it will get worse as time
> >goes on.
> [...]
> >> Guessing from the library name, have you looked on the OKI.com site
> >> for current software? Maybe here? What's your printer model?
> >>
> https://www.oki.com/au/printing/support/drivers-and-utilities/index.html
> >>
> >>
> >It comes from OKI with the Linux utilities for the printer, it's an
> >MC342N.
>
> From here?
>
>
> https://www.oki.com/uk/printing/support/drivers-and-utilities/colour-multifunction/01331401/?os=ab33=ac2
>
> This driver?
>
>
> https://www.oki.com/uk/printing/support/drivers-and-utilities/?id=46252701FZ01=drivers-and-utilities=colour-multifunction=01331401=ab33=ac2
>
> I've just installed the .deb above on my Ubuntu 20.04.1 LTS system.
> Aside from whinging about systemd it 

Re: Python 2 to Python 3 .so library incompatibility - need help

2020-12-17 Thread Chris Green
Cameron Simpson  wrote:
> >> Guessing from the library name, have you looked on the OKI.com site 
> >> for current software? Maybe here? What's your printer model?
> >> 
> >> https://www.oki.com/au/printing/support/drivers-and-utilities/index.html
> >>
> >>
> >It comes from OKI with the Linux utilities for the printer, it's an
> >MC342N.
> 
> From here?
> 
> https://www.oki.com/uk/printing/support/drivers-and-utilities/colour-multifunction/01331401/?os=ab33=ac2
>  
> 
> 
> This driver?
> 
> https://www.oki.com/uk/printing/support/drivers-and-utilities/?id=46252701FZ01=drivers-and-utilities=colour-multifunction=01331401=ab33=ac2
>  
> 
> 
> I've just installed the .deb above on my Ubuntu 20.04.1 LTS system.  
> Aside from whinging about systemd it installed ok. How do I reproduce 
> your problems? (I've got no printer of course, but...)
> 
Try running scantool.py, that should pop up a little GUI.

It uses GTK which of course in itself makes migration tricky because
one has to move from the native Python 2 code to the 'introspection'
code on Python 3.  However I can do those code changes, the killer is
that several of the scripts import pyscand and that's the Python 2
library.

The issue basically is that you can't run Python 2 GTK in a modern
system that's mostly Python 3 because the GTK libraries conflict. Thus
I need to convert the code to Python 3 but I can't because of the
library.

I've extracted all the calls/uses of pyscand from the Python code:-

pyscand.ADF:
pyscand.BEGIN:
pyscand.EVENT_PUSHSCAN:
pyscand.EVENT_PUSHSCANCCL:
pyscand.E_BUSY
pyscand.E_BUSY:
pyscand.E_CANCELED:
pyscand.E_CONNECTION_REFUSED:
pyscand.E_ERROR
pyscand.E_IOERROR:
pyscand.E_NODATA:
pyscand.E_SUCCESS
pyscand.E_SUCCESS:
pyscand.FINISHED:
pyscand.O_HEIGHT
pyscand.O_PAPER_HEIGHT
pyscand.O_PAPER_WIDTH
pyscand.O_WIDTH
pyscand.PRM_ACTION
pyscand.PRM_DEVICE
pyscand.PRM_DEVICE
pyscand.PRM_PAGE
pyscand.PRM_PATH
pyscand.PRM_PROGRESS
pyscand.PRM_PUSHSCAN_ID
pyscand.PRM_SOURCE
pyscand.PRM_STATUS
pyscand.PROGRESS:
pyscand.TO_APPLICATION:
pyscand.TO_FOLDER:
pyscand.cancel_register_client()
pyscand.cancel_scan(device)
pyscand.exit_client()
pyscand.get_device_list(devicelist)
pyscand.is_registered()
pyscand.recv_client_event()
pyscand.register_client()
pyscand.scan(self._device, self._cfg, outpath, self._scan_callback,
self._pushscanid)
pyscand.strstatus(rc)))
pyscand.strstatus(status)
pyscandsupp.to_device_name_list(devicelist)

As you can see it's mostly constants but there's that pyscand.scan()
at the bottom which I suspect is the fundamental scanning software.

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


Re: Python 2 to Python 3 .so library incompatibility - need help

2020-12-16 Thread Cameron Simpson
On 16Dec2020 21:59, Chris Green  wrote:
>Cameron Simpson  wrote:
>> On 16Dec2020 18:51, Chris Green  wrote:
>> >The specific problem that finally prevented me from managing to get it
>> >to work was a (Linux) .so file that had been built for Python 2 and,
>> >as I don't have the source, I can't build for Python 3.
>>
>> ChrisA I think suggested keeping a Python 2.7 install around for this.
>>
>Not possible really as there are other python conflicts that start
>appearing if one tries to retain the libraries needed.

Runtime python issues like you missing symbol error, or package conflict 
issues?

i.e. can you keep the OKI stuff sitting around along with Python 2 
install without having trouble with the PPA?

>> >I need to have another go at fixing this as otherwise the code that 
>> >I need to manage my printer will stop working as I update my Ubuntu
>> >systems.

I'm leaning towards ChrisA's JSON suggestion at this point (absent newer 
driver software). Keep a small Python 2 programme around which uses the 
printer driver in whatever _basic_ ways you need, and _invoke that_ from 
your modern Python 3 code as an external command, passing/receiving the 
necessary information in JSON form as input.output, or on its command 
line if that is more convenient.

>> Have you considered keeping a legacy VM around as well? I have a few VMs
>> sitting here I use for some legacy software.
>>
>That's not a lot of use.  The programs that I want to run (by
>converting to Python 3) are utility programs for my printer, they
>install with a handy 'app' in my toolbar.  Having them in a VM
>wouldn't really do much good! :-)

Fair enough. It seemed cumbersome to me too, but it is a viable way to 
keep something legacy around, particularly if that legacy thing requires 
a legacy OS.

>I still have python 2.  The issue is that the programs need modules
>which come from a PPA to support Python GTK, these conflict with
>ongoing updates to Python.  The PPA works OK in Ubuntu 20.04 but
>prevents some updates in 20.10.  I expect it will get worse as time
>goes on.
[...]
>> Guessing from the library name, have you looked on the OKI.com site 
>> for current software? Maybe here? What's your printer model?
>> https://www.oki.com/au/printing/support/drivers-and-utilities/index.html
>>
>>
>It comes from OKI with the Linux utilities for the printer, it's an
>MC342N.

>From here?


https://www.oki.com/uk/printing/support/drivers-and-utilities/colour-multifunction/01331401/?os=ab33=ac2

This driver?


https://www.oki.com/uk/printing/support/drivers-and-utilities/?id=46252701FZ01=drivers-and-utilities=colour-multifunction=01331401=ab33=ac2

I've just installed the .deb above on my Ubuntu 20.04.1 LTS system.  
Aside from whinging about systemd it installed ok. How do I reproduce 
your problems? (I've got no printer of course, but...)

>I have tried asking them for a Python 3 version, maybe I should try
>again.

Can't hurt, but may not be necessary if you are prepared to split your 
Python 3 code form the Python 2 stuff that ships with the .deb.

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


Re: Python 2 to Python 3 .so library incompatibility - need help

2020-12-16 Thread Chris Angelico
On Thu, Dec 17, 2020 at 9:06 AM Chris Green  wrote:
> > Also, make note of the specific Python 2 version where your software
> > works - the CPython API does change somewhat sometimes.
> >
> I still have python 2.  The issue is that the programs need modules
> which come from a PPA to support Python GTK, these conflict with
> ongoing updates to Python.  The PPA works OK in Ubuntu 20.04 but
> prevents some updates in 20.10.  I expect it will get worse as time
> goes on.
>

Try getting JUST the printer info in Python 2, and then outputting
that to stdout in JSON format. Then your Python 3 script can run your
Python 2 script, read what it sends on stdout, and do whatever it
needs to.

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


Re: Python 2 to Python 3 .so library incompatibility - need help

2020-12-16 Thread Chris Green
Cameron Simpson  wrote:
> On 16Dec2020 18:51, Chris Green  wrote:
> >The specific problem that finally prevented me from managing to get it
> >to work was a (Linux) .so file that had been built for Python 2 and,
> >as I don't have the source, I can't build for Python 3.
> 
> ChrisA I think suggested keeping a Python 2.7 install around for this.
> 
Not possible really as there are other python conflicts that start
appearing if one tries to retain the libraries needed.


> >I need to have another go at fixing this as otherwise the code that I
> >need to manage my printer will stop working as I update my Ubuntu
> >systems.
> 
> Have you considered keeping a legacy VM around as well? I have a few VMs 
> sitting here I use for some legacy software.
> 
That's not a lot of use.  The programs that I want to run (by
converting to Python 3) are utility programs for my printer, they
install with a handy 'app' in my toolbar.  Having them in a VM
wouldn't really do much good! :-)


> Have you checked an upgraded Ubuntu to failure to run your software 
> using Python 2? Python 2 won't be installed by default, but I'm pretty 
> sure you can add it in. It is just the "system Python" which is moving 
> to Python 3.
> 
> Also, make note of the specific Python 2 version where your software 
> works - the CPython API does change somewhat sometimes.
> 
I still have python 2.  The issue is that the programs need modules
which come from a PPA to support Python GTK, these conflict with
ongoing updates to Python.  The PPA works OK in Ubuntu 20.04 but
prevents some updates in 20.10.  I expect it will get worse as time
goes on.


> >The specific error I'm getting is as follows:-
> >File "/usr/libexec/okimfputl.new/guicom.py", line 66, in  import 
> > pyscand
> >ImportError: /usr/libexec/okimfpdrv/pyscand.so: undefined symbol: 
> > _Py_ZeroStruct
> 
> 
> Guessing from the library name, have you looked on the OKI.com site for 
> current software? Maybe here? What's your printer model?
> 
> https://www.oki.com/au/printing/support/drivers-and-utilities/index.html
> 
> Not that I've found anything helpful...
> 
> What Ubuntu package supplies that .so file?
> 
It comes from OKI with the Linux utilities for the printer, it's an
MC342N.

I have tried asking them for a Python 3 version, maybe I should try
again.

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


Re: Python 2 to Python 3 .so library incompatibility - need help

2020-12-16 Thread Chris Angelico
On Thu, Dec 17, 2020 at 8:26 AM Cameron Simpson  wrote:
>
> On 16Dec2020 18:51, Chris Green  wrote:
> >The specific problem that finally prevented me from managing to get it
> >to work was a (Linux) .so file that had been built for Python 2 and,
> >as I don't have the source, I can't build for Python 3.
>
> ChrisA I think suggested keeping a Python 2.7 install around for this.

(MRAB did, but I agree with it.)

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


Re: Python 2 to Python 3 .so library incompatibility - need help

2020-12-16 Thread Cameron Simpson
On 16Dec2020 18:51, Chris Green  wrote:
>The specific problem that finally prevented me from managing to get it
>to work was a (Linux) .so file that had been built for Python 2 and,
>as I don't have the source, I can't build for Python 3.

ChrisA I think suggested keeping a Python 2.7 install around for this.

>I need to have another go at fixing this as otherwise the code that I
>need to manage my printer will stop working as I update my Ubuntu
>systems.

Have you considered keeping a legacy VM around as well? I have a few VMs 
sitting here I use for some legacy software.

Have you checked an upgraded Ubuntu to failure to run your software 
using Python 2? Python 2 won't be installed by default, but I'm pretty 
sure you can add it in. It is just the "system Python" which is moving 
to Python 3.

Also, make note of the specific Python 2 version where your software 
works - the CPython API does change somewhat sometimes.

>The specific error I'm getting is as follows:-
>File "/usr/libexec/okimfputl.new/guicom.py", line 66, in  import 
> pyscand
>ImportError: /usr/libexec/okimfpdrv/pyscand.so: undefined symbol: 
> _Py_ZeroStruct


Guessing from the library name, have you looked on the OKI.com site for 
current software? Maybe here? What's your printer model?

https://www.oki.com/au/printing/support/drivers-and-utilities/index.html

Not that I've found anything helpful...

What Ubuntu package supplies that .so file?

>Is there *any* other way around this, like a 'compatibility module' to
>use Python 2 .so files in Python 3 or anything like it?  I have all
>the Python code and have (up to hitting this problem) converted it to
>Python 3.

Almost certainly not. I think ChrisA's Python 2 suggestion is the go 
here.

You may need to manually copy the requisite .so files if the package is 
about to vanish.

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


Re: Python 2 to Python 3 .so library incompatibility - need help

2020-12-16 Thread Chris Angelico
On Thu, Dec 17, 2020 at 7:27 AM MRAB  wrote:
>
> On 2020-12-16 19:16, Chris Angelico wrote:
> > On Thu, Dec 17, 2020 at 6:06 AM Chris Green  wrote:
> >>
> >> Some time ago (in July) I asked some questions here
> >> about problems migrating some code from Python 2 to Python 3.
> >>
> >> The specific problem that finally prevented me from managing to get it
> >> to work was a (Linux) .so file that had been built for Python 2 and,
> >> as I don't have the source, I can't build for Python 3.
> >>
> >> I need to have another go at fixing this as otherwise the code that I
> >> need to manage my printer will stop working as I update my Ubuntu
> >> systems.
> >>
> >> The specific error I'm getting is as follows:-
> >>
> >> File "/usr/libexec/okimfputl.new/guicom.py", line 66, in  
> >> import pyscand
> >> ImportError: /usr/libexec/okimfpdrv/pyscand.so: undefined symbol: 
> >> _Py_ZeroStruct
> >>
> >> I know this is because the extension module is compiled for Python 2
> >> and _Py_ZeroStruct is only available in Python 2.  I don't have the C
> >> code for the module.
> >>
> >> Is there *any* other way around this, like a 'compatibility module' to
> >> use Python 2 .so files in Python 3 or anything like it?  I have all
> >> the Python code and have (up to hitting this problem) converted it to
> >> Python 3.
> >>
> >
> > Basically no. The error you're seeing is a nice noisy one, but even if
> > you got past that, there'll be a LOT of incompatibilities.
> > Unfortunately, a quick google search for 'pyscand' showed up
> > places where you've asked this question, suggesting that nobody else
> > uses this library. It looks like you're going to have to take a big
> > step back and figure out what the library is doing for you, and
> > reimplement that somehow. :(
> >
> > Good luck.
> >
> Alternatively, run something in Python 2.7 that can import it and talk
> to the main Python 3 code, at least until you have a long-term solution.

Yes, that's a possibility. A hack, but a definite hack. But this is
one of the places where the universality of stdin/stdout is extremely
handy.

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


Re: Python 2 to Python 3 .so library incompatibility - need help

2020-12-16 Thread MRAB

On 2020-12-16 19:16, Chris Angelico wrote:

On Thu, Dec 17, 2020 at 6:06 AM Chris Green  wrote:


Some time ago (in July) I asked some questions here
about problems migrating some code from Python 2 to Python 3.

The specific problem that finally prevented me from managing to get it
to work was a (Linux) .so file that had been built for Python 2 and,
as I don't have the source, I can't build for Python 3.

I need to have another go at fixing this as otherwise the code that I
need to manage my printer will stop working as I update my Ubuntu
systems.

The specific error I'm getting is as follows:-

File "/usr/libexec/okimfputl.new/guicom.py", line 66, in  import 
pyscand
ImportError: /usr/libexec/okimfpdrv/pyscand.so: undefined symbol: 
_Py_ZeroStruct

I know this is because the extension module is compiled for Python 2
and _Py_ZeroStruct is only available in Python 2.  I don't have the C
code for the module.

Is there *any* other way around this, like a 'compatibility module' to
use Python 2 .so files in Python 3 or anything like it?  I have all
the Python code and have (up to hitting this problem) converted it to
Python 3.



Basically no. The error you're seeing is a nice noisy one, but even if
you got past that, there'll be a LOT of incompatibilities.
Unfortunately, a quick google search for 'pyscand' showed up
places where you've asked this question, suggesting that nobody else
uses this library. It looks like you're going to have to take a big
step back and figure out what the library is doing for you, and
reimplement that somehow. :(

Good luck.

Alternatively, run something in Python 2.7 that can import it and talk 
to the main Python 3 code, at least until you have a long-term solution.

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


Re: Python 2 to Python 3 .so library incompatibility - need help

2020-12-16 Thread Chris Angelico
On Thu, Dec 17, 2020 at 6:06 AM Chris Green  wrote:
>
> Some time ago (in July) I asked some questions here
> about problems migrating some code from Python 2 to Python 3.
>
> The specific problem that finally prevented me from managing to get it
> to work was a (Linux) .so file that had been built for Python 2 and,
> as I don't have the source, I can't build for Python 3.
>
> I need to have another go at fixing this as otherwise the code that I
> need to manage my printer will stop working as I update my Ubuntu
> systems.
>
> The specific error I'm getting is as follows:-
>
> File "/usr/libexec/okimfputl.new/guicom.py", line 66, in  import 
> pyscand
> ImportError: /usr/libexec/okimfpdrv/pyscand.so: undefined symbol: 
> _Py_ZeroStruct
>
> I know this is because the extension module is compiled for Python 2
> and _Py_ZeroStruct is only available in Python 2.  I don't have the C
> code for the module.
>
> Is there *any* other way around this, like a 'compatibility module' to
> use Python 2 .so files in Python 3 or anything like it?  I have all
> the Python code and have (up to hitting this problem) converted it to
> Python 3.
>

Basically no. The error you're seeing is a nice noisy one, but even if
you got past that, there'll be a LOT of incompatibilities.
Unfortunately, a quick google search for 'pyscand' showed up
places where you've asked this question, suggesting that nobody else
uses this library. It looks like you're going to have to take a big
step back and figure out what the library is doing for you, and
reimplement that somehow. :(

Good luck.

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


Python 2 to Python 3 .so library incompatibility - need help

2020-12-16 Thread Chris Green
Some time ago (in July) I asked some questions here
about problems migrating some code from Python 2 to Python 3.  

The specific problem that finally prevented me from managing to get it
to work was a (Linux) .so file that had been built for Python 2 and,
as I don't have the source, I can't build for Python 3.

I need to have another go at fixing this as otherwise the code that I
need to manage my printer will stop working as I update my Ubuntu
systems.

The specific error I'm getting is as follows:-

File "/usr/libexec/okimfputl.new/guicom.py", line 66, in  import 
pyscand
ImportError: /usr/libexec/okimfpdrv/pyscand.so: undefined symbol: 
_Py_ZeroStruct

I know this is because the extension module is compiled for Python 2
and _Py_ZeroStruct is only available in Python 2.  I don't have the C
code for the module. 

Is there *any* other way around this, like a 'compatibility module' to
use Python 2 .so files in Python 3 or anything like it?  I have all
the Python code and have (up to hitting this problem) converted it to
Python 3.


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


Re: Need help in installing numpy

2020-11-11 Thread MRAB

On 2020-11-10 23:32, adelamsaleh--- via Python-list wrote:

Dear Python Community,
I am new to python.  I sucessfully installed python 3.9 from python.org on my 
windows 10 pc.
I checked it by typing 'py' in the windows cmd prompt and the system indeed responds 
with the version number, then the >>> prompt, and I can run simple programs 
without any problem.
BUT, if I go back to the cmd prompt and type 'python --version', I simply get 
the cmd prompt again with no outputs whatsoever.
I want to install the 'numpy' package. But when I type on the cmd prompt 'pip 
install numpy', I get the response:pip : The term 'pip' is not recognized as 
the name of a cmd let ... etc.

I thought that pip is now a part of later versions of python versions 3.x. If 
so, what did I do wrong?

I know this is a very elementary question for this site, but I would appreciate 
any help.


Using the Python launcher:

py --version


and:

py -m pip install numpy
--
https://mail.python.org/mailman/listinfo/python-list


Need help in installing numpy

2020-11-11 Thread adelamsaleh--- via Python-list
Dear Python Community,
I am new to python.  I sucessfully installed python 3.9 from python.org on my 
windows 10 pc.
I checked it by typing 'py' in the windows cmd prompt and the system indeed 
responds with the version number, then the >>> prompt, and I can run simple 
programs without any problem.
BUT, if I go back to the cmd prompt and type 'python --version', I simply get 
the cmd prompt again with no outputs whatsoever.
I want to install the 'numpy' package. But when I type on the cmd prompt 'pip 
install numpy', I get the response:pip : The term 'pip' is not recognized as 
the name of a cmd let ... etc.

I thought that pip is now a part of later versions of python versions 3.x. If 
so, what did I do wrong?

I know this is a very elementary question for this site, but I would appreciate 
any help.

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


Re: Need Help Urgently

2020-02-26 Thread Bob Gailer
On Feb 26, 2020 10:56 AM, "Prakash Samal" 
wrote:
>
> [ABCD client error]: Connection to broker at  126.0.0.1: lost!
> "timestamp":"Wed Feb 19 11:48:41
>
> [XYZ]: Connection to broker at  126.0.0.1: lost!
> "timestamp":"Wed Feb 19 11:48:40
>
> Note: I want to read the error code i.e ABCD Client error from the line
and also wrt timestamp value.

First a couple of pointers to help you get the results you want in future
communications.

Use a meaningful subject rather than help. Why? Because we keep track of a
communication thread by the subject. It also helps us decide whether or not
we can even tackle that particular problem.

Send such requests to tu...@python.org.

Understand that urgency on your part does not translate to urgency on our
part. We are volunteers who donate some of our time to giving help.

You can accomplish your objective by using various string processing
functions or by using regular expressions. I will assume that you want to
extract everything between square brackets as the error and everything
following the 2nd quote as the timestamp. Let's use the string find method.
With that you can get the index of a particular character and use string
slicing with those indexes to get the actual strings. If you have a basic
understanding of python that should be enough to get you started. Otherwise
I suggest you start with a tutorial that will get you those basics.

if you just want someone to write the program for you then one of us will
be glad to act as a paid consultant and do that for you.

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


Need Help Urgently

2020-02-26 Thread Prakash Samal
[ABCD client error]: Connection to broker at  126.0.0.1: lost!
"timestamp":"Wed Feb 19 11:48:41

[XYZ]: Connection to broker at  126.0.0.1: lost!
"timestamp":"Wed Feb 19 11:48:40

Note: I want to read the error code i.e ABCD Client error from the line and 
also wrt timestamp value.
Let me know how to do?

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


Re: I need help for multidimensional loop

2020-01-26 Thread DL Neil via Python-list

On 27/01/20 12:08 PM, pyotr filipivich wrote:

Growth Hacking Formation  on Sun, 26
Jan 2020 12:36:05 -0800 (PST) typed in comp.lang.python  the
following:

Hi guys,

I need your help please to sold a complicate problem.

It is difficult for me to find the solution but in fact, I am sure it is just a 
few lines of code.

The problem is about some kind of multidimensional loop with some test IF.

...


https://docs.google.com/document/d/1UQ1-PdU00kQnJCaLJDYHveWyEXLX_5MTv56fwvECb1w/edit?usp=sharing


I realize that if you could explain it well enough for someone
else to realize what your problem is, you should be able to see the
solution yourself.

It would be better if you could provide a short "elevator itch" on
what you're trying to do.

Cause "multidimensional arrays" can get hairy really fast.  I
mean, try building a sieve of erostothenses using arrays in integers
[0..maxint] in size.


+1

Unfortunately, (given that this is a Python list) I would suggest that 
(full-fat) SQL already offers solutions to such 'relationship issues'. 
(hah!) I'm not sufficiently familiar with SQL-Lite to know if/how well 
it manages multi-table "joins". So, back to Python...


Are you aware that it is possible to have one for-loop inside another? 
("nested")


In this case, use one for-loop to one of the tables, another loop for 
another table...


Start with (almost) empty loops which print only the key or identifier 
of 'that' particular table. You should then be able to assure yourself 
that every single combination of account and phone is covered.


Thereafter, complicate things by adding if-statements which cause 
appropriate action, or "pass"/do nothing.


Let us know how you get on...
--
Regards =dn
--
https://mail.python.org/mailman/listinfo/python-list


Re: I need help for multidimensional loop

2020-01-26 Thread pyotr filipivich
Growth Hacking Formation  on Sun, 26
Jan 2020 12:36:05 -0800 (PST) typed in comp.lang.python  the
following:
>Hi guys,
>
>I need your help please to sold a complicate problem.
>
>It is difficult for me to find the solution but in fact, I am sure it is just 
>a few lines of code.
>
>The problem is about some kind of multidimensional loop with some test IF.
>
>I worked hours on it, but I am a newbie and it is too difficult.
>
>I was wondering if a super expert in python could give me a hand.
>
>In order to give a maximum of info (explanations + code + screenshot), I 
>prepared a google doc for better understanding. Here in a Facebook post would 
>be too hard to read.
>
>https://docs.google.com/document/d/1UQ1-PdU00kQnJCaLJDYHveWyEXLX_5MTv56fwvECb1w/edit?usp=sharing
>
>Thanks for help.
>
>Have a great evening.

I realize that if you could explain it well enough for someone
else to realize what your problem is, you should be able to see the
solution yourself.

It would be better if you could provide a short "elevator itch" on
what you're trying to do.

Cause "multidimensional arrays" can get hairy really fast.  I
mean, try building a sieve of erostothenses using arrays in integers
[0..maxint] in size.

-- 
pyotr filipivich
Next month's Panel: Graft - Boon or blessing?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: I need help for multidimensional loop

2020-01-26 Thread Python

Le 26/01/2020 à 21:36, Growth Hacking Formation a écrit :

Hi guys,

I need your help please to sold a complicate problem.

It is difficult for me to find the solution but in fact, I am sure it is just a 
few lines of code.

The problem is about some kind of multidimensional loop with some test IF.

I worked hours on it, but I am a newbie and it is too difficult.

I was wondering if a super expert in python could give me a hand.

In order to give a maximum of info (explanations + code + screenshot), I 
prepared a google doc for better understanding. Here in a Facebook post would 
be too hard to read.

https://docs.google.com/document/d/1UQ1-PdU00kQnJCaLJDYHveWyEXLX_5MTv56fwvECb1w/edit?usp=sharing

Thanks for help.

Have a great evening.



You are a joke, aren't you?


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


I need help for multidimensional loop

2020-01-26 Thread Growth Hacking Formation
Hi guys,

I need your help please to sold a complicate problem.

It is difficult for me to find the solution but in fact, I am sure it is just a 
few lines of code.

The problem is about some kind of multidimensional loop with some test IF.

I worked hours on it, but I am a newbie and it is too difficult.

I was wondering if a super expert in python could give me a hand.

In order to give a maximum of info (explanations + code + screenshot), I 
prepared a google doc for better understanding. Here in a Facebook post would 
be too hard to read.

https://docs.google.com/document/d/1UQ1-PdU00kQnJCaLJDYHveWyEXLX_5MTv56fwvECb1w/edit?usp=sharing

Thanks for help.

Have a great evening.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Hello, I need help.

2019-10-15 Thread Piet van Oostrum
Damla Pehlivan  writes:

> Dear Python Team,
[...]
>  I am writing this mail quite emotionally. I asked a new "friend" for help,
> but he laughed. He said it was because I am a girl and this is why I could
> not do it. I want to prove to him and the whole world that I can do it. I
> have a lesson next Monday, so could you please help me with my problem?

That is very nasty. Fortunately Python is not gender-sensitive.

What Operating system do you use? I suppose it probably is Windows or Linux.
And did you use the installer from www.python.org?
These have an IDE that is called IDLE. It is simpler than Pycharm, but it can 
do the job. So you can try that. If that also gives an error you could try to 
reinstall Python.

If you are familiar with the command line, then that is also a possibility.
-- 
Piet van Oostrum 
WWW: http://piet.vanoostrum.org/
PGP key: [8DAE142BE17999C4]
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Hello, I need help.

2019-10-15 Thread Peter Pearson
On Tue, 15 Oct 2019 18:57:04 +0300, Damla Pehlivan  wrote:
[snip]

> . . .  I downloaded the python program, and I
> also downloaded Pycharm to use it. To be fair, I do not know what I am
> doing, but I made some progress last night and I was happy about it. Today
> when I came back from university, I realised the program was updated, I
> updated it and now I cannot use it. When I clicked on it, it kept opening
> the modify tab. I did modify it and repaired it. But it kept not opening
> the actual program.

A clearer description of your situation would improve your odds
of getting a useful result.  For starters, what operating system
are you using?  What application presents the "modify tab" that
you mention?  Is this perhaps a problem with your software-installing
process, rather than with Python or with Pycharm?

Have you found a good Python tutorial?

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


Re: Hello, I need help.

2019-10-15 Thread Igor Korot
Hi,
Are you trying to run your program, PyCharm, or the python console?

Thank you.


On Tue, Oct 15, 2019 at 12:01 PM Damla Pehlivan  wrote:
>
> Dear Python Team,
> First, I would like to introduce myself. My name is Damla Pehlivan, and I
> live in Ankara/Turkey. I am a university student at Ankara University. My
> major is Biology; therefore, I want to learn Python to use for Data
> Science. When I researched and asked my professors, they suggested me to
> learn Python.
>  Sadly, I am quite a beginner but I downloaded the python program, and I
> also downloaded Pycharm to use it. To be fair, I do not know what I am
> doing, but I made some progress last night and I was happy about it. Today
> when I came back from university, I realised the program was updated, I
> updated it and now I cannot use it. When I clicked on it, it kept opening
> the modify tab. I did modify it and repaired it. But it kept not opening
> the actual program.
>  I am writing this mail quite emotionally. I asked a new "friend" for help,
> but he laughed. He said it was because I am a girl and this is why I could
> not do it. I want to prove to him and the whole world that I can do it. I
> have a lesson next Monday, so could you please help me with my problem?
>  With
> kindest regards
> --
> https://mail.python.org/mailman/listinfo/python-list
-- 
https://mail.python.org/mailman/listinfo/python-list


Hello, I need help.

2019-10-15 Thread Damla Pehlivan
Dear Python Team,
First, I would like to introduce myself. My name is Damla Pehlivan, and I
live in Ankara/Turkey. I am a university student at Ankara University. My
major is Biology; therefore, I want to learn Python to use for Data
Science. When I researched and asked my professors, they suggested me to
learn Python.
 Sadly, I am quite a beginner but I downloaded the python program, and I
also downloaded Pycharm to use it. To be fair, I do not know what I am
doing, but I made some progress last night and I was happy about it. Today
when I came back from university, I realised the program was updated, I
updated it and now I cannot use it. When I clicked on it, it kept opening
the modify tab. I did modify it and repaired it. But it kept not opening
the actual program.
 I am writing this mail quite emotionally. I asked a new "friend" for help,
but he laughed. He said it was because I am a girl and this is why I could
not do it. I want to prove to him and the whole world that I can do it. I
have a lesson next Monday, so could you please help me with my problem?
 With
kindest regards
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Need help: integrating unittest with setuptools

2019-09-02 Thread YuXuan Dong
No, it doesn't. The stackoverflow question you posted is about the renaming of 
`winreg`.  `_winreg`  is renamed to `winreg`. That's why the poster can't find 
the module.  My program is written for and running on unix-like systems. I 
think `winreg` should not appear here. I have tried running `pip3 install 
winreg` on MacOS and I got: `Could not find a version that satisfies the 
requirement winreg`.

On 2019/9/2, 08:11, "Python-list on behalf of Sayth Renshaw" 
 wrote:

On Monday, 2 September 2019 04:44:29 UTC+10, YuXuan Dong  wrote:
> Hi, everybody:
> 
> I have met a problem while I ran `python setup.py test`:
> 
>   unittest.case.SkipTest: No module named 'winreg'
> 
> I ran the command in MacOS and my project is written for only UNIX-like 
systems. I don't use any Windows-specified API. How dose `winreg` come here?
> 
> In my `setup.py`:
> 
>   test_suite="test"
> 
> In my `test/test.py`:
> 
>   import unittest
> 
>   class TestAll(unittest.TestCase):
>   def testall(self):
>   return None
> 
> It works if I ran `python -m uniittest test.py` alone but raises the 
above exception if I ran `python setup.py test`.
> 
> I'm working on this for the whole day, searching for every keywords I can 
think of with Google but can't find why or how. Could you help me? Thanks.
> 
> --
> YX. D.

Does this help?

https://stackoverflow.com/questions/4320761/importerror-no-module-named-winreg-python3

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


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


Re: Need help: integrating unittest with setuptools

2019-09-01 Thread Sayth Renshaw
On Monday, 2 September 2019 04:44:29 UTC+10, YuXuan Dong  wrote:
> Hi, everybody:
> 
> I have met a problem while I ran `python setup.py test`:
> 
>   unittest.case.SkipTest: No module named 'winreg'
> 
> I ran the command in MacOS and my project is written for only UNIX-like 
> systems. I don't use any Windows-specified API. How dose `winreg` come here?
> 
> In my `setup.py`:
> 
>   test_suite="test"
> 
> In my `test/test.py`:
> 
>   import unittest
> 
>   class TestAll(unittest.TestCase):
>   def testall(self):
>   return None
> 
> It works if I ran `python -m uniittest test.py` alone but raises the above 
> exception if I ran `python setup.py test`.
> 
> I'm working on this for the whole day, searching for every keywords I can 
> think of with Google but can't find why or how. Could you help me? Thanks.
> 
> --
> YX. D.

Does this help?
https://stackoverflow.com/questions/4320761/importerror-no-module-named-winreg-python3

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


Need help: integrating unittest with setuptools

2019-09-01 Thread YuXuan Dong
Hi, everybody:

I have met a problem while I ran `python setup.py test`:

unittest.case.SkipTest: No module named 'winreg'

I ran the command in MacOS and my project is written for only UNIX-like 
systems. I don't use any Windows-specified API. How dose `winreg` come here?

In my `setup.py`:

test_suite="test"

In my `test/test.py`:

import unittest

class TestAll(unittest.TestCase):
def testall(self):
return None

It works if I ran `python -m uniittest test.py` alone but raises the above 
exception if I ran `python setup.py test`.

I'm working on this for the whole day, searching for every keywords I can think 
of with Google but can't find why or how. Could you help me? Thanks.

--
YX. D.

-- 
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: need help understanding: converting text to binary

2019-04-23 Thread Gregory Ewing

Cameron Simpson wrote:
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.


Not necessarily, it could be a superset of ASCII such as latin-1 or
utf-8.

You do need to know that it is such an encoding, however. If the
encoding is completely unknown, you can't make any assumptions.

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


Re: need help understanding: converting text to binary

2019-04-23 Thread Cameron Simpson

On 23Apr2019 20:35, Eli the Bearded <*@eli.users.panix.com> wrote:

In comp.lang.python, Chris Angelico   wrote:
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.

[...]

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.


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.


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.


Cheers,
Cameron Simpson 
--
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, 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-22 Thread MRAB

On 2019-04-23 01:54, Eli the Bearded wrote:

Here's some code I wrote today:


[snip]


# 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'):


There's a bug here:


 return c - ord(b'a') + 10


It should be:

 return c - ord(b'A') + 10


 else:
 return c - ord(b'0')


However, the entire function can be replaced with int(c, 16), anyway. :-)

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


Re: need help understanding: converting text to binary

2019-04-22 Thread Chris Angelico
On Tue, Apr 23, 2019 at 10:58 AM Eli the Bearded <*@eli.users.panix.com> wrote:
>
> 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):

Have you checked to see if Python can already do this? You mention
quopri from the stdlib (that's
https://docs.python.org/3/library/quopri.html for those following
along at home), so I'm curious which ways your code differs from that;
it might be that the easiest way is to use that module, and then add
some extra framing around the outside of it.

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

The bytes constructor will take a sequence of integers and return a
byte string with those values. For instance, bytes([1, 2, 3, 4, 5]) is
the same as bytes(range(1, 6)) and is the same as b"\1\2\3\4\5". In
this case, the iterable is a tuple of one byte value.

> Is there a more python-esque way to convert what should be plain ascii

What does "plain ASCII" actually mean, though?

> 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, but I would strongly recommend just
encoding and decoding regardless. Use text internally and bytes at the
outside.

ChrisA
-- 
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 with Python3.4 and Avro

2019-02-28 Thread Terry Reedy

On 2/28/2019 11:19 AM, Mihir Kothari wrote:


I am not sure if this is the right list, but trying to get help from
experienced python users for my issue.


This is a good place to get a somewhat different set of such people.


I have posted the issue in stackoverflow, but yet to see any response. I am
trying my luck here.

I have my question here: https://stackoverflow.com/q/54833834/3165644


You should edit the title and body of your SO question.

Titles should get the attention of people who might be able to answer, 
and not push them away.  Including '3.4' in the title implies that 
specific practical knowledge of 3.4 is essential.  The fraction of 
'experienced Python users' using 3.4 is around .01  You can mention in 
the body that you are currently using 3.4, but I do not expect that this 
is completely essential to your problem, or an answer.  An answer given 
for 3.7, say, should very likely run on 3.4, or be modifiable to do.


In the title, I would change 'Avro' to the more specific 'Apache Avro'.

Copy and paste the complete traceback in the body.  Format it as code.

> If needed, I can give the details in this email too, please let me know.

I believe most people consider stackoverflow to be a safe link to click 
on.  However, a brief summary would more likely get such a click.


"When trying to convert an Avro schema to JSON, I get
  AvroError(sp?): Tha datum is not the example of schema"
['AvroError is hypothesized since not given.  The spelling error 
indicates that the message was re-typed instead of pasted.]


--
Terry Jan Reedy

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


Need help with Python3.4 and Avro

2019-02-28 Thread Mihir Kothari
Hi,

I am not sure if this is the right list, but trying to get help from
experienced python users for my issue.
I have posted the issue in stackoverflow, but yet to see any response. I am
trying my luck here.

I have my question here: https://stackoverflow.com/q/54833834/3165644

If needed, I can give the details in this email too, please let me know.

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


Re: OT - need help with PHP

2019-02-02 Thread Bob Gailer
Thank you. I will get back to you on that shortly.

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


Re: OT - need help with PHP

2019-02-01 Thread Chris Angelico
On Sat, Feb 2, 2019 at 7:08 AM bob gailer  wrote:
> HOW TO CALL A FUNCTION USING VOIP.MS REST/JSON API
> The following samples show how to get all Servers Information from our
> database and how to select a specific Server for your display purposes.
>
> Please Note:
> - When using our REST/JSON API you need to send the Method to be used
> and the Required Parameters as part of the URL.
> - By default the output Content-Type is "text/html".
> - If you want the output Content-Type to be "application/json", add the
> following to your URL: _type=json

Cool, this is the most important information.

> PHP - Using cURL POST - Sample Code
>
> |$postfields = array( 'api_username'=>'j...@domain.com',
> 'api_password'=>'password', 'method'=>'getServersInfo',
> 'server_pop'=>'1'); $ch = curl_init(); curl_setopt($ch,
> CURLOPT_RETURNTRANSFER, true ); curl_setopt($ch, CURLOPT_POST, true );
> curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields); curl_setopt($ch,
> CURLOPT_URL, "https://voip.ms/api/v1/rest.php;); $result =
> curl_exec($ch); curl_close($ch); $data=json_decode($result,true);
> print_r($data); |

The PHP array can be converted easily into a Python dictionary:

postfields = {
"api_username": "j...@domain.com",
"api_password": "password",
"method": "getServersInfo",
"server_pop": "1",
}

I don't know what the CURLOPT_RETURNTRANSFER option does, so I'm going
to ignore it.

Since there's nothing obvious about the format of POST data, I'm going
to assume that it's meant to be form encoded. Give this a try and see
if it works.

r = requests.post("https://voip.ms/api/v1/rest.php;, data=postfields)

Many APIs use JSON rather than form encoding, in which case you'd say
"json=" instead of "data=", but that seems unlikely in this case.

> Note: I have edited these examples by removing unnecessary stuff, to
> make their size reasonable.

Assuming you haven't omitted anything important, the translation to
requests should be fairly straight-forward.

> One of my needs is to upload a .wav file. The vendor requires the file
> to be encoded into base64  and the result string included in the POST
> data, which can lead to enormously long POST data. I can successfully
> use GET to send very short .wav files, but the url length limit is
> quickly reached for a reasonable length recording. Trying to use the
> POST ability that allows me to specify the file by path fails at the
> vendor side.

http://docs.python-requests.org/en/master/user/quickstart/#post-a-multipart-encoded-file

You'd need to match the PHP examples to the way Requests does file
uploads, but it ought to work.

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


Re: OT - need help with PHP

2019-02-01 Thread bob gailer

Thank you for your various responses.  All helpful and encouraging.

RE mailing list: I followed the instructions at 
http://php.net/manual/en/faq.mailinglist.php.


I have had no response. Shouldn't I get something either welcoming me to 
the list or requesting a confirmation?


Here are the instructions from the api vendor: (somewhat lengthy)

HOW TO CALL A FUNCTION USING VOIP.MS REST/JSON API
The following samples show how to get all Servers Information from our 
database and how to select a specific Server for your display purposes.


Please Note:
- When using our REST/JSON API you need to send the Method to be used 
and the Required Parameters as part of the URL.

- By default the output Content-Type is "text/html".
- If you want the output Content-Type to be "application/json", add the 
following to your URL: _type=json


PHP - Using cURL GET - Sample Code

|$ch = curl_init(); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true ); 
curl_setopt($ch, CURLOPT_URL, 
"https://voip.ms/api/v1/rest.php?api_username=j...@domain.com_password=password=getServersInfo_pop=1;); 
$result1 = curl_exec($ch); curl_close($ch); 
$data1=json_decode($result1,true); print_r($data1);|



PHP - Using cURL POST - Sample Code

|$postfields = array( 'api_username'=>'j...@domain.com', 
'api_password'=>'password', 'method'=>'getServersInfo', 
'server_pop'=>'1'); $ch = curl_init(); curl_setopt($ch, 
CURLOPT_RETURNTRANSFER, true ); curl_setopt($ch, CURLOPT_POST, true ); 
curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields); curl_setopt($ch, 
CURLOPT_URL, "https://voip.ms/api/v1/rest.php;); $result = 
curl_exec($ch); curl_close($ch); $data=json_decode($result,true); 
print_r($data); |


Note: I have edited these examples by removing unnecessary stuff, to 
make their size reasonable.


On the Python side, I can make the GET version work using 
urllib.request. I will try requests soon.


When I try to run the post example using php -r "path-to-php-progran"; 
It just prints the program.


Any attempt at converting that to POST get me a Bad Request response.

One of my needs is to upload a .wav file. The vendor requires the file 
to be encoded into base64  and the result string included in the POST 
data, which can lead to enormously long POST data. I can successfully 
use GET to send very short .wav files, but the url length limit is 
quickly reached for a reasonable length recording. Trying to use the 
POST ability that allows me to specify the file by path fails at the 
vendor side.


Apology for long post, but I don't know what to omit. Again any help is 
welcome.


--
Bob Gailer


---
This email has been checked for viruses by Avast antivirus software.
https://www.avast.com/antivirus

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


Re: OT - need help with PHP

2019-02-01 Thread mm0fmf

On 01/02/2019 15:36, Chris Angelico wrote:

On Sat, Feb 2, 2019 at 2:31 AM Bob Gailer  wrote:


Trying to setup PHP on Windows 10  using the curl extension to run
standalone. Why? I am trying to use an API where the only coding examples
are written in PHP. My goal is to use python, and the place where I'm stuck
is: the examples use Curl to post requests; my attempts to translate this
to urllib. request have failed.



If it's an HTTP-based API, it's probably easier to translate the
examples to use the 'requests' library than to first set up PHP and
then translate everything to urllib after that.

http://docs.python-requests.org/en/master/

Feel free to post questions here of the form "here's an example of
doing something in PHP - how can I do that in Python", as that would
be 100% on topic.

ChrisA


+1 for using requests.
--
https://mail.python.org/mailman/listinfo/python-list


Re: OT - need help with PHP

2019-02-01 Thread Larry Martell
On Fri, Feb 1, 2019 at 10:30 AM Bob Gailer  wrote:
> I can't even figure out how to sign up for a PHP email list.

http://php.net/manual/en/faq.mailinglist.php
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: OT - need help with PHP

2019-02-01 Thread Chris Angelico
On Sat, Feb 2, 2019 at 2:31 AM Bob Gailer  wrote:
>
> Trying to setup PHP on Windows 10  using the curl extension to run
> standalone. Why? I am trying to use an API where the only coding examples
> are written in PHP. My goal is to use python, and the place where I'm stuck
> is: the examples use Curl to post requests; my attempts to translate this
> to urllib. request have failed.
>

If it's an HTTP-based API, it's probably easier to translate the
examples to use the 'requests' library than to first set up PHP and
then translate everything to urllib after that.

http://docs.python-requests.org/en/master/

Feel free to post questions here of the form "here's an example of
doing something in PHP - how can I do that in Python", as that would
be 100% on topic.

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


OT - need help with PHP

2019-02-01 Thread Bob Gailer
Trying to setup PHP on Windows 10  using the curl extension to run
standalone. Why? I am trying to use an API where the only coding examples
are written in PHP. My goal is to use python, and the place where I'm stuck
is: the examples use Curl to post requests; my attempts to translate this
to urllib. request have failed.

I can't even figure out how to sign up for a PHP email list.

Help with either of the above would be welcome.

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


Need help with a message embedded in an image

2018-12-22 Thread rootsfinder
I am doing a series of puzzles.
One of the puzzles has to do with a message embedded in an image.

I am not familiar with python can someone please help me.

Here is a link to the images and the code.

https://drive.google.com/open?id=1dg5jMFtkUvKzhxv_Fqe7QMI_5x-p_CIr

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


Need help for python on my pc.

2018-11-22 Thread Sourav Banik
Hello Python team,
I'm using python 3.7(32 bit) for several months on my same laptop (x64
processor). I worked on some django project very swiftly without any
problem. But for a few days I am facing a serious problem. My python files
are not showing properly by the file manager. It is just showing 'python
source file' without any logo. When I open my cmd to work on django, it is
not also working though virtualenv is working properly I think. I'm sending
some screenshots of cmd and files for your reference.
I've tried reinstalling (64 bit) and repairing of python but nothing is
working. I want your help to sort out this issue.
From
Sourav Banik,
Dhaka,Bangladesh.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Need help for python on my pc.

2018-11-21 Thread boB Stepp
On Wed, Nov 21, 2018 at 12:19 PM Sourav Banik  wrote:
>
> Hello Python team,
> I'm using python 3.7(32 bit) for several months on my same laptop (x64
> processor). I worked on some django project very swiftly without any
> problem. But for a few days I am facing a serious problem. My python files
> are not showing properly by the file manager. It is just showing 'python
> source file' without any logo. When I open my cmd to work on django, it is
> not also working though virtualenv is working properly I think.

Are you on Windows 10?  There have been reports of a recent update
breaking Windows 10 file associations.  One such article reporting
this behavior:

https://www.howtogeek.com/fyi/microsoft-broke-windows-10s-file-associations-with-a-botched-update/

which refers to this Microsoft update:

https://support.microsoft.com/en-us/help/4462919/windows-10-update-kb4462919

In this, it says:


After installing this update, some users cannot set Win32 program
defaults for certain app and file type combinations using the Open
with… command or Settings > Apps > Default apps.

In some cases, Microsoft Notepad or other Win32 programs cannot be set
as the default.

In some cases, attempting to set application defaults again will succeed.

Microsoft is working on a resolution and estimates a solution will be
available in late November 2018.


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


Re: Need help for python on my pc.

2018-11-21 Thread Calvin Spealman
Hi, I'm afraid attachments are stripped out of e-mails sent to this list.
Anything you sent was not included, so you'll need to share them in some
other way if you'd like to ask for help.

On Wed, Nov 21, 2018 at 1:18 PM Sourav Banik  wrote:

> Hello Python team,
> I'm using python 3.7(32 bit) for several months on my same laptop (x64
> processor). I worked on some django project very swiftly without any
> problem. But for a few days I am facing a serious problem. My python files
> are not showing properly by the file manager. It is just showing 'python
> source file' without any logo. When I open my cmd to work on django, it is
> not also working though virtualenv is working properly I think. I'm sending
> some screenshots of cmd and files for your reference.
> I've tried reinstalling (64 bit) and repairing of python but nothing is
> working. I want your help to sort out this issue.
> From
> Sourav Banik,
> Dhaka,Bangladesh.
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Need help for python on my pc.

2018-11-21 Thread Sourav Banik
Hello Python team,
I'm using python 3.7(32 bit) for several months on my same laptop (x64
processor). I worked on some django project very swiftly without any
problem. But for a few days I am facing a serious problem. My python files
are not showing properly by the file manager. It is just showing 'python
source file' without any logo. When I open my cmd to work on django, it is
not also working though virtualenv is working properly I think. I'm sending
some screenshots of cmd and files for your reference.
I've tried reinstalling (64 bit) and repairing of python but nothing is
working. I want your help to sort out this issue.
From
Sourav Banik,
Dhaka,Bangladesh.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Creating dice game : NEED HELP ON CHECKING ELEMENTS IN A LIST

2018-10-10 Thread Abdur-Rahmaan Janhangeer
*if any(roll != 1 and roll != 5 for roll in result):*

another extract of py's beauty!

Abdur-Rahmaan Janhangeer
https://github.com/Abdur-rahmaanJ
Mauritius
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Creating dice game : NEED HELP ON CHECKING ELEMENTS IN A LIST

2018-10-10 Thread Neil Cerutti
On 2018-10-06, eliteanarchyra...@gmail.com
 wrote:
> Hi, I am new to python and would like someones help on the
> following:
>
> After rolling 5 dice and putting the results into a list, I
> need to check if any dice is not a 1 or 5.

if any(roll != 1 and roll != 5 for roll in result):

> # - THIS LINE IS WHERE I NEED HELP  # ( if 2, 3, 4, 6 in list: )
> print("you can roll again")
> else:
> print("you have all 1's and 5's in your result")

Ha! Didn't think I'd get to apply DeMorgan's Law so soon.

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


Re: Creating dice game : NEED HELP ON CHECKING ELEMENTS IN A LIST

2018-10-06 Thread bob gailer
# your program is quite complicated. classes are overkill. A simpler 
solution is:

import random
for i in range(5):
    roll = random.randint(1,6)
    if roll not in (1,5):
    print('you can roll again')
    break
else:
    print("you have all 1's and 5's in your result'")

# comments on  using classes:
class Dice:
    ...
# no need for die1...die5 - use list comprehension:
alldice = [Dice(6) for i in range(5)]

# object is a bult-in type. it is inadvisable to assign to names of 
built-ins
# as this makes the built-in unavailable. Look up builtins (module) in 
help for

# a complete list.

# use list comprehension roll and report:
print([d.roll_dice() for d in alldice])

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


Re: Creating dice game : NEED HELP ON CHECKING ELEMENTS IN A LIST

2018-10-06 Thread eliteanarchyracer
Well these worked like a charm. Cant say I understand some of them and will 
have to look into utilizing them in the future, but I appreciate everyones 
responses and thank you all. Never needed to check for multiple instances in a 
list before.

Nice to have help!
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Creating dice game : NEED HELP ON CHECKING ELEMENTS IN A LIST

2018-10-06 Thread Alister via Python-list
On Sat, 06 Oct 2018 21:56:09 +0200, Thomas Jollans wrote:

> On 06/10/2018 20:10, eliteanarchyra...@gmail.com wrote:
>> # - THIS LINE IS WHERE I NEED HELP  # ( if 2, 3, 4, 6 in list:
>> )
>>  print("you can roll again")
>> else:
>>  print("you have all 1's and 5's in your result")
>> 
>> 
> You can use a loop:
> 
> for good_number in [2,3,4,6]:
>  if good_number in result:
>  print("you can roll again")
>  break
> else:
>  print("you have all 1's and 5's in your result")

or simply check for 1 & 5 to exit otherwise continue



-- 
Someone hooked the twisted pair wires into the answering machine.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re : Creating dice game : NEED HELP ON CHECKING ELEMENTS IN A LIST

2018-10-06 Thread armand.fouca...@telecom-bretagne.eu
   You could use any and a generator expression.
   It sounds pretty hard, but it's actually easily expressed, and pretty
   intelligible.
   Here you go:

   if any(n in result for n in [2, 3, 4, 6]):
   # reroll
   else:
   # do your thing

   -
   Armand FOUCAULT
   armand.fouca...@telecom-bretagne.eu

    Message original 
   Objet**: Creating dice game : NEED HELP ON CHECKING ELEMENTS IN A LIST
   De**: eliteanarchyra...@gmail.com
   : python-list@python.org
   Cc**:

 Hi, I am new to python and would like someones help on the following:

 After rolling 5 dice and putting the results into a list, I need to
 check if any dice is not a 1 or 5.

 if all dice in the list are either a 1 or 5 , I want to calculate a
 result.
 if there is a 2,3,4 or 6 in the list i want to let the user roll again
 FOR EXACT LINE: PLEASE CHECK CODE

 CODE:

 from random import *

 class Dice:

 def __init__(self, sides, color="white"):
 self.sides = sides
 self.color = color

 def roll_dice(self):
 result = randint(1, self.sides)
 return result

 die1 = Dice(6)
 die2 = Dice(6)
 die3 = Dice(6)
 die4 = Dice(6)
 die5 = Dice(6)

 alldice = [die1, die2, die3, die4, die5]

 result = []

 start = input("Press enter to roll your dice:")

 for object in alldice:
 temp = object.roll_dice()
 result.append(temp)
 print(result)

 # - THIS LINE IS WHERE I NEED HELP  # ( if 2, 3, 4, 6 in list: )
 print("you can roll again")
 else:
 print("you have all 1's and 5's in your result")
 --
 https://mail.python.org/mailman/listinfo/python-list
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Creating dice game : NEED HELP ON CHECKING ELEMENTS IN A LIST

2018-10-06 Thread Thomas Jollans

On 06/10/2018 20:10, eliteanarchyra...@gmail.com wrote:

# - THIS LINE IS WHERE I NEED HELP  # ( if 2, 3, 4, 6 in list: )
 print("you can roll again")
else:
 print("you have all 1's and 5's in your result")



You can use a loop:

for good_number in [2,3,4,6]:
if good_number in result:
print("you can roll again")
break
else:
print("you have all 1's and 5's in your result")
--
https://mail.python.org/mailman/listinfo/python-list


Re: Creating dice game : NEED HELP ON CHECKING ELEMENTS IN A LIST

2018-10-06 Thread MRAB

On 2018-10-06 19:10, eliteanarchyra...@gmail.com wrote:

Hi, I am new to python and would like someones help on the following:

After rolling 5 dice and putting the results into a list, I need to check if 
any dice is not a 1 or 5.

if all dice in the list are either a 1 or 5 , I want to calculate a result.
if there is a 2,3,4 or 6 in the list i want to let the user roll again
FOR EXACT LINE: PLEASE CHECK CODE


CODE:


from random import *

class Dice:

 def __init__(self, sides, color="white"):
 self.sides = sides
 self.color = color

 def roll_dice(self):
 result = randint(1, self.sides)
 return result


die1 = Dice(6)
die2 = Dice(6)
die3 = Dice(6)
die4 = Dice(6)
die5 = Dice(6)

alldice = [die1, die2, die3, die4, die5]

result = []

start = input("Press enter to roll your dice:")

for object in alldice:
 temp = object.roll_dice()
 result.append(temp)
print(result)

# - THIS LINE IS WHERE I NEED HELP  # ( if 2, 3, 4, 6 in list: )
 print("you can roll again")
else:
 print("you have all 1's and 5's in your result")


The simplest (and longest) way is:

if 2 in result or 3 in result or 4 in result or 6 in result:

A cleverer way is to use sets:

if set(result) & {2, 3, 4, 6}:
--
https://mail.python.org/mailman/listinfo/python-list


Creating dice game : NEED HELP ON CHECKING ELEMENTS IN A LIST

2018-10-06 Thread eliteanarchyracer
Hi, I am new to python and would like someones help on the following:

After rolling 5 dice and putting the results into a list, I need to check if 
any dice is not a 1 or 5.

if all dice in the list are either a 1 or 5 , I want to calculate a result.
if there is a 2,3,4 or 6 in the list i want to let the user roll again
FOR EXACT LINE: PLEASE CHECK CODE


CODE: 


from random import *

class Dice:

def __init__(self, sides, color="white"):
self.sides = sides
self.color = color

def roll_dice(self):
result = randint(1, self.sides)
return result


die1 = Dice(6)
die2 = Dice(6)
die3 = Dice(6)
die4 = Dice(6)
die5 = Dice(6)

alldice = [die1, die2, die3, die4, die5]

result = []

start = input("Press enter to roll your dice:")

for object in alldice:
temp = object.roll_dice()
result.append(temp)
print(result)

# - THIS LINE IS WHERE I NEED HELP  # ( if 2, 3, 4, 6 in list: )
print("you can roll again")
else:
print("you have all 1's and 5's in your result")
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: I need help to put the output from terminal in a csv file

2018-09-07 Thread catanaangelo
Thanks a lot, I've managed to make it work they way I wanted
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: I need help to put the output from terminal in a csv file

2018-09-07 Thread Rhodri James

On 07/09/18 13:55, catanaang...@gmail.com wrote:

HI! I need help putting the output from terminal in a csv file. I work on linux 
and I have python 2.7.15. I am running a python program which also runs some 
shell scripts.

I need to capture the output from the .sh scripts and put it nicely in a csv table. I am 
using "commands.getoutput('bash example.sh')" to capture the output of the 
scripts (I can use subprocess too if needed).

The outputs looks something like this:
In case of an error
{
"error" : {
   "body" : "The requested device is currently not online.
   "detail" : "Make sure to connect the device",
   "event" : 123456,
   "header" : "Device Unavailable (123456)"
}
}
And in case of a good output it look similar but has "status :0" instead of 
event and ofc it does say that it passed the test.

I need to export the results of the .sh tests in a csv file with my .py program.
The boss expects a table with 3 columns. The first one with The title TEST which has the 
name of the tests (.sh scripts). The 2nd with PASS/FAIL (this is determined by the 
"status" : 0 output for some tests and with a number between 1 and 4000 for 
others (i used regex for this, but I struggle a bit here too) and the 3rd one which 
returns the Value ( 0 in case status is 0 or the number between 1 and 4000 for the other 
tests).

I really need some ideas, I struggle for 3 days already using regex, commands, 
subprocess and watching tutorials.

I just can't solve this yet, I really need some ideas.


From what you've said above, your basic problem is that you need to 
parse the output looking for lines containing '"status": ' where  
is some number.


Let's assume that you have run one of the shell scripts and captured its 
output into a string.  The first thing to do is to split the output into 
lines, which you can do with the "split()" string method.  Then check 
each line in turn.  If it contains a colon it may be what you want. 
"split()" the line at the colon and look at the first half.  Once you 
have "strip()"ed off the spaces at the beginning and the end, is it 
"status"?  If so, you've got your pass and the VALUE you want is in the 
second half.


I hope that helps.

--
Rhodri James *-* Kynesim Ltd
--
https://mail.python.org/mailman/listinfo/python-list


Re: I need help to put the output from terminal in a csv file

2018-09-07 Thread Brian Oney via Python-list
Please study the following to get you started. It looks like JSON output that 
you are dealing,
which is good. I added a ", to the "body"-line, because I assume that you 
botched that when giving
an example.

```python
#!/usr/bin/env python


import json


output = '''
{
   "error" : {
  "body" : "The requested device is currently not online.",
  "detail" : "Make sure to connect the device",
  "event" : 123456,
  "header" : "Device Unavailable (123456)"
   }
}
'''


# help(json.loads)
parsed = json.loads(output)

if type(parsed) == dict:
if type(parsed['error']) == dict:
print("yay!")
```

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


I need help to put the output from terminal in a csv file

2018-09-07 Thread catanaangelo
HI! I need help putting the output from terminal in a csv file. I work on linux 
and I have python 2.7.15. I am running a python program which also runs some 
shell scripts.

I need to capture the output from the .sh scripts and put it nicely in a csv 
table. I am using "commands.getoutput('bash example.sh')" to capture the output 
of the scripts (I can use subprocess too if needed).

The outputs looks something like this:
In case of an error
{
   "error" : {
  "body" : "The requested device is currently not online.
  "detail" : "Make sure to connect the device",
  "event" : 123456,
  "header" : "Device Unavailable (123456)"
   }
}
And in case of a good output it look similar but has "status :0" instead of 
event and ofc it does say that it passed the test.

I need to export the results of the .sh tests in a csv file with my .py program.
The boss expects a table with 3 columns. The first one with The title TEST 
which has the name of the tests (.sh scripts). The 2nd with PASS/FAIL (this is 
determined by the "status" : 0 output for some tests and with a number between 
1 and 4000 for others (i used regex for this, but I struggle a bit here too) 
and the 3rd one which returns the Value ( 0 in case status is 0 or the number 
between 1 and 4000 for the other tests).

I really need some ideas, I struggle for 3 days already using regex, commands, 
subprocess and watching tutorials.

I just can't solve this yet, I really need some ideas.

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


Re: I need help with this python regex

2018-04-28 Thread Peter J. Holzer
On 2018-04-27 21:04:49 -0700, Ed Manning wrote:
> Here is the source code.
> 
> 
> import re
> 
> 
> log = open("csg.txt", "r") # Opens a file call session.txt
> regex = re.compile(r'policy id \d+') # search for the policy ID
> regex1 = re.compile(r'log count \d+') # search for the policy ID
> 
> for match in log:
> x = regex.findall(match)
> y = regex1.findall(match)
> 
> q = x + y
> print(q)
>  
> 
> The problem I am having i when it print out ti looks like this
> 
> 
> L'Policy ID 243"|
> []
> []
> []
> []
> []
> []
> []
> []
> {'log count 777,"]
> 
> 
> 
> How so I fix the code sone that it does not print empty []

Print the result only if findall actually found something.

hp

-- 
   _  | Peter J. Holzer| we build much bigger, better disasters now
|_|_) || because we have much more sophisticated
| |   | h...@hjp.at | management tools.
__/   | http://www.hjp.at/ | -- Ross Anderson 


signature.asc
Description: PGP signature
-- 
https://mail.python.org/mailman/listinfo/python-list


I need help with this python regex

2018-04-27 Thread Ed Manning
Here is the source code.


import re


log = open("csg.txt", "r") # Opens a file call session.txt
regex = re.compile(r'policy id \d+') # search for the policy ID
regex1 = re.compile(r'log count \d+') # search for the policy ID

for match in log:
x = regex.findall(match)
y = regex1.findall(match)

q = x + y
print(q)
 

The problem I am having i when it print out ti looks like this


L'Policy ID 243"|
[]
[]
[]
[]
[]
[]
[]
[]
{'log count 777,"]



How so I fix the code sone that it does not print empty []






Here so to the test file 


 get policy id 243
name:"csg to wes" (id 243), zone csg -> fwc,action Permit, status "enabled"
10 sources: "206.221.59.229", "206.221.59.246/32", "csg_205.144.151.107/32", 
"csg_205.144.151.177/32", "csg_205.144.151.24/32", "csg_205.144.152.50/32", 
"csg_205.144.153.55/32", "csg_206.221.59.244/32", "csg_206.221.59.250/32", 
"csg_206.221.61.29/32"
19 destinations: "MIP(204.235.119.135)", "MIP(204.235.119.136)", 
"MIP(204.235.119.243)", "MIP(204.235.119.34)", "MIP(204.235.119.39)", 
"MIP(204.235.119.40)", "MIP(204.235.119.41)", "MIP(204.235.119.42)", 
"MIP(204.235.119.43)", "MIP(204.235.119.44)", "MIP(204.235.119.45)", 
"MIP(204.235.119.46)", "MIP(204.235.119.47)", "MIP(204.235.119.50)", 
"MIP(204.235.119.51)", "MIP(204.235.119.52)", "MIP(204.235.119.79)", 
"MIP(204.235.119.82)", "MIP(204.235.119.83)"
1 service: "ANY"
Rules on this VPN policy: 0
nat off, Web filtering : disabled
vpn unknown vpn, policy flag 0001, session backup: on
traffic shaping off, scheduler n/a, serv flag 00
log close, log count 777, alert no, counter yes(79) byte rate(sec/min) 0/0
total octets 0, counter(session/packet/octet) 0/0/79
priority 7, diffserv marking Off
tadapter: state off, gbw/mbw 0/0 policing (no)
No Authentication
No User, User Group or Group expression se
 get policy id 602
name:"ID 36129" (id 602), zone csg -> fwc,action Permit, status "enabled"
src "csg_205.144.151.107/32", dst "MIP(204.235.119.191)", serv "ANY"
Rules on this VPN policy: 0
nat off, Web filtering : disabled
vpn unknown vpn, policy flag 0001, session backup: on
traffic shaping off, scheduler n/a, serv flag 00
log close, log count 0, alert no, counter yes(80) byte rate(sec/min) 0/0
total octets 0, counter(session/packet/octet) 0/0/80
priority 7, diffserv marking Off
tadapter: state off, gbw/mbw 0/0 policing (no)
No Authentication
No User, User Group or Group expression set
csg-vx-fw-n-12:csg-vx-fw-n-01(M)-> get policy id 420
name:"ID 12637" (id 420), zone csg -> fwc,action Permit, status "enabled"
1 source: "csg_204.235.119.78/32"
1 destination: "eg_csg"
6 services: "PING", "tcp_30001-30100", "tcp_6051-6055", "tcp_7041-7091", 
"TELNET", "TRACEROUTE"
Rules on this VPN policy: 0
nat off, Web filtering : disabled
vpn unknown vpn, policy flag 0001, session backup: on
traffic shaping off, scheduler n/a, serv flag 00
log close, log count 0, alert no, counter yes(81) byte rate(sec/min) 0/0
total octets 0, counter(session/packet/octet) 0/0/81
priority 7, diffserv marking Off
tadapter: state off, gbw/mbw 0/0 policing (no)
No Authentication
No User, User Group or Group expression set
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Need help to understand not the answer

2017-07-30 Thread Rick Johnson
On Saturday, July 29, 2017 at 2:16:36 PM UTC-5, new_to_c0ding wrote:
> Hello all, I have been scratching my head since morning but
> could not understand this quiz question. I would appreciate
> if someone could help me understand what is it asking me to
> do. I dont need the answer but just the right direction to
> look at.

Hello.

First of all, as i look over this "script template" that
your instructor has supposedly provided, i am disgusted by
the abysmal formatting. I'm not sure if what you provided
here is an exact replica, or something that you have
modified, but in either case, a little bit of proper
formatting can go a loong way towards readability.

For instance,

When writing in natural languages (such as English), we
utilize common structural elements and rules so that our
text will be presented in manner that is recognizable to
most readers. A few of these "high level structural
components" include _spaces_, _sentences_ and _paragraphs_.
And when writing code, we also utilize a "common structure".
And one of the most important components of this "common
structure" is the use of vertical whitespace. By properly
utilizing vertical whitespace, we can separate the
"paragraphs" of our code (aka: classes and functions) so
that reading the code will be more intuitive. 

Of course, 

Structuring code is far more complicated than simply
creating "visual buffers zones" around classes and
functions, and many hours have been spent debating what is
proper, and what is not. But being that in the "realms of
the OOP paradigm" classes and methods are the most
fundamental elements, it should come as no surprise that
mastering the formatting of these elements is a vital first
lesson.

Now,

Even though there is something of an "ideological war"
raging as to exactly how much vertical whitespace should be
used, and _where_ it should be used, most programmers will
agree that the following example is acceptable. A common
style is to place *ONE* vertical whitespace between each
method in a class,and two vertical whitespaces between the
classes themselves. Observe the following...

## BEGIN: READABLE CODE EXAMPLE ##

 class Location(object):
 """DOCSTRING MISSING!!!"""

 def __init__(self, x, y):
 self.x = x
 self.y = y

 def move(self, deltaX, deltaY):
 return Location(self.x + deltaX, self.y + deltaY)

 def getX(self):
 return self.x

 def getY(self):
 return self.y

 def dist_from(self, other):
 xDist = self.x - other.x
 yDist = self.y - other.y
 return (xDist**2 + yDist**2)**0.5

 def __eq__(self, other):
 return (self.x == other.x and self.y == other.y)

 def __str__(self):
 return '<' + str(self.x) + ',' + str(self.y) + '>'


 class Campus(object):
 """DOCSTRING MISSING!!!"""

 def __init__(self, center_loc):
 self.center_loc = center_loc

 def __str__(self):
 return str(self.center_loc)


 class MITCampus(Campus):
 """ A MITCampus is a Campus that contains tents """

 def __init__(self, center_loc, tent_loc=Location(0,0)):
 """ Assumes center_loc and tent_loc are Location objects
 Initializes a new Campus centered at location center_loc
 with a tent at location tent_loc """
 # Your code here

 def add_tent(self, new_tent_loc):
 """ Assumes new_tent_loc is a[n *INSTANCE* of] Location
 Adds new_tent_loc to the campus only if the tent is at least 0.5 
distance
 away from all other tents already there. Campus is unchanged otherwise.
 Returns True if it could add the tent, False otherwise. """
 # Your code here

 def remove_tent(self, tent_loc):
 """ Assumes tent_loc is a[n *INSTANCE* of] Location
 Removes tent_loc from the campus.
 Raises a ValueError if there is not a tent at tent_loc.
 Does not return anything """
 # Your code here

 def get_tents(self):
 """ Returns a list of all tents on the campus. The list should contain
 the string representation of the Location of a tent. The list should
 be sorted by the x coordinate of the location. """
 # Your code here

## END: READABLE CODE EXAMPLE ##

But what is most important to remember here is _not_ so much
the _number_ of spaces used, but that the number is greater
than _zero_, and that the spacing is _consistent_. For
instance: if one feels that two spaces between methods is
more desirable then that is okay, but, one should maintain
the two space buffer between *ALL* methods in the script
*AND* furthermore, expand the buffer between classes to four
spaces -- because consistency is the key!

But this code is not only lacking an intuitive format, it is
also lacking an intelligent design. For instance: this
object model is just begging for a "Tent object" with the
Location being an attribute of each individual "Tent".
Because it makes absolutely no sense for the 

Re: Need help to understand not the answer

2017-07-29 Thread devinderaujla
On Saturday, July 29, 2017 at 3:49:55 PM UTC-4, MRAB wrote:
> On 2017-07-29 20:16, new_to_c0ding wrote:
> > Hello all,
> > I have been scratching my head since morning but could not understand this 
> > quiz question. I would appreciate if someone could help me understand what 
> > is it asking me to do. I dont need the answer but just the right direction 
> > to look at.
> > 
> > ### Do not change the Location or Campus classes. ###
> > ### Location class is the same as in lecture. ###
> > class Location(object):
> >  def __init__(self, x, y):
> >  self.x = x
> >  self.y = y
> >  def move(self, deltaX, deltaY):
> >  return Location(self.x + deltaX, self.y + deltaY)
> >  def getX(self):
> >  return self.x
> >  def getY(self):
> >  return self.y
> >  def dist_from(self, other):
> >  xDist = self.x - other.x
> >  yDist = self.y - other.y
> >  return (xDist**2 + yDist**2)**0.5
> >  def __eq__(self, other):
> >  return (self.x == other.x and self.y == other.y)
> >  def __str__(self):
> >  return '<' + str(self.x) + ',' + str(self.y) + '>'
> >  
> > class Campus(object):
> >  def __init__(self, center_loc):
> >  self.center_loc = center_loc
> >  def __str__(self):
> >  return str(self.center_loc)
> > class MITCampus(Campus):
> >  """ A MITCampus is a Campus that contains tents """
> >  def __init__(self, center_loc, tent_loc = Location(0,0)):
> >  """ Assumes center_loc and tent_loc are Location objects
> >  Initializes a new Campus centered at location center_loc
> >  with a tent at location tent_loc """
> >  # Your code here
> >
> >  def add_tent(self, new_tent_loc):
> >  """ Assumes new_tent_loc is a Location
> >  Adds new_tent_loc to the campus only if the tent is at least 0.5 
> > distance
> >  away from all other tents already there. Campus is unchanged 
> > otherwise.
> >  Returns True if it could add the tent, False otherwise. """
> >  # Your code here
> >
> >  def remove_tent(self, tent_loc):
> >  """ Assumes tent_loc is a Location
> >  Removes tent_loc from the campus.
> >  Raises a ValueError if there is not a tent at tent_loc.
> >  Does not return anything """
> >  # Your code here
> >
> >  def get_tents(self):
> >  """ Returns a list of all tents on the campus. The list should 
> > contain
> >  the string representation of the Location of a tent. The list 
> > should
> >  be sorted by the x coordinate of the location. """
> >  # Your code here
> > 
> > 
> > 
> > -=-=-=-=-=-=-=
> > 
> > For example, if c = MITCampus(Location(1,2)) then executing the following 
> > sequence of commands:
> > 
> > c.add_tent(Location(2,3)) should return True
> > c.add_tent(Location(1,2)) should return True
> > c.add_tent(Location(0,0)) should return False
> > c.add_tent(Location(2,3)) should return False
> > c.get_tents() should return ['<0,0>', '<1,2>', '<2,3>']
> > 
> > -=-=-=-=-=-=-
> > 
> > Now as per instructions, class MITCampus(Campus) has  (self, center_loc, 
> > tent_loc = Location(0,0)) and it is mentioned that center_loc and tent_loc 
> > are Location objects but when I code them as Locations, I get error from 
> > the tester:
> > Traceback (most recent call last):
> >File "submission.py", line 61, in __init__
> >  self.cloc=Location(center_loc)
> > TypeError: __init__() missing 1 required positional argument: 'y'
> > 
> > -=-=-=-==
> > 
> > Please help
> > 
> Location.__init__ expects 3 arguments: self, x, y
> 
> self is already provided, so that leaves 2 arguments: x, y
> 
> You're giving it only 1 argument: center_loc
> 
> What is center_loc? Is it a tuple?
> 
> If it is, then you could do:
> 
>  self.cloc=Location(center_loc[0], center_loc[1])
> 
> or:
> 
>  self.cloc=Location(*center_loc)

Hi, thanks for replying. As per the description it is a Location object. And 
that result is from the tester so it should have provided two values if it was 
expecting it to be a location object.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Need help to understand not the answer

2017-07-29 Thread MRAB

On 2017-07-29 20:16, new_to_c0ding wrote:

Hello all,
I have been scratching my head since morning but could not understand this quiz 
question. I would appreciate if someone could help me understand what is it 
asking me to do. I dont need the answer but just the right direction to look at.

### Do not change the Location or Campus classes. ###
### Location class is the same as in lecture. ###
class Location(object):
 def __init__(self, x, y):
 self.x = x
 self.y = y
 def move(self, deltaX, deltaY):
 return Location(self.x + deltaX, self.y + deltaY)
 def getX(self):
 return self.x
 def getY(self):
 return self.y
 def dist_from(self, other):
 xDist = self.x - other.x
 yDist = self.y - other.y
 return (xDist**2 + yDist**2)**0.5
 def __eq__(self, other):
 return (self.x == other.x and self.y == other.y)
 def __str__(self):
 return '<' + str(self.x) + ',' + str(self.y) + '>'
 
class Campus(object):

 def __init__(self, center_loc):
 self.center_loc = center_loc
 def __str__(self):
 return str(self.center_loc)
class MITCampus(Campus):
 """ A MITCampus is a Campus that contains tents """
 def __init__(self, center_loc, tent_loc = Location(0,0)):
 """ Assumes center_loc and tent_loc are Location objects
 Initializes a new Campus centered at location center_loc
 with a tent at location tent_loc """
 # Your code here
   
 def add_tent(self, new_tent_loc):

 """ Assumes new_tent_loc is a Location
 Adds new_tent_loc to the campus only if the tent is at least 0.5 
distance
 away from all other tents already there. Campus is unchanged otherwise.
 Returns True if it could add the tent, False otherwise. """
 # Your code here
   
 def remove_tent(self, tent_loc):

 """ Assumes tent_loc is a Location
 Removes tent_loc from the campus.
 Raises a ValueError if there is not a tent at tent_loc.
 Does not return anything """
 # Your code here
   
 def get_tents(self):

 """ Returns a list of all tents on the campus. The list should contain
 the string representation of the Location of a tent. The list should
 be sorted by the x coordinate of the location. """
 # Your code here



-=-=-=-=-=-=-=

For example, if c = MITCampus(Location(1,2)) then executing the following 
sequence of commands:

c.add_tent(Location(2,3)) should return True
c.add_tent(Location(1,2)) should return True
c.add_tent(Location(0,0)) should return False
c.add_tent(Location(2,3)) should return False
c.get_tents() should return ['<0,0>', '<1,2>', '<2,3>']

-=-=-=-=-=-=-

Now as per instructions, class MITCampus(Campus) has  (self, center_loc, 
tent_loc = Location(0,0)) and it is mentioned that center_loc and tent_loc are 
Location objects but when I code them as Locations, I get error from the tester:
Traceback (most recent call last):
   File "submission.py", line 61, in __init__
 self.cloc=Location(center_loc)
TypeError: __init__() missing 1 required positional argument: 'y'

-=-=-=-==

Please help


Location.__init__ expects 3 arguments: self, x, y

self is already provided, so that leaves 2 arguments: x, y

You're giving it only 1 argument: center_loc

What is center_loc? Is it a tuple?

If it is, then you could do:

self.cloc=Location(center_loc[0], center_loc[1])

or:

self.cloc=Location(*center_loc)
--
https://mail.python.org/mailman/listinfo/python-list


Re: Need help to understand not the answer

2017-07-29 Thread Piet van Oostrum
new_to_c0ding  writes:

> Now as per instructions, class MITCampus(Campus) has  (self, center_loc, 
> tent_loc = Location(0,0)) and it is mentioned that center_loc and tent_loc 
> are Location objects but when I code them as Locations, I get error from the 
> tester:
> Traceback (most recent call last):
>   File "submission.py", line 61, in __init__
> self.cloc=Location(center_loc)
> TypeError: __init__() missing 1 required positional argument: 'y'

Location must be called with 2 parameters: a x and a y coordinate, not
with another location as parameter.
-- 
Piet van Oostrum 
WWW: http://piet.vanoostrum.org/
PGP key: [8DAE142BE17999C4]
-- 
https://mail.python.org/mailman/listinfo/python-list


Need help to understand not the answer

2017-07-29 Thread new_to_c0ding
Hello all,
I have been scratching my head since morning but could not understand this quiz 
question. I would appreciate if someone could help me understand what is it 
asking me to do. I dont need the answer but just the right direction to look at.

### Do not change the Location or Campus classes. ###
### Location class is the same as in lecture. ###
class Location(object):
def __init__(self, x, y):
self.x = x
self.y = y
def move(self, deltaX, deltaY):
return Location(self.x + deltaX, self.y + deltaY)
def getX(self):
return self.x
def getY(self):
return self.y
def dist_from(self, other):
xDist = self.x - other.x
yDist = self.y - other.y
return (xDist**2 + yDist**2)**0.5
def __eq__(self, other):
return (self.x == other.x and self.y == other.y)
def __str__(self):
return '<' + str(self.x) + ',' + str(self.y) + '>'

class Campus(object):
def __init__(self, center_loc):
self.center_loc = center_loc
def __str__(self):
return str(self.center_loc)
class MITCampus(Campus):
""" A MITCampus is a Campus that contains tents """
def __init__(self, center_loc, tent_loc = Location(0,0)):
""" Assumes center_loc and tent_loc are Location objects 
Initializes a new Campus centered at location center_loc 
with a tent at location tent_loc """
# Your code here
  
def add_tent(self, new_tent_loc):
""" Assumes new_tent_loc is a Location
Adds new_tent_loc to the campus only if the tent is at least 0.5 
distance 
away from all other tents already there. Campus is unchanged otherwise.
Returns True if it could add the tent, False otherwise. """
# Your code here
  
def remove_tent(self, tent_loc):
""" Assumes tent_loc is a Location
Removes tent_loc from the campus. 
Raises a ValueError if there is not a tent at tent_loc.
Does not return anything """
# Your code here
  
def get_tents(self):
""" Returns a list of all tents on the campus. The list should contain 
the string representation of the Location of a tent. The list should 
be sorted by the x coordinate of the location. """
# Your code here



-=-=-=-=-=-=-=

For example, if c = MITCampus(Location(1,2)) then executing the following 
sequence of commands:

c.add_tent(Location(2,3)) should return True
c.add_tent(Location(1,2)) should return True
c.add_tent(Location(0,0)) should return False
c.add_tent(Location(2,3)) should return False
c.get_tents() should return ['<0,0>', '<1,2>', '<2,3>']

-=-=-=-=-=-=-

Now as per instructions, class MITCampus(Campus) has  (self, center_loc, 
tent_loc = Location(0,0)) and it is mentioned that center_loc and tent_loc are 
Location objects but when I code them as Locations, I get error from the tester:
Traceback (most recent call last):
  File "submission.py", line 61, in __init__
self.cloc=Location(center_loc)
TypeError: __init__() missing 1 required positional argument: 'y'

-=-=-=-==

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


Re: I need help with making my claculator

2017-05-24 Thread woooee
This is most likely using class objects instead of instance objects.  Not a 
normal thing in Python.  As stated above, it is difficult, as the responses in 
this thread show, to get assistance with some alternate coding style.  It is 
better to use Python in the way that is intended.  Otherwise, you can not 
expect volunteers to spend extra time trying to figure out someone's alternate 
style.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: I need help with making my claculator

2017-05-24 Thread MRAB

On 2017-05-25 00:02, woo...@gmail.com wrote:

How do you then run the mainloop, i.e. get it to do something?


tkinter.mainloop()
--
https://mail.python.org/mailman/listinfo/python-list


Re: I need help with making my claculator

2017-05-24 Thread woooee
How do you then run the mainloop, i.e. get it to do something?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: I need help with making my claculator

2017-05-22 Thread Peter Otten
woo...@gmail.com wrote:

> First, you have to have a Tk instance before you do anything else.  Take a
> look at this example, and then expand upon it to create the calculator 
> http://python-textbok.readthedocs.io/en/1.0/Introduction_to_GUI_Programming.html

While I agree that creating a Tk instance explicitly is preferable tkinter 
will create one if you don't:

>>> import tkinter
>>> tkinter._default_root is None
True
>>> frame = tkinter.Frame()
>>> tkinter._default_root

>>> frame.master is tkinter._default_root
True


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


Re: I need help with making my claculator

2017-05-21 Thread woooee
First, you have to have a Tk instance before you do anything else.  Take a look 
at this example, and then expand upon it to create the calculator  
http://python-textbok.readthedocs.io/en/1.0/Introduction_to_GUI_Programming.html
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: I need help with making my claculator

2017-05-20 Thread bartc

On 20/05/2017 14:49, Steve D'Aprano wrote:

On Sat, 20 May 2017 09:13 pm, bartc wrote:



Try running the program.

(I did that but I can't follow this style of coding so can't help.)


Chris is within his rights to refuse to run untrusted code downloaded over
the internet.

It's not even the security aspect: the code is fairly short, and doesn't
appear to be obfuscated or do anything nasty.

But its a matter of fairness: we're volunteers, not slaves or paid workers,
and we get to choose on what problems we work on.


I think of these as little puzzles to solve.

And in this case, it had a nifty little display; but I couldn't even get 
to the point where I could use that display setup as a start point and 
add my own logic to make it work.


(Could such a program be implemented using simple linear logic? I dusted 
off some old, half-finished graphics library of mine [not Python] and 
tried emulating a 4-function calculator. The answer was yes, it could. 
For a simple app like this, you don't need classes or lambdas or 
whatever else it is using; a simple loop will do.)



We're not being paid to solve people's problems, we're doing it from a sense
of community (and maybe to show off, a bit). We've only got so much time
and energy for solving people's problems, and the more vague those problems
are, the less likely we are to care enough to put the work in to solve it.

Give us an interesting problem, and some of us will put *hours* of work into
it. But give us something vague or boring or trivial, and What's In It For
Us?


OK, if I ever get stuck with a Python problem, I'd better make it 
interesting then!


--
bartc

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


Re: I need help with making my claculator

2017-05-20 Thread Joel Goldstick
On Sat, May 20, 2017 at 9:49 AM, Steve D'Aprano
<steve+pyt...@pearwood.info> wrote:
> On Sat, 20 May 2017 09:13 pm, bartc wrote:
>
>> On 20/05/2017 03:10, Chris Angelico wrote:
>>> Without any specific questions, you're not going to get anything more
>>> than a basic eyeballing of the code.
>>
>> Try running the program.
>>
>> (I did that but I can't follow this style of coding so can't help.)
>
> Chris is within his rights to refuse to run untrusted code downloaded over
> the internet.
>
> It's not even the security aspect: the code is fairly short, and doesn't
> appear to be obfuscated or do anything nasty.
>
> But its a matter of fairness: we're volunteers, not slaves or paid workers,
> and we get to choose on what problems we work on.
>
> We're not being paid to solve people's problems, we're doing it from a sense
> of community (and maybe to show off, a bit). We've only got so much time
> and energy for solving people's problems, and the more vague those problems
> are, the less likely we are to care enough to put the work in to solve it.
>
> Give us an interesting problem, and some of us will put *hours* of work into
> it. But give us something vague or boring or trivial, and What's In It For
> Us?
>
> The Original Poster garsink at gmail.com cares so little for our time that
> he or she didn't even *ask* a question. Or give a name we can call them
> (email addresses are so impersonal and unfriendly). Nothing but a pair of
> statements: I need help, here's my code.
>
> Well, we all need help, and thank you for sharing.
>
> Why should we bother to run your code if you can't even be bothered to say
> Please or Thank You or tell us what's wrong with it?
>
> "garsink", or whatever you would like us to call you, please help us to help
> you. Don't expect us to run your code until you've made it interesting for
> us. Please read this webpage before answering:
>
> http://sscce.org/
>
> It is written for Java programmers, but it applies to Python too.
>
> Thank you.
>
>
>
> --
> Steve
> Emoji: a small, fuzzy, indistinct picture used to replace a clear and
> perfectly comprehensible word.
>
> --
> https://mail.python.org/mailman/listinfo/python-list

I took a look at the url from the email address.  Its some private
school for apparently youngish kids.  So, a little perspective on the
rather vague query.

Poster, maybe try the python-tutor mailing list

-- 
Joel Goldstick
http://joelgoldstick.com/blog
http://cc-baseballstats.info/stats/birthdays
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: I need help with making my calculator

2017-05-20 Thread Steve D'Aprano
On Sat, 20 May 2017 11:42 am, gars...@gmail.com wrote:

> m using Python 3.4.2
> This is my code:

Please read this first:

http://sscce.org/

And then indent the "calc" method so that it is part of the class:

> def calc(self, display):
> try:
> display.set(eval(display.get()))
> except:
> display.set("Type an actual equation please!")

That's not indented. It needs to be indented by one level.




-- 
Steve
Emoji: a small, fuzzy, indistinct picture used to replace a clear and
perfectly comprehensible word.

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


  1   2   3   4   5   6   7   8   9   10   >