hsinaDitaM / CSA_Notes

My notes and blogs for CSA
https://hsinaditam.github.io/CSA_Notes/
MIT License
0 stars 1 forks source link

Associations #7

Open hsinaDitaM opened 8 months ago

hsinaDitaM commented 8 months ago

Arrays

In order to solve this issue, a number of array-related tasks had to be completed. In particular, summing elements and determining if sums in a two-dimensional array context are unique required attention. Arrays are shown through how it deals with JSON objects and arrays, which are often used to represent structured data received from APIs. This Java code snippet is a part of an application that communicates with a server via HTTP requests to retrieve and process JSON data. It includes methods for sending HTTP GET and POST requests (sendHttpGet and sendHttpPost). The sendHttpGet method sends an HTTP GET request to a specified URL and returns the JSON response received from the server. The response is then parsed to extract relevant information, such as the first_id and data array containing messages from a specific thread. The code iterates through the data array to find and extract the text value of messages sent by an assistant. These messages are appended to a StringBuilder named chatResponse, which holds the response generated by the model for the given thread.

String getResponseUrl = "https://api.openai.com/v1/threads/" + threadId + "/messages";

    JSONObject rObj = sendHttpGet(getResponseUrl, contentType, auth, openAiBeta, org);

    System.out.println(rObj.toJSONString());
    // the response will match the first id
    String firstId = (String)rObj.get("first_id");
    // get data array from json
    JSONArray dataArray = (JSONArray)rObj.get("data");

    // to create the response string
    StringBuilder chatReponse = new StringBuilder();

    for (int i = 0; i < dataArray.size(); i++) {
        JSONObject anObj = (JSONObject)dataArray.get(i);

        // the role must be assistant to hold the value and id must match firstId
        if (anObj.get("role").equals("assistant") && anObj.get("id").equals(firstId)) {
            JSONArray contentArray = (JSONArray)anObj.get("content");

            for (int j = 0; j < contentArray.size(); j++) {
                JSONObject contentObj = (JSONObject)contentArray.get(j);
                JSONObject textObj = (JSONObject)contentObj.get("text");

                // this contains the chat gpt's response
                chatReponse.append((String)textObj.get("value"));
                break;
            }
        }
    }

    return chatReponse.toString();
}

// send http post and return JSON response
public static JSONObject sendHttpPost(String url, String body, Header... headers) throws Exception {
    JSONObject json = null;

    try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(new StringEntity(body));
        httpPost.setHeaders(headers);
        json = httpClient.execute(httpPost, new JSONResponseHandler());
    }

    return json;
}

// send http get and return JSON response
public static JSONObject sendHttpGet(String url, Header... headers) throws Exception {
    JSONObject json = null;

    try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
        HttpGet httpGet = new HttpGet(url);
        httpGet.setHeaders(headers);
        json = httpClient.execute(httpGet, new JSONResponseHandler());
    }

    return json;

Classes

For this FRQ, I had to create the HiddenWord class, which is essential to a word-guessing game in which the player tries to guess a concealed word. I had to create a coherent class structure that contained both data and logic for this project. The class design was extremely impotant for the entire project because it represented the POJO which works which both the JPA repository and the Controller.

package com.nighthawk.spring_portfolio.mvc.chathistory;

import java.sql.Date;

import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;

import org.json.simple.JSONObject;

https://github.com/entity
public class Chat {
// automatic unique identifier for Person record
@id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;

public Long getId() {
    return id;
}
private String chatMessage;
private String chatReponse;
private Date timestamp;
private Long personId;

public Long getPersonId() {
    return personId;
}
public String getChatMessage() {
    return chatMessage;
}
public String getChatReponse() {
    return chatReponse;
}
public Date getTimestamp() {
    return timestamp;
}
public Chat(String chatMessage, String chatReponse, Date timestamp, Long personId) {
    super();
    this.chatMessage = chatMessage;
    this.chatReponse = chatReponse;
    this.timestamp = timestamp;
    this.personId = personId;
}

public Chat() {

}
// todo add person id foreign key

@Override
public String toString() {
    JSONObject obj = new JSONObject();
    obj.put(idStr, id);
    obj.put(chat_message, chatMessage);
    obj.put(chat_response, chatReponse);
    obj.put(timestamp_str, timestamp.toString());
    obj.put(person_id, personId);

    return obj.toString();
}

public JSONObject toJSON() {
    JSONObject obj = new JSONObject();
    obj.put(idStr, id);
    obj.put(chat_message, chatMessage);
    obj.put(chat_response, chatReponse);
    obj.put(timestamp_str, timestamp.toString());
    obj.put(person_id, personId);

    return obj;
}

private static final String chat_message="chat_message";
private static final String idStr="id";
private static final String chat_response="chat_response";
private static final String timestamp_str="timestamp";
private static final String person_id="person_id";

2D arrays

The goal of the task was to have me come up with an effective representation and manipulation technique for a sparse array, which is a two-dimensional array where the majority of its members are zeros. The major goals were to change the array by eliminating columns and obtain certain element values from this sparse structure while preserving the array's structural integrity.

The Chat class serves as a representation of a chat message entity within a Spring Boot application. Annotated with https://github.com/entity, it indicates that instances of this class can be mapped to a database table. The class encapsulates various attributes of a chat message, such as its unique identifier (id), the actual message content (chatMessage), the response to the message (chatResponse), the timestamp of the message (timestamp), and the associated person's identifier (personId). The inclusion of JPA annotations like @id and @GeneratedValue ensures proper database mapping, with automatic generation of unique IDs for new records. The class also provides methods to convert instances to JSON format, facilitating data transfer and persistence tasks. Following the POJO pattern, the Chat class is a simple Java object focused solely on data representation, making it suitable for various data manipulation tasks within the application.


@GetMapping("/chat/history/all")
// get all chats and return as a two dimensional string array
public String[][] getAllChats() {
// get all chats
List chats = chatJpaRepository.findAll();
// initialize the two dimensional array
// array size is same as number of chats in the list above
// the other dimension of the two dimensional array is fixed at 4 to hold:
// person id; chat message; chat response; and time stamp
String[][] allChats = new String[chats.size()][4];
    // initialize the counter
    int counter = 0;

    // iterate over the list of chats
    for (Chat c : chats) {
        // retrieve values
        long personId = c.getPersonId();
        String chatMsg = c.getChatMessage();
        String response = c.getChatReponse();
        Date timeStamp = c.getTimestamp();
        // set values in the two dimensional array
        // counter is incremented at the end
        allChats[counter][0] = String.valueOf(personId);
        allChats[counter][1] = chatMsg;
        allChats[counter][2] = response;
        allChats[counter][3] = timeStamp.toString();

        // increment counter
        counter++;
    }

    // return the chats for all users
    return allChats;
}

method and control structures.

My job in this project was to create a database which could both delete chat history as well as get chat history. I had to employ a variety of techniques and control structures to create a flexible and dynamic framework for this task. This required developing techniques that made sure that loops would not run indefinitely if the specific utterance is not found so that caused me to utilize different conditional and complex statements.

@DeleteMapping("/chat/history/clear")
public String clearCharHistory() {
List chats = chatJpaRepository.deleteByPersonId(1l);
JSONObject obj = new JSONObject();
JSONArray list = new JSONArray();
    for (Chat c : chats) {
        System.out.println(c.getId());
         list.add(c.toJSON());
    }

    obj.put("chats", list);
    return obj.toJSONString();
}

@GetMapping("/chat/history")
public String getAllChats() {
    List<Chat>  chats = chatJpaRepository.findByPersonId(1l);
    JSONObject obj = new JSONObject();
    JSONArray list = new JSONArray();

    for (Chat c : chats) {
        System.out.println(c.getId());
         list.add(c.toJSON());
    }

    obj.put("chats", list);
    return obj.toString();
}

There are two controller methods in a RESTful API for managing chat history. The clearCharHistory() method, triggered by a DELETE request to "/chat/history/clear", utilizes the deleteByPersonId() method of the chatJpaRepository to remove all chats associated with a person ID of 1. The method then constructs a JSON response containing details of the deleted chats. Similarly, the getAllChats() method, triggered by a GET request to "/chat/history", retrieves all chats associated with the same person ID from the database using the findByPersonId() method. It constructs a JSON response containing details of these chats. Both methods iterate through the retrieved or deleted chats, printing their IDs to the console and adding their JSON representations to a JSONArray, which is then added to a JSONObject as part of the response.

tanayp327 commented 8 months ago

FRQ Code Grading (3.12/3.6)

FRQ 1 0.79/0.9

He completed what the FRQ was asking for, didn't see him go above and beyond though. I wish there was some more prior preparation with frq type and frq key algorithm, but he did convey these things out loud when I asked him about these things. He was good with talking about the code and showed me that he knew how it worked, not cheesing.

FRQ 2:

0.79/0.9 He said that these were really easy, and showed me this with his explanation of the code that was really good, and we had a somewhat similar solution. Of course, I made sure it correctly ran in the notebook file.

FRQ 3:

0.76/0.9 He said that this was a difficult concept for him to understand, we again had a similar issue with actually understanding what the question was asking, he and I didn't understand what a sparse array actually was, but he showed me that the code actually worked. It ran properly in the notebook as well, he had a small typo and then quickly fixed this error.

FRQ 4:

0.78/0.9 He completed what the FRQ was asking for, didn't see him go above and beyond though. I wish that he had thought out the explanation of the key algorithm and FRQ type, but we had a good discussion on this, even though we had a little confusion at first about the type. I think he deserved slightly above a 90% because he was able to properly comminucate about the FRQ and we were able to uphold a discussion properly.

FRQ Association Grading (3.2/3.6)

Overall points:

I like how you applied array tasks in both contexts and the code snippet demonstrates your understanding of arrays, JSON parsing, and HTTP communication, highlighting practical usage within your application for handling structured data from APIs, but there should have been more emphasis on what the FRQ is about, not veering a little too much off course. You also showed good ideas in class design and database mapping, I like how you talked about the Chat class for JPA mapping and its methods for JSON conversion. The controller methods showcase your ability to implement RESTful API endpoints for managing chat history, employing techniques such as deleting and retrieving data based on specific criteria, but you did not explain the . Your explanation of control structures and techniques used in your project, like preventing indefinite loops, indicates thoughtful consideration of program flow and error handling for a robust application.