diff --git a/.ipynb_checkpoints/Assignment1-checkpoint.ipynb b/.ipynb_checkpoints/Assignment1-checkpoint.ipynb new file mode 100644 index 0000000..2fd6442 --- /dev/null +++ b/.ipynb_checkpoints/Assignment1-checkpoint.ipynb @@ -0,0 +1,6 @@ +{ + "cells": [], + "metadata": {}, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/README.md b/README.md deleted file mode 100644 index 8bb7dbd..0000000 --- a/README.md +++ /dev/null @@ -1,25 +0,0 @@ -# SP2018-Python220-Accelerated -This repo is for Spring 2018 Python 220 Advanced Python - Accelerated Program -You can find the session notes rendered here: - -https://github.com/UWPCE-PythonCert-ClassRepos/SP2018-Python220-Accelerated - - -Class Repository For Spring 2018 Accelerated class -UWPCE Python Certificate Program - -This repository is used by the class to share information and for students to submit their work. - -Structure of the Repo -The class repo has three top level directories: - -examples: Used to store example code and example documents for the class. - -solutions: Used to post solutions to the exercises. - -students: Used for the students to submit their work. Each student will create a directory, then store work for each exercise in a subdirectory of that. - -For Students: -If you are a student in the class, you should create a fork of this repo, add your work to your fork, and use Pull Requests to submit your work for review: - -https://uwpce-pythoncert.github.io/PythonCertDevel/modules/Git.html#setting-up-your-fork-of-the-class-repository diff --git a/Students/Wayne/Activities/Lesson_01/.ipynb_checkpoints/Activity1-checkpoint.ipynb b/Students/Wayne/Activities/Lesson_01/.ipynb_checkpoints/Activity1-checkpoint.ipynb new file mode 100644 index 0000000..cb488bb --- /dev/null +++ b/Students/Wayne/Activities/Lesson_01/.ipynb_checkpoints/Activity1-checkpoint.ipynb @@ -0,0 +1,968 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Iterators and Iterables" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [], + "source": [ + "class IterateMe_1:\n", + " \"\"\"\n", + " About as simple an iterator as you can get:\n", + "\n", + " returns the sequence of numbers from zero to 4\n", + " ( like range(4) )\n", + " \"\"\"\n", + "\n", + " def __init__(self, stop=10):\n", + " self.current = -1\n", + " self.stop = stop\n", + "\n", + " def __iter__(self):\n", + " return self\n", + "\n", + " def __next__(self):\n", + " self.current += 1\n", + " if self.current < self.stop:\n", + " return self.current\n", + " else:\n", + " raise StopIteration\n", + "\n", + "\n", + "class IterateMe_2:\n", + "\n", + " def __init__(self, start, stop, step):\n", + " self.current = start - step\n", + " self.stop = stop\n", + " self.start = start\n", + " self.step = step\n", + "\n", + " def __iter__(self):\n", + " return self\n", + "\n", + " def __next__(self):\n", + " self.current += self.step\n", + " if self.current < self.stop:\n", + " return self.current\n", + " else:\n", + " raise StopIteration\n", + "\n", + "\n", + "it = IterateMe_2(2, 20, 2)\n", + "for i in it:\n", + " if i > 10: break\n", + "\n", + "\n", + "def rng():\n", + " print(\"Range function\")\n", + " for i in range(2, 20, 2):\n", + " print(i)\n" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Testing the iterator\n", + "0\n", + "1\n", + "2\n", + "3\n", + "4\n", + "5\n", + "6\n", + "7\n", + "8\n", + "9\n", + "Testing the IT iterator\n", + "14\n", + "16\n", + "18\n", + "Range function\n", + "2\n", + "4\n", + "6\n", + "8\n", + "10\n", + "12\n", + "14\n", + "16\n", + "18\n" + ] + } + ], + "source": [ + "if __name__ == \"__main__\":\n", + "\n", + " print(\"Testing the iterator\")\n", + " for i in IterateMe_1():\n", + " print(i)\n", + "\n", + " print(\"Testing the IT iterator\")\n", + " for i in it:\n", + " print(i)\n", + "\n", + "rng()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "is range an iterator or an iteratable? Range is an interables, because you cannot call next on range. An iterator will change the state of the objects in the sequence." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# GENERATOR" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Sum of the integers:\n", + "\n", + "keep adding the next integer\n", + "\n", + "0 + 1 + 2 + 3 + 4 + 5 + …\n", + "\n", + "so the sequence is:\n", + "\n", + "0, 1, 3, 6, 10, 15 ….." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "def sum_fun():\n", + " for n in range(1,6,1):\n", + " yield n*(n+1)/2\n", + " \n", + "sum_it = (sum_fun())" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "list(sum_it)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Doubler:\n", + "\n", + "Each value is double the previous value:\n", + "\n", + "1, 2, 4, 8, 16, 32," + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "def doubler():\n", + " for n in range(1,7,1):\n", + " yield (n+1)*2\n", + " \n", + " \n", + "double_it = (doubler())" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "list(double_it)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Fibonacci sequence:\n", + " \n", + "The Fibonacci sequence as a generator:\n", + "\n", + "f(n) = f(n-1) + f(n-2)\n", + "\n", + "1, 1, 2, 3, 5, 8, 13, 21, 34…" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Generate the prime numbers (numbers only divisible by them self and 1):\n", + "\n", + "2, 3, 5, 7, 11, 13, 17, 19, 23…" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Calculator Exercise\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "This is the functional vs imperative exervise" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "OPERATORS = '+', '-', '*', '/'\n", + "\n", + "\n", + "def p_main():\n", + " \n", + " \"\"\"The main flow.\"\"\"\n", + "\n", + " print('Welcome to the barely functional calculator!')\n", + " number1 = p_get_number()\n", + " operator = p_get_operator()\n", + " number2 = p_get_number()\n", + " result = p_calculate(number1, operator, number2)\n", + " print('The result is: %s' % result)\n", + "\n", + "\n", + "def p_get_number():\n", + " \n", + " \"\"\"Reads an integer from the standard input and returns it.\n", + " If a non-integer value is entered, a warning is printed,\n", + " and a new value is read.\"\"\"\n", + " \n", + " while True:\n", + " s = input('Enter an integer: ')\n", + " try:\n", + " return int(s)\n", + " except ValueError:\n", + " print('That is not an integer!')\n", + " \n", + "\n", + "def p_get_operator():\n", + " \n", + " \"\"\"Reads an operator from the standard input and returns it.\n", + " Valid operators are: +, -, *, and /. If an invalid operator\n", + " is entered, a warning is printed, and a new value is read.\"\"\" \n", + " \n", + " while True:\n", + " s = input('Enter an operator (+, -, *, or /): ')\n", + " if s in OPERATORS:\n", + " return s\n", + " print('That is not an operator!')\n", + " \n", + " \n", + "def p_calculate(number1, operator, number2):\n", + " \n", + " \"\"\"Performs a calculation with two numbers and an operator,\n", + " and returns the result.\"\"\"\n", + " \n", + " if operator == '+':\n", + " return number1 + number2\n", + " if operator == '-':\n", + " return number1 - number2\n", + " if operator == '*':\n", + " return number1 * number2\n", + " if operator == '/':\n", + " return number1 / number2\n", + " raise Exception('Invalid operator!')\n", + "\n", + " \n", + "p_main()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "OPERATORS = '+', '-', '*', '/'\n", + "\n", + "def f_get_number():\n", + " return int(input('Enter an integer:'))\n", + "\n", + "\n", + "def f_get_operator():\n", + " return input('Enter an operator(+,-,*,/):')\n", + "\n", + "\n", + "def f_calculate(number1, operator, number2) :\n", + " return number1+number2 if operator == '+' \\\n", + " else number1*number2 if operator == \"*\"\\\n", + " else number1-number2 if operator == '-'\\\n", + " else number1/number2 if operator == '/'\\\n", + " else None\n", + "\n", + "\n", + "def f_main():\n", + " return f_calculate(\n", + " f_get_number(),\n", + " f_get_operator(),\n", + " f_get_number()\n", + " )\n", + "print('the result is :%s' % f_main())\n", + "\n", + " " + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Comprehensions" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "list(range(10))" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "for x in range(10):\n", + " print (x)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# MAP" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "items = [1, 2, 3, 4, 5]\n", + "squared = list(map(lambda x: x**2, items))\n", + "print(squared)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Filter" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "number_list = range(-10, 10)\n", + "less_than_zero = list(filter(lambda x: x < 0, number_list))\n", + "print(less_than_zero)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "number_list = range(-10, 10)\n", + "less_than_zero = list(filter(lambda x: x > 0, number_list))\n", + "print(less_than_zero)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "l = [2,3,4,5,6,8,9,10,11,12]\n", + "list(filter(lambda x: not x%2, l))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Reduce" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "from functools import reduce\n", + "product = reduce((lambda x, y: x * y), [1, 2, 3])\n", + "print(product)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# List Comprehension" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "multiples = [i for i in range(30) if i % 3 == 0]\n", + "print(multiples)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "squared = [x**2 for x in range(10)]\n", + "print(squared)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Dict Comprehension" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "mcase = {'a': 5, 'b': 3, 'A': 7, 'Z': 6}\n", + "{v: k for k, v in mcase.items()}" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Set Comprehension" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "squared = {x**2 for x in [0,1,1,2]}\n", + "print(squared)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# In the previous set example, can you explain the output?" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "the output of 0, 1, 4 is explained by the fact that a set can only have one unique output...\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# LAMBDA" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "lambda x: x*2" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "lambda x:x*2" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "(lambda x:x*2)(4)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "l = [lambda x, y: x+y]" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "type(l[0])" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "leg = ((27.154167, -80.195663), (29.195168, -81.002998), 129.7748)\n", + "start= lambda x: x[0]\n", + "end = lambda x: x[1]\n", + "dist = lambda x: x[2]\n", + "dist(leg)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Iter() Operation\n", + "Examples of Iter - lists, dictionaries etc ...." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "iter([2,3,4])" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "iter({1:2, 3:4, 5:8})" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "## is this iterable? Try ....\n", + "\n", + "iter(104)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "##Lets start with user defined String class\n", + "class String(object):\n", + " def __init__(self, val):\n", + " self.val = val\n", + " def __str__(self):\n", + " return self.val" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "st = String('sample string')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Is the above string iterable? lets test it." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Why didn't this work?\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# What's missing?" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "the magic - an_iterator.iter()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Then, how should we make user defined type iterable?" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "This can be done by extending our String class with iter constructor" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "class String(object):\n", + " def __init__(self, val):\n", + " self.val = val\n", + " def __str__(self):\n", + " return self.val\n", + " def __iter__(self):\n", + " print (\"This is __iter__ method of String class\")\n", + " return iter(self.val) #self.val is python string so iter() will return it's iterator" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "st = String('Sample String')" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "iter(st)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# We added a iter method in our String class to make String type as iterable. That means iter(iterable) calls iterable.iter() internally.\n", + "You could also do this using getitem" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "class String(object):\n", + " def __init__(self, val):\n", + " self.val = val\n", + " def __str__(self):\n", + " return self.val\n", + " def __getitem__(self, index):\n", + " return self.val[index]" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "st = String('Sample String')" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "iter(st)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# We added getitem method and user defined String type becomes iterable. So iter(iterable) look for iterable.getitem() also.¶" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Iterator\n", + "1)Iterator object produces values of iterable during iteration. next() or next() is applied on iterator for producing next value\n", + "\n", + "2)It raises StopIteration exception at the end of iteration\n", + "\n", + "3)iter() function return iterator object for an iterable\n", + "\n", + "4)If iter() function is applied on iterator object, it returns same object" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "## List as an iterator\n", + "\n", + "a_list = [1,2,3]\n", + "list_iter = a_list.__iter__()\n", + "\n", + "## before python 2.6 I think - list_iter.next()\n", + "list_iter.__next__()\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "list_iter.__next__()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# IterTools\n", + "itertools is a collection of utilities that make it easy to build an iterator that iterates over sequences in various common ways\n", + "\n", + "http://docs.python.org/library/itertools.html\n", + "\n", + "NOTE:\n", + "\n", + "iterators are not only for for\n", + "\n", + "They can be used with anything that expects an iterator:\n", + "\n", + "sum, tuple, sorted, and list\n", + "\n", + "For example." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import itertools\n", + "\n", + "letters = ['a', 'b', 'c', 'd', 'e', 'f']\n", + "booleans = [1, 0, 1, 0, 0, 1]\n", + "numbers = [23, 20, 44, 32, 7, 12]\n", + "decimals = [0.1, 0.7, 0.4, 0.4, 0.5]" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Chain" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "print (list(itertools.chain(letters, booleans, decimals)))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# compress()\n", + "compress(): given two lists a and b, return the elements of a for which the corresponding elements of b are Tru" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "print (list(itertools.compress(letters, booleans)))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Zip ()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "xi= [1.47, 1.50, 1.52, 1.55, 1.57, 1.60, 1.63, 1.65]\n", + "yi= [52.21, 53.12, 54.48, 55.84, 57.20, 58.57, 59.93, 61.29]\n", + "zip( xi, yi )" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "list(zip( xi, yi ))" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "zip( xi, yi )" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "list(_)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# We can see that the zip() function with no arguments is a generator function, but there won't be any items. This fits the requirement that the output is iterable." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "zip( (1,2,3) )" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "list(_)\n", + "\n", + "## In this case, the zip() function emitted one tuple from each input value. This too makes considerable sense." + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.6.5" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/Students/Wayne/Activities/Lesson_01/.ipynb_checkpoints/Concept-7-Iterables-Iter-Iterators-Etc-checkpoint.ipynb b/Students/Wayne/Activities/Lesson_01/.ipynb_checkpoints/Concept-7-Iterables-Iter-Iterators-Etc-checkpoint.ipynb new file mode 100644 index 0000000..6746afe --- /dev/null +++ b/Students/Wayne/Activities/Lesson_01/.ipynb_checkpoints/Concept-7-Iterables-Iter-Iterators-Etc-checkpoint.ipynb @@ -0,0 +1,418 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Iter() Operation\n", + "\n", + "Examples of Iter - lists, dictionaries etc ....\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "iter([2,3,4])" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "iter({1:2, 3:4, 5:8})" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "## is this iterable? Try ....\n", + "\n", + "iter(104)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "##Lets start with user defined String class\n", + "class String(object):\n", + " def __init__(self, val):\n", + " self.val = val\n", + " def __str__(self):\n", + " return self.val" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "st = String('sample string')\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Is the above string iterable? lets test it. \n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "iter(st)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Why didn't this work? \n", + "## What's missing?\n", + "\n", + "the magic - an_iterator.__iter__()\n", + "\n", + "## Then, how should we make user defined type iterable? \n", + "This can be done by extending our String class with iter constructor\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "class String(object):\n", + " def __init__(self, val):\n", + " self.val = val\n", + " def __str__(self):\n", + " return self.val\n", + " def __iter__(self):\n", + " print (\"This is __iter__ method of String class\")\n", + " return iter(self.val) #self.val is python string so iter() will return it's iterator" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "st = String('Sample String')" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "iter(st)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## We added a __iter__ method in our String class to make String type as iterable. That means iter(iterable) calls iterable.__iter__() internally.\n", + "\n", + "You could also do this using getitem" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "class String(object):\n", + " def __init__(self, val):\n", + " self.val = val\n", + " def __str__(self):\n", + " return self.val\n", + " def __getitem__(self, index):\n", + " return self.val[index]" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "st = String('Sample String')" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "iter(st)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## We added __getitem__ method and user defined String type becomes iterable. So iter(iterable) look for iterable.__getitem__() also." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Iterator\n", + "\n", + "1. Iterator object produces values of iterable during iteration. next() or __next__() is applied on iterator for producing next value\n", + "2. It raises StopIteration exception at the end of iteration\n", + "3. iter() function return iterator object for an iterable\n", + "4. If iter() function is applied on iterator object, it returns same object" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "## List as an iterator\n", + "\n", + "a_list = [1,2,3]\n", + "list_iter = a_list.__iter__()\n", + "\n", + "## before python 2.6 I think - list_iter.next()\n", + "list_iter.__next__()\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "list_iter.__next__()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "## see what happens after 2 more times?\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## IterTools\n", + "\n", + "\n", + "itertools is a collection of utilities that make it easy to build an iterator that iterates over sequences in various common ways\n", + "\n", + "http://docs.python.org/library/itertools.html\n", + "\n", + "NOTE:\n", + "\n", + "iterators are not only for for\n", + "\n", + "They can be used with anything that expects an iterator:\n", + "\n", + "sum, tuple, sorted, and list\n", + "\n", + "For example.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import itertools\n", + "\n", + "letters = ['a', 'b', 'c', 'd', 'e', 'f']\n", + "booleans = [1, 0, 1, 0, 0, 1]\n", + "numbers = [23, 20, 44, 32, 7, 12]\n", + "decimals = [0.1, 0.7, 0.4, 0.4, 0.5]" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Chain\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "print (list(itertools.chain(letters, booleans, decimals)))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## compress()\n", + "\n", + "compress(): given two lists a and b, return the elements of a for which the corresponding elements of b are True.\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "print (list(itertools.compress(letters, booleans)))\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Zip ()\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "xi= [1.47, 1.50, 1.52, 1.55, 1.57, 1.60, 1.63, 1.65]\n", + "yi= [52.21, 53.12, 54.48, 55.84, 57.20, 58.57, 59.93, 61.29]\n", + "zip( xi, yi )\n", + " " + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "list(zip( xi, yi ))" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "zip( xi, yi )" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "list(_)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## We can see that the zip() function with no arguments is a generator function, but there won't be any items. This fits the requirement that the output is iterable.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "zip( (1,2,3) )" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "list(_)\n", + "\n", + "## In this case, the zip() function emitted one tuple from each input value. This too makes considerable sense." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.6.5" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/Students/Wayne/Activities/Lesson_01/Activity1.ipynb b/Students/Wayne/Activities/Lesson_01/Activity1.ipynb new file mode 100644 index 0000000..cb488bb --- /dev/null +++ b/Students/Wayne/Activities/Lesson_01/Activity1.ipynb @@ -0,0 +1,968 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Iterators and Iterables" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [], + "source": [ + "class IterateMe_1:\n", + " \"\"\"\n", + " About as simple an iterator as you can get:\n", + "\n", + " returns the sequence of numbers from zero to 4\n", + " ( like range(4) )\n", + " \"\"\"\n", + "\n", + " def __init__(self, stop=10):\n", + " self.current = -1\n", + " self.stop = stop\n", + "\n", + " def __iter__(self):\n", + " return self\n", + "\n", + " def __next__(self):\n", + " self.current += 1\n", + " if self.current < self.stop:\n", + " return self.current\n", + " else:\n", + " raise StopIteration\n", + "\n", + "\n", + "class IterateMe_2:\n", + "\n", + " def __init__(self, start, stop, step):\n", + " self.current = start - step\n", + " self.stop = stop\n", + " self.start = start\n", + " self.step = step\n", + "\n", + " def __iter__(self):\n", + " return self\n", + "\n", + " def __next__(self):\n", + " self.current += self.step\n", + " if self.current < self.stop:\n", + " return self.current\n", + " else:\n", + " raise StopIteration\n", + "\n", + "\n", + "it = IterateMe_2(2, 20, 2)\n", + "for i in it:\n", + " if i > 10: break\n", + "\n", + "\n", + "def rng():\n", + " print(\"Range function\")\n", + " for i in range(2, 20, 2):\n", + " print(i)\n" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Testing the iterator\n", + "0\n", + "1\n", + "2\n", + "3\n", + "4\n", + "5\n", + "6\n", + "7\n", + "8\n", + "9\n", + "Testing the IT iterator\n", + "14\n", + "16\n", + "18\n", + "Range function\n", + "2\n", + "4\n", + "6\n", + "8\n", + "10\n", + "12\n", + "14\n", + "16\n", + "18\n" + ] + } + ], + "source": [ + "if __name__ == \"__main__\":\n", + "\n", + " print(\"Testing the iterator\")\n", + " for i in IterateMe_1():\n", + " print(i)\n", + "\n", + " print(\"Testing the IT iterator\")\n", + " for i in it:\n", + " print(i)\n", + "\n", + "rng()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "is range an iterator or an iteratable? Range is an interables, because you cannot call next on range. An iterator will change the state of the objects in the sequence." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# GENERATOR" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Sum of the integers:\n", + "\n", + "keep adding the next integer\n", + "\n", + "0 + 1 + 2 + 3 + 4 + 5 + …\n", + "\n", + "so the sequence is:\n", + "\n", + "0, 1, 3, 6, 10, 15 ….." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "def sum_fun():\n", + " for n in range(1,6,1):\n", + " yield n*(n+1)/2\n", + " \n", + "sum_it = (sum_fun())" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "list(sum_it)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Doubler:\n", + "\n", + "Each value is double the previous value:\n", + "\n", + "1, 2, 4, 8, 16, 32," + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "def doubler():\n", + " for n in range(1,7,1):\n", + " yield (n+1)*2\n", + " \n", + " \n", + "double_it = (doubler())" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "list(double_it)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Fibonacci sequence:\n", + " \n", + "The Fibonacci sequence as a generator:\n", + "\n", + "f(n) = f(n-1) + f(n-2)\n", + "\n", + "1, 1, 2, 3, 5, 8, 13, 21, 34…" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Generate the prime numbers (numbers only divisible by them self and 1):\n", + "\n", + "2, 3, 5, 7, 11, 13, 17, 19, 23…" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Calculator Exercise\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "This is the functional vs imperative exervise" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "OPERATORS = '+', '-', '*', '/'\n", + "\n", + "\n", + "def p_main():\n", + " \n", + " \"\"\"The main flow.\"\"\"\n", + "\n", + " print('Welcome to the barely functional calculator!')\n", + " number1 = p_get_number()\n", + " operator = p_get_operator()\n", + " number2 = p_get_number()\n", + " result = p_calculate(number1, operator, number2)\n", + " print('The result is: %s' % result)\n", + "\n", + "\n", + "def p_get_number():\n", + " \n", + " \"\"\"Reads an integer from the standard input and returns it.\n", + " If a non-integer value is entered, a warning is printed,\n", + " and a new value is read.\"\"\"\n", + " \n", + " while True:\n", + " s = input('Enter an integer: ')\n", + " try:\n", + " return int(s)\n", + " except ValueError:\n", + " print('That is not an integer!')\n", + " \n", + "\n", + "def p_get_operator():\n", + " \n", + " \"\"\"Reads an operator from the standard input and returns it.\n", + " Valid operators are: +, -, *, and /. If an invalid operator\n", + " is entered, a warning is printed, and a new value is read.\"\"\" \n", + " \n", + " while True:\n", + " s = input('Enter an operator (+, -, *, or /): ')\n", + " if s in OPERATORS:\n", + " return s\n", + " print('That is not an operator!')\n", + " \n", + " \n", + "def p_calculate(number1, operator, number2):\n", + " \n", + " \"\"\"Performs a calculation with two numbers and an operator,\n", + " and returns the result.\"\"\"\n", + " \n", + " if operator == '+':\n", + " return number1 + number2\n", + " if operator == '-':\n", + " return number1 - number2\n", + " if operator == '*':\n", + " return number1 * number2\n", + " if operator == '/':\n", + " return number1 / number2\n", + " raise Exception('Invalid operator!')\n", + "\n", + " \n", + "p_main()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "OPERATORS = '+', '-', '*', '/'\n", + "\n", + "def f_get_number():\n", + " return int(input('Enter an integer:'))\n", + "\n", + "\n", + "def f_get_operator():\n", + " return input('Enter an operator(+,-,*,/):')\n", + "\n", + "\n", + "def f_calculate(number1, operator, number2) :\n", + " return number1+number2 if operator == '+' \\\n", + " else number1*number2 if operator == \"*\"\\\n", + " else number1-number2 if operator == '-'\\\n", + " else number1/number2 if operator == '/'\\\n", + " else None\n", + "\n", + "\n", + "def f_main():\n", + " return f_calculate(\n", + " f_get_number(),\n", + " f_get_operator(),\n", + " f_get_number()\n", + " )\n", + "print('the result is :%s' % f_main())\n", + "\n", + " " + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Comprehensions" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "list(range(10))" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "for x in range(10):\n", + " print (x)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# MAP" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "items = [1, 2, 3, 4, 5]\n", + "squared = list(map(lambda x: x**2, items))\n", + "print(squared)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Filter" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "number_list = range(-10, 10)\n", + "less_than_zero = list(filter(lambda x: x < 0, number_list))\n", + "print(less_than_zero)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "number_list = range(-10, 10)\n", + "less_than_zero = list(filter(lambda x: x > 0, number_list))\n", + "print(less_than_zero)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "l = [2,3,4,5,6,8,9,10,11,12]\n", + "list(filter(lambda x: not x%2, l))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Reduce" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "from functools import reduce\n", + "product = reduce((lambda x, y: x * y), [1, 2, 3])\n", + "print(product)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# List Comprehension" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "multiples = [i for i in range(30) if i % 3 == 0]\n", + "print(multiples)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "squared = [x**2 for x in range(10)]\n", + "print(squared)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Dict Comprehension" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "mcase = {'a': 5, 'b': 3, 'A': 7, 'Z': 6}\n", + "{v: k for k, v in mcase.items()}" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Set Comprehension" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "squared = {x**2 for x in [0,1,1,2]}\n", + "print(squared)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# In the previous set example, can you explain the output?" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "the output of 0, 1, 4 is explained by the fact that a set can only have one unique output...\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# LAMBDA" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "lambda x: x*2" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "lambda x:x*2" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "(lambda x:x*2)(4)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "l = [lambda x, y: x+y]" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "type(l[0])" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "leg = ((27.154167, -80.195663), (29.195168, -81.002998), 129.7748)\n", + "start= lambda x: x[0]\n", + "end = lambda x: x[1]\n", + "dist = lambda x: x[2]\n", + "dist(leg)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Iter() Operation\n", + "Examples of Iter - lists, dictionaries etc ...." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "iter([2,3,4])" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "iter({1:2, 3:4, 5:8})" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "## is this iterable? Try ....\n", + "\n", + "iter(104)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "##Lets start with user defined String class\n", + "class String(object):\n", + " def __init__(self, val):\n", + " self.val = val\n", + " def __str__(self):\n", + " return self.val" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "st = String('sample string')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Is the above string iterable? lets test it." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Why didn't this work?\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# What's missing?" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "the magic - an_iterator.iter()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Then, how should we make user defined type iterable?" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "This can be done by extending our String class with iter constructor" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "class String(object):\n", + " def __init__(self, val):\n", + " self.val = val\n", + " def __str__(self):\n", + " return self.val\n", + " def __iter__(self):\n", + " print (\"This is __iter__ method of String class\")\n", + " return iter(self.val) #self.val is python string so iter() will return it's iterator" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "st = String('Sample String')" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "iter(st)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# We added a iter method in our String class to make String type as iterable. That means iter(iterable) calls iterable.iter() internally.\n", + "You could also do this using getitem" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "class String(object):\n", + " def __init__(self, val):\n", + " self.val = val\n", + " def __str__(self):\n", + " return self.val\n", + " def __getitem__(self, index):\n", + " return self.val[index]" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "st = String('Sample String')" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "iter(st)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# We added getitem method and user defined String type becomes iterable. So iter(iterable) look for iterable.getitem() also.¶" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Iterator\n", + "1)Iterator object produces values of iterable during iteration. next() or next() is applied on iterator for producing next value\n", + "\n", + "2)It raises StopIteration exception at the end of iteration\n", + "\n", + "3)iter() function return iterator object for an iterable\n", + "\n", + "4)If iter() function is applied on iterator object, it returns same object" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "## List as an iterator\n", + "\n", + "a_list = [1,2,3]\n", + "list_iter = a_list.__iter__()\n", + "\n", + "## before python 2.6 I think - list_iter.next()\n", + "list_iter.__next__()\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "list_iter.__next__()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# IterTools\n", + "itertools is a collection of utilities that make it easy to build an iterator that iterates over sequences in various common ways\n", + "\n", + "http://docs.python.org/library/itertools.html\n", + "\n", + "NOTE:\n", + "\n", + "iterators are not only for for\n", + "\n", + "They can be used with anything that expects an iterator:\n", + "\n", + "sum, tuple, sorted, and list\n", + "\n", + "For example." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import itertools\n", + "\n", + "letters = ['a', 'b', 'c', 'd', 'e', 'f']\n", + "booleans = [1, 0, 1, 0, 0, 1]\n", + "numbers = [23, 20, 44, 32, 7, 12]\n", + "decimals = [0.1, 0.7, 0.4, 0.4, 0.5]" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Chain" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "print (list(itertools.chain(letters, booleans, decimals)))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# compress()\n", + "compress(): given two lists a and b, return the elements of a for which the corresponding elements of b are Tru" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "print (list(itertools.compress(letters, booleans)))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Zip ()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "xi= [1.47, 1.50, 1.52, 1.55, 1.57, 1.60, 1.63, 1.65]\n", + "yi= [52.21, 53.12, 54.48, 55.84, 57.20, 58.57, 59.93, 61.29]\n", + "zip( xi, yi )" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "list(zip( xi, yi ))" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "zip( xi, yi )" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "list(_)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# We can see that the zip() function with no arguments is a generator function, but there won't be any items. This fits the requirement that the output is iterable." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "zip( (1,2,3) )" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "list(_)\n", + "\n", + "## In this case, the zip() function emitted one tuple from each input value. This too makes considerable sense." + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.6.5" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/Students/Wayne/Activities/Lesson_01/Activity1.py b/Students/Wayne/Activities/Lesson_01/Activity1.py new file mode 100644 index 0000000..81c1c04 --- /dev/null +++ b/Students/Wayne/Activities/Lesson_01/Activity1.py @@ -0,0 +1,601 @@ + +# coding: utf-8 + +# # Iterators and Iterables + +# In[1]: + + +class IterateMe_1: + """ + About as simple an iterator as you can get: + + returns the sequence of numbers from zero to 4 + ( like range(4) ) + """ + + def __init__(self, stop=10): + self.current = -1 + self.stop = stop + + def __iter__(self): + return self + + def __next__(self): + self.current += 1 + if self.current < self.stop: + return self.current + else: + raise StopIteration + + +class IterateMe_2: + + def __init__(self, start, stop, step): + self.current = start - step + self.stop = stop + self.start = start + self.step = step + + def __iter__(self): + return self + + def __next__(self): + self.current += self.step + if self.current < self.stop: + return self.current + else: + raise StopIteration + + +it = IterateMe_2(2, 20, 2) +for i in it: + if i > 10: break + + +def rng(): + print("Range function") + for i in range(2, 20, 2): + print(i) + + +# In[2]: + + +if __name__ == "__main__": + + print("Testing the iterator") + for i in IterateMe_1(): + print(i) + + print("Testing the IT iterator") + for i in it: + print(i) + +rng() + + +# is range an iterator or an iteratable? Range is an interables, because you cannot call next on range. An iterator will change the state of the objects in the sequence. + +# # GENERATOR + +# Sum of the integers: +# +# keep adding the next integer +# +# 0 + 1 + 2 + 3 + 4 + 5 + … +# +# so the sequence is: +# +# 0, 1, 3, 6, 10, 15 ….. + +# In[ ]: + + +def sum_fun(): + for n in range(1,6,1): + yield n*(n+1)/2 + +sum_it = (sum_fun()) + + +# In[ ]: + + +list(sum_it) + + +# Doubler: +# +# Each value is double the previous value: +# +# 1, 2, 4, 8, 16, 32, + +# In[ ]: + + +def doubler(): + for n in range(1,7,1): + yield (n+1)*2 + + +double_it = (doubler()) + + +# In[ ]: + + +list(double_it) + + +# Fibonacci sequence: +# +# The Fibonacci sequence as a generator: +# +# f(n) = f(n-1) + f(n-2) +# +# 1, 1, 2, 3, 5, 8, 13, 21, 34… + +# Generate the prime numbers (numbers only divisible by them self and 1): +# +# 2, 3, 5, 7, 11, 13, 17, 19, 23… + +# # Calculator Exercise +# + +# This is the functional vs imperative exervise + +# In[ ]: + + +OPERATORS = '+', '-', '*', '/' + + +def p_main(): + + """The main flow.""" + + print('Welcome to the barely functional calculator!') + number1 = p_get_number() + operator = p_get_operator() + number2 = p_get_number() + result = p_calculate(number1, operator, number2) + print('The result is: %s' % result) + + +def p_get_number(): + + """Reads an integer from the standard input and returns it. + If a non-integer value is entered, a warning is printed, + and a new value is read.""" + + while True: + s = input('Enter an integer: ') + try: + return int(s) + except ValueError: + print('That is not an integer!') + + +def p_get_operator(): + + """Reads an operator from the standard input and returns it. + Valid operators are: +, -, *, and /. If an invalid operator + is entered, a warning is printed, and a new value is read.""" + + while True: + s = input('Enter an operator (+, -, *, or /): ') + if s in OPERATORS: + return s + print('That is not an operator!') + + +def p_calculate(number1, operator, number2): + + """Performs a calculation with two numbers and an operator, + and returns the result.""" + + if operator == '+': + return number1 + number2 + if operator == '-': + return number1 - number2 + if operator == '*': + return number1 * number2 + if operator == '/': + return number1 / number2 + raise Exception('Invalid operator!') + + +p_main() + + +# In[ ]: + + +OPERATORS = '+', '-', '*', '/' + +def f_get_number(): + return int(input('Enter an integer:')) + + +def f_get_operator(): + return input('Enter an operator(+,-,*,/):') + + +def f_calculate(number1, operator, number2) : + return number1+number2 if operator == '+' else number1*number2 if operator == "*" else number1-number2 if operator == '-' else number1/number2 if operator == '/' else None + + +def f_main(): + return f_calculate( + f_get_number(), + f_get_operator(), + f_get_number() + ) +print('the result is :%s' % f_main()) + + + + +# # Comprehensions + +# In[ ]: + + +list(range(10)) + + +# In[ ]: + + +for x in range(10): + print (x) + + +# # MAP + +# In[ ]: + + +items = [1, 2, 3, 4, 5] +squared = list(map(lambda x: x**2, items)) +print(squared) + + +# # Filter + +# In[ ]: + + +number_list = range(-10, 10) +less_than_zero = list(filter(lambda x: x < 0, number_list)) +print(less_than_zero) + + +# In[ ]: + + +number_list = range(-10, 10) +less_than_zero = list(filter(lambda x: x > 0, number_list)) +print(less_than_zero) + + +# In[ ]: + + +l = [2,3,4,5,6,8,9,10,11,12] +list(filter(lambda x: not x%2, l)) + + +# # Reduce + +# In[ ]: + + +from functools import reduce +product = reduce((lambda x, y: x * y), [1, 2, 3]) +print(product) + + +# # List Comprehension + +# In[ ]: + + +multiples = [i for i in range(30) if i % 3 == 0] +print(multiples) + + +# In[ ]: + + +squared = [x**2 for x in range(10)] +print(squared) + + +# # Dict Comprehension + +# In[ ]: + + +mcase = {'a': 5, 'b': 3, 'A': 7, 'Z': 6} +{v: k for k, v in mcase.items()} + + +# # Set Comprehension + +# In[ ]: + + +squared = {x**2 for x in [0,1,1,2]} +print(squared) + + +# # In the previous set example, can you explain the output? + +# the output of 0, 1, 4 is explained by the fact that a set can only have one unique output... +# +# + +# # LAMBDA + +# In[ ]: + + +lambda x: x*2 + + +# In[ ]: + + +lambda x:x*2 + + +# In[ ]: + + +(lambda x:x*2)(4) + + +# In[ ]: + + +l = [lambda x, y: x+y] + + +# In[ ]: + + +type(l[0]) + + +# In[ ]: + + +leg = ((27.154167, -80.195663), (29.195168, -81.002998), 129.7748) +start= lambda x: x[0] +end = lambda x: x[1] +dist = lambda x: x[2] +dist(leg) + + +# # Iter() Operation +# Examples of Iter - lists, dictionaries etc .... + +# In[ ]: + + +iter([2,3,4]) + + +# In[ ]: + + +iter({1:2, 3:4, 5:8}) + + +# In[ ]: + + +## is this iterable? Try .... + +iter(104) + + +# In[ ]: + + +##Lets start with user defined String class +class String(object): + def __init__(self, val): + self.val = val + def __str__(self): + return self.val + + +# In[ ]: + + +st = String('sample string') + + +# # Is the above string iterable? lets test it. + +# # Why didn't this work? +# + +# # What's missing? + +# the magic - an_iterator.iter() + +# # Then, how should we make user defined type iterable? + +# This can be done by extending our String class with iter constructor + +# In[ ]: + + +class String(object): + def __init__(self, val): + self.val = val + def __str__(self): + return self.val + def __iter__(self): + print ("This is __iter__ method of String class") + return iter(self.val) #self.val is python string so iter() will return it's iterator + + +# In[ ]: + + +st = String('Sample String') + + +# In[ ]: + + +iter(st) + + +# # We added a iter method in our String class to make String type as iterable. That means iter(iterable) calls iterable.iter() internally. +# You could also do this using getitem + +# In[ ]: + + +class String(object): + def __init__(self, val): + self.val = val + def __str__(self): + return self.val + def __getitem__(self, index): + return self.val[index] + + +# In[ ]: + + +st = String('Sample String') + + +# In[ ]: + + +iter(st) + + +# # We added getitem method and user defined String type becomes iterable. So iter(iterable) look for iterable.getitem() also.¶ + +# # Iterator +# 1)Iterator object produces values of iterable during iteration. next() or next() is applied on iterator for producing next value +# +# 2)It raises StopIteration exception at the end of iteration +# +# 3)iter() function return iterator object for an iterable +# +# 4)If iter() function is applied on iterator object, it returns same object + +# In[ ]: + + +## List as an iterator + +a_list = [1,2,3] +list_iter = a_list.__iter__() + +## before python 2.6 I think - list_iter.next() +list_iter.__next__() + + +# In[ ]: + + +list_iter.__next__() + + +# # IterTools +# itertools is a collection of utilities that make it easy to build an iterator that iterates over sequences in various common ways +# +# http://docs.python.org/library/itertools.html +# +# NOTE: +# +# iterators are not only for for +# +# They can be used with anything that expects an iterator: +# +# sum, tuple, sorted, and list +# +# For example. + +# In[ ]: + + +import itertools + +letters = ['a', 'b', 'c', 'd', 'e', 'f'] +booleans = [1, 0, 1, 0, 0, 1] +numbers = [23, 20, 44, 32, 7, 12] +decimals = [0.1, 0.7, 0.4, 0.4, 0.5] + + +# # Chain + +# In[ ]: + + +print (list(itertools.chain(letters, booleans, decimals))) + + +# # compress() +# compress(): given two lists a and b, return the elements of a for which the corresponding elements of b are Tru + +# In[ ]: + + +print (list(itertools.compress(letters, booleans))) + + +# # Zip () + +# In[ ]: + + +xi= [1.47, 1.50, 1.52, 1.55, 1.57, 1.60, 1.63, 1.65] +yi= [52.21, 53.12, 54.48, 55.84, 57.20, 58.57, 59.93, 61.29] +zip( xi, yi ) + + +# In[ ]: + + +list(zip( xi, yi )) + + +# In[ ]: + + +zip( xi, yi ) + + +# In[ ]: + + +list(_) + + +# # We can see that the zip() function with no arguments is a generator function, but there won't be any items. This fits the requirement that the output is iterable. + +# In[ ]: + + +zip( (1,2,3) ) + + +# In[ ]: + + +list(_) + +## In this case, the zip() function emitted one tuple from each input value. This too makes considerable sense. + diff --git a/Students/Wayne/Activities/Lesson_01/Calculator.ipynb b/Students/Wayne/Activities/Lesson_01/Calculator.ipynb new file mode 100644 index 0000000..3e42017 --- /dev/null +++ b/Students/Wayne/Activities/Lesson_01/Calculator.ipynb @@ -0,0 +1,153 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "This is the functional vs imperative exervise " + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Welcome to the barely functional calculator!\n", + "Enter an integer: 5\n", + "Enter an operator (+, -, *, or /): *\n", + "Enter an integer: 10\n", + "The result is: 50\n" + ] + } + ], + "source": [ + "OPERATORS = '+', '-', '*', '/'\n", + "\n", + "\n", + "def p_main():\n", + " \n", + " \"\"\"The main flow.\"\"\"\n", + "\n", + " print('Welcome to the barely functional calculator!')\n", + " number1 = p_get_number()\n", + " operator = p_get_operator()\n", + " number2 = p_get_number()\n", + " result = p_calculate(number1, operator, number2)\n", + " print('The result is: %s' % result)\n", + "\n", + "\n", + "def p_get_number():\n", + " \n", + " \"\"\"Reads an integer from the standard input and returns it.\n", + " If a non-integer value is entered, a warning is printed,\n", + " and a new value is read.\"\"\"\n", + " \n", + " while True:\n", + " s = input('Enter an integer: ')\n", + " try:\n", + " return int(s)\n", + " except ValueError:\n", + " print('That is not an integer!')\n", + " \n", + "\n", + "def p_get_operator():\n", + " \n", + " \"\"\"Reads an operator from the standard input and returns it.\n", + " Valid operators are: +, -, *, and /. If an invalid operator\n", + " is entered, a warning is printed, and a new value is read.\"\"\" \n", + " \n", + " while True:\n", + " s = input('Enter an operator (+, -, *, or /): ')\n", + " if s in OPERATORS:\n", + " return s\n", + " print('That is not an operator!')\n", + " \n", + " \n", + "def p_calculate(number1, operator, number2):\n", + " \n", + " \"\"\"Performs a calculation with two numbers and an operator,\n", + " and returns the result.\"\"\"\n", + " \n", + " if operator == '+':\n", + " return number1 + number2\n", + " if operator == '-':\n", + " return number1 - number2\n", + " if operator == '*':\n", + " return number1 * number2\n", + " if operator == '/':\n", + " return number1 / number2\n", + " raise Exception('Invalid operator!')\n", + "\n", + " \n", + "p_main()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "OPERATORS = '+', '-', '*', '/'\n", + "\n", + "def f_get_number():\n", + " return int(input('Enter an integer:'))\n", + "\n", + "\n", + "def f_get_operator():\n", + " return input('Enter an operator(+,-,*,/):')\n", + "\n", + "\n", + "def f_calculate(number1, operator, number2) :\n", + " return number1+number2 if operator == '+' \\\n", + " else number1*number2 if operator == \"*\"\\\n", + " else number1-number2 if operator == '-'\\\n", + " else number1/number2 if operator == '/'\\\n", + " else None\n", + "\n", + "\n", + "def f_main():\n", + " return f_calculate(\n", + " f_get_number(),\n", + " f_get_operator(),\n", + " f_get_number()\n", + " )\n", + "print('the result is :%s' % f_main())\n", + "\n", + " " + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.6.5" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/Students/Wayne/Activities/Lesson_01/Concept-5-Comprehensions-Example.ipynb b/Students/Wayne/Activities/Lesson_01/Concept-5-Comprehensions-Example.ipynb new file mode 100644 index 0000000..02d6544 --- /dev/null +++ b/Students/Wayne/Activities/Lesson_01/Concept-5-Comprehensions-Example.ipynb @@ -0,0 +1,298 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "list(range(10))" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "0\n", + "1\n", + "2\n", + "3\n", + "4\n", + "5\n", + "6\n", + "7\n", + "8\n", + "9\n" + ] + } + ], + "source": [ + "for x in range(10):\n", + " print (x)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## MAP" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[1, 4, 9, 16, 25]\n" + ] + } + ], + "source": [ + "items = [1, 2, 3, 4, 5]\n", + "squared = list(map(lambda x: x**2, items))\n", + "print(squared)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Filter\n" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[-10, -9, -8, -7, -6, -5, -4, -3, -2, -1]\n" + ] + } + ], + "source": [ + "number_list = range(-10, 10)\n", + "less_than_zero = list(filter(lambda x: x < 0, number_list))\n", + "print(less_than_zero)" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[1, 2, 3, 4, 5, 6, 7, 8, 9]\n" + ] + } + ], + "source": [ + "number_list = range(-10, 10)\n", + "less_than_zero = list(filter(lambda x: x > 0, number_list))\n", + "print(less_than_zero)" + ] + }, + { + "cell_type": "code", + "execution_count": 18, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "[2, 4, 6, 8, 10, 12]" + ] + }, + "execution_count": 18, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "l = [2,3,4,5,6,8,9,10,11,12]\n", + "list(filter(lambda x: not x%2, l))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Reduce" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "6\n", + "9\n", + "9\n" + ] + } + ], + "source": [ + "from functools import reduce\n", + "product = reduce((lambda x, y: x * y), [1, 2, 3])\n", + "print(product)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## List Comprehension\n" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[0, 3, 6, 9, 12, 15, 18, 21, 24, 27]\n" + ] + } + ], + "source": [ + "multiples = [i for i in range(30) if i % 3 == 0]\n", + "print(multiples)" + ] + }, + { + "cell_type": "code", + "execution_count": 20, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]\n" + ] + } + ], + "source": [ + "squared = [x**2 for x in range(10)]\n", + "print(squared)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Dict Comprehension\n" + ] + }, + { + "cell_type": "code", + "execution_count": 21, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "{5: 'a', 3: 'b', 7: 'A', 6: 'Z'}" + ] + }, + "execution_count": 21, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "mcase = {'a': 5, 'b': 3, 'A': 7, 'Z': 6}\n", + "{v: k for k, v in mcase.items()}" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Set Comprehension" + ] + }, + { + "cell_type": "code", + "execution_count": 22, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "{0, 1, 4}\n" + ] + } + ], + "source": [ + "squared = {x**2 for x in [0,1,1,2]}\n", + "print(squared)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## In the previous set example, can you explain the output?" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "the output of 0, 1, 4 is explained by the fact that a set can only have one unique output..." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.6.5" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/Students/Wayne/Activities/Lesson_01/Concept-6-Lambda.ipynb b/Students/Wayne/Activities/Lesson_01/Concept-6-Lambda.ipynb new file mode 100644 index 0000000..a9d4ad9 --- /dev/null +++ b/Students/Wayne/Activities/Lesson_01/Concept-6-Lambda.ipynb @@ -0,0 +1,134 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "(x)>" + ] + }, + "execution_count": 4, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "lambda x: x*2" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "lambda x:x*2" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "8" + ] + }, + "execution_count": 5, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "(lambda x:x*2)(4)" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": {}, + "outputs": [], + "source": [ + "l = [lambda x, y: x+y]" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "function" + ] + }, + "execution_count": 7, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "type(l[0])" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "129.7748" + ] + }, + "execution_count": 8, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "leg = ((27.154167, -80.195663), (29.195168, -81.002998), 129.7748)\n", + "start= lambda x: x[0]\n", + "end = lambda x: x[1]\n", + "dist = lambda x: x[2]\n", + "dist(leg)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.6.5" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/Students/Wayne/Activities/Lesson_01/Concept-7-Iterables-Iter-Iterators-Etc.ipynb b/Students/Wayne/Activities/Lesson_01/Concept-7-Iterables-Iter-Iterators-Etc.ipynb new file mode 100644 index 0000000..6746afe --- /dev/null +++ b/Students/Wayne/Activities/Lesson_01/Concept-7-Iterables-Iter-Iterators-Etc.ipynb @@ -0,0 +1,418 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Iter() Operation\n", + "\n", + "Examples of Iter - lists, dictionaries etc ....\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "iter([2,3,4])" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "iter({1:2, 3:4, 5:8})" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "## is this iterable? Try ....\n", + "\n", + "iter(104)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "##Lets start with user defined String class\n", + "class String(object):\n", + " def __init__(self, val):\n", + " self.val = val\n", + " def __str__(self):\n", + " return self.val" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "st = String('sample string')\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Is the above string iterable? lets test it. \n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "iter(st)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Why didn't this work? \n", + "## What's missing?\n", + "\n", + "the magic - an_iterator.__iter__()\n", + "\n", + "## Then, how should we make user defined type iterable? \n", + "This can be done by extending our String class with iter constructor\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "class String(object):\n", + " def __init__(self, val):\n", + " self.val = val\n", + " def __str__(self):\n", + " return self.val\n", + " def __iter__(self):\n", + " print (\"This is __iter__ method of String class\")\n", + " return iter(self.val) #self.val is python string so iter() will return it's iterator" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "st = String('Sample String')" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "iter(st)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## We added a __iter__ method in our String class to make String type as iterable. That means iter(iterable) calls iterable.__iter__() internally.\n", + "\n", + "You could also do this using getitem" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "class String(object):\n", + " def __init__(self, val):\n", + " self.val = val\n", + " def __str__(self):\n", + " return self.val\n", + " def __getitem__(self, index):\n", + " return self.val[index]" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "st = String('Sample String')" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "iter(st)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## We added __getitem__ method and user defined String type becomes iterable. So iter(iterable) look for iterable.__getitem__() also." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Iterator\n", + "\n", + "1. Iterator object produces values of iterable during iteration. next() or __next__() is applied on iterator for producing next value\n", + "2. It raises StopIteration exception at the end of iteration\n", + "3. iter() function return iterator object for an iterable\n", + "4. If iter() function is applied on iterator object, it returns same object" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "## List as an iterator\n", + "\n", + "a_list = [1,2,3]\n", + "list_iter = a_list.__iter__()\n", + "\n", + "## before python 2.6 I think - list_iter.next()\n", + "list_iter.__next__()\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "list_iter.__next__()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "## see what happens after 2 more times?\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## IterTools\n", + "\n", + "\n", + "itertools is a collection of utilities that make it easy to build an iterator that iterates over sequences in various common ways\n", + "\n", + "http://docs.python.org/library/itertools.html\n", + "\n", + "NOTE:\n", + "\n", + "iterators are not only for for\n", + "\n", + "They can be used with anything that expects an iterator:\n", + "\n", + "sum, tuple, sorted, and list\n", + "\n", + "For example.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import itertools\n", + "\n", + "letters = ['a', 'b', 'c', 'd', 'e', 'f']\n", + "booleans = [1, 0, 1, 0, 0, 1]\n", + "numbers = [23, 20, 44, 32, 7, 12]\n", + "decimals = [0.1, 0.7, 0.4, 0.4, 0.5]" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Chain\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "print (list(itertools.chain(letters, booleans, decimals)))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## compress()\n", + "\n", + "compress(): given two lists a and b, return the elements of a for which the corresponding elements of b are True.\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "print (list(itertools.compress(letters, booleans)))\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Zip ()\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "xi= [1.47, 1.50, 1.52, 1.55, 1.57, 1.60, 1.63, 1.65]\n", + "yi= [52.21, 53.12, 54.48, 55.84, 57.20, 58.57, 59.93, 61.29]\n", + "zip( xi, yi )\n", + " " + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "list(zip( xi, yi ))" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "zip( xi, yi )" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "list(_)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## We can see that the zip() function with no arguments is a generator function, but there won't be any items. This fits the requirement that the output is iterable.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "zip( (1,2,3) )" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "list(_)\n", + "\n", + "## In this case, the zip() function emitted one tuple from each input value. This too makes considerable sense." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.6.5" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/Students/Wayne/Activities/Lesson_01/concept-3-truth-table.ipynb b/Students/Wayne/Activities/Lesson_01/concept-3-truth-table.ipynb new file mode 100644 index 0000000..4355906 --- /dev/null +++ b/Students/Wayne/Activities/Lesson_01/concept-3-truth-table.ipynb @@ -0,0 +1,1499 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Concept-3-Truth-Table.ipynb | UW-Python-220 Slack + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + Menu + + +

+ + + UW-Python-220 + +

+ + + + +
+
+ +
+ + + +
+ + + +
+ +

+ + 2KB Plain Text snippet created on May 21, 2018. + +

+ + + Actions + + + + + + +
+
{
+ "cells": [
+  {
+   "cell_type": "code",
+   "execution_count": null,
+   "metadata": {},
+   "outputs": [],
+   "source": [
+    "-2"
+   ]
+  },
+  {
+   "cell_type": "code",
+   "execution_count": null,
+   "metadata": {},
+   "outputs": [],
+   "source": [
+    "not True"
+   ]
+  },
+  {
+   "cell_type": "code",
+   "execution_count": null,
+   "metadata": {},
+   "outputs": [],
+   "source": [
+    "not False"
+   ]
+  },
+  {
+   "cell_type": "code",
+   "execution_count": null,
+   "metadata": {},
+   "outputs": [],
+   "source": [
+    "x=False\n"
+   ]
+  },
+  {
+   "cell_type": "code",
+   "execution_count": null,
+   "metadata": {},
+   "outputs": [],
+   "source": [
+    "not x"
+   ]
+  },
+  {
+   "cell_type": "code",
+   "execution_count": null,
+   "metadata": {},
+   "outputs": [],
+   "source": [
+    "x,y=True, False"
+   ]
+  },
+  {
+   "cell_type": "code",
+   "execution_count": null,
+   "metadata": {},
+   "outputs": [],
+   "source": [
+    "not (x or y)"
+   ]
+  },
+  {
+   "cell_type": "code",
+   "execution_count": null,
+   "metadata": {},
+   "outputs": [],
+   "source": [
+    "not x or y\n"
+   ]
+  },
+  {
+   "cell_type": "code",
+   "execution_count": null,
+   "metadata": {},
+   "outputs": [],
+   "source": [
+    "x and y"
+   ]
+  },
+  {
+   "cell_type": "code",
+   "execution_count": null,
+   "metadata": {},
+   "outputs": [],
+   "source": [
+    "not (x and y)"
+   ]
+  },
+  {
+   "cell_type": "code",
+   "execution_count": null,
+   "metadata": {},
+   "outputs": [],
+   "source": [
+    "not x and y"
+   ]
+  },
+  {
+   "cell_type": "code",
+   "execution_count": null,
+   "metadata": {},
+   "outputs": [],
+   "source": []
+  }
+ ],
+ "metadata": {
+  "kernelspec": {
+   "display_name": "Python 3",
+   "language": "python",
+   "name": "python3"
+  },
+  "language_info": {
+   "codemirror_mode": {
+    "name": "ipython",
+    "version": 3
+   },
+   "file_extension": ".py",
+   "mimetype": "text/x-python",
+   "name": "python",
+   "nbconvert_exporter": "python",
+   "pygments_lexer": "ipython3",
+   "version": "3.6.4"
+  }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 2
+}
+
+ +

+ +

+ +
+ +
+
+
+
+ + +
+ Loading
loading...
+ +
+ + + + +
+ + + + + + + + + + + + + + + + + + + + +
+
+ + shift+enter to add a new line
+
+ + +
+
+
+
+ + + + +
+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Students/Wayne/Activities/Lesson_01/iterator_1.py b/Students/Wayne/Activities/Lesson_01/iterator_1.py new file mode 100644 index 0000000..16c3c9c --- /dev/null +++ b/Students/Wayne/Activities/Lesson_01/iterator_1.py @@ -0,0 +1,72 @@ +#!/usr/bin/env python + +""" +Simple iterator examples +""" + + +class IterateMe_1: + """ + About as simple an iterator as you can get: + + returns the sequence of numbers from zero to 4 + ( like range(4) ) + """ + + def __init__(self, stop=10): + self.current = -1 + self.stop = stop + + def __iter__(self): + return self + + def __next__(self): + self.current += 1 + if self.current < self.stop: + return self.current + else: + raise StopIteration + + +class IterateMe_2: + + def __init__(self, start, stop, step): + self.current = start - step + self.stop = stop + self.start = start + self.step = step + + def __iter__(self): + return self + + def __next__(self): + self.current += self.step + if self.current < self.stop: + return self.current + else: + raise StopIteration + + +it = IterateMe_2(2, 20, 2) +for i in it: + if i > 10: break + + +def rng(): + print("Range function") + for i in range(2, 20, 2): + print(i) + + + +if __name__ == "__main__": + + print("Testing the iterator") + for i in IterateMe_1(): + print(i) + + print("Testing the IT iterator") + for i in it: + print(i) + +rng() diff --git a/Students/Wayne/Activities/Lesson_02/Activity2.py b/Students/Wayne/Activities/Lesson_02/Activity2.py new file mode 100644 index 0000000..cc748e1 --- /dev/null +++ b/Students/Wayne/Activities/Lesson_02/Activity2.py @@ -0,0 +1,229 @@ + +# coding: utf-8 + +# In[1]: + + +def check_prime(number): + for divisor in range(2, int(number ** 0.5) + 1): + if number % divisor == 0: + return False + return True + + +# In[4]: + + +class Primes: + def __init__(self, max): + self.max = max + self.number = 1 + def __iter__(self): + return self + def __next__(self): + self.number += 1 + if self.number >= self.max: + raise StopIteration + elif check_prime(self.number): + return self.number + else: + return self.__next__() + + +# In[6]: + + +primes = Primes(10) +print(primes) +for x in primes: + print(x) + + +# ##Generator +# +# A generator must have yield +# it can yield many number of times +# Yield is two way - you can input and output +# it saves state +# It is a better version than Iterator or regular function + +# In[8]: + + +def Primes(max): + number = 1 + while number < max: + number += 1 + if check_prime(number): + yield number +primes = Primes(10) +print(primes) +for x in primes: + print(x) + + +# ##Generator Expressions +# +# similiar to a list comprehension +# +# [x*x for x in range(10)] +# +# A typical list looks like this +# +# variable = [out_exp for out_exp in input_list if out_exp == 2] +# +# A a generator expression: +# + +# In[10]: + + +sum([x*x for x in range(10)]) + + +# There are interesting examples of generators and iterators here 0- +# +# http://www.learningpython.com/2009/02/23/iterators-iterables-and-generators-oh-my/ +# +# https://www.youtube.com/watch?v=OSGv2VnC0go + +# # Closure examples + +# In[11]: + + +def outerFunction(text): + text = text ## the text on the left side is a non local variable + + def innerFunction(): + print(text) + + return innerFunction # Note we are returning function WITHOUT parenthesis + +if __name__ == '__main__': + myFunction = outerFunction('Hey!') + myFunction() + + +# # Non Local Vs Global + +# In[80]: + + +def outside(): + d = {"outside": 1} + def inside(): + nonlocal d + d=["inside"] = 2 + print(d) + inside() + print(d) + +outside() + + + +# In[20]: + + +import functools +import heapq + + +# In[21]: + + +heap = [] +heapq.heappush(heap,1) +heapq.heappush(heap,2) +heapq.heappush(heap,4) +heapq.heappush(heap,6) +heapq.heappush(heap,7) +heapq.heappush(heap,9) +heapq.heappush(heap,10) +heapq.heappush(heap,12) + + +# In[22]: + + +heapq.nsmallest(4,heap) + + +# In[57]: + + +import functools +import heapq +heap =[] + + +# In[58]: + + + +push = functools.partial(heapq.heappush, heap) + + +# In[59]: + + + +smallest = functools.partial(heapq.nsmallest, iterable=heap) + + +# In[60]: + + +push(1) +push(3) +push(5) +push(6) +push(8) +push(11) +push(4) +push(16) +push(17) + + +# In[61]: + + +smallest(6) + + +# In[63]: + + +taco = islice('ABCDFEG',2, None) + + +# In[66]: + + +list(taco) + + +# In[70]: + + +tacos = islice('ABCDFEG',2) + + +# In[71]: + + +list(tacos) + + +# In[78]: + + +stacos = islice('ABCDFEG',2, 4) + + +# In[79]: + + +list(stacos) + diff --git a/Students/Wayne/Activities/Lesson_02/InClassExamples.ipynb b/Students/Wayne/Activities/Lesson_02/InClassExamples.ipynb new file mode 100644 index 0000000..1709c3a --- /dev/null +++ b/Students/Wayne/Activities/Lesson_02/InClassExamples.ipynb @@ -0,0 +1,447 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [], + "source": [ + "def check_prime(number):\n", + " for divisor in range(2, int(number ** 0.5) + 1):\n", + " if number % divisor == 0:\n", + " return False\n", + " return True" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [], + "source": [ + "class Primes:\n", + " def __init__(self, max):\n", + " self.max = max\n", + " self.number = 1\n", + " def __iter__(self):\n", + " return self\n", + " def __next__(self):\n", + " self.number += 1\n", + " if self.number >= self.max:\n", + " raise StopIteration\n", + " elif check_prime(self.number):\n", + " return self.number\n", + " else:\n", + " return self.__next__()\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "<__main__.Primes object at 0x10c0ea2e8>\n", + "2\n", + "3\n", + "5\n", + "7\n" + ] + } + ], + "source": [ + " primes = Primes(10)\n", + "print(primes)\n", + "for x in primes:\n", + " print(x)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "##Generator \n", + "\n", + "A generator must have yield \n", + "it can yield many number of times\n", + "Yield is two way - you can input and output \n", + "it saves state \n", + "It is a better version than Iterator or regular function " + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + "2\n", + "3\n", + "5\n", + "7\n" + ] + } + ], + "source": [ + "def Primes(max):\n", + " number = 1\n", + " while number < max:\n", + " number += 1\n", + " if check_prime(number):\n", + " yield number\n", + "primes = Primes(10)\n", + "print(primes)\n", + "for x in primes:\n", + " print(x) " + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "##Generator Expressions \n", + "\n", + "similiar to a list comprehension\n", + "\n", + "[x*x for x in range(10)]\n", + "\n", + "A typical list looks like this \n", + "\n", + "variable = [out_exp for out_exp in input_list if out_exp == 2]\n", + "\n", + "A a generator expression: \n" + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "285" + ] + }, + "execution_count": 10, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "sum([x*x for x in range(10)])" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "There are interesting examples of generators and iterators here 0-\n", + "\n", + "http://www.learningpython.com/2009/02/23/iterators-iterables-and-generators-oh-my/\n", + "\n", + "https://www.youtube.com/watch?v=OSGv2VnC0go" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Closure examples " + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Hey!\n" + ] + } + ], + "source": [ + "def outerFunction(text):\n", + " text = text ## the text on the left side is a non local variable\n", + " \n", + " def innerFunction():\n", + " print(text)\n", + " \n", + " return innerFunction # Note we are returning function WITHOUT parenthesis\n", + " \n", + "if __name__ == '__main__':\n", + " myFunction = outerFunction('Hey!')\n", + " myFunction() " + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Non Local Vs Global " + ] + }, + { + "cell_type": "code", + "execution_count": 80, + "metadata": {}, + "outputs": [ + { + "ename": "SyntaxError", + "evalue": "can't assign to literal (, line 5)", + "output_type": "error", + "traceback": [ + "\u001b[0;36m File \u001b[0;32m\"\"\u001b[0;36m, line \u001b[0;32m5\u001b[0m\n\u001b[0;31m d=[\"inside\"] = 2\u001b[0m\n\u001b[0m ^\u001b[0m\n\u001b[0;31mSyntaxError\u001b[0m\u001b[0;31m:\u001b[0m can't assign to literal\n" + ] + } + ], + "source": [ + " def outside():\n", + " d = {\"outside\": 1}\n", + " def inside():\n", + " nonlocal d\n", + " d=[\"inside\"] = 2\n", + " print(d)\n", + " inside()\n", + " print(d)\n", + " \n", + "outside()\n", + " " + ] + }, + { + "cell_type": "code", + "execution_count": 20, + "metadata": {}, + "outputs": [], + "source": [ + "import functools\n", + "import heapq\n" + ] + }, + { + "cell_type": "code", + "execution_count": 21, + "metadata": {}, + "outputs": [], + "source": [ + "heap = []\n", + "heapq.heappush(heap,1)\n", + "heapq.heappush(heap,2)\n", + "heapq.heappush(heap,4)\n", + "heapq.heappush(heap,6)\n", + "heapq.heappush(heap,7)\n", + "heapq.heappush(heap,9)\n", + "heapq.heappush(heap,10)\n", + "heapq.heappush(heap,12)\n" + ] + }, + { + "cell_type": "code", + "execution_count": 22, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "[1, 2, 4, 6]" + ] + }, + "execution_count": 22, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "heapq.nsmallest(4,heap)" + ] + }, + { + "cell_type": "code", + "execution_count": 57, + "metadata": {}, + "outputs": [], + "source": [ + "import functools\n", + "import heapq\n", + "heap =[]" + ] + }, + { + "cell_type": "code", + "execution_count": 58, + "metadata": {}, + "outputs": [], + "source": [ + "\n", + "push = functools.partial(heapq.heappush, heap)" + ] + }, + { + "cell_type": "code", + "execution_count": 59, + "metadata": {}, + "outputs": [], + "source": [ + "\n", + "smallest = functools.partial(heapq.nsmallest, iterable=heap)" + ] + }, + { + "cell_type": "code", + "execution_count": 60, + "metadata": {}, + "outputs": [], + "source": [ + "push(1)\n", + "push(3)\n", + "push(5)\n", + "push(6)\n", + "push(8)\n", + "push(11)\n", + "push(4)\n", + "push(16)\n", + "push(17)\n" + ] + }, + { + "cell_type": "code", + "execution_count": 61, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "[1, 3, 4, 5, 6, 8]" + ] + }, + "execution_count": 61, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "smallest(6)" + ] + }, + { + "cell_type": "code", + "execution_count": 63, + "metadata": {}, + "outputs": [], + "source": [ + "taco = islice('ABCDFEG',2, None)" + ] + }, + { + "cell_type": "code", + "execution_count": 66, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "['C', 'D', 'F', 'E', 'G']" + ] + }, + "execution_count": 66, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "list(taco)" + ] + }, + { + "cell_type": "code", + "execution_count": 70, + "metadata": {}, + "outputs": [], + "source": [ + "tacos = islice('ABCDFEG',2)" + ] + }, + { + "cell_type": "code", + "execution_count": 71, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "['A', 'B']" + ] + }, + "execution_count": 71, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "list(tacos)" + ] + }, + { + "cell_type": "code", + "execution_count": 78, + "metadata": {}, + "outputs": [], + "source": [ + "stacos = islice('ABCDFEG',2, 4)" + ] + }, + { + "cell_type": "code", + "execution_count": 79, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "['C', 'D']" + ] + }, + "execution_count": 79, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "list(stacos)" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.6.5" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/Students/Wayne/Activities/Lesson_03/.ipynb_checkpoints/Lesson3_InClassNotes-checkpoint.ipynb b/Students/Wayne/Activities/Lesson_03/.ipynb_checkpoints/Lesson3_InClassNotes-checkpoint.ipynb new file mode 100644 index 0000000..c0d6659 --- /dev/null +++ b/Students/Wayne/Activities/Lesson_03/.ipynb_checkpoints/Lesson3_InClassNotes-checkpoint.ipynb @@ -0,0 +1,39 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "In class notes for 05/31/2018" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.6.5" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/Students/Wayne/Activities/Lesson_03/Lesson3_InClassNotes.ipynb b/Students/Wayne/Activities/Lesson_03/Lesson3_InClassNotes.ipynb new file mode 100644 index 0000000..c0d6659 --- /dev/null +++ b/Students/Wayne/Activities/Lesson_03/Lesson3_InClassNotes.ipynb @@ -0,0 +1,39 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "In class notes for 05/31/2018" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.6.5" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/Students/Wayne/Activities/Lesson_05/.ipynb_checkpoints/Lesson_05-checkpoint.ipynb b/Students/Wayne/Activities/Lesson_05/.ipynb_checkpoints/Lesson_05-checkpoint.ipynb new file mode 100644 index 0000000..066a845 --- /dev/null +++ b/Students/Wayne/Activities/Lesson_05/.ipynb_checkpoints/Lesson_05-checkpoint.ipynb @@ -0,0 +1,1200 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Logging and Debugging ##\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# New Words, Concepts, and Tools\n", + "logging\n", + "log levels\n", + "syslog\n", + "debugger\n", + "pdb\n", + "breakpoint\n", + "\"step in\"\n", + "continue" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Logging\n", + "\n", + "https://docs.python.org/3/library/logging.html#levels" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [ + { + "ename": "ZeroDivisionError", + "evalue": "division by zero", + "output_type": "error", + "traceback": [ + "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[0;31mZeroDivisionError\u001b[0m Traceback (most recent call last)", + "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[1;32m 5\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 6\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0m__name__\u001b[0m \u001b[0;34m==\u001b[0m \u001b[0;34m\"__main__\"\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 7\u001b[0;31m \u001b[0mmy_fun\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;36m100\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", + "\u001b[0;32m\u001b[0m in \u001b[0;36mmy_fun\u001b[0;34m(n)\u001b[0m\n\u001b[1;32m 2\u001b[0m \u001b[0;32mdef\u001b[0m \u001b[0mmy_fun\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mn\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 3\u001b[0m \u001b[0;32mfor\u001b[0m \u001b[0mi\u001b[0m \u001b[0;32min\u001b[0m \u001b[0mrange\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;36m0\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mn\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 4\u001b[0;31m \u001b[0mi\u001b[0m \u001b[0;34m/\u001b[0m \u001b[0;34m(\u001b[0m\u001b[0;36m50\u001b[0m \u001b[0;34m-\u001b[0m \u001b[0mi\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 5\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 6\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0m__name__\u001b[0m \u001b[0;34m==\u001b[0m \u001b[0;34m\"__main__\"\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", + "\u001b[0;31mZeroDivisionError\u001b[0m: division by zero" + ] + } + ], + "source": [ + "# simple.py\n", + "def my_fun(n):\n", + " for i in range(0, n):\n", + " i / (50 - i)\n", + "\n", + "if __name__ == \"__main__\":\n", + " my_fun(100)" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "0\n", + "1\n", + "2\n", + "3\n", + "4\n", + "5\n", + "6\n", + "7\n", + "8\n", + "9\n", + "10\n", + "11\n", + "12\n", + "13\n", + "14\n", + "15\n", + "16\n", + "17\n", + "18\n", + "19\n", + "20\n", + "21\n", + "22\n", + "23\n", + "24\n", + "25\n", + "26\n", + "27\n", + "28\n", + "29\n", + "30\n", + "31\n", + "32\n", + "33\n", + "34\n", + "35\n", + "36\n", + "37\n", + "38\n", + "39\n", + "40\n", + "41\n", + "42\n", + "43\n", + "44\n", + "45\n", + "46\n", + "47\n", + "48\n", + "49\n", + "50\n" + ] + }, + { + "ename": "ZeroDivisionError", + "evalue": "division by zero", + "output_type": "error", + "traceback": [ + "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[0;31mZeroDivisionError\u001b[0m Traceback (most recent call last)", + "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[1;32m 6\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 7\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0m__name__\u001b[0m \u001b[0;34m==\u001b[0m \u001b[0;34m\"__main__\"\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 8\u001b[0;31m \u001b[0mmy_fun\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;36m100\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", + "\u001b[0;32m\u001b[0m in \u001b[0;36mmy_fun\u001b[0;34m(n)\u001b[0m\n\u001b[1;32m 3\u001b[0m \u001b[0;32mfor\u001b[0m \u001b[0mi\u001b[0m \u001b[0;32min\u001b[0m \u001b[0mrange\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;36m0\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mn\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 4\u001b[0m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mi\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;31m# <-- Add this line\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 5\u001b[0;31m \u001b[0;36m100\u001b[0m \u001b[0;34m/\u001b[0m \u001b[0;34m(\u001b[0m\u001b[0;36m50\u001b[0m \u001b[0;34m-\u001b[0m \u001b[0mi\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 6\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 7\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0m__name__\u001b[0m \u001b[0;34m==\u001b[0m \u001b[0;34m\"__main__\"\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", + "\u001b[0;31mZeroDivisionError\u001b[0m: division by zero" + ] + } + ], + "source": [ + "# simple.py\n", + "def my_fun(n):\n", + " for i in range(0, n):\n", + " print(i) # <-- Add this line\n", + " 100 / (50 - i)\n", + " \n", + "if __name__ == \"__main__\":\n", + " my_fun(100)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Here are a few problems with using a print statement to debug your code:\n", + "\n", + "- You have to go back in and take them out, otherwise they produce distracting output when you're running your program.\n", + "\n", + "- If you have more than a couple of print statements, it becomes hard to keep track of where they all are and what each one specifically is reporting on.\n", + "\n", + "- Print statements don't help you when your code is being run in production: you can only use print statements when you're running the code on your own machine from your console." + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "metadata": {}, + "outputs": [ + { + "name": "stderr", + "output_type": "stream", + "text": [ + "DEBUG:root:0\n", + "DEBUG:root:1\n", + "DEBUG:root:2\n", + "DEBUG:root:3\n", + "DEBUG:root:4\n", + "DEBUG:root:5\n", + "DEBUG:root:6\n", + "DEBUG:root:7\n", + "DEBUG:root:8\n", + "DEBUG:root:9\n", + "DEBUG:root:10\n", + "DEBUG:root:11\n", + "DEBUG:root:12\n", + "DEBUG:root:13\n", + "DEBUG:root:14\n", + "DEBUG:root:15\n", + "DEBUG:root:16\n", + "DEBUG:root:17\n", + "DEBUG:root:18\n", + "DEBUG:root:19\n", + "DEBUG:root:20\n", + "DEBUG:root:21\n", + "DEBUG:root:22\n", + "DEBUG:root:23\n", + "DEBUG:root:24\n", + "DEBUG:root:25\n", + "DEBUG:root:26\n", + "DEBUG:root:27\n", + "DEBUG:root:28\n", + "DEBUG:root:29\n", + "DEBUG:root:30\n", + "DEBUG:root:31\n", + "DEBUG:root:32\n", + "DEBUG:root:33\n", + "DEBUG:root:34\n", + "DEBUG:root:35\n", + "DEBUG:root:36\n", + "DEBUG:root:37\n", + "DEBUG:root:38\n", + "DEBUG:root:39\n", + "DEBUG:root:40\n", + "DEBUG:root:41\n", + "DEBUG:root:42\n", + "DEBUG:root:43\n", + "DEBUG:root:44\n", + "DEBUG:root:45\n", + "DEBUG:root:46\n", + "DEBUG:root:47\n", + "DEBUG:root:48\n", + "DEBUG:root:49\n", + "DEBUG:root:50\n" + ] + }, + { + "ename": "ZeroDivisionError", + "evalue": "division by zero", + "output_type": "error", + "traceback": [ + "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[0;31mZeroDivisionError\u001b[0m Traceback (most recent call last)", + "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[1;32m 8\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 9\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0m__name__\u001b[0m \u001b[0;34m==\u001b[0m \u001b[0;34m\"__main__\"\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 10\u001b[0;31m \u001b[0mmy_fun\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;36m100\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", + "\u001b[0;32m\u001b[0m in \u001b[0;36mmy_fun\u001b[0;34m(n)\u001b[0m\n\u001b[1;32m 5\u001b[0m \u001b[0;32mfor\u001b[0m \u001b[0mi\u001b[0m \u001b[0;32min\u001b[0m \u001b[0mrange\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;36m0\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mn\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 6\u001b[0m \u001b[0mlogging\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mdebug\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mi\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 7\u001b[0;31m \u001b[0mi\u001b[0m \u001b[0;34m/\u001b[0m \u001b[0;34m(\u001b[0m\u001b[0;36m50\u001b[0m \u001b[0;34m-\u001b[0m \u001b[0mi\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 8\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 9\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0m__name__\u001b[0m \u001b[0;34m==\u001b[0m \u001b[0;34m\"__main__\"\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", + "\u001b[0;31mZeroDivisionError\u001b[0m: division by zero" + ] + } + ], + "source": [ + "import logging\n", + "\n", + "logging.basicConfig(level=logging.DEBUG)\n", + "def my_fun(n):\n", + " for i in range(0, n):\n", + " logging.debug(i)\n", + " i / (50 - i)\n", + "\n", + "if __name__ == \"__main__\":\n", + " my_fun(100)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "So far, this doesn't look very different from the print statement that we were using before. But let's change one line of the script:" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "metadata": {}, + "outputs": [ + { + "name": "stderr", + "output_type": "stream", + "text": [ + "DEBUG:root:0\n", + "DEBUG:root:1\n", + "DEBUG:root:2\n", + "DEBUG:root:3\n", + "DEBUG:root:4\n", + "DEBUG:root:5\n", + "DEBUG:root:6\n", + "DEBUG:root:7\n", + "DEBUG:root:8\n", + "DEBUG:root:9\n", + "DEBUG:root:10\n", + "DEBUG:root:11\n", + "DEBUG:root:12\n", + "DEBUG:root:13\n", + "DEBUG:root:14\n", + "DEBUG:root:15\n", + "DEBUG:root:16\n", + "DEBUG:root:17\n", + "DEBUG:root:18\n", + "DEBUG:root:19\n", + "DEBUG:root:20\n", + "DEBUG:root:21\n", + "DEBUG:root:22\n", + "DEBUG:root:23\n", + "DEBUG:root:24\n", + "DEBUG:root:25\n", + "DEBUG:root:26\n", + "DEBUG:root:27\n", + "DEBUG:root:28\n", + "DEBUG:root:29\n", + "DEBUG:root:30\n", + "DEBUG:root:31\n", + "DEBUG:root:32\n", + "DEBUG:root:33\n", + "DEBUG:root:34\n", + "DEBUG:root:35\n", + "DEBUG:root:36\n", + "DEBUG:root:37\n", + "DEBUG:root:38\n", + "DEBUG:root:39\n", + "DEBUG:root:40\n", + "DEBUG:root:41\n", + "DEBUG:root:42\n", + "DEBUG:root:43\n", + "DEBUG:root:44\n", + "DEBUG:root:45\n", + "DEBUG:root:46\n", + "DEBUG:root:47\n", + "DEBUG:root:48\n", + "DEBUG:root:49\n", + "DEBUG:root:50\n" + ] + }, + { + "ename": "ZeroDivisionError", + "evalue": "division by zero", + "output_type": "error", + "traceback": [ + "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[0;31mZeroDivisionError\u001b[0m Traceback (most recent call last)", + "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[1;32m 8\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 9\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0m__name__\u001b[0m \u001b[0;34m==\u001b[0m \u001b[0;34m\"__main__\"\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 10\u001b[0;31m \u001b[0mmy_fun\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;36m100\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", + "\u001b[0;32m\u001b[0m in \u001b[0;36mmy_fun\u001b[0;34m(n)\u001b[0m\n\u001b[1;32m 5\u001b[0m \u001b[0;32mfor\u001b[0m \u001b[0mi\u001b[0m \u001b[0;32min\u001b[0m \u001b[0mrange\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;36m0\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mn\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 6\u001b[0m \u001b[0mlogging\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mdebug\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mi\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 7\u001b[0;31m \u001b[0mi\u001b[0m \u001b[0;34m/\u001b[0m \u001b[0;34m(\u001b[0m\u001b[0;36m50\u001b[0m \u001b[0;34m-\u001b[0m \u001b[0mi\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 8\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 9\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0m__name__\u001b[0m \u001b[0;34m==\u001b[0m \u001b[0;34m\"__main__\"\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", + "\u001b[0;31mZeroDivisionError\u001b[0m: division by zero" + ] + } + ], + "source": [ + "import logging\n", + "\n", + "logging.basicConfig(level=logging.WARNING) # Change the level to logging.WARNING\n", + "def my_fun(n):\n", + " for i in range(0, n):\n", + " logging.debug(i)\n", + " i / (50 - i)\n", + "\n", + "if __name__ == \"__main__\":\n", + " my_fun(100)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "This logging statement is just giving us some information about how the function is being used, so we've used the logging.info method.\n", + "\n", + "In our example script, when we were trying to figure out what value of i was causing our script to crash, we were debugging our code. That's why we used a logging.debug statement. Now that we know that the value 50 causes our code to crash, we could put in a logging.warning statement that will warn us of dangerous conditions:" + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "metadata": {}, + "outputs": [ + { + "name": "stderr", + "output_type": "stream", + "text": [ + "DEBUG:root:0\n", + "DEBUG:root:1\n", + "DEBUG:root:2\n", + "DEBUG:root:3\n", + "DEBUG:root:4\n", + "DEBUG:root:5\n", + "DEBUG:root:6\n", + "DEBUG:root:7\n", + "DEBUG:root:8\n", + "DEBUG:root:9\n", + "DEBUG:root:10\n", + "DEBUG:root:11\n", + "DEBUG:root:12\n", + "DEBUG:root:13\n", + "DEBUG:root:14\n", + "DEBUG:root:15\n", + "DEBUG:root:16\n", + "DEBUG:root:17\n", + "DEBUG:root:18\n", + "DEBUG:root:19\n", + "DEBUG:root:20\n", + "DEBUG:root:21\n", + "DEBUG:root:22\n", + "DEBUG:root:23\n", + "DEBUG:root:24\n", + "DEBUG:root:25\n", + "DEBUG:root:26\n", + "DEBUG:root:27\n", + "DEBUG:root:28\n", + "DEBUG:root:29\n", + "DEBUG:root:30\n", + "DEBUG:root:31\n", + "DEBUG:root:32\n", + "DEBUG:root:33\n", + "DEBUG:root:34\n", + "DEBUG:root:35\n", + "DEBUG:root:36\n", + "DEBUG:root:37\n", + "DEBUG:root:38\n", + "DEBUG:root:39\n", + "DEBUG:root:40\n", + "DEBUG:root:41\n", + "DEBUG:root:42\n", + "DEBUG:root:43\n", + "DEBUG:root:44\n", + "DEBUG:root:45\n", + "DEBUG:root:46\n", + "DEBUG:root:47\n", + "DEBUG:root:48\n", + "DEBUG:root:49\n", + "DEBUG:root:50\n", + "WARNING:root:The value of i is 50.\n" + ] + }, + { + "ename": "ZeroDivisionError", + "evalue": "division by zero", + "output_type": "error", + "traceback": [ + "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[0;31mZeroDivisionError\u001b[0m Traceback (most recent call last)", + "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[1;32m 10\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 11\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0m__name__\u001b[0m \u001b[0;34m==\u001b[0m \u001b[0;34m\"__main__\"\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 12\u001b[0;31m \u001b[0mmy_fun\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;36m100\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", + "\u001b[0;32m\u001b[0m in \u001b[0;36mmy_fun\u001b[0;34m(n)\u001b[0m\n\u001b[1;32m 7\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0mi\u001b[0m \u001b[0;34m==\u001b[0m \u001b[0;36m50\u001b[0m\u001b[0;34m:\u001b[0m \u001b[0;31m# Add this line\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 8\u001b[0m \u001b[0mlogging\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mwarning\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m\"The value of i is 50.\"\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;31m# Add this line\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 9\u001b[0;31m \u001b[0mi\u001b[0m \u001b[0;34m/\u001b[0m \u001b[0;34m(\u001b[0m\u001b[0;36m50\u001b[0m \u001b[0;34m-\u001b[0m \u001b[0mi\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 10\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 11\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0m__name__\u001b[0m \u001b[0;34m==\u001b[0m \u001b[0;34m\"__main__\"\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", + "\u001b[0;31mZeroDivisionError\u001b[0m: division by zero" + ] + } + ], + "source": [ + "import logging\n", + "\n", + "logging.basicConfig(level=logging.WARNING)\n", + "def my_fun(n):\n", + " for i in range(0, n):\n", + " logging.debug(i)\n", + " if i == 50: # Add this line\n", + " logging.warning(\"The value of i is 50.\") # Add this line\n", + " i / (50 - i)\n", + "\n", + "if __name__ == \"__main__\":\n", + " my_fun(100)" + ] + }, + { + "cell_type": "code", + "execution_count": 16, + "metadata": {}, + "outputs": [ + { + "name": "stderr", + "output_type": "stream", + "text": [ + "DEBUG:root:0\n", + "DEBUG:root:1\n", + "DEBUG:root:2\n", + "DEBUG:root:3\n", + "DEBUG:root:4\n", + "DEBUG:root:5\n", + "DEBUG:root:6\n", + "DEBUG:root:7\n", + "DEBUG:root:8\n", + "DEBUG:root:9\n", + "DEBUG:root:10\n", + "DEBUG:root:11\n", + "DEBUG:root:12\n", + "DEBUG:root:13\n", + "DEBUG:root:14\n", + "DEBUG:root:15\n", + "DEBUG:root:16\n", + "DEBUG:root:17\n", + "DEBUG:root:18\n", + "DEBUG:root:19\n", + "DEBUG:root:20\n", + "DEBUG:root:21\n", + "DEBUG:root:22\n", + "DEBUG:root:23\n", + "DEBUG:root:24\n", + "DEBUG:root:25\n", + "DEBUG:root:26\n", + "DEBUG:root:27\n", + "DEBUG:root:28\n", + "DEBUG:root:29\n", + "DEBUG:root:30\n", + "DEBUG:root:31\n", + "DEBUG:root:32\n", + "DEBUG:root:33\n", + "DEBUG:root:34\n", + "DEBUG:root:35\n", + "DEBUG:root:36\n", + "DEBUG:root:37\n", + "DEBUG:root:38\n", + "DEBUG:root:39\n", + "DEBUG:root:40\n", + "DEBUG:root:41\n", + "DEBUG:root:42\n", + "DEBUG:root:43\n", + "DEBUG:root:44\n", + "DEBUG:root:45\n", + "DEBUG:root:46\n", + "DEBUG:root:47\n", + "DEBUG:root:48\n", + "DEBUG:root:49\n", + "DEBUG:root:50\n", + "WARNING:root:The value of i is 50.\n", + "ERROR:root:Tried to divide by zero. Var i was 50. Recovered gracefully.\n", + "DEBUG:root:51\n", + "DEBUG:root:52\n", + "DEBUG:root:53\n", + "DEBUG:root:54\n", + "DEBUG:root:55\n", + "DEBUG:root:56\n", + "DEBUG:root:57\n", + "DEBUG:root:58\n", + "DEBUG:root:59\n", + "DEBUG:root:60\n", + "DEBUG:root:61\n", + "DEBUG:root:62\n", + "DEBUG:root:63\n", + "DEBUG:root:64\n", + "DEBUG:root:65\n", + "DEBUG:root:66\n", + "DEBUG:root:67\n", + "DEBUG:root:68\n", + "DEBUG:root:69\n", + "DEBUG:root:70\n", + "DEBUG:root:71\n", + "DEBUG:root:72\n", + "DEBUG:root:73\n", + "DEBUG:root:74\n", + "DEBUG:root:75\n", + "DEBUG:root:76\n", + "DEBUG:root:77\n", + "DEBUG:root:78\n", + "DEBUG:root:79\n", + "DEBUG:root:80\n", + "DEBUG:root:81\n", + "DEBUG:root:82\n", + "DEBUG:root:83\n", + "DEBUG:root:84\n", + "DEBUG:root:85\n", + "DEBUG:root:86\n", + "DEBUG:root:87\n", + "DEBUG:root:88\n", + "DEBUG:root:89\n", + "DEBUG:root:90\n", + "DEBUG:root:91\n", + "DEBUG:root:92\n", + "DEBUG:root:93\n", + "DEBUG:root:94\n", + "DEBUG:root:95\n", + "DEBUG:root:96\n", + "DEBUG:root:97\n", + "DEBUG:root:98\n", + "DEBUG:root:99\n" + ] + } + ], + "source": [ + "import logging\n", + "\n", + "logging.basicConfig(level=logging.WARNING)\n", + "\n", + "def my_fun(n):\n", + " for i in range(0, n):\n", + " logging.debug(i)\n", + " if i == 50:\n", + " logging.warning(\"The value of i is 50.\")\n", + " try:\n", + " i / (50 - i)\n", + " except ZeroDivisionError:\n", + " logging.error(\"Tried to divide by zero. Var i was {}. Recovered gracefully.\".format(i))\n", + "\n", + "if __name__ == \"__main__\":\n", + " my_fun(100)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The statement logging.basicConfig(level=logging.WARNING) tells the logger to only display log messages with level WARNING and above. Look back to the logging levels documenation. You'll see that the DEBUG level is below the WARNING level: it won't be displayed. When we were debugging this code, the debug statements were helping us understand why our code was failing, but now it would be overwhelming to see them every time we run our code. We've hidden the statements by making a single configuration change.\n", + "\n", + "The idea is that you might be working on a project with a lot of Python files. You may have put debugging or information statements into several of these files. While you're authoring the project, these messages are useful. And once you think you've worked out all of the bugs in your code, you don't have to go through all of your files and find every logging statement: you can just turn off the unimportant ones by setting the log level in your main script." + ] + }, + { + "cell_type": "code", + "execution_count": 17, + "metadata": {}, + "outputs": [ + { + "name": "stderr", + "output_type": "stream", + "text": [ + "CRITICAL:root:This is a critical error!\n", + "ERROR:root:I'm an error.\n", + "WARNING:root:Hello! I'm a warning!\n", + "INFO:root:This is some information.\n", + "DEBUG:root:Perhaps this information will help you find your problem?\n" + ] + } + ], + "source": [ + "# loggingtest.py\n", + "import logging\n", + "\n", + "logging.critical(\"This is a critical error!\")\n", + "logging.error(\"I'm an error.\")\n", + "logging.warning(\"Hello! I'm a warning!\")\n", + "logging.info(\"This is some information.\")\n", + "logging.debug(\"Perhaps this information will help you find your problem?\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Although I used the logging.basicConfig method to set the logging level in these examples, there are other ways to set this value. We'll learn about this later in the lesson." + ] + }, + { + "cell_type": "code", + "execution_count": 20, + "metadata": {}, + "outputs": [ + { + "name": "stderr", + "output_type": "stream", + "text": [ + "DEBUG:root:0\n", + "DEBUG:root:1\n", + "DEBUG:root:2\n", + "DEBUG:root:3\n", + "DEBUG:root:4\n", + "DEBUG:root:5\n", + "DEBUG:root:6\n", + "DEBUG:root:7\n", + "DEBUG:root:8\n", + "DEBUG:root:9\n", + "DEBUG:root:10\n", + "DEBUG:root:11\n", + "DEBUG:root:12\n", + "DEBUG:root:13\n", + "DEBUG:root:14\n", + "DEBUG:root:15\n", + "DEBUG:root:16\n", + "DEBUG:root:17\n", + "DEBUG:root:18\n", + "DEBUG:root:19\n", + "DEBUG:root:20\n", + "DEBUG:root:21\n", + "DEBUG:root:22\n", + "DEBUG:root:23\n", + "DEBUG:root:24\n", + "DEBUG:root:25\n", + "DEBUG:root:26\n", + "DEBUG:root:27\n", + "DEBUG:root:28\n", + "DEBUG:root:29\n", + "DEBUG:root:30\n", + "DEBUG:root:31\n", + "DEBUG:root:32\n", + "DEBUG:root:33\n", + "DEBUG:root:34\n", + "DEBUG:root:35\n", + "DEBUG:root:36\n", + "DEBUG:root:37\n", + "DEBUG:root:38\n", + "DEBUG:root:39\n", + "DEBUG:root:40\n", + "DEBUG:root:41\n", + "DEBUG:root:42\n", + "DEBUG:root:43\n", + "DEBUG:root:44\n", + "DEBUG:root:45\n", + "DEBUG:root:46\n", + "DEBUG:root:47\n", + "DEBUG:root:48\n", + "DEBUG:root:49\n", + "DEBUG:root:50\n", + "WARNING:root:The value of i is 50.\n", + "ERROR:root:Tried to divide by zero. Var i was 50. Recovered gracefully.\n", + "DEBUG:root:51\n", + "DEBUG:root:52\n", + "DEBUG:root:53\n", + "DEBUG:root:54\n", + "DEBUG:root:55\n", + "DEBUG:root:56\n", + "DEBUG:root:57\n", + "DEBUG:root:58\n", + "DEBUG:root:59\n", + "DEBUG:root:60\n", + "DEBUG:root:61\n", + "DEBUG:root:62\n", + "DEBUG:root:63\n", + "DEBUG:root:64\n", + "DEBUG:root:65\n", + "DEBUG:root:66\n", + "DEBUG:root:67\n", + "DEBUG:root:68\n", + "DEBUG:root:69\n", + "DEBUG:root:70\n", + "DEBUG:root:71\n", + "DEBUG:root:72\n", + "DEBUG:root:73\n", + "DEBUG:root:74\n", + "DEBUG:root:75\n", + "DEBUG:root:76\n", + "DEBUG:root:77\n", + "DEBUG:root:78\n", + "DEBUG:root:79\n", + "DEBUG:root:80\n", + "DEBUG:root:81\n", + "DEBUG:root:82\n", + "DEBUG:root:83\n", + "DEBUG:root:84\n", + "DEBUG:root:85\n", + "DEBUG:root:86\n", + "DEBUG:root:87\n", + "DEBUG:root:88\n", + "DEBUG:root:89\n", + "DEBUG:root:90\n", + "DEBUG:root:91\n", + "DEBUG:root:92\n", + "DEBUG:root:93\n", + "DEBUG:root:94\n", + "DEBUG:root:95\n", + "DEBUG:root:96\n", + "DEBUG:root:97\n", + "DEBUG:root:98\n", + "DEBUG:root:99\n" + ] + } + ], + "source": [ + "import logging\n", + "\n", + "format = \"%(asctime)s %(filename)s:%(lineno)-4d %(levelname)s %(message)s\" # Add/modify these\n", + "logging.basicConfig(level=logging.WARNING, format=format) # two lines\n", + "\n", + "def my_fun(n):\n", + " for i in range(0, n):\n", + " logging.debug(i)\n", + " if i == 50:\n", + " logging.warning(\"The value of i is 50.\")\n", + " try:\n", + " i / (50 - i)\n", + " except ZeroDivisionError:\n", + " logging.error(\"Tried to divide by zero. Var i was {}. Recovered gracefully.\".format(i))\n", + "\n", + "if __name__ == \"__main__\":\n", + " my_fun(100)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Allows us to put items into a structured format so that we can make sense of what we are tracking \n", + "\n", + "format = \"%(asctime)s %(filename)s:%(lineno)-4d %(levelname)s %(message)s\"\n", + "logging.basicConfig(level=logging.WARNING, format=format)" + ] + }, + { + "cell_type": "code", + "execution_count": 21, + "metadata": {}, + "outputs": [], + "source": [ + "# Create a \"formatter\" using our format string\n", + "formatter = logging.Formatter(format)\n", + "\n", + "# Create a log message handler that sends output to the file 'mylog.log'\n", + "file_handler = logging.FileHandler('mylog.log') \n", + "# Set the formatter for this log message handler to the formatter we created above.\n", + "file_handler.setFormatter(formatter)\n", + "\n", + "# Get the \"root\" logger. More on that below.\n", + "logger = logging.getLogger()\n", + "# Add our file_handler to the \"root\" logger's handlers.\n", + "logger.addHandler(file_handler)" + ] + }, + { + "cell_type": "code", + "execution_count": 23, + "metadata": {}, + "outputs": [ + { + "name": "stderr", + "output_type": "stream", + "text": [ + "DEBUG:root:0\n", + "2018-06-07 19:46:14,997 :22 DEBUG 0\n", + "2018-06-07 19:46:14,997 :22 DEBUG 0\n", + "DEBUG:root:1\n", + "2018-06-07 19:46:15,005 :22 DEBUG 1\n", + "2018-06-07 19:46:15,005 :22 DEBUG 1\n", + "DEBUG:root:2\n", + "2018-06-07 19:46:15,011 :22 DEBUG 2\n", + "2018-06-07 19:46:15,011 :22 DEBUG 2\n", + "DEBUG:root:3\n", + "2018-06-07 19:46:15,017 :22 DEBUG 3\n", + "2018-06-07 19:46:15,017 :22 DEBUG 3\n", + "DEBUG:root:4\n", + "2018-06-07 19:46:15,025 :22 DEBUG 4\n", + "2018-06-07 19:46:15,025 :22 DEBUG 4\n", + "DEBUG:root:5\n", + "2018-06-07 19:46:15,028 :22 DEBUG 5\n", + "2018-06-07 19:46:15,028 :22 DEBUG 5\n", + "DEBUG:root:6\n", + "2018-06-07 19:46:15,031 :22 DEBUG 6\n", + "2018-06-07 19:46:15,031 :22 DEBUG 6\n", + "DEBUG:root:7\n", + "2018-06-07 19:46:15,033 :22 DEBUG 7\n", + "2018-06-07 19:46:15,033 :22 DEBUG 7\n", + "DEBUG:root:8\n", + "2018-06-07 19:46:15,037 :22 DEBUG 8\n", + "2018-06-07 19:46:15,037 :22 DEBUG 8\n", + "DEBUG:root:9\n", + "2018-06-07 19:46:15,039 :22 DEBUG 9\n", + "2018-06-07 19:46:15,039 :22 DEBUG 9\n", + "DEBUG:root:10\n", + "2018-06-07 19:46:15,043 :22 DEBUG 10\n", + "2018-06-07 19:46:15,043 :22 DEBUG 10\n", + "DEBUG:root:11\n", + "2018-06-07 19:46:15,045 :22 DEBUG 11\n", + "2018-06-07 19:46:15,045 :22 DEBUG 11\n", + "DEBUG:root:12\n", + "2018-06-07 19:46:15,051 :22 DEBUG 12\n", + "2018-06-07 19:46:15,051 :22 DEBUG 12\n", + "DEBUG:root:13\n", + "2018-06-07 19:46:15,053 :22 DEBUG 13\n", + "2018-06-07 19:46:15,053 :22 DEBUG 13\n", + "DEBUG:root:14\n", + "2018-06-07 19:46:15,056 :22 DEBUG 14\n", + "2018-06-07 19:46:15,056 :22 DEBUG 14\n", + "DEBUG:root:15\n", + "2018-06-07 19:46:15,058 :22 DEBUG 15\n", + "2018-06-07 19:46:15,058 :22 DEBUG 15\n", + "DEBUG:root:16\n", + "2018-06-07 19:46:15,061 :22 DEBUG 16\n", + "2018-06-07 19:46:15,061 :22 DEBUG 16\n", + "DEBUG:root:17\n", + "2018-06-07 19:46:15,063 :22 DEBUG 17\n", + "2018-06-07 19:46:15,063 :22 DEBUG 17\n", + "DEBUG:root:18\n", + "2018-06-07 19:46:15,066 :22 DEBUG 18\n", + "2018-06-07 19:46:15,066 :22 DEBUG 18\n", + "DEBUG:root:19\n", + "2018-06-07 19:46:15,068 :22 DEBUG 19\n", + "2018-06-07 19:46:15,068 :22 DEBUG 19\n", + "DEBUG:root:20\n", + "2018-06-07 19:46:15,071 :22 DEBUG 20\n", + "2018-06-07 19:46:15,071 :22 DEBUG 20\n", + "DEBUG:root:21\n", + "2018-06-07 19:46:15,073 :22 DEBUG 21\n", + "2018-06-07 19:46:15,073 :22 DEBUG 21\n", + "DEBUG:root:22\n", + "2018-06-07 19:46:15,076 :22 DEBUG 22\n", + "2018-06-07 19:46:15,076 :22 DEBUG 22\n", + "DEBUG:root:23\n", + "2018-06-07 19:46:15,078 :22 DEBUG 23\n", + "2018-06-07 19:46:15,078 :22 DEBUG 23\n", + "DEBUG:root:24\n", + "2018-06-07 19:46:15,084 :22 DEBUG 24\n", + "2018-06-07 19:46:15,084 :22 DEBUG 24\n", + "DEBUG:root:25\n", + "2018-06-07 19:46:15,096 :22 DEBUG 25\n", + "2018-06-07 19:46:15,096 :22 DEBUG 25\n", + "DEBUG:root:26\n", + "2018-06-07 19:46:15,100 :22 DEBUG 26\n", + "2018-06-07 19:46:15,100 :22 DEBUG 26\n", + "DEBUG:root:27\n", + "2018-06-07 19:46:15,102 :22 DEBUG 27\n", + "2018-06-07 19:46:15,102 :22 DEBUG 27\n", + "DEBUG:root:28\n", + "2018-06-07 19:46:15,109 :22 DEBUG 28\n", + "2018-06-07 19:46:15,109 :22 DEBUG 28\n", + "DEBUG:root:29\n", + "2018-06-07 19:46:15,112 :22 DEBUG 29\n", + "2018-06-07 19:46:15,112 :22 DEBUG 29\n", + "DEBUG:root:30\n", + "2018-06-07 19:46:15,116 :22 DEBUG 30\n", + "2018-06-07 19:46:15,116 :22 DEBUG 30\n", + "DEBUG:root:31\n", + "2018-06-07 19:46:15,118 :22 DEBUG 31\n", + "2018-06-07 19:46:15,118 :22 DEBUG 31\n", + "DEBUG:root:32\n", + "2018-06-07 19:46:15,121 :22 DEBUG 32\n", + "2018-06-07 19:46:15,121 :22 DEBUG 32\n", + "DEBUG:root:33\n", + "2018-06-07 19:46:15,124 :22 DEBUG 33\n", + "2018-06-07 19:46:15,124 :22 DEBUG 33\n", + "DEBUG:root:34\n", + "2018-06-07 19:46:15,126 :22 DEBUG 34\n", + "2018-06-07 19:46:15,126 :22 DEBUG 34\n", + "DEBUG:root:35\n", + "2018-06-07 19:46:15,129 :22 DEBUG 35\n", + "2018-06-07 19:46:15,129 :22 DEBUG 35\n", + "DEBUG:root:36\n", + "2018-06-07 19:46:15,132 :22 DEBUG 36\n", + "2018-06-07 19:46:15,132 :22 DEBUG 36\n", + "DEBUG:root:37\n", + "2018-06-07 19:46:15,134 :22 DEBUG 37\n", + "2018-06-07 19:46:15,134 :22 DEBUG 37\n", + "DEBUG:root:38\n", + "2018-06-07 19:46:15,137 :22 DEBUG 38\n", + "2018-06-07 19:46:15,137 :22 DEBUG 38\n", + "DEBUG:root:39\n", + "2018-06-07 19:46:15,139 :22 DEBUG 39\n", + "2018-06-07 19:46:15,139 :22 DEBUG 39\n", + "DEBUG:root:40\n", + "2018-06-07 19:46:15,164 :22 DEBUG 40\n", + "2018-06-07 19:46:15,164 :22 DEBUG 40\n", + "DEBUG:root:41\n", + "2018-06-07 19:46:15,208 :22 DEBUG 41\n", + "2018-06-07 19:46:15,208 :22 DEBUG 41\n", + "DEBUG:root:42\n", + "2018-06-07 19:46:15,224 :22 DEBUG 42\n", + "2018-06-07 19:46:15,224 :22 DEBUG 42\n", + "DEBUG:root:43\n", + "2018-06-07 19:46:15,231 :22 DEBUG 43\n", + "2018-06-07 19:46:15,231 :22 DEBUG 43\n", + "DEBUG:root:44\n", + "2018-06-07 19:46:15,259 :22 DEBUG 44\n", + "2018-06-07 19:46:15,259 :22 DEBUG 44\n", + "DEBUG:root:45\n", + "2018-06-07 19:46:15,278 :22 DEBUG 45\n", + "2018-06-07 19:46:15,278 :22 DEBUG 45\n", + "DEBUG:root:46\n", + "2018-06-07 19:46:15,306 :22 DEBUG 46\n", + "2018-06-07 19:46:15,306 :22 DEBUG 46\n", + "DEBUG:root:47\n", + "2018-06-07 19:46:15,312 :22 DEBUG 47\n", + "2018-06-07 19:46:15,312 :22 DEBUG 47\n", + "DEBUG:root:48\n", + "2018-06-07 19:46:15,340 :22 DEBUG 48\n", + "2018-06-07 19:46:15,340 :22 DEBUG 48\n", + "DEBUG:root:49\n", + "2018-06-07 19:46:15,345 :22 DEBUG 49\n", + "2018-06-07 19:46:15,345 :22 DEBUG 49\n", + "DEBUG:root:50\n", + "2018-06-07 19:46:15,391 :22 DEBUG 50\n", + "2018-06-07 19:46:15,391 :22 DEBUG 50\n", + "WARNING:root:The value of i is 50.\n", + "2018-06-07 19:46:15,398 :24 WARNING The value of i is 50.\n", + "2018-06-07 19:46:15,398 :24 WARNING The value of i is 50.\n", + "ERROR:root:Tried to divide by zero. Var i was 50. Recovered gracefully.\n", + "2018-06-07 19:46:15,406 :28 ERROR Tried to divide by zero. Var i was 50. Recovered gracefully.\n", + "2018-06-07 19:46:15,406 :28 ERROR Tried to divide by zero. Var i was 50. Recovered gracefully.\n" + ] + }, + { + "name": "stderr", + "output_type": "stream", + "text": [ + "DEBUG:root:51\n", + "2018-06-07 19:46:15,409 :22 DEBUG 51\n", + "2018-06-07 19:46:15,409 :22 DEBUG 51\n", + "DEBUG:root:52\n", + "2018-06-07 19:46:15,417 :22 DEBUG 52\n", + "2018-06-07 19:46:15,417 :22 DEBUG 52\n", + "DEBUG:root:53\n", + "2018-06-07 19:46:15,422 :22 DEBUG 53\n", + "2018-06-07 19:46:15,422 :22 DEBUG 53\n", + "DEBUG:root:54\n", + "2018-06-07 19:46:15,426 :22 DEBUG 54\n", + "2018-06-07 19:46:15,426 :22 DEBUG 54\n", + "DEBUG:root:55\n", + "2018-06-07 19:46:15,432 :22 DEBUG 55\n", + "2018-06-07 19:46:15,432 :22 DEBUG 55\n", + "DEBUG:root:56\n", + "2018-06-07 19:46:15,437 :22 DEBUG 56\n", + "2018-06-07 19:46:15,437 :22 DEBUG 56\n", + "DEBUG:root:57\n", + "2018-06-07 19:46:15,441 :22 DEBUG 57\n", + "2018-06-07 19:46:15,441 :22 DEBUG 57\n", + "DEBUG:root:58\n", + "2018-06-07 19:46:15,446 :22 DEBUG 58\n", + "2018-06-07 19:46:15,446 :22 DEBUG 58\n", + "DEBUG:root:59\n", + "2018-06-07 19:46:15,451 :22 DEBUG 59\n", + "2018-06-07 19:46:15,451 :22 DEBUG 59\n", + "DEBUG:root:60\n", + "2018-06-07 19:46:15,455 :22 DEBUG 60\n", + "2018-06-07 19:46:15,455 :22 DEBUG 60\n", + "DEBUG:root:61\n", + "2018-06-07 19:46:15,459 :22 DEBUG 61\n", + "2018-06-07 19:46:15,459 :22 DEBUG 61\n", + "DEBUG:root:62\n", + "2018-06-07 19:46:15,464 :22 DEBUG 62\n", + "2018-06-07 19:46:15,464 :22 DEBUG 62\n", + "DEBUG:root:63\n", + "2018-06-07 19:46:15,468 :22 DEBUG 63\n", + "2018-06-07 19:46:15,468 :22 DEBUG 63\n", + "DEBUG:root:64\n", + "2018-06-07 19:46:15,474 :22 DEBUG 64\n", + "2018-06-07 19:46:15,474 :22 DEBUG 64\n", + "DEBUG:root:65\n", + "2018-06-07 19:46:15,479 :22 DEBUG 65\n", + "2018-06-07 19:46:15,479 :22 DEBUG 65\n", + "DEBUG:root:66\n", + "2018-06-07 19:46:15,483 :22 DEBUG 66\n", + "2018-06-07 19:46:15,483 :22 DEBUG 66\n", + "DEBUG:root:67\n", + "2018-06-07 19:46:15,488 :22 DEBUG 67\n", + "2018-06-07 19:46:15,488 :22 DEBUG 67\n", + "DEBUG:root:68\n", + "2018-06-07 19:46:15,492 :22 DEBUG 68\n", + "2018-06-07 19:46:15,492 :22 DEBUG 68\n", + "DEBUG:root:69\n", + "2018-06-07 19:46:15,497 :22 DEBUG 69\n", + "2018-06-07 19:46:15,497 :22 DEBUG 69\n", + "DEBUG:root:70\n", + "2018-06-07 19:46:15,502 :22 DEBUG 70\n", + "2018-06-07 19:46:15,502 :22 DEBUG 70\n", + "DEBUG:root:71\n", + "2018-06-07 19:46:15,505 :22 DEBUG 71\n", + "2018-06-07 19:46:15,505 :22 DEBUG 71\n", + "DEBUG:root:72\n", + "2018-06-07 19:46:15,544 :22 DEBUG 72\n", + "2018-06-07 19:46:15,544 :22 DEBUG 72\n", + "DEBUG:root:73\n", + "2018-06-07 19:46:15,550 :22 DEBUG 73\n", + "2018-06-07 19:46:15,550 :22 DEBUG 73\n", + "DEBUG:root:74\n", + "2018-06-07 19:46:15,555 :22 DEBUG 74\n", + "2018-06-07 19:46:15,555 :22 DEBUG 74\n", + "DEBUG:root:75\n", + "2018-06-07 19:46:15,572 :22 DEBUG 75\n", + "2018-06-07 19:46:15,572 :22 DEBUG 75\n", + "DEBUG:root:76\n", + "2018-06-07 19:46:15,577 :22 DEBUG 76\n", + "2018-06-07 19:46:15,577 :22 DEBUG 76\n", + "DEBUG:root:77\n", + "2018-06-07 19:46:15,584 :22 DEBUG 77\n", + "2018-06-07 19:46:15,584 :22 DEBUG 77\n", + "DEBUG:root:78\n", + "2018-06-07 19:46:15,589 :22 DEBUG 78\n", + "2018-06-07 19:46:15,589 :22 DEBUG 78\n", + "DEBUG:root:79\n", + "2018-06-07 19:46:15,594 :22 DEBUG 79\n", + "2018-06-07 19:46:15,594 :22 DEBUG 79\n", + "DEBUG:root:80\n", + "2018-06-07 19:46:15,600 :22 DEBUG 80\n", + "2018-06-07 19:46:15,600 :22 DEBUG 80\n", + "DEBUG:root:81\n", + "2018-06-07 19:46:15,605 :22 DEBUG 81\n", + "2018-06-07 19:46:15,605 :22 DEBUG 81\n", + "DEBUG:root:82\n", + "2018-06-07 19:46:15,610 :22 DEBUG 82\n", + "2018-06-07 19:46:15,610 :22 DEBUG 82\n", + "DEBUG:root:83\n", + "2018-06-07 19:46:15,615 :22 DEBUG 83\n", + "2018-06-07 19:46:15,615 :22 DEBUG 83\n", + "DEBUG:root:84\n", + "2018-06-07 19:46:15,621 :22 DEBUG 84\n", + "2018-06-07 19:46:15,621 :22 DEBUG 84\n", + "DEBUG:root:85\n", + "2018-06-07 19:46:15,625 :22 DEBUG 85\n", + "2018-06-07 19:46:15,625 :22 DEBUG 85\n", + "DEBUG:root:86\n", + "2018-06-07 19:46:15,630 :22 DEBUG 86\n", + "2018-06-07 19:46:15,630 :22 DEBUG 86\n", + "DEBUG:root:87\n", + "2018-06-07 19:46:15,635 :22 DEBUG 87\n", + "2018-06-07 19:46:15,635 :22 DEBUG 87\n", + "DEBUG:root:88\n", + "2018-06-07 19:46:15,654 :22 DEBUG 88\n", + "2018-06-07 19:46:15,654 :22 DEBUG 88\n", + "DEBUG:root:89\n", + "2018-06-07 19:46:15,659 :22 DEBUG 89\n", + "2018-06-07 19:46:15,659 :22 DEBUG 89\n", + "DEBUG:root:90\n", + "2018-06-07 19:46:15,664 :22 DEBUG 90\n", + "2018-06-07 19:46:15,664 :22 DEBUG 90\n", + "DEBUG:root:91\n", + "2018-06-07 19:46:15,670 :22 DEBUG 91\n", + "2018-06-07 19:46:15,670 :22 DEBUG 91\n", + "DEBUG:root:92\n", + "2018-06-07 19:46:15,674 :22 DEBUG 92\n", + "2018-06-07 19:46:15,674 :22 DEBUG 92\n", + "DEBUG:root:93\n", + "2018-06-07 19:46:15,679 :22 DEBUG 93\n", + "2018-06-07 19:46:15,679 :22 DEBUG 93\n", + "DEBUG:root:94\n", + "2018-06-07 19:46:15,684 :22 DEBUG 94\n", + "2018-06-07 19:46:15,684 :22 DEBUG 94\n", + "DEBUG:root:95\n", + "2018-06-07 19:46:15,689 :22 DEBUG 95\n", + "2018-06-07 19:46:15,689 :22 DEBUG 95\n", + "DEBUG:root:96\n", + "2018-06-07 19:46:15,694 :22 DEBUG 96\n", + "2018-06-07 19:46:15,694 :22 DEBUG 96\n", + "DEBUG:root:97\n", + "2018-06-07 19:46:15,699 :22 DEBUG 97\n", + "2018-06-07 19:46:15,699 :22 DEBUG 97\n", + "DEBUG:root:98\n", + "2018-06-07 19:46:15,704 :22 DEBUG 98\n", + "2018-06-07 19:46:15,704 :22 DEBUG 98\n", + "DEBUG:root:99\n", + "2018-06-07 19:46:15,709 :22 DEBUG 99\n", + "2018-06-07 19:46:15,709 :22 DEBUG 99\n" + ] + } + ], + "source": [ + "import logging\n", + "\n", + "format = \"%(asctime)s %(filename)s:%(lineno)-3d %(levelname)s %(message)s\"\n", + "\n", + "formatter = logging.Formatter(format)\n", + "\n", + "file_handler = logging.FileHandler('mylog.log')\n", + "file_handler.setLevel(logging.WARNING) # Add this line\n", + "file_handler.setFormatter(formatter)\n", + "\n", + "console_handler = logging.StreamHandler() # Add this line\n", + "console_handler.setLevel(logging.DEBUG) # Add this line\n", + "console_handler.setFormatter(formatter) # Add this line\n", + "\n", + "logger = logging.getLogger()\n", + "logger.setLevel(logging.DEBUG) # Add this line\n", + "logger.addHandler(file_handler)\n", + "logger.addHandler(console_handler) # Add this line\n", + "\n", + "def my_fun(n):\n", + " for i in range(0, n):\n", + " logging.debug(i)\n", + " if i == 50:\n", + " logging.warning(\"The value of i is 50.\")\n", + " try:\n", + " i / (50 - i)\n", + " except ZeroDivisionError:\n", + " logging.error(\"Tried to divide by zero. Var i was {}. Recovered gracefully.\".format(i))\n", + "\n", + "if __name__ == \"__main__\":\n", + " my_fun(100)" + ] + }, + { + "cell_type": "code", + "execution_count": 24, + "metadata": {}, + "outputs": [ + { + "ename": "ZeroDivisionError", + "evalue": "division by zero", + "output_type": "error", + "traceback": [ + "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[0;31mZeroDivisionError\u001b[0m Traceback (most recent call last)", + "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[1;32m 5\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 6\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0m__name__\u001b[0m \u001b[0;34m==\u001b[0m \u001b[0;34m'__main__'\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 7\u001b[0;31m \u001b[0mmy_fun\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", + "\u001b[0;32m\u001b[0m in \u001b[0;36mmy_fun\u001b[0;34m()\u001b[0m\n\u001b[1;32m 2\u001b[0m \u001b[0;32mdef\u001b[0m \u001b[0mmy_fun\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 3\u001b[0m \u001b[0;32mfor\u001b[0m \u001b[0mi\u001b[0m \u001b[0;32min\u001b[0m \u001b[0mrange\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;36m1\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;36m500\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 4\u001b[0;31m \u001b[0;36m123\u001b[0m\u001b[0;34m/\u001b[0m \u001b[0;34m(\u001b[0m\u001b[0;36m50\u001b[0m \u001b[0;34m-\u001b[0m \u001b[0mi\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 5\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 6\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0m__name__\u001b[0m \u001b[0;34m==\u001b[0m \u001b[0;34m'__main__'\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", + "\u001b[0;31mZeroDivisionError\u001b[0m: division by zero" + ] + } + ], + "source": [ + "# simple.py\n", + "def my_fun():\n", + " for i in range(1, 500):\n", + " 123/ (50 - i)\n", + "\n", + "if __name__ == '__main__':\n", + " my_fun()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.6.5" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/Students/Wayne/Activities/Lesson_05/Lesson_05.ipynb b/Students/Wayne/Activities/Lesson_05/Lesson_05.ipynb new file mode 100644 index 0000000..066a845 --- /dev/null +++ b/Students/Wayne/Activities/Lesson_05/Lesson_05.ipynb @@ -0,0 +1,1200 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Logging and Debugging ##\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# New Words, Concepts, and Tools\n", + "logging\n", + "log levels\n", + "syslog\n", + "debugger\n", + "pdb\n", + "breakpoint\n", + "\"step in\"\n", + "continue" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Logging\n", + "\n", + "https://docs.python.org/3/library/logging.html#levels" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [ + { + "ename": "ZeroDivisionError", + "evalue": "division by zero", + "output_type": "error", + "traceback": [ + "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[0;31mZeroDivisionError\u001b[0m Traceback (most recent call last)", + "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[1;32m 5\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 6\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0m__name__\u001b[0m \u001b[0;34m==\u001b[0m \u001b[0;34m\"__main__\"\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 7\u001b[0;31m \u001b[0mmy_fun\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;36m100\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", + "\u001b[0;32m\u001b[0m in \u001b[0;36mmy_fun\u001b[0;34m(n)\u001b[0m\n\u001b[1;32m 2\u001b[0m \u001b[0;32mdef\u001b[0m \u001b[0mmy_fun\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mn\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 3\u001b[0m \u001b[0;32mfor\u001b[0m \u001b[0mi\u001b[0m \u001b[0;32min\u001b[0m \u001b[0mrange\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;36m0\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mn\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 4\u001b[0;31m \u001b[0mi\u001b[0m \u001b[0;34m/\u001b[0m \u001b[0;34m(\u001b[0m\u001b[0;36m50\u001b[0m \u001b[0;34m-\u001b[0m \u001b[0mi\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 5\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 6\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0m__name__\u001b[0m \u001b[0;34m==\u001b[0m \u001b[0;34m\"__main__\"\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", + "\u001b[0;31mZeroDivisionError\u001b[0m: division by zero" + ] + } + ], + "source": [ + "# simple.py\n", + "def my_fun(n):\n", + " for i in range(0, n):\n", + " i / (50 - i)\n", + "\n", + "if __name__ == \"__main__\":\n", + " my_fun(100)" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "0\n", + "1\n", + "2\n", + "3\n", + "4\n", + "5\n", + "6\n", + "7\n", + "8\n", + "9\n", + "10\n", + "11\n", + "12\n", + "13\n", + "14\n", + "15\n", + "16\n", + "17\n", + "18\n", + "19\n", + "20\n", + "21\n", + "22\n", + "23\n", + "24\n", + "25\n", + "26\n", + "27\n", + "28\n", + "29\n", + "30\n", + "31\n", + "32\n", + "33\n", + "34\n", + "35\n", + "36\n", + "37\n", + "38\n", + "39\n", + "40\n", + "41\n", + "42\n", + "43\n", + "44\n", + "45\n", + "46\n", + "47\n", + "48\n", + "49\n", + "50\n" + ] + }, + { + "ename": "ZeroDivisionError", + "evalue": "division by zero", + "output_type": "error", + "traceback": [ + "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[0;31mZeroDivisionError\u001b[0m Traceback (most recent call last)", + "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[1;32m 6\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 7\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0m__name__\u001b[0m \u001b[0;34m==\u001b[0m \u001b[0;34m\"__main__\"\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 8\u001b[0;31m \u001b[0mmy_fun\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;36m100\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", + "\u001b[0;32m\u001b[0m in \u001b[0;36mmy_fun\u001b[0;34m(n)\u001b[0m\n\u001b[1;32m 3\u001b[0m \u001b[0;32mfor\u001b[0m \u001b[0mi\u001b[0m \u001b[0;32min\u001b[0m \u001b[0mrange\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;36m0\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mn\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 4\u001b[0m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mi\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;31m# <-- Add this line\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 5\u001b[0;31m \u001b[0;36m100\u001b[0m \u001b[0;34m/\u001b[0m \u001b[0;34m(\u001b[0m\u001b[0;36m50\u001b[0m \u001b[0;34m-\u001b[0m \u001b[0mi\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 6\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 7\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0m__name__\u001b[0m \u001b[0;34m==\u001b[0m \u001b[0;34m\"__main__\"\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", + "\u001b[0;31mZeroDivisionError\u001b[0m: division by zero" + ] + } + ], + "source": [ + "# simple.py\n", + "def my_fun(n):\n", + " for i in range(0, n):\n", + " print(i) # <-- Add this line\n", + " 100 / (50 - i)\n", + " \n", + "if __name__ == \"__main__\":\n", + " my_fun(100)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Here are a few problems with using a print statement to debug your code:\n", + "\n", + "- You have to go back in and take them out, otherwise they produce distracting output when you're running your program.\n", + "\n", + "- If you have more than a couple of print statements, it becomes hard to keep track of where they all are and what each one specifically is reporting on.\n", + "\n", + "- Print statements don't help you when your code is being run in production: you can only use print statements when you're running the code on your own machine from your console." + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "metadata": {}, + "outputs": [ + { + "name": "stderr", + "output_type": "stream", + "text": [ + "DEBUG:root:0\n", + "DEBUG:root:1\n", + "DEBUG:root:2\n", + "DEBUG:root:3\n", + "DEBUG:root:4\n", + "DEBUG:root:5\n", + "DEBUG:root:6\n", + "DEBUG:root:7\n", + "DEBUG:root:8\n", + "DEBUG:root:9\n", + "DEBUG:root:10\n", + "DEBUG:root:11\n", + "DEBUG:root:12\n", + "DEBUG:root:13\n", + "DEBUG:root:14\n", + "DEBUG:root:15\n", + "DEBUG:root:16\n", + "DEBUG:root:17\n", + "DEBUG:root:18\n", + "DEBUG:root:19\n", + "DEBUG:root:20\n", + "DEBUG:root:21\n", + "DEBUG:root:22\n", + "DEBUG:root:23\n", + "DEBUG:root:24\n", + "DEBUG:root:25\n", + "DEBUG:root:26\n", + "DEBUG:root:27\n", + "DEBUG:root:28\n", + "DEBUG:root:29\n", + "DEBUG:root:30\n", + "DEBUG:root:31\n", + "DEBUG:root:32\n", + "DEBUG:root:33\n", + "DEBUG:root:34\n", + "DEBUG:root:35\n", + "DEBUG:root:36\n", + "DEBUG:root:37\n", + "DEBUG:root:38\n", + "DEBUG:root:39\n", + "DEBUG:root:40\n", + "DEBUG:root:41\n", + "DEBUG:root:42\n", + "DEBUG:root:43\n", + "DEBUG:root:44\n", + "DEBUG:root:45\n", + "DEBUG:root:46\n", + "DEBUG:root:47\n", + "DEBUG:root:48\n", + "DEBUG:root:49\n", + "DEBUG:root:50\n" + ] + }, + { + "ename": "ZeroDivisionError", + "evalue": "division by zero", + "output_type": "error", + "traceback": [ + "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[0;31mZeroDivisionError\u001b[0m Traceback (most recent call last)", + "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[1;32m 8\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 9\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0m__name__\u001b[0m \u001b[0;34m==\u001b[0m \u001b[0;34m\"__main__\"\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 10\u001b[0;31m \u001b[0mmy_fun\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;36m100\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", + "\u001b[0;32m\u001b[0m in \u001b[0;36mmy_fun\u001b[0;34m(n)\u001b[0m\n\u001b[1;32m 5\u001b[0m \u001b[0;32mfor\u001b[0m \u001b[0mi\u001b[0m \u001b[0;32min\u001b[0m \u001b[0mrange\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;36m0\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mn\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 6\u001b[0m \u001b[0mlogging\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mdebug\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mi\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 7\u001b[0;31m \u001b[0mi\u001b[0m \u001b[0;34m/\u001b[0m \u001b[0;34m(\u001b[0m\u001b[0;36m50\u001b[0m \u001b[0;34m-\u001b[0m \u001b[0mi\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 8\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 9\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0m__name__\u001b[0m \u001b[0;34m==\u001b[0m \u001b[0;34m\"__main__\"\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", + "\u001b[0;31mZeroDivisionError\u001b[0m: division by zero" + ] + } + ], + "source": [ + "import logging\n", + "\n", + "logging.basicConfig(level=logging.DEBUG)\n", + "def my_fun(n):\n", + " for i in range(0, n):\n", + " logging.debug(i)\n", + " i / (50 - i)\n", + "\n", + "if __name__ == \"__main__\":\n", + " my_fun(100)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "So far, this doesn't look very different from the print statement that we were using before. But let's change one line of the script:" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "metadata": {}, + "outputs": [ + { + "name": "stderr", + "output_type": "stream", + "text": [ + "DEBUG:root:0\n", + "DEBUG:root:1\n", + "DEBUG:root:2\n", + "DEBUG:root:3\n", + "DEBUG:root:4\n", + "DEBUG:root:5\n", + "DEBUG:root:6\n", + "DEBUG:root:7\n", + "DEBUG:root:8\n", + "DEBUG:root:9\n", + "DEBUG:root:10\n", + "DEBUG:root:11\n", + "DEBUG:root:12\n", + "DEBUG:root:13\n", + "DEBUG:root:14\n", + "DEBUG:root:15\n", + "DEBUG:root:16\n", + "DEBUG:root:17\n", + "DEBUG:root:18\n", + "DEBUG:root:19\n", + "DEBUG:root:20\n", + "DEBUG:root:21\n", + "DEBUG:root:22\n", + "DEBUG:root:23\n", + "DEBUG:root:24\n", + "DEBUG:root:25\n", + "DEBUG:root:26\n", + "DEBUG:root:27\n", + "DEBUG:root:28\n", + "DEBUG:root:29\n", + "DEBUG:root:30\n", + "DEBUG:root:31\n", + "DEBUG:root:32\n", + "DEBUG:root:33\n", + "DEBUG:root:34\n", + "DEBUG:root:35\n", + "DEBUG:root:36\n", + "DEBUG:root:37\n", + "DEBUG:root:38\n", + "DEBUG:root:39\n", + "DEBUG:root:40\n", + "DEBUG:root:41\n", + "DEBUG:root:42\n", + "DEBUG:root:43\n", + "DEBUG:root:44\n", + "DEBUG:root:45\n", + "DEBUG:root:46\n", + "DEBUG:root:47\n", + "DEBUG:root:48\n", + "DEBUG:root:49\n", + "DEBUG:root:50\n" + ] + }, + { + "ename": "ZeroDivisionError", + "evalue": "division by zero", + "output_type": "error", + "traceback": [ + "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[0;31mZeroDivisionError\u001b[0m Traceback (most recent call last)", + "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[1;32m 8\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 9\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0m__name__\u001b[0m \u001b[0;34m==\u001b[0m \u001b[0;34m\"__main__\"\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 10\u001b[0;31m \u001b[0mmy_fun\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;36m100\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", + "\u001b[0;32m\u001b[0m in \u001b[0;36mmy_fun\u001b[0;34m(n)\u001b[0m\n\u001b[1;32m 5\u001b[0m \u001b[0;32mfor\u001b[0m \u001b[0mi\u001b[0m \u001b[0;32min\u001b[0m \u001b[0mrange\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;36m0\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mn\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 6\u001b[0m \u001b[0mlogging\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mdebug\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mi\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 7\u001b[0;31m \u001b[0mi\u001b[0m \u001b[0;34m/\u001b[0m \u001b[0;34m(\u001b[0m\u001b[0;36m50\u001b[0m \u001b[0;34m-\u001b[0m \u001b[0mi\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 8\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 9\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0m__name__\u001b[0m \u001b[0;34m==\u001b[0m \u001b[0;34m\"__main__\"\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", + "\u001b[0;31mZeroDivisionError\u001b[0m: division by zero" + ] + } + ], + "source": [ + "import logging\n", + "\n", + "logging.basicConfig(level=logging.WARNING) # Change the level to logging.WARNING\n", + "def my_fun(n):\n", + " for i in range(0, n):\n", + " logging.debug(i)\n", + " i / (50 - i)\n", + "\n", + "if __name__ == \"__main__\":\n", + " my_fun(100)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "This logging statement is just giving us some information about how the function is being used, so we've used the logging.info method.\n", + "\n", + "In our example script, when we were trying to figure out what value of i was causing our script to crash, we were debugging our code. That's why we used a logging.debug statement. Now that we know that the value 50 causes our code to crash, we could put in a logging.warning statement that will warn us of dangerous conditions:" + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "metadata": {}, + "outputs": [ + { + "name": "stderr", + "output_type": "stream", + "text": [ + "DEBUG:root:0\n", + "DEBUG:root:1\n", + "DEBUG:root:2\n", + "DEBUG:root:3\n", + "DEBUG:root:4\n", + "DEBUG:root:5\n", + "DEBUG:root:6\n", + "DEBUG:root:7\n", + "DEBUG:root:8\n", + "DEBUG:root:9\n", + "DEBUG:root:10\n", + "DEBUG:root:11\n", + "DEBUG:root:12\n", + "DEBUG:root:13\n", + "DEBUG:root:14\n", + "DEBUG:root:15\n", + "DEBUG:root:16\n", + "DEBUG:root:17\n", + "DEBUG:root:18\n", + "DEBUG:root:19\n", + "DEBUG:root:20\n", + "DEBUG:root:21\n", + "DEBUG:root:22\n", + "DEBUG:root:23\n", + "DEBUG:root:24\n", + "DEBUG:root:25\n", + "DEBUG:root:26\n", + "DEBUG:root:27\n", + "DEBUG:root:28\n", + "DEBUG:root:29\n", + "DEBUG:root:30\n", + "DEBUG:root:31\n", + "DEBUG:root:32\n", + "DEBUG:root:33\n", + "DEBUG:root:34\n", + "DEBUG:root:35\n", + "DEBUG:root:36\n", + "DEBUG:root:37\n", + "DEBUG:root:38\n", + "DEBUG:root:39\n", + "DEBUG:root:40\n", + "DEBUG:root:41\n", + "DEBUG:root:42\n", + "DEBUG:root:43\n", + "DEBUG:root:44\n", + "DEBUG:root:45\n", + "DEBUG:root:46\n", + "DEBUG:root:47\n", + "DEBUG:root:48\n", + "DEBUG:root:49\n", + "DEBUG:root:50\n", + "WARNING:root:The value of i is 50.\n" + ] + }, + { + "ename": "ZeroDivisionError", + "evalue": "division by zero", + "output_type": "error", + "traceback": [ + "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[0;31mZeroDivisionError\u001b[0m Traceback (most recent call last)", + "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[1;32m 10\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 11\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0m__name__\u001b[0m \u001b[0;34m==\u001b[0m \u001b[0;34m\"__main__\"\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 12\u001b[0;31m \u001b[0mmy_fun\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;36m100\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", + "\u001b[0;32m\u001b[0m in \u001b[0;36mmy_fun\u001b[0;34m(n)\u001b[0m\n\u001b[1;32m 7\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0mi\u001b[0m \u001b[0;34m==\u001b[0m \u001b[0;36m50\u001b[0m\u001b[0;34m:\u001b[0m \u001b[0;31m# Add this line\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 8\u001b[0m \u001b[0mlogging\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mwarning\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m\"The value of i is 50.\"\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;31m# Add this line\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 9\u001b[0;31m \u001b[0mi\u001b[0m \u001b[0;34m/\u001b[0m \u001b[0;34m(\u001b[0m\u001b[0;36m50\u001b[0m \u001b[0;34m-\u001b[0m \u001b[0mi\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 10\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 11\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0m__name__\u001b[0m \u001b[0;34m==\u001b[0m \u001b[0;34m\"__main__\"\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", + "\u001b[0;31mZeroDivisionError\u001b[0m: division by zero" + ] + } + ], + "source": [ + "import logging\n", + "\n", + "logging.basicConfig(level=logging.WARNING)\n", + "def my_fun(n):\n", + " for i in range(0, n):\n", + " logging.debug(i)\n", + " if i == 50: # Add this line\n", + " logging.warning(\"The value of i is 50.\") # Add this line\n", + " i / (50 - i)\n", + "\n", + "if __name__ == \"__main__\":\n", + " my_fun(100)" + ] + }, + { + "cell_type": "code", + "execution_count": 16, + "metadata": {}, + "outputs": [ + { + "name": "stderr", + "output_type": "stream", + "text": [ + "DEBUG:root:0\n", + "DEBUG:root:1\n", + "DEBUG:root:2\n", + "DEBUG:root:3\n", + "DEBUG:root:4\n", + "DEBUG:root:5\n", + "DEBUG:root:6\n", + "DEBUG:root:7\n", + "DEBUG:root:8\n", + "DEBUG:root:9\n", + "DEBUG:root:10\n", + "DEBUG:root:11\n", + "DEBUG:root:12\n", + "DEBUG:root:13\n", + "DEBUG:root:14\n", + "DEBUG:root:15\n", + "DEBUG:root:16\n", + "DEBUG:root:17\n", + "DEBUG:root:18\n", + "DEBUG:root:19\n", + "DEBUG:root:20\n", + "DEBUG:root:21\n", + "DEBUG:root:22\n", + "DEBUG:root:23\n", + "DEBUG:root:24\n", + "DEBUG:root:25\n", + "DEBUG:root:26\n", + "DEBUG:root:27\n", + "DEBUG:root:28\n", + "DEBUG:root:29\n", + "DEBUG:root:30\n", + "DEBUG:root:31\n", + "DEBUG:root:32\n", + "DEBUG:root:33\n", + "DEBUG:root:34\n", + "DEBUG:root:35\n", + "DEBUG:root:36\n", + "DEBUG:root:37\n", + "DEBUG:root:38\n", + "DEBUG:root:39\n", + "DEBUG:root:40\n", + "DEBUG:root:41\n", + "DEBUG:root:42\n", + "DEBUG:root:43\n", + "DEBUG:root:44\n", + "DEBUG:root:45\n", + "DEBUG:root:46\n", + "DEBUG:root:47\n", + "DEBUG:root:48\n", + "DEBUG:root:49\n", + "DEBUG:root:50\n", + "WARNING:root:The value of i is 50.\n", + "ERROR:root:Tried to divide by zero. Var i was 50. Recovered gracefully.\n", + "DEBUG:root:51\n", + "DEBUG:root:52\n", + "DEBUG:root:53\n", + "DEBUG:root:54\n", + "DEBUG:root:55\n", + "DEBUG:root:56\n", + "DEBUG:root:57\n", + "DEBUG:root:58\n", + "DEBUG:root:59\n", + "DEBUG:root:60\n", + "DEBUG:root:61\n", + "DEBUG:root:62\n", + "DEBUG:root:63\n", + "DEBUG:root:64\n", + "DEBUG:root:65\n", + "DEBUG:root:66\n", + "DEBUG:root:67\n", + "DEBUG:root:68\n", + "DEBUG:root:69\n", + "DEBUG:root:70\n", + "DEBUG:root:71\n", + "DEBUG:root:72\n", + "DEBUG:root:73\n", + "DEBUG:root:74\n", + "DEBUG:root:75\n", + "DEBUG:root:76\n", + "DEBUG:root:77\n", + "DEBUG:root:78\n", + "DEBUG:root:79\n", + "DEBUG:root:80\n", + "DEBUG:root:81\n", + "DEBUG:root:82\n", + "DEBUG:root:83\n", + "DEBUG:root:84\n", + "DEBUG:root:85\n", + "DEBUG:root:86\n", + "DEBUG:root:87\n", + "DEBUG:root:88\n", + "DEBUG:root:89\n", + "DEBUG:root:90\n", + "DEBUG:root:91\n", + "DEBUG:root:92\n", + "DEBUG:root:93\n", + "DEBUG:root:94\n", + "DEBUG:root:95\n", + "DEBUG:root:96\n", + "DEBUG:root:97\n", + "DEBUG:root:98\n", + "DEBUG:root:99\n" + ] + } + ], + "source": [ + "import logging\n", + "\n", + "logging.basicConfig(level=logging.WARNING)\n", + "\n", + "def my_fun(n):\n", + " for i in range(0, n):\n", + " logging.debug(i)\n", + " if i == 50:\n", + " logging.warning(\"The value of i is 50.\")\n", + " try:\n", + " i / (50 - i)\n", + " except ZeroDivisionError:\n", + " logging.error(\"Tried to divide by zero. Var i was {}. Recovered gracefully.\".format(i))\n", + "\n", + "if __name__ == \"__main__\":\n", + " my_fun(100)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The statement logging.basicConfig(level=logging.WARNING) tells the logger to only display log messages with level WARNING and above. Look back to the logging levels documenation. You'll see that the DEBUG level is below the WARNING level: it won't be displayed. When we were debugging this code, the debug statements were helping us understand why our code was failing, but now it would be overwhelming to see them every time we run our code. We've hidden the statements by making a single configuration change.\n", + "\n", + "The idea is that you might be working on a project with a lot of Python files. You may have put debugging or information statements into several of these files. While you're authoring the project, these messages are useful. And once you think you've worked out all of the bugs in your code, you don't have to go through all of your files and find every logging statement: you can just turn off the unimportant ones by setting the log level in your main script." + ] + }, + { + "cell_type": "code", + "execution_count": 17, + "metadata": {}, + "outputs": [ + { + "name": "stderr", + "output_type": "stream", + "text": [ + "CRITICAL:root:This is a critical error!\n", + "ERROR:root:I'm an error.\n", + "WARNING:root:Hello! I'm a warning!\n", + "INFO:root:This is some information.\n", + "DEBUG:root:Perhaps this information will help you find your problem?\n" + ] + } + ], + "source": [ + "# loggingtest.py\n", + "import logging\n", + "\n", + "logging.critical(\"This is a critical error!\")\n", + "logging.error(\"I'm an error.\")\n", + "logging.warning(\"Hello! I'm a warning!\")\n", + "logging.info(\"This is some information.\")\n", + "logging.debug(\"Perhaps this information will help you find your problem?\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Although I used the logging.basicConfig method to set the logging level in these examples, there are other ways to set this value. We'll learn about this later in the lesson." + ] + }, + { + "cell_type": "code", + "execution_count": 20, + "metadata": {}, + "outputs": [ + { + "name": "stderr", + "output_type": "stream", + "text": [ + "DEBUG:root:0\n", + "DEBUG:root:1\n", + "DEBUG:root:2\n", + "DEBUG:root:3\n", + "DEBUG:root:4\n", + "DEBUG:root:5\n", + "DEBUG:root:6\n", + "DEBUG:root:7\n", + "DEBUG:root:8\n", + "DEBUG:root:9\n", + "DEBUG:root:10\n", + "DEBUG:root:11\n", + "DEBUG:root:12\n", + "DEBUG:root:13\n", + "DEBUG:root:14\n", + "DEBUG:root:15\n", + "DEBUG:root:16\n", + "DEBUG:root:17\n", + "DEBUG:root:18\n", + "DEBUG:root:19\n", + "DEBUG:root:20\n", + "DEBUG:root:21\n", + "DEBUG:root:22\n", + "DEBUG:root:23\n", + "DEBUG:root:24\n", + "DEBUG:root:25\n", + "DEBUG:root:26\n", + "DEBUG:root:27\n", + "DEBUG:root:28\n", + "DEBUG:root:29\n", + "DEBUG:root:30\n", + "DEBUG:root:31\n", + "DEBUG:root:32\n", + "DEBUG:root:33\n", + "DEBUG:root:34\n", + "DEBUG:root:35\n", + "DEBUG:root:36\n", + "DEBUG:root:37\n", + "DEBUG:root:38\n", + "DEBUG:root:39\n", + "DEBUG:root:40\n", + "DEBUG:root:41\n", + "DEBUG:root:42\n", + "DEBUG:root:43\n", + "DEBUG:root:44\n", + "DEBUG:root:45\n", + "DEBUG:root:46\n", + "DEBUG:root:47\n", + "DEBUG:root:48\n", + "DEBUG:root:49\n", + "DEBUG:root:50\n", + "WARNING:root:The value of i is 50.\n", + "ERROR:root:Tried to divide by zero. Var i was 50. Recovered gracefully.\n", + "DEBUG:root:51\n", + "DEBUG:root:52\n", + "DEBUG:root:53\n", + "DEBUG:root:54\n", + "DEBUG:root:55\n", + "DEBUG:root:56\n", + "DEBUG:root:57\n", + "DEBUG:root:58\n", + "DEBUG:root:59\n", + "DEBUG:root:60\n", + "DEBUG:root:61\n", + "DEBUG:root:62\n", + "DEBUG:root:63\n", + "DEBUG:root:64\n", + "DEBUG:root:65\n", + "DEBUG:root:66\n", + "DEBUG:root:67\n", + "DEBUG:root:68\n", + "DEBUG:root:69\n", + "DEBUG:root:70\n", + "DEBUG:root:71\n", + "DEBUG:root:72\n", + "DEBUG:root:73\n", + "DEBUG:root:74\n", + "DEBUG:root:75\n", + "DEBUG:root:76\n", + "DEBUG:root:77\n", + "DEBUG:root:78\n", + "DEBUG:root:79\n", + "DEBUG:root:80\n", + "DEBUG:root:81\n", + "DEBUG:root:82\n", + "DEBUG:root:83\n", + "DEBUG:root:84\n", + "DEBUG:root:85\n", + "DEBUG:root:86\n", + "DEBUG:root:87\n", + "DEBUG:root:88\n", + "DEBUG:root:89\n", + "DEBUG:root:90\n", + "DEBUG:root:91\n", + "DEBUG:root:92\n", + "DEBUG:root:93\n", + "DEBUG:root:94\n", + "DEBUG:root:95\n", + "DEBUG:root:96\n", + "DEBUG:root:97\n", + "DEBUG:root:98\n", + "DEBUG:root:99\n" + ] + } + ], + "source": [ + "import logging\n", + "\n", + "format = \"%(asctime)s %(filename)s:%(lineno)-4d %(levelname)s %(message)s\" # Add/modify these\n", + "logging.basicConfig(level=logging.WARNING, format=format) # two lines\n", + "\n", + "def my_fun(n):\n", + " for i in range(0, n):\n", + " logging.debug(i)\n", + " if i == 50:\n", + " logging.warning(\"The value of i is 50.\")\n", + " try:\n", + " i / (50 - i)\n", + " except ZeroDivisionError:\n", + " logging.error(\"Tried to divide by zero. Var i was {}. Recovered gracefully.\".format(i))\n", + "\n", + "if __name__ == \"__main__\":\n", + " my_fun(100)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Allows us to put items into a structured format so that we can make sense of what we are tracking \n", + "\n", + "format = \"%(asctime)s %(filename)s:%(lineno)-4d %(levelname)s %(message)s\"\n", + "logging.basicConfig(level=logging.WARNING, format=format)" + ] + }, + { + "cell_type": "code", + "execution_count": 21, + "metadata": {}, + "outputs": [], + "source": [ + "# Create a \"formatter\" using our format string\n", + "formatter = logging.Formatter(format)\n", + "\n", + "# Create a log message handler that sends output to the file 'mylog.log'\n", + "file_handler = logging.FileHandler('mylog.log') \n", + "# Set the formatter for this log message handler to the formatter we created above.\n", + "file_handler.setFormatter(formatter)\n", + "\n", + "# Get the \"root\" logger. More on that below.\n", + "logger = logging.getLogger()\n", + "# Add our file_handler to the \"root\" logger's handlers.\n", + "logger.addHandler(file_handler)" + ] + }, + { + "cell_type": "code", + "execution_count": 23, + "metadata": {}, + "outputs": [ + { + "name": "stderr", + "output_type": "stream", + "text": [ + "DEBUG:root:0\n", + "2018-06-07 19:46:14,997 :22 DEBUG 0\n", + "2018-06-07 19:46:14,997 :22 DEBUG 0\n", + "DEBUG:root:1\n", + "2018-06-07 19:46:15,005 :22 DEBUG 1\n", + "2018-06-07 19:46:15,005 :22 DEBUG 1\n", + "DEBUG:root:2\n", + "2018-06-07 19:46:15,011 :22 DEBUG 2\n", + "2018-06-07 19:46:15,011 :22 DEBUG 2\n", + "DEBUG:root:3\n", + "2018-06-07 19:46:15,017 :22 DEBUG 3\n", + "2018-06-07 19:46:15,017 :22 DEBUG 3\n", + "DEBUG:root:4\n", + "2018-06-07 19:46:15,025 :22 DEBUG 4\n", + "2018-06-07 19:46:15,025 :22 DEBUG 4\n", + "DEBUG:root:5\n", + "2018-06-07 19:46:15,028 :22 DEBUG 5\n", + "2018-06-07 19:46:15,028 :22 DEBUG 5\n", + "DEBUG:root:6\n", + "2018-06-07 19:46:15,031 :22 DEBUG 6\n", + "2018-06-07 19:46:15,031 :22 DEBUG 6\n", + "DEBUG:root:7\n", + "2018-06-07 19:46:15,033 :22 DEBUG 7\n", + "2018-06-07 19:46:15,033 :22 DEBUG 7\n", + "DEBUG:root:8\n", + "2018-06-07 19:46:15,037 :22 DEBUG 8\n", + "2018-06-07 19:46:15,037 :22 DEBUG 8\n", + "DEBUG:root:9\n", + "2018-06-07 19:46:15,039 :22 DEBUG 9\n", + "2018-06-07 19:46:15,039 :22 DEBUG 9\n", + "DEBUG:root:10\n", + "2018-06-07 19:46:15,043 :22 DEBUG 10\n", + "2018-06-07 19:46:15,043 :22 DEBUG 10\n", + "DEBUG:root:11\n", + "2018-06-07 19:46:15,045 :22 DEBUG 11\n", + "2018-06-07 19:46:15,045 :22 DEBUG 11\n", + "DEBUG:root:12\n", + "2018-06-07 19:46:15,051 :22 DEBUG 12\n", + "2018-06-07 19:46:15,051 :22 DEBUG 12\n", + "DEBUG:root:13\n", + "2018-06-07 19:46:15,053 :22 DEBUG 13\n", + "2018-06-07 19:46:15,053 :22 DEBUG 13\n", + "DEBUG:root:14\n", + "2018-06-07 19:46:15,056 :22 DEBUG 14\n", + "2018-06-07 19:46:15,056 :22 DEBUG 14\n", + "DEBUG:root:15\n", + "2018-06-07 19:46:15,058 :22 DEBUG 15\n", + "2018-06-07 19:46:15,058 :22 DEBUG 15\n", + "DEBUG:root:16\n", + "2018-06-07 19:46:15,061 :22 DEBUG 16\n", + "2018-06-07 19:46:15,061 :22 DEBUG 16\n", + "DEBUG:root:17\n", + "2018-06-07 19:46:15,063 :22 DEBUG 17\n", + "2018-06-07 19:46:15,063 :22 DEBUG 17\n", + "DEBUG:root:18\n", + "2018-06-07 19:46:15,066 :22 DEBUG 18\n", + "2018-06-07 19:46:15,066 :22 DEBUG 18\n", + "DEBUG:root:19\n", + "2018-06-07 19:46:15,068 :22 DEBUG 19\n", + "2018-06-07 19:46:15,068 :22 DEBUG 19\n", + "DEBUG:root:20\n", + "2018-06-07 19:46:15,071 :22 DEBUG 20\n", + "2018-06-07 19:46:15,071 :22 DEBUG 20\n", + "DEBUG:root:21\n", + "2018-06-07 19:46:15,073 :22 DEBUG 21\n", + "2018-06-07 19:46:15,073 :22 DEBUG 21\n", + "DEBUG:root:22\n", + "2018-06-07 19:46:15,076 :22 DEBUG 22\n", + "2018-06-07 19:46:15,076 :22 DEBUG 22\n", + "DEBUG:root:23\n", + "2018-06-07 19:46:15,078 :22 DEBUG 23\n", + "2018-06-07 19:46:15,078 :22 DEBUG 23\n", + "DEBUG:root:24\n", + "2018-06-07 19:46:15,084 :22 DEBUG 24\n", + "2018-06-07 19:46:15,084 :22 DEBUG 24\n", + "DEBUG:root:25\n", + "2018-06-07 19:46:15,096 :22 DEBUG 25\n", + "2018-06-07 19:46:15,096 :22 DEBUG 25\n", + "DEBUG:root:26\n", + "2018-06-07 19:46:15,100 :22 DEBUG 26\n", + "2018-06-07 19:46:15,100 :22 DEBUG 26\n", + "DEBUG:root:27\n", + "2018-06-07 19:46:15,102 :22 DEBUG 27\n", + "2018-06-07 19:46:15,102 :22 DEBUG 27\n", + "DEBUG:root:28\n", + "2018-06-07 19:46:15,109 :22 DEBUG 28\n", + "2018-06-07 19:46:15,109 :22 DEBUG 28\n", + "DEBUG:root:29\n", + "2018-06-07 19:46:15,112 :22 DEBUG 29\n", + "2018-06-07 19:46:15,112 :22 DEBUG 29\n", + "DEBUG:root:30\n", + "2018-06-07 19:46:15,116 :22 DEBUG 30\n", + "2018-06-07 19:46:15,116 :22 DEBUG 30\n", + "DEBUG:root:31\n", + "2018-06-07 19:46:15,118 :22 DEBUG 31\n", + "2018-06-07 19:46:15,118 :22 DEBUG 31\n", + "DEBUG:root:32\n", + "2018-06-07 19:46:15,121 :22 DEBUG 32\n", + "2018-06-07 19:46:15,121 :22 DEBUG 32\n", + "DEBUG:root:33\n", + "2018-06-07 19:46:15,124 :22 DEBUG 33\n", + "2018-06-07 19:46:15,124 :22 DEBUG 33\n", + "DEBUG:root:34\n", + "2018-06-07 19:46:15,126 :22 DEBUG 34\n", + "2018-06-07 19:46:15,126 :22 DEBUG 34\n", + "DEBUG:root:35\n", + "2018-06-07 19:46:15,129 :22 DEBUG 35\n", + "2018-06-07 19:46:15,129 :22 DEBUG 35\n", + "DEBUG:root:36\n", + "2018-06-07 19:46:15,132 :22 DEBUG 36\n", + "2018-06-07 19:46:15,132 :22 DEBUG 36\n", + "DEBUG:root:37\n", + "2018-06-07 19:46:15,134 :22 DEBUG 37\n", + "2018-06-07 19:46:15,134 :22 DEBUG 37\n", + "DEBUG:root:38\n", + "2018-06-07 19:46:15,137 :22 DEBUG 38\n", + "2018-06-07 19:46:15,137 :22 DEBUG 38\n", + "DEBUG:root:39\n", + "2018-06-07 19:46:15,139 :22 DEBUG 39\n", + "2018-06-07 19:46:15,139 :22 DEBUG 39\n", + "DEBUG:root:40\n", + "2018-06-07 19:46:15,164 :22 DEBUG 40\n", + "2018-06-07 19:46:15,164 :22 DEBUG 40\n", + "DEBUG:root:41\n", + "2018-06-07 19:46:15,208 :22 DEBUG 41\n", + "2018-06-07 19:46:15,208 :22 DEBUG 41\n", + "DEBUG:root:42\n", + "2018-06-07 19:46:15,224 :22 DEBUG 42\n", + "2018-06-07 19:46:15,224 :22 DEBUG 42\n", + "DEBUG:root:43\n", + "2018-06-07 19:46:15,231 :22 DEBUG 43\n", + "2018-06-07 19:46:15,231 :22 DEBUG 43\n", + "DEBUG:root:44\n", + "2018-06-07 19:46:15,259 :22 DEBUG 44\n", + "2018-06-07 19:46:15,259 :22 DEBUG 44\n", + "DEBUG:root:45\n", + "2018-06-07 19:46:15,278 :22 DEBUG 45\n", + "2018-06-07 19:46:15,278 :22 DEBUG 45\n", + "DEBUG:root:46\n", + "2018-06-07 19:46:15,306 :22 DEBUG 46\n", + "2018-06-07 19:46:15,306 :22 DEBUG 46\n", + "DEBUG:root:47\n", + "2018-06-07 19:46:15,312 :22 DEBUG 47\n", + "2018-06-07 19:46:15,312 :22 DEBUG 47\n", + "DEBUG:root:48\n", + "2018-06-07 19:46:15,340 :22 DEBUG 48\n", + "2018-06-07 19:46:15,340 :22 DEBUG 48\n", + "DEBUG:root:49\n", + "2018-06-07 19:46:15,345 :22 DEBUG 49\n", + "2018-06-07 19:46:15,345 :22 DEBUG 49\n", + "DEBUG:root:50\n", + "2018-06-07 19:46:15,391 :22 DEBUG 50\n", + "2018-06-07 19:46:15,391 :22 DEBUG 50\n", + "WARNING:root:The value of i is 50.\n", + "2018-06-07 19:46:15,398 :24 WARNING The value of i is 50.\n", + "2018-06-07 19:46:15,398 :24 WARNING The value of i is 50.\n", + "ERROR:root:Tried to divide by zero. Var i was 50. Recovered gracefully.\n", + "2018-06-07 19:46:15,406 :28 ERROR Tried to divide by zero. Var i was 50. Recovered gracefully.\n", + "2018-06-07 19:46:15,406 :28 ERROR Tried to divide by zero. Var i was 50. Recovered gracefully.\n" + ] + }, + { + "name": "stderr", + "output_type": "stream", + "text": [ + "DEBUG:root:51\n", + "2018-06-07 19:46:15,409 :22 DEBUG 51\n", + "2018-06-07 19:46:15,409 :22 DEBUG 51\n", + "DEBUG:root:52\n", + "2018-06-07 19:46:15,417 :22 DEBUG 52\n", + "2018-06-07 19:46:15,417 :22 DEBUG 52\n", + "DEBUG:root:53\n", + "2018-06-07 19:46:15,422 :22 DEBUG 53\n", + "2018-06-07 19:46:15,422 :22 DEBUG 53\n", + "DEBUG:root:54\n", + "2018-06-07 19:46:15,426 :22 DEBUG 54\n", + "2018-06-07 19:46:15,426 :22 DEBUG 54\n", + "DEBUG:root:55\n", + "2018-06-07 19:46:15,432 :22 DEBUG 55\n", + "2018-06-07 19:46:15,432 :22 DEBUG 55\n", + "DEBUG:root:56\n", + "2018-06-07 19:46:15,437 :22 DEBUG 56\n", + "2018-06-07 19:46:15,437 :22 DEBUG 56\n", + "DEBUG:root:57\n", + "2018-06-07 19:46:15,441 :22 DEBUG 57\n", + "2018-06-07 19:46:15,441 :22 DEBUG 57\n", + "DEBUG:root:58\n", + "2018-06-07 19:46:15,446 :22 DEBUG 58\n", + "2018-06-07 19:46:15,446 :22 DEBUG 58\n", + "DEBUG:root:59\n", + "2018-06-07 19:46:15,451 :22 DEBUG 59\n", + "2018-06-07 19:46:15,451 :22 DEBUG 59\n", + "DEBUG:root:60\n", + "2018-06-07 19:46:15,455 :22 DEBUG 60\n", + "2018-06-07 19:46:15,455 :22 DEBUG 60\n", + "DEBUG:root:61\n", + "2018-06-07 19:46:15,459 :22 DEBUG 61\n", + "2018-06-07 19:46:15,459 :22 DEBUG 61\n", + "DEBUG:root:62\n", + "2018-06-07 19:46:15,464 :22 DEBUG 62\n", + "2018-06-07 19:46:15,464 :22 DEBUG 62\n", + "DEBUG:root:63\n", + "2018-06-07 19:46:15,468 :22 DEBUG 63\n", + "2018-06-07 19:46:15,468 :22 DEBUG 63\n", + "DEBUG:root:64\n", + "2018-06-07 19:46:15,474 :22 DEBUG 64\n", + "2018-06-07 19:46:15,474 :22 DEBUG 64\n", + "DEBUG:root:65\n", + "2018-06-07 19:46:15,479 :22 DEBUG 65\n", + "2018-06-07 19:46:15,479 :22 DEBUG 65\n", + "DEBUG:root:66\n", + "2018-06-07 19:46:15,483 :22 DEBUG 66\n", + "2018-06-07 19:46:15,483 :22 DEBUG 66\n", + "DEBUG:root:67\n", + "2018-06-07 19:46:15,488 :22 DEBUG 67\n", + "2018-06-07 19:46:15,488 :22 DEBUG 67\n", + "DEBUG:root:68\n", + "2018-06-07 19:46:15,492 :22 DEBUG 68\n", + "2018-06-07 19:46:15,492 :22 DEBUG 68\n", + "DEBUG:root:69\n", + "2018-06-07 19:46:15,497 :22 DEBUG 69\n", + "2018-06-07 19:46:15,497 :22 DEBUG 69\n", + "DEBUG:root:70\n", + "2018-06-07 19:46:15,502 :22 DEBUG 70\n", + "2018-06-07 19:46:15,502 :22 DEBUG 70\n", + "DEBUG:root:71\n", + "2018-06-07 19:46:15,505 :22 DEBUG 71\n", + "2018-06-07 19:46:15,505 :22 DEBUG 71\n", + "DEBUG:root:72\n", + "2018-06-07 19:46:15,544 :22 DEBUG 72\n", + "2018-06-07 19:46:15,544 :22 DEBUG 72\n", + "DEBUG:root:73\n", + "2018-06-07 19:46:15,550 :22 DEBUG 73\n", + "2018-06-07 19:46:15,550 :22 DEBUG 73\n", + "DEBUG:root:74\n", + "2018-06-07 19:46:15,555 :22 DEBUG 74\n", + "2018-06-07 19:46:15,555 :22 DEBUG 74\n", + "DEBUG:root:75\n", + "2018-06-07 19:46:15,572 :22 DEBUG 75\n", + "2018-06-07 19:46:15,572 :22 DEBUG 75\n", + "DEBUG:root:76\n", + "2018-06-07 19:46:15,577 :22 DEBUG 76\n", + "2018-06-07 19:46:15,577 :22 DEBUG 76\n", + "DEBUG:root:77\n", + "2018-06-07 19:46:15,584 :22 DEBUG 77\n", + "2018-06-07 19:46:15,584 :22 DEBUG 77\n", + "DEBUG:root:78\n", + "2018-06-07 19:46:15,589 :22 DEBUG 78\n", + "2018-06-07 19:46:15,589 :22 DEBUG 78\n", + "DEBUG:root:79\n", + "2018-06-07 19:46:15,594 :22 DEBUG 79\n", + "2018-06-07 19:46:15,594 :22 DEBUG 79\n", + "DEBUG:root:80\n", + "2018-06-07 19:46:15,600 :22 DEBUG 80\n", + "2018-06-07 19:46:15,600 :22 DEBUG 80\n", + "DEBUG:root:81\n", + "2018-06-07 19:46:15,605 :22 DEBUG 81\n", + "2018-06-07 19:46:15,605 :22 DEBUG 81\n", + "DEBUG:root:82\n", + "2018-06-07 19:46:15,610 :22 DEBUG 82\n", + "2018-06-07 19:46:15,610 :22 DEBUG 82\n", + "DEBUG:root:83\n", + "2018-06-07 19:46:15,615 :22 DEBUG 83\n", + "2018-06-07 19:46:15,615 :22 DEBUG 83\n", + "DEBUG:root:84\n", + "2018-06-07 19:46:15,621 :22 DEBUG 84\n", + "2018-06-07 19:46:15,621 :22 DEBUG 84\n", + "DEBUG:root:85\n", + "2018-06-07 19:46:15,625 :22 DEBUG 85\n", + "2018-06-07 19:46:15,625 :22 DEBUG 85\n", + "DEBUG:root:86\n", + "2018-06-07 19:46:15,630 :22 DEBUG 86\n", + "2018-06-07 19:46:15,630 :22 DEBUG 86\n", + "DEBUG:root:87\n", + "2018-06-07 19:46:15,635 :22 DEBUG 87\n", + "2018-06-07 19:46:15,635 :22 DEBUG 87\n", + "DEBUG:root:88\n", + "2018-06-07 19:46:15,654 :22 DEBUG 88\n", + "2018-06-07 19:46:15,654 :22 DEBUG 88\n", + "DEBUG:root:89\n", + "2018-06-07 19:46:15,659 :22 DEBUG 89\n", + "2018-06-07 19:46:15,659 :22 DEBUG 89\n", + "DEBUG:root:90\n", + "2018-06-07 19:46:15,664 :22 DEBUG 90\n", + "2018-06-07 19:46:15,664 :22 DEBUG 90\n", + "DEBUG:root:91\n", + "2018-06-07 19:46:15,670 :22 DEBUG 91\n", + "2018-06-07 19:46:15,670 :22 DEBUG 91\n", + "DEBUG:root:92\n", + "2018-06-07 19:46:15,674 :22 DEBUG 92\n", + "2018-06-07 19:46:15,674 :22 DEBUG 92\n", + "DEBUG:root:93\n", + "2018-06-07 19:46:15,679 :22 DEBUG 93\n", + "2018-06-07 19:46:15,679 :22 DEBUG 93\n", + "DEBUG:root:94\n", + "2018-06-07 19:46:15,684 :22 DEBUG 94\n", + "2018-06-07 19:46:15,684 :22 DEBUG 94\n", + "DEBUG:root:95\n", + "2018-06-07 19:46:15,689 :22 DEBUG 95\n", + "2018-06-07 19:46:15,689 :22 DEBUG 95\n", + "DEBUG:root:96\n", + "2018-06-07 19:46:15,694 :22 DEBUG 96\n", + "2018-06-07 19:46:15,694 :22 DEBUG 96\n", + "DEBUG:root:97\n", + "2018-06-07 19:46:15,699 :22 DEBUG 97\n", + "2018-06-07 19:46:15,699 :22 DEBUG 97\n", + "DEBUG:root:98\n", + "2018-06-07 19:46:15,704 :22 DEBUG 98\n", + "2018-06-07 19:46:15,704 :22 DEBUG 98\n", + "DEBUG:root:99\n", + "2018-06-07 19:46:15,709 :22 DEBUG 99\n", + "2018-06-07 19:46:15,709 :22 DEBUG 99\n" + ] + } + ], + "source": [ + "import logging\n", + "\n", + "format = \"%(asctime)s %(filename)s:%(lineno)-3d %(levelname)s %(message)s\"\n", + "\n", + "formatter = logging.Formatter(format)\n", + "\n", + "file_handler = logging.FileHandler('mylog.log')\n", + "file_handler.setLevel(logging.WARNING) # Add this line\n", + "file_handler.setFormatter(formatter)\n", + "\n", + "console_handler = logging.StreamHandler() # Add this line\n", + "console_handler.setLevel(logging.DEBUG) # Add this line\n", + "console_handler.setFormatter(formatter) # Add this line\n", + "\n", + "logger = logging.getLogger()\n", + "logger.setLevel(logging.DEBUG) # Add this line\n", + "logger.addHandler(file_handler)\n", + "logger.addHandler(console_handler) # Add this line\n", + "\n", + "def my_fun(n):\n", + " for i in range(0, n):\n", + " logging.debug(i)\n", + " if i == 50:\n", + " logging.warning(\"The value of i is 50.\")\n", + " try:\n", + " i / (50 - i)\n", + " except ZeroDivisionError:\n", + " logging.error(\"Tried to divide by zero. Var i was {}. Recovered gracefully.\".format(i))\n", + "\n", + "if __name__ == \"__main__\":\n", + " my_fun(100)" + ] + }, + { + "cell_type": "code", + "execution_count": 24, + "metadata": {}, + "outputs": [ + { + "ename": "ZeroDivisionError", + "evalue": "division by zero", + "output_type": "error", + "traceback": [ + "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[0;31mZeroDivisionError\u001b[0m Traceback (most recent call last)", + "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[1;32m 5\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 6\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0m__name__\u001b[0m \u001b[0;34m==\u001b[0m \u001b[0;34m'__main__'\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 7\u001b[0;31m \u001b[0mmy_fun\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", + "\u001b[0;32m\u001b[0m in \u001b[0;36mmy_fun\u001b[0;34m()\u001b[0m\n\u001b[1;32m 2\u001b[0m \u001b[0;32mdef\u001b[0m \u001b[0mmy_fun\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 3\u001b[0m \u001b[0;32mfor\u001b[0m \u001b[0mi\u001b[0m \u001b[0;32min\u001b[0m \u001b[0mrange\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;36m1\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;36m500\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 4\u001b[0;31m \u001b[0;36m123\u001b[0m\u001b[0;34m/\u001b[0m \u001b[0;34m(\u001b[0m\u001b[0;36m50\u001b[0m \u001b[0;34m-\u001b[0m \u001b[0mi\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 5\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 6\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0m__name__\u001b[0m \u001b[0;34m==\u001b[0m \u001b[0;34m'__main__'\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", + "\u001b[0;31mZeroDivisionError\u001b[0m: division by zero" + ] + } + ], + "source": [ + "# simple.py\n", + "def my_fun():\n", + " for i in range(1, 500):\n", + " 123/ (50 - i)\n", + "\n", + "if __name__ == '__main__':\n", + " my_fun()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.6.5" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/Students/Wayne/Activities/Lesson_05/OlsonWayneDebugging.txt b/Students/Wayne/Activities/Lesson_05/OlsonWayneDebugging.txt new file mode 100644 index 0000000..c980580 --- /dev/null +++ b/Students/Wayne/Activities/Lesson_05/OlsonWayneDebugging.txt @@ -0,0 +1,348 @@ +Last login: Sat Jun 9 12:37:18 on ttys000 +Wayne-Olsons-MacBook-Pro:Lesson_05 weepler$ python -m Pdb recursive.py 5 +/anaconda3/bin/python: No module named Pdb +Wayne-Olsons-MacBook-Pro:Lesson_05 weepler$ python -m pdb recursive.py 5 +> /Users/weepler/SP2018-Python220-Accelerated-master/Students/Wayne/Activities/Lesson_05/recursive.py(1)() +-> import sys +(Pdb) ll + 1 -> import sys + 2 + 3 + 4 def my_fun(n): + 5 if n == 2: + 6 return True + 7 + 8 return my_fun(n/2) + 9 + 10 if __name__ == '__main__': + 11 n = int(sys.argv[1]) + 12 print(my_fun(n)) +(Pdb) n +> /Users/weepler/SP2018-Python220-Accelerated-master/Students/Wayne/Activities/Lesson_05/recursive.py(4)() +-> def my_fun(n): +(Pdb) n +> /Users/weepler/SP2018-Python220-Accelerated-master/Students/Wayne/Activities/Lesson_05/recursive.py(10)() +-> if __name__ == '__main__': +(Pdb) n +> /Users/weepler/SP2018-Python220-Accelerated-master/Students/Wayne/Activities/Lesson_05/recursive.py(11)() +-> n = int(sys.argv[1]) +(Pdb) pp n +*** NameError: name 'n' is not defined +(Pdb) n +> /Users/weepler/SP2018-Python220-Accelerated-master/Students/Wayne/Activities/Lesson_05/recursive.py(12)() +-> print(my_fun(n)) +(Pdb) n +Traceback (most recent call last): + File "/anaconda3/lib/python3.6/pdb.py", line 1667, in main + pdb._runscript(mainpyfile) + File "/anaconda3/lib/python3.6/pdb.py", line 1548, in _runscript + self.run(statement) + File "/anaconda3/lib/python3.6/bdb.py", line 434, in run + exec(cmd, globals, locals) + File "", line 1, in + File "/Users/weepler/SP2018-Python220-Accelerated-master/Students/Wayne/Activities/Lesson_05/recursive.py", line 12, in + print(my_fun(n)) + File "/Users/weepler/SP2018-Python220-Accelerated-master/Students/Wayne/Activities/Lesson_05/recursive.py", line 8, in my_fun + return my_fun(n/2) + File "/Users/weepler/SP2018-Python220-Accelerated-master/Students/Wayne/Activities/Lesson_05/recursive.py", line 8, in my_fun + return my_fun(n/2) + File "/Users/weepler/SP2018-Python220-Accelerated-master/Students/Wayne/Activities/Lesson_05/recursive.py", line 8, in my_fun + return my_fun(n/2) + [Previous line repeated 980 more times] + File "/Users/weepler/SP2018-Python220-Accelerated-master/Students/Wayne/Activities/Lesson_05/recursive.py", line 4, in my_fun + def my_fun(n): + File "/anaconda3/lib/python3.6/bdb.py", line 53, in trace_dispatch + return self.dispatch_call(frame, arg) + File "/anaconda3/lib/python3.6/bdb.py", line 79, in dispatch_call + if not (self.stop_here(frame) or self.break_anywhere(frame)): + File "/anaconda3/lib/python3.6/bdb.py", line 176, in break_anywhere + return self.canonic(frame.f_code.co_filename) in self.breaks + File "/anaconda3/lib/python3.6/bdb.py", line 32, in canonic + if filename == "<" + filename[1:-1] + ">": +RecursionError: maximum recursion depth exceeded in comparison +Uncaught exception. Entering post mortem debugging +Running 'cont' or 'step' will restart the program +> /anaconda3/lib/python3.6/bdb.py(32)canonic() +-> if filename == "<" + filename[1:-1] + ">": +(Pdb) n +Post mortem debugger finished. The recursive.py will be restarted +> /Users/weepler/SP2018-Python220-Accelerated-master/Students/Wayne/Activities/Lesson_05/recursive.py(1)() +-> import sys +(Pdb) n +> /Users/weepler/SP2018-Python220-Accelerated-master/Students/Wayne/Activities/Lesson_05/recursive.py(4)() +-> def my_fun(n): +(Pdb) s +> /Users/weepler/SP2018-Python220-Accelerated-master/Students/Wayne/Activities/Lesson_05/recursive.py(10)() +-> if __name__ == '__main__': +(Pdb) n +> /Users/weepler/SP2018-Python220-Accelerated-master/Students/Wayne/Activities/Lesson_05/recursive.py(11)() +-> n = int(sys.argv[1]) +(Pdb) n +> /Users/weepler/SP2018-Python220-Accelerated-master/Students/Wayne/Activities/Lesson_05/recursive.py(12)() +-> print(my_fun(n)) +(Pdb) n +Traceback (most recent call last): + File "/anaconda3/lib/python3.6/pdb.py", line 1667, in main + pdb._runscript(mainpyfile) + File "/anaconda3/lib/python3.6/pdb.py", line 1548, in _runscript + self.run(statement) + File "/anaconda3/lib/python3.6/bdb.py", line 434, in run + exec(cmd, globals, locals) + File "", line 1, in + File "/Users/weepler/SP2018-Python220-Accelerated-master/Students/Wayne/Activities/Lesson_05/recursive.py", line 12, in + print(my_fun(n)) + File "/Users/weepler/SP2018-Python220-Accelerated-master/Students/Wayne/Activities/Lesson_05/recursive.py", line 8, in my_fun + return my_fun(n/2) + File "/Users/weepler/SP2018-Python220-Accelerated-master/Students/Wayne/Activities/Lesson_05/recursive.py", line 8, in my_fun + return my_fun(n/2) + File "/Users/weepler/SP2018-Python220-Accelerated-master/Students/Wayne/Activities/Lesson_05/recursive.py", line 8, in my_fun + return my_fun(n/2) + [Previous line repeated 980 more times] + File "/Users/weepler/SP2018-Python220-Accelerated-master/Students/Wayne/Activities/Lesson_05/recursive.py", line 4, in my_fun + def my_fun(n): + File "/anaconda3/lib/python3.6/bdb.py", line 53, in trace_dispatch + return self.dispatch_call(frame, arg) + File "/anaconda3/lib/python3.6/bdb.py", line 79, in dispatch_call + if not (self.stop_here(frame) or self.break_anywhere(frame)): + File "/anaconda3/lib/python3.6/bdb.py", line 176, in break_anywhere + return self.canonic(frame.f_code.co_filename) in self.breaks + File "/anaconda3/lib/python3.6/bdb.py", line 32, in canonic + if filename == "<" + filename[1:-1] + ">": +RecursionError: maximum recursion depth exceeded in comparison +Uncaught exception. Entering post mortem debugging +Running 'cont' or 'step' will restart the program +> /anaconda3/lib/python3.6/bdb.py(32)canonic() +-> if filename == "<" + filename[1:-1] + ">": +(Pdb) n +Post mortem debugger finished. The recursive.py will be restarted +> /Users/weepler/SP2018-Python220-Accelerated-master/Students/Wayne/Activities/Lesson_05/recursive.py(1)() +-> import sys +(Pdb) n +> /Users/weepler/SP2018-Python220-Accelerated-master/Students/Wayne/Activities/Lesson_05/recursive.py(4)() +-> def my_fun(n): +(Pdb) n +> /Users/weepler/SP2018-Python220-Accelerated-master/Students/Wayne/Activities/Lesson_05/recursive.py(10)() +-> if __name__ == '__main__': +(Pdb) n +> /Users/weepler/SP2018-Python220-Accelerated-master/Students/Wayne/Activities/Lesson_05/recursive.py(11)() +-> n = int(sys.argv[1]) +(Pdb) n +> /Users/weepler/SP2018-Python220-Accelerated-master/Students/Wayne/Activities/Lesson_05/recursive.py(12)() +-> print(my_fun(n)) +(Pdb) s +--Call-- +> /Users/weepler/SP2018-Python220-Accelerated-master/Students/Wayne/Activities/Lesson_05/recursive.py(4)my_fun() +-> def my_fun(n): +(Pdb) s +> /Users/weepler/SP2018-Python220-Accelerated-master/Students/Wayne/Activities/Lesson_05/recursive.py(5)my_fun() +-> if n == 2: +(Pdb) pp n +5 +(Pdb) ll + 4 def my_fun(n): + 5 -> if n == 2: + 6 return True + 7 + 8 return my_fun(n/2) +(Pdb) n +> /Users/weepler/SP2018-Python220-Accelerated-master/Students/Wayne/Activities/Lesson_05/recursive.py(8)my_fun() +-> return my_fun(n/2) +(Pdb) pp n +5 +(Pdb) n +Traceback (most recent call last): + File "/anaconda3/lib/python3.6/pdb.py", line 1667, in main + pdb._runscript(mainpyfile) + File "/anaconda3/lib/python3.6/pdb.py", line 1548, in _runscript + self.run(statement) + File "/anaconda3/lib/python3.6/bdb.py", line 434, in run + exec(cmd, globals, locals) + File "", line 1, in + File "/Users/weepler/SP2018-Python220-Accelerated-master/Students/Wayne/Activities/Lesson_05/recursive.py", line 12, in + print(my_fun(n)) + File "/Users/weepler/SP2018-Python220-Accelerated-master/Students/Wayne/Activities/Lesson_05/recursive.py", line 8, in my_fun + return my_fun(n/2) + File "/Users/weepler/SP2018-Python220-Accelerated-master/Students/Wayne/Activities/Lesson_05/recursive.py", line 8, in my_fun + return my_fun(n/2) + File "/Users/weepler/SP2018-Python220-Accelerated-master/Students/Wayne/Activities/Lesson_05/recursive.py", line 8, in my_fun + return my_fun(n/2) + [Previous line repeated 980 more times] + File "/Users/weepler/SP2018-Python220-Accelerated-master/Students/Wayne/Activities/Lesson_05/recursive.py", line 4, in my_fun + def my_fun(n): + File "/anaconda3/lib/python3.6/bdb.py", line 53, in trace_dispatch + return self.dispatch_call(frame, arg) + File "/anaconda3/lib/python3.6/bdb.py", line 79, in dispatch_call + if not (self.stop_here(frame) or self.break_anywhere(frame)): + File "/anaconda3/lib/python3.6/bdb.py", line 176, in break_anywhere + return self.canonic(frame.f_code.co_filename) in self.breaks + File "/anaconda3/lib/python3.6/bdb.py", line 32, in canonic + if filename == "<" + filename[1:-1] + ">": +RecursionError: maximum recursion depth exceeded in comparison +Uncaught exception. Entering post mortem debugging +Running 'cont' or 'step' will restart the program +> /anaconda3/lib/python3.6/bdb.py(32)canonic() +-> if filename == "<" + filename[1:-1] + ">": +(Pdb) n +Post mortem debugger finished. The recursive.py will be restarted +> /Users/weepler/SP2018-Python220-Accelerated-master/Students/Wayne/Activities/Lesson_05/recursive.py(1)() +-> import sys +(Pdb) n +> /Users/weepler/SP2018-Python220-Accelerated-master/Students/Wayne/Activities/Lesson_05/recursive.py(4)() +-> def my_fun(n): +(Pdb) s +> /Users/weepler/SP2018-Python220-Accelerated-master/Students/Wayne/Activities/Lesson_05/recursive.py(10)() +-> if __name__ == '__main__': +(Pdb) n +> /Users/weepler/SP2018-Python220-Accelerated-master/Students/Wayne/Activities/Lesson_05/recursive.py(11)() +-> n = int(sys.argv[1]) +(Pdb) n +> /Users/weepler/SP2018-Python220-Accelerated-master/Students/Wayne/Activities/Lesson_05/recursive.py(12)() +-> print(my_fun(n)) +(Pdb) s +--Call-- +> /Users/weepler/SP2018-Python220-Accelerated-master/Students/Wayne/Activities/Lesson_05/recursive.py(4)my_fun() +-> def my_fun(n): +(Pdb) s +> /Users/weepler/SP2018-Python220-Accelerated-master/Students/Wayne/Activities/Lesson_05/recursive.py(5)my_fun() +-> if n == 2: +(Pdb) ll + 4 def my_fun(n): + 5 -> if n == 2: + 6 return True + 7 + 8 return my_fun(n/2) +(Pdb) n +> /Users/weepler/SP2018-Python220-Accelerated-master/Students/Wayne/Activities/Lesson_05/recursive.py(8)my_fun() +-> return my_fun(n/2) +(Pdb) pp n +5 +(Pdb) ? + +Documented commands (type help ): +======================================== +EOF c d h list q rv undisplay +a cl debug help ll quit s unt +alias clear disable ignore longlist r source until +args commands display interact n restart step up +b condition down j next return tbreak w +break cont enable jump p retval u whatis +bt continue exit l pp run unalias where + +Miscellaneous help topics: +========================== +exec pdb + +(Pdb) ll + 1 -> import sys + 2 + 3 + 4 def my_fun(n): + 5 if n == 2: + 6 return True + 7 + 8 return my_fun(n/2) + 9 + 10 if __name__ == '__main__': + 11 n = int(sys.argv[1]) + 12 print(my_fun(n)) +(Pdb) n +> /Users/weepler/SP2018-Python220-Accelerated-master/Students/Wayne/Activities/Lesson_05/recursive.py(4)() +-> def my_fun(n): +(Pdb) s +> /Users/weepler/SP2018-Python220-Accelerated-master/Students/Wayne/Activities/Lesson_05/recursive.py(10)() +-> if __name__ == '__main__': +(Pdb) s +> /Users/weepler/SP2018-Python220-Accelerated-master/Students/Wayne/Activities/Lesson_05/recursive.py(11)() +-> n = int(sys.argv[1]) +(Pdb) s +> /Users/weepler/SP2018-Python220-Accelerated-master/Students/Wayne/Activities/Lesson_05/recursive.py(12)() +-> print(my_fun(n)) +(Pdb) s +--Call-- +> /Users/weepler/SP2018-Python220-Accelerated-master/Students/Wayne/Activities/Lesson_05/recursive.py(4)my_fun() +-> def my_fun(n): +(Pdb) s +> /Users/weepler/SP2018-Python220-Accelerated-master/Students/Wayne/Activities/Lesson_05/recursive.py(5)my_fun() +-> if n == 2: +(Pdb) ll + 4 def my_fun(n): + 5 -> if n == 2: + 6 return True + 7 + 8 return my_fun(n/2) +(Pdb) n +> /Users/weepler/SP2018-Python220-Accelerated-master/Students/Wayne/Activities/Lesson_05/recursive.py(8)my_fun() +-> return my_fun(n/2) +(Pdb) s +--Call-- +> /Users/weepler/SP2018-Python220-Accelerated-master/Students/Wayne/Activities/Lesson_05/recursive.py(4)my_fun() +-> def my_fun(n): +(Pdb) n +> /Users/weepler/SP2018-Python220-Accelerated-master/Students/Wayne/Activities/Lesson_05/recursive.py(5)my_fun() +-> if n == 2: +(Pdb) pp n +2.5 +(Pdb) ll + 4 def my_fun(n): + 5 -> if n == 2: + 6 return True + 7 + 8 return my_fun(n/2) +(Pdb) n +> /Users/weepler/SP2018-Python220-Accelerated-master/Students/Wayne/Activities/Lesson_05/recursive.py(8)my_fun() +-> return my_fun(n/2) +(Pdb) s +--Call-- +> /Users/weepler/SP2018-Python220-Accelerated-master/Students/Wayne/Activities/Lesson_05/recursive.py(4)my_fun() +-> def my_fun(n): +(Pdb) pp n +1.25 +(Pdb) ll + 4 -> def my_fun(n): + 5 if n == 2: + 6 return True + 7 + 8 return my_fun(n/2) +(Pdb) n +> /Users/weepler/SP2018-Python220-Accelerated-master/Students/Wayne/Activities/Lesson_05/recursive.py(5)my_fun() +-> if n == 2: +(Pdb) n +> /Users/weepler/SP2018-Python220-Accelerated-master/Students/Wayne/Activities/Lesson_05/recursive.py(8)my_fun() +-> return my_fun(n/2) +(Pdb) s +--Call-- +> /Users/weepler/SP2018-Python220-Accelerated-master/Students/Wayne/Activities/Lesson_05/recursive.py(4)my_fun() +-> def my_fun(n): +(Pdb) c +Traceback (most recent call last): + File "/anaconda3/lib/python3.6/pdb.py", line 1667, in main + pdb._runscript(mainpyfile) + File "/anaconda3/lib/python3.6/pdb.py", line 1548, in _runscript + self.run(statement) + File "/anaconda3/lib/python3.6/bdb.py", line 434, in run + exec(cmd, globals, locals) + File "", line 1, in + File "/Users/weepler/SP2018-Python220-Accelerated-master/Students/Wayne/Activities/Lesson_05/recursive.py", line 12, in + print(my_fun(n)) + File "/Users/weepler/SP2018-Python220-Accelerated-master/Students/Wayne/Activities/Lesson_05/recursive.py", line 8, in my_fun + return my_fun(n/2) + File "/Users/weepler/SP2018-Python220-Accelerated-master/Students/Wayne/Activities/Lesson_05/recursive.py", line 8, in my_fun + return my_fun(n/2) + File "/Users/weepler/SP2018-Python220-Accelerated-master/Students/Wayne/Activities/Lesson_05/recursive.py", line 8, in my_fun + return my_fun(n/2) + File "/Users/weepler/SP2018-Python220-Accelerated-master/Students/Wayne/Activities/Lesson_05/recursive.py", line 4, in my_fun + def my_fun(n): + File "/Users/weepler/SP2018-Python220-Accelerated-master/Students/Wayne/Activities/Lesson_05/recursive.py", line 8, in my_fun + return my_fun(n/2) + File "/Users/weepler/SP2018-Python220-Accelerated-master/Students/Wayne/Activities/Lesson_05/recursive.py", line 8, in my_fun + return my_fun(n/2) + File "/Users/weepler/SP2018-Python220-Accelerated-master/Students/Wayne/Activities/Lesson_05/recursive.py", line 8, in my_fun + return my_fun(n/2) + [Previous line repeated 982 more times] + File "/Users/weepler/SP2018-Python220-Accelerated-master/Students/Wayne/Activities/Lesson_05/recursive.py", line 5, in my_fun + if n == 2: +RecursionError: maximum recursion depth exceeded in comparison +Uncaught exception. Entering post mortem debugging +Running 'cont' or 'step' will restart the program +> /Users/weepler/SP2018-Python220-Accelerated-master/Students/Wayne/Activities/Lesson_05/recursive.py(5)my_fun() +-> if n == 2: \ No newline at end of file diff --git a/Students/Wayne/Activities/Lesson_05/mylog.log b/Students/Wayne/Activities/Lesson_05/mylog.log new file mode 100644 index 0000000..cdcd5fd --- /dev/null +++ b/Students/Wayne/Activities/Lesson_05/mylog.log @@ -0,0 +1,210 @@ +2018-06-07 19:34:57,775 :22 DEBUG 0 +2018-06-07 19:34:57,780 :22 DEBUG 1 +2018-06-07 19:34:57,785 :22 DEBUG 2 +2018-06-07 19:34:57,788 :22 DEBUG 3 +2018-06-07 19:34:57,791 :22 DEBUG 4 +2018-06-07 19:34:57,794 :22 DEBUG 5 +2018-06-07 19:34:57,808 :22 DEBUG 6 +2018-06-07 19:34:57,811 :22 DEBUG 7 +2018-06-07 19:34:57,815 :22 DEBUG 8 +2018-06-07 19:34:57,821 :22 DEBUG 9 +2018-06-07 19:34:57,824 :22 DEBUG 10 +2018-06-07 19:34:57,827 :22 DEBUG 11 +2018-06-07 19:34:57,854 :22 DEBUG 12 +2018-06-07 19:34:57,858 :22 DEBUG 13 +2018-06-07 19:34:57,861 :22 DEBUG 14 +2018-06-07 19:34:57,864 :22 DEBUG 15 +2018-06-07 19:34:57,868 :22 DEBUG 16 +2018-06-07 19:34:57,871 :22 DEBUG 17 +2018-06-07 19:34:57,874 :22 DEBUG 18 +2018-06-07 19:34:57,877 :22 DEBUG 19 +2018-06-07 19:34:57,880 :22 DEBUG 20 +2018-06-07 19:34:57,883 :22 DEBUG 21 +2018-06-07 19:34:57,886 :22 DEBUG 22 +2018-06-07 19:34:57,889 :22 DEBUG 23 +2018-06-07 19:34:57,892 :22 DEBUG 24 +2018-06-07 19:34:57,895 :22 DEBUG 25 +2018-06-07 19:34:57,898 :22 DEBUG 26 +2018-06-07 19:34:57,901 :22 DEBUG 27 +2018-06-07 19:34:57,905 :22 DEBUG 28 +2018-06-07 19:34:57,907 :22 DEBUG 29 +2018-06-07 19:34:57,911 :22 DEBUG 30 +2018-06-07 19:34:57,915 :22 DEBUG 31 +2018-06-07 19:34:57,918 :22 DEBUG 32 +2018-06-07 19:34:57,921 :22 DEBUG 33 +2018-06-07 19:34:57,925 :22 DEBUG 34 +2018-06-07 19:34:57,927 :22 DEBUG 35 +2018-06-07 19:34:57,930 :22 DEBUG 36 +2018-06-07 19:34:57,934 :22 DEBUG 37 +2018-06-07 19:34:57,937 :22 DEBUG 38 +2018-06-07 19:34:57,939 :22 DEBUG 39 +2018-06-07 19:34:57,942 :22 DEBUG 40 +2018-06-07 19:34:57,945 :22 DEBUG 41 +2018-06-07 19:34:57,948 :22 DEBUG 42 +2018-06-07 19:34:57,959 :22 DEBUG 43 +2018-06-07 19:34:57,963 :22 DEBUG 44 +2018-06-07 19:34:57,978 :22 DEBUG 45 +2018-06-07 19:34:57,981 :22 DEBUG 46 +2018-06-07 19:34:57,985 :22 DEBUG 47 +2018-06-07 19:34:58,008 :22 DEBUG 48 +2018-06-07 19:34:58,022 :22 DEBUG 49 +2018-06-07 19:34:58,026 :22 DEBUG 50 +2018-06-07 19:34:58,030 :24 WARNING The value of i is 50. +2018-06-07 19:34:58,030 :24 WARNING The value of i is 50. +2018-06-07 19:34:58,034 :28 ERROR Tried to divide by zero. Var i was 50. Recovered gracefully. +2018-06-07 19:34:58,034 :28 ERROR Tried to divide by zero. Var i was 50. Recovered gracefully. +2018-06-07 19:34:58,037 :22 DEBUG 51 +2018-06-07 19:34:58,041 :22 DEBUG 52 +2018-06-07 19:34:58,044 :22 DEBUG 53 +2018-06-07 19:34:58,047 :22 DEBUG 54 +2018-06-07 19:34:58,051 :22 DEBUG 55 +2018-06-07 19:34:58,054 :22 DEBUG 56 +2018-06-07 19:34:58,057 :22 DEBUG 57 +2018-06-07 19:34:58,060 :22 DEBUG 58 +2018-06-07 19:34:58,063 :22 DEBUG 59 +2018-06-07 19:34:58,067 :22 DEBUG 60 +2018-06-07 19:34:58,070 :22 DEBUG 61 +2018-06-07 19:34:58,074 :22 DEBUG 62 +2018-06-07 19:34:58,077 :22 DEBUG 63 +2018-06-07 19:34:58,080 :22 DEBUG 64 +2018-06-07 19:34:58,093 :22 DEBUG 65 +2018-06-07 19:34:58,108 :22 DEBUG 66 +2018-06-07 19:34:58,111 :22 DEBUG 67 +2018-06-07 19:34:58,114 :22 DEBUG 68 +2018-06-07 19:34:58,118 :22 DEBUG 69 +2018-06-07 19:34:58,121 :22 DEBUG 70 +2018-06-07 19:34:58,124 :22 DEBUG 71 +2018-06-07 19:34:58,128 :22 DEBUG 72 +2018-06-07 19:34:58,131 :22 DEBUG 73 +2018-06-07 19:34:58,135 :22 DEBUG 74 +2018-06-07 19:34:58,141 :22 DEBUG 75 +2018-06-07 19:34:58,178 :22 DEBUG 76 +2018-06-07 19:34:58,181 :22 DEBUG 77 +2018-06-07 19:34:58,185 :22 DEBUG 78 +2018-06-07 19:34:58,191 :22 DEBUG 79 +2018-06-07 19:34:58,200 :22 DEBUG 80 +2018-06-07 19:34:58,203 :22 DEBUG 81 +2018-06-07 19:34:58,240 :22 DEBUG 82 +2018-06-07 19:34:58,248 :22 DEBUG 83 +2018-06-07 19:34:58,252 :22 DEBUG 84 +2018-06-07 19:34:58,257 :22 DEBUG 85 +2018-06-07 19:34:58,263 :22 DEBUG 86 +2018-06-07 19:34:58,266 :22 DEBUG 87 +2018-06-07 19:34:58,270 :22 DEBUG 88 +2018-06-07 19:34:58,282 :22 DEBUG 89 +2018-06-07 19:34:58,295 :22 DEBUG 90 +2018-06-07 19:34:58,299 :22 DEBUG 91 +2018-06-07 19:34:58,302 :22 DEBUG 92 +2018-06-07 19:34:58,305 :22 DEBUG 93 +2018-06-07 19:34:58,308 :22 DEBUG 94 +2018-06-07 19:34:58,311 :22 DEBUG 95 +2018-06-07 19:34:58,314 :22 DEBUG 96 +2018-06-07 19:34:58,318 :22 DEBUG 97 +2018-06-07 19:34:58,321 :22 DEBUG 98 +2018-06-07 19:34:58,324 :22 DEBUG 99 +2018-06-07 19:46:14,997 :22 DEBUG 0 +2018-06-07 19:46:15,005 :22 DEBUG 1 +2018-06-07 19:46:15,011 :22 DEBUG 2 +2018-06-07 19:46:15,017 :22 DEBUG 3 +2018-06-07 19:46:15,025 :22 DEBUG 4 +2018-06-07 19:46:15,028 :22 DEBUG 5 +2018-06-07 19:46:15,031 :22 DEBUG 6 +2018-06-07 19:46:15,033 :22 DEBUG 7 +2018-06-07 19:46:15,037 :22 DEBUG 8 +2018-06-07 19:46:15,039 :22 DEBUG 9 +2018-06-07 19:46:15,043 :22 DEBUG 10 +2018-06-07 19:46:15,045 :22 DEBUG 11 +2018-06-07 19:46:15,051 :22 DEBUG 12 +2018-06-07 19:46:15,053 :22 DEBUG 13 +2018-06-07 19:46:15,056 :22 DEBUG 14 +2018-06-07 19:46:15,058 :22 DEBUG 15 +2018-06-07 19:46:15,061 :22 DEBUG 16 +2018-06-07 19:46:15,063 :22 DEBUG 17 +2018-06-07 19:46:15,066 :22 DEBUG 18 +2018-06-07 19:46:15,068 :22 DEBUG 19 +2018-06-07 19:46:15,071 :22 DEBUG 20 +2018-06-07 19:46:15,073 :22 DEBUG 21 +2018-06-07 19:46:15,076 :22 DEBUG 22 +2018-06-07 19:46:15,078 :22 DEBUG 23 +2018-06-07 19:46:15,084 :22 DEBUG 24 +2018-06-07 19:46:15,096 :22 DEBUG 25 +2018-06-07 19:46:15,100 :22 DEBUG 26 +2018-06-07 19:46:15,102 :22 DEBUG 27 +2018-06-07 19:46:15,109 :22 DEBUG 28 +2018-06-07 19:46:15,112 :22 DEBUG 29 +2018-06-07 19:46:15,116 :22 DEBUG 30 +2018-06-07 19:46:15,118 :22 DEBUG 31 +2018-06-07 19:46:15,121 :22 DEBUG 32 +2018-06-07 19:46:15,124 :22 DEBUG 33 +2018-06-07 19:46:15,126 :22 DEBUG 34 +2018-06-07 19:46:15,129 :22 DEBUG 35 +2018-06-07 19:46:15,132 :22 DEBUG 36 +2018-06-07 19:46:15,134 :22 DEBUG 37 +2018-06-07 19:46:15,137 :22 DEBUG 38 +2018-06-07 19:46:15,139 :22 DEBUG 39 +2018-06-07 19:46:15,164 :22 DEBUG 40 +2018-06-07 19:46:15,208 :22 DEBUG 41 +2018-06-07 19:46:15,224 :22 DEBUG 42 +2018-06-07 19:46:15,231 :22 DEBUG 43 +2018-06-07 19:46:15,259 :22 DEBUG 44 +2018-06-07 19:46:15,278 :22 DEBUG 45 +2018-06-07 19:46:15,306 :22 DEBUG 46 +2018-06-07 19:46:15,312 :22 DEBUG 47 +2018-06-07 19:46:15,340 :22 DEBUG 48 +2018-06-07 19:46:15,345 :22 DEBUG 49 +2018-06-07 19:46:15,391 :22 DEBUG 50 +2018-06-07 19:46:15,398 :24 WARNING The value of i is 50. +2018-06-07 19:46:15,398 :24 WARNING The value of i is 50. +2018-06-07 19:46:15,398 :24 WARNING The value of i is 50. +2018-06-07 19:46:15,406 :28 ERROR Tried to divide by zero. Var i was 50. Recovered gracefully. +2018-06-07 19:46:15,406 :28 ERROR Tried to divide by zero. Var i was 50. Recovered gracefully. +2018-06-07 19:46:15,406 :28 ERROR Tried to divide by zero. Var i was 50. Recovered gracefully. +2018-06-07 19:46:15,409 :22 DEBUG 51 +2018-06-07 19:46:15,417 :22 DEBUG 52 +2018-06-07 19:46:15,422 :22 DEBUG 53 +2018-06-07 19:46:15,426 :22 DEBUG 54 +2018-06-07 19:46:15,432 :22 DEBUG 55 +2018-06-07 19:46:15,437 :22 DEBUG 56 +2018-06-07 19:46:15,441 :22 DEBUG 57 +2018-06-07 19:46:15,446 :22 DEBUG 58 +2018-06-07 19:46:15,451 :22 DEBUG 59 +2018-06-07 19:46:15,455 :22 DEBUG 60 +2018-06-07 19:46:15,459 :22 DEBUG 61 +2018-06-07 19:46:15,464 :22 DEBUG 62 +2018-06-07 19:46:15,468 :22 DEBUG 63 +2018-06-07 19:46:15,474 :22 DEBUG 64 +2018-06-07 19:46:15,479 :22 DEBUG 65 +2018-06-07 19:46:15,483 :22 DEBUG 66 +2018-06-07 19:46:15,488 :22 DEBUG 67 +2018-06-07 19:46:15,492 :22 DEBUG 68 +2018-06-07 19:46:15,497 :22 DEBUG 69 +2018-06-07 19:46:15,502 :22 DEBUG 70 +2018-06-07 19:46:15,505 :22 DEBUG 71 +2018-06-07 19:46:15,544 :22 DEBUG 72 +2018-06-07 19:46:15,550 :22 DEBUG 73 +2018-06-07 19:46:15,555 :22 DEBUG 74 +2018-06-07 19:46:15,572 :22 DEBUG 75 +2018-06-07 19:46:15,577 :22 DEBUG 76 +2018-06-07 19:46:15,584 :22 DEBUG 77 +2018-06-07 19:46:15,589 :22 DEBUG 78 +2018-06-07 19:46:15,594 :22 DEBUG 79 +2018-06-07 19:46:15,600 :22 DEBUG 80 +2018-06-07 19:46:15,605 :22 DEBUG 81 +2018-06-07 19:46:15,610 :22 DEBUG 82 +2018-06-07 19:46:15,615 :22 DEBUG 83 +2018-06-07 19:46:15,621 :22 DEBUG 84 +2018-06-07 19:46:15,625 :22 DEBUG 85 +2018-06-07 19:46:15,630 :22 DEBUG 86 +2018-06-07 19:46:15,635 :22 DEBUG 87 +2018-06-07 19:46:15,654 :22 DEBUG 88 +2018-06-07 19:46:15,659 :22 DEBUG 89 +2018-06-07 19:46:15,664 :22 DEBUG 90 +2018-06-07 19:46:15,670 :22 DEBUG 91 +2018-06-07 19:46:15,674 :22 DEBUG 92 +2018-06-07 19:46:15,679 :22 DEBUG 93 +2018-06-07 19:46:15,684 :22 DEBUG 94 +2018-06-07 19:46:15,689 :22 DEBUG 95 +2018-06-07 19:46:15,694 :22 DEBUG 96 +2018-06-07 19:46:15,699 :22 DEBUG 97 +2018-06-07 19:46:15,704 :22 DEBUG 98 +2018-06-07 19:46:15,709 :22 DEBUG 99 diff --git a/Students/Wayne/Activities/Lesson_05/recursive.py b/Students/Wayne/Activities/Lesson_05/recursive.py new file mode 100644 index 0000000..fc1144e --- /dev/null +++ b/Students/Wayne/Activities/Lesson_05/recursive.py @@ -0,0 +1,12 @@ +import sys + + +def my_fun(n): + if n == 2: + return True + + return my_fun(n/2) + +if __name__ == '__main__': + n = int(sys.argv[1]) + print(my_fun(n)) \ No newline at end of file diff --git a/Students/Wayne/Assignments/Assignment_01/.ipynb_checkpoints/Activity1-checkpoint.ipynb b/Students/Wayne/Assignments/Assignment_01/.ipynb_checkpoints/Activity1-checkpoint.ipynb new file mode 100644 index 0000000..9da4a00 --- /dev/null +++ b/Students/Wayne/Assignments/Assignment_01/.ipynb_checkpoints/Activity1-checkpoint.ipynb @@ -0,0 +1,249 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Iterators and Iterables" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [], + "source": [ + "class IterateMe_1:\n", + " \"\"\"\n", + " About as simple an iterator as you can get:\n", + "\n", + " returns the sequence of numbers from zero to 4\n", + " ( like range(4) )\n", + " \"\"\"\n", + "\n", + " def __init__(self, stop=10):\n", + " self.current = -1\n", + " self.stop = stop\n", + "\n", + " def __iter__(self):\n", + " return self\n", + "\n", + " def __next__(self):\n", + " self.current += 1\n", + " if self.current < self.stop:\n", + " return self.current\n", + " else:\n", + " raise StopIteration\n", + "\n", + "\n", + "class IterateMe_2:\n", + "\n", + " def __init__(self, start, stop, step):\n", + " self.current = start - step\n", + " self.stop = stop\n", + " self.start = start\n", + " self.step = step\n", + "\n", + " def __iter__(self):\n", + " return self\n", + "\n", + " def __next__(self):\n", + " self.current += self.step\n", + " if self.current < self.stop:\n", + " return self.current\n", + " else:\n", + " raise StopIteration\n", + "\n", + "\n", + "it = IterateMe_2(2, 20, 2)\n", + "for i in it:\n", + " if i > 10: break\n", + "\n", + "\n", + "def rng():\n", + " print(\"Range function\")\n", + " for i in range(2, 20, 2):\n", + " print(i)\n" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Testing the iterator\n", + "0\n", + "1\n", + "2\n", + "3\n", + "4\n", + "5\n", + "6\n", + "7\n", + "8\n", + "9\n", + "Testing the IT iterator\n", + "14\n", + "16\n", + "18\n", + "Range function\n", + "2\n", + "4\n", + "6\n", + "8\n", + "10\n", + "12\n", + "14\n", + "16\n", + "18\n" + ] + } + ], + "source": [ + "if __name__ == \"__main__\":\n", + "\n", + " print(\"Testing the iterator\")\n", + " for i in IterateMe_1():\n", + " print(i)\n", + "\n", + " print(\"Testing the IT iterator\")\n", + " for i in it:\n", + " print(i)\n", + "\n", + "rng()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "is range an iterator or an iteratable? Range is an interables, because you cannot call next on range. An iterator will change the state of the objects in the sequence." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# GENERATOR" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Sum of the integers:\n", + "\n", + "keep adding the next integer\n", + "\n", + "0 + 1 + 2 + 3 + 4 + 5 + …\n", + "\n", + "so the sequence is:\n", + "\n", + "0, 1, 3, 6, 10, 15 ….." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "def sum_fun():\n", + " for n in range(1,6,1):\n", + " yield n*(n+1)/2\n", + " \n", + "sum_it = (sum_fun())" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "list(sum_it)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Doubler:\n", + "\n", + "Each value is double the previous value:\n", + "\n", + "1, 2, 4, 8, 16, 32," + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "def doubler():\n", + " for n in range(1,7,1):\n", + " yield (n+1)*2\n", + " \n", + " \n", + "double_it = (doubler())" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "list(double_it)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Fibonacci sequence:\n", + " \n", + "The Fibonacci sequence as a generator:\n", + "\n", + "f(n) = f(n-1) + f(n-2)\n", + "\n", + "1, 1, 2, 3, 5, 8, 13, 21, 34…" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Generate the prime numbers (numbers only divisible by them self and 1):\n", + "\n", + "2, 3, 5, 7, 11, 13, 17, 19, 23…" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.6.5" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/Students/Wayne/Assignments/Assignment_01/.ipynb_checkpoints/Assignment1-checkpoint.ipynb b/Students/Wayne/Assignments/Assignment_01/.ipynb_checkpoints/Assignment1-checkpoint.ipynb new file mode 100644 index 0000000..d65905c --- /dev/null +++ b/Students/Wayne/Assignments/Assignment_01/.ipynb_checkpoints/Assignment1-checkpoint.ipynb @@ -0,0 +1,648 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Comprehensions " + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Bring up an interpreter and load the data." + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [], + "source": [ + "import pandas as pd \n", + "music = pd.read_csv('spotify.csv')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "music.head gives us the headers and the overall datashape from the csv file " + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [ + { + "data": { + "text/html": [ + "
\n", + "\n", + "\n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + "
idnameartistsdanceabilityenergykeyloudnessmodespeechinessacousticnessinstrumentalnesslivenessvalencetempoduration_mstime_signature
07qiZfU4dY1lWllzX7mPBIShape of YouEd Sheeran0.8250.6521-3.18300.08020.58100.0000000.09310.93195.9772337134
15CtI0qwDJkDQGwXD1H1cLDespacito - RemixLuis Fonsi0.6940.8152-4.32810.12000.22900.0000000.09240.81388.9312288274
24aWmUDTfIPGksMNLV2rQPDespacito (Featuring Daddy Yankee)Luis Fonsi0.6600.7862-4.75710.17000.20900.0000000.11200.846177.8332282004
36RUKPb4LETWmmr3iAEQktSomething Just Like ThisThe Chainsmokers0.6170.63511-6.76900.03170.04980.0000140.16400.446103.0192471604
43DXncPQOG4VBw3QHh3S81I'm the OneDJ Khaled0.6090.6687-4.28410.03670.05520.0000000.16700.81180.9242886004
\n", + "
" + ], + "text/plain": [ + " id name \\\n", + "0 7qiZfU4dY1lWllzX7mPBI Shape of You \n", + "1 5CtI0qwDJkDQGwXD1H1cL Despacito - Remix \n", + "2 4aWmUDTfIPGksMNLV2rQP Despacito (Featuring Daddy Yankee) \n", + "3 6RUKPb4LETWmmr3iAEQkt Something Just Like This \n", + "4 3DXncPQOG4VBw3QHh3S81 I'm the One \n", + "\n", + " artists danceability energy key loudness mode speechiness \\\n", + "0 Ed Sheeran 0.825 0.652 1 -3.183 0 0.0802 \n", + "1 Luis Fonsi 0.694 0.815 2 -4.328 1 0.1200 \n", + "2 Luis Fonsi 0.660 0.786 2 -4.757 1 0.1700 \n", + "3 The Chainsmokers 0.617 0.635 11 -6.769 0 0.0317 \n", + "4 DJ Khaled 0.609 0.668 7 -4.284 1 0.0367 \n", + "\n", + " acousticness instrumentalness liveness valence tempo duration_ms \\\n", + "0 0.5810 0.000000 0.0931 0.931 95.977 233713 \n", + "1 0.2290 0.000000 0.0924 0.813 88.931 228827 \n", + "2 0.2090 0.000000 0.1120 0.846 177.833 228200 \n", + "3 0.0498 0.000014 0.1640 0.446 103.019 247160 \n", + "4 0.0552 0.000000 0.1670 0.811 80.924 288600 \n", + "\n", + " time_signature \n", + "0 4 \n", + "1 4 \n", + "2 4 \n", + "3 4 \n", + "4 4 " + ] + }, + "execution_count": 2, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "music.head()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "music.describe gives us the count, mean, std, min, quartiles and max " + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [ + { + "data": { + "text/html": [ + "
\n", + "\n", + "\n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + "
danceabilityenergykeyloudnessmodespeechinessacousticnessinstrumentalnesslivenessvalencetempoduration_mstime_signature
count100.00000100.000000100.000000100.000000100.000000100.000000100.000000100.000000100.000000100.000000100.000000100.00000100.00
mean0.696820.6606905.570000-5.6526500.5800000.1039690.1663060.0047960.1506070.517049119.202460218387.280003.99
std0.125080.1392073.7315341.8020670.4960450.0951150.1667300.0260380.0790110.21643627.95292832851.077720.10
min0.258000.3460000.000000-11.4620000.0000000.0232000.0002590.0000000.0424000.08620075.016000165387.000003.00
25%0.635000.5565002.000000-6.5945000.0000000.0431250.0391000.0000000.0982750.37550099.911750198490.500004.00
50%0.714000.6675006.000000-5.4370001.0000000.0626500.1065000.0000000.1250000.502500112.468000214106.000004.00
75%0.770250.7875009.000000-4.3267501.0000000.1230000.2312500.0000130.1792500.679000137.166000230543.000004.00
max0.927000.93200011.000000-2.3960001.0000000.4310000.6950000.2100000.4400000.966000199.864000343150.000004.00
\n", + "
" + ], + "text/plain": [ + " danceability energy key loudness mode \\\n", + "count 100.00000 100.000000 100.000000 100.000000 100.000000 \n", + "mean 0.69682 0.660690 5.570000 -5.652650 0.580000 \n", + "std 0.12508 0.139207 3.731534 1.802067 0.496045 \n", + "min 0.25800 0.346000 0.000000 -11.462000 0.000000 \n", + "25% 0.63500 0.556500 2.000000 -6.594500 0.000000 \n", + "50% 0.71400 0.667500 6.000000 -5.437000 1.000000 \n", + "75% 0.77025 0.787500 9.000000 -4.326750 1.000000 \n", + "max 0.92700 0.932000 11.000000 -2.396000 1.000000 \n", + "\n", + " speechiness acousticness instrumentalness liveness valence \\\n", + "count 100.000000 100.000000 100.000000 100.000000 100.000000 \n", + "mean 0.103969 0.166306 0.004796 0.150607 0.517049 \n", + "std 0.095115 0.166730 0.026038 0.079011 0.216436 \n", + "min 0.023200 0.000259 0.000000 0.042400 0.086200 \n", + "25% 0.043125 0.039100 0.000000 0.098275 0.375500 \n", + "50% 0.062650 0.106500 0.000000 0.125000 0.502500 \n", + "75% 0.123000 0.231250 0.000013 0.179250 0.679000 \n", + "max 0.431000 0.695000 0.210000 0.440000 0.966000 \n", + "\n", + " tempo duration_ms time_signature \n", + "count 100.000000 100.00000 100.00 \n", + "mean 119.202460 218387.28000 3.99 \n", + "std 27.952928 32851.07772 0.10 \n", + "min 75.016000 165387.00000 3.00 \n", + "25% 99.911750 198490.50000 4.00 \n", + "50% 112.468000 214106.00000 4.00 \n", + "75% 137.166000 230543.00000 4.00 \n", + "max 199.864000 343150.00000 4.00 " + ] + }, + "execution_count": 3, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "music.describe()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The following function gives us tracks with danceability greater than .8 " + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": { + "scrolled": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "[0.825,\n", + " 0.904,\n", + " 0.853,\n", + " 0.833,\n", + " 0.857,\n", + " 0.809,\n", + " 0.8690000000000001,\n", + " 0.893,\n", + " 0.852,\n", + " 0.927,\n", + " 0.927,\n", + " 0.818,\n", + " 0.8759999999999999,\n", + " 0.841,\n", + " 0.8320000000000001,\n", + " 0.855,\n", + " 0.884]" + ] + }, + "execution_count": 4, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "[d for d in music.danceability if d > 0.8]" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Returns tracks with a loudness score under -5.0" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "[-6.769,\n", + " -6.8420000000000005,\n", + " -6.596,\n", + " -5.043,\n", + " -8.374,\n", + " -6.3660000000000005,\n", + " -6.428,\n", + " -5.024,\n", + " -8.795,\n", + " -7.398,\n", + " -6.327000000000001,\n", + " -6.864,\n", + " -7.7860000000000005,\n", + " -5.599,\n", + " -5.94,\n", + " -7.028,\n", + " -6.257999999999999,\n", + " -7.733,\n", + " -11.377,\n", + " -6.593999999999999,\n", + " -5.595,\n", + " -5.827000000000001,\n", + " -6.312,\n", + " -6.745,\n", + " -11.462,\n", + " -5.313,\n", + " -9.433,\n", + " -5.309,\n", + " -5.002,\n", + " -5.886,\n", + " -6.922999999999999,\n", + " -10.401,\n", + " -6.763,\n", + " -5.535,\n", + " -6.053999999999999,\n", + " -5.3629999999999995,\n", + " -5.445,\n", + " -6.166,\n", + " -9.601,\n", + " -6.678,\n", + " -5.6979999999999995,\n", + " -6.351,\n", + " -7.607,\n", + " -6.287999999999999,\n", + " -8.279,\n", + " -6.377999999999999,\n", + " -5.126,\n", + " -5.882999999999999,\n", + " -5.428999999999999,\n", + " -7.621,\n", + " -6.237,\n", + " -5.092,\n", + " -6.406000000000001,\n", + " -5.098,\n", + " -7.843999999999999,\n", + " -5.516,\n", + " -5.35,\n", + " -8.228,\n", + " -5.651,\n", + " -7.226,\n", + " -6.593]" + ] + }, + "execution_count": 5, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "[l for l in music.loudness if l < -5.0]" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": {}, + "outputs": [], + "source": [ + "def shake_it_off():\n", + " \n", + " return(sorted([[a, n, d, l] for a, n, d, l in zip(music.artists,\n", + " music.name,\n", + " music.danceability,\n", + " music.loudness)\n", + " if d >.8 and l < -5.0],key=lambda x: x[2],reverse =True))\n", + "\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[['Migos', 'Bad and Boujee (feat. Lil Uzi Vert)', 0.927, -5.313], ['Drake', 'Fake Love', 0.927, -9.433], ['Kendrick Lamar', 'HUMBLE.', 0.904, -6.8420000000000005], ['21 Savage', 'Bank Account', 0.884, -8.228], ['Jax Jones', \"You Don't Know Me - Radio Edit\", 0.8759999999999999, -6.053999999999999], ['Liam Payne', 'Strip That Down', 0.8690000000000001, -5.595], ['Future', 'Mask Off', 0.833, -8.795], ['Zion & Lennox', 'Otra Vez (feat. J Balvin)', 0.8320000000000001, -5.428999999999999], ['Drake', 'Passionfruit', 0.809, -11.377]]\n" + ] + } + ], + "source": [ + "print(shake_it_off())" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "-------------------------------------------------------------------------------------------\n", + "\n", + "\n", + "The following songs below meet both the danceability and loudness constraints listed in the assignment. \n", + "\n", + "1. ['Migos', 'Bad and Boujee (feat. Lil Uzi Vert)', 0.927, -5.313], \n", + "2. ['Drake', 'Fake Love', 0.927, -9.433], \n", + "3. ['Kendrick Lamar', 'HUMBLE.', 0.904, -6.8420000000000005], \n", + "4. ['21 Savage', 'Bank Account', 0.884, -8.228], \n", + "5. ['Jax Jones', \"You Don't Know Me - Radio Edit\", 0.8759999999999999, -6.053999999999999], 6. ['Liam Payne', 'Strip That Down', 0.8690000000000001, -5.595], \n", + "7. ['Future', 'Mask Off', 0.833, -8.795], \n", + "8. ['Zion & Lennox', 'Otra Vez (feat. J Balvin)', 8.0.8320000000000001, -5.428999999999999], \n", + "9. ['Drake', 'Passionfruit', 0.809, -11.377]]\n", + "\n", + "-------------------------------------------------------------------------------------------" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.6.5" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/Students/Wayne/Assignments/Assignment_01/.ipynb_checkpoints/Random Exampes-checkpoint.ipynb b/Students/Wayne/Assignments/Assignment_01/.ipynb_checkpoints/Random Exampes-checkpoint.ipynb new file mode 100644 index 0000000..2fd6442 --- /dev/null +++ b/Students/Wayne/Assignments/Assignment_01/.ipynb_checkpoints/Random Exampes-checkpoint.ipynb @@ -0,0 +1,6 @@ +{ + "cells": [], + "metadata": {}, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/Students/Wayne/Assignments/Assignment_01/Assignment1.ipynb b/Students/Wayne/Assignments/Assignment_01/Assignment1.ipynb new file mode 100644 index 0000000..d65905c --- /dev/null +++ b/Students/Wayne/Assignments/Assignment_01/Assignment1.ipynb @@ -0,0 +1,648 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Comprehensions " + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Bring up an interpreter and load the data." + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [], + "source": [ + "import pandas as pd \n", + "music = pd.read_csv('spotify.csv')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "music.head gives us the headers and the overall datashape from the csv file " + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [ + { + "data": { + "text/html": [ + "
\n", + "\n", + "\n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + "
idnameartistsdanceabilityenergykeyloudnessmodespeechinessacousticnessinstrumentalnesslivenessvalencetempoduration_mstime_signature
07qiZfU4dY1lWllzX7mPBIShape of YouEd Sheeran0.8250.6521-3.18300.08020.58100.0000000.09310.93195.9772337134
15CtI0qwDJkDQGwXD1H1cLDespacito - RemixLuis Fonsi0.6940.8152-4.32810.12000.22900.0000000.09240.81388.9312288274
24aWmUDTfIPGksMNLV2rQPDespacito (Featuring Daddy Yankee)Luis Fonsi0.6600.7862-4.75710.17000.20900.0000000.11200.846177.8332282004
36RUKPb4LETWmmr3iAEQktSomething Just Like ThisThe Chainsmokers0.6170.63511-6.76900.03170.04980.0000140.16400.446103.0192471604
43DXncPQOG4VBw3QHh3S81I'm the OneDJ Khaled0.6090.6687-4.28410.03670.05520.0000000.16700.81180.9242886004
\n", + "
" + ], + "text/plain": [ + " id name \\\n", + "0 7qiZfU4dY1lWllzX7mPBI Shape of You \n", + "1 5CtI0qwDJkDQGwXD1H1cL Despacito - Remix \n", + "2 4aWmUDTfIPGksMNLV2rQP Despacito (Featuring Daddy Yankee) \n", + "3 6RUKPb4LETWmmr3iAEQkt Something Just Like This \n", + "4 3DXncPQOG4VBw3QHh3S81 I'm the One \n", + "\n", + " artists danceability energy key loudness mode speechiness \\\n", + "0 Ed Sheeran 0.825 0.652 1 -3.183 0 0.0802 \n", + "1 Luis Fonsi 0.694 0.815 2 -4.328 1 0.1200 \n", + "2 Luis Fonsi 0.660 0.786 2 -4.757 1 0.1700 \n", + "3 The Chainsmokers 0.617 0.635 11 -6.769 0 0.0317 \n", + "4 DJ Khaled 0.609 0.668 7 -4.284 1 0.0367 \n", + "\n", + " acousticness instrumentalness liveness valence tempo duration_ms \\\n", + "0 0.5810 0.000000 0.0931 0.931 95.977 233713 \n", + "1 0.2290 0.000000 0.0924 0.813 88.931 228827 \n", + "2 0.2090 0.000000 0.1120 0.846 177.833 228200 \n", + "3 0.0498 0.000014 0.1640 0.446 103.019 247160 \n", + "4 0.0552 0.000000 0.1670 0.811 80.924 288600 \n", + "\n", + " time_signature \n", + "0 4 \n", + "1 4 \n", + "2 4 \n", + "3 4 \n", + "4 4 " + ] + }, + "execution_count": 2, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "music.head()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "music.describe gives us the count, mean, std, min, quartiles and max " + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [ + { + "data": { + "text/html": [ + "
\n", + "\n", + "\n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + "
danceabilityenergykeyloudnessmodespeechinessacousticnessinstrumentalnesslivenessvalencetempoduration_mstime_signature
count100.00000100.000000100.000000100.000000100.000000100.000000100.000000100.000000100.000000100.000000100.000000100.00000100.00
mean0.696820.6606905.570000-5.6526500.5800000.1039690.1663060.0047960.1506070.517049119.202460218387.280003.99
std0.125080.1392073.7315341.8020670.4960450.0951150.1667300.0260380.0790110.21643627.95292832851.077720.10
min0.258000.3460000.000000-11.4620000.0000000.0232000.0002590.0000000.0424000.08620075.016000165387.000003.00
25%0.635000.5565002.000000-6.5945000.0000000.0431250.0391000.0000000.0982750.37550099.911750198490.500004.00
50%0.714000.6675006.000000-5.4370001.0000000.0626500.1065000.0000000.1250000.502500112.468000214106.000004.00
75%0.770250.7875009.000000-4.3267501.0000000.1230000.2312500.0000130.1792500.679000137.166000230543.000004.00
max0.927000.93200011.000000-2.3960001.0000000.4310000.6950000.2100000.4400000.966000199.864000343150.000004.00
\n", + "
" + ], + "text/plain": [ + " danceability energy key loudness mode \\\n", + "count 100.00000 100.000000 100.000000 100.000000 100.000000 \n", + "mean 0.69682 0.660690 5.570000 -5.652650 0.580000 \n", + "std 0.12508 0.139207 3.731534 1.802067 0.496045 \n", + "min 0.25800 0.346000 0.000000 -11.462000 0.000000 \n", + "25% 0.63500 0.556500 2.000000 -6.594500 0.000000 \n", + "50% 0.71400 0.667500 6.000000 -5.437000 1.000000 \n", + "75% 0.77025 0.787500 9.000000 -4.326750 1.000000 \n", + "max 0.92700 0.932000 11.000000 -2.396000 1.000000 \n", + "\n", + " speechiness acousticness instrumentalness liveness valence \\\n", + "count 100.000000 100.000000 100.000000 100.000000 100.000000 \n", + "mean 0.103969 0.166306 0.004796 0.150607 0.517049 \n", + "std 0.095115 0.166730 0.026038 0.079011 0.216436 \n", + "min 0.023200 0.000259 0.000000 0.042400 0.086200 \n", + "25% 0.043125 0.039100 0.000000 0.098275 0.375500 \n", + "50% 0.062650 0.106500 0.000000 0.125000 0.502500 \n", + "75% 0.123000 0.231250 0.000013 0.179250 0.679000 \n", + "max 0.431000 0.695000 0.210000 0.440000 0.966000 \n", + "\n", + " tempo duration_ms time_signature \n", + "count 100.000000 100.00000 100.00 \n", + "mean 119.202460 218387.28000 3.99 \n", + "std 27.952928 32851.07772 0.10 \n", + "min 75.016000 165387.00000 3.00 \n", + "25% 99.911750 198490.50000 4.00 \n", + "50% 112.468000 214106.00000 4.00 \n", + "75% 137.166000 230543.00000 4.00 \n", + "max 199.864000 343150.00000 4.00 " + ] + }, + "execution_count": 3, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "music.describe()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The following function gives us tracks with danceability greater than .8 " + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": { + "scrolled": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "[0.825,\n", + " 0.904,\n", + " 0.853,\n", + " 0.833,\n", + " 0.857,\n", + " 0.809,\n", + " 0.8690000000000001,\n", + " 0.893,\n", + " 0.852,\n", + " 0.927,\n", + " 0.927,\n", + " 0.818,\n", + " 0.8759999999999999,\n", + " 0.841,\n", + " 0.8320000000000001,\n", + " 0.855,\n", + " 0.884]" + ] + }, + "execution_count": 4, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "[d for d in music.danceability if d > 0.8]" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Returns tracks with a loudness score under -5.0" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "[-6.769,\n", + " -6.8420000000000005,\n", + " -6.596,\n", + " -5.043,\n", + " -8.374,\n", + " -6.3660000000000005,\n", + " -6.428,\n", + " -5.024,\n", + " -8.795,\n", + " -7.398,\n", + " -6.327000000000001,\n", + " -6.864,\n", + " -7.7860000000000005,\n", + " -5.599,\n", + " -5.94,\n", + " -7.028,\n", + " -6.257999999999999,\n", + " -7.733,\n", + " -11.377,\n", + " -6.593999999999999,\n", + " -5.595,\n", + " -5.827000000000001,\n", + " -6.312,\n", + " -6.745,\n", + " -11.462,\n", + " -5.313,\n", + " -9.433,\n", + " -5.309,\n", + " -5.002,\n", + " -5.886,\n", + " -6.922999999999999,\n", + " -10.401,\n", + " -6.763,\n", + " -5.535,\n", + " -6.053999999999999,\n", + " -5.3629999999999995,\n", + " -5.445,\n", + " -6.166,\n", + " -9.601,\n", + " -6.678,\n", + " -5.6979999999999995,\n", + " -6.351,\n", + " -7.607,\n", + " -6.287999999999999,\n", + " -8.279,\n", + " -6.377999999999999,\n", + " -5.126,\n", + " -5.882999999999999,\n", + " -5.428999999999999,\n", + " -7.621,\n", + " -6.237,\n", + " -5.092,\n", + " -6.406000000000001,\n", + " -5.098,\n", + " -7.843999999999999,\n", + " -5.516,\n", + " -5.35,\n", + " -8.228,\n", + " -5.651,\n", + " -7.226,\n", + " -6.593]" + ] + }, + "execution_count": 5, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "[l for l in music.loudness if l < -5.0]" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": {}, + "outputs": [], + "source": [ + "def shake_it_off():\n", + " \n", + " return(sorted([[a, n, d, l] for a, n, d, l in zip(music.artists,\n", + " music.name,\n", + " music.danceability,\n", + " music.loudness)\n", + " if d >.8 and l < -5.0],key=lambda x: x[2],reverse =True))\n", + "\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[['Migos', 'Bad and Boujee (feat. Lil Uzi Vert)', 0.927, -5.313], ['Drake', 'Fake Love', 0.927, -9.433], ['Kendrick Lamar', 'HUMBLE.', 0.904, -6.8420000000000005], ['21 Savage', 'Bank Account', 0.884, -8.228], ['Jax Jones', \"You Don't Know Me - Radio Edit\", 0.8759999999999999, -6.053999999999999], ['Liam Payne', 'Strip That Down', 0.8690000000000001, -5.595], ['Future', 'Mask Off', 0.833, -8.795], ['Zion & Lennox', 'Otra Vez (feat. J Balvin)', 0.8320000000000001, -5.428999999999999], ['Drake', 'Passionfruit', 0.809, -11.377]]\n" + ] + } + ], + "source": [ + "print(shake_it_off())" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "-------------------------------------------------------------------------------------------\n", + "\n", + "\n", + "The following songs below meet both the danceability and loudness constraints listed in the assignment. \n", + "\n", + "1. ['Migos', 'Bad and Boujee (feat. Lil Uzi Vert)', 0.927, -5.313], \n", + "2. ['Drake', 'Fake Love', 0.927, -9.433], \n", + "3. ['Kendrick Lamar', 'HUMBLE.', 0.904, -6.8420000000000005], \n", + "4. ['21 Savage', 'Bank Account', 0.884, -8.228], \n", + "5. ['Jax Jones', \"You Don't Know Me - Radio Edit\", 0.8759999999999999, -6.053999999999999], 6. ['Liam Payne', 'Strip That Down', 0.8690000000000001, -5.595], \n", + "7. ['Future', 'Mask Off', 0.833, -8.795], \n", + "8. ['Zion & Lennox', 'Otra Vez (feat. J Balvin)', 8.0.8320000000000001, -5.428999999999999], \n", + "9. ['Drake', 'Passionfruit', 0.809, -11.377]]\n", + "\n", + "-------------------------------------------------------------------------------------------" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.6.5" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/Students/Wayne/Assignments/Assignment_01/Assignment1.py b/Students/Wayne/Assignments/Assignment_01/Assignment1.py new file mode 100644 index 0000000..076820d --- /dev/null +++ b/Students/Wayne/Assignments/Assignment_01/Assignment1.py @@ -0,0 +1,81 @@ + +# coding: utf-8 + +# # Comprehensions + +# Bring up an interpreter and load the data. + +# In[1]: + + +import pandas as pd +music = pd.read_csv('spotify.csv') + + +# music.head gives us the headers and the overall datashape from the csv file + +# In[2]: + + +music.head() + + +# music.describe gives us the count, mean, std, min, quartiles and max + +# In[3]: + + +music.describe() + + +# The following function gives us tracks with danceability greater than .8 + +# In[4]: + + +[d for d in music.danceability if d > 0.8] + + +# Returns tracks with a loudness score under -5.0 + +# In[5]: + + +[l for l in music.loudness if l < -5.0] + + +# In[6]: + + +def shake_it_off(): + + return(sorted([[a, n, d, l] for a, n, d, l in zip(music.artists, + music.name, + music.danceability, + music.loudness) + if d >.8 and l < -5.0],key=lambda x: x[2],reverse =True)) + + + +# In[7]: + + +print(shake_it_off()) + + +# ------------------------------------------------------------------------------------------- +# +# +# The following songs below meet both the danceability and loudness constraints listed in the assignment. +# +# 1. ['Migos', 'Bad and Boujee (feat. Lil Uzi Vert)', 0.927, -5.313], +# 2. ['Drake', 'Fake Love', 0.927, -9.433], +# 3. ['Kendrick Lamar', 'HUMBLE.', 0.904, -6.8420000000000005], +# 4. ['21 Savage', 'Bank Account', 0.884, -8.228], +# 5. ['Jax Jones', "You Don't Know Me - Radio Edit", 0.8759999999999999, -6.053999999999999], +# 6. ['Liam Payne', 'Strip That Down', 0.8690000000000001, -5.595], +# 7. ['Future', 'Mask Off', 0.833, -8.795], +# 8. ['Zion & Lennox', 'Otra Vez (feat. J Balvin)', 8.0.8320000000000001, -5.428999999999999], +# 9. ['Drake', 'Passionfruit', 0.809, -11.377]] +# +# ------------------------------------------------------------------------------------------- diff --git a/Students/Wayne/Assignments/Assignment_01/spotify.csv b/Students/Wayne/Assignments/Assignment_01/spotify.csv new file mode 100644 index 0000000..83b453d --- /dev/null +++ b/Students/Wayne/Assignments/Assignment_01/spotify.csv @@ -0,0 +1 @@ +id,name,artists,danceability,energy,key,loudness,mode,speechiness,acousticness,instrumentalness,liveness,valence,tempo,duration_ms,time_signature 7qiZfU4dY1lWllzX7mPBI,Shape of You,Ed Sheeran,0.825,0.652,1,-3.183,0,0.0802,0.581,0,0.0931,0.931,95.977,233713,4 5CtI0qwDJkDQGwXD1H1cL,Despacito - Remix,Luis Fonsi,0.694,0.815,2,-4.328,1,0.12,0.229,0,0.0924,0.813,88.931,228827,4 4aWmUDTfIPGksMNLV2rQP,Despacito (Featuring Daddy Yankee),Luis Fonsi,0.66,0.786,2,-4.757,1,0.17,0.209,0,0.112,0.846,177.833,228200,4 6RUKPb4LETWmmr3iAEQkt,Something Just Like This,The Chainsmokers,0.617,0.635,11,-6.769,0,0.0317,0.0498,1.44E-05,0.164,0.446,103.019,247160,4 3DXncPQOG4VBw3QHh3S81,I'm the One,DJ Khaled,0.609,0.668,7,-4.284,1,0.0367,0.0552,0,0.167,0.811,80.924,288600,4 7KXjTSCq5nL1LoYtL7XAw,HUMBLE.,Kendrick Lamar,0.904,0.611,1,-6.842,0,0.0888,0.000259,2.03E-05,0.0976,0.4,150.02,177000,4 3eR23VReFzcdmS7TYCrhC,It Ain't Me (with Selena Gomez),Kygo,0.64,0.533,0,-6.596,1,0.0706,0.119,0,0.0864,0.515,99.968,220781,4 3B54sVLJ402zGa6Xm4YGN,Unforgettable,French Montana,0.726,0.769,6,-5.043,1,0.123,0.0293,0.0101,0.104,0.733,97.985,233902,4 0KKkJNfGyhkQ5aFogxQAP,That's What I Like,Bruno Mars,0.853,0.56,1,-4.961,1,0.0406,0.013,0,0.0944,0.86,134.066,206693,4 3NdDpSvN911VPGivFlV5d,"I Don‰Ûªt Wanna Live Forever (Fifty Shades Darker) - From ""Fifty Shades Darker (Original Motion Picture Soundtrack)""",ZAYN,0.735,0.451,0,-8.374,1,0.0585,0.0631,1.30E-05,0.325,0.0862,117.973,245200,4 7GX5flRQZVHRAGd6B4TmD,XO TOUR Llif3,Lil Uzi Vert,0.732,0.75,11,-6.366,0,0.231,0.00264,0,0.109,0.401,155.096,182707,4 72jbDTw1piOOj770jWNea,Paris,The Chainsmokers,0.653,0.658,2,-6.428,1,0.0304,0.0215,1.66E-06,0.0939,0.219,99.99,221507,4 0dA2Mk56wEzDgegdC6R17,Stay (with Alessia Cara),Zedd,0.679,0.634,5,-5.024,0,0.0654,0.232,0,0.115,0.498,102.013,210091,4 4iLqG9SeJSnt0cSPICSjx,Attention,Charlie Puth,0.774,0.626,3,-4.432,0,0.0432,0.0969,3.12E-05,0.0848,0.777,100.041,211475,4 0VgkVdmE4gld66l8iyGjg,Mask Off,Future,0.833,0.434,2,-8.795,1,0.431,0.0102,0.0219,0.165,0.281,150.062,204600,4 3a1lNhkSLSkpJE4MSHpDu,Congratulations,Post Malone,0.627,0.812,6,-4.215,1,0.0358,0.198,0,0.212,0.504,123.071,220293,4 6kex4EBAj0WHXDKZMEJaa,Swalla (feat. Nicki Minaj & Ty Dolla $ign),Jason Derulo,0.696,0.817,1,-3.862,1,0.109,0.075,0,0.187,0.782,98.064,216409,4 6PCUP3dWmTjcTtXY02oFd,Castle on the Hill,Ed Sheeran,0.461,0.834,2,-4.868,1,0.0989,0.0232,1.14E-05,0.14,0.471,135.007,261154,4 5knuzwU65gJK7IF5yJsua,Rockabye (feat. Sean Paul & Anne-Marie),Clean Bandit,0.72,0.763,9,-4.068,0,0.0523,0.406,0,0.18,0.742,101.965,251088,4 0CcQNd8CINkwQfe1RDtGV,Believer,Imagine Dragons,0.779,0.787,10,-4.305,0,0.108,0.0524,0,0.14,0.708,124.982,204347,4 2rb5MvYT7ZIxbKW5hfcHx,Mi Gente,J Balvin,0.543,0.677,11,-4.915,0,0.0993,0.0148,6.21E-06,0.13,0.294,103.809,189440,4 0tKcYR2II1VCQWT79i5Nr,Thunder,Imagine Dragons,0.6,0.81,0,-4.749,1,0.0479,0.00683,0.21,0.155,0.298,167.88,187147,4 5uCax9HTNlzGybIStD3vD,Say You Won't Let Go,James Arthur,0.358,0.557,10,-7.398,1,0.059,0.695,0,0.0902,0.494,85.043,211467,4 79cuOz3SPQTuFrp8WgftA,There's Nothing Holdin' Me Back,Shawn Mendes,0.857,0.8,2,-4.035,1,0.0583,0.381,0,0.0913,0.966,121.996,199440,4 6De0lHrwBfPfrhorm9q1X,Me Reh̼so,Danny Ocean,0.744,0.804,1,-6.327,1,0.0677,0.0231,0,0.0494,0.426,104.823,205715,4 6D0b04NJIKfEMg040WioJ,Issues,Julia Michaels,0.706,0.427,8,-6.864,1,0.0879,0.413,0,0.0609,0.42,113.804,176320,4 0afhq8XCExXpqazXczTSv,Galway Girl,Ed Sheeran,0.624,0.876,9,-3.374,1,0.1,0.0735,0,0.327,0.781,99.943,170827,4 3ebXMykcMXOcLeJ9xZ17X,Scared to Be Lonely,Martin Garrix,0.584,0.54,1,-7.786,0,0.0576,0.0895,0,0.261,0.195,137.972,220883,4 7BKLCZ1jbUBVqRi2FVlTV,Closer,The Chainsmokers,0.748,0.524,8,-5.599,1,0.0338,0.414,0,0.111,0.661,95.01,244960,4 1x5sYLZiu9r5E43kMlt9f,Symphony (feat. Zara Larsson),Clean Bandit,0.707,0.629,0,-4.581,0,0.0563,0.259,1.60E-05,0.138,0.457,122.863,212459,4 5GXAXm5YOmYT0kL5jHvYB,I Feel It Coming,The Weeknd,0.768,0.813,0,-5.94,0,0.128,0.427,0,0.102,0.579,92.994,269187,4 5aAx2yezTd8zXrkmtKl66,Starboy,The Weeknd,0.681,0.594,7,-7.028,1,0.282,0.165,3.49E-06,0.134,0.535,186.054,230453,4 1OAh8uOEOvTDqkKFsKksC,Wild Thoughts,DJ Khaled,0.671,0.672,0,-3.094,0,0.0688,0.0329,0,0.118,0.632,97.98,204173,4 7tr2za8SQg2CI8EDgrdtN,Slide,Calvin Harris,0.736,0.795,1,-3.299,0,0.0545,0.498,1.21E-06,0.254,0.511,104.066,230813,4 2ekn2ttSfGqwhhate0LSR,New Rules,Dua Lipa,0.771,0.696,9,-6.258,0,0.0755,0.00256,9.71E-06,0.179,0.656,116.054,208827,4 5tz69p7tJuGPeMGwNTxYu,1-800-273-8255,Logic,0.629,0.572,5,-7.733,0,0.0387,0.57,0,0.192,0.386,100.015,250173,4 7hDc8b7IXETo14hHIHdnh,Passionfruit,Drake,0.809,0.463,11,-11.377,1,0.0396,0.256,0.085,0.109,0.364,111.98,298941,4 7wGoVu4Dady5GV0Sv4UIs,rockstar,Post Malone,0.577,0.522,5,-6.594,0,0.0984,0.13,9.03E-05,0.142,0.119,159.772,218320,4 6EpRaXYhGOB3fj4V2uDkM,Strip That Down,Liam Payne,0.869,0.485,6,-5.595,1,0.0545,0.246,0,0.0765,0.527,106.028,204502,4 3A7qX2QjDlPnazUsRk5y0,2U (feat. Justin Bieber),David Guetta,0.548,0.65,8,-5.827,0,0.0591,0.219,0,0.225,0.557,144.937,194897,4 0tgVpDi06FyKpA1z0VMD4,Perfect,Ed Sheeran,0.599,0.448,8,-6.312,1,0.0232,0.163,0,0.106,0.168,95.05,263400,3 78rIJddV4X0HkNAInEcYd,Call On Me - Ryan Riback Extended Remix,Starley,0.676,0.843,0,-4.068,1,0.0367,0.0623,0.000752,0.181,0.718,105.003,222041,4 5bcTCxgc7xVfSaMV3RuVk,Feels,Calvin Harris,0.893,0.745,11,-3.105,0,0.0571,0.0642,0,0.0943,0.872,101.018,223413,4 0NiXXAI876aGImAd6rTj8,Mama,Jonas Blue,0.746,0.793,11,-4.209,0,0.0412,0.11,0,0.0528,0.557,104.027,181615,4 0qYTZCo5Bwh1nsUFGZP3z,Felices los 4,Maluma,0.755,0.789,5,-4.502,1,0.146,0.231,0,0.351,0.737,93.973,229849,4 2EEeOnHehOozLq4aS0n6S,iSpy (feat. Lil Yachty),KYLE,0.746,0.653,7,-6.745,1,0.289,0.378,0,0.229,0.672,75.016,253107,4 152lZdxL1OR0ZMW6KquMi,Location,Khalid,0.736,0.449,1,-11.462,0,0.425,0.33,0.000162,0.0898,0.326,80.126,219080,4 6mICuAdrwEjh6Y6lroV2K,Chantaje,Shakira,0.852,0.773,8,-2.921,0,0.0776,0.187,3.05E-05,0.159,0.907,102.034,195840,4 4Km5HrUvYTaSUfiSGPJeQ,Bad and Boujee (feat. Lil Uzi Vert),Migos,0.927,0.665,11,-5.313,1,0.244,0.061,0,0.123,0.175,127.076,343150,4 0ofbQMrRDsUaVKq2mGLEA,Havana,Camila Cabello,0.768,0.517,7,-4.323,0,0.0312,0.186,3.80E-05,0.104,0.418,104.992,216897,4 6HUnnBwYZqcED1eQztxMB,Solo Dance,Martin Jensen,0.744,0.836,6,-2.396,0,0.0507,0.0435,0,0.194,0.36,114.965,174933,4 343YBumqHu19cGoGARUTs,Fake Love,Drake,0.927,0.488,9,-9.433,0,0.42,0.108,0,0.196,0.605,133.987,210937,4 4pdPtRcBmOSQDlJ3Fk945,Let Me Love You,DJ Snake,0.476,0.718,8,-5.309,1,0.0576,0.0784,1.02E-05,0.122,0.142,199.864,205947,4 3PEgB3fkiojxms35ntsTg,More Than You Know,Axwell /\ Ingrosso,0.644,0.743,5,-5.002,0,0.0355,0.034,0,0.257,0.544,123.074,203000,4 1xznGGDReH1oQq0xzbwXa,One Dance,Drake,0.791,0.619,1,-5.886,1,0.0532,0.00784,0.00423,0.351,0.371,103.989,173987,4 7nKBxz47S9SD79N086fuh,SUBEME LA RADIO,Enrique Iglesias,0.684,0.823,9,-3.297,0,0.0773,0.0744,0,0.111,0.647,91.048,208163,4 1NDxZ7cFAo481dtYWdrUn,Pretty Girl - Cheat Codes X CADE Remix,Maggie Lindemann,0.703,0.868,7,-4.661,0,0.0291,0.15,0.132,0.104,0.733,121.03,193613,4 3m660poUr1chesgkkjQM7,Sorry Not Sorry,Demi Lovato,0.704,0.633,11,-6.923,0,0.241,0.0214,0,0.29,0.863,144.021,203760,4 3kxfsdsCpFgN412fpnW85,Redbone,Childish Gambino,0.743,0.359,1,-10.401,1,0.0794,0.199,0.00611,0.137,0.587,160.083,326933,4 6b8Be6ljOzmkOmFslEb23,24K Magic,Bruno Mars,0.818,0.803,1,-4.282,1,0.0797,0.034,0,0.153,0.632,106.97,225983,4 6HZILIRieu8S0iqY8kIKh,DNA.,Kendrick Lamar,0.637,0.514,1,-6.763,1,0.365,0.0047,0,0.094,0.402,139.931,185947,4 3umS4y3uQDkqekNjVpiRU,El Amante,Nicky Jam,0.683,0.691,8,-5.535,1,0.0432,0.243,0,0.14,0.732,179.91,219507,4 00lNx0OcTJrS3MKHcB80H,You Don't Know Me - Radio Edit,Jax Jones,0.876,0.669,11,-6.054,0,0.138,0.163,0,0.185,0.682,124.007,213947,4 6520aj0B4FSKGVuKNsOCO,Chained To The Rhythm,Katy Perry,0.448,0.801,0,-5.363,1,0.165,0.0733,0,0.146,0.462,189.798,237734,4 1louJpMmzEicAn7lzDalP,No Promises (feat. Demi Lovato),Cheat Codes,0.741,0.667,10,-5.445,1,0.134,0.0575,0,0.106,0.595,112.956,223504,4 2QbFClFyhMMtiurUjuQlA,Don't Wanna Know (feat. Kendrick Lamar),Maroon 5,0.775,0.617,7,-6.166,1,0.0701,0.341,0,0.0985,0.485,100.048,214265,4 5hYTyyh2odQKphUbMqc5g,"How Far I'll Go - From ""Moana""",Alessia Cara,0.314,0.555,9,-9.601,1,0.37,0.157,0.000108,0.067,0.159,179.666,175517,4 38yBBH2jacvDxrznF7h08,Slow Hands,Niall Horan,0.734,0.418,0,-6.678,1,0.0425,0.0129,0,0.0579,0.868,85.909,188174,4 2cnKEkpVUSV4wnjQiTWfH,EscÌÁpate Conmigo,Wisin,0.747,0.864,8,-3.181,0,0.0599,0.0245,4.46E-05,0.0853,0.754,92.028,232787,4 0SGkqnVQo9KPytSri1H6c,Bounce Back,Big Sean,0.77,0.567,2,-5.698,1,0.175,0.105,0,0.125,0.26,81.477,222360,4 5Ohxk2dO5COHF1krpoPig,Sign of the Times,Harry Styles,0.516,0.595,5,-4.63,1,0.0313,0.0275,0,0.109,0.222,119.972,340707,4 6gBFPUFcJLzWGx4lenP6h,goosebumps,Travis Scott,0.841,0.728,7,-3.37,1,0.0484,0.0847,0,0.149,0.43,130.049,243837,4 5Z3GHaZ6ec9bsiI5Benrb,Young Dumb & Broke,Khalid,0.798,0.539,1,-6.351,1,0.0421,0.199,1.66E-05,0.165,0.394,136.949,202547,4 6jA8HL9i4QGzsj6fjoxp8,There for You,Martin Garrix,0.611,0.644,6,-7.607,0,0.0553,0.124,0,0.124,0.13,105.969,221904,4 21TdkDRXuAB3k90ujRU1e,Cold (feat. Future),Maroon 5,0.697,0.716,9,-6.288,0,0.113,0.118,0,0.0424,0.506,99.905,234308,4 7vGuf3Y35N4wmASOKLUVV,Silence,Marshmello,0.52,0.761,4,-3.093,1,0.0853,0.256,4.96E-06,0.17,0.286,141.971,180823,4 1mXVgsBdtIVeCLJnSnmtd,Too Good At Goodbyes,Sam Smith,0.698,0.375,5,-8.279,1,0.0491,0.652,0,0.173,0.534,91.92,201000,4 3EmmCZoqpWOTY1g2GBwJo,Just Hold On,Steve Aoki,0.647,0.932,11,-3.515,1,0.0824,0.00383,1.50E-06,0.0574,0.374,114.991,198774,4 6uFsE1JgZ20EXyU0JQZbU,Look What You Made Me Do,Taylor Swift,0.773,0.68,9,-6.378,0,0.141,0.213,1.57E-05,0.122,0.497,128.062,211859,4 0CokSRCu5hZgPxcZBaEzV,Glorious (feat. Skylar Grey),Macklemore,0.731,0.794,0,-5.126,0,0.0522,0.0323,2.59E-05,0.112,0.356,139.994,220454,4 6875MeXyCW0wLyT72Eetm,Starving,Hailee Steinfeld,0.721,0.626,4,-4.2,1,0.123,0.402,0,0.102,0.558,99.914,181933,4 3AEZUABDXNtecAOSC1qTf,ReggaetÌ_n Lento (Bailemos),CNCO,0.761,0.838,4,-3.073,0,0.0502,0.4,0,0.176,0.71,93.974,222560,4 3E2Zh20GDCR9B1EYjfXWy,Weak,AJR,0.673,0.637,5,-4.518,1,0.0429,0.137,0,0.184,0.678,123.98,201160,4 4pLwZjInHj3SimIyN9SnO,Side To Side,Ariana Grande,0.648,0.738,6,-5.883,0,0.247,0.0408,0,0.292,0.603,159.145,226160,4 3QwBODjSEzelZyVjxPOHd,Otra Vez (feat. J Balvin),Zion & Lennox,0.832,0.772,10,-5.429,1,0.1,0.0559,0.000486,0.44,0.704,96.016,209453,4 1wjzFQodRWrPcQ0AnYnvQ,I Like Me Better,Lauv,0.752,0.505,9,-7.621,1,0.253,0.535,2.55E-06,0.104,0.419,91.97,197437,4 04DwTuZ2VBdJCCC5TROn7,In the Name of Love,Martin Garrix,0.49,0.485,4,-6.237,0,0.0406,0.0592,0,0.337,0.196,133.889,195840,4 6DNtNfH8hXkqOX1sjqmI7,Cold Water (feat. Justin Bieber & MÌ÷),Major Lazer,0.608,0.798,6,-5.092,0,0.0432,0.0736,0,0.156,0.501,92.943,185352,4 1UZOjK1BwmwWU14Erba9C,Malibu,Miley Cyrus,0.573,0.781,8,-6.406,1,0.0555,0.0767,2.64E-05,0.0813,0.343,139.934,231907,4 4b4KcovePX8Ke2cLIQTLM,All Night,The Vamps,0.544,0.809,8,-5.098,1,0.0363,0.0038,0,0.323,0.448,145.017,197640,4 1a5Yu5L18qNxVhXx38njO,Hear Me Now,Alok,0.789,0.442,11,-7.844,1,0.0421,0.586,0.00366,0.0927,0.45,121.971,192846,4 4c2W3VKsOFoIg2SFaO6DY,Your Song,Rita Ora,0.855,0.624,1,-4.093,1,0.0488,0.158,0,0.0513,0.962,117.959,180757,4 22eADXu8DfOAUEDw4vU8q,Ahora Dice,Chris Jeday,0.708,0.693,6,-5.516,1,0.138,0.246,0,0.129,0.427,143.965,271080,4 7nZmah2llfvLDiUjm0kiy,Friends (with BloodPopå¨),Justin Bieber,0.744,0.739,8,-5.35,1,0.0387,0.00459,0,0.306,0.649,104.99,189467,4 2fQrGHiQOvpL9UgPvtYy6,Bank Account,21 Savage,0.884,0.346,8,-8.228,0,0.351,0.0151,7.04E-06,0.0871,0.376,75.016,220307,4 1PSBzsahR2AKwLJgx8ehB,Bad Things (with Camila Cabello),Machine Gun Kelly,0.675,0.69,2,-4.761,1,0.132,0.21,0,0.287,0.272,137.817,239293,4 0QsvXIfqM0zZoerQfsI9l,Don't Let Me Down,The Chainsmokers,0.542,0.859,11,-5.651,1,0.197,0.16,0.00466,0.137,0.403,159.797,208053,4 7mldq42yDuxiUNn08nvzH,Body Like A Back Road,Sam Hunt,0.731,0.469,5,-7.226,1,0.0326,0.463,1.04E-06,0.103,0.631,98.963,165387,4 7i2DJ88J7jQ8K7zqFX2fW,Now Or Never,Halsey,0.658,0.588,6,-4.902,0,0.0367,0.105,1.28E-06,0.125,0.434,110.075,214802,4 1j4kHkkpqZRBwE0A4CN4Y,Dusk Till Dawn - Radio Edit,ZAYN,0.258,0.437,11,-6.593,0,0.039,0.101,1.27E-06,0.106,0.0967,180.043,239000,4 \ No newline at end of file diff --git a/Students/Wayne/Assignments/Assignment_02/.ipynb_checkpoints/Activity1-checkpoint.ipynb b/Students/Wayne/Assignments/Assignment_02/.ipynb_checkpoints/Activity1-checkpoint.ipynb new file mode 100644 index 0000000..9da4a00 --- /dev/null +++ b/Students/Wayne/Assignments/Assignment_02/.ipynb_checkpoints/Activity1-checkpoint.ipynb @@ -0,0 +1,249 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Iterators and Iterables" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [], + "source": [ + "class IterateMe_1:\n", + " \"\"\"\n", + " About as simple an iterator as you can get:\n", + "\n", + " returns the sequence of numbers from zero to 4\n", + " ( like range(4) )\n", + " \"\"\"\n", + "\n", + " def __init__(self, stop=10):\n", + " self.current = -1\n", + " self.stop = stop\n", + "\n", + " def __iter__(self):\n", + " return self\n", + "\n", + " def __next__(self):\n", + " self.current += 1\n", + " if self.current < self.stop:\n", + " return self.current\n", + " else:\n", + " raise StopIteration\n", + "\n", + "\n", + "class IterateMe_2:\n", + "\n", + " def __init__(self, start, stop, step):\n", + " self.current = start - step\n", + " self.stop = stop\n", + " self.start = start\n", + " self.step = step\n", + "\n", + " def __iter__(self):\n", + " return self\n", + "\n", + " def __next__(self):\n", + " self.current += self.step\n", + " if self.current < self.stop:\n", + " return self.current\n", + " else:\n", + " raise StopIteration\n", + "\n", + "\n", + "it = IterateMe_2(2, 20, 2)\n", + "for i in it:\n", + " if i > 10: break\n", + "\n", + "\n", + "def rng():\n", + " print(\"Range function\")\n", + " for i in range(2, 20, 2):\n", + " print(i)\n" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Testing the iterator\n", + "0\n", + "1\n", + "2\n", + "3\n", + "4\n", + "5\n", + "6\n", + "7\n", + "8\n", + "9\n", + "Testing the IT iterator\n", + "14\n", + "16\n", + "18\n", + "Range function\n", + "2\n", + "4\n", + "6\n", + "8\n", + "10\n", + "12\n", + "14\n", + "16\n", + "18\n" + ] + } + ], + "source": [ + "if __name__ == \"__main__\":\n", + "\n", + " print(\"Testing the iterator\")\n", + " for i in IterateMe_1():\n", + " print(i)\n", + "\n", + " print(\"Testing the IT iterator\")\n", + " for i in it:\n", + " print(i)\n", + "\n", + "rng()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "is range an iterator or an iteratable? Range is an interables, because you cannot call next on range. An iterator will change the state of the objects in the sequence." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# GENERATOR" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Sum of the integers:\n", + "\n", + "keep adding the next integer\n", + "\n", + "0 + 1 + 2 + 3 + 4 + 5 + …\n", + "\n", + "so the sequence is:\n", + "\n", + "0, 1, 3, 6, 10, 15 ….." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "def sum_fun():\n", + " for n in range(1,6,1):\n", + " yield n*(n+1)/2\n", + " \n", + "sum_it = (sum_fun())" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "list(sum_it)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Doubler:\n", + "\n", + "Each value is double the previous value:\n", + "\n", + "1, 2, 4, 8, 16, 32," + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "def doubler():\n", + " for n in range(1,7,1):\n", + " yield (n+1)*2\n", + " \n", + " \n", + "double_it = (doubler())" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "list(double_it)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Fibonacci sequence:\n", + " \n", + "The Fibonacci sequence as a generator:\n", + "\n", + "f(n) = f(n-1) + f(n-2)\n", + "\n", + "1, 1, 2, 3, 5, 8, 13, 21, 34…" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Generate the prime numbers (numbers only divisible by them self and 1):\n", + "\n", + "2, 3, 5, 7, 11, 13, 17, 19, 23…" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.6.5" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/Students/Wayne/Assignments/Assignment_02/.ipynb_checkpoints/Assignment1-checkpoint.ipynb b/Students/Wayne/Assignments/Assignment_02/.ipynb_checkpoints/Assignment1-checkpoint.ipynb new file mode 100644 index 0000000..d65905c --- /dev/null +++ b/Students/Wayne/Assignments/Assignment_02/.ipynb_checkpoints/Assignment1-checkpoint.ipynb @@ -0,0 +1,648 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Comprehensions " + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Bring up an interpreter and load the data." + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [], + "source": [ + "import pandas as pd \n", + "music = pd.read_csv('spotify.csv')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "music.head gives us the headers and the overall datashape from the csv file " + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [ + { + "data": { + "text/html": [ + "
\n", + "\n", + "\n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + "
idnameartistsdanceabilityenergykeyloudnessmodespeechinessacousticnessinstrumentalnesslivenessvalencetempoduration_mstime_signature
07qiZfU4dY1lWllzX7mPBIShape of YouEd Sheeran0.8250.6521-3.18300.08020.58100.0000000.09310.93195.9772337134
15CtI0qwDJkDQGwXD1H1cLDespacito - RemixLuis Fonsi0.6940.8152-4.32810.12000.22900.0000000.09240.81388.9312288274
24aWmUDTfIPGksMNLV2rQPDespacito (Featuring Daddy Yankee)Luis Fonsi0.6600.7862-4.75710.17000.20900.0000000.11200.846177.8332282004
36RUKPb4LETWmmr3iAEQktSomething Just Like ThisThe Chainsmokers0.6170.63511-6.76900.03170.04980.0000140.16400.446103.0192471604
43DXncPQOG4VBw3QHh3S81I'm the OneDJ Khaled0.6090.6687-4.28410.03670.05520.0000000.16700.81180.9242886004
\n", + "
" + ], + "text/plain": [ + " id name \\\n", + "0 7qiZfU4dY1lWllzX7mPBI Shape of You \n", + "1 5CtI0qwDJkDQGwXD1H1cL Despacito - Remix \n", + "2 4aWmUDTfIPGksMNLV2rQP Despacito (Featuring Daddy Yankee) \n", + "3 6RUKPb4LETWmmr3iAEQkt Something Just Like This \n", + "4 3DXncPQOG4VBw3QHh3S81 I'm the One \n", + "\n", + " artists danceability energy key loudness mode speechiness \\\n", + "0 Ed Sheeran 0.825 0.652 1 -3.183 0 0.0802 \n", + "1 Luis Fonsi 0.694 0.815 2 -4.328 1 0.1200 \n", + "2 Luis Fonsi 0.660 0.786 2 -4.757 1 0.1700 \n", + "3 The Chainsmokers 0.617 0.635 11 -6.769 0 0.0317 \n", + "4 DJ Khaled 0.609 0.668 7 -4.284 1 0.0367 \n", + "\n", + " acousticness instrumentalness liveness valence tempo duration_ms \\\n", + "0 0.5810 0.000000 0.0931 0.931 95.977 233713 \n", + "1 0.2290 0.000000 0.0924 0.813 88.931 228827 \n", + "2 0.2090 0.000000 0.1120 0.846 177.833 228200 \n", + "3 0.0498 0.000014 0.1640 0.446 103.019 247160 \n", + "4 0.0552 0.000000 0.1670 0.811 80.924 288600 \n", + "\n", + " time_signature \n", + "0 4 \n", + "1 4 \n", + "2 4 \n", + "3 4 \n", + "4 4 " + ] + }, + "execution_count": 2, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "music.head()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "music.describe gives us the count, mean, std, min, quartiles and max " + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [ + { + "data": { + "text/html": [ + "
\n", + "\n", + "\n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + "
danceabilityenergykeyloudnessmodespeechinessacousticnessinstrumentalnesslivenessvalencetempoduration_mstime_signature
count100.00000100.000000100.000000100.000000100.000000100.000000100.000000100.000000100.000000100.000000100.000000100.00000100.00
mean0.696820.6606905.570000-5.6526500.5800000.1039690.1663060.0047960.1506070.517049119.202460218387.280003.99
std0.125080.1392073.7315341.8020670.4960450.0951150.1667300.0260380.0790110.21643627.95292832851.077720.10
min0.258000.3460000.000000-11.4620000.0000000.0232000.0002590.0000000.0424000.08620075.016000165387.000003.00
25%0.635000.5565002.000000-6.5945000.0000000.0431250.0391000.0000000.0982750.37550099.911750198490.500004.00
50%0.714000.6675006.000000-5.4370001.0000000.0626500.1065000.0000000.1250000.502500112.468000214106.000004.00
75%0.770250.7875009.000000-4.3267501.0000000.1230000.2312500.0000130.1792500.679000137.166000230543.000004.00
max0.927000.93200011.000000-2.3960001.0000000.4310000.6950000.2100000.4400000.966000199.864000343150.000004.00
\n", + "
" + ], + "text/plain": [ + " danceability energy key loudness mode \\\n", + "count 100.00000 100.000000 100.000000 100.000000 100.000000 \n", + "mean 0.69682 0.660690 5.570000 -5.652650 0.580000 \n", + "std 0.12508 0.139207 3.731534 1.802067 0.496045 \n", + "min 0.25800 0.346000 0.000000 -11.462000 0.000000 \n", + "25% 0.63500 0.556500 2.000000 -6.594500 0.000000 \n", + "50% 0.71400 0.667500 6.000000 -5.437000 1.000000 \n", + "75% 0.77025 0.787500 9.000000 -4.326750 1.000000 \n", + "max 0.92700 0.932000 11.000000 -2.396000 1.000000 \n", + "\n", + " speechiness acousticness instrumentalness liveness valence \\\n", + "count 100.000000 100.000000 100.000000 100.000000 100.000000 \n", + "mean 0.103969 0.166306 0.004796 0.150607 0.517049 \n", + "std 0.095115 0.166730 0.026038 0.079011 0.216436 \n", + "min 0.023200 0.000259 0.000000 0.042400 0.086200 \n", + "25% 0.043125 0.039100 0.000000 0.098275 0.375500 \n", + "50% 0.062650 0.106500 0.000000 0.125000 0.502500 \n", + "75% 0.123000 0.231250 0.000013 0.179250 0.679000 \n", + "max 0.431000 0.695000 0.210000 0.440000 0.966000 \n", + "\n", + " tempo duration_ms time_signature \n", + "count 100.000000 100.00000 100.00 \n", + "mean 119.202460 218387.28000 3.99 \n", + "std 27.952928 32851.07772 0.10 \n", + "min 75.016000 165387.00000 3.00 \n", + "25% 99.911750 198490.50000 4.00 \n", + "50% 112.468000 214106.00000 4.00 \n", + "75% 137.166000 230543.00000 4.00 \n", + "max 199.864000 343150.00000 4.00 " + ] + }, + "execution_count": 3, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "music.describe()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The following function gives us tracks with danceability greater than .8 " + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": { + "scrolled": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "[0.825,\n", + " 0.904,\n", + " 0.853,\n", + " 0.833,\n", + " 0.857,\n", + " 0.809,\n", + " 0.8690000000000001,\n", + " 0.893,\n", + " 0.852,\n", + " 0.927,\n", + " 0.927,\n", + " 0.818,\n", + " 0.8759999999999999,\n", + " 0.841,\n", + " 0.8320000000000001,\n", + " 0.855,\n", + " 0.884]" + ] + }, + "execution_count": 4, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "[d for d in music.danceability if d > 0.8]" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Returns tracks with a loudness score under -5.0" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "[-6.769,\n", + " -6.8420000000000005,\n", + " -6.596,\n", + " -5.043,\n", + " -8.374,\n", + " -6.3660000000000005,\n", + " -6.428,\n", + " -5.024,\n", + " -8.795,\n", + " -7.398,\n", + " -6.327000000000001,\n", + " -6.864,\n", + " -7.7860000000000005,\n", + " -5.599,\n", + " -5.94,\n", + " -7.028,\n", + " -6.257999999999999,\n", + " -7.733,\n", + " -11.377,\n", + " -6.593999999999999,\n", + " -5.595,\n", + " -5.827000000000001,\n", + " -6.312,\n", + " -6.745,\n", + " -11.462,\n", + " -5.313,\n", + " -9.433,\n", + " -5.309,\n", + " -5.002,\n", + " -5.886,\n", + " -6.922999999999999,\n", + " -10.401,\n", + " -6.763,\n", + " -5.535,\n", + " -6.053999999999999,\n", + " -5.3629999999999995,\n", + " -5.445,\n", + " -6.166,\n", + " -9.601,\n", + " -6.678,\n", + " -5.6979999999999995,\n", + " -6.351,\n", + " -7.607,\n", + " -6.287999999999999,\n", + " -8.279,\n", + " -6.377999999999999,\n", + " -5.126,\n", + " -5.882999999999999,\n", + " -5.428999999999999,\n", + " -7.621,\n", + " -6.237,\n", + " -5.092,\n", + " -6.406000000000001,\n", + " -5.098,\n", + " -7.843999999999999,\n", + " -5.516,\n", + " -5.35,\n", + " -8.228,\n", + " -5.651,\n", + " -7.226,\n", + " -6.593]" + ] + }, + "execution_count": 5, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "[l for l in music.loudness if l < -5.0]" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": {}, + "outputs": [], + "source": [ + "def shake_it_off():\n", + " \n", + " return(sorted([[a, n, d, l] for a, n, d, l in zip(music.artists,\n", + " music.name,\n", + " music.danceability,\n", + " music.loudness)\n", + " if d >.8 and l < -5.0],key=lambda x: x[2],reverse =True))\n", + "\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[['Migos', 'Bad and Boujee (feat. Lil Uzi Vert)', 0.927, -5.313], ['Drake', 'Fake Love', 0.927, -9.433], ['Kendrick Lamar', 'HUMBLE.', 0.904, -6.8420000000000005], ['21 Savage', 'Bank Account', 0.884, -8.228], ['Jax Jones', \"You Don't Know Me - Radio Edit\", 0.8759999999999999, -6.053999999999999], ['Liam Payne', 'Strip That Down', 0.8690000000000001, -5.595], ['Future', 'Mask Off', 0.833, -8.795], ['Zion & Lennox', 'Otra Vez (feat. J Balvin)', 0.8320000000000001, -5.428999999999999], ['Drake', 'Passionfruit', 0.809, -11.377]]\n" + ] + } + ], + "source": [ + "print(shake_it_off())" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "-------------------------------------------------------------------------------------------\n", + "\n", + "\n", + "The following songs below meet both the danceability and loudness constraints listed in the assignment. \n", + "\n", + "1. ['Migos', 'Bad and Boujee (feat. Lil Uzi Vert)', 0.927, -5.313], \n", + "2. ['Drake', 'Fake Love', 0.927, -9.433], \n", + "3. ['Kendrick Lamar', 'HUMBLE.', 0.904, -6.8420000000000005], \n", + "4. ['21 Savage', 'Bank Account', 0.884, -8.228], \n", + "5. ['Jax Jones', \"You Don't Know Me - Radio Edit\", 0.8759999999999999, -6.053999999999999], 6. ['Liam Payne', 'Strip That Down', 0.8690000000000001, -5.595], \n", + "7. ['Future', 'Mask Off', 0.833, -8.795], \n", + "8. ['Zion & Lennox', 'Otra Vez (feat. J Balvin)', 8.0.8320000000000001, -5.428999999999999], \n", + "9. ['Drake', 'Passionfruit', 0.809, -11.377]]\n", + "\n", + "-------------------------------------------------------------------------------------------" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.6.5" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/Students/Wayne/Assignments/Assignment_02/.ipynb_checkpoints/Assignment2-checkpoint.ipynb b/Students/Wayne/Assignments/Assignment_02/.ipynb_checkpoints/Assignment2-checkpoint.ipynb new file mode 100644 index 0000000..9050773 --- /dev/null +++ b/Students/Wayne/Assignments/Assignment_02/.ipynb_checkpoints/Assignment2-checkpoint.ipynb @@ -0,0 +1,373 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": 28, + "metadata": {}, + "outputs": [], + "source": [ + "import pandas as pd \n", + "music = pd.read_csv('spotify.csv')" + ] + }, + { + "cell_type": "code", + "execution_count": 16, + "metadata": {}, + "outputs": [ + { + "data": { + "text/html": [ + "
\n", + "\n", + "\n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + "
idnameartistsdanceabilityenergykeyloudnessmodespeechinessacousticnessinstrumentalnesslivenessvalencetempoduration_mstime_signature
07qiZfU4dY1lWllzX7mPBIShape of YouEd Sheeran0.8250.6521-3.18300.08020.58100.0000000.09310.93195.9772337134
15CtI0qwDJkDQGwXD1H1cLDespacito - RemixLuis Fonsi0.6940.8152-4.32810.12000.22900.0000000.09240.81388.9312288274
24aWmUDTfIPGksMNLV2rQPDespacito (Featuring Daddy Yankee)Luis Fonsi0.6600.7862-4.75710.17000.20900.0000000.11200.846177.8332282004
36RUKPb4LETWmmr3iAEQktSomething Just Like ThisThe Chainsmokers0.6170.63511-6.76900.03170.04980.0000140.16400.446103.0192471604
43DXncPQOG4VBw3QHh3S81I'm the OneDJ Khaled0.6090.6687-4.28410.03670.05520.0000000.16700.81180.9242886004
\n", + "
" + ], + "text/plain": [ + " id name \\\n", + "0 7qiZfU4dY1lWllzX7mPBI Shape of You \n", + "1 5CtI0qwDJkDQGwXD1H1cL Despacito - Remix \n", + "2 4aWmUDTfIPGksMNLV2rQP Despacito (Featuring Daddy Yankee) \n", + "3 6RUKPb4LETWmmr3iAEQkt Something Just Like This \n", + "4 3DXncPQOG4VBw3QHh3S81 I'm the One \n", + "\n", + " artists danceability energy key loudness mode speechiness \\\n", + "0 Ed Sheeran 0.825 0.652 1 -3.183 0 0.0802 \n", + "1 Luis Fonsi 0.694 0.815 2 -4.328 1 0.1200 \n", + "2 Luis Fonsi 0.660 0.786 2 -4.757 1 0.1700 \n", + "3 The Chainsmokers 0.617 0.635 11 -6.769 0 0.0317 \n", + "4 DJ Khaled 0.609 0.668 7 -4.284 1 0.0367 \n", + "\n", + " acousticness instrumentalness liveness valence tempo duration_ms \\\n", + "0 0.5810 0.000000 0.0931 0.931 95.977 233713 \n", + "1 0.2290 0.000000 0.0924 0.813 88.931 228827 \n", + "2 0.2090 0.000000 0.1120 0.846 177.833 228200 \n", + "3 0.0498 0.000014 0.1640 0.446 103.019 247160 \n", + "4 0.0552 0.000000 0.1670 0.811 80.924 288600 \n", + "\n", + " time_signature \n", + "0 4 \n", + "1 4 \n", + "2 4 \n", + "3 4 \n", + "4 4 " + ] + }, + "execution_count": 16, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "music.head()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Ed Sheerhan Generator" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Write a generator to find and print all of your favorite artist’s tracks from the data set. Your favorite artist isn’t represented in that set? In that case, find Ed Sheeran’s tracks.\n", + "\n", + "Load the data set following the instructions from last week. Submit your generator expression and the titles of Ed’s tracks.\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": 176, + "metadata": {}, + "outputs": [], + "source": [ + "def thinking_outloud_generator():\n", + " track = []\n", + " for track in ([a, n] for a, n in zip(music.artists,\n", + " music.name)\n", + " if a == 'Ed Sheeran'): \n", + " yield track\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": 180, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n" + ] + } + ], + "source": [ + "print(thinking_outloud_generator())" + ] + }, + { + "cell_type": "code", + "execution_count": 179, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "[['Ed Sheeran', 'Shape of You'],\n", + " ['Ed Sheeran', 'Castle on the Hill'],\n", + " ['Ed Sheeran', 'Galway Girl'],\n", + " ['Ed Sheeran', 'Perfect']]" + ] + }, + "execution_count": 179, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "list(thinking_outloud_generator())" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Get Amped Closures " + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "Using the same data set, write a closure to capture high energy tracks. We will define high energy tracks as anything over 8.0. Submit your code and the tracks it finds, artist name, track name and energy value." + ] + }, + { + "cell_type": "code", + "execution_count": 140, + "metadata": {}, + "outputs": [], + "source": [ + "def get_amped():\n", + " energy = music.energy\n", + " he = .8 < energy\n", + " def high_energy():\n", + " nonlocal he\n", + " return([[a, n, he] for a, n, he in zip(music.artists,\n", + " music.name,\n", + " music.energy,\n", + " he)])\n", + " \n", + " return ([[a, n, e, he] for a,n,e, he in zip(\n", + " music.artists,\n", + " music.name,\n", + " music.energy,\n", + " he\n", + " )if he==True])\n", + " " + ] + }, + { + "cell_type": "code", + "execution_count": 141, + "metadata": { + "scrolled": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "[['Luis Fonsi', 'Despacito - Remix', 0.815, True],\n", + " ['Post Malone', 'Congratulations', 0.812, True],\n", + " ['Jason Derulo',\n", + " 'Swalla (feat. Nicki Minaj & Ty Dolla $ign)',\n", + " 0.8170000000000001,\n", + " True],\n", + " ['Ed Sheeran', 'Castle on the Hill', 0.8340000000000001, True],\n", + " ['Imagine Dragons', 'Thunder', 0.81, True],\n", + " ['Danny Ocean', 'Me Reh̼so', 0.804, True],\n", + " ['Ed Sheeran', 'Galway Girl', 0.8759999999999999, True],\n", + " ['The Weeknd', 'I Feel It Coming', 0.813, True],\n", + " ['Starley', 'Call On Me - Ryan Riback Extended Remix', 0.843, True],\n", + " ['Martin Jensen', 'Solo Dance', 0.836, True],\n", + " ['Enrique Iglesias', 'SUBEME LA RADIO', 0.823, True],\n", + " ['Maggie Lindemann', 'Pretty Girl - Cheat Codes X CADE Remix', 0.868, True],\n", + " ['Bruno Mars', '24K Magic', 0.8029999999999999, True],\n", + " ['Katy Perry', 'Chained To The Rhythm', 0.8009999999999999, True],\n", + " ['Wisin', 'EscÌÁpate Conmigo', 0.8640000000000001, True],\n", + " ['Steve Aoki', 'Just Hold On', 0.932, True],\n", + " ['CNCO', 'ReggaetÌ_n Lento (Bailemos)', 0.838, True],\n", + " ['The Vamps', 'All Night', 0.809, True],\n", + " ['The Chainsmokers', \"Don't Let Me Down\", 0.8590000000000001, True]]" + ] + }, + "execution_count": 141, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "list(get_amped())" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.6.5" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/Students/Wayne/Assignments/Assignment_02/.ipynb_checkpoints/Random Exampes-checkpoint.ipynb b/Students/Wayne/Assignments/Assignment_02/.ipynb_checkpoints/Random Exampes-checkpoint.ipynb new file mode 100644 index 0000000..2fd6442 --- /dev/null +++ b/Students/Wayne/Assignments/Assignment_02/.ipynb_checkpoints/Random Exampes-checkpoint.ipynb @@ -0,0 +1,6 @@ +{ + "cells": [], + "metadata": {}, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/Students/Wayne/Assignments/Assignment_02/Assignment2.ipynb b/Students/Wayne/Assignments/Assignment_02/Assignment2.ipynb new file mode 100644 index 0000000..9050773 --- /dev/null +++ b/Students/Wayne/Assignments/Assignment_02/Assignment2.ipynb @@ -0,0 +1,373 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": 28, + "metadata": {}, + "outputs": [], + "source": [ + "import pandas as pd \n", + "music = pd.read_csv('spotify.csv')" + ] + }, + { + "cell_type": "code", + "execution_count": 16, + "metadata": {}, + "outputs": [ + { + "data": { + "text/html": [ + "
\n", + "\n", + "\n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + "
idnameartistsdanceabilityenergykeyloudnessmodespeechinessacousticnessinstrumentalnesslivenessvalencetempoduration_mstime_signature
07qiZfU4dY1lWllzX7mPBIShape of YouEd Sheeran0.8250.6521-3.18300.08020.58100.0000000.09310.93195.9772337134
15CtI0qwDJkDQGwXD1H1cLDespacito - RemixLuis Fonsi0.6940.8152-4.32810.12000.22900.0000000.09240.81388.9312288274
24aWmUDTfIPGksMNLV2rQPDespacito (Featuring Daddy Yankee)Luis Fonsi0.6600.7862-4.75710.17000.20900.0000000.11200.846177.8332282004
36RUKPb4LETWmmr3iAEQktSomething Just Like ThisThe Chainsmokers0.6170.63511-6.76900.03170.04980.0000140.16400.446103.0192471604
43DXncPQOG4VBw3QHh3S81I'm the OneDJ Khaled0.6090.6687-4.28410.03670.05520.0000000.16700.81180.9242886004
\n", + "
" + ], + "text/plain": [ + " id name \\\n", + "0 7qiZfU4dY1lWllzX7mPBI Shape of You \n", + "1 5CtI0qwDJkDQGwXD1H1cL Despacito - Remix \n", + "2 4aWmUDTfIPGksMNLV2rQP Despacito (Featuring Daddy Yankee) \n", + "3 6RUKPb4LETWmmr3iAEQkt Something Just Like This \n", + "4 3DXncPQOG4VBw3QHh3S81 I'm the One \n", + "\n", + " artists danceability energy key loudness mode speechiness \\\n", + "0 Ed Sheeran 0.825 0.652 1 -3.183 0 0.0802 \n", + "1 Luis Fonsi 0.694 0.815 2 -4.328 1 0.1200 \n", + "2 Luis Fonsi 0.660 0.786 2 -4.757 1 0.1700 \n", + "3 The Chainsmokers 0.617 0.635 11 -6.769 0 0.0317 \n", + "4 DJ Khaled 0.609 0.668 7 -4.284 1 0.0367 \n", + "\n", + " acousticness instrumentalness liveness valence tempo duration_ms \\\n", + "0 0.5810 0.000000 0.0931 0.931 95.977 233713 \n", + "1 0.2290 0.000000 0.0924 0.813 88.931 228827 \n", + "2 0.2090 0.000000 0.1120 0.846 177.833 228200 \n", + "3 0.0498 0.000014 0.1640 0.446 103.019 247160 \n", + "4 0.0552 0.000000 0.1670 0.811 80.924 288600 \n", + "\n", + " time_signature \n", + "0 4 \n", + "1 4 \n", + "2 4 \n", + "3 4 \n", + "4 4 " + ] + }, + "execution_count": 16, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "music.head()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Ed Sheerhan Generator" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Write a generator to find and print all of your favorite artist’s tracks from the data set. Your favorite artist isn’t represented in that set? In that case, find Ed Sheeran’s tracks.\n", + "\n", + "Load the data set following the instructions from last week. Submit your generator expression and the titles of Ed’s tracks.\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": 176, + "metadata": {}, + "outputs": [], + "source": [ + "def thinking_outloud_generator():\n", + " track = []\n", + " for track in ([a, n] for a, n in zip(music.artists,\n", + " music.name)\n", + " if a == 'Ed Sheeran'): \n", + " yield track\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": 180, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n" + ] + } + ], + "source": [ + "print(thinking_outloud_generator())" + ] + }, + { + "cell_type": "code", + "execution_count": 179, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "[['Ed Sheeran', 'Shape of You'],\n", + " ['Ed Sheeran', 'Castle on the Hill'],\n", + " ['Ed Sheeran', 'Galway Girl'],\n", + " ['Ed Sheeran', 'Perfect']]" + ] + }, + "execution_count": 179, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "list(thinking_outloud_generator())" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Get Amped Closures " + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "Using the same data set, write a closure to capture high energy tracks. We will define high energy tracks as anything over 8.0. Submit your code and the tracks it finds, artist name, track name and energy value." + ] + }, + { + "cell_type": "code", + "execution_count": 140, + "metadata": {}, + "outputs": [], + "source": [ + "def get_amped():\n", + " energy = music.energy\n", + " he = .8 < energy\n", + " def high_energy():\n", + " nonlocal he\n", + " return([[a, n, he] for a, n, he in zip(music.artists,\n", + " music.name,\n", + " music.energy,\n", + " he)])\n", + " \n", + " return ([[a, n, e, he] for a,n,e, he in zip(\n", + " music.artists,\n", + " music.name,\n", + " music.energy,\n", + " he\n", + " )if he==True])\n", + " " + ] + }, + { + "cell_type": "code", + "execution_count": 141, + "metadata": { + "scrolled": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "[['Luis Fonsi', 'Despacito - Remix', 0.815, True],\n", + " ['Post Malone', 'Congratulations', 0.812, True],\n", + " ['Jason Derulo',\n", + " 'Swalla (feat. Nicki Minaj & Ty Dolla $ign)',\n", + " 0.8170000000000001,\n", + " True],\n", + " ['Ed Sheeran', 'Castle on the Hill', 0.8340000000000001, True],\n", + " ['Imagine Dragons', 'Thunder', 0.81, True],\n", + " ['Danny Ocean', 'Me Reh̼so', 0.804, True],\n", + " ['Ed Sheeran', 'Galway Girl', 0.8759999999999999, True],\n", + " ['The Weeknd', 'I Feel It Coming', 0.813, True],\n", + " ['Starley', 'Call On Me - Ryan Riback Extended Remix', 0.843, True],\n", + " ['Martin Jensen', 'Solo Dance', 0.836, True],\n", + " ['Enrique Iglesias', 'SUBEME LA RADIO', 0.823, True],\n", + " ['Maggie Lindemann', 'Pretty Girl - Cheat Codes X CADE Remix', 0.868, True],\n", + " ['Bruno Mars', '24K Magic', 0.8029999999999999, True],\n", + " ['Katy Perry', 'Chained To The Rhythm', 0.8009999999999999, True],\n", + " ['Wisin', 'EscÌÁpate Conmigo', 0.8640000000000001, True],\n", + " ['Steve Aoki', 'Just Hold On', 0.932, True],\n", + " ['CNCO', 'ReggaetÌ_n Lento (Bailemos)', 0.838, True],\n", + " ['The Vamps', 'All Night', 0.809, True],\n", + " ['The Chainsmokers', \"Don't Let Me Down\", 0.8590000000000001, True]]" + ] + }, + "execution_count": 141, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "list(get_amped())" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.6.5" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/Students/Wayne/Assignments/Assignment_02/Assignment2.py b/Students/Wayne/Assignments/Assignment_02/Assignment2.py new file mode 100644 index 0000000..4b3ec87 --- /dev/null +++ b/Students/Wayne/Assignments/Assignment_02/Assignment2.py @@ -0,0 +1,70 @@ + +# coding: utf-8 + +# In[28]: + + +import pandas as pd +music = pd.read_csv('spotify.csv') + + +# In[16]: + + +music.head() + + +# # Ed Sheerhan Generator + +# Write a generator to find and print all of your favorite artist’s tracks +# from the data set. Your favorite artist isn’t represented in that set? +# In that case, find Ed Sheeran’s tracks. +# +# Load the data set following the instructions from last week. Submit +# your generator expression and the titles of Ed’s tracks. + + +# In[176]: + + +def thinking_outloud_generator(): + track = [] + for track in ([a, n] for a, n in zip(music.artists, + music.name) + if a == 'Ed Sheeran'): + yield track + +# # Get Amped Closures + +# Using the same data set, write a closure to capture high energy tracks. +# We will define high energy tracks as anything over 8.0. Submit your code +# and the tracks it finds, artist name, track name and energy value. + +# In[140]: + + +def get_amped(): + energy = music.energy + he = .8 < energy + + def high_energy(): + nonlocal he + return([[a, n, he] for a, n, he in zip(music.artists, + music.name, + music.energy, + he)]) + + return ([[a, n, e, he] for a, n, e, he in zip(music.artists, + music.name, + music.energy, + he + )if he==True]) + +# In[141]: + + +if __name__ == "__main__": + + list(get_amped()) + print(thinking_outloud_generator()) + list(thinking_outloud_generator()) diff --git a/Students/Wayne/Assignments/Assignment_02/spotify.csv b/Students/Wayne/Assignments/Assignment_02/spotify.csv new file mode 100644 index 0000000..83b453d --- /dev/null +++ b/Students/Wayne/Assignments/Assignment_02/spotify.csv @@ -0,0 +1 @@ +id,name,artists,danceability,energy,key,loudness,mode,speechiness,acousticness,instrumentalness,liveness,valence,tempo,duration_ms,time_signature 7qiZfU4dY1lWllzX7mPBI,Shape of You,Ed Sheeran,0.825,0.652,1,-3.183,0,0.0802,0.581,0,0.0931,0.931,95.977,233713,4 5CtI0qwDJkDQGwXD1H1cL,Despacito - Remix,Luis Fonsi,0.694,0.815,2,-4.328,1,0.12,0.229,0,0.0924,0.813,88.931,228827,4 4aWmUDTfIPGksMNLV2rQP,Despacito (Featuring Daddy Yankee),Luis Fonsi,0.66,0.786,2,-4.757,1,0.17,0.209,0,0.112,0.846,177.833,228200,4 6RUKPb4LETWmmr3iAEQkt,Something Just Like This,The Chainsmokers,0.617,0.635,11,-6.769,0,0.0317,0.0498,1.44E-05,0.164,0.446,103.019,247160,4 3DXncPQOG4VBw3QHh3S81,I'm the One,DJ Khaled,0.609,0.668,7,-4.284,1,0.0367,0.0552,0,0.167,0.811,80.924,288600,4 7KXjTSCq5nL1LoYtL7XAw,HUMBLE.,Kendrick Lamar,0.904,0.611,1,-6.842,0,0.0888,0.000259,2.03E-05,0.0976,0.4,150.02,177000,4 3eR23VReFzcdmS7TYCrhC,It Ain't Me (with Selena Gomez),Kygo,0.64,0.533,0,-6.596,1,0.0706,0.119,0,0.0864,0.515,99.968,220781,4 3B54sVLJ402zGa6Xm4YGN,Unforgettable,French Montana,0.726,0.769,6,-5.043,1,0.123,0.0293,0.0101,0.104,0.733,97.985,233902,4 0KKkJNfGyhkQ5aFogxQAP,That's What I Like,Bruno Mars,0.853,0.56,1,-4.961,1,0.0406,0.013,0,0.0944,0.86,134.066,206693,4 3NdDpSvN911VPGivFlV5d,"I Don‰Ûªt Wanna Live Forever (Fifty Shades Darker) - From ""Fifty Shades Darker (Original Motion Picture Soundtrack)""",ZAYN,0.735,0.451,0,-8.374,1,0.0585,0.0631,1.30E-05,0.325,0.0862,117.973,245200,4 7GX5flRQZVHRAGd6B4TmD,XO TOUR Llif3,Lil Uzi Vert,0.732,0.75,11,-6.366,0,0.231,0.00264,0,0.109,0.401,155.096,182707,4 72jbDTw1piOOj770jWNea,Paris,The Chainsmokers,0.653,0.658,2,-6.428,1,0.0304,0.0215,1.66E-06,0.0939,0.219,99.99,221507,4 0dA2Mk56wEzDgegdC6R17,Stay (with Alessia Cara),Zedd,0.679,0.634,5,-5.024,0,0.0654,0.232,0,0.115,0.498,102.013,210091,4 4iLqG9SeJSnt0cSPICSjx,Attention,Charlie Puth,0.774,0.626,3,-4.432,0,0.0432,0.0969,3.12E-05,0.0848,0.777,100.041,211475,4 0VgkVdmE4gld66l8iyGjg,Mask Off,Future,0.833,0.434,2,-8.795,1,0.431,0.0102,0.0219,0.165,0.281,150.062,204600,4 3a1lNhkSLSkpJE4MSHpDu,Congratulations,Post Malone,0.627,0.812,6,-4.215,1,0.0358,0.198,0,0.212,0.504,123.071,220293,4 6kex4EBAj0WHXDKZMEJaa,Swalla (feat. Nicki Minaj & Ty Dolla $ign),Jason Derulo,0.696,0.817,1,-3.862,1,0.109,0.075,0,0.187,0.782,98.064,216409,4 6PCUP3dWmTjcTtXY02oFd,Castle on the Hill,Ed Sheeran,0.461,0.834,2,-4.868,1,0.0989,0.0232,1.14E-05,0.14,0.471,135.007,261154,4 5knuzwU65gJK7IF5yJsua,Rockabye (feat. Sean Paul & Anne-Marie),Clean Bandit,0.72,0.763,9,-4.068,0,0.0523,0.406,0,0.18,0.742,101.965,251088,4 0CcQNd8CINkwQfe1RDtGV,Believer,Imagine Dragons,0.779,0.787,10,-4.305,0,0.108,0.0524,0,0.14,0.708,124.982,204347,4 2rb5MvYT7ZIxbKW5hfcHx,Mi Gente,J Balvin,0.543,0.677,11,-4.915,0,0.0993,0.0148,6.21E-06,0.13,0.294,103.809,189440,4 0tKcYR2II1VCQWT79i5Nr,Thunder,Imagine Dragons,0.6,0.81,0,-4.749,1,0.0479,0.00683,0.21,0.155,0.298,167.88,187147,4 5uCax9HTNlzGybIStD3vD,Say You Won't Let Go,James Arthur,0.358,0.557,10,-7.398,1,0.059,0.695,0,0.0902,0.494,85.043,211467,4 79cuOz3SPQTuFrp8WgftA,There's Nothing Holdin' Me Back,Shawn Mendes,0.857,0.8,2,-4.035,1,0.0583,0.381,0,0.0913,0.966,121.996,199440,4 6De0lHrwBfPfrhorm9q1X,Me Reh̼so,Danny Ocean,0.744,0.804,1,-6.327,1,0.0677,0.0231,0,0.0494,0.426,104.823,205715,4 6D0b04NJIKfEMg040WioJ,Issues,Julia Michaels,0.706,0.427,8,-6.864,1,0.0879,0.413,0,0.0609,0.42,113.804,176320,4 0afhq8XCExXpqazXczTSv,Galway Girl,Ed Sheeran,0.624,0.876,9,-3.374,1,0.1,0.0735,0,0.327,0.781,99.943,170827,4 3ebXMykcMXOcLeJ9xZ17X,Scared to Be Lonely,Martin Garrix,0.584,0.54,1,-7.786,0,0.0576,0.0895,0,0.261,0.195,137.972,220883,4 7BKLCZ1jbUBVqRi2FVlTV,Closer,The Chainsmokers,0.748,0.524,8,-5.599,1,0.0338,0.414,0,0.111,0.661,95.01,244960,4 1x5sYLZiu9r5E43kMlt9f,Symphony (feat. Zara Larsson),Clean Bandit,0.707,0.629,0,-4.581,0,0.0563,0.259,1.60E-05,0.138,0.457,122.863,212459,4 5GXAXm5YOmYT0kL5jHvYB,I Feel It Coming,The Weeknd,0.768,0.813,0,-5.94,0,0.128,0.427,0,0.102,0.579,92.994,269187,4 5aAx2yezTd8zXrkmtKl66,Starboy,The Weeknd,0.681,0.594,7,-7.028,1,0.282,0.165,3.49E-06,0.134,0.535,186.054,230453,4 1OAh8uOEOvTDqkKFsKksC,Wild Thoughts,DJ Khaled,0.671,0.672,0,-3.094,0,0.0688,0.0329,0,0.118,0.632,97.98,204173,4 7tr2za8SQg2CI8EDgrdtN,Slide,Calvin Harris,0.736,0.795,1,-3.299,0,0.0545,0.498,1.21E-06,0.254,0.511,104.066,230813,4 2ekn2ttSfGqwhhate0LSR,New Rules,Dua Lipa,0.771,0.696,9,-6.258,0,0.0755,0.00256,9.71E-06,0.179,0.656,116.054,208827,4 5tz69p7tJuGPeMGwNTxYu,1-800-273-8255,Logic,0.629,0.572,5,-7.733,0,0.0387,0.57,0,0.192,0.386,100.015,250173,4 7hDc8b7IXETo14hHIHdnh,Passionfruit,Drake,0.809,0.463,11,-11.377,1,0.0396,0.256,0.085,0.109,0.364,111.98,298941,4 7wGoVu4Dady5GV0Sv4UIs,rockstar,Post Malone,0.577,0.522,5,-6.594,0,0.0984,0.13,9.03E-05,0.142,0.119,159.772,218320,4 6EpRaXYhGOB3fj4V2uDkM,Strip That Down,Liam Payne,0.869,0.485,6,-5.595,1,0.0545,0.246,0,0.0765,0.527,106.028,204502,4 3A7qX2QjDlPnazUsRk5y0,2U (feat. Justin Bieber),David Guetta,0.548,0.65,8,-5.827,0,0.0591,0.219,0,0.225,0.557,144.937,194897,4 0tgVpDi06FyKpA1z0VMD4,Perfect,Ed Sheeran,0.599,0.448,8,-6.312,1,0.0232,0.163,0,0.106,0.168,95.05,263400,3 78rIJddV4X0HkNAInEcYd,Call On Me - Ryan Riback Extended Remix,Starley,0.676,0.843,0,-4.068,1,0.0367,0.0623,0.000752,0.181,0.718,105.003,222041,4 5bcTCxgc7xVfSaMV3RuVk,Feels,Calvin Harris,0.893,0.745,11,-3.105,0,0.0571,0.0642,0,0.0943,0.872,101.018,223413,4 0NiXXAI876aGImAd6rTj8,Mama,Jonas Blue,0.746,0.793,11,-4.209,0,0.0412,0.11,0,0.0528,0.557,104.027,181615,4 0qYTZCo5Bwh1nsUFGZP3z,Felices los 4,Maluma,0.755,0.789,5,-4.502,1,0.146,0.231,0,0.351,0.737,93.973,229849,4 2EEeOnHehOozLq4aS0n6S,iSpy (feat. Lil Yachty),KYLE,0.746,0.653,7,-6.745,1,0.289,0.378,0,0.229,0.672,75.016,253107,4 152lZdxL1OR0ZMW6KquMi,Location,Khalid,0.736,0.449,1,-11.462,0,0.425,0.33,0.000162,0.0898,0.326,80.126,219080,4 6mICuAdrwEjh6Y6lroV2K,Chantaje,Shakira,0.852,0.773,8,-2.921,0,0.0776,0.187,3.05E-05,0.159,0.907,102.034,195840,4 4Km5HrUvYTaSUfiSGPJeQ,Bad and Boujee (feat. Lil Uzi Vert),Migos,0.927,0.665,11,-5.313,1,0.244,0.061,0,0.123,0.175,127.076,343150,4 0ofbQMrRDsUaVKq2mGLEA,Havana,Camila Cabello,0.768,0.517,7,-4.323,0,0.0312,0.186,3.80E-05,0.104,0.418,104.992,216897,4 6HUnnBwYZqcED1eQztxMB,Solo Dance,Martin Jensen,0.744,0.836,6,-2.396,0,0.0507,0.0435,0,0.194,0.36,114.965,174933,4 343YBumqHu19cGoGARUTs,Fake Love,Drake,0.927,0.488,9,-9.433,0,0.42,0.108,0,0.196,0.605,133.987,210937,4 4pdPtRcBmOSQDlJ3Fk945,Let Me Love You,DJ Snake,0.476,0.718,8,-5.309,1,0.0576,0.0784,1.02E-05,0.122,0.142,199.864,205947,4 3PEgB3fkiojxms35ntsTg,More Than You Know,Axwell /\ Ingrosso,0.644,0.743,5,-5.002,0,0.0355,0.034,0,0.257,0.544,123.074,203000,4 1xznGGDReH1oQq0xzbwXa,One Dance,Drake,0.791,0.619,1,-5.886,1,0.0532,0.00784,0.00423,0.351,0.371,103.989,173987,4 7nKBxz47S9SD79N086fuh,SUBEME LA RADIO,Enrique Iglesias,0.684,0.823,9,-3.297,0,0.0773,0.0744,0,0.111,0.647,91.048,208163,4 1NDxZ7cFAo481dtYWdrUn,Pretty Girl - Cheat Codes X CADE Remix,Maggie Lindemann,0.703,0.868,7,-4.661,0,0.0291,0.15,0.132,0.104,0.733,121.03,193613,4 3m660poUr1chesgkkjQM7,Sorry Not Sorry,Demi Lovato,0.704,0.633,11,-6.923,0,0.241,0.0214,0,0.29,0.863,144.021,203760,4 3kxfsdsCpFgN412fpnW85,Redbone,Childish Gambino,0.743,0.359,1,-10.401,1,0.0794,0.199,0.00611,0.137,0.587,160.083,326933,4 6b8Be6ljOzmkOmFslEb23,24K Magic,Bruno Mars,0.818,0.803,1,-4.282,1,0.0797,0.034,0,0.153,0.632,106.97,225983,4 6HZILIRieu8S0iqY8kIKh,DNA.,Kendrick Lamar,0.637,0.514,1,-6.763,1,0.365,0.0047,0,0.094,0.402,139.931,185947,4 3umS4y3uQDkqekNjVpiRU,El Amante,Nicky Jam,0.683,0.691,8,-5.535,1,0.0432,0.243,0,0.14,0.732,179.91,219507,4 00lNx0OcTJrS3MKHcB80H,You Don't Know Me - Radio Edit,Jax Jones,0.876,0.669,11,-6.054,0,0.138,0.163,0,0.185,0.682,124.007,213947,4 6520aj0B4FSKGVuKNsOCO,Chained To The Rhythm,Katy Perry,0.448,0.801,0,-5.363,1,0.165,0.0733,0,0.146,0.462,189.798,237734,4 1louJpMmzEicAn7lzDalP,No Promises (feat. Demi Lovato),Cheat Codes,0.741,0.667,10,-5.445,1,0.134,0.0575,0,0.106,0.595,112.956,223504,4 2QbFClFyhMMtiurUjuQlA,Don't Wanna Know (feat. Kendrick Lamar),Maroon 5,0.775,0.617,7,-6.166,1,0.0701,0.341,0,0.0985,0.485,100.048,214265,4 5hYTyyh2odQKphUbMqc5g,"How Far I'll Go - From ""Moana""",Alessia Cara,0.314,0.555,9,-9.601,1,0.37,0.157,0.000108,0.067,0.159,179.666,175517,4 38yBBH2jacvDxrznF7h08,Slow Hands,Niall Horan,0.734,0.418,0,-6.678,1,0.0425,0.0129,0,0.0579,0.868,85.909,188174,4 2cnKEkpVUSV4wnjQiTWfH,EscÌÁpate Conmigo,Wisin,0.747,0.864,8,-3.181,0,0.0599,0.0245,4.46E-05,0.0853,0.754,92.028,232787,4 0SGkqnVQo9KPytSri1H6c,Bounce Back,Big Sean,0.77,0.567,2,-5.698,1,0.175,0.105,0,0.125,0.26,81.477,222360,4 5Ohxk2dO5COHF1krpoPig,Sign of the Times,Harry Styles,0.516,0.595,5,-4.63,1,0.0313,0.0275,0,0.109,0.222,119.972,340707,4 6gBFPUFcJLzWGx4lenP6h,goosebumps,Travis Scott,0.841,0.728,7,-3.37,1,0.0484,0.0847,0,0.149,0.43,130.049,243837,4 5Z3GHaZ6ec9bsiI5Benrb,Young Dumb & Broke,Khalid,0.798,0.539,1,-6.351,1,0.0421,0.199,1.66E-05,0.165,0.394,136.949,202547,4 6jA8HL9i4QGzsj6fjoxp8,There for You,Martin Garrix,0.611,0.644,6,-7.607,0,0.0553,0.124,0,0.124,0.13,105.969,221904,4 21TdkDRXuAB3k90ujRU1e,Cold (feat. Future),Maroon 5,0.697,0.716,9,-6.288,0,0.113,0.118,0,0.0424,0.506,99.905,234308,4 7vGuf3Y35N4wmASOKLUVV,Silence,Marshmello,0.52,0.761,4,-3.093,1,0.0853,0.256,4.96E-06,0.17,0.286,141.971,180823,4 1mXVgsBdtIVeCLJnSnmtd,Too Good At Goodbyes,Sam Smith,0.698,0.375,5,-8.279,1,0.0491,0.652,0,0.173,0.534,91.92,201000,4 3EmmCZoqpWOTY1g2GBwJo,Just Hold On,Steve Aoki,0.647,0.932,11,-3.515,1,0.0824,0.00383,1.50E-06,0.0574,0.374,114.991,198774,4 6uFsE1JgZ20EXyU0JQZbU,Look What You Made Me Do,Taylor Swift,0.773,0.68,9,-6.378,0,0.141,0.213,1.57E-05,0.122,0.497,128.062,211859,4 0CokSRCu5hZgPxcZBaEzV,Glorious (feat. Skylar Grey),Macklemore,0.731,0.794,0,-5.126,0,0.0522,0.0323,2.59E-05,0.112,0.356,139.994,220454,4 6875MeXyCW0wLyT72Eetm,Starving,Hailee Steinfeld,0.721,0.626,4,-4.2,1,0.123,0.402,0,0.102,0.558,99.914,181933,4 3AEZUABDXNtecAOSC1qTf,ReggaetÌ_n Lento (Bailemos),CNCO,0.761,0.838,4,-3.073,0,0.0502,0.4,0,0.176,0.71,93.974,222560,4 3E2Zh20GDCR9B1EYjfXWy,Weak,AJR,0.673,0.637,5,-4.518,1,0.0429,0.137,0,0.184,0.678,123.98,201160,4 4pLwZjInHj3SimIyN9SnO,Side To Side,Ariana Grande,0.648,0.738,6,-5.883,0,0.247,0.0408,0,0.292,0.603,159.145,226160,4 3QwBODjSEzelZyVjxPOHd,Otra Vez (feat. J Balvin),Zion & Lennox,0.832,0.772,10,-5.429,1,0.1,0.0559,0.000486,0.44,0.704,96.016,209453,4 1wjzFQodRWrPcQ0AnYnvQ,I Like Me Better,Lauv,0.752,0.505,9,-7.621,1,0.253,0.535,2.55E-06,0.104,0.419,91.97,197437,4 04DwTuZ2VBdJCCC5TROn7,In the Name of Love,Martin Garrix,0.49,0.485,4,-6.237,0,0.0406,0.0592,0,0.337,0.196,133.889,195840,4 6DNtNfH8hXkqOX1sjqmI7,Cold Water (feat. Justin Bieber & MÌ÷),Major Lazer,0.608,0.798,6,-5.092,0,0.0432,0.0736,0,0.156,0.501,92.943,185352,4 1UZOjK1BwmwWU14Erba9C,Malibu,Miley Cyrus,0.573,0.781,8,-6.406,1,0.0555,0.0767,2.64E-05,0.0813,0.343,139.934,231907,4 4b4KcovePX8Ke2cLIQTLM,All Night,The Vamps,0.544,0.809,8,-5.098,1,0.0363,0.0038,0,0.323,0.448,145.017,197640,4 1a5Yu5L18qNxVhXx38njO,Hear Me Now,Alok,0.789,0.442,11,-7.844,1,0.0421,0.586,0.00366,0.0927,0.45,121.971,192846,4 4c2W3VKsOFoIg2SFaO6DY,Your Song,Rita Ora,0.855,0.624,1,-4.093,1,0.0488,0.158,0,0.0513,0.962,117.959,180757,4 22eADXu8DfOAUEDw4vU8q,Ahora Dice,Chris Jeday,0.708,0.693,6,-5.516,1,0.138,0.246,0,0.129,0.427,143.965,271080,4 7nZmah2llfvLDiUjm0kiy,Friends (with BloodPopå¨),Justin Bieber,0.744,0.739,8,-5.35,1,0.0387,0.00459,0,0.306,0.649,104.99,189467,4 2fQrGHiQOvpL9UgPvtYy6,Bank Account,21 Savage,0.884,0.346,8,-8.228,0,0.351,0.0151,7.04E-06,0.0871,0.376,75.016,220307,4 1PSBzsahR2AKwLJgx8ehB,Bad Things (with Camila Cabello),Machine Gun Kelly,0.675,0.69,2,-4.761,1,0.132,0.21,0,0.287,0.272,137.817,239293,4 0QsvXIfqM0zZoerQfsI9l,Don't Let Me Down,The Chainsmokers,0.542,0.859,11,-5.651,1,0.197,0.16,0.00466,0.137,0.403,159.797,208053,4 7mldq42yDuxiUNn08nvzH,Body Like A Back Road,Sam Hunt,0.731,0.469,5,-7.226,1,0.0326,0.463,1.04E-06,0.103,0.631,98.963,165387,4 7i2DJ88J7jQ8K7zqFX2fW,Now Or Never,Halsey,0.658,0.588,6,-4.902,0,0.0367,0.105,1.28E-06,0.125,0.434,110.075,214802,4 1j4kHkkpqZRBwE0A4CN4Y,Dusk Till Dawn - Radio Edit,ZAYN,0.258,0.437,11,-6.593,0,0.039,0.101,1.27E-06,0.106,0.0967,180.043,239000,4 \ No newline at end of file diff --git a/Students/Wayne/Assignments/Assignment_03/.ipynb_checkpoints/Assignment3_ContextManagers-checkpoint.ipynb b/Students/Wayne/Assignments/Assignment_03/.ipynb_checkpoints/Assignment3_ContextManagers-checkpoint.ipynb new file mode 100644 index 0000000..9aee836 --- /dev/null +++ b/Students/Wayne/Assignments/Assignment_03/.ipynb_checkpoints/Assignment3_ContextManagers-checkpoint.ipynb @@ -0,0 +1,147 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#Context Managers\n", + "\n", + "The Ballard LocksLinks to an external site. in Seattle, Washington are a limited, controlled resource. You have been hired by the Army Corps of Engineers to help build a software control system for the lockes. There are two lockes at the Ballard complex, one small (30 x 150 feet, 8.5 x 45.7 meter) and one large (80 x 825 feet, 24.4 x 251.5 meter). There are myriad ways in which different components of the lockes represent limited resources with specialized subsystems, and a missed or out-of-sequence step could mean disaster. For instance, there are two sets of doors for each locke, one upstream and one down, that cannot both be open at the same time; boats need to clear the doors before they are closed and sealed; pumps need to be shut down before doors are opened; tourists, who can get very close to observe the action, need to be safely managed; the lockes themselves can only handle a certain number of boats. At every step of the way there is a limited resource that must be managed and in lock step with the others, yes, pun intended. In effect it involves the coordinated management of resources all the way down.\n", + "\n", + "For this first task you do not need to model every aspect of the lockes, indeed you only need model its operation overall. Early on you learn that there will be other software developers interacting with the system and that not everyone is going to remember all the details of using the resources of each component. Your task is to model the use of resources, of system components, as simply as possible. You recognize that with all the operational and sequencing details to be encapsulated, this is a good use case for context managers.\n", + "\n", + "Wondering about the consistent misspelling of the word lock? As an early design decision we have decided to avoid overloading the term, which in the context can be interpreted both as a verb and as a noun and thereby cause confusion. For any instances of the verb use its usual spelling: lock. For any instances of the noun use an alternative spelling: locke. We have adopted this convention throughout the exercise.\n", + "\n", + "Write a context manager class Locke to simulate the overall functioning of the system. When the locke is entered it stops the pumps, opens the doors, closes the doors, and restarts the pumps. Likewise when the locke is exited it runs through the same steps: it stops the pumps, opens the doors, closes the doors, and restarts the pumps. Don’t worry for now that in the real world there are both upstream and downstream doors, and that they should never be opened at the same time; perhaps you’ll get to that later. During initialization the context manger class accepts the locke’s capacity in number of boats. If someone tries to move too many boats through the locke, anything over its established capacity, raise a suitable error. Since this is a simulation you need do nothing more than print what is happening with the doors and pumps, like this:" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Print Statements\n", + " \n", + " \"Stopping the pumps.\"\n", + " \"Opening the doors.\"\n", + " \"Closing the doors.\"\n", + " \"Restarting the pumps.\"" + ] + }, + { + "cell_type": "code", + "execution_count": 75, + "metadata": {}, + "outputs": [], + "source": [ + "class Locke():\n", + " def __init__(self, boats, locke=None, error=None):\n", + " self.boats = boats\n", + " self.locke = locke\n", + " self.error = error\n", + "\n", + " def __enter__(self):\n", + " if not self.error:\n", + " print('''Lock Status:\n", + " Stopping the pumps\n", + " Opening the doors\n", + " Closing the doors\n", + " Starting the pumps\n", + " ''')\n", + " return self\n", + "\n", + " def move_boats_through(self, boats, locke):\n", + " \n", + " if self.boats > self.locke:\n", + " raise ValueError('Too many boats for the locks')\n", + " else:\n", + " return self\n", + "\n", + " def __exit__(self, exc_type, exc_val, exc_tb):\n", + " if not self.error:\n", + " print('''Lock Status:\n", + " Stopping the pumps\n", + " Opening the doors\n", + " Closing the doors\n", + " Starting the pumps\n", + " ''')\n", + " return self.error\n", + "\n", + " " + ] + }, + { + "cell_type": "code", + "execution_count": 77, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Lock Status:\n", + " Stopping the pumps\n", + " Opening the doors\n", + " Closing the doors\n", + " Starting the pumps\n", + " \n", + "Lock Status:\n", + " Stopping the pumps\n", + " Opening the doors\n", + " Closing the doors\n", + " Starting the pumps\n", + " \n" + ] + }, + { + "ename": "TypeError", + "evalue": "'>' not supported between instances of 'int' and 'NoneType'", + "output_type": "error", + "traceback": [ + "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)", + "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[1;32m 7\u001b[0m \u001b[0;31m# Too many boats through a small locke will raise an exception\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 8\u001b[0m \u001b[0;32mwith\u001b[0m \u001b[0msmall_locke\u001b[0m \u001b[0;32mas\u001b[0m \u001b[0mlocke\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 9\u001b[0;31m \u001b[0mlocke\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mmove_boats_through\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mboats\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0mlocke\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 10\u001b[0m \u001b[0;31m# A lock with sufficient capacity can move boats without incident.\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 11\u001b[0m \u001b[0;32mwith\u001b[0m \u001b[0mlarge_locke\u001b[0m \u001b[0;32mas\u001b[0m \u001b[0mlocke\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", + "\u001b[0;32m\u001b[0m in \u001b[0;36mmove_boats_through\u001b[0;34m(self, boats, locke)\u001b[0m\n\u001b[1;32m 19\u001b[0m \u001b[0;31m#This is how you might interact with your Locke class.\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 20\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 21\u001b[0;31m \u001b[0;32mif\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mboats\u001b[0m \u001b[0;34m>\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mlocke\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 22\u001b[0m \u001b[0;32mraise\u001b[0m \u001b[0mValueError\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m'Too many boats for the locks'\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 23\u001b[0m \u001b[0;32melse\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", + "\u001b[0;31mTypeError\u001b[0m: '>' not supported between instances of 'int' and 'NoneType'" + ] + } + ], + "source": [ + "# Tests the Context Manager \n", + "\n", + "small_locke = Locke(5)\n", + "large_locke = Locke(10)\n", + "boats = 15\n", + "\n", + "# Too many boats through a small locke will raise an exception\n", + "with small_locke as locke:\n", + " locke.move_boats_through(boats,locke)\n", + "# A lock with sufficient capacity can move boats without incident.\n", + "with large_locke as locke:\n", + " locke.move_boats_through(boats,locke)\n", + "\n", + " " + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.6.5" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/Students/Wayne/Assignments/Assignment_03/.ipynb_checkpoints/Assignment3_Recursion-checkpoint.ipynb b/Students/Wayne/Assignments/Assignment_03/.ipynb_checkpoints/Assignment3_Recursion-checkpoint.ipynb new file mode 100644 index 0000000..12ff2be --- /dev/null +++ b/Students/Wayne/Assignments/Assignment_03/.ipynb_checkpoints/Assignment3_Recursion-checkpoint.ipynb @@ -0,0 +1,110 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Write a recursive solution for the factorial function.\n", + "\n", + "5!=5x4x3x2x1=120\n", + "\n", + "n n!\n", + "\n", + "0\t1\n", + "1\t1\n", + "2\t2\n", + "3\t6\n", + "4\t24\n", + "5\t120\n", + "6\t720\n", + "7\t5,040\n", + "8\t40,320\n", + "9\t362,880\n", + "10\t3,628,800" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [], + "source": [ + "## >>> from factorial import factorial\n", + "## >>> factorial(4)\n", + "\n", + "def factorial(n):\n", + "\tif n==1:\n", + "\t return 1\n", + "\treturn n*factorial(n-1)" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "120" + ] + }, + "execution_count": 2, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "factorial(5)" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000" + ] + }, + "execution_count": 3, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "factorial(100)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.6.5" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/Students/Wayne/Assignments/Assignment_03/Assignment3_ContextManagers.ipynb b/Students/Wayne/Assignments/Assignment_03/Assignment3_ContextManagers.ipynb new file mode 100644 index 0000000..9aee836 --- /dev/null +++ b/Students/Wayne/Assignments/Assignment_03/Assignment3_ContextManagers.ipynb @@ -0,0 +1,147 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#Context Managers\n", + "\n", + "The Ballard LocksLinks to an external site. in Seattle, Washington are a limited, controlled resource. You have been hired by the Army Corps of Engineers to help build a software control system for the lockes. There are two lockes at the Ballard complex, one small (30 x 150 feet, 8.5 x 45.7 meter) and one large (80 x 825 feet, 24.4 x 251.5 meter). There are myriad ways in which different components of the lockes represent limited resources with specialized subsystems, and a missed or out-of-sequence step could mean disaster. For instance, there are two sets of doors for each locke, one upstream and one down, that cannot both be open at the same time; boats need to clear the doors before they are closed and sealed; pumps need to be shut down before doors are opened; tourists, who can get very close to observe the action, need to be safely managed; the lockes themselves can only handle a certain number of boats. At every step of the way there is a limited resource that must be managed and in lock step with the others, yes, pun intended. In effect it involves the coordinated management of resources all the way down.\n", + "\n", + "For this first task you do not need to model every aspect of the lockes, indeed you only need model its operation overall. Early on you learn that there will be other software developers interacting with the system and that not everyone is going to remember all the details of using the resources of each component. Your task is to model the use of resources, of system components, as simply as possible. You recognize that with all the operational and sequencing details to be encapsulated, this is a good use case for context managers.\n", + "\n", + "Wondering about the consistent misspelling of the word lock? As an early design decision we have decided to avoid overloading the term, which in the context can be interpreted both as a verb and as a noun and thereby cause confusion. For any instances of the verb use its usual spelling: lock. For any instances of the noun use an alternative spelling: locke. We have adopted this convention throughout the exercise.\n", + "\n", + "Write a context manager class Locke to simulate the overall functioning of the system. When the locke is entered it stops the pumps, opens the doors, closes the doors, and restarts the pumps. Likewise when the locke is exited it runs through the same steps: it stops the pumps, opens the doors, closes the doors, and restarts the pumps. Don’t worry for now that in the real world there are both upstream and downstream doors, and that they should never be opened at the same time; perhaps you’ll get to that later. During initialization the context manger class accepts the locke’s capacity in number of boats. If someone tries to move too many boats through the locke, anything over its established capacity, raise a suitable error. Since this is a simulation you need do nothing more than print what is happening with the doors and pumps, like this:" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Print Statements\n", + " \n", + " \"Stopping the pumps.\"\n", + " \"Opening the doors.\"\n", + " \"Closing the doors.\"\n", + " \"Restarting the pumps.\"" + ] + }, + { + "cell_type": "code", + "execution_count": 75, + "metadata": {}, + "outputs": [], + "source": [ + "class Locke():\n", + " def __init__(self, boats, locke=None, error=None):\n", + " self.boats = boats\n", + " self.locke = locke\n", + " self.error = error\n", + "\n", + " def __enter__(self):\n", + " if not self.error:\n", + " print('''Lock Status:\n", + " Stopping the pumps\n", + " Opening the doors\n", + " Closing the doors\n", + " Starting the pumps\n", + " ''')\n", + " return self\n", + "\n", + " def move_boats_through(self, boats, locke):\n", + " \n", + " if self.boats > self.locke:\n", + " raise ValueError('Too many boats for the locks')\n", + " else:\n", + " return self\n", + "\n", + " def __exit__(self, exc_type, exc_val, exc_tb):\n", + " if not self.error:\n", + " print('''Lock Status:\n", + " Stopping the pumps\n", + " Opening the doors\n", + " Closing the doors\n", + " Starting the pumps\n", + " ''')\n", + " return self.error\n", + "\n", + " " + ] + }, + { + "cell_type": "code", + "execution_count": 77, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Lock Status:\n", + " Stopping the pumps\n", + " Opening the doors\n", + " Closing the doors\n", + " Starting the pumps\n", + " \n", + "Lock Status:\n", + " Stopping the pumps\n", + " Opening the doors\n", + " Closing the doors\n", + " Starting the pumps\n", + " \n" + ] + }, + { + "ename": "TypeError", + "evalue": "'>' not supported between instances of 'int' and 'NoneType'", + "output_type": "error", + "traceback": [ + "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)", + "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[1;32m 7\u001b[0m \u001b[0;31m# Too many boats through a small locke will raise an exception\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 8\u001b[0m \u001b[0;32mwith\u001b[0m \u001b[0msmall_locke\u001b[0m \u001b[0;32mas\u001b[0m \u001b[0mlocke\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 9\u001b[0;31m \u001b[0mlocke\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mmove_boats_through\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mboats\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0mlocke\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 10\u001b[0m \u001b[0;31m# A lock with sufficient capacity can move boats without incident.\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 11\u001b[0m \u001b[0;32mwith\u001b[0m \u001b[0mlarge_locke\u001b[0m \u001b[0;32mas\u001b[0m \u001b[0mlocke\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", + "\u001b[0;32m\u001b[0m in \u001b[0;36mmove_boats_through\u001b[0;34m(self, boats, locke)\u001b[0m\n\u001b[1;32m 19\u001b[0m \u001b[0;31m#This is how you might interact with your Locke class.\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 20\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 21\u001b[0;31m \u001b[0;32mif\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mboats\u001b[0m \u001b[0;34m>\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mlocke\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 22\u001b[0m \u001b[0;32mraise\u001b[0m \u001b[0mValueError\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m'Too many boats for the locks'\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 23\u001b[0m \u001b[0;32melse\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", + "\u001b[0;31mTypeError\u001b[0m: '>' not supported between instances of 'int' and 'NoneType'" + ] + } + ], + "source": [ + "# Tests the Context Manager \n", + "\n", + "small_locke = Locke(5)\n", + "large_locke = Locke(10)\n", + "boats = 15\n", + "\n", + "# Too many boats through a small locke will raise an exception\n", + "with small_locke as locke:\n", + " locke.move_boats_through(boats,locke)\n", + "# A lock with sufficient capacity can move boats without incident.\n", + "with large_locke as locke:\n", + " locke.move_boats_through(boats,locke)\n", + "\n", + " " + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.6.5" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/Students/Wayne/Assignments/Assignment_03/Assignment3_ContextManagers.py b/Students/Wayne/Assignments/Assignment_03/Assignment3_ContextManagers.py new file mode 100644 index 0000000..e1cb107 --- /dev/null +++ b/Students/Wayne/Assignments/Assignment_03/Assignment3_ContextManagers.py @@ -0,0 +1,34 @@ +# canvas submitting version + +class Locke(): + def __init__(self, boats, locke=None, error=None): + self.boats = boats + self.locke = locke + self.error = error + + def __enter__(self): + if not self.error: + print('''Lock Status: + Stopping the pumps + Opening the doors + Closing the doors + Starting the pumps + ''') + return self + + def move_boats_through(self, boats, locke): + + if self.boats > self.locke: + raise ValueError('Too many boats for the locks') + else: + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + if not self.error: + print('''Lock Status: + Stopping the pumps + Opening the doors + Closing the doors + Starting the pumps + ''') + return self.error \ No newline at end of file diff --git a/Students/Wayne/Assignments/Assignment_03/Assignment3_Recursion.ipynb b/Students/Wayne/Assignments/Assignment_03/Assignment3_Recursion.ipynb new file mode 100644 index 0000000..12ff2be --- /dev/null +++ b/Students/Wayne/Assignments/Assignment_03/Assignment3_Recursion.ipynb @@ -0,0 +1,110 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Write a recursive solution for the factorial function.\n", + "\n", + "5!=5x4x3x2x1=120\n", + "\n", + "n n!\n", + "\n", + "0\t1\n", + "1\t1\n", + "2\t2\n", + "3\t6\n", + "4\t24\n", + "5\t120\n", + "6\t720\n", + "7\t5,040\n", + "8\t40,320\n", + "9\t362,880\n", + "10\t3,628,800" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [], + "source": [ + "## >>> from factorial import factorial\n", + "## >>> factorial(4)\n", + "\n", + "def factorial(n):\n", + "\tif n==1:\n", + "\t return 1\n", + "\treturn n*factorial(n-1)" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "120" + ] + }, + "execution_count": 2, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "factorial(5)" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000" + ] + }, + "execution_count": 3, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "factorial(100)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.6.5" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/Students/Wayne/Assignments/Assignment_03/Assignment3_Recursion.py b/Students/Wayne/Assignments/Assignment_03/Assignment3_Recursion.py new file mode 100644 index 0000000..d33831e --- /dev/null +++ b/Students/Wayne/Assignments/Assignment_03/Assignment3_Recursion.py @@ -0,0 +1,15 @@ +# Finished inclass activity/assignment + +# Write a recursive solution for the factorial function. + +# 5!=5x4x3x2x1=120 + +# n n! + +# 0 1 1 1 2 2 3 6 4 24 5 120 6 720 7 5,040 8 40,320 9 362,880 10 3,628,800 + + +def factorial(n): + if n==1: + return 1 + return n*factorial(n- 1) \ No newline at end of file diff --git a/Students/Wayne/Assignments/Assignment_04/__pycache__/mailroom_oo.cpython-36.pyc b/Students/Wayne/Assignments/Assignment_04/__pycache__/mailroom_oo.cpython-36.pyc new file mode 100644 index 0000000..eaadb44 Binary files /dev/null and b/Students/Wayne/Assignments/Assignment_04/__pycache__/mailroom_oo.cpython-36.pyc differ diff --git a/Students/Wayne/Assignments/Assignment_04/json_save/.cache/v/cache/lastfailed b/Students/Wayne/Assignments/Assignment_04/json_save/.cache/v/cache/lastfailed new file mode 100644 index 0000000..051b538 --- /dev/null +++ b/Students/Wayne/Assignments/Assignment_04/json_save/.cache/v/cache/lastfailed @@ -0,0 +1,12 @@ +{ + "json_save/test/test_savables.py::test_bad_dicts[val4]": true, + "json_save/test/test_savables.py::test_basics": true, + "json_save/test/test_savables.py::test_basics[Tuple-val5]": true, + "json_save/test/test_savables.py::test_containers[Dict-val0]": true, + "json_save/test/test_savables.py::test_dicts[Dict-val0]": true, + "json_save/test/test_savables.py::test_dicts[Dict-val1]": true, + "json_save/test/test_savables.py::test_dicts[Dict-val2]": true, + "json_save/test/test_savables.py::test_dicts[Dict-val3]": true, + "json_save/test/test_savables.py::test_dicts[val10]": true, + "json_save/test/test_savables.py::test_dicts[val7]": true +} \ No newline at end of file diff --git a/Students/Wayne/Assignments/Assignment_04/json_save/json_save/README.txt b/Students/Wayne/Assignments/Assignment_04/json_save/json_save/README.txt new file mode 100644 index 0000000..a80b252 --- /dev/null +++ b/Students/Wayne/Assignments/Assignment_04/json_save/json_save/README.txt @@ -0,0 +1,4 @@ +This is a simple meta-class based system for saving objects in the JSON format. + +It can make any arbitrary class savable and re-loadable from JSON. + diff --git a/Students/Wayne/Assignments/Assignment_04/json_save/json_save/examples/example_dec.py b/Students/Wayne/Assignments/Assignment_04/json_save/json_save/examples/example_dec.py new file mode 100755 index 0000000..2e1a224 --- /dev/null +++ b/Students/Wayne/Assignments/Assignment_04/json_save/json_save/examples/example_dec.py @@ -0,0 +1,67 @@ +#!/usr/bin/env python + +""" +Examples of using json_save +""" + +import json_save.json_save_dec as js + + +# Examples using the decorator + +@js.json_save +class MyClass: + + x = js.Int() + y = js.Float() + lst = js.List() + + def __init__(self, x, lst): + self.x = x + self.lst = lst + + +@js.json_save +class OtherSaveable: + + foo = js.String() + bar = js.Int() + + def __init__(self, foo, bar): + self.foo = foo + self.bar = bar + + +# create one: +print("about to create a instance") +mc = MyClass(5, [3, 5, 7, 9]) + +print(mc) + +jc = mc.to_json_compat() + +# re-create it from the dict: +mc2 = MyClass.from_json_dict(jc) + +print(mc2 == "fred") + +assert mc2 == mc + +print(mc.to_json()) + +# now try it nested... +mc_nest = MyClass(34, [OtherSaveable("this", 2), + OtherSaveable("that", 64), + ]) + +mc_nest_comp = mc_nest.to_json_compat() +print(mc_nest_comp) + +# can we re-create it? +mc_nest2 = MyClass.from_json_dict(mc_nest_comp) + +print(mc_nest) +print(mc_nest2) + +assert mc_nest == mc_nest2 + diff --git a/Students/Wayne/Assignments/Assignment_04/json_save/json_save/examples/example_meta.py b/Students/Wayne/Assignments/Assignment_04/json_save/json_save/examples/example_meta.py new file mode 100755 index 0000000..13719ab --- /dev/null +++ b/Students/Wayne/Assignments/Assignment_04/json_save/json_save/examples/example_meta.py @@ -0,0 +1,63 @@ +#!/usr/bin/env python + +""" +Examples of using json_save +""" + +import json_save.json_save_meta as js + +# Metaclass examples + +class MyClass(js.JsonSaveable): + + x = js.Int() + y = js.Float() + lst = js.List() + + def __init__(self, x, lst): + self.x = x + self.lst = lst + + +class OtherSaveable(js.JsonSaveable): + + foo = js.String() + bar = js.Int() + + def __init__(self, foo, bar): + self.foo = foo + self.bar = bar + +# create one: +print("about to create a instance") +mc = MyClass(5, [3, 5, 7, 9]) + +print(mc) + +jc = mc.to_json_compat() + +# re-create it from the dict: +mc2 = MyClass.from_json_dict(jc) + +print(mc2 == "fred") + +assert mc2 == mc + +print(mc.to_json()) + +# now try it nested... +mc_nest = MyClass(34, [OtherSaveable("this", 2), + OtherSaveable("that", 64), + ]) + +mc_nest_comp = mc_nest.to_json_compat() +print(mc_nest_comp) + +# can we re-create it? +mc_nest2 = MyClass.from_json_dict(mc_nest_comp) + +print(mc_nest) +print(mc_nest2) + +assert mc_nest == mc_nest2 + diff --git a/Students/Wayne/Assignments/Assignment_04/json_save/json_save/json_save/__init__.py b/Students/Wayne/Assignments/Assignment_04/json_save/json_save/json_save/__init__.py new file mode 100644 index 0000000..db59bd9 --- /dev/null +++ b/Students/Wayne/Assignments/Assignment_04/json_save/json_save/json_save/__init__.py @@ -0,0 +1,8 @@ +""" +json_save package + +Pulling in names from the other packages. +""" + +__version__ = "0.4.0" + diff --git a/Students/Wayne/Assignments/Assignment_04/json_save/json_save/json_save/__pycache__/__init__.cpython-36.pyc b/Students/Wayne/Assignments/Assignment_04/json_save/json_save/json_save/__pycache__/__init__.cpython-36.pyc new file mode 100644 index 0000000..3f20e63 Binary files /dev/null and b/Students/Wayne/Assignments/Assignment_04/json_save/json_save/json_save/__pycache__/__init__.cpython-36.pyc differ diff --git a/Students/Wayne/Assignments/Assignment_04/json_save/json_save/json_save/__pycache__/json_save_dec.cpython-36.pyc b/Students/Wayne/Assignments/Assignment_04/json_save/json_save/json_save/__pycache__/json_save_dec.cpython-36.pyc new file mode 100644 index 0000000..abdfbff Binary files /dev/null and b/Students/Wayne/Assignments/Assignment_04/json_save/json_save/json_save/__pycache__/json_save_dec.cpython-36.pyc differ diff --git a/Students/Wayne/Assignments/Assignment_04/json_save/json_save/json_save/__pycache__/json_save_meta.cpython-36.pyc b/Students/Wayne/Assignments/Assignment_04/json_save/json_save/json_save/__pycache__/json_save_meta.cpython-36.pyc new file mode 100644 index 0000000..68b6e44 Binary files /dev/null and b/Students/Wayne/Assignments/Assignment_04/json_save/json_save/json_save/__pycache__/json_save_meta.cpython-36.pyc differ diff --git a/Students/Wayne/Assignments/Assignment_04/json_save/json_save/json_save/__pycache__/saveables.cpython-36.pyc b/Students/Wayne/Assignments/Assignment_04/json_save/json_save/json_save/__pycache__/saveables.cpython-36.pyc new file mode 100644 index 0000000..f2ed72f Binary files /dev/null and b/Students/Wayne/Assignments/Assignment_04/json_save/json_save/json_save/__pycache__/saveables.cpython-36.pyc differ diff --git a/Students/Wayne/Assignments/Assignment_04/json_save/json_save/json_save/json_save_dec.py b/Students/Wayne/Assignments/Assignment_04/json_save/json_save/json_save/json_save_dec.py new file mode 100644 index 0000000..842b8c0 --- /dev/null +++ b/Students/Wayne/Assignments/Assignment_04/json_save/json_save/json_save/json_save_dec.py @@ -0,0 +1,147 @@ +#!/usr/bin/env python + +""" +json_save implemented as a decorator +""" + +import json +from pathlib import Path + +from json_save_meta import * + + + +# assorted methods that will need to be added to the decorated class: +def _to_json_compat(self): + """ + converts this object to a json-compatible dict. + + returns the dict + """ + # add and __obj_type attribute, so it can be reconstructed + dic = {"__obj_type": self.__class__.__qualname__} + for attr, typ in self._attrs_to_save.items(): + dic[attr] = typ.to_json_compat(getattr(self, attr)) + return dic + + +def __eq__(self, other): + """ + default equality method that checks if all of the saved attributes + are equal + """ + for attr in self._attrs_to_save: + try: + if getattr(self, attr) != getattr(other, attr): + return False + except AttributeError: + return False + return True + +@classmethod +def _from_json_dict(cls, dic): + """ + creates an instance of this class populated by the contents of + the json compatible dict + + the object is created with __new__ before setting the attributes + + NOTE: __init__ is not called. + There should not be any extra initialization required in __init__ + """ + # create a new object + obj = cls.__new__(cls) + for attr, typ in cls._attrs_to_save.items(): + setattr(obj, attr, typ.to_python(dic[attr])) + return obj + + +def __new__(cls, *args, **kwargs): + """ + This adds instance attributes to assure they are all there, even if + they are not set in the subclasses __init__ + + it's in __new__ so that it will get called before the decorated class' + __init__ -- the __init__ will override anything here. + """ + # create the instance by calling the base class __new__ + obj = cls.__base__.__new__(cls) + # using super() did not work here -- why?? + # set the instance attributes to defaults + for attr, typ in cls._attrs_to_save.items(): + setattr(obj, attr, typ.default) + return obj + + +def _to_json(self, fp=None, indent=4): + """ + Converts the object to JSON + + :param fp=None: an open file_like object to write the json to. + If it is None, then a string with the JSON + will be returned as a string + + :param indent=4: The indentation level desired in the JSON + """ + if fp is None: + return json.dumps(self.to_json_compat(), indent=indent) + else: + json.dump(self.to_json_compat(), fp, indent=indent) + + +# now the actual decorator +def json_save(cls): + """ + json_save decorator + + makes decorated classes Saveable to json + """ + # make sure this is decorating a class object + if type(cls) is not type: + raise TypeError("json_save can only be used on classes") + + # find the saveable attributes + # these will the attributes that get saved and reconstructed from json. + # each class object gets its own dict + attr_dict = vars(cls) + cls._attrs_to_save = {} + for key, attr in attr_dict.items(): + if isinstance(attr, Saveable): + cls._attrs_to_save[key] = attr + if not cls._attrs_to_save: + raise TypeError(f"{cls.__name__} class has no saveable attributes.\n" + " Note that Savable attributes must be instances") + # register this class so we can re-construct instances. + Saveable.ALL_SAVEABLES[cls.__qualname__] = cls + + # add the methods: + cls.__new__ = __new__ + cls.to_json_compat = _to_json_compat + cls.__eq__ = __eq__ + cls.from_json_dict = _from_json_dict + cls.to_json = _to_json + + return cls + + +# utilities for loading arbitrary objects from json +def from_json_dict(j_dict): + """ + factory function that creates an arbitrary JsonSaveable + object from a json-compatible dict. + """ + # determine the class it is. + obj_type = j_dict["__obj_type"] + obj = Saveable.ALL_SAVEABLES[obj_type].from_json_dict(j_dict) + return obj + + +def from_json(_json): + """ + Factory function that re-creates a JsonSaveable object + from a json string or file + """ + if isinstance(_json, (str, Path)): + return from_json_dict(json.loads(_json)) + else: # assume a file-like object + return from_json_dict(json.load(_json)) diff --git a/Students/Wayne/Assignments/Assignment_04/json_save/json_save/json_save/json_save_meta.py b/Students/Wayne/Assignments/Assignment_04/json_save/json_save/json_save/json_save_meta.py new file mode 100644 index 0000000..c853b64 --- /dev/null +++ b/Students/Wayne/Assignments/Assignment_04/json_save/json_save/json_save/json_save_meta.py @@ -0,0 +1,211 @@ +#!/usr/bin/env python3 + +""" +json_save + +metaclass based system for saving objects in a JSON format + +This could be useful, but it's kept simple to show the use of metaclasses + +The idea is that you subclass from JsonSavable, and then you get an object +that be saved and reloaded to/from JSON +""" + +import json + +# import * is a bad idea in general, but helpful for a modules that's part +# of a package, where you control the names. +from saveables import * + + +class MetaJsonSaveable(type): + """ + The metaclass for creating JsonSavable classes + + Deriving from type makes it a metaclass. + + Note: the __init__ gets run at compile time, not run time. + (module import time) + """ + def __init__(cls, name, bases, attr_dict): + # it gets the class object as the first param. + # and then the same parameters as the type() factory function + + # you want to call the regular type initilizer: + super().__init__(name, bases, attr_dict) + + # here's where we work with the class attributes: + # these will the attributes that get saved and reconstructed from json. + # each class object gets its own dict + cls._attrs_to_save = {} + for key, attr in attr_dict.items(): + if isinstance(attr, Saveable): + cls._attrs_to_save[key] = attr + # special case JsonSaveable -- no attrs to save yet + if cls.__name__ != "JsonSaveable" and (not cls._attrs_to_save): + raise TypeError(f"{cls.__name__} class has no saveable attributes.\n" + " Note that Savable attributes must be instances") + + # register this class so we can re-construct instances. + Saveable.ALL_SAVEABLES[attr_dict["__qualname__"]] = cls + + +class JsonSaveable(metaclass=MetaJsonSaveable): + """ + mixin for JsonSavable objects + """ + def __new__(cls, *args, **kwargs): + """ + This adds instance attributes to assure they are all there, even if + they are not set in the subclasses __init__ + """ + # create the instance + obj = super().__new__(cls) + # set the instance attributes to defaults + for attr, typ in cls._attrs_to_save.items(): + setattr(obj, attr, typ.default) + return obj + + def __eq__(self, other): + """ + default equality method that checks if all of the saved attributes + are equal + """ + for attr in self._attrs_to_save: + try: + if getattr(self, attr) != getattr(other, attr): + return False + except AttributeError: + return False + return True + + def to_json_compat(self): + """ + converts this object to a json-compatible dict. + + returns the dict + """ + # add and __obj_type attribute, so it can be reconstructed + dic = {"__obj_type": self.__class__.__qualname__} + for attr, typ in self._attrs_to_save.items(): + dic[attr] = typ.to_json_compat(getattr(self, attr)) + return dic + + @classmethod + def from_json_dict(cls, dic): + """ + creates an instance of this class populated by the contents of + the json compatible dict + + the object is created with __new__ before setting the attributes + + NOTE: __init__ is not called. + There should not be any extra initialization required in __init__ + """ + # create a new object + obj = cls.__new__(cls) + for attr, typ in cls._attrs_to_save.items(): + setattr(obj, attr, typ.to_python(dic[attr])) + # make sure it gets initialized + # obj.__init__() + return obj + + def to_json(self, fp=None, indent=4): + """ + Converts the object to JSON + + :param fp=None: an open file_like object to write the json to. + If it is None, then a string with the JSON + will be returned as a string + + :param indent=4: The indentation level desired in the JSON + """ + if fp is None: + return json.dumps(self.to_json_compat(), indent=indent) + else: + json.dump(self.to_json_compat(), fp, indent=indent) + + def __str__(self): + msg = ["{} object, with attributes:".format(self.__class__.__qualname__)] + for attr in self._attrs_to_save.keys(): + msg.append("{}: {}".format(attr, getattr(self, attr))) + return "\n".join(msg) + + +def from_json_dict(j_dict): + """ + factory function that creates an arbitrary JsonSavable + object from a json-compatible dict. + """ + # determine the class it is. + obj_type = j_dict["__obj_type"] + obj = Saveable.ALL_SAVEABLES[obj_type].from_json_dict(j_dict) + return obj + + +def from_json(_json): + """ + factory function that re-creates a JsonSavable object + from a json string or file + """ + if isinstance(_json, str): + return from_json_dict(json.loads(_json)) + else: # assume a file-like object + return from_json_dict(json.load(_json)) + + +# if __name__ == "__main__": + +# # Example of using it. + # class MyClass(JsonSaveable): + + # x = Int() + # y = Float() + # l = List() + + # def __init__(self, x, lst): + # self.x = x + # self.lst = lst + + + # class OtherSaveable(JsonSavable): + + # foo = String() + # bar = Int() + + # def __init__(self, foo, bar): + # self.foo = foo + # self.bar = bar + + # # create one: + # print("about to create a instance") + # mc = MyClass(5, [3, 5, 7, 9]) + + # print(mc) + + # jc = mc.to_json_compat() + + # # re-create it from the dict: + # mc2 = MyClass.from_json_dict(jc) + + # print(mc2 == "fred") + + # assert mc2 == mc + + # print(mc.to_json()) + + # # now try it nested... + # mc_nest = MyClass(34, [OtherSaveable("this", 2), + # OtherSaveable("that", 64), + # ]) + + # mc_nest_comp = mc_nest.to_json_compat() + # print(mc_nest_comp) + + # # can we re-create it? + # mc_nest2 = MyClass.from_json_dict(mc_nest_comp) + + # print(mc_nest) + # print(mc_nest2) + + # assert mc_nest == mc_nest2 \ No newline at end of file diff --git a/Students/Wayne/Assignments/Assignment_04/json_save/json_save/json_save/saveables.py b/Students/Wayne/Assignments/Assignment_04/json_save/json_save/json_save/saveables.py new file mode 100644 index 0000000..16ac75f --- /dev/null +++ b/Students/Wayne/Assignments/Assignment_04/json_save/json_save/json_save/saveables.py @@ -0,0 +1,218 @@ +#!/usr/bin/env python + +""" +The Saveable objects used by both the metaclass and decorator approach. +""" +import ast + +# import json + +__all__ = ['Bool', + 'Dict', + 'Float', + 'Int', + 'List', + 'Saveable', + 'String', + 'Tuple', + ] + + +class Saveable(): + """ + Base class for all saveable types + """ + default = None + ALL_SAVEABLES = {} + + @staticmethod + def to_json_compat(val): + """ + returns a json-compatible version of val + + should be overridden in saveable types that are not json compatible. + """ + return val + + @staticmethod + def to_python(val): + """ + convert from a json compatible version to the python version + + Must be overridden if not a one-to-one match + + This is where validation could be added as well. + """ + return val + + +class String(Saveable): + """ + A Saveable string + + Strings are the same in JSON as Python, so nothing to do here + """ + default = "" + + +class Bool(Saveable): + """ + A Saveable boolean + + Booleans are pretty much the same in JSON as Python, so nothing to do here + """ + default = False + + +class Int(Saveable): + + """ + A Saveable integer + + Integers are a little different in JSON than Python. Strictly speaking + JSON only has "numbers", which can be integer or float, so a little to + do here to make sure we get an int in Python. + """ + + default = 0 + + @staticmethod + def to_python(val): + """ + Convert a number to a python integer + """ + return int(val) + + +class Float(Saveable): + """ + A Saveable floating point number + + floats are a little different in JSON than Python. Strictly speaking + JSON only has "numbers", which can be integer or float, so a little to + do here to make sure we get a float in Python. + """ + + default = 0.0 + + @staticmethod + def to_python(val): + """ + Convert a number to a python float + """ + return float(val) + +# Container types: these need to hold Saveable objects. + + +class Tuple(Saveable): + """ + This assumes that whatever is in the tuple is Saveable or a "usual" + type: numbers, strings. + """ + default = () + + @staticmethod + def to_python(val): + """ + Convert a list to a tuple -- json only has one array type, + which matches to a list. + """ + # simply uses the List to_python method -- that part is the same. + return tuple(List.to_python(val)) + + +class List(Saveable): + """ + This assumes that whatever is in the list is Saveable or a "usual" + type: numbers, strings. + """ + default = [] + + @staticmethod + def to_json_compat(val): + lst = [] + for item in val: + try: + lst.append(item.to_json_compat()) + except AttributeError: + lst.append(item) + return lst + + @staticmethod + def to_python(val): + """ + Convert an array to a list. + + Complicated because list may contain non-json-compatible objects + """ + # try to reconstitute using the obj method + new_list = [] + for item in val: + try: + obj_type = item["__obj_type"] + obj = Saveable.ALL_SAVEABLES[obj_type].from_json_dict(item) + new_list.append(obj) + except (TypeError, KeyError): + new_list.append(item) + return new_list + + +class Dict(Saveable): + """ + This assumes that whatever in the dict is Saveable as well. + + This supports non-string keys, but all keys must be the same type. + """ + default = {} + + @staticmethod + def to_json_compat(val): + d = {} + # first key, arbitrarily + key_type = type(next(iter(val.keys()))) + if key_type is not str: + # need to add key_type to json + d['__key_not_string'] = True + key_not_string = True + else: + key_not_string = False + for key, item in val.items(): + kis = type(key) is str + if ((kis and key_not_string) or (not (kis or key_not_string))): + raise TypeError("dict keys must be all strings or no strings") + if key_type is not str: + # convert key to string + s_key = repr(key) + # make sure it can be reconstituted + if ast.literal_eval(s_key) != key: + raise ValueError(f"json save cannot save dicts with key:{key}") + else: + s_key = key + try: + d[s_key] = item.to_json_compat() + except AttributeError: + d[s_key] = item + return d + + @staticmethod + def to_python(val): + """ + Convert a json object to a dict + + Complicated because object may contain non-json-compatible objects + """ + + # try to reconstitute using the obj method + new_dict = {} + key_not_string = val.pop('__key_not_string', False) + for key, item in val.items(): + if key_not_string: + key = ast.literal_eval(key) + try: + obj_type = item["__obj_type"] + obj = Saveable.ALL_SAVEABLES[obj_type].from_json_dict(item) + new_dict[key] = obj + except (KeyError, TypeError): + new_dict[key] = item + return new_dict diff --git a/Students/Wayne/Assignments/Assignment_04/json_save/json_save/json_save/test/__init__.py b/Students/Wayne/Assignments/Assignment_04/json_save/json_save/json_save/test/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/Students/Wayne/Assignments/Assignment_04/json_save/json_save/json_save/test/temp.json b/Students/Wayne/Assignments/Assignment_04/json_save/json_save/json_save/test/temp.json new file mode 100644 index 0000000..760c652 --- /dev/null +++ b/Students/Wayne/Assignments/Assignment_04/json_save/json_save/json_save/test/temp.json @@ -0,0 +1,21 @@ +{ + "__obj_type": "ClassWithList", + "x": 34, + "lst": [ + { + "__obj_type": "SimpleClass", + "a": 3, + "b": 4.5 + }, + { + "__obj_type": "SimpleClass", + "a": 100, + "b": 5.2 + }, + { + "__obj_type": "SimpleClass", + "a": 34, + "b": 89.1 + } + ] +} \ No newline at end of file diff --git a/Students/Wayne/Assignments/Assignment_04/json_save/json_save/json_save/test/test_json_save_dec.py b/Students/Wayne/Assignments/Assignment_04/json_save/json_save/json_save/test/test_json_save_dec.py new file mode 100644 index 0000000..f587517 --- /dev/null +++ b/Students/Wayne/Assignments/Assignment_04/json_save/json_save/json_save/test/test_json_save_dec.py @@ -0,0 +1,256 @@ +#!/usr/bin/env python + +""" +test code for the decorator version of json_save +""" + +import pytest + +import json_save.json_save_dec as js + + +# Some simple classes to test: + +@js.json_save +class NoInit: + """ + A class with saveable attribute, but no __init__ + """ + x = js.Int() + y = js.String() + + +@js.json_save +class SimpleClass: + + a = js.Int() + b = js.Float() + + def __init__(self, a=None, b=None): + if a is not None: + self.a = a + if b is not None: + self.b = b + + +@js.json_save +class ClassWithList: + + x = js.Int() + lst = js.List() + + def __init__(self, x, lst): + self.x = x + self.lst = lst + + +@js.json_save +class ClassWithDict: + x = js.Int() + d = js.Dict() + + def __init__(self, x, d): + self.x = x + self.d = d + + +@pytest.fixture +def nested_example(): + l = [SimpleClass(3, 4.5), + SimpleClass(100, 5.2), + SimpleClass(34, 89.1), + ] + + return ClassWithList(34, l) + +@pytest.fixture +def nested_dict(): + d = {'this': SimpleClass(3, 4.5), + 'that': SimpleClass(100, 5.2), + 'other': SimpleClass(34, 89.1), + } + + return ClassWithDict(34, d) + + +# now the actual test code + +def test_hasattr(): + """ + checks that the default attributes get set if they are not created by an __init__ + """ + ts = NoInit() + # has the instance attributes even though no __init__ exists + # they should be the default values + assert ts.x == 0 + assert ts.y == "" + + +def test_attrs(): + ts = SimpleClass() + + attrs = ts._attrs_to_save + assert list(attrs.keys()) == ['a', 'b'] + + +def test_simple_save(): + + ts = SimpleClass() + ts.a = 5 + ts.b = 3.14 + + saved = ts.to_json_compat() + assert saved['a'] == 5 + assert saved['b'] == 3.14 + assert saved['__obj_type'] == 'SimpleClass' + + +def test_list_attr(): + + cwl = ClassWithList(10, [1, 5, 2, 8]) + + saved = cwl.to_json_compat() + assert saved['x'] == 10 + assert saved['lst'] == [1, 5, 2, 8] + assert saved['__obj_type'] == 'ClassWithList' + + +def test_nested(nested_example): + + saved = nested_example.to_json_compat() + + assert saved['x'] == 34 + assert len(saved['lst']) == 3 + for obj in saved['lst']: + assert obj['__obj_type'] == 'SimpleClass' + + +def test_save_load_simple(): + sc = SimpleClass(5, 3.14) + + jc = sc.to_json_compat() + + # re-create it from the dict: + sc2 = SimpleClass.from_json_dict(jc) + + assert sc == sc2 + + +def test_save_load_nested(nested_example): + + jc = nested_example.to_json_compat() + + # re-create it from the dict: + nested_example2 = ClassWithList.from_json_dict(jc) + + assert nested_example == nested_example2 + + +def test_from_json_dict(nested_example): + + j_dict = nested_example.to_json_compat() + + reconstructed = js.from_json_dict(j_dict) + + assert reconstructed == nested_example + + +def test_from_json(nested_example): + """ + can it be re-created from an actual json string? + """ + + json_str = nested_example.to_json() + + reconstructed = js.from_json(json_str) + + assert reconstructed == nested_example + + +def test_from_json_file(nested_example): + """ + can it be re-created from an actual json file? + """ + + json_str = nested_example.to_json() + with open("temp.json", 'w') as tempfile: + tempfile.write(nested_example.to_json()) + + with open("temp.json") as tempfile: + reconstructed = js.from_json(tempfile) + + reconstructed = js.from_json(json_str) + + assert reconstructed == nested_example + + +def test_dict(): + """ + a simple class with a dict attribute + """ + cwd = ClassWithDict(45, {"this": 34, "that": 12}) + + # see if it can be reconstructed + + jc = cwd.to_json_compat() + + # re-create it from the dict: + cwd2 = ClassWithDict.from_json_dict(jc) + + assert cwd == cwd2 + + +def test_from_json_dict2(nested_dict): + """ + can it be re-created from an actual json string? + """ + + json_str = nested_dict.to_json() + reconstructed = js.from_json(json_str) + + assert reconstructed == nested_dict + + +def test_eq(): + sc1 = SimpleClass(3, 4.5) + sc2 = SimpleClass(3, 4.5) + + assert sc1 == sc2 + + +def test_not_eq(): + sc1 = SimpleClass(3, 4.5) + sc2 = SimpleClass(3, 4.4) + + assert sc1 != sc2 + + +def test_not_eq_reconstruct(): + sc1 = SimpleClass.from_json_dict(SimpleClass(3, 4.5).to_json_compat()) + sc2 = SimpleClass.from_json_dict(SimpleClass(2, 4.5).to_json_compat()) + + assert sc1 != sc2 + assert sc2 != sc1 + + +def test_not_valid(): + """ + You should get an error trying to make a savable class with + no savable attributes. + """ + with pytest.raises(TypeError): + @js.json_save + class NotValid(): + pass + + +def test_not_valid_class_not_instance(): + """ + You should get an error trying to make a savable class with + no savable attributes. + """ + with pytest.raises(TypeError): + @js.json_save + class NotValid(): + a = js.Int + b = js.Float diff --git a/Students/Wayne/Assignments/Assignment_04/json_save/json_save/json_save/test/test_json_save_meta.py b/Students/Wayne/Assignments/Assignment_04/json_save/json_save/json_save/test/test_json_save_meta.py new file mode 100644 index 0000000..2f42c22 --- /dev/null +++ b/Students/Wayne/Assignments/Assignment_04/json_save/json_save/json_save/test/test_json_save_meta.py @@ -0,0 +1,235 @@ +#!/usr/bin/env python3 + +""" +tests for json_save +""" + +import json_save.json_save_meta as js + +import pytest + + +class NoInit(js.JsonSaveable): + x = js.Int() + y = js.String() + + +# A few simple examples to test +class SimpleClass(js.JsonSaveable): + + a = js.Int() + b = js.Float() + + def __init__(self, a=None, b=None): + if a is not None: + self.a = a + if b is not None: + self.b = b + + +class ClassWithList(js.JsonSaveable): + + x = js.Int() + lst = js.List() + + def __init__(self, x, lst): + self.x = x + self.lst = lst + + +class ClassWithDict(js.JsonSaveable): + x = js.Int() + d = js.Dict() + + def __init__(self, x, d): + self.x = x + self.d = d + + +@pytest.fixture +def nested_example(): + lst = [SimpleClass(3, 4.5), + SimpleClass(100, 5.2), + SimpleClass(34, 89.1), + ] + + return ClassWithList(34, lst) + + +@pytest.fixture +def nested_dict(): + d = {'this': SimpleClass(3, 4.5), + 'that': SimpleClass(100, 5.2), + 'other': SimpleClass(34, 89.1), + } + + return ClassWithDict(34, d) + + +def test_hasattr(): + ts = NoInit() + # has the attributes even though no __init__ exists + # they should be the default values + assert ts.x == 0 + assert ts.y == "" + + +def test_simple_save(): + + ts = SimpleClass() + ts.a = 5 + ts.b = 3.14 + + saved = ts.to_json_compat() + assert saved['a'] == 5 + assert saved['b'] == 3.14 + assert saved['__obj_type'] == 'SimpleClass' + + +def test_list_attr(): + + cwl = ClassWithList(10, [1, 5, 2, 8]) + + saved = cwl.to_json_compat() + assert saved['x'] == 10 + assert saved['lst'] == [1, 5, 2, 8] + assert saved['__obj_type'] == 'ClassWithList' + + +def test_nested(nested_example): + + saved = nested_example.to_json_compat() + + assert saved['x'] == 34 + assert len(saved['lst']) == 3 + for obj in saved['lst']: + assert obj['__obj_type'] == 'SimpleClass' + + +def test_save_load_simple(): + sc = SimpleClass(5, 3.14) + + jc = sc.to_json_compat() + + # re-create it from the dict: + sc2 = SimpleClass.from_json_dict(jc) + + assert sc == sc2 + + +def test_save_load_nested(nested_example): + + jc = nested_example.to_json_compat() + + # re-create it from the dict: + nested_example2 = ClassWithList.from_json_dict(jc) + + assert nested_example == nested_example2 + + +def test_from_json_dict(nested_example): + + j_dict = nested_example.to_json_compat() + + reconstructed = js.from_json_dict(j_dict) + + assert reconstructed == nested_example + + +def test_from_json(nested_example): + """ + can it be re-created from an actual json string? + """ + + json_str = nested_example.to_json() + + reconstructed = js.from_json(json_str) + + assert reconstructed == nested_example + + +def test_from_json_file(nested_example): + """ + can it be re-created from an actual json file? + """ + + json_str = nested_example.to_json() + with open("temp.json", 'w') as tempfile: + tempfile.write(nested_example.to_json()) + + with open("temp.json") as tempfile: + reconstructed = js.from_json(tempfile) + + reconstructed = js.from_json(json_str) + + assert reconstructed == nested_example + + +def test_dict(): + """ + a simple class with a dict attribute + """ + cwd = ClassWithDict(45, {"this": 34, "that": 12}) + + # see if it can be reconstructed + + jc = cwd.to_json_compat() + + # re-create it from the dict: + cwd2 = ClassWithDict.from_json_dict(jc) + + assert cwd == cwd2 + + +def test_from_json_dict2(nested_dict): + """ + can it be re-created from an actual json string? + """ + + json_str = nested_dict.to_json() + + reconstructed = js.from_json(json_str) + + assert reconstructed == nested_dict + +def test_eq(): + sc1 = SimpleClass(3, 4.5) + sc2 = SimpleClass(3, 4.5) + + assert sc1 == sc2 + + +def test_not_eq(): + sc1 = SimpleClass(3, 4.5) + sc2 = SimpleClass(3, 4.4) + + assert sc1 != sc2 + + +def test_not_eq_reconstruct(): + sc1 = SimpleClass.from_json_dict(SimpleClass(3, 4.5).to_json_compat()) + sc2 = SimpleClass.from_json_dict(SimpleClass(2, 4.5).to_json_compat()) + + assert sc1 != sc2 + assert sc2 != sc1 + + +def test_not_valid(): + """ + You should get an error trying to make a savable class with + no savable attributes. + """ + with pytest.raises(TypeError): + class NotValid(js.JsonSaveable): + pass + + +def test_not_valid_class_not_instance(): + """ + You should get an error trying to make a savable class with + no savable attributes. + """ + with pytest.raises(TypeError): + class NotValid(js.JsonSaveable): + a = js.Int + b = js.Float diff --git a/Students/Wayne/Assignments/Assignment_04/json_save/json_save/json_save/test/test_savables.py b/Students/Wayne/Assignments/Assignment_04/json_save/json_save/json_save/test/test_savables.py new file mode 100644 index 0000000..831374c --- /dev/null +++ b/Students/Wayne/Assignments/Assignment_04/json_save/json_save/json_save/test/test_savables.py @@ -0,0 +1,87 @@ +#!/usr/bin/env python + +""" +tests for the savable objects +""" +import pytest + +import json + +from json_save.saveables import * + +# The simple, almost json <-> python ones: +# Type, default, example +basics = [(String, "This is a string"), + (Int, 23), + (Float, 3.1458), + (Bool, True), + (Bool, False), + (List, [2, 3, 4]), + (Tuple, (1, 2, 3.4, "this")), + (List, [[1, 2, 3], [4, 5, 6]]), + (List, [{"3": 34}, {"4": 5}]), # list with dicts in it. + (Dict, {"this": {"3": 34}, "that": {"4": 5}}) # dict with dicts + ] + + +@pytest.mark.parametrize(('Type', 'val'), basics) +def test_basics(Type, val): + js = json.dumps(Type.to_json_compat(val)) + val2 = Type.to_python(json.loads(js)) + assert val == val2 + assert type(val) == type(val2) + + +nested = [(List, [(1, 2), (3, 4), (5, 6)]), # tuple in list + (Tuple, ((1, 2), (3, 4), (5, 6))), # tuple in tuple + ] + + +# This maybe should be fixed in the future?? +@pytest.mark.xfail(reason="nested not-standard types not supported") +@pytest.mark.parametrize(('Type', 'val'), nested) +def test_nested(Type, val): + print("original value:", val) + js = json.dumps(Type.to_json_compat(val)) + print("js is:", js) + val2 = Type.to_python(json.loads(js)) + print("new value is:", val2) + assert val == val2 + assert type(val) == type(val2) + + + + +dicts = [{"this": 14, "that": 1.23}, + {34: 15, 23: 5}, + {3.4: "float_key", 1.2: "float_key"}, + {(1, 2, 3): "tuple_key"}, + {(3, 4, 5): "tuple_int", ("this", "that"): "tuple_str"}, + {4: "int_key", 1.23: "float_key", (1, 2, 3): "tuple_key"}, + ] + + +@pytest.mark.parametrize('val', dicts) +def test_dicts(val): + js = json.dumps(Dict.to_json_compat(val)) + val2 = Dict.to_python(json.loads(js)) + assert val == val2 + assert type(val) == type(val2) + # check that the types of the keys is the same + for k1, k2 in zip(val.keys(), val2.keys()): + assert type(k1) is type(k2) + + +# These are dicts that can't be saved +# -- mixing string and non-string keys +bad_dicts = [{"this": "string_key", 4: "int_key"}, + {3: "int_key", "this": "string_key"}, + {None: "none_key", "this": "string_key"}, + {"this": "string_key", None: "none_key"}, + ] + + +@pytest.mark.parametrize("val", bad_dicts) +def test_bad_dicts(val): + with pytest.raises(TypeError): + Dict.to_json_compat(val) diff --git a/Students/Wayne/Assignments/Assignment_04/json_save/json_save/setup.py b/Students/Wayne/Assignments/Assignment_04/json_save/json_save/setup.py new file mode 100755 index 0000000..d85dd95 --- /dev/null +++ b/Students/Wayne/Assignments/Assignment_04/json_save/json_save/setup.py @@ -0,0 +1,36 @@ +#!/usr/bin/env python + +""" +This is about as simple a setup.py as you can have + +But its enough to support the json_save package + +""" + +import os + +from setuptools import setup, find_packages + + +def get_version(): + """ + Reads the version string from the package __init__ and returns it + """ + with open(os.path.join("json_save", "__init__.py")) as init_file: + for line in init_file: + parts = line.strip().partition("=") + if parts[0].strip() == "__version__": + return parts[2].strip().strip("'").strip('"') + return None + + +setup( + name='json_save', + version=get_version(), + author='Chris Barker', + author_email='PythonCHB@gmail.com', + packages=find_packages(), + # license='LICENSE.txt', + description='Metaclass based system for saving object to JSON', + long_description=open('README.txt').read(), +) diff --git a/Students/Wayne/Assignments/Assignment_04/mailroom_jsonsave.py b/Students/Wayne/Assignments/Assignment_04/mailroom_jsonsave.py new file mode 100644 index 0000000..4cb1de1 --- /dev/null +++ b/Students/Wayne/Assignments/Assignment_04/mailroom_jsonsave.py @@ -0,0 +1,51 @@ + +from mailroom_oo import * +import json_save.json_save.json_save.json_save_dec as js +import os + + +############################################################################## +# # +# https://docs.python.org/3/library/json.html: # +# ________________________________________________________________________ # +# # +# json.load(,fp, *, cls=None, object_hook=None, parse_float=None, # +# parse_int=None, parse_constant=None, object_pairs_hook=None, **kw) # +# # +# serialize obj as a JSON formatted stream to fp (a .write()-supporting # +# file-like object) using this conversion table. The json module always # +# produces str objects, not bytes objects. Therefore, fp.write() must # +# support str input. # +# # +# +# ________________________________________________________________________ # +# # +# writing file from json out: # +# ________________________________________________________________________ # +# # +# https://stackoverflow.com/questions/12309269/ # +# how-do-i-write-json-data-to-a-file # +# # +# with open('data.txt', 'w') as outfile: # +# json.dump(jsonData, outfile, sort_keys = True, indent = 4, # +# ensure_ascii = False) # +# # +############################################################################## + + +@js.json_save +class save_donor_db: + Donors = js.List() # uses list function from json_save_dec + + def __init__(self, donordb): + self.Donors = [{'name': donor.name, 'donations': donor.donations} + for donor in donors.values()] # packs db into a list + + def save(self): # Should save as an outfile + with open('json._mr.txt', 'w') as outfile: + self.dump(self.donors, fp=outfile) + + @classmethod # Should load in file + def load(cls, file='json_in.json'): + with open(file, 'r') as infile: + return js.from_json(infile) diff --git a/Students/Wayne/Assignments/Assignment_04/mailroom_oo.py b/Students/Wayne/Assignments/Assignment_04/mailroom_oo.py new file mode 100755 index 0000000..b36ffab --- /dev/null +++ b/Students/Wayne/Assignments/Assignment_04/mailroom_oo.py @@ -0,0 +1,296 @@ +#!/usr/bin/env python +""" + +#Starting with a clean version of mailroom_oo.py + + +JSON Save System + +Goal is to use a JSON-save system to make your model classes saveable +and loadable. + + +https://stackoverflow.com/questions/35090264/what-is-the-best-way-to- +save-tuples-in-python + +""" + +import sys +import math + + +# handy utility to make pretty printing easier +from textwrap import dedent + + + +# In memory representation of the donor database +# using a tuple for each donor +# -- kind of like a record in a database table +# using a dict with a lower case version of the donor's name as the key +# This makes it easier to have a 'normalized' key. +# you could get a bit fancier by having each "record" be a dict, with +# "name" and "donations" as keys. +def get_donor_db(): + return {'william gates iii': ("William Gates III", [653772.32, 12.17]), + 'jeff bezos': ("Jeff Bezos", [877.33]), + 'paul allen': ("Paul Allen", [663.23, 43.87, 1.32]), + 'mark zuckerberg': ("Mark Zuckerberg", [1663.23, 4300.87, 10432.0]), + } + +def get_donor_db_oo(): + db = DonorDB() + raw_data = get_donor_db() + + for k, v in raw_data.items(): + donor = Donor(k) + for donation in v: + donor.add_donations(donation) + + +class Donor: + def __init__(self, name, donations=None): + self.name = name + self.donations = [] if donations is None else donations + + @property + def name(self): + return self.name + + @property + def donations(self): + return self.donations + + def add_donations(self, donation): + return self.donations.append(donation) + + @property + def total_donations(self): + return sum(self.donations) + #return reduce(lamda a,x: a+x, self.donations,0) + # s= 0 + # for d in self.donations: + # s +=d + # return s + + def ___str___(self): + return "{} : {}".format(self.name, self.donations) + + +class DonorDB: + def __init__(self): + self.donors = {} + + def add_donor(self, donor): + self.donors[donor.name.lower()] = donor + + def get_total_from_donor(self, donor_name): + return self.donors[donor_name.lower()].total_donations + + def get_donor(self, donor_name): + return self.donors[donor_name.lower()] + + @property + def num_donors(self): + return len(donors) + + def __repr__(self): + return repr(self.donors) + + +def list_donors(): + """ + creates a list of the donors as a string, so they can be printed + + Not calling print from here makes it more flexible and easier to + test + """ + listing = ["Donor list:"] + for donor in donor_db.values(): + listing.append(donor[0]) + return "\n".join(listing) + + +def find_donor(name): + """ + find a donor in the donor db + + :param: the name of the donor + + :returns: The donor data structure -- None if not in the donor_db + """ + key = name.strip().lower() + return donor_db.get(key) + + +def add_donor(name): + """ + Add a new donor to the donor db + + :param: the name of the donor + + :returns: the new Donor data structure + """ + name = name.strip() + donor = (name, []) + donor_db[name.lower()] = donor + return donor + + +def main_menu_selection(): + """ + Print out the main application menu and then read the user input. + """ + action = input(dedent(''' + Choose an action: + + 1 - Send a Thank You + 2 - Create a Report + 3 - Send letters to everyone + 4 - Quit + + > ''')) + return action.strip() + + +def gen_letter(donor): + """ + Generate a thank you letter for the donor + + :param: donor tuple + + :returns: string with letter + + note: This doesn't actually write to a file -- that's a separate + function. This makes it more flexible and easier to test. + """ + return dedent('''Dear {0:s}, + + Thank you for your very kind donation of ${1:.2f}. + It will be put to very good use. + + Sincerely, + -The Team + '''.format(donor[0], donor[1][-1])) + + +def send_thank_you(): + """ + Execute the logic to record a donation and generate a thank you message. + """ + # Read a valid donor to send a thank you from, handling special commands to + # let the user navigate as defined. + while True: + name = input("Enter a donor's name (or list to see all donors or 'menu' to exit)> ").strip() + if name == "list": + print(list_donors()) + elif name == "menu": + return + else: + break + + # Now prompt the user for a donation amount to apply. Since this is + # also an exit point to the main menu, we want to make sure this is + # done before mutating the db. + while True: + amount_str = input("Enter a donation amount (or 'menu' to exit)> ").strip() + if amount_str == "menu": + return + # Make sure amount is a valid amount before leaving the input loop + try: + amount = float(amount_str) + # extra check here -- unlikely that someone will type "NaN", but + # it IS possible, and it is a valid floating point number: + # http://en.wikipedia.org/wiki/NaN + if math.isnan(amount) or math.isinf(amount) or round(amount, 2) == 0.00: + raise ValueError + # in this case, the ValueError could be raised by the float() call, or by the NaN-check + except ValueError: + print("error: donation amount is invalid\n") + else: + break + + # If this is a new user, ensure that the database has the necessary + # data structure. + donor = find_donor(name) + if donor is None: + donor = add_donor(name) + + # Record the donation + donor[1].append(amount) + print(gen_letter(donor)) + + +def sort_key(item): + # used to sort on name in donor_db + return item[1] + + +def generate_donor_report(): + """ + Generate the report of the donors and amounts donated. + + :returns: the donor report as a string. + """ + # First, reduce the raw data into a summary list view + report_rows = [] + for (name, gifts) in donor_db.values(): + total_gifts = sum(gifts) + num_gifts = len(gifts) + avg_gift = total_gifts / num_gifts + report_rows.append((name, total_gifts, num_gifts, avg_gift)) + + # sort the report data + report_rows.sort(key=sort_key) + report = [] + report.append("{:25s} | {:11s} | {:9s} | {:12s}".format("Donor Name", + "Total Given", + "Num Gifts", + "Average Gift")) + report.append("-" * 66) + for row in report_rows: + report.append("{:25s} ${:10.2f} {:9d} ${:11.2f}".format(*row)) + return "\n".join(report) + + +def save_letters_to_disk(): + """ + make a letter for each donor, and save it to disk. + """ + for donor in donor_db.values(): + letter = gen_letter(donor) + # I don't like spaces in filenames... + filename = donor[0].replace(" ", "_") + ".txt" + open(filename, 'w').write(letter) + + +def print_donor_report(): + print(generate_donor_report()) + + +def quit(): + sys.exit(0) + + +def main(): + donor_db = get_donor_db_oo() + donor_name = input('Whose donation record would you like to see?') + + +if __name__ == "__main__": + + donor_db = get_donor_db() + + running = True + + selection_dict = {"1": send_thank_you, + "2": print_donor_report, + "3": save_letters_to_disk, + "4": quit} + + while True: + selection = main_menu_selection() + try: + selection_dict[selection]() + except KeyError: + print("error: menu selection is invalid!") diff --git a/Students/Wayne/Assignments/Assignment_05/.ipynb_checkpoints/Assignment_5-checkpoint.ipynb b/Students/Wayne/Assignments/Assignment_05/.ipynb_checkpoints/Assignment_5-checkpoint.ipynb new file mode 100644 index 0000000..2fd6442 --- /dev/null +++ b/Students/Wayne/Assignments/Assignment_05/.ipynb_checkpoints/Assignment_5-checkpoint.ipynb @@ -0,0 +1,6 @@ +{ + "cells": [], + "metadata": {}, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/Students/Wayne/Assignments/Assignment_05/app.py b/Students/Wayne/Assignments/Assignment_05/app.py new file mode 100644 index 0000000..7dfb9c5 --- /dev/null +++ b/Students/Wayne/Assignments/Assignment_05/app.py @@ -0,0 +1,18 @@ +import logging +import socket +from logging.handlers import SysLogHandler + +logger = logging.getLogger() +logger.setLevel(logging.INFO) + +syslog = SysLogHandler(address=('127.0.0.1', 9999)) +formatter = logging.Formatter( + '%(asctime)s' + 'FAKE_APP_NAME: %(message)s', + datefmt='%b %d %H:%M:%S' +) + +syslog.setFormatter(formatter) +logger.addHandler(syslog) + +logger.info("This is a message") diff --git a/Students/Wayne/Assignments/Assignment_05/mylog.log b/Students/Wayne/Assignments/Assignment_05/mylog.log new file mode 100644 index 0000000..5340640 --- /dev/null +++ b/Students/Wayne/Assignments/Assignment_05/mylog.log @@ -0,0 +1,2 @@ +2018-06-08 21:04:10,396 simple.py:26 WARNING The value of i is 50. +2018-06-08 21:04:10,396 simple.py:31 ERROR Tried to divide by zero. Var i was 50. Recovered gracefully. diff --git a/Students/Wayne/Assignments/Assignment_05/mylog_2018_06_08.log b/Students/Wayne/Assignments/Assignment_05/mylog_2018_06_08.log new file mode 100644 index 0000000..350acba --- /dev/null +++ b/Students/Wayne/Assignments/Assignment_05/mylog_2018_06_08.log @@ -0,0 +1,2 @@ +2018-06-08 23:19:30,492 simple.py:31 WARNING The value of i is 50. +2018-06-08 23:19:30,492 simple.py:36 ERROR Tried to divide by zero. Var i was 50. Recovered gracefully. diff --git a/Students/Wayne/Assignments/Assignment_05/mylog_2018_06_09.log b/Students/Wayne/Assignments/Assignment_05/mylog_2018_06_09.log new file mode 100644 index 0000000..15da38b --- /dev/null +++ b/Students/Wayne/Assignments/Assignment_05/mylog_2018_06_09.log @@ -0,0 +1,4 @@ +2018-06-09 15:19:19,960 simple.py:38 WARNING The value of i is 50. +2018-06-09 15:19:19,961 simple.py:43 ERROR Tried to divide by zero. Var i was 50. Recovered gracefully. +2018-06-09 16:01:48,144 simple.py:38 WARNING The value of i is 50. +2018-06-09 16:01:48,145 simple.py:43 ERROR Tried to divide by zero. Var i was 50. Recovered gracefully. diff --git a/Students/Wayne/Assignments/Assignment_05/mylog_2018_06_10.log b/Students/Wayne/Assignments/Assignment_05/mylog_2018_06_10.log new file mode 100644 index 0000000..977f631 --- /dev/null +++ b/Students/Wayne/Assignments/Assignment_05/mylog_2018_06_10.log @@ -0,0 +1,6 @@ +2018-06-10 22:04:59,070 simple.py:38 WARNING The value of i is 50. +2018-06-10 22:04:59,070 simple.py:43 ERROR Tried to divide by zero. Var i was 50. Recovered gracefully. +2018-06-10 22:06:10,166 simple.py:38 WARNING The value of i is 50. +2018-06-10 22:06:10,166 simple.py:38 WARNING The value of i is 50. +2018-06-10 22:06:10,168 simple.py:43 ERROR Tried to divide by zero. Var i was 50. Recovered gracefully. +2018-06-10 22:06:10,168 simple.py:43 ERROR Tried to divide by zero. Var i was 50. Recovered gracefully. diff --git a/Students/Wayne/Assignments/Assignment_05/mylog_2018_06_11.log b/Students/Wayne/Assignments/Assignment_05/mylog_2018_06_11.log new file mode 100644 index 0000000..6aa0a27 --- /dev/null +++ b/Students/Wayne/Assignments/Assignment_05/mylog_2018_06_11.log @@ -0,0 +1,2 @@ +2018-06-11 17:13:06,117 simple.py:38 WARNING The value of i is 50. +2018-06-11 17:13:06,118 simple.py:43 ERROR Tried to divide by zero. Var i was 50. Recovered gracefully. diff --git a/Students/Wayne/Assignments/Assignment_05/mylog_2018_06_16.log b/Students/Wayne/Assignments/Assignment_05/mylog_2018_06_16.log new file mode 100644 index 0000000..30eec8a --- /dev/null +++ b/Students/Wayne/Assignments/Assignment_05/mylog_2018_06_16.log @@ -0,0 +1,2 @@ +2018-06-16 11:02:49,901 simple.py:38 WARNING The value of i is 50. +2018-06-16 11:02:49,901 simple.py:43 ERROR Tried to divide by zero. Var i was 50. Recovered gracefully. diff --git a/Students/Wayne/Assignments/Assignment_05/pysyslog.py b/Students/Wayne/Assignments/Assignment_05/pysyslog.py new file mode 100644 index 0000000..49f6831 --- /dev/null +++ b/Students/Wayne/Assignments/Assignment_05/pysyslog.py @@ -0,0 +1,37 @@ +#!/usr/bin/env python + +## Tiny Syslog Server in Python. +## +## This is a tiny syslog server that is able to receive UDP based syslog +## entries on a specified port and save them to a file. +## That's it... it does nothing else... +## There are a few configuration parameters. + +LOG_FILE = 'syslog.log' +HOST, PORT = "127.0.0.1", 514 + +# +# NO USER SERVICEABLE PARTS BELOW HERE... +# + +import logging +import socketserver + +logging.basicConfig(level=logging.INFO, format='%(message)s', datefmt='', filename=LOG_FILE, filemode='a') + +class SyslogUDPHandler(socketserver.BaseRequestHandler): + + def handle(self): + data = bytes.decode(self.request[0].strip()) + socket = self.request[1] + print( "%s : " % self.client_address[0], str(data)) + logging.info(str(data)) + +if __name__ == "__main__": + try: + server = socketserver.UDPServer((HOST,PORT), SyslogUDPHandler) + server.serve_forever(poll_interval=0.5) + except (IOError, SystemExit): + raise + except KeyboardInterrupt: + print ("Crtl+C Pressed. Shutting down.") diff --git a/Students/Wayne/Assignments/Assignment_05/simple.py b/Students/Wayne/Assignments/Assignment_05/simple.py new file mode 100644 index 0000000..9ee1efa --- /dev/null +++ b/Students/Wayne/Assignments/Assignment_05/simple.py @@ -0,0 +1,51 @@ +# simple.py + + +import logging +import logging.handlers +from time import strftime + +format = "%(asctime)s %(filename)s:%(lineno)-3d %(levelname)s %(message)s" +sysformat = "%(filename)s:%(lineno)-3d %(levelname)s %(message)s" + +formatter = logging.Formatter(format) +sysformatter = logging.Formatter(sysformat) + +file_handler = logging.FileHandler(strftime('mylog_%Y_%m_%d.log')) +file_handler.setLevel(logging.WARNING) +file_handler.setFormatter(formatter) + +console_handler = logging.StreamHandler() +console_handler.setLevel(logging.INFO) +console_handler.setFormatter(formatter) + +sys_handler = logging.handlers.SysLogHandler(address=("127.0.0.1", 9999)) +sys_handler.setLevel(logging.ERROR) +sys_handler.setFormatter(sysformatter) + +logger = logging.getLogger() +logger.setLevel(logging.DEBUG) +logger.addHandler(file_handler) +logger.addHandler(console_handler) +logger.addHandler(sys_handler) + + + +def my_fun(n): + for i in range(0, n): + logging.debug(i) + if i == 50: + logging.warning("The value of i is 50.") + try: + i / (50 - i) + except ZeroDivisionError: + logging.error("Tried to divide by zero. Var i was {}." + " Recovered gracefully.".format(i)) + + +if __name__ == "__main__": + + + + + my_fun(100) \ No newline at end of file diff --git a/Students/Wayne/Assignments/Assignment_05/syslog.log b/Students/Wayne/Assignments/Assignment_05/syslog.log new file mode 100644 index 0000000..e69de29 diff --git a/Students/Wayne/Assignments/Assignment_06/.coverage b/Students/Wayne/Assignments/Assignment_06/.coverage new file mode 100644 index 0000000..151a46b --- /dev/null +++ b/Students/Wayne/Assignments/Assignment_06/.coverage @@ -0,0 +1 @@ +!coverage.py: This is a private format, don't read it directly!{"lines":{"/Users/weepler/SP2018-Python220-Accelerated-master/Students/Wayne/Assignments/Assignment_06/roman_numerals/__init__.py":[1],"/Users/weepler/SP2018-Python220-Accelerated-master/Students/Wayne/Assignments/Assignment_06/roman_numerals/roman_to_int.py":[1,3,22,25,26,27,30,5,7,9,11,13,14,32,15,16,6,12,17,18,8,10,28]}} \ No newline at end of file diff --git a/Students/Wayne/Assignments/Assignment_06/__pycache__/test.cpython-36.pyc b/Students/Wayne/Assignments/Assignment_06/__pycache__/test.cpython-36.pyc new file mode 100644 index 0000000..1d33a38 Binary files /dev/null and b/Students/Wayne/Assignments/Assignment_06/__pycache__/test.cpython-36.pyc differ diff --git a/Students/Wayne/Assignments/Assignment_06/htmlcov/coverage_html.js b/Students/Wayne/Assignments/Assignment_06/htmlcov/coverage_html.js new file mode 100644 index 0000000..f6f5de2 --- /dev/null +++ b/Students/Wayne/Assignments/Assignment_06/htmlcov/coverage_html.js @@ -0,0 +1,584 @@ +// Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0 +// For details: https://bitbucket.org/ned/coveragepy/src/default/NOTICE.txt + +// Coverage.py HTML report browser code. +/*jslint browser: true, sloppy: true, vars: true, plusplus: true, maxerr: 50, indent: 4 */ +/*global coverage: true, document, window, $ */ + +coverage = {}; + +// Find all the elements with shortkey_* class, and use them to assign a shortcut key. +coverage.assign_shortkeys = function () { + $("*[class*='shortkey_']").each(function (i, e) { + $.each($(e).attr("class").split(" "), function (i, c) { + if (/^shortkey_/.test(c)) { + $(document).bind('keydown', c.substr(9), function () { + $(e).click(); + }); + } + }); + }); +}; + +// Create the events for the help panel. +coverage.wire_up_help_panel = function () { + $("#keyboard_icon").click(function () { + // Show the help panel, and position it so the keyboard icon in the + // panel is in the same place as the keyboard icon in the header. + $(".help_panel").show(); + var koff = $("#keyboard_icon").offset(); + var poff = $("#panel_icon").position(); + $(".help_panel").offset({ + top: koff.top-poff.top, + left: koff.left-poff.left + }); + }); + $("#panel_icon").click(function () { + $(".help_panel").hide(); + }); +}; + +// Create the events for the filter box. +coverage.wire_up_filter = function () { + // Cache elements. + var table = $("table.index"); + var table_rows = table.find("tbody tr"); + var table_row_names = table_rows.find("td.name a"); + var no_rows = $("#no_rows"); + + // Create a duplicate table footer that we can modify with dynamic summed values. + var table_footer = $("table.index tfoot tr"); + var table_dynamic_footer = table_footer.clone(); + table_dynamic_footer.attr('class', 'total_dynamic hidden'); + table_footer.after(table_dynamic_footer); + + // Observe filter keyevents. + $("#filter").on("keyup change", $.debounce(150, function (event) { + var filter_value = $(this).val(); + + if (filter_value === "") { + // Filter box is empty, remove all filtering. + table_rows.removeClass("hidden"); + + // Show standard footer, hide dynamic footer. + table_footer.removeClass("hidden"); + table_dynamic_footer.addClass("hidden"); + + // Hide placeholder, show table. + if (no_rows.length > 0) { + no_rows.hide(); + } + table.show(); + + } + else { + // Filter table items by value. + var hidden = 0; + var shown = 0; + + // Hide / show elements. + $.each(table_row_names, function () { + var element = $(this).parents("tr"); + + if ($(this).text().indexOf(filter_value) === -1) { + // hide + element.addClass("hidden"); + hidden++; + } + else { + // show + element.removeClass("hidden"); + shown++; + } + }); + + // Show placeholder if no rows will be displayed. + if (no_rows.length > 0) { + if (shown === 0) { + // Show placeholder, hide table. + no_rows.show(); + table.hide(); + } + else { + // Hide placeholder, show table. + no_rows.hide(); + table.show(); + } + } + + // Manage dynamic header: + if (hidden > 0) { + // Calculate new dynamic sum values based on visible rows. + for (var column = 2; column < 20; column++) { + // Calculate summed value. + var cells = table_rows.find('td:nth-child(' + column + ')'); + if (!cells.length) { + // No more columns...! + break; + } + + var sum = 0, numer = 0, denom = 0; + $.each(cells.filter(':visible'), function () { + var ratio = $(this).data("ratio"); + if (ratio) { + var splitted = ratio.split(" "); + numer += parseInt(splitted[0], 10); + denom += parseInt(splitted[1], 10); + } + else { + sum += parseInt(this.innerHTML, 10); + } + }); + + // Get footer cell element. + var footer_cell = table_dynamic_footer.find('td:nth-child(' + column + ')'); + + // Set value into dynamic footer cell element. + if (cells[0].innerHTML.indexOf('%') > -1) { + // Percentage columns use the numerator and denominator, + // and adapt to the number of decimal places. + var match = /\.([0-9]+)/.exec(cells[0].innerHTML); + var places = 0; + if (match) { + places = match[1].length; + } + var pct = numer * 100 / denom; + footer_cell.text(pct.toFixed(places) + '%'); + } + else { + footer_cell.text(sum); + } + } + + // Hide standard footer, show dynamic footer. + table_footer.addClass("hidden"); + table_dynamic_footer.removeClass("hidden"); + } + else { + // Show standard footer, hide dynamic footer. + table_footer.removeClass("hidden"); + table_dynamic_footer.addClass("hidden"); + } + } + })); + + // Trigger change event on setup, to force filter on page refresh + // (filter value may still be present). + $("#filter").trigger("change"); +}; + +// Loaded on index.html +coverage.index_ready = function ($) { + // Look for a cookie containing previous sort settings: + var sort_list = []; + var cookie_name = "COVERAGE_INDEX_SORT"; + var i; + + // This almost makes it worth installing the jQuery cookie plugin: + if (document.cookie.indexOf(cookie_name) > -1) { + var cookies = document.cookie.split(";"); + for (i = 0; i < cookies.length; i++) { + var parts = cookies[i].split("="); + + if ($.trim(parts[0]) === cookie_name && parts[1]) { + sort_list = eval("[[" + parts[1] + "]]"); + break; + } + } + } + + // Create a new widget which exists only to save and restore + // the sort order: + $.tablesorter.addWidget({ + id: "persistentSort", + + // Format is called by the widget before displaying: + format: function (table) { + if (table.config.sortList.length === 0 && sort_list.length > 0) { + // This table hasn't been sorted before - we'll use + // our stored settings: + $(table).trigger('sorton', [sort_list]); + } + else { + // This is not the first load - something has + // already defined sorting so we'll just update + // our stored value to match: + sort_list = table.config.sortList; + } + } + }); + + // Configure our tablesorter to handle the variable number of + // columns produced depending on report options: + var headers = []; + var col_count = $("table.index > thead > tr > th").length; + + headers[0] = { sorter: 'text' }; + for (i = 1; i < col_count-1; i++) { + headers[i] = { sorter: 'digit' }; + } + headers[col_count-1] = { sorter: 'percent' }; + + // Enable the table sorter: + $("table.index").tablesorter({ + widgets: ['persistentSort'], + headers: headers + }); + + coverage.assign_shortkeys(); + coverage.wire_up_help_panel(); + coverage.wire_up_filter(); + + // Watch for page unload events so we can save the final sort settings: + $(window).unload(function () { + document.cookie = cookie_name + "=" + sort_list.toString() + "; path=/"; + }); +}; + +// -- pyfile stuff -- + +coverage.pyfile_ready = function ($) { + // If we're directed to a particular line number, highlight the line. + var frag = location.hash; + if (frag.length > 2 && frag[1] === 'n') { + $(frag).addClass('highlight'); + coverage.set_sel(parseInt(frag.substr(2), 10)); + } + else { + coverage.set_sel(0); + } + + $(document) + .bind('keydown', 'j', coverage.to_next_chunk_nicely) + .bind('keydown', 'k', coverage.to_prev_chunk_nicely) + .bind('keydown', '0', coverage.to_top) + .bind('keydown', '1', coverage.to_first_chunk) + ; + + $(".button_toggle_run").click(function (evt) {coverage.toggle_lines(evt.target, "run");}); + $(".button_toggle_exc").click(function (evt) {coverage.toggle_lines(evt.target, "exc");}); + $(".button_toggle_mis").click(function (evt) {coverage.toggle_lines(evt.target, "mis");}); + $(".button_toggle_par").click(function (evt) {coverage.toggle_lines(evt.target, "par");}); + + coverage.assign_shortkeys(); + coverage.wire_up_help_panel(); + + coverage.init_scroll_markers(); + + // Rebuild scroll markers after window high changing + $(window).resize(coverage.resize_scroll_markers); +}; + +coverage.toggle_lines = function (btn, cls) { + btn = $(btn); + var hide = "hide_"+cls; + if (btn.hasClass(hide)) { + $("#source ."+cls).removeClass(hide); + btn.removeClass(hide); + } + else { + $("#source ."+cls).addClass(hide); + btn.addClass(hide); + } +}; + +// Return the nth line div. +coverage.line_elt = function (n) { + return $("#t" + n); +}; + +// Return the nth line number div. +coverage.num_elt = function (n) { + return $("#n" + n); +}; + +// Return the container of all the code. +coverage.code_container = function () { + return $(".linenos"); +}; + +// Set the selection. b and e are line numbers. +coverage.set_sel = function (b, e) { + // The first line selected. + coverage.sel_begin = b; + // The next line not selected. + coverage.sel_end = (e === undefined) ? b+1 : e; +}; + +coverage.to_top = function () { + coverage.set_sel(0, 1); + coverage.scroll_window(0); +}; + +coverage.to_first_chunk = function () { + coverage.set_sel(0, 1); + coverage.to_next_chunk(); +}; + +coverage.is_transparent = function (color) { + // Different browsers return different colors for "none". + return color === "transparent" || color === "rgba(0, 0, 0, 0)"; +}; + +coverage.to_next_chunk = function () { + var c = coverage; + + // Find the start of the next colored chunk. + var probe = c.sel_end; + var color, probe_line; + while (true) { + probe_line = c.line_elt(probe); + if (probe_line.length === 0) { + return; + } + color = probe_line.css("background-color"); + if (!c.is_transparent(color)) { + break; + } + probe++; + } + + // There's a next chunk, `probe` points to it. + var begin = probe; + + // Find the end of this chunk. + var next_color = color; + while (next_color === color) { + probe++; + probe_line = c.line_elt(probe); + next_color = probe_line.css("background-color"); + } + c.set_sel(begin, probe); + c.show_selection(); +}; + +coverage.to_prev_chunk = function () { + var c = coverage; + + // Find the end of the prev colored chunk. + var probe = c.sel_begin-1; + var probe_line = c.line_elt(probe); + if (probe_line.length === 0) { + return; + } + var color = probe_line.css("background-color"); + while (probe > 0 && c.is_transparent(color)) { + probe--; + probe_line = c.line_elt(probe); + if (probe_line.length === 0) { + return; + } + color = probe_line.css("background-color"); + } + + // There's a prev chunk, `probe` points to its last line. + var end = probe+1; + + // Find the beginning of this chunk. + var prev_color = color; + while (prev_color === color) { + probe--; + probe_line = c.line_elt(probe); + prev_color = probe_line.css("background-color"); + } + c.set_sel(probe+1, end); + c.show_selection(); +}; + +// Return the line number of the line nearest pixel position pos +coverage.line_at_pos = function (pos) { + var l1 = coverage.line_elt(1), + l2 = coverage.line_elt(2), + result; + if (l1.length && l2.length) { + var l1_top = l1.offset().top, + line_height = l2.offset().top - l1_top, + nlines = (pos - l1_top) / line_height; + if (nlines < 1) { + result = 1; + } + else { + result = Math.ceil(nlines); + } + } + else { + result = 1; + } + return result; +}; + +// Returns 0, 1, or 2: how many of the two ends of the selection are on +// the screen right now? +coverage.selection_ends_on_screen = function () { + if (coverage.sel_begin === 0) { + return 0; + } + + var top = coverage.line_elt(coverage.sel_begin); + var next = coverage.line_elt(coverage.sel_end-1); + + return ( + (top.isOnScreen() ? 1 : 0) + + (next.isOnScreen() ? 1 : 0) + ); +}; + +coverage.to_next_chunk_nicely = function () { + coverage.finish_scrolling(); + if (coverage.selection_ends_on_screen() === 0) { + // The selection is entirely off the screen: select the top line on + // the screen. + var win = $(window); + coverage.select_line_or_chunk(coverage.line_at_pos(win.scrollTop())); + } + coverage.to_next_chunk(); +}; + +coverage.to_prev_chunk_nicely = function () { + coverage.finish_scrolling(); + if (coverage.selection_ends_on_screen() === 0) { + var win = $(window); + coverage.select_line_or_chunk(coverage.line_at_pos(win.scrollTop() + win.height())); + } + coverage.to_prev_chunk(); +}; + +// Select line number lineno, or if it is in a colored chunk, select the +// entire chunk +coverage.select_line_or_chunk = function (lineno) { + var c = coverage; + var probe_line = c.line_elt(lineno); + if (probe_line.length === 0) { + return; + } + var the_color = probe_line.css("background-color"); + if (!c.is_transparent(the_color)) { + // The line is in a highlighted chunk. + // Search backward for the first line. + var probe = lineno; + var color = the_color; + while (probe > 0 && color === the_color) { + probe--; + probe_line = c.line_elt(probe); + if (probe_line.length === 0) { + break; + } + color = probe_line.css("background-color"); + } + var begin = probe + 1; + + // Search forward for the last line. + probe = lineno; + color = the_color; + while (color === the_color) { + probe++; + probe_line = c.line_elt(probe); + color = probe_line.css("background-color"); + } + + coverage.set_sel(begin, probe); + } + else { + coverage.set_sel(lineno); + } +}; + +coverage.show_selection = function () { + var c = coverage; + + // Highlight the lines in the chunk + c.code_container().find(".highlight").removeClass("highlight"); + for (var probe = c.sel_begin; probe > 0 && probe < c.sel_end; probe++) { + c.num_elt(probe).addClass("highlight"); + } + + c.scroll_to_selection(); +}; + +coverage.scroll_to_selection = function () { + // Scroll the page if the chunk isn't fully visible. + if (coverage.selection_ends_on_screen() < 2) { + // Need to move the page. The html,body trick makes it scroll in all + // browsers, got it from http://stackoverflow.com/questions/3042651 + var top = coverage.line_elt(coverage.sel_begin); + var top_pos = parseInt(top.offset().top, 10); + coverage.scroll_window(top_pos - 30); + } +}; + +coverage.scroll_window = function (to_pos) { + $("html,body").animate({scrollTop: to_pos}, 200); +}; + +coverage.finish_scrolling = function () { + $("html,body").stop(true, true); +}; + +coverage.init_scroll_markers = function () { + var c = coverage; + // Init some variables + c.lines_len = $('td.text p').length; + c.body_h = $('body').height(); + c.header_h = $('div#header').height(); + c.missed_lines = $('td.text p.mis, td.text p.par'); + + // Build html + c.resize_scroll_markers(); +}; + +coverage.resize_scroll_markers = function () { + var c = coverage, + min_line_height = 3, + max_line_height = 10, + visible_window_h = $(window).height(); + + $('#scroll_marker').remove(); + // Don't build markers if the window has no scroll bar. + if (c.body_h <= visible_window_h) { + return; + } + + $("body").append("
 
"); + var scroll_marker = $('#scroll_marker'), + marker_scale = scroll_marker.height() / c.body_h, + line_height = scroll_marker.height() / c.lines_len; + + // Line height must be between the extremes. + if (line_height > min_line_height) { + if (line_height > max_line_height) { + line_height = max_line_height; + } + } + else { + line_height = min_line_height; + } + + var previous_line = -99, + last_mark, + last_top; + + c.missed_lines.each(function () { + var line_top = Math.round($(this).offset().top * marker_scale), + id_name = $(this).attr('id'), + line_number = parseInt(id_name.substring(1, id_name.length)); + + if (line_number === previous_line + 1) { + // If this solid missed block just make previous mark higher. + last_mark.css({ + 'height': line_top + line_height - last_top + }); + } + else { + // Add colored line in scroll_marker block. + scroll_marker.append('
'); + last_mark = $('#m' + line_number); + last_mark.css({ + 'height': line_height, + 'top': line_top + }); + last_top = line_top; + } + + previous_line = line_number; + }); +}; diff --git a/Students/Wayne/Assignments/Assignment_06/htmlcov/index.html b/Students/Wayne/Assignments/Assignment_06/htmlcov/index.html new file mode 100644 index 0000000..e034421 --- /dev/null +++ b/Students/Wayne/Assignments/Assignment_06/htmlcov/index.html @@ -0,0 +1,113 @@ + + + + + + + + Coverage report + + + + + + + + + + + + + +
+ Hide keyboard shortcuts +

Hot-keys on this page

+
+

+ n + s + m + x + + c   change column sorting +

+
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Modulestatementsmissingexcludedcoverage
Total241096%
roman_numerals/__init__.py000100%
roman_numerals/roman_to_int.py241096%
+ +

+ No items found using the specified filter. +

+
+ + + + + diff --git a/Students/Wayne/Assignments/Assignment_06/htmlcov/jquery.ba-throttle-debounce.min.js b/Students/Wayne/Assignments/Assignment_06/htmlcov/jquery.ba-throttle-debounce.min.js new file mode 100644 index 0000000..648fe5d --- /dev/null +++ b/Students/Wayne/Assignments/Assignment_06/htmlcov/jquery.ba-throttle-debounce.min.js @@ -0,0 +1,9 @@ +/* + * jQuery throttle / debounce - v1.1 - 3/7/2010 + * http://benalman.com/projects/jquery-throttle-debounce-plugin/ + * + * Copyright (c) 2010 "Cowboy" Ben Alman + * Dual licensed under the MIT and GPL licenses. + * http://benalman.com/about/license/ + */ +(function(b,c){var $=b.jQuery||b.Cowboy||(b.Cowboy={}),a;$.throttle=a=function(e,f,j,i){var h,d=0;if(typeof f!=="boolean"){i=j;j=f;f=c}function g(){var o=this,m=+new Date()-d,n=arguments;function l(){d=+new Date();j.apply(o,n)}function k(){h=c}if(i&&!h){l()}h&&clearTimeout(h);if(i===c&&m>e){l()}else{if(f!==true){h=setTimeout(i?k:l,i===c?e-m:e)}}}if($.guid){g.guid=j.guid=j.guid||$.guid++}return g};$.debounce=function(d,e,f){return f===c?a(d,e,false):a(d,f,e!==false)}})(this); diff --git a/Students/Wayne/Assignments/Assignment_06/htmlcov/jquery.hotkeys.js b/Students/Wayne/Assignments/Assignment_06/htmlcov/jquery.hotkeys.js new file mode 100644 index 0000000..09b21e0 --- /dev/null +++ b/Students/Wayne/Assignments/Assignment_06/htmlcov/jquery.hotkeys.js @@ -0,0 +1,99 @@ +/* + * jQuery Hotkeys Plugin + * Copyright 2010, John Resig + * Dual licensed under the MIT or GPL Version 2 licenses. + * + * Based upon the plugin by Tzury Bar Yochay: + * http://github.com/tzuryby/hotkeys + * + * Original idea by: + * Binny V A, http://www.openjs.com/scripts/events/keyboard_shortcuts/ +*/ + +(function(jQuery){ + + jQuery.hotkeys = { + version: "0.8", + + specialKeys: { + 8: "backspace", 9: "tab", 13: "return", 16: "shift", 17: "ctrl", 18: "alt", 19: "pause", + 20: "capslock", 27: "esc", 32: "space", 33: "pageup", 34: "pagedown", 35: "end", 36: "home", + 37: "left", 38: "up", 39: "right", 40: "down", 45: "insert", 46: "del", + 96: "0", 97: "1", 98: "2", 99: "3", 100: "4", 101: "5", 102: "6", 103: "7", + 104: "8", 105: "9", 106: "*", 107: "+", 109: "-", 110: ".", 111 : "/", + 112: "f1", 113: "f2", 114: "f3", 115: "f4", 116: "f5", 117: "f6", 118: "f7", 119: "f8", + 120: "f9", 121: "f10", 122: "f11", 123: "f12", 144: "numlock", 145: "scroll", 191: "/", 224: "meta" + }, + + shiftNums: { + "`": "~", "1": "!", "2": "@", "3": "#", "4": "$", "5": "%", "6": "^", "7": "&", + "8": "*", "9": "(", "0": ")", "-": "_", "=": "+", ";": ": ", "'": "\"", ",": "<", + ".": ">", "/": "?", "\\": "|" + } + }; + + function keyHandler( handleObj ) { + // Only care when a possible input has been specified + if ( typeof handleObj.data !== "string" ) { + return; + } + + var origHandler = handleObj.handler, + keys = handleObj.data.toLowerCase().split(" "); + + handleObj.handler = function( event ) { + // Don't fire in text-accepting inputs that we didn't directly bind to + if ( this !== event.target && (/textarea|select/i.test( event.target.nodeName ) || + event.target.type === "text") ) { + return; + } + + // Keypress represents characters, not special keys + var special = event.type !== "keypress" && jQuery.hotkeys.specialKeys[ event.which ], + character = String.fromCharCode( event.which ).toLowerCase(), + key, modif = "", possible = {}; + + // check combinations (alt|ctrl|shift+anything) + if ( event.altKey && special !== "alt" ) { + modif += "alt+"; + } + + if ( event.ctrlKey && special !== "ctrl" ) { + modif += "ctrl+"; + } + + // TODO: Need to make sure this works consistently across platforms + if ( event.metaKey && !event.ctrlKey && special !== "meta" ) { + modif += "meta+"; + } + + if ( event.shiftKey && special !== "shift" ) { + modif += "shift+"; + } + + if ( special ) { + possible[ modif + special ] = true; + + } else { + possible[ modif + character ] = true; + possible[ modif + jQuery.hotkeys.shiftNums[ character ] ] = true; + + // "$" can be triggered as "Shift+4" or "Shift+$" or just "$" + if ( modif === "shift+" ) { + possible[ jQuery.hotkeys.shiftNums[ character ] ] = true; + } + } + + for ( var i = 0, l = keys.length; i < l; i++ ) { + if ( possible[ keys[i] ] ) { + return origHandler.apply( this, arguments ); + } + } + }; + } + + jQuery.each([ "keydown", "keyup", "keypress" ], function() { + jQuery.event.special[ this ] = { add: keyHandler }; + }); + +})( jQuery ); diff --git a/Students/Wayne/Assignments/Assignment_06/htmlcov/jquery.isonscreen.js b/Students/Wayne/Assignments/Assignment_06/htmlcov/jquery.isonscreen.js new file mode 100644 index 0000000..0182ebd --- /dev/null +++ b/Students/Wayne/Assignments/Assignment_06/htmlcov/jquery.isonscreen.js @@ -0,0 +1,53 @@ +/* Copyright (c) 2010 + * @author Laurence Wheway + * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) + * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses. + * + * @version 1.2.0 + */ +(function($) { + jQuery.extend({ + isOnScreen: function(box, container) { + //ensure numbers come in as intgers (not strings) and remove 'px' is it's there + for(var i in box){box[i] = parseFloat(box[i])}; + for(var i in container){container[i] = parseFloat(container[i])}; + + if(!container){ + container = { + left: $(window).scrollLeft(), + top: $(window).scrollTop(), + width: $(window).width(), + height: $(window).height() + } + } + + if( box.left+box.width-container.left > 0 && + box.left < container.width+container.left && + box.top+box.height-container.top > 0 && + box.top < container.height+container.top + ) return true; + return false; + } + }) + + + jQuery.fn.isOnScreen = function (container) { + for(var i in container){container[i] = parseFloat(container[i])}; + + if(!container){ + container = { + left: $(window).scrollLeft(), + top: $(window).scrollTop(), + width: $(window).width(), + height: $(window).height() + } + } + + if( $(this).offset().left+$(this).width()-container.left > 0 && + $(this).offset().left < container.width+container.left && + $(this).offset().top+$(this).height()-container.top > 0 && + $(this).offset().top < container.height+container.top + ) return true; + return false; + } +})(jQuery); diff --git a/Students/Wayne/Assignments/Assignment_06/htmlcov/jquery.min.js b/Students/Wayne/Assignments/Assignment_06/htmlcov/jquery.min.js new file mode 100644 index 0000000..d1608e3 --- /dev/null +++ b/Students/Wayne/Assignments/Assignment_06/htmlcov/jquery.min.js @@ -0,0 +1,4 @@ +/*! jQuery v1.11.1 | (c) 2005, 2014 jQuery Foundation, Inc. | jquery.org/license */ +!function(a,b){"object"==typeof module&&"object"==typeof module.exports?module.exports=a.document?b(a,!0):function(a){if(!a.document)throw new Error("jQuery requires a window with a document");return b(a)}:b(a)}("undefined"!=typeof window?window:this,function(a,b){var c=[],d=c.slice,e=c.concat,f=c.push,g=c.indexOf,h={},i=h.toString,j=h.hasOwnProperty,k={},l="1.11.1",m=function(a,b){return new m.fn.init(a,b)},n=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,o=/^-ms-/,p=/-([\da-z])/gi,q=function(a,b){return b.toUpperCase()};m.fn=m.prototype={jquery:l,constructor:m,selector:"",length:0,toArray:function(){return d.call(this)},get:function(a){return null!=a?0>a?this[a+this.length]:this[a]:d.call(this)},pushStack:function(a){var b=m.merge(this.constructor(),a);return b.prevObject=this,b.context=this.context,b},each:function(a,b){return m.each(this,a,b)},map:function(a){return this.pushStack(m.map(this,function(b,c){return a.call(b,c,b)}))},slice:function(){return this.pushStack(d.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(a){var b=this.length,c=+a+(0>a?b:0);return this.pushStack(c>=0&&b>c?[this[c]]:[])},end:function(){return this.prevObject||this.constructor(null)},push:f,sort:c.sort,splice:c.splice},m.extend=m.fn.extend=function(){var a,b,c,d,e,f,g=arguments[0]||{},h=1,i=arguments.length,j=!1;for("boolean"==typeof g&&(j=g,g=arguments[h]||{},h++),"object"==typeof g||m.isFunction(g)||(g={}),h===i&&(g=this,h--);i>h;h++)if(null!=(e=arguments[h]))for(d in e)a=g[d],c=e[d],g!==c&&(j&&c&&(m.isPlainObject(c)||(b=m.isArray(c)))?(b?(b=!1,f=a&&m.isArray(a)?a:[]):f=a&&m.isPlainObject(a)?a:{},g[d]=m.extend(j,f,c)):void 0!==c&&(g[d]=c));return g},m.extend({expando:"jQuery"+(l+Math.random()).replace(/\D/g,""),isReady:!0,error:function(a){throw new Error(a)},noop:function(){},isFunction:function(a){return"function"===m.type(a)},isArray:Array.isArray||function(a){return"array"===m.type(a)},isWindow:function(a){return null!=a&&a==a.window},isNumeric:function(a){return!m.isArray(a)&&a-parseFloat(a)>=0},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},isPlainObject:function(a){var b;if(!a||"object"!==m.type(a)||a.nodeType||m.isWindow(a))return!1;try{if(a.constructor&&!j.call(a,"constructor")&&!j.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}if(k.ownLast)for(b in a)return j.call(a,b);for(b in a);return void 0===b||j.call(a,b)},type:function(a){return null==a?a+"":"object"==typeof a||"function"==typeof a?h[i.call(a)]||"object":typeof a},globalEval:function(b){b&&m.trim(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(o,"ms-").replace(p,q)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toLowerCase()===b.toLowerCase()},each:function(a,b,c){var d,e=0,f=a.length,g=r(a);if(c){if(g){for(;f>e;e++)if(d=b.apply(a[e],c),d===!1)break}else for(e in a)if(d=b.apply(a[e],c),d===!1)break}else if(g){for(;f>e;e++)if(d=b.call(a[e],e,a[e]),d===!1)break}else for(e in a)if(d=b.call(a[e],e,a[e]),d===!1)break;return a},trim:function(a){return null==a?"":(a+"").replace(n,"")},makeArray:function(a,b){var c=b||[];return null!=a&&(r(Object(a))?m.merge(c,"string"==typeof a?[a]:a):f.call(c,a)),c},inArray:function(a,b,c){var d;if(b){if(g)return g.call(b,a,c);for(d=b.length,c=c?0>c?Math.max(0,d+c):c:0;d>c;c++)if(c in b&&b[c]===a)return c}return-1},merge:function(a,b){var c=+b.length,d=0,e=a.length;while(c>d)a[e++]=b[d++];if(c!==c)while(void 0!==b[d])a[e++]=b[d++];return a.length=e,a},grep:function(a,b,c){for(var d,e=[],f=0,g=a.length,h=!c;g>f;f++)d=!b(a[f],f),d!==h&&e.push(a[f]);return e},map:function(a,b,c){var d,f=0,g=a.length,h=r(a),i=[];if(h)for(;g>f;f++)d=b(a[f],f,c),null!=d&&i.push(d);else for(f in a)d=b(a[f],f,c),null!=d&&i.push(d);return e.apply([],i)},guid:1,proxy:function(a,b){var c,e,f;return"string"==typeof b&&(f=a[b],b=a,a=f),m.isFunction(a)?(c=d.call(arguments,2),e=function(){return a.apply(b||this,c.concat(d.call(arguments)))},e.guid=a.guid=a.guid||m.guid++,e):void 0},now:function(){return+new Date},support:k}),m.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(a,b){h["[object "+b+"]"]=b.toLowerCase()});function r(a){var b=a.length,c=m.type(a);return"function"===c||m.isWindow(a)?!1:1===a.nodeType&&b?!0:"array"===c||0===b||"number"==typeof b&&b>0&&b-1 in a}var s=function(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u="sizzle"+-new Date,v=a.document,w=0,x=0,y=gb(),z=gb(),A=gb(),B=function(a,b){return a===b&&(l=!0),0},C="undefined",D=1<<31,E={}.hasOwnProperty,F=[],G=F.pop,H=F.push,I=F.push,J=F.slice,K=F.indexOf||function(a){for(var b=0,c=this.length;c>b;b++)if(this[b]===a)return b;return-1},L="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",M="[\\x20\\t\\r\\n\\f]",N="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",O=N.replace("w","w#"),P="\\["+M+"*("+N+")(?:"+M+"*([*^$|!~]?=)"+M+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+O+"))|)"+M+"*\\]",Q=":("+N+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+P+")*)|.*)\\)|)",R=new RegExp("^"+M+"+|((?:^|[^\\\\])(?:\\\\.)*)"+M+"+$","g"),S=new RegExp("^"+M+"*,"+M+"*"),T=new RegExp("^"+M+"*([>+~]|"+M+")"+M+"*"),U=new RegExp("="+M+"*([^\\]'\"]*?)"+M+"*\\]","g"),V=new RegExp(Q),W=new RegExp("^"+O+"$"),X={ID:new RegExp("^#("+N+")"),CLASS:new RegExp("^\\.("+N+")"),TAG:new RegExp("^("+N.replace("w","w*")+")"),ATTR:new RegExp("^"+P),PSEUDO:new RegExp("^"+Q),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+M+"*(even|odd|(([+-]|)(\\d*)n|)"+M+"*(?:([+-]|)"+M+"*(\\d+)|))"+M+"*\\)|)","i"),bool:new RegExp("^(?:"+L+")$","i"),needsContext:new RegExp("^"+M+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+M+"*((?:-\\d)?\\d*)"+M+"*\\)|)(?=[^-]|$)","i")},Y=/^(?:input|select|textarea|button)$/i,Z=/^h\d$/i,$=/^[^{]+\{\s*\[native \w/,_=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,ab=/[+~]/,bb=/'|\\/g,cb=new RegExp("\\\\([\\da-f]{1,6}"+M+"?|("+M+")|.)","ig"),db=function(a,b,c){var d="0x"+b-65536;return d!==d||c?b:0>d?String.fromCharCode(d+65536):String.fromCharCode(d>>10|55296,1023&d|56320)};try{I.apply(F=J.call(v.childNodes),v.childNodes),F[v.childNodes.length].nodeType}catch(eb){I={apply:F.length?function(a,b){H.apply(a,J.call(b))}:function(a,b){var c=a.length,d=0;while(a[c++]=b[d++]);a.length=c-1}}}function fb(a,b,d,e){var f,h,j,k,l,o,r,s,w,x;if((b?b.ownerDocument||b:v)!==n&&m(b),b=b||n,d=d||[],!a||"string"!=typeof a)return d;if(1!==(k=b.nodeType)&&9!==k)return[];if(p&&!e){if(f=_.exec(a))if(j=f[1]){if(9===k){if(h=b.getElementById(j),!h||!h.parentNode)return d;if(h.id===j)return d.push(h),d}else if(b.ownerDocument&&(h=b.ownerDocument.getElementById(j))&&t(b,h)&&h.id===j)return d.push(h),d}else{if(f[2])return I.apply(d,b.getElementsByTagName(a)),d;if((j=f[3])&&c.getElementsByClassName&&b.getElementsByClassName)return I.apply(d,b.getElementsByClassName(j)),d}if(c.qsa&&(!q||!q.test(a))){if(s=r=u,w=b,x=9===k&&a,1===k&&"object"!==b.nodeName.toLowerCase()){o=g(a),(r=b.getAttribute("id"))?s=r.replace(bb,"\\$&"):b.setAttribute("id",s),s="[id='"+s+"'] ",l=o.length;while(l--)o[l]=s+qb(o[l]);w=ab.test(a)&&ob(b.parentNode)||b,x=o.join(",")}if(x)try{return I.apply(d,w.querySelectorAll(x)),d}catch(y){}finally{r||b.removeAttribute("id")}}}return i(a.replace(R,"$1"),b,d,e)}function gb(){var a=[];function b(c,e){return a.push(c+" ")>d.cacheLength&&delete b[a.shift()],b[c+" "]=e}return b}function hb(a){return a[u]=!0,a}function ib(a){var b=n.createElement("div");try{return!!a(b)}catch(c){return!1}finally{b.parentNode&&b.parentNode.removeChild(b),b=null}}function jb(a,b){var c=a.split("|"),e=a.length;while(e--)d.attrHandle[c[e]]=b}function kb(a,b){var c=b&&a,d=c&&1===a.nodeType&&1===b.nodeType&&(~b.sourceIndex||D)-(~a.sourceIndex||D);if(d)return d;if(c)while(c=c.nextSibling)if(c===b)return-1;return a?1:-1}function lb(a){return function(b){var c=b.nodeName.toLowerCase();return"input"===c&&b.type===a}}function mb(a){return function(b){var c=b.nodeName.toLowerCase();return("input"===c||"button"===c)&&b.type===a}}function nb(a){return hb(function(b){return b=+b,hb(function(c,d){var e,f=a([],c.length,b),g=f.length;while(g--)c[e=f[g]]&&(c[e]=!(d[e]=c[e]))})})}function ob(a){return a&&typeof a.getElementsByTagName!==C&&a}c=fb.support={},f=fb.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return b?"HTML"!==b.nodeName:!1},m=fb.setDocument=function(a){var b,e=a?a.ownerDocument||a:v,g=e.defaultView;return e!==n&&9===e.nodeType&&e.documentElement?(n=e,o=e.documentElement,p=!f(e),g&&g!==g.top&&(g.addEventListener?g.addEventListener("unload",function(){m()},!1):g.attachEvent&&g.attachEvent("onunload",function(){m()})),c.attributes=ib(function(a){return a.className="i",!a.getAttribute("className")}),c.getElementsByTagName=ib(function(a){return a.appendChild(e.createComment("")),!a.getElementsByTagName("*").length}),c.getElementsByClassName=$.test(e.getElementsByClassName)&&ib(function(a){return a.innerHTML="
",a.firstChild.className="i",2===a.getElementsByClassName("i").length}),c.getById=ib(function(a){return o.appendChild(a).id=u,!e.getElementsByName||!e.getElementsByName(u).length}),c.getById?(d.find.ID=function(a,b){if(typeof b.getElementById!==C&&p){var c=b.getElementById(a);return c&&c.parentNode?[c]:[]}},d.filter.ID=function(a){var b=a.replace(cb,db);return function(a){return a.getAttribute("id")===b}}):(delete d.find.ID,d.filter.ID=function(a){var b=a.replace(cb,db);return function(a){var c=typeof a.getAttributeNode!==C&&a.getAttributeNode("id");return c&&c.value===b}}),d.find.TAG=c.getElementsByTagName?function(a,b){return typeof b.getElementsByTagName!==C?b.getElementsByTagName(a):void 0}:function(a,b){var c,d=[],e=0,f=b.getElementsByTagName(a);if("*"===a){while(c=f[e++])1===c.nodeType&&d.push(c);return d}return f},d.find.CLASS=c.getElementsByClassName&&function(a,b){return typeof b.getElementsByClassName!==C&&p?b.getElementsByClassName(a):void 0},r=[],q=[],(c.qsa=$.test(e.querySelectorAll))&&(ib(function(a){a.innerHTML="",a.querySelectorAll("[msallowclip^='']").length&&q.push("[*^$]="+M+"*(?:''|\"\")"),a.querySelectorAll("[selected]").length||q.push("\\["+M+"*(?:value|"+L+")"),a.querySelectorAll(":checked").length||q.push(":checked")}),ib(function(a){var b=e.createElement("input");b.setAttribute("type","hidden"),a.appendChild(b).setAttribute("name","D"),a.querySelectorAll("[name=d]").length&&q.push("name"+M+"*[*^$|!~]?="),a.querySelectorAll(":enabled").length||q.push(":enabled",":disabled"),a.querySelectorAll("*,:x"),q.push(",.*:")})),(c.matchesSelector=$.test(s=o.matches||o.webkitMatchesSelector||o.mozMatchesSelector||o.oMatchesSelector||o.msMatchesSelector))&&ib(function(a){c.disconnectedMatch=s.call(a,"div"),s.call(a,"[s!='']:x"),r.push("!=",Q)}),q=q.length&&new RegExp(q.join("|")),r=r.length&&new RegExp(r.join("|")),b=$.test(o.compareDocumentPosition),t=b||$.test(o.contains)?function(a,b){var c=9===a.nodeType?a.documentElement:a,d=b&&b.parentNode;return a===d||!(!d||1!==d.nodeType||!(c.contains?c.contains(d):a.compareDocumentPosition&&16&a.compareDocumentPosition(d)))}:function(a,b){if(b)while(b=b.parentNode)if(b===a)return!0;return!1},B=b?function(a,b){if(a===b)return l=!0,0;var d=!a.compareDocumentPosition-!b.compareDocumentPosition;return d?d:(d=(a.ownerDocument||a)===(b.ownerDocument||b)?a.compareDocumentPosition(b):1,1&d||!c.sortDetached&&b.compareDocumentPosition(a)===d?a===e||a.ownerDocument===v&&t(v,a)?-1:b===e||b.ownerDocument===v&&t(v,b)?1:k?K.call(k,a)-K.call(k,b):0:4&d?-1:1)}:function(a,b){if(a===b)return l=!0,0;var c,d=0,f=a.parentNode,g=b.parentNode,h=[a],i=[b];if(!f||!g)return a===e?-1:b===e?1:f?-1:g?1:k?K.call(k,a)-K.call(k,b):0;if(f===g)return kb(a,b);c=a;while(c=c.parentNode)h.unshift(c);c=b;while(c=c.parentNode)i.unshift(c);while(h[d]===i[d])d++;return d?kb(h[d],i[d]):h[d]===v?-1:i[d]===v?1:0},e):n},fb.matches=function(a,b){return fb(a,null,null,b)},fb.matchesSelector=function(a,b){if((a.ownerDocument||a)!==n&&m(a),b=b.replace(U,"='$1']"),!(!c.matchesSelector||!p||r&&r.test(b)||q&&q.test(b)))try{var d=s.call(a,b);if(d||c.disconnectedMatch||a.document&&11!==a.document.nodeType)return d}catch(e){}return fb(b,n,null,[a]).length>0},fb.contains=function(a,b){return(a.ownerDocument||a)!==n&&m(a),t(a,b)},fb.attr=function(a,b){(a.ownerDocument||a)!==n&&m(a);var e=d.attrHandle[b.toLowerCase()],f=e&&E.call(d.attrHandle,b.toLowerCase())?e(a,b,!p):void 0;return void 0!==f?f:c.attributes||!p?a.getAttribute(b):(f=a.getAttributeNode(b))&&f.specified?f.value:null},fb.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},fb.uniqueSort=function(a){var b,d=[],e=0,f=0;if(l=!c.detectDuplicates,k=!c.sortStable&&a.slice(0),a.sort(B),l){while(b=a[f++])b===a[f]&&(e=d.push(f));while(e--)a.splice(d[e],1)}return k=null,a},e=fb.getText=function(a){var b,c="",d=0,f=a.nodeType;if(f){if(1===f||9===f||11===f){if("string"==typeof a.textContent)return a.textContent;for(a=a.firstChild;a;a=a.nextSibling)c+=e(a)}else if(3===f||4===f)return a.nodeValue}else while(b=a[d++])c+=e(b);return c},d=fb.selectors={cacheLength:50,createPseudo:hb,match:X,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(cb,db),a[3]=(a[3]||a[4]||a[5]||"").replace(cb,db),"~="===a[2]&&(a[3]=" "+a[3]+" "),a.slice(0,4)},CHILD:function(a){return a[1]=a[1].toLowerCase(),"nth"===a[1].slice(0,3)?(a[3]||fb.error(a[0]),a[4]=+(a[4]?a[5]+(a[6]||1):2*("even"===a[3]||"odd"===a[3])),a[5]=+(a[7]+a[8]||"odd"===a[3])):a[3]&&fb.error(a[0]),a},PSEUDO:function(a){var b,c=!a[6]&&a[2];return X.CHILD.test(a[0])?null:(a[3]?a[2]=a[4]||a[5]||"":c&&V.test(c)&&(b=g(c,!0))&&(b=c.indexOf(")",c.length-b)-c.length)&&(a[0]=a[0].slice(0,b),a[2]=c.slice(0,b)),a.slice(0,3))}},filter:{TAG:function(a){var b=a.replace(cb,db).toLowerCase();return"*"===a?function(){return!0}:function(a){return a.nodeName&&a.nodeName.toLowerCase()===b}},CLASS:function(a){var b=y[a+" "];return b||(b=new RegExp("(^|"+M+")"+a+"("+M+"|$)"))&&y(a,function(a){return b.test("string"==typeof a.className&&a.className||typeof a.getAttribute!==C&&a.getAttribute("class")||"")})},ATTR:function(a,b,c){return function(d){var e=fb.attr(d,a);return null==e?"!="===b:b?(e+="","="===b?e===c:"!="===b?e!==c:"^="===b?c&&0===e.indexOf(c):"*="===b?c&&e.indexOf(c)>-1:"$="===b?c&&e.slice(-c.length)===c:"~="===b?(" "+e+" ").indexOf(c)>-1:"|="===b?e===c||e.slice(0,c.length+1)===c+"-":!1):!0}},CHILD:function(a,b,c,d,e){var f="nth"!==a.slice(0,3),g="last"!==a.slice(-4),h="of-type"===b;return 1===d&&0===e?function(a){return!!a.parentNode}:function(b,c,i){var j,k,l,m,n,o,p=f!==g?"nextSibling":"previousSibling",q=b.parentNode,r=h&&b.nodeName.toLowerCase(),s=!i&&!h;if(q){if(f){while(p){l=b;while(l=l[p])if(h?l.nodeName.toLowerCase()===r:1===l.nodeType)return!1;o=p="only"===a&&!o&&"nextSibling"}return!0}if(o=[g?q.firstChild:q.lastChild],g&&s){k=q[u]||(q[u]={}),j=k[a]||[],n=j[0]===w&&j[1],m=j[0]===w&&j[2],l=n&&q.childNodes[n];while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if(1===l.nodeType&&++m&&l===b){k[a]=[w,n,m];break}}else if(s&&(j=(b[u]||(b[u]={}))[a])&&j[0]===w)m=j[1];else while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if((h?l.nodeName.toLowerCase()===r:1===l.nodeType)&&++m&&(s&&((l[u]||(l[u]={}))[a]=[w,m]),l===b))break;return m-=e,m===d||m%d===0&&m/d>=0}}},PSEUDO:function(a,b){var c,e=d.pseudos[a]||d.setFilters[a.toLowerCase()]||fb.error("unsupported pseudo: "+a);return e[u]?e(b):e.length>1?(c=[a,a,"",b],d.setFilters.hasOwnProperty(a.toLowerCase())?hb(function(a,c){var d,f=e(a,b),g=f.length;while(g--)d=K.call(a,f[g]),a[d]=!(c[d]=f[g])}):function(a){return e(a,0,c)}):e}},pseudos:{not:hb(function(a){var b=[],c=[],d=h(a.replace(R,"$1"));return d[u]?hb(function(a,b,c,e){var f,g=d(a,null,e,[]),h=a.length;while(h--)(f=g[h])&&(a[h]=!(b[h]=f))}):function(a,e,f){return b[0]=a,d(b,null,f,c),!c.pop()}}),has:hb(function(a){return function(b){return fb(a,b).length>0}}),contains:hb(function(a){return function(b){return(b.textContent||b.innerText||e(b)).indexOf(a)>-1}}),lang:hb(function(a){return W.test(a||"")||fb.error("unsupported lang: "+a),a=a.replace(cb,db).toLowerCase(),function(b){var c;do if(c=p?b.lang:b.getAttribute("xml:lang")||b.getAttribute("lang"))return c=c.toLowerCase(),c===a||0===c.indexOf(a+"-");while((b=b.parentNode)&&1===b.nodeType);return!1}}),target:function(b){var c=a.location&&a.location.hash;return c&&c.slice(1)===b.id},root:function(a){return a===o},focus:function(a){return a===n.activeElement&&(!n.hasFocus||n.hasFocus())&&!!(a.type||a.href||~a.tabIndex)},enabled:function(a){return a.disabled===!1},disabled:function(a){return a.disabled===!0},checked:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&!!a.checked||"option"===b&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,a.selected===!0},empty:function(a){for(a=a.firstChild;a;a=a.nextSibling)if(a.nodeType<6)return!1;return!0},parent:function(a){return!d.pseudos.empty(a)},header:function(a){return Z.test(a.nodeName)},input:function(a){return Y.test(a.nodeName)},button:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&"button"===a.type||"button"===b},text:function(a){var b;return"input"===a.nodeName.toLowerCase()&&"text"===a.type&&(null==(b=a.getAttribute("type"))||"text"===b.toLowerCase())},first:nb(function(){return[0]}),last:nb(function(a,b){return[b-1]}),eq:nb(function(a,b,c){return[0>c?c+b:c]}),even:nb(function(a,b){for(var c=0;b>c;c+=2)a.push(c);return a}),odd:nb(function(a,b){for(var c=1;b>c;c+=2)a.push(c);return a}),lt:nb(function(a,b,c){for(var d=0>c?c+b:c;--d>=0;)a.push(d);return a}),gt:nb(function(a,b,c){for(var d=0>c?c+b:c;++db;b++)d+=a[b].value;return d}function rb(a,b,c){var d=b.dir,e=c&&"parentNode"===d,f=x++;return b.first?function(b,c,f){while(b=b[d])if(1===b.nodeType||e)return a(b,c,f)}:function(b,c,g){var h,i,j=[w,f];if(g){while(b=b[d])if((1===b.nodeType||e)&&a(b,c,g))return!0}else while(b=b[d])if(1===b.nodeType||e){if(i=b[u]||(b[u]={}),(h=i[d])&&h[0]===w&&h[1]===f)return j[2]=h[2];if(i[d]=j,j[2]=a(b,c,g))return!0}}}function sb(a){return a.length>1?function(b,c,d){var e=a.length;while(e--)if(!a[e](b,c,d))return!1;return!0}:a[0]}function tb(a,b,c){for(var d=0,e=b.length;e>d;d++)fb(a,b[d],c);return c}function ub(a,b,c,d,e){for(var f,g=[],h=0,i=a.length,j=null!=b;i>h;h++)(f=a[h])&&(!c||c(f,d,e))&&(g.push(f),j&&b.push(h));return g}function vb(a,b,c,d,e,f){return d&&!d[u]&&(d=vb(d)),e&&!e[u]&&(e=vb(e,f)),hb(function(f,g,h,i){var j,k,l,m=[],n=[],o=g.length,p=f||tb(b||"*",h.nodeType?[h]:h,[]),q=!a||!f&&b?p:ub(p,m,a,h,i),r=c?e||(f?a:o||d)?[]:g:q;if(c&&c(q,r,h,i),d){j=ub(r,n),d(j,[],h,i),k=j.length;while(k--)(l=j[k])&&(r[n[k]]=!(q[n[k]]=l))}if(f){if(e||a){if(e){j=[],k=r.length;while(k--)(l=r[k])&&j.push(q[k]=l);e(null,r=[],j,i)}k=r.length;while(k--)(l=r[k])&&(j=e?K.call(f,l):m[k])>-1&&(f[j]=!(g[j]=l))}}else r=ub(r===g?r.splice(o,r.length):r),e?e(null,g,r,i):I.apply(g,r)})}function wb(a){for(var b,c,e,f=a.length,g=d.relative[a[0].type],h=g||d.relative[" "],i=g?1:0,k=rb(function(a){return a===b},h,!0),l=rb(function(a){return K.call(b,a)>-1},h,!0),m=[function(a,c,d){return!g&&(d||c!==j)||((b=c).nodeType?k(a,c,d):l(a,c,d))}];f>i;i++)if(c=d.relative[a[i].type])m=[rb(sb(m),c)];else{if(c=d.filter[a[i].type].apply(null,a[i].matches),c[u]){for(e=++i;f>e;e++)if(d.relative[a[e].type])break;return vb(i>1&&sb(m),i>1&&qb(a.slice(0,i-1).concat({value:" "===a[i-2].type?"*":""})).replace(R,"$1"),c,e>i&&wb(a.slice(i,e)),f>e&&wb(a=a.slice(e)),f>e&&qb(a))}m.push(c)}return sb(m)}function xb(a,b){var c=b.length>0,e=a.length>0,f=function(f,g,h,i,k){var l,m,o,p=0,q="0",r=f&&[],s=[],t=j,u=f||e&&d.find.TAG("*",k),v=w+=null==t?1:Math.random()||.1,x=u.length;for(k&&(j=g!==n&&g);q!==x&&null!=(l=u[q]);q++){if(e&&l){m=0;while(o=a[m++])if(o(l,g,h)){i.push(l);break}k&&(w=v)}c&&((l=!o&&l)&&p--,f&&r.push(l))}if(p+=q,c&&q!==p){m=0;while(o=b[m++])o(r,s,g,h);if(f){if(p>0)while(q--)r[q]||s[q]||(s[q]=G.call(i));s=ub(s)}I.apply(i,s),k&&!f&&s.length>0&&p+b.length>1&&fb.uniqueSort(i)}return k&&(w=v,j=t),r};return c?hb(f):f}return h=fb.compile=function(a,b){var c,d=[],e=[],f=A[a+" "];if(!f){b||(b=g(a)),c=b.length;while(c--)f=wb(b[c]),f[u]?d.push(f):e.push(f);f=A(a,xb(e,d)),f.selector=a}return f},i=fb.select=function(a,b,e,f){var i,j,k,l,m,n="function"==typeof a&&a,o=!f&&g(a=n.selector||a);if(e=e||[],1===o.length){if(j=o[0]=o[0].slice(0),j.length>2&&"ID"===(k=j[0]).type&&c.getById&&9===b.nodeType&&p&&d.relative[j[1].type]){if(b=(d.find.ID(k.matches[0].replace(cb,db),b)||[])[0],!b)return e;n&&(b=b.parentNode),a=a.slice(j.shift().value.length)}i=X.needsContext.test(a)?0:j.length;while(i--){if(k=j[i],d.relative[l=k.type])break;if((m=d.find[l])&&(f=m(k.matches[0].replace(cb,db),ab.test(j[0].type)&&ob(b.parentNode)||b))){if(j.splice(i,1),a=f.length&&qb(j),!a)return I.apply(e,f),e;break}}}return(n||h(a,o))(f,b,!p,e,ab.test(a)&&ob(b.parentNode)||b),e},c.sortStable=u.split("").sort(B).join("")===u,c.detectDuplicates=!!l,m(),c.sortDetached=ib(function(a){return 1&a.compareDocumentPosition(n.createElement("div"))}),ib(function(a){return a.innerHTML="","#"===a.firstChild.getAttribute("href")})||jb("type|href|height|width",function(a,b,c){return c?void 0:a.getAttribute(b,"type"===b.toLowerCase()?1:2)}),c.attributes&&ib(function(a){return a.innerHTML="",a.firstChild.setAttribute("value",""),""===a.firstChild.getAttribute("value")})||jb("value",function(a,b,c){return c||"input"!==a.nodeName.toLowerCase()?void 0:a.defaultValue}),ib(function(a){return null==a.getAttribute("disabled")})||jb(L,function(a,b,c){var d;return c?void 0:a[b]===!0?b.toLowerCase():(d=a.getAttributeNode(b))&&d.specified?d.value:null}),fb}(a);m.find=s,m.expr=s.selectors,m.expr[":"]=m.expr.pseudos,m.unique=s.uniqueSort,m.text=s.getText,m.isXMLDoc=s.isXML,m.contains=s.contains;var t=m.expr.match.needsContext,u=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,v=/^.[^:#\[\.,]*$/;function w(a,b,c){if(m.isFunction(b))return m.grep(a,function(a,d){return!!b.call(a,d,a)!==c});if(b.nodeType)return m.grep(a,function(a){return a===b!==c});if("string"==typeof b){if(v.test(b))return m.filter(b,a,c);b=m.filter(b,a)}return m.grep(a,function(a){return m.inArray(a,b)>=0!==c})}m.filter=function(a,b,c){var d=b[0];return c&&(a=":not("+a+")"),1===b.length&&1===d.nodeType?m.find.matchesSelector(d,a)?[d]:[]:m.find.matches(a,m.grep(b,function(a){return 1===a.nodeType}))},m.fn.extend({find:function(a){var b,c=[],d=this,e=d.length;if("string"!=typeof a)return this.pushStack(m(a).filter(function(){for(b=0;e>b;b++)if(m.contains(d[b],this))return!0}));for(b=0;e>b;b++)m.find(a,d[b],c);return c=this.pushStack(e>1?m.unique(c):c),c.selector=this.selector?this.selector+" "+a:a,c},filter:function(a){return this.pushStack(w(this,a||[],!1))},not:function(a){return this.pushStack(w(this,a||[],!0))},is:function(a){return!!w(this,"string"==typeof a&&t.test(a)?m(a):a||[],!1).length}});var x,y=a.document,z=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,A=m.fn.init=function(a,b){var c,d;if(!a)return this;if("string"==typeof a){if(c="<"===a.charAt(0)&&">"===a.charAt(a.length-1)&&a.length>=3?[null,a,null]:z.exec(a),!c||!c[1]&&b)return!b||b.jquery?(b||x).find(a):this.constructor(b).find(a);if(c[1]){if(b=b instanceof m?b[0]:b,m.merge(this,m.parseHTML(c[1],b&&b.nodeType?b.ownerDocument||b:y,!0)),u.test(c[1])&&m.isPlainObject(b))for(c in b)m.isFunction(this[c])?this[c](b[c]):this.attr(c,b[c]);return this}if(d=y.getElementById(c[2]),d&&d.parentNode){if(d.id!==c[2])return x.find(a);this.length=1,this[0]=d}return this.context=y,this.selector=a,this}return a.nodeType?(this.context=this[0]=a,this.length=1,this):m.isFunction(a)?"undefined"!=typeof x.ready?x.ready(a):a(m):(void 0!==a.selector&&(this.selector=a.selector,this.context=a.context),m.makeArray(a,this))};A.prototype=m.fn,x=m(y);var B=/^(?:parents|prev(?:Until|All))/,C={children:!0,contents:!0,next:!0,prev:!0};m.extend({dir:function(a,b,c){var d=[],e=a[b];while(e&&9!==e.nodeType&&(void 0===c||1!==e.nodeType||!m(e).is(c)))1===e.nodeType&&d.push(e),e=e[b];return d},sibling:function(a,b){for(var c=[];a;a=a.nextSibling)1===a.nodeType&&a!==b&&c.push(a);return c}}),m.fn.extend({has:function(a){var b,c=m(a,this),d=c.length;return this.filter(function(){for(b=0;d>b;b++)if(m.contains(this,c[b]))return!0})},closest:function(a,b){for(var c,d=0,e=this.length,f=[],g=t.test(a)||"string"!=typeof a?m(a,b||this.context):0;e>d;d++)for(c=this[d];c&&c!==b;c=c.parentNode)if(c.nodeType<11&&(g?g.index(c)>-1:1===c.nodeType&&m.find.matchesSelector(c,a))){f.push(c);break}return this.pushStack(f.length>1?m.unique(f):f)},index:function(a){return a?"string"==typeof a?m.inArray(this[0],m(a)):m.inArray(a.jquery?a[0]:a,this):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(a,b){return this.pushStack(m.unique(m.merge(this.get(),m(a,b))))},addBack:function(a){return this.add(null==a?this.prevObject:this.prevObject.filter(a))}});function D(a,b){do a=a[b];while(a&&1!==a.nodeType);return a}m.each({parent:function(a){var b=a.parentNode;return b&&11!==b.nodeType?b:null},parents:function(a){return m.dir(a,"parentNode")},parentsUntil:function(a,b,c){return m.dir(a,"parentNode",c)},next:function(a){return D(a,"nextSibling")},prev:function(a){return D(a,"previousSibling")},nextAll:function(a){return m.dir(a,"nextSibling")},prevAll:function(a){return m.dir(a,"previousSibling")},nextUntil:function(a,b,c){return m.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return m.dir(a,"previousSibling",c)},siblings:function(a){return m.sibling((a.parentNode||{}).firstChild,a)},children:function(a){return m.sibling(a.firstChild)},contents:function(a){return m.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:m.merge([],a.childNodes)}},function(a,b){m.fn[a]=function(c,d){var e=m.map(this,b,c);return"Until"!==a.slice(-5)&&(d=c),d&&"string"==typeof d&&(e=m.filter(d,e)),this.length>1&&(C[a]||(e=m.unique(e)),B.test(a)&&(e=e.reverse())),this.pushStack(e)}});var E=/\S+/g,F={};function G(a){var b=F[a]={};return m.each(a.match(E)||[],function(a,c){b[c]=!0}),b}m.Callbacks=function(a){a="string"==typeof a?F[a]||G(a):m.extend({},a);var b,c,d,e,f,g,h=[],i=!a.once&&[],j=function(l){for(c=a.memory&&l,d=!0,f=g||0,g=0,e=h.length,b=!0;h&&e>f;f++)if(h[f].apply(l[0],l[1])===!1&&a.stopOnFalse){c=!1;break}b=!1,h&&(i?i.length&&j(i.shift()):c?h=[]:k.disable())},k={add:function(){if(h){var d=h.length;!function f(b){m.each(b,function(b,c){var d=m.type(c);"function"===d?a.unique&&k.has(c)||h.push(c):c&&c.length&&"string"!==d&&f(c)})}(arguments),b?e=h.length:c&&(g=d,j(c))}return this},remove:function(){return h&&m.each(arguments,function(a,c){var d;while((d=m.inArray(c,h,d))>-1)h.splice(d,1),b&&(e>=d&&e--,f>=d&&f--)}),this},has:function(a){return a?m.inArray(a,h)>-1:!(!h||!h.length)},empty:function(){return h=[],e=0,this},disable:function(){return h=i=c=void 0,this},disabled:function(){return!h},lock:function(){return i=void 0,c||k.disable(),this},locked:function(){return!i},fireWith:function(a,c){return!h||d&&!i||(c=c||[],c=[a,c.slice?c.slice():c],b?i.push(c):j(c)),this},fire:function(){return k.fireWith(this,arguments),this},fired:function(){return!!d}};return k},m.extend({Deferred:function(a){var b=[["resolve","done",m.Callbacks("once memory"),"resolved"],["reject","fail",m.Callbacks("once memory"),"rejected"],["notify","progress",m.Callbacks("memory")]],c="pending",d={state:function(){return c},always:function(){return e.done(arguments).fail(arguments),this},then:function(){var a=arguments;return m.Deferred(function(c){m.each(b,function(b,f){var g=m.isFunction(a[b])&&a[b];e[f[1]](function(){var a=g&&g.apply(this,arguments);a&&m.isFunction(a.promise)?a.promise().done(c.resolve).fail(c.reject).progress(c.notify):c[f[0]+"With"](this===d?c.promise():this,g?[a]:arguments)})}),a=null}).promise()},promise:function(a){return null!=a?m.extend(a,d):d}},e={};return d.pipe=d.then,m.each(b,function(a,f){var g=f[2],h=f[3];d[f[1]]=g.add,h&&g.add(function(){c=h},b[1^a][2].disable,b[2][2].lock),e[f[0]]=function(){return e[f[0]+"With"](this===e?d:this,arguments),this},e[f[0]+"With"]=g.fireWith}),d.promise(e),a&&a.call(e,e),e},when:function(a){var b=0,c=d.call(arguments),e=c.length,f=1!==e||a&&m.isFunction(a.promise)?e:0,g=1===f?a:m.Deferred(),h=function(a,b,c){return function(e){b[a]=this,c[a]=arguments.length>1?d.call(arguments):e,c===i?g.notifyWith(b,c):--f||g.resolveWith(b,c)}},i,j,k;if(e>1)for(i=new Array(e),j=new Array(e),k=new Array(e);e>b;b++)c[b]&&m.isFunction(c[b].promise)?c[b].promise().done(h(b,k,c)).fail(g.reject).progress(h(b,j,i)):--f;return f||g.resolveWith(k,c),g.promise()}});var H;m.fn.ready=function(a){return m.ready.promise().done(a),this},m.extend({isReady:!1,readyWait:1,holdReady:function(a){a?m.readyWait++:m.ready(!0)},ready:function(a){if(a===!0?!--m.readyWait:!m.isReady){if(!y.body)return setTimeout(m.ready);m.isReady=!0,a!==!0&&--m.readyWait>0||(H.resolveWith(y,[m]),m.fn.triggerHandler&&(m(y).triggerHandler("ready"),m(y).off("ready")))}}});function I(){y.addEventListener?(y.removeEventListener("DOMContentLoaded",J,!1),a.removeEventListener("load",J,!1)):(y.detachEvent("onreadystatechange",J),a.detachEvent("onload",J))}function J(){(y.addEventListener||"load"===event.type||"complete"===y.readyState)&&(I(),m.ready())}m.ready.promise=function(b){if(!H)if(H=m.Deferred(),"complete"===y.readyState)setTimeout(m.ready);else if(y.addEventListener)y.addEventListener("DOMContentLoaded",J,!1),a.addEventListener("load",J,!1);else{y.attachEvent("onreadystatechange",J),a.attachEvent("onload",J);var c=!1;try{c=null==a.frameElement&&y.documentElement}catch(d){}c&&c.doScroll&&!function e(){if(!m.isReady){try{c.doScroll("left")}catch(a){return setTimeout(e,50)}I(),m.ready()}}()}return H.promise(b)};var K="undefined",L;for(L in m(k))break;k.ownLast="0"!==L,k.inlineBlockNeedsLayout=!1,m(function(){var a,b,c,d;c=y.getElementsByTagName("body")[0],c&&c.style&&(b=y.createElement("div"),d=y.createElement("div"),d.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",c.appendChild(d).appendChild(b),typeof b.style.zoom!==K&&(b.style.cssText="display:inline;margin:0;border:0;padding:1px;width:1px;zoom:1",k.inlineBlockNeedsLayout=a=3===b.offsetWidth,a&&(c.style.zoom=1)),c.removeChild(d))}),function(){var a=y.createElement("div");if(null==k.deleteExpando){k.deleteExpando=!0;try{delete a.test}catch(b){k.deleteExpando=!1}}a=null}(),m.acceptData=function(a){var b=m.noData[(a.nodeName+" ").toLowerCase()],c=+a.nodeType||1;return 1!==c&&9!==c?!1:!b||b!==!0&&a.getAttribute("classid")===b};var M=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,N=/([A-Z])/g;function O(a,b,c){if(void 0===c&&1===a.nodeType){var d="data-"+b.replace(N,"-$1").toLowerCase();if(c=a.getAttribute(d),"string"==typeof c){try{c="true"===c?!0:"false"===c?!1:"null"===c?null:+c+""===c?+c:M.test(c)?m.parseJSON(c):c}catch(e){}m.data(a,b,c)}else c=void 0}return c}function P(a){var b;for(b in a)if(("data"!==b||!m.isEmptyObject(a[b]))&&"toJSON"!==b)return!1;return!0}function Q(a,b,d,e){if(m.acceptData(a)){var f,g,h=m.expando,i=a.nodeType,j=i?m.cache:a,k=i?a[h]:a[h]&&h; +if(k&&j[k]&&(e||j[k].data)||void 0!==d||"string"!=typeof b)return k||(k=i?a[h]=c.pop()||m.guid++:h),j[k]||(j[k]=i?{}:{toJSON:m.noop}),("object"==typeof b||"function"==typeof b)&&(e?j[k]=m.extend(j[k],b):j[k].data=m.extend(j[k].data,b)),g=j[k],e||(g.data||(g.data={}),g=g.data),void 0!==d&&(g[m.camelCase(b)]=d),"string"==typeof b?(f=g[b],null==f&&(f=g[m.camelCase(b)])):f=g,f}}function R(a,b,c){if(m.acceptData(a)){var d,e,f=a.nodeType,g=f?m.cache:a,h=f?a[m.expando]:m.expando;if(g[h]){if(b&&(d=c?g[h]:g[h].data)){m.isArray(b)?b=b.concat(m.map(b,m.camelCase)):b in d?b=[b]:(b=m.camelCase(b),b=b in d?[b]:b.split(" ")),e=b.length;while(e--)delete d[b[e]];if(c?!P(d):!m.isEmptyObject(d))return}(c||(delete g[h].data,P(g[h])))&&(f?m.cleanData([a],!0):k.deleteExpando||g!=g.window?delete g[h]:g[h]=null)}}}m.extend({cache:{},noData:{"applet ":!0,"embed ":!0,"object ":"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"},hasData:function(a){return a=a.nodeType?m.cache[a[m.expando]]:a[m.expando],!!a&&!P(a)},data:function(a,b,c){return Q(a,b,c)},removeData:function(a,b){return R(a,b)},_data:function(a,b,c){return Q(a,b,c,!0)},_removeData:function(a,b){return R(a,b,!0)}}),m.fn.extend({data:function(a,b){var c,d,e,f=this[0],g=f&&f.attributes;if(void 0===a){if(this.length&&(e=m.data(f),1===f.nodeType&&!m._data(f,"parsedAttrs"))){c=g.length;while(c--)g[c]&&(d=g[c].name,0===d.indexOf("data-")&&(d=m.camelCase(d.slice(5)),O(f,d,e[d])));m._data(f,"parsedAttrs",!0)}return e}return"object"==typeof a?this.each(function(){m.data(this,a)}):arguments.length>1?this.each(function(){m.data(this,a,b)}):f?O(f,a,m.data(f,a)):void 0},removeData:function(a){return this.each(function(){m.removeData(this,a)})}}),m.extend({queue:function(a,b,c){var d;return a?(b=(b||"fx")+"queue",d=m._data(a,b),c&&(!d||m.isArray(c)?d=m._data(a,b,m.makeArray(c)):d.push(c)),d||[]):void 0},dequeue:function(a,b){b=b||"fx";var c=m.queue(a,b),d=c.length,e=c.shift(),f=m._queueHooks(a,b),g=function(){m.dequeue(a,b)};"inprogress"===e&&(e=c.shift(),d--),e&&("fx"===b&&c.unshift("inprogress"),delete f.stop,e.call(a,g,f)),!d&&f&&f.empty.fire()},_queueHooks:function(a,b){var c=b+"queueHooks";return m._data(a,c)||m._data(a,c,{empty:m.Callbacks("once memory").add(function(){m._removeData(a,b+"queue"),m._removeData(a,c)})})}}),m.fn.extend({queue:function(a,b){var c=2;return"string"!=typeof a&&(b=a,a="fx",c--),arguments.lengthh;h++)b(a[h],c,g?d:d.call(a[h],h,b(a[h],c)));return e?a:j?b.call(a):i?b(a[0],c):f},W=/^(?:checkbox|radio)$/i;!function(){var a=y.createElement("input"),b=y.createElement("div"),c=y.createDocumentFragment();if(b.innerHTML="
a",k.leadingWhitespace=3===b.firstChild.nodeType,k.tbody=!b.getElementsByTagName("tbody").length,k.htmlSerialize=!!b.getElementsByTagName("link").length,k.html5Clone="<:nav>"!==y.createElement("nav").cloneNode(!0).outerHTML,a.type="checkbox",a.checked=!0,c.appendChild(a),k.appendChecked=a.checked,b.innerHTML="",k.noCloneChecked=!!b.cloneNode(!0).lastChild.defaultValue,c.appendChild(b),b.innerHTML="",k.checkClone=b.cloneNode(!0).cloneNode(!0).lastChild.checked,k.noCloneEvent=!0,b.attachEvent&&(b.attachEvent("onclick",function(){k.noCloneEvent=!1}),b.cloneNode(!0).click()),null==k.deleteExpando){k.deleteExpando=!0;try{delete b.test}catch(d){k.deleteExpando=!1}}}(),function(){var b,c,d=y.createElement("div");for(b in{submit:!0,change:!0,focusin:!0})c="on"+b,(k[b+"Bubbles"]=c in a)||(d.setAttribute(c,"t"),k[b+"Bubbles"]=d.attributes[c].expando===!1);d=null}();var X=/^(?:input|select|textarea)$/i,Y=/^key/,Z=/^(?:mouse|pointer|contextmenu)|click/,$=/^(?:focusinfocus|focusoutblur)$/,_=/^([^.]*)(?:\.(.+)|)$/;function ab(){return!0}function bb(){return!1}function cb(){try{return y.activeElement}catch(a){}}m.event={global:{},add:function(a,b,c,d,e){var f,g,h,i,j,k,l,n,o,p,q,r=m._data(a);if(r){c.handler&&(i=c,c=i.handler,e=i.selector),c.guid||(c.guid=m.guid++),(g=r.events)||(g=r.events={}),(k=r.handle)||(k=r.handle=function(a){return typeof m===K||a&&m.event.triggered===a.type?void 0:m.event.dispatch.apply(k.elem,arguments)},k.elem=a),b=(b||"").match(E)||[""],h=b.length;while(h--)f=_.exec(b[h])||[],o=q=f[1],p=(f[2]||"").split(".").sort(),o&&(j=m.event.special[o]||{},o=(e?j.delegateType:j.bindType)||o,j=m.event.special[o]||{},l=m.extend({type:o,origType:q,data:d,handler:c,guid:c.guid,selector:e,needsContext:e&&m.expr.match.needsContext.test(e),namespace:p.join(".")},i),(n=g[o])||(n=g[o]=[],n.delegateCount=0,j.setup&&j.setup.call(a,d,p,k)!==!1||(a.addEventListener?a.addEventListener(o,k,!1):a.attachEvent&&a.attachEvent("on"+o,k))),j.add&&(j.add.call(a,l),l.handler.guid||(l.handler.guid=c.guid)),e?n.splice(n.delegateCount++,0,l):n.push(l),m.event.global[o]=!0);a=null}},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,n,o,p,q,r=m.hasData(a)&&m._data(a);if(r&&(k=r.events)){b=(b||"").match(E)||[""],j=b.length;while(j--)if(h=_.exec(b[j])||[],o=q=h[1],p=(h[2]||"").split(".").sort(),o){l=m.event.special[o]||{},o=(d?l.delegateType:l.bindType)||o,n=k[o]||[],h=h[2]&&new RegExp("(^|\\.)"+p.join("\\.(?:.*\\.|)")+"(\\.|$)"),i=f=n.length;while(f--)g=n[f],!e&&q!==g.origType||c&&c.guid!==g.guid||h&&!h.test(g.namespace)||d&&d!==g.selector&&("**"!==d||!g.selector)||(n.splice(f,1),g.selector&&n.delegateCount--,l.remove&&l.remove.call(a,g));i&&!n.length&&(l.teardown&&l.teardown.call(a,p,r.handle)!==!1||m.removeEvent(a,o,r.handle),delete k[o])}else for(o in k)m.event.remove(a,o+b[j],c,d,!0);m.isEmptyObject(k)&&(delete r.handle,m._removeData(a,"events"))}},trigger:function(b,c,d,e){var f,g,h,i,k,l,n,o=[d||y],p=j.call(b,"type")?b.type:b,q=j.call(b,"namespace")?b.namespace.split("."):[];if(h=l=d=d||y,3!==d.nodeType&&8!==d.nodeType&&!$.test(p+m.event.triggered)&&(p.indexOf(".")>=0&&(q=p.split("."),p=q.shift(),q.sort()),g=p.indexOf(":")<0&&"on"+p,b=b[m.expando]?b:new m.Event(p,"object"==typeof b&&b),b.isTrigger=e?2:3,b.namespace=q.join("."),b.namespace_re=b.namespace?new RegExp("(^|\\.)"+q.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,b.result=void 0,b.target||(b.target=d),c=null==c?[b]:m.makeArray(c,[b]),k=m.event.special[p]||{},e||!k.trigger||k.trigger.apply(d,c)!==!1)){if(!e&&!k.noBubble&&!m.isWindow(d)){for(i=k.delegateType||p,$.test(i+p)||(h=h.parentNode);h;h=h.parentNode)o.push(h),l=h;l===(d.ownerDocument||y)&&o.push(l.defaultView||l.parentWindow||a)}n=0;while((h=o[n++])&&!b.isPropagationStopped())b.type=n>1?i:k.bindType||p,f=(m._data(h,"events")||{})[b.type]&&m._data(h,"handle"),f&&f.apply(h,c),f=g&&h[g],f&&f.apply&&m.acceptData(h)&&(b.result=f.apply(h,c),b.result===!1&&b.preventDefault());if(b.type=p,!e&&!b.isDefaultPrevented()&&(!k._default||k._default.apply(o.pop(),c)===!1)&&m.acceptData(d)&&g&&d[p]&&!m.isWindow(d)){l=d[g],l&&(d[g]=null),m.event.triggered=p;try{d[p]()}catch(r){}m.event.triggered=void 0,l&&(d[g]=l)}return b.result}},dispatch:function(a){a=m.event.fix(a);var b,c,e,f,g,h=[],i=d.call(arguments),j=(m._data(this,"events")||{})[a.type]||[],k=m.event.special[a.type]||{};if(i[0]=a,a.delegateTarget=this,!k.preDispatch||k.preDispatch.call(this,a)!==!1){h=m.event.handlers.call(this,a,j),b=0;while((f=h[b++])&&!a.isPropagationStopped()){a.currentTarget=f.elem,g=0;while((e=f.handlers[g++])&&!a.isImmediatePropagationStopped())(!a.namespace_re||a.namespace_re.test(e.namespace))&&(a.handleObj=e,a.data=e.data,c=((m.event.special[e.origType]||{}).handle||e.handler).apply(f.elem,i),void 0!==c&&(a.result=c)===!1&&(a.preventDefault(),a.stopPropagation()))}return k.postDispatch&&k.postDispatch.call(this,a),a.result}},handlers:function(a,b){var c,d,e,f,g=[],h=b.delegateCount,i=a.target;if(h&&i.nodeType&&(!a.button||"click"!==a.type))for(;i!=this;i=i.parentNode||this)if(1===i.nodeType&&(i.disabled!==!0||"click"!==a.type)){for(e=[],f=0;h>f;f++)d=b[f],c=d.selector+" ",void 0===e[c]&&(e[c]=d.needsContext?m(c,this).index(i)>=0:m.find(c,this,null,[i]).length),e[c]&&e.push(d);e.length&&g.push({elem:i,handlers:e})}return h]","i"),hb=/^\s+/,ib=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,jb=/<([\w:]+)/,kb=/\s*$/g,rb={option:[1,""],legend:[1,"
","
"],area:[1,"",""],param:[1,"",""],thead:[1,"","
"],tr:[2,"","
"],col:[2,"","
"],td:[3,"","
"],_default:k.htmlSerialize?[0,"",""]:[1,"X
","
"]},sb=db(y),tb=sb.appendChild(y.createElement("div"));rb.optgroup=rb.option,rb.tbody=rb.tfoot=rb.colgroup=rb.caption=rb.thead,rb.th=rb.td;function ub(a,b){var c,d,e=0,f=typeof a.getElementsByTagName!==K?a.getElementsByTagName(b||"*"):typeof a.querySelectorAll!==K?a.querySelectorAll(b||"*"):void 0;if(!f)for(f=[],c=a.childNodes||a;null!=(d=c[e]);e++)!b||m.nodeName(d,b)?f.push(d):m.merge(f,ub(d,b));return void 0===b||b&&m.nodeName(a,b)?m.merge([a],f):f}function vb(a){W.test(a.type)&&(a.defaultChecked=a.checked)}function wb(a,b){return m.nodeName(a,"table")&&m.nodeName(11!==b.nodeType?b:b.firstChild,"tr")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function xb(a){return a.type=(null!==m.find.attr(a,"type"))+"/"+a.type,a}function yb(a){var b=pb.exec(a.type);return b?a.type=b[1]:a.removeAttribute("type"),a}function zb(a,b){for(var c,d=0;null!=(c=a[d]);d++)m._data(c,"globalEval",!b||m._data(b[d],"globalEval"))}function Ab(a,b){if(1===b.nodeType&&m.hasData(a)){var c,d,e,f=m._data(a),g=m._data(b,f),h=f.events;if(h){delete g.handle,g.events={};for(c in h)for(d=0,e=h[c].length;e>d;d++)m.event.add(b,c,h[c][d])}g.data&&(g.data=m.extend({},g.data))}}function Bb(a,b){var c,d,e;if(1===b.nodeType){if(c=b.nodeName.toLowerCase(),!k.noCloneEvent&&b[m.expando]){e=m._data(b);for(d in e.events)m.removeEvent(b,d,e.handle);b.removeAttribute(m.expando)}"script"===c&&b.text!==a.text?(xb(b).text=a.text,yb(b)):"object"===c?(b.parentNode&&(b.outerHTML=a.outerHTML),k.html5Clone&&a.innerHTML&&!m.trim(b.innerHTML)&&(b.innerHTML=a.innerHTML)):"input"===c&&W.test(a.type)?(b.defaultChecked=b.checked=a.checked,b.value!==a.value&&(b.value=a.value)):"option"===c?b.defaultSelected=b.selected=a.defaultSelected:("input"===c||"textarea"===c)&&(b.defaultValue=a.defaultValue)}}m.extend({clone:function(a,b,c){var d,e,f,g,h,i=m.contains(a.ownerDocument,a);if(k.html5Clone||m.isXMLDoc(a)||!gb.test("<"+a.nodeName+">")?f=a.cloneNode(!0):(tb.innerHTML=a.outerHTML,tb.removeChild(f=tb.firstChild)),!(k.noCloneEvent&&k.noCloneChecked||1!==a.nodeType&&11!==a.nodeType||m.isXMLDoc(a)))for(d=ub(f),h=ub(a),g=0;null!=(e=h[g]);++g)d[g]&&Bb(e,d[g]);if(b)if(c)for(h=h||ub(a),d=d||ub(f),g=0;null!=(e=h[g]);g++)Ab(e,d[g]);else Ab(a,f);return d=ub(f,"script"),d.length>0&&zb(d,!i&&ub(a,"script")),d=h=e=null,f},buildFragment:function(a,b,c,d){for(var e,f,g,h,i,j,l,n=a.length,o=db(b),p=[],q=0;n>q;q++)if(f=a[q],f||0===f)if("object"===m.type(f))m.merge(p,f.nodeType?[f]:f);else if(lb.test(f)){h=h||o.appendChild(b.createElement("div")),i=(jb.exec(f)||["",""])[1].toLowerCase(),l=rb[i]||rb._default,h.innerHTML=l[1]+f.replace(ib,"<$1>")+l[2],e=l[0];while(e--)h=h.lastChild;if(!k.leadingWhitespace&&hb.test(f)&&p.push(b.createTextNode(hb.exec(f)[0])),!k.tbody){f="table"!==i||kb.test(f)?""!==l[1]||kb.test(f)?0:h:h.firstChild,e=f&&f.childNodes.length;while(e--)m.nodeName(j=f.childNodes[e],"tbody")&&!j.childNodes.length&&f.removeChild(j)}m.merge(p,h.childNodes),h.textContent="";while(h.firstChild)h.removeChild(h.firstChild);h=o.lastChild}else p.push(b.createTextNode(f));h&&o.removeChild(h),k.appendChecked||m.grep(ub(p,"input"),vb),q=0;while(f=p[q++])if((!d||-1===m.inArray(f,d))&&(g=m.contains(f.ownerDocument,f),h=ub(o.appendChild(f),"script"),g&&zb(h),c)){e=0;while(f=h[e++])ob.test(f.type||"")&&c.push(f)}return h=null,o},cleanData:function(a,b){for(var d,e,f,g,h=0,i=m.expando,j=m.cache,l=k.deleteExpando,n=m.event.special;null!=(d=a[h]);h++)if((b||m.acceptData(d))&&(f=d[i],g=f&&j[f])){if(g.events)for(e in g.events)n[e]?m.event.remove(d,e):m.removeEvent(d,e,g.handle);j[f]&&(delete j[f],l?delete d[i]:typeof d.removeAttribute!==K?d.removeAttribute(i):d[i]=null,c.push(f))}}}),m.fn.extend({text:function(a){return V(this,function(a){return void 0===a?m.text(this):this.empty().append((this[0]&&this[0].ownerDocument||y).createTextNode(a))},null,a,arguments.length)},append:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=wb(this,a);b.appendChild(a)}})},prepend:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=wb(this,a);b.insertBefore(a,b.firstChild)}})},before:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this)})},after:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this.nextSibling)})},remove:function(a,b){for(var c,d=a?m.filter(a,this):this,e=0;null!=(c=d[e]);e++)b||1!==c.nodeType||m.cleanData(ub(c)),c.parentNode&&(b&&m.contains(c.ownerDocument,c)&&zb(ub(c,"script")),c.parentNode.removeChild(c));return this},empty:function(){for(var a,b=0;null!=(a=this[b]);b++){1===a.nodeType&&m.cleanData(ub(a,!1));while(a.firstChild)a.removeChild(a.firstChild);a.options&&m.nodeName(a,"select")&&(a.options.length=0)}return this},clone:function(a,b){return a=null==a?!1:a,b=null==b?a:b,this.map(function(){return m.clone(this,a,b)})},html:function(a){return V(this,function(a){var b=this[0]||{},c=0,d=this.length;if(void 0===a)return 1===b.nodeType?b.innerHTML.replace(fb,""):void 0;if(!("string"!=typeof a||mb.test(a)||!k.htmlSerialize&&gb.test(a)||!k.leadingWhitespace&&hb.test(a)||rb[(jb.exec(a)||["",""])[1].toLowerCase()])){a=a.replace(ib,"<$1>");try{for(;d>c;c++)b=this[c]||{},1===b.nodeType&&(m.cleanData(ub(b,!1)),b.innerHTML=a);b=0}catch(e){}}b&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(){var a=arguments[0];return this.domManip(arguments,function(b){a=this.parentNode,m.cleanData(ub(this)),a&&a.replaceChild(b,this)}),a&&(a.length||a.nodeType)?this:this.remove()},detach:function(a){return this.remove(a,!0)},domManip:function(a,b){a=e.apply([],a);var c,d,f,g,h,i,j=0,l=this.length,n=this,o=l-1,p=a[0],q=m.isFunction(p);if(q||l>1&&"string"==typeof p&&!k.checkClone&&nb.test(p))return this.each(function(c){var d=n.eq(c);q&&(a[0]=p.call(this,c,d.html())),d.domManip(a,b)});if(l&&(i=m.buildFragment(a,this[0].ownerDocument,!1,this),c=i.firstChild,1===i.childNodes.length&&(i=c),c)){for(g=m.map(ub(i,"script"),xb),f=g.length;l>j;j++)d=i,j!==o&&(d=m.clone(d,!0,!0),f&&m.merge(g,ub(d,"script"))),b.call(this[j],d,j);if(f)for(h=g[g.length-1].ownerDocument,m.map(g,yb),j=0;f>j;j++)d=g[j],ob.test(d.type||"")&&!m._data(d,"globalEval")&&m.contains(h,d)&&(d.src?m._evalUrl&&m._evalUrl(d.src):m.globalEval((d.text||d.textContent||d.innerHTML||"").replace(qb,"")));i=c=null}return this}}),m.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){m.fn[a]=function(a){for(var c,d=0,e=[],g=m(a),h=g.length-1;h>=d;d++)c=d===h?this:this.clone(!0),m(g[d])[b](c),f.apply(e,c.get());return this.pushStack(e)}});var Cb,Db={};function Eb(b,c){var d,e=m(c.createElement(b)).appendTo(c.body),f=a.getDefaultComputedStyle&&(d=a.getDefaultComputedStyle(e[0]))?d.display:m.css(e[0],"display");return e.detach(),f}function Fb(a){var b=y,c=Db[a];return c||(c=Eb(a,b),"none"!==c&&c||(Cb=(Cb||m("