%%html
<html lang="en-US">
<head>
  <!-- ... (your existing head content) ... -->
  <style>
    /* ... (your existing styles) ... */

    .chatroom {
      width: 700px;
      background-color: #000; /* Black background color */
      border-radius: 10px;
      box-shadow: 0 0 10px rgba(0, 0, 0, 0.3);
      overflow: hidden;
    }
    .chatroom-header {
      background-color: #45284c; /* Purple header background color */
      color: #fff; /* White text color */
      text-align: center;
      padding: 10px;
      border-bottom: 1px solid #000;
    }
    .chatroom-messages {
      min-height: 200px;
      padding: 10px;
      overflow-y: auto;
      background-color: #45284c; /* Purple background color */
    }
    .chatroom-messages div {
      background-color: #000; /* Black message background color */
      border-radius: 5px;
      margin: 5px 0;
      padding: 10px;
      word-wrap: break-word;
      color: #fff; /* White text color */
    }
    .chatroom-input {
      padding: 10px;
      display: flex;
      border-top: 1px solid #45284c; /* Purple border */
    }
    input[type="text"] {
      flex: 1;
      padding: 10px;
      border: none;
      border-radius: 5px;
      background-color: #45284c; /* Purple input background color */
      color: #fff; /* White text color */
    }
    button {
      background-color: #45284c; /* Purple button background color */
      color: #fff; /* White text color */
      border: none;
      border-radius: 5px;
      padding: 10px 20px;
      cursor: pointer;
      margin-left: 10px;
    }
  </style>
</head>
<body>
  <!-- ... (your existing HTML structure) ... -->
</body>
</html>

Learning College Board Pseudo Code

College Board uses a kind-of programming language in its Multiple Choice exam. There are thousands of different programming languages have been created, and more are being created every year. College Board has designed a pseudo code, a non operational programming language, to highlight concepts that it wants every student to learn.

College Board is trying to remain neutral and build Computer Science Principles off of any language, thus the Teacher is left to pick the language(s) according to application and curriculum.

College Board Pseudo Code Exam Reference Sheet

Comparison of CB Pseudo Code to Python with descriptions

Command Vocabulary Pseudo code Python Purpose
Output DISPLAY(expression) print(expression, end=” “) Displays the value of expression, followed by a space. Python defaults to newline, thus the end=” “
Input a ← INPUT() a = input(prompt) Accepts a value from the user and returns it to the variable a.
Assignment a ← expression a = expression Evaluates expression and assigns the result to the variable a.
Selection IF (expression) if expression: Run commands in the code block associated with the selection
Iteration n times REPEAT n TIMES for i in range(n): Repeat commands in the code block associated withe the iteration n times
Iteration expression REPEAT UNTIL (expression) while expression: Repeat commands in the code block associated withe the iteration while expression is true
List Assignment list ← [expression1, expression2, expression3] list = [expression1, expression2, expression3] Assigns 3 values to list, value can be literal or expressions
First index in List list[1] list[0] Access the 1st element in the list[]. FYI, most programming languages start a zero.
Last index in List list[LENGTH(list)] list[len(list) - 1] Access the last element in the list[]. If you start at zero, last element is length - 1.
Define Procedure PROCEDURE name (parameter) def name(parameter): Create a procedure containing a sequence of programming instructions.
Expression equals a = b a == b Evaluate if assigned value of a equals assigned value of b
Expression not equals a ≠ b a != b Evaluate if assigned value of a is NOT equal to assigned value of b

Pseudo code IF Code Block

a ← 1
b ← 1

IF (a = b) {
   DISPLAY("A equals B")
}
# Python code if block to match Pseudo Code
a = 1
b = 1
if (a == b):
    # Python uses indent to establish code block, Teacher use tab key
    print("A equals B")
A equals B

Hacks

Key Learnings. It is very important that you become fluent in “ Vocabulary” and researching problems.

  • Code a JavaScript cell, this must start with %%js%% in first line of cell. Match the IF condition example in this blog.

  • Code a REPEAT n TIMES as described in comparison sheet in Pseudo code, Python, and JavaScript. Be sure to comment your code.
    • REPEAT 100 TIMES
    • Sum all the numpers
    • PRINT the result
  • Reflect on our PSEUDO code and how it helped with your problem solving in these hacks.

  • Maked efinition for: code block, sequence, selections, iteration. Consider a strategy to remember Pseudo Code, Python and JavaScript for these definitions.
<html>
<head>
    <title>Discussion Board</title>
    <style>
        /* Basic styling for the discussion board */
        body {
            font-family: Arial, sans-serif;
            margin: 20px;
        }
        .discussion {
            border: 1px solid #ccc;
            padding: 10px;
            margin: 10px 0;
        }
        .post {
            border: 1px solid #eee;
            padding: 10px;
            margin: 10px 0;
        }
        .comment {
            border: 1px solid #f0f0f0;
            padding: 5px;
            margin: 5px 0;
        }
    </style>
</head>
<body>
    <h1>Discussion Board</h1>
    <!-- Create a new discussion form -->
    <h2>Create a New Discussion</h2>
    <form id="create-discussion-form">
        <input type="text" id="discussion-title" placeholder="Discussion Title">
        <button type="submit">Submit</button>
    </form>
    <!-- List of discussions -->
    <div id="discussion-list"></div>
    <script>
        // Function to fetch and display discussions
        function fetchDiscussions() {
            fetch('/api/discussions/list', { method: 'GET' })
                .then(response => response.json())
                .then(data => {
                    const discussionList = document.getElementById('discussion-list');
                    discussionList.innerHTML = '';
                    data.forEach(discussion => {
                        // Create a discussion container
                        const discussionDiv = document.createElement('div');
                        discussionDiv.className = 'discussion';
                        // Add the discussion title
                        const title = document.createElement('h3');
                        title.innerText = discussion.title;
                        discussionDiv.appendChild(title);
                        // Add a form for creating a post
                        const postForm = document.createElement('form');
                        postForm.className = 'create-post-form';
                        postForm.innerHTML = `
                            <input type="text" placeholder="New Post">
                            <button type="submit">Post</button>
                        `;
                        // Add the post form to the discussion container
                        discussionDiv.appendChild(postForm);
                        // Add an empty div to display posts
                        const postContainer = document.createElement('div');
                        postContainer.className = 'post-container';
                        // Event listener to create a new post
                        postForm.addEventListener('submit', function (e) {
                            e.preventDefault();
                            const newPostInput = postForm.querySelector('input');
                            const newPost = newPostInput.value;
                            if (newPost) {
                                // Call the create post API and then refresh the discussion
                                createPost(discussion.title, newPost);
                                fetchDiscussions();
                                newPostInput.value = '';
                            }
                        });
                        // Append the post container to the discussion container
                        discussionDiv.appendChild(postContainer);
                        // Fetch and display posts for this discussion
                        fetchPosts(discussion.title, postContainer);
                        // Append the discussion container to the list
                        discussionList.appendChild(discussionDiv);
                    });
                });
        }
        // Function to create a new post
        function createPost(discussionTitle, content) {
            fetch(`/api/discussions/${discussionTitle}/create`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ 'content': content }),
            });
        }
        // Function to fetch and display posts for a discussion
        function fetchPosts(discussionTitle, postContainer) {
            fetch(`/api/discussions/${discussionTitle}/list`, { method: 'GET' })
                .then(response => response.json())
                .then(data => {
                    const posts = data;
                    postContainer.innerHTML = '';
                    posts.forEach(post => {
                        // Create a post container
                        const postDiv = document.createElement('div');
                        postDiv.className = 'post';
                        // Add the post content
                        const content = document.createElement('p');
                        content.innerText = post.content;
                        postDiv.appendChild(content);
                        // Add a form for creating a comment
                        const commentForm = document.createElement('form');
                        commentForm.className = 'create-comment-form';
                        commentForm.innerHTML = `
                            <input type="text" placeholder="Leave a Comment">
                            <button type="submit">Comment</button>
                        `;
                        // Add the comment form to the post container
                        postDiv.appendChild(commentForm);
                        // Add an empty div to display comments
                        const commentContainer = document.createElement('div');
                        commentContainer.className = 'comment-container';
                        // Event listener to create a new comment
                        commentForm.addEventListener('submit', function (e) {
                            e.preventDefault();
                            const newCommentInput = commentForm.querySelector('input');
                            const newComment = newCommentInput.value;
                            if (newComment) {
                                // Call the create comment API and then refresh the comments
                                createComment(discussionTitle, post.post_id, newComment);
                                fetchComments(discussionTitle, post.post_id, commentContainer);
                                newCommentInput.value = '';
                            }
                        });
                        // Append the post container to the post container
                        postContainer.appendChild(postDiv);
                        // Append the comment container to the post container
                        postContainer.appendChild(commentContainer);
                        // Fetch and display comments for this post
                        fetchComments(discussionTitle, post.post_id, commentContainer);
                    });
                });
        }
        // Function to create a new comment
        function createComment(discussionTitle, postId, content) {
            fetch(`/api/discussions/${discussionTitle}/${postId}/comment`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ 'content': content }),
            });
        }
        // Function to fetch and display comments for a post
        function fetchComments(discussionTitle, postId, commentContainer) {
            fetch(`/api/discussions/${discussionTitle}/${postId}/comment`, { method: 'GET' })
                .then(response => response.json())
                .then(data => {
                    const comments = data.comments;
                    commentContainer.innerHTML = '';
                    comments.forEach(comment => {
                        // Create a comment container
                        const commentDiv = document.createElement('div');
                        commentDiv.className = 'comment';
                        // Add the comment content
                        const content = document.createElement('p');
                        content.innerText = comment.content;
                        commentDiv.appendChild(content);
                        // Append the comment container to the comment container
                        commentContainer.appendChild(commentDiv);
                    });
                });
        }
        // Initial fetch of discussions
        fetchDiscussions();
    </script>
</body>
</html>
Discussion Board

Discussion Board

Create a New Discussion

from flask import Blueprint, request, jsonify
from flask_restful import Api, Resource
from flask_cors import CORS

discussion_api = Blueprint('discussion_api', __name__, url_prefix='/api/discussions')
api = Api(discussion_api)
CORS(discussion_api, resources={r"/api/*": {"origins": "*"}})

# Sample data
discussions = []
posts = []
comments = []

class DiscussionAPI:
    class CreateDiscussion(Resource):
        def post(self):
            data = request.json
            discussion = {
                'title': data.get('title'),
                'posts': []  # Store posts related to this discussion
            }
            discussions.append(discussion)
            return jsonify({"message": "Discussion created successfully"})

    class ListDiscussions(Resource):
        def get(self):
            return jsonify(discussions)

    class CreatePost(Resource):
        def post(self, discussion_id):
            data = request.json
            post = {
                'content': data.get('content'),
                'comments': []  # Store comments related to this post
            }
            discussion = next((d for d in discussions if d['title'] == discussion_id), None)
            if discussion:
                discussion['posts'].append(post)
                posts.append(post)
                return jsonify({"message": "Post created successfully"})
            return jsonify({"message": "Discussion not found"}, 404)

    class CreateComment(Resource):
        def post(self, discussion_id, post_id):
            data = request.json
            comment = {
                'content': data.get('content')
            }
            discussion = next((d for d in discussions if d['title'] == discussion_id), None)
            if discussion:
                post = next((p for p in discussion['posts'] if p == post_id), None)
                if post:
                    post['comments'].append(comment)
                    comments.append(comment)
                    return jsonify({"message": "Comment created successfully"})
            return jsonify({"message": "Discussion or post not found"}, 404)

api.add_resource(DiscussionAPI.CreateDiscussion, '/create')
api.add_resource(DiscussionAPI.ListDiscussions, '/list')
api.add_resource(DiscussionAPI.CreatePost, '/<string:discussion_id>/create')
api.add_resource(DiscussionAPI.CreateComment, '/<string:discussion_id>/<string:post_id>/comment')

if __name__ == "__main__":
    # Run the Flask app
    app.run(debug=True)

comments: false layout: default title: Discussion Board permalink: /discussionboard —

Joke HaHa Boohoo
---
comments: false
layout: default
title: Discussion Board
permalink: /discussionboard
---

<html>
<table>
  <thead>
  <tr>
    <th>Joke</th>
    <th>HaHa</th>
    <th>Boohoo</th>
  </tr>
  </thead>
  <tbody id="result">
    <!-- javascript generated data -->
  </tbody>
</table>
<script>
// prepare HTML defined "result" container for new output
const resultContainer = document.getElementById("result");
// keys for joke reactions
const HAHA = "haha";
const BOOHOO = "boohoo";
// prepare fetch urls
const url = "https://chat.stu.nighthawkcodingsociety.com/api/jokes";
const like_url = url + "/like/";  // haha reaction
const jeer_url = url + "/jeer/";  // boohoo reaction
// prepare fetch GET options
const options = {
  method: 'GET', // *GET, POST, PUT, DELETE, etc.
  mode: 'cors', // no-cors, *cors, same-origin
  cache: 'default', // *default, no-cache, reload, force-cache, only-if-cached
  credentials: 'omit', // include, *same-origin, omit
  headers: {
    'Content-Type': 'application/json'
    // 'Content-Type': 'application/x-www-form-urlencoded',
  },
};
// prepare fetch PUT options, clones with JS Spread Operator (...)
const put_options = {...options, method: 'PUT'}; // clones and replaces method
// fetch the API
fetch(url, options)
  // response is a RESTful "promise" on any successful fetch
  .then(response => {
    // check for response errors
    if (response.status !== 200) {
        error('GET API response failure: ' + response.status);
        return;
    }
    // valid response will have JSON data
    response.json().then(data => {
        console.log(data);
        for (const row of data) {
          // make "tr element" for each "row of data"
          const tr = document.createElement("tr");
          // td for joke cell
          const joke = document.createElement("td");
            joke.innerHTML = row.id + ". " + row.joke;  // add fetched data to innerHTML
          // td for haha cell with onclick actions
          const haha = document.createElement("td");
            const haha_but = document.createElement('button');
            haha_but.id = HAHA+row.id   // establishes a HAHA JS id for cell
            haha_but.innerHTML = row.haha;  // add fetched "haha count" to innerHTML
            haha_but.onclick = function () {
              // onclick function call with "like parameters"
              reaction(HAHA, like_url+row.id, haha_but.id);  
            };
            haha.appendChild(haha_but);  // add "haha button" to haha cell
          // td for boohoo cell with onclick actions
          const boohoo = document.createElement("td");
            const boohoo_but = document.createElement('button');
            boohoo_but.id = BOOHOO+row.id  // establishes a BOOHOO JS id for cell
            boohoo_but.innerHTML = row.boohoo;  // add fetched "boohoo count" to innerHTML
            boohoo_but.onclick = function () {
              // onclick function call with "jeer parameters"
              reaction(BOOHOO, jeer_url+row.id, boohoo_but.id);  
            };
            boohoo.appendChild(boohoo_but);  // add "boohoo button" to boohoo cell
          // this builds ALL td's (cells) into tr (row) element
          tr.appendChild(joke);
          tr.appendChild(haha);
          tr.appendChild(boohoo);
          // this adds all the tr (row) work above to the HTML "result" container
          resultContainer.appendChild(tr);
        }
    })
})
// catch fetch errors (ie Nginx ACCESS to server blocked)
.catch(err => {
  error(err + " " + url);
});
// Reaction function to likes or jeers user actions
function reaction(type, put_url, elemID) {
  // fetch the API
  fetch(put_url, put_options)
  // response is a RESTful "promise" on any successful fetch
  .then(response => {
    // check for response errors
    if (response.status !== 200) {
        error("PUT API response failure: " + response.status)
        return;  // api failure
    }
    // valid response will have JSON data
    response.json().then(data => {
        console.log(data);
        // Likes or Jeers updated/incremented
        if (type === HAHA) // like data element
          document.getElementById(elemID).innerHTML = data.haha;  // fetched haha data assigned to haha Document Object Model (DOM)
        else if (type === BOOHOO) // jeer data element
          document.getElementById(elemID).innerHTML = data.boohoo;  // fetched boohoo data assigned to boohoo Document Object Model (DOM)
        else
          error("unknown type: " + type);  // should never occur
    })
  })
  // catch fetch errors (ie Nginx ACCESS to server blocked)
  .catch(err => {
    error(err + " " + put_url);
  });
}
// Something went wrong with actions or responses
function error(err) {
  // log as Error in console
  console.error(err);
  // append error to resultContainer
  const tr = document.createElement("tr");
  const td = document.createElement("td");
  td.innerHTML = err;
  tr.appendChild(td);
  resultContainer.appendChild(tr);
}
</script>
</html>


%%html
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Chatroom</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #301934;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            margin: 0;
        }

        .chatroom {
            width: 700px;
            height: 600px;
            background-color: #1a1a1a;
            border-radius: 10px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
            overflow: hidden;
            display: flex;
            flex-direction: column;
        }

        .chatroom-header {
            background-color: #301934;
            color: #fff;
            text-align: center;
            padding: 10px;
            border-bottom: 1px solid #1a1a1a;
        }

        .chatroom-messages {
            flex-grow: 1;
            padding: 10px;
            overflow-y: auto;
            background-color: #1a1a1a;
            scrollbar-width: thin; /* for Firefox */
            scrollbar-color: #301934 #1a1a1a; /* for Firefox */
        }

        .chatroom-messages::-webkit-scrollbar {
            width: 8px; /* for Chrome, Safari, and Opera */
        }

        .chatroom-messages::-webkit-scrollbar-thumb {
            background-color: #301934; /* for Chrome, Safari, and Opera */
        }

        .chatroom-messages div {
            background-color: #1a1a1a;
            border-radius: 5px;
            margin: 5px 0;
            padding: 10px;
            word-wrap: break-word;
            color: #fff;
        }

        .chatroom-input {
            padding: 10px;
            display: flex;
            border-top: 1px solid #301934;
            background-color: #1a1a1a;
        }

        input[type="text"] {
            flex: 1;
            padding: 10px;
            border: none;
            border-radius: 5px;
            background-color: #301934;
            color: #fff;
        }

        button {
            background-color: #301934;
            color: #fff;
            border: none;
            border-radius: 5px;
            padding: 10px 20px;
            cursor: pointer;
            margin-left: 10px;
        }

        #toggleModeButton, #moodCheck {
            background-color: #301934;
            color: #fff;
        }

        #toggleModeButton:hover, #moodCheck:hover {
            background-color: #301934;
        }
    </style>
</head>
<body>
    <div class="chatroom">
        <div class="chatroom-header">
            <h1>Chatroom</h1>
        </div>
        <div class="chatroom-messages" id="chatroom-messages">
            <!-- Messages will be displayed here -->
        </div>
        <div class="chatroom-input">
            <input type="text" id="message" placeholder="Type your message" onkeypress="handleKeyPress(event)">
            <button id="send" onclick="sendMessage()">Send</button>
            <button id="toggleModeButton" onclick="toggleMode()">Toggle Mode</button>
            <button id="moodCheck">Neutral Mood</button>
Chatroom

Chatroom