Re: Are there any other better ways to access a single bit of string of digits?

2015-05-31 Thread Denis McMahon
On Sun, 31 May 2015 11:36:35 -0700, fl wrote:

 I am new to Python. I would manipulate a string of hex numbers. If the
 first digit is bigger than 7, the first two digits are required to add
 4.

What happens if the first two digits are ff, does it become 103 or 03.

If you have __

Do you want to create 103ff_103ff_103ff

or

03ff_03ff_03ff

or

0400_0400_03ff

or

10400_0400_03ff ..

 For example, '8022_3345' will be changed to '8422_3345'. The underscore
 between two 4-digit's was generated previously (i.e.
 it is already in the .txt file).
 
 I have not tried to read the .txt file to a list yet. I just try the
 following:
 
 tmp ['12345678', '23456789', '3456789a', '456789ab']
 
 Each 8-digit hex number is assigned to a variable, such as:
 
 digit8=tmp[0]
 
 I can compare digit8[0] with 7, and so on...
 
 The underscore, I think, can be removed by first a string replace.
 
 My question here is:
 
 Do you have better ways than my tmp, digit8 operation?

Yes, if these are numbers, manipulate them as numbers, not strings.

def bing(n):
n = int(n.replace(_, ), base=16)  # convert to numbers
if n  0x7fff:# if 0x8000 or more
n = n + 0x0400# add 0x0400
return n  # and return result

newnums = [ bing(x) for x in oldnums ]

It could probably be done as a single list comprehension, but it might 
get a bit messy.

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Decoding JSON file using python

2015-05-28 Thread Denis McMahon
On Thu, 28 May 2015 13:32:39 +1000, Cameron Simpson wrote:

 On 28May2015 01:38, Jon Ribbens jon+use...@unequivocal.co.uk wrote:
On 2015-05-27, Karthik Sharma karthik.sha...@gmail.com wrote:
 I tried modifying the program as follows as per your
 suggestion.Doesn't seem to work.

That's because you didn't modify the program as per their suggestion,
you made completely different changes that bore no relation to what they
said.
 
 Actually, his changes looked good to me. He does print from data first,
 but only for debugging. Then he goes:
 
   message = json.loads(data)
 
 and tried to access message['Message'].
 
 However I am having trouble reproducing his issue because his quoted
 code is incorrect. I've tried to fix it, as listed below, but I don't
 know what is really meant to be in the 'data string.

it looks like data is a broken array of one object, part of which is a 
further quoted json string.

There should be a string value after the isEvent but I have no idea what 
it should be, nor what else should come after.

message:tdetails:{att:val pairs}

is also wrong in the first level of inner json.

I think he wants data[0]['message'], but the inner json strings are 
broken too, and should look more like.

data: [{\Severity\:\warn\,\Subject\:\Reporting\,\Message\:
\tdetails\,\attr_name\:\{\\\Product\\\:\\\Gecko\\\,\\\CPUs\\
\:8,\\\Language\\\:\\\en-GB\\\,\\\isEvent\\\:\\\attr_value\\\}\}
],

In this model, if the data attribute is a json string, then

data maps to a list / array

data[0] maps to an object / dictionary

data[0][Message] maps to the string literal tdetails

data[0][attr_name] maps to a string representation of a json ob with 
another level of escaping.

That string can then be loaded, eg:

attr_name = json.loads(data[0][attr_name])

See: http:/www.sined.co.uk/python/nested_json.py.txt


-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Decoding JSON file using python

2015-05-28 Thread Denis McMahon
On Wed, 27 May 2015 15:23:31 -0700, Karthik Sharma wrote:

 The JSON structure is valid as shown by http://jsonlint.com/

Not when I paste it in it's not. The data attribute is an unterminated 
string and is not followed by a comma.

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Logic problem: need better logic for desired thruth table.

2015-05-28 Thread Denis McMahon
On Thu, 28 May 2015 14:58:19 -0700, sohcahtoa82 wrote:

 On Thursday, May 28, 2015 at 2:50:18 PM UTC-7, Skybuck Flying wrote:
 Hello,

 # Desired truth table for BotWaitForCooldown and CooldownDetected 
 # BotWaitForCooldown:  CooldownDetected: Desired Result:
 # FalseFalse True 
 # FalseTrue  False 
 # True False True 
 # True True  True 

 I think the logic you're really looking for is:

 return BotWaitForCooldown or (not (BotWaitForCooldown or
 CooldownDetected))

Nope, it simplifies to:

BotWaitForCooldown or not CooldownDetected

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Extract email address from Java script in html source using python

2015-05-25 Thread Denis McMahon
On Sat, 23 May 2015 12:16:06 +0530, savitha devi wrote:

 I am developing a web scraper code using HTMLParser. I need to extract
 text/email address from java script with in the HTMLCode.I am beginner
 level in python coding and totally lost here. Need some help on this.

(a) Try a less ambitious learning project.
(b) Start reading the relevant documentation.

Pick one and go with it.

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Convert c file to csv file(unix format) in python

2015-05-22 Thread Denis McMahon
On Wed, 20 May 2015 01:57:51 +, Denis McMahon wrote:

 Based on the sample you sent, the output csv file is 1657 lines in
 length, and the first and last lines are:

[snip]

Well he didn't tell me if I was generating the right output, or what was 
wrong with it if it was wrong, so I guess he got a solution elsewhere.

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Best approach to create humongous amount of files

2015-05-20 Thread Denis McMahon
On Wed, 20 May 2015 17:14:15 +0530, Parul Mogra wrote:

 Hello everyone,
 My objective is to create large amount of data files (say a million
 *.json files), using a pre-existing template file (*.json). Each file
 would have a unique name, possibly by incorporating time stamp
 information. The files have to be generated in a folder specified.

 What is the best strategy to achieve this task, so that the files will
 be generated in the shortest possible time? Say within an hour.

timestamps are normally unixtime in seconds. There are 3600 seconds in an 
hour. You'll have a hard job creating a million files with timestamp 
based naming inside of an hour.

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Convert c file to csv file(unix format) in python

2015-05-19 Thread Denis McMahon
On Tue, 19 May 2015 12:26:05 -0700, umasrinath88 wrote:

 I have shared c file with you.Iorder to convert to unix format csv,
 below are the main steps we can follow.

What you're trying to do doesn't match with what you're explaining here.

What you're actually trying to do is extract a constant data declaration 
from a c source code file and output it in a different format.

You haven't explained whether you want the hexadecimal values converted 
to decimal integers or not.

Nor have you stated whether you want the hexadecimal values as quoted 
strings or not.

I believe I have a short program that does what you require based on the 
file you sent me and what I think is the output you're looking for. 
However, before I show you my solution, I'd like to see evidence of your 
own attempt to solve the problem.

Based on the sample you sent, the output csv file is 1657 lines in 
length, and the first and last lines are:

16,0x0800,0xCC,0x16,0x00,0x20,0x35,0x15,0x00,0x08,0x29,0x15,0x00,0x08,0x2D,0x15,0x00,0x08

12,0x08006780,0x40,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0xFF,0x00,0x00,0x00

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Convert c file to csv file(unix format) in python

2015-05-19 Thread Denis McMahon
On Tue, 19 May 2015 09:30:15 -0700, umasrinath88 wrote:

 I have a python script file which converts .hex file  to c file.

Hex is generally an ascii file containing hexadecimal values.

.c is generally an ascii file formatted in a way that corrsponds to the 
structures of the c programming language.

 Can anyone help me in converting .c file to csv file (unix format).

csv is generally a way of exchanging data between different software 
applications in a generally human readable format.

I'm unsure as to the translations you expect to be made to convert a .c 
file into a csv file. Perhaps you could elaborate on these.

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Rule of order for dot operators?

2015-05-17 Thread Denis McMahon
On Sun, 17 May 2015 11:45:02 +1000, Steven D'Aprano wrote:

 On Sun, 17 May 2015 05:40 am, Thomas 'PointedEars' Lahn wrote:
 
 C.D. Reimer wrote:
 
 Who?
 
 Don't be a dick, Thomas.

Thomas is a professional dick, he can't help it, he's been a professional 
dick for years in php and javascript groups, and now he's obviously 
spreading himself further afield. He usually confines his wisdom to 
pointing out faults in other's posts, rather than offering any 
constructive input himself.

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Fastest way to remove the first x characters from a very long string

2015-05-16 Thread Denis McMahon
On Sat, 16 May 2015 06:28:19 -0700, bruceg113355 wrote:

 I have a string that contains 10 million characters.
 
 The string is formatted as:
 
 001 : some hexadecimal text ... \n 002 : some hexadecimal text
 ... \n 003 : some hexadecimal text ... \n ...
 010 : some hexadecimal text ... \n 011 : some hexadecimal text
 ... \n
 
 and I need the string to look like:
 
 some hexadecimal text ... \n some hexadecimal text ... \n some
 hexadecimal text ... \n ...
 some hexadecimal text ... \n some hexadecimal text ... \n

Looks to me as if you have a 10 Mbyte encoded file with line numbers as 
ascii text and you're trying to strip the line numbers before decoding 
the file.

Are you looking for a one-off solution, or do you have a lot of these 
files?

If you have a lot of files to process, you could try using something like 
sed.

sed -i.old 's/^\d+ : //' *.ext

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Encrypt python files

2015-05-08 Thread Denis McMahon
On Wed, 06 May 2015 00:23:39 -0700, Palpandi wrote:

 On Wednesday, May 6, 2015 at 12:07:13 PM UTC+5:30, Palpandi wrote:
 Hi,
 
 What are the ways to encrypt python files?
 
 No, I just want to hide the scripts from others.

You can do that by deleting the scripts. Make sure you use a secure 
deletion tool.

I'm not aware of any mechanism for encrypted executable python scripts. 
You can obfuscate the code, but you can't encrypt it because the python 
interpreter needs the script file to execute it.

The same holds true for any mechanism designed to encrypt executable code 
regardless of whether it's script or compiled. At the lowest level the 
processor only understands the instruction set, and encrypted code has to 
be decrypted to execute.

As the decryption method is always available to anyone who has legitimate 
access to execute the code, it's impossible to hide the code at that 
point.

Example - if I give you an encrypted binary to run on your system, it 
either has to be unencryptable using tools you already have, or using a 
built in unencrypter, both of which you have access to and can use to 
unencrypt the encrypted executable code.

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Encrypt python files

2015-05-08 Thread Denis McMahon
On Tue, 05 May 2015 23:37:02 -0700, Palpandi wrote:

 What are the ways to encrypt python files?

Depends why you want to encrypt them, and what you want to do with the 
encrypted files.

Do you mean executable python code files, or do you mean data files 
generated by python.

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Beacon controller

2015-05-08 Thread Denis McMahon
On Tue, 05 May 2015 16:37:06 -0700, bmanogna.17 wrote:

 I'm new to pyhton, can anyone suggest me how can I implement a DOS or
 DDOS attack in Beacon Controller.

Contact your nearest LEO cybercrime unit and ask them.

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Json Comaprision

2015-05-08 Thread Denis McMahon
On Tue, 05 May 2015 12:55:20 -0700, pra devOPS wrote:

 I wanted to compare two json files ignoring few of the keys in the json
 files.
 
 Can anybody suggest me few things?

json files usually get imported to either a list or a dictionary (unless 
they're a simple string or number).

If the files are json arrays they'll get imported as lists. otherwise if 
they're key:value pairs they'll get imported as a dictionary.

Basically you need a routine that can take two arbitrary objects, check 
if they're the same data type, and then check their values. If they're of 
a collection type, checking their values means recursively checking that 
every element in the collection matches in type and value.

You need to be able to handle lists, dictionaries, strings, ordinals and 
floats, and for floats you might want to consider that if two floats are 
generated by two different systems, perhaps a cray xmp running compiled 
fortran and an acorn risc os box running compiled c++ for example, they 
might disagree at the least significant digit but still be considered 
equal for your purposes.

It's much easier to prove things are different than to prove they are the 
same, and you're much more likely to falsely detect difference than you 
are to correctly detect equality as the complexity of the objects you are 
checking increases unless you get the code right.

For a list, you need to consider if the order of elements is important. 
If not, then for every element in list a you need to detect if an 
identical element is in list b.

Supposing you have two lists of lists. This might mean that for every sub 
list in a, you need to check every sub list in b to see if it matches. 
You probably also want to check for lists and dictionaries if the sizes 
are equivalent too. Here's an example why:

a = [ [a,b,c] ]

b = [ [a,b,c], [a,c,b], [b,a,c], [b,c,a], [c,a,b], [c,b,a] ]

If you compare sublists purely on the basis that they contain the same 
elements, then a[0] == each of b[0..5]

Does that make a and b equal?

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: CHALLENGE HELP - GOOGLE DEVELOPER DAY

2015-05-06 Thread Denis McMahon
On Tue, 05 May 2015 09:59:03 -0700, worship.brother wrote:

 Archaeologists have found a scroll with the following texts:

First you need to visit the hidden Temple of Offler, where you will find 
the Tears of Offler (they're the big gems set into the statue just above 
the teeth) after making your way through the maze with the big rolling 
ball, spiky pit, deadfall and spinning blade traps.

Then you offer the tears off Offler up on the altar of Cthulhu[1].

Either your brain will melt when Cthulhu appears to you, or you will be 
blessed with the inspiration to write the code to solve your problem.

If the latter, and the code doesn't work, show us the code and we might 
be able to make suggestions for you.

[1] If you thought getting Offler's Tears was hard, wait until you try 
reaching the altar of Cthulhu.

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Writing list of dictionaries to CSV

2015-05-06 Thread Denis McMahon
On Tue, 05 May 2015 22:32:28 -0700, Kashif Rana wrote:

 thanks for the feedback. I think its problem with excel itself, showing
 wrong value. Because when I opened the csv file in text editor, I can
 see correct value but opening in excel showing wrong value. What I can
 do to see correct in excel as well.

You need to format your CSV date into a date format that Excel 
understands when it imports it.

First thing to try would be to export some dates from excel as CSV and 
see what format excel puts them in.

The see if excel recognises them as dates when you re-import the same 
file.

If excel recognises it's own csv exported dates, reformat your dates to 
match the excel ones when you generate the csv.

Otherwise, you might need to convert the dates to a numeric value and 
tell excel to format the field as date after input.

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: [Matplotlib] Ploting an exponential distribution frequency curve

2015-04-26 Thread Denis McMahon
On Sat, 25 Apr 2015 23:33:10 +0100, Mario Figueiredo wrote:

 plot(list(results.keys()), list(results.values()))

I found multiple plots in matplotlib. You need to specify which one 
you're using.

The first thing you need to do is create a small self contained example 
of your problem.

State the problem: Plot does not create the output you expect.

Give an example:

plot( [1,11], [5,5] )

Explain what you expect the output to be:

You expect a line to be plotted from (1,5) to (11,5)

Explain what you actually see: ???

Note that it may be possible to correlate the data values and the output 
of the simple case in a way that shows you that you have in some way 
fundamentally misunderstood how the arguments should be passed to the 
plot function. If this is the case, work out what you need to do to fix 
the simple case, and then apply the same solution to your more complex 
data set.

If, for example, you see a line from (1,11) to (5,5) instead of a line 
from (1,5) to (11,5), then it might be that you need to combine the two 
lists into a single list of co-ordinate tuples, using eg:

plot(zip(list(results.keys()), list(results.values(

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: [Matplotlib] Ploting an exponential distribution frequency curve

2015-04-25 Thread Denis McMahon
On Sat, 25 Apr 2015 23:33:10 +0100, Mario Figueiredo wrote:

 plot(list(results.keys()), list(results.values()))

matplotlib supports at least (from searching the website) 5 plot methods.

Which one are you using?

My first guess would be that the data format that plot expects isn't the 
format it's getting, as you appear to be passing a list of x values and a 
list of y values, is it possible that it expects a list of value pairs?

Sorry, but given a choice of 5 plot methods in matplotlib and no hint as 
to which one you're calling, I'm not inclined to go and look at the 
arguments of all of them.

One suggestion I would make, though:

try plot([0,1,2,3,4,5,6,7,8,9,10],[0,1,2,3,4,5,6,7,8,9,10])

and see if you get a straight line running through the co-ord pairs:

0,0; 1,1; 2,2; 3,3; 4,4; 5,5; 6,6; 7,7; 8,8; 9,9 and 10,10

If not, then try:

plot(zip([0,1,2,3,4,5,6,7,8,9,10],[0,1,2,3,4,5,6,7,8,9,10]))

And see what that produces.

If the second plot produces the line I described, try:

plot(zip(list(results.keys()), list(results.values(

in your code.

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Getting rid of

2015-04-12 Thread Denis McMahon
On Sun, 12 Apr 2015 21:27:30 +0200, Cecil Westerhof wrote:

 When you run my script you do not get warnings?

I ran into too many issues trying to install the modules I needed to try 
and run it.

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Getting rid of

2015-04-12 Thread Denis McMahon
On Sun, 12 Apr 2015 19:48:53 +0200, Cecil Westerhof wrote:

 What should I do to get rid of the warnings:
 /usr/lib/python2.7/site-packages/requests-2.6.0-py2.7.egg/requests/
packages/urllib3/connectionpool.py:769:
 InsecureRequestWarning: Unverified HTTPS request is being made.
 Adding certificate verification is strongly advised. See:
 https://urllib3.readthedocs.org/en/latest/security.html
   InsecureRequestWarning)

Have you checked that your certificates file exists? You can find the 
location using the python console:

$ python

 import certifi
 certifi.where()

'/usr/local/lib/python2.7/dist-packages/certifi/cacert.pem'

 exit()

And then check the location from the command line:

$ ls -l /usr/local/lib/python2.7/dist-packages/certifi/cacert.pem

-rw-r--r-- 1 root staff 315159 Apr 12 19:46 /usr/local/lib/python2.7/dist-
packages/certifi/cacert.pem

$ 

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Best search algorithm to find condition within a range

2015-04-08 Thread Denis McMahon
On Tue, 07 Apr 2015 23:18:14 -0700, wxjmfauth wrote:

 Le mercredi 8 avril 2015 08:08:04 UTC+2, wxjm...@gmail.com a écrit :
 Le mercredi 8 avril 2015 00:57:27 UTC+2, Steven D'Aprano a écrit :
  On Tue, 7 Apr 2015 07:44 pm, jonas.thornv...@gmail.com wrote:
  
  
   I want todo faster baseconversion for very big bases like base 1
   000 000,
   so instead of adding up digits i search it.
  
  What digits would you use for base one-million?
  
  Base 2 uses 0 1.
  Base 3 uses 0 1 2.
  Base 10 uses 0 1 2 3 4 5 6 7 8 9.
  Base 16 uses 0 1 2 3 4 5 6 7 8 9 A B C D E F.
  
  Base one million uses what?
  
  How would you write down 12345 in base one-million?
  
  
 =
 
 Why should a digit contain a single/unique character?
 
 Representation of the number 257 in base 256:
 
 257 (base 10) -- FF 02 (base 256)
 
 ==
 
 Oops, typo, erratum
 
 *** 257 (base 10) -- 01 01 (base 256) ***

Bt. Wrong.

0101(256) is 0 * 256^3 + 1 * 256^2 + 0 * 256^1 + 1 * 256^0

= 65537

The whole point of base x is that any number in the range 0 .. x^1 is 
represented with a single characterisation, otherwise you don't have 
base x.

This is the same fundamental issue as the OP is failing to understand - 
base x notation is a human readability and representation thing, not an 
inherent feature of numbers.

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Get nesting of regex groups

2015-04-08 Thread Denis McMahon
On Wed, 08 Apr 2015 22:54:57 +0200, Mattias Ugelvik wrote:

 Example: re.compile('(?Pouter(?Pinnera))')
 
 How can I detect that 'inner' is a nested group of 'outer'? I know that
 'inner' comes later, because I can use the `regex.groupindex` (thanks to
 your help earlier:
 https://mail.python.org/pipermail/python-list/2015-April/701594.html).

Pardon me for stating the obvious, but as the person defining the re, and 
assuming you haven't generated another sub-pattern somewhere in the same 
re with the same name, how can inner ever not be a nested group of outer?

Even in the contrived example below, it is clear that the list of tuples 
generated by by findall is of the form:

()[0] = 'outer', ()[1] = 'inner'

from the order of matches principle.



#!/usr/bin/python

import re

patt = re.compile('(?Poutera+(?Pinnerb+))')

result = patt.findall('abaabbaaabbb')

print result



however if all you are doing is using .search or .find for the first 
match of the pattern, then there should be no scope for confusion anyway.

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Best search algorithm to find condition within a range

2015-04-07 Thread Denis McMahon
On Tue, 07 Apr 2015 09:29:59 -0400, Dave Angel wrote:

 On 04/07/2015 05:44 AM, jonas.thornv...@gmail.com wrote:

 I want todo faster baseconversion for very big bases like base 1 000
 000, so instead of adding up digits i search it.

 How do you know the baseconversion is the bottleneck, if you haven't
 written any Python code yet?

He doesn't. He doesn't comprehend that as far as a computer is concerned 
an integer has no specific 'base', it's only when presented in a form for 
humans to read that it gets base information added in the representation.

He's making these and other similar errors in the javascript groups too.

I suspect he's one of those people that spends his time thinking up 
elaborate solutions that he has no idea how to implement as a response to 
dreamt up non existent problems.

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: New to Programming: Adding custom functions with ipynotify classes

2015-04-03 Thread Denis McMahon
On Thu, 02 Apr 2015 18:30:42 -0700, Saran A wrote:

 Here is the program that I am trying to write (with specs):

Saran, please stop prefacing every subject with New to programming: - 
it does not give an clue whatsoever as to what your post is about.

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Error in processing JSON files in Python

2015-03-31 Thread Denis McMahon
On Mon, 30 Mar 2015 14:27:14 -0700, Karthik Sharma wrote:

 I have the following python program to read a set of JSON files do some
 processing on it and dump them back to the same folder. However When I
 run the below program and then try to see the output of the JSON file
 using
 
 `cat file.json | python -m json.tool`
 
 I get the following error
 
 `extra data: line 1 column 307 - line 1 column 852 (char 306 - 851)`
 
 What is wrong with my program?
  
 #Process 'new' events to extract more info from 'Messages'
 rootDir = '/home/s_parts'
 for dirName, subdirList, fileList in os.walk(rootDir):
 print('Found directory: %s' % dirName)
 for fname in fileList:
 fname='s_parts/'+fname with open(fname, 'r+') as f:
 json_data = json.load(f)
 # do stuff to the data
 json.dump(json_data,f)

You're writing back to the same file as you loaded the data from having 
opened the file in append mode.

This probably leads to a file containing two json objects, the original 
one and the one which you have processed.

That's a bad json file.

Note the caution in the python documentation:

Note - Unlike pickle and marshal, JSON is not a framed protocol, so 
trying to serialize multiple objects with repeated calls to dump() using 
the same fp will result in an invalid JSON file.

Writing back to the same file as you read with json.load is the same 
thing. If you want to use the same file, you need to close it after the 
json.load(), and then open it again in write mode before the json.dump(). 

Write is w, *NOT* w+.

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Python 3 lack of support for fcgi/wsgi.

2015-03-30 Thread Denis McMahon
On Sun, 29 Mar 2015 11:57:54 -0700, John Nagle wrote:

 The Python 2 module fcgi is gone in Python 3.

Was this part of the python standard library, or was it a third party 
library? I can only find cgi documentation https://docs.python.org/2/
library/cgi.html in the python 2 core documentation, not fcgi 
documentation. Documentation for cgi is also present in the python 3 core 
documentation: https://docs.python.org/3.4/library/cgi.html

Perhaps the issue is that your python 2 web application was built using 
3rd party implementations of cgi interfaces which have not kept up with 
the development of python 3. The only core module I can find in python 
that appears relevant is the cgi module, and that exists both in python 2 
and python 3.

 The Python 3 documentation at
 
 https://docs.python.org/3/howto/webservers.html

That appears to be a copy of the Python 2 Howto. It should probably make 
that clearer! It contains the following caveat:

See also: While this HOWTO tries to give an overview of Python in the 
web, it cannot always be as up to date as desired. Web development in 
Python is rapidly moving forward, so the wiki page on Web Programming 
https://wiki.python.org/moin/WebProgramming may be more in sync with 
recent development.

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Python 3 lack of support for fcgi/wsgi.

2015-03-30 Thread Denis McMahon
On Mon, 30 Mar 2015 15:47:23 +1100, Chris Angelico wrote:

 On Mon, Mar 30, 2015 at 3:35 PM, Paul Rubin no.email@nospam.invalid
 wrote:
 2b. John, thank you for describing your experience and making the
 community's picture of the current overall state of Python 3 more
 accurate.  It was apparently a bit too rosy before, and we should avoid
 fostering unrealistic expectations in the future.

 Not without some evidence of where this a bit too rosy picture came
 from. So far, we've had rebuttals of vaguenesses, which pretty much
 amount to FUD.

I went and looked earlier - the HOWTO on the Python 3 documentation site 
https://docs.python.org/3.4/howto/webservers.html appears to be almost 
a straight copy of the HOWTO from the Python 2 documentation. https://
docs.python.org/2/howto/webservers.html

As such, it should either be updated to ensure that any external 
libraries and modules are Python 3 compatible, have a suitable caveat 
inserted, or be removed.

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Regex Python Help

2015-03-26 Thread Denis McMahon
On Wed, 25 Mar 2015 14:19:39 -0700, Gregg Dotoli wrote:

 On Wednesday, March 25, 2015 at 4:36:01 PM UTC-4, Denis McMahon wrote:
 On Tue, 24 Mar 2015 11:13:41 -0700, gdotoli wrote:
 
  I am creating a tool to search a filesystem for one simple string.
 
 man grep
 
 STOP! REINVENTING! THE! WHEEL!
 
 Your new wheel will invariably be slower and less efficient than the
 old one.

 Grep is regular expressions. If I'm using Python, I'll use the Python
 modules.
 Silly

1. Please don't top post, this is usenet, we don't top post, comments go 
after the text they comment on soi we can read down the page and it makes 
sense.

2. You gave the thread the title of regex python help.

3. Your initial comment was I am creating a tool to search a filesystem 
for one simple string.

4. The tool (see 3) already exists, it's called grep, it uses regular 
expressions (see 2). It's also going to be a lot faster than using python.

5. According to your post, grep seems to be the tool you are looking for.

6. Reinventing grep in python seems much more silly to me, by the time 
you've finished writing and testing the python code (especially if you 
need to seek help from a newsgroup in the process) grep would have found 
and identified every file containing your one simple string.

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: test1

2015-03-26 Thread Denis McMahon
On Thu, 26 Mar 2015 10:00:56 -0700, Tiglath Suriol wrote:

 I posted two test messages containing code.

No, you excreted a pile of steaming excrement and have continued to do 
so. Your original post in this thread had no relevance to the newsgroup 
or the gated mailing list, it was purely internet vandalism, and your 
ongoing posts are simply trolling.

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: test1

2015-03-26 Thread Denis McMahon
On Thu, 26 Mar 2015 14:06:28 -0700, marcuslom101 wrote:

 I posted two test messages containing code.  They are still there, are
 you blind as well as dumb?

The message that you posted at the start of this thread may have 
contained code, but it wasn't python code, so it's off topic here. Hence 
its a pile of steaming excrement from a troll.

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Regex Python Help

2015-03-25 Thread Denis McMahon
On Tue, 24 Mar 2015 11:13:41 -0700, gdotoli wrote:

 I am creating a tool to search a filesystem for one simple string.

man grep

STOP! REINVENTING! THE! WHEEL!

Your new wheel will invariably be slower and less efficient than the old 
one.

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: beautifulSoup 4.1

2015-03-20 Thread Denis McMahon
On Thu, 19 Mar 2015 21:20:30 -0700, Sayth Renshaw wrote:

 But how can I get the value of the following td

# find all tds with a class attribute of abbreviation

abbtds = soup.find_all(td, attrs={class: abbreviation})

# display the text of each abbtd with the text of the next td

for td in abbtds:

print td.get_text(), td.find_next_sibling().get_text()

This works for the html fragment example given, once I fixed it up by 
removing the extra tr at the end.

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: beautifulSoup 4.1

2015-03-20 Thread Denis McMahon
On Fri, 20 Mar 2015 07:23:22 +, Denis McMahon wrote:

 print td.get_text(), td.find_next_sibling().get_text()

A slightly better solution might even be:

print td.get_text(), td.find_next_sibling(td).get_text()

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: beautifulSoup 4.1

2015-03-20 Thread Denis McMahon
On Fri, 20 Mar 2015 00:18:33 -0700, Sayth Renshaw wrote:

 Just finding it odd that the next sibling is a \n and not the next
 td otherwise that would be the perfect solution.

Whitespace between elements creates a node in the parsed document. This 
is correct, because whitespace between elements will be interpreted as 
whitespace by a browser.

a href=blah1text1/aa href=blah2text2/a

will be displayed differently to

a href=blah1text1/a a href=blah2text2/a

in a browser, because the space between the a two elements in the 
second case is a text node in the dom.

A newline has the same effect (because to a browser for display purposes 
it's just whitespace) but in the dom the text node will contain the 
newline rather than a space.

bs4 tries to parse the html the same way a browser does, so you get all 
the text nodes, including the whitespace between elements which includes 
any newlines.

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


ANN: Lea 2.1.1 released

2015-03-18 Thread Pierre Denis
I am pleased to announce the release of Lea 2.1.1 !

What is Lea?

Lea is a Python package aiming at working with discrete probability
distributions in an intuitive way. It allows you to model a broad range of 
random phenomenons, like dice throwing, coin tossing, gambling, weather, etc. It
offers several modelling features of a PPL (Probabilistic Programming Language),
including bayesian inference and Markov chains.
Lea is open-source (LGPL) and runs on Python 2 or 3. See project page below for
more information (installation, tutorials, examples,  etc).

What's new in Lea 2.1.1?

(compared to 2.0.0)
- new methods: mode, if_ and reduce
- bug fixes on CPT (conditional probability tables)
- fixed broken withProb method
- performance improvements for Python 2

Lea project page

http://code.google.com/p/lea

Download Lea (PyPI)
---
http://pypi.python.org/pypi/lea


With the hope that Lea can make your happiness less uncertain,

Pierre Denis
-- 
https://mail.python.org/mailman/listinfo/python-announce-list

Support the Python Software Foundation:
http://www.python.org/psf/donations/


Re: A simple single line, triple-quoted comment is giving syntax error. Why?

2015-03-18 Thread Denis McMahon
On Wed, 18 Mar 2015 10:46:20 -0700, Aditya Raj Bhatt wrote:

 I always do single line comments with # but just for the sake of it I
 tried it with ''' ''' and it gives me a syntax error.

 ...

 So can someone tell me why a triple-quoted string gives a syntax error
 if only in one line?

A triple quoted string is a multiline string literal. A string literal 
(of any sort) is a basic python expression.

An expression is often, but by no means exclusively, part of an 
assignment statement. However, an expression may also exist just as a 
simple expression.

There is nothing special about a triple quoted string that makes it a 
comment, other than it is sometimes used as such in it's guise as a basic 
expression.

However, you can't have multiple expressions on a line without some sort 
of operand or separator between them.

a = 5 '''text'''

is just as wrong as:

q = 4,5,6   [3,5,7,9]

or

k = 6-2  {56:91, 'fred': 'peter'}

or even

m = 62.3   56.7   101.2

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Md5 is different in Windows and Linux

2015-03-02 Thread Denis McMahon
On Mon, 02 Mar 2015 12:04:46 +0545, Sarvagya Pant wrote:

 When I run the program I get the checksum value:
 2f9cc8da53ee89762a34702f745d2956
 
 But on this site http://onlinemd5.com/ and on linux it has value
 E10D4E3847713472F51BC606852712F1.
 
 Why is there difference in value of Checksum computed by python in
 windows and other system.?

Perhaps windows file io is padding the file to the block size? Or maybe 
the windows version has different end of lines.

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: requesting you all to please guide me , which tutorials is best to learn redis database

2015-02-28 Thread Denis McMahon
On Thu, 26 Feb 2015 11:14:50 -0800, Jai wrote:

 i want to learn redis database and its use via python , please 
 guide me which tutorials i should be study, so that i can learn it
 in good way

Using databases via python often involves working with dictionaries or 
lists, lists of dictionaries, lists of lists etc.

Before you start trying to work with a database and python together, you 
should have a good grasp of the core python data structures, built in 
functions, statements, io, statements, flow control etc.

You should also have a good grasp of the language (presumably an sql 
variant) used by the database, and a very good understanding of how 
string formatting works in python, as you'll be using python to build 
command strings to send to the database.

Then you may be ready to start gluing the two together.

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: progress bar

2015-02-25 Thread Denis McMahon
On Tue, 24 Feb 2015 23:42:42 -0800, Swapnil Pande wrote:

 i want to call another tkinter window after completing the progress bar
 an n e one help me

Try shouting Oi, Window!

Or show us the code that isn't working (just the bit that isn't working) 
and explain what it should be doing and what actually happens. Also 
please tell us what you tried to fix it.

For example, you have a problem communicating between output windows 
after displaying a progress bar, so your example code should:

(a) draw two windows
(b) display a progress bar in one window
(c) Make some sort of call to the second window after the progress bar 
completes.

We only need to see that code. We don't need to see the rest of the code.

If my description of what I expect your example code to do doesn't make 
sense to you, then perhaps it's because your original problem description 
doesn't make sense to me. ;)

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How to design a search engine in Python?

2015-02-21 Thread Denis McMahon
On Sat, 21 Feb 2015 21:02:34 -0800, subhabangalore wrote:

 Thank you for your suggestion. But I was looking for a small tutorial of
 algorithm of the whole engine. I would try to check it build individual
 modules and integrate them. I was getting some in google and youtube,
 but I tried to consult you as I do not know whether they would be fine.
 I am trying your way, let me see how much I go. There are so many search
 algorithms in our popular data structure books, that is not an issue but
 how a search engine is getting done, I am thinking bit on that.

Presumably a search engine is simply a database of keyword - result, 
possibly with some scoring factor.

Calculating scoring factor is going to be fun.

Then of course result pages might have scoring factors too. What about a 
search with multiple keywords. Some result pages might match more than 
one keyword, so you might add their score for each keyword together to 
get the ranking in that enquiry for that page.

But then pages with lots and lots of different keywords might be low 
scoring, because searchers are looking for content, not pages of keywords.

Finally, What special, unique feature is your search engine going to have 
that makes it better than all the existing ones?

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: urgent help

2015-02-20 Thread Denis McMahon
On Fri, 20 Feb 2015 16:14:18 -0800, ms.isma222 wrote:


 sir what mean by the following errors:
 Traceback (most recent call last):
   File D:\My Documents\Desktop\scripts\WebMD\getWebMDExperts.py, line
   143, in module
 links = getExpertInfoLinks()
   File D:\My Documents\Desktop\scripts\WebMD\getWebMDExperts.py, line
   119, in getExpertInfoLinks
 fid = open(health-experts.htm,rb)

This line tried to open a file called health-experts.htm

 IOError: [Errno 2] No such file or directory: 'health-experts.htm'

This error says the file does not exist.

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: What behavior would you expect?

2015-02-19 Thread Denis McMahon
On Fri, 20 Feb 2015 02:08:49 +1100, Chris Angelico wrote:

 On Fri, Feb 20, 2015 at 1:16 AM, Denis McMahon
 denismfmcma...@gmail.com
 wrote:
 2. no files match the given pattern

 Return either None, 0, False or an empty string.

 In both cases, it is then a matter for the calling code to catch the
 exception or handle the return value appropriately.
 
 I'd avoid the empty string here, because absence of file should be
 very different from first file matching pattern. Imagine this naive
 code:

If your function documentation states that a failure to match any 
existing file returns an empty string (and if that's the case, then the 
documentation should do), then whoever calls the function should check 
the return value isn't an empty string.

There's two conflicting paradigms as it were here.

On the one hand, the return type of a function (when it returns, rather 
than raising an exception) should be consistent to itself, even if using 
a language where types are not declared.

On the other hand, a failure condition should clearly be a failure 
condition, which for a language that supports untyped functions means 
that we have the luxury of being able to return None / Nul[l] / NaN / 
False / 0 etc instead of a string / object / array / list / dictionary / 
mapping etc instead of raising an exception for the failure, and so we 
can try and handle the failure at the calling level without worrying 
about trapping exceptions.

I guess at the end of the day the programmer has to consider and 
determine which is most appropriate to his application, given the case.

As an aside, it's always a good idea to check that what you get looks 
like what you expected, whether it comes from a function call or as a 
data packet over the internet, before you start using it to do other 
things. ;)

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: What behavior would you expect?

2015-02-19 Thread Denis McMahon
On Wed, 18 Feb 2015 21:44:12 -0700, Jason Friedman wrote:

 My question is, what would be a reasonable behavior/result/return value
 if:

 1. /path/to/dir does not exist or is not readable 

Normally I'd say raise an exception. Whether you choose to use an 
existing exception (will trying to read a non existent dir raise one 
anyway?) or define your own is up to you. This condition would probably 
indicate an error in the data received by the function - you should be 
given a readable directory.

If (and only if) being called with an invalid directory is potentially 
valid, then you could respond to (1) the same as to (2).

 2. no files match the given pattern

Return either None, 0, False or an empty string.

In both cases, it is then a matter for the calling code to catch the 
exception or handle the return value appropriately.

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: urgent help

2015-02-19 Thread Denis McMahon
On Thu, 19 Feb 2015 04:00:50 -0500, Dave Angel wrote:

 On 02/19/2015 03:35 AM, ismaham...@gcuf.edu.pk wrote:
 this is the error in the following python code, can any one help me
 error{Traceback (most recent call last):
File C:\Python27\Scripts\BeOk\getBeOKExperts.py, line 6, in
module
  from BeautifulSoup import BeautifulSoup
 ImportError: No module named BeautifulSoup}

 #encoding=utf8 from codecs import open from collections import
 defaultdict import re

 from BeautifulSoup import BeautifulSoup

 When you can demonstrate a problem in a couple of lines of source code,
 why would you waste our bandwidth showing us dozens of unrelated  lines?
 
 Since the error says there's no module named BeautifulSoup, perhaps
 that's because you haven't installed BeautifulSoup.  it's not in the
 standard library.
 
 I've never used it, but a quick web search found me the page:
 
 http://www.crummy.com/software/BeautifulSoup/bs4/doc/

  *

  *

   

  And that seems to say the module is called bs4. 

   

  *

  *

It seems that the OP has failed to read your post, the documentation or 
the examples for the code he is using.

As a very strong hint, I have highlighted your fix for his main problem 
above with a few (ok, several) asterisks. Let's see if he can find it now.

If he can't, I don't understand why he bothered to ask for help, because 
I'm pretty sure you nailed the issue right there, and unless he's going 
to read the responses to his post to see the answers that are provided 
it's a bit stupid to post asking for help in the first place.

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: python implementation of a new integer encoding algorithm.

2015-02-19 Thread Denis McMahon
On Tue, 17 Feb 2015 03:22:47 -0800, janhein.vanderburg wrote:

 In http://optarbvalintenc.blogspot.nl/ I propose a new way to encode
 arbitrarily valued integers

I'm not quite sure I understand the problem that you're trying to solve 
with this.

If I want to transmit some arbitrarily huge integer value between two 
systems there are several ways to do it:

Numeric text - roughly 24 bits are used to carry 10 bits of value

Alphanumeric text - 8 bits are used to carry every 4 bits of value

A bit sequence of length n bits where 2^n  the value I wish to convey, 
providing that there is some mechanism by which the sender can tell the 
receiver the next n bits represent a binary integer. It might be 
desirable to pad the bit stream to a byte boundary. Assuming an 8 bit 
clean transmission path and a maximum padding of 7 bits, this is 
increasingly efficient as the integer being transmitted gets larger.

The thing is, for all practical purposes, any integer that is capable of 
being processed as an integer by a computer is probably already being 
stored in a binary format in a storage space of n bytes, where n is a 
power of 2. Very little additional processing should be needed to 
packetize those n bytes and transmit them.

Additionally, you're talking about efficiency and the need to optimise, 
but you're using a scripted language. If you need a highly efficient 
protocol to transfer binary numbers between two systems with minimum 
wasted bits and maximum cpu and memory efficiency, python really isn't 
the language in which to solve your problem.

Perhaps it's time to take a step back and redefine the problem a bit more 
clearly, because at the moment I'm not sure you're solution will ever 
solve anything that needs solving.

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Varable parsing error with python

2015-02-10 Thread Denis McMahon
On Tue, 10 Feb 2015 18:39:42 +1100, Chris Angelico wrote:

 On Tue, Feb 10, 2015 at 6:30 PM, OmPs torque.in...@gmail.com wrote:
 def _getPackgeVersion(xmlfile, p):
 package = str(p)
 if isinstance(fpmdict[application][package], list):
 for i in fpmdict[application][package]:
 if i[@name] == p:
 _pkgVersion = i[version]
 else:
 _pkgversion = fpmdict[application][package][version]
 return _pkgVersion
 
 One of your branches doesn't have a return statement in it, so Python
 just returns None. You may want to unindent that return statement one
 level.

Even if he unindents the return, it will still return None if it doesn't 
find an i such that i[@name] == p, as _pkgVersion only gets set if such 
a match is found.

Could this be cause by eg a string case match issue? Perhaps:

if i[@name].lower() == p.lower():

would be a better comparison to use?

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Indentation issues with python

2015-02-05 Thread Denis McMahon
On Wed, 04 Feb 2015 19:07:53 -0800, syed khalid wrote:

 I downloaded this code and am attempting to run it. I keep getting
 indentation error.

 class EventHubClient(object):
 def sendMessage(self,body,partition):eventHubHost =
 pac-ns.servicebus.windows.net
httpclient = _HTTPClient(service_instance=self)

 def sendMessage(self,body,partition):
 ^

 IndentationError: expected an indented block
 ***
 sasKeyName = SendPolicy
 sasKeyValue = erENqf/5wdWCNEbCA9NsDIRqd5MRKdkii07+wezl/NU=

class starts a class definition. def starts a function (or method) 
definition. The parser expects these definitions to be followed by one or 
more indented lines being the code of the class or function (method).

The following lines down to either a return or the next function 
definition line should probably all be indented.

eg:

class EventHubClient(object):

def sendMessage(self,body,partition):
eventHubHost = pac-ns.servicebus.windows.net
httpclient = _HTTPClient(service_instance=self)
sasKeyName = SendPolicy
sasKeyValue = erENqf/5wdWCNEbCA9NsDIRqd5MRKdkii07+wezl/NU=
.. more indented code should probably follow

Getting the indentation correct is absolutely critical in Python.

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


ANN: Lea 2.0.0 released

2015-02-03 Thread Pierre Denis
I am pleased to announce the release of Lea 2.0.0 !

What is Lea?

Lea is a Python package aiming at working with discrete probability
distributions in an intuitive way. It allows you to model a broad range of
random phenomenons, like dice throwing, coin tossing, gambling,
weather , etc. Lea is open-source (LGPL) and runs on Python 2 or 3.

What's new in Lea 2?

Here are the main new features, as of Lea 1.x :
- new methods: pmf, cdf, fromSeq, binom, bernoulli, interval, ...
- CPT (Conditional Probability Tables)
- Bayesian networks
- Markov chains
- *Leapp*, a small probabilistic programming language
- in-depth extension of wiki tutorials

Lea project page + documentation

 http://code.google.com/p/lea/

Download Lea (PyPI)
---
  http://pypi.python.org/pypi/lea http://pypi.python.org/pypi/lea/2.0.0-beta.2


With the hope that Lea can make your happiness less uncertain,

Pierre Denis
-- 
https://mail.python.org/mailman/listinfo/python-announce-list

Support the Python Software Foundation:
http://www.python.org/psf/donations/


[issue23346] shutil.rmtree doesn't work correctly on FreeBSD.

2015-01-29 Thread Denis Sukhonin

Denis Sukhonin added the comment:

It returns an integer.

 import os
 os.open('/tmp/test', os.O_RDONLY)
3

--

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue23346
___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue23346] shutil.rmtree doesn't work correctly on FreeBSD.

2015-01-29 Thread Denis Sukhonin

Denis Sukhonin added the comment:

No, it throws 22.

 os.listdir(os.open('/tmp/test', os.O_RDONLY))
Traceback (most recent call last):
  File stdin, line 1, in module
OSError: [Errno 22] Invalid argument

--

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue23346
___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue23346] shutil.rmtree doesn't work correctly on FreeBSD.

2015-01-29 Thread Denis Sukhonin

Denis Sukhonin added the comment:

The same problem.

 os.listdir(os.open('/tmp/test/', os.O_RDONLY))
Traceback (most recent call last):
  File stdin, line 1, in module
OSError: [Errno 22] Invalid argument

--

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue23346
___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue23346] shutil.rmtree doesn't work correctly on FreeBSD.

2015-01-28 Thread Denis Sukhonin

New submission from Denis Sukhonin:

shutil.rmtree doesn't work correctly on FreeBSD 9.1.

For example if I create a path /tmp/test and try to remove it, I get an 
exception:

 shutil.rmtree('/tmp/test')
Traceback (most recent call last):
  File stdin, line 1, in module
  File /usr/local/lib/python3.4/shutil.py, line 463, in rmtree
_rmtree_safe_fd(fd, path, onerror)
  File /usr/local/lib/python3.4/shutil.py, line 385, in _rmtree_safe_fd
onerror(os.listdir, path, sys.exc_info())
  File /usr/local/lib/python3.4/shutil.py, line 382, in _rmtree_safe_fd
names = os.listdir(topfd)
OSError: [Errno 22] Invalid argument: '/tmp/test'

---

shutil._use_fd_functions has value True. When I change it to False, the 
shutil.rmtree works perfecty.

Version info:
 print(sys.version)
3.4.2 (default, Dec 22 2014, 21:56:20) 
[GCC 4.2.1 20070831 patched [FreeBSD]]
 print(sys.platform)
freebsd9

$ uname -r
9.1-RELEASE

--
components: Library (Lib)
messages: 234946
nosy: negval
priority: normal
severity: normal
status: open
title: shutil.rmtree doesn't work correctly on FreeBSD.
type: behavior
versions: Python 3.4

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue23346
___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



Re: Python simple Code

2015-01-27 Thread Denis McMahon
On Tue, 27 Jan 2015 15:22:01 -0800, Salem Alqahtani wrote:

 I appreciate your answers and the output that I am expected from my
 simple code is the following:
 
 ['salem','Ali','sultan']
 ['salem','sultan','Ali']
 ['Ali','sultan','salem']
 ['Ali','salem','sultan']
 ['sultan','Ali','salem']
 ['sultan','salem','sultan']

A long way to do this is as follows (you've already been shown the short 
way using permutations)

words = ['salem','Ali','sultan']

for a in words:
for b in words:
 if b != a:
  for c in words:
  if c != a:
  if c != b:
  print [a, b, c]

Not quite so long:

words = ['salem','Ali','sultan']

for a in words:
for b in [x for x in words if x != a]:
for c in [x for x in words if x != a and x != b]:
print [a, b, c]

Observe that neither of these scale as elegantly as the permutations 
example already given.

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Python simple Code

2015-01-24 Thread Denis McMahon
On Sat, 24 Jan 2015 16:16:16 -0800, Salem Alqahtani wrote:

 import sys
 import array

 a=['salem','Ali','sultan']
 m = len(a)

 def Factorials(m):
 if m == 0:
 return 1
 else:
 print m
 return m * Factorials(m-1)

 def output():
 print a

 def main():
 print Factorials(m)
 output()

 main()

When I run the program, the output is:

3
2
1
6
['salem', 'Ali', 'sultan']

I'm not sure which output you think is wrong, or is not doing what you 
expect.

Observations:

a) There is no need to import array, you are only using a list.
b) If you try and index into a list using a number greater than the list 
length, you will receive an error IndexError: list index out of range, 
hence if you have a list where len(list) is x items you will never be 
able to use x! as an index to the list.
c) To refer to a single member of a list, use list[n] where n is the zero 
indexed element you wish to refer to.
d) Note point b. l[len(l)!] (or l[Factorials(len(l))]) will always fail.

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Concerning Dictionaries and += in Python 2.x

2015-01-21 Thread Denis McMahon
On Wed, 21 Jan 2015 09:43:31 +0100, Peter Otten wrote:

 There is also dict.from_keys()

See, I learned something too.

 The inner loop is not just inefficient for stock sold in large
 quantities,

Agreed, but as for:

 it will fail for stock sold by weight, volume etc.

I was trying to stay true to OPs original code and not introduce [too 
many] additional complications to his learning exercise.

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Random ALL CAPS posts on this group

2015-01-20 Thread Denis McMahon
On Mon, 19 Jan 2015 16:15:58 -0800, Luke Tomaneng wrote:

 Has anyone noticed these? There have been about three of them recently
 and they don't seem to have anything to do with Python at all. Does
 anyone know if there is a good reason they are here?

Abusive spam from idiots. I have a regex that simply ignores any posting 
with no lower case in the subject.

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: python traceroute

2015-01-20 Thread Denis McMahon
On Tue, 20 Jan 2015 19:37:26 -0800, Chandrakant Tiwari wrote:

 in the program below i want it to make it work  the same way as TRACERT 
 command.

As an observation, you're re-inventing a wheel that already works 
perfectly well, in that any failings of tracert tend to be more down to 
the way routers are configured to handle icmp than the tracert 
application itself. Unless you're doing this purely as an exercise in 
socket programming with python, it might be better to find a new problem 
to solve.

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Concerning Dictionaries and += in Python 2.x

2015-01-20 Thread Denis McMahon
On Mon, 19 Jan 2015 16:12:57 -0800, Luke Tomaneng wrote:

 I have been having a bit of trouble with the things mentioned in the
 title.

I've uploaded a slightly different approach to your code at:

http://www.sined.co.uk/tmp/shop.py.txt

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Attribute error

2015-01-18 Thread Denis McMahon
On Sun, 18 Jan 2015 20:50:49 +, Mahendra Prajapati wrote:

 Hello,
 I'm facing this problem with python class, while practising the python
 programming language.It creates an attribute error. I use windows 7 OS.
 i don't why.I just need to know why it gives such an error.please let me
 know.
 Regards

The python docs https://docs.python.org/2/library/exceptions.html say the 
following about AttributeError:

exception AttributeError

Raised when an attribute reference (see Attribute references) or 
assignment fails. (When an object does not support attribute references 
or attribute assignments at all, TypeError is raised.)

Given your description of the problem, the best guess I can make is that 
you are trying to reference a non existent attribute, possibly because 
you have mistyped the name of the attribute you are trying to access.

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: what would be the regular expression for null byte present in a string

2015-01-13 Thread Denis McMahon
On Tue, 13 Jan 2015 13:40:52 +, Shambhu Rajak wrote:

 I have a string that I get as an output of a command as:
 '\x01\x00\x00\x00\x00\x00\x00\x00\x0c\x00\x00\x0010232ae8944a\x02\x00
\x00\x00\x00\x00\x00\x00\n'
 
 I want to fetch '10232ae8944a' from the above string.
 
 I want to find a re pattern that could replace all the \x01..\x0z to be
 replace by empty string '',  so that I can get the desired portion of
 string
 
 Can anyone help me with a working regex for it.

What have you tried, and what was the result?

Regex isn't designed to work with byte strings.

 str = '\x01\x00\x00\x00\x00\x00\x00\x00\x0c\x00\x00\x0010232ae8944a
\x02\x00\x00\x00\x00\x00\x00\x00\n'

 str.replace('\x00','').replace('\x0c','').replace('\x01','').replace
('\x02','').replace('\n','')
'10232ae8944a'

This works for the specific example you gave, will your string ever 
contain unwanted characters apart from \x00, \x01, \x02, \x0c, \n, and is 
it ever possible for one of those to be in the wanted set?

 str[12:24]
'10232ae8944a'

This also works for the specific example you gave, is the data you want 
to extract always going to be at the same offset in the string, and of 
the same length?

 ''.join([str[x] for x in range(len(str)) if str[x] = ' ' and str[x] 
= '~'])
'10232ae8944a'

This also works for the specific example you gave, and is a way to remove 
non printing and 8bit characters from a string. Is this what you actually 
want to do?

 str.strip('\x00\x0c\x01\x02\n')
'10232ae8944a'

This also works for the specific example that you gave, it uses the strip 
function with a string of characters to be stripped, this will work as 
long as you can predefine all the characters to strip and none of the 
characters to strip is ever desired as part of the result.

So 4 different methods, each of which seems to do, in the case of the 
specific example you gave, exactly what you want.

However although I tried a few patterns, I don't seem to be able to 
create an re that will do the job.

eg:

 patt = re.compile(r'[0-9a-zA-Z]+')
 res = patt.match(str)
 res
 print res
None
 type(res)
type 'NoneType'

 patt = re.compile(r'[0-z]+')
 res = patt.match(str)
 res
 print res
None
 type(res)
type 'NoneType'
 

 patt = re.compile(r'[ -~]+')
 res = patt.match(str)
 res
 print res
None
 type(res)
type 'NoneType'
 

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: how can I create a class and decode/encode as json?

2015-01-13 Thread Denis McMahon
On Tue, 13 Jan 2015 08:17:18 -0800, robertchen117 wrote:

 I want to send Message to rabbitmq and receive from rabbitmq, message
 format is below.
 
 how can I create a class and decode/encode as json?

It may be easier to use dictionaries than classes.

 import json
 thing = {}
 thing[message] = {}
 thing[message][dateCreated] = 1417713299
 thing[message][operations] = []
 for i in range(3):
... bit = {}
... bit[sequence] = i
... bit[data] = blah blah blah
... thing[message][operations].append(bit)
... 
 json.dumps(thing)
'{message: {operations: [{data: blah blah blah, sequence: 0}, 
{data: blah blah blah, sequence: 1}, {data: blah blah blah, 
sequence: 2}], dateCreated: 1417713299}}'

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Generate jpg files using line length (pixels) and orientation (degrees)

2015-01-11 Thread Denis McMahon
On Sun, 11 Jan 2015 11:41:28 -0800, semeon.risom wrote:

 The code is working correctly. Thank you! The only change I had to make
 was referring to it as a float instead of an integer.
 
 The images are generating, however I'm noticing that it's making an
 image for every possible pair in each list (i.e. Image 1: a1 and b1;
 Image 2: a1 and b2; Image 3: a1 and b3) instead of an image for each
 row (e.g. Image 1: a1 and b1; Image 2: a2 and b2; Image 3: a3 and
 b3...).

Try these changes:

# before the csv reader, declare a single list
params = []

# in the csv reader, append each pair of params to the list as
# a tuple

for row in rdr:
params.append( ( int(row[0]), int(row[1]) ) )


# use the lists of tuples to generate one image per tuple

for item in params:
makeimg(item[0], item[1])

#

You could also skip the list generation entirely.

After the main function definition:

f = open(filename, 'r')
rdr = csv.reader(f)
for row in rdr:
makeimg(int(row[0]), int(row[1]))

Also please note that you only need to quote the bits of the post that 
you are replying to to give context, not the whole post.

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Few coding suggestions

2015-01-11 Thread Denis McMahon
On Sun, 11 Jan 2015 17:14:35 +0530, Ganesh Pal wrote:

 (a)  How do I modify the output to have an another column with a
 difference of 5 mins

I'm not sure I understand the problem you're trying to solve, and it 
seems to me that you are presenting your problem in terms of your partial 
solution.

Try stating the actual problem.

Some hints, based on my best guess of what you're actually trying to do.

If you want a program to execute every n minutes, the easiest way to do 
this is normally to use the cron scheduler to start your program every n 
minutes.

If you want to append the output of a program to an existing file, open 
the file in append mode.

You normally add lines to a file, not columns.

You my want to investigate various ways of serialising data inside a 
file, eg csv, json etc. Also things like date and time formats if this is 
some sort of log file.

It would however be much easier to help you with your problem if you 
stated the problem you're trying to solve, eg I wish to create a 
snapshot of process memory and cpu use every 5 minutes and send it to 
another server.

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Generate jpg files using line length (pixels) and orientation (degrees)

2015-01-10 Thread Denis McMahon
On Fri, 09 Jan 2015 09:49:25 -0800, semeon.risom wrote:

 Thank you for the help btw. I think I'm close to a solution, but I'm
 having issue feeding the coordinates from my csv file into the formula.
 
 This is the error I get:
 Traceback (most recent call last):
   File C:\Users\Owner\Desktop\Stimuli Generation\Coordinates\Generate_w
   corr.py, line 68, in module
 makeimg(length, orientation)
   File C:\Users\Owner\Desktop\Stimuli Generation\Coordinates\Generate_w
   corr.py, line 40, in makeimg
 orientation = orientation % 180
 TypeError: unsupported operand type(s) for %: 'list' and 'int'
 
 
 and here's the code:
 
 from PIL import Image, ImageDraw from numpy import math
 
 # import csv import csv f = open('C:\Users\Owner\DesktopStimuli
 Generation\Coordinates\file.csv', 'rb')
 rdr = csv.reader(f)
 f.seek(0)
 i = 0 a = []
 b = []
 for row in rdr:
 a.append(row[0]) 
 b.append(row[1])

This makes a and b both lists

Having read some other errors that you are having, you need to make sure 
that these items are numeric and not string data

for row in rdr:
a.append(int(row[0]))
b.append(int(row[1]))

 # using lists of values for length in [a]:
 for orientation in [b]:
 makeimg(length, orientation)

This puts list a inside another list, and puts list b inside another 
list, and then passes the whole of lists a and b in the first call to 
makeimg.

makeimg expects 2 integer parameters on each call, not two lists!

As you have already created lists, you don't need to wrap them inside 
another list.

# using lists of values 
for length in a:
for orientation in b:
makeimg(length, orientation)

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Generate jpg files using line length (pixels) and orientation (degrees)

2015-01-08 Thread Denis McMahon
On Thu, 08 Jan 2015 22:07:03 +, Denis McMahon wrote:

 On Thu, 08 Jan 2015 09:09:18 -0800, semeon.risom wrote:
 
 Simple question. I hope. .

To follow up, below is a solution to the problem you stated.

#!/usr/bin/python

import Image, ImageDraw, math

def makeimg(length, orientation):

Make an image file of a black 4 pixel wide line of defined length 
crossing and centered on a white background of 800 px square, save
as a png file identifying line length and orientation in the file 
name.
param length - pixels, length of the line
param orientation - degrees, orientation ccw of the line from +ve x 
axis
Files are saved in imgs subdir, this must already exist.
File name is image_lll_ooo.jpg
lll = length, ooo = orientation, both 0 padded to 3 digits


# check length is +ve and not greater than 800
if length  0:
length = length * -1
if length  800:
length = 800

# check orientation is positive in range 0 .. 179
while orientation  0:
orientation = orientation + 360
if orientation  179:
orientation = orientation % 180

# calculate radius in pixels and orientation in radians
radius = length / 2
orient = math.radians(orientation)

# calculate xy coords in image space of line end points
x1 = int(400 + (radius * math.cos(orient)))
y1 = int(400 - (radius * math.sin(orient)))
x2 = int(400 + (-radius * math.cos(orient)))
y2 = int(400 - (-radius * math.sin(orient)))

# create an image
img = Image.new('RGB', (800,800), 'rgb(255, 255, 255)')
# create a draw interface
draw = ImageDraw.Draw(img)

# draw the line on the image
draw.line([(x1, y1), (x2, y2)], fill='rgb(0, 0, 0)', width=4)

# determine file name, save image file
fn = 'imgs/image_{:03d}_{:03d}.jpg'.format(length,orientation)
img.save(fn)

# stepping through ranges of values
for length in range(100, 601, 100):
for orientation in range(0, 171, 10):
makeimg(length, orientation)

# using lists of values
for length in [50, 150, 250, 350, 450, 550, 650]:
for orientation in [0, 15, 40, 45, 60, 75, 90, 105, 120, 135, 150, 
165]:
makeimg(length, orientation)




-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Generate jpg files using line length (pixels) and orientation (degrees)

2015-01-08 Thread Denis McMahon
On Thu, 08 Jan 2015 09:09:18 -0800, semeon.risom wrote:

 Simple question. I hope. .

We just covered this in the PHP newsgroup where you were trying to use a 
PHP library to generate these images.

As your library code is written in PHP, I suggest you return to the 
discussion there unless you plan to rewrite your library in Python, and 
I'd point out now that the level of programming ability you've 
demonstrated so far in the PHP group does not bode well for you 
attempting to rewrite the PHP library code as Python!

You were given a complete PHP solution to your problem, showing different 
ways to loop through your variables.

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Why For Loop Skips the Last element?

2015-01-01 Thread Denis McMahon
On Thu, 01 Jan 2015 02:55:49 +0530, Thuruv V wrote:

 Hi all,
 
 Here's the list. .
 
 inlist = [Fossil Women's Natalie Stainless Steel Watch Brown (JR1385),
 'Balmer Swiss Made Veyron Mens Watch: Black Band/ Black Dial
 (62625241)',
 'Fortune NYC Ladies Quilted Dial Watch: Brown',
 'Jeanne Collection w/ Swarovski Elements Watch: Dark Purple Band
 (62623659)',
 'Swiss Legend Commander Chronograph: Watch Orange/Black
 (SL-10067-01-ORS)',
 'Debussy Ladies Watch: Brown/Gray/Silver 14070 - 62625292',
 '#2 Swiss Legend Commander Chronograph: Green (SL-10067-BB-017)',
 'Auguste Jaccard 3 Timezone Watch: Black Band/ Gray  Black Dial
 (62625184)'
 ]
 
 My code :
 i = 0 while i = len(inlist):
 if 'watch' in str(inlist[i]).lower() or 'watches' in
 str(inlist[i]).lower():
 if 'women' in str(inlist[i]).lower() or 'female' in
 str(inlist[i]).lower() or 'ladies' in str(inlist[i]).lower():
 print 'FEMale Watch', inlist.index(i),str(i)
 elif 'men' in str(inlist[i]).lower() or 'male' in
 str(inlist[i]).lower() or 'chronograph' in str(inlist[i]).lower():
 print 'Male Watch',inlist.index(i),str(i)
 i = next(inlist)

..^

If the indents are correct, i will only increment if watch or watches are 
found. Your last but 1 item doesn't match these strings (chronograph 
instead of watch).

It would still be better as others have posted to use a for loop.

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: suggestions for VIN parsing

2014-12-29 Thread Denis McMahon
On Sun, 28 Dec 2014 16:27:20 -0700, Vincent Davis wrote:

 On Fri, Dec 26, 2014 at 12:15 PM, Denis McMahon
 denismfmcma...@gmail.com
 wrote:
 
 Note, I think the 1981 model year ran KCA - DCA prefixes, not as shown
 on the website you quoted.

 ​Denis,
 Regarding the KCA - DCA prefixes, do you have a source as to why you
 think this?

Study the website carefully. Calculate the prefixes for the 1981 and 1982 
model years according to the table on the website.

K .. D would be the appropriate month prefixes for the 1981 model year, 
but if both the 1981 and 1982 model years used DA as a year prefix, there 
would be some prefixes that appeared twice, in the 1981 model year and 
the 1982 model year.

Which suggests to me that there's been a slip up somewhere.

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


ANN: Lea 2.0.0 (beta.2) released

2014-12-27 Thread Pierre Denis
I am pleased to announce that Lea 2.0.0 (beta.2) is released!

What is Lea?

Lea is a Python package aiming at working with discrete probability
distributions in an intuitive way. It allows you to model a broad range of
random phenomenons, like dice throwing, coin tossing, gambling, weather,
finance, etc. Lea is open-source (LGPL) and runs on Python 2 or 3.

What's new in Lea 2?

Here are the main new features, as of Lea 1.x :
- new methods: pmf, cdf, fromSeq, ...
- CPT (Conditional Probability Tables)
- Bayesian networks
- Markov chains
- *Leapp*, a small probabilistic programming language on top of Lea/Python
- in-depth extension of wiki tutorials
- new logo!

Lea project page + documentation

 http://code.google.com/p/lea/

Download Lea (PyPi)
---
 http://pypi.python.org/pypi/lea/2.0.0-beta.2


Hoping Lea could be helpful in this uncertain universe... !

Pierre Denis
-- 
https://mail.python.org/mailman/listinfo/python-announce-list

Support the Python Software Foundation:
http://www.python.org/psf/donations/


Re: smtplib not working as expected

2014-12-27 Thread Denis McMahon
On Sat, 27 Dec 2014 02:52:39 +, Juan Christian wrote:

 So, I changed the code how you said, but still not working.
 Traceback:
 
 reply: b'550 SMTP is available only with SSL or TLS connection
 enabled.\r\n'
 reply: retcode (550); Msg: b'SMTP is available only with SSL or TLS
 connection enabled.'

^^ have a guess what these messages in the traceback mean.

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: suggestions for VIN parsing

2014-12-26 Thread Denis McMahon
On Thu, 25 Dec 2014 17:02:33 -0700, Vincent Davis wrote:

 I would like to parse the VIN, frame and engine numbers found on this
 page (below).

First of all you need to define the number of different patterns that are 
possible:

eg:

H + 3-5 digits - twins Unit 350cc  500cc '57 - '69

3 (or more?) digits + N - twins Pre-Unit 500cc  650cc '50
3-5 digits + NA - twins Pre-Unit 500cc  650cc '51 - '52
4-6 digits - twins Pre-Unit 500cc  650cc '52 - '60
D + 3-5 digits - twins Pre-Unit 500cc  650cc '60 - '62

DU + 3-5 digits - twins Unit 650cc '63 - '69

etc etc etc

You need to define these closely enough so that there is no ambiguity 
between two different expressions.

Then you create regular expressions for each pattern, and test a given 
engine / frame number against each re in turn until you get a match.

You may then need to extract the digits and letters from the pattern to 
determine the actual month / year data. Here's an example algorithm:

if matches H + 3-5 digits:
get integer value of numeric part
if num = 101 and num = 760:
print Unit 350cc  500cc, 1957
if num = 761 and num = 5484:
print Unit 350cc  500cc, 1958
.
if matches DU + 3-5 digits:
get integer value of numeric part
if num = 101 and num = 5824:
print Unit 650cc, 1963
if num = 5825 and num = 13374:
print Unit 650cc, 1964

etc etc etc

Note, I think the 1981 model year ran KCA - DCA prefixes, not as shown on 
the website you quoted.

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: question on string object handling in Python 2.7.8

2014-12-25 Thread Denis McMahon
On Tue, 23 Dec 2014 20:28:30 -0500, Dave Tian wrote:

 Hi,
 
 There are 2 statements:
 A: a = ‘h’
 B: b = ‘hh’
 
 According to me understanding, A should be faster as characters would
 shortcut this 1-byte string ‘h’ without malloc; B should be slower than
 A as characters does not work for 2-byte string ‘hh’, which triggers the
 malloc. However, when I put A/B into a big loop and try to measure the
 performance using cProfile, B seems always faster than A.
 Testing code:
 for i in range(0, 1):
   a = ‘h’ #or b = ‘hh’
 Testing cmd: python -m cProfile test.py
 
 So what is wrong here? B has one more malloc than A but is faster than
 B?

Your understanding.

The first time through the loop, python creates a string object h or 
hh and creates a pointer (a or b) and assigns it to the string object.

The next range(1, 1) times through the loop, python re-assigns 
the existing pointer to the existing string object.

Maybe a 2 character string is faster to locate in the object table than a 
1 character string, so that in the 2 character case, the lookup is faster.

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Python re.search simple question

2014-12-08 Thread Denis McMahon
On Mon, 08 Dec 2014 12:22:37 +0530, Ganesh Pal wrote:

 pattern
 'Token-based migrations cannot be mixed with level-based: [prev 0 , now
 1]'

Because [] defines a character class in a regex, if you want literal 
[ and ] you need to escape them with backslash.

[prev 0 , now 1] - match any single character from the set prev0,now1 

\[prev 0 , now 1\] - match the actual text [prev 0 , now 1]

Try these:

re.search('[prev 0 , now 1]','p') # matches (p in prev0,now1 )

re.search('[prev 0 , now 1]','x') # doesn't match (x not in prev0,now1 )

re.search('\[prev 0 , now 1\]','p') # doesn't match

re.search('\[prev 0 , now 1\]','[prev 0 , now 1]') # matches

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Nested dictionaries from a list ?

2014-12-07 Thread Denis McMahon
On Sun, 07 Dec 2014 08:18:03 -0800, Wacky wrote:

 New to Python, so please go easy.
 I've a list of users, who have different profiles .

How are you getting on with this assignment / homework?

I have a solution I could post, but I thought I'd wait to see what your 
solution was first.

Here's a hint though, I defined the following functions to work on my 
profiles data:

def is_user(user):
def is_machine(machine):
def is_user_of_machine(user, machine):
def is_machine_of_user(user, machine):
def query_machines_of_user(user):
def query_machines():
def query_users_of_machine(machine):
def query_users():
def add_profile(user, machine, profile):
def get_profile(user, machine):
def remove_profile(user, machine):
def remove_user(user):

After defining the functions, I was able to add the following code:

add_profile('Tom', 'computerA', 'Profile101')
add_profile('Tom', 'computerB', 'Profile102')
add_profile('Tom', 'computerC', 'Profile103')
add_profile('Dick', 'computerA', 'Profile389')
add_profile('Dick', 'computerB', 'Profile390')
add_profile('Harry', 'computerA', 'Profile201')
add_profile('Harry', 'computerB', 'Profile202')
add_profile('Harry', 'computerC', 'Profile203')
add_profile('Harry', 'computerD', 'Profile204')

print 'The users are:', query_users()

print 'The machines are:', query_machines()

print 'Users of computerC are:', query_users_of_machine('computerC')

print 'Harry\'s profile on computerB is:', get_profile('Harry', 
'computerB')

print 'Tom uses the machines:', query_machines_of_user('Tom')

which generated the following output:

The users are: ['Harry', 'Dick', 'Tom']
The machines are: ['computerA', 'computerB', 'computerC', 'computerD']
Users of computerC are: ['Harry', 'Tom']
Harry's profile on computerB is: Profile202
Tom uses the machines: ['computerA', 'computerB', 'computerC']

Then I added functions to return all of a user's machines and profiles, 
and all of a machine's users and profiles.

def query_machine_profiles(user):
def query_user_profiles(machine):

So I could add things like:

print 'The user profiles on computerB are:', query_user_profiles
('computerB')

and get the result:

The user profiles on computerB are: {'Tom': 'Profile102', 'Dick': 
'Profile390', 'Harry': 'Profile202'}

By the way, my longest function definition used 7 lines of code, these 
are all fairly simple functions, and no list comprehensions.

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Nested dictionaries from a list ?

2014-12-07 Thread Denis McMahon
On Sun, 07 Dec 2014 12:01:26 -0500, Dave Angel wrote:

 On 12/07/2014 11:18 AM, Wacky wrote:

 I've a list of users 

 I haven't run this through the Python, so please forgive any typos.

 users = [ 
 mess = { 

users is redundant, as it's mess.keys()

maintaining a separate list of users and having the users as the keys in 
mess suggests redundancy, and the potential for errors if the two data 
items get out of synch. Better imo to just have the data in one place.

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Help needed

2014-11-30 Thread Denis McMahon
On Sat, 29 Nov 2014 11:35:18 -0800, Gautam R Bharadwaj wrote:

 Here is the code in python, this code arranges the alphabets in
 descending order and now I want to encode each alphabet with 0 and next
 alphabet with 1, then 00,01,10,11,000,001 and so on. Please help me with
 that.
 
 //
 //CODE
 
 from collections import defaultdict import string text ='intalks is an
 organization comprised of passionate
 students'.lower().translate(None,string.punctuation+' ')
 c = defaultdict(int)
 c.update({letter:0 for letter in string.lowercase[:26]})
 for letter in text:
 c[letter] += 1
 
 for letter,freq in sorted(c.iteritems(),key=lambda (l,f): (-f,l)):
 print freq, letter

If you can confirm that the following:

000111101100010110010011001101001111010101011001100100011110

is the output you want in terms of the original string encoded according 
to your encoding scheme, then your problem domain currently is two fold:

a) To write a function that generates the encoding
b) To apply the encoding to the original string

To achieve the former, I used a combination of determining a string 
length, converting a string to an integer using base 2, converting a 
number to a string in binary form, and generating arbitrary length 
strings of zeroes.

Not necessarily all done in the most pythonic of manners I must admit. 
Have you attempted anything to generate you string of encodings yet? 
Because until you show a good faith effort, you don't my solution to your 
homework problem for free.

To achieve the latter, I took the encodings and strung them together 
according to the letters they represented in the original string.

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: FW: Unexpexted behaviot of python operators on list

2014-11-25 Thread Denis McMahon
On Tue, 25 Nov 2014 12:20:26 +, Mark Lawrence wrote:

 a=[1,2,3]

binds a to the list [1,2,3]

 b=a

binds b to a

 b+=[4,5]

Changes existing b, which is also a

 x=[1,2,3]

binds x to the list [1,2,3]

 y=x

binds y to x

 y=y+[4,5]

Binds y to a new list which comprises previous y plus [4,5]

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Working with HTML5 documents

2014-11-20 Thread Denis McMahon
On Wed, 19 Nov 2014 13:43:17 -0800, Novocastrian_Nomad wrote:

 On Wednesday, November 19, 2014 2:08:27 PM UTC-7, Denis McMahon wrote:
 So what I'm looking for is a method to create an html5 document using
 dom manipulation, ie:
 
 doc = new htmldocument(doctype=HTML)
 html = new html5element(html)
 doc.appendChild(html)
 head = new html5element(body)
 html.appendChild(head)
 body = new html5element(body)
 html.appendChild(body)
 title = new html5element(title)
 txt = new textnode(This Is The Title)
 title.appendChild(txt)
 head.appendChild(title)
 para = new html5element(p)
 txt = new textnode(This is some text.)
 para.appendChild(txt)
 body.appendChild(para)
 
 print(doc.serialise())
 
 generates:
 
 !doctype HTMLhtmlheadtitleThis Is The Title/title/
 headbodypThis is some text./p/body/html
 
 I'm finding various mechanisms to generate the structure from an
 existing piece of html (eg html5lib, beautifulsoup etc) but I can't
 seem to find any mechanism to generate, manipulate and produce html5
 documents using this dom manipulation approach. Where should I be
 looking?

 Use a search engine (Google, DuckDuckGo etc) and search for 'python
 write html'

Surprise surprise, already tried that, can't find anything that holds the 
document in the sort of tree structure that I want to manipulate it in.

Everything there seems to assume I'll be creating a document serially, eg 
that I won't get to some point in the document and decide that I want to 
add an element earlier.

bs4 and html5lib will parse a document into a tree structure, but they're 
not so hot on manipulating the tree structure, eg adding and moving nodes.

Actually it looks like bs4 is going to be my best bet, although limited 
it does have most of what I'm looking for. I just need to start by giving 
it html/html to parse.

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Tag objects in Beautiful Soup

2014-11-20 Thread Denis McMahon
On Thu, 20 Nov 2014 06:31:08 -0800, Simon Evans wrote:

 Can anyone tell me where I am going wrong or where the text is wrong ?
 So far the given code has run okay, I have put to the console everything
 the text tells you to. Thank you for reading.
 Simon Evans

Having looked at the ebook, there seems to be an error in the book. 
Unfortunately I'm not 100% sure what the error is.

However, it may be that:

atag = soup_atag.a

is meant to be:

atag = soup.a

There are also errors in the html itself in the ebook, the href of each 
of the urls is quoted as href=' (mixing single and double quotes) 
and one of the urls has a semi-colon where a colon is expected, these 
seem to throw the parser.

These errors also appear in your html snippet:

html_atag = htmlbodypTest html a tag example/p

a href=http://www.packtpub.com'Home/a
^...^

a href=http;//www.packtpub.com/books'.Books/a
^^^

/body
/html

In addition to these errors in the source html, you seem to have replaced 
a '' with a '.' on the second anchor tag in the html.

a href=http;//www.packtpub.com/books'.Books/a
...^

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Working with HTML5 documents

2014-11-19 Thread Denis McMahon
So what I'm looking for is a method to create an html5 document using dom 
manipulation, ie:

doc = new htmldocument(doctype=HTML)
html = new html5element(html)
doc.appendChild(html)
head = new html5element(body)
html.appendChild(head)
body = new html5element(body)
html.appendChild(body)
title = new html5element(title)
txt = new textnode(This Is The Title)
title.appendChild(txt)
head.appendChild(title)
para = new html5element(p)
txt = new textnode(This is some text.)
para.appendChild(txt)
body.appendChild(para)

print(doc.serialise())

generates:

!doctype HTMLhtmlheadtitleThis Is The Title/title/
headbodypThis is some text./p/body/html

I'm finding various mechanisms to generate the structure from an existing 
piece of html (eg html5lib, beautifulsoup etc) but I can't seem to find 
any mechanism to generate, manipulate and produce html5 documents using 
this dom manipulation approach. Where should I be looking?

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Error when trying to open an image

2014-11-19 Thread Denis McMahon
On Mon, 17 Nov 2014 02:03:01 +0100, Abdul Abdul wrote:

 Thanks for your kind reply. Yes, it seemed it worked with an older
 version than 3.x
 
 I got the following output:
 
 Process finished with exit code 0
 
 So, what is the purpose of open() here?

*STOP TOP-POSTING! IT@S GETTING ANNOYING NOW!*

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: caught in the import web again

2014-11-15 Thread Denis McMahon
On Sat, 15 Nov 2014 22:52:33 +, Charles T. Smith wrote:

 Now, I'm getting these errors:
 
   ImportError: cannot import name ...
 
 and
 
   AttributeError: 'module' object has no attribute ...

It would be useful to know what you're actually trying to import and what 
the complete error messages are. For example, are these imports of code 
that you've written yourself, or part of the standard library modules, or 
third party modules.

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Curious function argument

2014-11-12 Thread Denis McMahon
On Wed, 12 Nov 2014 14:07:14 +0100, ast wrote:

[function def with mutable default parameter]

 I understand that the author wants to implement a global variable x . It
 would be better to write 'global x' inside the function.

It may not be the case that the purpose was to implement a global 
variable, but rather to illustrate what happens when you use a mutable 
default parameter.

 At first test() function call, it prints 0, that's OK.
 But at the second call, since we dont pass any argument to test(), x
 should be equal to its default value [0] (a single item list). But it
 seems that Python keeps the original object whose content has been
 changed to 1.

This is explained in the docs:

https://docs.python.org/3/reference/compound_stmts.html#function-
definitions

Default parameter values are evaluated from left to right *when the 
function definition is executed*[1]. This means that the expression is 
evaluated once, when the function is defined, and that the same “pre-
computed” value is used for each call. This is especially important to 
understand when a default parameter is a mutable object, such as a list 
or a dictionary: if the function modifies the object (e.g. by appending 
an item to a list), the default value is in effect modified.

[1] ie when the function is 'compiled', not each time it executes.

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Communicating with a PHP script (and pretending I'm a browser)

2014-11-11 Thread Denis McMahon
On Tue, 11 Nov 2014 10:48:41 -0500, Larry Martell wrote:

 Is there some way python can communicate like curl ... it needs to send
 the request string in the body of a POST request to the URL that will
 route to the PHP script and get the output back.

http://www.lmgtfy.com/?q=python+http+request

and perhaps

http://www.lmgtfy.com/?q=python+parse+html

Personally I think last time I wanted to do we scraping in python I used 
requests and beautifulsoup, but ymmv.

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: What is ?s here?

2014-11-11 Thread Denis McMahon
On Tue, 11 Nov 2014 01:37:21 -0800, satishmlmlml wrote:

 What does ?s do in the following piece of code?

It tells you to learn about regex.

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: What is \1 here?

2014-11-11 Thread Denis McMahon
On Tue, 11 Nov 2014 01:18:02 -0800, satishmlmlml wrote:

 What does \1 do in the following piece of code(fourth line)?

It tells you to learn about regex.

http://www.pcre.org/pcre.txt

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Python script that does batch find and replace in txt files

2014-11-11 Thread Denis McMahon
On Sun, 09 Nov 2014 11:58:49 -0800, Syed Khalid wrote:

 Python script that does batch find and replace in txt files Need a
 python script that opens all .txt files in a folder find replace/delete
 text and save files.

Sounds like you need sed, not python.

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Combining lists to dictionary

2014-11-11 Thread Denis McMahon
Hi

Given x,y are a lists of keys and value that I wish to combine to a 
dictionary, such that x[n] is the key for value y[n], which is preferred:

z = {a:b for (a,b) in zip(x,y)}
z = {x[n]:y[n] for n in range(min(len(x),len(y)))}

The zip feels more elegant, but it seems clunky to use the zip method to 
create a list of tuples just to split them up into key:value pairs. 
However the zip method handles the inequal length list problem. Granted 
it would probably be advisable to check that x and y are the same length 
before starting anyway.

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: I don't read docs and don't know how to use Google. What does the print function do?

2014-11-10 Thread Denis McMahon
On Mon, 10 Nov 2014 10:56:18 -0800, sohcahtoa82 wrote:

 ... I know software engineers
 make lots of money so I want to be one.

I hear that pretty boy male escorts can make even more money than 
software engineers.

They also don't need to learn how to program, which is something software 
engineers do need to do, so it sounds as if you'd be better off signing 
up with an escort agency.

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How do i reduce this to a single function - the code is largely similar, just a direction of search toggle.

2014-11-07 Thread Denis McMahon
On Fri, 07 Nov 2014 21:22:22 +0630, Veek M wrote:

 Veek M wrote:
 
 
 new_col = self.b[row].index('def') self.w.cursor = row,
 new_col
 
 new_col = self.b[row].rindex('def')
 self.w.cursor = row, new_col
 
 There's also the different methods index vs rindex.

yes, those fall under point 2 of my earlier post. something and 
something else would be the complete means of calculating the value to 
assign to variable.

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How do i reduce this to a single function - the code is largely similar, just a direction of search toggle.

2014-11-07 Thread Denis McMahon
On Fri, 07 Nov 2014 16:46:19 +0630, Veek M wrote:

(1) Pass a true or false parameter to the function as the direction of 
search toggle.

(2) replace the relevant assignments with something like:

variable = something if condition else something else

(3) Figuring out the while loop control is a bit trickier, the best I 
came up with was:

while direction and condition_a or (not direction) and condition_b

But I'm sure someone has something better

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


[issue22438] eventlet broke by python 2.7.x

2014-11-07 Thread Denis Bilenko

Denis Bilenko added the comment:

gevent's ssl support is also broken by 2.7.9.

https://github.com/gevent/gevent/issues/477

IMO, it is totally unexpected to have some API (even though it's undocumented 
and internal) removed in non-major release.

Even though both gevent and eventlet can be fixed, there still be combinations 
of versions that break (python = 2.7.9  gevent = 1.0.1)

Please put _ssl.sslwrap back. It would save a lot of people a lot of time. I 
don't mind fixing gevent not to use it, but there's nothing I can do about 
versions already released.

--
nosy: +Denis.Bilenko

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue22438
___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



Re: I need algorithm for my task

2014-11-05 Thread Denis McMahon
On Wed, 05 Nov 2014 03:58:33 -0800, lordvital21 wrote:

 I have line 'pythonpythonpyth'. How do I know which word is the
 foundation line?.
 Other examples:
 pythonpythonpyth is python DOLORIUMD is DOLORIUM HELLOLHELLO is
 HELLOL thewordword is thewordword
 
 I need to know whether the word in the text is repeated and get it. This
 will be the key.

Well, the way you describe it:

So first you want to check if the first letter is also the second letter
Then you want to check if the first 2 letters are also the 3rd and 4th
Then you want to check if the first 3 letters are also the 4th-6th
Then you want to check if the first 4 letters are also the 5th-8th

So generally you want to check if the first n letters are also the second 
n letters, increasing n by 1 at a time until you reach your terminating 
condition.

So what is your terminating condition? I can see two possibilities. You 
run out of letters in the second section, or you find a match.

Here are a few more hints to help get you started:

A string is a list of characters.
A list can be sliced.
You can measure the length of a list.
You can compare the lengths of two lists.
You can compare two lists.
You can get the length of a string.
The maximum length of a repeated word in a string can not be more than 
half the length of the string.

However, the examples you give do not match the way you describe it. The 
examples you give assume the first word ends when the letter that started 
it is found again.

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: [OFF-TOPIC] It is true that is impossible write in binary code, the lowest level of programming that you can write is in hex code?

2014-11-05 Thread Denis McMahon
On Tue, 04 Nov 2014 21:30:06 -0500, Dennis Lee Bieber wrote:

   If you have an old system with front-panel toggle switches, you 
set the
 switches for binary values, and then push the enter switch.

You've booted a PDP-8 then ;)

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: I need algorithm for my task

2014-11-05 Thread Denis McMahon
On Wed, 05 Nov 2014 18:49:01 +, MRAB wrote:

 On 2014-11-05 18:05, C@rlos wrote:
 I thing this work:

 stg='pythonpython'
 foundationline=stg[ 0:( stg [ 1: ].index( stg[ 0 ])+1 ) ]

 It doesn't work for the final example or barbaz.

I have two algorithms I've implemented.

Still not sure exactly which algorithm he wants though. The first one is 
as he describes, in that the word is only reported if it's repeated, else 
report the whole string.

The second algorithm reads up until the first letter is repeated, or 
reports the whole string if no repeat found.

I did see a third algorithm suggested, I should add that and see what 
happens.

OK, implemented the third algorithm (repeat first n chars of s int(n/len
(s))+1 times, truncate to len(s) and compare with s), I also added 
another test case, now my test cases are:

t = [pythonpythonpyth, DOLORIUMD, HELLOLHELLO, thewordword, 
barbaz, dibdibdobdibdibdob]

and my output is:

$ ./words.py

python DOLORIUMD HELLOLHELLO thewordword barbaz dib

python DOLORIUM HELLOL thewordword bar dib

python DOLORIUM HELLOL thewordword barbaz dibdibdob

$

I wonder which of these three is actually the algorithm the OP wants.

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: I need algorithm for my task

2014-11-05 Thread Denis McMahon
On Wed, 05 Nov 2014 18:49:01 +, MRAB wrote:

 It doesn't work for the final example or barbaz.

Oh, and we really need a private python homework answers list where we 
can discuss the most pythonic solution we can think of for all these 
homework / coursework questions without showing the solutions to the 
students.

I'm quite proud of a 2 line solution to the third algorithm that I 
implemented, although it might be considered as somewhat obfuscated code 
by some. ;)

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: I need algorithm for my task

2014-11-05 Thread Denis McMahon
On Thu, 06 Nov 2014 03:36:40 +, Denis McMahon wrote:

 On Wed, 05 Nov 2014 18:49:01 +, MRAB wrote:
 
 It doesn't work for the final example or barbaz.
 
 Oh, and we really need a private python homework answers list where we
 can discuss the most pythonic solution we can think of for all these
 homework / coursework questions without showing the solutions to the
 students.

 I'm quite proud of a 2 line solution to the third algorithm that I
 implemented, although it might be considered as somewhat obfuscated code
 by some. ;)

Even prouder of the 1 liner!

In fact I'm going to post it, because I think any student who can walk 
his instructor through how my one-liner works deserves the marks. Of 
course, any student who presents this as a solution and is unable to walk 
their instructor through it should be failed for stupidity and plagiarism!

t = [pythonpythonpyth, DOLORIUMD, HELLOLHELLO, thewordword, 
barbaz, dibdibdobdibdibdob]

def baseword(s):
find shortest sequence which repeats to generate s
return s[0:[.join([s[0:x]for k in range(int(len(s)/x)+1)])[0:len
(s)]for x in range(1,len(s)+1)].index(s)+1]

for w in t:

print(baseword(w))

p.s. I really want to be in the room when the instructor asks this 
student to come up in front of the class and explain how his solution 
works!

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: I need algorithm for my task

2014-11-05 Thread Denis McMahon
On Thu, 06 Nov 2014 15:14:05 +1100, Chris Angelico wrote:

 On Thu, Nov 6, 2014 at 3:00 PM, Denis McMahon denismfmcma...@gmail.com
 wrote:
 def baseword(s):
 find shortest sequence which repeats to generate s
 return s[0:[.join([s[0:x]for k in range(int(len(s)/x)+1)])[0:len
 (s)]for x in range(1,len(s)+1)].index(s)+1]
 
 That's hardly a PEP-8 compliant line, but I can help out a bit.
 
 return s[0:[(s[0:x]*(len(s)//x+1))[0:len(s)]for x in
 range(1,len(s)+1)].index(s)+1]
 
 That's still 83 characters without indentation, but it's close now.

l = len
r = range

but technically then it's no longer a one liner.

 I love the algorithm. Took me a bit of analysis (and inspection of
 partial results) to understand what your code's doing, but it's stupidly
 elegant and elegantly stupid.

:)

Well yes, building that list is a stupid way to solve the problem, but I 
can't see another way to do it in one line. It's an implementation of my 
algorithm 3 (which I think you described) but working from the other end 
as it were.

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: generating unique variable name via loops

2014-11-04 Thread Denis McMahon
On Tue, 04 Nov 2014 05:45:04 -0800, Fatih Güven wrote:

 4 Kasım 2014 Salı 15:19:20 UTC+2 tarihinde Veek M yazdı:
 Fatih Güven wrote:
 
  4 Kas?m 2014 Sal? 13:29:34 UTC+2 tarihinde Fatih Güven yazd?:
  I want to generate a unique variable name for list using python.
  
  list1=...
  list2=...
 
 for x in range(1,10):
 exec(list%d = [] % x)
 
 This is okay but i can't use the method .append for example
 list1.append(abc)

This is one solution using a dictionary of lists to maintain the name 
association. It may not be the best method. It may not be the best 
solution for you. It may not be the answer your instructor is looking 
for, and it contains deliberate syntax errors.

lists = {}

for fn in filenames
infile = open(fn, r)
lists[fn] = []
for line in infile
lists[fn].append(line)
infile.close()

If you have to ask how to do this sort of thing, you probably shouldn't 
be coding employee data processing systems anyway!

If this was a coding assignment for a course, you should have had 
sufficient instruction in the relevant algorithms and language features 
to be able to figure it out yourself.

In either case, what not explain what you tried, what you expected it to 
do, and what it actually did.


-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


<    1   2   3   4   5   6   7   >