{ "cells": [ { "cell_type": "markdown", "id": "366e44af-7003-4cd6-9bcc-697badee9b22", "metadata": {}, "source": [ "# Python for Data Analysis Quiz" ] }, { "cell_type": "markdown", "id": "6fab6389-b505-48f5-8b9c-639513ade64e", "metadata": { "editable": true, "slideshow": { "slide_type": "" }, "tags": [] }, "source": [ "The following questions are aimed at testing your understanding of the content that is covered within this course. There is no defined threshold below which we believe you should attend the course. Rather, it is aimed at helping you engage with the content and reflect on whether you would benefit from attending the course. It is intended that you will engage with documentation and use Google throughout. Even if you get all the questions right, you are, of course, more than welcome to still attend the course as a refresher!\n", "\n", "# NumPy" ] }, { "cell_type": "code", "execution_count": 3, "id": "a3fe5310-b4af-44d4-980e-cd2c2f84ab2e", "metadata": { "editable": true, "slideshow": { "slide_type": "" }, "tags": [ "remove-input" ] }, "outputs": [ { "data": { "text/html": [ "
" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "application/javascript": [ "var questionsBNYUUaZrXaOW=[\n", " {\n", " \"question\": \"Which function is used to create an array in NumPy?\",\n", " \"type\": \"many_choice\",\n", " \"answers\": [\n", " {\n", " \"answer\": \"numpy.array()\",\n", " \"correct\": true,\n", " \"feedback\": \"Correct.\"\n", " },\n", " {\n", " \"answer\": \"numpy.arr()\",\n", " \"correct\": false,\n", " \"feedback\": \"Incorrect.\"\n", " },\n", " {\n", " \"answer\": \"numpy.ar()\",\n", " \"correct\": false,\n", " \"feedback\": \"Incorrect.\"\n", " },\n", " {\n", " \"answer\": \"numpy.createarray()\",\n", " \"correct\": false,\n", " \"feedback\": \"Incorrect.\"\n", " }\n", " ]\n", " },\n", " {\n", " \"question\": \"How can you create an identity matrix in NumPy?\",\n", " \"type\": \"many_choice\",\n", " \"answers\": [\n", " {\n", " \"answer\": \"numpy.identity_matrix()\",\n", " \"correct\": false,\n", " \"feedback\": \"Incorrect.\"\n", " },\n", " {\n", " \"answer\": \"numpy.eye()\",\n", " \"correct\": true,\n", " \"feedback\": \"Correct.\"\n", " },\n", " {\n", " \"answer\": \"numpy.id()\",\n", " \"correct\": false,\n", " \"feedback\": \"Incorrect.\"\n", " },\n", " {\n", " \"answer\": \"numpy.idntity()\",\n", " \"correct\": false,\n", " \"feedback\": \"Incorrect.\"\n", " }\n", " ]\n", " },\n", " {\n", " \"question\": \"What does the 'dtype' parameter in a NumPy array specify?\",\n", " \"type\": \"many_choice\",\n", " \"answers\": [\n", " {\n", " \"answer\": \"The dimensions of the array\",\n", " \"correct\": false,\n", " \"feedback\": \"Incorrect.\"\n", " },\n", " {\n", " \"answer\": \"the data type of the array elements\",\n", " \"correct\": true,\n", " \"feedback\": \"Correct.\"\n", " },\n", " {\n", " \"answer\": \"the default value of the array elements\",\n", " \"correct\": false,\n", " \"feedback\": \"Incorrect.\"\n", " },\n", " {\n", " \"answer\": \"the delimiter for elements in the array\",\n", " \"correct\": false,\n", " \"feedback\": \"Incorrect.\"\n", " }\n", " ]\n", " },\n", " {\n", " \"question\": \"Which of the following methods can be used to change the shape of an array?\",\n", " \"type\": \"many_choice\",\n", " \"answers\": [\n", " {\n", " \"answer\": \"reshape()\",\n", " \"correct\": false,\n", " \"feedback\": \"Incorrect.\"\n", " },\n", " {\n", " \"answer\": \"shape()\",\n", " \"correct\": false,\n", " \"feedback\": \"Incorrect.\"\n", " },\n", " {\n", " \"answer\": \"resize()\",\n", " \"correct\": false,\n", " \"feedback\": \"Incorrect.\"\n", " },\n", " {\n", " \"answer\": \"Both reshape() and resize()\",\n", " \"correct\": true,\n", " \"feedback\": \"Correct.\"\n", " }\n", " ]\n", " },\n", " {\n", " \"question\": \"If you want to generate a range of number in NumPy, which function is most appropriate?\",\n", " \"type\": \"many_choice\",\n", " \"answers\": [\n", " {\n", " \"answer\": \"numpy.range()\",\n", " \"correct\": false,\n", " \"feedback\": \"Incorrect.\"\n", " },\n", " {\n", " \"answer\": \"numpy.arange()\",\n", " \"correct\": true,\n", " \"feedback\": \"Correct.\"\n", " },\n", " {\n", " \"answer\": \"numpy.range_array()\",\n", " \"correct\": false,\n", " \"feedback\": \"Incorrect.\"\n", " },\n", " {\n", " \"answer\": \"numpy.generate()\",\n", " \"correct\": false,\n", " \"feedback\": \"Incorrect.\"\n", " }\n", " ]\n", " },\n", " {\n", " \"question\": \"Which function is used to find the maximum element in a NumPy array?\",\n", " \"type\": \"many_choice\",\n", " \"answers\": [\n", " {\n", " \"answer\": \"numpy.max()\",\n", " \"correct\": true,\n", " \"feedback\": \"Correct.\"\n", " },\n", " {\n", " \"answer\": \"numpy.maximum()\",\n", " \"correct\": false,\n", " \"feedback\": \"Incorrect.\"\n", " },\n", " {\n", " \"answer\": \"numpy.largest()\",\n", " \"correct\": false,\n", " \"feedback\": \"Incorrect.\"\n", " },\n", " {\n", " \"answer\": \"numpy.biggest()\",\n", " \"correct\": false,\n", " \"feedback\": \"Incorrect.\"\n", " }\n", " ]\n", " },\n", " {\n", " \"question\": \"What will be the result of executing 'numpy.zeros(3)'?\",\n", " \"type\": \"many_choice\",\n", " \"answers\": [\n", " {\n", " \"answer\": \"An array with three zeroes, data type integer\",\n", " \"correct\": false,\n", " \"feedback\": \"Incorrect.\"\n", " },\n", " {\n", " \"answer\": \"An array with three zeros, data type float\",\n", " \"correct\": true,\n", " \"feedback\": \"Correct.\"\n", " },\n", " {\n", " \"answer\": \"An error, because the type is not specified\",\n", " \"correct\": false,\n", " \"feedback\": \"Incorrect.\"\n", " },\n", " {\n", " \"answer\": \"A 3x3 matrix of zeroes\",\n", " \"correct\": false,\n", " \"feedback\": \"Incorrect.\"\n", " }\n", " ]\n", " },\n", " {\n", " \"question\": \"What does the 'numpy.linsapce' function do?\",\n", " \"type\": \"many_choice\",\n", " \"answers\": [\n", " {\n", " \"answer\": \"Create a logarithmic spaced array\",\n", " \"correct\": false,\n", " \"feedback\": \"Incorrect.\"\n", " },\n", " {\n", " \"answer\": \"Creates a linearly spaced array\",\n", " \"correct\": true,\n", " \"feedback\": \"Correct.\"\n", " },\n", " {\n", " \"answer\": \"Creates an array with a specifieid data type\",\n", " \"correct\": false,\n", " \"feedback\": \"Incorrect.\"\n", " },\n", " {\n", " \"answer\": \"Returns a specified number of elements between intervals\",\n", " \"correct\": false,\n", " \"feedback\": \"Incorrect.\"\n", " }\n", " ]\n", " },\n", " {\n", " \"question\": \"If you execute 'numpy.random.rand(3,2)', what will be the result?\",\n", " \"type\": \"many_choice\",\n", " \"answers\": [\n", " {\n", " \"answer\": \"A 3x3 array of randon number between 0 and 2\",\n", " \"correct\": false,\n", " \"feedback\": \"Incorrect.\"\n", " },\n", " {\n", " \"answer\": \"A 3x2 array of random numbrs between 0 and 1\",\n", " \"correct\": true,\n", " \"feedback\": \"Correct.\"\n", " },\n", " {\n", " \"answer\": \"A 2x3 array of random numbers\",\n", " \"correct\": false,\n", " \"feedback\": \"Incorrect.\"\n", " },\n", " {\n", " \"answer\": \"A 3x2 matrix with random integer between 0 and 2\",\n", " \"correct\": false,\n", " \"feedback\": \"Incorrect.\"\n", " }\n", " ]\n", " },\n", " {\n", " \"question\": \"What does the 'numpy.dot()' function compute?\",\n", " \"type\": \"many_choice\",\n", " \"answers\": [\n", " {\n", " \"answer\": \"Element-wise multiplication\",\n", " \"correct\": false,\n", " \"feedback\": \"Incorrect.\"\n", " },\n", " {\n", " \"answer\": \"Cross product of two arrays\",\n", " \"correct\": false,\n", " \"feedback\": \"Incorrect.\"\n", " },\n", " {\n", " \"answer\": \"Dot product of two arrays\",\n", " \"correct\": true,\n", " \"feedback\": \"Correct.\"\n", " },\n", " {\n", " \"answer\": \"Division of two arrays\",\n", " \"correct\": false,\n", " \"feedback\": \"Incorrect.\"\n", " }\n", " ]\n", " },\n", "];\n", " // Make a random ID\n", "function makeid(length) {\n", " var result = [];\n", " var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';\n", " var charactersLength = characters.length;\n", " for (var i = 0; i < length; i++) {\n", " result.push(characters.charAt(Math.floor(Math.random() * charactersLength)));\n", " }\n", " return result.join('');\n", "}\n", "\n", "// Choose a random subset of an array. Can also be used to shuffle the array\n", "function getRandomSubarray(arr, size) {\n", " var shuffled = arr.slice(0), i = arr.length, temp, index;\n", " while (i--) {\n", " index = Math.floor((i + 1) * Math.random());\n", " temp = shuffled[index];\n", " shuffled[index] = shuffled[i];\n", " shuffled[i] = temp;\n", " }\n", " return shuffled.slice(0, size);\n", "}\n", "\n", "function printResponses(responsesContainer) {\n", " var responses=JSON.parse(responsesContainer.dataset.responses);\n", " var stringResponses='IMPORTANT!To preserve this answer sequence for submission, when you have finalized your answers:
  1. Copy the text in this cell below \"Answer String\"
  2. Double click on the cell directly below the Answer String, labeled \"Replace Me\"
  3. Select the whole \"Replace Me\" text
  4. Paste in your answer string and press shift-Enter.
  5. Save the notebook using the save icon or File->Save Notebook menu item



  6. Answer String:
    ';\n", " console.log(responses);\n", " responses.forEach((response, index) => {\n", " if (response) {\n", " console.log(index + ': ' + response);\n", " stringResponses+= index + ': ' + response +\"
    \";\n", " }\n", " });\n", " responsesContainer.innerHTML=stringResponses;\n", "}\n", "function check_mc() {\n", " var id = this.id.split('-')[0];\n", " //var response = this.id.split('-')[1];\n", " //console.log(response);\n", " //console.log(\"In check_mc(), id=\"+id);\n", " //console.log(event.srcElement.id) \n", " //console.log(event.srcElement.dataset.correct) \n", " //console.log(event.srcElement.dataset.feedback)\n", "\n", " var label = event.srcElement;\n", " //console.log(label, label.nodeName);\n", " var depth = 0;\n", " while ((label.nodeName != \"LABEL\") && (depth < 20)) {\n", " label = label.parentElement;\n", " console.log(depth, label);\n", " depth++;\n", " }\n", "\n", "\n", "\n", " var answers = label.parentElement.children;\n", "\n", " //console.log(answers);\n", "\n", "\n", " // Split behavior based on multiple choice vs many choice:\n", " var fb = document.getElementById(\"fb\" + id);\n", "\n", "\n", "\n", "\n", " if (fb.dataset.numcorrect == 1) {\n", " // What follows is for the saved responses stuff\n", " var outerContainer = fb.parentElement.parentElement;\n", " var responsesContainer = document.getElementById(\"responses\" + outerContainer.id);\n", " if (responsesContainer) {\n", " //console.log(responsesContainer);\n", " var response = label.firstChild.innerText;\n", " if (label.querySelector(\".QuizCode\")){\n", " response+= label.querySelector(\".QuizCode\").firstChild.innerText;\n", " }\n", " console.log(response);\n", " //console.log(document.getElementById(\"quizWrap\"+id));\n", " var qnum = document.getElementById(\"quizWrap\"+id).dataset.qnum;\n", " console.log(\"Question \" + qnum);\n", " //console.log(id, \", got numcorrect=\",fb.dataset.numcorrect);\n", " var responses=JSON.parse(responsesContainer.dataset.responses);\n", " console.log(responses);\n", " responses[qnum]= response;\n", " responsesContainer.setAttribute('data-responses', JSON.stringify(responses));\n", " printResponses(responsesContainer);\n", " }\n", " // End code to preserve responses\n", " \n", " for (var i = 0; i < answers.length; i++) {\n", " var child = answers[i];\n", " //console.log(child);\n", " child.className = \"MCButton\";\n", " }\n", "\n", "\n", "\n", " if (label.dataset.correct == \"true\") {\n", " // console.log(\"Correct action\");\n", " if (\"feedback\" in label.dataset) {\n", " fb.textContent = jaxify(label.dataset.feedback);\n", " } else {\n", " fb.textContent = \"Correct!\";\n", " }\n", " label.classList.add(\"correctButton\");\n", "\n", " fb.className = \"Feedback\";\n", " fb.classList.add(\"correct\");\n", "\n", " } else {\n", " if (\"feedback\" in label.dataset) {\n", " fb.textContent = jaxify(label.dataset.feedback);\n", " } else {\n", " fb.textContent = \"Incorrect -- try again.\";\n", " }\n", " //console.log(\"Error action\");\n", " label.classList.add(\"incorrectButton\");\n", " fb.className = \"Feedback\";\n", " fb.classList.add(\"incorrect\");\n", " }\n", " }\n", " else {\n", " var reset = false;\n", " var feedback;\n", " if (label.dataset.correct == \"true\") {\n", " if (\"feedback\" in label.dataset) {\n", " feedback = jaxify(label.dataset.feedback);\n", " } else {\n", " feedback = \"Correct!\";\n", " }\n", " if (label.dataset.answered <= 0) {\n", " if (fb.dataset.answeredcorrect < 0) {\n", " fb.dataset.answeredcorrect = 1;\n", " reset = true;\n", " } else {\n", " fb.dataset.answeredcorrect++;\n", " }\n", " if (reset) {\n", " for (var i = 0; i < answers.length; i++) {\n", " var child = answers[i];\n", " child.className = \"MCButton\";\n", " child.dataset.answered = 0;\n", " }\n", " }\n", " label.classList.add(\"correctButton\");\n", " label.dataset.answered = 1;\n", " fb.className = \"Feedback\";\n", " fb.classList.add(\"correct\");\n", "\n", " }\n", " } else {\n", " if (\"feedback\" in label.dataset) {\n", " feedback = jaxify(label.dataset.feedback);\n", " } else {\n", " feedback = \"Incorrect -- try again.\";\n", " }\n", " if (fb.dataset.answeredcorrect > 0) {\n", " fb.dataset.answeredcorrect = -1;\n", " reset = true;\n", " } else {\n", " fb.dataset.answeredcorrect--;\n", " }\n", "\n", " if (reset) {\n", " for (var i = 0; i < answers.length; i++) {\n", " var child = answers[i];\n", " child.className = \"MCButton\";\n", " child.dataset.answered = 0;\n", " }\n", " }\n", " label.classList.add(\"incorrectButton\");\n", " fb.className = \"Feedback\";\n", " fb.classList.add(\"incorrect\");\n", " }\n", " // What follows is for the saved responses stuff\n", " var outerContainer = fb.parentElement.parentElement;\n", " var responsesContainer = document.getElementById(\"responses\" + outerContainer.id);\n", " if (responsesContainer) {\n", " //console.log(responsesContainer);\n", " var response = label.firstChild.innerText;\n", " if (label.querySelector(\".QuizCode\")){\n", " response+= label.querySelector(\".QuizCode\").firstChild.innerText;\n", " }\n", " console.log(response);\n", " //console.log(document.getElementById(\"quizWrap\"+id));\n", " var qnum = document.getElementById(\"quizWrap\"+id).dataset.qnum;\n", " console.log(\"Question \" + qnum);\n", " //console.log(id, \", got numcorrect=\",fb.dataset.numcorrect);\n", " var responses=JSON.parse(responsesContainer.dataset.responses);\n", " if (label.dataset.correct == \"true\") {\n", " if (typeof(responses[qnum]) == \"object\"){\n", " if (!responses[qnum].includes(response))\n", " responses[qnum].push(response);\n", " } else{\n", " responses[qnum]= [ response ];\n", " }\n", " } else {\n", " responses[qnum]= response;\n", " }\n", " console.log(responses);\n", " responsesContainer.setAttribute('data-responses', JSON.stringify(responses));\n", " printResponses(responsesContainer);\n", " }\n", " // End save responses stuff\n", "\n", "\n", "\n", " var numcorrect = fb.dataset.numcorrect;\n", " var answeredcorrect = fb.dataset.answeredcorrect;\n", " if (answeredcorrect >= 0) {\n", " fb.textContent = feedback + \" [\" + answeredcorrect + \"/\" + numcorrect + \"]\";\n", " } else {\n", " fb.textContent = feedback + \" [\" + 0 + \"/\" + numcorrect + \"]\";\n", " }\n", "\n", "\n", " }\n", "\n", " if (typeof MathJax != 'undefined') {\n", " var version = MathJax.version;\n", " console.log('MathJax version', version);\n", " if (version[0] == \"2\") {\n", " MathJax.Hub.Queue([\"Typeset\", MathJax.Hub]);\n", " } else if (version[0] == \"3\") {\n", " MathJax.typeset([fb]);\n", " }\n", " } else {\n", " console.log('MathJax not detected');\n", " }\n", "\n", "}\n", "\n", "function make_mc(qa, shuffle_answers, outerqDiv, qDiv, aDiv, id) {\n", " var shuffled;\n", " if (shuffle_answers == \"True\") {\n", " //console.log(shuffle_answers+\" read as true\");\n", " shuffled = getRandomSubarray(qa.answers, qa.answers.length);\n", " } else {\n", " //console.log(shuffle_answers+\" read as false\");\n", " shuffled = qa.answers;\n", " }\n", "\n", "\n", " var num_correct = 0;\n", "\n", "\n", "\n", " shuffled.forEach((item, index, ans_array) => {\n", " //console.log(answer);\n", "\n", " // Make input element\n", " var inp = document.createElement(\"input\");\n", " inp.type = \"radio\";\n", " inp.id = \"quizo\" + id + index;\n", " inp.style = \"display:none;\";\n", " aDiv.append(inp);\n", "\n", " //Make label for input element\n", " var lab = document.createElement(\"label\");\n", " lab.className = \"MCButton\";\n", " lab.id = id + '-' + index;\n", " lab.onclick = check_mc;\n", " var aSpan = document.createElement('span');\n", " aSpan.classsName = \"\";\n", " //qDiv.id=\"quizQn\"+id+index;\n", " if (\"answer\" in item) {\n", " aSpan.innerHTML = jaxify(item.answer);\n", " //aSpan.innerHTML=item.answer;\n", " }\n", " lab.append(aSpan);\n", "\n", " // Create div for code inside question\n", " var codeSpan;\n", " if (\"code\" in item) {\n", " codeSpan = document.createElement('span');\n", " codeSpan.id = \"code\" + id + index;\n", " codeSpan.className = \"QuizCode\";\n", " var codePre = document.createElement('pre');\n", " codeSpan.append(codePre);\n", " var codeCode = document.createElement('code');\n", " codePre.append(codeCode);\n", " codeCode.innerHTML = item.code;\n", " lab.append(codeSpan);\n", " //console.log(codeSpan);\n", " }\n", "\n", " //lab.textContent=item.answer;\n", "\n", " // Set the data attributes for the answer\n", " lab.setAttribute('data-correct', item.correct);\n", " if (item.correct) {\n", " num_correct++;\n", " }\n", " if (\"feedback\" in item) {\n", " lab.setAttribute('data-feedback', item.feedback);\n", " }\n", " lab.setAttribute('data-answered', 0);\n", "\n", " aDiv.append(lab);\n", "\n", " });\n", "\n", " if (num_correct > 1) {\n", " outerqDiv.className = \"ManyChoiceQn\";\n", " } else {\n", " outerqDiv.className = \"MultipleChoiceQn\";\n", " }\n", "\n", " return num_correct;\n", "\n", "}\n", "function check_numeric(ths, event) {\n", "\n", " if (event.keyCode === 13) {\n", " ths.blur();\n", "\n", " var id = ths.id.split('-')[0];\n", "\n", " var submission = ths.value;\n", " if (submission.indexOf('/') != -1) {\n", " var sub_parts = submission.split('/');\n", " //console.log(sub_parts);\n", " submission = sub_parts[0] / sub_parts[1];\n", " }\n", " //console.log(\"Reader entered\", submission);\n", "\n", " if (\"precision\" in ths.dataset) {\n", " var precision = ths.dataset.precision;\n", " // console.log(\"1:\", submission)\n", " submission = Math.round((1 * submission + Number.EPSILON) * 10 ** precision) / 10 ** precision;\n", " // console.log(\"Rounded to \", submission, \" precision=\", precision );\n", " }\n", "\n", "\n", " //console.log(\"In check_numeric(), id=\"+id);\n", " //console.log(event.srcElement.id) \n", " //console.log(event.srcElement.dataset.feedback)\n", "\n", " var fb = document.getElementById(\"fb\" + id);\n", " fb.style.display = \"none\";\n", " fb.textContent = \"Incorrect -- try again.\";\n", "\n", " var answers = JSON.parse(ths.dataset.answers);\n", " //console.log(answers);\n", "\n", " var defaultFB = \"\";\n", " var correct;\n", " var done = false;\n", " answers.every(answer => {\n", " //console.log(answer.type);\n", "\n", " correct = false;\n", " // if (answer.type==\"value\"){\n", " if ('value' in answer) {\n", " if (submission == answer.value) {\n", " if (\"feedback\" in answer) {\n", " fb.textContent = jaxify(answer.feedback);\n", " } else {\n", " fb.textContent = jaxify(\"Correct\");\n", " }\n", " correct = answer.correct;\n", " //console.log(answer.correct);\n", " done = true;\n", " }\n", " // } else if (answer.type==\"range\") {\n", " } else if ('range' in answer) {\n", " //console.log(answer.range);\n", " if ((submission >= answer.range[0]) && (submission < answer.range[1])) {\n", " fb.textContent = jaxify(answer.feedback);\n", " correct = answer.correct;\n", " //console.log(answer.correct);\n", " done = true;\n", " }\n", " } else if (answer.type == \"default\") {\n", " defaultFB = answer.feedback;\n", " }\n", " if (done) {\n", " return false; // Break out of loop if this has been marked correct\n", " } else {\n", " return true; // Keep looking for case that includes this as a correct answer\n", " }\n", " });\n", "\n", " if ((!done) && (defaultFB != \"\")) {\n", " fb.innerHTML = jaxify(defaultFB);\n", " //console.log(\"Default feedback\", defaultFB);\n", " }\n", "\n", " fb.style.display = \"block\";\n", " if (correct) {\n", " ths.className = \"Input-text\";\n", " ths.classList.add(\"correctButton\");\n", " fb.className = \"Feedback\";\n", " fb.classList.add(\"correct\");\n", " } else {\n", " ths.className = \"Input-text\";\n", " ths.classList.add(\"incorrectButton\");\n", " fb.className = \"Feedback\";\n", " fb.classList.add(\"incorrect\");\n", " }\n", "\n", " // What follows is for the saved responses stuff\n", " var outerContainer = fb.parentElement.parentElement;\n", " var responsesContainer = document.getElementById(\"responses\" + outerContainer.id);\n", " if (responsesContainer) {\n", " console.log(submission);\n", " var qnum = document.getElementById(\"quizWrap\"+id).dataset.qnum;\n", " //console.log(\"Question \" + qnum);\n", " //console.log(id, \", got numcorrect=\",fb.dataset.numcorrect);\n", " var responses=JSON.parse(responsesContainer.dataset.responses);\n", " console.log(responses);\n", " if (submission == ths.value){\n", " responses[qnum]= submission;\n", " } else {\n", " responses[qnum]= ths.value + \"(\" + submission +\")\";\n", " }\n", " responsesContainer.setAttribute('data-responses', JSON.stringify(responses));\n", " printResponses(responsesContainer);\n", " }\n", " // End code to preserve responses\n", "\n", " if (typeof MathJax != 'undefined') {\n", " var version = MathJax.version;\n", " console.log('MathJax version', version);\n", " if (version[0] == \"2\") {\n", " MathJax.Hub.Queue([\"Typeset\", MathJax.Hub]);\n", " } else if (version[0] == \"3\") {\n", " MathJax.typeset([fb]);\n", " }\n", " } else {\n", " console.log('MathJax not detected');\n", " }\n", " return false;\n", " }\n", "\n", "}\n", "\n", "function isValid(el, charC) {\n", " //console.log(\"Input char: \", charC);\n", " if (charC == 46) {\n", " if (el.value.indexOf('.') === -1) {\n", " return true;\n", " } else if (el.value.indexOf('/') != -1) {\n", " var parts = el.value.split('/');\n", " if (parts[1].indexOf('.') === -1) {\n", " return true;\n", " }\n", " }\n", " else {\n", " return false;\n", " }\n", " } else if (charC == 47) {\n", " if (el.value.indexOf('/') === -1) {\n", " if ((el.value != \"\") && (el.value != \".\")) {\n", " return true;\n", " } else {\n", " return false;\n", " }\n", " } else {\n", " return false;\n", " }\n", " } else if (charC == 45) {\n", " var edex = el.value.indexOf('e');\n", " if (edex == -1) {\n", " edex = el.value.indexOf('E');\n", " }\n", "\n", " if (el.value == \"\") {\n", " return true;\n", " } else if (edex == (el.value.length - 1)) { // If just after e or E\n", " return true;\n", " } else {\n", " return false;\n", " }\n", " } else if (charC == 101) { // \"e\"\n", " if ((el.value.indexOf('e') === -1) && (el.value.indexOf('E') === -1) && (el.value.indexOf('/') == -1)) {\n", " // Prev symbol must be digit or decimal point:\n", " if (el.value.slice(-1).search(/\\d/) >= 0) {\n", " return true;\n", " } else if (el.value.slice(-1).search(/\\./) >= 0) {\n", " return true;\n", " } else {\n", " return false;\n", " }\n", " } else {\n", " return false;\n", " }\n", " } else {\n", " if (charC > 31 && (charC < 48 || charC > 57))\n", " return false;\n", " }\n", " return true;\n", "}\n", "\n", "function numeric_keypress(evnt) {\n", " var charC = (evnt.which) ? evnt.which : evnt.keyCode;\n", "\n", " if (charC == 13) {\n", " check_numeric(this, evnt);\n", " } else {\n", " return isValid(this, charC);\n", " }\n", "}\n", "\n", "\n", "\n", "\n", "\n", "function make_numeric(qa, outerqDiv, qDiv, aDiv, id) {\n", "\n", "\n", "\n", " //console.log(answer);\n", "\n", "\n", " outerqDiv.className = \"NumericQn\";\n", " aDiv.style.display = 'block';\n", "\n", " var lab = document.createElement(\"label\");\n", " lab.className = \"InpLabel\";\n", " lab.textContent = \"Type numeric answer here:\";\n", " aDiv.append(lab);\n", "\n", " var inp = document.createElement(\"input\");\n", " inp.type = \"text\";\n", " //inp.id=\"input-\"+id;\n", " inp.id = id + \"-0\";\n", " inp.className = \"Input-text\";\n", " inp.setAttribute('data-answers', JSON.stringify(qa.answers));\n", " if (\"precision\" in qa) {\n", " inp.setAttribute('data-precision', qa.precision);\n", " }\n", " aDiv.append(inp);\n", " //console.log(inp);\n", "\n", " //inp.addEventListener(\"keypress\", check_numeric);\n", " //inp.addEventListener(\"keypress\", numeric_keypress);\n", " /*\n", " inp.addEventListener(\"keypress\", function(event) {\n", " return numeric_keypress(this, event);\n", " }\n", " );\n", " */\n", " //inp.onkeypress=\"return numeric_keypress(this, event)\";\n", " inp.onkeypress = numeric_keypress;\n", " inp.onpaste = event => false;\n", "\n", " inp.addEventListener(\"focus\", function (event) {\n", " this.value = \"\";\n", " return false;\n", " }\n", " );\n", "\n", "\n", "}\n", "function jaxify(string) {\n", " var mystring = string;\n", "\n", " var count = 0;\n", " var loc = mystring.search(/([^\\\\]|^)(\\$)/);\n", "\n", " var count2 = 0;\n", " var loc2 = mystring.search(/([^\\\\]|^)(\\$\\$)/);\n", "\n", " //console.log(loc);\n", "\n", " while ((loc >= 0) || (loc2 >= 0)) {\n", "\n", " /* Have to replace all the double $$ first with current implementation */\n", " if (loc2 >= 0) {\n", " if (count2 % 2 == 0) {\n", " mystring = mystring.replace(/([^\\\\]|^)(\\$\\$)/, \"$1\\\\[\");\n", " } else {\n", " mystring = mystring.replace(/([^\\\\]|^)(\\$\\$)/, \"$1\\\\]\");\n", " }\n", " count2++;\n", " } else {\n", " if (count % 2 == 0) {\n", " mystring = mystring.replace(/([^\\\\]|^)(\\$)/, \"$1\\\\(\");\n", " } else {\n", " mystring = mystring.replace(/([^\\\\]|^)(\\$)/, \"$1\\\\)\");\n", " }\n", " count++;\n", " }\n", " loc = mystring.search(/([^\\\\]|^)(\\$)/);\n", " loc2 = mystring.search(/([^\\\\]|^)(\\$\\$)/);\n", " //console.log(mystring,\", loc:\",loc,\", loc2:\",loc2);\n", " }\n", "\n", " //console.log(mystring);\n", " return mystring;\n", "}\n", "\n", "\n", "function show_questions(json, mydiv) {\n", " console.log('show_questions');\n", " //var mydiv=document.getElementById(myid);\n", " var shuffle_questions = mydiv.dataset.shufflequestions;\n", " var num_questions = mydiv.dataset.numquestions;\n", " var shuffle_answers = mydiv.dataset.shuffleanswers;\n", " var max_width = mydiv.dataset.maxwidth;\n", "\n", " if (num_questions > json.length) {\n", " num_questions = json.length;\n", " }\n", "\n", " var questions;\n", " if ((num_questions < json.length) || (shuffle_questions == \"True\")) {\n", " //console.log(num_questions+\",\"+json.length);\n", " questions = getRandomSubarray(json, num_questions);\n", " } else {\n", " questions = json;\n", " }\n", "\n", " //console.log(\"SQ: \"+shuffle_questions+\", NQ: \" + num_questions + \", SA: \", shuffle_answers);\n", "\n", " // Iterate over questions\n", " questions.forEach((qa, index, array) => {\n", " //console.log(qa.question); \n", "\n", " var id = makeid(8);\n", " //console.log(id);\n", "\n", "\n", " // Create Div to contain question and answers\n", " var iDiv = document.createElement('div');\n", " //iDiv.id = 'quizWrap' + id + index;\n", " iDiv.id = 'quizWrap' + id;\n", " iDiv.className = 'Quiz';\n", " iDiv.setAttribute('data-qnum', index);\n", " iDiv.style.maxWidth =max_width+\"px\";\n", " mydiv.appendChild(iDiv);\n", " // iDiv.innerHTML=qa.question;\n", " \n", " var outerqDiv = document.createElement('div');\n", " outerqDiv.id = \"OuterquizQn\" + id + index;\n", " // Create div to contain question part\n", " var qDiv = document.createElement('div');\n", " qDiv.id = \"quizQn\" + id + index;\n", " \n", " if (qa.question) {\n", " iDiv.append(outerqDiv);\n", "\n", " //qDiv.textContent=qa.question;\n", " qDiv.innerHTML = jaxify(qa.question);\n", " outerqDiv.append(qDiv);\n", " }\n", "\n", " // Create div for code inside question\n", " var codeDiv;\n", " if (\"code\" in qa) {\n", " codeDiv = document.createElement('div');\n", " codeDiv.id = \"code\" + id + index;\n", " codeDiv.className = \"QuizCode\";\n", " var codePre = document.createElement('pre');\n", " codeDiv.append(codePre);\n", " var codeCode = document.createElement('code');\n", " codePre.append(codeCode);\n", " codeCode.innerHTML = qa.code;\n", " outerqDiv.append(codeDiv);\n", " //console.log(codeDiv);\n", " }\n", "\n", "\n", " // Create div to contain answer part\n", " var aDiv = document.createElement('div');\n", " aDiv.id = \"quizAns\" + id + index;\n", " aDiv.className = 'Answer';\n", " iDiv.append(aDiv);\n", "\n", " //console.log(qa.type);\n", "\n", " var num_correct;\n", " if ((qa.type == \"multiple_choice\") || (qa.type == \"many_choice\") ) {\n", " num_correct = make_mc(qa, shuffle_answers, outerqDiv, qDiv, aDiv, id);\n", " if (\"answer_cols\" in qa) {\n", " //aDiv.style.gridTemplateColumns = 'auto '.repeat(qa.answer_cols);\n", " aDiv.style.gridTemplateColumns = 'repeat(' + qa.answer_cols + ', 1fr)';\n", " }\n", " } else if (qa.type == \"numeric\") {\n", " //console.log(\"numeric\");\n", " make_numeric(qa, outerqDiv, qDiv, aDiv, id);\n", " }\n", "\n", "\n", " //Make div for feedback\n", " var fb = document.createElement(\"div\");\n", " fb.id = \"fb\" + id;\n", " //fb.style=\"font-size: 20px;text-align:center;\";\n", " fb.className = \"Feedback\";\n", " fb.setAttribute(\"data-answeredcorrect\", 0);\n", " fb.setAttribute(\"data-numcorrect\", num_correct);\n", " iDiv.append(fb);\n", "\n", "\n", " });\n", " var preserveResponses = mydiv.dataset.preserveresponses;\n", " console.log(preserveResponses);\n", " console.log(preserveResponses == \"true\");\n", " if (preserveResponses == \"true\") {\n", " console.log(preserveResponses);\n", " // Create Div to contain record of answers\n", " var iDiv = document.createElement('div');\n", " iDiv.id = 'responses' + mydiv.id;\n", " iDiv.className = 'JCResponses';\n", " // Create a place to store responses as an empty array\n", " iDiv.setAttribute('data-responses', '[]');\n", "\n", " // Dummy Text\n", " iDiv.innerHTML=\"Select your answers and then follow the directions that will appear here.\"\n", " //iDiv.className = 'Quiz';\n", " mydiv.appendChild(iDiv);\n", " }\n", "//console.log(\"At end of show_questions\");\n", " if (typeof MathJax != 'undefined') {\n", " console.log(\"MathJax version\", MathJax.version);\n", " var version = MathJax.version;\n", " setTimeout(function(){\n", " var version = MathJax.version;\n", " console.log('After sleep, MathJax version', version);\n", " if (version[0] == \"2\") {\n", " MathJax.Hub.Queue([\"Typeset\", MathJax.Hub]);\n", " } else if (version[0] == \"3\") {\n", " MathJax.typeset([mydiv]);\n", " }\n", " }, 500);\n", "if (typeof version == 'undefined') {\n", " } else\n", " {\n", " if (version[0] == \"2\") {\n", " MathJax.Hub.Queue([\"Typeset\", MathJax.Hub]);\n", " } else if (version[0] == \"3\") {\n", " MathJax.typeset([mydiv]);\n", " } else {\n", " console.log(\"MathJax not found\");\n", " }\n", " }\n", " }\n", " return false;\n", "}\n", "/* This is to handle asynchrony issues in loading Jupyter notebooks\n", " where the quiz has been previously run. The Javascript was generally\n", " being run before the div was added to the DOM. I tried to do this\n", " more elegantly using Mutation Observer, but I didn't get it to work.\n", "\n", " Someone more knowledgeable could make this better ;-) */\n", "\n", " function try_show() {\n", " if(document.getElementById(\"BNYUUaZrXaOW\")) {\n", " show_questions(questionsBNYUUaZrXaOW, BNYUUaZrXaOW); \n", " } else {\n", " setTimeout(try_show, 200);\n", " }\n", " };\n", " \n", " {\n", " // console.log(element);\n", "\n", " //console.log(\"BNYUUaZrXaOW\");\n", " // console.log(document.getElementById(\"BNYUUaZrXaOW\"));\n", "\n", " try_show();\n", " }\n", " " ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "from jupyterquiz import display_quiz\n", "display_quiz(\"quizes/numpy_course_skip_quiz.json\")" ] }, { "cell_type": "markdown", "id": "58ef4bc1-6a8e-4e1d-82f9-ba7d0792194a", "metadata": {}, "source": [ "# Pandas " ] }, { "cell_type": "code", "execution_count": 4, "id": "c28a78e0-950f-448a-97ca-0ccd944d71de", "metadata": { "editable": true, "slideshow": { "slide_type": "" }, "tags": [ "remove-input" ] }, "outputs": [ { "data": { "text/html": [ "
    " ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "application/javascript": [ "var questionsfgrNkQGwsBOS=[\n", " {\n", " \"question\": \"Which function is used to read a .csv file in Pandas?\",\n", " \"type\": \"many_choice\",\n", " \"answers\": [\n", " {\n", " \"answer\": \"open_csv()\",\n", " \"correct\": false,\n", " \"feedback\": \"Incorrect.\"\n", " },\n", " {\n", " \"answer\": \"csv_read()\",\n", " \"correct\": false,\n", " \"feedback\": \"Incorrect.\"\n", " },\n", " {\n", " \"answer\": \"read_csv()\",\n", " \"correct\": true,\n", " \"feedback\": \"Correct.\"\n", " },\n", " {\n", " \"answer\": \"load_csv()\",\n", " \"correct\": false,\n", " \"feedback\": \"Incorrect.\"\n", " }\n", " ]\n", " },\n", " {\n", " \"question\": \"How can you select the 'Age' columns from a dataframe named 'df'?\",\n", " \"type\": \"many_choice\",\n", " \"answers\": [\n", " {\n", " \"answer\": \"df('Age')\",\n", " \"correct\": false,\n", " \"feedback\": \"Incorrect.\"\n", " },\n", " {\n", " \"answer\": \"df[Age]\",\n", " \"correct\": false,\n", " \"feedback\": \"Incorrect.\"\n", " },\n", " {\n", " \"answer\": \"df['Age']\",\n", " \"correct\": true,\n", " \"feedback\": \"Correct.\"\n", " },\n", " {\n", " \"answer\": \"df.Age()\",\n", " \"correct\": false,\n", " \"feedback\": \"Incorrect.\"\n", " }\n", " ]\n", " },\n", " {\n", " \"question\": \"Which function would you use to get a quick statistical summary of a DataFrame df?\",\n", " \"type\": \"many_choice\",\n", " \"answers\": [\n", " {\n", " \"answer\": \"df.describe()\",\n", " \"correct\": true,\n", " \"feedback\": \"Correct.\"\n", " },\n", " {\n", " \"answer\": \"df.summary()\",\n", " \"correct\": false,\n", " \"feedback\": \"Incorrect.\"\n", " },\n", " {\n", " \"answer\": \"df.info()\",\n", " \"correct\": false,\n", " \"feedback\": \"Incorrect.\"\n", " },\n", " {\n", " \"answer\": \"df.details()\",\n", " \"correct\": false,\n", " \"feedback\": \"Incorrect.\"\n", " }\n", " ]\n", " },\n", " {\n", " \"question\": \"What is the purpose of the dropna() method in Pandas?\",\n", " \"type\": \"many_choice\",\n", " \"answers\": [\n", " {\n", " \"answer\": \"Add new NaN values to the DataFrame\",\n", " \"correct\": false,\n", " \"feedback\": \"Incorrect.\"\n", " },\n", " {\n", " \"answer\": \"Drop columns that contain any NaN values\",\n", " \"correct\": false,\n", " \"feedback\": \"Incorrect.\"\n", " },\n", " {\n", " \"answer\": \"Drop rows that contain any NaN values\",\n", " \"correct\": false,\n", " \"feedback\": \"Incorrect.\"\n", " },\n", " {\n", " \"answer\": \"Both rop columns that contain any NaN values and Drop rows that contain any NaN values are correct\",\n", " \"correct\": true,\n", " \"feedback\": \"Correct.\"\n", " }\n", " ]\n", " },\n", " {\n", " \"question\": \"If you want to change the index of a DataFrame df to be the values from the 'email' column, which method should you use?\",\n", " \"type\": \"many_choice\",\n", " \"answers\": [\n", " {\n", " \"answer\": \"df.set_index('email')\",\n", " \"correct\": true,\n", " \"feedback\": \"Correct.\"\n", " },\n", " {\n", " \"answer\": \"df.index('email')\",\n", " \"correct\": false,\n", " \"feedback\": \"Incorrect.\"\n", " },\n", " {\n", " \"answer\": \"df.reset_index('email')\",\n", " \"correct\": false,\n", " \"feedback\": \"Incorrect.\"\n", " },\n", " {\n", " \"answer\": \"df.reindex('email')\",\n", " \"correct\": false,\n", " \"feedback\": \"Incorrect.\"\n", " }\n", " ]\n", " },\n", " {\n", " \"question\": \"In the dataframe 'df' with the column 'date_string' containing date information in the format '2023-04-25', which of the following correctly converts the column to a datetime format?\",\n", " \"type\": \"many_choice\",\n", " \"answers\": [\n", " {\n", " \"answer\": \"df['date_string'] = pd.to_datetime(df['date_string'], format='%Y-%d-%m')\",\n", " \"correct\": false,\n", " \"feedback\": \"Incorrect.\"\n", " },\n", " {\n", " \"answer\": \"df['date_string'].datetime('%Y-%m-%d')\",\n", " \"correct\": false,\n", " \"feedback\": \"Incorrect.\"\n", " },\n", " {\n", " \"answer\": \"df['date_string'] = pd.to_datetime(df['date_string'], format='%Y-%m-%d')\",\n", " \"correct\": true,\n", " \"feedback\": \"Correct.\"\n", " },\n", " {\n", " \"answer\": \"df['date_string'].convert('datetime', '%Y-%m-%d')\",\n", " \"correct\": false,\n", " \"feedback\": \"Incorrect.\"\n", " }\n", " ]\n", " },\n", " {\n", " \"question\": \"How can you handle missing data in a DataFrame df by replacing NaN values with 0?\",\n", " \"type\": \"many_choice\",\n", " \"answers\": [\n", " {\n", " \"answer\": \"df.fillna(0)\",\n", " \"correct\": true,\n", " \"feedback\": \"Correct.\"\n", " },\n", " {\n", " \"answer\": \"df.replace_nan(0)\",\n", " \"correct\": false,\n", " \"feedback\": \"Incorrect.\"\n", " },\n", " {\n", " \"answer\": \"df.dropna(0)\",\n", " \"correct\": false,\n", " \"feedback\": \"Incorrect.\"\n", " },\n", " {\n", " \"answer\": \"df.nan_to_num(0)\",\n", " \"correct\": false,\n", " \"feedback\": \"Incorrect.\"\n", " }\n", " ]\n", " },\n", " {\n", " \"question\": \"What is the output of df.iloc[0] if df is a DataFrame?\",\n", " \"type\": \"many_choice\",\n", " \"answers\": [\n", " {\n", " \"answer\": \"It returns the first row as a Series\",\n", " \"correct\": true,\n", " \"feedback\": \"Correct.\"\n", " },\n", " {\n", " \"answer\": \"It returns the first column as a Series\",\n", " \"correct\": false,\n", " \"feedback\": \"Incorrect.\"\n", " },\n", " {\n", " \"answer\": \"It returns the first element of the DataFrame\",\n", " \"correct\": false,\n", " \"feedback\": \"Incorrect.\"\n", " },\n", " {\n", " \"answer\": \"It returns the first index label\",\n", " \"correct\": false,\n", " \"feedback\": \"Incorrect.\"\n", " }\n", " ]\n", " },\n", " {\n", " \"question\": \"Which Pandas function would you use to concatenate two DataFrames vertically?\",\n", " \"type\": \"many_choice\",\n", " \"answers\": [\n", " {\n", " \"answer\": \"pd.concat() with parameter axis=0\",\n", " \"correct\": true,\n", " \"feedback\": \"Correct.\"\n", " },\n", " {\n", " \"answer\": \"pd.join()\",\n", " \"correct\": false,\n", " \"feedback\": \"Incorrect.\"\n", " },\n", " {\n", " \"answer\": \"pd.merge()\",\n", " \"correct\": false,\n", " \"feedback\": \"Incorrect.\"\n", " },\n", " {\n", " \"answer\": \"pd.append()\",\n", " \"correct\": false,\n", " \"feedback\": \"Incorrect.\"\n", " }\n", " ]\n", " },\n", " {\n", " \"question\": \"How do you slice rows 10 through 20 from a DataFrame df?\",\n", " \"type\": \"many_choice\",\n", " \"answers\": [\n", " {\n", " \"answer\": \"df[10:21]\",\n", " \"correct\": false,\n", " \"feedback\": \"Incorrect.\"\n", " },\n", " {\n", " \"answer\": \"df.iloc[10:20]\",\n", " \"correct\": true,\n", " \"feedback\": \"Correct.\"\n", " },\n", " {\n", " \"answer\": \"df.loc[10:20]\",\n", " \"correct\": false,\n", " \"feedback\": \"Incorrect.\"\n", " },\n", " {\n", " \"answer\": \"df.rows[10:20]\",\n", " \"correct\": false,\n", " \"feedback\": \"Incorrect.\"\n", " }\n", " ]\n", " }\n", "];\n", " // Make a random ID\n", "function makeid(length) {\n", " var result = [];\n", " var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';\n", " var charactersLength = characters.length;\n", " for (var i = 0; i < length; i++) {\n", " result.push(characters.charAt(Math.floor(Math.random() * charactersLength)));\n", " }\n", " return result.join('');\n", "}\n", "\n", "// Choose a random subset of an array. Can also be used to shuffle the array\n", "function getRandomSubarray(arr, size) {\n", " var shuffled = arr.slice(0), i = arr.length, temp, index;\n", " while (i--) {\n", " index = Math.floor((i + 1) * Math.random());\n", " temp = shuffled[index];\n", " shuffled[index] = shuffled[i];\n", " shuffled[i] = temp;\n", " }\n", " return shuffled.slice(0, size);\n", "}\n", "\n", "function printResponses(responsesContainer) {\n", " var responses=JSON.parse(responsesContainer.dataset.responses);\n", " var stringResponses='IMPORTANT!To preserve this answer sequence for submission, when you have finalized your answers:
    1. Copy the text in this cell below \"Answer String\"
    2. Double click on the cell directly below the Answer String, labeled \"Replace Me\"
    3. Select the whole \"Replace Me\" text
    4. Paste in your answer string and press shift-Enter.
    5. Save the notebook using the save icon or File->Save Notebook menu item



    6. Answer String:
      ';\n", " console.log(responses);\n", " responses.forEach((response, index) => {\n", " if (response) {\n", " console.log(index + ': ' + response);\n", " stringResponses+= index + ': ' + response +\"
      \";\n", " }\n", " });\n", " responsesContainer.innerHTML=stringResponses;\n", "}\n", "function check_mc() {\n", " var id = this.id.split('-')[0];\n", " //var response = this.id.split('-')[1];\n", " //console.log(response);\n", " //console.log(\"In check_mc(), id=\"+id);\n", " //console.log(event.srcElement.id) \n", " //console.log(event.srcElement.dataset.correct) \n", " //console.log(event.srcElement.dataset.feedback)\n", "\n", " var label = event.srcElement;\n", " //console.log(label, label.nodeName);\n", " var depth = 0;\n", " while ((label.nodeName != \"LABEL\") && (depth < 20)) {\n", " label = label.parentElement;\n", " console.log(depth, label);\n", " depth++;\n", " }\n", "\n", "\n", "\n", " var answers = label.parentElement.children;\n", "\n", " //console.log(answers);\n", "\n", "\n", " // Split behavior based on multiple choice vs many choice:\n", " var fb = document.getElementById(\"fb\" + id);\n", "\n", "\n", "\n", "\n", " if (fb.dataset.numcorrect == 1) {\n", " // What follows is for the saved responses stuff\n", " var outerContainer = fb.parentElement.parentElement;\n", " var responsesContainer = document.getElementById(\"responses\" + outerContainer.id);\n", " if (responsesContainer) {\n", " //console.log(responsesContainer);\n", " var response = label.firstChild.innerText;\n", " if (label.querySelector(\".QuizCode\")){\n", " response+= label.querySelector(\".QuizCode\").firstChild.innerText;\n", " }\n", " console.log(response);\n", " //console.log(document.getElementById(\"quizWrap\"+id));\n", " var qnum = document.getElementById(\"quizWrap\"+id).dataset.qnum;\n", " console.log(\"Question \" + qnum);\n", " //console.log(id, \", got numcorrect=\",fb.dataset.numcorrect);\n", " var responses=JSON.parse(responsesContainer.dataset.responses);\n", " console.log(responses);\n", " responses[qnum]= response;\n", " responsesContainer.setAttribute('data-responses', JSON.stringify(responses));\n", " printResponses(responsesContainer);\n", " }\n", " // End code to preserve responses\n", " \n", " for (var i = 0; i < answers.length; i++) {\n", " var child = answers[i];\n", " //console.log(child);\n", " child.className = \"MCButton\";\n", " }\n", "\n", "\n", "\n", " if (label.dataset.correct == \"true\") {\n", " // console.log(\"Correct action\");\n", " if (\"feedback\" in label.dataset) {\n", " fb.textContent = jaxify(label.dataset.feedback);\n", " } else {\n", " fb.textContent = \"Correct!\";\n", " }\n", " label.classList.add(\"correctButton\");\n", "\n", " fb.className = \"Feedback\";\n", " fb.classList.add(\"correct\");\n", "\n", " } else {\n", " if (\"feedback\" in label.dataset) {\n", " fb.textContent = jaxify(label.dataset.feedback);\n", " } else {\n", " fb.textContent = \"Incorrect -- try again.\";\n", " }\n", " //console.log(\"Error action\");\n", " label.classList.add(\"incorrectButton\");\n", " fb.className = \"Feedback\";\n", " fb.classList.add(\"incorrect\");\n", " }\n", " }\n", " else {\n", " var reset = false;\n", " var feedback;\n", " if (label.dataset.correct == \"true\") {\n", " if (\"feedback\" in label.dataset) {\n", " feedback = jaxify(label.dataset.feedback);\n", " } else {\n", " feedback = \"Correct!\";\n", " }\n", " if (label.dataset.answered <= 0) {\n", " if (fb.dataset.answeredcorrect < 0) {\n", " fb.dataset.answeredcorrect = 1;\n", " reset = true;\n", " } else {\n", " fb.dataset.answeredcorrect++;\n", " }\n", " if (reset) {\n", " for (var i = 0; i < answers.length; i++) {\n", " var child = answers[i];\n", " child.className = \"MCButton\";\n", " child.dataset.answered = 0;\n", " }\n", " }\n", " label.classList.add(\"correctButton\");\n", " label.dataset.answered = 1;\n", " fb.className = \"Feedback\";\n", " fb.classList.add(\"correct\");\n", "\n", " }\n", " } else {\n", " if (\"feedback\" in label.dataset) {\n", " feedback = jaxify(label.dataset.feedback);\n", " } else {\n", " feedback = \"Incorrect -- try again.\";\n", " }\n", " if (fb.dataset.answeredcorrect > 0) {\n", " fb.dataset.answeredcorrect = -1;\n", " reset = true;\n", " } else {\n", " fb.dataset.answeredcorrect--;\n", " }\n", "\n", " if (reset) {\n", " for (var i = 0; i < answers.length; i++) {\n", " var child = answers[i];\n", " child.className = \"MCButton\";\n", " child.dataset.answered = 0;\n", " }\n", " }\n", " label.classList.add(\"incorrectButton\");\n", " fb.className = \"Feedback\";\n", " fb.classList.add(\"incorrect\");\n", " }\n", " // What follows is for the saved responses stuff\n", " var outerContainer = fb.parentElement.parentElement;\n", " var responsesContainer = document.getElementById(\"responses\" + outerContainer.id);\n", " if (responsesContainer) {\n", " //console.log(responsesContainer);\n", " var response = label.firstChild.innerText;\n", " if (label.querySelector(\".QuizCode\")){\n", " response+= label.querySelector(\".QuizCode\").firstChild.innerText;\n", " }\n", " console.log(response);\n", " //console.log(document.getElementById(\"quizWrap\"+id));\n", " var qnum = document.getElementById(\"quizWrap\"+id).dataset.qnum;\n", " console.log(\"Question \" + qnum);\n", " //console.log(id, \", got numcorrect=\",fb.dataset.numcorrect);\n", " var responses=JSON.parse(responsesContainer.dataset.responses);\n", " if (label.dataset.correct == \"true\") {\n", " if (typeof(responses[qnum]) == \"object\"){\n", " if (!responses[qnum].includes(response))\n", " responses[qnum].push(response);\n", " } else{\n", " responses[qnum]= [ response ];\n", " }\n", " } else {\n", " responses[qnum]= response;\n", " }\n", " console.log(responses);\n", " responsesContainer.setAttribute('data-responses', JSON.stringify(responses));\n", " printResponses(responsesContainer);\n", " }\n", " // End save responses stuff\n", "\n", "\n", "\n", " var numcorrect = fb.dataset.numcorrect;\n", " var answeredcorrect = fb.dataset.answeredcorrect;\n", " if (answeredcorrect >= 0) {\n", " fb.textContent = feedback + \" [\" + answeredcorrect + \"/\" + numcorrect + \"]\";\n", " } else {\n", " fb.textContent = feedback + \" [\" + 0 + \"/\" + numcorrect + \"]\";\n", " }\n", "\n", "\n", " }\n", "\n", " if (typeof MathJax != 'undefined') {\n", " var version = MathJax.version;\n", " console.log('MathJax version', version);\n", " if (version[0] == \"2\") {\n", " MathJax.Hub.Queue([\"Typeset\", MathJax.Hub]);\n", " } else if (version[0] == \"3\") {\n", " MathJax.typeset([fb]);\n", " }\n", " } else {\n", " console.log('MathJax not detected');\n", " }\n", "\n", "}\n", "\n", "function make_mc(qa, shuffle_answers, outerqDiv, qDiv, aDiv, id) {\n", " var shuffled;\n", " if (shuffle_answers == \"True\") {\n", " //console.log(shuffle_answers+\" read as true\");\n", " shuffled = getRandomSubarray(qa.answers, qa.answers.length);\n", " } else {\n", " //console.log(shuffle_answers+\" read as false\");\n", " shuffled = qa.answers;\n", " }\n", "\n", "\n", " var num_correct = 0;\n", "\n", "\n", "\n", " shuffled.forEach((item, index, ans_array) => {\n", " //console.log(answer);\n", "\n", " // Make input element\n", " var inp = document.createElement(\"input\");\n", " inp.type = \"radio\";\n", " inp.id = \"quizo\" + id + index;\n", " inp.style = \"display:none;\";\n", " aDiv.append(inp);\n", "\n", " //Make label for input element\n", " var lab = document.createElement(\"label\");\n", " lab.className = \"MCButton\";\n", " lab.id = id + '-' + index;\n", " lab.onclick = check_mc;\n", " var aSpan = document.createElement('span');\n", " aSpan.classsName = \"\";\n", " //qDiv.id=\"quizQn\"+id+index;\n", " if (\"answer\" in item) {\n", " aSpan.innerHTML = jaxify(item.answer);\n", " //aSpan.innerHTML=item.answer;\n", " }\n", " lab.append(aSpan);\n", "\n", " // Create div for code inside question\n", " var codeSpan;\n", " if (\"code\" in item) {\n", " codeSpan = document.createElement('span');\n", " codeSpan.id = \"code\" + id + index;\n", " codeSpan.className = \"QuizCode\";\n", " var codePre = document.createElement('pre');\n", " codeSpan.append(codePre);\n", " var codeCode = document.createElement('code');\n", " codePre.append(codeCode);\n", " codeCode.innerHTML = item.code;\n", " lab.append(codeSpan);\n", " //console.log(codeSpan);\n", " }\n", "\n", " //lab.textContent=item.answer;\n", "\n", " // Set the data attributes for the answer\n", " lab.setAttribute('data-correct', item.correct);\n", " if (item.correct) {\n", " num_correct++;\n", " }\n", " if (\"feedback\" in item) {\n", " lab.setAttribute('data-feedback', item.feedback);\n", " }\n", " lab.setAttribute('data-answered', 0);\n", "\n", " aDiv.append(lab);\n", "\n", " });\n", "\n", " if (num_correct > 1) {\n", " outerqDiv.className = \"ManyChoiceQn\";\n", " } else {\n", " outerqDiv.className = \"MultipleChoiceQn\";\n", " }\n", "\n", " return num_correct;\n", "\n", "}\n", "function check_numeric(ths, event) {\n", "\n", " if (event.keyCode === 13) {\n", " ths.blur();\n", "\n", " var id = ths.id.split('-')[0];\n", "\n", " var submission = ths.value;\n", " if (submission.indexOf('/') != -1) {\n", " var sub_parts = submission.split('/');\n", " //console.log(sub_parts);\n", " submission = sub_parts[0] / sub_parts[1];\n", " }\n", " //console.log(\"Reader entered\", submission);\n", "\n", " if (\"precision\" in ths.dataset) {\n", " var precision = ths.dataset.precision;\n", " // console.log(\"1:\", submission)\n", " submission = Math.round((1 * submission + Number.EPSILON) * 10 ** precision) / 10 ** precision;\n", " // console.log(\"Rounded to \", submission, \" precision=\", precision );\n", " }\n", "\n", "\n", " //console.log(\"In check_numeric(), id=\"+id);\n", " //console.log(event.srcElement.id) \n", " //console.log(event.srcElement.dataset.feedback)\n", "\n", " var fb = document.getElementById(\"fb\" + id);\n", " fb.style.display = \"none\";\n", " fb.textContent = \"Incorrect -- try again.\";\n", "\n", " var answers = JSON.parse(ths.dataset.answers);\n", " //console.log(answers);\n", "\n", " var defaultFB = \"\";\n", " var correct;\n", " var done = false;\n", " answers.every(answer => {\n", " //console.log(answer.type);\n", "\n", " correct = false;\n", " // if (answer.type==\"value\"){\n", " if ('value' in answer) {\n", " if (submission == answer.value) {\n", " if (\"feedback\" in answer) {\n", " fb.textContent = jaxify(answer.feedback);\n", " } else {\n", " fb.textContent = jaxify(\"Correct\");\n", " }\n", " correct = answer.correct;\n", " //console.log(answer.correct);\n", " done = true;\n", " }\n", " // } else if (answer.type==\"range\") {\n", " } else if ('range' in answer) {\n", " //console.log(answer.range);\n", " if ((submission >= answer.range[0]) && (submission < answer.range[1])) {\n", " fb.textContent = jaxify(answer.feedback);\n", " correct = answer.correct;\n", " //console.log(answer.correct);\n", " done = true;\n", " }\n", " } else if (answer.type == \"default\") {\n", " defaultFB = answer.feedback;\n", " }\n", " if (done) {\n", " return false; // Break out of loop if this has been marked correct\n", " } else {\n", " return true; // Keep looking for case that includes this as a correct answer\n", " }\n", " });\n", "\n", " if ((!done) && (defaultFB != \"\")) {\n", " fb.innerHTML = jaxify(defaultFB);\n", " //console.log(\"Default feedback\", defaultFB);\n", " }\n", "\n", " fb.style.display = \"block\";\n", " if (correct) {\n", " ths.className = \"Input-text\";\n", " ths.classList.add(\"correctButton\");\n", " fb.className = \"Feedback\";\n", " fb.classList.add(\"correct\");\n", " } else {\n", " ths.className = \"Input-text\";\n", " ths.classList.add(\"incorrectButton\");\n", " fb.className = \"Feedback\";\n", " fb.classList.add(\"incorrect\");\n", " }\n", "\n", " // What follows is for the saved responses stuff\n", " var outerContainer = fb.parentElement.parentElement;\n", " var responsesContainer = document.getElementById(\"responses\" + outerContainer.id);\n", " if (responsesContainer) {\n", " console.log(submission);\n", " var qnum = document.getElementById(\"quizWrap\"+id).dataset.qnum;\n", " //console.log(\"Question \" + qnum);\n", " //console.log(id, \", got numcorrect=\",fb.dataset.numcorrect);\n", " var responses=JSON.parse(responsesContainer.dataset.responses);\n", " console.log(responses);\n", " if (submission == ths.value){\n", " responses[qnum]= submission;\n", " } else {\n", " responses[qnum]= ths.value + \"(\" + submission +\")\";\n", " }\n", " responsesContainer.setAttribute('data-responses', JSON.stringify(responses));\n", " printResponses(responsesContainer);\n", " }\n", " // End code to preserve responses\n", "\n", " if (typeof MathJax != 'undefined') {\n", " var version = MathJax.version;\n", " console.log('MathJax version', version);\n", " if (version[0] == \"2\") {\n", " MathJax.Hub.Queue([\"Typeset\", MathJax.Hub]);\n", " } else if (version[0] == \"3\") {\n", " MathJax.typeset([fb]);\n", " }\n", " } else {\n", " console.log('MathJax not detected');\n", " }\n", " return false;\n", " }\n", "\n", "}\n", "\n", "function isValid(el, charC) {\n", " //console.log(\"Input char: \", charC);\n", " if (charC == 46) {\n", " if (el.value.indexOf('.') === -1) {\n", " return true;\n", " } else if (el.value.indexOf('/') != -1) {\n", " var parts = el.value.split('/');\n", " if (parts[1].indexOf('.') === -1) {\n", " return true;\n", " }\n", " }\n", " else {\n", " return false;\n", " }\n", " } else if (charC == 47) {\n", " if (el.value.indexOf('/') === -1) {\n", " if ((el.value != \"\") && (el.value != \".\")) {\n", " return true;\n", " } else {\n", " return false;\n", " }\n", " } else {\n", " return false;\n", " }\n", " } else if (charC == 45) {\n", " var edex = el.value.indexOf('e');\n", " if (edex == -1) {\n", " edex = el.value.indexOf('E');\n", " }\n", "\n", " if (el.value == \"\") {\n", " return true;\n", " } else if (edex == (el.value.length - 1)) { // If just after e or E\n", " return true;\n", " } else {\n", " return false;\n", " }\n", " } else if (charC == 101) { // \"e\"\n", " if ((el.value.indexOf('e') === -1) && (el.value.indexOf('E') === -1) && (el.value.indexOf('/') == -1)) {\n", " // Prev symbol must be digit or decimal point:\n", " if (el.value.slice(-1).search(/\\d/) >= 0) {\n", " return true;\n", " } else if (el.value.slice(-1).search(/\\./) >= 0) {\n", " return true;\n", " } else {\n", " return false;\n", " }\n", " } else {\n", " return false;\n", " }\n", " } else {\n", " if (charC > 31 && (charC < 48 || charC > 57))\n", " return false;\n", " }\n", " return true;\n", "}\n", "\n", "function numeric_keypress(evnt) {\n", " var charC = (evnt.which) ? evnt.which : evnt.keyCode;\n", "\n", " if (charC == 13) {\n", " check_numeric(this, evnt);\n", " } else {\n", " return isValid(this, charC);\n", " }\n", "}\n", "\n", "\n", "\n", "\n", "\n", "function make_numeric(qa, outerqDiv, qDiv, aDiv, id) {\n", "\n", "\n", "\n", " //console.log(answer);\n", "\n", "\n", " outerqDiv.className = \"NumericQn\";\n", " aDiv.style.display = 'block';\n", "\n", " var lab = document.createElement(\"label\");\n", " lab.className = \"InpLabel\";\n", " lab.textContent = \"Type numeric answer here:\";\n", " aDiv.append(lab);\n", "\n", " var inp = document.createElement(\"input\");\n", " inp.type = \"text\";\n", " //inp.id=\"input-\"+id;\n", " inp.id = id + \"-0\";\n", " inp.className = \"Input-text\";\n", " inp.setAttribute('data-answers', JSON.stringify(qa.answers));\n", " if (\"precision\" in qa) {\n", " inp.setAttribute('data-precision', qa.precision);\n", " }\n", " aDiv.append(inp);\n", " //console.log(inp);\n", "\n", " //inp.addEventListener(\"keypress\", check_numeric);\n", " //inp.addEventListener(\"keypress\", numeric_keypress);\n", " /*\n", " inp.addEventListener(\"keypress\", function(event) {\n", " return numeric_keypress(this, event);\n", " }\n", " );\n", " */\n", " //inp.onkeypress=\"return numeric_keypress(this, event)\";\n", " inp.onkeypress = numeric_keypress;\n", " inp.onpaste = event => false;\n", "\n", " inp.addEventListener(\"focus\", function (event) {\n", " this.value = \"\";\n", " return false;\n", " }\n", " );\n", "\n", "\n", "}\n", "function jaxify(string) {\n", " var mystring = string;\n", "\n", " var count = 0;\n", " var loc = mystring.search(/([^\\\\]|^)(\\$)/);\n", "\n", " var count2 = 0;\n", " var loc2 = mystring.search(/([^\\\\]|^)(\\$\\$)/);\n", "\n", " //console.log(loc);\n", "\n", " while ((loc >= 0) || (loc2 >= 0)) {\n", "\n", " /* Have to replace all the double $$ first with current implementation */\n", " if (loc2 >= 0) {\n", " if (count2 % 2 == 0) {\n", " mystring = mystring.replace(/([^\\\\]|^)(\\$\\$)/, \"$1\\\\[\");\n", " } else {\n", " mystring = mystring.replace(/([^\\\\]|^)(\\$\\$)/, \"$1\\\\]\");\n", " }\n", " count2++;\n", " } else {\n", " if (count % 2 == 0) {\n", " mystring = mystring.replace(/([^\\\\]|^)(\\$)/, \"$1\\\\(\");\n", " } else {\n", " mystring = mystring.replace(/([^\\\\]|^)(\\$)/, \"$1\\\\)\");\n", " }\n", " count++;\n", " }\n", " loc = mystring.search(/([^\\\\]|^)(\\$)/);\n", " loc2 = mystring.search(/([^\\\\]|^)(\\$\\$)/);\n", " //console.log(mystring,\", loc:\",loc,\", loc2:\",loc2);\n", " }\n", "\n", " //console.log(mystring);\n", " return mystring;\n", "}\n", "\n", "\n", "function show_questions(json, mydiv) {\n", " console.log('show_questions');\n", " //var mydiv=document.getElementById(myid);\n", " var shuffle_questions = mydiv.dataset.shufflequestions;\n", " var num_questions = mydiv.dataset.numquestions;\n", " var shuffle_answers = mydiv.dataset.shuffleanswers;\n", " var max_width = mydiv.dataset.maxwidth;\n", "\n", " if (num_questions > json.length) {\n", " num_questions = json.length;\n", " }\n", "\n", " var questions;\n", " if ((num_questions < json.length) || (shuffle_questions == \"True\")) {\n", " //console.log(num_questions+\",\"+json.length);\n", " questions = getRandomSubarray(json, num_questions);\n", " } else {\n", " questions = json;\n", " }\n", "\n", " //console.log(\"SQ: \"+shuffle_questions+\", NQ: \" + num_questions + \", SA: \", shuffle_answers);\n", "\n", " // Iterate over questions\n", " questions.forEach((qa, index, array) => {\n", " //console.log(qa.question); \n", "\n", " var id = makeid(8);\n", " //console.log(id);\n", "\n", "\n", " // Create Div to contain question and answers\n", " var iDiv = document.createElement('div');\n", " //iDiv.id = 'quizWrap' + id + index;\n", " iDiv.id = 'quizWrap' + id;\n", " iDiv.className = 'Quiz';\n", " iDiv.setAttribute('data-qnum', index);\n", " iDiv.style.maxWidth =max_width+\"px\";\n", " mydiv.appendChild(iDiv);\n", " // iDiv.innerHTML=qa.question;\n", " \n", " var outerqDiv = document.createElement('div');\n", " outerqDiv.id = \"OuterquizQn\" + id + index;\n", " // Create div to contain question part\n", " var qDiv = document.createElement('div');\n", " qDiv.id = \"quizQn\" + id + index;\n", " \n", " if (qa.question) {\n", " iDiv.append(outerqDiv);\n", "\n", " //qDiv.textContent=qa.question;\n", " qDiv.innerHTML = jaxify(qa.question);\n", " outerqDiv.append(qDiv);\n", " }\n", "\n", " // Create div for code inside question\n", " var codeDiv;\n", " if (\"code\" in qa) {\n", " codeDiv = document.createElement('div');\n", " codeDiv.id = \"code\" + id + index;\n", " codeDiv.className = \"QuizCode\";\n", " var codePre = document.createElement('pre');\n", " codeDiv.append(codePre);\n", " var codeCode = document.createElement('code');\n", " codePre.append(codeCode);\n", " codeCode.innerHTML = qa.code;\n", " outerqDiv.append(codeDiv);\n", " //console.log(codeDiv);\n", " }\n", "\n", "\n", " // Create div to contain answer part\n", " var aDiv = document.createElement('div');\n", " aDiv.id = \"quizAns\" + id + index;\n", " aDiv.className = 'Answer';\n", " iDiv.append(aDiv);\n", "\n", " //console.log(qa.type);\n", "\n", " var num_correct;\n", " if ((qa.type == \"multiple_choice\") || (qa.type == \"many_choice\") ) {\n", " num_correct = make_mc(qa, shuffle_answers, outerqDiv, qDiv, aDiv, id);\n", " if (\"answer_cols\" in qa) {\n", " //aDiv.style.gridTemplateColumns = 'auto '.repeat(qa.answer_cols);\n", " aDiv.style.gridTemplateColumns = 'repeat(' + qa.answer_cols + ', 1fr)';\n", " }\n", " } else if (qa.type == \"numeric\") {\n", " //console.log(\"numeric\");\n", " make_numeric(qa, outerqDiv, qDiv, aDiv, id);\n", " }\n", "\n", "\n", " //Make div for feedback\n", " var fb = document.createElement(\"div\");\n", " fb.id = \"fb\" + id;\n", " //fb.style=\"font-size: 20px;text-align:center;\";\n", " fb.className = \"Feedback\";\n", " fb.setAttribute(\"data-answeredcorrect\", 0);\n", " fb.setAttribute(\"data-numcorrect\", num_correct);\n", " iDiv.append(fb);\n", "\n", "\n", " });\n", " var preserveResponses = mydiv.dataset.preserveresponses;\n", " console.log(preserveResponses);\n", " console.log(preserveResponses == \"true\");\n", " if (preserveResponses == \"true\") {\n", " console.log(preserveResponses);\n", " // Create Div to contain record of answers\n", " var iDiv = document.createElement('div');\n", " iDiv.id = 'responses' + mydiv.id;\n", " iDiv.className = 'JCResponses';\n", " // Create a place to store responses as an empty array\n", " iDiv.setAttribute('data-responses', '[]');\n", "\n", " // Dummy Text\n", " iDiv.innerHTML=\"Select your answers and then follow the directions that will appear here.\"\n", " //iDiv.className = 'Quiz';\n", " mydiv.appendChild(iDiv);\n", " }\n", "//console.log(\"At end of show_questions\");\n", " if (typeof MathJax != 'undefined') {\n", " console.log(\"MathJax version\", MathJax.version);\n", " var version = MathJax.version;\n", " setTimeout(function(){\n", " var version = MathJax.version;\n", " console.log('After sleep, MathJax version', version);\n", " if (version[0] == \"2\") {\n", " MathJax.Hub.Queue([\"Typeset\", MathJax.Hub]);\n", " } else if (version[0] == \"3\") {\n", " MathJax.typeset([mydiv]);\n", " }\n", " }, 500);\n", "if (typeof version == 'undefined') {\n", " } else\n", " {\n", " if (version[0] == \"2\") {\n", " MathJax.Hub.Queue([\"Typeset\", MathJax.Hub]);\n", " } else if (version[0] == \"3\") {\n", " MathJax.typeset([mydiv]);\n", " } else {\n", " console.log(\"MathJax not found\");\n", " }\n", " }\n", " }\n", " return false;\n", "}\n", "/* This is to handle asynchrony issues in loading Jupyter notebooks\n", " where the quiz has been previously run. The Javascript was generally\n", " being run before the div was added to the DOM. I tried to do this\n", " more elegantly using Mutation Observer, but I didn't get it to work.\n", "\n", " Someone more knowledgeable could make this better ;-) */\n", "\n", " function try_show() {\n", " if(document.getElementById(\"fgrNkQGwsBOS\")) {\n", " show_questions(questionsfgrNkQGwsBOS, fgrNkQGwsBOS); \n", " } else {\n", " setTimeout(try_show, 200);\n", " }\n", " };\n", " \n", " {\n", " // console.log(element);\n", "\n", " //console.log(\"fgrNkQGwsBOS\");\n", " // console.log(document.getElementById(\"fgrNkQGwsBOS\"));\n", "\n", " try_show();\n", " }\n", " " ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "from jupyterquiz import display_quiz\n", "display_quiz(\"quizes/pandas_course_skip_quiz.json\")" ] }, { "cell_type": "code", "execution_count": 5, "id": "79091bc7-9979-4e6b-adc5-385b5986b4f4", "metadata": { "editable": true, "slideshow": { "slide_type": "" }, "tags": [ "remove-input" ] }, "outputs": [ { "data": { "text/html": [ "
      " ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "application/javascript": [ "var questionsUiLVShUiZHNA=[\n", " {\n", " \"question\": \"What is Matplotlib used for in Python?\",\n", " \"type\": \"many_choice\",\n", " \"answers\": [\n", " {\n", " \"answer\": \"Web development\",\n", " \"correct\": false,\n", " \"feedback\": \"Incorrect.\"\n", " },\n", " {\n", " \"answer\": \"Data visualization\",\n", " \"correct\": true,\n", " \"feedback\": \"Correct.\"\n", " },\n", " {\n", " \"answer\": \"Machine Learning\",\n", " \"correct\": false,\n", " \"feedback\": \"Incorrect.\"\n", " },\n", " {\n", " \"answer\": \"Networking\",\n", " \"correct\": false,\n", " \"feedback\": \"Incorrect.\"\n", " }\n", " ]\n", " },\n", " {\n", " \"question\": \"How do you import the pyplot module from matplotlib?\",\n", " \"type\": \"many_choice\",\n", " \"answers\": [\n", " {\n", " \"answer\": \"from matplotlib import pyplot as plt\",\n", " \"correct\": true,\n", " \"feedback\": \"Correct.\"\n", " },\n", " {\n", " \"answer\": \"import matplotlib as plt\",\n", " \"correct\": false,\n", " \"feedback\": \"Incorrect.\"\n", " },\n", " {\n", " \"answer\": \"import pyplot from matplotlib\",\n", " \"correct\": false,\n", " \"feedback\": \"Incorrect.\"\n", " },\n", " {\n", " \"answer\": \"import matplotlib.pyplot\",\n", " \"correct\": false,\n", " \"feedback\": \"Incorrect.\"\n", " }\n", " ]\n", " },\n", " {\n", " \"question\": \"Which function is used to create a simple line plot in matplotlib?\",\n", " \"type\": \"many_choice\",\n", " \"answers\": [\n", " {\n", " \"answer\": \"plt.line()\",\n", " \"correct\": false,\n", " \"feedback\": \"Incorrect.\"\n", " },\n", " {\n", " \"answer\": \"plt.plot()\",\n", " \"correct\": true,\n", " \"feedback\": \"Correct.\"\n", " },\n", " {\n", " \"answer\": \"plt.show()\",\n", " \"correct\": false,\n", " \"feedback\": \"Incorrect.\"\n", " },\n", " {\n", " \"answer\": \"plt.graph()\",\n", " \"correct\": false,\n", " \"feedback\": \"Incorrect.\"\n", " }\n", " ]\n", " },\n", " {\n", " \"question\": \"If you want to save a plot to a file, whcih function would you use?\",\n", " \"type\": \"many_choice\",\n", " \"answers\": [\n", " {\n", " \"answer\": \"plt.save()\",\n", " \"correct\": false,\n", " \"feedback\": \"Incorrect.\"\n", " },\n", " {\n", " \"answer\": \"plt.savefig()\",\n", " \"correct\": true,\n", " \"feedback\": \"Correct.\"\n", " },\n", " {\n", " \"answer\": \"plt.export()\",\n", " \"correct\": false,\n", " \"feedback\": \"Incorrect.\"\n", " },\n", " {\n", " \"answer\": \"plt.store()\",\n", " \"correct\": false,\n", " \"feedback\": \"Incorrect.\"\n", " }\n", " ]\n", " },\n", " {\n", " \"question\": \"What is the correct way to show the plot that you have created?\",\n", " \"type\": \"many_choice\",\n", " \"answers\": [\n", " {\n", " \"answer\": \"plt.display()\",\n", " \"correct\": false,\n", " \"feedback\": \"Incorrect.\"\n", " },\n", " {\n", " \"answer\": \"plt.show()\",\n", " \"correct\": true,\n", " \"feedback\": \"Correct.\"\n", " },\n", " {\n", " \"answer\": \"plt.visualize()\",\n", " \"correct\": false,\n", " \"feedback\": \"Incorrect.\"\n", " },\n", " {\n", " \"answer\": \"plt.draw()\",\n", " \"correct\": false,\n", " \"feedback\": \"Incorrect.\"\n", " }\n", " ]\n", " },\n", " {\n", " \"question\": \"Which function would you use to create a histogram in Matplotlib?\",\n", " \"type\": \"many_choice\",\n", " \"answers\": [\n", " {\n", " \"answer\": \"plt.bar()\",\n", " \"correct\": false,\n", " \"feedback\": \"Incorrect.\"\n", " },\n", " {\n", " \"answer\": \"plt.hist()\",\n", " \"correct\": true,\n", " \"feedback\": \"Correct.\"\n", " },\n", " {\n", " \"answer\": \"plt.histogram()\",\n", " \"correct\": false,\n", " \"feedback\": \"Incorrect.\"\n", " },\n", " {\n", " \"answer\": \"plt.scatter()\",\n", " \"correct\": false,\n", " \"feedback\": \"Incorrect.\"\n", " }\n", " ]\n", " },\n", " {\n", " \"question\": \"What does the 'plt.xlabel('Label Name')' function do?\",\n", " \"type\": \"many_choice\",\n", " \"answers\": [\n", " {\n", " \"answer\": \"Changes the plot title to 'Label Name'\",\n", " \"correct\": false,\n", " \"feedback\": \"Incorrect.\"\n", " },\n", " {\n", " \"answer\": \"Sets the label of the x-axis to 'Label Name'\",\n", " \"correct\": true,\n", " \"feedback\": \"Correct.\"\n", " },\n", " {\n", " \"answer\": \"Labels the y-axis as 'Label Name'\",\n", " \"correct\": false,\n", " \"feedback\": \"Incorrect.\"\n", " },\n", " {\n", " \"answer\": \"Labels the first data point as 'Label Name'\",\n", " \"correct\": false,\n", " \"feedback\": \"Incorrect.\"\n", " }\n", " ]\n", " },\n", " {\n", " \"question\": \"How can you add a title to your plot in Matplotlib?\",\n", " \"type\": \"many_choice\",\n", " \"answers\": [\n", " {\n", " \"answer\": \"plt.title('Title of plot')\",\n", " \"correct\": true,\n", " \"feedback\": \"Correct.\"\n", " },\n", " {\n", " \"answer\": \"plt.set_title('Title of Plot')\",\n", " \"correct\": false,\n", " \"feedback\": \"Incorrect.\"\n", " },\n", " {\n", " \"answer\": \"plt.name('Title of Plot')\",\n", " \"correct\": false,\n", " \"feedback\": \"Incorrect.\"\n", " },\n", " {\n", " \"answer\": \"plt.plot_title('Title of Plot')\",\n", " \"correct\": false,\n", " \"feedback\": \"Incorrect.\"\n", " }\n", " ]\n", " },\n", " {\n", " \"question\": \"Which parameter would you adjust to change the line color to red in a plot command?\",\n", " \"type\": \"many_choice\",\n", " \"answers\": [\n", " {\n", " \"answer\": \"plt.plot(x, y, color='red')\",\n", " \"correct\": true,\n", " \"feedback\": \"Correct.\"\n", " },\n", " {\n", " \"answer\": \"plt.plot(x, y, line='red')\",\n", " \"correct\": false,\n", " \"feedback\": \"Incorrect.\"\n", " },\n", " {\n", " \"answer\": \"plt.plot(x, y, style='red')\",\n", " \"correct\": false,\n", " \"feedback\": \"Incorrect.\"\n", " },\n", " {\n", " \"answer\": \"plt.plot(x, y, 'red')\",\n", " \"correct\": false,\n", " \"feedback\": \"Incorrect.\"\n", " }\n", " ]\n", " },\n", " {\n", " \"question\": \"How do you add a legend to a plot in matplotlib?\",\n", " \"type\": \"many_choice\",\n", " \"answers\": [\n", " {\n", " \"answer\": \"plt.legend('Show legend')\",\n", " \"correct\": false,\n", " \"feedback\": \"Incorrect.\"\n", " },\n", " {\n", " \"answer\": \"plt.add_legend()\",\n", " \"correct\": false,\n", " \"feedback\": \"Incorrect.\"\n", " },\n", " {\n", " \"answer\": \"plt.legend()\",\n", " \"correct\": true,\n", " \"feedback\": \"Correct.\"\n", " },\n", " {\n", " \"answer\": \"plt.set_legend()\",\n", " \"correct\": false,\n", " \"feedback\": \"Incorrect.\"\n", " }\n", " ]\n", " }\n", "];\n", " // Make a random ID\n", "function makeid(length) {\n", " var result = [];\n", " var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';\n", " var charactersLength = characters.length;\n", " for (var i = 0; i < length; i++) {\n", " result.push(characters.charAt(Math.floor(Math.random() * charactersLength)));\n", " }\n", " return result.join('');\n", "}\n", "\n", "// Choose a random subset of an array. Can also be used to shuffle the array\n", "function getRandomSubarray(arr, size) {\n", " var shuffled = arr.slice(0), i = arr.length, temp, index;\n", " while (i--) {\n", " index = Math.floor((i + 1) * Math.random());\n", " temp = shuffled[index];\n", " shuffled[index] = shuffled[i];\n", " shuffled[i] = temp;\n", " }\n", " return shuffled.slice(0, size);\n", "}\n", "\n", "function printResponses(responsesContainer) {\n", " var responses=JSON.parse(responsesContainer.dataset.responses);\n", " var stringResponses='IMPORTANT!To preserve this answer sequence for submission, when you have finalized your answers:
      1. Copy the text in this cell below \"Answer String\"
      2. Double click on the cell directly below the Answer String, labeled \"Replace Me\"
      3. Select the whole \"Replace Me\" text
      4. Paste in your answer string and press shift-Enter.
      5. Save the notebook using the save icon or File->Save Notebook menu item



      6. Answer String:
        ';\n", " console.log(responses);\n", " responses.forEach((response, index) => {\n", " if (response) {\n", " console.log(index + ': ' + response);\n", " stringResponses+= index + ': ' + response +\"
        \";\n", " }\n", " });\n", " responsesContainer.innerHTML=stringResponses;\n", "}\n", "function check_mc() {\n", " var id = this.id.split('-')[0];\n", " //var response = this.id.split('-')[1];\n", " //console.log(response);\n", " //console.log(\"In check_mc(), id=\"+id);\n", " //console.log(event.srcElement.id) \n", " //console.log(event.srcElement.dataset.correct) \n", " //console.log(event.srcElement.dataset.feedback)\n", "\n", " var label = event.srcElement;\n", " //console.log(label, label.nodeName);\n", " var depth = 0;\n", " while ((label.nodeName != \"LABEL\") && (depth < 20)) {\n", " label = label.parentElement;\n", " console.log(depth, label);\n", " depth++;\n", " }\n", "\n", "\n", "\n", " var answers = label.parentElement.children;\n", "\n", " //console.log(answers);\n", "\n", "\n", " // Split behavior based on multiple choice vs many choice:\n", " var fb = document.getElementById(\"fb\" + id);\n", "\n", "\n", "\n", "\n", " if (fb.dataset.numcorrect == 1) {\n", " // What follows is for the saved responses stuff\n", " var outerContainer = fb.parentElement.parentElement;\n", " var responsesContainer = document.getElementById(\"responses\" + outerContainer.id);\n", " if (responsesContainer) {\n", " //console.log(responsesContainer);\n", " var response = label.firstChild.innerText;\n", " if (label.querySelector(\".QuizCode\")){\n", " response+= label.querySelector(\".QuizCode\").firstChild.innerText;\n", " }\n", " console.log(response);\n", " //console.log(document.getElementById(\"quizWrap\"+id));\n", " var qnum = document.getElementById(\"quizWrap\"+id).dataset.qnum;\n", " console.log(\"Question \" + qnum);\n", " //console.log(id, \", got numcorrect=\",fb.dataset.numcorrect);\n", " var responses=JSON.parse(responsesContainer.dataset.responses);\n", " console.log(responses);\n", " responses[qnum]= response;\n", " responsesContainer.setAttribute('data-responses', JSON.stringify(responses));\n", " printResponses(responsesContainer);\n", " }\n", " // End code to preserve responses\n", " \n", " for (var i = 0; i < answers.length; i++) {\n", " var child = answers[i];\n", " //console.log(child);\n", " child.className = \"MCButton\";\n", " }\n", "\n", "\n", "\n", " if (label.dataset.correct == \"true\") {\n", " // console.log(\"Correct action\");\n", " if (\"feedback\" in label.dataset) {\n", " fb.textContent = jaxify(label.dataset.feedback);\n", " } else {\n", " fb.textContent = \"Correct!\";\n", " }\n", " label.classList.add(\"correctButton\");\n", "\n", " fb.className = \"Feedback\";\n", " fb.classList.add(\"correct\");\n", "\n", " } else {\n", " if (\"feedback\" in label.dataset) {\n", " fb.textContent = jaxify(label.dataset.feedback);\n", " } else {\n", " fb.textContent = \"Incorrect -- try again.\";\n", " }\n", " //console.log(\"Error action\");\n", " label.classList.add(\"incorrectButton\");\n", " fb.className = \"Feedback\";\n", " fb.classList.add(\"incorrect\");\n", " }\n", " }\n", " else {\n", " var reset = false;\n", " var feedback;\n", " if (label.dataset.correct == \"true\") {\n", " if (\"feedback\" in label.dataset) {\n", " feedback = jaxify(label.dataset.feedback);\n", " } else {\n", " feedback = \"Correct!\";\n", " }\n", " if (label.dataset.answered <= 0) {\n", " if (fb.dataset.answeredcorrect < 0) {\n", " fb.dataset.answeredcorrect = 1;\n", " reset = true;\n", " } else {\n", " fb.dataset.answeredcorrect++;\n", " }\n", " if (reset) {\n", " for (var i = 0; i < answers.length; i++) {\n", " var child = answers[i];\n", " child.className = \"MCButton\";\n", " child.dataset.answered = 0;\n", " }\n", " }\n", " label.classList.add(\"correctButton\");\n", " label.dataset.answered = 1;\n", " fb.className = \"Feedback\";\n", " fb.classList.add(\"correct\");\n", "\n", " }\n", " } else {\n", " if (\"feedback\" in label.dataset) {\n", " feedback = jaxify(label.dataset.feedback);\n", " } else {\n", " feedback = \"Incorrect -- try again.\";\n", " }\n", " if (fb.dataset.answeredcorrect > 0) {\n", " fb.dataset.answeredcorrect = -1;\n", " reset = true;\n", " } else {\n", " fb.dataset.answeredcorrect--;\n", " }\n", "\n", " if (reset) {\n", " for (var i = 0; i < answers.length; i++) {\n", " var child = answers[i];\n", " child.className = \"MCButton\";\n", " child.dataset.answered = 0;\n", " }\n", " }\n", " label.classList.add(\"incorrectButton\");\n", " fb.className = \"Feedback\";\n", " fb.classList.add(\"incorrect\");\n", " }\n", " // What follows is for the saved responses stuff\n", " var outerContainer = fb.parentElement.parentElement;\n", " var responsesContainer = document.getElementById(\"responses\" + outerContainer.id);\n", " if (responsesContainer) {\n", " //console.log(responsesContainer);\n", " var response = label.firstChild.innerText;\n", " if (label.querySelector(\".QuizCode\")){\n", " response+= label.querySelector(\".QuizCode\").firstChild.innerText;\n", " }\n", " console.log(response);\n", " //console.log(document.getElementById(\"quizWrap\"+id));\n", " var qnum = document.getElementById(\"quizWrap\"+id).dataset.qnum;\n", " console.log(\"Question \" + qnum);\n", " //console.log(id, \", got numcorrect=\",fb.dataset.numcorrect);\n", " var responses=JSON.parse(responsesContainer.dataset.responses);\n", " if (label.dataset.correct == \"true\") {\n", " if (typeof(responses[qnum]) == \"object\"){\n", " if (!responses[qnum].includes(response))\n", " responses[qnum].push(response);\n", " } else{\n", " responses[qnum]= [ response ];\n", " }\n", " } else {\n", " responses[qnum]= response;\n", " }\n", " console.log(responses);\n", " responsesContainer.setAttribute('data-responses', JSON.stringify(responses));\n", " printResponses(responsesContainer);\n", " }\n", " // End save responses stuff\n", "\n", "\n", "\n", " var numcorrect = fb.dataset.numcorrect;\n", " var answeredcorrect = fb.dataset.answeredcorrect;\n", " if (answeredcorrect >= 0) {\n", " fb.textContent = feedback + \" [\" + answeredcorrect + \"/\" + numcorrect + \"]\";\n", " } else {\n", " fb.textContent = feedback + \" [\" + 0 + \"/\" + numcorrect + \"]\";\n", " }\n", "\n", "\n", " }\n", "\n", " if (typeof MathJax != 'undefined') {\n", " var version = MathJax.version;\n", " console.log('MathJax version', version);\n", " if (version[0] == \"2\") {\n", " MathJax.Hub.Queue([\"Typeset\", MathJax.Hub]);\n", " } else if (version[0] == \"3\") {\n", " MathJax.typeset([fb]);\n", " }\n", " } else {\n", " console.log('MathJax not detected');\n", " }\n", "\n", "}\n", "\n", "function make_mc(qa, shuffle_answers, outerqDiv, qDiv, aDiv, id) {\n", " var shuffled;\n", " if (shuffle_answers == \"True\") {\n", " //console.log(shuffle_answers+\" read as true\");\n", " shuffled = getRandomSubarray(qa.answers, qa.answers.length);\n", " } else {\n", " //console.log(shuffle_answers+\" read as false\");\n", " shuffled = qa.answers;\n", " }\n", "\n", "\n", " var num_correct = 0;\n", "\n", "\n", "\n", " shuffled.forEach((item, index, ans_array) => {\n", " //console.log(answer);\n", "\n", " // Make input element\n", " var inp = document.createElement(\"input\");\n", " inp.type = \"radio\";\n", " inp.id = \"quizo\" + id + index;\n", " inp.style = \"display:none;\";\n", " aDiv.append(inp);\n", "\n", " //Make label for input element\n", " var lab = document.createElement(\"label\");\n", " lab.className = \"MCButton\";\n", " lab.id = id + '-' + index;\n", " lab.onclick = check_mc;\n", " var aSpan = document.createElement('span');\n", " aSpan.classsName = \"\";\n", " //qDiv.id=\"quizQn\"+id+index;\n", " if (\"answer\" in item) {\n", " aSpan.innerHTML = jaxify(item.answer);\n", " //aSpan.innerHTML=item.answer;\n", " }\n", " lab.append(aSpan);\n", "\n", " // Create div for code inside question\n", " var codeSpan;\n", " if (\"code\" in item) {\n", " codeSpan = document.createElement('span');\n", " codeSpan.id = \"code\" + id + index;\n", " codeSpan.className = \"QuizCode\";\n", " var codePre = document.createElement('pre');\n", " codeSpan.append(codePre);\n", " var codeCode = document.createElement('code');\n", " codePre.append(codeCode);\n", " codeCode.innerHTML = item.code;\n", " lab.append(codeSpan);\n", " //console.log(codeSpan);\n", " }\n", "\n", " //lab.textContent=item.answer;\n", "\n", " // Set the data attributes for the answer\n", " lab.setAttribute('data-correct', item.correct);\n", " if (item.correct) {\n", " num_correct++;\n", " }\n", " if (\"feedback\" in item) {\n", " lab.setAttribute('data-feedback', item.feedback);\n", " }\n", " lab.setAttribute('data-answered', 0);\n", "\n", " aDiv.append(lab);\n", "\n", " });\n", "\n", " if (num_correct > 1) {\n", " outerqDiv.className = \"ManyChoiceQn\";\n", " } else {\n", " outerqDiv.className = \"MultipleChoiceQn\";\n", " }\n", "\n", " return num_correct;\n", "\n", "}\n", "function check_numeric(ths, event) {\n", "\n", " if (event.keyCode === 13) {\n", " ths.blur();\n", "\n", " var id = ths.id.split('-')[0];\n", "\n", " var submission = ths.value;\n", " if (submission.indexOf('/') != -1) {\n", " var sub_parts = submission.split('/');\n", " //console.log(sub_parts);\n", " submission = sub_parts[0] / sub_parts[1];\n", " }\n", " //console.log(\"Reader entered\", submission);\n", "\n", " if (\"precision\" in ths.dataset) {\n", " var precision = ths.dataset.precision;\n", " // console.log(\"1:\", submission)\n", " submission = Math.round((1 * submission + Number.EPSILON) * 10 ** precision) / 10 ** precision;\n", " // console.log(\"Rounded to \", submission, \" precision=\", precision );\n", " }\n", "\n", "\n", " //console.log(\"In check_numeric(), id=\"+id);\n", " //console.log(event.srcElement.id) \n", " //console.log(event.srcElement.dataset.feedback)\n", "\n", " var fb = document.getElementById(\"fb\" + id);\n", " fb.style.display = \"none\";\n", " fb.textContent = \"Incorrect -- try again.\";\n", "\n", " var answers = JSON.parse(ths.dataset.answers);\n", " //console.log(answers);\n", "\n", " var defaultFB = \"\";\n", " var correct;\n", " var done = false;\n", " answers.every(answer => {\n", " //console.log(answer.type);\n", "\n", " correct = false;\n", " // if (answer.type==\"value\"){\n", " if ('value' in answer) {\n", " if (submission == answer.value) {\n", " if (\"feedback\" in answer) {\n", " fb.textContent = jaxify(answer.feedback);\n", " } else {\n", " fb.textContent = jaxify(\"Correct\");\n", " }\n", " correct = answer.correct;\n", " //console.log(answer.correct);\n", " done = true;\n", " }\n", " // } else if (answer.type==\"range\") {\n", " } else if ('range' in answer) {\n", " //console.log(answer.range);\n", " if ((submission >= answer.range[0]) && (submission < answer.range[1])) {\n", " fb.textContent = jaxify(answer.feedback);\n", " correct = answer.correct;\n", " //console.log(answer.correct);\n", " done = true;\n", " }\n", " } else if (answer.type == \"default\") {\n", " defaultFB = answer.feedback;\n", " }\n", " if (done) {\n", " return false; // Break out of loop if this has been marked correct\n", " } else {\n", " return true; // Keep looking for case that includes this as a correct answer\n", " }\n", " });\n", "\n", " if ((!done) && (defaultFB != \"\")) {\n", " fb.innerHTML = jaxify(defaultFB);\n", " //console.log(\"Default feedback\", defaultFB);\n", " }\n", "\n", " fb.style.display = \"block\";\n", " if (correct) {\n", " ths.className = \"Input-text\";\n", " ths.classList.add(\"correctButton\");\n", " fb.className = \"Feedback\";\n", " fb.classList.add(\"correct\");\n", " } else {\n", " ths.className = \"Input-text\";\n", " ths.classList.add(\"incorrectButton\");\n", " fb.className = \"Feedback\";\n", " fb.classList.add(\"incorrect\");\n", " }\n", "\n", " // What follows is for the saved responses stuff\n", " var outerContainer = fb.parentElement.parentElement;\n", " var responsesContainer = document.getElementById(\"responses\" + outerContainer.id);\n", " if (responsesContainer) {\n", " console.log(submission);\n", " var qnum = document.getElementById(\"quizWrap\"+id).dataset.qnum;\n", " //console.log(\"Question \" + qnum);\n", " //console.log(id, \", got numcorrect=\",fb.dataset.numcorrect);\n", " var responses=JSON.parse(responsesContainer.dataset.responses);\n", " console.log(responses);\n", " if (submission == ths.value){\n", " responses[qnum]= submission;\n", " } else {\n", " responses[qnum]= ths.value + \"(\" + submission +\")\";\n", " }\n", " responsesContainer.setAttribute('data-responses', JSON.stringify(responses));\n", " printResponses(responsesContainer);\n", " }\n", " // End code to preserve responses\n", "\n", " if (typeof MathJax != 'undefined') {\n", " var version = MathJax.version;\n", " console.log('MathJax version', version);\n", " if (version[0] == \"2\") {\n", " MathJax.Hub.Queue([\"Typeset\", MathJax.Hub]);\n", " } else if (version[0] == \"3\") {\n", " MathJax.typeset([fb]);\n", " }\n", " } else {\n", " console.log('MathJax not detected');\n", " }\n", " return false;\n", " }\n", "\n", "}\n", "\n", "function isValid(el, charC) {\n", " //console.log(\"Input char: \", charC);\n", " if (charC == 46) {\n", " if (el.value.indexOf('.') === -1) {\n", " return true;\n", " } else if (el.value.indexOf('/') != -1) {\n", " var parts = el.value.split('/');\n", " if (parts[1].indexOf('.') === -1) {\n", " return true;\n", " }\n", " }\n", " else {\n", " return false;\n", " }\n", " } else if (charC == 47) {\n", " if (el.value.indexOf('/') === -1) {\n", " if ((el.value != \"\") && (el.value != \".\")) {\n", " return true;\n", " } else {\n", " return false;\n", " }\n", " } else {\n", " return false;\n", " }\n", " } else if (charC == 45) {\n", " var edex = el.value.indexOf('e');\n", " if (edex == -1) {\n", " edex = el.value.indexOf('E');\n", " }\n", "\n", " if (el.value == \"\") {\n", " return true;\n", " } else if (edex == (el.value.length - 1)) { // If just after e or E\n", " return true;\n", " } else {\n", " return false;\n", " }\n", " } else if (charC == 101) { // \"e\"\n", " if ((el.value.indexOf('e') === -1) && (el.value.indexOf('E') === -1) && (el.value.indexOf('/') == -1)) {\n", " // Prev symbol must be digit or decimal point:\n", " if (el.value.slice(-1).search(/\\d/) >= 0) {\n", " return true;\n", " } else if (el.value.slice(-1).search(/\\./) >= 0) {\n", " return true;\n", " } else {\n", " return false;\n", " }\n", " } else {\n", " return false;\n", " }\n", " } else {\n", " if (charC > 31 && (charC < 48 || charC > 57))\n", " return false;\n", " }\n", " return true;\n", "}\n", "\n", "function numeric_keypress(evnt) {\n", " var charC = (evnt.which) ? evnt.which : evnt.keyCode;\n", "\n", " if (charC == 13) {\n", " check_numeric(this, evnt);\n", " } else {\n", " return isValid(this, charC);\n", " }\n", "}\n", "\n", "\n", "\n", "\n", "\n", "function make_numeric(qa, outerqDiv, qDiv, aDiv, id) {\n", "\n", "\n", "\n", " //console.log(answer);\n", "\n", "\n", " outerqDiv.className = \"NumericQn\";\n", " aDiv.style.display = 'block';\n", "\n", " var lab = document.createElement(\"label\");\n", " lab.className = \"InpLabel\";\n", " lab.textContent = \"Type numeric answer here:\";\n", " aDiv.append(lab);\n", "\n", " var inp = document.createElement(\"input\");\n", " inp.type = \"text\";\n", " //inp.id=\"input-\"+id;\n", " inp.id = id + \"-0\";\n", " inp.className = \"Input-text\";\n", " inp.setAttribute('data-answers', JSON.stringify(qa.answers));\n", " if (\"precision\" in qa) {\n", " inp.setAttribute('data-precision', qa.precision);\n", " }\n", " aDiv.append(inp);\n", " //console.log(inp);\n", "\n", " //inp.addEventListener(\"keypress\", check_numeric);\n", " //inp.addEventListener(\"keypress\", numeric_keypress);\n", " /*\n", " inp.addEventListener(\"keypress\", function(event) {\n", " return numeric_keypress(this, event);\n", " }\n", " );\n", " */\n", " //inp.onkeypress=\"return numeric_keypress(this, event)\";\n", " inp.onkeypress = numeric_keypress;\n", " inp.onpaste = event => false;\n", "\n", " inp.addEventListener(\"focus\", function (event) {\n", " this.value = \"\";\n", " return false;\n", " }\n", " );\n", "\n", "\n", "}\n", "function jaxify(string) {\n", " var mystring = string;\n", "\n", " var count = 0;\n", " var loc = mystring.search(/([^\\\\]|^)(\\$)/);\n", "\n", " var count2 = 0;\n", " var loc2 = mystring.search(/([^\\\\]|^)(\\$\\$)/);\n", "\n", " //console.log(loc);\n", "\n", " while ((loc >= 0) || (loc2 >= 0)) {\n", "\n", " /* Have to replace all the double $$ first with current implementation */\n", " if (loc2 >= 0) {\n", " if (count2 % 2 == 0) {\n", " mystring = mystring.replace(/([^\\\\]|^)(\\$\\$)/, \"$1\\\\[\");\n", " } else {\n", " mystring = mystring.replace(/([^\\\\]|^)(\\$\\$)/, \"$1\\\\]\");\n", " }\n", " count2++;\n", " } else {\n", " if (count % 2 == 0) {\n", " mystring = mystring.replace(/([^\\\\]|^)(\\$)/, \"$1\\\\(\");\n", " } else {\n", " mystring = mystring.replace(/([^\\\\]|^)(\\$)/, \"$1\\\\)\");\n", " }\n", " count++;\n", " }\n", " loc = mystring.search(/([^\\\\]|^)(\\$)/);\n", " loc2 = mystring.search(/([^\\\\]|^)(\\$\\$)/);\n", " //console.log(mystring,\", loc:\",loc,\", loc2:\",loc2);\n", " }\n", "\n", " //console.log(mystring);\n", " return mystring;\n", "}\n", "\n", "\n", "function show_questions(json, mydiv) {\n", " console.log('show_questions');\n", " //var mydiv=document.getElementById(myid);\n", " var shuffle_questions = mydiv.dataset.shufflequestions;\n", " var num_questions = mydiv.dataset.numquestions;\n", " var shuffle_answers = mydiv.dataset.shuffleanswers;\n", " var max_width = mydiv.dataset.maxwidth;\n", "\n", " if (num_questions > json.length) {\n", " num_questions = json.length;\n", " }\n", "\n", " var questions;\n", " if ((num_questions < json.length) || (shuffle_questions == \"True\")) {\n", " //console.log(num_questions+\",\"+json.length);\n", " questions = getRandomSubarray(json, num_questions);\n", " } else {\n", " questions = json;\n", " }\n", "\n", " //console.log(\"SQ: \"+shuffle_questions+\", NQ: \" + num_questions + \", SA: \", shuffle_answers);\n", "\n", " // Iterate over questions\n", " questions.forEach((qa, index, array) => {\n", " //console.log(qa.question); \n", "\n", " var id = makeid(8);\n", " //console.log(id);\n", "\n", "\n", " // Create Div to contain question and answers\n", " var iDiv = document.createElement('div');\n", " //iDiv.id = 'quizWrap' + id + index;\n", " iDiv.id = 'quizWrap' + id;\n", " iDiv.className = 'Quiz';\n", " iDiv.setAttribute('data-qnum', index);\n", " iDiv.style.maxWidth =max_width+\"px\";\n", " mydiv.appendChild(iDiv);\n", " // iDiv.innerHTML=qa.question;\n", " \n", " var outerqDiv = document.createElement('div');\n", " outerqDiv.id = \"OuterquizQn\" + id + index;\n", " // Create div to contain question part\n", " var qDiv = document.createElement('div');\n", " qDiv.id = \"quizQn\" + id + index;\n", " \n", " if (qa.question) {\n", " iDiv.append(outerqDiv);\n", "\n", " //qDiv.textContent=qa.question;\n", " qDiv.innerHTML = jaxify(qa.question);\n", " outerqDiv.append(qDiv);\n", " }\n", "\n", " // Create div for code inside question\n", " var codeDiv;\n", " if (\"code\" in qa) {\n", " codeDiv = document.createElement('div');\n", " codeDiv.id = \"code\" + id + index;\n", " codeDiv.className = \"QuizCode\";\n", " var codePre = document.createElement('pre');\n", " codeDiv.append(codePre);\n", " var codeCode = document.createElement('code');\n", " codePre.append(codeCode);\n", " codeCode.innerHTML = qa.code;\n", " outerqDiv.append(codeDiv);\n", " //console.log(codeDiv);\n", " }\n", "\n", "\n", " // Create div to contain answer part\n", " var aDiv = document.createElement('div');\n", " aDiv.id = \"quizAns\" + id + index;\n", " aDiv.className = 'Answer';\n", " iDiv.append(aDiv);\n", "\n", " //console.log(qa.type);\n", "\n", " var num_correct;\n", " if ((qa.type == \"multiple_choice\") || (qa.type == \"many_choice\") ) {\n", " num_correct = make_mc(qa, shuffle_answers, outerqDiv, qDiv, aDiv, id);\n", " if (\"answer_cols\" in qa) {\n", " //aDiv.style.gridTemplateColumns = 'auto '.repeat(qa.answer_cols);\n", " aDiv.style.gridTemplateColumns = 'repeat(' + qa.answer_cols + ', 1fr)';\n", " }\n", " } else if (qa.type == \"numeric\") {\n", " //console.log(\"numeric\");\n", " make_numeric(qa, outerqDiv, qDiv, aDiv, id);\n", " }\n", "\n", "\n", " //Make div for feedback\n", " var fb = document.createElement(\"div\");\n", " fb.id = \"fb\" + id;\n", " //fb.style=\"font-size: 20px;text-align:center;\";\n", " fb.className = \"Feedback\";\n", " fb.setAttribute(\"data-answeredcorrect\", 0);\n", " fb.setAttribute(\"data-numcorrect\", num_correct);\n", " iDiv.append(fb);\n", "\n", "\n", " });\n", " var preserveResponses = mydiv.dataset.preserveresponses;\n", " console.log(preserveResponses);\n", " console.log(preserveResponses == \"true\");\n", " if (preserveResponses == \"true\") {\n", " console.log(preserveResponses);\n", " // Create Div to contain record of answers\n", " var iDiv = document.createElement('div');\n", " iDiv.id = 'responses' + mydiv.id;\n", " iDiv.className = 'JCResponses';\n", " // Create a place to store responses as an empty array\n", " iDiv.setAttribute('data-responses', '[]');\n", "\n", " // Dummy Text\n", " iDiv.innerHTML=\"Select your answers and then follow the directions that will appear here.\"\n", " //iDiv.className = 'Quiz';\n", " mydiv.appendChild(iDiv);\n", " }\n", "//console.log(\"At end of show_questions\");\n", " if (typeof MathJax != 'undefined') {\n", " console.log(\"MathJax version\", MathJax.version);\n", " var version = MathJax.version;\n", " setTimeout(function(){\n", " var version = MathJax.version;\n", " console.log('After sleep, MathJax version', version);\n", " if (version[0] == \"2\") {\n", " MathJax.Hub.Queue([\"Typeset\", MathJax.Hub]);\n", " } else if (version[0] == \"3\") {\n", " MathJax.typeset([mydiv]);\n", " }\n", " }, 500);\n", "if (typeof version == 'undefined') {\n", " } else\n", " {\n", " if (version[0] == \"2\") {\n", " MathJax.Hub.Queue([\"Typeset\", MathJax.Hub]);\n", " } else if (version[0] == \"3\") {\n", " MathJax.typeset([mydiv]);\n", " } else {\n", " console.log(\"MathJax not found\");\n", " }\n", " }\n", " }\n", " return false;\n", "}\n", "/* This is to handle asynchrony issues in loading Jupyter notebooks\n", " where the quiz has been previously run. The Javascript was generally\n", " being run before the div was added to the DOM. I tried to do this\n", " more elegantly using Mutation Observer, but I didn't get it to work.\n", "\n", " Someone more knowledgeable could make this better ;-) */\n", "\n", " function try_show() {\n", " if(document.getElementById(\"UiLVShUiZHNA\")) {\n", " show_questions(questionsUiLVShUiZHNA, UiLVShUiZHNA); \n", " } else {\n", " setTimeout(try_show, 200);\n", " }\n", " };\n", " \n", " {\n", " // console.log(element);\n", "\n", " //console.log(\"UiLVShUiZHNA\");\n", " // console.log(document.getElementById(\"UiLVShUiZHNA\"));\n", "\n", " try_show();\n", " }\n", " " ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "from jupyterquiz import display_quiz\n", "display_quiz(\"quizes/matplotlib_course_skip_quiz.json\")" ] }, { "cell_type": "markdown", "id": "6d5afc1b-db4a-4ff1-8542-b266a531bfe8", "metadata": {}, "source": [ "# Scikit Learn" ] }, { "cell_type": "code", "execution_count": 7, "id": "8e0eaf20-7491-4002-b0a6-e9fe6b5ceafc", "metadata": { "editable": true, "slideshow": { "slide_type": "" }, "tags": [ "remove-input" ] }, "outputs": [ { "data": { "text/html": [ "
        " ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "application/javascript": [ "var questionsVBwdbPbLuQFv=[\n", " {\n", " \"question\": \"What function from scikit-learn is typically used to fit a linear regression model?\",\n", " \"type\": \"many_choice\",\n", " \"answers\": [\n", " {\n", " \"answer\": \"linear_model.LogisticRegression()\",\n", " \"correct\": false,\n", " \"feedback\": \"Incorrect.\"\n", " },\n", " {\n", " \"answer\": \"linear_model.LinearRegression()\",\n", " \"correct\": true,\n", " \"feedback\": \"Correct.\"\n", " },\n", " {\n", " \"answer\": \"cluster.KMeans()\",\n", " \"correct\": false,\n", " \"feedback\": \"Incorrect.\"\n", " },\n", " {\n", " \"answer\": \"tree.DecisionTreeClassifier()\",\n", " \"correct\": false,\n", " \"feedback\": \"Incorrect.\"\n", " }\n", " ]\n", " },\n", " {\n", " \"question\": \"What is the main purpose of the KMeans algorithm in scikit-learn?\",\n", " \"type\": \"many_choice\",\n", " \"answers\": [\n", " {\n", " \"answer\": \"To classify data into pre-defined categories\",\n", " \"correct\": false,\n", " \"feedback\": \"Incorrect.\"\n", " },\n", " {\n", " \"answer\": \"To reduce the dimensionality of the feature space\",\n", " \"correct\": false,\n", " \"feedback\": \"Incorrect.\"\n", " },\n", " {\n", " \"answer\": \"To partition the data into a set of k groups based on feature similarities\",\n", " \"correct\": true,\n", " \"feedback\": \"correct.\"\n", " },\n", " {\n", " \"answer\": \"To predict a continuous target variable\",\n", " \"correct\": false,\n", " \"feedback\": \"Incorrect.\"\n", " }\n", " ]\n", " },\n", " {\n", " \"question\": \"What is the purpose of the 'random_state' parameter in scikit-learn algorithms?\",\n", " \"type\": \"many_choice\",\n", " \"answers\": [\n", " {\n", " \"answer\": \"To select the number of features to include in a model automatically.\",\n", " \"correct\": false,\n", " \"feedback\": \"Incorrect.\"\n", " },\n", " {\n", " \"answer\": \"To determine the number of cluster or classes in the output.\",\n", " \"correct\": false,\n", " \"feedback\": \"Incorrect.\"\n", " },\n", " {\n", " \"answer\": \"To ensure reproducibility of results by setting a seed for the random number generator.\",\n", " \"correct\": true,\n", " \"feedback\": \"Correct.\"\n", " },\n", " {\n", " \"answer\": \"To increase the computational efficiency of the algorithm.\",\n", " \"correct\": false,\n", " \"feedback\": \"Incorrect.\"\n", " }\n", " ]\n", " },\n", " {\n", " \"question\": \"In a Linear regression model, after fitting the model, where can you find the slope and intercept of the linear equation?\",\n", " \"type\": \"many_choice\",\n", " \"answers\": [\n", " {\n", " \"answer\": \"Slope in coef_, intercept in intercept_\",\n", " \"correct\": false,\n", " \"feedback\": \"Incorrect.\"\n", " },\n", " {\n", " \"answer\": \"Slope in coef_, intercept in intercept_\",\n", " \"correct\": true,\n", " \"feedback\": \"Correct.\"\n", " },\n", " {\n", " \"answer\": \"Slope in slope_, intercept in constant_\",\n", " \"correct\": false,\n", " \"feedback\": \"Incorrect.\"\n", " },\n", " {\n", " \"answer\": \"Slope in parameters_, intercept in bias_'\",\n", " \"correct\": false,\n", " \"feedback\": \"Incorrect.\"\n", " }\n", " ]\n", " },\n", " {\n", " \"question\": \"After a model has been trained using scikit-learn, which method is used to make predicitions on new data?\",\n", " \"type\": \"many_choice\",\n", " \"answers\": [\n", " {\n", " \"answer\": \"predict()\",\n", " \"correct\": true,\n", " \"feedback\": \"Correct.\"\n", " },\n", " {\n", " \"answer\": \"fit()\",\n", " \"correct\": false,\n", " \"feedback\": \"Incorrect.\"\n", " },\n", " {\n", " \"answer\": \"transform()\",\n", " \"correct\": false,\n", " \"feedback\": \"Incorrect.\"\n", " },\n", " {\n", " \"answer\": \"score()\",\n", " \"correct\": false,\n", " \"feedback\": \"Incorrect.\"\n", " }\n", " ]\n", " }\n", "];\n", " // Make a random ID\n", "function makeid(length) {\n", " var result = [];\n", " var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';\n", " var charactersLength = characters.length;\n", " for (var i = 0; i < length; i++) {\n", " result.push(characters.charAt(Math.floor(Math.random() * charactersLength)));\n", " }\n", " return result.join('');\n", "}\n", "\n", "// Choose a random subset of an array. Can also be used to shuffle the array\n", "function getRandomSubarray(arr, size) {\n", " var shuffled = arr.slice(0), i = arr.length, temp, index;\n", " while (i--) {\n", " index = Math.floor((i + 1) * Math.random());\n", " temp = shuffled[index];\n", " shuffled[index] = shuffled[i];\n", " shuffled[i] = temp;\n", " }\n", " return shuffled.slice(0, size);\n", "}\n", "\n", "function printResponses(responsesContainer) {\n", " var responses=JSON.parse(responsesContainer.dataset.responses);\n", " var stringResponses='IMPORTANT!To preserve this answer sequence for submission, when you have finalized your answers:
        1. Copy the text in this cell below \"Answer String\"
        2. Double click on the cell directly below the Answer String, labeled \"Replace Me\"
        3. Select the whole \"Replace Me\" text
        4. Paste in your answer string and press shift-Enter.
        5. Save the notebook using the save icon or File->Save Notebook menu item



        6. Answer String:
          ';\n", " console.log(responses);\n", " responses.forEach((response, index) => {\n", " if (response) {\n", " console.log(index + ': ' + response);\n", " stringResponses+= index + ': ' + response +\"
          \";\n", " }\n", " });\n", " responsesContainer.innerHTML=stringResponses;\n", "}\n", "function check_mc() {\n", " var id = this.id.split('-')[0];\n", " //var response = this.id.split('-')[1];\n", " //console.log(response);\n", " //console.log(\"In check_mc(), id=\"+id);\n", " //console.log(event.srcElement.id) \n", " //console.log(event.srcElement.dataset.correct) \n", " //console.log(event.srcElement.dataset.feedback)\n", "\n", " var label = event.srcElement;\n", " //console.log(label, label.nodeName);\n", " var depth = 0;\n", " while ((label.nodeName != \"LABEL\") && (depth < 20)) {\n", " label = label.parentElement;\n", " console.log(depth, label);\n", " depth++;\n", " }\n", "\n", "\n", "\n", " var answers = label.parentElement.children;\n", "\n", " //console.log(answers);\n", "\n", "\n", " // Split behavior based on multiple choice vs many choice:\n", " var fb = document.getElementById(\"fb\" + id);\n", "\n", "\n", "\n", "\n", " if (fb.dataset.numcorrect == 1) {\n", " // What follows is for the saved responses stuff\n", " var outerContainer = fb.parentElement.parentElement;\n", " var responsesContainer = document.getElementById(\"responses\" + outerContainer.id);\n", " if (responsesContainer) {\n", " //console.log(responsesContainer);\n", " var response = label.firstChild.innerText;\n", " if (label.querySelector(\".QuizCode\")){\n", " response+= label.querySelector(\".QuizCode\").firstChild.innerText;\n", " }\n", " console.log(response);\n", " //console.log(document.getElementById(\"quizWrap\"+id));\n", " var qnum = document.getElementById(\"quizWrap\"+id).dataset.qnum;\n", " console.log(\"Question \" + qnum);\n", " //console.log(id, \", got numcorrect=\",fb.dataset.numcorrect);\n", " var responses=JSON.parse(responsesContainer.dataset.responses);\n", " console.log(responses);\n", " responses[qnum]= response;\n", " responsesContainer.setAttribute('data-responses', JSON.stringify(responses));\n", " printResponses(responsesContainer);\n", " }\n", " // End code to preserve responses\n", " \n", " for (var i = 0; i < answers.length; i++) {\n", " var child = answers[i];\n", " //console.log(child);\n", " child.className = \"MCButton\";\n", " }\n", "\n", "\n", "\n", " if (label.dataset.correct == \"true\") {\n", " // console.log(\"Correct action\");\n", " if (\"feedback\" in label.dataset) {\n", " fb.textContent = jaxify(label.dataset.feedback);\n", " } else {\n", " fb.textContent = \"Correct!\";\n", " }\n", " label.classList.add(\"correctButton\");\n", "\n", " fb.className = \"Feedback\";\n", " fb.classList.add(\"correct\");\n", "\n", " } else {\n", " if (\"feedback\" in label.dataset) {\n", " fb.textContent = jaxify(label.dataset.feedback);\n", " } else {\n", " fb.textContent = \"Incorrect -- try again.\";\n", " }\n", " //console.log(\"Error action\");\n", " label.classList.add(\"incorrectButton\");\n", " fb.className = \"Feedback\";\n", " fb.classList.add(\"incorrect\");\n", " }\n", " }\n", " else {\n", " var reset = false;\n", " var feedback;\n", " if (label.dataset.correct == \"true\") {\n", " if (\"feedback\" in label.dataset) {\n", " feedback = jaxify(label.dataset.feedback);\n", " } else {\n", " feedback = \"Correct!\";\n", " }\n", " if (label.dataset.answered <= 0) {\n", " if (fb.dataset.answeredcorrect < 0) {\n", " fb.dataset.answeredcorrect = 1;\n", " reset = true;\n", " } else {\n", " fb.dataset.answeredcorrect++;\n", " }\n", " if (reset) {\n", " for (var i = 0; i < answers.length; i++) {\n", " var child = answers[i];\n", " child.className = \"MCButton\";\n", " child.dataset.answered = 0;\n", " }\n", " }\n", " label.classList.add(\"correctButton\");\n", " label.dataset.answered = 1;\n", " fb.className = \"Feedback\";\n", " fb.classList.add(\"correct\");\n", "\n", " }\n", " } else {\n", " if (\"feedback\" in label.dataset) {\n", " feedback = jaxify(label.dataset.feedback);\n", " } else {\n", " feedback = \"Incorrect -- try again.\";\n", " }\n", " if (fb.dataset.answeredcorrect > 0) {\n", " fb.dataset.answeredcorrect = -1;\n", " reset = true;\n", " } else {\n", " fb.dataset.answeredcorrect--;\n", " }\n", "\n", " if (reset) {\n", " for (var i = 0; i < answers.length; i++) {\n", " var child = answers[i];\n", " child.className = \"MCButton\";\n", " child.dataset.answered = 0;\n", " }\n", " }\n", " label.classList.add(\"incorrectButton\");\n", " fb.className = \"Feedback\";\n", " fb.classList.add(\"incorrect\");\n", " }\n", " // What follows is for the saved responses stuff\n", " var outerContainer = fb.parentElement.parentElement;\n", " var responsesContainer = document.getElementById(\"responses\" + outerContainer.id);\n", " if (responsesContainer) {\n", " //console.log(responsesContainer);\n", " var response = label.firstChild.innerText;\n", " if (label.querySelector(\".QuizCode\")){\n", " response+= label.querySelector(\".QuizCode\").firstChild.innerText;\n", " }\n", " console.log(response);\n", " //console.log(document.getElementById(\"quizWrap\"+id));\n", " var qnum = document.getElementById(\"quizWrap\"+id).dataset.qnum;\n", " console.log(\"Question \" + qnum);\n", " //console.log(id, \", got numcorrect=\",fb.dataset.numcorrect);\n", " var responses=JSON.parse(responsesContainer.dataset.responses);\n", " if (label.dataset.correct == \"true\") {\n", " if (typeof(responses[qnum]) == \"object\"){\n", " if (!responses[qnum].includes(response))\n", " responses[qnum].push(response);\n", " } else{\n", " responses[qnum]= [ response ];\n", " }\n", " } else {\n", " responses[qnum]= response;\n", " }\n", " console.log(responses);\n", " responsesContainer.setAttribute('data-responses', JSON.stringify(responses));\n", " printResponses(responsesContainer);\n", " }\n", " // End save responses stuff\n", "\n", "\n", "\n", " var numcorrect = fb.dataset.numcorrect;\n", " var answeredcorrect = fb.dataset.answeredcorrect;\n", " if (answeredcorrect >= 0) {\n", " fb.textContent = feedback + \" [\" + answeredcorrect + \"/\" + numcorrect + \"]\";\n", " } else {\n", " fb.textContent = feedback + \" [\" + 0 + \"/\" + numcorrect + \"]\";\n", " }\n", "\n", "\n", " }\n", "\n", " if (typeof MathJax != 'undefined') {\n", " var version = MathJax.version;\n", " console.log('MathJax version', version);\n", " if (version[0] == \"2\") {\n", " MathJax.Hub.Queue([\"Typeset\", MathJax.Hub]);\n", " } else if (version[0] == \"3\") {\n", " MathJax.typeset([fb]);\n", " }\n", " } else {\n", " console.log('MathJax not detected');\n", " }\n", "\n", "}\n", "\n", "function make_mc(qa, shuffle_answers, outerqDiv, qDiv, aDiv, id) {\n", " var shuffled;\n", " if (shuffle_answers == \"True\") {\n", " //console.log(shuffle_answers+\" read as true\");\n", " shuffled = getRandomSubarray(qa.answers, qa.answers.length);\n", " } else {\n", " //console.log(shuffle_answers+\" read as false\");\n", " shuffled = qa.answers;\n", " }\n", "\n", "\n", " var num_correct = 0;\n", "\n", "\n", "\n", " shuffled.forEach((item, index, ans_array) => {\n", " //console.log(answer);\n", "\n", " // Make input element\n", " var inp = document.createElement(\"input\");\n", " inp.type = \"radio\";\n", " inp.id = \"quizo\" + id + index;\n", " inp.style = \"display:none;\";\n", " aDiv.append(inp);\n", "\n", " //Make label for input element\n", " var lab = document.createElement(\"label\");\n", " lab.className = \"MCButton\";\n", " lab.id = id + '-' + index;\n", " lab.onclick = check_mc;\n", " var aSpan = document.createElement('span');\n", " aSpan.classsName = \"\";\n", " //qDiv.id=\"quizQn\"+id+index;\n", " if (\"answer\" in item) {\n", " aSpan.innerHTML = jaxify(item.answer);\n", " //aSpan.innerHTML=item.answer;\n", " }\n", " lab.append(aSpan);\n", "\n", " // Create div for code inside question\n", " var codeSpan;\n", " if (\"code\" in item) {\n", " codeSpan = document.createElement('span');\n", " codeSpan.id = \"code\" + id + index;\n", " codeSpan.className = \"QuizCode\";\n", " var codePre = document.createElement('pre');\n", " codeSpan.append(codePre);\n", " var codeCode = document.createElement('code');\n", " codePre.append(codeCode);\n", " codeCode.innerHTML = item.code;\n", " lab.append(codeSpan);\n", " //console.log(codeSpan);\n", " }\n", "\n", " //lab.textContent=item.answer;\n", "\n", " // Set the data attributes for the answer\n", " lab.setAttribute('data-correct', item.correct);\n", " if (item.correct) {\n", " num_correct++;\n", " }\n", " if (\"feedback\" in item) {\n", " lab.setAttribute('data-feedback', item.feedback);\n", " }\n", " lab.setAttribute('data-answered', 0);\n", "\n", " aDiv.append(lab);\n", "\n", " });\n", "\n", " if (num_correct > 1) {\n", " outerqDiv.className = \"ManyChoiceQn\";\n", " } else {\n", " outerqDiv.className = \"MultipleChoiceQn\";\n", " }\n", "\n", " return num_correct;\n", "\n", "}\n", "function check_numeric(ths, event) {\n", "\n", " if (event.keyCode === 13) {\n", " ths.blur();\n", "\n", " var id = ths.id.split('-')[0];\n", "\n", " var submission = ths.value;\n", " if (submission.indexOf('/') != -1) {\n", " var sub_parts = submission.split('/');\n", " //console.log(sub_parts);\n", " submission = sub_parts[0] / sub_parts[1];\n", " }\n", " //console.log(\"Reader entered\", submission);\n", "\n", " if (\"precision\" in ths.dataset) {\n", " var precision = ths.dataset.precision;\n", " // console.log(\"1:\", submission)\n", " submission = Math.round((1 * submission + Number.EPSILON) * 10 ** precision) / 10 ** precision;\n", " // console.log(\"Rounded to \", submission, \" precision=\", precision );\n", " }\n", "\n", "\n", " //console.log(\"In check_numeric(), id=\"+id);\n", " //console.log(event.srcElement.id) \n", " //console.log(event.srcElement.dataset.feedback)\n", "\n", " var fb = document.getElementById(\"fb\" + id);\n", " fb.style.display = \"none\";\n", " fb.textContent = \"Incorrect -- try again.\";\n", "\n", " var answers = JSON.parse(ths.dataset.answers);\n", " //console.log(answers);\n", "\n", " var defaultFB = \"\";\n", " var correct;\n", " var done = false;\n", " answers.every(answer => {\n", " //console.log(answer.type);\n", "\n", " correct = false;\n", " // if (answer.type==\"value\"){\n", " if ('value' in answer) {\n", " if (submission == answer.value) {\n", " if (\"feedback\" in answer) {\n", " fb.textContent = jaxify(answer.feedback);\n", " } else {\n", " fb.textContent = jaxify(\"Correct\");\n", " }\n", " correct = answer.correct;\n", " //console.log(answer.correct);\n", " done = true;\n", " }\n", " // } else if (answer.type==\"range\") {\n", " } else if ('range' in answer) {\n", " //console.log(answer.range);\n", " if ((submission >= answer.range[0]) && (submission < answer.range[1])) {\n", " fb.textContent = jaxify(answer.feedback);\n", " correct = answer.correct;\n", " //console.log(answer.correct);\n", " done = true;\n", " }\n", " } else if (answer.type == \"default\") {\n", " defaultFB = answer.feedback;\n", " }\n", " if (done) {\n", " return false; // Break out of loop if this has been marked correct\n", " } else {\n", " return true; // Keep looking for case that includes this as a correct answer\n", " }\n", " });\n", "\n", " if ((!done) && (defaultFB != \"\")) {\n", " fb.innerHTML = jaxify(defaultFB);\n", " //console.log(\"Default feedback\", defaultFB);\n", " }\n", "\n", " fb.style.display = \"block\";\n", " if (correct) {\n", " ths.className = \"Input-text\";\n", " ths.classList.add(\"correctButton\");\n", " fb.className = \"Feedback\";\n", " fb.classList.add(\"correct\");\n", " } else {\n", " ths.className = \"Input-text\";\n", " ths.classList.add(\"incorrectButton\");\n", " fb.className = \"Feedback\";\n", " fb.classList.add(\"incorrect\");\n", " }\n", "\n", " // What follows is for the saved responses stuff\n", " var outerContainer = fb.parentElement.parentElement;\n", " var responsesContainer = document.getElementById(\"responses\" + outerContainer.id);\n", " if (responsesContainer) {\n", " console.log(submission);\n", " var qnum = document.getElementById(\"quizWrap\"+id).dataset.qnum;\n", " //console.log(\"Question \" + qnum);\n", " //console.log(id, \", got numcorrect=\",fb.dataset.numcorrect);\n", " var responses=JSON.parse(responsesContainer.dataset.responses);\n", " console.log(responses);\n", " if (submission == ths.value){\n", " responses[qnum]= submission;\n", " } else {\n", " responses[qnum]= ths.value + \"(\" + submission +\")\";\n", " }\n", " responsesContainer.setAttribute('data-responses', JSON.stringify(responses));\n", " printResponses(responsesContainer);\n", " }\n", " // End code to preserve responses\n", "\n", " if (typeof MathJax != 'undefined') {\n", " var version = MathJax.version;\n", " console.log('MathJax version', version);\n", " if (version[0] == \"2\") {\n", " MathJax.Hub.Queue([\"Typeset\", MathJax.Hub]);\n", " } else if (version[0] == \"3\") {\n", " MathJax.typeset([fb]);\n", " }\n", " } else {\n", " console.log('MathJax not detected');\n", " }\n", " return false;\n", " }\n", "\n", "}\n", "\n", "function isValid(el, charC) {\n", " //console.log(\"Input char: \", charC);\n", " if (charC == 46) {\n", " if (el.value.indexOf('.') === -1) {\n", " return true;\n", " } else if (el.value.indexOf('/') != -1) {\n", " var parts = el.value.split('/');\n", " if (parts[1].indexOf('.') === -1) {\n", " return true;\n", " }\n", " }\n", " else {\n", " return false;\n", " }\n", " } else if (charC == 47) {\n", " if (el.value.indexOf('/') === -1) {\n", " if ((el.value != \"\") && (el.value != \".\")) {\n", " return true;\n", " } else {\n", " return false;\n", " }\n", " } else {\n", " return false;\n", " }\n", " } else if (charC == 45) {\n", " var edex = el.value.indexOf('e');\n", " if (edex == -1) {\n", " edex = el.value.indexOf('E');\n", " }\n", "\n", " if (el.value == \"\") {\n", " return true;\n", " } else if (edex == (el.value.length - 1)) { // If just after e or E\n", " return true;\n", " } else {\n", " return false;\n", " }\n", " } else if (charC == 101) { // \"e\"\n", " if ((el.value.indexOf('e') === -1) && (el.value.indexOf('E') === -1) && (el.value.indexOf('/') == -1)) {\n", " // Prev symbol must be digit or decimal point:\n", " if (el.value.slice(-1).search(/\\d/) >= 0) {\n", " return true;\n", " } else if (el.value.slice(-1).search(/\\./) >= 0) {\n", " return true;\n", " } else {\n", " return false;\n", " }\n", " } else {\n", " return false;\n", " }\n", " } else {\n", " if (charC > 31 && (charC < 48 || charC > 57))\n", " return false;\n", " }\n", " return true;\n", "}\n", "\n", "function numeric_keypress(evnt) {\n", " var charC = (evnt.which) ? evnt.which : evnt.keyCode;\n", "\n", " if (charC == 13) {\n", " check_numeric(this, evnt);\n", " } else {\n", " return isValid(this, charC);\n", " }\n", "}\n", "\n", "\n", "\n", "\n", "\n", "function make_numeric(qa, outerqDiv, qDiv, aDiv, id) {\n", "\n", "\n", "\n", " //console.log(answer);\n", "\n", "\n", " outerqDiv.className = \"NumericQn\";\n", " aDiv.style.display = 'block';\n", "\n", " var lab = document.createElement(\"label\");\n", " lab.className = \"InpLabel\";\n", " lab.textContent = \"Type numeric answer here:\";\n", " aDiv.append(lab);\n", "\n", " var inp = document.createElement(\"input\");\n", " inp.type = \"text\";\n", " //inp.id=\"input-\"+id;\n", " inp.id = id + \"-0\";\n", " inp.className = \"Input-text\";\n", " inp.setAttribute('data-answers', JSON.stringify(qa.answers));\n", " if (\"precision\" in qa) {\n", " inp.setAttribute('data-precision', qa.precision);\n", " }\n", " aDiv.append(inp);\n", " //console.log(inp);\n", "\n", " //inp.addEventListener(\"keypress\", check_numeric);\n", " //inp.addEventListener(\"keypress\", numeric_keypress);\n", " /*\n", " inp.addEventListener(\"keypress\", function(event) {\n", " return numeric_keypress(this, event);\n", " }\n", " );\n", " */\n", " //inp.onkeypress=\"return numeric_keypress(this, event)\";\n", " inp.onkeypress = numeric_keypress;\n", " inp.onpaste = event => false;\n", "\n", " inp.addEventListener(\"focus\", function (event) {\n", " this.value = \"\";\n", " return false;\n", " }\n", " );\n", "\n", "\n", "}\n", "function jaxify(string) {\n", " var mystring = string;\n", "\n", " var count = 0;\n", " var loc = mystring.search(/([^\\\\]|^)(\\$)/);\n", "\n", " var count2 = 0;\n", " var loc2 = mystring.search(/([^\\\\]|^)(\\$\\$)/);\n", "\n", " //console.log(loc);\n", "\n", " while ((loc >= 0) || (loc2 >= 0)) {\n", "\n", " /* Have to replace all the double $$ first with current implementation */\n", " if (loc2 >= 0) {\n", " if (count2 % 2 == 0) {\n", " mystring = mystring.replace(/([^\\\\]|^)(\\$\\$)/, \"$1\\\\[\");\n", " } else {\n", " mystring = mystring.replace(/([^\\\\]|^)(\\$\\$)/, \"$1\\\\]\");\n", " }\n", " count2++;\n", " } else {\n", " if (count % 2 == 0) {\n", " mystring = mystring.replace(/([^\\\\]|^)(\\$)/, \"$1\\\\(\");\n", " } else {\n", " mystring = mystring.replace(/([^\\\\]|^)(\\$)/, \"$1\\\\)\");\n", " }\n", " count++;\n", " }\n", " loc = mystring.search(/([^\\\\]|^)(\\$)/);\n", " loc2 = mystring.search(/([^\\\\]|^)(\\$\\$)/);\n", " //console.log(mystring,\", loc:\",loc,\", loc2:\",loc2);\n", " }\n", "\n", " //console.log(mystring);\n", " return mystring;\n", "}\n", "\n", "\n", "function show_questions(json, mydiv) {\n", " console.log('show_questions');\n", " //var mydiv=document.getElementById(myid);\n", " var shuffle_questions = mydiv.dataset.shufflequestions;\n", " var num_questions = mydiv.dataset.numquestions;\n", " var shuffle_answers = mydiv.dataset.shuffleanswers;\n", " var max_width = mydiv.dataset.maxwidth;\n", "\n", " if (num_questions > json.length) {\n", " num_questions = json.length;\n", " }\n", "\n", " var questions;\n", " if ((num_questions < json.length) || (shuffle_questions == \"True\")) {\n", " //console.log(num_questions+\",\"+json.length);\n", " questions = getRandomSubarray(json, num_questions);\n", " } else {\n", " questions = json;\n", " }\n", "\n", " //console.log(\"SQ: \"+shuffle_questions+\", NQ: \" + num_questions + \", SA: \", shuffle_answers);\n", "\n", " // Iterate over questions\n", " questions.forEach((qa, index, array) => {\n", " //console.log(qa.question); \n", "\n", " var id = makeid(8);\n", " //console.log(id);\n", "\n", "\n", " // Create Div to contain question and answers\n", " var iDiv = document.createElement('div');\n", " //iDiv.id = 'quizWrap' + id + index;\n", " iDiv.id = 'quizWrap' + id;\n", " iDiv.className = 'Quiz';\n", " iDiv.setAttribute('data-qnum', index);\n", " iDiv.style.maxWidth =max_width+\"px\";\n", " mydiv.appendChild(iDiv);\n", " // iDiv.innerHTML=qa.question;\n", " \n", " var outerqDiv = document.createElement('div');\n", " outerqDiv.id = \"OuterquizQn\" + id + index;\n", " // Create div to contain question part\n", " var qDiv = document.createElement('div');\n", " qDiv.id = \"quizQn\" + id + index;\n", " \n", " if (qa.question) {\n", " iDiv.append(outerqDiv);\n", "\n", " //qDiv.textContent=qa.question;\n", " qDiv.innerHTML = jaxify(qa.question);\n", " outerqDiv.append(qDiv);\n", " }\n", "\n", " // Create div for code inside question\n", " var codeDiv;\n", " if (\"code\" in qa) {\n", " codeDiv = document.createElement('div');\n", " codeDiv.id = \"code\" + id + index;\n", " codeDiv.className = \"QuizCode\";\n", " var codePre = document.createElement('pre');\n", " codeDiv.append(codePre);\n", " var codeCode = document.createElement('code');\n", " codePre.append(codeCode);\n", " codeCode.innerHTML = qa.code;\n", " outerqDiv.append(codeDiv);\n", " //console.log(codeDiv);\n", " }\n", "\n", "\n", " // Create div to contain answer part\n", " var aDiv = document.createElement('div');\n", " aDiv.id = \"quizAns\" + id + index;\n", " aDiv.className = 'Answer';\n", " iDiv.append(aDiv);\n", "\n", " //console.log(qa.type);\n", "\n", " var num_correct;\n", " if ((qa.type == \"multiple_choice\") || (qa.type == \"many_choice\") ) {\n", " num_correct = make_mc(qa, shuffle_answers, outerqDiv, qDiv, aDiv, id);\n", " if (\"answer_cols\" in qa) {\n", " //aDiv.style.gridTemplateColumns = 'auto '.repeat(qa.answer_cols);\n", " aDiv.style.gridTemplateColumns = 'repeat(' + qa.answer_cols + ', 1fr)';\n", " }\n", " } else if (qa.type == \"numeric\") {\n", " //console.log(\"numeric\");\n", " make_numeric(qa, outerqDiv, qDiv, aDiv, id);\n", " }\n", "\n", "\n", " //Make div for feedback\n", " var fb = document.createElement(\"div\");\n", " fb.id = \"fb\" + id;\n", " //fb.style=\"font-size: 20px;text-align:center;\";\n", " fb.className = \"Feedback\";\n", " fb.setAttribute(\"data-answeredcorrect\", 0);\n", " fb.setAttribute(\"data-numcorrect\", num_correct);\n", " iDiv.append(fb);\n", "\n", "\n", " });\n", " var preserveResponses = mydiv.dataset.preserveresponses;\n", " console.log(preserveResponses);\n", " console.log(preserveResponses == \"true\");\n", " if (preserveResponses == \"true\") {\n", " console.log(preserveResponses);\n", " // Create Div to contain record of answers\n", " var iDiv = document.createElement('div');\n", " iDiv.id = 'responses' + mydiv.id;\n", " iDiv.className = 'JCResponses';\n", " // Create a place to store responses as an empty array\n", " iDiv.setAttribute('data-responses', '[]');\n", "\n", " // Dummy Text\n", " iDiv.innerHTML=\"Select your answers and then follow the directions that will appear here.\"\n", " //iDiv.className = 'Quiz';\n", " mydiv.appendChild(iDiv);\n", " }\n", "//console.log(\"At end of show_questions\");\n", " if (typeof MathJax != 'undefined') {\n", " console.log(\"MathJax version\", MathJax.version);\n", " var version = MathJax.version;\n", " setTimeout(function(){\n", " var version = MathJax.version;\n", " console.log('After sleep, MathJax version', version);\n", " if (version[0] == \"2\") {\n", " MathJax.Hub.Queue([\"Typeset\", MathJax.Hub]);\n", " } else if (version[0] == \"3\") {\n", " MathJax.typeset([mydiv]);\n", " }\n", " }, 500);\n", "if (typeof version == 'undefined') {\n", " } else\n", " {\n", " if (version[0] == \"2\") {\n", " MathJax.Hub.Queue([\"Typeset\", MathJax.Hub]);\n", " } else if (version[0] == \"3\") {\n", " MathJax.typeset([mydiv]);\n", " } else {\n", " console.log(\"MathJax not found\");\n", " }\n", " }\n", " }\n", " return false;\n", "}\n", "/* This is to handle asynchrony issues in loading Jupyter notebooks\n", " where the quiz has been previously run. The Javascript was generally\n", " being run before the div was added to the DOM. I tried to do this\n", " more elegantly using Mutation Observer, but I didn't get it to work.\n", "\n", " Someone more knowledgeable could make this better ;-) */\n", "\n", " function try_show() {\n", " if(document.getElementById(\"VBwdbPbLuQFv\")) {\n", " show_questions(questionsVBwdbPbLuQFv, VBwdbPbLuQFv); \n", " } else {\n", " setTimeout(try_show, 200);\n", " }\n", " };\n", " \n", " {\n", " // console.log(element);\n", "\n", " //console.log(\"VBwdbPbLuQFv\");\n", " // console.log(document.getElementById(\"VBwdbPbLuQFv\"));\n", "\n", " try_show();\n", " }\n", " " ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "from jupyterquiz import display_quiz\n", "display_quiz(\"quizes/scikitlearn_course_skip_quiz.json\")" ] }, { "cell_type": "code", "execution_count": null, "id": "ab2caefa-072a-401e-b264-0b2c3d521fcf", "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.9.19" } }, "nbformat": 4, "nbformat_minor": 5 }