Thursday, August 11, 2022

A browser-based runner for Faded Parsons Problems

A Parsons Problem is a kind of programming exercise where learners rearrange blocks of code in order to create functional programs, and has been shown by CS Ed researchers to be an effective way to learn code writing skills. One particularly helpful aspect is that students are re-creating an expert solution, versus writing sub-optimal or messy solutions, so they pick up better programming practices along the way. [See Barbara Ericson's dissertation for more details.]

However, one issue with Parsons Problems is that some learners may brute force the solution, trying all possible orders without thinking. Fortunately, UC Berkeley Ph.D. student Nate Weinman invented Faded Parsons Problems, a variant where the blocks sometimes have blanks in them, and learners must fill in the blanks after arranging the blocks. Learners are no longer able to brute force, but they still receive the other benefits of Parsons Problems. [See Weinman's CHI 2021 research paper for more details.]

While I was teaching CS61A at UC Berkeley, we experimented with integrating Faded Parsons Problems into our Python class assignments. To complete the problems, students ran a local Flask server on their own machine that sent data to our OKPy grading infrastructure. It seems to have been a positive addition to the course, though we discovered it was difficult for many students to run a local Flask server on their personal laptop. [A research paper is in the works with more details on what we learned.]

I wanted to try using Faded Parsons Problems in my upcoming Python course and to make it generally easier for any teacher to use them, so I've made a website that can run Faded Parsons Problems entirely in the browser (no backend). The website uses Pyodide to run the Python code and localStorage to remember learner progress.

The website checks the correctness of the learner's solution using Python doctests and displays pass/fail results. It also shows syntax errors, which can happen if they indent the blocks incorrectly or write something syntactically incorrect in the blanks.

The website is deployed on my Github pages currently, but it can be deployed on any static website hosting platform. If you're a Python teacher and would like to make up your own problems, you can learn more from the Github project README. Let me know if you end up using this in a class; I'd love to see your problems and hear how it goes.

If you teach a different language besides Python, it may be possible for you to get it working if there's a way to run that language in the browser. Forks or pull requests are welcome.

Tuesday, August 9, 2022

My bed-sharing setup

When I had my first baby, we struggled a lot with finding a sleep strategy that worked for both me and the baby. I talked about that journey in a blog post a few years ago, and how I ended up deciding to share a bed with my baby. I've now had another baby, and we're using the same bed-sharing approach again. Thanks to making the decision early on, I'm much better rested this time around.

Just like people share their office setups filled with geek gear, I'm going to share my bed-sharing setup. Maybe it'll help other breastfeeding mothers out there, or perhaps inspire someone to invent better gear!

Here's the sleeping setup:

Photo of floor mattress with sheets and pillows

Let's break down the sleeping components:

  • Floor mattress: 6" full-sized firm memory foam mattress. I bought the same one for baby #2, since baby #1 is still using it as a three year old. I figure these will be their mattresses for life, or at least their life in my house.
  • Slats: With my first baby, we had the mattress directly on the hardwood floor, and that led to black mold. I found some Korean-made slats on Etsy that fit the mattress size well enough and bought slats for both our mattresses. They're super low down so they don't make the mattress significantly higher (i.e. more dangerous in case of rolling), but hopefully they'll help prevent mold. Sadly, their Etsy shop is closed now, so you'd have to find similar ones or construct them yourself.
  • Bedsheets: You have to be super careful with bedsheets/blankets around babies, since they don't have the dexterity to move them away from their face. I wrap the sheet just around me, and often only use the blanket on the bottom half of my body. (Making milk keeps me pretty warm at night anyway, I often awake at 2AM in a sweat!)
  • Kindle: My favorite thing, both to help me fall asleep and to entertain me while nursing. I lean it against a pillow so that I don't have to hold it and can just flick it with whatever finger/limb is available.
  • Burp cloths: For late night spit ups. Yay.
  • Noise machine: The little elephant makes a heartbeat-like white noise. I'm not sure if it helps her, but it does help my partner to get less distracted by her little grunts and cries at night. We also have a humidifier in the room, as that's often recommended by doctors.
  • Alarm clock: I haven't set an alarm on it for years, but I do use it to make sure we haven't slept too long, since babies are supposed to nurse every 4 hours. Whenever I wake up, either due to my internal clock or her restlessness, I check the clock and decide if it's time to nurse.

So now let's talk about the nursing setup:

Photo of floor mattress with sheets and pillows in nursing position
  • Back support pillow: I lean against the wall while nursing, so this pillow makes that position more comfortable for me.
  • Boppy pillow: This is my favorite nursing pillow, and is the same model I use during the day.
  • Adjustable height pillow: I bought this to try as a nursing pillow (its intended use), but the form factor didn't work out that well for me. However, it's the perfect height/firmness to put under my knee when nursing, to elevate whichever side of the body my baby's nursing on.
  • Cooler: This stores an icepak and a Haakaa, a manual pump that works via suction only. I use the Haakaa to get extra milk out of whatever side my baby isn't nursing on, especially if she isn't eating much that night, and then I transfer the milk to a freezer bag in the morning. The Haakaa is an amazing invention, I still can't believe it works!
  • Nightlight: It helps to have a little light when positioning the baby. I also use my Kindle for additional illumination as needed.

That's my setup! I'd love to see more mothers sharing their gear. Let's nerd out on nursing! :D

Monday, August 8, 2022

Porting a project from spaces to tabs

I'm currently working on a JavaScript codebase that has some old crusty code, and I'm modernizing it in various ways, like upgrading to ES6 syntax and linting with ESLint. I also like to add in Prettier to every codebase, as an automated step, so that my code is always consistently formatted, and so that future pull requests from other developers can easily follow the same conventions.

But I had a dilemma: half my code was written with 2 space indents, the other half was written with 4 space indents, and I needed to tell Prettier what to use. What's a girl to do?? Well, I considered averaging it for nice 3-space indents everywhere (I kid, I kid), but I instead made a radical decision: just use tabs! I'd heard that Prettier is considering making tabs the default anyway, and after reading the many comments on their PR thread, I became convinced that tabs are better than spaces, at least for an autoformatted project.

Since my projects and editors have used spaces forever, there were a few things I needed to do in order to smoothly move over to tabs. Here's the steps I took:

  • Reformat files to use tabs. To change all my current files to tabs, I used Prettier. First I configured it by specifying "useTabs" in my .prettierrc.json:

    {
    	"useTabs": true
    }
    

    Then I ran the prettier command on all my JS/JSON files:

    prettier \"**/*.{js,json}\" --ignore-path ./.eslintignore --write
          
  • Ignore the reformat commit in git blame. I really hate when reformatting commits make it harder to use git blame to track logical changes, so I was thrilled to discover that there's a way for Git/Github to ignore particular revisions while blaming. I followed this blog post, adding a .git-blame-ignore-revs with my most recent commit:

    # Reformat js/json with Prettier, spaces to tabs
    a08f09aa7c4e9381ae2036754bd9311e78c3b40f
    

    Then I ran a command to tell my local git to ignore the revision:
    git config blame.ignoreRevsFile .git-blame-ignore-revs

    Once I pushed the commit with that file, I saw that Github does indeed ignore changes from that commit when I use the blame feature. So cool! Screenshot from Github blame UI

  • Make Github render tabs using 4 spaces.For whatever reason, Github defaults to 8 spaces for tabs, and that is too dang much. To make Github render the tabs in my projects with just 4 spaces, I added an .editorconfig file to my project:

    root = true
    
    [*]
    indent_style = tab
    indent_size = 4
    

    Github also allows users to customize tabs across all project repositories, and that user setting takes precedence over the per-project .editorconfig setting. That's likely for accessibility reasons, since some folks might require a large number of spaces for better readability. To change my account preference, I opened up Settings > Appearance and selected my desired number of spaces:

    Screenshot of Github settings

    So, if I visit my project in an incognito window, Github will render the tabs with 4 spaces, but if I visit the project from my logged in browser, Github will render the tab with 2 spaces.

  • Make VS Code insert tabs when I tab. VS Code tries to adjust its indentation style with autodetection based on the current file, but I wanted to make sure it always inserted a tab in new files in my project, too. It defaults to inserting spaces when it isn't sure, so I needed to explicitly override that setting. I could have changed the setting across all projects, but most of my other projects use spaces, so I instead figured out how to change it in just this project for now.

    To change it, I opened up Settings > Workspace, searched for "insert spaces", and un-checked the "Editor: Insert spaces" setting. That created a .vscode/settings.json file with an "editor.insertSpaces" property:

    {
    	"editor.insertSpaces": false
    }
    

    Another option for VS Code is to use a VS Code plugin that understands .editorconfig files. If you go that route, you don't need to finagle with the VS Code settings yourself.

Friday, July 22, 2022

Tips for planting milkweeds in the Bay area

Since the recent article about the endangerment of Monarch butterflies, a lot of people are interested in planting milkweeds for Monarch caterpillars. I've been doing that for the last few years in my garden in the east bay in California, so I thought I'd share my personal tips.

Milkweed species: Narrow-Leaf

There are many species of milkweed, but not all of them are native to California, and non-native milkweeds are associated with issues like disease and disrupting natural butterfly cycles. The two most commonly sold native milkweeds in CA are the Narrow-leaf milkweed and the Showy milkweed. I have planted both, and based on my observation of caterpillar behavior, I highly recommend the Narrow-leaf. My caterpillars will only eat the Showy as an absolute last resort, and sometimes not even then. They are ravenous for Narrow-leaf, however.



Where to buy

You can use Calscape.org to find local nurseries that sell narrow-leaf milkweed. Before you go to the nursery in person, check their website or give them a call to see if it's currently in stock. 

You can often get Narrow-leaf from a generic nursery that sells both native and non-native plants, but some of the generic nurseries spray their plants with insecticide or use soil with insecticides - no good! If you instead go to native nurseries, that shouldn't be an issue (but you should double check just in case). My favorite native nurseries are Oaktown Native and Watershed.

You can also grow it from seed fairly easily. My favorite native seed source is Larner Seeds. It will take some time for the plant to grow large, and small plants may get overwhelmed early by caterpillars, but I've found that even the small plants can bounce back after being devoured. 

Planting wildflowers

There are two reasons to plant native wildflowers near the milkweed: 1) munchies for the adult butterflies 2) familiar places for the caterpillars to pupate. We happened to plant a Salvia Clevelandii near our milkweed, and that's where a caterpillar happily pupated. 

Once again, I recommend purchasing native wildflowers either from local native-specializing nurseries or from seed. Use Calscape.org to make sure that a particular plant is actually native to your area.

Moving the caterpillars

I will often find that a caterpillar will have completely decimated milkweed in one part of my garden (since my milkweed are still quite small). In that case, I often move the caterpillar to a more milkweed-y part of the garden. To safely transport, I make sure that they're actively moving (i.e. not in a delicate phase of changing instars), snip off the milkweed segment with scissors, and place that segment near the new milkweed. Sometimes I even bring them to the neighbors' milkweed if we're all out.

Where do they pupate?

This is still my top question as a Monarch-raiser, as I love to watch the metamorphosis but can rarely find a chrysalis. In my garden, the only chrysalis I located was on our Salvia. 

Here's the butterfly that emerged from the chrysalis on the Salvia (and video of their  first flight):

For my neighbor's garden, they love to pupate on the underside of the top of their fence. 

It's important that wherever they pupate, they have enough room for their wings to unfold and dry out. I'm curious to hear where other Monarchs pupate; let me know what you've seen!

Wednesday, July 20, 2022

Line highlighting extension for Code Mirror 6

A little background: Dis This is my online tool for viewing the disassembled bytecode of Python snippets. I started it off with a simple text editor, but I wanted to upgrade it to a nice code editor with line numbers and syntax highlighting.

The most commonly used online code editor libraries are Monaco, CodeMirror, and ACE. I believe Monaco is the most full featured and accessible, but I opted to try CodeMirror for this project as I don’t need as many features. (I avoided ACE since its what we used for the Khan Academy coding environment, and we found it fairly buggy).

CodeMirror recently released a new version, v6, and its quite different architecturally from previous versions.

One of those differences is that the library can only be loaded as a module and cannot be loaded via CDN, so my first task was adding module bundling via rollup.

Once I got rollup running, it was fairly straightforward to get a basic editor working:

import {basicSetup} from 'codemirror';
import {EditorState} from '@codemirror/state';
import {python} from '@codemirror/lang-python';
import {EditorView} from '@codemirror/view';

const editorView = new EditorView({
    state: EditorState.create({
        doc: code,
        extensions: [basicSetup, python()],
    }),
    parent: document.getElementById(“editor”),
});

But now I wanted a new feature: bi-directional line highlighting. Whenever a user highlighted a line in the editor, it should highlight relevant rows in the bytecode table, and vice versa. The end goal:

To try to understand CodeMirror's new approach to extensibility, I did a lot of reading in the docs: Migration Guide, System Guide, Decorations, Zebra Stripes, etc. Here's the code I came up with.

First I make a Decoration of the line variety:

const lineHighlightMark = Decoration.line({
  attributes: {style: 'background-color: yellow'}
});

Then I define a StateEffect:

const addLineHighlight = StateEffect.define();

Tying those together, I define a StateField. When the field receives an addLineHighlight effect, it clears existing decorations and adds the line decoration to the desired line:

const lineHighlightField = StateField.define({
  create() {
    return Decoration.none;
  },
  update(lines, tr) {
    lines = lines.map(tr.changes);
    for (let e of tr.effects) {
      if (e.is(addLineHighlight)) {
        lines = Decoration.none;
        lines = lines.update({add: [lineHighlightMark.range(e.value)]});
      }
    }
    return lines;
  },
  provide: (f) => EditorView.decorations.from(f),
});

To be able to use that effect, I add it to the list of extensions in the original editor constructor:

extensions: [basicSetup, python(), lineHighlightField],

Now I need to setup each direction of line highlighting. To enable highlighting when a user moves their mouse over the code editor, I add an event listener which converts the mouse position to a line number, converts the line number to a “document position”, then dispatches the addLineHighlight effect:

editorView.dom.addEventListener('mousemove', (event) => {
    const lastMove = {
        x: event.clientX,
        y: event.clientY,
        target: event.target,
        time: Date.now(),
    };
    const pos = this.editorView.posAtCoords(lastMove);
    let lineNo = this.editorView.state.doc.lineAt(pos).number;
    const docPosition = this.editorView.state.doc.line(lineNo).from;
    this.editorView.dispatch({effects: addLineHighlight.of(docPosition)});
});

To enable highlighting when the user mouses over rows in the corresponding HTML table, I call a function that converts the line number to a document position and dispatches the effect (same as the last two lines of the previous code).

function highlightLine(lineNo) {
    const docPosition = this.editorView.state.doc.line(lineNo).from;
    this.editorView.dispatch({effects: addLineHighlight.of(docPosition)});
}

For ease of use, I wrap all that code into a HighlightableEditor class:

editor = new HighlightableEditor(codeDiv, code});

Check out the full highlightable-editor.js code on Github.

Wednesday, July 13, 2022

Inactivity timer for Chrome extensions

My Quiz Cards browser extensions are interactive flash cards, giving users a way to practice their Spanish, German, US Capitals, and World Capitals, by simply clicking an icon on their browser.


Screenshot of Quiz Cards popup asking a spanish word

One of the Quiz Cards features is updating the browser icon with a little number to indicate how many days have passed since the last time you answered a card. 

When I upgraded the extension to manifest v3, I found I also needed to update that feature.

How it worked in manifest v2: whenever a user answered a question, the extension stored a timestamp in localStorage. The background script used setInterval to call a function every so often to see how many days passed since that timestamp, and if more than 0, it updated the badge with the number of days.

When using manifest v3, background pages are actually service workers. Using setInterval will no longer work reliably, since the browser stops and starts service workers when not in use. Instead, Chrome recommends using their alarms API instead. They also suggest using their storage API instead of localStorage.

So, in the flash card pop up, I run this code when a user answers a card:

chrome.storage.local.set({'last-asked': (new Date()).getTime())

chrome.action.setBadgeText({text: ''});


That stores the latest timestamp in storage and clears out any number that might have been previously set on the badge.


In the background service worker, I set an alarm to call a function every 60 minutes. That function retrieves the timestamp from storage, compares it to the current time, and updates the badge number if relevant.


async function sync() {

    const result = await chrome.storage.local.get(['last-asked']);

    const lastAsked = result[key];

    if (lastAsked) {

      const rightNow = (new Date()).getTime();

      const timeDiff = (rightNow - lastAsked);

      const DAY_MS = 86400000;

      if (timeDiff > DAY_MS) {

         chrome.action.setBadgeBackgroundColor({color:[0, 0, 0, 255]});

         const numDays = Math.floor(timeDiff/DAY_MS);

         chrome.action.setBadgeText({text: numDays + ''});

      }

   }

}


// Once an hour, check if it's been too long

sync();

chrome.alarms.create('check-inactivity', {periodInMinutes: 60});

chrome.alarms.onAlarm.addListener(sync);


And that's it! I figure this may be a common use case for the alarms API, so I'm hoping this post helps anyone looking to implement a similar feature.


Sunday, July 10, 2022

Diversifying historical references in CS classes

 A few years ago, I discovered #DisruptTexts, a movement by teachers to challenge the traditional canon in English classes, i.e. spending less time on Shakespeare and more time on historically underrepresented authors.

I teach programming, not English lit, but I still wondered if there were opportunities in my curriculum to shift emphasis away from white male “authors” to people from other cultures. I realized that there are a few standard spots in programming courses that reference the inventor of some algorithm or concept, and that inventor is typically a white male. However, as a general rule, many "inventions" actually get invented by multiple people, and history books try to simplify it down to a single origin story. So, each time I found a reference to an inventor in my curriculum, I researched the web to find any additional inventors.


Here’s what I found for the topics I taught last year:


Fibonacci → Virahanka


When teaching iteration or recursion, I often show how to calculate the numeric sequence where each number is the sum of the two numbers before (1,1,2,3,5,8,13,…). 


The sequence is typically named after Fibonacci, an Italian mathematician from the middle ages who encountered it while modeling the reproduction of rabbits. 


Slide on Fibonacci's study of rabbit reproduction


As it turns out, a Sanskrit grammarian named Virahanka discovered the same sequence many centuries before, while modeling the syllabic structure of Sanskrit poetry. 


Slide on Virahanka's study of Sanskrit poetry


I love when programming and linguistics overlap, so i was fascinated to learn about Virahanka's sequence. To acknowledge the earlier discovery, I added slides on Virahanka and renamed the fib functions in CS61A to virfib.

def virfib(n):
  if n == 0:
    return 0
  if n == 1:
    return 1
  else:
    return virfib(n - 1) + virfib(n - 2)



Backus-Naur → Panini-Backus


Backus-Naur Form is a notation for describing the rules of a language’s grammar (as long as it is context-free). IBM engineer Peter Backus invented the notation in the 1950s to describe the grammar of Algol programming language:


Screenshot of section on syntax of for statements from ALGOL report

BNF is still used today to describe the grammar of modern programming languages. For example, the SQLite syntax reference uses railroad diagrams, a visualization of BNF grammar rules:


Screenshot of DELETE reference for SQLite



I was amazed to discover that this recent “invention” also has a much earlier origin story from the study of Sanskrit. Around 500 BCE, a grammarian named Panini used a formal notation to describe Sanskrit, and that system was very similar to what Backus created in the 50s. I won't share the Sanskrit rules since I don't read Sanskrit and can't be sure of what I'm sharing. However, here's a grammar diagram from a Sanskrit teacher:

Grammar diagram for Sanskrit

As you can see, the construction of a word in Sanskrit follows similar flows as the construction of a DELETE statement in SQLite. There are elements that can be repeated, elements that must be at the beginning or the end,  recursive elements, etc. Those are the sorts of requirements that could be described both by Panini's 500 BCE notation or by Backus' 1950s' notation. 

For that reason, some propose renaming BNF to Panini-Backus form. I did not end up doing that when I taught BNF, since we were also teaching EBNF and I wasn’t prepared to also rename that. However, I do mention its much earlier invention in India when lecturing in class.


George *and* Mary Boole


One of the most foundational concepts in programming is logic, the way we can combine true/false expressions using AND/OR/NOT/etc, and yield a true/false result. That’s called Boolean logic, named after the English logician George Boole who described the system in the 1854 book, The Laws of Thought.


George Boole was married to another mathematician, Mary Everest, who also wrote books on math, despite living at a time when women weren’t welcomed in academics. Mary is known to have contributed heavily to the editing of George’s book and was a loud proponent of its ideas after George’s early death. I am certain that many inventions of married men throughout history were helped significantly by their significant others but not attributed to them. How many women and non-binary inventors would we know about today if history wasn't so rife with patriarchal systems?


Fortunately, we know about Mary’s contributions. Heres how I describe it in my co:rise Python course:


Booleans are named after George Boole, a self-taught logician. He described a system of logic in an 1854 book, The Laws of Thought, that was edited by his wife Mary Everest Boole, another self-taught logician. According to Mary, George was inspired by Indian logic systems dating back to 500 BCE. We can actually find the origins of many "modern" computer science concepts in ancient systems of India, Africa, or the Mediterranean.


And look, another reference to Indian scholars from thousands of years ago! It makes me wonder how many times logic was independently invented across the world.


Those are the places I found so far where I could diversify the historical mentions. Unfortunately, most inventors are still male and from the upper class of society, since we history rarely hear from oppressed genders and classes. 


I’d love to know if other CS teachers have discovered ways to #DisruptTexts in your CS classrooms.