🎭 Jester gist stars for pamelafox
A♦
exportjson.js966 stars

Google Spreadsheet JSON ExportHow-to at http://blog.pamelafox.org/2013/06/exporting-google-spreadsheet-as-json.html

// Includes functions for exporting active sheet or all sheets as JSON object (also Python object syntax compatible).
// Tweak the makePrettyJSON_ function to customize what kind of JSON to export.

var FORMAT_ONELINE   = 'One-line';
var FORMAT_MULTILINE = 'Multi-line';
var FORMAT_PRETTY    = 'Pretty';

var LANGUAGE_JS      = 'JavaScript';
var LANGUAGE_PYTHON  = 'Python';

var STRUCTURE_LIST = 'List';
var STRUCTURE_HASH = 'Hash (keyed by "id" column)';
A♦
K♣
countryinfo.py148 stars

Python list of country codes, names, continents, capitals, and pytz timezones

countries = [
{'timezones': ['Europe/Andorra'], 'code': 'AD', 'continent': 'Europe', 'name': 'Andorra', 'capital': 'Andorra la Vella'},
{'timezones': ['Asia/Kabul'], 'code': 'AF', 'continent': 'Asia', 'name': 'Afghanistan', 'capital': 'Kabul'},
{'timezones': ['America/Antigua'], 'code': 'AG', 'continent': 'North America', 'name': 'Antigua and Barbuda', 'capital': "St. John's"},
{'timezones': ['Europe/Tirane'], 'code': 'AL', 'continent': 'Europe', 'name': 'Albania', 'capital': 'Tirana'},
{'timezones': ['Asia/Yerevan'], 'code': 'AM', 'continent': 'Asia', 'name': 'Armenia', 'capital': 'Yerevan'},
{'timezones': ['Africa/Luanda'], 'code': 'AO', 'continent': 'Africa', 'name': 'Angola', 'capital': 'Luanda'},
{'timezones': ['America/Argentina/Buenos_Aires', 'America/Argentina/Cordoba', 'America/Argentina/Jujuy', 'America/Argentina/Tucuman', 'America/Argentina/Catamarca', 'America/Argentina/La_Rioja', 'America/Argentina/San_Juan', 'America/Argentina/Mendoza', 'America/Argentina/Rio_Gallegos', '
K♣
Q♥
showspreadsheet.php51 stars

PHP for parsing the JSON output a published Google spreadsheet and displaying columns from each row.

<?php

// Parsing this spreadsheet: https://spreadsheets.google.com/pub?key=0Ah0xU81penP1dFNLWk5YMW41dkcwa1JNQXk3YUJoOXc&hl=en&output=html
$url = 'http://spreadsheets.google.com/feeds/list/0Ah0xU81penP1dFNLWk5YMW41dkcwa1JNQXk3YUJoOXc/od6/public/values?alt=json';
$file= file_get_contents($url);

$json = json_decode($file);
$rows = $json->{'feed'}->{'entry'};
foreach($rows as $row) {
  echo '<p>';
  $title = $row->{'gsx$title'}->{'$t'};
  $author = $row->{'gsx$author'}->{'$t'};
Q♥
J♠
zepto-extras.js47 stars

My Zepto Extras - more info @ http://blog.pamelafox.org/2011/11/porting-from-jquery-to-zepto.html

(function($) {
  // Used by dateinput
  $.expr = {':': {}};

  // Used by bootstrap
  $.support = {};

  // Used by dateinput
  $.fn.clone = function(){
      var ret = $();
      this.each(function(){
          ret.push(this.cloneNode(true))
J♠
十♦
senderror.js43 stars

Sending JS errors to server

function sendError(message, url, lineNum) { 
    var i;

    // First check the URL and line number of the error
    url = url || window.location.href;
    lineNum = lineNum || 'None';

    // If the error is from these 3rd party script URLs, we ignore
    // We could also just ignore errors from all scripts that aren't our own
    var scriptURLs = [
      // Facebook flakiness
      'https://graph.facebook.com',
十♦
9♣
tumlbr_template.html20 stars

Twitter Bootstrap Tumblr Theme

<!doctype html>
<!--[if lt IE 7 ]> <html class="no-js ie6" lang="en"> <![endif]-->
<!--[if IE 7 ]>    <html class="no-js ie7" lang="en"> <![endif]-->
<!--[if IE 8 ]>    <html class="no-js ie8" lang="en"> <![endif]-->
<!--[if (gte IE 9)|!(IE)]><!--> <html class="no-js" lang="en" xmlns:fb="http://www.facebook.com/2008/fbml" xmlns:og="http://ogp.me/ns#"> <!--<![endif]-->
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name='description'  content='{MetaDescription}'>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="chrome=1">
    <link rel="stylesheet" media="screen" href="http://twitter.github.com/bootstrap/assets/css/bootstrap.css" />
9♣
8♥
util.js17 stars

JavaScript Utility Libraries (Scroll down!)

var ED = ED || {};

// Utility functions

ED.util = (function() {

  // Data structure functions

  function each(object, callback) {
    if (object === null) return;
    if (object instanceof Array) {
      for (var i = 0, item; i < object.length; i++) {
8♥
7♠
browser.js17 stars

Browser banner warning

(function(wndw) {
  var Browsers, OS, Platform, Versions, browser_name, browser_version, os, platform;
  Versions = {
    Firefox: /firefox\/([\d\w\.\-]+)/i,
    IE: /msie\s([\d\.]+[\d])/i,
    Chrome: /chrome\/([\d\w\.\-]+)/i,
    Safari: /version\/([\d\w\.\-]+)/i,
    Ps3: /([\d\w\.\-]+)\)\s*$/i,
    Psp: /([\d\w\.\-]+)\)?\s*$/i
  };
  Browsers = {
    Konqueror: /konqueror/i,
7♠
6♦
ajax-exercises.txt16 stars

AJAX Exercises

Exercise: Nutrition Facts

    Create an empty webpage.
    Download nutrition.xml from https://gist.github.com/3000322 and place in your project folder.
    Use AJAX via jQuery or JS API to fetch the file into the page.
    Create a table. For each <food> in the XML file, create a row in the table with the food name and nutritional facts - serving size, calories, carbs.
    Bonus: Use the tablesorter jQuery plugin to make the table sortable by the nutritional facts.

Exercise: Lady Gaga News

    Create an empty webpage.
    Download the RSS feed at http://www.ladygaga.com/feeds/artist/content/ and store it in your project folder.
6♦
5♣
selenium_dom.py12 stars

Python Selenium Dom Helper Functions

from selenium.common.exceptions import NoSuchElementException, TimeoutException


class DomHelper(object):
    driver = None
    waiter = None

    def open_page(self, url):
        self.driver.get(url)

    def reload_page(self):
        self.driver.refresh()
5♣
4♥
view.html12 stars

Google Maps AutoComplete for Profile Location Field

<div class="control-group">
   <label class="control-label">Location</label>
   <div class="controls">
     <input name="location" type="text" placeholder="City, State, Country" value=""> 
     <input name="location_city" type="hidden" value="">
     <input name="location_state" type="hidden" value="">
     <input name="location_country" type="hidden" value="">
     <input name="location_lat" type="hidden">
     <input name="location_lng" type="hidden">
    </div>
</div>
4♥
3♠
email_logger.py10 stars

Email Logging for App Engine

#!/usr/bin/env python
#
# based on XMPPLoggingHandler, Copyright 2011 Calvin Rien,
# based on ExceptionRecordHandler, Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
3♠
2♦
personalize.js10 stars

Javascript grammatical personalization library

/**
 * A function that takes a template and grammatical options ('gender', 'person', 'name') and returns the computed string.
 * See below for examples.
 *
 * See wikipedia for more on grammar: 
 * http://en.wikipedia.org/wiki/English_personal_pronouns
 * http://en.wikipedia.org/wiki/Grammatical_conjugation
 */
function personalize(template, options) {
  var GENDERS = ['neutral', 'female', 'male'];
  var PERSONS = ['first', 'second', 'third'];
2♦
A♦
phonegap-photofetcher.js10 stars

PhoneGap Convert Photo File URI to Data URI

function getPhoto() {
  navigator.camera.getPicture(onPhotoSuccess, onPhotoFail, 
    {quality: 70,  targetWidth: 500, targetHeight: 500,
     sourceType: navigator.camera.SourceType.PHOTOLIBRARY,
     destinationType: navigator.camera.DestinationType.FILE_URI,
    });
}

function onPhotoSuccess(imageUri) {
  var $img = $('<img/>');
  $img.attr('src', imageUri);
  $img.css({position: 'absolute', left: '0px', top: '-999999em', maxWidth: 'none', width: 'auto', height: 'auto'});
A♦
K♣
usermodel.py9 stars

SimpleGeo Timezone Calculation on Python App Engine

class User(db.Model):
  location      = db.StringProperty()
  timezone      = db.StringProperty(default='America/Los_Angeles')

  # Do this once per user
  def calculate_timezone(self):
    from simplegeo import Client
    client = Client('oauth key', 'oauth secret SHH')
    response = client.context.get_context_by_address(self.location)
    for feature in response['features']:
      if feature['classifiers'][0]['category'] == 'Time Zone':
        timezone = feature['name']
K♣
Q♥
views.py9 stars

CORS on Python/Flask

from flask import request, make_response,

def any_response(data):
  ALLOWED = ['http://localhost:8888']
  response = make_response(data)
  origin = request.headers['Origin']
  if origin in ALLOWED:
    response.headers['Access-Control-Allow-Origin'] = origin
  return response
Q♥
J♠
selenium_page.py9 stars

Selenium Utility Funcs

from selenium.common.exceptions import NoSuchElementException, TimeoutException, WebDriverException


class SeleniumPage(object):
    driver = None
    waiter = None

    def open_page(self, url):
        self.driver.get(url)

    def reload_page(self):
        self.driver.refresh()
J♠
十♦
autoresizer.js9 stars

TextArea AutoResizer (Bootstrap jQuery/Zepto Plugin)


var AutoResizer = function (textArea, options) {
  var self = this;

  this.$textArea = $(textArea);
  this.minHeight = this.$textArea.height();

  this.options = $.extend({}, $.fn.autoResizer.defaults, options)

  this.$shadowArea = $('<div></div>').css({
      position: 'absolute',
      top: -10000,
十♦
9♣
catalog_test.js8 stars

Coursera catalog view test

describe('catalogyBody', function() {

  var chai        = require('chai');
  var path        = require('path');
  var env         = require(path.join(testDir, 'lib', 'environment'));
  var requirejs   = env.requirejs(staticDir);
  var sinon       = requirejs('js/lib/sinon');
  var fs          = require('fs');
  var server;
  var router;

  describe('catalog list', function(){
9♣
8♥
send.js7 stars

CORS XHR (jQuery/Flask)

  function sendData(url, data, onSuccess, onError) {

    $.ajax({
        url: url,
        type: 'POST',
        data: data,
        dataType: 'json',
        xhrFields: {
          withCredentials: true
        },
        success: function(responseJSON) {
          onSuccess(processJSON(responseJSON));
8♥
7♠
twitter-bootstrap.scss7 stars

Bootstrap Android Overrides

body.android {
  .modal {
    @include box-shadow(none);
    @include background-clip(border-box);
    @include border-radius(0px);
    border: 1px solid black;
  }
  .alert {
    @include border-radius(0px);
    text-shadow: none;
  }
  .nav-pills {
7♠
6♦
geonames.py7 stars

Geonames Python wrapper

import sys
import urllib
import urllib2
import json
import logging


class GeonamesError(Exception):
    
    def __init__(self, status):
        Exception.__init__(self, status)        # Exception is an old-school class
        self.status = status
6♦
5♣
Makefile6 stars

JS/CSS Compressor Makefile

# Javascript/CSS Compressor Makefile
# Original by Benjamin "balupton" Lupton (MIT Licenced)
# Modified by Pamela Fox

MAKEFLAGS = --no-print-directory --always-make
MAKE = make $(MAKEFLAGS)

BUILDDIR = ./.build

CLOSUREURL = http://closure-compiler.googlecode.com/files/compiler-latest.zip
CLOSUREDIR = $(BUILDDIR)/closure
CLOSUREFILE = $(CLOSUREDIR)/compiler.jar
5♣
4♥
Makefile6 stars

Closure/YUI/JsHint Makefile

# Makefile for JS/CSS:
# Uses Closure for JS compiling, YUI for CSS compiling, and JsHint for code quality checking

MAKEFLAGS = --no-print-directory --always-make
MAKE = make $(MAKEFLAGS)

BUILDDIR = ./.build

CLOSUREURL = http://closure-compiler.googlecode.com/files/compiler-latest.zip
CLOSUREDIR = $(BUILDDIR)/closure
CLOSUREFILE = $(CLOSUREDIR)/compiler.jar
YUIURL = http://yui.zenfs.com/releases/yuicompressor/yuicompressor-2.4.6.zip
4♥
3♠
bootstrap.datepicker.js6 stars

jQuery/Zepto Bootstrap Datepicker

/* ===========================================================
 * bootstrap-datepicker.js v1.3.0
 * http://twitter.github.com/bootstrap/javascript.html#datepicker
 * ===========================================================
 * Copyright 2011 Twitter, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
3♠
2♦
gistfile1.py5 stars

Sendgrid Python Web API example

import urllib2, urllib
import logging

def send_mail_sendgrid(from, to, subject, body):
  base_url = 'https://sendgrid.com/api/mail.send.json'
  params = {
    'api_user': 'you@you.com',
    'api_key': 'yourpassword',
    'from': from,
    'to': to,
    'subject':  subject,
    'text': body
2♦
A♦
withings.py5 stars

Withings Python OAuth Wrapper

# -*- coding: utf-8 -*-
# Based on https://github.com/ikasamah/withings-garmin/blob/master/withings.py

import urllib
from datetime import datetime
import urlparse
import oauth2 as oauth

try:
    import json
except ImportError:
    import simplejson as json
A♦
K♣
_ie_warning.html5 stars

IE ChromeFrame conditional prompt and alert

    <!--[if lt IE 7]>
    <script type="text/javascript" 
   src="http://ajax.googleapis.com/ajax/libs/chrome-frame/1/CFInstall.min.js"></script>
    <script>
     // The conditional ensures that this code will only execute in IE,
     // Therefore we can use the IE-specific attachEvent without worry
     window.attachEvent("onload", function() {
       CFInstall.check({
         mode: "overlay"
       });
     });
    </script>
K♣
Q♥
datepicker.scss4 stars

Zepto Bootstrap Datepicker SASS


.datepicker {
    background-color: $white;
    border-color: #999;
    border-color: rgba(0, 0, 0, 0.2);
    border-style: solid;
    border-width: 1px;
    @include border-radius(4px);
    @include box-shadow(0 2px 4px rgba(0,0,0,.2));
    @include background-clip(padding-box);
    display: none;
    position: absolute;
Q♥
J♠
touch.js4 stars

Touch Events

 dom.each(function() {
        $(this).unbind('tap', callback);
        $(this).bind('tap', callback);

        $(this).bind('touchstart', function(e) {
          e.preventDefault();

          var item = e.currentTarget;
          if (ISTOUCHING) return;
          item.moved = false;
          ISTOUCHING = true;
          item.startX = e.touches[0].pageX;
J♠
十♦
README.md4 stars

Instagram Python API Reference

python-instagram
======
A Python client for the Instagram REST and Search APIs

Installation
-----
pip install python-instagram

Requires
-----
  * httplib2
  * simplejson
十♦
9♣
grunt.js4 stars

Grunt for a CSS/JS WebApp

/*global module:false*/

module.exports = function(grunt) {

  var CSS_DIR   = 'src/css/';
  var JS_DIR    = 'src/js/';
  var BUILD_DIR = '../build/';

  // Project configuration.
  grunt.initConfig({
    lint: {
      files: [JS_DIR + 'app/**/*.js']
9♣
8♥
yahoogeocoder.py4 stars

YahooGeocoder

import urllib
import settings
try:
	import json
except ImportError:
	import simplejson as json


class YahooException(Exception): 
	pass 

8♥
7♠
focus.js4 stars

Hack for Android focus() on PhoneGap

// From Lindsey Simon
/**
 * This is a hack to make text input focus work in Android/PhoneGap
 * where calling el.focus() doesn't actually have the blinking cursor
 * effect = scumbag.
 * @param {Zepto} $el A zepto element.
 */
ws.focus = function($el) {
  var el = $el.get(0);
  el.focus();
  el.setSelectionRange && el.setSelectionRange(0, 0);
};
7♠
6♦
newtalk.html3 stars

Calculating timezone from city/country

<!DOCTYPE html> 
<html"> 
  <head>
    <script src="/static/js/jquery.min.js"></script> 
    <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script> 
  </head> 
  <body>
 
  <h2 class="headline">New Talk</h2> 
 
  <form id="talkform-form" method="post" action="/admin/talks/add"> 
 
6♦
5♣
jsonexport.js3 stars

JSON Export Apps Script

// Exports current sheet as JSON and displays in message box.
function exportJSON() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getActiveSheet();
  var rowsData = getRowsData(sheet);
  ss.msgBox(Utilities.jsonStringify(rowsData));
}

// getRowsData iterates row by row in the input range and returns an array of objects.
// Each object contains all the data for a given row, indexed by its normalized column name.
// Arguments:
//   - sheet: the sheet object that contains the data to be processed
5♣
4♥
qunit_tests.py3 stars

Python Selenium QUnit Runner

import unittest
from sys import *
import os

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.common.exceptions import NoSuchElementException, TimeoutException

class QUnitTests(unittest.TestCase):
    driver = None
    waiter = None
    failed = False
4♥
3♠
phonegap-mock.js3 stars

Phonegap Mock Camera API getPicture

var navigator = window.navigator || {};

navigator.camera =  (function() {
  function resizeImage(img, maxHeight, maxWidth) {
    var ratio = maxHeight/maxWidth;
    if (img.height/img.width > ratio){
         // height is the problem
        if (img.height > maxHeight){
          img.width = Math.round(img.width*(maxHeight/img.height));
          img.height = maxHeight;
        }
    } else {
3♠
2♦
redirect.py3 stars

App Engine Redirect Handler

"""
 Licensed under the Apache License, Version 2.0:
 http://www.apache.org/licenses/LICENSE-2.0
"""
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app


redirects = {
 '/learning': 'http://blog.pamelafox.org',
 '/learning/reusing-html-css-js.html': 'http://blog.pamelafox.org/2011/12/reusing-htmlcssjs-across-web-mobile.html',
 '/learning/using-oauth-apis-appengine.html': 'http://blog.pamelafox.org/2011/12/using-3-legged-oauth-apis-with-flask.html',
2♦
A♦
Completely Static App2 stars

For App Engine

application: oliverfoxmurals
version: 1
runtime: python
api_version: 1

handlers:
- url: /
  static_files: static/index.html
  upload: static/index.html
  
- url: /
  static_dir: static/
A♦
K♣
friendsearch.html2 stars

Facebook API + jQuery Autosuggest

<!doctype html> 
<head> 
  <link rel="stylesheet" href="/css/style.css"> 
<body> 

  <input class="friend-search"></input> 
  <div id="fb-root"></div> 
 
  <script>window.jQuery || document.write("<script src='/js/libs/jquery-1.5.1.min.js'>\x3C/script>")</script> 
  <script src="/js/jquery.autosuggest.js"></script> 
  <script>
window.fbAsyncInit = function() {
K♣
Q♥
models.py2 stars

Using SendGrid Incoming API with Python Flask

# Setup datastore model for storing mail
class ParsedMail(db.Model):
  from_address   = db.StringProperty()
  to_address     = db.StringProperty()
  text           = db.TextProperty()
  subject        = db.StringProperty()
Q♥
J♠
gistfile1.js2 stars

Sending JS errors to server

window.onerror = function(message, url, line_num) {

  // Standard error information
  var error = '\n JS Error: ' + message + ' from ' + url + ':' + line_num;
  error += '\n URL: ' + document.URL;
  
  // User agent info, using https://github.com/caseyohara/user-agent
  var user_agent = new UserAgent();
  error += '\n Browser: ' + user_agent.browser_name + ' ' + user_agent.browser_version + ' | OS: ' + user_agent.os + ' | Platform: ' + user_agent.platform;

  // User information - I find it useful to know who's logged in, so I can contact them for more info. Modify for your own use.
  if (USER_INFO) error += '\n User: ' + USER_INFO.email + ' http://' + window.location.host + '/user/' + USER_INFO.id; 
J♠
十♦
phonegap.html2 stars

PhoneGap Timing Template

<!doctype html>
<html>
 <head>
  <meta name="viewport" content="initial-scale=1.0, user-scalable=no, width=device-width" />
  <title>PhoneGap App</title>
  <script>
  var timedEvents = [];
  function timeEvent(name) {
    timedEvents.push({'name': name || 'unnamed', time: Date.now()});
  }

  function showTimedEvents() {
十♦
9♣
button.html2 stars

Changing button states (Bootstrap)

<button class="btn save-button primary" type="submit" data-startmsg="Save" data-loadingmsg="Saving..." data-successmsg="Saved!">Save</button>
9♣
8♥
superfeedr_client.py2 stars

SuperFeedr Python Client

import urllib
import logging
import base64
from httplib2 import Http

API_URL = 'http://superfeedr.com/hubbub'
MODE_SUBSCRIBE   = 'subscribe'
MODE_UNSUBSCRIBE = 'unsubscribe'    
MODE_RETRIEVE    = 'retrieve'

class SuperFeedrClient(object):
8♥
7♠
impressflow.js2 stars

impress.js: Attempt at flowchart generation

 // Each DIV has data-parent="parentid" (except the top)
 // Go through all steps, make hierarchy of parent to children
 var childrenIds = {};
 var topId;
 $('.step').each(function() {
  var id = $(this).attr('id');
  var parentId = $(this).attr('data-parent');
  if (!parentId) { 
    topId = id;
  } else {
    if (!childrenIds[parentId]) {
      childrenIds[parentId] = [];
7♠
6♦
queue.yaml2 stars

Geocoding with named task queue parameters on App Engine

queue:
- name: geocoding
  rate: 1/m
  retry_parameters:
    task_retry_limit: 60
    task_age_limit:   3d
    min_backoff_seconds: 120
6♦
5♣
form.html2 stars

Functions for showing form save messages and errors

<form id="coursera-form" action="/api/save" enctype="multipart/form-data" method="POST" class="form-horizontal">
      <!-- form inputs here -->

     <div class="form-actions"><button type="submit" data-default-message="Save Changes" data-inflight-message="Saving..." data-success-message="Saved!" class="coursera-save-button btn btn-primary" disabled="disabled">Saved!</button></div>

</form>
5♣
4♥
header.html2 stars

Handlebars Design Prototyping

<html>
<head>
  <style>
    .w100percent {
    }
    .w1280px {
    }
    .w900px {
    }
    .w768px {
    }
    .w480px {
4♥
3♠
visibleimages.js2 stars

Load Visible Images

  function loadVisibleImages() {
    var placeholders = {
      'meal': 'img/meal.png',
      'avatar': 'img/blankpic.png'
    };

    $('img').each(function() {
      var $img = $(this);
      var realUrl = $img.attr('data-src');
      if (!realUrl) return;

      // If the image is visible and in view, try to load the real image.
3♠
2♦
greasemonkey-exercises.txt2 stars

GreaseMonkey Exercises

GreaseMonkey

    Read this tutorial to learn how to make GreaseMonkey scripts for Firefox, you should have a basic script by the end.
    Read this article to learn how to get them working in Chrome and check yours works.


Amazon Linker
In this exercise, you’ll make a GreaseMonkey script that will run on Amazon product pages for movies and TV shows (e.g., The Matrix), and add a link to your favorite review site, like Rotten Tomatoes or MetaCritic. The steps:

    Make sure your script only runs on Amazon URLs.
    Verify that the page is in the "Movies & TV" department.
    Extract the movie's title from the page. Watch out for extra information in () and [] that isn't part of the title (e.g., the entry for "Batman Begins" is actually "Batman Begins [Blu-ray] (2005)").
2♦
A♦
googl.py1 stars

Shortening URLS using goo.gl

import cgi
import urllib, urllib2
import logging

from django.utils import simplejson

class Googl():
  def __init__(self, api_key):
    self.api_key = api_key
    self.base_url = 'https://www.googleapis.com/urlshortener/v1/url?key=%s' % self.api_key

  def shorten(self, long_url):
A♦
K♣
models.py1 stars

App Engine Photo Upload (with BlobStore)

from __future__ import with_statement
from google.appengine.ext import db, blobstore
from google.appengine.api import memcache, files, images

class Photo(db.Model):
  created         = db.DateTimeProperty(auto_now_add=True)
  updated         = db.DateTimeProperty(auto_now=True)
  blob_key        = blobstore.BlobReferenceProperty()
  url             = db.StringProperty()
  thumbnail_url   = db.StringProperty()

  def upload_blob(self, file):
K♣
Q♥
gistfile1.txt1 stars

Click/touchstart wrapper

function addClickHandler(dom, callback, logThis) {

    if (useTouchEvents()) {
      dom.each(function() {
        $(this).unbind('tap', callback);
        $(this).bind('tap', callback);

        $(this).bind('touchstart', function(e) {
          var item = e.currentTarget;
          if (ISTOUCHING) return;
          item.moved = false;
          ISTOUCHING = true;
Q♥
J♠
Makefile1 stars

Android PhoneGap Workflow

MAKEFLAGS = --no-print-directory --always-make
MAKE = make $(MAKEFLAGS)

BUILDDIR = ./.build

CLOSUREURL = http://closure-compiler.googlecode.com/files/compiler-latest.zip
CLOSUREDIR = $(BUILDDIR)/closure
CLOSUREFILE = $(CLOSUREDIR)/compiler.jar
YUIURL = http://yui.zenfs.com/releases/yuicompressor/yuicompressor-2.4.6.zip
YUIDIR = $(BUILDDIR)/yui
YUIFILE = $(YUIDIR)/yuicompressor-2.4.6/build/yuicompressor-2.4.6.jar
JSHINTURL = https://github.com/jshint/jshint/zipball/master
J♠
十♦
render_index.py1 stars

PhoneGap Index Renderer (Jinja2)

import sys

sys.path.append('/Library/Python/2.7/site-packages')

from jinja2 import Environment, FileSystemLoader

if __name__ == "__main__":
  env = Environment(loader=FileSystemLoader('application/templates/'))
  template = env.get_template('phonegap/index.html')
  print template.render(debug=False, mobile=True, native=True)
十♦
9♣
phonegap.html1 stars

Phonegap Index (Jinja2)

<!doctype html>
<html>
 <head>
  <meta name="viewport" content="initial-scale=1.0, user-scalable=no, width=device-width" />
  <meta name="apple-mobile-web-app-capable" content="yes" />
  <title>everyday.io</title>
  {% if g and g.debug %}
  <link rel="stylesheet" href="css/colorslider.css" />
  <link rel="stylesheet" href="css/dateinput.css" />
  <link rel="stylesheet" href="css/bootstrap-1.3.0.min.css">
  <link rel="stylesheet" href="css/phonegap.css" />
  {% else %}
9♣
8♥
touch.js1 stars

Touch/click events wrapper

  ISTOUCHING = false;

  function useTouchEvents() {
    return isTouchDevice();
  }

  function triggerClick(dom) {
    if (useTouchEvents()) {
      dom.trigger('tap');
    } else {
      dom.trigger('click');
    }
8♥
7♠
base_tests.py1 stars

Python Selenium Base TestCase

import unittest
import datetime
from sys import *

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait

import login_dom

class BaseTests(unittest.TestCase):
    driver = None
    waiter = None
7♠
6♦
fancybox.diff1 stars

Zepto + FancyBox Diffs

diff --git a/application/static/js/libs/jquery.fancybox.js b/application/static/js/libs/jquery.fancybox.js
index be77275..c1d74b7 100755
--- a/application/static/js/libs/jquery.fancybox.js
+++ b/application/static/js/libs/jquery.fancybox.js
@@ -359,7 +359,6 @@
 							this.style.visibility = 'inherit';
 						});
 					}
-
 					overlay.show();
 				}
 			} else {
6♦
5♣
zepto.js1 stars

Zepto Port (Bootstrap-friendly, Plugin-friendly, etc)

//     Zepto.js
//     (c) 2010, 2011 Thomas Fuchs
//     Zepto.js may be freely distributed under the MIT license.

(function(undefined){
  if (String.prototype.trim === undefined) // fix for iOS 3.2
    String.prototype.trim = function(){ return this.replace(/^\s+/, '').replace(/\s+$/, '') };

  // For iOS 3.x
  // from https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/reduce
  if (Array.prototype.reduce === undefined)
    Array.prototype.reduce = function(fun){
5♣
4♥
hearty.user.js1 stars

TxJS Hearty User Extension

// Also requires jQuery pasted in the top in Chrome

function loadHearts() {
	$('#speakers').hide();
	$('#scene').hide();
	
	$('#schedule td').each(function() { 
		var $talkCell = $(this);
		var rateLink = $talkCell.find('a');
		if (!rateLink.length) return;
		
		var id = rateLink.attr('href').split('/t/')[1];
4♥
3♠
nutrition.xml1 stars

Sample XML: Foods

<?xml version="1.0"?>
<nutrition>
<daily-values>
	<total-fat units="g">65</total-fat>
	<saturated-fat units="g">20</saturated-fat>
	<cholesterol units="mg">300</cholesterol>
	<sodium units="mg">2400</sodium>
	<carb units="g">300</carb>
	<fiber units="g">25</fiber>
	<protein units="g">50</protein>
</daily-values>
<food>
3♠
2♦
thirdparties.js1 stars

isDefined

  // isDefined(window, 'google');
  // isDefined(window, 'google.maps.places'); 
  var isDefined = function(parent, name) {
      var parts   = name.split('.');
      var part    = parts.shift();
      var cur     = parent;

      while (part) {
        if (cur[part]) {
            cur = cur[part];
            part = parts.shift();
        } else {
2♦
A♦
project.txt1 stars

JavaScript Data Visualization Project

Project: JavaScript Data Visualization

The purpose of this project is to find some interesting data, display that data in JS, give users a way to do calculations on it, and visualize it using graphics libraries and/or APIs.

    Create a folder for the project.
    Initialize a git repository for the project and create a Github repo for it, so that you can push commits to the remote Github repo. Commit for each stage of the project (or even more often than that, if you’d like)
        See slides: Git
    Find an interesting dataset in some sort of text format (XML, JSON, CSV, etc). Store the dataset in your project folder. Truncate it to a reasonable length if it’s very long (i.e. 1000 rows). Some possible sources are:
        https://explore.data.gov/
        http://www.usgovxml.com/
        http://geocommons.com/
    Create an empty webpage and load the dataset into your webpage using an AJAX or JSONP request.
A♦
K♣
player.js1 stars

Changing Playback of HTML5 Video

    this.isSetSpeedEnabled = function() {
        if(typeof(this.mediaElement) === 'object'
                && this.mediaElement !== null
                && typeof(this.mediaElement.playbackRate) === 'number'
                && this.mediaElement.playbackRate > 0){
            return true;
        }
        else{
            return false;
        } 
    }
K♣
Q♥
gistfile1.txt1 stars

Detect and change playbackRate


    /** function set_speed(speed)
      * Set the video speed
      *
      * @param double speed - target speed
      *
      * @return void
      */
    this.is_set_speed_enabled = function(){
        if(typeof(this.mediaelement_media) === 'object'
                && this.mediaelement_media !== null
                && typeof(this.mediaelement_media.playbackRate) === 'number'
Q♥
J♠
linkify.js1 stars

linkify


  function linkifyText(string){
    if (string) {
      string = string.replace(
        /((https?\:\/\/)|(www\.))(\S+)(\w{2,4})(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/gi,
        function(url){
            var full_url = url;
            if (!full_url.match('^https?:\/\/')) {
                full_url = 'http://' + full_url;
            }
            return '<a target="_blank" href="' + full_url + '">' + url.substring(0, Math.min(full_url.length, 20)) + '...</a>';
        });
J♠
十♦
gistfile1.txt1 stars

truncate based off offscreen

  function truncateText(string, nMaxChars) {
    if (string.length <= nMaxChars)
      return string;

    var xMaxFit = nMaxChars - 3;
    var xTruncateAt = string.lastIndexOf(' ', xMaxFit);
    if (xTruncateAt == -1 || xTruncateAt < nMaxChars / 2)
      xTruncateAt = xMaxFit;

    return string.substr(0, xTruncateAt) + "&hellip;";
  }
十♦
9♣
gistfile1.js0 stars

Finding component in maps api geocoder result

function findComponent(result, type) {
      for (var i = 0; i , result.address_components.length; i++) {
        var component = result.address_components[i];
        for (var j = 0; j < component.types.length; j++) {
          if (component.types[j] == type) {
            return component.short_name;
          }
        }
      }
    }
9♣
8♥
jsonp.js0 stars

jsonp + lscache

//Lightweight JSONP fetcher - www.nonobtrusive.com
var JSONP = (function(){
  var counter = 0, head, query, key, window = this;
  function load(url) {
    var script = document.createElement('script'),
      done = false;
    script.src = url;
    script.async = true;

    script.onload = script.onreadystatechange = function() {
      if ( !done && (!this.readyState || this.readyState === "loaded" || this.readyState === "complete") ) {
        done = true;
8♥
7♠
deferred.py0 stars

Deferred handler for Flask

"""
deferred.py

Primary App Engine app handler

"""

import sys, os

package_dir = "packages"

# Allow unzipped packages to be imported
7♠
6♦
gistfile1.js0 stars

Loading fonts CSS

  var fontNum = 0;
  var maxCharacters = 1730;
  var cssBaseUrl = 'http://fonts.googleapis.com/css?family=';

  function addCss() {
    var cssUrl = cssBaseUrl;
    while ((cssUrl.length + allFontNames[fontNum].length) < maxCharacters && (fontNum < (allFontNames.length-1))) {
      // dont load khmer, no point
      if (fonts[allFontNames[fontNum]].subsets[0] != 'khmer') {
        cssUrl += escape(allFontNames[fontNum]) + '|';
      }
      fontNum++;
6♦
5♣
index_renderer.py0 stars

Jinja2 Rendering Templates

from jinja2 import Environment, FileSystemLoader

if __name__ == "__main__":
  env = Environment(loader=FileSystemLoader('application/templates/'))
  template = env.get_template('phonegap/index.html')
  print template.render()

5♣
4♥
Makefile0 stars

My phonegap/web/gae makefile

# Javascript/CSS Compressor Makefile - By Benjamin "balupton" Lupton (MIT Licenced)

MAKEFLAGS = --no-print-directory --always-make
MAKE = make $(MAKEFLAGS)

BUILDDIR = ./.build

CLOSUREURL = http://closure-compiler.googlecode.com/files/compiler-latest.zip
CLOSUREDIR = $(BUILDDIR)/closure
CLOSUREFILE = $(CLOSUREDIR)/compiler.jar
YUIURL = http://yui.zenfs.com/releases/yuicompressor/yuicompressor-2.4.6.zip
YUIDIR = $(BUILDDIR)/yui
4♥
3♠
views.py0 stars

Facebook logout (Flask)

@login_required
def handle_logout():
    import facebook

    if g.user.facebook_id:
        base_domain     = util.get_base_domain()
        default_fb_data = FB_DATA['appspot.com']
        fb_app_id       = FB_DATA.get(base_domain, default_fb_data).get('appid')
        fb_app_secret   = FB_DATA.get(base_domain, default_fb_data).get('appsecret')
        cookie = facebook.get_user_from_cookie(request.cookies, fb_app_id, fb_app_secret)

        if cookie:
3♠
2♦
dimensions.js0 stars

outer/inner/Width/Height


  ['width', 'height'].forEach(function(dimension) {
    var offset, Dimension = dimension.replace(/./, function(m) { return m[0].toUpperCase() });
    $.fn['outer' + Dimension] = function(margin) {
      var elem = this;
      if (elem) {
        var size = elem[dimension]();
        var sides = {'width': ['left', 'right'], 'height': ['top', 'bottom']};
        sides[dimension].forEach(function(side) {
          size += parseInt(elem.css('padding-' + side), 10);
          size += parseInt(elem.css('border-' + side + '-width'), 10);
          if (margin) size += parseInt(elem.css('margin-' + side), 10);
2♦
A♦
dateinput.js0 stars

Zepto jQueryTools DateInput

/**
 * @license                                     
 * jQuery Tools @VERSION Dateinput - <input type="date" /> for humans
 * 
 * NO COPYRIGHTS OR LICENSES. DO WHAT YOU LIKE.
 * 
 * http://flowplayer.org/tools/form/dateinput/
 *
 * Since: Mar 2010
 * Date: @DATE 
 */
(function($, undefined) {   
A♦
K♣
flask_tests.py0 stars

Python Flask App Engine Unit Test

import unittest
import sys
import os
import logging

# locate app-engine SDK
AE_PATH = "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/"

# path to app code
APP_PATH = os.path.abspath(".")

# load the AE paths (as stolen from dev_appserver.py)
K♣
Q♥
log.html0 stars

Jinja2 Template Example (Everyday.io Log)

{% extends "yourbase.html" %}

{% block subheader %}
<div class="page-header">
<h1>
  <span id="log-date">{{ title }}</span>
  <a data-tooltip="Change the date" id="log-date-button" href="javascript:void(0);" style="margin-left: 10px;"><img src="img/calendar.png"></a>
</h1>
</div>
{% endblock %}

{% block content %}
Q♥
J♠
facebook_tests.py0 stars

Facebook Python Selenium Tests

import base_tests
import dom_helper
import facebook_dom

class FacebookTests(base_tests.BaseTests):

    @classmethod
    def setUpClass(cls):
        super(StartTests, cls).setUpClass()
        StartTests.clear_data()

    def setUp(self):
J♠
十♦
facebook_dom.py0 stars

Facebook Selenium Dom Helper Functions

import dom_helper
import test_defaults

FBEMAIL     = '#email'
FBPASS      = '#pass'
FBLOGIN     = 'input[name="login"]'
FBGRANT     = 'input[name="grant_clicked"]'

class FacebookDom(dom_helper.DomHelper):

    def is_window_open(self):
        return len(self.driver.window_handles) > 1
十♦
9♣
gistfile1.js0 stars

Moving average calculation

      // Calculate moving average
      var averageData = [];
      var lastValue = null;
      var movingAverage = null;
      for (var i = 0; i < dates.length; i++) {
        var value = measurementData[i] || missingData[i];
        if (!movingAverage) {
          movingAverage = value;
        } else {
          movingAverage = ((value - movingAverage)/7) + movingAverage;
        }
        if (isNaN(movingAverage)) {
9♣
8♥
Makefile0 stars

Phonegap/App Engine Makefile

# Javascript/CSS Compressor Makefile - By Benjamin "balupton" Lupton (MIT Licenced)

MAKEFLAGS = --no-print-directory --always-make
MAKE = make $(MAKEFLAGS)

BUILDDIR = ./.build

CLOSUREURL = http://closure-compiler.googlecode.com/files/compiler-latest.zip
CLOSUREDIR = $(BUILDDIR)/closure
CLOSUREFILE = $(CLOSUREDIR)/compiler.jar
YUIURL = http://yui.zenfs.com/releases/yuicompressor/yuicompressor-2.4.6.zip
YUIDIR = $(BUILDDIR)/yui
8♥
7♠
fancybox.js0 stars

Zepto + FancyBox

/*
 * FancyBox - jQuery Plugin
 * Simple and fancy lightbox alternative
 *
 * Examples and documentation at: http://fancybox.net
 *
 * Copyright (c) 2008 - 2010 Janis Skarnelis
 * That said, it is hardly a one-person project. Many people have submitted bugs, code, and offered their advice freely. Their support is greatly appreciated.
 *
 * Version: 1.3.4 (11/11/2010)
 * Requires: jQuery v1.3+
 *
7♠
6♦
mobilelogpage.js0 stars

MobileLogPage

  MobileLogPage.prototype = MobilePage.prototype;

  MobileLogPage.prototype.getForm = function() {
    return ED.shared.logForms[this.id];
  };

  MobileLogPage.prototype.getErrorDOM = function() {
    return $('#mobile-' + this.id + '-page .log-error');
  };

  MobileLogPage.prototype.getErrorMessage = function() {
    return $('#mobile-' + this.id + '-page .log-error-message');
6♦
5♣
impl_example.js0 stars

impl example

  function MobilePage() {
    this.initialized = false;
  }

  MobilePage.prototype.setup = function() {};

  MobilePage.prototype.setupOnce = function() {
    if (this.initialized !== true) this.setup();
    this.initialized = true;
  };

  MobilePage.prototype.show = function() {};
5♣
4♥
mobile_photo.js0 stars

Getting/rotating photos in PhoneGap

  function getPhoto(mealId, sourceType, saveOnSuccess) {
    var $mealDiv = $('#log-meal-' + mealId);
    var $mealImg = $mealDiv.find('.log-meal-photo-button img');
    var $quickpicStatus = $('#mobile-quickpic-link span');

    function resetQuickPicStatus() {
      $quickpicStatus.html('').addClass('icon-camera');
    }


    function getDataUri(imageUri, onSuccess, onFail) {
      var $img = $('<img/>');
4♥
3♠
util_log.js0 stars

ED.util.log()

  // Logging
  var allLogs = [];
  function log(something) {
    // Store
    var storedSomething = something;
    if (window.JSON) {
      storedSomething = JSON.stringify(something);
    }
    storedSomething = 'LOG @ ' + new Date().toString() + ': ' + truncateText(storedSomething, 200);
    allLogs.push(storedSomething);
    $('#mobile-feedback-logs').html(allLogs.reverse().join('<br>'));
3♠
2♦
phonegap.html0 stars

Android localStorage in PhoneGap timing test

<!doctype html>
<html>
 <head>
  <meta name="viewport" content="initial-scale=1.0, user-scalable=no, width=device-width" />
  <meta name="apple-mobile-web-app-capable" content="yes" />
  <base target="_blank">
  <title>eatdifferent</title>
  <script>
  var ED = ED || {};
  ED.VERSION = '36'
  ED.timing = (function() {
    var timingOn  = true;
2♦
A♦
CameraLauncher.java0 stars

PhoneGap Camera.java (Hacked up)

/*
       Licensed to the Apache Software Foundation (ASF) under one
       or more contributor license agreements.  See the NOTICE file
       distributed with this work for additional information
       regarding copyright ownership.  The ASF licenses this file
       to you under the Apache License, Version 2.0 (the
       "License"); you may not use this file except in compliance
       with the License.  You may obtain a copy of the License at

         http://www.apache.org/licenses/LICENSE-2.0

       Unless required by applicable law or agreed to in writing,
A♦
K♣
IframeViewer.js0 stars

IframeViewer for Brackets

/*
 * Copyright (c) 2012 Adobe Systems Incorporated. All rights reserved.
 *  
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"), 
 * to deal in the Software without restriction, including without limitation 
 * the rights to use, copy, modify, merge, publish, distribute, sublicense, 
 * and/or sell copies of the Software, and to permit persons to whom the 
 * Software is furnished to do so, subject to the following conditions:
 *  
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
K♣
Q♥
editorhack.diff0 stars

EditorManager + CommandManager

diff --git a/src/brackets.js b/src/brackets.js
index 39e30b2..cb20367 100644
--- a/src/brackets.js
+++ b/src/brackets.js
@@ -199,7 +199,8 @@ define(function (require, exports, module) {
                     //{"Ctrl-X": Commands.EDIT_CUT},
                     //{"Ctrl-C": Commands.EDIT_COPY}, 
                     //{"Ctrl-V": Commands.EDIT_PASTE},
-
+                    {"Ctrl-I": Commands.SHOW_OTHER_STUFF},
+                  
                     {"Ctrl-A": Commands.EDIT_SELECT_ALL},
Q♥
J♠
gistfile1.txt0 stars

JS Errors and Causes

These arent always the causes, just in the cases I saw them.

Unexpected {    
Cause: mismatched curly braces, count your braces

Unexpected token . 
Cause: var buttonDiv.bla = 4

SyntaxError: Unexpected string  
Cause: var bla = bla + ' hi ' ' you'

Cannot read property stuff of null
J♠
十♦
render_handlebars.py0 stars

Handlebars Folder Renderer Script

import os

input_path  = 'application/templates'
output_path = 'application/static/js/templates'

os.system('mkdir %s' % output_path)
dir_list = os.listdir(input_path)
for file_name in dir_list:
    if file_name.endswith('.handlebars'):
        cmd = 'handlebars %s/%s -f %s/%s' % (input_path, file_name, output_path, file_name.replace('handlebars', 'js'))
        print cmd
        os.system(cmd)
十♦
9♣
idiomatic_JA.md0 stars

Idiomatic.JS, japanese translation from Mashashi

                                                                     
                                                                     
                                                                     
                                             
#慣用的なJavaScript, 矛盾しないコードの書き方


## これは現在使っているドキュメントです。私達が使っているコードを向上させるためのアイディアはいつでも歓迎です。意見を述べるには、fork, clone, branch, commit, push, pull requestなどをしてください。



9♣
8♥
restaurants.xml0 stars

Sample XML: Seattle Restaurants

<?xml version="1.0"?>
<restaurants>
<restaurant name="Pan Africa Market" address="1521 1st Ave, Seattle, WA" lat="47.608940" lng="-122.340141" type="sitdown"/>
<restaurant name="Buddha Thai & Bar" address="2222 2nd Ave, Seattle, WA" lat="47.613590" lng="-122.344391" type="bar"/>
<restaurant name="The Melting Pot" address="14 Mercer St, Seattle, WA" lat="47.624561" lng="-122.356445" type="sitdown"/>
<restaurant name="Ipanema Grill" address="1225 1st Ave, Seattle, WA" lat="47.606365" lng="-122.337654" type="sitdown"/>
<restaurant name="Sake House" address="2230 1st Ave, Seattle, WA" lat="47.612823" lng="-122.345673" type="bar"/>
<restaurant name="Crab Pot" address="1301 Alaskan Way, Seattle, WA" lat="47.605961" lng="-122.340363" type="sitdown"/>
<restaurant name="Mama's Mexican Kitchen" address="2234 2nd Ave, Seattle, WA" lat="47.613976" lng="-122.345467" type="bar"/>
<restaurant name="Wingdome" address="1416 E Olive Way, Seattle, WA" lat="47.617214" lng="-122.326584" type="bar"/>
<resta
8♥
7♠
test_hand_val.py0 stars

Basic unit test of function in Python

import unittest

BUST_VAL = 22
ACE_HIGH = 11
ACE_LOW = 1

def calculate_hand_val(low_hand_val, num_aces):
    hand_val = low_hand_val

    for x in range(1, num_aces + 1):
        if (hand_val + (ACE_HIGH - ACE_LOW)) < BUST_VAL:
            print 'adding high'
7♠
6♦
table.html0 stars

An accessible table


<style type="text/css">
  .hidden-accessible {
    position: absolute !important;
    height: 1px; width: 1px;
    overflow: hidden;
    clip: rect(1px 1px 1px 1px); /* IE6, IE7 */
    clip: rect(1px, 1px, 1px, 1px);
  }
</style>

<table>
6♦