4 |
5 |
6 |
--------------------------------------------------------------------------------
/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
--------------------------------------------------------------------------------
/.idea/modules.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/.idea/vcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | # CONTRIBUTING
2 |
3 | ### Contributing Guidelines!
4 |
5 | Read this space to know the contributing guidelines. Please follow the guidelines for smooth contribution. Following the guidelines reflect your courtesy towards the open source contribution. The issues, potential changes and pull requests will be addressed in compliance with the quality of need and urgency.
6 |
7 | ### Expected Contribution:
8 | In case you are willing to contribute in any form, You're most Welcome! Improvement in documentation, reporting bugs and mistakes is expected in general.
9 |
10 | # Getting started
11 |
12 | ## Ground Rules
13 | Issues should be created to submit a change to the repository before opening a pull request. Communication in any form except the repository channels is not expected and will not be entertained.
14 |
15 |
16 | # Your First Contribution
17 | In case you have additions to the concepts, codebase, or anything relevant, You're most welcome to open an issue, followed by opening a pull request. You are again welcome to report a mistake in the existing content, and code obselete issues.
18 |
19 |
20 | ### Know More about open Source Contributions:
21 | Here are a couple of friendly tutorials you can go through: http://makeapullrequest.com/ and http://www.firsttimersonly.com/
22 |
--------------------------------------------------------------------------------
/Course Introduction/Introduction.md:
--------------------------------------------------------------------------------
1 | # Learning Object Oriented Python
2 |
3 | This repository walks you through the Object Oriented Programming concepts in python. Illustrates real-world examples, working codes and how to go about finding a coding solution.
4 |
5 | The course plan is as shown in the repository. There are four lessons which govern the flow of the course. It is highly recommended to refer to online resources for a detailed study about the mentioned topics which have been briefly covered.
6 |
7 | For the Tasks study in depth about the problem statements, conduct online research about various available modules and then start coding. Coding solutions have been provided in the resources folder.
8 |
9 |
10 | ## Course Breakdown:
11 |
12 |
13 |
14 | * Lesson 1: Introduction To Python
15 | * Download
16 | * Installation
17 | * About Python
18 | * Lesson 2: Using Functions
19 | * About Functions
20 | * Python Standard Library
21 | * Inbuilt Functions
22 | * Task 1
23 | * Task 2
24 | * Lesson 3: Introduction To OOP
25 | * About
26 | * Lesson 4: OOP Implementation
27 | * Task 1
28 | * Task 2
29 | * Lesson 5: Web Sraping
30 | * Web Scraping - Introduction
31 |
--------------------------------------------------------------------------------
/Examples/.gitignore:
--------------------------------------------------------------------------------
1 | # Byte-compiled / optimized / DLL files
2 | __pycache__/
3 | *.py[cod]
4 | *$py.class
5 |
6 | # C extensions
7 | *.so
8 |
9 | # Distribution / packaging
10 | .Python
11 | build/
12 | develop-eggs/
13 | dist/
14 | downloads/
15 | eggs/
16 | .eggs/
17 | lib/
18 | lib64/
19 | parts/
20 | sdist/
21 | var/
22 | wheels/
23 | pip-wheel-metadata/
24 | share/python-wheels/
25 | *.egg-info/
26 | .installed.cfg
27 | *.egg
28 | MANIFEST
29 |
30 | # PyInstaller
31 | # Usually these files are written by a python script from a template
32 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
33 | *.manifest
34 | *.spec
35 |
36 | # Installer logs
37 | pip-log.txt
38 | pip-delete-this-directory.txt
39 |
40 | # Unit test / coverage reports
41 | htmlcov/
42 | .tox/
43 | .nox/
44 | .coverage
45 | .coverage.*
46 | .cache
47 | nosetests.xml
48 | coverage.xml
49 | *.cover
50 | .hypothesis/
51 | .pytest_cache/
52 |
53 | # Translations
54 | *.mo
55 | *.pot
56 |
57 | # Django stuff:
58 | *.log
59 | local_settings.py
60 | db.sqlite3
61 | db.sqlite3-journal
62 |
63 | # Flask stuff:
64 | instance/
65 | .webassets-cache
66 |
67 | # Scrapy stuff:
68 | .scrapy
69 |
70 | # Sphinx documentation
71 | docs/_build/
72 |
73 | # PyBuilder
74 | target/
75 |
76 | # Jupyter Notebook
77 | .ipynb_checkpoints
78 |
79 | # IPython
80 | profile_default/
81 | ipython_config.py
82 |
83 | # pyenv
84 | .python-version
85 |
86 | # pipenv
87 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
88 | # However, in case of collaboration, if having platform-specific dependencies or dependencies
89 | # having no cross-platform support, pipenv may install dependencies that don't work, or not
90 | # install all needed dependencies.
91 | #Pipfile.lock
92 |
93 | # celery beat schedule file
94 | celerybeat-schedule
95 |
96 | # SageMath parsed files
97 | *.sage.py
98 |
99 | # Environments
100 | .env
101 | .venv
102 | env/
103 | venv/
104 | ENV/
105 | env.bak/
106 | venv.bak/
107 |
108 | # Spyder project settings
109 | .spyderproject
110 | .spyproject
111 |
112 | # Rope project settings
113 | .ropeproject
114 |
115 | # mkdocs documentation
116 | /site
117 |
118 | # mypy
119 | .mypy_cache/
120 | .dmypy.json
121 | dmypy.json
122 |
123 | # Pyre type checker
124 | .pyre/
125 |
126 | .DS_Store
127 |
128 | .vscode/
129 |
130 | # Elastic Beanstalk Files
131 | .elasticbeanstalk/*
132 | !.elasticbeanstalk/*.cfg.yml
133 | !.elasticbeanstalk/*.global.yml
134 |
--------------------------------------------------------------------------------
/Examples/Binary_Search.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | """
3 | Created on Wed Oct 9 07:36:45 2019
4 |
5 | @author: hp
6 | """
7 |
8 | # Returns index of x in arr if present, else -1
9 | def binarySearch (arr, l, r, x):
10 |
11 | # Check base case
12 | if r >= l:
13 |
14 | mid = l + (r - l)/2
15 |
16 | # If element is present at the middle itself
17 | if arr[mid] == x:
18 | return mid
19 |
20 | # If element is smaller than mid, then it can only
21 | # be present in left subarray
22 | elif arr[mid] > x:
23 | return binarySearch(arr, l, mid-1, x)
24 |
25 | # Else the element can only be present in right subarray
26 | else:
27 | return binarySearch(arr, mid+1, r, x)
28 |
29 | else:
30 | # Element is not present in the array
31 | return -1
32 |
--------------------------------------------------------------------------------
/Examples/LinkedList.py:
--------------------------------------------------------------------------------
1 | # Linked list implementation using OOP
2 |
3 | # Node class
4 | class Node:
5 |
6 | # Function to initialize the node object
7 | def __init__(self, data):
8 | self.data = data # Assign data
9 | self.next = None # Initialize
10 | # next as null
11 |
12 | # Linked List class
13 | class LinkedList:
14 |
15 | # Function to initialize the Linked
16 | # List object
17 | def __init__(self):
18 | self.head = None
19 | # Here self.head is basically initialised with a null value
20 | # This function prints contents of linked list
21 | # starting from head
22 | def printList(self):
23 | temp = self.head
24 | while (temp):
25 | print(temp.data)
26 | temp = temp.next
27 |
28 | # Code execution starts here
29 | if __name__ == '__main__':
30 |
31 | # Start with the empty list
32 | llist = LinkedList()
33 |
34 | llist.head = Node(1)
35 | second = Node(2)
36 | third = Node(3)
37 |
38 | # Three nodes have been created.
39 | # We have references to these three blocks as head,
40 | # second and third
41 |
42 | llist.head.next = second # Link first node with second
43 | second.next = third # Link second node with the third node
44 | llist.printList()
45 |
--------------------------------------------------------------------------------
/Examples/Multilevel_Inheritance.py:
--------------------------------------------------------------------------------
1 | """
2 | This is an example of Multilevel Inheritance
3 |
4 | Instructions:
5 | - Create a class Person with Name, Age & Sex
6 | - Create a class Employee which inherits from Person and has properties Id, Salary & Department
7 | - Create a class Manager which inherits from Employee and has properties List of Reportees
8 | - The Employee class inherits from Person, so it gets all the properties of Person class
9 | - The Manager class inherits from Employee so it gets all properties of Employees as well as Person class
10 | """
11 |
12 |
13 | class Person(object):
14 | def __init__(self, name, age, sex):
15 | self.name = name
16 | self.age = age
17 | self.sex = sex
18 |
19 | def print_details(self):
20 | print("Name: {}".format(self.name))
21 | print("Age: {}".format(self.age))
22 | print("Sex: {}".format(self.sex))
23 |
24 |
25 | class Employee(Person):
26 | """
27 | Employee class inherits from Person
28 | """
29 | employee_count = 0
30 |
31 | def __init__(self, name, age, sex, department):
32 | super().__init__(name, age, sex)
33 | self.department = department
34 | Employee.employee_count = Employee.employee_count + 1
35 | self.id = Employee.employee_count
36 | self.manager = None
37 | print("Employee Added : Id {} Name {}".format(self.id, self.name))
38 |
39 | def print_details(self):
40 | print("Id: {}".format(self.id))
41 | super().print_details()
42 | print("Department: {}".format(self.department))
43 |
44 | def print_manager(self):
45 | print("{} reports to {}".format(self.name, self.manager.name))
46 |
47 |
48 | class Manager(Employee):
49 | """
50 | Manager class inherits from Employee because every Manager is also an Employee
51 | """
52 | def __init__(self, name, age, sex, department):
53 | super().__init__(name, age, sex, department)
54 | self.reportees = []
55 |
56 | def print_details(self):
57 | print("\nTeam Information")
58 | super().print_details()
59 | self.print_reportees()
60 |
61 | def add_reportee(self, reportee):
62 | reportee.manager = self
63 | self.reportees.append(reportee)
64 | print("{} now reports to {}".format(reportee.name, self.name))
65 |
66 | def print_reportees(self):
67 | print("Employees reporting to {} are:".format(self.name))
68 | for employee in self.reportees:
69 | employee.print_details()
70 |
71 |
72 | def main():
73 | # Lets create few employees
74 | joe = Employee("Joe", 25, "M", "Tech")
75 | mark = Employee("Mark", 26, "M", "Finance")
76 | anjali = Employee("Anjalee", 24, "F", "Tech")
77 | sweta = Employee("Sweta", 29, "F", "Tech")
78 |
79 | # Lets create few Managers
80 | abhilash = Manager("Abhilash",32, "M", "Finance")
81 | paul = Manager("Paul", 28, "M", "Tech")
82 |
83 | # Mark reports to Abhilash
84 | abhilash.add_reportee(mark)
85 |
86 | # Lets add reportees to paul
87 | paul.add_reportee(joe)
88 | paul.add_reportee(anjali)
89 | paul.add_reportee(sweta)
90 |
91 | # Let's display some info!
92 | abhilash.print_details()
93 | paul.print_details()
94 |
95 |
96 | # To run the code
97 | if __name__ == '__main__':
98 | main()
99 |
--------------------------------------------------------------------------------
/Examples/String Manipulation/BooleanStringTest.py:
--------------------------------------------------------------------------------
1 | print("python".isalnum())
2 | print("3".isdigit())
3 | print("3rd".isalnum())
4 | print("Hii".islower())
5 | print("Super".startswith("s"))
6 | print("Harry Potter".istitle())
7 | length = "3"
8 | print("s")
9 | print(length.isalnum())
--------------------------------------------------------------------------------
/Examples/String Manipulation/FormatString.py:
--------------------------------------------------------------------------------
1 | print("Python is awesome".capitalize())
2 | print("PYTHON IS KING".lower())
3 | print("python is hot".upper())
4 | print("Harry potter and the half-blood prince".title())
5 | print("AVENGER:the war of infinity".swapcase())
--------------------------------------------------------------------------------
/Examples/String Manipulation/FormatStringInput.py:
--------------------------------------------------------------------------------
1 | favColor = input("What is your favorite color:-").upper() #makes every letter CAPITAL
2 | print(favColor)
3 |
4 | #or
5 |
6 | favColor = input("What's your favorite color:-")
7 | print(favColor.capitalize()) #makes first letter Capital
--------------------------------------------------------------------------------
/Examples/String Manipulation/StringComparison.py:
--------------------------------------------------------------------------------
1 | name = input("Enter name: ")
2 |
3 | if name.lower() < "c":
4 | print("less than")
5 | else:
6 | print("greater than")
--------------------------------------------------------------------------------
/Examples/String Manipulation/StringLength.py:
--------------------------------------------------------------------------------
1 | word = "Hey Python"
2 | print(len(word))
3 |
4 | len_word = len(word)
5 | mid_pt = int(len_word/2)
6 |
7 | print(word[mid_pt:])
8 | print(word[:mid_pt])
--------------------------------------------------------------------------------
/Examples/String Manipulation/StringSlicing.py:
--------------------------------------------------------------------------------
1 | word = "photosynthesis"
2 |
3 | #otosy
4 | print(word[2:7]) #strts from 2 and ends before 7
5 | #photo
6 | print(word[:5]) #ends before 5
7 | #photosynthesis
8 | print(word[:]) #print whole string
9 | #ptyhi
10 | print(word[::3]) #print 0 and multiple of 3 afterwards
11 | #tyhi
12 | print(word[3::3]) #print 3 and multiple of 3 afterwards
13 | #photosynthesi
14 | print(word[:-1]) #ends before -1
15 | #photosy
16 | print(word[:-7]) #ends before -7
17 | #sisehtnysotohp
18 | print(word[::-1]) #print string in reverse
19 | #sotohp
20 | print(word[5::-1]) #print reverse till 5
--------------------------------------------------------------------------------
/Examples/Student_Professor.py:
--------------------------------------------------------------------------------
1 | #Anuneet Anand
2 |
3 | '''
4 | A sample code to show Object Oriented Programming in Python.
5 | Two class definitions are given : Student Class & Professor Class
6 | Student Class has attributes - Roll Number , Name , Group (Red/Blue)
7 | Professor Class has attributes - Name , Subject , List Of Student Objects
8 | Three objects of student class are instantiated in main() and are assigned to a professor which is also instantiated in main().
9 | Another student object is instantiated and it's equality is tested, followed by modification of it's data attributes through Setters.
10 | Print Details Function of both the classes are called in main()
11 | '''
12 |
13 | #Information about a student.
14 | class Student:
15 |
16 | # Constructor
17 | def __init__(self,Roll_Number,Name,Group):
18 | self.Roll_Number = Roll_Number
19 | self.Name = Name
20 | self.Group = Group
21 |
22 | # Equals Method : To check if two objects of this class are equal.
23 | def __eq__(self, other):
24 | if isinstance(other, self.__class__):
25 | return (self.Roll_Number == other.Roll_Number) and (self.Name == other.Name) and (self.Group == other.Group)
26 | else:
27 | return False
28 |
29 | #SETTERS
30 | def set_Group(self,New_Group):
31 | self.Group = New_Group
32 |
33 | #GETTERS
34 | def get_Roll_Number(self):
35 | return self.Roll_Number
36 | def get_Name(self):
37 | return self.Name
38 | def get_Group(self):
39 | return self.Group
40 |
41 | # Print Method : To print the data attributes of the class.
42 | def Print_Details(self):
43 | print(">--- Student Details ---<")
44 | print("Roll Number:",self.Roll_Number)
45 | print("Name:",self.Name)
46 | print("Group:",self.Group)
47 |
48 | #Information about a professor.
49 | class Professor:
50 |
51 | # Constructor
52 | def __init__(self,Name,Subject):
53 | self.Name = Name
54 | self.Subject = Subject
55 | self.Students = []
56 |
57 | #SETTERS
58 | def set_Students(self,Students_List):
59 | self.Students = Students_List
60 |
61 | #GETTERS
62 | def get_Name(self):
63 | return self.Name
64 | def get_Subject(self):
65 | return self.Subject
66 | def get_Students(self):
67 | return self.Students
68 |
69 | # Print Method : To print the data attributes of the class.
70 | def Print_Details(self):
71 | print(">--- Professor Details ---<")
72 | print("Name:",self.Name)
73 | print("Subject:",self.Subject)
74 | print("NUmber Of Students:",len(self.Students))
75 |
76 |
77 | if __name__ == '__main__':
78 | P = Professor("Samuel","Physics")
79 | S1 = Student(1,"Andy","Red")
80 | S2 = Student(2,"Jack","Blue")
81 | S3 = Student(3,"Sam","Blue")
82 | SX = Student(2,"Jack","Red") # Extra Student
83 | L = [S1,S2,S3] # List Of Students
84 | P.set_Students(L)
85 |
86 | if (S2==SX): # Testing Equality
87 | S2.Print_Details() # Fails : Red in SX but Blue in S2
88 | else:
89 | print("Not Equal")
90 |
91 | SX.set_Group("Blue") # Modifying Data Attribute
92 |
93 | if (S2==SX): # Testing Equality
94 | S2.Print_Details() # Passes :- Printing Details Of S2
95 | else:
96 | print("Not Equal")
97 |
98 | P.Print_Details() # Printing Details Of Professor
99 |
100 | #END OF CODE
101 |
102 |
--------------------------------------------------------------------------------
/Examples/basic_class.py:
--------------------------------------------------------------------------------
1 | # Example of Object Oriented Programming (OOP) classes and objects.
2 |
3 | # First we need to declare the class that will server us as a "template".
4 | class Plane:
5 | def __init__(self, model, seats):
6 | # The init function is the function executed when we first create (instanciate)
7 | # the class in the main programm. When we instanciate a class we have an object.
8 | # In this init we declare the variables that we are going to use for the class.
9 | self.plane_model = model
10 | self.number_seats = seats
11 |
12 | # This two functions will return us the value of the object when we call them on the
13 | # main program.
14 | def model(self):
15 | return self.model
16 |
17 | def seats(self):
18 | return self.seats
19 |
20 | # And with this two functions we can change the values of the class variables.
21 | def change_model(self, model):
22 | self.plane_model = model
23 |
24 | def change_seats(self, seats):
25 | self.number_seats = seats
26 |
27 |
28 | def main():
29 | # To use a class, first we have to create an object of that class (instanciate it).
30 | # And since we defined the init function with two parameters, we have to pass them
31 | # to the class. As you can see here we have an object "boeing" and an "object" cesna,
32 | # both of the class "Plane".
33 | boeing = Plane('Boeing 787', '200')
34 | cesna = Plane('Cesna', '4')
35 |
36 | # And now with the objects we can call the other functions we have defined.
37 | print(boeing.model())
38 | print(cesna.seats())
39 |
40 | # We can also change the values of the object with the functions we have made.
41 | boeing.change_seats(202)
42 | cesna.change_model('Cesna 070')
43 |
44 |
45 | if __name__ == "__main__":
46 | main()
47 |
--------------------------------------------------------------------------------
/Examples/calculator.py:
--------------------------------------------------------------------------------
1 | '''
2 | A simple calculator using oop in python
3 | '''
4 |
5 | # A calculator class
6 | class Calc():
7 |
8 | # functions to define our operators (+,-,*,/)
9 | @staticmethod
10 | def add(x, y):
11 | return x + y
12 |
13 | @staticmethod
14 | def sub(x, y):
15 | return x - y
16 |
17 | @staticmethod
18 | def mul(x, y):
19 | return x * y
20 |
21 | @staticmethod
22 | def div(x, y):
23 | return x / y
24 |
25 | # Define a function to get our integer inputs
26 | @staticmethod
27 | def get_numbers():
28 | num1 = int(input("Enter first number: "))
29 | num2 = int(input("Enter second number: "))
30 | return num1, num2
31 |
32 | # Define a function to get the operator which will determine the operation to carry out on the inputed integers
33 | @staticmethod
34 | def get_operator():
35 | operator = input('''
36 | Please type in the math operation you would like to complete:
37 | + for addition
38 | - for subtraction
39 | * for multiplication
40 | / for division
41 | ''')
42 | return operator
43 |
44 | # Define our function to perform the operation
45 | @classmethod
46 | def calculate(cls):
47 | num1, num2 = cls.get_numbers()
48 | operator = cls.get_operator()
49 | if operator == '+':
50 | print (cls.add(num1, num2))
51 | elif operator == '-':
52 | print (cls.sub(num1, num2))
53 | elif operator == '*':
54 | print (cls.mul(num1, num2))
55 | elif operator == '/':
56 | print (cls.div(num1, num2))
57 | else:
58 | print('You have not typed a valid operator, please run the program again.')
59 |
60 | Calc.again()
61 |
62 | # Define again() function to ask user if they want to use the calculator again
63 | @classmethod
64 | def again(cls):
65 |
66 | # Take input from user
67 | calc_again = input('''
68 | Do you want to calculate again?
69 | Please type Y for YES or N for NO.
70 | ''')
71 |
72 | # If user types Y, run the calculate() function
73 | if calc_again.upper() == 'Y':
74 | Calc.calculate()
75 |
76 | # If user types N, say good-bye to the user and end the program
77 | elif calc_again.upper() == 'N':
78 | print('See you later.')
79 |
80 | # If user types another key, run the function again
81 | else:
82 | Calc.again()
83 |
84 | # Call calculate() outside of the function
85 | Calc.calculate()
--------------------------------------------------------------------------------
/Examples/circular_queue.py:
--------------------------------------------------------------------------------
1 | #This is an example class that implements a circular queue
2 | #An explanation of how the circular queue operates can be found
3 | #here https://www.studytonight.com/data-structures/circular-queue
4 |
5 | class Queue():
6 | SIZE = 5 #A constant to define the size of the queue
7 |
8 | def __init__(self):
9 | self.__items =[""]*self.SIZE
10 | self.__front = -1
11 | self.__rear = -1
12 |
13 | def isFull(self):
14 | if(self.__front == 0 and self.__rear == self.SIZE -1):
15 | return True
16 | if(self.__front == self.__rear + 1):
17 | return True
18 | return False
19 |
20 | def isEmpty(self):
21 | if(self.__front == -1):
22 | return True
23 | return False
24 |
25 | def enQueue(self, element):
26 | if(self.isFull()):
27 | print("Queue is full")
28 | else:
29 | if(self.__front == -1):
30 | self.__front = 0
31 | self.__rear = (self.__rear + 1)%self.SIZE
32 | self.__items[self.__rear] = element
33 | print("Inserted", element)
34 |
35 | def deQueue(self):
36 | if(self.isEmpty()):
37 | print("Queue is empty")
38 | return -1
39 | else:
40 | element = self.__items[self.__front]
41 | if(self.__front == self.__rear):
42 | self.__front = -1
43 | self.__rear = -1
44 | else:
45 | self.__front = (self.__front+1)%self.SIZE
46 | return element
47 |
48 | def Display(self):
49 | if(self.isEmpty()):
50 | print("Empty Queue")
51 | else:
52 | print("Front",self.__front)
53 | print("End", self.__rear)
54 | print("Items")
55 | i = self.__front
56 | while(i != self.__rear):
57 | print(self.__items[i])
58 | i = (i+1)%self.SIZE
59 | print(self.__items[i])
60 |
61 | #This is the main program illustrating the use of the queue
62 |
63 | myQ = Queue() #Instantiate a new queue
64 | myQ.deQueue() #Should give -1 error
65 |
66 | myQ.enQueue(1) #Add some data to the queue
67 | myQ.enQueue(2)
68 | myQ.enQueue(3)
69 | myQ.enQueue(4)
70 | myQ.enQueue(5)
71 |
72 | #This one should fail, queue full
73 | myQ.enQueue(6)
74 |
75 | myQ.Display()
76 |
77 | x = myQ.deQueue() #Remove 2 items from the queue
78 | x = myQ.deQueue()
79 |
80 | myQ.Display()
81 |
--------------------------------------------------------------------------------
/Examples/comprehensive_example.py:
--------------------------------------------------------------------------------
1 | """
2 | This is a comprehensive example of classes, instantiating its objects
3 | inside another class, and using its properties, static variables and static methods
4 |
5 | What this example demonstrates:
6 | - Idea of class, object, static / class variables, properties
7 | Instructions:
8 | - Create the classes Student, Teacher, Course, Degree and Program.
9 | - Each class should have a variable for the no. of students, teachers, courses, degrees and programs respectively
10 | - The private members of the class should be encapsulated via properties
11 | - The Course class should be able to hold the number of students enrolled in that specific course
12 | - Similarly, the Degree class should hold the number of courses and the Program class should hold the number of degrees
13 | - Instantiate 4 students, 4 teachers, 2 courses to demonstrate the use of classes in this context
14 | - At the end of this exercise, display the total number of students, teachers and courses, the name of
15 | students enrolled in each course.
16 | """
17 |
18 | class Student(object):
19 | # this is a static or class variable
20 | __student_count = 0
21 |
22 | # this is the constructor. Note that self implies that specific
23 | # instance or object of the class
24 | def __init__(self, name, age):
25 | # here, we assign the name and age given through the constructor
26 | # to the instance variables name and age respectively
27 | self.__name = name
28 | self.__age = age
29 | Student.__student_count += 1
30 |
31 | # use properties to get and set a private variable - data encapsulation
32 | @property
33 | def name(self):
34 | return self.__name
35 |
36 | @name.setter
37 | def name(self, name):
38 | self.__name = name
39 |
40 | @property
41 | def age(self):
42 | return self.__age
43 |
44 | @age.setter
45 | def age(self, age):
46 | self.__age = age
47 |
48 | @staticmethod
49 | def student_count():
50 | return Student.__student_count
51 |
52 |
53 | # Now, let's create a teacher class
54 | class Teacher(object):
55 | # this is again a static or class variable
56 | __teacher_count = 0
57 |
58 | # constructor
59 | def __init__(self, name, course):
60 | # let's use __ to represent private variables
61 | self.__name = name
62 | self.__course = course
63 | Teacher.__teacher_count += 1
64 |
65 | # use properties to get and set a private variable - data encapsulation
66 | @property
67 | def name(self):
68 | return self.__name
69 |
70 | @name.setter
71 | def name(self, name):
72 | self.__name = name
73 |
74 | @property
75 | def course(self):
76 | return self.__course
77 |
78 | @course.setter
79 | def course(self, course):
80 | self.__course = course
81 |
82 | @staticmethod
83 | def teacher_count():
84 | return Teacher.__teacher_count
85 |
86 |
87 | # Next, let's create a course class
88 | class Course(object):
89 | # class variable
90 | __course_count = 0
91 |
92 | # constructor
93 | def __init__(self, course_name):
94 | self.__course_name = course_name
95 | # let's store an array of students enrolled for a specific course
96 | self.__students_enrolled = []
97 | self.__teacher = None
98 | Course.__course_count += 1
99 |
100 | @property
101 | def course_name(self):
102 | return self.__course_name
103 |
104 | @course_name.setter
105 | def course_name(self, name):
106 | self.__course_name = name
107 |
108 | @property
109 | def students_enrolled(self):
110 | return self.__students_enrolled
111 |
112 | @students_enrolled.setter
113 | def students_enrolled(self, students):
114 | self.__students_enrolled = students
115 |
116 | @property
117 | def teacher(self):
118 | return self.__teacher
119 |
120 | @teacher.setter
121 | def teacher(self, teacher):
122 | self.__teacher = teacher
123 |
124 | # static, since it needs to be called independent of the object
125 | @staticmethod
126 | def course_count():
127 | return Course.__course_count
128 |
129 |
130 | # Let's create a class for Degree
131 | class Degree(object):
132 | # a static/class variable
133 | __degree_count = 0
134 |
135 | # constructor
136 | def __init__(self, name):
137 | self.__degree_name = name
138 | self.__courses = []
139 | Degree.__degree_count += 1
140 |
141 | @property
142 | def degree_name(self):
143 | return self.__degree_name
144 |
145 | @degree_name.setter
146 | def degree_name(self, name):
147 | self.__degree_name = name
148 |
149 | @property
150 | def courses(self):
151 | return self.__courses
152 |
153 | @courses.setter
154 | def courses(self, courses):
155 | self.__courses = courses
156 |
157 | @staticmethod
158 | def degree_count():
159 | return Degree.__degree_count
160 |
161 |
162 | # Let's create a class for University Program
163 | class Program(object):
164 | # static variable
165 | __program_count = 0
166 |
167 | # constructor
168 | def __init__(self, name):
169 | self.__program_name = name
170 | self.__degrees = []
171 | Program.__program_count += 1
172 |
173 | @property
174 | def program(self):
175 | return self.__program_name
176 |
177 | @program.setter
178 | def program(self, name):
179 | self.__program_name = name
180 |
181 | @property
182 | def degrees(self):
183 | return self.__degrees
184 |
185 | @degrees.setter
186 | def degrees(self, degrees):
187 | self.__degrees = degrees
188 |
189 | @staticmethod
190 | def program_count():
191 | return Program.__program_count
192 |
193 |
194 | # main entry point function
195 | def main():
196 | # Let's create four students
197 | joe = Student("Joe", 15)
198 | mark = Student("Mark", 16)
199 | anjali = Student("Anjalee", 14)
200 | sweta = Student("Sweta", 15)
201 |
202 | # Let's create four teachers
203 | abhilash = Teacher("Abhilash", "Digital Signal Processing")
204 | paul = Teacher("Paul", "Signals and Systems")
205 | raghu = Teacher("Raghu", "Electronic Circuits")
206 | george = Teacher("George", "Logic Design")
207 |
208 | # Let's create 2 courses and assign students for each course and a teacher
209 | digital_signal_processing = Course("Digital Signal Processing")
210 | # can also use .append() method of list
211 | digital_signal_processing.students_enrolled = [joe, mark, sweta]
212 | digital_signal_processing.teacher = abhilash
213 |
214 | signals_systems = Course("Signals and Systems")
215 | # one can also use .append() method of list for this
216 | signals_systems.students_enrolled = [george, mark, anjali]
217 |
218 | signals_systems.teacher = paul
219 |
220 | # Let's now create a degree
221 | btech = Degree("Bachelor of Technology")
222 | # add students to the degree
223 | btech.courses.append(digital_signal_processing)
224 | btech.courses.append(signals_systems)
225 | # Finally, create a program
226 | ece = Program("Electronics and Communication Engineering")
227 | ece.degrees.append(btech)
228 |
229 | # Let's display some info!
230 | print('No. of students: {0}'.format(Student.student_count()))
231 | print('No. of teachers: {0}'.format(Teacher.teacher_count()))
232 | print('No. of courses: {0}'.format(Course.course_count()))
233 | # Students enrolled in course Digital Signal Processing Course:
234 | for course in btech.courses:
235 | students = [student.name for student in course.students_enrolled]
236 | print('Students enrolled in {0} course: {1}'.format(course.course_name, students))
237 |
238 |
239 | # use this if you want to run the code following this only from
240 | # within your current script!
241 | if __name__ == '__main__':
242 | main()
243 |
--------------------------------------------------------------------------------
/Examples/dice.py:
--------------------------------------------------------------------------------
1 | """
2 | A sample code to demonstrate how Object-Oriented Programming in Python works.
3 | In the example below, we define a class Dice.
4 | Besides, we demonstrate usage of several dunder (magic) methods, class decorators and a private method for input values checkup
5 | """
6 |
7 | import random
8 |
9 |
10 | class Dice:
11 |
12 | # constructor
13 | def __init__(self, min_eyes=1, max_eyes=6):
14 | self.__check_input(min_eyes, max_eyes)
15 | self.eyes = list(range(min_eyes, max_eyes + 1))
16 |
17 |
18 | # turns instances of a class into callables
19 | def __call__(self):
20 | return random.choice(self.eyes)
21 |
22 |
23 | # returns machine-readable representation of a type
24 | def __repr__(self):
25 | return "Dice {} .. {} at {}".format(min(self), max(self), hex(id(self)))
26 |
27 |
28 | # returns the next item in the sequence
29 | def __next__(self):
30 | return random.choice(self.eyes)
31 |
32 |
33 | # returns an iterator object
34 | def __iter__(self):
35 | return self.eyes.__iter__()
36 |
37 |
38 | # returns object length
39 | def __len__(self):
40 | return len(self.eyes)
41 |
42 |
43 | # method for rolling the dice
44 | def roll(self, n=1):
45 | return [self() for _ in range(n)]
46 |
47 |
48 | # class property: expected value of the dice's eyes
49 | @property
50 | def expected_value(self):
51 | return sum(self.eyes)/len(self)
52 |
53 |
54 | # class property: variance of the dice's eyes
55 | @property
56 | def var(self):
57 | return sum([(x - self.expected_value)**2 for x in self.eyes]) / len(self)
58 |
59 |
60 | # class property: number of dice's sides
61 | @property
62 | def sides(self):
63 | return len(self)
64 |
65 |
66 | # check input values for minimum and maximum number of eyes
67 | # this method is private, i.e., it should only be accessed from inside the class
68 | def __check_input(self, min_eyes, max_eyes):
69 | if min_eyes > max_eyes:
70 | raise ValueError("Min_eyes must be < max_eyes, now: {} > {}".format(min_eyes, max_eyes))
71 | if not isinstance(min_eyes, int):
72 | raise ValueError("min eyes must be numeric")
73 | if not isinstance(max_eyes, int):
74 | raise ValueError("mac_eyes must be numeric")
75 |
--------------------------------------------------------------------------------
/Examples/graph.py:
--------------------------------------------------------------------------------
1 | #Graph implementation using OOPS in Python
2 | #Graph Class
3 |
4 | '''A graph is a pictorial representation of a set of objects where some pairs of objects are connected by links. The interconnected objects are represented by points termed as vertices, and the links that connect the vertices are called edges.
5 |
6 | Formally, a graph is a pair of sets (V, E), where V is the set of vertices and E is the set of edges, connecting the pairs of vertices.'''
7 |
8 | class Graph(object):
9 |
10 | def __init__(self, graph_dict=None):
11 | """ initializes a graph object
12 | If no dictionary or None is given,
13 | an empty dictionary will be used
14 | """
15 | if graph_dict == None:
16 | graph_dict = {}
17 | self.__graph_dict = graph_dict
18 |
19 | def vertices(self):
20 | """ returns the vertices of a graph """
21 | return list(self.__graph_dict.keys())
22 |
23 | def edges(self):
24 | """ returns the edges of a graph """
25 | return self.__generate_edges()
26 |
27 | def add_vertex(self, vertex):
28 | """ If the vertex "vertex" is not in
29 | self.__graph_dict, a key "vertex" with an empty
30 | list as a value is added to the dictionary.
31 | Otherwise nothing has to be done.
32 | """
33 | if vertex not in self.__graph_dict:
34 | self.__graph_dict[vertex] = []
35 |
36 | def add_edge(self, edge):
37 | """ assumes that edge is of type set, tuple or list;
38 | between two vertices can be multiple edges!
39 | """
40 | edge = set(edge)
41 | (vertex1, vertex2) = tuple(edge)
42 | if vertex1 in self.__graph_dict:
43 | self.__graph_dict[vertex1].append(vertex2)
44 | else:
45 | self.__graph_dict[vertex1] = [vertex2]
46 |
47 | def __generate_edges(self):
48 | """ A static method generating the edges of the
49 | graph "graph". Edges are represented as sets
50 | with one (a loop back to the vertex) or two
51 | vertices
52 | """
53 | edges = []
54 | for vertex in self.__graph_dict:
55 | for neighbour in self.__graph_dict[vertex]:
56 | if {neighbour, vertex} not in edges:
57 | edges.append({vertex, neighbour})
58 | return edges
59 |
60 | def __str__(self):
61 | res = "vertices: "
62 | for k in self.__graph_dict:
63 | res += str(k) + " "
64 | res += "\nedges: "
65 | for edge in self.__generate_edges():
66 | res += str(edge) + " "
67 | return res
68 |
69 |
70 | if __name__ == "__main__":
71 |
72 | g = { "a" : ["d"],
73 | "b" : ["c"],
74 | "c" : ["b", "c", "d", "e"],
75 | "d" : ["a", "c"],
76 | "e" : ["c"],
77 | "f" : []
78 | }
79 |
80 | '''Here, graph is a an object of class Grpah with the constructors passed with the parameter dictionary defined above as g
81 | containing the vertices as key of dictionary and the values of key representing the adjacent neighbors. It will call the __str__ function with the dictionary
82 | to form the respecting edges of the graph'''
83 |
84 | graph = Graph(g)
85 |
86 | #Printing the nodes of the graph
87 | print("Vertices of graph:")
88 | print(graph.vertices())
89 | #Printing the edges of the graph
90 | print("Edges of graph:")
91 | print(graph.edges())
92 | #Adding a new vertex to the above graph using member function add_vertex
93 | print("Add vertex:")
94 | graph.add_vertex("z")
95 | #Printing the new list of nodes
96 | print("Vertices of graph:")
97 | print(graph.vertices())
98 | #Adding a new edge to the graph from a node to z
99 | print("Add an edge:")
100 | graph.add_edge({"a","z"})
101 |
102 | print("Vertices of graph:")
103 | print(graph.vertices())
104 | #Printing all the edges present in the graph
105 | print("Edges of graph:")
106 | print(graph.edges())
107 |
108 | print('Adding an edge {"x","y"} with new vertices:')
109 | graph.add_edge({"x","y"})
110 | print("Vertices of graph:")
111 | print(graph.vertices())
112 | print("Edges of graph:")
113 | print(graph.edges())
114 |
115 | ''' The corresponding output of the above:
116 | Vertices of graph:
117 | ['a', 'b', 'c', 'd', 'e', 'f']
118 | Edges of graph:
119 | [{'d', 'a'}, {'b', 'c'}, {'c'}, {'c', 'd'}, {'e', 'c'}]
120 | Add vertex:
121 | Vertices of graph:
122 | ['a', 'b', 'c', 'd', 'e', 'f', 'z']
123 | Add an edge:
124 | Vertices of graph:
125 | ['a', 'b', 'c', 'd', 'e', 'f', 'z']
126 | Edges of graph:
127 | [{'d', 'a'}, {'b', 'c'}, {'c'}, {'c', 'd'}, {'e', 'c'}, {'z', 'a'}]
128 | Adding an edge {"x","y"} with new vertices:
129 | Vertices of graph:
130 | ['a', 'b', 'c', 'd', 'e', 'f', 'z', 'y']
131 | Edges of graph:
132 | [{'d', 'a'}, {'b', 'c'}, {'c'}, {'c', 'd'}, {'e', 'c'}, {'z', 'a'}, {'y', 'x'}]'''
133 |
134 |
--------------------------------------------------------------------------------
/Examples/inheritance.py:
--------------------------------------------------------------------------------
1 | class Animal:
2 |
3 | def __init__(self):
4 | print("Animal created")
5 |
6 | def defineMe(self):
7 | print("This is parent class Animal")
8 |
9 | def eat(self):
10 | print("All animals have a common property, they eat!")
11 |
12 | class Lion(Animal):
13 |
14 | def __init__(self):
15 | super().__init__()
16 | print("Lion created")
17 |
18 | def defineMe(self):
19 | print("This is child class Lion")
20 |
21 | def prey(self):
22 | print("I am the king of the jungle!")
23 |
24 |
25 | # Initializing 'simba the lion'...
26 | simba = Lion()
27 |
28 | # Let simba define himself...
29 | simba.defineMe()
30 |
31 | # simba is a lion, but can also eat! It is a child of Animal class afterall!
32 | simba.eat()
33 |
34 | # And obviously, simba can prey, and it will! Beware!!
35 | simba.prey()
36 |
--------------------------------------------------------------------------------
/Examples/method_overriding.py:
--------------------------------------------------------------------------------
1 | """
2 | Overriding is one of the oops concepts which allows us to change the implementation of a method
3 | in child class that is defined in the parent class.
4 | Conditions of overriding:
5 | 1) Inheritance should be there.
6 | 2) Child class method should have same number of parameters as parent method.
7 |
8 | Below is an example which demonstrates method overriding.
9 | Create an Animal class and implement feed method with print statement
10 | Create a Vegetarian class which is inherits Animal class
11 | and add feed method with different implementation
12 | """
13 |
14 |
15 | class Animal:
16 | def feed(self):
17 | print('I eat everything whatever you feed me')
18 |
19 |
20 | class Vegetarian(Animal):
21 | def feed(self):
22 | print('I eat only vegetables')
23 |
24 |
25 | if __name__ == '__main__':
26 | a = Animal()
27 | a.feed()
28 | v = Vegetarian()
29 | v.feed()
30 |
--------------------------------------------------------------------------------
/Examples/operator_overloading.py:
--------------------------------------------------------------------------------
1 | """
2 | This example demonstrates the operator overloading example
3 | Instructions:
4 | - Create a class named Point
5 | - Overload the add operator '+' to add two Point objects
6 | - Also added is an additional function that calculates the length between 2 points
7 | to demonstrate the application of this exercise
8 | """
9 |
10 |
11 | class Point(object):
12 | # the constructor
13 | def __init__(self, x, y):
14 | # these are the x, y coordinates
15 | self.x = x
16 | self.y = y
17 |
18 | # override the __add__ function to return a new Point class
19 | # with the x coordinate as the sum of the x coordinates of two points
20 | # and y coordinate as the sum of y coordinates of two points
21 | def __add__(self, other):
22 | x = self.x + other.x
23 | y = self.y + other.y
24 | return Point(x, y)
25 |
26 |
27 | # Bonus: Find the length between two points!
28 | def calculate_length(p1, p2):
29 | import math
30 | # length = sqrt((x2 - x1)^2 + (y2 - y1)^2)
31 | length = math.sqrt((p1.x - p2.x)**2 + (p1.y - p2.y)**2)
32 | return length
33 |
34 |
35 | # the main entry point function
36 | def main():
37 | p1 = Point(3, 5)
38 | p2 = Point(-4, 10)
39 | p3 = p1 + p2
40 | print('Point p3: ({0}, {1})'.format(p3.x, p3.y))
41 | print('Length of the line between p1 and p2 is: {0}'.format(calculate_length(p1, p2)))
42 |
43 |
44 | if __name__ == '__main__':
45 | main()
46 |
--------------------------------------------------------------------------------
/Examples/polygon.py:
--------------------------------------------------------------------------------
1 | import math
2 |
3 | class Point(object):
4 | """simple class Point"""
5 | def __init__(self, x, y):
6 | """pass x, y coordinates to build a 2d point"""
7 | self.x = x
8 | self.y = y
9 |
10 | def dist(self, p):
11 | """return distance between to another point (p)"""
12 | return math.sqrt(math.pow((p.x - self.x), 2) + math.pow((p.y - self.y), 2))
13 |
14 | def minus(self, p):
15 | """return a new point that's equal to actual point minus a point p"""
16 | return Point(self.x - p.x, self.y - p.y)
17 |
18 | def plus(self, p):
19 | """return a new point that's equal to actual point plus a point p"""
20 | return Point(self.x + p.x, self.y + p.y)
21 |
22 | def info(self):
23 | """show info about the point"""
24 | print('({}, {})'.format(self.x, self.y))
25 |
26 | class Polygon(object):
27 | """this class is a simple polygon, in other words, a list of points"""
28 | def __init__(self, points):
29 | self.points = points
30 |
31 | """show polygon about the polygon"""
32 | def info(self):
33 | for p in self.points:
34 | p.info()
35 |
36 | if __name__ == '__main__':
37 | # create two points p1, p2
38 | p1 = Point(3, 4)
39 | p2 = Point(7, 2)
40 |
41 | p1.info()
42 | p2.info()
43 |
44 | # create a new point p3 = p1 - p2
45 | p3 = p1.minus(p2)
46 | p3.info()
47 |
48 | # create a new point p4 = p1 + p2
49 | p4 = p1.plus(p2)
50 | p4.info()
51 |
52 | # show distance between p3 and p4
53 | print(p3.dist(p4))
54 |
55 | # create a polygon passing a list with the previous points as parameter
56 | polygon = Polygon(list([p1, p2, p3, p4]))
57 |
58 | # show polygon info
59 | polygon.info()
60 |
61 |
--------------------------------------------------------------------------------
/Examples/sample_oo_api/.sample_venv:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/josharsh/OPython-Init/11d33bfdcc8e35203edcec1efeb39506ea133d2a/Examples/sample_oo_api/.sample_venv
--------------------------------------------------------------------------------
/Examples/sample_oo_api/README.md:
--------------------------------------------------------------------------------
1 | # Sample: Python API
2 | This repository is built to serve as a sample to how you can build a modern Python API with minimal code.
3 |
4 | ## How to run:
5 | 1. Import world_x db (in database folder!)
6 | 2. Set environment variables for DB Connection
7 | 3. Run `pip3 install -r requirements.txt`
8 | 4. Run `python3 application.py`
9 |
10 | ## Credits
11 | - Orator ORM for database management: https://orator-orm.com
12 | - Connexion for OpenAPI: https://github.com/zalando/connexion
13 | - MySQL for World_X DB: https://dev.mysql.com/doc/index-other.html
14 |
--------------------------------------------------------------------------------
/Examples/sample_oo_api/app.py:
--------------------------------------------------------------------------------
1 | # Python core imports
2 | import os
3 | import uuid
4 |
5 | # Python third-party imports
6 | import connexion
7 | from flask import redirect, url_for
8 |
9 |
10 | # Connexion setup
11 | debugging = os.environ.get('debugging')
12 | options = {"swagger_ui": debugging}
13 |
14 | application = connexion.FlaskApp(
15 | __name__,
16 | specification_dir='config/',
17 | options=options
18 | )
19 |
20 | application.add_api(
21 | 'openAPI.yaml',
22 | base_path='/api',
23 | arguments={'title': 'Sample API'}
24 | )
25 |
26 | # CSRF Key/Secret for forms
27 | application.app.config.update(
28 | dict(
29 | SECRET_KEY=str(uuid.uuid4()),
30 | WTF_CSRF_SECRET_KEY=str(uuid.uuid4())
31 | )
32 | )
33 |
34 | # Max payload (to restrict large file uploads)
35 | application.app.config['MAX_CONTENT_LENGTH'] = 10 * 1024 * 1024
36 |
37 | # Re-direct to Swagger/OpenAPI UI
38 | @application.app.route('/')
39 | def index():
40 | return redirect(
41 | location=url_for(
42 | endpoint='/api./api_swagger_ui_index'
43 | ),
44 | code=302
45 | )
46 |
47 |
48 | # Default robots reply
49 | @application.app.route('/robots.txt', methods=['GET'])
50 | def robots():
51 | return "User-agent: *\nDisallow: /"
52 |
53 |
54 | # Run
55 | if __name__ == '__main__':
56 | application.run()
57 |
--------------------------------------------------------------------------------
/Examples/sample_oo_api/config/openAPI.yaml:
--------------------------------------------------------------------------------
1 | openapi: 3.0.1
2 | info:
3 | version: 0.0.1
4 | title: API World_X
5 | description: "Sample API using the free Oracle World_X DB. All objects referenced are JSON objects."
6 | paths:
7 | /getCity:
8 | summary: Returns information about a given city
9 | description: Returns information about a given city
10 | get:
11 | summary: Returns information about a given city
12 | parameters:
13 | - in: query
14 | name: name
15 | schema:
16 | type: string
17 | required: true
18 | description: the name of the city.
19 | description: Returns information about a given city
20 | operationId: controllers.api.get_city
21 | responses:
22 | '200':
23 | description: OK
24 | content:
25 | application/json:
26 | schema:
27 | type: object
28 | properties:
29 | id:
30 | type: number
31 | Name:
32 | type: string
33 | CountryCode:
34 | type: string
35 | Info:
36 | type: object
37 | example:
38 | id: 1
39 | Name: Kabul
40 | CountryCode: AFG
41 | Info: object
42 |
43 | tags:
44 | - city
45 | /getCityAll:
46 | summary: Returns all city information
47 | description: Returns all city information
48 | get:
49 | summary: Returns all city information
50 | description: Returns all city information
51 | operationId: controllers.api.get_city_all
52 | responses:
53 | '200':
54 | description: OK
55 | content:
56 | application/json:
57 | schema:
58 | type: object
59 | properties:
60 | id:
61 | type: number
62 | Name:
63 | type: string
64 | CountryCode:
65 | type: string
66 | Info:
67 | type: object
68 | example: [
69 | {
70 | "id": 1,
71 | "Name": "Kabul",
72 | "CountryCode": "AFG",
73 | "Info": object
74 | },
75 | {
76 | "id": 1,
77 | "Name": "Kabul",
78 | "CountryCode": "AFG",
79 | "Info": object
80 | }
81 | ]
82 | tags:
83 | - city
84 | /getCountry:
85 | summary: Returns information about a given country
86 | description: Returns information about a given country
87 | get:
88 | summary: Returns information about a given country
89 | parameters:
90 | - in: query
91 | name: name
92 | schema:
93 | type: string
94 | required: true
95 | description: the name of the country
96 | description: Returns information about a given country
97 | operationId: controllers.api.get_country
98 | responses:
99 | '200':
100 | description: OK
101 | content:
102 | application/json:
103 | schema:
104 | type: object
105 | properties:
106 | Code:
107 | type: string
108 | Name:
109 | type: string
110 | Capital:
111 | type: string
112 | Code2:
113 | type: string
114 | example:
115 | Code: ABW
116 | Name: Aruba
117 | Capital: 129
118 | Code2: AW
119 |
120 |
121 | tags:
122 | - country
123 | /getCountryAll:
124 | summary: Returns all country information
125 | description: Returns all country information
126 | get:
127 | summary: Returns all country information
128 | description: Returns all country information
129 | operationId: controllers.api.get_country_all
130 | responses:
131 | '200':
132 | description: OK
133 | content:
134 | application/json:
135 | schema:
136 | type: object
137 | properties:
138 | id:
139 | type: number
140 | Name:
141 | type: string
142 | CountryCode:
143 | type: string
144 | Info:
145 | type: object
146 | example: [
147 | {
148 | "Code": 1,
149 | "Name": "Armenia",
150 | "Capital": 126,
151 | "Code2": "AM"
152 | },
153 | {
154 | "Code": 1,
155 | "Name": "American Samoa",
156 | "Capital": 54,
157 | "Code2": "AS"
158 | }
159 | ]
160 |
161 | tags:
162 | - country
163 | /getCountryInfo:
164 | summary: Returns detailed information about a given country
165 | description: Returns detailed information about a given country
166 | get:
167 | summary: Returns detailed information about a given country
168 | parameters:
169 | - in: query
170 | name: name
171 | schema:
172 | type: string
173 | required: true
174 | description: the name of the country
175 | description: Returns detailed information about a given country
176 | operationId: controllers.api.get_countryinfo
177 | responses:
178 | '200':
179 | description: OK
180 | content:
181 | application/json:
182 | schema:
183 | type: object
184 | properties:
185 | doc:
186 | type: string
187 | _id:
188 | type: string
189 | example:
190 | doc: dataMap
191 | _id: ABW
192 | tags:
193 | - country
194 | /getCountryLanguage:
195 | summary: Returns language information about a given country
196 | parameters:
197 | - in: query
198 | name: name
199 | schema:
200 | type: string
201 | required: true
202 | description: the name of the language
203 | description: Returns language information about a given country
204 | get:
205 | summary: 'Returns language information about a given country'
206 | description: 'Returns language information about a given country'
207 | operationId: controllers.api.get_countrylanguage
208 | responses:
209 | '200':
210 | description: OK
211 | content:
212 | application/json:
213 | schema:
214 | type: object
215 | properties:
216 | CountryCode:
217 | type: string
218 | Language:
219 | type: string
220 | IsOfficial:
221 | type: string
222 | enum: ['T', 'F']
223 | Percentage:
224 | type: number
225 | example:
226 | CountryCode: ABW
227 | Language: Dutch
228 | IsOfficial: T
229 | Percentage: 5.3
230 | tags:
231 | - language
232 | /getCountryLanguageAll:
233 | summary: Returns all country language information
234 | description: Returns all country language information
235 | get:
236 | summary: 'Returns all country language information'
237 | description: 'Returns all country language information'
238 | operationId: controllers.api.get_countrylanguage_all
239 | responses:
240 | '200':
241 | description: OK
242 | content:
243 | application/json:
244 | schema:
245 | type: object
246 | properties:
247 | CountryCode:
248 | type: string
249 | Language:
250 | type: string
251 | IsOfficial:
252 | type: string
253 | enum: ['T', 'F']
254 | Percentage:
255 | type: number
256 | example: [
257 | {
258 | "CountryCode": "ABW",
259 | "Language": "Dutch",
260 | "IsOfficial": "T",
261 | "Percentage": 5.3
262 | }
263 | ]
264 | tags:
265 | - language
266 |
--------------------------------------------------------------------------------
/Examples/sample_oo_api/controllers/api.py:
--------------------------------------------------------------------------------
1 | # # Local imports (relative)
2 | # from database.manager import db
3 |
4 | # Local imports (absolute)
5 | from Examples.sample_oo_api.database.manager import db
6 |
7 |
8 | # City calls
9 | def get_city(name: str) -> dict:
10 | """
11 | API Controlled method to retrieve city details for specified city
12 | Arguements:
13 | - name name of the city
14 |
15 | Returns a dict with information about the requested city
16 | """
17 | return db.City.where('Name', '=', name.capitalize()).get().serialize()
18 |
19 |
20 | def get_city_all():
21 | """
22 | API Controlled method to retrieve city details for all available cities
23 |
24 | Returns a dict with information about all available cities
25 | """
26 | return db.City.all().serialize()
27 |
28 |
29 | def get_country(name: str) -> dict:
30 | """
31 | API Controlled method to retrieve country details for specified country
32 | Arguements:
33 | - name name of the country
34 |
35 | Returns a dict with information about the requested city
36 | """
37 | return db.Country.where('Name', '=', name.capitalize()).get().serialize()
38 |
39 |
40 | def get_country_all() -> dict:
41 | """
42 | API Controlled method to retrieve country details for
43 | all available countries
44 |
45 | Returns a dict with information about all available countries
46 | """
47 | return db.Country.all().serialize()
48 |
49 |
50 | # Country info calls
51 | def get_countryinfo(id: str):
52 | """
53 | API Controlled method to retrieve:
54 | Arguements:
55 | - id ID code of a specific country
56 |
57 | Returns a dict with detailed information about the requested country
58 | """
59 | return db.CountryInfo.where('_id', '=', id.upper()).get().serialize()
60 |
61 |
62 | # Country language calls
63 | def get_countrylanguage(language: str):
64 | """
65 | API Controlled method to retrieve:
66 | Arguements:
67 | - language language of the country to retrieve
68 |
69 | Returns a dict with requested data
70 | """
71 | return db.CountryLanguage.where('Language', '=', language.capitalize()) \
72 | .get() \
73 | .serialize()
74 |
75 |
76 | def get_countrylanguage_all():
77 | """
78 | API Controlled method to retrieve:
79 | Arguements:
80 | -
81 |
82 | Returns a dict with requested data
83 | """
84 | return db.CountryLanguage.all().get().serialize()
85 |
--------------------------------------------------------------------------------
/Examples/sample_oo_api/database/manager.py:
--------------------------------------------------------------------------------
1 | # Python core imports
2 | import os
3 |
4 | # Third-party imports
5 | from orator import DatabaseManager
6 | from orator import Model
7 |
8 | # Importing local models
9 | from models.city import city
10 | from models.country import country
11 | from models.countryinfo import countryinfo
12 | from models.countrylanguage import countrylanguage
13 |
14 |
15 | class Database:
16 | """
17 | Contains database methods
18 | """
19 |
20 | db = None
21 | config = {}
22 |
23 | City = None
24 | Country = None
25 | CountryInfo = None
26 | CountryLanguage = None
27 |
28 | # Config
29 | config = {}
30 |
31 | def __init__(self):
32 | """
33 | Initializes a database instance and binds the models to it.
34 |
35 | Arguement(s)
36 | - self
37 |
38 | """
39 | # Bind Models to local variables
40 | self.City = city
41 | self.Country = country
42 | self.CountryInfo = countryinfo
43 | self.CountryLanguage = countrylanguage
44 |
45 | # Set config
46 | self.config = {
47 | 'mysql': {
48 | 'driver': 'mysql',
49 | 'host': os.getenv('DB_HOST'),
50 | 'database': os.getenv('DB_NAME'),
51 | 'user': os.getenv('DB_USER'),
52 | 'password': os.getenv('DB_PASSWORD'),
53 | 'prefix': ''
54 | }
55 | }
56 |
57 | # Create database from config
58 | self.db = DatabaseManager(self.config)
59 |
60 | # Auto-resolve connection
61 | Model.set_connection_resolver(self.db)
62 |
63 |
64 | # Create public instance
65 | db = Database()
66 |
--------------------------------------------------------------------------------
/Examples/sample_oo_api/models/city.py:
--------------------------------------------------------------------------------
1 | # Import base for the model
2 | from orator import Model
3 |
4 | class city(Model):
5 | __table__ = 'city'
6 |
--------------------------------------------------------------------------------
/Examples/sample_oo_api/models/country.py:
--------------------------------------------------------------------------------
1 | # Import base for the model
2 | from orator import Model
3 |
4 |
5 | class country(Model):
6 | __table__ = 'country'
7 |
--------------------------------------------------------------------------------
/Examples/sample_oo_api/models/countryinfo.py:
--------------------------------------------------------------------------------
1 | # Import base for the model
2 | from orator import Model
3 |
4 |
5 | class countryinfo(Model):
6 | __table__ = 'countryinfo'
7 |
--------------------------------------------------------------------------------
/Examples/sample_oo_api/models/countrylanguage.py:
--------------------------------------------------------------------------------
1 | # Import base for the model
2 | from orator import Model
3 |
4 |
5 | class countrylanguage(Model):
6 | __table__ = 'countrylanguage'
7 |
--------------------------------------------------------------------------------
/Examples/sample_oo_dashboard/README.md:
--------------------------------------------------------------------------------
1 | # Sample web application
2 | This is a simple sample webapp built with flask, dash and orator.
3 |
4 | ## How to Install
5 | - run `pip3 install -r requirements_dashboard.txt`
6 |
7 | ## How to run
8 | - run app.py
9 |
10 | ## Extra
11 | There is a sample database set up but not yet used,
12 | this is so that it can be a base for you to build on.
13 |
14 | Simply import the sample_database.sql to get started!
--------------------------------------------------------------------------------
/Examples/sample_oo_dashboard/app.py:
--------------------------------------------------------------------------------
1 | # Python core imports
2 | import os
3 | import secrets
4 |
5 | # Third-party imports
6 | import dash
7 | import dash_bootstrap_components as dbc
8 | from flask import Flask
9 |
10 | # Local imports (relative)
11 | # from controllers.router import Router
12 | # from controllers.hello import Hello
13 | # from layouts.layouts import Layouts
14 |
15 | # Local imports (absolute)
16 | from Examples.sample_oo_dashboard.controllers.router import Router
17 | from Examples.sample_oo_dashboard.controllers.hello import Hello
18 | from Examples.sample_oo_dashboard.layouts.layouts import Layouts
19 |
20 |
21 | # App variables
22 | debug = os.getenv('DEBUG')
23 |
24 | # Setting up flask for session management
25 | application = Flask(__name__)
26 | application.config.update(
27 | dict(
28 | SECRET_KEY=secrets.token_urlsafe(),
29 | WTF_CSRF_SECRET_KEY=secrets.token_urlsafe()
30 | )
31 | )
32 |
33 | # Setting up dash
34 | app = dash.Dash(
35 | __name__,
36 | server=application,
37 | external_stylesheets=[dbc.themes.FLATLY],
38 | suppress_callback_exceptions=True
39 | )
40 |
41 | app.title = 'Sample webapp'
42 | app.layout = Layouts.base()
43 |
44 | # Registering the router
45 | Router(app)
46 |
47 | # Registering callbacks
48 | Hello(app)
49 |
50 | # Run
51 | if __name__ == '__main__':
52 | app.run_server(debug=debug)
--------------------------------------------------------------------------------
/Examples/sample_oo_dashboard/assets/main.js:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/josharsh/OPython-Init/11d33bfdcc8e35203edcec1efeb39506ea133d2a/Examples/sample_oo_dashboard/assets/main.js
--------------------------------------------------------------------------------
/Examples/sample_oo_dashboard/assets/style.css:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/josharsh/OPython-Init/11d33bfdcc8e35203edcec1efeb39506ea133d2a/Examples/sample_oo_dashboard/assets/style.css
--------------------------------------------------------------------------------
/Examples/sample_oo_dashboard/controllers/hello.py:
--------------------------------------------------------------------------------
1 | # Third-party imports
2 | from dash import Dash
3 | from dash.dependencies import Input, Output
4 |
5 | class Hello:
6 | '''
7 | Callback that greets the visitor
8 | '''
9 |
10 | def __init__(self, app: Dash):
11 | @app.callback(
12 | Output('hello_output', 'children'),
13 | [Input('hello_input', 'value')]
14 | )
15 |
16 | def update(hello_input: str):
17 | '''
18 | Takes in one arguement(s);
19 | - : (str)
20 |
21 | Returns a layout_page matching requested pathname.
22 | '''
23 | # Some validation
24 | if len(hello_input) > 2:
25 | return f'Hello {hello_input}! Welcome to the app!'
26 |
--------------------------------------------------------------------------------
/Examples/sample_oo_dashboard/controllers/router.py:
--------------------------------------------------------------------------------
1 | # Third-party imports
2 | from dash import Dash
3 | from dash.dependencies import Input, Output
4 |
5 | # Local imports (relative)
6 | # from layouts.layouts import Layouts
7 | # from data.session import Session
8 |
9 | # Local imports (absolute)
10 | from Examples.sample_oo_dashboard.layouts.layouts import Layouts
11 | from Examples.sample_oo_dashboard.data.session import Session
12 |
13 |
14 | class Router():
15 | '''
16 | Providing routing family
17 | '''
18 |
19 | def __init__(self, app: Dash):
20 | @app.callback(
21 | Output(
22 | component_id='page_content',
23 | component_property='children'
24 | ),
25 | [Input(
26 | component_id='url',
27 | component_property='pathname'
28 | )]
29 | )
30 | def redirect(pathname):
31 | '''
32 | Takes in one arguement(s);
33 | - : (str) the url pathname to redirect to
34 |
35 | Returns a layout_page matching requested pathname.
36 | '''
37 | if pathname == '/':
38 | Session['page'] = '/'
39 | return Layouts.index()
40 |
41 | if pathname == '/hello':
42 | Session['page'] = '/hello'
43 | return Layouts.hello()
44 |
45 | # Default if no pathname is matched
46 | Session['page'] = '/404'
47 | return Layouts.not_found()
48 |
--------------------------------------------------------------------------------
/Examples/sample_oo_dashboard/data/session.py:
--------------------------------------------------------------------------------
1 | from flask.sessions import SecureCookieSession
2 |
3 | Session = SecureCookieSession()
4 |
--------------------------------------------------------------------------------
/Examples/sample_oo_dashboard/database/manager.py:
--------------------------------------------------------------------------------
1 | # Python core imports
2 | import os
3 |
4 | # Third-party imports
5 | from orator import DatabaseManager
6 | from orator import Model
7 |
8 | # Local imports (relative)
9 | # from database.models import posts
10 | # from database.models import drafts
11 | # from database.models import users
12 | # from database.models import notes
13 |
14 | # Local imports (relative)
15 | from Examples.sample_oo_dashboard.database.models import posts
16 | from Examples.sample_oo_dashboard.database.models import drafts
17 | from Examples.sample_oo_dashboard.database.models import users
18 | from Examples.sample_oo_dashboard.database.models import notes
19 |
20 |
21 | class Database:
22 | """
23 | Provides database methods
24 | """
25 |
26 | db = None
27 | Posts = None
28 | Drafts = None
29 | Users = None
30 | Notes = None
31 |
32 | config: dict
33 |
34 | # Config
35 | config = {}
36 |
37 | def __init__(self):
38 | """
39 | Initializes a database instance and binds the models to it.
40 |
41 | Arguement(s)
42 | - self
43 |
44 | """
45 |
46 | # Set config
47 | self.config = {
48 | 'mysql': {
49 | 'driver': 'mysql',
50 | 'host': os.getenv('DB_HOST'),
51 | 'database': os.getenv('DB_NAME'),
52 | 'user': os.getenv('DB_USER'),
53 | 'password': os.getenv('DB_PASSWORD'),
54 | 'prefix': ''
55 | }
56 | }
57 |
58 | # Bind Models to local variables
59 | self.Posts = posts
60 | self.Drafts = drafts
61 | self.Users = users
62 | self.Notes = notes
63 |
64 | # Create database from config
65 | self.db = DatabaseManager(self.config)
66 |
67 | # Auto-resolve connection
68 | Model.set_connection_resolver(self.db)
69 |
70 |
71 | # Create public instance
72 | db = Database()
73 |
--------------------------------------------------------------------------------
/Examples/sample_oo_dashboard/database/models.py:
--------------------------------------------------------------------------------
1 | # Import model base
2 | from orator import Model
3 |
4 |
5 | class posts(Model):
6 | __table__ = 'posts'
7 | pass
8 |
9 |
10 | class drafts(Model):
11 | __table__ = 'drafts'
12 |
13 |
14 | class users(Model):
15 | __table__ = 'users'
16 | pass
17 |
18 |
19 | class notes(Model):
20 | __table__ = 'notes'
21 | pass
22 |
--------------------------------------------------------------------------------
/Examples/sample_oo_dashboard/database/sample_database.sql:
--------------------------------------------------------------------------------
1 | -- -------------------------------------------------------------
2 | -- TablePlus 2.9.1(264)
3 | --
4 | -- https://tableplus.com/
5 | --
6 | -- Database: webapp
7 | -- Generation Time: 2019-10-03 19:05:13.8350
8 | -- -------------------------------------------------------------
9 |
10 |
11 | /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
12 | /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
13 | /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
14 | /*!40101 SET NAMES utf8mb4 */;
15 | /*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
16 | /*!40103 SET TIME_ZONE='+00:00' */;
17 | /*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
18 | /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
19 | /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
20 | /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
21 |
22 |
23 | CREATE TABLE `drafts` (
24 | `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
25 | `title` varchar(255) DEFAULT NULL,
26 | `content` varchar(255) DEFAULT NULL,
27 | `created` datetime DEFAULT NULL,
28 | `last_updated` datetime DEFAULT NULL,
29 | PRIMARY KEY (`id`),
30 | UNIQUE KEY `id` (`id`)
31 | ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
32 |
33 | CREATE TABLE `events` (
34 | `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
35 | `start` datetime DEFAULT NULL,
36 | `end` datetime DEFAULT NULL,
37 | `header` varchar(255) DEFAULT NULL,
38 | `body` varchar(255) DEFAULT NULL,
39 | PRIMARY KEY (`id`),
40 | UNIQUE KEY `id` (`id`)
41 | ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
42 |
43 | CREATE TABLE `notes` (
44 | `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
45 | `title` varchar(255) DEFAULT NULL,
46 | `content` varchar(255) DEFAULT NULL,
47 | `created` datetime DEFAULT NULL,
48 | `last_updated` datetime DEFAULT NULL,
49 | PRIMARY KEY (`id`),
50 | UNIQUE KEY `id` (`id`)
51 | ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
52 |
53 | CREATE TABLE `posts` (
54 | `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
55 | `title` varchar(255) DEFAULT NULL,
56 | `content` varchar(255) DEFAULT NULL,
57 | `created` datetime DEFAULT NULL,
58 | `last_updated` datetime DEFAULT NULL,
59 | PRIMARY KEY (`id`),
60 | UNIQUE KEY `id` (`id`)
61 | ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
62 |
63 | CREATE TABLE `users` (
64 | `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
65 | `username` varchar(255) DEFAULT NULL,
66 | `password` varchar(255) DEFAULT NULL,
67 | `email` varchar(255) DEFAULT NULL,
68 | `registered` datetime DEFAULT NULL,
69 | `last_updated` datetime DEFAULT NULL,
70 | `hash` varchar(255) DEFAULT NULL,
71 | PRIMARY KEY (`id`),
72 | UNIQUE KEY `id` (`id`)
73 | ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
74 |
75 |
76 |
77 |
78 | /*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;
79 | /*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
80 | /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
81 | /*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
82 | /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
83 | /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
84 | /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
85 | /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
--------------------------------------------------------------------------------
/Examples/sample_oo_dashboard/layouts/layouts.py:
--------------------------------------------------------------------------------
1 | # Third-party imports
2 | from dash_core_components import Location, Link as internal_link, Input
3 | from dash_html_components import Link as external_link
4 | from dash_html_components import Div, H1, P, Br
5 | from dash_bootstrap_components import Container, Row, Col
6 |
7 |
8 | class Layouts:
9 | '''
10 | Contains all default layouts for the application as callable functions.
11 | '''
12 |
13 | @staticmethod
14 | def base() -> Div:
15 | '''
16 | Returns a dash website base
17 | '''
18 | return Div([
19 | Location(id='url', refresh=False),
20 | external_link(
21 | rel='icon',
22 | href='assets/img/favicon.ico'
23 | ),
24 | Div(id='page_content')
25 | ])
26 |
27 | @staticmethod
28 | def index() -> Div:
29 | '''
30 | Returns the app index page
31 | '''
32 | return Container([
33 | Row([
34 | Col([
35 | H1('Welcome to the Index Page'),
36 | P(
37 | 'You can visit a second page by'
38 | ' clicking the link below'
39 | ),
40 | internal_link('Hello Page', href='/hello'),
41 | ])
42 | ])
43 | ])
44 |
45 | @staticmethod
46 | def not_found() -> Div:
47 | '''
48 | Returns the 404 page not found page
49 | '''
50 | return Container([
51 | Row([
52 | Col([
53 | H1('404 Page not found'),
54 | internal_link('Home', href='/'),
55 | ])
56 | ])
57 | ])
58 |
59 | @staticmethod
60 | def hello() -> Div:
61 | '''
62 | Returns the hello page
63 | '''
64 | return Container([
65 | Row([
66 | Col([
67 | H1('Hello, World!'),
68 | Br(),
69 | Input(
70 | id='hello_input',
71 | value='',
72 | type='text',
73 | placeholder='Enter name',
74 | debounce=True
75 | ),
76 | Br(),
77 | Div(id='hello_output'),
78 | internal_link('Home', href='/'),
79 | ])
80 | ])
81 | ])
82 |
--------------------------------------------------------------------------------
/Examples/sample_oo_dashboard/requirements_dashboard.txt:
--------------------------------------------------------------------------------
1 | backpack==0.1
2 | blinker==1.4
3 | cleo==0.6.8
4 | Click==7.0
5 | dash==1.3.1
6 | dash-bootstrap-components==0.7.1
7 | dash-core-components==1.2.1
8 | dash-html-components==1.0.1
9 | dash-renderer==1.1.0
10 | dash-table==4.3.0
11 | entrypoints==0.3
12 | Faker==0.8.18
13 | flake8==3.7.8
14 | Flask==1.1.1
15 | Flask-Compress==1.4.0
16 | future==0.17.1
17 | inflection==0.3.1
18 | itsdangerous==1.1.0
19 | Jinja2==2.10.1
20 | lazy-object-proxy==1.4.2
21 | MarkupSafe==1.1.1
22 | mccabe==0.6.1
23 | orator==0.9.9
24 | pastel==0.1.1
25 | pendulum==1.5.1
26 | plotly==4.1.1
27 | pyaml==16.12.2
28 | pycodestyle==2.5.0
29 | pyflakes==2.1.1
30 | Pygments==2.4.2
31 | pylev==1.3.0
32 | python-dateutil==2.8.0
33 | pytz==2019.2
34 | pytzdata==2019.3
35 | PyYAML==5.1.2
36 | retrying==1.3.3
37 | simplejson==3.16.0
38 | six==1.12.0
39 | text-unidecode==1.2
40 | tzlocal==1.5.1
41 | Werkzeug==0.16.0
42 | wrapt==1.11.2
43 |
--------------------------------------------------------------------------------
/Examples/stack.py:
--------------------------------------------------------------------------------
1 |
2 | # Stack
3 | * A stack is a group of elements stored in LIFO (Last In First Out) order. The element which is stored as a last element into the stack
4 | * will be the first element to be removed from the stack. The stack is used by operating system to save the program execution environment.
5 | * basically there are five operations we are performing on stack.
6 | * Push operation: Inserting element into stack
7 | * Pop operation: Removing element from stack
8 | * Search operation: Searching an element in the stack
9 | * Peep/Peak operation: Returning the topmost element of the stack without deleting the element
10 | * Empty stack operation: Returning stack is empty or not
11 |
12 |
13 | # Stack class
14 | class Stack:
15 | def __init__(self):
16 | self.st = []
17 |
18 | # checking stack is empty or not
19 | def isempty(self):
20 | return self.st == []
21 |
22 | # Inserting an element in the list
23 | def push(self):
24 | self.st.append(element)
25 |
26 | # Removing the last element from the list
27 | def pop(self):
28 | if self.isempty():
29 | return - 1
30 | else:
31 | self.st.pop()
32 |
33 | # Returning the topmost element from the list
34 | def peek(self):
35 | num = len(self.st)
36 | return self.st[num - 1]
37 |
38 |
39 | # Searching an element in the list and return its index position
40 | def search(self, element):
41 | if self.isempty():
42 | return -1
43 | else:
44 | try:
45 | num = self.st.index(element)
46 | return len(self.st) - num
47 | except valueError:
48 | return 2
49 |
50 | # Display the operations
51 | def display(self):
52 | return self.st
53 |
54 |
55 | #### This is a basic Stack data structure usin OOP programming in python.
56 | A stack is a data structure which uses a LIFO(Last In First Out) order to preform operations.
57 | Last In First Out means that the last item to be added to the stack will be the first one to be taken out
58 | It is used in many cases. For example internet search history and creating programming languages.
59 | This program is a bare bones version but can be improved and added to
60 | Python implements a Stack by using a list.
61 | The list contains all the information held in the stack and we use python list functions within our stack methods.
62 | # Example 2
63 | class Stack(object):
64 |
65 | def __init__(self):
66 | self.l = []
67 |
68 | def push(self, arg):
69 | self.l.append(arg)
70 |
71 | def pop(self):
72 | return self.l.pop()
73 |
74 | def top(self):
75 | return self.l[-1]
76 |
77 | def __len__(self):
78 | return len(self.l)
79 |
80 | def is_empty(self):
81 | return len(self) == 0
82 |
83 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/Lesson 1 - Introduction to Python/Introduction.md:
--------------------------------------------------------------------------------
1 | # Python: An Introduction.
2 |
3 | Designed by Guido van Rossum, Python is a popular open source programming language released in 1991. It is a general-purpose, high-level programming language maintained by the Python Software Foundation.
4 |
5 | Before you head forward, it is important to note that there are two major Python versions- Python 2 and Python 3. Both the versions have significant differences.
6 |
7 |
8 | ## Why Learn Python:
9 |
10 |
11 |
12 | * Simple to Learn
13 | * Free & open source
14 | * High-level
15 | * Emphasizes code readability
16 | * Interpreted
17 | * Dynamically typed language(No need to mention data type based on value assigned, it takes data type)
18 | * Object-oriented language
19 | * Large Community Support
20 | * Portable across Operating systems
21 | * And many other reasons you will discover yourself while learning it.
22 |
23 |
24 |
25 | ## Downloading and Installing Python:
26 |
27 | You can download python from here: [https://www.python.org/downloads/](https://www.python.org/downloads/)
28 |
29 | For a detailed tutorial on installation refer to this or any other site on the Internet: [https://realpython.com/installing-python/](https://realpython.com/installing-python/)
30 |
31 |
32 | ## Python Capabilities:
33 |
34 | (Source: [https://www.w3schools.com/python/python_intro.asp](https://www.w3schools.com/python/python_intro.asp))
35 |
36 | * Python can be used on a server to create web applications.
37 | * Python can be used GUI based desktop applications.
38 | * Python can be used alongside software to create workflows.
39 | * Python can connect to database systems. It can also read and modify files.
40 | * Python can be used to handle big data and perform complex mathematics.
41 | * Python can be used for rapid prototyping, or for production-ready software development.
42 |
43 |
--------------------------------------------------------------------------------
/Lesson 1 - Introduction to Python/intro.py:
--------------------------------------------------------------------------------
1 | '''
2 | Beginning with Python programming:
3 |
4 | Finding an Interpreter:
5 |
6 | Before we start Python programming, we need to have an interpreter to interpret and run our programs.
7 | There are certain online interpreters like http://ideone.com/ or http://codepad.org/ that can be used to start Python
8 | without installing an interpreter.
9 |
10 | Windows:There are many interpreters available freely to run Python scripts like IDLE ( Integrated Development Environment )
11 | which is installed when you install the python software from http://python.org/
12 |
13 | Linux:For Linux, Python comes bundled with the linux.
14 |
15 | '''
16 | #first program in Python
17 | # Script Begins
18 |
19 | print("Hello!!")
20 |
21 | # Scripts Ends
22 | '''
23 | OUTPUT
24 | Hello!!
25 | '''
26 | '''
27 | NOTE
28 | In a Python script to print something on the console print() function is used – it simply prints out a line ( and also
29 | includes a newline unlike in C ). One difference between Python 2 and Python 3 is the print statement. In Python 2, the “print”
30 | atement is not a function, and therefore can be invoked without a parenthesis. However, in Python 3, it is a function, and must
31 | invoked with parentheses.
32 | '''
33 | '''
34 | A suggestion would be to visit the documentation page of Python and study the keywords, functions, classes before actually
35 | going ahead with python programming.
36 | '''
37 |
38 | # Variables
39 | x = 5
40 | y = "John"
41 | print(x)
42 | print(y)
43 |
44 | # String Operations
45 | a = "Hello"
46 | b = "World"
47 | print(a+b)
48 |
49 | # For loop travesing a list
50 | fruits = ["apple", "banana", "cherry"]
51 | for x in fruits:
52 | print(x)
53 |
54 | # For loop iterating 6 times
55 | for i in range(6):
56 | print(i)
57 |
58 |
--------------------------------------------------------------------------------
/Lesson 2 - Using Functions/Function.py:
--------------------------------------------------------------------------------
1 | def say(phrase):
2 | print(phrase)
3 |
4 | say("Python")
5 |
6 | #############################################################
7 |
8 | def yello(phrase):
9 | print(phrase.upper() + "!")
10 |
11 | yello("Yepp")
12 |
13 |
14 | #############################################################
15 |
16 | def hey(phrase = "Gooden Morden"):
17 | print(phrase, '!')
18 |
19 | hey()
--------------------------------------------------------------------------------
/Lesson 2 - Using Functions/functions.md:
--------------------------------------------------------------------------------
1 | # Functions in Python
2 |
3 |
4 | ## Brief Introduction:
5 |
6 | (Source: [https://www.w3schools.com/python/python_functions.asp](https://www.w3schools.com/python/python_functions.asp))
7 |
8 |
9 |
10 | * A function is a block of code which only runs when it is called.It performs a specific task.
11 | * You can pass data, known as parameters, into a function.
12 | * A function can return data as a result to the calling function.
13 |
14 |
15 | ### Python Sample program to display the use of functions:
16 | ```
17 | #This function checks whether the entered number is a multiple of 5 or not:
18 | def check( x ):
19 | if (x % 5 == 0):
20 | print "Yes"
21 | else:
22 | print "No"
23 | #Driver code
24 | check(2)
25 | check(3)
26 | ```
27 |
28 | In python we can also assign functions to variables
29 |
30 | ```
31 | evenOdd = check
32 | #Driver code
33 | evenOdd(2)
34 | evenOdd(3)
35 | #the output will be same as of previous function calls: check(2) , check(3)
36 |
37 | ```
38 |
39 | ## Creating a Function
40 |
41 | In Python a function is defined using the `def` keyword:
42 |
43 |
44 | ```
45 | def my_function():
46 | print("I am a Function")
47 | ```
48 |
49 |
50 |
51 | ## Calling a Function
52 |
53 | To call a function, use the function name followed by parenthesis:
54 |
55 |
56 | ```
57 | def my_function():
58 | print("Hello from a function")
59 |
60 | my_function()
61 | ```
62 |
63 |
64 |
65 | #### With this short and crisp refresher on functions in python, the Lesson will now walk you through some in-built functions in python. It is expected that you have preliminary programming knowledge (Iterators, Conditions, Syntax, Semantics, etc.)
66 |
67 |
68 | # MODULE 1: CREATING A REMINDER APP
69 |
70 | Before heading further to module 1, It is important to know where the functions of python are stored. Python uses the concept of libraries to store functions and classes (later in this course).
71 |
72 |
73 | # The Python Standard Library
74 |
75 |
76 | (Source:[https://docs.python.org/3/library/](https://docs.python.org/3/library/))
77 |
78 | While [The Python Language Reference](https://docs.python.org/3/reference/index.html#reference-index) describes the exact syntax and semantics of the Python language, this library reference manual describes the standard library that is distributed with Python. It also describes some of the optional components that are commonly included in Python distributions.
79 |
80 |
81 | ### Task 1: Create a python script to set a reminder in about a fix duration of time that opens a youtube video using the concept of functions in python.
82 |
83 | (This can be used to take a break from long and continuous computer hours)
84 |
85 |
86 | ### Assistance:
87 |
88 |
89 |
90 | * Python Standard Library has a module called 'webbrowser'
91 | * Check on Resources to get the solution
92 |
93 |
94 | ### TASK 2: There is a message to be decoded. There have been pictures of file format .jpg which have to be renamed in such a way that the digits in the names have to be removed which upon sorting would show a message. There is a folder containing all those images along this lesson. Write a python script to do the needful
95 |
96 | (Wait What??....Yes! This can be playful with your friends.)
97 |
98 |
99 | ### Assistance:
100 |
101 |
102 |
103 | * Python Standard Library has a module called 'os'
104 | * Use listdir function inside the os module
105 | * Refer to the Internet for complete documentation of os module
106 | * Check on Resources to get the solution
107 |
108 |
109 | # About Used Modules:
110 |
111 |
112 |
113 | * [https://docs.python.org/2/library/webbrowser.html](https://docs.python.org/2/library/webbrowser.html)
114 | * [https://docs.python.org/2/library/os.html](https://docs.python.org/2/library/os.html)
115 |
116 |
117 | Refer to [https://data-flair.training/blogs/python-built-in-functions/](https://data-flair.training/blogs/python-built-in-functions/) for a list of python inbuilt functions and explore their potential.
118 |
119 |
120 |
--------------------------------------------------------------------------------
/Lesson 2 - Using Functions/prank/athens.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/josharsh/OPython-Init/11d33bfdcc8e35203edcec1efeb39506ea133d2a/Lesson 2 - Using Functions/prank/athens.jpg
--------------------------------------------------------------------------------
/Lesson 2 - Using Functions/prank/austin.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/josharsh/OPython-Init/11d33bfdcc8e35203edcec1efeb39506ea133d2a/Lesson 2 - Using Functions/prank/austin.jpg
--------------------------------------------------------------------------------
/Lesson 2 - Using Functions/prank/bangalore.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/josharsh/OPython-Init/11d33bfdcc8e35203edcec1efeb39506ea133d2a/Lesson 2 - Using Functions/prank/bangalore.jpg
--------------------------------------------------------------------------------
/Lesson 2 - Using Functions/prank/barcelona.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/josharsh/OPython-Init/11d33bfdcc8e35203edcec1efeb39506ea133d2a/Lesson 2 - Using Functions/prank/barcelona.jpg
--------------------------------------------------------------------------------
/Lesson 2 - Using Functions/prank/beijing.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/josharsh/OPython-Init/11d33bfdcc8e35203edcec1efeb39506ea133d2a/Lesson 2 - Using Functions/prank/beijing.jpg
--------------------------------------------------------------------------------
/Lesson 2 - Using Functions/prank/berkeley.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/josharsh/OPython-Init/11d33bfdcc8e35203edcec1efeb39506ea133d2a/Lesson 2 - Using Functions/prank/berkeley.jpg
--------------------------------------------------------------------------------
/Lesson 2 - Using Functions/prank/bogota.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/josharsh/OPython-Init/11d33bfdcc8e35203edcec1efeb39506ea133d2a/Lesson 2 - Using Functions/prank/bogota.jpg
--------------------------------------------------------------------------------
/Lesson 2 - Using Functions/prank/bristol.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/josharsh/OPython-Init/11d33bfdcc8e35203edcec1efeb39506ea133d2a/Lesson 2 - Using Functions/prank/bristol.jpg
--------------------------------------------------------------------------------
/Lesson 2 - Using Functions/prank/bucharest.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/josharsh/OPython-Init/11d33bfdcc8e35203edcec1efeb39506ea133d2a/Lesson 2 - Using Functions/prank/bucharest.jpg
--------------------------------------------------------------------------------
/Lesson 2 - Using Functions/prank/buenos aires.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/josharsh/OPython-Init/11d33bfdcc8e35203edcec1efeb39506ea133d2a/Lesson 2 - Using Functions/prank/buenos aires.jpg
--------------------------------------------------------------------------------
/Lesson 2 - Using Functions/prank/cairo.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/josharsh/OPython-Init/11d33bfdcc8e35203edcec1efeb39506ea133d2a/Lesson 2 - Using Functions/prank/cairo.jpg
--------------------------------------------------------------------------------
/Lesson 2 - Using Functions/prank/chennai.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/josharsh/OPython-Init/11d33bfdcc8e35203edcec1efeb39506ea133d2a/Lesson 2 - Using Functions/prank/chennai.jpg
--------------------------------------------------------------------------------
/Lesson 2 - Using Functions/prank/chicago.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/josharsh/OPython-Init/11d33bfdcc8e35203edcec1efeb39506ea133d2a/Lesson 2 - Using Functions/prank/chicago.jpg
--------------------------------------------------------------------------------
/Lesson 2 - Using Functions/prank/colombo.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/josharsh/OPython-Init/11d33bfdcc8e35203edcec1efeb39506ea133d2a/Lesson 2 - Using Functions/prank/colombo.jpg
--------------------------------------------------------------------------------
/Lesson 2 - Using Functions/prank/dallas.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/josharsh/OPython-Init/11d33bfdcc8e35203edcec1efeb39506ea133d2a/Lesson 2 - Using Functions/prank/dallas.jpg
--------------------------------------------------------------------------------
/Lesson 2 - Using Functions/prank/delhi.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/josharsh/OPython-Init/11d33bfdcc8e35203edcec1efeb39506ea133d2a/Lesson 2 - Using Functions/prank/delhi.jpg
--------------------------------------------------------------------------------
/Lesson 2 - Using Functions/prank/edinbrugh.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/josharsh/OPython-Init/11d33bfdcc8e35203edcec1efeb39506ea133d2a/Lesson 2 - Using Functions/prank/edinbrugh.jpg
--------------------------------------------------------------------------------
/Lesson 2 - Using Functions/prank/gainesville.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/josharsh/OPython-Init/11d33bfdcc8e35203edcec1efeb39506ea133d2a/Lesson 2 - Using Functions/prank/gainesville.jpg
--------------------------------------------------------------------------------
/Lesson 2 - Using Functions/prank/houston.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/josharsh/OPython-Init/11d33bfdcc8e35203edcec1efeb39506ea133d2a/Lesson 2 - Using Functions/prank/houston.jpg
--------------------------------------------------------------------------------
/Lesson 2 - Using Functions/prank/hyderabad.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/josharsh/OPython-Init/11d33bfdcc8e35203edcec1efeb39506ea133d2a/Lesson 2 - Using Functions/prank/hyderabad.jpg
--------------------------------------------------------------------------------
/Lesson 2 - Using Functions/prank/istanbul.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/josharsh/OPython-Init/11d33bfdcc8e35203edcec1efeb39506ea133d2a/Lesson 2 - Using Functions/prank/istanbul.jpg
--------------------------------------------------------------------------------
/Lesson 2 - Using Functions/prank/ithaca.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/josharsh/OPython-Init/11d33bfdcc8e35203edcec1efeb39506ea133d2a/Lesson 2 - Using Functions/prank/ithaca.jpg
--------------------------------------------------------------------------------
/Lesson 2 - Using Functions/prank/jacksonville.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/josharsh/OPython-Init/11d33bfdcc8e35203edcec1efeb39506ea133d2a/Lesson 2 - Using Functions/prank/jacksonville.jpg
--------------------------------------------------------------------------------
/Lesson 2 - Using Functions/prank/karachi.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/josharsh/OPython-Init/11d33bfdcc8e35203edcec1efeb39506ea133d2a/Lesson 2 - Using Functions/prank/karachi.jpg
--------------------------------------------------------------------------------
/Lesson 2 - Using Functions/prank/kiev.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/josharsh/OPython-Init/11d33bfdcc8e35203edcec1efeb39506ea133d2a/Lesson 2 - Using Functions/prank/kiev.jpg
--------------------------------------------------------------------------------
/Lesson 2 - Using Functions/prank/london.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/josharsh/OPython-Init/11d33bfdcc8e35203edcec1efeb39506ea133d2a/Lesson 2 - Using Functions/prank/london.jpg
--------------------------------------------------------------------------------
/Lesson 2 - Using Functions/prank/madrid.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/josharsh/OPython-Init/11d33bfdcc8e35203edcec1efeb39506ea133d2a/Lesson 2 - Using Functions/prank/madrid.jpg
--------------------------------------------------------------------------------
/Lesson 2 - Using Functions/prank/manchester.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/josharsh/OPython-Init/11d33bfdcc8e35203edcec1efeb39506ea133d2a/Lesson 2 - Using Functions/prank/manchester.jpg
--------------------------------------------------------------------------------
/Lesson 2 - Using Functions/prank/miami.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/josharsh/OPython-Init/11d33bfdcc8e35203edcec1efeb39506ea133d2a/Lesson 2 - Using Functions/prank/miami.jpg
--------------------------------------------------------------------------------
/Lesson 2 - Using Functions/prank/new york.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/josharsh/OPython-Init/11d33bfdcc8e35203edcec1efeb39506ea133d2a/Lesson 2 - Using Functions/prank/new york.jpg
--------------------------------------------------------------------------------
/Lesson 2 - Using Functions/prank/oakland.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/josharsh/OPython-Init/11d33bfdcc8e35203edcec1efeb39506ea133d2a/Lesson 2 - Using Functions/prank/oakland.jpg
--------------------------------------------------------------------------------
/Lesson 2 - Using Functions/prank/pune.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/josharsh/OPython-Init/11d33bfdcc8e35203edcec1efeb39506ea133d2a/Lesson 2 - Using Functions/prank/pune.jpg
--------------------------------------------------------------------------------
/Lesson 2 - Using Functions/prank/rochester.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/josharsh/OPython-Init/11d33bfdcc8e35203edcec1efeb39506ea133d2a/Lesson 2 - Using Functions/prank/rochester.jpg
--------------------------------------------------------------------------------
/Lesson 2 - Using Functions/prank/san diego.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/josharsh/OPython-Init/11d33bfdcc8e35203edcec1efeb39506ea133d2a/Lesson 2 - Using Functions/prank/san diego.jpg
--------------------------------------------------------------------------------
/Lesson 2 - Using Functions/prank/san jose.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/josharsh/OPython-Init/11d33bfdcc8e35203edcec1efeb39506ea133d2a/Lesson 2 - Using Functions/prank/san jose.jpg
--------------------------------------------------------------------------------
/Lesson 2 - Using Functions/prank/sao paulo.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/josharsh/OPython-Init/11d33bfdcc8e35203edcec1efeb39506ea133d2a/Lesson 2 - Using Functions/prank/sao paulo.jpg
--------------------------------------------------------------------------------
/Lesson 2 - Using Functions/prank/seattle.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/josharsh/OPython-Init/11d33bfdcc8e35203edcec1efeb39506ea133d2a/Lesson 2 - Using Functions/prank/seattle.jpg
--------------------------------------------------------------------------------
/Lesson 2 - Using Functions/prank/seoul.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/josharsh/OPython-Init/11d33bfdcc8e35203edcec1efeb39506ea133d2a/Lesson 2 - Using Functions/prank/seoul.jpg
--------------------------------------------------------------------------------
/Lesson 2 - Using Functions/prank/shanghai.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/josharsh/OPython-Init/11d33bfdcc8e35203edcec1efeb39506ea133d2a/Lesson 2 - Using Functions/prank/shanghai.jpg
--------------------------------------------------------------------------------
/Lesson 2 - Using Functions/prank/singapore.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/josharsh/OPython-Init/11d33bfdcc8e35203edcec1efeb39506ea133d2a/Lesson 2 - Using Functions/prank/singapore.jpg
--------------------------------------------------------------------------------
/Lesson 2 - Using Functions/prank/sunnyvale.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/josharsh/OPython-Init/11d33bfdcc8e35203edcec1efeb39506ea133d2a/Lesson 2 - Using Functions/prank/sunnyvale.jpg
--------------------------------------------------------------------------------
/Lesson 2 - Using Functions/prank/sydney.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/josharsh/OPython-Init/11d33bfdcc8e35203edcec1efeb39506ea133d2a/Lesson 2 - Using Functions/prank/sydney.jpg
--------------------------------------------------------------------------------
/Lesson 2 - Using Functions/prank/tel aviv.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/josharsh/OPython-Init/11d33bfdcc8e35203edcec1efeb39506ea133d2a/Lesson 2 - Using Functions/prank/tel aviv.jpg
--------------------------------------------------------------------------------
/Lesson 3 - Introduction to OOP Concepts/inheritance.py:
--------------------------------------------------------------------------------
1 | class p:
2 | def __init__(self, x):
3 | self.x = x
4 | def display_p(self):
5 | print(self.x)
6 |
7 | class a:
8 | def __init__(self, x):
9 | self.x = x
10 | def display_a(self):
11 | print(self.x)
12 |
13 | obA = a(2)
14 | obA.display_a()
15 |
16 | class b(a): #example of single level inheritance of a in b
17 | def __init__(self, x,y):
18 | a.__init__(self,x)
19 | self.y = y
20 | def display_b(self):
21 | print(self.x, self.y)
22 | obB = b(2,3)
23 | obB.display_b()
24 |
25 | class c(b): #example of muti-level inheritance of a in b and then b in c
26 | def __init__(self, x, y ,z):
27 | a.__init__(self, x)
28 | b.__init__(self, x, y)
29 | self.z = z
30 | def display_c(self):
31 | print(self.x,self.y,self.z)
32 |
33 | obC = c(2,3,4)
34 | obC.display_c()
35 |
36 | class d(a, p): #multiple inheritance example
37 | def __init__(self, x, y, z):
38 | a.__init__(self,x)
39 | self.z = z
40 | def display_d(self):
41 | print(self.x, self.z)
42 | obD = d(2,34, 5)
43 | obD.display_d()
44 |
--------------------------------------------------------------------------------
/Lesson 3 - Introduction to OOP Concepts/oops.md:
--------------------------------------------------------------------------------
1 |
2 |
3 | # Object-Oriented Basics Using Python
4 |
5 | (Source: [https://www.tutorialspoint.com/python/python_classes_objects.htm](https://www.tutorialspoint.com/python/python_classes_objects.htm))
6 |
7 | Python has been an object-oriented language since it existed. Because of this, creating and using classes and objects are downright easy. This chapter helps you become an expert in using Python's object-oriented programming support.If you do not have any previous experience with object-oriented (OO) programming, you may want to consult an introductory course on it or at least a tutorial of some sort so that you have a grasp of the basic concepts.However, here is a small introduction of Object-Oriented Programming (OOP) to bring you at speed −
8 |
9 |
10 | ## Overview of OOP Terminology
11 |
12 |
13 |
14 | * Class − A user-defined prototype for an object that defines a set of attributes that characterize an object of the class. The attributes are data members (class variables and instance variables) and methods, accessed via dot notation.
15 | * Class variable − A variable that is shared by all instances of a class. Class variables are defined within a class but outside any of the class's methods. Class variables are not used as frequently as instance variables are.
16 | * Data member − A class variable or instance variable that holds data associated with a class and its objects.
17 | * Function overloading − The assignment of more than one behavior to a particular function. The operation performed varies by the types of objects or arguments involved.
18 | * Instance variable − A variable that is defined inside a method and belongs only to the current instance of a class.
19 | * Inheritance − The transfer of the characteristics of a class to other classes that are derived from it.
20 | * Instance − An individual object of a certain class. An object obj that belongs to a class Circle, for example, is an instance of the class Circle.
21 | * Instantiation − The creation of an instance of a class.
22 | * Method − A special kind of function that is defined in a class definition.
23 | * Object − A unique instance of a data structure that's defined by its class. An object comprises both data members (class variables and instance variables) and methods.
24 | * Operator overloading − The assignment of more than one function to a particular operator.
25 |
26 | EXAMPLE:
27 |
28 |
29 | ```
30 | class Student:
31 | 'Common base class for all Students'
32 | stuCount = 0
33 |
34 | def __init__(self, name, marks):
35 | self.name = name
36 | self.marks = marks
37 | Student.stuCount += 1
38 |
39 | def displayCount(self):
40 | print "Total Student %d" % Student.stuCount
41 |
42 | def displayStudent(self):
43 | print "Name : ", self.name, ", marks: ", self.marks
44 | ```
45 |
46 |
47 |
48 | ## **Python Objects (Instances)**
49 |
50 | (Source: [https://realpython.com/python3-object-oriented-programming/](https://realpython.com/python3-object-oriented-programming/))
51 |
52 | While the class is the blueprint, an _instance_ is a copy of the class with _actual_ values, literally an object belonging to a specific class. It's not an idea anymore; it's an actual animal, like a dog named Roger who's eight years old.
53 |
54 | Put another way, a class is like a form or questionnaire. It defines the needed information. After you fill out the form, your specific copy is an instance of the class; it contains actual information relevant to you.
55 |
56 | You can fill out multiple copies to create many different instances, but without the form as a guide, you would be lost, not knowing what information is required. Thus, before you can create individual instances of an object, we must first specify what is needed by defining a class.
57 |
58 | ### CREATING CLASS AND OBJECT IN PYTHON
59 |
60 | ```
61 | class Parrot:
62 |
63 | # class attribute
64 | species = "bird"
65 |
66 | # instance attribute
67 | def __init__(self, name, age):
68 | self.name = name
69 | self.age = age
70 | ```
71 | # instantiate the Parrot class
72 | ~~~
73 | blu = Parrot("Blu", 10)
74 | woo = Parrot("Woo", 15)
75 | ~~~
76 | # access the class attributes
77 | ~~~
78 | print("Blu is a {}".format(blu.__class__.species))
79 | print("Woo is also a {}".format(woo.__class__.species))
80 | ~~~
81 | # access the instance attributes
82 | ~~~
83 | print("{} is {} years old".format( blu.name, blu.age))
84 | print("{} is {} years old".format( woo.name, woo.age))
85 | ~~~
86 |
87 | ## **Python Inheritance **
88 |
89 | (Source: [https://www.geeksforgeeks.org/oop-in-python-set-3-inheritance-examples-of-object-issubclass-and-super/](https://www.geeksforgeeks.org/oop-in-python-set-3-inheritance-examples-of-object-issubclass-and-super/)
90 |
91 | Inheritance is one of the core concepts of object-oriented programming (OOP) languages. It is a mechanism where you can to derive a class from another class for a hierarchy of classes that share a set of attributes and methods.
92 |
--------------------------------------------------------------------------------
/Lesson 3 - Introduction to OOP Concepts/oops.py:
--------------------------------------------------------------------------------
1 | #class
2 | class Tiger:
3 | pass
4 |
5 | #object
6 | obj = Tiger()
7 |
8 | #Creating Class and Object in Python
9 | class Tiger:
10 |
11 | # class attribute
12 | species = "animal"
13 |
14 | # instance attribute
15 | def __init__(self, name, age):
16 | self.name = name
17 | self.age = age
18 |
19 | # instantiate the Tiger class
20 | blu = Tiger("Blu", 10)
21 | woo = Tiger("Woo", 15)
22 |
23 | # access the class attributes
24 | print("Blu is a {}".format(blu.__class__.species))
25 | print("Woo is also a {}".format(woo.__class__.species))
26 |
27 | # access the instance attributes
28 | print("{} is {} years old".format( blu.name, blu.age))
29 | print("{} is {} years old".format( woo.name, woo.age))
30 |
31 | '''OUTPUT
32 | Blu is a tiger
33 | Woo is also a tiger
34 | Blu is 10 years old
35 | Woo is 15 years old'''
36 |
37 | #Creating Methods in Python
38 | class Tiger:
39 |
40 | # instance attributes
41 | def __init__(self, name, age):
42 | self.name = name
43 | self.age = age
44 |
45 | # instance method
46 | def growl(self, growl):
47 | return "{} growls {}".format(self.name, growl)
48 |
49 | def hunt(self):
50 | return "{} is now hunting".format(self.name)
51 |
52 | # instantiate the object
53 | blu = Tiger("Blu", 10)
54 |
55 | # call our instance methods
56 | print(blu.growl("'GROWL'"))
57 | print(blu.hunt())
58 |
59 | '''OUTPUT
60 | Blu growls 'GROWL'
61 | Blu is now hunting'''
62 |
63 | #Use of Inheritance in Python
64 | # parent class
65 | class Bird:
66 |
67 | def __init__(self):
68 | print("Bird is ready")
69 |
70 | def whoisThis(self):
71 | print("Bird")
72 |
73 | def swim(self):
74 | print("Swim faster")
75 |
76 | # child class
77 | class Penguin(Bird):
78 |
79 | def __init__(self):
80 | # call super() function
81 | super().__init__()
82 | print("Penguin is ready")
83 |
84 | def whoisThis(self):
85 | print("Penguin")
86 |
87 | def run(self):
88 | print("Run faster")
89 |
90 | peggy = Penguin()
91 | peggy.whoisThis()
92 | peggy.swim()
93 | peggy.run()
94 |
95 | '''OUTPUT
96 | Bird is ready
97 | Penguin is ready
98 | Penguin
99 | Swim faster
100 | Run faster'''
101 |
102 | #Data Encapsulation in Python
103 | class Computer:
104 |
105 | def __init__(self):
106 | self.__maxprice = 900
107 |
108 | def sell(self):
109 | print("Selling Price: {}".format(self.__maxprice))
110 |
111 | def setMaxPrice(self, price):
112 | self.__maxprice = price
113 |
114 | c = Computer()
115 | c.sell()
116 |
117 | # change the price
118 | c.__maxprice = 1000
119 | c.sell()
120 |
121 | # using setter function
122 | c.setMaxPrice(1000)
123 | c.sell()
124 |
125 | '''OUTPUT
126 | Selling Price: 900
127 | Selling Price: 900
128 | Selling Price: 1000'''
129 |
130 | #Using Polymorphism in Python
131 | class Parrot:
132 |
133 | def fly(self):
134 | print("Parrot can fly")
135 |
136 | def swim(self):
137 | print("Parrot can't swim")
138 |
139 | class Penguin:
140 |
141 | def fly(self):
142 | print("Penguin can't fly")
143 |
144 | def swim(self):
145 | print("Penguin can swim")
146 |
147 | # common interface
148 | def flying_test(bird):
149 | bird.fly()
150 |
151 | #instantiate objects
152 | blu = Parrot()
153 | peggy = Penguin()
154 |
155 | # passing the object
156 | flying_test(blu)
157 | flying_test(peggy)
158 |
159 | '''OUTPUT
160 | Parrot can fly
161 | Penguin can't fly'''
162 |
--------------------------------------------------------------------------------
/Lesson 4 - OOP Implementation/TurtleTutorial.py:
--------------------------------------------------------------------------------
1 | from turtle import *
2 |
3 | # Welcome this is the turtle tutorial
4 | # Turtle library is a drawing library check them out on
5 | # https://docs.python.org/3.3/library/turtle.html?highlight=turtle#turtle.speed
6 |
7 | # To make a square we have to move forward then a direction 4 times.
8 |
9 | for i in range(4): # Start a loop
10 | forward(100) # Move forward
11 | right(90) # Turn
12 |
13 | # Now we just need to make a circle by a square
14 | # To make it easy for us let us make a function to the square
15 |
16 | def square():
17 | for i in range(4):
18 | forward(100)
19 | right(90)
20 | speed(0)
21 | # return None
22 |
23 | for i in range(360):
24 | square()
25 | right(1)
26 | speed(0)
27 |
28 | # And if you want to speed up stuff and get the result faster
29 | # speed(10) # 0 is the fastest while 1 is the slowest, 10 is fast
30 |
31 | # Have fun and try out different challenges
--------------------------------------------------------------------------------
/Lesson 4 - OOP Implementation/Twilio.py:
--------------------------------------------------------------------------------
1 | # from twilio.rest import Client
2 |
3 | # Do a pip install twilio
4 | # Go to twilio.com to make an account and open project.
5 |
6 | # # Your Account SID from twilio.com/console
7 | # account_sid = "SAME THING AS BELOW"
8 | # # Your Auth Token from twilio.com/console
9 | # auth_token = "Your OWN AUTH TOKEN FROM CONSOLE"
10 |
11 | # client = Client(account_sid, auth_token)
12 |
13 | # message = client.messages.create(
14 | # to="+Your-Own-Number-Please",
15 | # from_="+The-Number-In-your-Console",
16 | # body="Hello from Python! LUG_VCU")
17 |
18 | # print(message.sid)
19 |
20 | # Idea's to increase on this project
21 |
22 | # Parse data from sports sites and send scores and updates
23 | # Make a diy security system. OpenCV, rasberry pi and twilio
24 | # Parse motivating quotes and send them to your self.
25 | # Don't just limit yourself to words. Send cat images to your self along with a yasuo highlight.
26 |
27 | # The twilio module has a lot of stuff check their documentation.
28 | # https://www.twilio.com/docs/libraries/python
--------------------------------------------------------------------------------
/Lesson 4 - OOP Implementation/oopimplementation.md:
--------------------------------------------------------------------------------
1 | # OOP Implementation Using Python
2 |
3 |
4 | ## TASK 1: Refer the Internet for turtle module of Python. Study about Class implementation from given repository resources and write a python script for making an animation of multiple squares deviating at an angle to form a circle.
5 |
6 |
7 | ## Assistance:
8 |
9 |
10 |
11 | * Python Standard Library has a module called 'turtle'
12 | * turtle module has a class called Turtle
13 | * Calling turtle.Turtle() instantiates the class.
14 | * Refer to the Internet for turtle documentation
15 | * Check on Resources to get the solution
16 |
17 |
18 | ## TASK 2: Using Twilio module of python (which is not a part of Standard Python Library) write a python script that can send a message to a phone number. Study about Twilio and python usage from the Internet.
19 |
20 | (Messages from a small piece of code?? Interesting!)
21 |
22 |
23 | ## Assistance:
24 |
25 |
26 |
27 | * Study about module called Twilio
28 | * Twilio account in needed to use the API
29 | * Be careful about Auth Token
30 | * Refer to the Internet for complete documentation of Twilio module
31 | * Check on Resources to get the solution
32 |
33 |
34 | # About Used Modules:
35 |
36 |
37 |
38 | * [https://www.twilio.com/docs/libraries/python](https://www.twilio.com/docs/libraries/python)
39 | * [https://docs.python.org/2/library/turtle.html](https://docs.python.org/2/library/turtle.html)
--------------------------------------------------------------------------------
/Lesson 5 - Web Sraping/README.md:
--------------------------------------------------------------------------------
1 | **Web Scraping**
2 |
3 | Web scraping is a technique to automatically access and extract large amounts of information from a website, which can save a huge amount of time and effort. In this article, we will go through an easy example of how to automate downloading hundreds of files from the New York MTA. This is a great exercise for web scraping beginners who are looking to understand how to web scrape. Web scraping can be slightly intimidating, so this tutorial will break down the process of how to go about the process.
4 |
5 | ** **
6 |
7 | **New York MTA Data**
8 |
9 | We will be downloading turnstile data from this site:
10 |
11 | ```
12 | http://web.mta.info/developers/turnstile.html
13 | ```
14 |
15 | Turnstile data is compiled every week from May 2010 to present, so hundreds of .txt files exist on the site. Each date is a link to the .txt file that you can download.
16 |
17 | It would be torturous to manually right click on each link and save to your desktop. Luckily, there’s web-scraping!
18 |
19 | **Important notes about web scraping:**
20 | 1. Read through the website’s Terms and Conditions to understand how you can legally use the data. Most sites prohibit you from using the data for commercial purposes.
21 |
22 | 2. Make sure you are not downloading data at too rapid a rate because this may break the website. You may potentially be blocked from the site as well.
23 |
24 | **Inspecting the Website**
25 |
26 | The first thing that we need to do is to figure out where we can locate the links to the files we want to download inside the multiple levels of HTML tags. Simply put, there is a lot of code on a website page and we want to find the relevant pieces of code that contains our data. If you are not familiar with HTML tags, refer to W3Schools [Tutorials](http://www.w3schools.com/). It is important to understand the basics of HTML in order to successfully web scrape.
27 |
28 | On the website, right click and click on “Inspect”. This allows you to see the raw code behind the site.
29 |
30 | Once you’ve clicked on “Inspect”, you should see this console pop up.
31 |
32 | **Console**
33 |
34 | Notice that on the top left of the console, there is an arrow symbol.
35 |
36 | If you click on this arrow and then click on an area of the site itself, the code for that particular item will be highlighted in the console. I’ve clicked on the very first data file, Saturday, September 22, 2018 and the console has highlighted in blue the link to that particular file.
37 |
38 | ```
39 | Saturday, September 22, 2018
40 | ```
41 |
42 | Notice that all the .txt files are inside the `` tag following the line above. As you do more web scraping, you will find that the `` is used for hyperlinks.
43 |
44 | Now that we’ve identified the location of the links, let’s get started on coding!
45 |
46 | ** **
47 |
48 | **Python Code**
49 |
50 | We start by importing the following libraries.
51 |
52 | ```
53 | import requests
54 | import urllib.request
55 | import time
56 | from bs4 import BeautifulSoup
57 | ```
58 |
59 | Next, we set the url to the website and access the site with our requests library.
60 |
61 | ```
62 | url = 'http://web.mta.info/developers/turnstile.html'
63 | response = requests.get(url)
64 | ```
65 |
66 | If the access was successful, you should see the following output:
67 |
68 | Next we parse the html with BeautifulSoup so that we can work with a nicer, nested BeautifulSoup data structure. If you are interested in learning more about this library, check out the [BeatifulSoup documentation](https://www.crummy.com/software/BeautifulSoup/bs4/doc/).
69 |
70 | ```
71 | soup = BeautifulSoup(response.text, "html.parser")
72 | ```
73 |
74 | We use the method .findAll to locate all of our `` tags.
75 |
76 | ```
77 | soup.findAll('a')
78 | ```
79 |
80 | This code gives us every line of code that has an `` tag. The information that we are interested in starts on line 36. Not all links are relevant to what we want, but most of it is, so we can easily slice from line 36. Below is a subset of what BeautifulSoup returns to us when we call the code above.
81 |
82 | **subset of all tags**
83 |
84 | Next, let’s extract the actual link that we want. Let’s test out the first link.
85 |
86 | ```
87 | one_a_tag = soup.findAll('a')[36]
88 | link = one_a_tag['href']
89 | ```
90 |
91 | This code saves ‘data/nyct/turnstile/turnstile_180922.txt’ to our variable link. The full url to download the data is actually http://web.mta.info/developers/data/nyct/turnstile/turnstile_180922.txt which I discovered by clicking on the first data file on the website as a test. We can use our `urllib.request library to download this file path to our computer. We provide request.urlretrieve with two parameters: file url and the filename. For my files, I named them “turnstile_180922.txt”, “turnstile_180901”, etc.
92 |
93 | ```
94 | download_url = 'http://web.mta.info/developers/'+ link
95 | urllib.request.urlretrieve(download_url,'./'+link[link.find('/turnstile_')+1:])
96 | ```
97 |
98 | Last but not least, we should include this line of code so that we can pause our code for a second so that we are not spamming the website with requests. This helps us avoid getting flagged as a spammer.
99 |
100 | ```
101 | time.sleep(1)
102 | ```
103 |
104 | Now that we understand how to download a file, let’s try downloading the entire set of data files with a for loop. The code below contains the entire set of code for web scraping the NY MTA turnstile data.
105 |
--------------------------------------------------------------------------------
/Lesson 5 - Web Sraping/Web Scraping.md.docx:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/josharsh/OPython-Init/11d33bfdcc8e35203edcec1efeb39506ea133d2a/Lesson 5 - Web Sraping/Web Scraping.md.docx
--------------------------------------------------------------------------------
/Lesson 6 - String Manipulation/BooleanStringTest.py:
--------------------------------------------------------------------------------
1 | print("python".isalnum())
2 | print("3".isdigit())
3 | print("3rd".isalnum())
4 | print("Hii".islower())
5 | print("Super".startswith("s"))
6 | print("Harry Potter".istitle())
7 | length = "3"
8 | print("s")
9 | print(length.isalnum())
--------------------------------------------------------------------------------
/Lesson 6 - String Manipulation/FormatString.py:
--------------------------------------------------------------------------------
1 | print("Python is awesome".capitalize())
2 | print("PYTHON IS KING".lower())
3 | print("python is hot".upper())
4 | print("Harry potter and the half-blood prince".title())
5 | print("AVENGER:the war of infinity".swapcase())
--------------------------------------------------------------------------------
/Lesson 6 - String Manipulation/FormatStringInput.py:
--------------------------------------------------------------------------------
1 | import string # make sure that you import string to utilize the .capwords() method
2 |
3 | favColor = input("What is your favorite color?:-").upper() # makes every letter CAPITAL
4 | print(favColor)
5 |
6 | # or
7 |
8 | favColor = input("What's your favorite color?:-")
9 | print(favColor.capitalize()) # will capitalize first character and convert all other characters to lower case. Does
10 | # not work if the first character is not a letter (empty space, number, etc.). See example below:
11 |
12 | capitalizeExample = "the quick brown FOX jumps ovEr the lazy DOG" # this will print when you run the file, but take note of the formatting
13 | print('This is the string prior to calling the .capitalize() method on it: -->',
14 | capitalizeExample) # this is the string
15 | # prior to calling the capitalize method on it
16 | print('This is what happens after calling .capitalize() on the string: -->', capitalizeExample.capitalize())
17 |
18 | # or
19 |
20 | favColor = input("What's are your favorite colors?:-")
21 | print(string.capwords(
22 | favColor)) # utilize string.capwords() method from Python library to make the first letter of every word capitalized
23 |
--------------------------------------------------------------------------------
/Lesson 6 - String Manipulation/StringComparison.py:
--------------------------------------------------------------------------------
1 | name = input("Enter name: ")
2 |
3 | if name.lower() < "c":
4 | print("less than")
5 | else:
6 | print("greater than")
--------------------------------------------------------------------------------
/Lesson 6 - String Manipulation/StringLength.py:
--------------------------------------------------------------------------------
1 | word = "Hey Python"
2 | print(len(word))
3 |
4 | len_word = len(word)
5 | mid_pt = int(len_word/2)
6 |
7 | print(word[mid_pt:])
8 | print(word[:mid_pt])
--------------------------------------------------------------------------------
/Lesson 6 - String Manipulation/StringSlicing.py:
--------------------------------------------------------------------------------
1 | # 0 1 2 3 4 5 6 7 8 9 10 11 12 13 -> index
2 | word = "photosynthesis" # p h o t o s y n t h e s i s
3 |
4 | #OBS: always stops at the previous index(number)
5 |
6 |
7 | print(word[2:7]) -> #Result: otosy -> #strts from 2 and ends before 7
8 |
9 | print(word[:5]) -> #Result: photo -> #ends before 5
10 |
11 | print(word[:]) -> #Result: photosynthesis -> #print whole string
12 |
13 | print(word[::3]) -> #Result: ptyhi -> #print 0 and multiple of 3 afterwards
14 |
15 | print(word[3::3]) -> #Result: tyhi -> #print 3 and multiple of 3 afterwards
16 |
17 | print(word[:-1]) -> #Result: photosynthesi -> #ends before -1
18 |
19 | print(word[:-7]) -> #Result: photosy -> #ends before -7
20 |
21 | print(word[::-1]) -> #Result: sisehtnysotohp -> #print string in reverse
22 |
23 | print(word[5::-1]) -> #Result: sotohp -> #print reverse till 5
24 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Learning-Object-Oriented-Python
2 | 
3 | This repository walks you through the Object Oriented Programming in python. Illustrates real world examples, working codes and going about finding a coding solution.
4 |
5 |
--------------------------------------------------------------------------------
/Resources/Code Solutions/Reminder_App/takeabreak.py:
--------------------------------------------------------------------------------
1 | import webbrowser
2 | import time
3 | total_time=3
4 | time_counter=0
5 | print("This Program started on "+time.ctime())
6 | while(time_counter