<commit_before>var gulp = require('gulp');
var gautoprefixer = require('gulp-autoprefixer');
var mbfiles = require('main-bower-files');
var gflatten = require('gulp-flatten');
var gchanged = require('gulp-changed');
var gcssvalidator = require('gulp-css-validator');
var gcsslint = require('gulp-csslint');
var ginject = require('gulp-inject');
var gminifycss = require('gulp-minify-css');
var gminifyhtml = require('gulp-minify-html');
var gngannotate = require('gulp-ng-annotate');
var gorder = require('gulp-order');
var gplumber = require('gulp-plumber');
var rimraf = require('rimraf');
var gstripdebug = require('gulp-strip-debug');
var gstylus = require('gulp-stylus');
var gtodo = require('gulp-todo');
var guglify = require('gulp-uglify');
var gusing = require('gulp-using');
var gutil = require('gulp-util');
var eventstream = require('event-stream');
var imageminpngcrush = require('imagemin-pngcrush');

gulp.task('default', function() {
  // place code for your default task here
});
<commit_msg>commiting gulp<commit_after>var gulp = require('gulp');

var gautoprefixer = require('gulp-autoprefixer');
var mbowerfiles = require('main-bower-files');
var gflatten = require('gulp-flatten');
var gchanged = require('gulp-changed');
var gcssvalidator = require('gulp-css-validator');
var gcsslint = require('gulp-csslint');
var ginject = require('gulp-inject');
var gminifycss = require('gulp-minify-css');
var gminifyhtml = require('gulp-minify-html');
var gngannotate = require('gulp-ng-annotate');
var gorder = require('gulp-order');
var gplumber = require('gulp-plumber');
var rimraf = require('rimraf');
var gstripdebug = require('gulp-strip-debug');
var gstylus = require('gulp-stylus');
var gtodo = require('gulp-todo');
var guglify = require('gulp-uglify');
var gusing = require('gulp-using');
var gutil = require('gulp-util');
var eventstream = require('event-stream');
var imageminpngcrush = require('imagemin-pngcrush');

var cache = require('gulp-cache');
var concat = require('gulp-concat');
var imagemin = require('gulp-imagemin');
var jshint = require('gulp-jshint');
var rename = require('gulp-rename');
var connect = require('gulp-connect');
var indexTemplate = "index_template.html";

gulp.task('default', function() {
  // place code for your default task here
});

var p = {

	htmlTemplate: indexTemplate,

	// ----- Our libs ------
	libsCss: [

		// 'dist/lib/font-awesome/**/*.css',
		// 'dist/lib/sass-bootstrap/**/*.css',
		// 'dist/lib/leaflet/**/*.css',
		// 'dist/lib/**/*.css'
	],
	libsJs: [

		// 'dist/lib/es5-shim/es5-shim.js',
		// 'dist/lib/json3/**/*.js',
		// 'dist/lib/proj4/**/*.js',
		// 'dist/lib/jquery/**/*.js',
		// 'dist/lib/sass-bootstrap/**/*.js',
		// 'dist/lib/leaflet/**/*.js',
		// "dist/lib/Leaflet.NonTiledLayer/NonTiledLayer.js", // Must come before NonTiledLayer.WMS.js
		// 'dist/lib/GeoJSON.WFS/index.js',
		// 'dist/lib/leaflet.draw/**/*.js',

		// 'dist/lib/Leaflet.GeometryUtil/dist/*.js',
		// 'dist/lib/Leaflet.Snap/*.js',

		// //'dist/lib/Leaflet.print-smap/**/*.js',
		// 'lib/jquery.mobile.custom/jquery.mobile.custom.min.js', // Note! I could not install this lib with bower.
		// 'dist/lib/**/*.js',
		// '!dist/lib/leaflet-dist/*', // messing up
		// '!dist/lib/libs.js', // Don't use previously compressed lib file
		// '!dist/lib/add-to-homescreen/**/*.js', // Exclude this lib, it's optionally injected by plugin
		// 'core/js/buildLibOverrides.js'  // Override libs js
	],

	// ----- Our code ------
	ourSass: [

		// // first
		// // "core/css/**/*.scss",

		// // last
		// "plugins/**/*.scss"

	],
	ourStylus: [

		// // first
		// "core/css/global.styl",
		// "core/css/**/*.styl",

		// // last
		// "plugins/**/*.styl"
	],
	ourCss: [

		// // first
		// "core/css/app.css",
		// "core/css/lib-overrides.css",

		// // last
		// "plugins/**/*.css",
		// "!plugins/**/_*.css",
		// "!plugins/DrawSmap/*.css",
		// "!plugins/Edit/**/*.css",
		// "!plugins/MyPlugin/**/*.css",
		// "!plugins/SideBars/**/*.css",
		// "!plugins/ThreeD/**/*.css",
		// "!plugins/WorkshopPlugin/**/*.css",
		// "core/css/themes/theme-malmo.css"

	],
	ourJs: [

		// "core/js/smap.js",
		// "core/js/*.js",
		// "plugins/**/*.js",
		// "!plugins/**/_*.js",
		// "!plugins/Test/**/*.js",
		// "!plugins/DrawSmap/*.js",
		// "!plugins/Edit/**/*.js",
		// "!plugins/MyPlugin/**/*.js",
		// "!plugins/SideBars/**/*.js",
		// "!plugins/ThreeD/**/*.js",
		// "!plugins/WorkshopPlugin/**/*.js",
		// "!plugins/PluginTemplate.js",
		// '!core/js/buildLibOverrides.js'

	]

};

// ----- Tasks ------

gulp.task('cleancode', function() {
	gulp.src("dist/css").pipe(rimraf());
	gulp.src("dist/js").pipe(rimraf());
	gulp.src("dist/*.*").pipe(rimraf());
});
gulp.task('cleanlib', function() {
	return gulp.src("dist/lib").pipe(rimraf());
});
// gulp.task('cleanconfigs', function() {
// 	return gulp.src("dist/configs").pipe(rimraf());
// });
gulp.task('cleanimg', function() {
	return gulp.src("dist/img").pipe(rimraf());
});
gulp.task('clean', ['cleanlib', 'cleancode']); // Clean all but img folder
gulp.task('cleantotal', function() {
	return gulp.src("dist").pipe(rimraf());
});

var onError = function(err) {
	console.log(err.toString());
  	// this.emit('end');
};

gulp.task('move', function() {
	gulp.src("plugins/**/resources/**/*") //, {base: "./"})
		.pipe(flatten())
		// .pipe(using())
		.pipe(gulp.dest("dist/resources/"));
});

// ---- Our code -----

gulp.task('ourcsscompile', function() {
	var streamStylus = gulp.src(p.ourStylus, {base: "./"})
			.pipe(stylus()).on("error", onError);
	// var streamSass = gulp.src(p.ourSass, {base: "./"})
	// 		.pipe(sass());

	return es.merge(streamStylus) //streamSass)
			.pipe(autoprefixer("last 1 version", "> 1%", "ie 8", "ie 9")) //.on('error', onError)
			.pipe(gulp.dest("."));
});

gulp.task('ourcss', ['ourcsscompile'], function() {
	return gulp
		.src(p.ourCss)
		.pipe(autoprefixer("last 1 version", "> 1%", "ie 8", "ie 9"))
		// .pipe(csslint())
		// .pipe(csslint.reporter())
		// .pipe(order(p.ourCss.concat("*")))
		.pipe(concat('smap.css'))
		.pipe(mincss())
		// .pipe(rename("smap.css"))
		.pipe(gulp.dest("dist"))
		.pipe(connect.reload());
});

gulp.task('ourjs', function() {
	return gulp
		.src(p.ourJs)
		// .pipe(order(p.ourJs.concat("*")))
		// .pipe(jshint())
  // 		.pipe(jshint.reporter('default'))
  		.pipe(stripDebug())
  		.pipe(ngAnnotate())
		.pipe(uglify())  // {mangle: false}
  		.pipe(concat("smap.js"))
		.pipe(gulp.dest("dist"))
		.pipe(connect.reload());
});

gulp.task('images', function () {
	var imgDest = 'dist/img';
    return gulp
    	.src(['img/**/*.{png,jpg,jpeg,gif}'])
    	.pipe(changed(imgDest))
        .pipe(imagemin({
        	progressive: true,
            svgoPlugins: [{removeViewBox: false}],
            use: [pngcrush()]
        }))
        .pipe(gulp.dest(imgDest));
});

gulp.task('configs', function() {
	return gulp
		.src(['examples/configs/*.js'])
			.pipe(gulp.dest("dist/configs"));
});

// gulp.task('movecssresources', function() {
// 	return gulp
// 		.src(['dist/lib/**/*.{eot,svg,ttf,woff,png,jpg,jpeg,gif}'], {base: "dist/lib/", ignorePath: "dist/lib/"})
// 		.pipe(gulp.dest("dist/css"));
// });

gulp.task('libs', function() {
	return gulp.src(bowerfiles(), {base: "./bower_components/"}).pipe(gulp.dest("dist/lib"));  // {checkExistence: true}
});

gulp.task('libsjs', ["libs"], function() {
	return gulp
		.src(p.libsJs)
		// .pipe(order(p.libsJs.concat("*")))
		// .pipe(using())
  		.pipe(concat("libs.js"))
		// .pipe(uglify())  // {mangle: false}
		.on('error', onError)
		.pipe(gulp.dest("dist"));
});

// gulp.task('libscss', function() {
// 	return gulp
// 		.src(p.libsCss)
// 		.pipe(autoprefixer("last 1 version", "> 1%", "ie 8"))
// 		// .pipe(csslint())
// 		// .pipe(csslint.reporter())
// 		// .pipe(order(p.ourCss.concat("*")))
// 		.pipe(concat('libs.css'))
// 		.pipe(mincss())
// 		// .pipe(rename("smap.css"))
// 		.pipe(gulp.dest("dist"));
// });

gulp.task('htmlinjectdev', ["libs", "ourcss", "ourjs"], function() {
	var libsJs = p.libsJs.slice(0, p.libsJs.length-1); // we don't want buildLibOverrides.js because we don't compress libs
	var devSrcs = libsJs.concat(p.libsCss).concat(p.ourJs).concat(p.ourCss);
	return gulp
		.src(p.htmlTemplate)
		.pipe(inject(gulp.src(devSrcs, {read: false}), {addRootSlash: false}))
		.pipe(rename("dev.html"))
		.pipe(gulp.dest("."));
});

gulp.task('htmlinjectprod', ["libsjs", "ourcss", "ourjs"], function() {
	var libsJs = ["dist/libs.js"]; //p.libsJs
	var libsCss = p.libsCss; //["dist/libs.css"];
	var prodSrcs = libsJs.concat(libsCss).concat("dist/smap.js").concat("dist/smap.css");
	return gulp
		.src(p.htmlTemplate)
		.pipe(inject(gulp.src(prodSrcs, {read: false}), {addRootSlash: false, ignorePath: 'dist/'}))
		.pipe(rename("index.html"))
		.pipe(gulp.dest("dist"));
});
gulp.task('htmlinject', ["htmlinjectdev", "htmlinjectprod"]);

gulp.task('htmlcompress', ['htmlinject'], function() {
	return gulp
		.src('index.html')
		.pipe(minhtml())
		.pipe(gulp.dest("."));
});
gulp.task('html', ["htmlcompress"]);

// Build our code (during dev)
gulp.task('ourcode', ["ourcss", "ourjs"]);  // "move"

gulp.task('_full', ["images", "html", "move", "configs"]);

// Clean the code and libs and then make a full build (i.e. fetch libs to dist,
// compile js/css/sass/styl and insert into HTML).
gulp.task('full', ["cleancode"], function() {
	return gulp.start("_full");
});

gulp.task('fullmalmo', ["cleancode"], function() {
	// p.ourSass.unshift("dist/lib/malmo_shared_assets/**/*.scss");  In case we need advanced sass functionality from malmo assets
	p.htmlTemplate = indexTemplate;
	return gulp.start("_full");
});

// Note! It's wise to run <bower update> before resetting. Thereby, packages will be
// up to date and any missing files (however that might happen...) will be filled-in.
gulp.task('reset', ["cleantotal", "full"]);

gulp.task('webserver', function() {
	connect.server({
		port: 8090,
		livereload: true
	});
});

gulp.task('watch', function() {
	var css = p.ourCss.concat(p.ourStylus).concat(p.ourSass);
	// var js = p.ourJs.concat("dist/configs/*.js");
	var tasks = ["ourcode"];
	gulp.start(tasks); // Start by running once
	return gulp.watch(css, tasks);
});

gulp.task('watchweb', ["webserver", "watch"]); // Allow auto-publishing whenever something changes

gulp.task('default', ["watch"]); // Note! <gulp> is same as <gulp default>

<|endoftext|>


<commit_before>function calculateLabel ($obj, possibilities){
	var possibilities = (typeof possibilities == 'object') ? possibilities : ["te_name", "name", "title", "id"];
	var eventLabel = null;
	for (var i = 0; i <= (possibilities.length - 1); i++) {
		var possibility = $obj.attr(possibilities[i]);
		if(possibility && possibility.length){
			eventLabel = possibility;
			break;
		}
	}
	return eventLabel;
}
function pushEvent ( eventInfo ) {
	if(window.trackeverything.settings.debug){ console.log(eventInfo); }
	_gaq.push(eventInfo);
}
jQuery(function ($){
	$.expr[':'].external = function(obj){
		return !obj.href.match(/^mailto:/) && !obj.href.match(/^#:/) && (obj.hostname.replace(/^www\./i, '') != document.location.hostname.replace(/^www\./i, ''));
	};

	for (var i = window.trackeverything.dictionary.length - 1; i >= 0; i--) {
		$(window.trackeverything.dictionary[i].selector).attr("te_name", window.trackeverything.dictionary[i].name);
	}
	if(window.trackeverything.settings.forms){
		$("form").on("submit.jqte.jqtedefault", function (e) {
			var formLabel = calculateLabel($(this));

			var eventInfo = ['_trackEvent', 'Form', 'Submission'];
			if(formLabel != null){
				eventInfo.push(formLabel);
			}
			if(!(window.trackeverything.settings.search == false && $(this).attr("method") && $(this).attr("method").toLowerCase() == "get" && $(this).children("input[name=s]").length)){
				pushEvent(eventInfo);
			}
		});
		if(window.trackeverything.settings.debug){
			$("form").addClass("track-everything track-everything-default track-everything-form");
		}
	}
	if(window.trackeverything.settings.outbound){
		$("a:external").on("click.jqte.jqtedefault keypress.jqte.jqtedefault", function (e) {
			var eventLabel = calculateLabel($(this), ["te_name", "href"]);

			var eventInfo = ['_trackEvent', 'Link', 'Outbound', eventLabel, null, true];
			pushEvent(eventInfo);
		});
		if(window.trackeverything.settings.debug){
			$("a:external").addClass("track-everything track-everything-default track-everything-outbound");
		}
	}
	if(window.trackeverything.settings.email){
		$('a[href^="mailto:"]').on("click.jqte.jqtedefault keypress.jqte.jqtedefault", function (e) {
			var eventLabel = $(this).attr("href").substring(7);

			var eventInfo = ['_trackEvent', 'Link', 'Email', eventLabel];
			pushEvent(eventInfo);
		});
		if(window.trackeverything.settings.debug){
			$('a[href^="mailto:"]').addClass("track-everything track-everything-default track-everything-email");
		}
	}
	for (var i = window.trackeverything.special.length - 1; i >= 0; i--) {
		var $special = window.trackeverything.special[i];
		$($special.selector).off(".jqtedefault");
		if(window.trackeverything.settings.debug){
			$($special.selector).addClass("track-everything track-everything-special").removeClass("track-everything-default");
		}
		var events = [];
		for (var j = $special.events.length - 1; j >= 0; j--) {
			events.push($special.events[j] + ".jqte.jqtespecial");
		}
		$($special.selector).on(events.join(" "), function () {
			if($special.name.length){
				$(this).attr("te_oname", $special.name);
			}
			var eventLabel = calculateLabel($(this), ["te_oname", "te_name", "name", "title", "id", "href"]);
			var eventInfo = ['_trackEvent', $special.category, $special.action, eventLabel];

			pushEvent(eventInfo);
		});
	};
});<commit_msg>Namespaced Javascript Functions<commit_after>function ethoseoteCalculateLabel ($obj, possibilities){
	var possibilities = (typeof possibilities == 'object') ? possibilities : ["te_name", "name", "title", "id"];
	var eventLabel = null;
	for (var i = 0; i <= (possibilities.length - 1); i++) {
		var possibility = $obj.attr(possibilities[i]);
		if(possibility && possibility.length){
			eventLabel = possibility;
			break;
		}
	}
	return eventLabel;
}
function ethoseotePushEvent ( eventInfo ) {
	if(window.trackeverything.settings.debug){ console.log(eventInfo); }
	_gaq.push(eventInfo);
}
jQuery(function ($){
	$.expr[':'].external = function(obj){
		return !obj.href.match(/^mailto:/) && !obj.href.match(/^#:/) && (obj.hostname.replace(/^www\./i, '') != document.location.hostname.replace(/^www\./i, ''));
	};

	for (var i = window.trackeverything.dictionary.length - 1; i >= 0; i--) {
		$(window.trackeverything.dictionary[i].selector).attr("te_name", window.trackeverything.dictionary[i].name);
	}
	if(window.trackeverything.settings.forms){
		$("form").on("submit.jqte.jqtedefault", function (e) {
			var formLabel = ethoseoteCalculateLabel($(this));

			var eventInfo = ['_trackEvent', 'Form', 'Submission'];
			if(formLabel != null){
				eventInfo.push(formLabel);
			}
			if(!(window.trackeverything.settings.search == false && $(this).attr("method") && $(this).attr("method").toLowerCase() == "get" && $(this).children("input[name=s]").length)){
				ethoseotePushEvent(eventInfo);
			}
		});
		if(window.trackeverything.settings.debug){
			$("form").addClass("track-everything track-everything-default track-everything-form");
		}
	}
	if(window.trackeverything.settings.outbound){
		$("a:external").on("click.jqte.jqtedefault keypress.jqte.jqtedefault", function (e) {
			var eventLabel = ethoseoteCalculateLabel($(this), ["te_name", "href"]);

			var eventInfo = ['_trackEvent', 'Link', 'Outbound', eventLabel, null, true];
			ethoseotePushEvent(eventInfo);
		});
		if(window.trackeverything.settings.debug){
			$("a:external").addClass("track-everything track-everything-default track-everything-outbound");
		}
	}
	if(window.trackeverything.settings.email){
		$('a[href^="mailto:"]').on("click.jqte.jqtedefault keypress.jqte.jqtedefault", function (e) {
			var eventLabel = $(this).attr("href").substring(7);

			var eventInfo = ['_trackEvent', 'Link', 'Email', eventLabel];
			ethoseotePushEvent(eventInfo);
		});
		if(window.trackeverything.settings.debug){
			$('a[href^="mailto:"]').addClass("track-everything track-everything-default track-everything-email");
		}
	}
	for (var i = window.trackeverything.special.length - 1; i >= 0; i--) {
		var $special = window.trackeverything.special[i];
		$($special.selector).off(".jqtedefault");
		if(window.trackeverything.settings.debug){
			$($special.selector).addClass("track-everything track-everything-special").removeClass("track-everything-default");
		}
		var events = [];
		for (var j = $special.events.length - 1; j >= 0; j--) {
			events.push($special.events[j] + ".jqte.jqtespecial");
		}
		$($special.selector).on(events.join(" "), function () {
			if($special.name.length){
				$(this).attr("te_oname", $special.name);
			}
			var eventLabel = ethoseoteCalculateLabel($(this), ["te_oname", "te_name", "name", "title", "id", "href"]);
			var eventInfo = ['_trackEvent', $special.category, $special.action, eventLabel];

			ethoseotePushEvent(eventInfo);
		});
	};
});<|endoftext|>


<commit_before>import React from 'react'
import Logo from './logo'
import styled from 'styled-components'
import Link from 'gatsby-link'
import { TypingText } from '../Intro'
import {MobileHide} from '../MobileHide'

const Sidebar = ({ className, color, bgColor }) => (

    <Link to="/">
      <Logo fill={color || "#000"} hoverfill={color ? '#CCC' : "#0000FF"} />
    </Link>
    <MobileHide>

Half of Eight

<TypingText />

    </MobileHide>

)

const SidebarStyled = styled(Sidebar)`
  min-width: 250px;
  width: 15.5%;
  height: 100%;
  position: fixed;
  padding-top: 26px;
  flex-shrink: 0;
  flex-grow: 0;
  text-align: center;
  font-size: 13px;
  background-color: ${props => props.bgColor ? props.bgColor : '#fff'};
  line-height: 1.7;
  max-width: 320px;
  p {
    color: ${props => props.color ? props.color : '#001d60'};
  }
  ${props => props.color ?
  `a{
    color ${props.color}
  }`
  : ''}
  @media(max-width: 560px){
    position: relative;
    width: 100%;
    margin: 0 auto;
  }
`

export default SidebarStyled
<commit_msg>no typing text<commit_after>import React from 'react'
import Logo from './logo'
import styled from 'styled-components'
import Link from 'gatsby-link'
import { TypingText } from '../Intro'
import {MobileHide} from '../MobileHide'

const Sidebar = ({ className, color, bgColor }) => (

    <Link to="/">
      <Logo fill={color || "#000"} hoverfill={color ? '#CCC' : "#0000FF"} />
    </Link>
    <MobileHide>

Half of Eight

    </MobileHide>

)

const SidebarStyled = styled(Sidebar)`
  min-width: 250px;
  width: 15.5%;
  height: 100%;
  position: fixed;
  padding-top: 26px;
  flex-shrink: 0;
  flex-grow: 0;
  text-align: center;
  font-size: 13px;
  background-color: ${props => props.bgColor ? props.bgColor : '#fff'};
  line-height: 1.7;
  max-width: 320px;
  p {
    color: ${props => props.color ? props.color : '#001d60'};
  }
  ${props => props.color ?
  `a{
    color ${props.color}
  }`
  : ''}
  @media(max-width: 560px){
    position: relative;
    width: 100%;
    margin: 0 auto;
  }
`

export default SidebarStyled
<|endoftext|>


<commit_before>import Imgflipper from 'imgflipper';
import nconf from 'nconf';

import sentry from './config/sentry';
import { drama as _drama, emoji as _emoji, memes } from '../data';

const imgflipper = new Imgflipper(nconf.get('IMGFLIP_USERNAME'), nconf.get('IMGFLIP_PASSWORD'));

function drama(bot, msg, suffix) {
  let rand = Math.floor(Math.random() * _drama.length);
  if (suffix && suffix >= 0 && suffix <= (_drama.length - 1)) {
    bot.sendMessage(msg.channel, _drama[suffix]);
  } else {
    bot.sendMessage(msg.channel, _drama[rand]);
  }
}

function emoji(bot, msg, suffix) {
  let rand = Math.floor(Math.random() * _emoji.length);
  if (suffix && suffix >= 0 && suffix <= (_emoji.length - 1)) {
    bot.sendMessage(msg.channel, _emoji[suffix]);
  } else {
    bot.sendMessage(msg.channel, _emoji[rand]);
  }
}

function meme(bot, msg, suffix) {
  if (!nconf.get('IMGFLIP_USERNAME') || !nconf.get('IMGFLIP_PASSWORD')) {
    bot.sendMessage(msg.channel, 'Please setup imgflip in config.js to use the **`!meme`** command.');
    return;
  }

  let usage_message = 'Usage: **`!meme`** `meme name` `"top text"` `"bottom text"`\nWrite **`!memelist`** for a list of meme names.';
  if (!suffix) {
    bot.sendMessage(msg.channel, usage_message);
    return;
  }
  let tags = suffix.split('"');
  let memetype = tags[0].trim();

  // Still send blank meme, but also send usage message.
  if (!tags[1] && !tags[3]) bot.sendMessage(msg.channel, usage_message);

  imgflipper.generateMeme(memes[memetype], tags[1] ? tags[1] : ' ', tags[3] ? tags[3] : ' ', (err, image) => {
    if (err) {
      sentry.captureError(err);
      bot.sendMessage(msg.channel, `Error: ${err.message}`);
    } else {
      bot.sendMessage(msg.channel, image);
    }
  });
}

export default {
  drama,
  emoji,
  emojis: emoji,
  meme,
  memes: meme
};
<commit_msg>don't send error on no text memes<commit_after>import Imgflipper from 'imgflipper';
import nconf from 'nconf';

import sentry from './config/sentry';
import { drama as _drama, emoji as _emoji, memes } from '../data';

const imgflipper = new Imgflipper(nconf.get('IMGFLIP_USERNAME'), nconf.get('IMGFLIP_PASSWORD'));

function drama(bot, msg, suffix) {
  let rand = Math.floor(Math.random() * _drama.length);
  if (suffix && suffix >= 0 && suffix <= (_drama.length - 1)) {
    bot.sendMessage(msg.channel, _drama[suffix]);
  } else {
    bot.sendMessage(msg.channel, _drama[rand]);
  }
}

function emoji(bot, msg, suffix) {
  let rand = Math.floor(Math.random() * _emoji.length);
  if (suffix && suffix >= 0 && suffix <= (_emoji.length - 1)) {
    bot.sendMessage(msg.channel, _emoji[suffix]);
  } else {
    bot.sendMessage(msg.channel, _emoji[rand]);
  }
}

function meme(bot, msg, suffix) {
  if (!nconf.get('IMGFLIP_USERNAME') || !nconf.get('IMGFLIP_PASSWORD')) {
    bot.sendMessage(msg.channel, 'Please setup imgflip in config.js to use the **`!meme`** command.');
    return;
  }

  let usage_message = 'Usage: **`!meme`** `meme name` `"top text"` `"bottom text"`\nWrite **`!memelist`** for a list of meme names.';
  if (!suffix) {
    bot.sendMessage(msg.channel, usage_message);
    return;
  }
  let tags = suffix.split('"');
  let memetype = tags[0].trim();

  // Still send blank meme, but also send usage message.
  if (!tags[1] && !tags[3]) bot.sendMessage(msg.channel, usage_message);

  imgflipper.generateMeme(memes[memetype], tags[1] ? tags[1] : ' ', tags[3] ? tags[3] : ' ', (err, image) => {
    if (err) {
      if (err.message !== 'No texts supplied') sentry.captureError(err);
      bot.sendMessage(msg.channel, `Error: ${err.message}`);
    } else {
      bot.sendMessage(msg.channel, image);
    }
  });
}

export default {
  drama,
  emoji,
  emojis: emoji,
  meme,
  memes: meme
};
<|endoftext|>


<commit_before>if(typeof environment == 'undefined') environment = 'default'; // Override me!

(function() {

  var results;

  var currentPackage;
  var currentMethod;
  var currentGroup;
  var currentArgs;

  var syncTestsRunning;
  var asyncTestsRunning;

  var startTime;
  var runtime;

  // The global context
  var globalContext = typeof global !== 'undefined' ? global : this;

  function package(name, fn) {
    // Set up results if there are none.
    if(!results) {
      results = [];
      syncTestsRunning = true;
      asyncTestsRunning = 0;
      testsStarted();
    }
    var split = name.split(' | ');
    currentPackage = {
      name: split[0],
      subname: split[1],
      assertions: 0,
      failures: []
    };
    // Run the tests...
    try {
      fn.call();
    } catch(e) {
      console.info(e.stack);
    }
    results.push(currentPackage);
    currentPackage = null;
  }

  function async(fn) {
    asyncTestsRunning++;
    setTimeout(wrapTestingScope(function() {
      fn(wrapTestingScope, asyncFinish);
    }), 1);
  }

  function asyncFinish() {
    asyncTestsRunning--;
    checkCanFinish();
  }

  function checkCanFinish() {
    if(!syncTestsRunning && asyncTestsRunning === 0) {
      testsFinished();
    }
  }

  function syncTestsFinished() {
    syncTestsRunning = false;
    checkCanFinish();
  }

  function wrapTestingScope(fn) {
    var cachedPackage = currentPackage;
    var cachedMethod = currentMethod;
    var cachedArgs = currentArgs;
    return function () {
      currentPackage = cachedPackage;
      currentMethod = cachedMethod;
      currentArgs = cachedArgs;
      fn.apply(this, arguments);
    }
  }

  function method(name) {
    var fn = arguments[arguments.length - 1];
    if(arguments.length === 3) {
      currentArgs = arguments[1];
    } else {
      currentArgs = [];
    }
    currentMethod = name;
    fn(async);
    currentMethod = null;
    currentArgs   = [];
  }

  function group(name, fn) {
    currentGroup = name;
    fn();
    currentGroup = null;
  }

  function test(subject) {
    var args, expected, message;
    switch(arguments.length) {
      case 2:
        expected = arguments[1];
        message  = subject;
        break;
      case 3:
        expected = arguments[1];
        message  = arguments[2];
        break;
      case 4:
        args     = arguments[1];
        expected = arguments[2];
        message  = arguments[3];
        break;
    }
    equal(run(subject, null, args), expected, message);
  }

  function run(subject, method, args) {
    method = method || currentMethod;
    args = args || currentArgs || [];
    if(Sugar.noConflict) {
      if(!subjectIsClass(subject)) {
        args = [subject].concat(Array.prototype.slice.call(args));
      }
      return Sugar[currentPackage.name][method].apply(null, args);
    } else {
      var globalObject = globalContext[currentPackage.name], fn;
      if(subject && subject[method]) {
        // If the method exists on the subject, then it is the target
        // to be called. This is true in normal prototype testing as well
        // as for Sugar defined objects such as Ranges and Extended Objects.
        fn = subject[method];
      } else if(globalObject.prototype[method]) {
        // If the method is defined on the prototype of the global object,
        // then use it instead. This is the case when testing methods not
        // originally defined on the prototype of the subject, such as string
        // methods on numbers, undefined/null, etc.
        fn = globalObject.prototype[method];
      } else {
        // Otherwise assume a class method of the global object.
        fn = globalObject[method];
      }
      return fn.apply(subject, args);
    }
  }

  function getProperty(subject, prop) {
    if(Sugar.noConflict) {
      return Sugar[currentPackage.name][prop];
    } else {
      return subject[prop];
    }
  }

  function subjectIsClass(subject) {
    switch(subject) {
      case Boolean:
      case Number:
      case String:
      case Array:
      case Object:
      case Date:
      case RegExp:
      case Function:
        return true;
    }
    return false;
  }

  function raisesError(fn, message, errorType) {
    var err, message = getFullMessage(message) + ' should raise an error';
    try {
      fn.call();
    } catch(e) {
      err = e;
    }
    if(!errorType) {
      equal(!!err, true, message, 1);
    } else {
      equal(err instanceof errorType, true, message, 1);
    }
  }

  function getFullMessage(tail) {
    var msg = '';
    var title = currentMethod || currentGroup;
    if(title) {
      msg += title;
      if(currentArgs && currentArgs.length > 0) {
        msg += '('+ currentArgs.join(',') +')';
      }
      msg += ' | ';
    }
    msg += tail;
    return msg;
  }

  // Runner methods

  function equal(actual, expected, message, stack) {
    currentPackage.assertions++;
    if(!isEqual(actual, expected)) {
      addFailure(actual, expected, getFullMessage(message), stack);
    }
  }

  function notEqual(actual, expected, message) {
    equal(actual !== expected, true, message + ' | strict equality', 1);
  }

  function testsStarted() {
    if(environment == 'node') {
      console.info('\n----------------------- STARTING TESTS ----------------------------\n');
    }
    startTime = new Date();
  }

  function testsFinished() {
    runtime = new Date() - startTime;
    if(environment == 'node') {
      // will exit now setting the status to the number of failed tests
      process.exit(logResults());
    } else if(this.testsFinishedCallback) {
      this.testsFinishedCallback(results, runtime);
    }
    results = [];
  }

  function logResults() {
    var i, j, failure, totalAssertions = 0, totalFailures = 0;
    for (i = 0; i < results.length; i += 1) {
      totalAssertions += results[i].assertions;
      totalFailures += results[i].failures.length;
      for(j = 0; j < results[i].failures.length; j++) {
        failure = results[i].failures[j];
        console.info('\n'+ (j + 1) + ') Failure:');
        console.info(failure.message);
        console.info('Expected: ' + JSON.stringify(failure.expected) + ' but was: ' + JSON.stringify(failure.actual));
        console.info('File: ' + failure.file + ', Line: ' + failure.line, ' Col: ' + failure.col + '\n');
      }
    };
    var time = (runtime / 1000);
    console.info(results.length + ' tests, ' + totalAssertions + ' assertions, ' + totalFailures + ' failures, ' + time + 's\n');
    return totalFailures;
  }

  function addFailure(actual, expected, message, stack, warning) {
    var meta = getMeta(stack);
    currentPackage.failures.push({
      actual: actual,
      expected: expected,
      message: message,
      file: meta.file,
      line: meta.line,
      col: meta.col,
      warning: !!warning
    });
  }

  function getMeta(stack) {
    var level = 4;
    if(stack !== undefined) {
      level += stack;
    }
    var e = new Error();
    if(!e.stack) {
      return {};
    }
    var s = e.stack.split(/@|^\s+at/m);
    var match = s[level].match(/(.+\.js):(\d+)(?::(\d+))?/);
    if(!match) match = [];
    return { file: match[1], line: match[2], col: match[3] };
  }

  // Equality test methods.

  function isEqual(one, two) {
    var type, klass;

    type = typeof one;

    if(type === 'string' || type === 'boolean' || one == null) {
      return one === two;
    } else if(type === 'number') {
      return typeof two === 'number' && ((isNaN(one) && isNaN(two)) || one === two);
    }

    klass = Object.prototype.toString.call(one);

    if(klass === '[object Date]') {
      return one.getTime() === two.getTime();
    } else if(klass === '[object RegExp]') {
      return String(one) === String(two);
    } else if(klass === '[object Array]') {
      return arrayIsEqual(one, two);
    } else if((klass === '[object Object]' || klass === '[object Arguments]') && ('hasOwnProperty' in one) && type === 'object') {
      return objectIsEqual(one, two);
    } else if(klass === '[object Number]' && isNaN(one) && isNaN(two)) {
      return true;
    }

    return one === two;
  }

  // Arrays and objects must be treated separately here because in IE arrays with undefined
  // elements will not pass the .hasOwnProperty check. For example [undefined].hasOwnProperty('0')
  // will report false.
  function arrayIsEqual(one, two) {
    var i, result = true;
    if(!one || !two) {
      return false;
    }
    arrayEach(one, function(a, i) {
      if(!isEqual(one[i], two[i])) {
        result = false;
      }
    });
    return result && one.length === two.length;
  }

  function objectIsEqual(one, two) {
    var onep = 0, twop = 0, key;
    if(one && two) {
      for(key in one) {
        if(!one.hasOwnProperty(key)) continue;
        onep++;
        if(!isEqual(one[key], two[key])) {
          return false;
        }
      }
      for(key in two) {
        if(!two.hasOwnProperty(key)) continue;
        twop++;
      }
    }
    return onep === twop && String(one) === String(two);
  }

  function equalWithMargin(actual, expected, margin, message) {
    equal((actual > expected - margin) && (actual < expected + margin), true, message, null, 1);
  }

  // Sets are equal, but order may differ
  function setIsEqual(a, b, message) {
    equal(sortOnStringValue(a), sortOnStringValue(b), message);
  }

  function sortOnStringValue(arr) {
    return arr.sort(function(a, b) {
      var aStr = getStringValueForObject(a);
      var bStr = getStringValueForObject(b);
      if(aStr === bStr) return 0;
      return aStr < bStr ? -1 : 1;
    });
  }

  function getStringValueForObject(obj) {
    var type = typeof obj, str;
    if(type === 'object') {
      str = 'obj:';
      for (var key in obj) {
        if(!obj.hasOwnProperty(key)) continue;
        str += key + getStringValueForObject(obj[key]);
      }
      return str;
    } else {
      return 'pri:' + type + String(obj);
    }
  }

  // Iteration methods

  // Tests may include sparse arrays, so need a way to iterate
  // over them safely here.
  function arrayEach(arr, fn, sparse) {
    var length = arr.length, i = 0;
    while(i < length) {
      if(!(i in arr)) {
        return iterateOverArray(arr, fn, i);
      } else if(fn.call(arr, arr[i], i, arr) === false) {
        break;
      }
      i++;
    }
  }

  function iterateOverArray(arr, fn, fromIndex) {
    var indexes = [], i;
    for(i in arr) {
      if(isArrayIndex(arr, i) && i >= fromIndex) {
        indexes.push(parseInt(i));
      }
    }
    arrayEach(indexes.sort(), function(index) {
      return fn.call(arr, arr[index], index, arr);
    });
    return arr;
  }

  function isArrayIndex(arr, i) {
    return i in arr && (i >>> 0) == i && i != 0xffffffff;
  }

  if(typeof console === 'undefined') {
    var consoleFn = function() {
      var messages = Array.prototype.slice.call(arguments);
      messages = messages.map(function(arg) {
        return String(arg);
      })
      $('<p/>').text(messages.join(',')).appendTo(document.body);
    }
    console = {
      log: consoleFn,
      info: consoleFn
    }
  }

  this.syncTestsFinished = syncTestsFinished;
  this.equalWithMargin = equalWithMargin;
  this.raisesError = raisesError;
  this.getProperty = getProperty;
  this.setIsEqual = setIsEqual;
  this.notEqual = notEqual;
  this.package = package;
  this.method = method;
  this.group = group;
  this.equal = equal;
  this.test = test;
  this.run = run;

})();
<commit_msg>rewriting globals to not use this. as it causes errors not to be thrown in IE7<commit_after>if(typeof environment == 'undefined') environment = 'default'; // Override me!

(function() {

  var results;

  var currentPackage;
  var currentMethod;
  var currentGroup;
  var currentArgs;

  var syncTestsRunning;
  var asyncTestsRunning;

  var startTime;
  var runtime;

  // The global context
  var globalContext = typeof global !== 'undefined' ? global : this;

  // Global methods.
  // BE CAREFUL HERE! If you declare these using window.xxx or
  // some form thereof they will not trigger errors in IE7!

  package = function (name, fn) {
    // Set up results if there are none.
    if(!results) {
      results = [];
      syncTestsRunning = true;
      asyncTestsRunning = 0;
      testsStarted();
    }
    var split = name.split(' | ');
    currentPackage = {
      name: split[0],
      subname: split[1],
      assertions: 0,
      failures: []
    };
    // Run the tests...
    try {
      fn.call();
    } catch(e) {
      console.info(e.stack);
    }
    results.push(currentPackage);
    currentPackage = null;
  }

  syncTestsFinished = function () {
    syncTestsRunning = false;
    checkCanFinish();
  }

  equal = function (actual, expected, message, stack) {
    currentPackage.assertions++;
    if(!isEqual(actual, expected)) {
      addFailure(actual, expected, getFullMessage(message), stack);
    }
  }

  equalWithMargin = function (actual, expected, margin, message) {
    equal((actual > expected - margin) && (actual < expected + margin), true, message, null, 1);
  }

  // Sets are equal, but order may differ
  setIsEqual = function (a, b, message) {
    equal(sortOnStringValue(a), sortOnStringValue(b), message);
  }

  notEqual = function (actual, expected, message) {
    equal(actual !== expected, true, message + ' | strict equality', 1);
  }

  raisesError = function (fn, message, errorType) {
    var err, message = getFullMessage(message) + ' should raise an error';
    try {
      fn.call();
    } catch(e) {
      err = e;
    }
    if(!errorType) {
      equal(!!err, true, message, 1);
    } else {
      equal(err instanceof errorType, true, message, 1);
    }
  }

  getProperty = function (subject, prop) {
    if(Sugar.noConflict) {
      return Sugar[currentPackage.name][prop];
    } else {
      return subject[prop];
    }
  }

  method = function (name) {
    var fn = arguments[arguments.length - 1];
    if(arguments.length === 3) {
      currentArgs = arguments[1];
    } else {
      currentArgs = [];
    }
    currentMethod = name;
    fn(async);
    currentMethod = null;
    currentArgs   = [];
  }

  group = function (name, fn) {
    currentGroup = name;
    fn();
    currentGroup = null;
  }

  test = function (subject) {
    var args, expected, message;
    switch(arguments.length) {
      case 2:
        expected = arguments[1];
        message  = subject;
        break;
      case 3:
        expected = arguments[1];
        message  = arguments[2];
        break;
      case 4:
        args     = arguments[1];
        expected = arguments[2];
        message  = arguments[3];
        break;
    }
    equal(run(subject, null, args), expected, message);
  }

  run = function (subject, method, args) {
    method = method || currentMethod;
    args = args || currentArgs || [];
    if(Sugar.noConflict) {
      if(!subjectIsClass(subject)) {
        args = [subject].concat(Array.prototype.slice.call(args));
      }
      return Sugar[currentPackage.name][method].apply(null, args);
    } else {
      var globalObject = globalContext[currentPackage.name], fn;
      if(subject && subject[method]) {
        // If the method exists on the subject, then it is the target
        // to be called. This is true in normal prototype testing as well
        // as for Sugar defined objects such as Ranges and Extended Objects.
        fn = subject[method];
      } else if(globalObject.prototype[method]) {
        // If the method is defined on the prototype of the global object,
        // then use it instead. This is the case when testing methods not
        // originally defined on the prototype of the subject, such as string
        // methods on numbers, undefined/null, etc.
        fn = globalObject.prototype[method];
      } else {
        // Otherwise assume a class method of the global object.
        fn = globalObject[method];
      }
      return fn.apply(subject, args);
    }
  }

  function async(fn) {
    asyncTestsRunning++;
    setTimeout(wrapTestingScope(function() {
      fn(wrapTestingScope, asyncFinish);
    }), 1);
  }

  function asyncFinish() {
    asyncTestsRunning--;
    checkCanFinish();
  }

  function checkCanFinish() {
    if(!syncTestsRunning && asyncTestsRunning === 0) {
      testsFinished();
    }
  }

  function wrapTestingScope(fn) {
    var cachedPackage = currentPackage;
    var cachedMethod = currentMethod;
    var cachedArgs = currentArgs;
    return function () {
      currentPackage = cachedPackage;
      currentMethod = cachedMethod;
      currentArgs = cachedArgs;
      fn.apply(this, arguments);
    }
  }

  function subjectIsClass(subject) {
    switch(subject) {
      case Boolean:
      case Number:
      case String:
      case Array:
      case Object:
      case Date:
      case RegExp:
      case Function:
        return true;
    }
    return false;
  }

  function getFullMessage(tail) {
    var msg = '';
    var title = currentMethod || currentGroup;
    if(title) {
      msg += title;
      if(currentArgs && currentArgs.length > 0) {
        msg += '('+ currentArgs.join(',') +')';
      }
      msg += ' | ';
    }
    msg += tail;
    return msg;
  }

  function testsStarted() {
    if(environment == 'node') {
      console.info('\n----------------------- STARTING TESTS ----------------------------\n');
    }
    startTime = new Date();
  }

  function testsFinished() {
    runtime = new Date() - startTime;
    if(environment == 'node') {
      // will exit now setting the status to the number of failed tests
      process.exit(logResults());
    } else if(this.testsFinishedCallback) {
      this.testsFinishedCallback(results, runtime);
    }
    results = [];
  }

  function logResults() {
    var i, j, failure, totalAssertions = 0, totalFailures = 0;
    for (i = 0; i < results.length; i += 1) {
      totalAssertions += results[i].assertions;
      totalFailures += results[i].failures.length;
      for(j = 0; j < results[i].failures.length; j++) {
        failure = results[i].failures[j];
        console.info('\n'+ (j + 1) + ') Failure:');
        console.info(failure.message);
        console.info('Expected: ' + JSON.stringify(failure.expected) + ' but was: ' + JSON.stringify(failure.actual));
        console.info('File: ' + failure.file + ', Line: ' + failure.line, ' Col: ' + failure.col + '\n');
      }
    };
    var time = (runtime / 1000);
    console.info(results.length + ' tests, ' + totalAssertions + ' assertions, ' + totalFailures + ' failures, ' + time + 's\n');
    return totalFailures;
  }

  function addFailure(actual, expected, message, stack, warning) {
    var meta = getMeta(stack);
    currentPackage.failures.push({
      actual: actual,
      expected: expected,
      message: message,
      file: meta.file,
      line: meta.line,
      col: meta.col,
      warning: !!warning
    });
  }

  function getMeta(stack) {
    var level = 4;
    if(stack !== undefined) {
      level += stack;
    }
    var e = new Error();
    if(!e.stack) {
      return {};
    }
    var s = e.stack.split(/@|^\s+at/m);
    var match = s[level].match(/(.+\.js):(\d+)(?::(\d+))?/);
    if(!match) match = [];
    return { file: match[1], line: match[2], col: match[3] };
  }

  // Equality test methods.

  function isEqual(one, two) {
    var type, klass;

    type = typeof one;

    if(type === 'string' || type === 'boolean' || one == null) {
      return one === two;
    } else if(type === 'number') {
      return typeof two === 'number' && ((isNaN(one) && isNaN(two)) || one === two);
    }

    klass = Object.prototype.toString.call(one);

    if(klass === '[object Date]') {
      return one.getTime() === two.getTime();
    } else if(klass === '[object RegExp]') {
      return String(one) === String(two);
    } else if(klass === '[object Array]') {
      return arrayIsEqual(one, two);
    } else if((klass === '[object Object]' || klass === '[object Arguments]') && ('hasOwnProperty' in one) && type === 'object') {
      return objectIsEqual(one, two);
    } else if(klass === '[object Number]' && isNaN(one) && isNaN(two)) {
      return true;
    }

    return one === two;
  }

  // Arrays and objects must be treated separately here because in IE arrays with undefined
  // elements will not pass the .hasOwnProperty check. For example [undefined].hasOwnProperty('0')
  // will report false.
  function arrayIsEqual(one, two) {
    var i, result = true;
    if(!one || !two) {
      return false;
    }
    arrayEach(one, function(a, i) {
      if(!isEqual(one[i], two[i])) {
        result = false;
      }
    });
    return result && one.length === two.length;
  }

  function objectIsEqual(one, two) {
    var onep = 0, twop = 0, key;
    if(one && two) {
      for(key in one) {
        if(!one.hasOwnProperty(key)) continue;
        onep++;
        if(!isEqual(one[key], two[key])) {
          return false;
        }
      }
      for(key in two) {
        if(!two.hasOwnProperty(key)) continue;
        twop++;
      }
    }
    return onep === twop && String(one) === String(two);
  }

  function sortOnStringValue(arr) {
    return arr.sort(function(a, b) {
      var aStr = getStringValueForObject(a);
      var bStr = getStringValueForObject(b);
      if(aStr === bStr) return 0;
      return aStr < bStr ? -1 : 1;
    });
  }

  function getStringValueForObject(obj) {
    var type = typeof obj, str;
    if(type === 'object') {
      str = 'obj:';
      for (var key in obj) {
        if(!obj.hasOwnProperty(key)) continue;
        str += key + getStringValueForObject(obj[key]);
      }
      return str;
    } else {
      return 'pri:' + type + String(obj);
    }
  }

  // Iteration methods

  // Tests may include sparse arrays, so need a way to iterate
  // over them safely here.
  function arrayEach(arr, fn, sparse) {
    var length = arr.length, i = 0;
    while(i < length) {
      if(!(i in arr)) {
        return iterateOverArray(arr, fn, i);
      } else if(fn.call(arr, arr[i], i, arr) === false) {
        break;
      }
      i++;
    }
  }

  function iterateOverArray(arr, fn, fromIndex) {
    var indexes = [], i;
    for(i in arr) {
      if(isArrayIndex(arr, i) && i >= fromIndex) {
        indexes.push(parseInt(i));
      }
    }
    arrayEach(indexes.sort(), function(index) {
      return fn.call(arr, arr[index], index, arr);
    });
    return arr;
  }

  function isArrayIndex(arr, i) {
    return i in arr && (i >>> 0) == i && i != 0xffffffff;
  }

  if(typeof console === 'undefined') {
    var consoleFn = function() {
      var messages = Array.prototype.slice.call(arguments);
      messages = messages.map(function(arg) {
        return String(arg);
      })
      $('<p/>').css({
        fontFamily: 'monospace',
        fontSize: '12px'
      }).text(messages.join(',')).appendTo(document.body);
    }
    console = {
      log: consoleFn,
      info: consoleFn
    }
  }

})();
<|endoftext|>


<commit_before>module.exports = function(route, app) {
app.get(route + ':person', function(req, res) {
    // Retrieve a given player's scores
    if (!fs.existsSync(filePath)) res.end("Cannot access scores");
    else {
        scoresString = fs.readFileSync(filePath);
        scores = JSON.parse(scoresString);  // inspect(scores['Dan'])
        result = JSON.stringify(scores[req.params.person] || {})
        res.end(result);
        }
    });
app.post(route + ':person', function(req, res) {
    // Update a player's posted scores
    if (!fs.existsSync(filePath)) res.end("Cannot access scores");
    else {
        scoresString = scores = newScores = LastReq = null;
        LastReq = req;
        scoresString = fs.readFileSync(filePath);
        scores = JSON.parse(scoresString);
        newScores = req.body;
        scores[req.params.person] = newScores;
        fs.writeFileSync(filePath, JSON.stringify(scores));
        res.end("written new scores for " + req.params.person + " " + inspect(req.body));
        }
    });
app.get(route, function(req, res) {
    // Retrieve all scores as a pile of JSON text
    if (pastMonth != new Date().getMonth()) {
        // reset scores at the end of the month
        fs.writeFileSync(filePath, '{}');
        pastMonth = new Date().getMonth()
        }
    if (!fs.existsSync(filePath)) fs.writeFileSync(filePath, '{}');
    var content = fs.readFileSync(filePath);
    res.end(content);
    });
};

pastMonth = new Date().getMonth();
process.env.PWD;  // can print the process working directory
path = require('path');
inspect = require('util').inspect;
fs = require('fs');
localFileName = 'QBFHighScores.json';
filePath = path.join(process.env.WORKSPACE_LK, localFileName);

// to reset scores:  fs.writeFileSync(filePath, '{}')
<commit_msg>QBF server update<commit_after>function doChecks() {
    // make sure our file exissts
    if (!fs.existsSync(filePath)) fs.writeFileSync(filePath, '{}');
    // reset scores at the end of the month
    if (pastMonth != new Date().getMonth()) {
        fs.writeFileSync(filePath, '{}');
        pastMonth = new Date().getMonth()
        }
    };
// --------

module.exports = function(route, app) {
app.get(route + ':person', function(req, res) {
    // Retrieve a given player's scores
    doChecks();
    scoresString = fs.readFileSync(filePath);
    scores = JSON.parse(scoresString);  // inspect(scores['Dan'])
    result = JSON.stringify(scores[req.params.person] || {})
    res.end(result);
    });
app.post(route + ':person', function(req, res) {
    // Update a player's posted scores
    doChecks();
    scoresString = scores = newScores = LastReq = null;
    LastReq = req;
    scoresString = fs.readFileSync(filePath);
    scores = JSON.parse(scoresString);
    newScores = req.body;
    scores[req.params.person] = newScores;
    fs.writeFileSync(filePath, JSON.stringify(scores));
    res.end("written new scores for " + req.params.person + " " + inspect(req.body));
    });
app.get(route, function(req, res) {
    // Retrieve all scores as a pile of JSON text
    doChecks();
    var content = fs.readFileSync(filePath);
    res.end(content);
    });
};

//  Initial settings
pastMonth = new Date().getMonth();
process.env.PWD;  // can print the process working directory
path = require('path');
inspect = require('util').inspect;
fs = require('fs');
localFileName = 'QBFHighScores.json';
filePath = path.join(process.env.WORKSPACE_LK, localFileName);
<|endoftext|>


<commit_before>

/// Shared menu bar code
var menuBar =
                        '
'+
                          ''+
                           'Favorite'+
                        '
'+
                        '
'+
                            ''+
                           'Africa'+
                        '
'+
                        '
'+
                            ''+
                           'U.S.A'+
                        '
'+
                        '
'+
                            ''+
                           'Antarcita'+
                        '
'+
                           '
'+
                          ''+
                           'Asia'+
                        '
'+
                         '
'+
                          ''+
                           'Animal'+
                        '
'+
                         '
'+
                          ''+
                           'Awesome'+
                        '
'+
                         '
'+
                          ''+
                           'Body'+
                        '
'+
                        '
'+
                          ''+
                           'Celebrity'+
                        '
'+
                         '
'+
                          ''+
                           'Companies'+
                        '
'+
                        '
'+
                          ''+
                           'Drug'+
                        '
'+
                         '
'+
                          ''+
                           'Food'+
                        '
'+
                         '
'+
                          ''+
                           'History'+
                        '
'+
                         '
'+
                          ''+
                           'Random'+
                        '
'+
                         '
'+
                          ''+
                           'Technology'+
                        '
'+
                        '
'+
                          ''+
                           'Science'+
                        '
'+

                         '
'+
                          ''+
                           'Settings'
                        /*
                        '
'+
                         '
'+
                          ''+
                           'Univers'+
                        '
' */

$(".side-menu").append(menuBar);

var bottombar = ''+
                    ''+
                    ''+
                    ''

$(".toolbar-inner").prepend(bottombar);

//// Scared functionality code

/// Scared functionality for the side menu bar

//opening the panels
 $$('.open-left-panel').on('click', function (e) {
        // 'left' position to open Left panel
        myApp.openPanel('left');
        mySwiper.lockSwipes();
    });

// closing the panels
  $$('.panel-close').on('click', function (e) {
    myApp.closePanel();
    mySwiper.unlockSwipes();
    });

///  Share fact to social media
function shareFact(){
    var imageLink;
        console.log("Calling from CapturePhoto");
        navigator.screenshot.save(function(error, res){
            if(error){
                console.log(error);
            }else{
                $(".sharing").fadeIn(500).fadeOut(3000);
                console.log('ok',res.filePath);
                imageLink = res.filePath;
                window.plugins.socialsharing.share(null,null, 'file://'+imageLink, null);

            }
        }, 'jpg',100,'myScreenShot');
    }

// Function that allow you to copy the text
function copyToClipboard(element) {
  var $temp = $("<input>");
  $("body").append($temp);
  $temp.val($(element).text()).select();
  document.execCommand("copy");
  $temp.remove();
}

$(".fa-files-o").click(function(){
    copyToClipboard(".swiper-slide-active");
    $(".text-copied").fadeIn(500).fadeOut(3000);

});

/// Code used to update the heart icon base on the data-favorite value

function slideChecker(){
  if($(".swiper-slide-active").attr("data-favorite")=="false"){

         $("#bottom-btn-favorite-hidden").css("color","white");

    }
    else if($(".swiper-slide-active").attr("data-favorite")=="true"){
         $("#bottom-btn-favorite-hidden").css("color","red");
    }
    }

function favoriteFact(){
$(document).ready(function(){

if($(".swiper-slide-active").attr("data-favorite")=="false")
    { /// check to see the slide data favorite (is not added to favorite)
/// adding it to favorite

    var fact_ID = $(".swiper-slide-active").attr("id") //  (true,false) getting fact id name which will be used to help control heart color and data favorite

    var fact_Value = $(".swiper-slide-active").attr("data-fact") ///  (fact number to reference text) get fact data number which will help reference the text

    var KeyValue = $(".swiper-slide-active").text();  // getting fact text value

    $(".swiper-slide-active").attr("data-favorite",true); // setting favorite data value to true

    $("#bottom-btn-favorite-hidden").css("color","red");  // changing the color of the white heart instantly

    localStorage.setItem(`${fact_ID}`,$("#"+`${fact_ID}`).attr("data-favorite")); // favorite heart color

    localStorage.setItem(`${fact_Value}`,`${KeyValue}`) /// favorite text value;

    }

/// removing it from favorite
else if($(".swiper-slide-active").attr("data-favorite")=="true")
{
    var fact_ID = $(".swiper-slide-active").attr("id") // getting fact id name

    var fact_Value = $(".swiper-slide-active").attr("data-fact")

    $(".swiper-slide-active").attr("data-favorite",false);

    $("#bottom-btn-favorite-hidden").css("color","white");

    localStorage.removeItem(`${fact_ID}`);

    localStorage.removeItem(`${fact_Value}`)

}

})
;}
var temp = true;
mySwiper.on('slideChangeEnd',function(){

    $("#bottom-btn-copy-hidden").fadeIn(100);
    $("#bottom-btn-forward-hidden").fadeIn(100);
    $("#bottom-btn-favorite-hidden").fadeIn(100);
    $("#bottom-btn-share-hidden").fadeIn(100);
    $(".fa-microphone").css("opacity","1");
    if(temp){
       mySwiper.removeSlide(0);
        temp = false;
    }

    if(localStorage.getItem("checkBoxValue")=="true"){
        text_to_speak();
    }

})

// Handle Cordova Device Ready Event

  $("#bottom-btn-forward-hidden").click(function(){
      mySwiper.slideNext();
  });

 function text_to_speak(){
         mySwiper.lockSwipes();
        var speak = $(".swiper-slide-active").text();
          TTS
            .speak(speak, function () {
             mySwiper.unlockSwipes();
        }, function (reason) {

        });

 }

 ///// Code for ad

var ad_units = {
			anroid : {
				banner : "234772"

			}
		};

//

var adid = ( /(android)/i.test(navigator.userAgent) ) ? ad_units.android : ad_units.ios;

if(mMedia) mMedia.createBanner({
        adId : adid.banner,
        autoShow : true,
        overlap : true,
        position : mMedia.AD_POSITION.BOTTOM_CENTER
    });<commit_msg>working<commit_after>

/// Shared menu bar code
var menuBar =
                        '
'+
                          ''+
                           'Favorite'+
                        '
'+
                        '
'+
                            ''+
                           'Africa'+
                        '
'+
                        '
'+
                            ''+
                           'U.S.A'+
                        '
'+
                        '
'+
                            ''+
                           'Antarcita'+
                        '
'+
                           '
'+
                          ''+
                           'Asia'+
                        '
'+
                         '
'+
                          ''+
                           'Animal'+
                        '
'+
                         '
'+
                          ''+
                           'Awesome'+
                        '
'+
                         '
'+
                          ''+
                           'Body'+
                        '
'+
                        '
'+
                          ''+
                           'Celebrity'+
                        '
'+
                         '
'+
                          ''+
                           'Companies'+
                        '
'+
                        '
'+
                          ''+
                           'Drug'+
                        '
'+
                         '
'+
                          ''+
                           'Food'+
                        '
'+
                         '
'+
                          ''+
                           'History'+
                        '
'+
                         '
'+
                          ''+
                           'Random'+
                        '
'+
                         '
'+
                          ''+
                           'Technology'+
                        '
'+
                        '
'+
                          ''+
                           'Science'+
                        '
'+

                         '
'+
                          ''+
                           'Settings'
                        /*
                        '
'+
                         '
'+
                          ''+
                           'Univers'+
                        '
' */

$(".side-menu").append(menuBar);

var bottombar = ''+
                    ''+
                    ''+
                    ''

$(".toolbar-inner").prepend(bottombar);

//// Scared functionality code

/// Scared functionality for the side menu bar

//opening the panels
 $$('.open-left-panel').on('click', function (e) {
        // 'left' position to open Left panel
        myApp.openPanel('left');
        mySwiper.lockSwipes();
    });

// closing the panels
  $$('.panel-close').on('click', function (e) {
    myApp.closePanel();
    mySwiper.unlockSwipes();
    });

///  Share fact to social media
function shareFact(){
    var imageLink;
        console.log("Calling from CapturePhoto");
        navigator.screenshot.save(function(error, res){
            if(error){
                console.log(error);
            }else{
                $(".sharing").fadeIn(500).fadeOut(3000);
                console.log('ok',res.filePath);
                imageLink = res.filePath;
                window.plugins.socialsharing.share(null,null, 'file://'+imageLink, null);

            }
        }, 'jpg',100,'myScreenShot');
    }

// Function that allow you to copy the text
function copyToClipboard(element) {
  var $temp = $("<input>");
  $("body").append($temp);
  $temp.val($(element).text()).select();
  document.execCommand("copy");
  $temp.remove();
}

$(".fa-files-o").click(function(){
    copyToClipboard(".swiper-slide-active");
    $(".text-copied").fadeIn(500).fadeOut(3000);

});

/// Code used to update the heart icon base on the data-favorite value

function slideChecker(){
  if($(".swiper-slide-active").attr("data-favorite")=="false"){

         $("#bottom-btn-favorite-hidden").css("color","white");

    }
    else if($(".swiper-slide-active").attr("data-favorite")=="true"){
         $("#bottom-btn-favorite-hidden").css("color","red");
    }
    }

function favoriteFact(){
$(document).ready(function(){

if($(".swiper-slide-active").attr("data-favorite")=="false")
    { /// check to see the slide data favorite (is not added to favorite)
/// adding it to favorite

    var fact_ID = $(".swiper-slide-active").attr("id") //  (true,false) getting fact id name which will be used to help control heart color and data favorite

    var fact_Value = $(".swiper-slide-active").attr("data-fact") ///  (fact number to reference text) get fact data number which will help reference the text

    var KeyValue = $(".swiper-slide-active").text();  // getting fact text value

    $(".swiper-slide-active").attr("data-favorite",true); // setting favorite data value to true

    $("#bottom-btn-favorite-hidden").css("color","red");  // changing the color of the white heart instantly

    localStorage.setItem(`${fact_ID}`,$("#"+`${fact_ID}`).attr("data-favorite")); // favorite heart color

    localStorage.setItem(`${fact_Value}`,`${KeyValue}`) /// favorite text value;

    }

/// removing it from favorite
else if($(".swiper-slide-active").attr("data-favorite")=="true")
{
    var fact_ID = $(".swiper-slide-active").attr("id") // getting fact id name

    var fact_Value = $(".swiper-slide-active").attr("data-fact")

    $(".swiper-slide-active").attr("data-favorite",false);

    $("#bottom-btn-favorite-hidden").css("color","white");

    localStorage.removeItem(`${fact_ID}`);

    localStorage.removeItem(`${fact_Value}`)

}

})
;}
var temp = true;
mySwiper.on('slideChangeEnd',function(){

    $("#bottom-btn-copy-hidden").fadeIn(100);
    $("#bottom-btn-forward-hidden").fadeIn(100);
    $("#bottom-btn-favorite-hidden").fadeIn(100);
    $("#bottom-btn-share-hidden").fadeIn(100);
    $(".fa-microphone").css("opacity","1");
    if(temp){
       mySwiper.removeSlide(0);
        temp = false;
    }

    if(localStorage.getItem("checkBoxValue")=="true"){
        text_to_speak();
    }

})

// Handle Cordova Device Ready Event

  $("#bottom-btn-forward-hidden").click(function(){
      mySwiper.slideNext();
  });

 function text_to_speak(){
         mySwiper.lockSwipes();
        var speak = $(".swiper-slide-active").text();
          TTS
            .speak(speak, function () {
             mySwiper.unlockSwipes();
        }, function (reason) {

        });

 }

 ///// Code for ad

var ad_units = {
			anroid : {
				banner : "234772"

			}
		};

//

var adid = ( /(android)/i.test(navigator.userAgent) ) ? ad_units.android : ad_units.ios;

if(mMedia) mMedia.createBanner({
        adId : adid.banner,
        autoShow : true,
        overlap : true,
        position : mMedia.AD_POSITION.BOTTOM_CENTER
    });

if(mMedia){
    alert("Working");
}<|endoftext|>


<commit_before>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing pu<commit_msg>Fixing an error introduced in the last commit<commit_after>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Corre<|endoftext|>


<commit_before>define(["dojo/_base/declare", "dojo/_base/lang", "dojo/Deferred", "dojo/when", "require", "dojo/dom-attr",
	"dijit/_TemplatedMixin", "dijit/_WidgetsInTemplateMixin", "./model"],
function(declare, lang, Deferred, when, require, dattr, TemplatedMixin, WidgetsInTemplateMixin, Model){
	// module:
	//		dojox/app/View
	// summary:
	//		dojox/app view object, each view can have one parent view and several children views.

	return declare("dojox.app.View", null, {
		constructor: function(params){
			// summary:
			//		init view object. A user can use configuration file or programing type to create a view instance.
			//
			// example:
			//		|	use configuration file
			//		|
			// 		|	// load view definition from views/simple.js by default
			//		|	"simple":{
			//		|		"template": "./templates/simple.html",
			//		|		"dependencies":["dojox/mobile/TextBox"]
			//		|	}
			//		|
			//		|	"home":{
			//		|		"template": "./templates/home.html",
			//		|		"definition": "none",	// identify no view definition
			//		|		"dependencies":["dojox/mobile/TextBox"]
			//		|	}
			//		|	"main":{
			//		|		"template": "./templates/main.html",
			//		|		"definition": "./views/main.js", // identify load view definition from views/main.js
			//		|		"dependencies":["dojox/mobile/TextBox"]
			//		|	}
			//
			// example:
			//		|	var viewObj = new View({
			//		|		app: this.app,
			//		|		id: this.id,
			//		|		name: this.name,
			//		|		parent: this,
			//		|		templateString: this.templateString,
			//		|		definition: this.definition
			//		|	});
			//		|	viewObj.start(); // start view
			//
			// params:
			//		view parameters, include:
			//
			//		- app: the app
			//		- id: view id
			//		- name: view name
			//		- template: view template url. If templateString not empty, ignore this parameter.
			//		- templateString: view template string
			//		- definition: view definition url
			//		- parent: parent view
			//		- children: children views
			this.id = "";
			this.name = "";
			this.templateString = "";
			this.template = "";
			this.definition = "";
			this.parent = null;
			this.children = {};
			this.selectedChild = null;
			// private
			this._started = false;
			this._definition = null;

			lang.mixin(this, params);
			// mixin views configuration to current view instance.
			if(this.parent.views){
				lang.mixin(this, this.parent.views[this.name]);
			}
		},

		_loadViewDefinition: function(){
			// summary:
			//		Load view definition by configuration or by default.
			// tags:
			//		private
			//
			var _definitionDef = new Deferred();
			var path;

			if(this.definition && (this.definition === "none")){
				_definitionDef.resolve(true);
				return _definitionDef;
			}else if(this.definition){
				path = this.definition.replace(/(\.js)$/, "");
			}else{
				path = this.id.split("_");
				path.shift();
				path = path.join("/");
				path = "./views/" + path;
			}

			var requireSignal;
			try{
				var loadFile = path;
				var index = loadFile.indexOf("./");
				if(index >= 0){
					loadFile = path.substring(index+2);
				}
				requireSignal = require.on("error", function(error){
					if (_definitionDef.isResolved() || _definitionDef.isRejected()) {
						return;
					}
					if(error.info[0] && (error.info[0].indexOf(loadFile)>= 0)){
						_definitionDef.resolve(false);
						requireSignal.remove();
					}
				});

				if(path.indexOf("./") == 0){
					path = "app/"+path;
				}

				require([path], function(definition){
					_definitionDef.resolve(definition);
					requireSignal.remove();
				});
			}catch(e){
				_definitionDef.reject(e);
				requireSignal.remove();
			}
			return _definitionDef;
		},

		_loadViewTemplate: function(){
			// summary:
			//		load view HTML template and dependencies.
			// tags:
			//		private
			//

			if(this.templateString){
				return true;
			}else{
				if(!this.dependencies){
					this.dependencies = [];
				}
				var tpl = this.template;
				if(tpl.indexOf("./") == 0){
					tpl = "app/"+tpl;
				}
				var deps = this.template ? this.dependencies.concat(["dojo/text!"+tpl]) : this.dependencies.concat([]);
				// if we have a build and that the view layer is built into the view definition this is good to have it
				// loaded here as well to avoid loading the dependencies from outside the layer
				var path;
				if(this.definition && this.definition != "none"){
					path = this.definition.replace(/(\.js)$/, "");
				}else if(!this.definition){
					path = this.id.split("_");
					path.shift();
					path = path.join("/");
					path = "./views/" + path;
				}
				if(path && path.indexOf("./") == 0){
					path = "app/"+path;
				}
				var def = new Deferred();
				require(path?[path]:[], function(){
					if(deps.length > 0){
						var requireSignal;
						try{
							requireSignal = require.on("error", lang.hitch(this, function(error){
								if(def.isResolved() || def.isRejected()){
									return;
								}
								if(error.info[0] && error.info[0].indexOf(this.template)>=0 ){
									def.resolve(false);
									requireSignal.remove();
								}
							}));
							require(deps, function(){
								def.resolve.call(def, arguments);
								requireSignal.remove();
							});
						}catch(e){
							def.resolve(false);
							requireSignal.remove();
						}
					}else{
						def.resolve(true);
					}
				});

				var loadViewDeferred = new Deferred();
				when(def, lang.hitch(this, function(){
					this.templateString = this.template ? arguments[0][arguments[0].length - 1] : "

";
					loadViewDeferred.resolve(this);
				}));
				return loadViewDeferred;
			}
		},

		// start view
		start: function(){
			// summary:
			//		start view object.
			//		load view template, view definition implement and startup all widgets in view template.
			if(this._started){
				return this;
			}

			var _definitionDef = this._loadViewDefinition();
			var _templateDef = this._loadViewTemplate();

			this._startDef = new Deferred();
			when(_definitionDef, lang.hitch(this, function(definition){
				this._definition = definition;
				when(_templateDef, lang.hitch(this, function(){
					// call setupModel, after setupModel startup will be called after startup the loadViewDeferred will be resolved
					this._setupModel();
				}));
			}));
			return this._startDef;
		},

		_setupModel: function(){
			// summary:
			//		Load views model if it is not already loaded then call _startup.
			// tags:
			//		private

			if (!this.loadedModels) {
				var loadModelLoaderDeferred = new Deferred();
				var createPromise;
				try{
					createPromise = Model(this.models, this.parent, this.app);
				}catch(e){
					loadModelLoaderDeferred.reject(e);
					return loadModelLoaderDeferred.promise;
				}
				if(createPromise.then){  // model returned a promise, so set loadedModels and call startup after the .when
					when(createPromise, lang.hitch(this, function(newModel){
						if(newModel){
							this.loadedModels = newModel;
						}
						this._startup();
					}),
					function(err){
						loadModelLoaderDeferred.reject(err);
					});
				}else{ // model returned the actual model not a promise, so set loadedModels and call _startup
					this.loadedModels = createPromise;
					this._startup();
				}
			}else{ // loadedModels already created so call _startup
				this._startup();
			}
		},

		_startup: function(){
			// summary:
			//		startup widgets in view template.
			// tags:
			//		private

			this._widget = this.render(this.templateString);
			// bind view level data model
			this.domNode = this._widget.domNode;
			this.parent.domNode.appendChild(this.domNode);

			//start widget
			this._widget.startup();

			// set widget attributes
			dattr.set(this.domNode, "id", this.id);
			dattr.set(this.domNode, "data-app-region", "center");
			// TODO here we are overriding the entire style of the node, instead of just width & height
			// maybe we could be a bit smarter
			dattr.set(this.domNode, "style", "width:100%; height:100%");
			this._widget.region = "center";

			//mixin view lifecycle implement
			if (this._definition) {
				lang.mixin(this, this._definition);
			}

			// call view assistant's init() method to initialize view
			this.app.log("  > in app/View calling init() name=[",this.name,"], parent.name=[",this.parent.name,"]");
			this.init();
			this._started = true;
			if(this._startDef){
				this._startDef.resolve(this);
			}
		},

		render: function(templateString){
			// summary:
			//		rendering view template HTML
			// templateString:
			//		template string
			var widgetTemplate = new TemplatedMixin();
			var widgetInTemplate = new WidgetsInTemplateMixin();
			// set the loadedModels here to be able to access the model on the parse.
			if(this.loadedModels){
				widgetInTemplate.loadedModels = this.loadedModels;
			}
			lang.mixin(widgetTemplate, widgetInTemplate);
			widgetTemplate.templateString = templateString;
			widgetTemplate.buildRendering();
			return widgetTemplate;
		},

		init: function(){
			// summary:
			//		view life cycle init()
		},

		beforeActivate: function(){
			// summary:
			//		view life cycle beforeActivate()
		},

		afterActivate: function(){
			// summary:
			//		view life cycle afterActivate()
		},

		beforeDeactivate: function(){
			// summary:
			//		view life cycle beforeDeactivate()
		},

		afterDeactivate: function(){
			// summary:
			//		view life cycle afterDeactivate()
		},

		destroy: function(){
			// summary:
			//		view life cycle destroy()
		}
	});
});
<commit_msg>allow dojo-attach-* to work<commit_after>define(["require", "dojo/when", "dojo/on", "dojo/dom-attr", "dojo/_base/declare", "dojo/_base/lang", "dojo/Deferred",
	"dijit/Destroyable", "dijit/_TemplatedMixin", "dijit/_WidgetsInTemplateMixin", "./model"],
function(require, when, on, domAttr, declare, lang, Deferred, Destroyable, _TemplatedMixin, _WidgetsInTemplateMixin, Model){
	// module:
	//		dojox/app/View
	// summary:
	//		dojox/app view object, each view can have one parent view and several children views.

	return declare("dojox.app.View", [_TemplatedMixin, _WidgetsInTemplateMixin, Destroyable], {
		constructor: function(params){
			// summary:
			//		init view object. A user can use configuration file or programing type to create a view instance.
			//
			// example:
			//		|	use configuration file
			//		|
			// 		|	// load view definition from views/simple.js by default
			//		|	"simple":{
			//		|		"template": "./templates/simple.html",
			//		|		"dependencies":["dojox/mobile/TextBox"]
			//		|	}
			//		|
			//		|	"home":{
			//		|		"template": "./templates/home.html",
			//		|		"definition": "none",	// identify no view definition
			//		|		"dependencies":["dojox/mobile/TextBox"]
			//		|	}
			//		|	"main":{
			//		|		"template": "./templates/main.html",
			//		|		"definition": "./views/main.js", // identify load view definition from views/main.js
			//		|		"dependencies":["dojox/mobile/TextBox"]
			//		|	}
			//
			// example:
			//		|	var viewObj = new View({
			//		|		app: this.app,
			//		|		id: this.id,
			//		|		name: this.name,
			//		|		parent: this,
			//		|		templateString: this.templateString,
			//		|		definition: this.definition
			//		|	});
			//		|	viewObj.start(); // start view
			//
			// params:
			//		view parameters, include:
			//
			//		- app: the app
			//		- id: view id
			//		- name: view name
			//		- template: view template url. If templateString not empty, ignore this parameter.
			//		- templateString: view template string
			//		- definition: view definition url
			//		- parent: parent view
			//		- children: children views
			this.id = "";
			this.name = "";
			this.template = "";
			this.definition = "";
			this.parent = null;
			this.children = {};
			this.selectedChild = null;
			// private
			this._started = false;
			this._definition = null;

			lang.mixin(this, params);
			// mixin views configuration to current view instance.
			if(this.parent.views){
				lang.mixin(this, this.parent.views[this.name]);
			}
		},

		// _TemplatedMixin requires a connect method if data-dojo-attach-* are used
		connect: function(obj, event, method){
			return this.own(on(obj, event, lang.hitch(this, method)))[0];  // handle
		},

		_loadViewDefinition: function(){
			// summary:
			//		Load view definition by configuration or by default.
			// tags:
			//		private
			//
			var _definitionDef = new Deferred();
			var path;

			if(this.definition && (this.definition === "none")){
				_definitionDef.resolve(true);
				return _definitionDef;
			}else if(this.definition){
				path = this.definition.replace(/(\.js)$/, "");
			}else{
				path = this.id.split("_");
				path.shift();
				path = path.join("/");
				path = "./views/" + path;
			}

			var requireSignal;
			try{
				var loadFile = path;
				var index = loadFile.indexOf("./");
				if(index >= 0){
					loadFile = path.substring(index+2);
				}
				requireSignal = require.on("error", function(error){
					if (_definitionDef.isResolved() || _definitionDef.isRejected()) {
						return;
					}
					if(error.info[0] && (error.info[0].indexOf(loadFile)>= 0)){
						_definitionDef.resolve(false);
						requireSignal.remove();
					}
				});

				if(path.indexOf("./") == 0){
					path = "app/"+path;
				}

				require([path], function(definition){
					_definitionDef.resolve(definition);
					requireSignal.remove();
				});
			}catch(e){
				_definitionDef.reject(e);
				requireSignal.remove();
			}
			return _definitionDef;
		},

		_loadViewTemplate: function(){
			// summary:
			//		load view HTML template and dependencies.
			// tags:
			//		private
			//

			if(this.templateString){
				return true;
			}else{
				if(!this.dependencies){
					this.dependencies = [];
				}
				var tpl = this.template;
				if(tpl.indexOf("./") == 0){
					tpl = "app/"+tpl;
				}
				var deps = this.template ? this.dependencies.concat(["dojo/text!"+tpl]) : this.dependencies.concat([]);
				// if we have a build and that the view layer is built into the view definition this is good to have it
				// loaded here as well to avoid loading the dependencies from outside the layer
				var path;
				if(this.definition && this.definition != "none"){
					path = this.definition.replace(/(\.js)$/, "");
				}else if(!this.definition){
					path = this.id.split("_");
					path.shift();
					path = path.join("/");
					path = "./views/" + path;
				}
				if(path && path.indexOf("./") == 0){
					path = "app/"+path;
				}
				var def = new Deferred();
				require(path?[path]:[], function(){
					if(deps.length > 0){
						var requireSignal;
						try{
							requireSignal = require.on("error", lang.hitch(this, function(error){
								if(def.isResolved() || def.isRejected()){
									return;
								}
								if(error.info[0] && error.info[0].indexOf(this.template)>=0 ){
									def.resolve(false);
									requireSignal.remove();
								}
							}));
							require(deps, function(){
								def.resolve.call(def, arguments);
								requireSignal.remove();
							});
						}catch(e){
							def.resolve(false);
							requireSignal.remove();
						}
					}else{
						def.resolve(true);
					}
				});

				var loadViewDeferred = new Deferred();
				when(def, lang.hitch(this, function(){
					this.templateString = this.template ? arguments[0][arguments[0].length - 1] : "

";
					loadViewDeferred.resolve(this);
				}));
				return loadViewDeferred;
			}
		},

		// start view
		start: function(){
			// summary:
			//		start view object.
			//		load view template, view definition implement and startup all widgets in view template.
			if(this._started){
				return this;
			}

			var _definitionDef = this._loadViewDefinition();
			var _templateDef = this._loadViewTemplate();

			this._startDef = new Deferred();
			when(_definitionDef, lang.hitch(this, function(definition){
				this._definition = definition;
				when(_templateDef, lang.hitch(this, function(){
					// call setupModel, after setupModel startup will be called after startup the loadViewDeferred will be resolved
					this._setupModel();
				}));
			}));
			return this._startDef;
		},

		_setupModel: function(){
			// summary:
			//		Load views model if it is not already loaded then call _startup.
			// tags:
			//		private

			if (!this.loadedModels) {
				var loadModelLoaderDeferred = new Deferred();
				var createPromise;
				try{
					createPromise = Model(this.models, this.parent, this.app);
				}catch(e){
					loadModelLoaderDeferred.reject(e);
					return loadModelLoaderDeferred.promise;
				}
				if(createPromise.then){  // model returned a promise, so set loadedModels and call startup after the .when
					when(createPromise, lang.hitch(this, function(newModel){
						if(newModel){
							this.loadedModels = newModel;
						}
						this._startup();
					}),
					function(err){
						loadModelLoaderDeferred.reject(err);
					});
				}else{ // model returned the actual model not a promise, so set loadedModels and call _startup
					this.loadedModels = createPromise;
					this._startup();
				}
			}else{ // loadedModels already created so call _startup
				this._startup();
			}
		},

		_startup: function(){
			// summary:
			//		startup widgets in view template.
			// tags:
			//		private

			this.render(this.templateString);
			// bind view level data model
			this.parent.domNode.appendChild(this.domNode);

			//start widget
			this.startup();

			// set widget attributes
			domAttr.set(this.domNode, "id", this.id);
			domAttr.set(this.domNode, "data-app-region", "center");
			// TODO here we are overriding the entire style of the node, instead of just width & height
			// maybe we could be a bit smarter
			domAttr.set(this.domNode, "style", "width:100%; height:100%");
			this.region = "center";

			// call view assistant's init() method to initialize view
			this.app.log("  > in app/View calling init() name=[",this.name,"], parent.name=[",this.parent.name,"]");
			this.init();
			this._started = true;
			if(this._startDef){
				this._startDef.resolve(this);
			}
		},

		render: function(templateString){
			// summary:
			//		rendering view template HTML
			// templateString:
			//		template string

			// TODO: we could  get rid of that method and use buildRendering directly...
			// mixin lifecycle implementation into view, we need that early for datat-dojo-attach-* to work correctly
			if(this._definition){
				lang.mixin(this, this._definition);
			}
			this.templateString = templateString;
			this.buildRendering();
		},

		init: function(){
			// summary:
			//		view life cycle init()
		},

		beforeActivate: function(){
			// summary:
			//		view life cycle beforeActivate()
		},

		afterActivate: function(){
			// summary:
			//		view life cycle afterActivate()
		},

		beforeDeactivate: function(){
			// summary:
			//		view life cycle beforeDeactivate()
		},

		afterDeactivate: function(){
			// summary:
			//		view life cycle afterDeactivate()
		},

		destroy: function(){
			// summary:
			//		view life cycle destroy()
		}
	});
});
<|endoftext|>


<commit_before><commit_msg>fixed typo<commit_after><|endoftext|>


<commit_before>var gulp = require("gulp");
var gutil = require("gulp-util");
var webpack = require("webpack");
var WebpackDevServer = require("webpack-dev-server");
var webpackConfig = require("./webpack.config.js");

// The development server (the recommended option for development)
gulp.task("default", ["webpack-dev-server"], function() {});

// Build and watch cycle (another option for development)
// Advantage: No server required, can run app from filesystem
// Disadvantage: Requests are not blocked until bundle is available,
//               can serve an old app on refresh
gulp.task("build-dev", ["webpack:build-dev"], function() {
	gulp.watch(["app/**/*"], function(event) {
		gulp.run("webpack:build-dev");
	});
});

// Production build
gulp.task("build", ["webpack:build"], function() {});

gulp.task("webpack:build", function(callback) {
	// modify some webpack config options
	var myConfig = Object.create(webpackConfig);
	myConfig.plugins = myConfig.plugins.concat(
		new webpack.DefinePlugin({
			"process.env": {
				"NODE_ENV": JSON.stringify("production")
			}
		}),
		new webpack.optimize.DedupePlugin(),
		new webpack.optimize.UglifyJsPlugin()
	);

	// run webpack
	webpack(myConfig, function(err, stats) {
		if(err) throw new gutil.PluginError("webpack:build", err);
		gutil.log("[webpack:build]", stats.toString({
			colors: true
		}));
		callback();
	});
});

// modify some webpack config options
var myDevConfig = Object.create(webpackConfig);
myDevConfig.devtool = "sourcemap";
myDevConfig.debug = true;

// create a single instance of the compiler to allow caching
var devCompiler = webpack(myDevConfig);

gulp.task("webpack:build-dev", function(callback) {
	// run webpack
	devCompiler.run(function(err, stats) {
		if(err) throw new gutil.PluginError("webpack:build-dev", err);
		gutil.log("[webpack:build-dev]", stats.toString({
			colors: true
		}));
		callback();
	});
});

gulp.task("webpack-dev-server", function(callback) {
	// modify some webpack config options
	var myConfig = Object.create(webpackConfig);
	myConfig.devtool = "eval";
	myConfig.debug = true;

	// Start a webpack-dev-server
	new WebpackDevServer(webpack(myConfig), {
		publicPath: "/" + myConfig.output.publicPath,
		stats: {
			colors: true
		}
	}).listen(8080, "localhost", function(err) {
		if(err) throw new gutil.PluginError("webpack-dev-server", err);
		gutil.log("[webpack-dev-server]", "http://localhost:8080/webpack-dev-server/index.html");
	});
});
<commit_msg>use new aliases<commit_after>var gulp = require("gulp");
var gutil = require("gulp-util");
var webpack = require("webpack");
var WebpackDevServer = require("webpack-dev-server");
var webpackConfig = require("./webpack.config.js");

// The development server (the recommended option for development)
gulp.task("default", ["webpack-dev-server"]);

// Build and watch cycle (another option for development)
// Advantage: No server required, can run app from filesystem
// Disadvantage: Requests are not blocked until bundle is available,
//               can serve an old app on refresh
gulp.task("build-dev", ["webpack:build-dev"], function() {
	gulp.watch(["app/**/*"], ["webpack:build-dev"]);
});

// Production build
gulp.task("build", ["webpack:build"]);

gulp.task("webpack:build", function(callback) {
	// modify some webpack config options
	var myConfig = Object.create(webpackConfig);
	myConfig.plugins = myConfig.plugins.concat(
		new webpack.DefinePlugin({
			"process.env": {
				"NODE_ENV": JSON.stringify("production")
			}
		}),
		new webpack.optimize.DedupePlugin(),
		new webpack.optimize.UglifyJsPlugin()
	);

	// run webpack
	webpack(myConfig, function(err, stats) {
		if(err) throw new gutil.PluginError("webpack:build", err);
		gutil.log("[webpack:build]", stats.toString({
			colors: true
		}));
		callback();
	});
});

// modify some webpack config options
var myDevConfig = Object.create(webpackConfig);
myDevConfig.devtool = "sourcemap";
myDevConfig.debug = true;

// create a single instance of the compiler to allow caching
var devCompiler = webpack(myDevConfig);

gulp.task("webpack:build-dev", function(callback) {
	// run webpack
	devCompiler.run(function(err, stats) {
		if(err) throw new gutil.PluginError("webpack:build-dev", err);
		gutil.log("[webpack:build-dev]", stats.toString({
			colors: true
		}));
		callback();
	});
});

gulp.task("webpack-dev-server", function(callback) {
	// modify some webpack config options
	var myConfig = Object.create(webpackConfig);
	myConfig.devtool = "eval";
	myConfig.debug = true;

	// Start a webpack-dev-server
	new WebpackDevServer(webpack(myConfig), {
		publicPath: "/" + myConfig.output.publicPath,
		stats: {
			colors: true
		}
	}).listen(8080, "localhost", function(err) {
		if(err) throw new gutil.PluginError("webpack-dev-server", err);
		gutil.log("[webpack-dev-server]", "http://localhost:8080/webpack-dev-server/index.html");
	});
});
<|endoftext|>


<commit_before>import React from 'react'
import Logo from './logo'
import styled from 'styled-components'
import Link from 'gatsby-link'
import {MobileHide} from '../MobileHide'

const Sidebar = ({ className, color, bgColor }) => (

    <Link to="/">
      <Logo fill={color || "#000"} hoverfill={color ? '#CCC' : "#0000FF"} />
    </Link>
    <MobileHide>

    </MobileHide>

)

const SidebarStyled = styled(Sidebar)`
  min-width: 250px;
  width: 15.5%;
  height: 100%;
  position: fixed;
  padding-top: 26px;
  flex-shrink: 0;
  flex-grow: 0;
  text-align: center;
  font-size: 13px;
  background-color: ${props => props.bgColor ? props.bgColor : '#fff'};
  line-height: 1.7;
  max-width: 320px;
  p {
    color: ${props => props.color ? props.color : '#001d60'};
  }
  ${props => props.color ?
  `a{
    color ${props.color}
  }`
  : ''}
  @media(max-width: 560px){
    position: relative;
    width: 100%;
    margin: 0 auto;
  }
`

export default SidebarStyled
<commit_msg>Update index.js<commit_after>import React from 'react'
import Logo from './logo'
import styled from 'styled-components'
import Link from 'gatsby-link'
import {MobileHide} from '../MobileHide'

const Sidebar = ({ className, color, bgColor }) => (

    <Link to="/">
      <Logo fill={color || "#000"} hoverfill={color ? '#CCC' : "#0000FF"} />
    </Link>
    <MobileHide>

Four, simply divided. Three, cut vertically down the middle. Zero, cut horizontally.

    </MobileHide>

)

const SidebarStyled = styled(Sidebar)`
  min-width: 250px;
  width: 15.5%;
  height: 100%;
  position: fixed;
  padding-top: 26px;
  flex-shrink: 0;
  flex-grow: 0;
  text-align: center;
  font-size: 13px;
  background-color: ${props => props.bgColor ? props.bgColor : '#fff'};
  line-height: 1.7;
  max-width: 320px;
  p {
    color: ${props => props.color ? props.color : '#001d60'};
  }
  ${props => props.color ?
  `a{
    color ${props.color}
  }`
  : ''}
  @media(max-width: 560px){
    position: relative;
    width: 100%;
    margin: 0 auto;
  }
`

export default SidebarStyled
<|endoftext|>


<commit_before>exports.config = {

  specs: ['e2e/responsiveSpec.js','e2e/scenariosSpec.js'],

  capabilities: {
    browserName: 'chrome',
    shardTestFiles: true,
    maxInstances: 2
  },

  chromeDriver: '/usr/local/lib/node_modules/chromedriver/lib/chromedriver/chromedriver',

  baseUrl: 'http://localhost:8080/',

  framework: 'jasmine',

};<commit_msg>Grunt && CircleCi && Heroku: tryng if Chromedriver is executed in CircleCi, changing path to /usr/local/bin/chromedriver<commit_after>exports.config = {

  specs: ['e2e/responsiveSpec.js','e2e/scenariosSpec.js'],

  capabilities: {
    browserName: 'chrome',
    shardTestFiles: true,
    maxInstances: 2
  },

  chromeDriver: '/usr/local/bin/chromedriver',

  baseUrl: 'http://localhost:8080/',

  framework: 'jasmine',

};<|endoftext|>