TIL about Python’s “enumerate”

I’ve been writing Python for more than 10 years, and I can’t count the number of times I’ve written code like this:

index = 0
for thing in array:
    do_something_with(index, thing) # Because I care about the index AND the item
    index += 1

But today I learned about the built-in enumerate function which does exactly the same thing, but avoids any chance of getting “index” and “thing” out of sync (not that I’ve ever made that mistake, of course…).

I’m not going to rewrite any old code for fear of adding new bugs, but I’ll remember to enumerate going forward.

Thanks, Dr. Drang!

Adding email addresses to Divi’s “person” module for District 101

The Divi theme is powerful, but it has some quirks. One of those is in the “person” module, which doesn’t provide a place for contact information (phone and email). I wanted to add email for the people listed on the District Leadership Team page; the obvious way was to add the email address to the text for each person, but that felt inelegant.

A quick Google search led me to a free plugin, Person Module Extended by Dani Dwiputra, made available through Divi Space. I installed the plugin, added emails in the appropriate fields, and could have called it a day, except that I wanted to make some changes to the presentation.

Here are the diffs to get the results I wanted:

++ Desktop/person-full-social/dd-person-modules.php 2016-07-24 21:12:21.000000000 -0700
@@ -465,2 +465,12 @@

+        if ( '' !== $member_email ) {
+            $contact = sprintf('<a href="mailto:%1$s" class="et_pb_member_email">%1$s</a>', esc_html( $member_email ) );
+            $contact .= ( '' !== $member_phone ? sprintf(' | <a href="tel://%1$s" class="et_pb_member_phone">%1$s</a>', esc_html( $member_phone ) ) : '' );
+        } else {
+            $contact = ( '' !== $member_phone ? sprintf('<a href="tel://%1$s" class="et_pb_member_phone">%1$s</a>', esc_html( $member_phone ) ) : '' );
+        }
+        if ( '' !== $contact ) {
+            $contact = '<p>' . $contact . '</p>';
+        }
        $output = sprintf(
@@ -471,4 +481,4 @@
+                   %7$s
-                   <p>%7$s  |  %6$s</p>
@@ -483,3 +493,3 @@
            ( '' !== $member_phone ? sprintf( '<a href="tel://%1$s" class="et_pb_member_phone">   %1$s</a>', esc_html( $member_phone ) ) : '' ),
-           ( '' !== $member_email ? sprintf( '<a href="mailto:%1$s" class="et_pb_member_email">   %1$s</a>', esc_html( $member_email ) ) : '' ),
+           $contact,
            ( '' !== $position ? sprintf( '<p class="et_pb_member_position">%1$s</p>', esc_html( $position ) ) : '' ),
@@ -493,2 +503,2 @@
-new DD_Builder_Module_Team_Member;
\ No newline at end of file
+new DD_Builder_Module_Team_Member;
diff -r -U1 Downloads/person-full-social/module-extend.php Desktop/person-full-social/module-extend.php
--- Downloads/person-full-social/module-extend.php  2016-07-20 10:58:09.000000000 -0700
+++ Desktop/person-full-social/module-extend.php    2016-07-24 21:15:17.000000000 -0700
@@ -9,2 +9,3 @@
  * License: GPL2
+ * Modified by David Singer

Thanks, Dani!

Speeding up “Feed Them Social” for District 101

The District 101 Toastmasters website uses the Feed Them Social plugin to add our Facebook and Twitter feeds to our homepage.

It works well, but it can be slow – if it needed to go to Facebook to update its data, it could take as much as 10 seconds to build the page; even if data was in the plugin’s cache, it took a couple of seconds to build the HTML. You can see the shortcodes I had on the home page below.

I thought about writing my own program to mine the Facebook Graph and the Twitter Feed. It would let me produce exactly what I needed, but it would be a perpetual maintenance headache (and I don’t plan to be Webmaster forever). I needed a better answer.

And then it struck me – if I could figure out a way to use the plugin as part of a batch process and save the HTML, I could get the plugin’s processing time out of the critical path, and I wouldn’t have to keep up with changes to the Facebook and Twitter APIs. Here’s what I did:

  • Created a special version of the home page, with the calls to the plugin in the proper place in the page layout (just in case it mattered), but with none of the other features of the home page.
  • Surrounded the calls to the plugin on the special page with flag lines so I could easily pull out the HTML generated by the plugin, using a simple Python program.
  • Made the special page password-protected in WordPress to keep it out of the visible menu structure shown to site visitors.
  • Wrote a script to be called periodically by cron that:
    • used curl to fetch the special page
    • ran the Python program to extract the HTML from Feed Them Social
    • saved the result as a file
  • Replaced the calls to the plugin on the homepage with a couple of lines of PHP to include the saved file as part of the homepage

The result: the homepage loads at least 3.5 seconds faster and looks the same.

Here’s the relevant part of the special page (the calls to FTS are the same as those I used to have on the homepage).

Start Flag
[fts_facebook id=d101tm posts_displayed=page_only type=page]
[fts_twitter twitter_name=d101tm]
End Flag

Here’s the shell script:

# Update the cached static file for social media from Feed Them Social
secret=password for the WordPress page
cd ~/files/social
# The next operation will take a while, so we write to a temporary file
curl -sL "http://d101tm.org/wp-login.php?action=postpass" -d "post_password=$secret" -e "http://d101tm.org/path to the special page/" -b /dev/null | $mydir/updatefts.py > $outfile
# If all went well, we can replace the real file
if [ -n $outfile ]; then
    mv $outfile fts.html
    echo $outfile is zero length!
    exit 1

And here’s the Python program:

#!/usr/bin/env python
""" Extract the HTML generated by Feed Them Social from stdin, write to stdout"""

import sys
startflag = 'Something unlikely to appear on the page'
endflag = 'Something else unlikely to appear on the page'
havestart = False
haveend = False

def findendflag(s):
    """ Returns a tuple: (any data before the endflag,
                          whether the endflag was found) """
    if endflag in s:
        return (s.split(endflag,1)[0], True)
        return (s, False)

for l in sys.stdin.readlines():
    if not havestart:
        res = l.split(startflag,1)
        if len(res) > 1:
            havestart = True
            (l, haveend) = findendflag(res[1])
    elif not haveend:
        (l, haveend) = findendflag(l)

Some Thoughts on the Toastmasters District 101 Website

I’m Webmaster for Toastmasters District 101, which started operations on July 1, 2016. For the previous two years, I had been on the Webmaster team for Toastmasters District 4; District 101 covers the area from Mountain View to Monterey, which was in District 4 until July 1.

As Webmaster for District 101, I had to choose a CMS (I chose WordPress and a theme (Divi)). I had help from other members of the District 101 Foundations team in picking other plug-ins and in creating the content for the website.

This will be the first, and possibly not the last, in a series of postings about the website and the other code I write in support of it. I’m posting here for two reasons:

  • Perhaps it’ll help someone else
  • Perhaps I’ll be able to find it in the future!

You can decide which is the more important reason.

Tweaking The Events Calendar

We chose to use The Events Calendar from Modern Tribe as our calendar tool.

Out of the box, it works well, but I wanted to display some information about the kinds of events we would show on the District Calendar and how to search for an event.

The obvious way to do that was to use the “Add HTML before event content” feature in Advanced Template Settings; unfortunately, when I added the information there, it not only appeared on calendar listings, it appeared when you chose a single event to display (and in that case, there was no search bar available, so it was really confusing!).

I found two ways to get the kind of display I wanted:

  • Override default-template.php by copying it from the-events-calendar/src/views/ to my-child-theme/tribe-events/ and then only calling tribe_events_before_html if I wasn’t displaying a single event; this has the advantage of making the information editable in the Events Calendar settings.
  • Add a new action for the tribe_events_bar_before_template hook that would display my information if and only if the search bar was going to be displayed. This has the disadvantage of requiring me to hard-code the information in my action.

I decided to go with the first choice, which also required me to be sure to use the “Default Events Template” instead of the “Default Page Template” in the Events Calendar settings.

Here’s the diff to create my modified default-template.php file:

@@ -17,7 +17,11 @@
 <div id="tribe-events-pg-template">
-        <?php tribe_events_before_html(); ?>
+    <?php
+        if (!(tribe_is_event() && is_single())) {
+            tribe_events_before_html();
+        };
+    ?>
         <?php tribe_get_view(); ?>
         <?php tribe_events_after_html(); ?>
 </div> <!-- #tribe-events-pg-template -->