{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "# Preview\n\n- Use these questions before class to check your familiarity with the chapter glossary and core terms.\n- Sign in from the account menu before you start answering the questions.\n- Multiple submissions are allowed. The highest score is kept.\n",
   "id": "ch09-preview-intro"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "<style>\n.ch09-preview-quiz { max-width: 900px; }\n.ch09-preview-question { border: 1px solid #d8dee4; border-radius: 6px; padding: 1rem; margin: 1rem 0; background: #fff; }\n.ch09-preview-question p { margin-top: 0; font-weight: 600; }\n.ch09-preview-question label { display: block; margin: 0.35rem 0; cursor: pointer; }\n.ch09-preview-question input { margin-right: 0.4rem; }\n.ch09-preview-actions { display: flex; gap: 0.75rem; align-items: center; margin: 1rem 0; flex-wrap: wrap; }\n.ch09-preview-actions button { border: 1px solid #176de8; border-radius: 6px; background: #176de8; color: white; padding: 0.55rem 0.9rem; cursor: pointer; font-weight: 600; }\n.ch09-preview-actions button.secondary { background: white; color: #176de8; }\n.ch09-preview-actions.is-locked { opacity: 0.55; }\n.ch09-preview-actions button:disabled { cursor: not-allowed; opacity: 0.65; }\n.ch09-preview-result { font-weight: 600; }\n.ch09-preview-feedback { margin-top: 0.65rem; font-weight: 600; }\n.ch09-preview-feedback.correct { color: #1a7f37; }\n.ch09-preview-feedback.incorrect { color: #cf222e; }\n</style>\n\n<div class='ch09-preview-quiz' id='ch09-preview-quiz'>\n  <div id='ch09-preview-questions'></div>\n  <div class='ch09-preview-actions'>\n    <button type='button' id='ch09-preview-submit' disabled>Submit</button>\n    <button type='button' class='secondary' id='ch09-preview-reset'>Reset</button>\n    <button type='button' class='secondary' id='ch09-preview-review'>Review released explanations</button>\n    <span class='ch09-preview-result' id='ch09-preview-result' aria-live='polite'></span>\n  </div>\n  <div id='ch09-preview-review-panel' aria-live='polite' hidden></div>\n</div>\n\n<script>\n(function () {\n  var quizId = 'ch09-preview';\n  var questionVersion = 'ch09-2026-10-27';\n  var questions = [\n    {\n        \"id\": \"q1\",\n        \"prompt\": \"Which programming style groups an object's state with the operations that use it?\",\n        \"choices\": {\n            \"A\": \"Functional programming\",\n            \"B\": \"Object-oriented programming\",\n            \"C\": \"Procedural programming\",\n            \"D\": \"Declarative programming\"\n        },\n        \"answer\": \"B\",\n        \"level\": \"recognition\",\n        \"hint\": \"Compare how the programming styles organize state and operations.\",\n        \"explanation\": \"Object-oriented programming groups related state and behavior in objects.\",\n        \"reading\": \"../0900-oop.html\"\n    },\n    {\n        \"id\": \"q2\",\n        \"prompt\": \"What defines the common structure and behavior used to create a family of objects?\",\n        \"choices\": {\n            \"A\": \"Class\",\n            \"B\": \"Instance\",\n            \"C\": \"Attribute\",\n            \"D\": \"Bound method\"\n        },\n        \"answer\": \"A\",\n        \"level\": \"recognition\",\n        \"hint\": \"Distinguish the definition from one object created using it.\",\n        \"explanation\": \"A class defines the structure and behavior; an instance is one object created from it.\",\n        \"reading\": \"../0900-oop.html\"\n    },\n    {\n        \"id\": \"q3\",\n        \"prompt\": \"Which feature lets callers read acct.balance like an attribute while the class controls access and provides no setter?\",\n        \"choices\": {\n            \"A\": \"Class variable\",\n            \"B\": \"@property\",\n            \"C\": \"@staticmethod\",\n            \"D\": \"Name mangling\"\n        },\n        \"answer\": \"B\",\n        \"level\": \"recognition\",\n        \"hint\": \"Look for the decorator that turns a method into attribute-style read access.\",\n        \"explanation\": \"@property makes a method readable with attribute syntax; without a setter, assigning to acct.balance raises AttributeError.\",\n        \"reading\": \"../0900-oop.html\"\n    },\n    {\n        \"id\": \"q4\",\n        \"prompt\": \"Inside a child class's __init__, which call reuses the parent class's initializer?\",\n        \"choices\": {\n            \"A\": \"self.__init__(...)\",\n            \"B\": \"super().__init__(...)\",\n            \"C\": \"Parent.__str__(...)\",\n            \"D\": \"cls(...)\"\n        },\n        \"answer\": \"B\",\n        \"level\": \"recognition\",\n        \"hint\": \"Review the glossary entry for calling behavior from a parent class.\",\n        \"explanation\": \"super().__init__(...) runs the parent's initializer so the child can then add its own attributes.\",\n        \"reading\": \"../0900-oop.html\"\n    },\n    {\n        \"id\": \"q5\",\n        \"prompt\": \"Which decorator makes a method receive the class itself as cls, as in an alternative constructor such as from_string?\",\n        \"choices\": {\n            \"A\": \"@classmethod\",\n            \"B\": \"@staticmethod\",\n            \"C\": \"@property\",\n            \"D\": \"@dataclass\"\n        },\n        \"answer\": \"A\",\n        \"level\": \"recognition\",\n        \"hint\": \"Compare which method types receive self, cls, or no implicit argument.\",\n        \"explanation\": \"A class method receives the calling class as cls, so cls(...) can build an instance of that class or a subclass.\",\n        \"reading\": \"../0900-oop.html\"\n    },\n    {\n        \"id\": \"q6\",\n        \"prompt\": \"Which conventional parameter name denotes the current object in an instance method?\",\n        \"choices\": {\n            \"A\": \"cls\",\n            \"B\": \"self\",\n            \"C\": \"super\",\n            \"D\": \"other\"\n        },\n        \"answer\": \"B\",\n        \"level\": \"recognition\",\n        \"hint\": \"Compare instance-method and class-method receivers.\",\n        \"explanation\": \"self conventionally names the current instance; cls conventionally names the class in a classmethod.\",\n        \"reading\": \"../0900-oop.html\"\n    },\n    {\n        \"id\": \"q7\",\n        \"prompt\": \"Which special method sets the initial state of a newly created instance?\",\n        \"choices\": {\n            \"A\": \"__str__\",\n            \"B\": \"__lt__\",\n            \"C\": \"__init__\",\n            \"D\": \"__eq__\"\n        },\n        \"answer\": \"C\",\n        \"level\": \"recognition\",\n        \"hint\": \"Distinguish initialization from representation and comparison.\",\n        \"explanation\": \"__init__ sets initial state on the new instance and returns None.\",\n        \"reading\": \"../0900-oop.html\"\n    },\n    {\n        \"id\": \"q8\",\n        \"prompt\": \"A service offers deposit and withdrawal operations while keeping balance storage behind that interface. Which principle does this illustrate?\",\n        \"choices\": {\n            \"A\": \"Inheritance\",\n            \"B\": \"Polymorphism\",\n            \"C\": \"Encapsulation\",\n            \"D\": \"Method overriding\"\n        },\n        \"answer\": \"C\",\n        \"level\": \"connection\",\n        \"hint\": \"Consider the relationship between an object's state and its public interface.\",\n        \"explanation\": \"Encapsulation keeps state and operations together behind an interface that controls how callers use them.\",\n        \"reading\": \"../0900-oop.html\"\n    },\n    {\n        \"id\": \"q9\",\n        \"prompt\": \"Different report classes can support the same render operation. Calling that shared operation on each report is polymorphism.\",\n        \"choices\": {\n            \"TRUE\": \"True\",\n            \"FALSE\": \"False\"\n        },\n        \"answer\": \"TRUE\",\n        \"level\": \"connection\",\n        \"hint\": \"Compare a shared interface with a shared parent class.\",\n        \"explanation\": \"True. Polymorphism uses the same interface with different object types; it does not require inheritance.\",\n        \"reading\": \"../0900-oop.html\"\n    },\n    {\n        \"id\": \"q10\",\n        \"prompt\": \"A dataclass is a tuple-compatible record that automatically supports positional indexing.\",\n        \"choices\": {\n            \"TRUE\": \"True\",\n            \"FALSE\": \"False\"\n        },\n        \"answer\": \"FALSE\",\n        \"level\": \"connection\",\n        \"hint\": \"Compare the glossary entries for dataclass and namedtuple.\",\n        \"explanation\": \"False. A dataclass generates methods for an ordinary class. namedtuple supplies tuple-compatible positional access.\",\n        \"reading\": \"../0900-oop.html\"\n    }\n];\n\n  function text(value) {\n    return document.createTextNode(value);\n  }\n\n  function getParams() {\n    var params = new URLSearchParams(window.location.search);\n    return {\n      canvas_course_id: params.get('canvas_course_id') || params.get('course_id') || '',\n      canvas_assignment_id: params.get('canvas_assignment_id') || params.get('assignment_id') || '',\n      canvas_user_id: params.get('canvas_user_id') || params.get('user_id') || ''\n    };\n  }\n\n  function loadSessionIdentity(identity, actions, submit, result) {\n    submit.disabled = true;\n    actions.classList.add('is-locked');\n    result.textContent = 'Sign in from the account menu to submit this assignment.';\n    return fetch('/api/v1/session.php', { credentials: 'same-origin' })\n      .then(function (response) { return response.ok ? response.json() : null; })\n      .then(function (payload) {\n        if (!payload || !payload.authenticated || !payload.identity) return identity;\n        identity.canvas_user_id = payload.identity.canvas_user_id || identity.canvas_user_id || '';\n        identity.student_identifier = payload.identity.student_identifier || '';\n        submit.disabled = false;\n        actions.classList.remove('is-locked');\n        result.textContent = payload.identity.display_name ? 'Signed in as ' + payload.identity.display_name + '.' : 'Signed in.';\n        return identity;\n      })\n      .catch(function () { return identity; });\n  }\n\n  var choiceOrderKey = quizId + ':choice-order:' + questionVersion;\n  var choiceOrder = {};\n\n  function isTrueFalse(question) {\n    return Object.prototype.hasOwnProperty.call(question.choices, 'TRUE');\n  }\n\n  function shuffled(items) {\n    var copy = items.slice();\n    for (var i = copy.length - 1; i > 0; i -= 1) {\n      var j = Math.floor(Math.random() * (i + 1));\n      var swap = copy[i];\n      copy[i] = copy[j];\n      copy[j] = swap;\n    }\n    return copy;\n  }\n\n  // Shuffle multiple-choice options once per attempt and keep that order across reloads.\n  // Radio values stay the canonical letters, so grading is unchanged.\n  function loadChoiceOrder() {\n    var stored = null;\n    try {\n      stored = JSON.parse(localStorage.getItem(choiceOrderKey) || 'null');\n    } catch (error) {\n      stored = null;\n    }\n    var valid = stored && questions.every(function (question) {\n      var order = stored[question.id];\n      return Array.isArray(order) && order.slice().sort().join() === Object.keys(question.choices).sort().join();\n    });\n    if (valid) return stored;\n    var order = {};\n    questions.forEach(function (question) {\n      var letters = Object.keys(question.choices);\n      order[question.id] = isTrueFalse(question) ? letters : shuffled(letters);\n    });\n    try {\n      localStorage.setItem(choiceOrderKey, JSON.stringify(order));\n    } catch (error) {\n      // Without storage, the order lasts for this page view only.\n    }\n    return order;\n  }\n\n  function startNewChoiceOrder() {\n    try {\n      localStorage.removeItem(choiceOrderKey);\n    } catch (error) {\n      // Nothing stored to clear.\n    }\n  }\n\n  function renderQuestions(container) {\n    choiceOrder = loadChoiceOrder();\n    questions.forEach(function (question, index) {\n      var card = document.createElement('div');\n      card.className = 'ch09-preview-question';\n      card.dataset.question = question.id;\n\n      var prompt = document.createElement('p');\n      prompt.appendChild(text((index + 1) + '. ' + question.prompt));\n      card.appendChild(prompt);\n\n      choiceOrder[question.id].forEach(function (letter, position) {\n        var label = document.createElement('label');\n        var input = document.createElement('input');\n        input.type = 'radio';\n        input.name = question.id;\n        input.value = letter;\n        label.appendChild(input);\n        label.appendChild(text(isTrueFalse(question) ? question.choices[letter] : 'ABCDEFGH'.charAt(position) + '. ' + question.choices[letter]));\n        card.appendChild(label);\n      });\n\n      var feedback = document.createElement('div');\n      feedback.className = 'ch09-preview-feedback';\n      feedback.setAttribute('aria-live', 'polite');\n      card.appendChild(feedback);\n      container.appendChild(card);\n    });\n  }\n\n  function collectAnswers(quiz) {\n    var answers = {};\n    questions.forEach(function (question) {\n      var selected = quiz.querySelector('input[name=' + question.id + ']:checked');\n      answers[question.id] = selected ? selected.value : '';\n    });\n    answers.__question_set = questionVersion;\n    answers.preview_questions = questions;\n    answers.choice_order = choiceOrder;\n    return answers;\n  }\n\n  function gradeAnswers(answers) {\n    var feedback = {};\n    var score = 0;\n    questions.forEach(function (question) {\n      var submitted = answers[question.id] || '';\n      var correct = submitted === question.answer;\n      if (correct) score += 1;\n      feedback[question.id] = {\n        submitted: submitted !== '',\n        correct: correct,\n        message: submitted === '' ? 'No answer submitted.' : (correct ? 'Correct.' : 'Try again.')\n      };\n    });\n    return { ok: true, score: score, max_score: questions.length, feedback: feedback, canvas_sync_status: 'not configured' };\n  }\n\n  function applyFeedback(quiz, feedback) {\n    questions.forEach(function (question) {\n      var card = quiz.querySelector('[data-question=' + question.id + ']');\n      var message = card.querySelector('.ch09-preview-feedback');\n      var item = feedback[question.id];\n      message.className = 'ch09-preview-feedback';\n      if (!item || !item.submitted) {\n        message.textContent = item && item.message ? item.message : 'No answer submitted.';\n        message.classList.add('incorrect');\n      } else if (item.correct) {\n        message.textContent = item.message || 'Correct.';\n        message.classList.add('correct');\n      } else {\n        message.textContent = item.message || 'Try again.';\n        message.classList.add('incorrect');\n      }\n      if (item && !item.correct) {\n        message.appendChild(text(' Hint: ' + question.hint + ' '));\n        var reading = document.createElement('a');\n        reading.href = question.reading;\n        reading.appendChild(text('Review the assigned glossary.'));\n        message.appendChild(reading);\n      }\n    });\n  }\n\n  function saveBestScore(payload) {\n    try {\n      var key = quizId + ':best-score';\n      var best = Number(localStorage.getItem(key) || '0');\n      if (payload.score > best) localStorage.setItem(key, String(payload.score));\n      return Math.max(best, payload.score);\n    } catch (error) {\n      return payload.score;\n    }\n  }\n\n  function submitAttempt(identity, answers) {\n    return fetch('/api/v1/quiz-attempts.php', {\n      method: 'POST',\n      headers: { 'Content-Type': 'application/json' },\n      credentials: 'same-origin',\n      body: JSON.stringify({\n        quiz_id: quizId,\n        answers: answers,\n        canvas_course_id: identity.canvas_course_id,\n        canvas_assignment_id: identity.canvas_assignment_id,\n        canvas_user_id: identity.canvas_user_id\n      })\n    })\n      .then(function (response) {\n        return response.text().then(function (body) {\n          var payload = null;\n          try {\n            payload = body ? JSON.parse(body) : null;\n          } catch (error) {\n            throw new Error('Server returned a non-JSON response.');\n          }\n          if (!payload || !response.ok || !payload.ok) {\n            throw new Error(payload && (payload.message || payload.error) ? (payload.message || payload.error) : 'Submission API is unavailable.');\n          }\n          return payload;\n        });\n      });\n  }\n\n  function initPreviewQuiz() {\n    var quiz = document.getElementById('ch09-preview-quiz');\n    if (!quiz || quiz.dataset.ready === 'true') return;\n    quiz.dataset.ready = 'true';\n\n    var identity = getParams();\n    var questionsContainer = document.getElementById('ch09-preview-questions');\n    var result = document.getElementById('ch09-preview-result');\n    var submit = document.getElementById('ch09-preview-submit');\n    var actions = quiz.querySelector('.ch09-preview-actions');\n    var reset = document.getElementById('ch09-preview-reset');\n\n    document.getElementById('ch09-preview-review').addEventListener('click', function () {\n      var panel = document.getElementById('ch09-preview-review-panel');\n      panel.hidden = false;\n      panel.textContent = 'Checking explanation availability.';\n      fetch('/api/v1/assignment-settings.php?assignment_id=' + encodeURIComponent(quizId), {\n        credentials: 'same-origin', cache: 'no-store'\n      }).then(function (response) {\n        if (!response.ok) throw new Error('Could not check explanation availability.');\n        return response.json();\n      }).then(function (settings) {\n        if (!settings.ok || !settings.answers_unlocked) {\n          panel.textContent = 'Explanations are available after your instructor releases Preview answers.';\n          return;\n        }\n        panel.textContent = '';\n        questions.forEach(function (question, index) {\n          var row = document.createElement('p');\n          row.appendChild(text((index + 1) + '. ' + question.prompt + ' Answer: ' +\n            question.choices[question.answer] + '. ' + question.explanation));\n          panel.appendChild(row);\n        });\n      }).catch(function (error) { panel.textContent = error.message; });\n    });\n\n    renderQuestions(questionsContainer);\n    loadSessionIdentity(identity, actions, submit, result);\n\n    submit.addEventListener('click', function () {\n      var answers = collectAnswers(quiz);\n      var localPayload = gradeAnswers(answers);\n      submit.disabled = true;\n      result.textContent = 'Submitting...';\n\n      submitAttempt(identity, answers)\n        .then(function (payload) {\n          saveBestScore(payload);\n          startNewChoiceOrder();\n          var best = (payload.best_score === null || typeof payload.best_score === 'undefined') ? payload.score : payload.best_score;\n          var attempt = (payload.attempt_count === null || typeof payload.attempt_count === 'undefined') ? '' : ' Attempt ' + payload.attempt_count + '.';\n          applyFeedback(quiz, payload.feedback || localPayload.feedback || {});\n          result.textContent = 'Submission saved.' + attempt + ' Score: ' + payload.score + ' / ' + payload.max_score + '. Best score: ' + best + ' / ' + payload.max_score + '. Canvas sync: ' + (payload.canvas_sync_status || 'not configured') + '.';\n        })\n        .catch(function (error) {\n          applyFeedback(quiz, localPayload.feedback || {});\n          result.textContent = 'Could not save this attempt: ' + error.message;\n        })\n        .finally(function () {\n          submit.disabled = false;\n        });\n    });\n\n    reset.addEventListener('click', function () {\n      quiz.querySelectorAll('input[type=radio]').forEach(function (input) {\n        input.checked = false;\n      });\n      quiz.querySelectorAll('.ch09-preview-feedback').forEach(function (feedback) {\n        feedback.className = 'ch09-preview-feedback';\n        feedback.textContent = '';\n      });\n      result.textContent = '';\n    });\n  }\n\n  if (document.readyState === 'loading') {\n    document.addEventListener('DOMContentLoaded', initPreviewQuiz);\n  } else {\n    initPreviewQuiz();\n  }\n})();\n</script>\n",
   "id": "ch09-preview-quiz"
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python",
   "version": "3.11.0"
  },
  "press_solutions_stripped": true
 },
 "nbformat": 4,
 "nbformat_minor": 5
}