liangkyle08 / csp-blog

MIT License
0 stars 0 forks source link

Data Structure Writeup #11

Open liangkyle08 opened 3 months ago

liangkyle08 commented 3 months ago

APIs and JSON

api.add_resource(MessageAPI._CRUD, '/') api.add_resource(MessageAPI._Send, '/send') api.add_resource(MessageAPI._Delete, '/delete') api.add_resource(MessageAPI._Likes, '/like')

> The algorithmic condition used to direct requests to the appropriate Python method based on the request method typically involves a conditional statement that checks the HTTP method of the incoming request. This condition is often implemented using an `if` statement or a similar construct that evaluates the method of the request, such as `request.method`, and routes the request to the corresponding Python method accordingly. For example, in Flask, this condition might look like `if request.method == 'GET':` to handle GET requests or `elif request.method == 'POST':` to handle POST requests. Each conditional branch then invokes the appropriate Python method responsible for processing the request corresponding to that HTTP method. This approach ensures that the application can handle different types of requests effectively and execute the appropriate logic based on the action being performed by the client.
- In VSCode, show algorithmic conditions used to validate data on a POST condition.
```python
@token_required
def post(self, current_user, Message): # Create Method
    body = request.get_json()

    # Validate message content
    message_content = body.get('message')
    if not message_content:
        return {'message': 'Message content is missing'}, 400

    # Create Message object
    message = Message(uid=current_user.uid, message=message_content)

    # Add message to database
    try:
        created_message = message.create()
        return jsonify(created_message.read()), 201
    except Exception as e:
        return {'message': f'Failed to create message: {str(e)}'}, 500
function displayPosts(posts) {
        const postsContainer = document.getElementById('posts');
        postsContainer.innerHTML = ''; // Clear existing posts
        posts.forEach(post => {
            updatePostsContainer(post.uid, post.message, post.likes);
        });
    }
    function updatePostsContainer(uid, message, likes) {
        const postsContainer = document.getElementById('posts');
        const postDiv = document.createElement('div');
        postDiv.className = 'post-container';
        const postContent = document.createElement('p');
        postContent.className = 'post-content';
        postContent.textContent = `UID: ${uid}, Message: ${message}`;
        const replyButton = document.createElement('button');
        replyButton.textContent = 'Reply';
        replyButton.addEventListener('click', () => showReplyForm(uid));
        const deleteButton = document.createElement('button'); // Delete button
        deleteButton.textContent = 'Delete'; // Set text content to 'Delete'
        deleteButton.addEventListener('click', () => deletePost(uid, message)); // Attach event listener to delete button
        const likeButton = document.createElement('button'); // Like button
        likeButton.textContent = 'Like';
        likeButton.addEventListener('click', () => {
            likePost(uid, message);
            // Hide the like button after clicking
            likeButton.style.display = 'none';
        });
        const likeCountContainer = document.createElement('div');
        likeCountContainer.className = 'like-count-container';
        const likesCountSpan = document.createElement('span');
        likesCountSpan.className = 'likes-count';
        likesCountSpan.textContent = `${likes} 👍`;
        likeCountContainer.appendChild(likesCountSpan);
        postDiv.appendChild(postContent);
        postDiv.appendChild(replyButton);
        postDiv.appendChild(deleteButton); // Append the delete button
        postDiv.appendChild(likeButton);
        postDiv.appendChild(likeCountContainer);
        postsContainer.appendChild(postDiv);
    }
function fetchPosts() {
        var myHeaders = new Headers();
        myHeaders.append("Content-Type", "application/json");
        const authOptions = {
            method: 'GET',
            cache: 'no-cache',
            headers: myHeaders,
            credentials: 'include'
        };
        fetch('http://127.0.0.1:8086/api/messages/', authOptions)
            .then(response => {
                if (!response.ok) {
                    console.error('Failed to fetch posts:', response.status);
                    return null;
                }
                return response.json();
            })
            .then(posts => {
                if (posts === null || posts === undefined) {
                    console.warn('Received null or undefined posts.');
                    alert('Please Log in first!')
                    return;
                }
                console.log('Fetched Posts:', posts);
                displayPosts(posts);
            })
            .catch(error => {
                console.error('Error:', error);
            });
    }

First program checks for JSON response from backend (if successful return the data, otherwise post "Failed to fetch posts" and respective error). Also, if user is not logged in, will also prompt the user to login.

liangkyle08 commented 3 months ago

Optional/Extra, Algorithm Analysis

🔗 Link to ML Project Blog

# data extraction
data = information[0]  # get the first element
age = data["age"]  # age extraction

bothGenders = data["gender"]  # get both gender confidence rates
woman = bothGenders["Woman"]  # woman confidence
man = bothGenders["Man"]  # man confidence

# based on the probabilities, find which is larger and return that
gender = None
if woman > man:
    gender = "Female"
elif woman < man:
    gender = "Male"

# the order is very important (must be gender THEN age)
returnData = [gender, age]  # create a list and send it

return returnData  # return
liangkyle08 commented 3 months ago

Collections

liangkyle08 commented 3 months ago

Lists and Dictionaries

AnvayYadav commented 3 months ago

Reviewer: Anvay Yadav Completedness: 0.9/1 Neatness: 1/1 +0.05 (extra credit)

I think this is a good issue but you could add more screenshots detailing the code and write more text explaining the code. Everything is super neat, so full points for that. You have everything, but doing a bit more will get you the last few points. Extra credit earns you 0.05 extra.

1.95/2 = 97.5%