Anda

Notes of study, work and life


  • Home

  • Tags28

  • Categories2

  • Archives29

  • Search

[Notes] CSS Basic

Posted on 2019-04-11 | In CS
Symbols count in article: 8.2k | Reading time ≈ 7 mins.

CSS Basic

CSS introduction


  • CSS stands for Cascading Style Sheets
  • describes how HTML elements (titles, images, paragraph…) are to be displayed on screen, paper, or in other media
  • CSS version 2.1/3.0
  • IE9 and above browsers support CSS 3.0

CSS in HTML


Usage of CSS in HTMl

  • Inline Style 内联样式 (highest priority) <h1 style="color:blue;">This is a heading</h1> (Not recommended)
  • Internal Style 嵌入样式 (second priority)

    1
    2
    3
    4
    5
    6
    7
    <head>
    <style>
    h1 {
    color: maroon;
    }
    </style>
    </head>
  • External Style 外部样式 (lowest priority)

    • Each page must include a reference to the external style sheet file inside the <link> element.
    • The <link> element goes inside the <head> section:

      1
      2
      3
      <head>
      <link rel="stylesheet" type="text/css" href="mystyle.css">
      </head>
      • type attribute: specifies the media type of the linked document
      • rel:specifies the relationship between the current document and the linked document
      • href:specifies the location of the linked document
  • Default Style 缺省样式
  • example
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    <!DOCTYPE html>
    <html>
    <head>
    <!-- external style -->
    <link rel="stylesheet" type="text/css" href="mystyle.css"> </head>
    <!-- internal style -->
    <style>
    h1 {
    color: blue;
    }
    </style>
    <body>
    <!-- default style -->
    <h2>test0</h2>
    <h1>test1</h1>
    <!-- Inline style -->
    <p style="color:brown">test2</p>

    </body>
    </html>

Syntax

Selector {Property: value; Property: value;}

  • example h1 {color:blue;font-size:12px;}
  • The selector
    • points to the HTML element you want to style.
  • The declaration block
    • contains one or more declarations separated by semicolons.
    • each declaration includes a CSS property name and a value, separated by a colon.
    • always ends with a semicolon
    • declaration blocks are surrounded by curly braces.
  • Comment /* */

Basic properties

  • width - 宽度, 单位px(像素)
  • height - 高度
  • color - 前景色, 也就是文字的颜色
  • background-color - 背景色
  • font-size - 字体的大小

CSS Selectors

  • * All Elements * {color:blue} /*all items set to blue*/
  • Element name. p {color:blue} /* all p tag turn to blue */
  • #id

    • The id selector uses the id attribute of an HTML element to select a specific element.
    • The id of an element should be unique within a page, so the id selector is used to select one unique element!
    • To select an element with a specific id, write a hash (#) character, followed by the id of the element.
      1
      2
      3
      4
      5

      <li id=”li-ca”>CA</li>
      #li-ca {
      color: blue;
      }
  • class

    • The class selector selects elements with a specific class attribute.
    • To select elements with a specific class, write a period (.) character, followed by the name of the class.
      1
      2
      3
      4
      5
      .nice {
      color: purple;
      }
      <p class="nice">lalala</p>
      <p class="nice">hohoho</p>

Combinator

  • Combinator is a selector combined by multiple selectors.
  • 后代选择器 div p : selects all <p> elements inside <div> elements`

    1
    .class h3 {color:red; font-size:25px;}
  • 并集选择器 div, p : selects all <div> elements and all <p> elements

    1
    .class, h3 {color:red; font-size:25px;}
  • 子元素选择器 div > p : selects all <p> elements where the parent is a <div> element

    1
    .class, h3 {color:red; font-size:25px;}
  • Difference of div p and div > p: div p includes all sons and grandsons, while div > p has only direct sons.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    <style>
    <!-- All strong whose parent is p -->
    p > strong {
    color: red;
    }
    p > span > strong {
    color: green;
    }
    <!-- All strong below div -->
    div strong {
    font-size: 50px;
    }
    </style>
    <!-- ... -->
    <div>
    <p id="aa">this is <span><strong>strong under span</strong></span></p>
    <p>this is paragraph 3</p>
    <p><strong>I am strong under p</strong></p>
    </div>
  • Attribute selector: Use a [] to select attributes

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    <style>
    <!-- all p with class attribute -->
    p[class] {
    color:red;
    }
    <!-- the class of p is "right -->
    p[class="right"] {
    color:blue;
    }
    <!-- class~="demo means class contains "demo"-->
    p[class~="demo"] {
    font-size: 60px;
    }
    </style>
    <body>
    <p class="right"> i am div1</p>
    <p> i am div2</p>
    <p class="left demo"> i am div3</p>
    <p id="side"> i am div4</p>
    </body>
  • Pseudo Classes 伪类

    • :link - (a:link) selects all unvisited links
    • :hover - (a:hover) selects links on mouse over
    • :active - (a:active) selects the active link
    • :visited - (a:visited) selects all visited links\
    • :first-child - (p:first-child) selects every <p> element that is the first child of its parent
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    <style>
    a:link {
    color: red;
    }
    a:visited {
    color: yellow;
    }
    a:hover {
    font-size: 50px;
    color: blue;
    }
    a:active {
    color: green;
    }
    p:first-child {
    background-color: brown;
    }
    </style>
  • Pesudo Elements

    • ::first-element (does not work on inline elements, such as span)
      1
      2
      3
      4
      5
      6
      <style>
      p::first-letter {
      font-size: 100px;
      color: pink;
      }
      </style>

CSS Cascade and Inheritance


CSS Cascade

  • the cascade is a set of rules for determining which style properties get applied to an element.
  • It specifies how a web browser should handle multiple styles that apply to the same tag and what to do when CSS properties conflict.
  • bottom > top

Inheritance

  • some property values applied to an element will be inherited by that element’s children, and some won’t.
  • font-family and color to be inherited, as that makes it easy for you to set a site-wide base font by applying a font-family to the <html> element;
  • margin, padding, border, and background-image to NOT be inherited
  • <a> does not support any kind of inheritance unless: a {color: inherit;}
  • eg. <span> inside a <p> will be overrided.

Specificity


First Principle

  • Inline style > Internal > external > inheritance > default

Second Principle

  • id > class/pseudo class > tag > inheritance > default

Specificity Collision

  • CSS provides a formula for determining a style’s specificity that’s based on a value assigned to the style’s selector - a tag selector, class selector, ID selector, and so on. Here’s how the system works:
    • A tag selector is worth 1 point.
    • A class selector is worth 10 points.
    • An ID selector is worth 100 points.
    • An inline style is worth 1,000 points.
    • The bigger the number, the greater the specificity.
  • Example
    • A tag style for the tag (specificity = 1)
    • A class style named .highlight (specificity = 10)
    • An ID style named #logo (specificity = 100)
    • Then say your web page has this HTML: <img id=”logo” class=”highlight” src=”logo.gif”/>. If you define the same property - such as the border property - in all three styles, then the value from the ID style (#logo) always wins out.
  • A pseudo-element (like ::before) is treated like a tag selector and is worth 1 point. A pseudo-class (:link) is treated like a class and is worth 10 points.
  • Since descendant selectors are composed of several selectors - #content p, or h2 strong, for example, the math gets a bit more complicated. The specificity of a descendant selector is the total value of all of the selectors listed.
  • A descendant selector = 1 tag + 1 tag/class

  • 5. CSS Basic-2019-4-11-11-28-42.png
  • If there’s still collision, last style wins
  • !important; This is an overruling specificity, it means ‘this is important, ignore subsequent rules, and any usual specificity issues, apply this rule!’ For example:
    1
    2
    3
    4
    <style>
    .nav a { color: red; }
    a { color: blue !important; }
    </style>

[Notes] TicketMaster API

Posted on 2019-04-09 | Edited on 2019-04-11 | In CS
Symbols count in article: 6.5k | Reading time ≈ 6 mins.

TicketMaster API

HTML request message

  • 4. TicketMasterAPI-2019-4-11-11-26-25.png
  • Request structure
    • GET /doc/test.html HTTP 1.1
      First part indicates the type of the request, second part indicates the resource it asks for, third part is the version of protocal
    • Request Header
    • Request Body bookId=12345&author=Tan+Ah+Teck
      • Some browser will process the data here.
        • Response structure
    • 4. TicketMasterAPI-2019-4-11-11-26-38.png
    • Status line HTTP/1.1 200 OK
      200 indicates that the response status number, and the “OK” is the explanation of the status.
    • Response Header
    • Response Body <h1>Home page</h1>

RESTful API

  • CRUD
    • Create/Read/Update/Delete
    • matches HTTP POST/GET/PUT/DELETE
  • server is stateless
    • No need to involve other requests when handling the request.

TicketMaster API

  • Request
    • URL of discover API protocol://hostname:port/endpoint?query :
      • protocol: https
      • hostname: app.ticketmaster.com
      • endpoint: /discovery/v2/events.json
      • query:
        • APIkey: it’s required by TicketMaster API for authn/authz
        • GeoPoint: lat/long since our search is based on client location
        • Radius: radius of search area
        • Keyword: search a specific kind of events
    • example https://app.ticketmaster.com/discovery/v2/events.json?apikey=12345&geoPoint=abcd&keyword=music&radius=50
    • Headers and Body: nothing to set since it’s not required for this API.
  • Response
    • 4. TicketMasterAPI-2019-4-11-11-27-25.png
    • data we need is located in _embedded(JSON Object) -> events(JSON Array) -> item object(JSON Object)
  • Implementation

    • Create a new Package external in src
    • Create a new class TicketMasterAPI
    • Add some constants

      1
      2
      3
      ​private static final String URL = "https://app.ticketmaster.com/discovery/v2/events.json";
      ​private static final String DEFAULT_KEYWORD = ""; // no restriction
      ​private static final String API_KEY = "USE_YOUR_OWN_KEY";
    • Add a search function

      1
      2
      3
      4
      5
      6
      7
      8
      9
      /**
      * Search the keyword through TM API
      * @param lat latitude
      * @param lon longitude
      * @param keyword keyword is optional
      */
      public JSONArray search(double lat, double lon, String keyword) {
      return null;
      }
    • Add queryAPI helper

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      /**
      * print the results of search(lat, lon)
      * @param lat latitude
      * @param lon longitude
      */
      private void queryAPI(double lat, double lon) {
      JSONArray events = search(lat, lon, null);
      try {
      for (int i = 0; i < events.length(); i++) {
      JSONObject event = events.getJSONObject(i);
      System.out.println(event);
      }
      } catch (Exception e) {
      e.printStackTrace();
      }
      }
    • Add GeoHash helper to convert lat, lon to geoPoint. Copy the code from http://developer-should-know.com/post/87283491372/geohash-encoding-and-decoding-algorithm

    • Implement search(lat,lon,keyword) function

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      26
      27
      28
      29
      30
      31
      32
      33
      34
      35
      36
      37
      38
      39
      40
      41
      42
      43
      44
      45
      46
      47
      48
      49
      50
      51
      52
      53
      54
      55
      56
      57
      58
      /**
      * Search the JSONArray results through TM API
      * @param lat latitude
      * @param lon longitude
      * @param keyword keyword is optional
      * @return JSONArray
      */
      public JSONArray search(double lat, double lon, String keyword) {
      JSONArray ret = new JSONArray();
      if (keyword == null) keyword = DEFAULT_KEYWORD;
      // translate keyword into URL-supported format
      try {
      keyword = java.net.URLEncoder.encode(keyword, "UTF-8");
      } catch (Exception e) {
      e.printStackTrace();
      }
      // Get geoPoint
      String geoHash = GeoHash.encodeGeohash(lat, lon, 8);
      // Create query
      // 50 is default search radius
      String query = String.format("apikey=%s&geoPoint=%s&keyword=%s&radius=%s", API_KEY, geoHash, keyword, 50);
      // Create URL
      try {
      // create a HTTP URL connection
      HttpURLConnection connection = (HttpURLConnection) new URL(URL + "?" + query).openConnection();
      // get the response code EG. 200/success, 404/fail
      int responseCode = connection.getResponseCode();
      // print res
      System.out.println("\nSending \"GET\" request to URL : " + URL + "?" + query);
      System.out.println("\nResponse Code: " + responseCode);
      // check responseCode (Implement it later)
      if (responseCode != 200) {

      }
      // read and write the response content
      BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
      String inputLine;
      StringBuilder response = new StringBuilder();
      while ((inputLine = in.readLine()) != null) {
      response.append(inputLine);
      }
      in.close();
      connection.disconnect();
      // write the response to a JSON object
      JSONObject obj = new JSONObject(response.toString());
      // check the result
      if (obj.isNull("_embedded")) {
      return ret;
      }
      // get the events from the whole JSON and return the events field of it as a JSON Array.
      JSONObject embedded = obj.getJSONObject("_embedded");
      JSONArray events = embedded.getJSONArray("events");
      ret = events;
      } catch (Exception e) {
      e.printStackTrace();
      }
      return ret;
      }
    • Create a new package entity and a new class Item(entity表示servelet储存数据的类)

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      26
      27
      /**
      * Item of event
      * @author andaluo
      *
      */
      public class Item {
      private String itemId;
      private String name;
      private double rating;
      private String address;
      private Set<String> categories;
      private String imageURL;
      private String url;
      private double distance;

      public JSONObject toJSONObject() {
      JSONObject obj = new JSONObject();
      try {
      obj.put("item_id", itemId);
      obj.put("name", name);
      obj.put("rating", rating);
      // ...
      } catch (Exception e) {
      e.printStackTrace();
      }
      return obj;
      }
    • Use builder pattern to create Item class

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      26
      27
      28
      29
      30
      31
      32
      33
      34
      35
      36
      37
      38
      39
      40
      41
      42
      43
        /**
      * A helper class to build the Item class
      * @author andaluo
      *
      */
      public static class ItemBuilder{
      private String itemId;
      private String name;
      // ...

      /**
      * Construct the Item using builder
      * @return
      */
      public Item build() {
      return new Item(this);
      }

      /**
      * return the builder itself to support continuous operation.
      * @param itemId
      * @return
      */
      public ItemBuilder setItemId(String itemId) {
      this.itemId = itemId;
      return this;
      }
      //...
      }

      /**
      * Builder pattern to create a class
      * @param builder
      */
      public Item(ItemBuilder builder) {
      this.itemId = builder.itemId;
      this.name = builder.name;
      // ...

      // when build the item we get
      public static void main(String[] args) {
      Item item = new Item.ItemBuilder().setAddress("abc").setDistance(19).build();
      }

How to Reverse A Linked List

Posted on 2019-04-09 | In CS
Symbols count in article: 780 | Reading time ≈ 1 mins.

Reverse linked list

  1. corner case

    1
    2
    dummy->1->null
    dummy->null
  2. general case

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    dummy-> 1 ->   2      -> 3 -> null
    pre cur nextNode

    dummy -> 2 -> 1 -> 3 -> null
    pre nextNode cur

    dummy -> 2 -> 1 -> 3 -> null
    pre cur nextNode

    dummy -> 3 -> 2 -> 1 -> null
    pre cur nextNode

  1. link cur to the next node cur.next = nextNode.next
  2. link nextNode to the head of the reversed part nextNode.next = pre.next
  3. link pre to the nextNode pre.next = nextNode
  4. update nextNode to next nextNode = cur.next
  5. when nextNode gets to the end, exit

cur represents the tail, and pre represents the the dummy, nextNode represents the node waiting to be added to the head of the list.

[Notes] HTML Basic

Posted on 2019-04-09 | Edited on 2019-04-11 | In CS
Symbols count in article: 7k | Reading time ≈ 6 mins.

HTML Basic

How Internet works(High Level)

  • ​find the right address www.google.com -> 172.217.8.132
    • Your query is submitted to your ISP( Internet service provider)
    • DNS(Domain Name System) takes the domain name and turns it into URI
  • a request is sent to the server and then the server response whatever requested, in this case, it is the combination of html, css and JavaScript
  • the browser display the website.

Basic Web Technologies

  • HTML: Structure
  • CSS: Style
  • JavaScript: Interaction

Tags

  • Hypertext Markup Language

  • Tags

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    1. <!DOCTYPE> (声明)
    2. <html>
    3. <body>
    4. <ul>
    5. <div>
    6. <span>
    7. <a>
    8. <img>
    9. <header>
    10. <nav>
    11. <section>
    12. <aside>
    13. <footer>
  • <!DOCTYPE>

    • <!DOCTYPE> declaration is not an HTML tag
    • it is an instruction to the web browser about what version of HTML the page is written in and how to render the content
    • always add the <!DOCTYPE> declaration to your HTML documents.
    • html5的声明是<!DOCTYPE html>
  • <head>

    • provides general information (metadata) about the document,including its title and links to its scripts and style sheets.
    • after <html> tag
    • only 1 pair of <head> tag in a html document
    • <title> can only be placed here.
    • <meta charset="UTF-8"> set the charSet of this page
  • <body>
    ​- represents the content of an HTML document.
    ​- after <head> tag but on the same level

    • only 1 pair of <body> element in a document
    • contains:
    • 标题标签 <h1> - <h6>
    • 段落标签 <p>
    • 注释标签 <!-- comment -- >
    • 水平线标签 <hr>(单标签)
    • 换行标签 <br>(单标签)
    • 文本节标签 <span>
  • <ul> Unordered list

    • represents an unordered list of items
    • typically rendered as a bulleted list
    • uses with <li>
  • <ol> ordered list

  • <li>

    • represent an item in a list.
    • must be contained in a parent element: an ordered list <ol>, an unordered list <ul>, or a menu <menu>.
  • <a> 超级链接

    • creates a hyperlink to other web pages, files, locations within the same page, email addresses, or any other URL.
    • <a href="https://www.google.com">Google</a>
    • href attribute: contains a URL or a URL fragment that the hyperlink points to.
    • #: link to an element with a specified id within the page (like href=”#top”)
    • target attribute: _blank vs. _self
      • example
        1
        2
        <a href="http://www.google.com" target="_blank"></a>
        <!-- _blank means open in new tag, _self means open in this tag--->
  • <img>图片标签(单标签)

    • defines an image in an HTML page.
    • has two required attributes: src and alt: <img src=”” alt=”” >
    • has no end tag(self-closing tag).
    • if the image is broken, then the alternative name shows up.

Blocks

  • <div>
    • the generic container for flow content and does not inherently represent anything.
    • use it to group elements for purposes.
  • recall<span>
    • a generic inline container for phrasing content.
    • does not inherently represent anything.
    • use it to group elements for purposes.
  • <div> vs. <span>
  • find all block elements and inline elements after the class
  • <p> 另起一行,因此也属于块状标签

Semantic Tags

  • A semantic element clearly describes its meaning to both the browser and the developer.
    • 语义标签
    • examples of non-semantic elements: <div> and <span> - tells nothing about its content.
    • examples of semantic elements: <form>, <table>, and <article> - clearly defines its content.
  • 3. HTMLBasic-2019-4-11-11-25-22.png
  • Semantic elements
    • <header> 页眉:
      represents a container for introductory content or a set of navigational links.
    • <section> 区块:
      represents a standalone section of functionality contained within an HTML document, typically with a heading, which doesn’t have a more specific semantic element to represent it.
    • <aside> 侧边栏:
      represents a section of a document with content connected tangentially to the main content of the document (often presented as a sidebar).
    • <nav> 导航:
      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.
    • <footer> 页脚:
      defines a footer for a document or section which contain information about its containing element.

Project Structure

  • structure

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <meta name="description" content="Item Recommendation">
    <meta name="author" content="Your Name">
    <title>Item Recommendation Final</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">
    </head>

    <body>
    <header>
    <nav>
    <a href="">Home</a>
    <a href="#name">Contact</a>
    <a href="">About</a>
    </nav>

    </header>

    <div>
    <header>
    <p>
    <span>Item</span>
    <i id="avatar" class="avatar fa fa-user fa-2x">Icon</i>

    <br> Recommendation
    </p>
    </header>

    <section>
    <aside>
    <nav>
    <a href="#">Nearby</a>
    <a href="#">My Favorites</a>
    <a href="#">Recommendation</a>
    </nav>
    </aside>

    <ul>
    <li>
    <img src="https://s1.ticketm.net/dam/c/48b/2352e3b5-8496-496b-97a3-e605177e848b_105851_ARTIST_PAGE_3_2.jpg" />
    <div>
    <a href="#">Item</a>
    <p>Music</p>
    </div>
    <p>99 Grove Street<br/>San Francisco<br/> CA</p>
    </li>
    </ul>
    </section>
    </div>

    <footer>
    <p>What We Do</p>
    <p>"Help you find the best place around."</p>
    <ul>
    <li>
    <p>Example office, CA</p>
    </li>
    <li>
    <p>info@example.com</p>
    </li>
    <li>
    <p>+1 800 123 456</p>
    </li>
    </ul>
    </footer>
    </body>

    </html>
  • Use FontAwesome to get icon. Add the css to

    1
    2
    3
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">

    <i id="avatar" class="avatar fa fa-user fa-2x"></i>

[Notes] Java Servlet

Posted on 2019-04-05 | Edited on 2019-04-11 | In CS
Symbols count in article: 5.1k | Reading time ≈ 5 mins.

Servlet

REST(Representational State Transfer)

  • REST is web server design pattern
  • Operations are directly based on HTTP methods, so that server don’t need to parse extra thing
  • URL clearly indicates which resource a client want, easy for client side users to understand.
  • Server is running in stateless mode, improve scalability.

Create Jupyter Project && SearchItem Servlet

  • Create Dynamic Project called “Jupiter”
  • Add Tomcat 9.0 to its Java Build Path
  • Add And Remove project Jupyter to existed Tomcat server
  • Create java Servlet in Jupyter project, name it SearchItem and name the package rpc
  • It should contain a doGet() and doPost()
  • change the mapping url

    1
    2
    3
    4
    // better style to set them all lowercase
    // 可以直接在创建servlet的页面修改
    @WebServlet("/SearchItem") // by default
    @WebServlet("/search")
  • Handle the doGet() method by adding tutorial code

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    // response.getWriter()表示得到response的输出流
    PrintWriter out = response.getWriter();

    // request.getParameter表示获取request中的body的参数信息
    if (request.getParameter("username") != null) {
    String username = request.getParameter("username");
    out.print("Hello " + username);
    }

    // 一定要关闭这个输出流
    out.close();
  • test the input

    1
    http://localhost:8080/Jupiter/search?username=abcd
  • return a HTML page

    1
    2
    3
    4
    5
    6
    7
    8
    9
    // 需要告诉浏览器页面的类型,渲染成所需的格式
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();

    out.println("<html><body>");
    out.println("<h1>This is a HTML page</h1>");
    out.println("</body></html>");

    out.close();
  • add Java-json jar support to the WebContent-WebInf-lib

  • test json support

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    // 把页面设置成json键值对格式
    response.setContentType("application/json");
    PrintWriter out = response.getWriter();

    String username = "";
    if (request.getParameter("username") != null) {
    username = request.getParameter("username");
    }
    JSONObject obj = new JSONObject();
    try {
    obj.put("username", username);
    } catch (JSONException e) {
    e.printStackTrace();
    }
    out.print(obj);
    out.close();
  • test jason array

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    response.setContentType("application/json");
    PrintWriter out = response.getWriter();
    //json array 存储多个键值对
    JSONArray array = new JSONArray();
    try {
    array.put(new JSONObject().put("username", "abcd"));
    array.put(new JSONObject().put("username", "1234"));
    } catch (JSONException e) {
    e.printStackTrace();
    }
    out.print(array);
    out.close();

Create RecommendItem Servlet

  • Create another Servlet called RecommendItem under prc package, and change the mapping url
  • practice on JSONArray
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    // 1. set content type
    response.setContentType("application/json");
    // 2. get output stream of response
    PrintWriter out = response.getWriter();
    // 3. create json array
    JSONArray arr = new JSONArray();
    try {
    // 4. create JSONObject and put those in the JSONArray
    arr.put(new JSONObject().put("name", "abcd").put("address", "san francisco").put("time","01/01/2017"));
    arr.put(new JSONObject().put("name", "1234").put("address", "san jose").put("time","01/02/2017"));
    } catch (JSONException e) {
    e.printStackTrace();
    }
    // 5. print the result
    out.print(arr);
    out.close();

Add RpcHelper utility class

  • create regular class RpcHelper under rpc package
  • add writeJSONObject(response, JSONObject)

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    public static void writeJSONObject(HttpServletResponse response , JSONObject obj) {
    try {
    // 1. 修改content type
    response.setContentType("application/json");
    // 2. 加入header response.addHeader
    response.addHeader("Access-Control-Allow-Origin", "*");
    // 3. 获取输出流 PrintWriter
    PrintWriter out = response.getWriter();
    // 4. 写入
    out.print(obj);
    out.close();
    } catch (Exception e) {
    e.printStackTrace();
    }
    }
  • add writeJSONArray(response, JSONArray)

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    public static void writeJSONArray(HttpServletResponse response , JSONArray array) {
    try {
    // 1. 修改content type
    response.setContentType("application/json");
    // 2. 加入header
    response.addHeader("Access-Control-Allow-Origin", "*");
    // 3. 获取输出流
    PrintWriter out = response.getWriter();
    // 4. 写入
    out.print(array);
    out.close();
    } catch (Exception e) {
    e.printStackTrace();
    }
    }
  • now apply the helper to the SearchItem and RecommendationItem

TicketMaster API

  • 2. JavaServlet-2019-4-11-11-24-33.png
  • An web based API provided by TicketMaster so that clients and get real events data from TicketMaster server. You cannot see the source code of it, but you can refer to the documentation to figure out how to use the interface to make connection by sending request to it’s backend.
  • It’s required by TicketMaster API so that it’ll know who is using their API. To get your API key, you need to register on this website: http://developer.ticketmaster.com, and you’ll see your API key when we navigate to API details.
  • The bottle neck of this project is TicketMaster API, since we cannot control its performance.
  • If we have to optimize it, we can create a cache.
  • Or we can make another API. Make a copy each time we query something from TicketMaster.
  • If TicketMaster is down. We can query local copy of nearest geo point.模仿一个曲线拟合的过程,即模糊搜索

[Notes] Web Application Basic

Posted on 2019-04-04 | In CS
Symbols count in article: 2.7k | Reading time ≈ 2 mins.

Web Application

Dependencies:

  1. Java 8
  2. Eclipse EE
  3. Postman
  4. Tomcat

Web Application: Clients ->Internet-> Server

  • Server(Backend)
  • Client(Frontend): User interface
  • Internet

TCP/IP区别:

  • IP对应特定机器的地址,TCP对应特定机器特定进程的地址
  • TCP通过端口来监听请求,请求包括IP和端口号

在浏览器输入www.example.com会发生什么?

  1. (client) client opens browser and goes to an Internet address (IP address/URL/hostname) and asks for page for (http://www.example.com), which means “I want to see ‘http://www.example.com/index.html’”
  2. (network) Internet redirects your request “I want to see ‘http://www.example.com’” to example’s server (a set of web servers)
  3. (server) One of example’s server sends a response to your Internet address (ip address). The response contains a HTML page. We will talk about HTML later.
  4. (network) The response goes through the Internet and received by your browser.
  5. (client) Your browser receives the response from example’s server and the HTML page contained in it. Render the page view and present to you. How to view the HTML page source? (Right click, and view page source)

如何设计web app? 三层结构

  1. presentation tier 直接与用户交互
  2. logic tier 应用具体的逻辑
  3. data tier 数据库

Tomcat 提供web server

  1. RPC(remote procedure call) 调用一个远端机器上的API
  2. Java Servlet 服务器端负责处理RPC的java class
  3. Tomcat 存放servlet的环境,负责接受请求并分配到对应的servlet处理,把处理的结果传给正确的客户

Tomcat配置

  1. 在properties里面点一下switch location找配置文件
  2. server location改成 use tomcat installation
  3. 地址localhost:8080

Http request methods

  1. GET(read in general)
  2. POST(write in general)
  3. PUT(write)
  4. DELETE(write)

URL(Unique Resource Locator)

  1. format:

    1
    2
    3
    4
    5
    6
    + protocal(http/https)
    + hostname(www.youtube.com)
    + port(8080): which process
    + endpoint: The name and location of the requested resource, under the server base directory. 相当于要触发的服务或功能
    + query: separated from the preceding part by a question mark (?), containing a query string of attribute–value pairs separated by a delimiter. 相当于参数
    + example: ```https://www.youtube.com/results?search_query=example

    • example:

      1
      2. url会自动将空格转码成```"20%"

    • 如果要inplace操作的话,先扫一遍找出空格数,然后再扩容字符串,然后冲后往前填。

http request body: 包含http request的数据

  • POST的body信息通常是隐藏的,GET通常没有必要隐藏
  • request例子

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    JSON(JavaScript Object Notation)
    {
    “instructor”:
    {
    "company": "Laioffer",
    "course": “Project” ,
    "name": “Vincent”
    }
    }

    // Alternative formats

    XML: eXtensible Markup Language
    <instructor>
    <company>Laioffer</company>
    <course>Project</course>
    <name>Vincent</name>
    </instructor>


    ProtocolBuffer
    Instructor {
    company = “Laioffer”,
    course= “Project”
    name= “Vincent”
    }
  • JSON简洁一些,xml长一些,ProtocalBuffer更新效率更高。前两种都是字符串,后一种是java class,相当于二进制文件,需要额外支持。

bitwise operation位运算相关

Posted on 2019-03-29 | Edited on 2019-03-28 | In CS
Symbols count in article: 211 | Reading time ≈ 1 mins.

1. How to check odd number

n & 1 means comparing last digit of binary number to 1

1
2
def is_odd(n):
return n & 1 == 1

2. Float division

n >> 1 means n floor divides 2

1
2
>>> 5 >> 1
2

HelloWorld

Posted on 2019-03-28 | Edited on 2019-04-09 | In Personal
Symbols count in article: 16 | Reading time ≈ 1 mins.

长风破浪会有时,直挂云帆济沧海!

[Leetcode] 3. Longest Substring Without Repeating Characters

Posted on 2019-03-28 | Edited on 2019-04-09 | In CS
Symbols count in article: 2.3k | Reading time ≈ 2 mins.

meidum

Given a string, find the length of the longest substring without repeating characters.

Example 1:

1
2
3
Input: "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.

Example 2:

1
2
3
Input: "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.

Example 3:

1
2
3
4
Input: "pwwkew"
Output: 3
Explanation: The answer is "wke", with the length of 3.
Note that the answer must be a substring, "pwke" is a subsequence and not a substring.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
class Solution1:
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
# DFS solution O(n2)
if not s:
return 0
memo = set()
self.max_length = float('-inf')
for i in range(len(s)):
if self.max_length >= len(s) - i:
break
self.helper("", i, s, memo)
return self.max_length

def helper(self, path, ind, string, memo):
self.max_length = max(self.max_length, len(path))
if ind >= len(string):
return

if string[ind] not in path:
path+=string[ind]
# print(path)
self.helper(path, ind+1, string, memo)
return

class Solution2:
# sliding window
# O(2n) time O(min(m, n)) space. m is 26, n is len of str
def lengthOfLongestSubstring(self, s):
if not s:
return 0
i = j = 0
res = 0
memo = set()
while i < len(s) and j < len(s):
if s[j] not in memo:
memo.add(s[j])
res = max(res, j - i + 1)
j+=1
else:
memo.remove(s[i])
i += 1
return res

class Solution:
# sliding window optimized using map
# O(n) time O(min(m, n)) space. m is 26, n is len of str
def lengthOfLongestSubstring(self, s):
if not s:
return 0
res = 0
i = j = 0
dic = {}
while j < len(s):
if s[j] in dic:
i = max(dic[s[j]], i)
res = max(res, j - i + 1)
dic[s[j]] = j + 1
j+=1
return res
123

Anda Luo

Notes of study, work and life
29 posts
2 categories
28 tags
GitHub E-Mail
© 2019 Anda Luo | 277k | 4:12
Powered by Hexo v3.8.0
|
Theme – NexT.Muse v7.0.1