ZZucker 342 Practically a Master Poster

Don't you feel important with all those emails?

ZZucker 342 Practically a Master Poster

When I was in Mumbai, India recently, I saw a sign on a vehicle that said, 'English speaking taxi driver'.

I thought to myself,
"What a wonderful idea. Why don't we have them in London, England?"

ZZucker 342 Practically a Master Poster

Oh wow, I didn't know about the magic dragon's demise. What a tragedy!

ZZucker 342 Practically a Master Poster

A look at module fractions:

import fractions
import math

fractional_pi = fractions.Fraction(str(math.pi))

# limit the denominator to 999 or less
fractional_pi_999 = fractional_pi.limit_denominator(999)

# show result
sf = "pi = {} as a fraction with a max. denominator of 999 is {}"
print(sf.format(math.pi, fractional_pi_999))

''' my result -->
pi = 3.14159265359 as a fraction with a max. denominator of 999 is 355/113
'''
ZZucker 342 Practically a Master Poster

McDonalds has sold so many hamburgers that if you lined them up side by side you could go around the world 52 times. Then with what's left stack them up to the moon and back.

ZZucker 342 Practically a Master Poster

The integral from -infinity to infinity of e^(-x^2) is sqrt(pi).

"Heads, she wins! Tails, you lose!"

¿umop apisdn upside down?

ZZucker 342 Practically a Master Poster

Writing your own IDE, here is a hint on how to do this sort of thing:
http://www.daniweb.com/software-development/python/code/445504/an-almost-ide-wxpython

I would use the PySide GUI toolkit, since wxPython is a mess with Python3.

ZZucker 342 Practically a Master Poster

The Eric IDE is full featured and written in Python:
http://eric-ide.python-projects.org/

For a beginner the nimble IDLE that comes with your Python installation is probably best.

ZZucker 342 Practically a Master Poster

To get more information on par you can do this:

# Importing support.py module 

import support
support.print_func("Zara")

# to get more insight ...
import inspect
print(inspect.getcallargs(support.print_func, "Zara"))

''' result ...
Hello :  Zara
{'par': 'Zara'}
'''
Gribouillis commented: nice! +14
ZZucker 342 Practically a Master Poster

pytony, red is a nice color

ddanbe commented: Keen eye! +15
ZZucker 342 Practically a Master Poster

Sometimes comes in handy:

''' ps_qt_version101.py
show the version number for PYSide and the QT version it used
'''

import PySide
import PySide.QtCore

# prints PySide version
print(PySide.__version__)

# gets a tuple with each version component
print(PySide.__version_info__)

print('-'*30)

# prints the Qt version used to compile PySide
print(PySide.QtCore.__version__)

# gets a tuple with each version components of Qt used to compile PySide
print(PySide.QtCore.__version_info__)

''' possible result ...
1.1.1
(1, 1, 1, 'final', 1)
------------------------------
4.7.4
(4, 7, 4)
'''
ZZucker 342 Practically a Master Poster

From last years vacation on Lake Michigan. 0bbe5a163bc1c00c67f1fbfbf1952853

ZZucker 342 Practically a Master Poster

A good approximation of the cosine of a given angle can be obtained with the following series calculation:

''' cos_approximate102.py
based on series ...
cos(x) = 1 - x2/2! + x4/4! - x6/6! + ..
'''

import math

theta = 45
x = math.radians(theta)
cosx = 1
alt = 1
for n in range(2, 15, 2):
    # alternate between 1 and -1
    alt *= -1
    cosx += alt*math.pow(x, n)/math.factorial(n)
    #print(cosx)  # test

print("Approximate cos({}) = {}".format(theta, cosx))
print("Module math cos({}) = {}".format(theta, math.cos(x)))

''' result ...
Approximate cos(45) = 0.707106781187
Module math cos(45) = 0.707106781187
'''

Write a Python program to do the calculation for this series:
sin(x) = x - x3/3! + x5/5! - x7/7! + ..

ZZucker 342 Practically a Master Poster

"A lie gets halfway around the world before the truth has a chance to get its pants on."
... Winston Churchill

ZZucker 342 Practically a Master Poster

I wonder if computers need to put up with humans 1000 years from now?

ZZucker 342 Practically a Master Poster

There ar three basic ways to load and display an image with Tkinter:

1) from an image file you have, GIF is native any other file format needs PIL
see tk example in:
http://www.daniweb.com/software-development/python/threads/191210/python-gui-programming#post866067

2) from a base64 encoded image string
pick an example from:
http://www.daniweb.com/software-development/python/code/440446/python2python3-base64-encoded-image

3) from a web page on the internet
example:
http://www.daniweb.com/software-development/python/code/467528/show-internet-image-with-tkinter

You seem to mix those thing up. Stick with one way or the other.

ZZucker 342 Practically a Master Poster

Study this in detail:
http://www.pygame.org/docs/tut/camera/CameraIntro.html
I think it supports only certain cameras.

ZZucker 342 Practically a Master Poster

This should work:

def is_string_in_list(mystring, mylist):
    for c in mystring:
        if c not in mylist:
            return False
    return True


# short test
mylist = ['a', 'b', 'c']
mystring = 'acb'
print(is_string_in_list(mystring, mylist))  # True

mystring = 'afc'
print(is_string_in_list(mystring, mylist))  # False
ZZucker 342 Practically a Master Poster

Since you are already using Python3, This would simplify it somewhat:

def get_int(prompt="Enter an integer: "):
    """this function will loop until an integer is entered"""
    while True:
        try:
            # return breaks out of the endless while loop
            return int(input(prompt))
        except ValueError:
            print("Try again, value entered was not an integer.")

width = get_int("Please enter the width of your garden in meters ")
length = get_int("Please enter the length of your garden in meters ")

# test
print(width, length)
ZZucker 342 Practically a Master Poster

I read somewhere that Google gets 15 thousand job applications a week. So good luck!

ZZucker 342 Practically a Master Poster

You might want to use a drone to crash other drones that pester you.

ZZucker 342 Practically a Master Poster

Blueberries and cream

ZZucker 342 Practically a Master Poster

The Washington Post reports that the NSA has done many thousands of illegal snooping without the approval of the rubberstamp courts. Is the system out of control?

By the time people are scared to say anything against their rulers, it's too late!

ZZucker 342 Practically a Master Poster

So this is where Samsung gets all their good ideas.

nitin1 commented: hehe.... yeah :p +0
ZZucker 342 Practically a Master Poster

To me Python has always been the quick tool to develop ideas. A bloated cumbersome IDE does not help.

ZZucker 342 Practically a Master Poster

However, if you want to use the error handler, things are a lot simpler and an integer wil be changed to a float too:

while True:
    s = raw_input("Enter a float: ")
    try:
        n = float(s)
        break
    except ValueError:
        pass

print(n)
ZZucker 342 Practically a Master Poster

Moral:
"Don't assume if a program does not work, that it is fault of the computer or the language."

ZZucker 342 Practically a Master Poster

Password expansion is a good idea. Here is one way to do it:

''' password_expand.py
a longer password is more secure, so expand it this way
'''

def password_expand(pw):
    s1 = pw
    s2 = "".join(chr(ord(c) + 1) for c in pw)
    s3 = "".join(chr(ord(c) - 1) for c in pw)
    return s1 + s2 + s3

# the user enters this password
pw = 'Nixon'

# program uses this password
pw2 = password_expand(pw)

# test
print(pw)
print('-'*30)
print(pw2)

''' my output -->
Nixon
------------------------------
NixonOjypoMhwnm
'''
ZZucker 342 Practically a Master Poster

The code from james.lu.75491856 (James Lu) can easily be cracked with character frequency analysis, since the most common characters in the English language (or any other language) will still be assigned the same sub characters.

ZZucker 342 Practically a Master Poster

Thanks Henri, module pyttsx is somewhat complicated to install, but works well.
Doesn't seem to work with Python3?

ZZucker 342 Practically a Master Poster

A slight modification of vegaseat's original code to take care of whole words:

''' re_sub_whole words.py
replace whole words in a text using Python module re
and a dictionary of key_word:replace_with pairs

tested with Python273  ZZ
'''

import re

def word_replace(text, replace_dict):
    '''
    Replace words in a text that match a key in replace_dict
    with the associated value, return the modified text.
    Only whole words are replaced.
    Note that replacement is case sensitive, but attached
    quotes and punctuation marks are neutral.
    '''
    rc = re.compile(r"[A-Za-z_]\w*")
    def translate(match):
        word = match.group(0)
        return replace_dict.get(word, word)
    return rc.sub(translate, text)

old_text = """\
In this text 'debug' will be changed but not 'debugger'.
Similarly red will be replaced but not reduce.
How about Fred, -red- and red?
Red, white and blue shipped a ship!"""

# create a dictionary of key_word:replace_with pairs
replace_dict = {
"red" : "redish",
"debug" : "fix",
'ship': 'boat'
}

new_text = word_replace(old_text, replace_dict)

print(old_text)
print('-'*60)
print(new_text)

''' my output -->
In this text 'debug' will be changed but not 'debugger'.
Similarly red will be replaced but not reduce.
How about Fred, -red- and red?
Red, white and blue shipped a ship!
------------------------------------------------------------
In this text 'fix' will be changed but not 'debugger'.
Similarly redish will be replaced but not reduce.
How about Fred, -redish- and redish?
Red, white and blue shipped a boat!
'''
ZZucker 342 Practically a Master Poster

Implement the Comb Sort algorithm in Python code.
See:
http://en.wikipedia.org/wiki/Comb_sort

ZZucker 342 Practically a Master Poster

This is my simple religion. There is no need for temples; no need for complicated philosophy. Our own brain, our own heart is our temple; the philosophy is kindness.
=== Dalai Lama

Reverend Jim commented: One of my favourites. +0
ZZucker 342 Practically a Master Poster

The Python3 str.format() method has been backported to Python 2.6.

See
http://docs.python.org/2.6/library/stdtypes.html
http://docs.python.org/2.6/whatsnew/2.6.html
and
PEP 3101

Even with Python33 you can still use the % specifier:

import sys
for key in sys.modules.keys():
    print("hello from %s" % key)
ZZucker 342 Practically a Master Poster

print(not None)

ZZucker 342 Practically a Master Poster

Thank y'all!
I studied up a little and came to these insights:

   NB. a simple 3 by 4 array ...
   array34 =: i. 3 4

   array34
0 1  2  3
4 5  6  7
8 9 10 11

   NB. this sums up each column
   +/ array34
12 15 18 21

   NB. link (;) box values original array34 (,.) and summed up (+/)
   box_vertical =: ,. @; +/
   box_horizontal =: ,. ; +/

   box_vertical array34
┌───────────┐
│0 1  2  3  │
│4 5  6  7  │
│8 9 10 11  │
├───────────┤
│12 15 18 21│
└───────────┘

   box_horizontal array34
┌─────────┬───────────┐
│0 1  2  3│12 15 18 21│
│4 5  6  7│           │
│8 9 10 11│           │
└─────────┴───────────┘
ZZucker 342 Practically a Master Poster

However, when Java is promoted as the sole programming language, its flaws and limitations become serious.
--- Bjarne Stroustrup

ZZucker 342 Practically a Master Poster

The lowest paying jobs in the USA are amongst
food preparation and serving workers (including fast food)

ZZucker 342 Practically a Master Poster

A decorator can be used to check a function's requirements:

''' require_decorator1.py
creating a general safe decorator
a safe decorator can be combined with other decorators
py2 and py3 tested on http://ideone.com/SPkbev
'''

def require(expr):
    """a general decorator checking args requirement"""
    def decorator(func):
        def wrapper(*__args,**__kw):
            message = "failed precondition %s" % expr
            assert eval(expr), message
            return func(*__args,**__kw)
        # optional next 3 lines make decorator safe
        wrapper.__name__ = func.__name__
        wrapper.__dict__ = func.__dict__
        wrapper.__doc__ = func.__doc__
        return wrapper
    return decorator

# allows only 1 argument here
@require("len(__args)==1")
def test(*args):
    print(args[0])

# no problem, prints Hello world!
test("Hello world!")

print('-'*50)

# has 2 arguments and will fail showing 
# AssertionError: failed precondition len(__args)==1
test("Hello", "World")
ZZucker 342 Practically a Master Poster

One more stone turned:

import collections
import random

# values are integers
ddict = collections.defaultdict(int)
for k in range(100):
    n = random.randint(0, 10)
    ddict[n] += 1

print(ddict[3])
ZZucker 342 Practically a Master Poster

A code snippet to search a folder full of of C code files for a given keyword/searchword. Maybe add some wildcard options.

ZZucker 342 Practically a Master Poster

The Phoenx project at least makes an attempt to create a half way good documentation for wxPython.

ZZucker 342 Practically a Master Poster

After a hint from Snippsat and Lardmeister I tested out wxPython Phoenix, a project still in development that modernizes wxPython and also makes it work for Python3:

'''wxp_html.HtmlWindow_101.py
exploring wxPython's
wx.html.HtmlWindow(parent, id, pos, size, style, name)
to show colourful text using relatively simple html code

for Python32 download the new wx phoenix version
(still in development, but works fairly well)
here the Windows version dated 11/12/2012
wxPython-Phoenix-r72945-win32-py3.2.tar.gz
from
http://wxpython.org/Phoenix/snapshot-builds/
then simply extract the wx folder to
C:\Python32\Lib\site-packages
'''

import wx
import wx.html

class MyFrame(wx.Frame):
    def __init__(self, parent, mytitle, mysize, html_code):
        wx.Frame.__init__(self, parent, wx.ID_ANY, mytitle,
            size=mysize)

        htmlwin = wx.html.HtmlWindow(self, wx.ID_ANY, style=wx.NO_BORDER)
        htmlwin.SetPage(html_code)


# simple HTML code ...
# text between <B> and </B> is bold
# <BR> inserts a line break (or new line)
# text between <FONT color="blue"> and </FONT> is that color
# text between <H3> and </H3> is header size
# etc. etc. just experiment with the <> tags
html_code = """\
This shows you how to display text in color
<BR>
<FONT color="blue">like blue text</FONT>
<FONT color="red"> or red text</FONT>
<B> or want to see it bold ...</B>
<BR>
<H3>or large size</H3><H2> or larger size</H2>
<BR>
<FONT size="+4">or even larger size</FONT>
<BR>
<FONT color="brown" size="+4">larger size and color</FONT>
<BR><BR>
... and yes, you can do scientific things like this ...
<BR>
H<sub>2</sub>O
<BR>
x<sup>3</sup> + y<sup>2</sup> - 15 = 0
"""

app = wx.App(0)
mytitle =  "wx.html.HtmlWindow formatted text"
width = 450
height = 380
frame = MyFrame(None, mytitle, (width, height), html_code)
frame.Show(True)
frame.Center() …
ZZucker 342 Practically a Master Poster

If you quickly want to try your Python code (Python2 or Python3), you can use the online IDE at:
ideone.com

It also lets you use many other languages.

Examples:
http://ideone.com/nj2Tqo
http://ideone.com/Vwo7xR

ZZucker 342 Practically a Master Poster

You can also try this:

    def incSpeed(self, event):
        print("Test", event.keysym)
ZZucker 342 Practically a Master Poster

Tkinter bind passes an event argument that you have to take care of even if you don't use it:

from tkinter import *

class App:

    def __init__(self, master):

        self.left = 0
        self.right = 0
        widget = Label(master, text='Hello bind world')
        widget.config(bg='red')
        widget.config(height=5, width=20)
        widget.pack(expand=YES, fill=BOTH)

        widget.bind('<Up>',self.incSpeed)
        widget.focus()

    def incSpeed(self, event):
        print("Test")

root = Tk()
app = App(root)
root.mainloop()
ZZucker 342 Practically a Master Poster

Maybe you mean something like this:

def create_string_list(mylist):
    string_list = ""
    for item in mylist:
        string_list += str(item) + '\n'
    return string_list


mylist = ['1','2','a','b']
string_list = create_string_list(mylist)
print(string_list)

'''result>>
1
2
a
b
'''
3e0jUn commented: Thanks! That was exactly what I wanted +1
ZZucker 342 Practically a Master Poster

You can also use the Python function eval():

print("A math expression is something like 3+5+7 (no spaces)")
math_expression = raw_input("Enter a math expression: ")
result = eval(math_expression)
print("Result of %s is %s" % (math_expression, result))
ZZucker 342 Practically a Master Poster

If you want to span over 2 rows (rows 4 and 5) use:
text.grid(row=4, column=1, rowspan=2)

ZZucker 342 Practically a Master Poster

Join the Air Force and bomb the beast called boredom.