Re: Style question -- plural of class name?
On Wed, 08 May 2013 16:20:48 -0400, Roy Smith wrote: > FooEntry is a class. How would you describe a list of these in a > docstring? > > "A list of FooEntries" > > "A list of FooEntrys" > > "A list of FooEntry's" > > "A list of FooEntry instances" > > The first one certainly sounds the best, but it seems wierd to change > the spelling of the class name to make it plural. I wouldn't use an apostrophe for pluralisation. The Normal pluralisation of FooEntry would be FooEntries. Who are you expecting to read the docstring? English majors, grammar nazis, wikipedia editors, programmers, or all 4? -- Denis McMahon, denismfmcma...@gmail.com -- http://mail.python.org/mailman/listinfo/python-list
Re: in need of some help regarding my rock paper scissors game
On Sun, 12 May 2013 20:33:44 +0100, Alex Norton wrote: > 'Traceback (most recent call last): File "C:\Users\Me\Desktop\testy.py", > line 174, in bWater.clicked.connect( water_clicked ) AttributeError: > 'int' > object has no attribute 'clicked'' appears when i run the module. It looks to me as if bWater is an integer value and doesn't have a .clicked attribute. Where is bWater assigned, and what is it assigned to? If you have a clickable "water" widget of some sort in your gui, what is the click handler for that widget defined as? -- Denis McMahon, denismfmcma...@gmail.com -- http://mail.python.org/mailman/listinfo/python-list
Re: A computer programmer, web developer and network admin resume
On Wed, 22 May 2013 01:15:27 +, i...@databaseprograms.biz wrote: > If you would like this in text format instead, please let me know. What if we don't want it at all? -- Denis McMahon, denismfmcma...@gmail.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Myth Busters: % "this old style of formatting will eventually be removed from the language"
On Tue, 21 May 2013 23:26:58 -0400, Ned Batchelder wrote: > On 5/21/2013 10:26 PM, Carlos Nepomuceno wrote: >> "Since str.format() is quite new, a lot of Python code still uses the % >> operator. However, because this old style of formatting will eventually >> be removed from the language, str.format() should generally be used." >> Is this tutorial outdated or this still an issue? > That tutorial is out of date. %-formatting isn't being removed. Indeed, removing %-formatting could break a substantial amount of live code, with potentially significant maintenance effort in the user community simply to make existing code work with the new interpreter. The effect of this on corporations using python code translates into "business risk", and the next step is "we can avoid the business risk by migrating our python scripts to some other language." For the designers and maintainers of any language to arbitrarily[1] (in the eyes of the user base) remove a widely used feature that would have a major effect on the user base could kill off a language, simply because many users will not want to take the risk of it happening again, even if they can easily automate the upgrade from removed obsolete language feature to new shiny language feature. [1] Some portion of the user base will always consider any such change that causes them headaches and additional effort as having been arbitrary, no matter how well the language designers and maintainers explain the need to break the old scripts. -- Denis McMahon, denismfmcma...@gmail.com -- http://mail.python.org/mailman/listinfo/python-list
Re: file I/O and arithmetic calculation
On Thu, 23 May 2013 01:13:19 +0900, Keira Wilson wrote: > I would appreciate if someone could write a simple python code for the > purpose below: Didn't have your data, so couldn't verify it completely, but try this: import re def v(s): l=len(s) t=0. for i in range(l): t=t+(abs(ord(s[i]))*1.) return t/(l*1.) for n in range(5): m="c:/test/"+str(n+1)+".txt" f=open(m,"r") d=[] t=0. for l in range(10): d=d+[re.findall(r"[0-9.eE+-]+",f.readline())] t=t+v(d[l][0]) f.close() c=t/10. if c==50.: t=0. for u in range(10): t=t+v(d[0][u]) r=t/10. print "%s C1: %f R1: %f"%(m,c,r) -- Denis McMahon, denismfmcma...@gmail.com -- http://mail.python.org/mailman/listinfo/python-list
Re: file I/O and arithmetic calculation
On Thu, 23 May 2013 07:17:58 -0700, Keira Wilson wrote: > Dear all who involved with responding to my question - Thank you so much > for your nice code which really helped me. Hold on a sec? Someone posted code that gave the correct answer to a homework question? -- Denis McMahon, denismfmcma...@gmail.com -- http://mail.python.org/mailman/listinfo/python-list
Re: How to create new python file with increament number, if doesn't exist?
On Mon, 27 May 2013 02:27:59 -0700, Avnesh Shakya wrote: > I want to create a new python file like 'data0.0.5', but if it is > already exist then it should create 'data0.0.6', if it's also exist > then next like 'data0.0.7'. I have done, but with range, please give > me suggestion so that I can do it with specifying range. Try and put your description into the sequence of instructions you want the computer follow. For this problem, my sequence of instructions would be: 1) Find the highest numbered existing file that matches the filename data0.0.[number] 2) Create a new file that is one number higher. Now the solution is easy. Find the list of filenames in the directory that match a suitable regular expression, take the numeric value of a substring of the filename for each file and find the highest, add one to it, then create the new file name. Something like the following (untested) with the relevant imports etc: nfn="data0.0."+str(max([int(f[8:])for f in os.listdir(p)if re.match ('^data0.0.[0-9]+$',f)])+1) -- Denis McMahon, denismfmcma...@gmail.com -- http://mail.python.org/mailman/listinfo/python-list
Re: how to compare two json file line by line using python?
On Sun, 26 May 2013 21:32:40 -0700, Avnesh Shakya wrote: >how to compare two json file line by line using python? Actually I am >doing it in this way.. Oh what a lot of homework you have today. Did you ever stop to think what the easiest way to compare two json datasets is? -- Denis McMahon, denismfmcma...@gmail.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Reading *.json from URL - json.loads() versus urllib.urlopen.readlines()
On Mon, 27 May 2013 14:29:38 -0700, Bryan Britten wrote: > Try to not sigh audibly as I ask what I'm sure are two asinine > questions. > > 1) How is this approach different from twtrDict = [json.loads(line) for > line in urllib.urlopen(urlStr)]? > > 2) How do I tell how many JSON objects are on each line? Your code at (1) creates a single list of all the json objects The code you replied to loaded each object, assumed you did something with it, and then over-wrote it with the next one. As for (2) - either inspection, or errors from the json parser. -- Denis McMahon, denismfmcma...@gmail.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Future standard GUI library
On Tue, 28 May 2013 08:21:25 +1000, Chris Angelico wrote: > I'll use XML when I have to, but if I'm inventing my own protocol, > nope. There are just too many quirks with it. How do you represent an > empty string named Foo? > > or equivalently > > How do you represent an empty list named Foo? The same way. How do you > represent an empty dict/mapping named Foo? Lemme look up my > documentation... ah, the same way. Does this seem right to > you? -- Denis McMahon, denismfmcma...@gmail.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Create a file in /etc/ as a non-root user
On Fri, 31 May 2013 02:12:58 -0700, BIBHU DAS wrote: > Any Idea how to create a file in /etc as non-root user?Can i use umask > or chmod...confused If you don't have root access, you probably shouldn't be trying to write in /etc. If you need to write in /etc, explain to the sysadmin why you need root access. -- Denis McMahon, denismfmcma...@gmail.com -- http://mail.python.org/mailman/listinfo/python-list
Re: AES 128 bits
On Tue, 04 Jun 2013 07:52:17 +0800, usman mjoda wrote: > Good day everyone, I need assistance for python codes of aes 128 bits > key that can be run on SAGE Application. Thanks google pycrypto -- Denis McMahon, denismfmcma...@gmail.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Redirecting to a third party site with injected HTML
On Sun, 09 Jun 2013 10:09:17 -0700, guytamir1 wrote: > i'm not really sure how to approach this problem.. > hints :) Let me restate the problem for you: You want to display a web page to a visitor that exists on a third party website, with some of your own html inserted into it. Setting aside the multitude of ethical, moral, legal and copyright issues, the only technical solution I can see that doesn't involve hacking the third party website is to scrape the third party website using eg curl, modify the html using your scripting environment of choice (I'll assume python) either using some form of dom manipulation or string manipulation, and then server the modified page to the visitor. so pycurl and pydom might be good places to start. Don't forget that you may need to rewrite urls in the scraped document for things such as anchors, images, css, javascript etc to point them back at the host server, or some script on your server that can obtain and serve the appropriate resources. Alternatively, how about displaying the third party website in an iframe within your own document? Although that's not really pythonic, just htmlic. -- Denis McMahon, denismfmcma...@gmail.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Sorting a set works, sorting a dictionary fails ?
On Mon, 10 Jun 2013 03:42:38 -0700, Νικόλαος Κούρας wrote: > for key in sorted( months.values() ): > print(''' >%s > ''' % (months[key], key) ) > == > > please tell me Uli why this dont work as expected to. Because inside the for loop, your value 'key' is an item from the sorted list of the values part of months. When you use months[key], you're trying to look up in months based on the value part, not the key part. Calling it key is confusing you. Try this: things = { "a":1, "b":3, "c":2 } for thing in sorted( things.values() ): print thing >> Prints 1, 2, 3 for thing in sorted( things.keys() ): print thing >> Prints a, b, c Now although things["b"] is a valid reference because "b" is a key in a key - value pair, things[3] is not a valid reference, because 3 is not a key in a key - value pair. -- Denis McMahon, denismfmcma...@gmail.com -- http://mail.python.org/mailman/listinfo/python-list
Re: A certainl part of an if() structure never gets executed.
On Tue, 11 Jun 2013 13:20:52 -0700, Νικόλαος Κούρας wrote: > The above if structure works correctly *only* if the user sumbits by > form: > > name, month, year or month, year > > If, he just enter a year in the form and sumbit then, i get no error, > but no results displayed back. > > Any ideas as to why this might happen? Yes, I know exactly why this is happening. It is for one of two reasons. You may determine which one using the following secret code which I stole from the illuminati in 1836: import random reason = { 1: "Input data is not as expected by coder", 2: "Flow control logic not performing as coder expects", 3: "Badger Badger Badger Badger Badger Badger Badger Badger Mushroom", 4: "Please try again", 5: "Snake", 6: "Grumpy cat says fix your own damn code", 7: "I'll be back" } print reason[ random.choice( reason.keys() ) ] Note - this only has a small chance of actually doing what you want (ie giving a possibly accurate answer), but it sounds as if that's a level of precision you're used to working with anyway. On a slightly more serious note, if you can't apply yourself to debugging a case of "the program logic isn't doing what I expect" for some value of program logic that you coded, that may be a hint that: a) you don't actually understand what the program logic is doing b) you shouldn't be writing logic so complex that you can't see how to debug it c) your logic is overly convoluted and complex d) all of the above So perhaps you need to scrub the logic altogether, and start again taking smaller steps. You could also perhaps do with a lesson in De Morgan's theorem: not a and not b and not c = not ( a or b or c ) not a or not b or not c = not ( a and b and c ) and sometimes the alternative form is easier to understand Now, looking at your code here are two important questions: (1) What is the initial values of name, month and year? (2) Which block is actually being executed? Bear in mind that if a branch other than one you expect to be executed is executing, the fail condition might not be what you think it is. Specifically, is it possible that the code is executing the wrong branch and tripping up when it tries to generate or perhaps execute the sql statement empty strings, or just not getting any result from the sql because of the empty strings? Hint - take the code from the current file, apply a liberal smattering of print statements, and test it for various values of month, year and name. def test(name, month, year): print "name, month, year ::", name, month, year if not re.search( '=', name ) and not re.search( '=', month ) and not re.search( '=', year ): print "branch 1" elif not re.search( '=', month ) and not re.search( '=', year ): print "branch 2" elif not re.search( '=', year ): print "branch 3" else: print "branch 4" # testing logic for 8 possible input conditions test("=", "=", "=") test("=", "=", "x") test("=", "x", "=") test("=", "x", "x") test("x", "=", "=") test("x", "=", "x") test("x", "x", "=") test("x", "x", "x") -- Denis McMahon, denismfmcma...@gmail.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Creating a Super Simple WWW Link, Copy, & Paste into Spreadsheet Program
On Thu, 13 Jun 2013 12:28:09 -0700, buford.lumbar wrote: > Hi, I'm new to Python. Would someone be able to write me and/or to show > me how to write a simple program that: > > 1-follows a hyperlink from MS Excel to the internet (one of many links > like this, http://www.zipdatamaps.com/76180, for e.g.) and then, > > 2-copies some data (a population number, e.g. 54195) and then, > > 3-pastes that data back into the same MS Excel spreadsheet, into the > adjacent cell. Why do you want to do this in python? I thought visual basic (or a variant thereof) was the preferred coding environment for such things in ms office? A quick google finds me vb code to download a url into a string - presumably once you've done that you can find the value you want to scrape into your spreadsheet. -- Denis McMahon, denismfmcma...@gmail.com -- http://mail.python.org/mailman/listinfo/python-list
Re: A certainl part of an if() structure never gets executed.
On Wed, 12 Jun 2013 11:54:25 +0300, Νικόλαος Κούρας wrote: > So, i must tell: > > for i, month in enumerate(months): > print(' %s ' % (i, month) ) > > to somehow return '==' instead of 0 but don't know how. You could test for (month == 0) instead of re.search('=', month)? Or you could try using "==" instead of i when i is 0 for i, month in enumerate(months): if i != 0: print(' %s ' % (i, month) ) else: print(' %s ' % ("==", month) ) But if you couldn't work either of these solutions out on your own, perhaps the really important question you need to be asking yourself right now is "should I even be trying to code this in python when my basic knowledge of python coding is so poor?" -- Denis McMahon, denismfmcma...@gmail.com -- http://mail.python.org/mailman/listinfo/python-list
Re: A few questiosn about encoding
On Fri, 14 Jun 2013 16:58:20 +0300, Nick the Gr33k wrote: > On 14/6/2013 1:14 μμ, Cameron Simpson wrote: >> Normally a character in a b'...' item represents the byte value >> matching the character's Unicode ordinal value. > The only thing that i didn't understood is this line. > First please tell me what is a byte value Seriously? You don't understand the term byte? And you're the support desk for a webhosting company? -- Denis McMahon, denismfmcma...@gmail.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Don't feed the troll...
On Fri, 14 Jun 2013 12:32:56 +0300, Nick the Gr33k wrote: > I'mm not trolling man, i just have hard time understanding why numbers > acts as strings. It depends on the context. -- Denis McMahon, denismfmcma...@gmail.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Eval of expr with 'or' and 'and' within
On Sat, 15 Jun 2013 10:04:41 +0300, Nick the Gr33k wrote: > I called my self 'Ferrous Cranus'(this is what a guy from a forum > initially called me for being hard-headed :-) ) because i'm indeed > hardheaded and if i believe that 1 thing should have worked in some way > i cant change my mind easily that it works in another fashon(only if the > counter-arguments are strong). Then you need to stop trying to write python code, because you refuse to accept how python works, and python is not going to change for you! -- Denis McMahon, denismfmcma...@gmail.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Pattern Search Regular Expression
On Sat, 15 Jun 2013 10:05:01 +, Steven D'Aprano wrote: > On Sat, 15 Jun 2013 02:42:55 -0700, subhabangalore wrote: > >> Dear Group, >> >> I am trying to search the following pattern in Python. >> >> I have following strings: >> >> (i)"In the ocean" (ii)"On the ocean" (iii) "By the ocean" (iv) "In >> this group" (v) "In this group" (vi) "By the new group" >>. >> >> I want to extract from the first word to the last word, where first >> word and last word are varying. >> >> I am looking to extract out: >> (i) the (ii) the (iii) the (iv) this (v) this (vi) the new >> . >> >> The problem may be handled by converting the string to list and then >> index of list. > > No need for a regular expression. > > py> sentence = "By the new group" > py> words = sentence.split() > py> words[1:-1] > ['the', 'new'] > > Does that help? I thought OP wanted: words[words[0],words[-1]] But that might be just my caffeine deprived misinterpretation of his terminology. -- Denis McMahon, denismfmcma...@gmail.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Pattern Search Regular Expression
On Sat, 15 Jun 2013 11:55:34 +0100, Mark Lawrence wrote: > >>> sentence = "By the new group" > >>> words = sentence.split() > >>> words[words[0],words[-1]] > Traceback (most recent call last): >File "", line 1, in > TypeError: list indices must be integers, not tuple > > So why would the OP want a TypeError? Or has caffeine deprivation > affected your typing skills? :) Yeah - that last: words[words[0],words[-1]] should probably have been: first_and_last = [words[0], words[-1]] or even: first_and_last = (words[0], words[-1]) Or even: first_and_last = [sentence.split()[i] for i in (0, -1)] middle = sentence.split()[1:-2] -- Denis McMahon, denismfmcma...@gmail.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Pattern Search Regular Expression
On Sat, 15 Jun 2013 13:41:21 +, Denis McMahon wrote: > first_and_last = [sentence.split()[i] for i in (0, -1)] middle = > sentence.split()[1:-2] Bugger! That last is actually: sentence.split()[1:-1] It just looks like a two. -- Denis McMahon, denismfmcma...@gmail.com -- http://mail.python.org/mailman/listinfo/python-list
Re: A certainl part of an if() structure never gets executed.
On Sat, 15 Jun 2013 19:18:53 +0300, Nick the Gr33k wrote: > In both situations we still have 2 memory units holding values, so hows > that different? Consider that each named variable is a pointer to a memory location that holds a value. This is one of the ways in that a typed compiled language and an untyped scripted language may differ in their treatment of data items (or variables). Consider the following C and Python code: C: int a, b; b = 6; a = b; In C, this places the numeric value 6 into the memory location identified by the variable "b", then copies the value from the location pointed to by "b" into the location pointed to by "a". b is a pointer to a memory location containing the value 6 a is a pointer to another memory location also containing the value 6 Python: b = 6 a = b In Python, this first puts the value 6 in in a memory location and points "b" at that memory location, then makes "a" point to the same memory location as "b" points to. b is a pointer to a memory location containing the value 6 a is a pointer to the same memory location Do you understand the difference? -- Denis McMahon, denismfmcma...@gmail.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Why 'files.py' does not print the filenames into a table format?
On Sat, 15 Jun 2013 22:38:38 +0300, Nick the Gr33k wrote: > PLEASE take a look, its not a huge code First, you need to start writing your code to less than 80 columns if you're going to keep posting it to usenet. I'm sure I'm not the only person who can't be bothered to unwrap it. Secondly, the code you posted only tells part of the story - it's obviously missing either relevant imports or defined functions or possibly both. Third, it would help to see examples of (a) what you expect it to generate, and (b) what it actually generates. You obviously have a web server available to you - you could put both code (just append .txt to the filename) and screenshots from your browser there with no difficulty at all and just include links. -- Denis McMahon, denismfmcma...@gmail.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Why 'files.py' does not print the filenames into a table format?
On Sun, 16 Jun 2013 11:35:12 +0300, Nick the Gr33k wrote: > TB behaves for me the same way. Any line > 80 chars gets a newline. Why > this is happening? Why not post up to 256 chars in a single line? Because this is usenet. Read the RFCs if you must know! -- Denis McMahon, denismfmcma...@gmail.com -- http://mail.python.org/mailman/listinfo/python-list
Re: A certainl part of an if() structure never gets executed.
On Sun, 16 Jun 2013 11:07:12 +0300, Nick the Gr33k wrote: > On 16/6/2013 9:32 πμ, Denis McMahon wrote: >> On Sat, 15 Jun 2013 19:18:53 +0300, Nick the Gr33k wrote: >> >>> In both situations we still have 2 memory units holding values, so >>> hows that different? >> >> Consider that each named variable is a pointer to a memory location >> that holds a value. This is one of the ways in that a typed compiled >> language and an untyped scripted language may differ in their treatment >> of data items (or variables). >> >> Consider the following C and Python code: >> >> C: >> >> int a, b; >> b = 6; >> a = b; >> >> In C, this places the numeric value 6 into the memory location >> identified by the variable "b", then copies the value from the location >> pointed to by "b" into the location pointed to by "a". >> >> b is a pointer to a memory location containing the value 6 a is a >> pointer to another memory location also containing the value 6 >> >> Python: >> >> b = 6 >> a = b >> >> In Python, this first puts the value 6 in in a memory location and >> points "b" at that memory location, then makes "a" point to the same >> memory location as "b" points to. >> >> b is a pointer to a memory location containing the value 6 a is a >> pointer to the same memory location >> >> Do you understand the difference? >> > Yes and thank you for explaining in detail to me. > So Python economies(saves) system's memory. Good job Python! No. Don't read that into it. For example, in Python a = 6 b = a c = 6 a and b point to one memory location that contains the value 6 c points to a different memory location that contains the value 6 Python doesn't point all the variables that have the same value at the same location. > A pointer = a variable that has as a value a memory address a variable = > a memory address that has as a value the actual value we want to store. These are really C terms, not Python terms. Stop thinking that C is behaving like Python. > Is this how the thing works? No. Python is an interpreted language. C is a compiled language. They present very different feature sets to the user. You need to understand this, and at the moment you're not doing so. -- Denis McMahon, denismfmcma...@gmail.com -- http://mail.python.org/mailman/listinfo/python-list
Re: A certainl part of an if() structure never gets executed.
On Sun, 16 Jun 2013 12:59:00 +0300, Nick the Gr33k wrote: > Whats the difference of "interpreting " to "compiling" ? OK, I give up! -- Denis McMahon, denismfmcma...@gmail.com -- http://mail.python.org/mailman/listinfo/python-list
Re: python game
On Wed, 19 Jun 2013 13:18:49 -0700, jacksonkemp1234 wrote: > windowSurface.blit(playerImage, player) > for bear in bears: > windowSurface.blit(bearImage, bear) Try changing this to draw the bears first, then the player. -- Denis McMahon, denismfmcma...@gmail.com -- http://mail.python.org/mailman/listinfo/python-list
Re: python game
On Wed, 19 Jun 2013 13:18:49 -0700, jacksonkemp1234 wrote: > if moveDown and player.right < WINDOW_WIDTH: > player.right += MOVE_SPEED Should this be moveRight instead of moveDown? -- Denis McMahon, denismfmcma...@gmail.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Need explanation of this error
On Mon, 01 Jul 2013 02:13:50 -0700, prerit86 wrote: > I'm new to Python and trying to run a already written code. Can someone > please explain the error below? And if possible, how do I resolve this? > ImportError: DLL load failed: The specified module could not be found. You're missing the dll that provides some function that you're trying to use. -- Denis McMahon, denismfmcma...@gmail.com -- http://mail.python.org/mailman/listinfo/python-list
Re: python adds an extra half space when reading from a string or list
On Mon, 01 Jul 2013 21:18:26 +0200, Antoon Pardon wrote: > I am not baiting Nikos. Your opinion, mine differs. > all I have done in the last two weeks that involves Nikos as a > subject is the "Don't feed the troll thread" Calling him a troll is baiting. Please stop. -- Denis McMahon, denismfmcma...@gmail.com -- http://mail.python.org/mailman/listinfo/python-list
Re: python adds an extra half space when reading from a string or list
On Mon, 01 Jul 2013 20:42:48 +0200, Antoon Pardon wrote: > How about the following comprimise. > Let me know what you think about this. How about you just ignore him. -- Denis McMahon, denismfmcma...@gmail.com -- http://mail.python.org/mailman/listinfo/python-list
Re: python adds an extra half space when reading from a string or list
On Tue, 02 Jul 2013 10:16:37 +0200, Antoon Pardon wrote: > I would like people to have that in mind when they try to tell others to > just ignore the behaviour that bothers them. Maybe it would help them to > be a bit more patient to those who have trouble following the advise. It's quite clear that you're more interested in having arguments and slinging insults than you are in discussing python. I'm here to discuss python. -- Denis McMahon, denismfmcma...@gmail.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Parsing Text file
On Tue, 02 Jul 2013 13:28:33 -0700, sas429s wrote: > Ok here is a snippet of the text file I have: > I hope this helps.. > . > Thanks for your help ok ... so you need to figure out how best to distinguish the filename, then loop through the file, remember each filename as you find it, and when you find lines containing your target text, print the current value of filename and the target text line. filenames might be distinguished by one or more of the following: They always start in column 0 and nothing else starts in column 0 They never contain spaces and all other lines contain spaces or are blank They always contain at least one / characters They always terminate with a . followed by one or more characters All the characters in them are lower case Then loop through the file in something like the following manner: open input file; open output file; for each line in input file: { if line is a filename: { thisfile = line; } elif line matches search term: { print thisfile in output file; print line in output file; } } close input file; close output file; (Note this is an algorithm written in a sort of pythonic manner, rather than actual python code - also because some newsreaders may break indenting etc, I've used ; as line terminators and {} to group blocks) -- Denis McMahon, denismfmcma...@gmail.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Python script help
On Tue, 30 Jul 2013 07:49:04 -0700, cool1574 wrote: > Hello, I am looking for a script that will be able to search an online > document (by giving the script the URL) and find all the downloadable > links in the document and then download them automatically. > I appreciate your help, Why use Python? Just: wget -m url -- Denis McMahon, denismfmcma...@gmail.com -- http://mail.python.org/mailman/listinfo/python-list
Re: datetime question
On Tue, 12 Nov 2013 12:47:58 +, Andy Lawton wrote: > (I think "Europe/Kiev" is Greece but I don't know) I suspect Nick is really in a coding sweatshop in "Asia/Mumbai" -- Denis McMahon, denismfmcma...@gmail.com -- https://mail.python.org/mailman/listinfo/python-list
Re: datetime question
On Tue, 12 Nov 2013 17:57:55 +0200, Ferrous Cranus wrote: > or perhaps by confiruing the timezone of the server to use Greece's > TimeZone by issuing a linux command? If you have that degreee of control over the server, yes, but UTC is always safer, because if you need to move your server to a different site (eg disaster recovery) UTC is still UTC. -- Denis McMahon, denismfmcma...@gmail.com -- https://mail.python.org/mailman/listinfo/python-list
Re: Chinese Zodiac - python project
On Tue, 12 Nov 2013 14:04:08 -0800, edmundicon wrote: > Greetings everyone! This is my first post on this forum :) > > TL;DR: I want to convert the gregorian years into Chinese years, and > deal with the fact that the Chinese new years are different each > gregorian year. If I manage to do that, I'll know which year the user is > born in Chinese years and can then give him a personal description based > upon that year! > > I started to learn Python programming language 2 months ago (noob), but > I like it and I feel like if I keep learning I might become a great > programmer one day! > > I recently started a small Python project in which my mission is to give > a personal description to a user based upon the year he / she is born in > the Chinese Zodiac and I have run into some trouble. For instance, if > someone is born on the 15'th January 1990, he is actually born 1989 > because the Chinese new year occurred on the 27:th January that year. > > I have a text file which shows when the Chinese new years in gregorian > years (normal years), starting from 1900-01-31 to 2007-02-18. It goes > like this: > 1900-1-31 1901-2-19 1902-2-08 1903-1-29 1904-2-16 1905-2-04 1906-1-25 > ...(and so on) > 2007-02-18 ( I can't see the logic behind this really) > > The Chinese calendar is divided into cycles of 60 years each, and each > year has a combination of an animal and an element. There are 12 animals > and 5 elements, the animals changes each year, and the elements every > other year. The current cycle was initiated in the year of 1984 which > was the year of the Wood Rat. The personal descriptions for each > combination has conveniently also been provided in text files. > > The animals are in this order: > > Rat Ox Tiger Rabbit Dragon Snake Horse Sheep Monkey Rooster Dog Boar > > And the elements are: > > Wood Fire Earth Metal Water > > I have already created a modulus method which takes the input year (the > gregorian year you were born) and gives you an element and an animal, > for example if you type "1990" you are given Metal Horse. The problem I > now have is to convert the gregorian years into Chinese years, and deal > with the fact that the Chinese new years are different each gregorian > year. If I manage to do that, I'll know which year the user is born in > Chinese years and can then give him a personal description based upon > that year! > > Any advice will be greatly appreciated! Have a nice day :) Here is one suggestion Write a function to convert a gregorian date into the number of days since 1st January 1900 (we'll call 1st january 1900 your epoch). You will need to take leap years into account. Convert the users date of birth using this function. Convert your chinese new year dates using this function. You now have the simple task of comparing the users date of birth as daynumber_since_epoch with the start date of each chinese year as daynumber_since_epoch. You may wish to create a list of tuples where each tuple has start_day, end_day, year_name: years = [(0,30,"stone pig"),(31,414,"stone weasel") ... ] You should be able to automate creating this list. You could then search through the list of tuples with a function such as: yearname( birthdate ): foreach thing in years if birthdate is in the range specified by the thing return the yearname from the thing return "constipated program" (this is obviously not written as python code, you have to do that bit yourself) -- Denis McMahon, denismfmcma...@gmail.com -- https://mail.python.org/mailman/listinfo/python-list
Re: Some python newb help please?
On Tue, 12 Nov 2013 14:14:42 -0800, lrwarren94 wrote: > http://pastebin.com/6QZTvx6Z Work through your code very very carefully. You're doing something in each if branch that you probably only want to do once in each execution of the while loop. If you can't figure it out, I'll post a corrected version next week. -- Denis McMahon, denismfmcma...@gmail.com -- https://mail.python.org/mailman/listinfo/python-list
Re: Chinese Zodiac - python project
On Wed, 13 Nov 2013 16:44:03 -0800, edmundicon wrote: > Den tisdagen den 12:e november 2013 kl. 23:50:03 UTC+1 skrev Denis > McMahon: >> On Tue, 12 Nov 2013 14:04:08 -0800, edmundicon wrote: >> >> >> >> > Greetings everyone! This is my first post on this forum :) >> >> >> > >> > TL;DR: I want to convert the gregorian years into Chinese years, and >> >> > deal with the fact that the Chinese new years are different each >> >> > gregorian year. If I manage to do that, I'll know which year the user >> > is >> >> > born in Chinese years and can then give him a personal description >> > based >> >> > upon that year! >> >> >> > >> > I started to learn Python programming language 2 months ago (noob), >> > but >> >> > I like it and I feel like if I keep learning I might become a great >> >> > programmer one day! >> >> >> > >> > I recently started a small Python project in which my mission is to >> > give >> >> > a personal description to a user based upon the year he / she is born >> > in >> >> > the Chinese Zodiac and I have run into some trouble. For instance, if >> >> > someone is born on the 15'th January 1990, he is actually born 1989 >> >> > because the Chinese new year occurred on the 27:th January that year. >> >> >> > >> > I have a text file which shows when the Chinese new years in >> > gregorian >> >> > years (normal years), starting from 1900-01-31 to 2007-02-18. It goes >> >> > like this: >> >> > 1900-1-31 1901-2-19 1902-2-08 1903-1-29 1904-2-16 1905-2-04 1906-1-25 >> >> > ...(and so on) >> >> > 2007-02-18 ( I can't see the logic behind this really) >> >> >> > >> > The Chinese calendar is divided into cycles of 60 years each, and >> > each >> >> > year has a combination of an animal and an element. There are 12 >> > animals >> >> > and 5 elements, the animals changes each year, and the elements every >> >> > other year. The current cycle was initiated in the year of 1984 which >> >> > was the year of the Wood Rat. The personal descriptions for each >> >> > combination has conveniently also been provided in text files. >> >> >> > >> > The animals are in this order: >> >> >> > >> > Rat Ox Tiger Rabbit Dragon Snake Horse Sheep Monkey Rooster Dog Boar >> >> >> > >> > And the elements are: >> >> >> > >> > Wood Fire Earth Metal Water >> >> >> > >> > I have already created a modulus method which takes the input year >> > (the >> >> > gregorian year you were born) and gives you an element and an animal, >> >> > for example if you type "1990" you are given Metal Horse. The problem >> > I >> >> > now have is to convert the gregorian years into Chinese years, and >> > deal >> >> > with the fact that the Chinese new years are different each gregorian >> >> > year. If I manage to do that, I'll know which year the user is born >> > in >> >> > Chinese years and can then give him a personal description based upon >> >> > that year! >> >> >> > >> > Any advice will be greatly appreciated! Have a nice day :) >> >> >> >> Here is one suggestion >> >> >> >> Write a function to convert a gregorian date into the number of days >> >> since 1st January 1900 (we'll call 1st january 1900 your epoch). You >> will >> >> need to take leap years into account. >> >> >> >> Convert the users date of birth using this function. >> >> >> >> Convert your chinese new year dates using this function. >> >> >> >> You now have the simple task of comparing the users date of birth as >> >> daynumber_since_epoch with the start date of each chinese year as >> >> daynumber_since_epoch. >> >> >> >> You may wish to create a list of tuples where each tuple has start_day, >> >> end_day, year_name: >> >> >> >> years = [(0,30,"stone pig"),(31,414,"stone weasel") ... ] >> >> >> >> You shou
Re: Trying tcompile an use the Python 3.4a
On Wed, 13 Nov 2013 16:17:22 +0200, Ferrous Cranus wrote: > root@secure [/home/nikos/www/cgi-bin]# python3 -V Python 3.4.0a4 Let me just check. Nobody is so stupid as to run alpha software on a production server[1] are they? [1] In this context, "production server" means any system facing the public internet upon which python code is executed in response to inputs from the public internet. -- Denis McMahon, denismfmcma...@gmail.com -- https://mail.python.org/mailman/listinfo/python-list
Re: understanding someone else's program
On Fri, 15 Nov 2013 03:05:04 -0800, C. Ng wrote: > Hi all, > > Please suggest how I can understand someone else's program where - > documentation is sparse - in function A, there will be calls to function > B, C, D and in those functions will be calls to functions R,S,T > and so on so forth... making it difficult to trace what happens to a > certain variable > > Am using ERIC4 IDE. You just have to work through it working out what each line does. Start with the inputs and give them sensible names, after all you presumably know where they come from and what they represent. Then you can see what operations are being performed on the input data, and presumably if you have enough knowledge in any relevant fields, may be able to determine that, for example, when the input 'x' is actually a temp in fahrenheit, then the math operation 'x=(x-32)*5/9' is really "convert temp from fahrenheit to centigrade". As you do this add relevant comments to the code. Eventually you'll have code with sensible variable names and comments that hopefully describe what it does. -- Denis McMahon, denismfmcma...@gmail.com -- https://mail.python.org/mailman/listinfo/python-list
Re: Question regarding 2 modules installed via 'pip'
On Sat, 16 Nov 2013 17:49:17 +0100, YBM wrote: > Le 16.11.2013 16:43, Ferrous Cranus a écrit : >> root@secure [~]# which python3 /usr/bin/python3 >> root@secure [~]# cd /usr/bin/python3 -bash: cd: /usr/bin/python3: Not a >> directory >> root@secure [~]# which pip /usr/bin/pip >> root@secure [~]# cd /usr/bin/pip -bash: cd: /usr/bin/pip: Not a >> directory >> WHAT THE FUCK IS GOING ON WITH THIS DAMN CentOS 6.4? >> WHY CANT I JUST CD INTO HESE DAMN FOLDERS? > What don't you understand in what bash told you with "Not a directory" ? He doesn't understand error messages until he's posted them on usenet and had them explained to him. I think his default state of mind is "I'm perfect, therefore I can't have made a mistake, so the software must be broken." Then he posts the error messages here and we all laugh at his ineptitude. I would answer his question, but I foreswore helping him days ago now, you just get too much abuse because (in his opinion) your answer includes excessive whitespace. -- Denis McMahon, denismfmcma...@gmail.com -- https://mail.python.org/mailman/listinfo/python-list
Re: Newbie - Trying to Help a Friend
On Tue, 19 Nov 2013 11:27:08 -0800, bradleybooth12345 wrote: > On Tuesday, November 19, 2013 6:40:18 PM UTC, bradleyb...@gmail.com > wrote: >> "Write a program that calculates how many positive integers less than N >> are not divisible by 2,3 or 5. >> "The collatz process . >> Any help would be appreciated > Think they just needed a starting point really to be honest as they > can't get there head round it. First of all there seems to be two problems, not 1. Here are some steps for each of the calculations. Any resemblance of these steps to actual program code is due to my not bothering to obfuscate the statement and function names more than I did. 1) Find all the numbers less than n that are not divisible by a, b, or c. ask the user for x; assign the value 0 to some other variable i; while i is not greater than than x do the following [ if i is not divisible by a and i is not divisible by b and i is not divisible by c then display i to the user; add 1 to i; ] 2) Find the collatz sequence for x. ask the user for initial x; while x is not 1 { if x is divisible by 2 [ new x = perform even number collatz math on x; ] otherwise [ new x = perform odd number collatz math on x; ] display new x to the user; } -- Denis McMahon, denismfmcma...@gmail.com -- https://mail.python.org/mailman/listinfo/python-list
Re: Got a Doubt ! Wanting for your Help ! Plz make it ASAP !
On Fri, 22 Nov 2013 18:22:29 +0530, Bharath Kummar wrote: > Could you please help me with my current research ? Am implementing the > concept in python language. > My doubts are : > 1) Is it possible to Retrieve the address of a variable in python ? > 2) Is it possible to Delete the Address of the Variable and create a > new dynamic address inside the compiler/interpreter itself ? > 3) Is it easy to find the Binary equivalence of a given Alphanumeric > String ? > 4) Is it possible to count the number of 1's in the Binary equivalence > ? > Could you PLEASE provide me with the codes (codes only for the asked > queries) ? The codes are: 1) 7373a28109a7c4473a475b2137aa92d5 2) f2fae9a4ad5ded75e4d8ac34b90d5c9c 3) 935544894ca6ad7239e0df048b9ec3e5 4) b1bc9942d029a4a67e4b368a1ff8d883 Please contact your local government eavesdropping agency for assistance on decoding the codes. -- Denis McMahon, denismfmcma...@gmail.com -- https://mail.python.org/mailman/listinfo/python-list
Re: Newbie - Trying to Help a Friend
On Wed, 20 Nov 2013 11:38:14 +, Duncan Booth wrote: > Denis McMahon wrote: >> 1) Find all the numbers less than n that are not divisible by a, b, or >> c. >> ask the user for x; >> assign the value 0 to some other variable i; >> while i is not greater than than x do the following [ >> if i is not divisible by a and i is not divisible by b and i is not >> divisible by c then display i to the user; >> add 1 to i; >> ] > The question didn't ask to find all the numbers, it asked to count how > many there are. My post was intended as a demonstration of how you can convert a problem into a sequence of steps that can then be programmed into a computer. Any resemblance to the posted question may have been accidental. -- Denis McMahon, denismfmcma...@gmail.com -- https://mail.python.org/mailman/listinfo/python-list
Re: Got a Doubt ! Wanting for your Help ! Plz make it ASAP !
On Sat, 23 Nov 2013 02:18:03 +, Steven D'Aprano wrote: > On Sat, 23 Nov 2013 01:55:44 +0000, Denis McMahon wrote: >> On Fri, 22 Nov 2013 18:22:29 +0530, Bharath Kummar wrote: >>> Could you PLEASE provide me with the codes (codes only for the asked >>> queries) ? >> The codes are: >> 1) 7373a28109a7c4473a475b2137aa92d5 2) f2fae9a4ad5ded75e4d8ac34b90d5c9c >> 3) 935544894ca6ad7239e0df048b9ec3e5 4) b1bc9942d029a4a67e4b368a1ff8d883 >> Please contact your local government eavesdropping agency for >> assistance on decoding the codes. > I'm not an expert on Indian English, but I understand that in that > dialect it is grammatically correct to say "the codes", just as in UK > and US English it is grammatically correct to say "the programs". Sorry, I should obviously have replied to the OP as follows: We don't write your python code for you, we help you to fix your python code. Please post the code you have developed to solve your problem, and explain what you expect it to do, and then we will try and explain to you why it's doing what it does instead of what you want it to. -- Denis McMahon, denismfmcma...@gmail.com -- https://mail.python.org/mailman/listinfo/python-list
Re: Cracking hashes with Python
On Tue, 26 Nov 2013 02:30:03 -0800, TheRandomPast wrote: >>for value in values: > print value ..^^^ so change this to: crackMD5Hash( value ) >> import hashlib >> def crackMD5Hash(): Nah def crackMD5Hash( hash ): print "cracking hash:", hash some code goes here ... print "original string was:", result Algorithms for cracking md5 hashes is not a python topic, but rather a cryptography topic. When you find an algorithm to use, then if you have trouble converting it into code we may be able to help with that bit. -- Denis McMahon, denismfmcma...@gmail.com -- https://mail.python.org/mailman/listinfo/python-list
Re: Cracking hashes with Python
On Tue, 26 Nov 2013 14:18:33 +, TheRandomPast . wrote: > - Teacher has taught us nothing about MD5. This being the script he > wanted us to write came as a surprise to everyone but complaints about > projects are constantly ignored. This particular teacher is complained > about for this reason every year but nothing ever changes. ok forget about python for a minute. write down the steps you need to follow to solve the problem in plain english. 1) Get the list of hashes from a website 2) Brute force the hashes using a dictionary But 2 needs a dictionary: 1) Load a dictionary 2) Get the list of hashes from a website 3) Brute force the hashes using a dictionary So you need a function to load the dictionary (from a local file?), a function to get the list of hashes, a function to try and brute force a hash using the dictionary, and some logic to tie it all together. global data: list of words, list of hashes load_dictionary ( file ) read the words from the file get_hashes( url ) read the hashes from the url brute_force() do every hash in hashes do every word in words if md5( word ) is hash solved this hash! load_dictionary( "dictionary file name" ) get_hashes( "http://www.website.tld/path/file.ext"; ) brute_force() -- Denis McMahon, denismfmcma...@gmail.com -- https://mail.python.org/mailman/listinfo/python-list
Re: Cracking hashes with Python
On Wed, 27 Nov 2013 12:40:41 +, TheRandomPast . wrote: > And dictionary is working, as is the brute force however the issue I > have having is with my chklength() as no matter how many characters I > input it skips the !=32 and goes straight to asking the user to chose > either Brute Force or Dictionary. I want an error to be shown if the > hash is less than or more than 32 characters but at present this > chklength() doesn't work as I thought it would. > > Can anyone point out an obvious error that I am missing? Yes - you don't need to type in the hashes by hand at all. You have code to read the hashes from a web page as strings. Read the hashes from the web into a list of hashes. Read the dictionary file into a list of words. for each word in the dictionary compare the hashed word with the list of hashes, and if you get a match, output the word and the hash. If you have code to get the hash strings from the web url, it is nuts to output them to the screen and then type them back in to the cracking program when you can just add the code to get them from the web to the cracking program. -- Denis McMahon, denismfmcma...@gmail.com -- https://mail.python.org/mailman/listinfo/python-list
Re: The input and output is as wanted, but why error?
On Tue, 03 Dec 2013 07:48:43 -0800, geezle86 wrote: > I am trying to solve this problem: > > http://codeforces.com/problemset/problem/71/A That's not a problem, it's a url. > The input and output is as wanted, but my answer keep rejected, here is > my source code http://txt.do/1smv That's not source code, it's a url. > Please, I need help. As my newsreader isn't a web browser, I can't help. Sorry. -- Denis McMahon, denismfmcma...@gmail.com -- https://mail.python.org/mailman/listinfo/python-list
Re: interactive help on the base object
On Sun, 08 Dec 2013 23:48:57 +, Mark Lawrence wrote: >>> >>> help(object) >>> Help on class object in module builtins: >>> >>> class object >>> | The most base type >> '''The default top superclass for all Python classes. >> Its methods are inherited by all classes unless overriden. >> ''' > Terry's suggestion above remains odds on favourite on the grounds that > there have been no other suggestions. I'll give it another day, then > raise a tracker issue, unless the overwhelming smell of pot that has > been drifting around this thread knocks me unconscious. """ The root class for all Python classes. Its methods are inherited by all classes unless overriden. """ -- Denis McMahon, denismfmcma...@gmail.com -- https://mail.python.org/mailman/listinfo/python-list
Re: Experiences/guidance on teaching Python as a first programming language
On Tue, 10 Dec 2013 20:35:47 -0500, Dennis Lee Bieber wrote: > On Tue, 10 Dec 2013 18:25:48 +1300, Gregory Ewing > declaimed the following: >>That's like saying that when teaching woodwork we shouldn't let people >>use hammers, we should make them use rocks to bang nails in, because it >>will make them better carpenters in the long run. > NAILS > Nails were verboten in my high school wood working class... > We used dowels and glue; chisels to carve dove-tails; etc. We were allowed to use screws, but they had to be brass, not steel, we had to drill appropriate clearance and pilot holes, and countersink where appropriate. And god help you if you deformed the slot in a brass screw head by over tightening - I think that may have been why they made us use brass ones only, so that such damage was easier to spot and more likely to happen. And yes, I can dovetail, mortise and tenon, dowel etc etc etc. -- Denis McMahon, denismfmcma...@gmail.com -- https://mail.python.org/mailman/listinfo/python-list
Re: min max from tuples in list
On Wed, 11 Dec 2013 23:25:53 -0800, Robert Voigtländer wrote: > I have a list like this: > > a = [(52, 193), .. (36, 133)] # iterate over the list of tuples # creates a dictionary n0:[n1a, n1b, n1c ... ] # from tuples (n0,n1a), (n0,n1b), (n0,n1c) ... b = {} for x in a: if x[0] in b: pass else: b[x[0]] = [] if x[1] not in b[x[0]]: b[x[0]].append( x[1] ) # iterate over the dictionary # create the list of result tuples (n0, n1min, n1max) . c = [ (x, min(y), max(y) ) for x,y in b.iteritems() ] print c There may be a more efficient test for whether b[x[0]] eists than trapping keyError. -- Denis McMahon, denismfmcma...@gmail.com -- https://mail.python.org/mailman/listinfo/python-list
Re: accessing a page which request an openID authentication
On Fri, 13 Dec 2013 02:32:49 -0800, uni.mail.2014 wrote: > I have a page that request an openID authentication And your Python question is? -- Denis McMahon, denismfmcma...@gmail.com -- https://mail.python.org/mailman/listinfo/python-list
Re: want to run proxy in python
On Fri, 13 Dec 2013 03:39:44 -0800, Jai wrote: > hey , will u guide me how to run proxies from python http://lmgtfy.com/?q=ip+address+spoofing -- Denis McMahon, denismfmcma...@gmail.com -- https://mail.python.org/mailman/listinfo/python-list
Re: New to Python, Help to get script working?
On Sat, 14 Dec 2013 20:51:59 -0800, Mark wrote: > I have successfully installed python 3.3 for windows, pip and > livestreamer that is needed for it to work. They are in my scripts > folder. I either do not understand the script or it no longer works. It > is more than likely my error. I get errors on line 19 and cant get it to > work at all. If you're getting the "not enough goats and chickens sacrificed error", sacrifice more goats and chickens. (Hint - it would help if you told us what the error was, and displayed at least the line the error occurs on and the preceding 10 lines or so) -- Denis McMahon, denismfmcma...@gmail.com -- https://mail.python.org/mailman/listinfo/python-list
Re: Want guidance to set proxy please help
On Sun, 15 Dec 2013 20:29:55 -0800, Jai wrote: > so , i need some step to set proxy so that my ip is not blocked by them This sounds like you're attempting to access a site other than for legitimate purposes. You probably want some 1337 script kiddies forum, not a serious programming newsgroup. -- Denis McMahon, denismfmcma...@gmail.com -- https://mail.python.org/mailman/listinfo/python-list
Re: Wrapping around a list in Python.
On Mon, 16 Dec 2013 15:59:32 +1100, Ben Finney wrote: > shengjie.sheng...@live.com writes: > >> Hi guys, I am trying to create a fixed list which would allow my values >> to be wrapped around it. > > This doesn't make a lot of sense to me, but I assume you have a purpose > in mind for this. What is the purpose? Perhaps it will help the > explanation if we know what it's for. > >> For example i have 10 values : 0,1,2,3,4,5,6,7,8,9 > > Does this mean the input is a list, ‘[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]’? Or > do you mean something else? What is the input? > >> I need to create a list which contains 4 numbers and when the number >> exceeds the list, it would overwrite the first value. > >> [0,1,2,3] >> [4,1,2,3] >> [5,4,1,2] > > That's three different lists. What is the input in each case? Under what > circumstances would you expect each one to be produced? I suspect the OP means: first input is 0, list = [ 0 ] next input is 1, list = [ 0, 1 ] next input is 2, list = [ 0, 1, 2 ] next input is 3, list = [ 0, 1, 2, 3 ] next input is 4, list = [ 4, 1, 2, 3 ] next input is 5, list = [ 5, 4, 1, 2 ] But this is a bit daft, because he starts by appending, and when he hits overflow he starts prepending. What I think he should do is use collections.dequeue and a couple of helper functions to add and get data items. For a queue moving from position 0 to position 3 (left to right): from collections import deque q = dequeue([]) def add_to_queue( item, q ): if len( q ) is 4: q.pop() q.appendleft( item ) def get_next( q ): if len( q ) > 0: return q.pop() return None To move from position 3 to position 0 (right to left), swap pop and appendleft for popleft and append. -- Denis McMahon, denismfmcma...@gmail.com -- https://mail.python.org/mailman/listinfo/python-list
Re: Web Server for Python
On Mon, 16 Dec 2013 19:20:20 -0800, Mura Zalukhu wrote: > Could you give me the best tutorial / web for python. For example how to > make a connection with database. Which database? Which version of Python? Google may help. So will the Python on-line documentation. -- Denis McMahon, denismfmcma...@gmail.com -- https://mail.python.org/mailman/listinfo/python-list
Struggling for inspiration with lists
Hi I have a list of data that presents as: timestamp: value Timestamps are used solely to determine the sequence of items in the list. I want to find the longest repeated sequence of values in the list. Example, in the following list: data = { 0: "d", 1: "x", 2: "y", 3: "t", 4: "d", 5: "y", 77: "g"' 78: "h", 79: "x", 80: "y", 206: "t", 210: "d", 211: "x" } I would pull out the sequence x-y-t-d (starting at 1 and 79) I need to keep the timestamp / data association because I need to generate output that identifies (a) the longest repeated sequence (b) how many elements in the longest repeated sequence (c) at what timestamps each occurrence started. I'm not sure of the best way, programatically, to aproach this task, which means I'm unsure whether eg a list of tuples ( time, data ) or an OrderedDict keyed on the timestamp is the best starting point. I can make a list of tuples using: d = [ (k,v) for k,v in data ] and with the list of tuples, I can do something like: d.sort( key=lambda tup: tup[0] ) max_start_a = 0 max_start_b = 0 max_len = 0 i = 0 while i < len( d ): j = i + 1 while j < len( d ): o = 0 while j+o < len( d ) and d[i+o][1] == d[j+o][1]: o += 1 if o > max_len: max_len = 0 max_start_a = i max_start_b = j j += 1 i += 1 print d[max_start_a][0], d[max_start_b][0], max_len Is there a better way to do this? -- Denis McMahon, denismfmcma...@gmail.com -- https://mail.python.org/mailman/listinfo/python-list
Re: HOW TO HANDLE CAPTCHA WHILE PARSING A WEB SITE
On Wed, 18 Dec 2013 16:38:00 +, Mark Lawrence wrote: > On 18/12/2013 09:37, Jai wrote: >> RIGHT NOW NOW I AM WORKING WITH MECHANIZE MODULE . BUT UNABLE TO >> SUBMIT CAPTACHA AUTOMATICALLY . DO U HAVE ANY IDEA PLEASE SHARE WITH ME > Ditto the Chris Angelico answer to your earlier request. +1 -- Denis McMahon, denismfmcma...@gmail.com -- https://mail.python.org/mailman/listinfo/python-list
Re: how to handle captcha through machanize module or any module
On Wed, 18 Dec 2013 04:56:17 -0800, Jai wrote: > please do replay how to handle captcha through machanize module The purpose of a captcha is to prevent automated scraping of data. Many of us may choose, or even need, to use captcha. What on earth makes you think for one minute that we'll help you bypass them. -- Denis McMahon, denismfmcma...@gmail.com -- https://mail.python.org/mailman/listinfo/python-list
Re: Variables in a loop, Newby question
On Tue, 24 Dec 2013 10:27:13 -0800, vanommen.robert wrote: > In this script i want to read the temperatures and make them available > to other scripts. The "global" keyword doesn't do that. "global" is used inside a function definition in python to tell the function that it is working with a global (to the program unit) variable. If you want this process to provide data to other processes, you might want to look at using a socket so they can request it as needed. -- Denis McMahon, denismfmcma...@gmail.com -- https://mail.python.org/mailman/listinfo/python-list
Re: Variables in a loop, Newby question
On Wed, 25 Dec 2013 16:42:47 +1100, Cameron Simpson wrote: > On 25Dec2013 02:54, Denis McMahon wrote: >> On Tue, 24 Dec 2013 10:27:13 -0800, vanommen.robert wrote: >> > In this script i want to read the temperatures and make them >> > available to other scripts. [...] >> If you want this process to provide data to other processes, you might >> want to look at using a socket so they can request it as needed. > > Or just write it to a file for another process to open and read... That can cause io sync errors, eg if another process has the file opened for read when you try to write, or you are writing when they try to read. For inter process communication, sockets are generally better than files. -- Denis McMahon, denismfmcma...@gmail.com -- https://mail.python.org/mailman/listinfo/python-list
Re: Creating a list with holes
On Fri, 03 Jan 2014 10:41:21 -0500, Larry Martell wrote: > The holes would be between the items I put in. In my example above, if I > assigned to [10] and [20], then the other items ([0..9] and [11..19]) > would have None. >>> dic = { 10:6, 20:11} >>> dic.get(10) 6 >>> dic.get(14) >>> dic.get(27,"oh god there's nothing here") "oh god there's nothing here" >>> dic.get(99,None) >>> dic.get(168,False) False >>> dic.get(20,"Boo Yah") 11 >>> So a standard dictionary does this returning None (or any other default value you care to pass it) as long as you use the dict.get(key[,default]) method rather than dict[key] to return the value. See also: http://stackoverflow.com/questions/6130768/return-none-if-dictionary-key- is-not-available -- Denis McMahon, denismfmcma...@gmail.com -- https://mail.python.org/mailman/listinfo/python-list
Re: Creating a list with holes
On Fri, 03 Jan 2014 20:18:06 -0500, Roy Smith wrote: > In article , > Larry Martell wrote: > > >> Thanks, but I know all that about dicts. I need to use a list for >> compatibility with existing code. > > Generalizing what I think the situation is, "A dict is the best data > structure for the parsing phase, but I need a list later to hand off to > legacy interfaces". > > No problem. Parse the data using a dict, then convert the dict to a > list later. I haven't been following all the details here, but just > wanted to point out that using different data structures to hold the > same data at different phases of a program is a perfectly reasonable > approach. Indeed, assuming the requirement is to have a list of some length n units representing integer keys into a range of values from start to end, and he creates a dict initially: list = [ dict.get(x,None) for x in range(start,end + 1) ] Examples: >>> dic = {1:"fred", 9:"jim", 15:"susan", 25:"albert" } >>> l = [ dic.get(x,None) for x in range(1,20) ] >>> l ['fred', None, None, None, None, None, None, None, 'jim', None, None, None, None, None, 'susan', None, None, None, None] >>> l = [ dic.get(x,None) for x in range(-10,50) ] >>> l [None, None, None, None, None, None, None, None, None, None, None, 'fred', None, None, None, None, None, None, None, 'jim', None, None, None, None, None, 'susan', None, None, None, None, None, None, None, None, None, 'albert', None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None] >>> len(l) 60 then the value of l[offset] will either be None or some string depending on the offset into the list -- Denis McMahon, denismfmcma...@gmail.com -- https://mail.python.org/mailman/listinfo/python-list
Re: Dos cursor and input management.
On Sun, 05 Jan 2014 20:25:11 +1100, Sean Murphy wrote: > The module must work under dos for now. Eventually Mac. Do you mean a windows command line terminal window, or some *nix shell? As far as I know, dos as an operating system hasn't been around since version 6.22 or thereabouts, although I believe ms windows provides a dos shell like interface on top of the windows os. I'm not aware that any version of python is supported on dos, but I may be wrong, there may be some 15 year old hardware running dos somewhere that also has a working python install. I associate dos with machines of the pre-pentium era, although I suspect that might not be quite accurate either. -- Denis McMahon, denismfmcma...@gmail.com -- https://mail.python.org/mailman/listinfo/python-list
Re: Send array back in result from urllib2.urlopen(request, postData)
On Fri, 10 Jan 2014 12:57:59 -0800, vanommen.robert wrote: > Hello, > > I have a Raspberry Pi with 10 temperature sensors. I send the data from > the sensors and some other values with json encoding and: > > result = urllib2.urlopen(request, postData) > > to a online PHP script wich places the data in a mysql database. > > In the result: > > result.read() > > i am trying to send data back from the PHP to the RPI. I make an array > in PHP > > $para[0] = $REGELING_ORG; > $para[1] = $VLVERWL_ORG; > $para[2] = $VLOERVRAAG_ORG; > $para[3] = $TIJDVLOER_ORG; > $para[4] = $SETPOINT_ORG; > > echo $para; This is php code that prints out a string representation of the variable, in so far as it can. What you probably want to do is encode the array somehow, such as one element value per line, or json encode, or some other method, and then decode it in your python. > In python when i do > > para = result.read() > print para > > the output is: > > [null,null,null,null,null,"J"] Yep, that's because para is a string containing the text: '[null,null,null,null,null,"J"]' > This is correct according to the data in PHP from the mysql. > > when I do > > print para[1] > > the output is: > > n > > the seccond character from the data. Why is this not the seccond > datafield? > And why is para[5] not "J" but , ? This is because python is looking at a string containing the character sequence '[null,null,null,null,null,"J"]' para[0] = '[' para[1] = 'n' para[2] = 'u' para[3] = 'l' para[4] = 'l' para[5] = ',' para[6] = 'n' para[7] = 'u' > How can I change the data back to an array? I've tried with json, but > that doesn't change anything. To use json to convert it back to an array in the python code, you also need to use json to serialise the array in the php code. eg in the php: echo $para; would become: echo php_json_encoding_function( para ); and in the python: para = result.read() would become: para = python_json_decoding_function( result.read() ) or possibly even: para = json.decode( result.read() ) (I don't know the details, I'm trying to give you the general idea so you can work out where to look to figure this out) These two web pages may also help: http://uk3.php.net/manual/en/function.json-encode.php http://docs.python.org/2/library/json.html -- Denis McMahon, denismfmcma...@gmail.com -- https://mail.python.org/mailman/listinfo/python-list
Re: python first project
On Fri, 10 Jan 2014 20:18:32 -0800, ngangsia akumbo wrote: > i have been learning python just for about 5 months now and i have been > given a task to do. This will be a leap into the programming industry > for me. > > i am programming a system that will be giving details about finance, > purchase(bills pending bills and paid bill), employees record and salary > details, warehouse records. It sounds as if your project has many aspects to it which may require you to understand and implement many different computing tasks. For example: You need to either analyse the data records that are required and produce a suitable database schema, or you need to work with an existing database schema. This may require some competence in developing database schemas, and will almost certainly require some sql knowledge in the chosen database (not all sqls are equal). You also need to develop a user interface. First of all you ned to consider who will access the user interface, and how? Mobile devices, desktop computers, both? Do you want os specific (eg ios, android) apps for mobile devices, or will you run in a mobile browser window? Will the application run on a web server, or locally on a single machine? Or will several gui clients connect to a single server host? In the latter case, you'll need to develop communication protocols (using a webapp removes some of this workload, but is a compromise that may require that you need other competences, possibly including but not limited to html, javascript and css). The most important phase of any project is the requirements capture, for if you do not capture all the requirements of all the users, you will not deliver the project that they want. Users are not just the people who sit in front of the screens, they may also be people who will want statistical reports based on the database, but who never expect to actually touch a computer themselves - they have secretaries for that sort of thing. However, if your system can't produce the report that the CEO or CFO wants at the end of each month / quarter / year, then it will be labelled as crap, even if no-one told you as the system designer that this report was required! So, first of all, you need to go and talk to everyone in the company that will use this system and obtain from them details of what they expect the system to do, what data they expect to input, and what data they expect to receive as outputs from it. Once you understand this, you may be in a position to start defining the database schema, and only then are you ready to think about the code that will put data into, and get it from, the database. -- Denis McMahon, denismfmcma...@gmail.com -- https://mail.python.org/mailman/listinfo/python-list
Re: Python example source code
On Sun, 12 Jan 2014 06:37:18 -0800, ngangsia akumbo wrote: > where can i find example source code by topic? > Any help please You don't want to be looking at source code yet, you want to be talking to the users of the system you're trying to design to find out what their requirements are. -- Denis McMahon, denismfmcma...@gmail.com -- https://mail.python.org/mailman/listinfo/python-list
Re: python adsl script
On Tue, 14 Jan 2014 09:27:07 -0800, ngangsia akumbo wrote: > what about a python script that can retrieve my entire isp setting from > my adsl router. > Any ideas This is probably possible using telnet, so it should be possible to do it over a socket interface, yes. > Also my grand mother forget her computer password, she can only login > through the guest account. what about a script that can solve that > problem. We are not your familiy's tech support group. Nor will we write your code from scratch for you. I suggest you learn to google. There are plenty of tools out there that can be used to reset passwords on various operating systems. -- Denis McMahon, denismfmcma...@gmail.com -- https://mail.python.org/mailman/listinfo/python-list
Re: Learning python networking
On Wed, 15 Jan 2014 02:37:05 -0800, Paul Pittlerson wrote: >> One extremely critical point about your protocol. TCP is a stream - you >> don't have message boundaries. You can't depend on one send() becoming >> one recv() at the other end. It might happen to work when you do one >> thing at a time on localhost, but it won't be reliable on the internet >> or when there's more traffic. So you'll need to delimit messages; I >> recommend you use one of two classic ways: either prefix it with a >> length (so you know how many more bytes to receive), or terminate it >> with a newline (which depends on there not being a newline in the >> text). > I don't understand. Can you show some examples of how to do this? How much do you understand about tcp/ip networking? because when trying to build something on top of tcp/ip, it's a good idea to understand the basics of tcp/ip first. A tcp/ip connection is just a pipe that you pour data (octets, more or less analagous to bytes or characters) into at one end, and it comes out at the other end. For your stream of octets (bytes / characters) to have any meaning to a higher level program, then the applications using the pipe at both ends have to understand that a message has some structure. The message structure might be to send an n character message length count (where in a simple protocol n would have to be a fixed number) followed by the specified number of characters. Assuming your maximum message length is characters: You could send the characters followed by characters of message content. The receiving end would receive 4 characters, convert them to the number , and assume the next characters will be the message. Then it expects another 4 character number. You could send json encoded strings, in which case each message might start with the "{" character and end with the "}" character, but you would have to allow for the fact that "}" can also occur within a json encoded string. You might decide that each message is simply going to end with a specific character or character sequence. Whatever you choose, you need some way for the receiving application to distinguish between individual messages in the stream of octets / bytes / characters that is coming out of the pipe. -- Denis McMahon, denismfmcma...@gmail.com -- https://mail.python.org/mailman/listinfo/python-list
Re: Python solve problem with string operation
On Fri, 17 Jan 2014 00:24:40 +0200, Nac Temha wrote: > Hi everyone, > > I want to do operation with chars in the given string. Actually I want > to grouping the same chars. > > For example; > > input : "3443331123377" > operation-> (3)(44)()(333)(11)(2)(33)(77) > output: "34131237" > How can I do without list, regular expression. just using string > operations. Using an effective methods of python for this problem. You can do it on one line, but it looks really messy: output = ''.join([{x:input[x]for x in range(len(input))}[x]for x in range (len({x:input[x]for x in range(len(input))}))if(x==0 or {x:input[x]for x in range(len(input))}[x-1]!={x:input[x]for x in range(len(input))}[x])]) It looks much better if you do it in steps: a = {x:input[x]for x in range(len(input))} b = [a[n]for n in range(len(a))if(n==0 or a[n-1]!=a[n])]) output = ''.join(b) If you really want to do it using just 'string' ops: for i in range(len(input)): if (i==0): output=input[0] elif input[i]!=input[i-1]: output+=input[i] -- Denis McMahon, denismfmcma...@gmail.com -- https://mail.python.org/mailman/listinfo/python-list
Re: Process datafeed in one MySql table and output to another MySql table
On Thu, 16 Jan 2014 17:03:24 -0800, Sam wrote: > I have a datafeed which is constantly sent to a MySql table ... > Which are the python libraries which are suitable for this purpose? Are > there any useful sample code or project on the web that I can use as > reference? Did you search for mysql on the python docs website, or perhaps try googling "python mysql"? -- Denis McMahon, denismfmcma...@gmail.com -- https://mail.python.org/mailman/listinfo/python-list
Re: python to enable javascript , tried selinium, ghost, pyQt4 already
On Sat, 18 Jan 2014 03:54:17 -0800, Jaiprakash Singh wrote: > can you please suggest me some method for study so that i can > scrap a site having JavaScript behind it Please expand upon the requirement, are you trying to: a) replace server side javascript with server side python, or b) replace client side javascript with server side python, or c) replace client side javascript with client side python, or d) something else? (c) is not possible (you can't guarantee that all clients will have python, or that there will be a mechanism for calling it from your webpages), (b) doesn't make a lot of sense (you'll be trading cpu in the client for cpu in the server + network bandwidth and latency). -- Denis McMahon, denismfmcma...@gmail.com -- https://mail.python.org/mailman/listinfo/python-list
Re: python to enable javascript , tried selinium, ghost, pyQt4 already
On Sun, 19 Jan 2014 05:13:57 +1100, Chris Angelico wrote: > On Sat, Jan 18, 2014 at 10:54 PM, Jaiprakash Singh > wrote: >> hi, >> >> can you please suggest me some method for study so that i can >> scrap a site having JavaScript behind it >> >> >> i have tried selenium, ghost, pyQt4, but it is slow and as a am >> working with thread it sinks my ram memory very fast. > > Do you mean "scrape"? You're trying to retrieve the displayed contents > of a web page that uses JavaScript? If so, that's basically impossible > without actually executing the JS code, which means largely replicating > the web browser. Oh, you think he meant scrape? I thought he was trying to scrap (as in throw away / replace) an old javascript heavy website with something using python instead. -- Denis McMahon, denismfmcma...@gmail.com -- https://mail.python.org/mailman/listinfo/python-list
Re: Help with simple code that has database defined
On Sat, 18 Jan 2014 18:23:01 -0800, indar kumar wrote: > I have to save students information in a database that is keeping > continuously track of the information. Format is as follows: You probably need to use one of the database modules. > Note: if this name already exists there in database, just update the > information of that(name) e.g course,grade and date. Otherwise, add it. That sounds like an sql issue specific to your chosen database, not a python issue. > This is just part because this is what I know how to do, for rest have > no idea I suggest you get idea fast. Or ask your lecturers for advice. Or return the advance you were paid on this coding job, because you don't seem to have the skills to do it. -- Denis McMahon, denismfmcma...@gmail.com -- https://mail.python.org/mailman/listinfo/python-list
Re: Separate Address number and name
On Tue, 21 Jan 2014 15:49:16 -0800, Shane Konings wrote: > I have the following sample from a data set and I am looking to split > the address number and name into separate headings as seen below. > > FarmIDAddress 1 1067 Niagara Stone 24260 Mountainview 3 25 Hunter 4 > 1091 Hutchinson 5 5172 Green Lane 6 500 Glenridge 7 471 Foss 8 758 > Niagara Stone 9 3836 Main 101025 York > > > FarmIDAddressNumAddressName 1 1067 Niagara Stone 2 4260 > Mountainview 3 25Hunter 4 1091 Hutchinson 5 > 5172 Green Lane 6500 Glenridge 7 471 Foss > 8 758 Niagara Stone 9 3836 Main 10 1025 York > > I have struggled with this for a while and know there must be a simple > method to achieve this result. Unfortunately the vagaries of nntp, my client and the google nntp posting host are such that I can't discern the format of your data from your post. However, if as I think you have a text field that is always: <1 or more digits><1 or more spaces> where you want to capture the initial "1 or more digits" and "the rest" as 2 data elements then this should be possible with a simple re: (\d+)\s+(.*) If you have numeric id, whitespace, numeric addr bit, whitespace, the rest, then you may need something more like: (\d+)\s+(\d+)\s+(.*) The assumption is that it's not necessary to hold your hand through the whole looping through the input and applying the re to each line, then reading the captured bits and using them process. -- Denis McMahon, denismfmcma...@gmail.com -- https://mail.python.org/mailman/listinfo/python-list
Re: Separate Address number and name
On Tue, 21 Jan 2014 16:06:56 -0800, Shane Konings wrote: > The following is a sample of the data. There are hundreds of lines that > need to have an automated process of splitting the strings into headings > to be imported into excel with theses headings > > ID Address StreetNum StreetName SufType Dir City Province > PostalCode Ok, the following general method seems to work: First, use a regex to capture two numeric groups and the rest of the line separated by whitespace. If you can't find all three fields, you have unexpected data format. re.search( r"(\d+)\s+(\d+)\s+(.*)", data ) Second, split the rest of the line on a regex of comma + 0 or more whitespace. re.split( r",\s+", data ) Check that the rest of the line has 3 or 4 bits, otherwise you have an unexpected lack or excess of data fields. Split the first bit of the rest of the line into street name and suffix/ type. If you can't split it, use it as the street name and set the suffix/ type to blank. re.search( r"(.*)\s+(\w+)", data ) If there are 3 bits in rest of line, set direction to blank, otherwise set direction to the second bit. Set the city to the last but one bit of the rest of the line. Capture one word followed by two words in the last bit of the rest of the line, and use these as the province and postcode. re.search( r"(\w+)\s+(\w+\s+\w+)", data ) Providing none of the searches or the split errored, you should now have the data fields you need to write. The easiest way to write them might be to assemble them as a list and use the csv module. I'm assuming you're capable of working out from the help on the python re module what to use for each data, and how to access the captured results of a search, and the results of a split. I'm also assuming you're capable of working out how to use the csv module from the documentation. If you're not, then either go back and ask your lecturer for help, or tell your boss to hire a real programmer for his quick and easy coding jobs. -- Denis McMahon, denismfmcma...@gmail.com -- https://mail.python.org/mailman/listinfo/python-list
Re: Separate Address number and name
On Wed, 22 Jan 2014 17:35:22 +, Denis McMahon wrote: > On Tue, 21 Jan 2014 16:06:56 -0800, Shane Konings wrote: >> The following is a sample of the data. > A mechanism using regexes Just to follow up, using regexes I transformed the sample data that I believe is as follows: inputData = [ "1 1067 Niagara Stone Rd, W, Niagara-On-The-Lake, ON L0S 1J0", "2 4260 Mountainview Rd, Lincoln, ON L0R 1B2", "3 25 Hunter Rd, Grimsby, E, ON L3M 4A3", "4 1091 Hutchinson Rd, Haldimand, ON N0A 1K0", "5 5172 Green Lane Rd, Lincoln, ON L0R 1B3", "6 500 Glenridge Ave, East, St. Catharines, ON L2S 3A1", "7 471 Foss Rd, Pelham, ON L0S 1C0", "8 758 Niagara Stone Rd, Niagara-On-The-Lake, ON L0S 1J0", "9 3836 Main St, North, Lincoln, ON L0R 1S0", "10 1025 York Rd, W, Niagara-On-The-Lake, ON L0S 1P0" ] Into the following: 1,1067,Niagara Stone,Rd,W,Niagara-On-The-Lake,ON,L0S 1J0 2,4260,Mountainview,Rd,,Lincoln,ON,L0R 1B2 3,25,Hunter,Rd,Grimsby,E,ON,L3M 4A3 4,1091,Hutchinson,Rd,,Haldimand,ON,N0A 1K0 5,5172,Green Lane,Rd,,Lincoln,ON,L0R 1B3 6,500,Glenridge,Ave,East,St. Catharines,ON,L2S 3A1 7,471,Foss,Rd,,Pelham,ON,L0S 1C0 8,758,Niagara Stone,Rd,,Niagara-On-The-Lake,ON,L0S 1J0 9,3836,Main,St,North,Lincoln,ON,L0R 1S0 10,1025,York,Rd,W,Niagara-On-The-Lake,ON,L0S 1P0 Which should then read into Excel as CSV just fine. One final question though, why are you using excel to manipulate data that looks as if it would be better held in and manipulated by a database? -- Denis McMahon, denismfmcma...@gmail.com -- https://mail.python.org/mailman/listinfo/python-list
Re: Help with my 8-year old son's first program. I'm stuck!
On Sat, 25 Jan 2014 02:02:15 -0800, justinpmullins wrote: > def a(): > import sys print("welcome to the calculation") print("please type a > number") > one = int(sys.stdin.readline()) print("type d for division,") > print("type m for multiplication,") print("type s for subtraction,") > print("and type p for plus") > op = (sys.stdin.readline()) print("%s selected" % op) print ("please > enter another number") > two = int(sys.stdin.readline()) > if op == str(d): > out == one / two print("the answer is %s" % out) > elif op == "m": > out == one * two print("the answer is %s" % out) > elif op == "s": > out == one - two print("the answer is %s" % out) > elif op == "p": > out == one + two print("the answer is %s" % out) > else: > print("huh") a() is a function, but I can see nothing in the code that invokes the function a() Ignore the comment about needing to define the type of file on the first line on linux, it's a red herring. You only need to do that (and possibly chmod the file) on a *nix system if you want to execute it directly as a command, rather than by calling the interpreter on it. I suspect that if you remove the line: "def a():" and un-indent the rest of the text, the program will run just fine. -- Denis McMahon, denismfmcma...@gmail.com -- https://mail.python.org/mailman/listinfo/python-list
Re: Need Help with Programming Science Project
On Fri, 24 Jan 2014 20:58:50 -0800, theguy wrote: > I know. I'm kind of ashamed of the code, but it does the job I need it > to up to a certain point OK, well first of all take a step back and look at the problem. You have n exemplars, each from a known author. You analyse each exemplar, and determine some statistics for it. You then take your unknown sample, determine the same statistics for the unknown sample. Finally, you compare each exemplar's stats with the sample's stats to try and find a best match. So, perhaps you want a dictionary of { author: statistics }, and a function to analyse a piece of text, which might call other functions to get eg avg words / sentence, avg letters / sentence, avg word length, and the sd in each, and the short word ratio (words <= 3 chars vs words >= 4 chars) and some other statistics. Given the statistics for each exemplar, you might store these in your dictionary as a tuple. this isn't python, it's a description of an algorithm, it just looks a bit pythonic: # tuple of weightings applied to different stats stat_weightings = ( 1.0, 1.3, 0.85, .. ) def get_some_stat( t ): # calculate some numerical statistic on a block of text # return it def analyse( f ): text = read_file( f ) return ( get_some_stat( text ), .. ) exemplars = {} for exemplar_file in exemplar_files: exemplar_data[author] = analyse( exemplar_file ) sample_data = analyse( sample_file ) scores = {} tmp = 0 x = 0 # score for a piece of work is sum of ( diff of stat * weighting ) # for all the stats, lower score = closer match for author in keys( exemplar_data ): for i in len( exemplar_data[ author ] ): tmp = tmp + sqrt( exemplar_data[ author ][ i ] - sample_data[ i ] ) * stat_weightings( i ) scores[ author ] = tmp if tmp > x: x = tmp names = [] for author in keys( scores ): if scores[ author ] < x: x = scores[ author ] names = [ author ] elif scores[ author ] == x: names.append( [ author ] ) print "the best matching author(s) is/are: ", names Then all you have to do is find enough ways to calculate stats, and the magic coefficients to use in the stat_weightings -- Denis McMahon, denismfmcma...@gmail.com -- https://mail.python.org/mailman/listinfo/python-list
Re: Lists inside dictionary and how to look for particular value
On Sun, 26 Jan 2014 10:47:11 -0800, mick verdu wrote: > z={ 'PC2': ['02:02:02:02:02:02', '192.168.0.2', '200'], > 'PC3': ['03:03:03:03:03:03', '192.168.0.3', '200'], 'PC1': > ['01:01:01:01:01:01', '192.168.0.1', '200'] } > > My solution: > > z=raw_input("Enter Host, Mac, ip and time") > t=z.split() > t[0]=z[1:] > for key in dic: > if t[2] in dic[key]: > del dic[t[0]] > else: > dic[t[0]] = t[1:] > > > What I really want to achieve is: > > > How to search for a particular value inside list. First, I want the user > to input hostname and ip. e.g. PC1 and 192.168.0.1, then need to find > out if 192.168.0.1 has already been assigned to some host in dictionary. > In this case I would need to skip for search inside list of user input > host. > > Forexample, if user inputs PC1 and 192.168.0.1 i would like to skip > searching in above PC1's values. So it should detect matching only with > different hosts and skip its own name. > > If i input PC4 and 192.168.0.1 then it should detect conflict with PC1. > So PC4 would be deleted(As soon as user inputs new host it is saved in > above database then if conflict with others deleted) Can we step back a few stages. What are you writing this software for? The network management at the level you're trying to observe happens for the most part automatically at the ip stack / network hardware level. Do you think this database of which ip maps to which MAC is actually going to have some human use? If so, what? Or is this some sort of homework exercise as part of a programming course? -- Denis McMahon, denismfmcma...@gmail.com -- https://mail.python.org/mailman/listinfo/python-list
Re: Remove unwanted characters from column
On Sun, 26 Jan 2014 19:49:01 -0800, matt.s.marotta wrote: > School assignment is to create a tab separated output with the original > given addresses in one column and then the addresses split into other > columns (ex, columns for city, postal code, street suffix). If you're trying to create fixed width output from variable width fields, format specifiers may be better to use than tabs. The problem with tabs is that columns end up misaligned when the data fields in a column contain a mixture of items of less length than the tab spacing and items of greater length than the tab spacing, unless you can work out the tab spacing and adjust accordingly. For example, my code which uses the re module to separate the various record components and a format specifier to print the text and html versions (and csvwriter for the csv) them creates the outputs seen here: http://www.sined.co.uk/tmp/farms.txt http://www.sined.co.uk/tmp/farms.csv http://www.sined.co.uk/tmp/farms.htm -- Denis McMahon, denismfmcma...@gmail.com -- https://mail.python.org/mailman/listinfo/python-list
Re: ANN: eGenix pyOpenSSL Distribution 0.13.3.1.0.1.6
On Tue, 28 Jan 2014 17:47:39 +0100, eGenix Team: M.-A. Lemburg wrote: > It comes with an easy-to-use installer that includes the most recent > OpenSSL library versions in pre-compiled form Hmm, well it all sounds very good, but how would I know that the pre- compiled library doesn't contain a backdoor that sends copies of all the plaintext to the NSA? -- Denis McMahon, denismfmcma...@gmail.com -- https://mail.python.org/mailman/listinfo/python-list
Re: Eclipse IDE printing values automatically
On Tue, 28 Jan 2014 22:26:56 -0800, mick verdu wrote: > I am using Pydev 2.8 on Eclipse IDE. It is printing some values that > haven't been printed with print command. How to deal with this problem? There's no print statement in the code you included to demonstrate the problem, which is probably why the data you expect to be printed isn't being printed. -- Denis McMahon, denismfmcma...@gmail.com -- https://mail.python.org/mailman/listinfo/python-list
Re: Large Two Dimensional Array
On Tue, 28 Jan 2014 21:25:54 -0800, Ayushi Dalmia wrote: > Hello, > > I am trying to implement IBM Model 1. In that I need to create a matrix > of 5*5 with double values. Currently I am using dict of dict but > it is unable to support such high dimensions and hence gives memory > error. Any help in this regard will be useful. I understand that I > cannot store the matrix in the RAM but what is the most efficient way to > do this? This looks to me like a table with columns: word1 (varchar 20) | word2 (varchar 20) | connection (double) might be your best solution, but it's going a huge table (2G5 rows) The primary key is going to be the combination of all 3 columns (or possibly the combination of word1 and word2) and you want indexes on word1 and word2, which will slow down populating the table, but speed up searching it, and I assume that searching is going to be a much more frequent operation than populating. Also, creating a database has the additional advantage that next time you want to use the program for a conversion between two languages that you've previously built the data for, the data already exists in the database, so you don't need to build it again. I imagine you would have either one table for each language pair, or one table for each conversion (treating a->b and b->a as two separate conversions). I'm also guessing that varchar 20 is long enough to hold any of your 50,000 words in either language, that value might need adjusting otherwise. -- Denis McMahon, denismfmcma...@gmail.com -- https://mail.python.org/mailman/listinfo/python-list
Re: Help with some python homework...
On Thu, 30 Jan 2014 21:12:19 -0800, scottwd80 wrote: > Here is the question that was asked and below that I'll paste the code I > have so far. The following is a reasonably but not highly obfuscated short solution to the problem set in python 2.7. With a bit of luck, after each lesson of your course, you'll be able to understand a bit more of how it works. M=60;H=M*60 def s(h,m,s): return h*H+m*M+s def hms(s): return (int(s/H),int((s%H)/M),s%M) (a,b,c)=hms(s(6,52,0)+3*s(0,7,12)+2*s(0,8,15)) print "{:02d}:{:02d}:{:02d}".format(a,b,c) When you can write a short paragraph describing what each line of the program does, you'll be on your way to understanding a few of the structures, syntaxes and mechanisms of python. Or you could show it to your lecturer or a TA and say it was suggested that you ask her or him to work through it with you. -- Denis McMahon, denismfmcma...@gmail.com -- https://mail.python.org/mailman/listinfo/python-list
Re: Help with some python homework...
On Fri, 31 Jan 2014 18:14:31 -0700, Scott W Dunning wrote: > little different from a few things you guys had mentioned. For one, I > got the correct time by calculating the number of time run and > converting that into seconds then back out to hr:mn:sc. I didn’t > calculate from midnight. > SECONDS = 1 MINUTES = 60 * SECONDS HOURS = 60 * MINUTES > > time_left_house = 6 * HOURS + 52 * MINUTES This does actually calculate the time in seconds since midnight that you left the house > miles_run_easy_pace = 2 * (8 * MINUTES + 15 * SECONDS) > > miles_run_fast_pace = 3 * (7 * MINUTES + 12 * SECONDS) > > time_returned_home = miles_run_easy_pace + miles_run_fast_pace + > time_left_house And this calculates the time in seconds since midnight that you returned home So although you don't realise it, you are actually working in seconds since midnight, and then converting seconds back into hours, minutes and seconds. -- Denis McMahon, denismfmcma...@gmail.com -- https://mail.python.org/mailman/listinfo/python-list
Re: Help with some python homework...
On Fri, 31 Jan 2014 22:18:34 -0700, Scott W Dunning wrote: > Any chance you guys could help with another question I have? Below is a > code to a different problem. The only thing I don’t understand is why > when calculating the 'discounted price’ you have to subtract 1? Thanks > again guys! price_per_book = 24.95 discount = .40 quantity = 60 discounted_price = (1-discount) * price_per_book shipping = 3.0 + (60 - 1) * .75 total_price = 60 * discounted_price + shipping print total_price, 'Total price' You subtract 1 from the shipping price (which should be quantity - 1) to allow for the fact that the first book costs 3.0 snargles to ship, and extra books in the same shipment cost 0.75 snargles each. So if the quantity is greater than one, the shipping cost is 3 snargles for the first book plus 0.75 snargles times (quantity minus one) The discounted price needs to be the cost, not the discount. If the discount is 0.4 (or 40%), then the cost is 0.6 (or 60%) of the list price. You are trying to calculate the cost, not the discount. list_price = discounted_price + discount_amount 1.0 * list_price = 0.6 * list_price + 0.4 * list_price Hence: discounted_price = list_price - discount_amount 0.6 * list_price = 1.0 * list_price - 0.4 * list_price so discounted_price = ( 1.0 - 0.4 ) * list_price where 0.4 is the decimal fraction of the discount -- Denis McMahon, denismfmcma...@gmail.com -- https://mail.python.org/mailman/listinfo/python-list
Re: Help with some python homework...
On Sun, 02 Feb 2014 08:57:03 -0800, David Hutto wrote: > Revised: > discounted_price = price_per_book - (price_per_book * percent_discount) by applying some simple algebra to the right hand side price_per_book - (price_per_book * percent_discount) "x = (x * 1)" so "price_per_book == (price_per_book * 1)" so rhs becomes (price_per_book * 1) - (price_per_book * percent_discount) and "(a * x) - (a * y)" == "a * (x - y)" so rhs becomes price_per_book * (1 - percent_discount) hence: discounted_price = price_per_book * (1 - percent_discount) -- Denis McMahon, denismfmcma...@gmail.com -- https://mail.python.org/mailman/listinfo/python-list
Re: Calculator Problem
On Sun, 02 Feb 2014 13:46:24 -0800, Gary Herron wrote: > Sorry, but in fact you did *not* run this program as you claim. +1 I can also see a call to a function named Question, but I can't see where that function is defined. That might not be a major issue, because I don't think the while condition that leads to the function call is ever fulfilled anyway. -- Denis McMahon, denismfmcma...@gmail.com -- https://mail.python.org/mailman/listinfo/python-list
Re: [newbie] making rows of table with discrete values for different number systems
On Sun, 02 Feb 2014 09:44:05 -0800, Jean Dupont wrote: > I'm looking for an efficient method to produce rows of tables like this: > > for base 2 0 0 0 0 0 0 0 1 0 0 1 0 0 0 1 1 0 1 0 0 . > . > . > 1 1 1 1 > > for base 3 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 2 0 0 0 0 1 0 0 0 0 0 1 1 0 > 0 0 0 1 2 . > . > 2 2 2 2 2 2 > > As you can see the rows are always twice the size of the base I _don't_ > need to have all rows available together in one array which would become > too large for higher value number bases. It's sufficient to produce one > row after the other, as I will do further data manipulation on such a > row immediately. > > If someone here could suggest best practices to perform this kind of > operations,I'd really appreciate it very much > > kind regards and thanks in advance jean s=3 p=s*2 def b(n,x): s=[] while n: s.append(str(n%x)) n=n/x if s==[]: return "0" return ''.join(s[::-1]) for i in range(s**p): r=("{:0"+str(p)+"d}").format(int(b(i,s))) if len(r)==p: print [int(r[a])for a in range(len(r))] change s to 2 or 4 etc -- Denis McMahon, denismfmcma...@gmail.com -- https://mail.python.org/mailman/listinfo/python-list
Re: Calculator Problem
On Mon, 03 Feb 2014 10:25:37 -0800, Charlie Winn wrote: > Python 3.3.3 (v3.3.3:c3896275c0f6, Nov 18 2013, 21:19:30) [MSC v.1600 64 > bit (AMD64)] on win32 Type "copyright", "credits" or "license()" for > more information. >>>> RESTART >>>> >>>> > What type of calculation would you like to do? > (Add, Subtract, Divide or Multiply)a Addition: What are two your > numbers? > First Number:5 Second Number:96 Your Final Result is: 101.0 None >>>> That wasn't obtained from running the code you posted. Your code *as you posted it* gives: $ python charlie.py File "charlie.py", line 4 1 = float(input('First Number:')) SyntaxError: can't assign to literal $ -- Denis McMahon, denismfmcma...@gmail.com -- https://mail.python.org/mailman/listinfo/python-list
Re: [newbie] troubles with tuples
On Mon, 03 Feb 2014 08:50:31 -0800, Jean Dupont wrote: > I'm looking at the way to address tuples e.g. > tup2 = (1, 2, 3, 4, 5, 6, 7 ); > > As I found out indices start with 0 in Python, so tup2[0] gives me 1, > the first element in the tuple as expected tup2[1] gives me 2, the > second element in the tuple as expected now here comes what surprises > me: > tup2[0:1] does not give me the expected (1,2) but (2,) > > what is the reason for this and how then should one get the first and > the second element of a tuple? Or the 3rd until the 5th? > > thanks in advance and kind regards, > > jean >>> tup = (0,1,2,3,4,5,6,7) >>> tup[0:1] (0,) >>> tup[1:2] (1,) >>> tup[2:3] (2,) >>> tup[0:2] (0, 1) >>> tup[2:5] (2, 3, 4) This is as I'd expect, as the notation [0:1] means: starting from the 0th element, up to and including the element preceding the first element Or [m:n] means starting from the mth element, everything up to and including the element preceding the nth element Are you sure you got (2,) for [0:1] and not for [2:3]? Are you sure your initial tuple is what you thought it was? -- Denis McMahon, denismfmcma...@gmail.com -- https://mail.python.org/mailman/listinfo/python-list
Re: What are the kinds of software that are not advisable to be developed using Python?
On Sat, 08 Feb 2014 15:54:30 -0800, Sam wrote: > I got to know about Python a few months ago and today, I want to develop > only using Python because of its code readability. This is not a healthy > bias. To play my own devil's advocate, I have a question. What are the > kinds of software that are not advisable to be developed using Python? OS Kernels. Hardware drivers. -- Denis McMahon, denismfmcma...@gmail.com -- https://mail.python.org/mailman/listinfo/python-list
Re: Screen scraper to get all 'a title' elements
On Wed, 25 Nov 2015 12:42:00 -0800, ryguy7272 wrote: > Hello experts. I'm looking at this url: > https://en.wikipedia.org/wiki/Wikipedia:Unusual_place_names > > I'm trying to figure out how to list all 'a title' elements. a is the element tag, title is an attribute of the htmlanchorelement. combining bs4 with python structures allows you to find all the specified attributes of an element type, for example to find the class attributes of all the paragraphs with a class attribute: stuff = [p.attrs['class'] for p in soup.find_all('p') if 'class' in p.attrs] Then you can do this for thing in stuff: print thing (Python 2.7) This may be adaptable to your requirement. -- Denis McMahon, denismfmcma...@gmail.com -- https://mail.python.org/mailman/listinfo/python-list
Re: read 4D binary data
On Thu, 26 Nov 2015 15:15:43 -0200, jorge.conrado wrote: > I'm startig in Python and I have a 4D binary data. The dimension of my > data is: > > 67 > longitude points 41 > latitude points 10 > pressure > levels points 33 > time points > > How can I read this data and what can I do to get a 2D array > (longitude,latitude) for a specific pressure and time dimension. First of all, define the data structure you want to create. I would have thought that for any given time, you would want a 2d array containing the pressure at each point (given by lat and lon) at that time. -- Denis McMahon, denismfmcma...@gmail.com -- https://mail.python.org/mailman/listinfo/python-list