// ==UserScript== // @name the_Moodle_major // @namespace Violentmonkey Scripts // @match https://lms.uj.ac.za/mod/quiz/attempt.php* // @match https://lms.uj.ac.za/mod/quiz/review.php* // @grant none // @version 4.0 // @author Nexus Elite Optimum // @description 4/9/2024, 11:13:57 PM // ==/UserScript== (function () { "use strict"; function roundNumber(number, decimalPlaces) { // Calculate the scaling factor based on the desired decimal places const scale = 10 ** decimalPlaces; // Multiply the number by the scaling factor, round up, and then divide by the scaling factor return Math.ceil(number * scale) / scale; } function findCircleIntersections(circle1, circle2) { // Extract circle parameters const [x1, y1, r1] = circle1; const [x2, y2, r2] = circle2; // Handle edge case where circles are identical if (x1 === x2 && y1 === y2 && r1 === r2) { return "Circles are identical"; } // Calculate distance between centers const distance = Math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2); // Handle cases with no intersection if (distance > r1 + r2 || distance < Math.abs(r1 - r2)) { return "Circles do not intersect"; } // Calculate intersection parameters const a = (r1 ** 2 - r2 ** 2 + distance ** 2) / (2 * distance); const h = Math.sqrt(r1 ** 2 - a ** 2); // Calculate the point where the line connecting the centers intersects the radical line const x3 = x1 + (a / distance) * (x2 - x1); const y3 = y1 + (a / distance) * (y2 - y1); // Calculate intersection points const intersection1 = [ roundNumber(x3 + (h * (y2 - y1)) / distance, 5), roundNumber(y3 - (h * (x2 - x1)) / distance, 5), ]; const intersection2 = [ roundNumber(x3 - (h * (y2 - y1)) / distance, 5), roundNumber(y3 + (h * (x2 - x1)) / distance, 5), ]; // Handle case with one intersection point if (distance === r1 + r2 || distance === Math.abs(r1 - r2)) { return [intersection1]; } return [intersection1, intersection2]; } function findCircleCenterAndRadius(point, knownCenterValue, isCenterXKnown) { // Extract point coordinates const [px, py] = point; // Calculate radius and unknown center coordinate if (isCenterXKnown) { // Center is (knownCenterValue, y) const cx = knownCenterValue; const radius = Math.sqrt((px - cx) ** 2 + (py - 0) ** 2); const cy = 0; // Since the center lies on the x-axis return { center: [cx, cy], radius }; } else { // Center is (x, knownCenterValue) const cy = knownCenterValue; const radius = Math.sqrt((px - 0) ** 2 + (py - cy) ** 2); const cx = 0; // Since the center lies on the y-axis return { center: [cx, cy], radius }; } } /* * Calculates the center coordinates and radius of a circle. * * @param {number} x - The known x-coordinate of the center or null if unknown. * @param {number} y - The known y-coordinate of the center or null if unknown. * @param {number} x2 - The x-coordinate of the second point on the circle. * @param {number} y2 - The y-coordinate of the second point on the circle. * @return {object} An object containing the center coordinates and radius of the circle. */ function findCircle(x, y, x2, y2) { // Handle case where x is known if (x !== null) { // Calculate the radius squared using the distance formula let rSquared = Math.pow(x2 - x, 2) + Math.pow(y2 - 0, 2); // Solve the quadratic equation to find the y-coordinate of the center // (x - x1)^2 + (y - y1)^2 = r^2 // (y - 0)^2 = r^2 - (x - x1)^2 // y^2 = r^2 - (x - x1)^2 // y = ±sqrt(r^2 - (x - x1)^2) let yCenter = Math.sqrt(rSquared - Math.pow(x - 1, 2)); // Return the center coordinates and radius return { x: x, y: yCenter, radius: Math.sqrt(rSquared), }; } // Handle case where y is known if (y !== null) { // Calculate the radius squared using the distance formula let rSquared = Math.pow(x2 - 1, 2) + Math.pow(y2 - y, 2); // Solve the quadratic equation to find the x-coordinate of the center // (x - x1)^2 + (y - y1)^2 = r^2 // (x - 1)^2 = r^2 - (y - y1)^2 // x^2 - 2x + 1 = r^2 - (y - y1)^2 // x^2 - 2x + (1 - r^2 + (y - y1)^2) = 0 let a = 1; let b = -2; let c = 1 - rSquared + Math.pow(y - 0, 2); let xCenter = (-b + Math.sqrt(Math.pow(b, 2) - 4 * a * c)) / (2 * a); // Return the center coordinates and radius return { x: xCenter, y: y, radius: Math.sqrt(rSquared), }; } // Handle case where neither x nor y is known throw new Error( "Either the x-coordinate or y-coordinate of the center must be known." ); } function calculateCircle(x2, y2, centerCoord, isXCenter) { // One point is always (1,0) const x1 = 1; const y1 = 0; let centerX, centerY, radius; if (isXCenter) { centerX = centerCoord; // Calculate centerY using the midpoint formula const midX = (x1 + x2) / 2; const midY = (y1 + y2) / 2; const slope = (y2 - y1) / (x2 - x1); const perpSlope = -1 / slope; centerY = perpSlope * (centerX - midX) + midY; } else { centerY = centerCoord; // Calculate centerX using the midpoint formula const midX = (x1 + x2) / 2; const midY = (y1 + y2) / 2; const slope = (y2 - y1) / (x2 - x1); const perpSlope = -1 / slope; centerX = (centerY - midY) / perpSlope + midX; } // Calculate radius using distance formula radius = Math.sqrt(Math.pow(centerX - x1, 2) + Math.pow(centerY - y1, 2)); return { center: { x: centerX, y: centerY }, radius: radius, }; } function calculateSWRRadius(real, imag) { // Calculate the reflection coefficient const numeratorReal = real - 1; const numeratorImag = imag; const denominatorReal = real + 1; const denominatorImag = imag; const numeratorMagnitude = Math.sqrt( numeratorReal ** 2 + numeratorImag ** 2 ); const denominatorMagnitude = Math.sqrt( denominatorReal ** 2 + denominatorImag ** 2 ); // Calculate the magnitude of the reflection coefficient const reflectionCoefficientMagnitude = numeratorMagnitude / denominatorMagnitude; return reflectionCoefficientMagnitude; } function calculateSWR(radius) { if (radius < 0 || radius > 1) { throw new Error("Radius must be between 0 and 1."); } const swr = (1 + radius) / (1 - radius); return swr; } function radiusToReal(radius) { return roundNumber((1 - radius) / radius, 3); } function radiusToImaginary(radius) { return roundNumber(1 / radius, 3); } function complexToFloat(complexStr) { const regex = /^([+-]?\d*\.?\d+)?([+-]?j\d*\.?\d*)?$/; const match = complexStr.match(regex); if (!match) { throw new Error("Invalid complex number format"); } const realPart = match[1] ? parseFloat(match[1]) : 0; let imaginaryPart = 0; if (match[2]) { const imagStr = match[2].replace("j", ""); if (imagStr === "+" || imagStr === "-") { imaginaryPart = parseFloat(imagStr + "1"); } else { imaginaryPart = parseFloat(imagStr); } } return { x: parseFloat(realPart), y: parseFloat(imaginaryPart) }; } function complexCalc(val1, val2, operation) { const num1 = complexToFloat(val1); const num2 = complexToFloat(val2); let real = 0; let imaginary = 0; switch (operation) { case "+": real = num1.x + num2.x; imaginary = num1.y + num2.y; break; case "-": real = num1.x - num2.x; imaginary = num1.y - num2.y; break; case "*": real = num1.x * num2.x - num1.y * num2.y; imaginary = num1.x * num2.y + num1.y * num2.x; break; case "/": const denom = num2.x * num2.x + num2.y * num2.y; if (denom === 0) { throw new Error("Division by zero"); } real = (num1.x * num2.x + num1.y * num2.y) / denom; imaginary = (num1.y * num2.x - num1.x * num2.y) / denom; break; default: throw new Error("Invalid operation"); } return `${real}${imaginary < 0 ? "-" : "+"}j${Math.abs(imaginary)}`; } function absValue(real, imaginary) { return Math.sqrt(real * real + imaginary * imaginary); } function radiansToDegrees(radians) { return radians * (180 / Math.PI); } function degreesToRadians(degrees) { return degrees * (Math.PI / 180); } function findSecondIntersection(x1, y1, r1, x2, y2, r2, x3, y3) { // Function to calculate distance between two points function distance(x1, y1, x2, y2) { return Math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2); } // Check if the given point is actually on both circles if ( Math.abs(distance(x1, y1, x3, y3) - r1) > 1e-6 || Math.abs(distance(x2, y2, x3, y3) - r2) > 1e-6 ) { return "Given point is not on both circles"; } // Calculate the distance between circle centers const d = distance(x1, y1, x2, y2); // Check if circles are identical if (d < 1e-6 && Math.abs(r1 - r2) < 1e-6) { return "Circles are identical, infinite intersection points"; } // Check if circles don't intersect or one circle is contained within the other if (d > r1 + r2 || d < Math.abs(r1 - r2)) { return "No intersection points"; } // Calculate the second intersection point const a = (r1 * r1 - r2 * r2 + d * d) / (2 * d); const h = Math.sqrt(r1 * r1 - a * a); const x4 = x1 + (a * (x2 - x1)) / d; const y4 = y1 + (a * (y2 - y1)) / d; // Calculate both potential intersection points const ix1 = x4 + (h * (y2 - y1)) / d; const iy1 = y4 - (h * (x2 - x1)) / d; const ix2 = x4 - (h * (y2 - y1)) / d; const iy2 = y4 + (h * (x2 - x1)) / d; // Check which point is not the given intersection point if (Math.abs(ix1 - x3) < 1e-6 && Math.abs(iy1 - y3) < 1e-6) { return [ix2, iy2]; } else { return [ix1, iy1]; } } function SIN(val) { return Math.sin(degreesToRadians(val)); } function COS(val) { return Math.cos(degreesToRadians(val)); } function TAN(val) { return Math.tan(degreesToRadians(val)); } function ASIN(val) { return radiansToDegrees(Math.asin(val)); } function ACOS(val) { return radiansToDegrees(Math.acos(val)); } function ATAN(val) { return radiansToDegrees(Math.atan(val)); } // let SWR = 3; // let re = 0.7; // let im = 0.5; // // // Example usage: // const SWR_circle = [0, 0, (SWR - 1) / (SWR + 1)]; // const circle1 = [re / (re + 1), 0, 1 / (re + 1)]; // Center (0, 0), radius 5 // const circle2 = [1, 1 / im, 1 / im]; // Center (5, 0), radius 3 // const intersections = findCircleIntersections(circle1, circle2); // console.log(intersections); // Output: [[3, -4], [3, 4]] // Example usage: // const point = [intersections[0][0], intersections[0][1]]; // const knownCenterX = 1; // const resultX = findCircleCenterAndRadius(point, knownCenterX, true); // console.log(resultX); // Output: { center: [2, 0], radius: 3.5355339059327378 } // console.log(`Im Value: ${radiusToImaginary(resultX.radius)}`); // const knownCenterY = 0; // const resultY = findCircleCenterAndRadius(point, knownCenterY, false); // console.log(resultY); // Output: { center: [0, -1], radius: 2.5 } // console.log(`Real Value: ${radiusToReal(resultY.radius)}`); // Example usage: // console.log( // calculateCircle(intersections[1][0], intersections[1][1], 0, false) // ); // Center X is 2 // console.log(calculateCircle(3, 2, 1, false)); // Center Y is 1 function currentStatus2(color) { // Define valid colors const validColors = ["green", "red", "yellow"]; // Check if the provided color is valid if (!validColors.includes(color)) { console.error( 'Invalid color specified. Use "green", "red", or "yellow".' ); return; } // Create a new div element for the status indicator var statusIndicator = document.createElement("div"); // Apply styles to make it a circle floating at the top statusIndicator.style.cssText = ` position: fixed; top: 0; right: 200px; width: 15px; height: 2px; background-color: ${color}; box-shadow: rgba(0, 0, 0, 0.2) 0px 2px 4px; z-index: 1000000000000; `; // Add an ID to the indicator or replace the existing one statusIndicator.id = "statusIndicator-3"; // Remove any existing status indicators before appending the new one var existingIndicator = document.getElementById("statusIndicator-3"); if (existingIndicator) { existingIndicator.parentNode.removeChild(existingIndicator); } // Append the status indicator to the body document.body.appendChild(statusIndicator); } function currentStatus(color) { // Define valid colors const validColors = ["green", "red", "yellow"]; // Check if the provided color is valid if (!validColors.includes(color)) { console.error( 'Invalid color specified. Use "green", "red", or "yellow".' ); return; } // Create a new div element for the status indicator var statusIndicator = document.createElement("div"); // Apply styles to make it a circle floating at the top statusIndicator.style.cssText = ` position: fixed; top: 50%; left: 0; width: 2px; height: 12px; background-color: ${color}; box-shadow: rgba(0, 0, 0, 0.2) 0px 2px 4px; z-index: 1000000000000; `; // Add an ID to the indicator or replace the existing one statusIndicator.id = "statusIndicator"; // Remove any existing status indicators before appending the new one var existingIndicator = document.getElementById("statusIndicator"); if (existingIndicator) { existingIndicator.parentNode.removeChild(existingIndicator); } // Append the status indicator to the body document.body.appendChild(statusIndicator); } function currentStatusMistral(color) { // Define valid colors const validColors = ["green", "red", "yellow"]; // Check if the provided color is valid if (!validColors.includes(color)) { console.error( 'Invalid color specified. Use "green", "red", or "yellow".' ); return; } // Create a new div element for the status indicator var statusIndicator = document.createElement("div"); // Apply styles to make it a circle floating at the top statusIndicator.style.cssText = ` position: fixed; top: 0; left: 200px; width: 15px; height: 2px; background-color: ${color}; box-shadow: rgba(0, 0, 0, 0.2) 0px 2px 4px; z-index: 1000000000000; `; // Add an ID to the indicator or replace the existing one statusIndicator.id = "statusIndicatorMistral"; // Remove any existing status indicators before appending the new one var existingIndicator = document.getElementById("statusIndicatorMistral"); if (existingIndicator) { existingIndicator.parentNode.removeChild(existingIndicator); } // Append the status indicator to the body document.body.appendChild(statusIndicator); } function top_blast() { var statusIndicator = document.createElement("div"); // Apply styles to make it a circle floating at the top statusIndicator.style.cssText = ` position: fixed; top: 0px; left: 0; width: 100%; z-index: 2147483647; font-size: 10px; color: rgb(77, 77, 77); height: 12px; background-color: #4c3821; `; // Add an ID to the indicator or replace the existing one statusIndicator.id = "top-block"; // Remove any existing status indicators before appending the new one var existingIndicator = document.getElementById("top-block"); if (existingIndicator) { existingIndicator.parentNode.removeChild(existingIndicator); } // Append the status indicator to the body document.body.appendChild(statusIndicator); } function dispAns(ans) { // Create a new div element for the status indicator var statusIndicator = document.createElement("div"); // Apply styles to make it a circle floating at the top statusIndicator.style.cssText = ` position: fixed; bottom: 0.5px; left: 2px; width: max-content; z-index: 1000000000000000000; font-size:10px; color:#4d4d4d; `; statusIndicator.innerHTML = ans; // Add an ID to the indicator or replace the existing one statusIndicator.id = "ans-disp"; // Remove any existing status indicators before appending the new one var existingIndicator = document.getElementById("ans-disp"); if (existingIndicator) { existingIndicator.parentNode.removeChild(existingIndicator); } // Append the status indicator to the body document.body.appendChild(statusIndicator); } function dispAns2(ans) { // Create a new div element for the status indicator var statusIndicator = document.createElement("div"); // Apply styles to make it a circle floating at the top statusIndicator.style.cssText = ` position: fixed; top: 0.5px; right: 2px; width: max-content; z-index: 10000000000; font-size:10px; color:#4d4d4d; background-color:#ffffff; `; statusIndicator.innerHTML = ans; // Add an ID to the indicator or replace the existing one statusIndicator.id = "ans-disp-3-nn"; // Remove any existing status indicators before appending the new one var existingIndicator = document.getElementById("ans-disp-3-nn"); if (existingIndicator) { existingIndicator.parentNode.removeChild(existingIndicator); } // Append the status indicator to the body document.body.appendChild(statusIndicator); } function dispAnsMistral(ans) { // Create a new div element for the status indicator var statusIndicator = document.createElement("div"); // Apply styles to make it a circle floating at the top statusIndicator.style.cssText = ` position: fixed; top: 0.5px; left: 2px; width: max-content; z-index: 10000000000; font-size:10px; color:#5d5d5d; background-color:#ffffff; `; statusIndicator.innerHTML = ans; // Add an ID to the indicator or replace the existing one statusIndicator.id = "ans-disp-3-ms"; // Remove any existing status indicators before appending the new one var existingIndicator = document.getElementById("ans-disp-3-ms"); if (existingIndicator) { existingIndicator.parentNode.removeChild(existingIndicator); } // Append the status indicator to the body document.body.appendChild(statusIndicator); } function copyText(text = "", func = (e) => {}) { // Use the Clipboard API when available if (navigator.clipboard && window.isSecureContext) { // Navigator clipboard api method' return navigator.clipboard .writeText(text) .then(function () { // console.log("Text successfully copied to clipboard"); }) .catch(function (err) { console.error("Could not copy text: ", err); }); } else { // Fallback method for older browsers // Create a new text area element let textArea = document.createElement("textarea"); textArea.value = text; // Make sure it's not visible on the page textArea.style.position = "absolute"; textArea.style.left = "-9999px"; textArea.style.top = "-9999px"; document.body.appendChild(textArea); textArea.focus(); textArea.select(); try { // Attempt to execute the copy command let successful = document.execCommand("copy"); let msg = successful ? "successful" : "unsuccessful"; console.log("Fallback: Copying text command was " + msg); } catch (err) { console.error("Fallback: Oops, unable to copy", err); } // Clean up the text area element from the DOM document.body.removeChild(textArea); } let elem = $(this.target); console.log(elem); console.log(elem.html()); func(); } function mistral(msg_prompt) { currentStatusMistral("yellow"); const url = "https://api.mistral.ai/v1/chat/completions"; const apiKey = "EVmalYbn6ChE2BkUfP9TCZNdMXxqRFGc"; // Replace with your actual API key const headers = { "Content-Type": "application/json", Accept: "application/json", Authorization: `Bearer ${apiKey}`, }; const data = { model: "mistral-large-latest", messages: [ { role: "user", content: msg_prompt, }, ], }; fetch(url, { method: "POST", headers: headers, body: JSON.stringify(data), }) .then((response) => { if (!response.ok) { currentStatusMistral("red"); throw new Error("Network response was not ok " + response.statusText); } return response.json(); }) .then((data) => { const messageContent = data.choices .map((choice) => choice.message.content) .join("\n"); console.log(messageContent); currentStatusMistral("green"); var regex = /<<([^>>]+)>>/g; var matches = messageContent.match(regex); // 'matches' will be an array of strings that match the regular expression //console.log(matches); // Output: ["{53}"] // If you want to extract just the numeric part or the content without the braces var contents = matches.map(function (match) { return match.replace(/<>/g, ""); // Remove the curly braces }); dispAnsMistral(contents); console.log("Mistral Ans: " + contents); $("#ans-disp").css("display", "none"); $("#ans-disp-3-nn").css("display", "none"); $("#ans-disp-3-ms").css("display", "none"); $("#ans-disp-2").css("display", "none"); }) .catch((error) => { console.error("There was a problem with your fetch operation:", error); currentStatusMistral("red"); }); } // currentStatusMistral("red"); function claude(message__ = "Hi", is_test = false) { !is_test ? currentStatus2("yellow") : void 0; const message = message__; fetch("http://127.0.0.1:5000/send-message", { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ message: message }), }) .then((response) => response.json()) .then((data) => { var answer_ = data.message; var regex = /<<([^>>]+)>>/g; var matches = answer_.match(regex); // 'matches' will be an array of strings that match the regular expression // console.log(matches); // Output: ["{53}"] // If you want to extract just the numeric part or the content without the braces var contents = matches.map(function (match) { return match.replace(/<>/g, ""); // Remove the curly braces }); // console.log(answer) currentStatus2("green"); console.log("Claude answer: " + contents); // copyText(contents); dispAns2(contents); }) .catch((error) => { currentStatus2("red"); console.error("Error:", error); }); } // currentStatus2("red"); // try {claude("Return \"{cc}\", I am testing program", true)} // catch(e) {} // Create the importmap script element const importMapScript = document.createElement("script"); importMapScript.type = "importmap"; importMapScript.textContent = JSON.stringify({ imports: { "@google/generative-ai": "https://esm.run/@google/generative-ai", }, }); // Append the importmap to the document document.head.appendChild(importMapScript); // Create the module script element const moduleScript = document.createElement("script"); moduleScript.type = "module"; moduleScript.textContent = ` function roundNumber(number, decimalPlaces) { // Calculate the scaling factor based on the desired decimal places const scale = 10 ** decimalPlaces; // Multiply the number by the scaling factor, round up, and then divide by the scaling factor return Math.ceil(number * scale) / scale; } function findCircleIntersections(circle1, circle2) { // Extract circle parameters const [x1, y1, r1] = circle1; const [x2, y2, r2] = circle2; // Handle edge case where circles are identical if (x1 === x2 && y1 === y2 && r1 === r2) { return "Circles are identical"; } // Calculate distance between centers const distance = Math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2); // Handle cases with no intersection if (distance > r1 + r2 || distance < Math.abs(r1 - r2)) { return "Circles do not intersect"; } // Calculate intersection parameters const a = (r1 ** 2 - r2 ** 2 + distance ** 2) / (2 * distance); const h = Math.sqrt(r1 ** 2 - a ** 2); // Calculate the point where the line connecting the centers intersects the radical line const x3 = x1 + (a / distance) * (x2 - x1); const y3 = y1 + (a / distance) * (y2 - y1); // Calculate intersection points const intersection1 = [ roundNumber(x3 + (h * (y2 - y1)) / distance, 5), roundNumber(y3 - (h * (x2 - x1)) / distance, 5), ]; const intersection2 = [ roundNumber(x3 - (h * (y2 - y1)) / distance, 5), roundNumber(y3 + (h * (x2 - x1)) / distance, 5), ]; // Handle case with one intersection point if (distance === r1 + r2 || distance === Math.abs(r1 - r2)) { return [intersection1]; } return [intersection1, intersection2]; } function findCircleCenterAndRadius(point, knownCenterValue, isCenterXKnown) { // Extract point coordinates const [px, py] = point; // Calculate radius and unknown center coordinate if (isCenterXKnown) { // Center is (knownCenterValue, y) const cx = knownCenterValue; const radius = Math.sqrt((px - cx) ** 2 + (py - 0) ** 2); const cy = 0; // Since the center lies on the x-axis return { center: [cx, cy], radius }; } else { // Center is (x, knownCenterValue) const cy = knownCenterValue; const radius = Math.sqrt((px - 0) ** 2 + (py - cy) ** 2); const cx = 0; // Since the center lies on the y-axis return { center: [cx, cy], radius }; } } /* * Calculates the center coordinates and radius of a circle. * * @param {number} x - The known x-coordinate of the center or null if unknown. * @param {number} y - The known y-coordinate of the center or null if unknown. * @param {number} x2 - The x-coordinate of the second point on the circle. * @param {number} y2 - The y-coordinate of the second point on the circle. * @return {object} An object containing the center coordinates and radius of the circle. */ function findCircle(x, y, x2, y2) { // Handle case where x is known if (x !== null) { // Calculate the radius squared using the distance formula let rSquared = Math.pow(x2 - x, 2) + Math.pow(y2 - 0, 2); // Solve the quadratic equation to find the y-coordinate of the center // (x - x1)^2 + (y - y1)^2 = r^2 // (y - 0)^2 = r^2 - (x - x1)^2 // y^2 = r^2 - (x - x1)^2 // y = ±sqrt(r^2 - (x - x1)^2) let yCenter = Math.sqrt(rSquared - Math.pow(x - 1, 2)); // Return the center coordinates and radius return { x: x, y: yCenter, radius: Math.sqrt(rSquared), }; } // Handle case where y is known if (y !== null) { // Calculate the radius squared using the distance formula let rSquared = Math.pow(x2 - 1, 2) + Math.pow(y2 - y, 2); // Solve the quadratic equation to find the x-coordinate of the center // (x - x1)^2 + (y - y1)^2 = r^2 // (x - 1)^2 = r^2 - (y - y1)^2 // x^2 - 2x + 1 = r^2 - (y - y1)^2 // x^2 - 2x + (1 - r^2 + (y - y1)^2) = 0 let a = 1; let b = -2; let c = 1 - rSquared + Math.pow(y - 0, 2); let xCenter = (-b + Math.sqrt(Math.pow(b, 2) - 4 * a * c)) / (2 * a); // Return the center coordinates and radius return { x: xCenter, y: y, radius: Math.sqrt(rSquared), }; } // Handle case where neither x nor y is known throw new Error( "Either the x-coordinate or y-coordinate of the center must be known." ); } function calculateCircle(x2, y2, centerCoord, isXCenter) { // One point is always (1,0) const x1 = 1; const y1 = 0; let centerX, centerY, radius; if (isXCenter) { centerX = centerCoord; // Calculate centerY using the midpoint formula const midX = (x1 + x2) / 2; const midY = (y1 + y2) / 2; const slope = (y2 - y1) / (x2 - x1); const perpSlope = -1 / slope; centerY = perpSlope * (centerX - midX) + midY; } else { centerY = centerCoord; // Calculate centerX using the midpoint formula const midX = (x1 + x2) / 2; const midY = (y1 + y2) / 2; const slope = (y2 - y1) / (x2 - x1); const perpSlope = -1 / slope; centerX = (centerY - midY) / perpSlope + midX; } // Calculate radius using distance formula radius = Math.sqrt(Math.pow(centerX - x1, 2) + Math.pow(centerY - y1, 2)); return { center: { x: centerX, y: centerY }, radius: radius, }; } function calculateSWRRadius(real, imag) { // Calculate the reflection coefficient const numeratorReal = real - 1; const numeratorImag = imag; const denominatorReal = real + 1; const denominatorImag = imag; const numeratorMagnitude = Math.sqrt(numeratorReal ** 2 + numeratorImag ** 2); const denominatorMagnitude = Math.sqrt( denominatorReal ** 2 + denominatorImag ** 2 ); // Calculate the magnitude of the reflection coefficient const reflectionCoefficientMagnitude = numeratorMagnitude / denominatorMagnitude; return reflectionCoefficientMagnitude; } function calculateSWR(radius) { if (radius < 0 || radius > 1) { throw new Error("Radius must be between 0 and 1."); } const swr = (1 + radius) / (1 - radius); return swr; } function radiusToReal(radius) { return roundNumber((1 - radius) / radius, 3); } function radiusToImaginary(radius) { return roundNumber(1 / radius, 3); } function complexToFloat(complexStr) { const regex = /^([+-]?\d*\.?\d+)?([+-]?j\d*\.?\d*)?$/; const match = complexStr.match(regex); if (!match) { throw new Error("Invalid complex number format"); } const realPart = match[1] ? parseFloat(match[1]) : 0; let imaginaryPart = 0; if (match[2]) { const imagStr = match[2].replace("j", ""); if (imagStr === "+" || imagStr === "-") { imaginaryPart = parseFloat(imagStr + "1"); } else { imaginaryPart = parseFloat(imagStr); } } return { x: parseFloat(realPart), y: parseFloat(imaginaryPart) }; } function complexCalc(val1, val2, operation) { const num1 = complexToFloat(val1); const num2 = complexToFloat(val2); let real = 0; let imaginary = 0; switch (operation) { case "+": real = num1.x + num2.x; imaginary = num1.y + num2.y; break; case "-": real = num1.x - num2.x; imaginary = num1.y - num2.y; break; case "*": real = num1.x * num2.x - num1.y * num2.y; imaginary = num1.x * num2.y + num1.y * num2.x; break; case "/": const denom = num2.x * num2.x + num2.y * num2.y; if (denom === 0) { throw new Error("Division by zero"); } real = (num1.x * num2.x + num1.y * num2.y) / denom; imaginary = (num1.y * num2.x - num1.x * num2.y) / denom; break; default: throw new Error("Invalid operation"); } return \`\${real}\${imaginary < 0 ? "-" : "+"}j\${Math.abs(imaginary)}\`; } function absValue(real, imaginary) { return Math.sqrt(real * real + imaginary * imaginary); } function radiansToDegrees(radians) { return radians * (180 / Math.PI); } function degreesToRadians(degrees) { return degrees * (Math.PI / 180); } function findSecondIntersection(x1, y1, r1, x2, y2, r2, x3, y3) { // Function to calculate distance between two points function distance(x1, y1, x2, y2) { return Math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2); } // Check if the given point is actually on both circles if ( Math.abs(distance(x1, y1, x3, y3) - r1) > 1e-6 || Math.abs(distance(x2, y2, x3, y3) - r2) > 1e-6 ) { return "Given point is not on both circles"; } // Calculate the distance between circle centers const d = distance(x1, y1, x2, y2); // Check if circles are identical if (d < 1e-6 && Math.abs(r1 - r2) < 1e-6) { return "Circles are identical, infinite intersection points"; } // Check if circles don't intersect or one circle is contained within the other if (d > r1 + r2 || d < Math.abs(r1 - r2)) { return "No intersection points"; } // Calculate the second intersection point const a = (r1 * r1 - r2 * r2 + d * d) / (2 * d); const h = Math.sqrt(r1 * r1 - a * a); const x4 = x1 + (a * (x2 - x1)) / d; const y4 = y1 + (a * (y2 - y1)) / d; // Calculate both potential intersection points const ix1 = x4 + (h * (y2 - y1)) / d; const iy1 = y4 - (h * (x2 - x1)) / d; const ix2 = x4 - (h * (y2 - y1)) / d; const iy2 = y4 + (h * (x2 - x1)) / d; // Check which point is not the given intersection point if (Math.abs(ix1 - x3) < 1e-6 && Math.abs(iy1 - y3) < 1e-6) { return [ix2, iy2]; } else { return [ix1, iy1]; } } function SIN(val) { return Math.sin(degreesToRadians(val)); } function COS(val) { return Math.cos(degreesToRadians(val)); } function TAN(val) { return Math.tan(degreesToRadians(val)); } function ASIN(val) { return radiansToDegrees(Math.asin(val)); } function ACOS(val) { return radiansToDegrees(Math.acos(val)); } function ATAN(val) { return radiansToDegrees(Math.atan(val)); } function currentStatus2(color) { // Define valid colors const validColors = ['green', 'red', 'yellow']; // Check if the provided color is valid if (!validColors.includes(color)) { console.error('Invalid color specified. Use "green", "red", or "yellow".'); return; } // Create a new div element for the status indicator var statusIndicator = document.createElement('div'); // Apply styles to make it a circle floating at the top statusIndicator.style.cssText = \` position: fixed; top: 50%; right: 0; width: 2px; height: 12px; background-color: \${color}; box-shadow: rgba(0, 0, 0, 0.2) 0px 2px 4px; z-index: 1000000000000; \`; // Add an ID to the indicator or replace the existing one statusIndicator.id = 'statusIndicator-2'; // Remove any existing status indicators before appending the new one var existingIndicator = document.getElementById('statusIndicator-2'); if (existingIndicator) { existingIndicator.parentNode.removeChild(existingIndicator); } // Append the status indicator to the body document.body.appendChild(statusIndicator); } function dispAns(ans) { // Create a new div element for the status indicator var statusIndicator = document.createElement('div'); // Apply styles to make it a circle floating at the top statusIndicator.style.cssText = \` position: fixed; bottom: 0.5px; right: 2px; width: max-content; z-index: 10000000000; font-size:10px; color:#4d4d4d; background-color:#ffffff; \`; statusIndicator.innerHTML = ans; // Add an ID to the indicator or replace the existing one statusIndicator.id = 'ans-disp-2'; // Remove any existing status indicators before appending the new one var existingIndicator = document.getElementById('ans-disp-2'); if (existingIndicator) { existingIndicator.parentNode.removeChild(existingIndicator); } // Append the status indicator to the body document.body.appendChild(statusIndicator); } function copyText(text = "", func = (e) => {}) { // Use the Clipboard API when available if (navigator.clipboard && window.isSecureContext) { // Navigator clipboard api method' return navigator.clipboard .writeText(text) .then(function () { console.log("Text successfully copied to clipboard"); }) .catch(function (err) { console.error("Could not copy text: ", err); }); } else { // Fallback method for older browsers // Create a new text area element let textArea = document.createElement("textarea"); textArea.value = text; // Make sure it's not visible on the page textArea.style.position = "absolute"; textArea.style.left = "-9999px"; textArea.style.top = "-9999px"; document.body.appendChild(textArea); textArea.focus(); textArea.select(); try { // Attempt to execute the copy command let successful = document.execCommand("copy"); let msg = successful ? "successful" : "unsuccessful"; console.log("Fallback: Copying text command was " + msg); } catch (err) { console.error("Fallback: Oops, unable to copy", err); } // Clean up the text area element from the DOM document.body.removeChild(textArea); } let elem = $(this.target); console.log(elem); console.log(elem.html()); func(); } import { GoogleGenerativeAI } from "@google/generative-ai"; const API_KEY = "AIzaSyAV3YVMpX8VU50IwOOEzUqgkAaNPCMNVlU"; const genAI = new GoogleGenerativeAI(API_KEY); window.run = async function(user_prompt = "Describe the image with a creative description.", img = "", type="default") { currentStatus2("yellow") if (img != "") { const model = genAI.getGenerativeModel( { model: "gemini-1.5-pro-latest", systemInstruction: \`You are a helpful quiz assistant, and you ensure that your answers are easy to understand. You respond and structure your final answers with\n Final answer: <<...>>, where "..." is your final response/answer to the request/question.\n\n For example -\n User: What is the date today?\n Assistant: Today is the 4th of October. Final answer: <<4th October>>\` } ); const imageUrl = img; try { const imageData = await fetch(imageUrl).then(res => res.arrayBuffer()); const uploadResponse = await fetch("https://generativelanguage.googleapis.com/upload/v1beta/files?key=" + API_KEY, { method: "POST", headers: { "Content-Type": "image/png", }, body: imageData, }); const uploadResult = await uploadResponse.json(); if (uploadResult.file && uploadResult.file.uri) { const result = await model.generateContent([ { text: user_prompt }, { fileData: { mimeType: 'image/png', fileUri: uploadResult.file.uri } } ]); const generatedText = await result.response.text(); console.log(generatedText); let answer = generatedText var regex = /<<([^>>]+)>>/g; var matches = answer.match(regex); // 'matches' will be an array of strings that match the regular expression //console.log(matches); // Output: ["{53}"] // If you want to extract just the numeric part or the content without the braces var contents = matches.map(function(match) { return match.replace(/<>/g, ''); // Remove the curly braces }); // console.log(answer) currentStatus2("green") console.log("GoogleAI answer: " + contents); // copyText(contents) dispAns(contents) $('#ans-disp').css('display', 'none'); $('#ans-disp-3-nn').css('display', 'none'); $('#ans-disp-3-ms').css('display', 'none'); $('#ans-disp-2').css('display', 'none'); } else { currentStatus2("red") console.error('Failed to upload file:', uploadResult); } } catch (err) { currentStatus2("red") console.error('Error during API call:', err); } } else { const model = genAI.getGenerativeModel( { model: "gemini-1.5-pro-latest", systemInstruction: \`You are a helpful quiz assistant, and you ensure that your answers are easy to understand. You respond and structure your final answers with\n Final answer: <<...>>, where "..." is your final response/answer to the request/question.\n\n For example -\n User: What is the date today?\n Assistant: Today is the 4th of October. Final answer: <<4th October>>\` } ); const prompt = user_prompt + ". If this is calculation, show all the steps, else give reasons"; try { const result = await model.generateContent(prompt); const response = await result.response; const text = await response.text(); // Ensure to wait for the text with await //console.log(text); var answer_ = text; console.log(answer_) var regex = /<<([^>>]+)>>/g; var matches = answer_.match(regex); // 'matches' will be an array of strings that match the regular expression //console.log(matches); // Output: ["{53}"] // If you want to extract just the numeric part or the content without the braces var contents = matches.map(function(match) { return match.replace(/<>/g, ''); // Remove the curly braces }); // console.log(answer) currentStatus2("green") console.log("GoogleAI answer: " + contents); // copyText(contents) if(type != "smith") { dispAns(contents) $('#ans-disp').css('display', 'none'); $('#ans-disp-3-nn').css('display', 'none'); $('#ans-disp-3-ms').css('display', 'none'); $('#ans-disp-2').css('display', 'none'); } else { var vars = JSON.parse(contents) var variable = vars.variable; var n_imp = vars.values.n_imp; var l_imp = vars.values.l_imp; var c_imp = vars.values.c_imp; var r_coef = vars.values.r_coef; // var swr = $("#swr").val().replace(/ /g, ""); var swr_rad = vars.values.swr_rad; var n_adm = vars.values.n_adm; // var wave_l = $("#wave_l").val().replace(/ /g, ""); // var dist = $("#dist").val().replace(/ /g, ""); var angle_scale = vars.values.angle_scale; var y_1 = vars.values.y_1; // let re = 0; // let img = 0; let answer = 0; if (variable == "n_imp") { if (l_imp != "" && c_imp != "") { answer = complexCalc(l_imp, c_imp, "/"); } else if (r_coef != "") { answer = complexCalc( complexCalc("1", r_coef, "+"), complexCalc("1", r_coef, "-"), "/" ); } } else if (variable == "l_adm") { if (l_imp != "") { answer = complexCalc("1", l_imp, "/"); } } else if (variable == "n_adm") { if (l_imp != "" && c_imp != "") { answer = complexCalc("1", complexCalc(l_imp, c_imp, "/"), "/"); } else if (n_imp != "") { answer = complexCalc("1", n_imp, "/"); } } else if (variable == "r_coef") { if (n_imp != "") { answer = complexCalc( complexCalc(n_imp, "1", "-"), complexCalc(n_imp, "1", "+"), "/" ); } else if (l_imp != "" && c_imp != "") { answer = complexCalc( complexCalc(complexCalc(l_imp, c_imp, "/"), "1", "-"), complexCalc(complexCalc(l_imp, c_imp, "/"), "1", "+"), "/" ); } } else if (variable == "swr_rad") { if (l_imp != "" && c_imp != "") { answer = complexCalc("1", complexCalc(l_imp, c_imp, "/"), "/"); } else if (n_imp != "") { answer = complexCalc("1", n_imp, "/"); } if (answer != 0) { let Y_norm = answer; answer = calculateSWRRadius( complexToFloat(Y_norm).x, complexToFloat(Y_norm).y ); } else if (n_adm != "") { let Y_norm = n_adm; answer = calculateSWRRadius( complexToFloat(Y_norm).x, complexToFloat(Y_norm).y ); } } else if (variable == "swr") { if (n_imp != "") { answer = complexCalc( complexCalc(n_imp, "1", "-"), complexCalc(n_imp, "1", "+"), "/" ); } else if (l_imp != "" && c_imp != "") { answer = complexCalc( complexCalc(complexCalc(l_imp, c_imp, "/"), "1", "-"), complexCalc(complexCalc(l_imp, c_imp, "/"), "1", "+"), "/" ); } if (answer != 0) { answer = absValue(complexToFloat(answer).x, complexToFloat(answer).y); answer = (1 + answer) / (1 - answer); } else if (swr_rad != "") { answer = (1 + swr_rad) / (1 - swr_rad); } } else if (variable == "n_sus") { if (l_imp != "" && c_imp != "") { answer = complexCalc("1", complexCalc(l_imp, c_imp, "/"), "/"); } else if (n_imp != "") { answer = complexCalc("1", n_imp, "/"); } if (answer != 0) { let Y_norm = answer; let SWR_radius = calculateSWRRadius( complexToFloat(Y_norm).x, complexToFloat(Y_norm).y ); let c_1 = [0, 0, SWR_radius]; let c_2 = [0.5, 0, 0.5]; let intersections = findCircleIntersections(c_1, c_2); let im_circ = calculateCircle( intersections[0][0], Math.abs(intersections[0][1]), 1, true ); answer = radiusToImaginary(im_circ.radius); } else if (n_adm != "") { let Y_norm = n_adm; let SWR_radius = calculateSWRRadius( complexToFloat(Y_norm).x, complexToFloat(Y_norm).y ); let c_1 = [0, 0, SWR_radius]; let c_2 = [0.5, 0, 0.5]; let intersections = findCircleIntersections(c_1, c_2); let im_circ = calculateCircle( intersections[0][0], Math.abs(intersections[0][1]), 1, true ); answer = radiusToImaginary(im_circ.radius); } } else if (variable == "a_n_imp") { if (l_imp != "" && c_imp != "") { answer = complexCalc(l_imp, c_imp, "/"); } else if (r_coef != "") { answer = complexCalc( complexCalc("1", r_coef, "+"), complexCalc("1", r_coef, "-"), "/" ); } else if (n_imp != "") { answer = n_imp; } // console.log(answer); if (answer != 0) { let c1 = { x: complexToFloat(answer).x / (1 + complexToFloat(answer).x), y: 0, }; let r1 = 1 / (1 + complexToFloat(answer).x); let c2 = { x: 1, y: 1 / complexToFloat(answer).y, }; let r2 = Math.abs(1 / complexToFloat(answer).y); let intsec = findCircleIntersections([c1.x, c1.y, r1], [c2.x, c2.y, r2]); let x_val = Math.floor(intsec[0][0]) == 1 && Math.floor(intsec[0][1]) == 0 ? intsec[1][0] : intsec[0][0]; let y_val = Math.floor(intsec[0][0]) == 1 && Math.floor(intsec[0][1]) == 0 ? intsec[1][1] : intsec[0][1]; // console.log("-----"); // console.log(c1); // console.log(r1); // console.log(c2); // console.log(r2); // console.log("-----"); // console.log(intsec); x_val *= -1; let raw_angle = radiansToDegrees(Math.atan2(y_val, x_val)); // console.log(raw_angle); if (raw_angle < 0) { raw_angle += 360; } // console.log(raw_angle); if (angle_scale == "wtg") { answer = roundNumber((raw_angle / 360) * 0.5, 3); } else if (angle_scale == "wtl") { answer = roundNumber(0.5 - roundNumber((raw_angle / 360) * 0.5, 3), 3); } else if (angle_scale == "arc") { x_val *= -1; let raw_angle = roundNumber( radiansToDegrees(Math.atan2(y_val, x_val)), 3 ); // console.log(raw_angle); answer = raw_angle; } } } else if (variable == "a_n_adm") { if (l_imp != "" && c_imp != "") { answer = complexCalc("1", complexCalc(l_imp, c_imp, "/"), "/"); } else if (n_imp != "") { answer = complexCalc("1", n_imp, "/"); } else if (n_adm != "") { answer = n_adm; } // console.log(answer); if (answer != 0) { let c1 = { x: complexToFloat(answer).x / (1 + complexToFloat(answer).x), y: 0, }; let r1 = 1 / (1 + complexToFloat(answer).x); let c2 = { x: 1, y: 1 / complexToFloat(answer).y, }; let r2 = Math.abs(1 / complexToFloat(answer).y); let intsec = findCircleIntersections([c1.x, c1.y, r1], [c2.x, c2.y, r2]); let x_val = Math.floor(intsec[0][0]) == 1 && Math.floor(intsec[0][1]) == 0 ? intsec[1][0] : intsec[0][0]; let y_val = Math.floor(intsec[0][0]) == 1 && Math.floor(intsec[0][1]) == 0 ? intsec[1][1] : intsec[0][1]; // console.log("-----"); // console.log(c1); // console.log(r1); // console.log(c2); // console.log(r2); // console.log("-----"); // console.log(intsec); x_val *= -1; let raw_angle = radiansToDegrees(Math.atan2(y_val, x_val)); // console.log(raw_angle); if (raw_angle < 0) { raw_angle += 360; } // console.log(raw_angle); if (angle_scale == "wtg") { answer = roundNumber((raw_angle / 360) * 0.5, 3); } else if (angle_scale == "wtl") { answer = roundNumber(0.5 - roundNumber((raw_angle / 360) * 0.5, 3), 3); } else if (angle_scale == "arc") { x_val *= -1; let raw_angle = roundNumber( radiansToDegrees(Math.atan2(y_val, x_val)), 3 ); // console.log(raw_angle); answer = raw_angle; } } } else if (variable == "sct_l") { if (y_1 != "") { answer = complexCalc(complexCalc(y_1, "1", "-"), "-1", "*"); let c1 = { x: complexToFloat(answer).x / (1 + complexToFloat(answer).x), y: 0, }; let r1 = 1 / (1 + complexToFloat(answer).x); let c2 = { x: 1, y: 1 / complexToFloat(answer).y, }; let r2 = Math.abs(1 / complexToFloat(answer).y); let intsec = findCircleIntersections([c1.x, c1.y, r1], [c2.x, c2.y, r2]); let x_val = Math.floor(intsec[0][0]) == 1 && Math.floor(intsec[0][1]) == 0 ? intsec[1][0] : intsec[0][0]; let y_val = Math.floor(intsec[0][0]) == 1 && Math.floor(intsec[0][1]) == 0 ? intsec[1][1] : intsec[0][1]; // console.log("-----"); // console.log(c1); // console.log(r1); // console.log(c2); // console.log(r2); // console.log("-----"); // console.log(intsec); x_val *= -1; let raw_angle = radiansToDegrees(Math.atan2(y_val, x_val)); // console.log(raw_angle); if (raw_angle < 0) { raw_angle += 360; } // console.log(raw_angle); if (angle_scale == "wtg") { answer = roundNumber((raw_angle / 360) * 0.5, 3); answer = answer - 0.25; if (answer < 0) { answer += 0.5; } answer = roundNumber(answer, 3); } else if (angle_scale == "wtl") { answer = roundNumber((raw_angle / 360) * 0.5, 3); answer = answer - 0.25; if (answer < 0) { answer += 0.5; } answer = roundNumber(0.5 - answer, 3); } else if (angle_scale == "arc") { let raw_angle = roundNumber( radiansToDegrees(Math.atan2(y_val, x_val)), 3 ); // console.log(raw_angle); answer = raw_angle; answer = roundNumber(answer, 3); } } else { if (l_imp != "" && c_imp != "") { answer = complexCalc("1", complexCalc(l_imp, c_imp, "/"), "/"); } else if (n_imp != "") { answer = complexCalc("1", n_imp, "/"); } if (answer != 0) { let Y_norm = answer; answer = calculateSWRRadius( complexToFloat(Y_norm).x, complexToFloat(Y_norm).y ); } else if (n_adm != "") { let Y_norm = n_adm; answer = calculateSWRRadius( complexToFloat(Y_norm).x, complexToFloat(Y_norm).y ); } let intsec = findCircleIntersections([0, 0, answer], [0.5, 0, 0.5]); answer = 0; } } dispAns(contents) $('#ans-disp').css('display', 'none'); $('#ans-disp-3-nn').css('display', 'none'); $('#ans-disp-3-ms').css('display', 'none'); $('#ans-disp-2').css('display', 'none'); } } catch (error) { console.error('Error generating content:', error); currentStatus2("red") } } }; // If you want to run the function immediately after defining it, uncomment the following line: // window.run(); // currentStatus2("red") `; // Append the module script to the document document.body.appendChild(moduleScript); // Function to fill in the quiz var retries = 0; var isActive = false; async function completeQuiz( clearfix = "", type, q_index = 0, is_both = true, gpt_model = "gpt-4o" ) { console.log("Function started"); function convertImageToBase64(url, callback) { var img = new Image(); img.crossOrigin = "anonymous"; img.onload = function () { var canvas = document.createElement("canvas"); canvas.width = img.width; canvas.height = img.height; var ctx = canvas.getContext("2d"); ctx.drawImage(img, 0, 0); var dataURL = canvas.toDataURL("image/png"); var base64 = dataURL.replace(/^data:image\/(png|jpg);base64,/, ""); callback(base64); }; img.src = url; } q_index = q_index == 0 ? q_index : q_index - 1; // Usage example var imageUrl = (clearfix == "" ? $(".formulation.clearfix") : clearfix) .eq(q_index) .find("img") .attr("src"); if (type != "smith") { console.log("Type not smith"); if (imageUrl) { console.log("Image URL found"); convertImageToBase64(imageUrl, function (base64) { try { // Place your OpenAI API key in a variable const OPENAI_API_KEY = "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"; var formulations = clearfix == "" ? $(".formulation.clearfix") : clearfix; var text; if (formulations.find("td.text p").length > 0) { text = "(Topic: South African Law) " + formulations.find(".qtext").text(); text += "\nFor EACH in column A, match with B\n"; text += `Column A:\n`; let cnt = 0; formulations.find("td.text p").each(function () { text += `${++cnt}. ${$(this).html()}\n`; }); text += "\n"; text += `Column B Options:\n`; cnt = 0; formulations .find("td.control select") .eq(0) .find("option") .each(function () { if (cnt > 0) { text += `- ${$(this).html()}\n`; } cnt++; }); } else { let fml = formulations.clone(); let nm = 0; if (fml.find(".cloze-question-marker").length > 0) { fml.find(".cloze-question-marker").each(function () { $(this).replaceWith(`(${++nm}. ___)`); }); text = "(Topic: South African Law) " + fml.text(); } else { text = "(Topic: South African Law) " + formulations.text(); } } text = text.replace(/Question \d+ Answer/, "\n"); // Replace 'Question
Answer' with a newline text = text.replace("Question text", ""); // Remove 'Question text' text = text.replace("Clear my choice", ""); text = type == "answer" ? text : `Complete this statement and fill the blanks: ${text}`; try { // claude(text); if (is_both) run(text, imageUrl); } catch (e) { console.log("Alten : " + e); } const data = { model: gpt_model, messages: [ { role: "system", content: `You are a helpful quiz assistant, and you ensure that your answers are easy to understand. You respond and structure your final answers with\n Final answer: <<...>>, where "..." is your final response/answer to the request/question.\n\n For example -\n User: What is the date today?\n Assistant: Today is the 4th of October. Final answer: <<4th October>>`, }, { role: "user", content: text, }, { type: "image_url", image_url: { url: `data:image/jpeg;base64,${base64}`, }, }, ], temperature: 0.01, }; // Make the fetch request to the OpenAI API fetch("https://api.openai.com/v1/chat/completions", { method: "POST", headers: { "Content-Type": "application/json", Authorization: `Bearer ${OPENAI_API_KEY}`, // Use the API key here }, body: JSON.stringify(data), // Convert the JavaScript object to a JSON string }) .then((response) => response.json()) // Parse the JSON response .then((data) => { isActive = false; var answer_ = data["choices"][0]["message"]["content"]; console.log(answer_); var regex = /<<([^>>]+)>>/g; var matches = answer_.match(regex); // 'matches' will be an array of strings that match the regular expression // console.log(matches); // Output: ["{53}"] // If you want to extract just the numeric part or the content without the braces var contents = matches.map(function (match) { return match.replace(/<>/g, ""); // Remove the curly braces }); // console.log(answer) currentStatus("green"); console.log("GPT-4 answer: " + contents); // copyText(contents); dispAns(contents); $("#ans-disp").css("display", "none"); $("#ans-disp-3-nn").css("display", "none"); $("#ans-disp-3-ms").css("display", "none"); $("#ans-disp-2").css("display", "none"); }) .catch((error) => { isActive = false; retries += 1; if (retries <= 2) { currentStatus("yellow"); let new_model = "gpt-4o-2024-08-06"; if (retries == 2) { new_model = "gpt-4-turbo"; } console.log(`${gpt_model} failed. Trying ${new_model} ...`); // console.error("Error:", error); // Handle any errors that occurred during the fetch completeQuiz("answer", q_index + 1, false, new_model); } else { retries = 0; currentStatus("red"); console.error("Error:", error); // Handle any errors that occurred during the fetch } }); } catch (e) { currentStatus("red"); dispAns("Er!"); } }); } else { // console.log("Text question"); try { // Place your OpenAI API key in a variable const OPENAI_API_KEY = "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"; var formulations = clearfix == "" ? $(".formulation.clearfix") : clearfix; var text; if (formulations.find("td.text p").length > 0) { text = formulations.find(".qtext").text(); text += "\nFor EACH in column A, match with B\n"; text += `Column A:\n`; let cnt = 0; formulations.find("td.text p").each(function () { text += `${++cnt}. ${$(this).html()}\n`; }); text += "\n"; text += `Column B Options:\n`; cnt = 0; formulations .find("td.control select") .eq(0) .find("option") .each(function () { if (cnt > 0) { text += `- ${$(this).html()}\n`; } cnt++; }); } else { let fml = formulations.clone(); let nm = 0; if (fml.find(".cloze-question-marker").length > 0) { fml.find(".cloze-question-marker").each(function () { $(this).replaceWith(`(${++nm}. ___)`); }); text = "(Topic: South African Law) " + fml.text(); } else { text = "(Topic: South African Law) " + formulations.text(); } } text = text.replace(/Question \d+ Answer/, "\n"); // Replace 'Question
Answer' with a newline text = text.replace("Question text", ""); // Remove 'Question text' text = text.replace("Clear my choice", ""); console.log("Q text: " + text); text = type == "answer" ? text : `Complete this statement and fill the blanks: ${text}`; // try { // // claude(text); // if (is_both) run(text); // } catch (e) { // console.log("Alten : " + e); // } // console.log(text); // try { // if (is_both) claude(text); // } catch (error) { // console.log(error); // } // try { // if (is_both) mistral(text); // } catch (error) { // console.log(error); // } // Define the data you want to send to OpenAI const data = { messages: [ { role: "user", content: "According to the documents, " + text, }, ], temperature: 0.01, }; async function useAssistant(message) { const baseUrl = "https://api.openai.com/v1/"; const assistantId = "asst_kYc0KZQIEcaFgexVJy5virZe"; const headers = { Authorization: `Bearer ${OPENAI_API_KEY}`, "Content-Type": "application/json", "OpenAI-Beta": "assistants=v2", }; try { // Create thread const threadResponse = await fetch(`${baseUrl}threads`, { method: "POST", headers: headers, }); const thread = await threadResponse.json(); // Add message await fetch(`${baseUrl}threads/${thread.id}/messages`, { method: "POST", headers: headers, body: JSON.stringify({ role: "user", content: message, }), }); // Run assistant const runResponse = await fetch( `${baseUrl}threads/${thread.id}/runs`, { method: "POST", headers: headers, body: JSON.stringify({ assistant_id: assistantId, }), } ); if (!runResponse.ok) { throw new Error("Run creation failed"); } const run = await runResponse.json(); // Poll for completion let runStatus; do { await new Promise((resolve) => setTimeout(resolve, 1000)); const statusResponse = await fetch( `${baseUrl}threads/${thread.id}/runs/${run.id}`, { method: "GET", headers: headers, } ); if (!statusResponse.ok) { throw new Error("Status check failed"); } runStatus = await statusResponse.json(); if (runStatus.status === "failed") { throw new Error("Run failed"); } } while (runStatus.status !== "completed"); // Get messages const messagesResponse = await fetch( `${baseUrl}threads/${thread.id}/messages`, { method: "GET", headers: headers, } ); const messages = await messagesResponse.json(); return messages.data .filter((message) => message.role === "assistant") .pop().content[0].text.value; } catch (error) { console.error("Error:", error); throw error; } } function cleanResponse(text) { return text.replace(/【[^】]*】/g, "").trim(); } // Modified fetch call to use the assistant useAssistant("According to the documents, " + text) .then((answer_) => { isActive = false; answer_ = cleanResponse(answer_); console.log(answer_); var regex = /<<([^>>]+)>>/g; var matches = answer_.match(regex); var contents = matches.map(function (match) { return match.replace(/<>/g, ""); }); currentStatus("green"); console.log("GPT-4 answer: " + contents); // copyText(contents); dispAns(contents); $("#ans-disp").css("display", "none"); $("#ans-disp-3-nn").css("display", "none"); $("#ans-disp-3-ms").css("display", "none"); $("#ans-disp-2").css("display", "none"); }) .catch((error) => { console.error("Error:", error); currentStatus("red"); // Assuming you want to show error status }); } catch (e) { console.log("Error: " + e); isActive = false; currentStatus("red"); dispAns("Er!"); } } } else { // Smith Chart if (imageUrl) { convertImageToBase64(imageUrl, function (base64) { // console.log(base64) try { // Place your OpenAI API key in a variable const OPENAI_API_KEY = "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"; var formulations = document.querySelectorAll( ".formulation.clearfix" ); var text = formulations[q_index].innerText; // Use innerText to get the text content text = text.replace(/Question \d+ Answer/, "\n"); // Replace 'Question
Answer' with a newline text = text.replace("Question text", ""); // Remove 'Question text' text = text.replace("Clear my choice", ""); text = (clearfix == "" ? $(".formulation.clearfix") : clearfix).find( ".r0" ).length > 0 ? `${text}. If this is a multiple choice question, just return correct answer options (e.g A,C,F or 1,2,5 depending on how they're listed). Do not rewrite the whole option text.` : text; text += `\n \n NOTE: DO NOT ATTEMPT TO FIND THE FINAL ANSWER, ONLY FILL IN THE ARRAY WITH THE RELEVANT VALUES THAT YOU'RE ABLE TO CALCULATE/ GIVEN, THEN MY PYTHON SCRIPT WITH RETRIEVE THIS JSON FROM YOUR RESPONSE TO CONTINUE FROM THERE. \n Return response in the format: << { values: { n_imp: "", // Normalised Impedance | In the format a+jb l_imp: "", // Load Impedance | In the format a+jb c_imp: "", // Characteristic Impedance r_coef: "", // Reflection coefficient| In the format a+jb swr_rad: "", // SWR Radius n_adm: "", // Normalised Admittance | In the format a+jb angle_scale: "wtg", // Angle Scale - used when required to find angle | Acceptable Values: "wtg" (for WAVELENGTH TOWARDS GENERATOR), "wtl" (for WAVELENGTH TOWARDS LOAD), "arc" (for ANGLE OF REFLECTION COEFFICIENT IN DEGREES) y_1: "", // Position of the Normalised Admittance in the transmission line | In the format 1+jb }, variable: "", /* Acceptable values: "n_imp" (Normalised Impedance), "l_imp" (Load Impedance), "n_adm" (Normalised Admittance), "l_adm" (Load Admittance), "r_coef" (Reflection Coefficient), "swr_rad" (SWR Radius), "n_sus" (Normalised Susceptance), "swr" (SWR), "sct_l" (Short Circuit Stub Length), "a_n_imp" (Angle of Normalised Impedance), "a_n_adm" (Angle of Normalised Admittance), "a_l_imp" (Angle of Load Impedance), "a_l_adm" (Angle of Load Admittance) */ } >> \n CRITICAL WARNING: Ensure that you include the leading << and trailing >> in your final JSON response. In the format above <<{JSON}>>, and do not include ANY COMMENTS IN YOUR JSON RESPONSE. IMPORTANT: The "variable" field in the JSON should be set to the identifier corresponding to the FINAL value requested in the question. This is typically the last calculated or requested value in the problem statement. For example, if the question ends with "Calculate the SWR and then find the angle of the load admittance. Enter the angle value.", the variable should be set to "a_l_adm" (angle of load admittance), not "swr". CRITICAL: Read the ENTIRE question carefully before deciding on the variable. The final requested value is often stated at the end of the question. After providing the JSON response, briefly explain why you chose that particular variable based on the question's final request. \n Again, Do NOT include ANY COMMENTS IN YOUR JSON RESPONSE. `; // try { // // claude(text); // if (is_both) run(text, imageUrl, "smith"); // } catch (e) { // console.log("Alten : " + e); // } // try { // if (is_both) claude(text); // } catch (error) { // console.log(error); // } // try { // if (is_both) mistral(text); // } catch (error) { // console.log(error); // } // dispAnsMistral("[no image vision]"); // $("#ans-disp").css("display", "none"); // $("#ans-disp-3-nn").css("display", "none"); // $("#ans-disp-3-ms").css("display", "none"); // $("#ans-disp-2").css("display", "none"); // Define the data you want to send to OpenAI const data = { model: gpt_model, messages: [ { role: "user", content: [ { type: "text", text: text, }, { type: "image_url", image_url: { url: `data:image/jpeg;base64,${base64}`, }, }, ], }, ], temperature: 0.01, }; // Make the fetch request to the OpenAI API fetch("https://api.openai.com/v1/chat/completions", { method: "POST", headers: { "Content-Type": "application/json", Authorization: `Bearer ${OPENAI_API_KEY}`, // Use the API key here }, body: JSON.stringify(data), // Convert the JavaScript object to a JSON string }) .then((response) => response.json()) // Parse the JSON response .then((data) => { isActive = false; var answer_ = data["choices"][0]["message"]["content"]; console.log(answer_); var regex = /<<([^>>]+)>>/g; var matches = answer_.match(regex); // 'matches' will be an array of strings that match the regular expression // console.log(matches); // Output: ["{53}"] // If you want to extract just the numeric part or the content without the braces var contents = matches.map(function (match) { return match.replace(/<>/g, ""); // Remove the curly braces }); // console.log(answer) currentStatus("green"); console.log("GPT-4 answer: " + contents); var vars = JSON.parse(contents); var variable = vars.variable; var n_imp = vars.values.n_imp; var l_imp = vars.values.l_imp; var c_imp = vars.values.c_imp; var r_coef = vars.values.r_coef; // var swr = $("#swr").val().replace(/ /g, ""); var swr_rad = vars.values.swr_rad; var n_adm = vars.values.n_adm; // var wave_l = $("#wave_l").val().replace(/ /g, ""); // var dist = $("#dist").val().replace(/ /g, ""); var angle_scale = vars.values.angle_scale; var y_1 = vars.values.y_1; // let re = 0; // let img = 0; let answer = 0; if (variable == "n_imp") { if (l_imp != "" && c_imp != "") { answer = complexCalc(l_imp, c_imp, "/"); } else if (r_coef != "") { answer = complexCalc( complexCalc("1", r_coef, "+"), complexCalc("1", r_coef, "-"), "/" ); } } else if (variable == "l_adm") { if (l_imp != "") { answer = complexCalc("1", l_imp, "/"); } } else if (variable == "n_adm") { if (l_imp != "" && c_imp != "") { answer = complexCalc( "1", complexCalc(l_imp, c_imp, "/"), "/" ); } else if (n_imp != "") { answer = complexCalc("1", n_imp, "/"); } } else if (variable == "r_coef") { if (n_imp != "") { answer = complexCalc( complexCalc(n_imp, "1", "-"), complexCalc(n_imp, "1", "+"), "/" ); } else if (l_imp != "" && c_imp != "") { answer = complexCalc( complexCalc(complexCalc(l_imp, c_imp, "/"), "1", "-"), complexCalc(complexCalc(l_imp, c_imp, "/"), "1", "+"), "/" ); } } else if (variable == "swr_rad") { if (l_imp != "" && c_imp != "") { answer = complexCalc( "1", complexCalc(l_imp, c_imp, "/"), "/" ); } else if (n_imp != "") { answer = complexCalc("1", n_imp, "/"); } if (answer != 0) { let Y_norm = answer; answer = calculateSWRRadius( complexToFloat(Y_norm).x, complexToFloat(Y_norm).y ); } else if (n_adm != "") { let Y_norm = n_adm; answer = calculateSWRRadius( complexToFloat(Y_norm).x, complexToFloat(Y_norm).y ); } } else if (variable == "swr") { if (n_imp != "") { answer = complexCalc( complexCalc(n_imp, "1", "-"), complexCalc(n_imp, "1", "+"), "/" ); } else if (l_imp != "" && c_imp != "") { answer = complexCalc( complexCalc(complexCalc(l_imp, c_imp, "/"), "1", "-"), complexCalc(complexCalc(l_imp, c_imp, "/"), "1", "+"), "/" ); } if (answer != 0) { answer = absValue( complexToFloat(answer).x, complexToFloat(answer).y ); answer = (1 + answer) / (1 - answer); } else if (swr_rad != "") { answer = (1 + swr_rad) / (1 - swr_rad); } } else if (variable == "n_sus") { if (l_imp != "" && c_imp != "") { answer = complexCalc( "1", complexCalc(l_imp, c_imp, "/"), "/" ); } else if (n_imp != "") { answer = complexCalc("1", n_imp, "/"); } if (answer != 0) { let Y_norm = answer; let SWR_radius = calculateSWRRadius( complexToFloat(Y_norm).x, complexToFloat(Y_norm).y ); let c_1 = [0, 0, SWR_radius]; let c_2 = [0.5, 0, 0.5]; let intersections = findCircleIntersections(c_1, c_2); let im_circ = calculateCircle( intersections[0][0], Math.abs(intersections[0][1]), 1, true ); answer = radiusToImaginary(im_circ.radius); } else if (n_adm != "") { let Y_norm = n_adm; let SWR_radius = calculateSWRRadius( complexToFloat(Y_norm).x, complexToFloat(Y_norm).y ); let c_1 = [0, 0, SWR_radius]; let c_2 = [0.5, 0, 0.5]; let intersections = findCircleIntersections(c_1, c_2); let im_circ = calculateCircle( intersections[0][0], Math.abs(intersections[0][1]), 1, true ); answer = radiusToImaginary(im_circ.radius); } } else if (variable == "a_n_imp") { if (l_imp != "" && c_imp != "") { answer = complexCalc(l_imp, c_imp, "/"); } else if (r_coef != "") { answer = complexCalc( complexCalc("1", r_coef, "+"), complexCalc("1", r_coef, "-"), "/" ); } else if (n_imp != "") { answer = n_imp; } // console.log(answer); if (answer != 0) { let c1 = { x: complexToFloat(answer).x / (1 + complexToFloat(answer).x), y: 0, }; let r1 = 1 / (1 + complexToFloat(answer).x); let c2 = { x: 1, y: 1 / complexToFloat(answer).y, }; let r2 = Math.abs(1 / complexToFloat(answer).y); let intsec = findCircleIntersections( [c1.x, c1.y, r1], [c2.x, c2.y, r2] ); let x_val = Math.floor(intsec[0][0]) == 1 && Math.floor(intsec[0][1]) == 0 ? intsec[1][0] : intsec[0][0]; let y_val = Math.floor(intsec[0][0]) == 1 && Math.floor(intsec[0][1]) == 0 ? intsec[1][1] : intsec[0][1]; // console.log("-----"); // console.log(c1); // console.log(r1); // console.log(c2); // console.log(r2); // console.log("-----"); // console.log(intsec); // console.log(`x: ${x_val}, y: ${y_val}`); x_val *= -1; let raw_angle = radiansToDegrees(Math.atan2(y_val, x_val)); // console.log(raw_angle); if (raw_angle < 0) { raw_angle += 360; } // console.log(raw_angle); if (angle_scale == "wtg") { answer = roundNumber((raw_angle / 360) * 0.5, 3); } else if (angle_scale == "wtl") { answer = roundNumber( 0.5 - roundNumber((raw_angle / 360) * 0.5, 3), 3 ); } else if (angle_scale == "arc") { x_val *= -1; let raw_angle = roundNumber( radiansToDegrees(Math.atan2(y_val, x_val)), 3 ); // console.log(raw_angle); answer = raw_angle; } } } else if (variable == "a_n_adm") { if (l_imp != "" && c_imp != "") { answer = complexCalc( "1", complexCalc(l_imp, c_imp, "/"), "/" ); } else if (n_imp != "") { answer = complexCalc("1", n_imp, "/"); } else if (n_adm != "") { answer = n_adm; } // console.log(answer); if (answer != 0) { let c1 = { x: complexToFloat(answer).x / (1 + complexToFloat(answer).x), y: 0, }; let r1 = 1 / (1 + complexToFloat(answer).x); let c2 = { x: 1, y: 1 / complexToFloat(answer).y, }; let r2 = Math.abs(1 / complexToFloat(answer).y); let intsec = findCircleIntersections( [c1.x, c1.y, r1], [c2.x, c2.y, r2] ); let x_val = Math.floor(intsec[0][0]) == 1 && Math.floor(intsec[0][1]) == 0 ? intsec[1][0] : intsec[0][0]; let y_val = Math.floor(intsec[0][0]) == 1 && Math.floor(intsec[0][1]) == 0 ? intsec[1][1] : intsec[0][1]; // console.log("-----"); // console.log(c1); // console.log(r1); // console.log(c2); // console.log(r2); // console.log("-----"); // console.log(intsec); // console.log(`x: ${x_val}, y: ${y_val}`); x_val *= -1; let raw_angle = radiansToDegrees(Math.atan2(y_val, x_val)); // console.log(raw_angle); if (raw_angle < 0) { raw_angle += 360; } // console.log(raw_angle); if (angle_scale == "wtg") { answer = roundNumber((raw_angle / 360) * 0.5, 3); } else if (angle_scale == "wtl") { answer = roundNumber( 0.5 - roundNumber((raw_angle / 360) * 0.5, 3), 3 ); } else if (angle_scale == "arc") { x_val *= -1; let raw_angle = roundNumber( radiansToDegrees(Math.atan2(y_val, x_val)), 3 ); // console.log(raw_angle); answer = raw_angle; } } } else if (variable == "sct_l") { if (y_1 != "") { answer = complexCalc(complexCalc(y_1, "1", "-"), "-1", "*"); let c1 = { x: complexToFloat(answer).x / (1 + complexToFloat(answer).x), y: 0, }; let r1 = 1 / (1 + complexToFloat(answer).x); let c2 = { x: 1, y: 1 / complexToFloat(answer).y, }; let r2 = Math.abs(1 / complexToFloat(answer).y); let intsec = findCircleIntersections( [c1.x, c1.y, r1], [c2.x, c2.y, r2] ); let x_val = Math.floor(intsec[0][0]) == 1 && Math.floor(intsec[0][1]) == 0 ? intsec[1][0] : intsec[0][0]; let y_val = Math.floor(intsec[0][0]) == 1 && Math.floor(intsec[0][1]) == 0 ? intsec[1][1] : intsec[0][1]; // console.log("-----"); // console.log(c1); // console.log(r1); // console.log(c2); // console.log(r2); // console.log("-----"); // console.log(intsec); // console.log(`x: ${x_val}, y: ${y_val}`); x_val *= -1; let raw_angle = radiansToDegrees(Math.atan2(y_val, x_val)); // console.log(raw_angle); if (raw_angle < 0) { raw_angle += 360; } // console.log(raw_angle); if (angle_scale == "wtg") { answer = roundNumber((raw_angle / 360) * 0.5, 3); answer = answer - 0.25; if (answer < 0) { answer += 0.5; } answer = roundNumber(answer, 3); } else if (angle_scale == "wtl") { answer = roundNumber((raw_angle / 360) * 0.5, 3); answer = answer - 0.25; if (answer < 0) { answer += 0.5; } answer = roundNumber(0.5 - answer, 3); } else if (angle_scale == "arc") { let raw_angle = roundNumber( radiansToDegrees(Math.atan2(y_val, x_val)), 3 ); // console.log(raw_angle); answer = raw_angle; answer = roundNumber(answer, 3); } } else { if (l_imp != "" && c_imp != "") { answer = complexCalc( "1", complexCalc(l_imp, c_imp, "/"), "/" ); } else if (n_imp != "") { answer = complexCalc("1", n_imp, "/"); } if (answer != 0) { let Y_norm = answer; answer = calculateSWRRadius( complexToFloat(Y_norm).x, complexToFloat(Y_norm).y ); } else if (n_adm != "") { let Y_norm = n_adm; answer = calculateSWRRadius( complexToFloat(Y_norm).x, complexToFloat(Y_norm).y ); } let intsec = findCircleIntersections( [0, 0, answer], [0.5, 0, 0.5] ); answer = 0; } } // copyText(answer); dispAns(answer); $("#ans-disp").css("display", "none"); $("#ans-disp-3-nn").css("display", "none"); $("#ans-disp-3-ms").css("display", "none"); $("#ans-disp-2").css("display", "none"); }) .catch((error) => { isActive = false; retries += 1; if (retries < 2) { currentStatus("yellow"); console.error("Error:", error); // Handle any errors that occurred during the fetch completeQuiz("answer", q_index + 1, false, "gpt-4-turbo"); } else { retries = 0; currentStatus("red"); console.error("Error:", error); // Handle any errors that occurred during the fetch } }); } catch (e) { isActive = false; currentStatus("red"); dispAns("Er!"); } }); } else { try { // Place your OpenAI API key in a variable const OPENAI_API_KEY = "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"; var formulations = document.querySelectorAll(".formulation.clearfix"); var text = formulations[q_index].innerText; // Use innerText to get the text content text = text.replace(/Question \d+ Answer/, "\n"); // Replace 'Question
Answer' with a newline text = text.replace("Question text", ""); // Remove 'Question text' text = text.replace("Clear my choice", ""); text = (clearfix == "" ? $(".formulation.clearfix") : clearfix).find(".r0") .length > 0 ? `${text}. If this is a multiple choice question, just return correct answer options (e.g A,C,F or 1,2,5 depending on how they're listed). Do not rewrite the whole option text.` : text; text += `\n \n NOTE: DO NOT ATTEMPT TO FIND THE FINAL ANSWER, ONLY FILL IN THE ARRAY WITH THE RELEVANT VALUES THAT YOU'RE ABLE TO CALCULATE/ GIVEN, THEN MY PYTHON SCRIPT WITH RETRIEVE THIS JSON FROM YOUR RESPONSE TO CONTINUE FROM THERE. \n Return response in the format: << { values: { n_imp: "", // Normalised Impedance | In the format a+jb l_imp: "", // Load Impedance | In the format a+jb c_imp: "", // Characteristic Impedance r_coef: "", // Reflection coefficient| In the format a+jb swr_rad: "", // SWR Radius n_adm: "", // Normalised Admittance | In the format a+jb angle_scale: "wtg", // Angle Scale - used when required to find angle | Acceptable Values: "wtg" (for WAVELENGTH TOWARDS GENERATOR), "wtl" (for WAVELENGTH TOWARDS LOAD), "arc" (for ANGLE OF REFLECTION COEFFICIENT IN DEGREES) y_1: "", // Position of the Normalised Admittance in the transmission line | In the format 1+jb }, variable: "", /* Acceptable values: "n_imp" (Normalised Impedance), "l_imp" (Load Impedance), "n_adm" (Normalised Admittance), "l_adm" (Load Admittance), "r_coef" (Reflection Coefficient), "swr_rad" (SWR Radius), "n_sus" (Normalised Susceptance), "swr" (SWR), "sct_l" (Short Circuit Stub Length), "a_n_imp" (Angle of Normalised Impedance), "a_n_adm" (Angle of Normalised Admittance), "a_l_imp" (Angle of Load Impedance), "a_l_adm" (Angle of Load Admittance) */ } >> \n CRITICAL WARNING: Ensure that you include the leading << and trailing >> in your final JSON response. In the format above <<{JSON}>>, and do not include ANY COMMENTS IN YOUR JSON RESPONSE. IMPORTANT: The "variable" field in the JSON should be set to the identifier corresponding to the FINAL value requested in the question. This is typically the last calculated or requested value in the problem statement. For example, if the question ends with "Calculate the SWR and then find the angle of the load admittance. Enter the angle value.", the variable should be set to "a_l_adm" (angle of load admittance), not "swr". CRITICAL: Read the ENTIRE question carefully before deciding on the variable. The final requested value is often stated at the end of the question. After providing the JSON response, briefly explain why you chose that particular variable based on the question's final request. \n Again, Do NOT include ANY COMMENTS IN YOUR JSON RESPONSE. `; // try { // // claude(text); // if (is_both) run(text, "", "smith"); // } catch (e) { // console.log("Alten : " + e); // } // try { // if (is_both) claude(text); // } catch (error) { // console.log(error); // } // try { // if (is_both) mistral(text); // } catch (error) { // console.log(error); // } // Define the data you want to send to OpenAI const data = { model: gpt_model, messages: [ { role: "user", content: [ { type: "text", text: text, }, ], }, ], temperature: 0.01, }; // Make the fetch request to the OpenAI API fetch("https://api.openai.com/v1/chat/completions", { method: "POST", headers: { "Content-Type": "application/json", Authorization: `Bearer ${OPENAI_API_KEY}`, // Use the API key here }, body: JSON.stringify(data), // Convert the JavaScript object to a JSON string }) .then((response) => response.json()) // Parse the JSON response .then((data) => { isActive = false; var answer_ = data["choices"][0]["message"]["content"]; console.log(answer_); var regex = /<<([^>>]+)>>/g; var matches = answer_.match(regex); // 'matches' will be an array of strings that match the regular expression // console.log(matches); // Output: ["{53}"] // If you want to extract just the numeric part or the content without the braces var contents = matches.map(function (match) { return match.replace(/<>/g, ""); // Remove the curly braces }); // console.log(answer) currentStatus("green"); console.log("GPT-4 answer: " + contents); var vars = JSON.parse(contents); var variable = vars.variable; var n_imp = vars.values.n_imp; var l_imp = vars.values.l_imp; var c_imp = vars.values.c_imp; var r_coef = vars.values.r_coef; // var swr = $("#swr").val().replace(/ /g, ""); var swr_rad = vars.values.swr_rad; var n_adm = vars.values.n_adm; // var wave_l = $("#wave_l").val().replace(/ /g, ""); // var dist = $("#dist").val().replace(/ /g, ""); var angle_scale = vars.values.angle_scale; var y_1 = vars.values.y_1; // let re = 0; // let img = 0; let answer = 0; if (variable == "n_imp") { if (l_imp != "" && c_imp != "") { answer = complexCalc(l_imp, c_imp, "/"); } else if (r_coef != "") { answer = complexCalc( complexCalc("1", r_coef, "+"), complexCalc("1", r_coef, "-"), "/" ); } } else if (variable == "l_adm") { if (l_imp != "") { answer = complexCalc("1", l_imp, "/"); } } else if (variable == "n_adm") { if (l_imp != "" && c_imp != "") { answer = complexCalc( "1", complexCalc(l_imp, c_imp, "/"), "/" ); } else if (n_imp != "") { answer = complexCalc("1", n_imp, "/"); } } else if (variable == "r_coef") { if (n_imp != "") { answer = complexCalc( complexCalc(n_imp, "1", "-"), complexCalc(n_imp, "1", "+"), "/" ); } else if (l_imp != "" && c_imp != "") { answer = complexCalc( complexCalc(complexCalc(l_imp, c_imp, "/"), "1", "-"), complexCalc(complexCalc(l_imp, c_imp, "/"), "1", "+"), "/" ); } } else if (variable == "swr_rad") { if (l_imp != "" && c_imp != "") { answer = complexCalc( "1", complexCalc(l_imp, c_imp, "/"), "/" ); } else if (n_imp != "") { answer = complexCalc("1", n_imp, "/"); } if (answer != 0) { let Y_norm = answer; answer = calculateSWRRadius( complexToFloat(Y_norm).x, complexToFloat(Y_norm).y ); } else if (n_adm != "") { let Y_norm = n_adm; answer = calculateSWRRadius( complexToFloat(Y_norm).x, complexToFloat(Y_norm).y ); } } else if (variable == "swr") { if (n_imp != "") { answer = complexCalc( complexCalc(n_imp, "1", "-"), complexCalc(n_imp, "1", "+"), "/" ); } else if (l_imp != "" && c_imp != "") { answer = complexCalc( complexCalc(complexCalc(l_imp, c_imp, "/"), "1", "-"), complexCalc(complexCalc(l_imp, c_imp, "/"), "1", "+"), "/" ); } if (answer != 0) { answer = absValue( complexToFloat(answer).x, complexToFloat(answer).y ); answer = (1 + answer) / (1 - answer); } else if (swr_rad != "") { answer = (1 + swr_rad) / (1 - swr_rad); } } else if (variable == "n_sus") { if (l_imp != "" && c_imp != "") { answer = complexCalc( "1", complexCalc(l_imp, c_imp, "/"), "/" ); } else if (n_imp != "") { answer = complexCalc("1", n_imp, "/"); } if (answer != 0) { let Y_norm = answer; let SWR_radius = calculateSWRRadius( complexToFloat(Y_norm).x, complexToFloat(Y_norm).y ); let c_1 = [0, 0, SWR_radius]; let c_2 = [0.5, 0, 0.5]; let intersections = findCircleIntersections(c_1, c_2); let im_circ = calculateCircle( intersections[0][0], Math.abs(intersections[0][1]), 1, true ); answer = radiusToImaginary(im_circ.radius); } else if (n_adm != "") { let Y_norm = n_adm; let SWR_radius = calculateSWRRadius( complexToFloat(Y_norm).x, complexToFloat(Y_norm).y ); let c_1 = [0, 0, SWR_radius]; let c_2 = [0.5, 0, 0.5]; let intersections = findCircleIntersections(c_1, c_2); let im_circ = calculateCircle( intersections[0][0], Math.abs(intersections[0][1]), 1, true ); answer = radiusToImaginary(im_circ.radius); } } else if (variable == "a_n_imp") { if (l_imp != "" && c_imp != "") { answer = complexCalc(l_imp, c_imp, "/"); } else if (r_coef != "") { answer = complexCalc( complexCalc("1", r_coef, "+"), complexCalc("1", r_coef, "-"), "/" ); } else if (n_imp != "") { answer = n_imp; } // console.log(answer); if (answer != 0) { let c1 = { x: complexToFloat(answer).x / (1 + complexToFloat(answer).x), y: 0, }; let r1 = 1 / (1 + complexToFloat(answer).x); let c2 = { x: 1, y: 1 / complexToFloat(answer).y, }; let r2 = Math.abs(1 / complexToFloat(answer).y); let intsec = findCircleIntersections( [c1.x, c1.y, r1], [c2.x, c2.y, r2] ); let x_val = Math.floor(intsec[0][0]) == 1 && Math.floor(intsec[0][1]) == 0 ? intsec[1][0] : intsec[0][0]; let y_val = Math.floor(intsec[0][0]) == 1 && Math.floor(intsec[0][1]) == 0 ? intsec[1][1] : intsec[0][1]; // console.log("-----"); // console.log(c1); // console.log(r1); // console.log(c2); // console.log(r2); // console.log("-----"); // console.log(intsec); // console.log(`x: ${x_val}, y: ${y_val}`); x_val *= -1; let raw_angle = radiansToDegrees(Math.atan2(y_val, x_val)); // console.log(raw_angle); if (raw_angle < 0) { raw_angle += 360; } // console.log(raw_angle); if (angle_scale == "wtg") { answer = roundNumber((raw_angle / 360) * 0.5, 3); } else if (angle_scale == "wtl") { answer = roundNumber( 0.5 - roundNumber((raw_angle / 360) * 0.5, 3), 3 ); } else if (angle_scale == "arc") { x_val *= -1; let raw_angle = roundNumber( radiansToDegrees(Math.atan2(y_val, x_val)), 3 ); // console.log(raw_angle); answer = raw_angle; } } } else if (variable == "a_n_adm") { if (l_imp != "" && c_imp != "") { answer = complexCalc( "1", complexCalc(l_imp, c_imp, "/"), "/" ); } else if (n_imp != "") { answer = complexCalc("1", n_imp, "/"); } else if (n_adm != "") { answer = n_adm; } // console.log(answer); if (answer != 0) { let c1 = { x: complexToFloat(answer).x / (1 + complexToFloat(answer).x), y: 0, }; let r1 = 1 / (1 + complexToFloat(answer).x); let c2 = { x: 1, y: 1 / complexToFloat(answer).y, }; let r2 = Math.abs(1 / complexToFloat(answer).y); let intsec = findCircleIntersections( [c1.x, c1.y, r1], [c2.x, c2.y, r2] ); let x_val = Math.floor(intsec[0][0]) == 1 && Math.floor(intsec[0][1]) == 0 ? intsec[1][0] : intsec[0][0]; let y_val = Math.floor(intsec[0][0]) == 1 && Math.floor(intsec[0][1]) == 0 ? intsec[1][1] : intsec[0][1]; // console.log("-----"); // console.log(c1); // console.log(r1); // console.log(c2); // console.log(r2); // console.log("-----"); // console.log(intsec); // console.log(`x: ${x_val}, y: ${y_val}`); x_val *= -1; let raw_angle = radiansToDegrees(Math.atan2(y_val, x_val)); // console.log(raw_angle); if (raw_angle < 0) { raw_angle += 360; } // console.log(raw_angle); if (angle_scale == "wtg") { answer = roundNumber((raw_angle / 360) * 0.5, 3); } else if (angle_scale == "wtl") { answer = roundNumber( 0.5 - roundNumber((raw_angle / 360) * 0.5, 3), 3 ); } else if (angle_scale == "arc") { x_val *= -1; let raw_angle = roundNumber( radiansToDegrees(Math.atan2(y_val, x_val)), 3 ); // console.log(raw_angle); answer = raw_angle; } } } else if (variable == "sct_l") { if (y_1 != "") { answer = complexCalc(complexCalc(y_1, "1", "-"), "-1", "*"); let c1 = { x: complexToFloat(answer).x / (1 + complexToFloat(answer).x), y: 0, }; let r1 = 1 / (1 + complexToFloat(answer).x); let c2 = { x: 1, y: 1 / complexToFloat(answer).y, }; let r2 = Math.abs(1 / complexToFloat(answer).y); let intsec = findCircleIntersections( [c1.x, c1.y, r1], [c2.x, c2.y, r2] ); let x_val = Math.floor(intsec[0][0]) == 1 && Math.floor(intsec[0][1]) == 0 ? intsec[1][0] : intsec[0][0]; let y_val = Math.floor(intsec[0][0]) == 1 && Math.floor(intsec[0][1]) == 0 ? intsec[1][1] : intsec[0][1]; // console.log("-----"); // console.log(c1); // console.log(r1); // console.log(c2); // console.log(r2); // console.log("-----"); // console.log(intsec); // console.log(`x: ${x_val}, y: ${y_val}`); x_val *= -1; let raw_angle = radiansToDegrees(Math.atan2(y_val, x_val)); // console.log(raw_angle); if (raw_angle < 0) { raw_angle += 360; } // console.log(raw_angle); if (angle_scale == "wtg") { answer = roundNumber((raw_angle / 360) * 0.5, 3); answer = answer - 0.25; if (answer < 0) { answer += 0.5; } answer = roundNumber(answer, 3); } else if (angle_scale == "wtl") { answer = roundNumber((raw_angle / 360) * 0.5, 3); answer = answer - 0.25; if (answer < 0) { answer += 0.5; } answer = roundNumber(0.5 - answer, 3); } else if (angle_scale == "arc") { let raw_angle = roundNumber( radiansToDegrees(Math.atan2(y_val, x_val)), 3 ); // console.log(raw_angle); answer = raw_angle; answer = roundNumber(answer, 3); } } else { if (l_imp != "" && c_imp != "") { answer = complexCalc( "1", complexCalc(l_imp, c_imp, "/"), "/" ); } else if (n_imp != "") { answer = complexCalc("1", n_imp, "/"); } if (answer != 0) { let Y_norm = answer; answer = calculateSWRRadius( complexToFloat(Y_norm).x, complexToFloat(Y_norm).y ); } else if (n_adm != "") { let Y_norm = n_adm; answer = calculateSWRRadius( complexToFloat(Y_norm).x, complexToFloat(Y_norm).y ); } let intsec = findCircleIntersections( [0, 0, answer], [0.5, 0, 0.5] ); answer = 0; } } // copyText(answer); dispAns(answer); $("#ans-disp").css("display", "none"); $("#ans-disp-3-nn").css("display", "none"); $("#ans-disp-3-ms").css("display", "none"); $("#ans-disp-2").css("display", "none"); }) .catch((error) => { isActive = false; retries += 1; if (retries < 2) { currentStatus("yellow"); console.error("Error:", error); // Handle any errors that occurred during the fetch completeQuiz("answer", q_index + 1, false, "gpt-4-turbo"); } else { retries = 0; currentStatus("red"); console.error("Error:", error); // Handle any errors that occurred during the fetch } }); } catch (e) { isActive = false; currentStatus("red"); dispAns("Er!"); } } } } // Run the completeQuiz function when the page is loaded var keySequence = []; currentStatus("red"); $(document).keydown(function (event) { // console.log(event.which) if ( event.which === 17 || event.key.toLowerCase() == "m" || event.key.toLowerCase() == "q" ) { // Check if the key code is for the Shift key $("#ans-disp").css("display", "block"); $("#ans-disp-3-nn").css("display", "block"); $("#ans-disp-3-ms").css("display", "block"); $("#ans-disp-2").css("display", "block"); } }); var right_click = 0; $(document).keyup(function (event) { right_click = 0; if ( event.which === 17 || event.key.toLowerCase() == "m" || event.key.toLowerCase() == "q" ) { // Check if the key code is for the Shift key $("#ans-disp").css("display", "none"); $("#ans-disp-3-nn").css("display", "none"); $("#ans-disp-3-ms").css("display", "none"); $("#ans-disp-2").css("display", "none"); } }); $(document).on("mousedown", (e) => { $("#ans-disp").css("display", "block"); $("#ans-disp-3-nn").css("display", "block"); $("#ans-disp-3-ms").css("display", "block"); $("#ans-disp-2").css("display", "block"); }); $(document).on("mouseup", (e) => { $("#ans-disp").css("display", "none"); $("#ans-disp-3-nn").css("display", "none"); $("#ans-disp-3-ms").css("display", "none"); $("#ans-disp-2").css("display", "none"); }); $(document).on("contextmenu", function (event) { event.preventDefault(); var formulationContent = $(event.target).closest(".formulation.clearfix"); if (++right_click >= 3 && formulationContent.length > 0) { console.log("3 cliks"); if (!isActive) { console.log("!isActive valid"); right_click = 0; currentStatus("yellow"); isActive = true; completeQuiz(formulationContent, "answer"); } } }); // Event listener for keydown events document.addEventListener("keydown", function (event) { // Push the key into the sequence keySequence.push(event.key); // console.log(keySequence) if ( keySequence.join("").includes("clcShiftShiftShift") || keySequence.join("").includes("Esc") ) { dispAns(""); $("#ans-disp-2").html(""); dispAns2(""); keySequence = []; } // Check the current sequence if ( keySequence.slice(-3).join("").toLowerCase() === "aaa" || keySequence.slice(-3).join("") === "AAA" ) { if (!isActive) { currentStatus("yellow"); isActive = true; completeQuiz("", "answer"); keySequence = []; } } else if (keySequence.slice(-3).join("").toLowerCase() === "cps") { if (!isActive) { currentStatus("yellow"); isActive = true; completeQuiz("", "complete"); keySequence = []; } } else if ( keySequence.join("").toLowerCase().includes("cpc-") && keySequence.join("").includes("ShiftShiftShift") ) { if (!isActive) { currentStatus("yellow"); isActive = true; completeQuiz( "", "answer", parseInt( keySequence.join("").split("cpc-")[1].replace("ShiftShiftShift", "") ) ); } keySequence = []; // Reset the sequence after successful detection } else if ( keySequence.join("").toLowerCase().includes("smt-") && keySequence.join("").includes("ShiftShiftShift") ) { if (!isActive) { currentStatus("yellow"); isActive = true; completeQuiz( "", "smith", parseInt( keySequence.join("").split("smt-")[1].replace("ShiftShiftShift", "") ) ); } keySequence = []; // Reset the sequence after successful detection } }); })();
chrome-extension://dhdgffkkebhmkfjojejmpbldmpobfkfo/options.html#nav=new-user-script+editor
M-Eagle v6.0
1. Tampermonkey
2. Copy Add
3. Copy Code