The document discusses various Python programming concepts including generator functions, list comprehensions, list processing features, and performance analysis using tools like timeit and memory_profiler. It provides examples of generator functions that produce sequences iteratively using yield instead of returning a list, and explores list comprehensions as a more concise way to create lists from expressions compared to traditional for loops. The document also demonstrates measuring the time and memory usage of functions to analyze performance differences between approaches.
This document discusses files and exception handling in Python. It begins by defining files and describing different types of files like data, text, and program files. It then covers topics like sequential and random file access, opening and closing files, reading and writing to files, and using file dialogs. The document also discusses retrieving data from the web using functions like urlopen. Finally, it defines exceptions and different types of errors like syntax, runtime, and logical errors. It explains how to handle exceptions in Python using try/except blocks and predefined or user-defined exceptions.
This document outlines the objectives and units of study for the course GE3151 Problem Solving and Python Programming. The course aims to teach algorithmic problem solving using Python conditionals, loops, functions, and data structures like lists, tuples and dictionaries. Students will learn to do input/output with files in Python. The 5 units cover computational thinking and problem solving, Python data types and statements, control flow and functions, lists, tuples and dictionaries, and files, modules and packages. Key concepts covered include algorithms, conditionals, iteration, functions, strings, lists, files operations like reading, writing and closing files, and exception handling.
This lecture covers files and exception handling in Python. It discusses opening, reading from, and writing to files. The key steps are opening the file, using it (reading or writing data), and closing it. Exceptions allow programs to handle and respond to errors and unexpected situations gracefully using try/except blocks. The case study demonstrates generating math tests randomly and writing the output to a file rather than displaying it on screen. This improves the program by storing the results for later use.
This document provides information about file handling in C++. It discusses key concepts like input/output streams, opening and closing files, and different file types. Specifically, it covers:
- The different stream classes like fstream, ifstream, and ofstream that are used for file input/output.
- Opening and closing files using functions like open() and close(), and specifying open modes like ios::out.
- The two main types of files - text files that use character translations and binary files that store raw bytes.
- Basic file operations in C++ like reading, writing, and manipulating files using functions like read(), write(), seekp() etc.
- Examples of opening
This document provides instructions for writing Perl scripts. It discusses four mandatory lines that must be included in every Perl script, useful modules for files and options, documentation methods, and an exercise for calculating assembly statistics from a file. The four mandatory lines are the shebang line, and lines to use warnings, use strict, and end the script. Useful file modules include File::Basename and File::Spec, while GetOpt::Std handles command line options. Documentation can be included through comments, perldoc, or print statements. The exercise involves calculating metrics like total base pairs, longest/shortest sequences, N50, and related values.
This document provides an overview of the key components of Django, including designing models, installing Django, accessing the model API, creating an admin interface, designing URLs and views, writing templates, and more. It explains these concepts at a high level and provides examples to illustrate how each component works and fits together. The goal is to help new users understand the basics of how to build a database-driven web application with Django.
Introduction to PHP: Declaring variables, data types, arrays, strings, operators, expressions, control structures, functions, Reading data from web form controls like text boxes, radio buttons, lists etc., Handling File Uploads, Connecting to database (MySQL as reference), executing simple queries, handling results, Handling sessions and cookies File Handling in PHP: File operations like opening, closing, reading, writing, appending, deleting etc. on text and binary files, listing directories
This document provides an overview of key Python concepts:
1. Modules allow organizing Python code into files and namespaces. The file name is the module name with a .py extension.
2. Python code is compiled into bytecode cache files (.pyc) for improved performance. These files are platform independent.
3. Advanced optimizations can be applied to bytecode with command line flags, but may affect program functionality in rare cases.
4. Standard modules provide useful functions like dir() to inspect modules and packages for organizing code. Input/output, strings, files and exceptions are also covered.
This document discusses files and exception handling in Python. It begins by defining files and describing different types of files like data, text, and program files. It then covers topics like sequential and random file access, opening and closing files, reading and writing to files, and using file dialogs. The document also discusses retrieving data from the web using functions like urlopen. Finally, it defines exceptions and different types of errors like syntax, runtime, and logical errors. It explains how to handle exceptions in Python using try/except blocks and predefined or user-defined exceptions.
This document outlines the objectives and units of study for the course GE3151 Problem Solving and Python Programming. The course aims to teach algorithmic problem solving using Python conditionals, loops, functions, and data structures like lists, tuples and dictionaries. Students will learn to do input/output with files in Python. The 5 units cover computational thinking and problem solving, Python data types and statements, control flow and functions, lists, tuples and dictionaries, and files, modules and packages. Key concepts covered include algorithms, conditionals, iteration, functions, strings, lists, files operations like reading, writing and closing files, and exception handling.
This lecture covers files and exception handling in Python. It discusses opening, reading from, and writing to files. The key steps are opening the file, using it (reading or writing data), and closing it. Exceptions allow programs to handle and respond to errors and unexpected situations gracefully using try/except blocks. The case study demonstrates generating math tests randomly and writing the output to a file rather than displaying it on screen. This improves the program by storing the results for later use.
This document provides information about file handling in C++. It discusses key concepts like input/output streams, opening and closing files, and different file types. Specifically, it covers:
- The different stream classes like fstream, ifstream, and ofstream that are used for file input/output.
- Opening and closing files using functions like open() and close(), and specifying open modes like ios::out.
- The two main types of files - text files that use character translations and binary files that store raw bytes.
- Basic file operations in C++ like reading, writing, and manipulating files using functions like read(), write(), seekp() etc.
- Examples of opening
This document provides instructions for writing Perl scripts. It discusses four mandatory lines that must be included in every Perl script, useful modules for files and options, documentation methods, and an exercise for calculating assembly statistics from a file. The four mandatory lines are the shebang line, and lines to use warnings, use strict, and end the script. Useful file modules include File::Basename and File::Spec, while GetOpt::Std handles command line options. Documentation can be included through comments, perldoc, or print statements. The exercise involves calculating metrics like total base pairs, longest/shortest sequences, N50, and related values.
This document provides an overview of the key components of Django, including designing models, installing Django, accessing the model API, creating an admin interface, designing URLs and views, writing templates, and more. It explains these concepts at a high level and provides examples to illustrate how each component works and fits together. The goal is to help new users understand the basics of how to build a database-driven web application with Django.
Introduction to PHP: Declaring variables, data types, arrays, strings, operators, expressions, control structures, functions, Reading data from web form controls like text boxes, radio buttons, lists etc., Handling File Uploads, Connecting to database (MySQL as reference), executing simple queries, handling results, Handling sessions and cookies File Handling in PHP: File operations like opening, closing, reading, writing, appending, deleting etc. on text and binary files, listing directories
This document provides an overview of key Python concepts:
1. Modules allow organizing Python code into files and namespaces. The file name is the module name with a .py extension.
2. Python code is compiled into bytecode cache files (.pyc) for improved performance. These files are platform independent.
3. Advanced optimizations can be applied to bytecode with command line flags, but may affect program functionality in rare cases.
4. Standard modules provide useful functions like dir() to inspect modules and packages for organizing code. Input/output, strings, files and exceptions are also covered.
COURSE TITLE: SOFTWARE DEVELOPMENT VI
COURSE CODE: VIT 351
TOPICS COVERED:
FILES
FILES I/O STREAM
TYPES OF FILES
DRAWBACKS OF TRADITIONAL METHOD OF DATA STORAGE
CONCEPT OF BUFFER
MODES OF FILE OPENING
END OF FILE
PROCESSORS DIRECTIVES
MACROS
TYPES OF MACROS
DIFFERENCE BETWEEN MACROS AND FUNCTIONS
QUIZ SET 5
This document provides an introduction to the Python programming language. It begins with an agenda that covers running Python, Python programming concepts like data types and control flows, and hands-on exercises. It then discusses running Python interactively and as programs, Python syntax and basic data types like numbers, strings, lists, dictionaries, and tuples. The document is intended to help users understand the basic structure of Python and write simple Python scripts.
** Python Certification Training: https://www.edureka.co/python **
This Edureka PPT on File Handling with Python covers all the important aspects of using files in Python right from the introduction to what fields are, all the way till checking out the major aspects of working with files and using the code-first approach to understand them better.
Python Tutorial Playlist: https://goo.gl/WsBpKe
Blog Series: http://bit.ly/2sqmP4s
Follow us to never miss an update in the future.
Instagram: https://www.instagram.com/edureka_learning/
Facebook: https://www.facebook.com/edurekaIN/
Twitter: https://twitter.com/edurekain
LinkedIn: https://www.linkedin.com/company/edureka
Python and Oracle : allies for best of data managementLaurent Leturgez
In this presentation, I described Python and how Python can Interact with Oracle database, and Oracle Cloud Infrastructure in various project : from data visualisation to data science.
The document discusses various PHP functions for manipulating files including:
- readfile() which reads a file and writes it to the output buffer
- fopen() which opens files and gives more options than readfile()
- fread() which reads from an open file
- fclose() which closes an open file
- fgets() which reads a single line from a file
- feof() which checks if the end-of-file has been reached
It also discusses sanitizing user input before passing it to execution functions to prevent malicious commands from being run.
The 30 hour Python training program covers the fundamentals of Python including installation, variables, functions, control flow statements, data structures, modules, file input/output, regular expressions, object-oriented programming concepts like classes and inheritance, integrating Python with other languages like C/C++, exception handling, debugging, and unittest frameworks. Hands-on exercises are included to practice working with lists, tuples, dictionaries, sets, file operations, regular expressions, classes, objects, inheritance and unit testing.
An image editing software developed and manufactured by Adobe Systems Inc. Photoshop is considered one of the leaders in photo editing software. The software allows users to manipulate, crop, resize, and correct color on digital photos.
Python covers how to create scripts that manipulate data, automate tasks, perform error handling and store and retrieve data by using relational databases and XML files
Python is an interpreted, object-oriented programming language similar to PERL, that has gained popularity because of its clear syntax and readability. ... Python was created by Guido van Rossum, a former resident of the Netherlands, whose favorite comedy group at the time was Monty Python's Flying Circus.
Python is a language with a simple syntax, and a powerful set of libraries. It is an interpreted language, with a rich programming environment, including a robust debugger and profiler. ... This course is an introduction to the Python programming language for students without prior programming experience.
File handling in Python allows programs to work with files stored on disk by performing operations like opening, reading, writing, and modifying files. The open() function is used to open a file and return a file object, which can then be used to read or write to the file. There are different file access modes like 'r' for read-only, 'w' for write-only, and 'a' for append. Common methods for reading files include read() to read characters, readline() to read one line, and readlines() to read all lines into a list. Files can be written to using write() and writelines() methods and deleted using functions in the os, shutil, or pathlib modules.
This document discusses file handling in Python. It begins by explaining that files allow permanent storage of data, unlike standard input/output which is volatile. It then covers opening files in different modes, reading files line-by-line or as a whole, and modifying the file pointer position using seek(). Key points include opening files returns a file object, reading can be done line-by-line with for loops or using read()/readlines(), and seek() allows changing the file pointer location.
This file contains the first steps any beginner can take as he/she starts a journey into the rich and beautiful world of Python programming. From basics such as variables to data types and recursions, this document touches briefly on these concepts. It is not, by any means, an exhaustive guide to learn Python, but it serves as a good starting point and motivation.
The document discusses files in Python. It describes that files allow storing data permanently on disk that can be accessed by Python programs. There are two main types of files - text files, which store data as characters, and binary files, which store data in the same format as memory. The document outlines various methods for opening, reading, writing, and closing files in Python. It also discusses file paths and different file access modes.
Files in Python can be used to read data from disk files into a Python program and write data from a Python program back to disk files. There are two main types of files: text files, which store data as characters, and binary files, which store data in the same format as memory. Common file operations in Python include opening, reading, writing, and closing files. The open() function is used to open a file and return a file object, and the close() method closes the file and releases it for other applications. The with statement provides a convenient way to ensure files are closed after use.
This document discusses C language files input/output (I/O), the preprocessor, and conditional compilation. It covers:
- Types of files for I/O: text and binary files. Text files store plain text while binary files store data in 0s and 1s.
- File operations in C: creating, opening, closing files and reading/writing data. Functions like fopen(), fclose(), fprintf(), fscanf(), fread(), fwrite() are used.
- The preprocessor allows inclusion of header files and definition of macros to transform code before compilation. Directives like #include, #define are used.
- Conditional compilation allows certain code blocks to be included or excluded
Python Programming - XII. File ProcessingRanel Padon
The document discusses file handling and processing in Python. It covers opening and closing files, different file open modes like read, write and append, parsing files, buffering, and random access files. Common file operations like reading, writing, splitting and stripping file contents are demonstrated. The document also provides examples of parsing HTML and CSV files, using files with classes, and serializing objects for efficient storage and transfer.
1) The document discusses file handling in C++ using fstream. Files allow storing data permanently unlike cin and cout streams.
2) Files can be opened using constructor functions or member functions like open(). open() allows specifying the file mode like read/write.
3) Reading and writing to files can be done using extraction/insertion operators, get()/put(), or read()/write() functions depending on data types. Member functions help check file status and position.
This document provides an overview of file handling in Python. It discusses different file types like text files, binary files, and CSV files. It explains how to open, read, write, close, and delete files using functions like open(), read(), write(), close(), and os.remove(). It also covers reading and writing specific parts of a file using readline(), readlines(), seek(), and tell(). The document demonstrates how to handle binary files using pickle for serialization and deserialization. Finally, it shows how the os module can be used for file operations and how the csv module facilitates reading and writing CSV files.
This document outlines a 4-day Python programming class covering basic Python, advanced Python, web scraping with Python, and building a web application with Python. On the fourth day, students will learn about CRUD operations, databases, and the ORM pattern. They will also learn to build an HTTP server, develop web applications with the Flask framework, access GPIO pins on the Raspberry Pi, and control an LCD display on the Raspberry Pi. As a final project, students will build a simple control center web application for the Raspberry Pi that accesses I/O using Flask and Python.
This document provides information about accessing and parsing web data using Python and BeautifulSoup. It discusses setting up a development environment on a Raspberry Pi with Python, Flask, and BeautifulSoup installed. It covers retrieving HTML data using urllib and parsing it using BeautifulSoup to extract tags and attributes. Common issues like HTTP errors and missing tags are addressed. Exercises demonstrate getting title data from a URL and extracting tags by class attribute.
COURSE TITLE: SOFTWARE DEVELOPMENT VI
COURSE CODE: VIT 351
TOPICS COVERED:
FILES
FILES I/O STREAM
TYPES OF FILES
DRAWBACKS OF TRADITIONAL METHOD OF DATA STORAGE
CONCEPT OF BUFFER
MODES OF FILE OPENING
END OF FILE
PROCESSORS DIRECTIVES
MACROS
TYPES OF MACROS
DIFFERENCE BETWEEN MACROS AND FUNCTIONS
QUIZ SET 5
This document provides an introduction to the Python programming language. It begins with an agenda that covers running Python, Python programming concepts like data types and control flows, and hands-on exercises. It then discusses running Python interactively and as programs, Python syntax and basic data types like numbers, strings, lists, dictionaries, and tuples. The document is intended to help users understand the basic structure of Python and write simple Python scripts.
** Python Certification Training: https://www.edureka.co/python **
This Edureka PPT on File Handling with Python covers all the important aspects of using files in Python right from the introduction to what fields are, all the way till checking out the major aspects of working with files and using the code-first approach to understand them better.
Python Tutorial Playlist: https://goo.gl/WsBpKe
Blog Series: http://bit.ly/2sqmP4s
Follow us to never miss an update in the future.
Instagram: https://www.instagram.com/edureka_learning/
Facebook: https://www.facebook.com/edurekaIN/
Twitter: https://twitter.com/edurekain
LinkedIn: https://www.linkedin.com/company/edureka
Python and Oracle : allies for best of data managementLaurent Leturgez
In this presentation, I described Python and how Python can Interact with Oracle database, and Oracle Cloud Infrastructure in various project : from data visualisation to data science.
The document discusses various PHP functions for manipulating files including:
- readfile() which reads a file and writes it to the output buffer
- fopen() which opens files and gives more options than readfile()
- fread() which reads from an open file
- fclose() which closes an open file
- fgets() which reads a single line from a file
- feof() which checks if the end-of-file has been reached
It also discusses sanitizing user input before passing it to execution functions to prevent malicious commands from being run.
The 30 hour Python training program covers the fundamentals of Python including installation, variables, functions, control flow statements, data structures, modules, file input/output, regular expressions, object-oriented programming concepts like classes and inheritance, integrating Python with other languages like C/C++, exception handling, debugging, and unittest frameworks. Hands-on exercises are included to practice working with lists, tuples, dictionaries, sets, file operations, regular expressions, classes, objects, inheritance and unit testing.
An image editing software developed and manufactured by Adobe Systems Inc. Photoshop is considered one of the leaders in photo editing software. The software allows users to manipulate, crop, resize, and correct color on digital photos.
Python covers how to create scripts that manipulate data, automate tasks, perform error handling and store and retrieve data by using relational databases and XML files
Python is an interpreted, object-oriented programming language similar to PERL, that has gained popularity because of its clear syntax and readability. ... Python was created by Guido van Rossum, a former resident of the Netherlands, whose favorite comedy group at the time was Monty Python's Flying Circus.
Python is a language with a simple syntax, and a powerful set of libraries. It is an interpreted language, with a rich programming environment, including a robust debugger and profiler. ... This course is an introduction to the Python programming language for students without prior programming experience.
File handling in Python allows programs to work with files stored on disk by performing operations like opening, reading, writing, and modifying files. The open() function is used to open a file and return a file object, which can then be used to read or write to the file. There are different file access modes like 'r' for read-only, 'w' for write-only, and 'a' for append. Common methods for reading files include read() to read characters, readline() to read one line, and readlines() to read all lines into a list. Files can be written to using write() and writelines() methods and deleted using functions in the os, shutil, or pathlib modules.
This document discusses file handling in Python. It begins by explaining that files allow permanent storage of data, unlike standard input/output which is volatile. It then covers opening files in different modes, reading files line-by-line or as a whole, and modifying the file pointer position using seek(). Key points include opening files returns a file object, reading can be done line-by-line with for loops or using read()/readlines(), and seek() allows changing the file pointer location.
This file contains the first steps any beginner can take as he/she starts a journey into the rich and beautiful world of Python programming. From basics such as variables to data types and recursions, this document touches briefly on these concepts. It is not, by any means, an exhaustive guide to learn Python, but it serves as a good starting point and motivation.
The document discusses files in Python. It describes that files allow storing data permanently on disk that can be accessed by Python programs. There are two main types of files - text files, which store data as characters, and binary files, which store data in the same format as memory. The document outlines various methods for opening, reading, writing, and closing files in Python. It also discusses file paths and different file access modes.
Files in Python can be used to read data from disk files into a Python program and write data from a Python program back to disk files. There are two main types of files: text files, which store data as characters, and binary files, which store data in the same format as memory. Common file operations in Python include opening, reading, writing, and closing files. The open() function is used to open a file and return a file object, and the close() method closes the file and releases it for other applications. The with statement provides a convenient way to ensure files are closed after use.
This document discusses C language files input/output (I/O), the preprocessor, and conditional compilation. It covers:
- Types of files for I/O: text and binary files. Text files store plain text while binary files store data in 0s and 1s.
- File operations in C: creating, opening, closing files and reading/writing data. Functions like fopen(), fclose(), fprintf(), fscanf(), fread(), fwrite() are used.
- The preprocessor allows inclusion of header files and definition of macros to transform code before compilation. Directives like #include, #define are used.
- Conditional compilation allows certain code blocks to be included or excluded
Python Programming - XII. File ProcessingRanel Padon
The document discusses file handling and processing in Python. It covers opening and closing files, different file open modes like read, write and append, parsing files, buffering, and random access files. Common file operations like reading, writing, splitting and stripping file contents are demonstrated. The document also provides examples of parsing HTML and CSV files, using files with classes, and serializing objects for efficient storage and transfer.
1) The document discusses file handling in C++ using fstream. Files allow storing data permanently unlike cin and cout streams.
2) Files can be opened using constructor functions or member functions like open(). open() allows specifying the file mode like read/write.
3) Reading and writing to files can be done using extraction/insertion operators, get()/put(), or read()/write() functions depending on data types. Member functions help check file status and position.
This document provides an overview of file handling in Python. It discusses different file types like text files, binary files, and CSV files. It explains how to open, read, write, close, and delete files using functions like open(), read(), write(), close(), and os.remove(). It also covers reading and writing specific parts of a file using readline(), readlines(), seek(), and tell(). The document demonstrates how to handle binary files using pickle for serialization and deserialization. Finally, it shows how the os module can be used for file operations and how the csv module facilitates reading and writing CSV files.
This document outlines a 4-day Python programming class covering basic Python, advanced Python, web scraping with Python, and building a web application with Python. On the fourth day, students will learn about CRUD operations, databases, and the ORM pattern. They will also learn to build an HTTP server, develop web applications with the Flask framework, access GPIO pins on the Raspberry Pi, and control an LCD display on the Raspberry Pi. As a final project, students will build a simple control center web application for the Raspberry Pi that accesses I/O using Flask and Python.
This document provides information about accessing and parsing web data using Python and BeautifulSoup. It discusses setting up a development environment on a Raspberry Pi with Python, Flask, and BeautifulSoup installed. It covers retrieving HTML data using urllib and parsing it using BeautifulSoup to extract tags and attributes. Common issues like HTTP errors and missing tags are addressed. Exercises demonstrate getting title data from a URL and extracting tags by class attribute.
This document outlines a 4-day Python Programming class taught by Paul Yang in 2016. The agenda covers basic Python on day 1, advanced Python on day 2, web scraping with Python on day 3, and web application development with Python on day 4. Day 1 of the class focuses on introducing Python, setting up the development environment, and covering basic Python concepts like data types, control flow, functions, and I/O. The class is intended to help students understand the history and features of Python, install Anaconda for package management, and get familiar with common data types, functions, and programming constructs in Python.
The document provides an agenda for a hands-on training on RHEL5 Xen virtualization technology. It discusses key concepts of virtualization including types of Xen virtualization, performance, and supporting status in RHEL5. Labs cover installing guest systems via paravirtualization and full virtualization, configuring networks, and known issues workarounds. The training aims to introduce virtualization technology, the RHEL5 implementation, and provide hands-on experience through guided labs.
This document provides an overview and instructions for validating the Intel AT-d platform on Intel vPro systems. It describes the hardware and firmware prerequisites, how to enable AT-d in the BIOS and Management Engine, and how to perform validation tests. The validation process includes checking AT-d hardware and software straps, enabling AT-d, and verifying BIOS compliance. It also outlines the steps for assigning an administrator, managing users, and configuring devices for encryption with AT-d.
HP Performance Tracking is a set of tools used by HP to measure the performance of PCs against HP set limits. The tools are based on the Microsoft Windows Assessment Kit and concentrate on power up/down measurements. HP Performance Tracking includes a customized HP client, a SharePoint site for uploading results, a SQL database to store results, and a viewer to view and analyze the results. The client collects additional HP-specific data and measures performance against HP limits to identify failures. Results are uploaded to SharePoint and transferred nightly to the SQL database for analysis in the viewer.
The custom HP Perftrack client allows HP to:
- Include custom color coded HP performance limits to control when a service incident should be written.
- Zip up results for consistent reporting instead of screen captures, and capture additional system information.
- Add additional tests beyond what the Microsoft Assessment Kit includes, such as first logon command time.
- HP Perftrack uses the same underlying tests as the ADK but with a smaller footprint and customized tests and limits.
The document provides instructions for analyzing performance issues using the Windows Assessment and Deployment Kit (ADK). It outlines the process for setting up and running ADK tests, managing results, and debugging issues. Key steps include installing the Windows Assessment Console (WAC) to view XML results files and launch the Windows Performance Analyzer (WPA) to analyze detail trace files to identify causes of performance problems like prolonged fast boot shutdown times.
A Special-Purpose Peer-to-Peer File Sharing System for Mobile ad Hoc Networks...Paul Yang
1) The document describes ORION, a peer-to-peer file sharing system designed for mobile ad hoc networks. ORION uses an overlay network constructed on-demand to efficiently route search queries and file transfers.
2) ORION maintains routing tables to track responses to queries and paths for file transfers. It uses link layer feedback to detect and route around failures during transfers.
3) Simulation results show ORION significantly outperforms off-the-shelf P2P systems in search accuracy and reliability of file transfers in mobile ad hoc networks.
A brief study on bottlenecks to Intel vs. Acer v0.1.pdfPaul Yang
This document discusses potential bottlenecks in the relationship between Intel and Acer from both companies' perspectives. It outlines identifying problems, determining causes, potential options for mitigating issues, verifying effectiveness of options, and developing an action plan. Specifically, it examines messy distribution channels, endless price bargaining, and declining support from Intel partners. More data is needed to fully understand organizational changes, strategies, requirements, and value propositions from both sides.
This document discusses opportunities for Arm in data center and edge computing infrastructure. It outlines Arm's growing footprint in servers through partners like AWS, Ampere, Marvell, and provides an overview of the Neoverse roadmap. It also discusses how Arm can address markets like smartNICs and uCPE through integrated solutions with better performance and cost than x86.
Building PoC ready ODM Platforms with Arm SystemReady v5.2.pdfPaul Yang
The purpose of this technical talk with the demo is to show ODMs, OEMs, and ISVs how to leverage SystemReady Lab, showcase the use-case based on the virtualization platform for the edge, and deploy open-source tools that set up ODMs to develop their Arm platforms.
Mitigating routing misbehavior in mobile ad hoc networks Paul Yang
Mitigating Routing Misbehavior in Mobile Ad Hoc Networks”, Sergio Marti,T.J. Giuli, Kevin Lai, and Mary Baker,MobiCom 2000
Introduces two techniques that improve throughput in an ad hoc network in the presence of “misbehaving” nodes.
Towards Routing Security, Fairness, and Robustness in Mobile Ad Hoc Networks
From Birds to Network Nodes
Components in Each Node
Information Flow in Each Node
Information Flow Between Nodes
Routing Security and Authentication Mechanism for Mobile Ad Hoc NetworksPaul Yang
The document proposes a two-tier authentication mechanism for routing security in mobile ad hoc networks (MANETs). The first tier, called cluster authentication, uses message authentication codes and hash functions to verify if a node belongs to the same group and prevent external attacks. The second tier, called individual authentication, applies secret sharing to authenticate the identity of specific nodes and prevent internal attacks. Together, the two-tier mechanism provides security against both external and internal threats with reasonable computational complexity and bandwidth usage for MANETs.
English teaching in icebreaker and grammar analysisPaul Yang
The document discusses grammar analysis and ice breaker series. It provides an overview of the ice breaker series which aims to help students practice spoken English through scenario-based conversations. It also compares the present simple tense and present perfect tense through examples and explanations of when to use each. The differences between the past simple tense, past progressive tense, and past perfect tense are also outlined through examples to help understand them logically rather than through memorization.
Blood finder application project report (1).pdfKamal Acharya
Blood Finder is an emergency time app where a user can search for the blood banks as
well as the registered blood donors around Mumbai. This application also provide an
opportunity for the user of this application to become a registered donor for this user have
to enroll for the donor request from the application itself. If the admin wish to make user
a registered donor, with some of the formalities with the organization it can be done.
Specialization of this application is that the user will not have to register on sign-in for
searching the blood banks and blood donors it can be just done by installing the
application to the mobile.
The purpose of making this application is to save the user’s time for searching blood of
needed blood group during the time of the emergency.
This is an android application developed in Java and XML with the connectivity of
SQLite database. This application will provide most of basic functionality required for an
emergency time application. All the details of Blood banks and Blood donors are stored
in the database i.e. SQLite.
This application allowed the user to get all the information regarding blood banks and
blood donors such as Name, Number, Address, Blood Group, rather than searching it on
the different websites and wasting the precious time. This application is effective and
user friendly.
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODELijaia
As digital technology becomes more deeply embedded in power systems, protecting the communication
networks of Smart Grids (SG) has emerged as a critical concern. Distributed Network Protocol 3 (DNP3)
represents a multi-tiered application layer protocol extensively utilized in Supervisory Control and Data
Acquisition (SCADA)-based smart grids to facilitate real-time data gathering and control functionalities.
Robust Intrusion Detection Systems (IDS) are necessary for early threat detection and mitigation because
of the interconnection of these networks, which makes them vulnerable to a variety of cyberattacks. To
solve this issue, this paper develops a hybrid Deep Learning (DL) model specifically designed for intrusion
detection in smart grids. The proposed approach is a combination of the Convolutional Neural Network
(CNN) and the Long-Short-Term Memory algorithms (LSTM). We employed a recent intrusion detection
dataset (DNP3), which focuses on unauthorized commands and Denial of Service (DoS) cyberattacks, to
train and test our model. The results of our experiments show that our CNN-LSTM method is much better
at finding smart grid intrusions than other deep learning algorithms used for classification. In addition,
our proposed approach improves accuracy, precision, recall, and F1 score, achieving a high detection
accuracy rate of 99.50%.
Road construction is not as easy as it seems to be, it includes various steps and it starts with its designing and
structure including the traffic volume consideration. Then base layer is done by bulldozers and levelers and after
base surface coating has to be done. For giving road a smooth surface with flexibility, Asphalt concrete is used.
Asphalt requires an aggregate sub base material layer, and then a base layer to be put into first place. Asphalt road
construction is formulated to support the heavy traffic load and climatic conditions. It is 100% recyclable and
saving non renewable natural resources.
With the advancement of technology, Asphalt technology gives assurance about the good drainage system and with
skid resistance it can be used where safety is necessary such as outsidethe schools.
The largest use of Asphalt is for making asphalt concrete for road surfaces. It is widely used in airports around the
world due to the sturdiness and ability to be repaired quickly, it is widely used for runways dedicated to aircraft
landing and taking off. Asphalt is normally stored and transported at 150’C or 300’F temperature
Applications of artificial Intelligence in Mechanical Engineering.pdfAtif Razi
Historically, mechanical engineering has relied heavily on human expertise and empirical methods to solve complex problems. With the introduction of computer-aided design (CAD) and finite element analysis (FEA), the field took its first steps towards digitization. These tools allowed engineers to simulate and analyze mechanical systems with greater accuracy and efficiency. However, the sheer volume of data generated by modern engineering systems and the increasing complexity of these systems have necessitated more advanced analytical tools, paving the way for AI.
AI offers the capability to process vast amounts of data, identify patterns, and make predictions with a level of speed and accuracy unattainable by traditional methods. This has profound implications for mechanical engineering, enabling more efficient design processes, predictive maintenance strategies, and optimized manufacturing operations. AI-driven tools can learn from historical data, adapt to new information, and continuously improve their performance, making them invaluable in tackling the multifaceted challenges of modern mechanical engineering.
Build the Next Generation of Apps with the Einstein 1 Platform.
Rejoignez Philippe Ozil pour une session de workshops qui vous guidera à travers les détails de la plateforme Einstein 1, l'importance des données pour la création d'applications d'intelligence artificielle et les différents outils et technologies que Salesforce propose pour vous apporter tous les bénéfices de l'IA.
Determination of Equivalent Circuit parameters and performance characteristic...pvpriya2
Includes the testing of induction motor to draw the circle diagram of induction motor with step wise procedure and calculation for the same. Also explains the working and application of Induction generator
Generative AI Use cases applications solutions and implementation.pdfmahaffeycheryld
Generative AI solutions encompass a range of capabilities from content creation to complex problem-solving across industries. Implementing generative AI involves identifying specific business needs, developing tailored AI models using techniques like GANs and VAEs, and integrating these models into existing workflows. Data quality and continuous model refinement are crucial for effective implementation. Businesses must also consider ethical implications and ensure transparency in AI decision-making. Generative AI's implementation aims to enhance efficiency, creativity, and innovation by leveraging autonomous generation and sophisticated learning algorithms to meet diverse business challenges.
https://www.leewayhertz.com/generative-ai-use-cases-and-applications/
14. Exercise 7 – a fix
14
• assign “1” to the arg of split() - maxsplit
data = open("dialogue_chinese.txt", encoding="utf-8")
for line in data:
(role,line_spoken) = line.split(":",maxsplit=1)
print(role,end="")
print("說: ", end="")
print(line_spoken, end="")
17. Decisions to make
17
If not line.find(“:”) == -1
#dosomething
Print()
• Put extra control logic to check and correct split error
• Endless check if data format changes again
• too many flows cause code unreadable
19. Try/Except
try:
#do your operations here;
except ExceptionI:
#If there is ExceptionI, then execute this block.
except ExceptionII:
#If there is ExceptionII, then execute this block.
else:
#If there is no exception then execute this block.
finally:
#This would always be executed.
20. Exercise 8 - A fix by Try/Except
data = open("dialogue_chinese.txt", encoding="utf-8")
for line in data:
try:
(role,line_spoken) = line.split(":",maxsplit=1)
print(role,end="")
print("說: ", end="")
print(line_spoken, end="")
except:
pass
data.close()
Do nothing
21. Exercise 8 – another problem
def print_file():
filename = input("輸入要開啟的檔名:")
data = open(filename, encoding="utf-8")
for line in data:
try:
(role,line_spoken) = line.split(":",maxsplit=1)
print(role,end="")
print("說: ", end="")
print(line_spoken, end="")
except:
pass
data.close()
print_file()
輸入要開啟的檔名: diagoue.txt
What if file doesn’t exist – you put incorrect filename
22. Exercise 8 – one way to fix
import os
def print_file():
filename = input("輸入要開啟的檔名:")
if os.path.exists(filename):
data = open(filename, encoding="utf-8")
for line in data:
try:
(role,line_spoken) = line.split(":",maxsplit=1)
print(role,end="")
print("說: ", end="")
print(line_spoken, end="")
except:
pass
data.close()
else:
print("檔名不存在")
>>> print_file()
>>> 輸入要開啟的檔名: diagoue.txt
檔名不存在
• Extra check-logic version
23. Exercise 8 – one way to fix
def print_file():
filename = input("輸入要開啟的檔名:")
try:
data = open(filename, encoding="utf-8")
for line in data:
try:
(role,line_spoken) = line.split(":",maxsplit=1)
print(role,end="")
print("說: ", end="")
print(line_spoken, end="")
except:
pass
data.close()
except:
print("檔名不存在")
>>> print_file()
>>> 輸入要開啟的檔名: diagoue.txt
檔名不存在
• Try-except version
Less is better!!
Complexity creates more problem and
prevent you from making right thing
24. Exercise 8 – one way to fix
try:
(role,line_spoken) = line.split(":",maxsplit=1)
print(role,end="")
print("說: ", end="")
print(line_spoken, end="")
except:
pass
• Be specific for the exception you gonna catch
This bypass all runtime error. you
may not notice other bugs and don’t
know how to handle afterward
filename = input("輸入要開啟的檔名:")
try:
data = open(filename, encoding="utf-8")
for line in data:
try:
(role,line_spoken) = line.split(":",maxsplit=1)
print(role,end="")
print("說: ", end="")
print(line_spoken, end="")
except ValueError:
pass
data.close()
except IOError as err:
print(err)
26. Full handling clause
• Try / Finally / else clauses
try:
fh = open("testfile", "w")
fh.write("This is my test file for exception handling!!")
finally:
print("Error: can't find file or read data")
try:
fh = open("testfile.txt", "w")
fh.write("This is my test file for exception handling!!")
except IOError as e:
print("Error: can't find file or write data")
print(e)
else:
print ("Written content in the file successfully")
29. Raising an Exception
• User defined exception - MyAppLookUpError
class MyAppLookupError(LookupError):
'''raise this when there's a lookup error for my app'''
def password_check(passwd):
if len(passwd) < 1:
raise MyAppLookupError("MyAppPasswordFormatError: length is
{}".format(len(passwd)))
if passwd.find('*') != -1:
raise MyAppLookupError("MyAppPasswordFormatError: contains *")
password = ""
try:
password_check(password)
except Exception as e:
print(e)
Inherit from baseclass : BaseException
34. • The function only executes on next() or forloop
• A generator is a one-time operation,
Generator function
>>> a = countdown(3)
>>> next(a)
Counting down from 3
3
>>> next(a)
2
>>> next(a)
2
>>> next(a)
1
>>> next(a)
One-time, exception
once it’s consumed
36. def firstn_list(n):
num, nums = 0, []
while num <= n:
nums.append(num)
num += 1
return nums
>>> sequnce_nums = firstn_list(10000)#10**5
>>> sum(sequnce_nums)
49995000
By normal function
• Let’s create a list and sum each up
• [0,1,2,3,4,………………,10000]
Here nums contains 10000
num variable in the memory
0
0 1 2
1
..
2 …
9999
10000
nums[]
Run
37. def firstn_generator(n):
num = 0
while num < n:
yield num
num += 1
>>>sequnce_nums = firstn_generator(10000)#10**5
>>>sum(sequnce_nums)
49995000
By generators function
1 2 … 10000
Run
1st
Run
2nd
Run
..th
Run
10000
num num num num
49. list-processing features
S = ['IBM',50,91.10]
s.append(x) # Append x to end of s
s.extend(t) # Add items in t to end of s
s.count(x) # Count occurences of x in s
s.index(x) # Return index of x in s
s.insert(i,x) # Insert x at index i
s.remove(x) # Remove first occurence of x
s.reverse() # Reverses items in list
s.sort() # Sort items in s in-place
• Python has a lot of list-processing features
50. list-processing features
x = [1, 2, -3, 4, -5]
a = []
for i in x:
if i > 0:
a.append(2*i)
• If we want to create a new list in which each element is
doubled in the old list when old value is not negative
• One way use forloop iterate
5 lines of code
51. List Comprehensions
• General syntax
[expression for x in s if condition]
• What it means
result = []
for x in s:
if condition:
result.append(expression)
• Can be used anywhere a sequence is expected
>>> a = [1,2,3,4]
>>> sum([x*x for x in a])
30
52. List Comprehensions
>>> x = [1, 2, -3, 4, -5]
>>> a = [i*2 for i in x if i > 0]
>>> b
[2,8,4,20]
• Same case by list comprehension
2 lines of code
53. List Comprehensions
• ASCII and str interchange between map
>>> ord('s')
115
>>> res = []
>>> for x in 'spam':
res.append(ord(x))
>>> res
[115, 112, 97, 109]
Content: http://www.ascii-code.com/
>>> res = list(map(ord, 'spam'))
>>> res
[115, 112, 97, 109]
>>> res = [ord(x) for x in 'spam']
>>> res
[115, 112, 97, 109]
Stand list
processing
Use map() to
combine ord()
Use map() to
combine ord()
54. List Comprehensions
• nested loop: we want to add each element from a ,b
a, b = [0, 1, 2] , [100,200,300]
>>> res = []
>>> for x in a:
for y in b:
res.append(x+y)
>>> res
[100, 200, 300, 101, 201, 301, 102, 202, 302]
>>>[x+y for x in a for y in b]
>>> res
[100, 200, 300, 101, 201, 301, 102, 202, 302]
Use 2 forloops
Finish on 1 line
56. Exercise 10 – transfer for to list comp (2)
>>>result = []
>>>for x in range(5):
if x % 2 == 0
for y in range(5):
if y % 2 == 1:
result.append((x,y))
• Intervene ‘even number’ with ‘odd number’ in one to five to
[(0,1),(0,3),(2,1)…..]
even
odd
57. Exercise 10– Answer(1)
>>> [x + y for x in 'spam' for y in 'SPAM']
['sS', 'sP', 'sA', 'sM', 'pS', 'pP', 'pA', 'pM',
'aS', 'aP', 'aA', 'aM', 'mS', 'mP', 'mA', 'mM']
Intervene ‘spam’ with ‘SPAM’ to
58. Exercise 10– Answer(2)
>>> [(x, y) for x in range(5) if x % 2 == 0 for y in range(5) if y % 2 == 1]
[(0, 1), (0, 3), (2, 1), (2, 3), (4, 1), (4, 3)]
Intervene even and odd number
65. Generator Expressions
>>> G = (x ** 2 for x in range(4))
>>> iter(G) is G # iter(G) optional: __iter__ returns self
True
>>> next(G) # Generator objects: automatic methods
0
>>> next(G)
1
>>> next(G)
4
>>> next(G)
9
>>> next(G)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
>>> G
<generator object <genexpr> at 0x00000000029A8318>
66. Exercise 11 – make Generator
wwwlog = open("access-log")
total = 0
for line in wwwlog:
bytestr = line.rsplit(None,1)[1]
if bytestr != '-':
total += int(bytestr)
print "Total", total
81.107.39.38 - ... "GET /ply/ply.html HTTP/1.1" 200 97238
81.107.39.38 - ... "GET /ply/ HTTP/1.1" 304 -
• Find out how many bytes of data were transferred
76. Functional programming
expr, result = "28+32+++32++39", 0
for t in expr.split("+"):
if t != "":
res += int(t)
print result
Imperative style = actions that change state from initial state to result
85. Functional tools - filter
filter()
• filter out all the elements of a list, for which the function returns True
• filter(func, SEQ)
filter(lambda x: x % 2, [0,1,2,3])
[1,3]
filter(lambda x: x % 2 == 0, [0,1,2,3])
[2,4]
f returns a Boolean value, i.e. either True or False
Leave it in list If x%2 is True - get odd num
Even num
Code credited http://www.python-course.eu/lambda.php
86. Functional tools - reduce
reduce()
• continually applies the function func() to the sequence seq. It returns a
single value
• reduce(func, SEQ)
>>>reduce(lambda x,y: x+y, [47,11,42,13])
113
Func(Func(Func(47,11),42),13)
Code credited http://www.python-course.eu/lambda.php
88. More Python FP
• Functools
• Itertools
• Generators
• Decorators
More on PYTHON FP:
https://newcircle.com/bookshelf/python_fundamentals_tutorial/functional_programming
http://thecodeship.com/patterns/guide-to-python-function-decorators/
Function decorators are simply wrappers to existing functions.
98. OS - Operating System Interface
98
>>> import os
>>> os.getcwd() # Return the current working directory
'C:Python35'
>>> os.chdir('/server/accesslogs') # Change current
working directory
>>> os.system('mkdir today') # Run the command mkdir in
the system shell 0
More on
https://docs.python.org/3/library/os.html#module-os
99. Sys - System-specific parameters and
functions
99
$python demo.py one two three
>>> import sys
>>> print(sys.argv)
['demo.py', 'one', 'two', 'three']
More on https://docs.python.org/3/library/os.html#module-os
argv[0]
Script name
argv[1:]
Arg1 - n
>>> import sys
>>> sys.version
‘3.6.5 (r265:79063, Apr 16 2016, 13:57:41) n[GCC 4.4.3]'
>>> sys.version_info
(3, 6, 5, 'final', 0)
Command Line Arguments
Information on the Python Interpreter
104. Regular expression (Regex)
104
• A regular expression is a special sequence of characters that
helps you match or find other strings or sets of strings, using a
specialized syntax held in a pattern.
• Regular expressions are widely used in UNIX world.
• Especially used for detecting word pattern
re.match(pattern, string, flags=0) #flag uses | (OR)
re.search(pattern, string, flags=0)
re.sub(pattern, repl, string, max=0)
match checks for a match only at the beginning of the string,
not quite useful compared with search
Search checks for a match anywhere in the
string
105. Regular expression (Regex)
105
>>> import re
>>> wordlist = ['hbasgoed', 'abhshooe', 'hbatisgoe', 'tbgoe', 'tbortgoe','abaisoed',
'abandoned', 'abased', 'abashed', 'abatised', 'abed', 'aborted','abaisogoe',
'abandongoe']
>>> [w for w in wordlist if re.search('ed$',w)]
['abaissed', 'abandoned', 'abased', 'abashed', 'abatised', 'abed', 'aborted']
• Detecting word pattern
Let's find words ending with ed using the regular expression
Let's find puzzle crossword for 8 letters with ‘a’ as its third letter and ‘y’ as sixth
>>> [w for w in wordlist if re.search('^..a..o..$',w)]
['hbasgoed', 'abaisoed']
. wildcard symbol match any single character
^ match beginning of line.
$ Matches end of line.
106. Regular expression (Regex)
106
>>> wordlist = ['abjectly', 'adjuster', 'gold','golder','dejected', 'golf', 'dejectly',
'injector', 'majestic','hold', 'hole']
>>> [w for w in wordlist if re.search('^[ghi][mno][jlk][def]$',w)]
['gold', 'golf', 'hold', 'hole']
>>> [w for w in wordlist if re.search('^[ghi][mno][jlk][def]',w)]
['gold', 'golder', 'golf', 'injector', 'hold', 'hole']
Ranges and Closures
Let’s find 4 letters word in which the first ranges from ‘g’,’h’ or ‘I’, the second ‘m’, ‘n’ or ‘o’
As 4653 in T9 system
the regular expression: ^[ghi][mno][jlk][def]$
Content credited http://www.nltk.org/images/T9.png
107. Regular expression (Regex)
107
>>> chat_words = ['miiinnee', 'mmmmmmmmiiiiiiiiinnnnnnnnneeeeeeee',
'mine','me','mingg','mi','ne' ]
>>> [w for w in chat_words if re.search('^m+i+n+e+$', w)]
['miiinnee', 'mmmmmmmmiiiiiiiiinnnnnnnnneeeeeeee', 'mine']
>>> [w for w in chat_words if re.search('^m*i*n*e*$', w)]
['miiinnee', 'mmmmmmmmiiiiiiiiinnnnnnnnneeeeeeee', 'mine', 'me', 'mi', 'ne']
Ranges and Closures
• + symbol means "one or more instances of the preceding item", which could be an
individual character like m, a set like [fed] or a range like [d-f]
• * symbol means "zero or more instances of the preceding item".
• The regular expression ^m*i*n*e*$ will match ^m+i+n+e+$
• e.g. me, min, and mmmmm.
108. Regular expression (Regex)
108
Ranges and Closures
: escape a control character
{n,m}: Matches n or more occurrences of preceding expression
(): Groups regular expressions
python|ruby: match “python” or “ruby”
digitlist = ['123','331-points', '0.0085', 'Adopting','C$','0.05','abv','2016'
'0.1', 'JAP#','92.2','911-ppppppp''43643', '1978', 'US$','1.1253553','bread-and-
butter','PO@','10-year','1.14', 'Advancing','1.1650', 'savings-and-loan','1.17',
'1.0','10-day','331-bigpoints', 'Absorbed']
>>> [w for w in digitlist if re.search('(ed|ing)$', w)]
['Adopting', 'Advancing', 'Absorbed']
>>> [w for w in digitlist if re.search('^[0-9]+.[0-9]+$', w)]
['0.0085', '0.05', '20160.1', '92.2', '1.1253553', '1.14', '1.1650', '1.17', '1.0']
>>> [w for w in digitlist if re.search('^[A-Z]+$$', w)]
['C$', 'US$']
>>> [w for w in digitlist if re.search('^[0-9]{4}$', w)]
['1978']
>>> [w for w in digitlist if re.search('^[0-9]+-[a-z]{3,5}$', w)]
['10-year', '10-day']
109. Regular expression (Regex)
109
>>> word1 = 'smartdog smatdog ldoedog ddwwlaj'
>>> re.findall('dog',word1)
['dog', 'dog', 'dog']
>>> word = 'supercalifragilisticexpialidocious'
>>> re.findall('[aeiou]', word)
['u', 'e', 'a', 'i', 'a', 'i', 'i', 'i', 'e', 'i', 'a', 'i', 'o', 'i', 'o',
'u']
Findall()
finds all (non-overlapping) matches of the given regular expression
126. Class
• Employee Class (a blueprint to employee data)
class Employee:
"""Common base class for all employees"""
empCount = 0
def __init__(self, name, salary):
self.name = name
self.salary = salary
Employee.empCount += 1
def displayCount(self):
print("Total Employee %d" % Employee.empCount)
def displayEmployee(self):
print("Name : ", self.name, ", Salary: ", self.salary)
Class Variable
Classname.var
Memebr variable
Different in each object
128. Class
• class-related BIFs
• dir(): show all supported methods and attributes
• help(): display class info
• Isinstance(x,y): check if x is the object of y
>>> dir(paul)
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__',
'__format__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__',
'displayCount', 'displayEmployee', 'empCount', 'name', 'salary']
>>> paul.__doc__
'Common base class for all employees'
>>> >>> help(paul)
Help on Employee in module __main__ object:
class Employee(builtins.object)
| Common base class for all employees
| Methods defined here:
| __init__(self, name, salary)
| Initialize self. See help(type(self)) for accurate signature.
| displayCount(self)
>>> >>> isinstance(paul,Employee)
True
130. __del__()
• Python interpreter invokes this func when the object is no longer
used – release memory
class Employee:
"""Common base class for all employees"""
empCount = 0
def __init__(self, name, salary):
self.name = name
self.salary = salary
Employee.empCount += 1
def __str__(self):
return str(self.name)
def __del__(self):
print("delcalled:"+ self.__str__())
>>> paul = Employee('Paul',10000)
>>> paul = "lol"
delcalled:Paul
133. Encapsulation
class Encapsulation(object):
def __init__(self, a, b, c):
self.public = a
self._protected = b
self.__private = c
>>> from encapsulation import Encapsulation
>>> x = Encapsulation(11,13,17)
>>> x.public
11
>>> x._protected
13
>>> x._protected = 23
>>> x._protected
23
>>> x.__private
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'Encapsulation' object has no attribute '__private'
Can be accessed inside/outside
Supposed to be retracted from
outside but python still allow
you to access
This changes virtually nothing
Can’t be accessed outsie
135. Exercise 13 – create your first class
• Enhance Employee class to support more operations:
• To support the below attributes:
• Instance attributes: name, grades, salary, position
• class attribute: managerCount , teacherCount, otherCount,
empCount
• To support the operations below:
• methods
• display_failure_count(): return sum of the failure class (the failure score is the subject
‘s score smaller than 60)
• add_grade(grade): to put class’s score like 100, 80 , 50
• Class Methods
• display_position_count(position)
• display_employee_count()
136. Exercise 13 – create your first class
paul = Employee('Paul',15000,"teacher")
jack = Employee('Jack',20000,"manager")
joy = Employee('Joy',15000,"writter")
mike = Employee('mike',20000,"teacher")
#add grade
paul.add_grade(100)
paul.add_grade(80)
paul.add_grade(90)
print("%s average grade:%d" % (paul.get_name(), paul.display_avg_grade()))
#add failure grade
paul.add_grade(40)
paul.add_grade(30)
paul.add_grade(58)
print("%s failed clount:%d" % (paul.get_name(), paul.display_failure_count()))
#check statistic by accessing class attribute by class methods
Employee.display_employee_count()
Employee.display_position_count("manager")
Employee.display_position_count("teacher")
Employee.display_position_count("other")
To test your employee class
139. Inheritance
• Implicit Inheritance:
• child will inherit all of its behavior from Parent.
class Parent(object):
def implicit(self):
print "PARENT implicit()"
class Child(Parent):
pass
>>> dad = Parent()
>>> son = Child()
>>> dad.implicit()
>>> son.implicit()
PARENT implicit()
PARENT implicit()
all subclasses (i.e., Child) will
automatically get those features
from base class (i.e., Parent)
141. Inheritance
• Alter
• overriding where you want to alter the behavior before or after the Parent class's
version runs.
class Parent(object):
def altered(self):
print "PARENT altered()"
class Child(Parent):
def altered(self):
print "CHILD, BEFORE PARENT altered()"
super(Child, self).altered()
print "CHILD, AFTER PARENT altered()"
>>> dad = Parent()
>>> son = Child()
>>> dad.altered()
>>> son.altered()
PARENT altered()
CHILD, BEFORE PARENT altered()
PARENT altered()
CHILD, AFTER PARENT altered()
use a Python built-in function
named super to get the Parent
version to call.
146. Polymorphism
a = "alfa"
b = (1, 2, 3, 4)
c = ['o', 'm', 'e', 'g', 'a']
>>>print(a[2])
>>>Print(b[1])
>>>Print(c[3])
f
2
g
Python uses polymorphism
extensively in built-in types. Here
we use the same indexing operator
for three different data types.
147. Polymorphism
class Bear(object):
def sound(self):
print "Groarrr"
class Dog(object):
def sound(self):
print "Woof woof!"
def makeSound(animalType):
animalType.sound()
bearObj = Bear()
dogObj = Dog()
makeSound(bearObj)
makeSound(dogObj)
Content credited: https://pythonspot.com/en/poylmorphism/
Polymorphism in Python with a function:
148. Polymorphism
class Animal:
def __init__(self, name=''):
self.name = name
def talk(self):# Abstract method, defined by convention only
raise NotImplementedError("Subclass must implement abstract method")
class Cat(Animal):
def talk(self):
print("Meow!")
class Dog(Animal):
def talk(self):
print("Woof!")
c = Cat("Missy")
c.talk()
d = Dog("Rocky")
d.talk()
Content credited: http://zetcode.com/lang/python/oop/
Polymorphism with abstract class
152. Generators Function
• The function only executes on next()
x = firstn_generator(10)
>>> x
<generator object at 0x58490>
>>>next(x)
0
>>>next(x)
1
Traceback (most recent call last):
File "<stdin>", line 1, in ?
StopIteration