Half-Elf on Tech

Thoughts From a Professional Lesbian

Tag: coding

  • Chart.js Category Statistics

    Chart.js Category Statistics

    One of the sites I work on is using the Metro Theme by StudioPress Themes for WordPress. And on that site, I have a page dedicated to some odd stats based on the categories and tags and custom taxonomies.

    What I have is a post type ‘shows’ and a custom taxonomy called ‘clichés’ and from that I was easily able to generate a percentage of how many shows use the cliché of queers in law enforcement (38%) or how many have the death of a queer (also 38% right now). But that wasn’t enough. We wanted ‘pretty graphs’ and for that I needed a tool like Chart.js and a little PHP magic.

    How to Chart.js?

    Chart.js is a super cool and super responsive and super flexible way to include a chart. And using it is incredibly easy once I figured out that I could just use inline script tags. A very basic chart that would show you how many days each month has looks like this:

    <script src="Chart.js"></script>
    <canvas id="barDays" width="600" height="400"></canvas>
    
    <script>
    var barDaysData = {
    	labels : ["January", "February", "March", "April", "May", "June", "July", "August", "September", "November", "December"],
    	datasets : [
    		{
    			fillColor : "#7d3255",
    			strokeColor : "#532138",
    			data : ["31","28","31","30","31","30","31","31","30","31","31"]
    		}
    	]
    }
    
    var barDays = document.getElementById("barDays").getContext("2d");
    new Chart(barDays).Bar(barDaysData);
    </script>
    

    If you’re using WordPress, you’ll want to use wp_enqueue_script to call it. Here’s what I did for my theme:

    wp_enqueue_script( 'chart.js', get_bloginfo('stylesheet_directory').'/inc/js/Chart.min.js' , array( 'jquery' ), CHILD_THEME_VERSION );

    But that’s the basics of it. Once I understood that, I was good to go.

    The Code

    Before I can do anything, I need to make sure I have the data I needed. What I wanted was a list of all the shows that were published and a list of all the cliches, ordered in the way I need them. The order is simply comma separated values, enclosed in quotes, enclosed in brackets:

    labels : ["January", "February", "March", "April", "May", "June", "July", "August", "September", "November", "December"],
    

    And the data is similar:

    data : ["31","28","31","30","31","30","31","31","30","31","31"]
    

    Since I’m lazy, I checked that the array worked if it ended in a , and it did! That means my PHP looks like this:

    $count_shows = wp_count_posts( 'post_type_shows' )->publish;
    $cliches = get_terms('cliches');
    
    $barshow_labels = '';
    foreach ( $cliches as $cliche ) {
    		$barshow_labels .= '"'.$cliche->name.'",';
    }
    
    $barshow_data = '';
    foreach ( $cliches as $cliche ) {
    		$barshow_data .= $cliche->count.',';
    }
    

    And my js looks like this:

    <script>
    var barShowsData = {
    	labels : [<?php echo $barshow_labels; ?>],
    	datasets : [
    		{
    			fillColor : "#7d3255",
    			strokeColor : "#532138",
    			data : [<?php echo $barshow_data; ?>]
    		}
    	]
    }
    
    var barShows = document.getElementById("barShows").getContext("2d");
    new Chart(barShows).Bar(barShowsData);
    </script>
    

    You may notice the simple call of <?php echo $barshow_data; ?> in there? That’s where it outputs the data I sorted out in the PHP section. Done. I’m could put it more inline, but I liked to separate them as much as I could.

    Putting it in the theme

    This is a Genesis theme so while I am making use of the Genesis loop, the call to get_template_part can be used by anyone. I’ll explain in a moment. First, here’s the page template:

    <?php
    /**
    * Template Name: Lezbian Stats Template
    * Description: Used as a page template to show page contents, followed by a loop
    * to show the stats of lezbians and what not.
    */
    
    // Show Dead count below the content:
    add_action( 'genesis_entry_footer', 'lez_stats_footer', 9 );
    
    function lez_stats_footer() {
    	get_template_part( 'stats' );
    }
    
    genesis();
    

    This works like any other page template. You make a page, you select the template, and it loads this custom design.

    The magic sauce is in get_template_part( 'stats' ); which calls the file stats.php and that file has all the code you saw above. This means I can edit my post with all the explanations I want, and then it always outputs the stats on the bottom. By calling the Genesis code in the bottom, I retain all of it’s magic while pulling in what I want.

    The Result

    The graph of cliches about queer women on TV

    Looks nice, doesn’t it? I’m quite fond of it.

  • Project Bloat

    Project Bloat

    Can we have a serious talk about project bloat?

    During the framework kerfluffle, I remarked that I hated seeing a 10 line plugin needlessly include a framework like CMB2 because of the size of plugin it created. Someone remarked that if the library helped them write something in ten lines instead of 100, wasn’t that better?

    And the answer to this is maybe.

    My issue is not using a library when the library is the best solution. My issue is people defaulting to use a library before they think about if it is the best solution.

    And my point is really quite simple and obvious to a large number of developers. I’ve touched on it time and again. I’ve told you how I handle packaging my vendor folders. Simply put, I think that before you include anything in your project, you should evaluate it’s merits and flaws.

    Look. There are always, and will always be, good reasons to use a library. There’s never a reason to use a library thoughtlessly, and that’s what I see every day. By ‘thoughtlessly’ I meant someone who has a plugin that adds one setting, a custom meta field let’s say, into all posts. And in order to do that, they wrap ACF into their plugin.

    For one field.

    One.

    Literally one.

    Jackie Chan WTF Meme Face

    And I get it, I really do. The settings API is a bag of wet hair, and the fields API needs love (so much props to Scott Clark for his work there), and figuring out how to do things can be a comprehensive battle of trial and error vs ‘How much hair do I have left?’ And yes, I do use some of those libraries, like CMB2 and ACF, when the need calls for it. When I’m making a massive custom tool or theme and I need to do a million things. But …

    What I don’t do is use it for one field. Sure I could, but that would make my plugin very large and to no real benefit except it’s ‘easier’ for me. And even that is questionable. When I do use them, and yes I do, I do so thinking about the weight I add to my project.

    A pause here. I say this a lot, the weight of a project.

    Everyone seem to assume I only mean the size (in MB) of a project. I don’t. When I say the ‘weight’ of a project I mean the file sizes, of course. Making your 10kb plugin over 500kb just to add one field (I’m being literal here, folks) is sketchy at best. Making it over a meg is borderline ignorant. But I also mean the weight of how it impacts the speed of the site. Will having the library called make a site slower? It might. And I also mean the weight of technical debt. Am I going to update the plugin and the library every single time? This is my responsibility now, and I have to test and test and ensure I don’t break anything.

    The weight isn’t just the size, it’s the time sink. It’s everything that has to go into keeping a library included in a way that doesn’t conflict with anything else. It’s managing my time so I can test and evaluate changes. It’s making sure I push code that won’t break on new versions of my main project (i.e. WordPress). It’s making sure my changes don’t break other co-projects (like WordPress plugins and themes), by assuming they’ll always work on the newer versions. Backwards compatibility isn’t a requirement for all projects, but when it is, you bear that weight too.

    And the weight is also the fact that I’m robbing myself of a greater understanding of WordPress core. Using a library isn’t ‘cheating’ but it does mean I might be less capable of debugging a conflict, if it’s due to the library.

    That’s the real weight of a library included in your project. If you’re not considering it when you add a library, you’re doing yourself a massive disservice.

  • Cooking as a Dev Skill

    Cooking as a Dev Skill

    My friend Dan asked if I’d be talking about cooking as a dev skill for WordCamp Minneapolis.

    While I won’t be making that camp this year (sorry folks), I thought I’d take a moment to talk about cooking as a dev skill. Or rather, what cooking teaches you about developing a website.

    Know What You Want to Cook

    You can’t just decide to throw things together until you’ve been cooking for so long, and you’re an expert at winging it. Most of the time, we pick a recipe we know, or feel we can follow, and decide what we want to make. We have to temper this with what we need to make. If I’m making dinner, I need protein and vegetables. If I’m making a pie, do I need the pie or do I just want something sweet?

    Websites are the same way. We pick the site we want to make before we start building. When you go into making your site, you have to know what you want the site to be. You also have to know what you need. I need a web presence (it’s 2016, yes you do), but I don’t need a video and an interactive game and all the bells and whistles.

    Check Your Ingredients

    Open the door to your refrigerator and make a list of what you have. Look at the recipe. Do you have what you require to make this dish? If you’re ordering out, you get the meal pre-made. When you’re making it yourself, you need to make sure you have salt and butter and tofu and eggs.

    When we talk about webpages, we talk about the code behind it. Can you design something out of nothing? Do you have the tools with which to do so? Can you write javascript and PHP and HTML? These are things you need, these are your ingredients. They’re also going to be your libraries like Backbone and React.

    Mise En Place

    In cooking, setting up everything beforehand makes the entire cooking experience better. I’m terrible at it, but I’m doing my best to get better, because once I’m prepared, everything flows and I’m less of a whirling dervish. The setup doesn’t just keep you organized, it keeps you real. It lays everything out and sometimes, when you look at 10 pats of butter, you may think about maybe cutting down a little.

    Speaking of those libraries, make sure you have only what you need. The whole Backbone repository is over 5 megs. The one file you need is 69kb. Use only what you need. The more individual pieces you need, the more you should scrutinize them. Did you really need all that in the first place? Do you really need eleven css files for options of display, or should you make a basic one and let people build what they want?

    The Cake Will Collapse

    You’re going to mess things up. You’ll burn the caramel, overcook the pasta, underboil the egg, and so on and so forth. These mistakes are okay. As Julia Child said it, “No on will ever know!”

    Do I even need to say it? Your code will fail. A lot. In weird ways. You may spend an hour wondering why WP-CLI fails, only to remember it’s WP_CLI instead.

  • Why CDN Media Needs a Plugin

    Why CDN Media Needs a Plugin

    I wanted to write a blog post for work (something I try to do once a month) so I thought “I should write about using a CDN for images. I wonder if you can do this without a plugin…”

    One hour later, and 1200 words, the answer is no. You cannot.

    My initial goal was to move media files (and only the media) from http://example.com/wp-content/uploads/ to http://static.example.com/wordpress/ on DreamObjects. I’ve written a plugin that does that, but to my frustration, I found you cannot do this without a plugin for one incredibly simple reason.

    But before the big reveal, let’s break down, in simple terms, what I would actually need to do in order to move the uploads. My two assumptions are that I already have a WordPress powered site (check) and I already have DreamObjects (check)

    1. Setup a bucket on DreamObjects (or AWS whatever) to house my images, and give it a CDN alias.
    2. Copy all the images to the bucket.
    3. Change the Upload URL to http://static.example.com/wordpress/ (my CDN alias for the bucket).
    4. Edit all posts and GUIDs to the new URL.

    The thing is, I can actually do all of that!

    Setup a Bucket on DreamObjects

    Log in to your Panel, click on Cloud, go to DreamObjects, and create a new bucket in DreamObjects. I called my domain-static because that’s easy for me to remember. Static content lives here. Once you have your bucket, click on the “Change Settings” link and add an alias of “static” to the domain you’re hosting all this on (example.com in this example).

    You can name your alias anything you want. I just picked static because I knew I wanted my URLs for images to be http://static.example.com/wordpress/2016/01/happynew.jpg and this makes it simple. I like to leave my CDN available for more than just WordPress, and doing this will let me have more folders like wiki or gallery.

    Next, scroll down to “DreamSpeed CDN” and turn on CDN Support. You’ll notice that tells you a special URL for CDN:

    Connect to the accelerated DreamSpeed CDN version of this bucket at: examplecom-uploads.objects-us-east-1.dream.io

    Don’t worry! You can use your custom URL too. You don’t have to, but most of us want to, to feel special. In order to use your custom alias that we just made, scroll up a little and check the box for ‘CDN’ on your alias. Press save and you’re good to go!

    Copy all the Images

    Set the bucket public first!

    Just trust me, here. Okay? Good. Set the bucket public and then upload all the images. I used Transmit. Cyberduck also works.

    Change the Upload URL

    This part was scary.

    We need a moment of history first. Up until WordPress 3.5 this was actually pretty easy to do. You went to your media page and you changed things. As of 3.5, WordPress decided that this was more trouble than it was worth. Too many people were accidentally doing silly things, breaking their sites, and it was too dangerous. So they removed the part of the screen that let you change this.

    I have issues with this, since for what I want to do, it makes it a hassle. But given the flaw in my great plan, I recognize the change as one that protects people who know less than I do.

    Using a plugin to restore this missing setting would be the easiest on many levels. And there are a few plugins that do this but I like Upload Url and Path Enabler. It’s simple and to the point.

    Of course, I love wp-cli and we have it on all our servers at DreamHost, so this command is similarly awesome:

    wp option set upload_url_path http://static.example.com/wordpress

    The last option for this is the secret WordPress page called “All Settings” — This is hands down the most powerful and dangerous page in all of WordPress. It lists all your options and settings that you have in the database. And yes, you can edit many of them in your browser at http://example.com/wp-admin/options.php

    Go ahead. Take a look. It lists a lot of things, most of which you should never, ever, ever, touch. If you were going to use this, search for upload_url_path, change the value from empty to http://static.example.com/wordpress, and press save.

    Edit All Your Posts

    This is a sucky part. You have to edit all your posts now to move the existing images. This is because those changes you made are only for images going forward. Which is really cool and means you didn’t break anything so far. But WordPress hardcodes the paths to images in your posts (for many reasons) so you need to change all of them.

    If you know how to use the command line, this is actually really easy:

    wp search-replace http://example.com/wp-content/uploads/ http://static.example.com/wordpress/

    Run that command and WP-CLI will magically fix all your posts.

    If you don’t want to use the command line, I recommend Velvet Blues Update URLs.

    Done!

    And to be clear on things, this worked perfectly. My media library showed properly, all my images showed, and everything looked perfect. So I decided to run some basic tests and upload new images…. and that’s where my house of cards fell apart.

    You cannot save files to another server.

    Actually You Can… if you sudo

    Now I have to tell you something. I lied. You totally can do this. The problem is that it’s hard and requires mounting your bucket as a local filesystem so that it would be available via the file-path of the server. You see, you could save files to /folder/location/wordpress/ anywhere on the server. I save mine to /home/user/public_html/static/ on one set up, and I have a static domain (domain-static.com) that runs from that folder.

    What that means if I had a location I could access, I could tell WordPress to save there, making it ‘local’ enough to trick it. You can do this with tools like s3fs-fuse, however they’re incredibly complicated and weird for the layman. And that right there was my problem.

    If you’re trying to present something as ‘Without a plugin’ then you don’t want to make the tradeoff be ‘..but with sudo access to a VPS.’ That’s unreasonable.

    And it’s why, right now, if you want to use a CDN for your media in WordPress, use a plugin.

  • Looping Hugo

    Looping Hugo

    I’m ending the year with something non-WordPress. But it has a weird JSON related journey.

    I asked three questions at the end of my last post:

    1. How do I properly mimic a for-loop with range?
    2. Can I make a responsive gallery out of Hugo?
    3. Can I power a Hugo site with WordPress JSON?

    This is the answer to the first one. However in the solving, I made a breakthrough in my head about how one calls data from JSON and structures it.

    But I’m getting ahead of myself, becuase changing a for loop from Jekyll to Hugo was harder than I expected. Way harder.

    One of the things I check in some posts is what the rating is. I set a parameter called ‘rating’ and if it’s there, I ran a quick check to determine how many stars to show:

    <strong>Rating:</strong> {% if page.rating %}{% for i in (1..page.rating) %}<i style="color:gold;" class="fa fa-star" name="star"></i>{% endfor %}{% if 5 > page.rating %}{% assign greystar = 5 | minus: page.rating %}{% for i in (1..greystar) %}<i style="color:grey;" class="fa fa-star" name="star"></i>{% endfor %}{% endif %}{% else %}<em>Not Available</em>{% endif %}
    

    I was pretty damn proud of that loop. Check the rating, output a gold star for each number over 0 and a grey star for every number between the rating and 5. It’s simple but it’s quick.

    Transposing from Liquid to GoLang was not as hard as all that. {% %} became {{ }} and {% endfor %} became {{ end }} and, at first, that was the easy stuff. The majority of my logic was a one-to-one translation. Change page.rating to .Params.rating and so on and so forth.

    The order of the if’s was strange to me, in that it became {{ if eq A B }} (except when it wasn’t) and I was used to thinking {% if A == B %} — it was fairly easy to overcome. In short order, all my simple if-checks were done.

    But those damn loops! I had the ugliest “if A == 1, show 1 gold and 4 grey” configuration. And worse, I had cases where I was checking “If there’s an entry in the Filmography for this show, get the rating from that and not the page itself.” The Filmography file was a straight-forward JSON file, you see (told you JSON was involved).

    Back to the first problem. I knew if I wanted a shortcode to say “Get me a list of all pages, by date, where section is news” I did this:

    {{ range where $.Page.Site.Pages.ByDate "Section" "news" }}

    And that $.Page.Site.Pages.ByDate call changed depending on what template I was on and what I was calling. For a shortcode I had to pass though page to site to pages. On a template I could do .Data.Pages.ByTitle (no $ needed either). I’m still at the trial and error stage of figuring out which call and where, but I know I’ll get there. It’s just mastering new syntax and understanding where I’m calling from and what variables are available to me.

    That’s really okay. It took me years to visualize the interrelations with WordPress themes and functions and plugins, and even then sometimes I’ll output an array in ugly, unformatted ways just to read through and make sure I understand what I’ve got at my disposal. This is normal for most of us.

    And it was fairly clear that if I wanted a shortcode to call the data file and not a list of Section pages, there was code for that: $.Page.Site.Data.filmography (back to Filmography again). And that worked fine. Right up until I wanted to say “For all values where X equals Foo…” and I was back to my loop-headache.

    Now. GoLang does have a for loop!

    func main() {
        sum := 0
        for i := 0; i < 10; i++ {
            sum += i
        }
        fmt.Println(sum)
    }
    

    And I though that I could just use that. Nope! So I asked myself why did {{ for i in (1..Params.rating) }} fail?

    First of all, that ‘in’ should be := instead. But even so, when I ran it I got “ERROR: function “for” not defined.” That means there is no for function. And no loop. After looking at how I was iterating in other places, I did this:

    {{ range $index, $element := .Params.rating }} 
       ONE
    {{ end }}
    

    ERROR: 2015/12/12 template: theme/partials/rating.html:3:26: executing “theme/partials/rating.html” at <.Params.rating>: range can’t iterate over 3 in theme/partials/rating.html

    The 3, in that case, had to do with a rating of 3. This makes a little sense, since you’re supposed to use range to iterate over a map, array or slice. A number is none of those.

    Thankfully I found a ticket talking about adding a loop function to Hugo that was addressing what I was trying to do and finally I had an answer:

        {{ range $star, seq .Params.rating }}
            <i style="color:gold;" class="fa fa-star" name="star"></i>
        {{ end }}
    
        {{ $greystar := sub 5 .Params.rating }}
    
        {{ range $star, seq $greystar }}
            <i style="color:grey;" class="fa fa-star" name="star"></i>
        {{ end }}
    

    The idea there is that seq makes a sequence of the value of .Params.rating for me. If the value is 3, I get an array of [1,2,3] to work with. And that’s something range can itterate over!

    Except…

    at <sub 5 .Params.rating>: error calling sub: Can’t apply the operator to the values in theme/partials/rating.html

    Now the amusing thing here is that the code worked! Even if it wasn’t seeing .Params.rating as an integer, it did the math. I suspect it’s related to this old bug, where variables from front matter are strings and not integers. Except that he said it worked in YAML and that’s what I’m using.

    This was the most perplexing issue. How is a number not a number if it’s being numbered? And then I noticed that I was able to make a sequence, so clearly at that point it knew it was a number. And then I did this:

        {{ $goldstar := seq .Params.rating }}
        {{ $goldstar := len $goldstar }}
    

    And yes it works.

    I’m basically saying “Hey, how many ones are in the number X?” and saving that as a number. There’s no real reason I can comprehend why it failed to work, but there it is. I’ll file a bug as soon as I can figure out how to explain that in a way that doesn’t make me sound crazy.

    How did all this teach me about JSON? You’ll have to wait a few days.

  • Say Thank You Publicly and Be a Better Coder

    Say Thank You Publicly and Be a Better Coder

    Takayuki Miyoshi is one of the best developers for WordPress you probably don’t know about. Miyoshi-san is quiet, thoughtful, and had written a handful of plugins you probably do know. Like Contact Form 7. He’s also written a wonderful multilanguage plugin called Bogo.

    He gave his very first presentation in English about why he uses free plugins. Miyoshi-san’s reasoning is plain and simple. By giving back to WordPress and open-sourcing the code, you have a greater chance of people helping you make your code better. More people will find bugs, more people will help you fix, more people will use it, and things will be made better for everyone.

    This is much the same idea as Pippin Williamson has about his open source philosophy. Now Pippin is pretty upfront that he thinks you should open source your plugins. And he’s got some strong views on supporting your site projects (and the responsibility there in). But he also mentioned once that he supports putting premium (i.e. paywall’d) products on Github.

    For free.

    That’s right. He said you can totally put your code up on Github for anyone to download or edit or fork.

    I thought about it for a moment, and how open and honest Pippin has always been with his code, and how some of his early WordPress code was not the greatest. Yes, I have been around WordPress long enough that some of the people I think of as being ‘The Real Shit’ about coding for WP were pretty bad. Maybe not as bad as I was when I started, maybe they were. My point is that Pippin, like everyone else, started out as a beginner. And some of his beginner code was bad, like everyone else’s.

    Would Pippin be as good a programmer as he is today without open source and without people giving him code corrections and suggestions?

    I think not.

    Furthermore, I don’t think that you’re going to lose any money here. The intersection of people who would both buy your plugin and are technically capable of using Github to install plugins is pretty small. I say this as someone who understands well the desire of people to get things ‘free’ from the internet and the seriousness of customers. If you make it easy for someone to buy your products (and in the case of WordPress, get updates for it), people will pay you. Because they like convenience. Remember the tale of Oatmeal vs HBO. If you stop people from being able to get your product easily, they just won’t.

    Most people are afraid of monetary loss, which I get. But you have to rethink things. First of all, most people won’t use Github. They won’t like not getting security updates, for one. And if you present Github as a technical place, they won’t use it. Done. Secondly, I happily bought the Person of Interest DVDs once Netflix got punched by (I presume) WGN on re-broadcast rights and couldn’t show me Season 4 before Season 5 airs. I get the added bonus of watching it on my Blu-Ray player, in super ultra HD. This behavior is NORMAL. Amazon made it easy for me to get what I wanted, and now I own it and if the Internet is out, well I’ll watch Root and Shaw and the Machine all day.

    And there’s something else to consider. The people who would use Github to get something for free are the folks who wouldn’t have paid in the first place. You’re losing money that you’d never have. To help explain this, I’ve made a little Venn Diagram for you, to show you how small this intersection is:

    percentage of people who would both buy your plugin and are technically capable of using Github to install plugins is pretty small

    I’m serious here. This is non-mathematical but based on my allegorical experiences of years in support be it free or paid. This is coming from someone who lives and breathes WordPress plugins. If you make it easy for them to pay, you will not lose money by putting the code up in a way for other developers to submit pull requests. That small sliver of green, the people who can use Git and would still pay you, those are your contributors. Those are the people you want. Because Open Source Code means more eyes, and more eyes means more reviews, and more reviews means better code.

    Everyone wins.

    And like Pippin and Miyoshi-san, I think that having your code available for others means I may learn new things and become a better developer. When I say ‘pull requests welcome’ what I mean is ‘teach me what you know, I love to learn!’ Even if I say “No, I don’t want to add that feature” trust me that your lesson was welcome and absorbed.

    When I went to WordCamp Tokyo, I had the intention of seeking Miyoshi-san out to tell him how much I like Bogo. That it solved a problem for me. That it just worked. That the code was good. Miyoshi-san also wanted to tell me thank you for the things I’ve done for him.

    It’s possible we both got a little teary eyed.

    And he and I agree on the big things. Make your code available for others to review and comment on and get pull requests. It will make you better.