Playground
Breadcrumb: /This page will help me learn new topics
%%html
<script>
fetch("https://cataas.com/cat")
.then(response => response.blob())
.then(blob => {
const imgUrl = URL.createObjectURL(blob);
const img = document.createElement('img');
img.src = imgUrl;
img.alt = "Random Cat";
img.style.maxWidth = "300px";
document.body.appendChild(img);
})
.catch(error => console.error("Error fetching cat image:", error));
</script>
Dictionary
Notes
API gives us a response which contains lots of data. In This code we are using the JSON data from the API
example at top of script block in below code
%%html
<html>
<head>
<title>Dict</title>
</head>
<body>
<input type="text" id="search" placeholder="Search for a word">
<button onclick="FetchData()">Search</button><br>
<div id="result"></div>
<script>
//Example of json Output
//{word: 'hello', phonetics: Array(3), meanings: Array(3), license: {…}, sourceUrls: Array(1)}length
async function FetchData() {
document.getElementById("result").innerHTML = "";
try {
const word = document.getElementById("search").value.toLowerCase();
if (!word) {
alert("Please enter a word to search.");
return;
}
if (word.includes(" ")) {
document.getElementById("result").innerHTML = "<p>Please enter a single word without spaces.</p>";
return;
}
const response = await fetch(`https://api.dictionaryapi.dev/api/v2/entries/en/${word}`);
if (response.status === 404) {
document.getElementById("result").innerHTML = "<p>Word not found.</p>";
throw new Error("word not found");
return;
}
if (response.status === 429) {
document.getElementById("result").innerHTML = "<p>Too many requests. Please try again later.</p>";
throw new Error("Too many requests. Please try again later.");
return;
}
if (response.status === 500) {
document.getElementById("result").innerHTML = "<p>Server error. Please try again later.</p>";
throw new Error("Server error. Please try again later.");
return;
}
if (!response.ok) {
console.log(response)
throw new Error("Network response was not ok");
}
const data = await response.json();
const meaning = data[0].meanings[0];
const input = document.getElementById("search");
const resultDiv = document.getElementById("result");
console.log(data)
console.log("Definition:", meaning.definitions[0].definition);
resultDiv.innerHTML = `
<h2>Word: ${data[0].word}</h2>
<p><strong>Definition:</strong> ${meaning.definitions[0].definition}</p>
<p><strong>Part of Speech:</strong> ${meaning.partOfSpeech}</p>
`;
}
catch (error) {
console.error("Fetch error:", error);
}
}
</script>
</body>
</html>
Bell API made on flask server
Make sure flask server is active
%%html
<!-- Only Works On Local Host-->
<body>
<div id="BellOutput"></div>
</body>
<script>
let countdownSeconds = 0; // current countdown in seconds
let currentPeriod = null;
let periodDuration = null;
// Convert "HH:MM:SS" string to total seconds
function parseTimeString(timeStr) {
const [hours, minutes, seconds] = timeStr.split(':').map(Number);
return hours * 3600 + minutes * 60 + seconds;
}
// Convert seconds to "HH:MM:SS"
function formatTime(seconds) {
const h = Math.floor(seconds / 3600).toString().padStart(2, '0');
const m = Math.floor((seconds % 3600) / 60).toString().padStart(2, '0');
const s = Math.floor(seconds % 60).toString().padStart(2, '0');
return `${h}:${m}:${s}`;
}
// Update the HTML display
function updateDisplay() {
const bellOutputDiv = document.getElementById('BellOutput');
bellOutputDiv.innerHTML = `
<h2>Current Period Time Left: ${formatTime(countdownSeconds)}</h2>
<h3>Current Period: ${currentPeriod ?? "N/A"}</h3>
<h4>Duration: ${periodDuration ?? "N/A"}</h4>
`;
}
// Fetch data from API
async function fetchData() {
try {
const response = await fetch('http://172.28.121.230:8087/api/bell');
if (!response.ok) throw new Error('Network response was not ok');
const data = await response.json();
if (data.current_period) {
countdownSeconds = parseTimeString(data.current_period.time_left);
currentPeriod = data.current_period.period.period;
periodDuration = data.current_period.period.time;
}
updateDisplay();
} catch (error) {
console.error('Error fetching data:', error);
}
}
// Local countdown every second
setInterval(() => {
if (countdownSeconds > 0) {
countdownSeconds--;
updateDisplay();
}
}, 1000);
// Align fetch to the start of each minute
function startMinuteAlignedFetch() {
const now = new Date();
const msToNextMinute = (60 - now.getSeconds()) * 1000 - now.getMilliseconds();
setTimeout(() => {
fetchData(); // fetch exactly at start of minute
setInterval(fetchData, 60000); // then every minute
}, msToNextMinute);
}
// Initial fetch immediately
fetchData();
startMinuteAlignedFetch();
</script>