Mandatory reading for PHP devs

I just wanted to give this site I stumbled upon some credit: http://www.hackingwithphp.com/. I’ve been developing with PHP for about 15 years, but still the part about performance taught me quite a lot. isset() is apparently faster than array_key_exists() and $i++is slow compared to ++$i. These are micro-optimizations, sure, but there’s no reason to rub PHP the wrong way…

/Peder

Finding out sentiment

Say you want to find out if a user generated text is happy, sad, upbeat or hateful. Not so easy is it? We were given this task as a part of a recent project. And to make things even more challenging we needed to do this in both Swedish and English.

After a bit of research I found a very interesting API that pretty much does this – SAPLO. Using their API we can create reference groups of texts, and compare user generated texts with these groups.

Say we create two groups; Positive and Negative.
We then measure each user generated text towards these groups, and get a sentiment back. For instance:

Jag har tråkigt (I’m bored):
[Negative] => 0.14
[Positive] => 0

Fisk är gott (Fish tastes good):
[Negative] => 0.22
[Positive] => 0.28

Många tycker det är tråkigt att resa, men inte jag (Many people things that it’s tedious to travel, but I don’t):
[Negative] => 0.40
[Positive] => 0.46

SAPLO works great on both English and Swedish.

How to make a wind chime door bell

Our doorbell was already connected to the Internet via an Arduino, but we couldn’t stand the sound it made. We needed a warmer sound, a sound that didn’t make us want to kill the doorbell users (mostly clients).

Step 1:
Buy an old Wind Chime, preferably with a coconut base (because awesome).
2015-01-22 14.34.26

Step 2:
Pick up a few Littlebit modules (Cloudbit, servo motor and power supply).
2015-01-22 15.41.33

Step 3:
Drill, glue and duct tape a bambu stick to the servo motor. Hide all the crap in a classy box.
download_20150122_143926

Step 4:
Make the old Slack door bell script also make a little curl post to the Cloudbit.

<?php
$data = array(
	"percent" => "100",
	"duration_ms" => "10000"
);
$url_send = "https://api-http.littlebitscloud.cc/devices/XXX/output";
$str_data = http_build_query($data);
$ch = curl_init($url_send);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Bearer XXX','Accept: application/vnd.littlebits.v2+json'));
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");  
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $str_data);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); 
echo curl_exec($ch);
curl_close($ch);

Step 5:
Ring the door bell. Voila!
doorbell

Integrera Swish i egna tjänster

I’ll write this in Swedish because it only applies to Swedes.

Swish är ju en väldigt lyckad tjänst. Den har, liksom t.ex. Uber, förändrat ett beteende. Över 2 millioner svenskar använder appen. Självklart borde man göra något smart på Internet med detta, nu när nästan hela Sverige har appen i fickan. Dock har Swish inget publikt API, vilket förmodligen är anledningen till att det inte hänt så mycket ännu.

Det man vill uppnå är att låta en egen tjänst/kampanj/server veta när en viss användare skickat pengar till ett visst Swishanslutet nummer. Och genom att använda lite tveksamma metoder gick det vägen.

Koden är alldeles för risig för att dela med sig av, men ett första proof of concept funkar. Här t.ex. skickar min vän Bruno 1 krona:

foto_2015-01-07_10_41_12

…och här tar jag emot den på vår utvecklingsserver:

apidump

Känns såklart lite olustigt att haxa fulkod mot sina egna banktjänster, men det kändes viktigt att komma i mål. Får se vad det blir för projekt av detta, men kul att det går iaf. Puss.

/peder

 

Why doesn’t all my Instagram embeds in WordPress look the same?

Well, Instagram changed the response on their Oembed service sometime in December 2014.
And WordPress caches all oembed lookups the first time they’re displayed.

This means that all of your little blog posts which had an Instagram image or video (and more than 1 pageview) before December 2014 will look different than all your new posts. There’s no simple way of making all new embeds look old. But the other way around is easy.

1. Open your PhpMyAdmin or similar tool
2. Select the database WordPress is using
3. Click SQL and run this oneliner:

DELETE FROM `wp_postmeta` WHERE `meta_key` LIKE '%oembed_%'

Reload your WordPress site and voilá. That should do it.

An API for Faking Swedish user details

Lorem Ipsum is great for generating place holder texts, and Placehold.it (and our own Place-A-Pet!) does the same job for images. Sometimes though, you need to create fake Swedish users. Say you want to generate dummy comments or fake forum users. What to do?

I just created a little webservice for this. Get a HTML-table by going here:
http://earthpeople.club/~peder/files/persons/?limit=5

…or get a JSON-feed by adding &format=json to the url, like this:
http://earthpeople.club/~peder/files/persons/?limit=5&format=json

Enjoy 🙂

Let Slack tell you what songs are currently playing in the office

At Earth People, there’s always music in the air (and the birds sing a pretty song).
Most of the stuff we play is fairly unknown to most of us, and in many cases only played once, ever.

To get rid of all the “Hey what’s this song”-chatter or Slack, I made a litte script which we run as a Slack Command.
The script just checks all the Last.fm-feeds of the people usually playing music, and returns what’s on.

Screenshot 2014-10-15 16.51.02

By no means magic, but adds another bit of homey feeling to Slack.
Here’s the Gist, be our guest.

<?php

date_default_timezone_set("Europe/Stockholm");

require 'vendor/autoload.php';

use GuzzleHttp\Pool;
use GuzzleHttp\Client;

$client = new Client();

$users = array('suprape','musikmarskinen','dafeather','brunobrandstrom','Algoritm','mjelle','hjalle','johannagrip','tumde');

$requests = array();
foreach($users as $user){
	$requests[] = $client->createRequest('GET', 'http://ws.audioscrobbler.com/2.0/', [
		'query' => array(
			'method' => 'user.getrecenttracks',
			'limit' => '5',
			'api_key' => 'GetThisFromLastFm',
			'format' => 'json',
			'nowplaying' => 'true',
			'user' => $user
		)
	]);	
}

$results = Pool::batch($client, $requests);
$nowplaying = array();
foreach ($results->getSuccessful() as $response) {
	$recenttracks = json_decode($response->getBody()->getContents());
	if(isset($recenttracks->recenttracks->track)){
		foreach($recenttracks->recenttracks->track as $track){
			if(isset($track->{"@attr"})){
				$temp = new StdClass();
				$temp->artist = $track->artist->{"#text"};
				$temp->title = $track->name;
				$temp->album = $track->album->{"#text"};
				$temp->image = $track->image[3]->{"#text"};
				$nowplaying[] = $temp;
				unset($temp);
			};
		}
	}
}

header('Content-type: text/plain;charset=utf-8');
echo "Verkar som att ".count($nowplaying)." låtar spelas på kontoret just nu:\n";
foreach($nowplaying as $track){
	echo '- "'.$track->artist.' - '. $track->title.'"';
	if($track->album){
		echo ' från skivan "'.$track->album.'"';
	}
	echo "\n";
}

Making headless screengrabs without PhantomJS

Ok this can be done with PhantomJS and it is probably better/simpler/etc. But if you, for any reason, can’t use PhantomJS to make screengrabs, here’s an over complicated alternative we came up with.

wkhtmltopdf is an easy way of making screengrabs of webpage:
$ wkhtmltopdf “http://google.com” googlescreendump.pdf
Most package managers (at least Rpm and Aptitude) has it, and it just works. Some arguments may or may not work, depending on version number, and this example is based on the 0.9.9 which Aptitude offers right now.

While this works fine on your local machine, it won’t on a headless server, so we install Xvfb which acts a virtual X-server.
$ xvfb-run –server-args=”-screen 0, 1024x768x24″ wkhtmltopdf googlescreendump.pdf

This will give you a pdf, probably with the webpage not filling the entire page. To get a usable image file, you need to run it through some Image Magick:
$ convert googlescreengrab.pdf -trim -gravity southeast -background none -splice 50×150 googlescreengrab.png
The arguments need to be tweaked for your setup, so you get the entire screengrab and nothing else.

In total, this is what the command looks like:
xvfb-run –server-args=”-screen 0, 1024x768x24″ wkhtmltopdf -s A1 -B 0 -L 0 -R 0 -T 0 –redirect-delay 3000 “http://google.com” googlescreengrab.pdf && convert googlescreengrab.pdf -trim -gravity southeast -background none -splice 50×150 googlescreengrab.png

So in short. Run PhantomJS if you can.
If not, this will make your client happy.
And make you feel dirty.

 

 

 

Slack integrations so far; deploys, doorbells, reddit and lunch menus

On Earth People, we recently fell in love with Slack (Oh yes that’s an affiliate link that will give us both 100 dollar credit). It got us off Skype (which we didn’t really love anyway) and on to something that felt fresh. What really got us hooked was all the integrations we could do. Here’s a couple we’ve done so far:

1. When the doorbell rings, an Arduino triggers a HTTP request to some shitty PHP script we’ve written, which checks GoogleCal for meetings and pings the chatroom with what’s at the door.

Hey open the door, says Slack

2. Lunch is obviously a big thing for us hoomans. We’ve made a little Curl based bot which checks what the nearby restaurants serve for lunch by typing /zum or /stadsmissionen.

Slackbot responds to /stadsmissionen

3. Whenever someone deploys to a production server, Slack will let everyone know.

Slackbot lets everyone know when we have a deploy to production

4. /reddit <any word> will try to fetch an image from a corresponding subreddit. And post it to everyone… yeah, we’ll see how long this one gets to live. Depends on when someone starts fetching NSFW stuff I guess…

Screen Shot 2014-03-20 at 21.35.36

Right now we’re working on a crappy little Raspberry-integration for our Moccamaster. Wouldn’t it just be great to be able to ask Slack if there’s any coffee…