<jupyter_start><jupyter_text>Learning Objectives

- [ ] *4.1.1 Explain the structure of the internet
- [ ] 4.2.1 Describe the differences between web applications and native applications 
- [ ] 4.2.2 State and apply usability principles in the design of web applications
- [ ] *4.2.3 Use HTML, CSS (for clients) and Python (for the server) to create a web application that is able to display the output (as formatted text/images/table). 
- [ ] 4.2.2 Test a web application on a local server.

 References

- https://developer.mozilla.org/en-US/docs/Learn/HTML/Introduction_to_HTML
- https://developer.mozilla.org/en-US/docs/Learn/CSS/Introduction_to_CSS
- Harvard's CS50 2020 https://www.youtube.com/watch?v=5g0x2xv3aHU&t=1758s
- ^4 http://web.stanford.edu/class/msande91si/www-spr04/readings/week1/InternetWhitepaper.htm
- https://www.w3schools.com/html/html_css.asp:~:text=CSS%20can%20be%20added%20to,to%20an%20external%20CSS%20file
- https://uxplanet.org/visual-hierarchy-and-the-fundamentals-of-interaction-320a9e633822
- https://www.programiz.com/python-programming/decorator
- https://realpython.com/primer-on-jinja-templating/  7 HTML  Chrome Developer Toolsipconfigtracert  7.0 InternetThe internet is the global system of interconnected computer networks that uses a specific, standardized procedure TCP/IP to communicate between networks and devices.^4 Protocol Stack 7.0.1 TCP/IP There are two procedures used for communication in the internet.1. Internet Protocol (IP) has the task of delivering units of data called **packets** from the source computer to the destination computer which are connected via the internet. To be able to do so, IP addresses, a numerical label, are assigned to each device connected to a computer network. An IP address serves two principal functions:     - it identifies the host, and     - it provides the location of the host in the network, and thus the capability of establishing a path to that host.  2. Transmission Control Protocol (TCP) provides a communication service at an intermediate level between an application program and the Internet Protocol. TCP is responsible for routing application protocols to the correct application on the destination computer. To accomplish this, port numbers are used. Ports can be thought of as seperate channels on each computer. For example, you can surf the web while reading e-mail in the middle of a Zoom call with Genshin Impact open in a window. This is because these these applications used different port numbers. When a packet arrives at a computer and makes its way up the protocol stack, the TCP layer decides which application receives the packet based on a port number. E.g., HTTP uses port 80, HTTPS uses 443, Genshin Impact is 42472. 7.0.2 World Wide WebThe World Wide Web (WWW), commonly known as the Web, is an information system where documents and other web resources are identified by Uniform Resource Locators (URLs, such as http://www.example.com/index.html), which may be interlinked by hyperlinks, and are accessible over the Internet. The resources of the Web are transferred via the Hypertext Transfer Protocol (HTTP), may be accessed by users by a software application called a **web browser**, and are published by a software application called a **web server**. The World Wide Web is not synonymous with the Internet. 7.0.3 Hyper Text Transfer ProtocolHypertext Transfer Protocol (HTTP) is an application-layer protocol for transmitting hypermedia documents, such as HTML. It was designed mainly for communication between web browsers and web servers. HTTP follows a classical client-server model, with a client opening a connection to make a request, then waiting until it receives a response.Domain names are human-readable addresses of an internet-connected computer. Whilst any internet-connected computer can be reached through a public IP address, IP addresses doesn't give a clear information about who's running the server or what service the website offers to a human user. Furthermore, IP addresses are hard to remember and might change over time.- `HTTP GET` method requests a representation of the specified resource. Requests using `GET` should only be used to request data (these requests shouldn't include data).- `HTTP POST` method sends data to the server. `POST` is designed to allow a uniform method to cover the following functions:        - Annotation of existing resources    - Posting a message to a bulletin board, newsgroup, mailing list, or similar group of articles;    - Adding a new user through a signup modal;    - Providing a block of data, such as the result of submitting a form, to a data-handling process;    - Extending a database through an append operation.The `index.html` is usually the default file returned when you open a website address.  7.1 Hyper Text Markup LanguageHTML (Hypertext Markup Language) is not a programming language. It is a **markup language** that tells web browsers how to structure the web pages you visit. HTML consists of a series of **elements**, which you use to enclose, wrap, or mark up different parts of content to make it appear or act in a certain way. The enclosing tags can make content into a hyperlink to connect to another page, italicize words, and so on.> Mark-up is a term from print editing - the editor would go through the text and add annotations (i.e. this in italic, that in bold) for the printers to use when producing the final version. This was called *marking up the text*.An **element** is a part of a webpage. An element may contain a data item or a chunk of text or an image, or perhaps nothing. A typical element includes an opening tag with some **attributes**, enclosed text content, and a closing tag.The anatomy of our element is:- The opening tag: This consists of the name of the element (in this example, `p` for paragraph), wrapped in opening `` brackets. This opening tag marks where the element begins or starts to take effect. - The content: This is the content of the element. - The closing tag: This is the same as the opening tag, except that it includes a forward slash `/` before the element name. This marks where the element ends. Failing to include a closing tag is a common beginner error that can produce peculiar results. Note that some elements only consist of a single tag, which is typically used to insert/embed something in the documentAn **attribute** extends an element, changing its behavior or providing metadata. Attributes contain extra information about the element that won't appear in the content.An attribute always has the form `name="value"` (the attribute's identifier `name` followed by its associated value `value`). The attributes without the equals sign or a value is a shorthand for providing the empty string in HTML.Elements and tags are not the same things. Tags begin or end an element in source code, whereas elements are part of the DOM (Document Object Model) that defines the logical structure of documents and the way a document is accessed and manipulated. Example of an HTML document<jupyter_code><!doctype html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Example HTML document</title>
    </head>
    <body>
        <p class="example">Hello,
            <a href="#">World</a>!. </p>
        <form action="http://127.0.0.1:12345/">
            <input id="button" type="submit">
        </form>
    </body>
</html><jupyter_output><empty_output><jupyter_text>You can try to see the displayed output on [http://www.codepen.io/pen]. Furthermore, if you open any webpage, you can check its html code by using the Developer Tools (`CTRL+SHIFT+I`) in Google Chrome.   7.1.1 Basic Structure of HTML documentHere we have:- ``: The doctype is a historical artifact that needs to be included for everything else to work right. It used to serve as links to a set of rules that the HTML page had to follow to be considered good HTML in the early days of HTML.- ``: The `` element. This element wraps all the content on the page. It is sometimes known as the root element.- ``: The `` element. This element acts as a container for everything you want to include on the HTML page, that isn't the content the page will show to viewers. This includes keywords and a page description that would appear in search results, CSS to style content, character set declarations, and more. - ``: This element specifies the character set for your document to UTF-8, which includes most characters from the vast majority of human written languages. With this setting, the page can now handle any textual content it might contain. There is no reason not to set this, and it can help avoid some problems later.- ``: The `` element. This sets the title of the page, which is the title that appears in the browser tab the page is loaded in. - ``: The `` element. This contains all the content that displays on the page, including text, images, videos, games, playable audio tracks, or whatever else.  7.1.2 Basic Formatting Elements of HTML document- `` element represents a paragraph.- `` `bold` element.- `` emphasis element. (italicizes the text)- &lt;a&gt; &lt;/a&gt;. The **anchor** element. An anchor can make the text it encloses into a hyperlink. Anchors can take a number of attributes, but several are as follows:    - `href`: This attribute's value specifies the web address for the link.     - `title`: The `title` attribute specifies extra information about the link, such as a description of the page that is being linked to.    - `target`: The `target` attribute specifies the browsing context used to display the link. For example, `target="_blank"` will display the link in a new tab.- `` element embeds an image into the document.- `,...,` represents six level of section headings with `` being the highest and `` the lowest.- special characters >| Character | `&`     | ``    | `"`      |>|-----------|-------|------|------|--------|>| Reference | `&amp;` | `&lt;` | `&gt;` | `&quot;` |- `` are used to wrap around the comments in HTML code. Browsers ignore comments, effectively making comments invisible to the user. - `` represents an **unordered list** of items, typically rendered as a bulleted list. Each item will be represented with an `` element.- `` represents an **ordered list** of items — typically rendered as a numbered list. Similar to the unordered list, each item will be represented with an `` element.- `` represents tabular data — that is, information presented in a two-dimensional table comprised of rows and columns of cells containing data. Inside the `table` element, there're subelements to be used as well.     - `` table header    - `` table body    - `` table row    - `` table cell.         Example of usage of ``        >```HTML    >    >      >    Month    >    Savings    >      >      >    January    >    $100    >      >      >    February    >    $80    >      >    ```Link to more HTML elements:- https://developer.mozilla.org/en-US/docs/Web/HTML/Element  7.1.3 The Navigation Section ElementThe HTML `` element represents a section of a page whose purpose is to provide navigation links, either within the current document or to other documents. Common examples of navigation sections are menus, tables of contents, and indexes.Check out https://developer.mozilla.org/en-US/docs/Web/HTML/Element/nav for more info. - https://www.clickandrent.fr/- https://www.spotify.com/us/- https://www.apple.com/sg/  7.2 Cascading Style SheetsCSS (Cascading Style Sheets) is a declarative language that controls how webpages look in the browser. A CSS rule-set consists of a selector and a declaration block. e.g:> h1 {color:blue; font-size:12px;}- `h1` in the example above is called a **selector** and it points to the HTML element you want to style.- the text enclosed within the `{...}` is called a **declaration block** and it contains one or more declarations separated by semicolons `;`.- each declaration includes a CSS property name and a value, separated by a colon `:`,- A CSS declaration always ends with a semicolon, and declaration blocks are surrounded by curly braces.In general, the rule-set is of the form:> SELECTOR {DECLARATION_1; DECLARATION_2;.....;DECLARATION_N} 7.2.1 CSS Properties for A-Level| Common     | Box Model     | Box Model      | Typography      ||------------|---------------|----------------|-----------------|| display    | height        | margin-left    | font-family     || background | width         | margin-right   | font-size       || color      | border        | margin-top     | font-style      ||            | border-bottom | padding        | font-weight     ||            | border-left   | padding-bottom | font-align      ||            | border-right  | padding-left   | text-decoration ||            | border-top    | padding-right  |                 ||            | margin        | padding-top    |                 ||            | margin-bottom |                |                 |For a complete reference of all the properties and values:  https://www.w3schools.com/cssref/default.aspNote: - A property (e.g., `border`) may have multiple values separated by whitespace- American language is used in CSS. (Eg `center` instead of `centre`, `color` instead of `colour`)- Units can be one of these:    - percentage e.g., `10%` of the parent container's width    - pixels, e.g., `100px`    - em e.g., `1em`, relative to the font size of parent's element.  CSS can be added to HTML documents in 3 ways:- Inline - by using the `style` attribute inside HTML elements- Internal - by using a `` element in the `` section- External - by using a `` element to link to an external CSS file    -    -    -<jupyter_code>#Example of Inline CSS
<h1 style="color:blue;">A Blue Heading</h1>
<p style="color:red;">A red paragraph.</p>
#Example of Internal CSS
<style>
    body {background-color: powderblue;}
    h1   {color: blue;}
    p    {color: red;}
</style>
#Example of External CSS<jupyter_output><empty_output><jupyter_text>Some commonly used CSS properties for your HTML elements include:- `color`- `font-family`- `font-size`- `border`- `padding`- `margin`CSS can be commented out by using `*/ SOME-CSS-HERE  */`.[https://fontjoy.com/][https://coolors.co/]  7.2.2 The `div` Element The HTML Content Division element (``) is the generic container for flow content. It has no effect on the content or layout until styled in some way using CSS (e.g. styling is directly applied to it, or some kind of layout model like Flexbox is applied to its parent element).As a "pure" container, the `` element does not inherently represent anything. Instead, it's used to group content so it can be easily styled using the `class` or `id` attributes, marking a section of a document as being written in a different language (using the `lang` attribute), and so on.Check out `https://developer.mozilla.org/en-US/docs/Web/HTML/Element/div` for more info.  7.2.3 `id` and `class` attributes of HTML elementsRecall that selector is a pattern of elements and other terms that tell the browser which HTML elements should be selected to have the CSS property values inside the rule applied to them. The element or elements which are selected by the selector are referred to as the subject of the selector.There are 3 classes of selector:- type e.g., `h1 {}`- `class` has the following syntax `.` followed `CLASS_NAME` e.g.,`.box{}`- `ID` selector has the syntax `` followed `` e.g., `unique{}`<jupyter_code>h1 {
    color:blue;
    background-color:yellow;
}

p{
    color:red;
}<jupyter_output><empty_output><jupyter_text>7.2.4 CSS Box ModelThe CSS box model is essentially a box that wraps around every HTML element. It consists of: - margins: the CSS margin properties are used to create space around elements, outside of any defined borders.- borders:  CSS border properties allow you to specify the style, width, and color of an element's border.- padding: CSS padding is used to create space around an element's content, inside of any defined borders.- the actual content.The image below illustrates the box model:Try out at: [https://codepen.io/beertino/pen/BapMXMw]  7.3 Usability Principles in Web Applications 7.3.1 Visual Hierarchy 7.3.2 Consistency (Mental Models) 7.3.3 Affordance 7.3.4 Responsiveness  7.4 Flexbox Layout Module

The Flexible Box (Flexbox) Layout Module, makes it easier to design flexible responsive layout structure without using float or positioning. To activate this, add `display: flex` inside the declaration of the selected HTML element.

Please check out the following links to see how you can use flexbox for your page.

- https://www.w3schools.com/css/css3_flexbox.asp
- https://css-tricks.com/snippets/css/a-guide-to-flexbox/  7.5 Web FormsA web form is used to get inputs from the user and submitted to be processed by the web application.Form elements in A level syllabus:| Elements | Attributes | Values                                                           ||----------|------------|------------------------------------------------------------------|| `` ``     | `action`     | URL to submit(identify the server)                               ||          | `method` (optional)    | `GET` or `POST`                                                      ||          | `enctype` (optional)    | Upload a file using `multiplart/form-data`                         || `` No Closing Tag    | `name`       | Similar to a variable name but different from `id`                 ||          | `type`       | text, submit, file ( radio, checkbox, date,... )                   ||          | `value`      | Values that will be submitted. Use for specifying default values || `` `` | `name`       | Multi-line textbox                                               || `` ``    | `for`        | `id` of the input elements that the label refers to                |- The `for` attribute of `` must be equal to the `id` attribute of the related element to bind them together.- `` element also increases the hit area of the form element.<jupyter_code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    
    <div>
    <h1> Text</h1>
    <form>
        <label for="fname">First name:</label><br>
        <input type="text" id="fname" name="fname"><br>
        <label for="lname">Last name:</label><br>
        <input type="text" id="lname" name="lname">
    </form>
    </div>
    
    <div>
    <h1>Radio</h1>
    <form>
        <input type="radio" id="male" name="gender" value="male">
        <label for="male">Male</label><br>
        <input type="radio" id="female" name="gender" value="female">
        <label for="female">Female</label><br>
        <input type="radio" id="other" name="gender" value="other">
        <label for="other">Other</label>
    </form>
    </div>
    <div>
    <h1>Checkbox</h1>
        <form action='/lmao'>
            <input type="checkbox" id="vehicle1" name="vehicle1" value="Bike">
            <label for="vehicle1"> I have a bike</label><br>
            <input type="checkbox" id="vehicle2" name="vehicle2" value="Car">
            <label for="vehicle2"> I have a car</label><br>
            <input type="checkbox" id="vehicle3" name="vehicle3" value="Boat">
            <label for="vehicle3"> I have a boat</label>
        </form>
    </div>
    <div>
        <h1>Submit</h1>
        <form action="/action_page.php">
            <label for="fname">First name:</label><br>
            <input type="text" id="fname" name="fname" value="John"><br>
            <label for="lname">Last name:</label><br>
            <input type="text" id="lname" name="lname" value="Doe"><br><br>
            <input type="submit" value="Submit">
        </form>
    </div>
    <div>
        <h1>File</h1>
        <form>
            <input type="file" id="myFile" name="filename">
            <input type="submit">
        </form>
    </div>
    <div>
        <h1>Button</h1>
        <form action="/action_page.php">
            <input type="file" id="myFile" name="filename">
            <button type='submit'>Add File</button>
        </form>
    </div>
</body>
</html><jupyter_output><empty_output><jupyter_text>7.6 Web Server  7.6.1 Software, Server and ApplicationsSoftware is the set of instructions that make the computer hardware usable. A server is a computer on a network that provides a resource to the other machines on the network. In particular, a **web server** accepts requests via HTTP, to distribute web pages. A **web browser** is a software that enables the access to the material requested from the web server. An application (software) is a set of instructions designed to make the computer do something for the user. If an application runs on a web server, such an application is termed **web application**. As such, web applications are accessed by the user through a web browser with an active network connection. In contrast, an application that runs locallly on the operating system of the device is called **native application**.A **web framework** is a software framework that is designed to support the development of web applications and it provide a standard way to build and deploy web applications. In other words, it is a code library that makes a developer's life easier when building reliable, scalable, and maintainable web applications.  7.6.2 FlaskFlask is a web framework written in Python. If you don't have it yet on your computer, please install by running in the terminal:>pip install flaskNote: Flask version for A-level is 0.12.2 when the current Flask version is 1.1.x.Basic code to run a Flask web server is given below:<jupyter_code>from flask import Flask #0 importing the flask module
#from flask import render_template

app = Flask(__name__) #1 creating the Flask object

@app.route('/') #2. decorator. the argument passed into the route method '/' denotes that it will respond web requests for the URL `/`
def hello():
    """Print 'Hello, world!' as the response body."""
    return 'Hello World!'
    #return "<h1 style='color: red;'>I'm a red H1 heading!</h1><p>This is a lovely little paragraph</p><code>Flask is <em>awesome</em></code>"
    
if __name__ == "__main__":
    app.run()<jupyter_output><empty_output><jupyter_text>- by default, the URL `http://127.0.0.1:5000/` is used to access the website. `127.0.0.1` is a reserved ip address to refer to the current computer used to access itself. `5000` is the default port number used by Flask. You can change the port number by providing `port=your_port_number` into the `app.run()` method.- change the argument in `route` method to specify the location of the resources you want to get. - remember to import `render_template` so that you can use the html as a template. Note that these template html files has to be stored in the `templates` folder if we're using Flask.- you can pass Python variables as an argument in `render_template()` function to be used for further templating (see Jinja below).- When a certain type of error is encountered in flask, we can use **error handler**, which is a function, to return a response. Some common errors are:    - `404 NOT FOUND`    - `403 FORBIDDEN`    - `410 GONE`    - `500 INTERNAL SERVER ERROR`<jupyter_code>@app.errorhandler(404)
def page_not_found(e):
    # note that we set the 404 status explicitly
    return render_template('404.html'), 404<jupyter_output><empty_output><jupyter_text>7.6.2.1 Request Form Elements

A query string is a part of a uniform resource locator (URL) that assigns values to specified parameters. This string can then be used by the web server to return a specific resource to the client. For example:

> https://duckduckgo.com/?q=mathematics+degree&t=hd&va=u&ia=web

Multiple query parameters are separated by the ampersand (&) symbol.

We pass the URL of the route we want to post the form data to in the `action` attribute of the `form` element. In our case `action="/"`.
You'll also need to pass the request method to the method attribute in the opening `` tag. We've added `method="POST"` because we're POSTing data to the server.

To access form data in our route, we use `request.form` object, which has the type `werkzeug.datastructures.ImmutableMultiDict`. However, effectively, we can essentially treat it like a dictionary.<jupyter_code>from flask import Flask, render_template, request
app = Flask(__name__)


@app.route("/")
def template_test():
    return render_template('template.html', my_string="Wheeeee!", my_list=[0,1,2,3,4,5])

@app.route('/notice',methods=['GET','POST'])
def notice_me():
    print(request.form)
    return render_template('notice.html',first=request.form['first_name'],last=request.form['last_name'])

if __name__ == '__main__':
    app.run(debug=True)<jupyter_output><empty_output><jupyter_text>7.7 Jinja Expressions

Jinja is a web template engine, which is a way to let web designers and developers work with web templates to automatically generate custom web pages, for the Python programming language. Example of use case is to generate a web page to display a result from a search. 

Jinja supports:
- basic arithmetic `(+,-,*,%,//,**)` and comparison operators `==,!=,=,>`.
- inserting of variables via `{{ VARIABLE_NAME }}`,
- control structures `for` and `if` using :
    - `{{% for %}}.......{{% endfor %}}`,
    - `{{% if %}}.......{{% endif %}}`.
- template inheritance via:
    - `{% extends NAME_OF_FILE.html%}` denotes that the html file (called **child html**) is to be inserted into another html file, called **parent html**.
    - `{% block SOME_NAME%}....{% endblock %}`, `SOME_NAME` is usually `content`, `footer`.<jupyter_code><!DOCTYPE html>
<html>

<head>
    <title>Flask Template Example</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <style type="text/css">
        .container {
            margin: auto;
            width: 20%
        }
    </style>
</head>

<body>
    <div class="container">
        <p>My string: {{my_string}}</p>
        <p>Value from the list: {{my_list[3]}}</p>
        <p>Loop through the list:</p>
        <ul>
            {% for n in my_list %}
                <li>{{n}}</li>
            {% endfor %}
        </ul>
        <div class='input_stuff'>
            <form action='/notice' method='POST'>
                <div>
                    First Name <input type='text' name='first_name'>
                </div>
                <div>
                    Last Name <input type='text' name='last_name'>
                </div>
                <div>
                    <input type='submit' name='submit'>
                </div>
            </form>
        </div>
        <div class="container">
      <h2>This is part of my base template</h2>
      <br>
      {% block content %}{% endblock %}
      <br>
      <h2>This is part of my base template</h2>
      <br>
      <div class="footer">
        {% block footer %}
          Watch! This will be added to my base and child templates using the super powerful super block!
          <br>
          <br>
          <br>
        {% endblock %}
      </div>
    </div>
    </div>
</body>

</html><jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.10392888498683055, 'fraction_numerical': 0.010206321334503951, 'mean_word_length': 3.1895785440613027, 'pattern_counts': {'":': 1, '<': 211, '<?xml version=': 0, '>': 235, 'https://': 20, 'lorem ipsum': 0, 'www.': 11, 'xml': 0}, 'pii_count': 4, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 16, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '8', 'dir': 'jupyter-structured-clean-dedup', 'id': '375901', 'license': 'MIT', 'n_tokens_mistral': 7421, 'n_tokens_neox': 7071, 'n_words': 3386, 'path': 'Notes/Web_7_HTML_And_CSS.ipynb', 'repo_name': 'javkoh/Materials', 'size': '27336'}