Collections

Blog Python Model code and SQLite Database.

  • From VSCode using SQLite3 Editor, show your unique collection/table in database, display rows and columns in the table of the SQLite database.
  • From VSCode model, show your unique code that was created to initialize table and create test data.

    • Data table creation
  • Initialization and test messages

Lists and Dictionaries

Blog Python API code and use of List and Dictionaries.

  • In VSCode using Debugger, show a list as extracted from database as Python objects.

  • In VSCode use Debugger and list, show two distinct example examples of dictionaries, show Keys/Values using debugger.

    • After messages are fetched, they are stored in python as a dictionary. This is viewable from the debugger. The purple values on the left are the keys, the values are shown.

    • When someone types a message, the frontend sends an object with the data about the message, such as its name and description. The backend then stores this data as a dictionary with keys in purple on the left.

APIs and JSON

Blog Python API code and use of Postman to request and respond with JSON.

  • In VSCode, show Python API code definition for request and response using GET, POST, UPDATE methods. Discuss algorithmic condition used to direct request to appropriate Python method based on request method.

    • A resource is then added to the API under the appropriate link.

    • When a request is sent to the link, the appropriate function is called according to the type of request send.

  • In VSCode, show algorithmic conditions used to validate data on a POST condition.

    • Check for Presence of Message: The code verifies that the message field exists in the input data. This is crucial to prevent attempts to store empty or null messages in the database, ensuring that only meaningful data is processed and stored.

    • Successful Data Storage: If a valid message is provided, the code creates a new instance of ChatMessage, adds it to the database session, and commits it to the database. Upon successful storage, it returns a JSON response indicating that the data was stored successfully.

    • Error Handling for Missing Data: If the message field is missing from the input data, the code responds with an HTTP status code of 400 (Bad Request) and a JSON message indicating that the “Message is missing”. This informs the client that the input was invalid due to the absence of necessary data.

  • In Postman, show the JSON response data for 200 success conditions on GET, POST, and UPDATE methods.

  • In Postman, show URL request and Body requirements for GET, POST, and UPDATE methods.

  • In Postman, show the JSON response for error for 400 when missing body on a POST request.

    • Purpose and Method: The /edit endpoint is designed for updating existing messages in the chat application. It uses the HTTP PUT method, which is typically reserved for updating or replacing an existing resource on the server. This approach adheres to RESTful API design principles, where PUT requests are idempotent, meaning repeated requests should result in the same state without additional changes after the first request.

    • Data Handling: When a request is made to the /edit endpoint, it expects JSON data containing at least two pieces of information: message_id and message. The message_id is used to identify and locate the specific message in the database that needs to be updated, and message contains the new text that will replace the old message content. The endpoint then processes this data to update the specified message in the database.

    • Response Mechanism: After the update operation, the endpoint provides feedback through JSON responses. If the update is successful, it returns a JSON object with a success message, such as {“message”: “Message updated successfully!”}. If the specified message ID does not exist or the required data is missing, it responds with an error message and an appropriate HTTP status code, such as 404 Not Found for missing messages or 400 Bad Request for incomplete data.

  • In Postman, show the JSON response for error for 404 when providing an unknown user ID to a UPDATE request.

Frontend

Blog JavaScript API fetch code and formatting code to display JSON.

  • In Chrome inspect, show response of JSON objects from fetch of GET, POST, and UPDATE methods.

    • After a search is done, a GET request is sent to the backend. The backend then fetches the messages and the associated data. The data is then sent to the frontend.
  • In the Chrome browser, show a demo (GET) of obtaining an Array of JSON objects that are formatted into the browsers screen.
  • In JavaScript code, describe fetch and method that obtained the Array of JSON objects.

    • Data Fetching: This function initiates by sending a GET request to the server to retrieve all chat messages stored in the database.

    • Data Verification and Processing: Upon receiving the response, it verifies the successful receipt of the data. If successful, it parses the JSON data returned by the server.

    • Displaying Data: The function then clears any previously displayed messages and iterates over the fetched data. For each chat message, it formats the timestamp, creates a new div element, sets its content, and adds it to the chat display area. Each message also gets an event handler for editing when clicked, enhancing interactivity.

  • In JavaScript code, show code that performs iteration and formatting of data into HTML.

    • Iteration
      • The displayChat() function uses the Array.prototype.forEach() method to iterate over each element in the JSON array returned by the server. Here’s what happens during each iteration:

        • Element Creation: For each message in the array, a new <div> element is created.

        • Content Formatting: The message’s text and timestamp are formatted into a readable format.

        • Event Handling Setup: An onclick event is attached to each message, allowing users to interact with them (for example, to edit a message).

    • HTML Formatting
      • The HTML content for each message is structured and styled dynamically:

        • Creating HTML Elements: A <div> element is created for each chat message.

        • Setting Attributes: Each <div> is given an ID based on the message’s ID, which helps in identifying the message for future operations like editing.

        • Appending Child Elements: The created <div> is then appended to the parent container (chatBox), which is the HTML element designated for displaying messages.

  • In the Chrome browser, show a demo (POST or UPDATE) gathering and sending input and receiving a response that show update. Repeat this demo showing both success and failure.
  • In JavaScript code, show and describe code that handles success.

  • In JavaScript code, show and describe code that handles failure.

  • Success

    • The sendMessage function effectively handles sending messages. Upon confirmation that the message input isn’t empty, it determines whether to update an existing message or create a new one based on the presence of currentMessageId. It then sends the appropriate HTTP request to the server

    • When the operation is successful, the chat messages are refreshed to include the updated or new message, visually confirming to the user in the Chrome browser that their action was successful. The input field is also cleared

  • Failures

    • The sendMessage and displayChat functions handle errors by catching exceptions and displaying error messages using the console, which is useful during development but not visible to end-users

Optional/Extra, Algorithm Analysis

In the ML projects, there is a great deal of algorithm analysis. Think about preparing data and predictions.

  • Show algorithms and preparation of data for analysis. This includes cleaning, encoding, and one-hot encoding.
  • Data Extraction and DataFrame Creation: It begins by converting the incoming JSON data into a pandas DataFrame, which is a typical format for manipulating data in Python.

  • One-Hot Encoding: The categorical variable ‘embarked’ is transformed using one-hot encoding to turn it into a numerical format that machine learning models can process.

  • Handling Missing Values: The snippet includes a placeholder for handling missing data, which is crucial for maintaining data integrity and ensuring the model receives clean and complete data.

  • Show algorithms and preparation for predictions.

  • Model Prediction: This code uses two different models, a Decision Tree and a Logistic Regression, to compute the probability of survival based on the features provided. It specifically calls the predict_proba method, which gives the probability estimates for all classes. For binary classification, it extracts the probability of the positive class (survival).

  • Formatting and Response: The results are formatted as percentages and packaged into a JSON response, which provides a user-friendly way to present the prediction results to the client or end-user.

  • Discuss concepts and understanding of Linear Regression algorithms.

    • Linear Regression takes data points of inputs and outputs and uses a line of best fit to find an expected outcome

    • Data needs to be encoded as numbers because of this (can’t put words on a graph as data points)

    • Here is a formula and graph for a basic LSRL (Least Square Regression Line) to help visualize the process

  • I was able to understand this because I took AP Statistics

  • Discuss concepts and understanding of Decision Tree analysis algorithms.

    • Decision tree analysis employs a tree-like model of decisions, where each decision leads to a series of consequences.

      • Decision Tree Nodes (Decision Nodes): Decision nodes in a decision tree represent points where decisions are made. At each decision node, the data is split according to certain criteria based on the input features. These nodes evaluate the input data and make decisions that direct the flow of the data to different branches of the tree based on specific conditions. Essentially, these are the “question” nodes, asking if the data meets certain criteria, then directing the analysis flow accordingly.

      • Terminal Nodes (Leaf Nodes): Terminal nodes, also known as leaf nodes, are the endpoints of a decision tree where no further splitting occurs. Each terminal node represents an output or a decision result. These nodes are reached once all the relevant conditions have been satisfied along the path from the root to the leaf.

      • Root Node: The root node is the starting point of a decision tree. It is from this node that the decision-making process begins, leading to multiple decision nodes based on the dataset’s attributes. All nodes, through their branches, eventually trace back to this root node, which holds the initial decision criterion that guides the entire tree structure.

    • How they work

      • Decision Making Process: The decision tree starts at the root node, where it chooses the best feature of the dataset to split the data based on a statistical measure like information gain or Gini impurity. This node directs the dataset into branches leading to decision nodes, which further split the data by testing other features. This splitting continues, decision by decision, following the path that the data points take based on their attribute values, until a stopping condition is met.

      • Terminal Node Outcomes: Once the conditions of the decision nodes are no longer met or when a predefined depth of the tree is reached, the algorithm stops splitting and the data points are grouped at the terminal nodes, or leaf nodes. Each terminal node represents a final decision or prediction outcome based on the combination of feature conditions that led to that specific leaf, encapsulating the end result of the decision path from the root.