Spreadsheet Column to Index Conversion in Python

If you’ve ever had to dig down into specific columns of a spreadsheet with > Z columns you probably know how annoying it is to try to convert something like ‘AQ’ to the appropriate index (e.g. row[42]). Here’s a quick one-liner to convert a spreadsheet letter-based column to the equivalent zero-based index.


col2num = lambda col: reduce(lambda x, y: x*26 + y, [ord(c.upper()) – ord('A') + 1 for c in col])-1

view raw

col2num.py

hosted with ❤ by GitHub

For example:

  • col2num(‘A’) -> 0

  • col2num(‘Z’) -> 25

  • col2num(‘BC’) -> 54

Using the WordPress Media Loader in the Front-End

Over a year ago I was checking out WordPress’ new JavaScript media uploader interface and I had the idea to try to get it working on the front-end. After playing around with it I managed to get something working and thought, “I should write a blog post about that,” and promptly forgot all about it. Since I’m at Loopconf at the moment and feeling inspired I guess it’s finally time 🙂

I created a simple plugin available at https://github.com/dbspringer/wp-frontend-media to demonstrate what you’ll need to do to get it working. There are some important caveats!

  1. You need to decide how you want to handle how it’ll work for users that aren’t logged in.
  2. You’ll also have to decide what to do about users without ‘upload_files’ permissions.

That said, let’s take a look!

The Plugin

The media interface is all JavaScript so the plugin mostly serves as a way to bootstrap the js libraries we’ll need. I also included a simple shortcode that spits out a button that summons the interface and replaces the button with the selected image. Otherwise, there are three important things happening:

  1. I’m calling wp_enqueue_media() to load the media interface libraries.
  2. I’m filtering ajax_query_attachments_args in filter_media() to retrieve only the images belonging to the user. If you don’t care about restricting the images just remove the filter.
  3. I’m checking current_user_can( 'upload_files' ) in the shortcode to restrict access to the interface, you’ll need a similar check somewhere in your own code.


<?php
/**
* Plugin Name: Front-end Media Example
* Plugin URI: https://derekspringer.wordpress.com
* Description: An example of adding the media loader on the front-end.
* Version: 0.1
* Author: Derek Springer
* Author URI: https://derekspringer.wordpress.com
* License: GPL-2.0+
* License URI: http://www.gnu.org/licenses/gpl-2.0.txt
* Text Domain: frontend-media
* Domain Path: /languages
*/
// If this file is called directly, abort.
if ( ! defined( 'WPINC' ) ) {
die;
}
/**
* Class wrapper for Front End Media example
*/
class Front_End_Media {
/**
* A simple call to init when constructed
*/
function __construct() {
add_action( 'init', array( $this, 'init' ) );
}
function init() {
load_plugin_textdomain(
'frontend-media',
false,
dirname( plugin_basename( __FILE__ ) ) . '/languages/' );
add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_scripts' ) );
add_filter( 'ajax_query_attachments_args', array( $this, 'filter_media' ) );
add_shortcode( 'frontend-button', array( $this, 'frontend_shortcode' ) );
}
/**
* Call wp_enqueue_media() to load up all the scripts we need for media uploader
*/
function enqueue_scripts() {
wp_enqueue_media();
wp_enqueue_script(
'some-script',
plugins_url( '/', __FILE__ ) . 'js/frontend.js',
array( 'jquery' ),
'2015-05-07'
);
}
/**
* This filter insures users only see their own media
*/
function filter_media( $query ) {
// admins get to see everything
if ( ! current_user_can( 'manage_options' ) )
$query['author'] = get_current_user_id();
return $query;
}
function frontend_shortcode( $args ) {
// check if user can upload files
if ( current_user_can( 'upload_files' ) ) {
$str = __( 'Select File', 'frontend-media' );
return '<input id="frontend-button" type="button" value="' . $str . '" class="button" style="position: relative; z-index: 1;"><img id="frontend-image" />';
}
return __( 'Please Login To Upload', 'frontend-media' );
}
}
new Front_End_Media();

view raw

plugin.php

hosted with ❤ by GitHub

The JavaScript

This is the meat of what you’ll need to use the media interface on the front-end. It’s actually pretty simple to summon the interface and then do something with the file that was retrieved. It’s all handled in these three easy steps:

  1. Create the file_frame object using wp.media().
  2. Attach a 'select' listener to the file_frame object to handle what you want to do when a file is selected. The attachment variable will have an object containing all the metadata for the selected item. Just do a console.log() to figure out what you’re getting.
  3. Tell the file_frame to pop open the interface based on a click (or whatever) on an element somewhere.


(function($) {
$(document).ready( function() {
var file_frame; // variable for the wp.media file_frame
// attach a click event (or whatever you want) to some element on your page
$( '#frontend-button' ).on( 'click', function( event ) {
event.preventDefault();
// if the file_frame has already been created, just reuse it
if ( file_frame ) {
file_frame.open();
return;
}
file_frame = wp.media.frames.file_frame = wp.media({
title: $( this ).data( 'uploader_title' ),
button: {
text: $( this ).data( 'uploader_button_text' ),
},
multiple: false // set this to true for multiple file selection
});
file_frame.on( 'select', function() {
attachment = file_frame.state().get('selection').first().toJSON();
// do something with the file here
$( '#frontend-button' ).hide();
$( '#frontend-image' ).attr('src', attachment.url);
});
file_frame.open();
});
});
})(jQuery);

view raw

frontend.js

hosted with ❤ by GitHub

There you have it! I’ll leave it up to you to do something non-trivial with it, but this should get you started. happy coding!

It's magic!

Word Scrambling in Python

To get this new blog started I’m poaching an old post I made about scrambling words while retaining legibility. In the time since I originally posted this I found the source.

I was recently reading the Lucky Basartd page on the Stone Brewery website and I remembered an (unverified) study claiming “scrambled words are legible as long as first and last letters are in place.” For grins, I whipped up a Python script to scramble a word/sentence.


#!/usr/bin/python
# -*- coding: utf-8 -*-
def scramble(unscrambled):
'''
Scrambles the word(s) in unscrambled such that the first and last letter remain the same,
but the inner letters are scrambled. Preserves the punctuation.
See also: http://science.slashdot.org/story/03/09/15/2227256/can-you-raed-tihs
'''
import string, random, re
splitter = re.compile(r'\s')
words = splitter.split(u''.join(ch for ch in unscrambled if ch not in set(string.punctuation)))
for word in words:
len_ = len(word)
if len_ < 4: continue
if len_ == 4:
scrambled = u'%c%c%c%c' % (word[0], word[2], word[1], word[3])
else:
mid = list(word[1:-1])
random.shuffle(mid)
scrambled = u'%c%s%c' % (word[0], ''.join(mid), word[-1])
unscrambled = unscrambled.replace(word, scrambled, 1)
return unscrambled
if __name__ == '__main__':
print scramble(u'Indeed, here be some scrÖmbled words!')

view raw

scramble.py

hosted with ❤ by GitHub

Featured image via mj ecker