DeadshotLegend / shivansh

MIT License
0 stars 0 forks source link

2/26/2024 2015 FRQ Connections #7

Open DeadshotLegend opened 7 months ago

DeadshotLegend commented 7 months ago

1 Array/ArrayList

In order to solve this issue, I had to complete a number of array-related tasks. Specifically, I needed to sum elements and determine if sums in a two-dimensional array context are unique, which required my attention. I handle arrays through how I deal with JSON objects and arrays, as they are often used to represent structured data received from APIs. This is a part of my application that communicates with a server via HTTP requests to retrieve and process JSON data. I include methods for sending HTTP GET and POST requests (sendHttpGet and sendHttpPost). My sendHttpGet method sends an HTTP GET request to a specified URL and returns the JSON response received from the server. I then parse the response to extract relevant information, such as the first_id and data array containing messages from a specific thread. My 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 me for the given thread. How this FRQ is related to my Project:: This FRQ is related to my project because in the FRQ problem I focused on summing elements within an array list and within the Project I did a very similar thing, I stored data in an array with JSON elements in a summative method.

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;

2 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.

How the FRQ is Related to the Project: In the FRQ I was forced to create a HiddenWord class with various elements which had to contain specific data and logic for the program to work. This was very similar to my own project where I was forced to create my own class with specifc data and lgoic to match with the database, Controller, and JPA Repository.

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;

@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";

}

In coding the Chat class, I designed it to serve as a representation of a chat message entity within our Spring Boot application. Annotating it with @Entity was essential, as it indicates that instances of this class can be mapped to a database table. I made sure to encapsulate various attributes of a chat message within the class, 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). To ensure proper database mapping and the automatic generation of unique IDs for new records, I included JPA annotations like @Id and @GeneratedValue. These annotations play a crucial role in maintaining the integrity of the database structure.

3 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.

How the FRQ is related to the Project: The FRQ focused on iterating through a 2D sparse array which is very similar to my project where I focused on iterating through my own 2D array where I iterated over the list of chats and then retrieved the values.

@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;
}

This method retrieves all chat records from a database and formats them into a two-dimensional array. Each row in the array represents a chat, and each column holds different details like the person's ID, chat message, response, and timestamp. It loops through each chat record, extracts these details, and stores them in the array. Finally, it returns the populated array containing all the chat data.

4 Methods 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.

How the FRQ is related to the Project: The FRQ forced me to create a method where it first iterates through the numbers in the group, then checks if the current number matches the given number, and then returns true if the number is found in the group. In my project I created a similar project where I focused on iterating through the structure, check the utterances, and then return the utterances if they are there or stop the process if false.

@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();
}

In coding the RESTful API for managing chat history, I implemented two controller methods. The first method, clearChatHistory(), is triggered by a DELETE request to "/chat/history/clear". Within this method, I utilize the deleteByPersonId() method of the chatJpaRepository to remove all chats associated with a person ID of 1. Subsequently, I construct a JSON response containing details of the deleted chats.

Similarly, the second method, getAllChats(), is triggered by a GET request to "/chat/history". This method retrieves all chats associated with the same person ID from the database using the findByPersonId() method. Like before, I construct a JSON response containing details of these chats. Both methods follow a similar process of iterating through the retrieved or deleted chats. During this iteration, I print their IDs to the console and add their JSON representations to a JSONArray. Finally, this JSONArray is added to a JSONObject as part of the response, completing the construction of the JSON response for each method.

Jw95z commented 7 months ago

Frq grading

Question 1

1.0/0.9 You meticulously craft a succinct overview of the solutions, ensuring they meet the criteria outlined in the FRQ. Your response reflects a thoughtful analysis of the task at hand, with a discernible reflection evident in your conclusion. Furthermore, by showcasing a heightened level of insight and understanding, you may be eligible for additional credit, demonstrating a mastery of the subject matter.

Question 2

0.9/0.9 Same as question 1. You have effectively articulated your insights gained from this FRQ and demonstrated your growth throughout the process. Your reflection indicates a noticeable enhancement in your comprehension of coding concepts. The code you've presented is well-structured and exhibits a depth of understanding, suggesting minimal reliance on ChatGPT for assistance. However, it would be advantageous to include the essential concepts relevant to this FRQ for a more comprehensive response.

Question 3

0.9/0.9. you have completed all of the requirements like the previous questions. The outcome for the code matched the requrirments on this frq. But I don't know what getNumCols() and getNumRows work for the entire code. I think it would be much better if you writes the explanation for that.

Question 4

He did what the FRQ asked, but didn't do extra. I wish he had explained the key algorithm and FRQ type better, but we had a good discussion, even though we were confused at first about the type. I think he should get slightly more than 90% because he communicated well about the FRQ and we had a good discussion. .85/.9

Overall point: 3.65/3.6

Association Grading

Overall point 3.6 / 3.6

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.