<commit_before>(function() {
    var el = document.getElementById('countdown'),
        endDate = new Date('March 30, 2012 18:10:00'),
        curDate,
        diff,
        days,
        hours,
        minutes,
        seconds,
        tmp,
        countdown,
        pad = function(number) { return (number < 10 ? '0' : '') + Math.floor(number) },
        minute = 60 * 1000,
        hour = minute * 60,
        day = hour * 24
    ;(function tick() {
        curDate = new Date()
        diff = Math.abs(new Date(curDate.getTime() - endDate.getTime()))
        days = diff / day

        tmp = diff % day
        hours = tmp / hour

        tmp = diff % hour
        minutes = tmp / minute

        tmp = diff % minute
        seconds = tmp / 1000

        countdown = pad(days) + ':' + pad(hours) + ':' + pad(minutes) + ':' + pad(seconds)

        if ('textContent' in el) {
            el.textContent = countdown
        }
        else {
            el.innerText = countdown
        }
        setTimeout(tick, 1000)
    }())
}())

<commit_msg>Last fix<commit_after>(function() {
    var el = document.getElementById('countdown'),
        endDate = new Date('March 30, 2012 18:10:00'),
        curDate,
        diff,
        days,
        hours,
        minutes,
        seconds,
        tmp,
        countdown,
        pad = function(number) { return (number < 10 ? '0' : '') + Math.floor(number) },
        minute = 60 * 1000,
        hour = minute * 60,
        day = hour * 24
    ;(function tick() {
        curDate = new Date()
        diff = new Date(curDate.getTime() - endDate.getTime())
        if (diff > 0) {
            countdown = "It's over!"
        }
        else {
            diff = Math.abs(diff)
            days = diff / day

            tmp = diff % day
            hours = tmp / hour

            tmp = diff % hour
            minutes = tmp / minute

            tmp = diff % minute
            seconds = tmp / 1000

            countdown = pad(days) + ':' + pad(hours) + ':' + pad(minutes) + ':' + pad(seconds)
        }

        if ('textContent' in el) {
            el.textContent = countdown
        }
        else {
            el.innerText = countdown
        }
        setTimeout(tick, 1000)
    }())
}())

<|endoftext|>


<commit_before><commit_msg>Added support for doc files<commit_after><|endoftext|>


<commit_before><commit_msg>Alias `tessel node` to `tessel run`.<commit_after><|endoftext|>


<commit_before>(function ( document ) {

	// jQuery equivalent selector: body > center > table > tbody > tr:eq(2) > td table:eq(1) > tbody > tr
	var comments = null;
	try {
		commentsTrs = document.querySelectorAll ( 'body > center > table > tbody > tr' )[2].querySelectorAll ( 'td table' )[1].querySelectorAll ( 'tbody > tr' );
	} catch ( e ) {
		alert ( "Ooops, something is wrong. Are you sure you are on a 'Ask HN: Who is hiring?' page?" );
		return;
	}

	for ( var i in commentsTrs ) {
		var commentTr = commentsTrs[i];

		try {
			// jQuery equivalent selector: 'table td:eq(2) span.comment'
			var commentText = commentTr.querySelectorAll ( 'table td' )[2].querySelector ( 'span.comment font' );
			console.log ( commentText.textContent );
		} catch ( e ) {
		}
	}
} ( document ) );<commit_msg>test regex & remove elements<commit_after>(function ( document ) {
	var searchCity = 'london';

	// jQuery equivalent selector: body > center > table > tbody > tr:eq(2) > td table:eq(1) > tbody > tr
	var comments = null;
	try {
		commentsTrs = document.querySelectorAll ( 'body > center > table > tbody > tr' )[2].querySelectorAll ( 'td table' )[1].querySelectorAll ( 'tbody > tr' );
	} catch ( e ) {
		alert ( "Ooops, something is wrong. Are you sure you are on a 'Ask HN: Who is hiring?' page?" );
		return;
	}

	for ( var i in commentsTrs ) {
		var commentTr = commentsTrs[i];

		try {
			// jQuery equivalent selector: 'table td:eq(2) span.comment'
			var commentText = commentTr.querySelectorAll ( 'table td' )[2].querySelector ( 'span.comment' ).textContent + '';

			if ( /\b(london)\b/ig.test ( commentText ) === false ) {
				commentTr.parentNode.removeChild ( commentTr );
			}
		} catch ( e ) {
			//console.log ( e.message );
		}
	}
} ( document ) );<|endoftext|>


<commit_before>var url = require('url'),
    fs = require('fs'),
    cheerio = require('cheerio'),
    yaml = require('js-yaml'),
    moment = require('moment'),
    getPage = require('./get-page'),
    personDir = __dirname + '/data/person',
    categoryUrl = 'https://en.wikipedia.org/wiki/Category:Members_of_the_Council_of_the_District_of_Columbia';

getPage(categoryUrl, function (err, body) {
    if (err) {
        throw err;
    }
    var $ = cheerio.load(body);
    $('div.mw-category a').each(function () {
        var personUrl = url.resolve(categoryUrl, this.attr('href')),
            personName = this.attr('title').replace(/\s+\([^)]*\)$/, '');
        if (/^List of/.test(personName)) {
            return;
        }
        getPage(personUrl, function (err, body) {
            processPerson(personName, personUrl, body);
        });
    });
});

function processPerson(personName, personUrl, body) {
    var reversedName = personName.replace(/^(.+?)\s+(\S+)(, [JS]r\.)?$/, '$2, $1$3'),
        personCode = reversedName.toLowerCase().replace(/\W+/g, '_').replace(/^_|_$/g, ''),
        $ = cheerio.load(body),
        data = {
            code: personCode,
            name: personName,
            wikipedia: personUrl,
            birth_date: $('span.bday').text(),
            death_date: $('span.dday,span.deathdate').text(),
            positions: []
        },
        filename = personDir + '/' + personCode + '.yaml',
        m;
    console.log(personCode, personName, personUrl);
    if (!data.birth_date) {
        if (m = body.toString().match(/\(born ([A-Z][a-z]+ \d\d?, \d{4})|\(([A-Z][a-z]+ \d\d?, \d{4})\W+([A-Z][a-z]+ \d\d?, \d{4})\)/)) {
            data.birth_date = moment(m[1] || m[2], 'MMMM D, YYYY').format('YYYY-MM-DD');
            if (m[3]) {
                data.death_date = moment(m[3], 'MMMM D, YYYY').format('YYYY-MM-DD');
            }
        }
    }
    if (!data.birth_date) {
        delete data.birth_date;
    }
    if (!data.death_date) {
        delete data.death_date;
    }
    $('table.succession-box tr').each(function () {
        var cells = this.find('td'),
            start, end, parts, dates, office;
        if (cells.length !== 3) {
            return;
        }
        parts = cells.eq(1).html().split(/\s*<br\s*\/?>\s*/);
        dates = parts.pop();
        office = parts.join(' ').replace(/<[^>]*>/g, '');
        if (m = dates.match(/(([A-Z][a-z]+ \d\d?, )?(?:19|20)\d\d)\W+(([A-Z][a-z]+ \d\d?, )?(?:19|20)\d\d|present|)/)) {
            start = m[2] ? moment(m[1], 'MMMM D, YYYY').format('YYYY-MM-DD') : m[1];
            end = m[4] ? moment(m[3], 'MMMM D, YYYY').format('YYYY-MM-DD') : (!m[3] || m[3] == 'present' ? null : m[3]);
        }
        else if (dates.match(/^(?:19|20)\d\d$/)) {
            start = end = dates;
        }
        else {
            console.log(parts);
            throw 'Unexpected date format: ' + dates;
        }
        if (/nominee/i.test(office)) {
            return;
        }
        data.positions.push({
            office: office,
            start: start,
            end: end
        });
    });
    fs.writeFileSync(personDir + '/' + personCode + '.html', body);
    fs.writeFileSync(filename, yaml.safeDump(data));
}
<commit_msg>fix accessing of HTML elements in scrape-wikipedia.js<commit_after>var url = require('url'),
    fs = require('fs'),
    cheerio = require('cheerio'),
    yaml = require('js-yaml'),
    moment = require('moment'),
    getPage = require('./get-page'),
    personDir = __dirname + '/data/person',
    categoryUrl = 'https://en.wikipedia.org/wiki/Category:Members_of_the_Council_of_the_District_of_Columbia';

getPage(categoryUrl, function (err, body) {
    if (err) {
        throw err;
    }
    var $ = cheerio.load(body);
    $('div.mw-category a').each(function () {
        var $a = $(this),
            personUrl = url.resolve(categoryUrl, $a.attr('href')),
            personName = $a.attr('title').replace(/\s+\([^)]*\)$/, '');
        if (/^List of/.test(personName)) {
            return;
        }
        getPage(personUrl, function (err, body) {
            processPerson(personName, personUrl, body);
        });
    });
});

function processPerson(personName, personUrl, body) {
    var reversedName = personName.replace(/^(.+?)\s+(\S+)(, [JS]r\.)?$/, '$2, $1$3'),
        personCode = reversedName.toLowerCase().replace(/\W+/g, '_').replace(/^_|_$/g, ''),
        $ = cheerio.load(body),
        data = {
            code: personCode,
            name: personName,
            wikipedia: personUrl,
            birth_date: $('span.bday').text(),
            death_date: $('span.dday,span.deathdate').text(),
            positions: []
        },
        filename = personDir + '/' + personCode + '.yaml',
        m;
    console.log(personCode, personName, personUrl);
    if (!data.birth_date) {
        if (m = body.toString().match(/\(born ([A-Z][a-z]+ \d\d?, \d{4})|\(([A-Z][a-z]+ \d\d?, \d{4})\W+([A-Z][a-z]+ \d\d?, \d{4})\)/)) {
            data.birth_date = moment(m[1] || m[2], 'MMMM D, YYYY').format('YYYY-MM-DD');
            if (m[3]) {
                data.death_date = moment(m[3], 'MMMM D, YYYY').format('YYYY-MM-DD');
            }
        }
    }
    if (!data.birth_date) {
        delete data.birth_date;
    }
    if (!data.death_date) {
        delete data.death_date;
    }
    $('table.succession-box tr').each(function () {
        var cells = $(this).find('td'),
            start, end, parts, dates, office;
        if (cells.length !== 3) {
            return;
        }
        parts = cells.eq(1).html().split(/\s*<br\s*\/?>\s*/);
        dates = parts.pop();
        office = parts.join(' ').replace(/<[^>]*>/g, '');
        if (m = dates.match(/(([A-Z][a-z]+ \d\d?, )?(?:19|20)\d\d)\W+(([A-Z][a-z]+ \d\d?, )?(?:19|20)\d\d|present|)/)) {
            start = m[2] ? moment(m[1], 'MMMM D, YYYY').format('YYYY-MM-DD') : m[1];
            end = m[4] ? moment(m[3], 'MMMM D, YYYY').format('YYYY-MM-DD') : (!m[3] || m[3] == 'present' ? null : m[3]);
        }
        else if (dates.match(/^(?:19|20)\d\d$/)) {
            start = end = dates;
        }
        else {
            console.log(parts);
            throw 'Unexpected date format: ' + dates;
        }
        if (/nominee/i.test(office)) {
            return;
        }
        data.positions.push({
            office: office,
            start: start,
            end: end
        });
    });
    fs.writeFileSync(personDir + '/' + personCode + '.html', body);
    fs.writeFileSync(filename, yaml.safeDump(data));
}
<|endoftext|>


<commit_before>var window = new Window({
  // Set window width to 1024.
  width: 1024,
  // Set window height to 576.
  height: 576,
  // Window should not be full screen.
  fullscreen: false,
});

while (!window.isClosing()) {
  // Clear window graphics to black.
  window.graphics.clear({r:0, g:0, b:0, a:1});
  // Present the back buffer.
  window.graphics.present();
  // Poll and handle window events.
  window.pollEvents();
}<commit_msg>Removed window example.<commit_after><|endoftext|>


<commit_before>
/*
Tipue Search 5.0
Copyright (c) 2015 Tipue
Tipue Search is released under the MIT License
http://www.tipue.com/search
*/

/*
Stop words
Stop words list from http://www.ranks.nl/stopwords
*/

var tipuesearch_stop_words = ["a", "about", "above", "after", "again", "against", "all", "am", "an", "and", "any", "are", "aren't", "as", "at", "be", "because", "been", "before", "being", "below", "between", "both", "but", "by", "can't", "cannot", "could", "couldn't", "did", "didn't", "do", "does", "doesn't", "doing", "don't", "down", "during", "each", "few", "for", "from", "further", "had", "hadn't", "has", "hasn't", "have", "haven't", "having", "he", "he'd", "he'll", "he's", "her", "here", "here's", "hers", "herself", "him", "himself", "his", "how", "how's", "i", "i'd", "i'll", "i'm", "i've", "if", "in", "into", "is", "isn't", "it", "it's", "its", "itself", "let's", "me", "more", "most", "mustn't", "my", "myself", "no", "nor", "not", "of", "off", "on", "once", "only", "or", "other", "ought", "our", "ours", "ourselves", "out", "over", "own", "same", "shan't", "she", "she'd", "she'll", "she's", "should", "shouldn't", "so", "some", "such", "than", "that", "that's", "the", "their", "theirs", "them", "themselves", "then", "there", "there's", "these", "they", "they'd", "they'll", "they're", "they've", "this", "those", "through", "to", "too", "under", "until", "up", "very", "was", "wasn't", "we", "we'd", "we'll", "we're", "we've", "were", "weren't", "what", "what's", "when", "when's", "where", "where's", "which", "while", "who", "who's", "whom", "why", "why's", "with", "won't", "would", "wouldn't", "you", "you'd", "you'll", "you're", "you've", "your", "yours", "yourself", "yourselves"];

// Word replace

var tipuesearch_replace = {'words': [
     {'word': 'tipua', 'replace_with': 'tipue'},
     {'word': 'javscript', 'replace_with': 'javascript'},
     {'word': 'jqeury', 'replace_with': 'jquery'}
]};

// Weighting

var tipuesearch_weight = {'weight': [
     {'url': 'http://www.tipue.com', 'score': 200},
     {'url': 'http://www.tipue.com/search', 'score': 100},
     {'url': 'http://www.tipue.com/about', 'score': 100}
]};

// Stemming

var tipuesearch_stem = {'words': [
     {'word': 'e-mail', 'stem': 'email'},
     {'word': 'javascript', 'stem': 'jquery'},
     {'word': 'javascript', 'stem': 'js'}
]};

// Internal strings

var tipuesearch_string_1 = 'No title';
var tipuesearch_string_2 = 'Showing results for';
var tipuesearch_string_3 = 'Search instead for';
var tipuesearch_string_4 = '1 result';
var tipuesearch_string_5 = 'results';
var tipuesearch_string_6 = 'Prev';
var tipuesearch_string_7 = 'Next';
var tipuesearch_string_8 = 'Nothing found';
var tipuesearch_string_9 = 'Common words are largely ignored';
var tipuesearch_string_10 = 'Search too short';
var tipuesearch_string_11 = 'Should be one character or more';
var tipuesearch_string_12 = 'Should be';
var tipuesearch_string_13 = 'characters or more';
<commit_msg>translate tipuesearch to traditional Chinese<commit_after>
/*
Tipue Search 5.0
Copyright (c) 2015 Tipue
Tipue Search is released under the MIT License
http://www.tipue.com/search
*/

/*
Stop words
Stop words list from http://www.ranks.nl/stopwords
*/

var tipuesearch_stop_words = ["a", "about", "above", "after", "again", "against", "all", "am", "an", "and", "any", "are", "aren't", "as", "at", "be", "because", "been", "before", "being", "below", "between", "both", "but", "by", "can't", "cannot", "could", "couldn't", "did", "didn't", "do", "does", "doesn't", "doing", "don't", "down", "during", "each", "few", "for", "from", "further", "had", "hadn't", "has", "hasn't", "have", "haven't", "having", "he", "he'd", "he'll", "he's", "her", "here", "here's", "hers", "herself", "him", "himself", "his", "how", "how's", "i", "i'd", "i'll", "i'm", "i've", "if", "in", "into", "is", "isn't", "it", "it's", "its", "itself", "let's", "me", "more", "most", "mustn't", "my", "myself", "no", "nor", "not", "of", "off", "on", "once", "only", "or", "other", "ought", "our", "ours", "ourselves", "out", "over", "own", "same", "shan't", "she", "she'd", "she'll", "she's", "should", "shouldn't", "so", "some", "such", "than", "that", "that's", "the", "their", "theirs", "them", "themselves", "then", "there", "there's", "these", "they", "they'd", "they'll", "they're", "they've", "this", "those", "through", "to", "too", "under", "until", "up", "very", "was", "wasn't", "we", "we'd", "we'll", "we're", "we've", "were", "weren't", "what", "what's", "when", "when's", "where", "where's", "which", "while", "who", "who's", "whom", "why", "why's", "with", "won't", "would", "wouldn't", "you", "you'd", "you'll", "you're", "you've", "your", "yours", "yourself", "yourselves"];

// Word replace

var tipuesearch_replace = {'words': [
     {'word': 'tipua', 'replace_with': 'tipue'},
     {'word': 'javscript', 'replace_with': 'javascript'},
     {'word': 'jqeury', 'replace_with': 'jquery'}
]};

// Weighting

var tipuesearch_weight = {'weight': [
     {'url': 'http://www.tipue.com', 'score': 200},
     {'url': 'http://www.tipue.com/search', 'score': 100},
     {'url': 'http://www.tipue.com/about', 'score': 100}
]};

// Stemming

var tipuesearch_stem = {'words': [
     {'word': 'e-mail', 'stem': 'email'},
     {'word': 'javascript', 'stem': 'jquery'},
     {'word': 'javascript', 'stem': 'js'}
]};

// Internal strings

var tipuesearch_string_1 = '沒有標題';
var tipuesearch_string_2 = '目前顯示的是以下字詞的搜尋結果：';
var tipuesearch_string_3 = '您可以改回搜尋：';
var tipuesearch_string_4 = '1 項結果';
var tipuesearch_string_5 = '項結果';
var tipuesearch_string_6 = '前一頁';
var tipuesearch_string_7 = '下一頁';
var tipuesearch_string_8 = '沒找到任何結果';
var tipuesearch_string_9 = '常用字大部份都被忽略';
var tipuesearch_string_10 = '搜尋的字詞過短';
var tipuesearch_string_11 = '須有一個或更多字元';
var tipuesearch_string_12 = '須為';
var tipuesearch_string_13 = '個或更多字元';
<|endoftext|>


<commit_before>/* SBHS-Timetable-Node: Countdown and timetable all at once (NodeJS app).
 * Copyright (C) 2014 James Ye,  Simon Shields
 *
 * This file is part of SBHS-Timetable-Node.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

var timetable,
	belltimes,
	year,
	dateOffset = -1,
	needMidnightCountdown = false,
	reloading = false,
	currentBellIndex = -1, // next bell
	nextStart,
	manualOverride = 0, // manual date offset for public holidays etc (should cap at some number, TODO)
	topExpanded = false,
	leftExpanded = false,
	rightExpanded = false,
	bottomExpanded = false,
	miniMode = false;

/** calculate the day that school will be starting on - this may NOT use DateJS functions as it may be called before DateJS is loaded. */
function calculateDay() {
	'use strict';
	var date = new Date(),
		dayOffset = 0,
		schoolEnd = new Date();
	schoolEnd.setHours(15, 15);
	if (date.getDay() === 5 && date > schoolEnd) { // Friday
		dayOffset += 2; // push to Sunday at this time.
		needMidnightCountdown = true;
	} else if (date.getDay() === 6 ) { // Saturday
		dayOffset += 1; // same as above
		needMidnightCountdown = true;
	} else if (date.getDay() === 0 || date > schoolEnd) { // Sunday
		needMidnightCountdown = true;
	}
	date.setDate(date.getDate() + dayOffset + manualOverride);
	dateOffset = dayOffset;
}

/** returns midnight ON the next school day */
function getNextSchoolDay() {
	'use strict';
	if (dateOffset == -1) {
		calculateDay();
	}
	var res = new Date();
	res.setDate(res.getDate() + dateOffset + manualOverride + (needMidnightCountdown ? 1 : 0));
	res.setHours(0,0,0);
	return res;
}

/** returns the CURRENT TIME in dateOffset days */
function getDateOffsetDate() {
	'use strict';
	if (dateOffset == -1) {
		calculateDay();
	}
	var res = new Date();
	res.setDate(res.getDate() + dateOffset + manualOverride);
	return res;
}

function reloadBelltimes() {
	'use strict';
	reloading = true;
	var d = getNextSchoolDay();
	var s = d.getFullYear() + '-' + (d.getMonth()+1) + '-' + d.getDate();
	var myXHR = new XMLHttpRequest();
	myXHR.onload = handleBells;
	myXHR.open('get', '/api/belltimes?date=' + s, handleBells);
	myXHR.send();
	//$.getJSON('/api/belltimes?date=' + getNextSchoolDay().toString('yyyy-MM-d'), handleBells);
}

function handleBells(bells) {
	/* jshint validthis: true */
	'use strict';
	belltimes = JSON.parse(this.responseText);
	if (belltimes.status === 'Error') {
		manualOverride++;
		if (manualOverride > 5) {
			document.getElementById('period-label').innerHTML = 'WAT?!?';
			console.error('No bells for more than five days in a row, SBHS might be down!');
			return;
		}
		document.getElementById('period-label').innerHTML = 'One sec...';
		reloadBelltimes();
		return;
	}
	setTimeout(loadTimetable, 0); // now that the belltimes are done, we can load the subject info
	setTimeout(loadNotices, 0);
	if (document.readyState == 'complete') {
		loadComplete();
	}
}

reloadBelltimes(); // do it ASAP

function domReady() {
	'use strict';
	if (document.readyState != 'complete') {
		return;
	}
	if (belltimes !== null && belltimes !== undefined) {
		setTimeout(loadComplete, 0);
	}
	if (getLoggedIn()) {
		$('#login-status').html('Logged in. Logout');
	}
	else {
		$('#login-status').html('Login');
	}

	$('#left-pane-arrow').click(function() {
		if (topExpanded) {
			$('#top-pane-arrow,#top-pane').toggleClass('expanded');
			topExpanded = !topExpanded;
		}
		leftExpanded = !leftExpanded;
		$('#left-pane-arrow,#left-pane').toggleClass('expanded');
	});

	$('#top-pane-arrow').click(function() {
		if (leftExpanded) {
			$('#left-pane-arrow,#left-pane').removeClass('expanded');
			leftExpanded = !leftExpanded;
		}
		topExpanded = !topExpanded;
		$('#top-pane-arrow,#top-pane').toggleClass('expanded');
	});
}

function loadComplete() {
	'use strict';
	reloading = false;
	calculateUpcomingLesson();
	updateCountdownLabel();
	setInterval(updateCountdownLabel, 1000);
}

function prettifySecondsLeft(sec) {
	'use strict';
	var secs, mins, hrs;
	secs = '' + sec % 60;
	sec -= sec % 60;
	sec /= 60;
	mins = '' + sec % 60;
	sec -= sec % 60;
	sec /= 60;
	hrs = '' + sec;
	if (secs.length == 1) {
		secs = '0' + secs;
	}
	if (mins.length == 1) {
		mins = '0' + mins;
	}
	if (hrs == '0') {
		hrs = '';
	} else if (hrs.length == 1) {
		hrs = '0' + hrs;
	}
	return (hrs !== '' ? hrs + 'h ' : '') + mins + 'm ' + secs + 's';
}

function calculateUpcomingLesson() {
	'use strict';
	reloading = true;
	var i, lastOK = 0, bell, bdate, nextBell, now;
	if (belltimes === null) {
		reloadBelltimes();
		reloading = false;
		return;
	}
	if ((new Date()).isAfter(Date.today().set({hour: 15, minute: 15})) || (new Date()).getDay() > 5) {
		now = getNextSchoolDay();
	} else {
		now = new Date();
	}
	for (i in belltimes.bells) {
		bell = belltimes.bells[i].time.split(':');
		bdate = now.clone().set({hour: Number(bell[0]), minute: Number(bell[1]), second: 0});
		if ((nextBell === undefined || nextBell.isAfter(bdate)) && bdate.isAfter(new Date())) {
			nextBell = bdate;
			lastOK = i;
		}
	}
	if (nextBell === undefined) {
		calculateDay();
		reloadBelltimes();
	}
	currentBellIndex = Number(lastOK);
	nextStart = nextBell;
	reloading = false;
	setTimeout(updatePeriodLabel, 100); // async
}

function updatePeriodLabel() {
	'use strict';
	var name = belltimes.bells[currentBellIndex].bell,
		inLabel = 'starts in', pNum, roomChangedInfo, hasCover, hasCasual;
	name = name.replace('Roll Call', 'School Starts').replace('End of Day', 'School Ends');
	if (/^\d$/.test(name)) { // 'Period x' instead of 'x'
		pNum = name;
		if (name in window.todayNames.timetable) {
			name = window.todayNames.timetable[name].fullName;
		}
		else {
			name = 'Period ' + name;
		}
	} else if (name == 'Transition') {
		pNum = belltimes.bells[currentBellIndex-1].bell;
		if (pNum in window.todayNames.timetable) {
			name = window.todayNames.timetable[belltimes.bells[currentBellIndex-1].bell].fullName;
		}
		else {
			name = 'Period ' + belltimes.bells[currentBellIndex - 1].bell;
		}
		inLabel = 'ends in';
	} else if (name == 'School Starts' || name == 'School Ends') {
		inLabel = 'in';
	}
	if (pNum && pNum in window.todayNames.timetable && window.todayNames.timetable[pNum].changed) {
		pNum = window.todayNames.timetable[pNum];
		roomChangedInfo = '';
		if ('roomTo' in pNum) {
			roomChangedInfo = name + ' is in room ' + pNum.roomTo + ' instead of ' + pNum.roomFrom + '. ';
		}
		if ('hasCover' in pNum) {
			if (pNum.hasCover && pNum.hasCasual) { // casual teacher
				roomChangedInfo += 'You\'ll be having ' + pNum.casualDisplay + ' instead of your usual teacher.';
			}
			else if (!pNum.hasCover) { // no teacher
				roomChangedInfo += 'There\'s no teacher covering this class today (we think).';
			}
		}
	}
	$('#period-label').text(name);
	$('#in-label').text(inLabel);
	$('#top-line-notice').text(roomChangedInfo);
}

function updateCountdownLabel() {
	'use strict';
	if (reloading) {
		return;
	}
	if (nextStart === null) {
		calculateUpcomingLesson();
		return;
	}
	var now = new Date(),
		left = nextStart - now;
	if (left < 0) {
		calculateUpcomingLesson();
		return;
	}
	left = nextStart - now;
	$('#countdown-label').text(prettifySecondsLeft(Math.floor(left/1000)));
}

document.addEventListener('readystatechange', domReady);
<commit_msg>countdown.js: blah<commit_after>/* SBHS-Timetable-Node: Countdown and timetable all at once (NodeJS app).
 * Copyright (C) 2014 James Ye,  Simon Shields
 *
 * This file is part of SBHS-Timetable-Node.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

/*jshint latedef:nofunc*/
var timetable,
	belltimes,
	year,
	dateOffset = -1,
	needMidnightCountdown = false,
	reloading = false,
	currentBellIndex = -1, // next bell
	nextStart,
	manualOverride = 0, // manual date offset for public holidays etc (should cap at some number, TODO)
	topExpanded = false,
	leftExpanded = false,
	rightExpanded = false,
	bottomExpanded = false,
	miniMode = false;

/** calculate the day that school will be starting on - this may NOT use DateJS functions as it may be called before DateJS is loaded. */
function calculateDay() {
	'use strict';
	var date = new Date(),
		dayOffset = 0,
		schoolEnd = new Date();
	schoolEnd.setHours(15, 15);
	if (date.getDay() === 5 && date > schoolEnd) { // Friday
		dayOffset += 2; // push to Sunday at this time.
		needMidnightCountdown = true;
	} else if (date.getDay() === 6 ) { // Saturday
		dayOffset += 1; // same as above
		needMidnightCountdown = true;
	} else if (date.getDay() === 0 || date > schoolEnd) { // Sunday
		needMidnightCountdown = true;
	}
	date.setDate(date.getDate() + dayOffset + manualOverride);
	dateOffset = dayOffset;
}

/** returns midnight ON the next school day */
function getNextSchoolDay() {
	'use strict';
	if (dateOffset == -1) {
		calculateDay();
	}
	var res = new Date();
	res.setDate(res.getDate() + dateOffset + manualOverride + (needMidnightCountdown ? 1 : 0));
	res.setHours(0,0,0);
	return res;
}

/** returns the CURRENT TIME in dateOffset days */
function getDateOffsetDate() {
	'use strict';
	if (dateOffset == -1) {
		calculateDay();
	}
	var res = new Date();
	res.setDate(res.getDate() + dateOffset + manualOverride);
	return res;
}

function reloadBelltimes() {
	'use strict';
	reloading = true;
	var d = getNextSchoolDay();
	var s = d.getFullYear() + '-' + (d.getMonth()+1) + '-' + d.getDate();
	var myXHR = new XMLHttpRequest();
	myXHR.onload = handleBells;
	myXHR.open('get', '/api/belltimes?date=' + s, handleBells);
	myXHR.send();
	//$.getJSON('/api/belltimes?date=' + getNextSchoolDay().toString('yyyy-MM-d'), handleBells);
}

function handleBells(bells) {
	/* jshint validthis: true */
	'use strict';
	belltimes = JSON.parse(this.responseText);
	if (belltimes.status === 'Error') {
		manualOverride++;
		if (manualOverride > 5) {
			document.getElementById('period-label').innerHTML = 'WAT?!?';
			console.error('No bells for more than five days in a row, SBHS might be down!');
			return;
		}
		document.getElementById('period-label').innerHTML = 'One sec...';
		reloadBelltimes();
		return;
	}
	setTimeout(loadTimetable, 0); // now that the belltimes are done, we can load the subject info
	setTimeout(loadNotices, 0);
	if (document.readyState == 'complete') {
		loadComplete();
	}
}

reloadBelltimes(); // do it ASAP

function domReady() {
	'use strict';
	if (document.readyState != 'complete') {
		return;
	}
	if (belltimes !== null && belltimes !== undefined) {
		setTimeout(loadComplete, 0);
	}
	if (getLoggedIn()) {
		$('#login-status').html('Logged in. Logout');
	}
	else {
		$('#login-status').html('Login');
	}

	$('#left-pane-arrow').click(function() {
		if (topExpanded) {
			$('#top-pane-arrow,#top-pane').toggleClass('expanded');
			topExpanded = !topExpanded;
		}
		leftExpanded = !leftExpanded;
		$('#left-pane-arrow,#left-pane').toggleClass('expanded');
	});

	$('#top-pane-arrow').click(function() {
		if (leftExpanded) {
			$('#left-pane-arrow,#left-pane').removeClass('expanded');
			leftExpanded = !leftExpanded;
		}
		topExpanded = !topExpanded;
		$('#top-pane-arrow,#top-pane').toggleClass('expanded');
	});
}

function loadComplete() {
	'use strict';
	reloading = false;
	calculateUpcomingLesson();
	updateCountdownLabel();
	setInterval(updateCountdownLabel, 1000);
}

function prettifySecondsLeft(sec) {
	'use strict';
	var secs, mins, hrs;
	secs = '' + sec % 60;
	sec -= sec % 60;
	sec /= 60;
	mins = '' + sec % 60;
	sec -= sec % 60;
	sec /= 60;
	hrs = '' + sec;
	if (secs.length == 1) {
		secs = '0' + secs;
	}
	if (mins.length == 1) {
		mins = '0' + mins;
	}
	if (hrs == '0') {
		hrs = '';
	} else if (hrs.length == 1) {
		hrs = '0' + hrs;
	}
	return (hrs !== '' ? hrs + 'h ' : '') + mins + 'm ' + secs + 's';
}

function calculateUpcomingLesson() {
	'use strict';
	reloading = true;
	var i, lastOK = 0, bell, bdate, nextBell, now;
	if (belltimes === null) {
		reloadBelltimes();
		reloading = false;
		return;
	}
	if ((new Date()).isAfter(Date.today().set({hour: 15, minute: 15})) || (new Date()).getDay() > 5) {
		now = getNextSchoolDay();
	} else {
		now = new Date();
	}
	for (i in belltimes.bells) {
		bell = belltimes.bells[i].time.split(':');
		bdate = now.clone().set({hour: Number(bell[0]), minute: Number(bell[1]), second: 0});
		if ((nextBell === undefined || nextBell.isAfter(bdate)) && bdate.isAfter(new Date())) {
			nextBell = bdate;
			lastOK = i;
		}
	}
	if (nextBell === undefined) {
		calculateDay();
		reloadBelltimes();
	}
	currentBellIndex = Number(lastOK);
	nextStart = nextBell;
	reloading = false;
	setTimeout(updatePeriodLabel, 100); // async
}

function updatePeriodLabel() {
	'use strict';
	var name = belltimes.bells[currentBellIndex].bell,
		inLabel = 'starts in', pNum, roomChangedInfo, hasCover, hasCasual;
	name = name.replace('Roll Call', 'School Starts').replace('End of Day', 'School Ends');
	if (/^\d$/.test(name)) { // 'Period x' instead of 'x'
		pNum = name;
		if (name in window.todayNames.timetable) {
			name = window.todayNames.timetable[name].fullName;
		}
		else {
			name = 'Period ' + name;
		}
	} else if (name == 'Transition') {
		pNum = belltimes.bells[currentBellIndex-1].bell;
		if (pNum in window.todayNames.timetable) {
			name = window.todayNames.timetable[belltimes.bells[currentBellIndex-1].bell].fullName;
		}
		else {
			name = 'Period ' + belltimes.bells[currentBellIndex - 1].bell;
		}
		inLabel = 'ends in';
	} else if (name == 'School Starts' || name == 'School Ends') {
		inLabel = 'in';
	}
	if (pNum && pNum in window.todayNames.timetable && window.todayNames.timetable[pNum].changed) {
		pNum = window.todayNames.timetable[pNum];
		roomChangedInfo = '';
		if ('roomTo' in pNum) {
			roomChangedInfo = name + ' is in room ' + pNum.roomTo + ' instead of ' + pNum.roomFrom + '. ';
		}
		if ('hasCover' in pNum) {
			if (pNum.hasCover && pNum.hasCasual) { // casual teacher
				roomChangedInfo += 'You\'ll be having ' + pNum.casualDisplay + ' instead of your usual teacher.';
			}
			else if (!pNum.hasCover) { // no teacher
				roomChangedInfo += 'There\'s no teacher covering this class today (we think).';
			}
		}
	}
	$('#period-label').text(name);
	$('#in-label').text(inLabel);
	$('#top-line-notice').text(roomChangedInfo);
}

function updateCountdownLabel() {
	'use strict';
	if (reloading) {
		return;
	}
	if (nextStart === null) {
		calculateUpcomingLesson();
		return;
	}
	var now = new Date(),
		left = nextStart - now;
	if (left < 0) {
		calculateUpcomingLesson();
		return;
	}
	left = nextStart - now;
	$('#countdown-label').text(prettifySecondsLeft(Math.floor(left/1000)));
}

document.addEventListener('readystatechange', domReady);
<|endoftext|>


<commit_before>'use strict';
if(process.env.NODE_ENV === 'dev') require('dotenv').config();

const Twit = require('twit'),
      AWS = require('aws-sdk'),
      Dynamo = new AWS.DynamoDB.DocumentClient(),
      uuidv1 =require('uuid/v1');

module.exports.hello = (event, context, callback) => {
  const response = {
    statusCode: 200,
    body: JSON.stringify({
      message: 'Go Serverless v1.0! Your function executed successfully!',
      input: event,
    }),
  };

  callback(null, response);

  // Use this code if you don't use the http event with the LAMBDA-PROXY integration
  // callback(null, { message: 'Go Serverless v1.0! Your function executed successfully!', event });
};

module.exports.getTwitterHottakes = (event, context, callback) => {

   let t = new Twit({
    consumer_key:         process.env.consumer_key,
    consumer_secret:      process.env.consumer_secret,
    access_token:         process.env.access_token,
    access_token_secret:  process.env.access_token_secret,
    timeout_ms:           10*1000,
  }), searchParams, yesterday;

  // set the yesterday variable
  yesterday = new Date();
  yesterday = yesterday.setDate(yesterday.getDate() - 1);

  searchParams = {
    q: `hottake -filter:retweets  since:${yesterday.getYear()-yesterday.getMonth()-yesterday.getDate()}`,
    lang: 'en',
    count: 25,
    include_rts: false
  }

  t.get('search/tweets', searchParams, (err, data, response) => {
    if(data.statuses.length)
    {
      let batchWriteDynamo = data.statuses.map( data => {
        let { created_at, id, text, user } = data,
        uuid = uuidv1();

        return {
           PutRequest: {
             Item: {
               "uuid": {
                S: uuid
               },
               "origin_id": {
                 S: id
               },
               "created_at": {
                 S: created_at
               },
               "user_id": {
                 S: user.id
               },
               "name": {
                 S: user.screen_name
               },
               "text": {
                 S: text
               },
               "origin": {
                 S: 'twitter'
               },
               "score": {
                 N: "0"
               },
               "ups": {
                 N: "0"
               },
               "downs": {
                 N: "0"
               }
             }
           }
        }
      });
      Dynamo.BatchWriteItem({ RequestItems: { "HottakesTable": batchWriteDynamo } }, (err, data) => {
        callback(err, data)
      })
    }
    callback()
  })
}

module.exports.voteUp = (event, context, callback) => {
  const uuid = event.path.id,
  params = {
    ExpressionAttributeNames: {
      "#S": "score",
      "#U": "ups"
    },
    ExpressionAttributeValues: {
      ":a": {
        N: "1"
      }
    },
    TableName: "HottakesTable",
    Key: {
      "uuid": {
        S: uuid
      }
    },
    UpdateExpression: "ADD #S :a, #U :a"
  };
  Dynamo.updateItem(params, (err, data) => {
      callback(err,data)
  })
};

module.exports.voteDown = (event, context, callback) => {
  const uuid = event.path.id,
  params = {
    ExpressionAttributeNames: {
      "#S": "score",
      "#D": "downs"
    },
    ExpressionAttributeValues: {
      ":m": {
        N: "-1"
      }
    },
    TableName: "HottakesTable",
    Key: {
      "uuid": {
        S: uuid
      }
    },
    UpdateExpression: "ADD #S :m, #D :m"
  };
  Dynamo.updateItem(params, (err, data) => {
      callback(err,data)
  })
};

module.exports.deleteTake = (event, context, callback) => {};

module.exports.submitTake = (event, context, callback) => {};

module.exports.getRandomTake = (event, context, callback) => {};

<commit_msg>add http responses to lambda calls<commit_after>'use strict';
if(process.env.NODE_ENV === 'dev') require('dotenv').config();

const Twit = require('twit'),
      AWS = require('aws-sdk'),
      Dynamo = new AWS.DynamoDB.DocumentClient(),
      uuidv1 =require('uuid/v1');

module.exports.hello = (event, context, callback) => {
  const response = {
    statusCode: 200,
    body: JSON.stringify({
      message: 'Go Serverless v1.0! Your function executed successfully!',
      input: event,
    }),
  };

  callback(null, response);

  // Use this code if you don't use the http event with the LAMBDA-PROXY integration
  // callback(null, { message: 'Go Serverless v1.0! Your function executed successfully!', event });
};

module.exports.getTwitterHottakes = (event, context, callback) => {

   let t = new Twit({
    consumer_key:         process.env.consumer_key,
    consumer_secret:      process.env.consumer_secret,
    access_token:         process.env.access_token,
    access_token_secret:  process.env.access_token_secret,
    timeout_ms:           10*1000,
  }), searchParams, yesterday;

  // set the yesterday variable
  yesterday = new Date();
  yesterday = yesterday.setDate(yesterday.getDate() - 1);

  searchParams = {
    q: `hottake -filter:retweets  since:${yesterday.getYear()-yesterday.getMonth()-yesterday.getDate()}`,
    lang: 'en',
    count: 25,
    include_rts: false
  }

  t.get('search/tweets', searchParams, (err, data, response) => {
      let batchWriteDynamo = data.statuses.map( data => {
        let { created_at, id, text, user } = data,
        uuid = uuidv1();

        return {
           PutRequest: {
             Item: {
               "uuid": {
                S: uuid
               },
               "origin_id": {
                 S: id
               },
               "created_at": {
                 S: created_at
               },
               "user_id": {
                 S: user.id
               },
               "name": {
                 S: user.screen_name
               },
               "text": {
                 S: text
               },
               "origin": {
                 S: 'twitter'
               },
               "score": {
                 N: "0"
               },
               "ups": {
                 N: "0"
               },
               "downs": {
                 N: "0"
               }
             }
           }
        }
      }),
      response = {};

      Dynamo.BatchWriteItem({ RequestItems: { "HottakesTable": batchWriteDynamo } }, (err, data) => {
        if(err){
          callback(new Error('[400] Bad Request'))
        }
        else{
          response.statusCode = 200
          response.body = { message: `Successfuly added takes to db`}
          callback(null, response)
        }
      })
  })
}

module.exports.voteUp = (event, context, callback) => {
  const uuid = event.path.id,
  params = {
    ExpressionAttributeNames: {
      "#S": "score",
      "#U": "ups"
    },
    ExpressionAttributeValues: {
      ":a": {
        N: "1"
      }
    },
    TableName: "HottakesTable",
    Key: {
      "uuid": {
        S: uuid
      }
    },
    UpdateExpression: "ADD #S :a, #U :a"
  },
  response = {};

  Dynamo.updateItem(params, (err, data) => {
    if(err){
      callback(new Error('[400] Bad Request'))
    }
    else{
      response.statusCode = 200
      response.body = { message: `Successfuly upvoted item ${uuid}`}
      callback(null, response)
    }
  })
};

module.exports.voteDown = (event, context, callback) => {
  const uuid = event.path.id,
  params = {
    ExpressionAttributeNames: {
      "#S": "score",
      "#D": "downs"
    },
    ExpressionAttributeValues: {
      ":m": {
        N: "-1"
      }
    },
    TableName: "HottakesTable",
    Key: {
      "uuid": {
        S: uuid
      }
    },
    UpdateExpression: "ADD #S :m, #D :m"
  },
  response = {};

  Dynamo.updateItem(params, (err, data) => {
    if(err){
      callback(new Error('[400] Bad Request'))
    }
    else{
      response.statusCode = 200
      response.body = { message: `Successfuly downvoted item ${uuid}`}
      callback(null, response)
    }
  })
};

module.exports.deleteTake = (event, context, callback) => {};

module.exports.submitTake = (event, context, callback) => {};

module.exports.getRandomTake = (event, context, callback) => {};
<|endoftext|>


<commit_before>var request = require("request");
var cheerio = require("cheerio");
var playlistdata = require('../lib/services/playlistdata');
var firebaseURL;

module.exports = {
	startFetcher: function startFetcher(firebaseURL) {
		this.firebaseURL = firebaseURL;

		playlistdata.init({
			firebaseURL: this.firebaseURL
		}, start);

		function start() {
			console.log('ClubFM fetcher starting');

			var postdata = {
				id: 'clubfm',
				description: 'Club FM',
				name: 'Club FM',
				website: 'http://www.radioclubfm.info/',
				icon: 'http://www.radiosplay.com/logos/5/4/8/0/54808.png'
			};

			console.log("ClubFM channel to be saved=", postdata);

			playlistdata.postChannel(postdata);

			fetchData();

			// fetch the data status every 3 min.
			var checkInterval = setInterval(function() {
				fetchData();
				//			}, (10 * 1000));
			}, (3 * 60 + Math.random() * 30) * 1000);
		}

	},
	status: function status() {
		return ({
			name: "ClubFM"
		});
	}

};

function fetchData() {
	request({
		uri: "http://id.web1.radiotuna.com/backpassage/backchannel.ashx?roomId=108982",
	}, function(error, response, body) {
		var result = extract(body);

		if (result) {

			var songdata = {
				channelid: 'clubfm',
				artist: result.artist,
				image: result.image,
				title: result.title,
				unixtimestamp: Math.floor(new Date().getTime() / 1000),
			};
			console.log('song data : ', songdata);

			playlistdata.postSong(songdata);
		} else {
			console.log('ClubFM : nothing to save');
		}

	});
}

/*
console.log(extract('
Ian Thomas
 Till The Morning (ft Flo Rida And Lilana
iTunes | Facebook | Twitter
'));
console.log(extract('
Live
 They Stood Up For Love
'));
console.log(extract('
Nieuws
'));
console.log(extract(''));
*/

//console.log(extract('<connectionId>76a3941affed401bb5c25fda66f775dd</connectionId><streams><stream streamName="ClubFM" streamUrl="http://shoutcast2.clubfmserver.be:8008/" bitrate="128" /></streams><song artistId="-1" trackId="-1">FELIX JAEHN - AINT NOBODY (LOVES ME BETTER)</song>'));

function extract(body) {

	try {

		var $ = cheerio.load(body);
		var result = {};

		var desc = $("song").text();
		result.artist = desc.split('-')[0];
		result.title = desc.split('-')[1];

		if (result.artist) {
			result.artist = result.artist.trim();
		}
		if (result.title) {
			result.title = result.title.trim();
		}

		if (result.artist.indexOf("NIEUWS") > -1) {
			console.log('clubFM - nieuws');
			return ();
		}

		return (result);
	} catch (e) {
		console.error(e);
		return;
	}
}

/*

Ian Thomas
 Till The Morning (ft Flo Rida And Lilana

iTunes | Facebook | Twitter

*/

/*

Live
 They Stood Up For Love

*/

/*

Nieuws

*/<commit_msg>typo fixed.<commit_after>var request = require("request");
var cheerio = require("cheerio");
var playlistdata = require('../lib/services/playlistdata');
var firebaseURL;

module.exports = {
	startFetcher: function startFetcher(firebaseURL) {
		this.firebaseURL = firebaseURL;

		playlistdata.init({
			firebaseURL: this.firebaseURL
		}, start);

		function start() {
			console.log('ClubFM fetcher starting');

			var postdata = {
				id: 'clubfm',
				description: 'Club FM',
				name: 'Club FM',
				website: 'http://www.radioclubfm.info/',
				icon: 'http://www.radiosplay.com/logos/5/4/8/0/54808.png'
			};

			console.log("ClubFM channel to be saved=", postdata);

			playlistdata.postChannel(postdata);

			fetchData();

			// fetch the data status every 3 min.
			var checkInterval = setInterval(function() {
				fetchData();
				//			}, (10 * 1000));
			}, (3 * 60 + Math.random() * 30) * 1000);
		}

	},
	status: function status() {
		return ({
			name: "ClubFM"
		});
	}

};

function fetchData() {
	request({
		uri: "http://id.web1.radiotuna.com/backpassage/backchannel.ashx?roomId=108982",
	}, function(error, response, body) {
		var result = extract(body);

		if (result) {

			var songdata = {
				channelid: 'clubfm',
				artist: result.artist,
				image: result.image,
				title: result.title,
				unixtimestamp: Math.floor(new Date().getTime() / 1000),
			};
			console.log('song data : ', songdata);

			playlistdata.postSong(songdata);
		} else {
			console.log('ClubFM : nothing to save');
		}

	});
}

/*
console.log(extract('
Ian Thomas
 Till The Morning (ft Flo Rida And Lilana
iTunes | Facebook | Twitter
'));
console.log(extract('
Live
 They Stood Up For Love
'));
console.log(extract('
Nieuws
'));
console.log(extract(''));
*/

//console.log(extract('<connectionId>76a3941affed401bb5c25fda66f775dd</connectionId><streams><stream streamName="ClubFM" streamUrl="http://shoutcast2.clubfmserver.be:8008/" bitrate="128" /></streams><song artistId="-1" trackId="-1">FELIX JAEHN - AINT NOBODY (LOVES ME BETTER)</song>'));

function extract(body) {

	try {

		var $ = cheerio.load(body);
		var result = {};

		var desc = $("song").text();
		result.artist = desc.split('-')[0];
		result.title = desc.split('-')[1];

		if (result.artist) {
			result.artist = result.artist.trim();
		}
		if (result.title) {
			result.title = result.title.trim();
		}

		if (result.artist.indexOf("NIEUWS") > -1) {
			console.log('clubFM - nieuws');
			return;
		}

		return (result);
	} catch (e) {
		console.error(e);
		return;
	}
}

/*

Ian Thomas
 Till The Morning (ft Flo Rida And Lilana

iTunes | Facebook | Twitter

*/

/*

Live
 They Stood Up For Love

*/

/*

Nieuws

*/<|endoftext|>


<commit_before>'use strict'

const path = require('path')

const projectRoot = path.join(__dirname, '..')
const appPackage = require(path.join(projectRoot, 'package.json'))

module.exports.getDistPath = function () {
  return path.join(projectRoot, 'dist', `${appPackage.productName}-${process.platform}-x64`)
}

module.exports.getProductName = function () {
  return appPackage.productName
}

module.exports.getCompanyName = function () {
  return appPackage.companyName
}
<commit_msg>Expose some of the artifact paths.<commit_after>'use strict'

const path = require('path')

const projectRoot = path.join(__dirname, '..')
const appPackage = require(path.join(projectRoot, 'package.json'))

function getDistPath () {
  return path.join(projectRoot, 'dist', `${appPackage.productName}-${process.platform}-x64`)
}

function getProductName () {
  return appPackage.productName
}

function getCompanyName () {
  return appPackage.companyName
}

function getVersion () {
  return appPackage.version
}

function getOSXZipPath () {
  const productName = getProductName()
  return path.join(getDistPath(), '..', `${productName}.zip`)
}

function getWindowsInstallerPath () {
  const productName = getProductName()
  return path.join(getDistPath(), '..', 'installer', `${productName}.msi`)
}

module.exports = {getDistPath, getProductName, getCompanyName, getVersion, getOSXZipPath, getWindowsInstallerPath}
<|endoftext|>


<commit_before>var CHROME_INNER_URL_PATTERN = /^chrome(-.+)?\:\/\/.+/,
    LOCAL_FILE_URL_PATTERN = /^file\:\/\/.+/,
    NEWTAB = { url: 'chrome://newtab/', selected : false },
    NOT_PINED_TABS = { pinned: false, windowType: 'normal' },
    KEY_YOUR_LAST_TABS = 'KEY_YOUR_LAST_TABS',
    KEY_YOUR_LAST_TABS_TMP = 'KEY_YOUR_LAST_TABS_TMP',
    GET_POSITION_INJECTION = { code: '({ top: document.body.scrollTop, left: document.body.scrollLeft })' },
    DEFAULT_POSITION = { top: 0, left: 0 },
    OPTIONS_URL = chrome.extension.getURL('page/options.html'),
    EMPTY_STR = '';

function is_newtab(tab) {
    return tab.url == NEWTAB.url;
}

function has_last_tabs_tmp(items) {
    return items != null && items.KEY_YOUR_LAST_TABS_TMP != null && items.KEY_YOUR_LAST_TABS_TMP.length > 0;
}

function is_url_ok(url) {
    return url != null && url != EMPTY_STR && !CHROME_INNER_URL_PATTERN.test(url) && !LOCAL_FILE_URL_PATTERN.test(url);
}

function is_position_valid(pos) {
    var typeNum = typeof(0);
    return pos != null && typeof(pos.top) == typeNum && typeof(pos.left) == typeNum;
}

function is_positions_ready(positions, current_tabs) {
    var i = 0, tab = null;
    for (; i < current_tabs.length; ++i) {
        tab = current_tabs[i];
        if (positions[tab.url] == null) {
            return false;
        }
    }
    return true;
}

function get_tab_title(url, title) {
    return title == null || title == EMPTY_STR ? url : title;
}

function extract_position(ary) {
    return chrome.runtime.lastError != null || ary == null || ary.length == 0 ? DEFAULT_POSITION : ary[0];
}

function save_all_windows_tabs() {
    chrome.tabs.query(NOT_PINED_TABS, function (tabs) {
        var current_tabs = [], url_map = {}, positions = {}, check_id = null;
        tabs.forEach(function (tab) {
            var url = tab.url;
            if (!url_map[url] && is_url_ok(url)) {
                chrome.tabs.get(tab.id, function (t) { // to ensure the tab was
                    if (t != null) {                   // not bean removed
                        var title = get_tab_title(url, t.title);
                        current_tabs.push({ url: url, title: title });
                        url_map[url] = true;
                        if (url != title) { // only execute get position script on those no error pages
                            chrome.tabs.executeScript(t.id, GET_POSITION_INJECTION, function (ary) {
                                positions[url] = extract_position(ary);
                            });
                        }
                        else {
                            positions[url] = DEFAULT_POSITION;
                        }
                    }
                });
            }
        });
        check_id = setInterval(function () {
            if (check_id !== null && is_positions_ready(positions, current_tabs)) {
                clearInterval(check_id);
                check_id = null;
                current_tabs.forEach(function (tab) {
                    tab.position = positions[tab.url];
                });
                get_options(function (options) {
                    var diff = current_tabs.length - options.MAX_RECORD_COUNT;
                    if (diff >= 0) {
                        if (diff > 0) {
                            current_tabs = current_tabs.slice(diff, current_tabs.length);
                        }
                        chrome.storage.local.set({ KEY_YOUR_LAST_TABS: current_tabs });
                    }
                    else {
                        chrome.storage.local.get(KEY_YOUR_LAST_TABS_TMP, function (items) {
                            if (has_last_tabs_tmp(items)) {
                                var legacy_tabs = items.KEY_YOUR_LAST_TABS_TMP;
                                diff += legacy_tabs.length;
                                if (diff < legacy_tabs.length) {
                                    if (diff > 0) {
                                        legacy_tabs = legacy_tabs.slice(diff, legacy_tabs.length);
                                    }
                                    current_tabs.push.apply(current_tabs, legacy_tabs);
                                }
                            }
                            chrome.storage.local.set({ KEY_YOUR_LAST_TABS: current_tabs });
                        });
                    }
                });
            }
        }, 400);
    });
}
<commit_msg>Remove useless judgement, fall back<commit_after>var CHROME_INNER_URL_PATTERN = /^chrome(-.+)?\:\/\/.+/,
    LOCAL_FILE_URL_PATTERN = /^file\:\/\/.+/,
    NEWTAB = { url: 'chrome://newtab/', selected : false },
    NOT_PINED_TABS = { pinned: false, windowType: 'normal' },
    KEY_YOUR_LAST_TABS = 'KEY_YOUR_LAST_TABS',
    KEY_YOUR_LAST_TABS_TMP = 'KEY_YOUR_LAST_TABS_TMP',
    GET_POSITION_INJECTION = { code: '({ top: document.body.scrollTop, left: document.body.scrollLeft })' },
    DEFAULT_POSITION = { top: 0, left: 0 },
    OPTIONS_URL = chrome.extension.getURL('page/options.html'),
    EMPTY_STR = '';

function is_newtab(tab) {
    return tab.url == NEWTAB.url;
}

function has_last_tabs_tmp(items) {
    return items != null && items.KEY_YOUR_LAST_TABS_TMP != null && items.KEY_YOUR_LAST_TABS_TMP.length > 0;
}

function is_url_ok(url) {
    return url != null && url != EMPTY_STR && !CHROME_INNER_URL_PATTERN.test(url) && !LOCAL_FILE_URL_PATTERN.test(url);
}

function is_position_valid(pos) {
    var typeNum = typeof(0);
    return pos != null && typeof(pos.top) == typeNum && typeof(pos.left) == typeNum;
}

function is_positions_ready(positions, current_tabs) {
    var i = 0, tab = null;
    for (; i < current_tabs.length; ++i) {
        tab = current_tabs[i];
        if (positions[tab.url] == null) {
            return false;
        }
    }
    return true;
}

function get_tab_title(url, title) {
    return title == null || title == EMPTY_STR ? url : title;
}

function extract_position(ary) {
    return chrome.runtime.lastError != null || ary == null || ary.length == 0 ? DEFAULT_POSITION : ary[0];
}

function save_all_windows_tabs() {
    chrome.tabs.query(NOT_PINED_TABS, function (tabs) {
        var current_tabs = [], url_map = {}, positions = {}, check_id = null;
        tabs.forEach(function (tab) {
            var url = tab.url;
            if (!url_map[url] && is_url_ok(url)) {
                chrome.tabs.get(tab.id, function (t) { // to ensure the tab was
                    if (t != null) {                   // not bean removed
                        current_tabs.push({ url: url, title: get_tab_title(url, t.title) });
                        url_map[url] = true;
                        chrome.tabs.executeScript(t.id, GET_POSITION_INJECTION, function (ary) {
                            positions[url] = extract_position(ary);
                        });
                    }
                });
            }
        });
        check_id = setInterval(function () {
            if (check_id !== null && is_positions_ready(positions, current_tabs)) {
                clearInterval(check_id);
                check_id = null;
                current_tabs.forEach(function (tab) {
                    tab.position = positions[tab.url];
                });
                get_options(function (options) {
                    var diff = current_tabs.length - options.MAX_RECORD_COUNT;
                    if (diff >= 0) {
                        if (diff > 0) {
                            current_tabs = current_tabs.slice(diff, current_tabs.length);
                        }
                        chrome.storage.local.set({ KEY_YOUR_LAST_TABS: current_tabs });
                    }
                    else {
                        chrome.storage.local.get(KEY_YOUR_LAST_TABS_TMP, function (items) {
                            if (has_last_tabs_tmp(items)) {
                                var legacy_tabs = items.KEY_YOUR_LAST_TABS_TMP;
                                diff += legacy_tabs.length;
                                if (diff < legacy_tabs.length) {
                                    if (diff > 0) {
                                        legacy_tabs = legacy_tabs.slice(diff, legacy_tabs.length);
                                    }
                                    current_tabs.push.apply(current_tabs, legacy_tabs);
                                }
                            }
                            chrome.storage.local.set({ KEY_YOUR_LAST_TABS: current_tabs });
                        });
                    }
                });
            }
        }, 400);
    });
}
<|endoftext|>


<commit_before>var fileService = require('./fileService');
var File = require('./fileModel');
var mysql = require('./mysql');
var dbPool = mysql.createPool();

var express = require('express');
var multer  = require('multer');
var upload = multer({ dest: 'uploads', files: 5 });

var app = express();

app.put('/file', upload.single('presentation'), function (request, response, next) {
  var uploadedFile = request.file;

  var file = new File({
    name: uploadedFile.originalname,
    url: uploadedFile.path,
    mime_type: uploadedFile.mimetype
  });

  fileService.createAttachment(file, dbPool, function (id) {
  	response.status(201).json({id: id});
  });
});

app.listen(3003);
<commit_msg>Set parameter name to 'file'<commit_after>var fileService = require('./fileService');
var File = require('./fileModel');
var mysql = require('./mysql');
var dbPool = mysql.createPool();

var express = require('express');
var multer  = require('multer');
var upload = multer({ dest: 'uploads', files: 5 });

var app = express();

app.put('/file', upload.single('file'), function (request, response, next) {
  var uploadedFile = request.file;

  var file = new File({
    name: uploadedFile.originalname,
    url: uploadedFile.path,
    mime_type: uploadedFile.mimetype
  });

  fileService.createAttachment(file, dbPool, function (id) {
  	response.status(201).json({id: id});
  });
});

app.listen(3003);
<|endoftext|>


<commit_before>module.exports = function(grunt) {

    var src_files = [
        '../src/_open.js',
        '../src/Utils.js',
        '../src/zoom.js',
        '../src/search.js',
        '../src/main.js',
        '../src/_close.js'
    ];

    grunt.initConfig({
        concat: {
            default: {
                src: src_files,
                dest: '../d3_clustergram.js'
            }
        },
        watch: {
            files: src_files,
            tasks: ['build']
        }
    });

    grunt.loadNpmTasks('grunt-contrib-watch');
    grunt.loadNpmTasks('grunt-contrib-concat');
    grunt.registerTask('build', ['concat']);
};
<commit_msg>Renamed search.js to Search.js since it is now a module<commit_after>module.exports = function(grunt) {

    var src_files = [
        '../src/_open.js',
        '../src/Utils.js',
        '../src/zoom.js',
        '../src/Search.js',
        '../src/main.js',
        '../src/_close.js'
    ];

    grunt.initConfig({
        concat: {
            default: {
                src: src_files,
                dest: '../d3_clustergram.js'
            }
        },
        watch: {
            files: src_files,
            tasks: ['build']
        }
    });

    grunt.loadNpmTasks('grunt-contrib-watch');
    grunt.loadNpmTasks('grunt-contrib-concat');
    grunt.registerTask('build', ['concat']);
};
<|endoftext|>


<commit_before>/* SBHS-Timetable-Node: Countdown and timetable all at once (NodeJS app).
 * Copyright (C) 2014 James Ye, Simon Shields
 *
 * This file is part of SBHS-Timetable-Node.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
/* global belltimes, currentBellIndex, calculateUpcomingLesson, reloadBelltimes, todayNames, updatePeriodLabel, updateSidebarStatus */ /* jshint -W098 */

function handleLeftPane() {
	/* Fill out the left pane */
	'use strict';
	var pane = document.getElementById('left-pane'),
		html = '

Subject	Teacher	Room
',
		timetable = todayNames.timetable,
		prefix, subj, suffix, room, teacher, fullTeacher, subjName, final,
		roomChanged, teacherChanged, cancelled = false;
	if (window.timetableCached) {
		html = '
This data may be outdated
' + html;
	}
	for (var i = 1; i < 6; i++) {
		if (!(i in timetable) || !timetable[i].room) {
			html += '
Free
';
		}
		else {
			todayNames.timetable[i].expanded = false;
			prefix = '';
			subj = '';
			suffix = '';
			subj = timetable[i].title;
			room = timetable[i].room;
			teacher = timetable[i].teacher;
			fullTeacher = timetable[i].fullTeacher;
			subjName = timetable[i].fullName;
			final = timetable.variationsFinalised;
			if (/\d$/.test(timetable[i].title) || /[a-z][A-Z]$/.test(timetable[i].title)) {
				suffix = timetable[i].title.substr(-1);
				subj = subj.slice(0,-1);
			}
			if (subj.length == 3 /*|| (subj.length == 2 && suffix === '')*/ || /^[WXYZ]/.test(subj)) { // very tentative guess that this is an elective - char 1 should be prefix
				prefix = subj[0];
				subj = subj.substr(1);
			}
			if (timetable[i].changed && todayNames.variationsFinalised) {
				if (timetable[i].hasOwnProperty('hasCover') && timetable[i].varies) { // don't show anything because I really don't get what the point of setting a casual but then not actually using aforementioned casual is.
					if (!timetable[i].hasCover) {
						cancelled = true;
					}
					else if (timetable[i].hasCasual) {
						teacherChanged = true;
						teacher = timetable[i].casual.toUpperCase();
						fullTeacher = timetable[i].casualDisplay.trim();
					}
				}
				if (timetable[i].roomFrom) {
					roomChanged = true;
					room = timetable[i].roomTo;
				}
			}
			var nSubj = '';
			var idx = 0;

			for (var j = 0; j < subj.length; j++) {
				var z = subjName.indexOf(subj[j+1]);
				z = z < 0 ? undefined : z;
				var mStr = subjName.substring(idx+1, z);
				nSubj += subj[j] + ''+mStr+'';
				idx = z;
			}
			var nTeach = '';
			idx = 0;
			var temp = teacher.toLowerCase();
			var fullTemp = fullTeacher;
			if (/^M(r|s) /.test(fullTemp)) {
				fullTemp = fullTemp.split(' ').slice(1).join(' ');
			}
			if (fullTemp[0].toLowerCase() !== teacher[0].toLowerCase()) {
				// we'll make up a prefix - probably a split class
				teacher = temp = fullTemp[0] + fullTemp.substr(-1);
				temp = temp.toLowerCase();
			}
			for (var k = 0; k < teacher.length; k++) {
				var y = fullTemp.toLowerCase().indexOf(temp[k+1]);
				y = y < 0 ? undefined : y;
				var extra = fullTemp.substring(idx+1, y);
				if (k !== 0) {
					nTeach += '';
				}
				nTeach += (k === 0 ? teacher[k].toUpperCase() : teacher[k].toLowerCase()) + ''+extra.toLowerCase()+'';
				if (k !== 0) {
					nTeach += '';
				}
				idx = y;
			}
			if (cancelled) {
				room = 'N/A';
			}
			html += '
'+timetable[i].year+prefix+''+nSubj+''+suffix+'	'+nTeach+'	'+room+'
';
			cancelled = false;
			roomChanged = false;
			teacherChanged = false;
		}
	}
	//html += '

';
	// Variations should not be shown if not final
	html += '>
';
	if (todayNames.variationsFinalised) {
		html += 'This info is final
';
	}
	else {
		html += 'This info may change
';
	}
	pane.innerHTML = html;

}

function getLoggedIn() {
	/* Are you logged in? */
	'use strict';
	return window.loggedIn;
}

function expandSubject(event, id) {
	'use strict';
	if (todayNames.timetable[id].expanded) {
		$('.subj-expand', event.currentTarget.parentNode).velocity('stop').velocity('transition.slideLeftBigOut');
		todayNames.timetable[id].expanded = false;
	}
	else {
		$('.subj-expand', event.currentTarget.parentNode).velocity('stop').velocity('transition.slideLeftBigIn');
		todayNames.timetable[id].expanded = true;
	}
}

function teacherExpand(event, id) {
	'use strict';
	var el = event.currentTarget.parentNode;
	if (el.tagName.toLowerCase() === 'span') {
		console.log('#nope');
		el = el.parentNode;
	}
	if (todayNames.timetable[id].teachExpanded) {
		$('.teach-expand', el).velocity('stop').velocity('transition.slideLeftBigOut');
		todayNames.timetable[id].teachExpanded = false;
	}
	else {
		$('.teach-expand', el).velocity('stop').velocity('transition.slideLeftBigIn');
		todayNames.timetable[id].teachExpanded = true;
	}
}

function handleTimetable() {
	/* Fill out the timetable */
	'use strict';
	/* jshint validthis: true, -W041 */
	window.timetableCached = false;
	if (window.belltimes == null || belltimes.status === 'Error') {
		reloadBelltimes(); // use today.json's date.
	}
	var res = JSON.parse(this.responseText);
	if (window.belltimes != null) {
		var lsKey = belltimes.day + belltimes.weekType;
		if (res.timetable && !res.hasVariations) {
			window.localStorage[lsKey] = this.responseText;
		}
	}
	if (!res.timetable) {
		$('#rtd-status').html('Real-time data inaccessible');
		return; // we don't want to do that... TODO refresh access token and stuff
	}
	window.todayNames = res;
	$('#rtd-status').html('Loaded real-time data');
	setTimeout(function() {
		$('#rtd-status').velocity('fadeOut');
		setTimeout(function() { $('#rtd-status').velocity('fadeOut').html('').css({'display': 'block'}); }, 1000);
	}, 3000);
	if (currentBellIndex == -1) {
		calculateUpcomingLesson();
	}
	handleLeftPane();
	if (belltimes.status !== 'Error') {
		updatePeriodLabel();
	}
	updateSidebarStatus();
}

function loadTimetable() {
	/* Get the timetable */
	'use strict';
	window.timetableCached = false;
	if (belltimes && (belltimes.day+belltimes.weekType) in window.localStorage) {
		window.timetableCached = true;
		console.log('loading from localStorage');
		window.todayNames = JSON.parse(window.localStorage[belltimes.day+belltimes.weekType]);
		setTimeout(handleLeftPane, 0);
		updateSidebarStatus();
		$('#rtd-status').html('Loading real-time data…');
	}
	else if (!getLoggedIn() && !window.todayNames) {
		console.log('umm');
		window.todayNames = {timetable: {failure: true}};
	}
	if (!getLoggedIn()) {
		$('#rtd-status').html('Log in for real-time data');
		return;
	}
	var xhr = new XMLHttpRequest();
	xhr.onload = handleTimetable;
	xhr.open('GET', '/api/today.json?stupid_proxy_caching_is_stupid', true);
	xhr.send();
}
<commit_msg>People don't actually need to know about shouldShowVariations<commit_after>/* SBHS-Timetable-Node: Countdown and timetable all at once (NodeJS app).
 * Copyright (C) 2014 James Ye, Simon Shields
 *
 * This file is part of SBHS-Timetable-Node.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
/* global belltimes, currentBellIndex, calculateUpcomingLesson, reloadBelltimes, todayNames, updatePeriodLabel, updateSidebarStatus */ /* jshint -W098 */

function handleLeftPane() {
	/* Fill out the left pane */
	'use strict';
	var pane = document.getElementById('left-pane'),
		html = '

Subject	Teacher	Room
',
		timetable = todayNames.timetable,
		prefix, subj, suffix, room, teacher, fullTeacher, subjName, final,
		roomChanged, teacherChanged, cancelled = false;
	if (window.timetableCached) {
		html = '
This data may be outdated
' + html;
	}
	for (var i = 1; i < 6; i++) {
		if (!(i in timetable) || !timetable[i].room) {
			html += '
Free
';
		}
		else {
			todayNames.timetable[i].expanded = false;
			prefix = '';
			subj = '';
			suffix = '';
			subj = timetable[i].title;
			room = timetable[i].room;
			teacher = timetable[i].teacher;
			fullTeacher = timetable[i].fullTeacher;
			subjName = timetable[i].fullName;
			final = timetable.variationsFinalised;
			if (/\d$/.test(timetable[i].title) || /[a-z][A-Z]$/.test(timetable[i].title)) {
				suffix = timetable[i].title.substr(-1);
				subj = subj.slice(0,-1);
			}
			if (subj.length == 3 /*|| (subj.length == 2 && suffix === '')*/ || /^[WXYZ]/.test(subj)) { // very tentative guess that this is an elective - char 1 should be prefix
				prefix = subj[0];
				subj = subj.substr(1);
			}
			if (timetable[i].changed && todayNames.variationsFinalised) {
				if (timetable[i].hasOwnProperty('hasCover') && timetable[i].varies) { // don't show anything because I really don't get what the point of setting a casual but then not actually using aforementioned casual is.
					if (!timetable[i].hasCover) {
						cancelled = true;
					}
					else if (timetable[i].hasCasual) {
						teacherChanged = true;
						teacher = timetable[i].casual.toUpperCase();
						fullTeacher = timetable[i].casualDisplay.trim();
					}
				}
				if (timetable[i].roomFrom) {
					roomChanged = true;
					room = timetable[i].roomTo;
				}
			}
			var nSubj = '';
			var idx = 0;

			for (var j = 0; j < subj.length; j++) {
				var z = subjName.indexOf(subj[j+1]);
				z = z < 0 ? undefined : z;
				var mStr = subjName.substring(idx+1, z);
				nSubj += subj[j] + ''+mStr+'';
				idx = z;
			}
			var nTeach = '';
			idx = 0;
			var temp = teacher.toLowerCase();
			var fullTemp = fullTeacher;
			if (/^M(r|s) /.test(fullTemp)) {
				fullTemp = fullTemp.split(' ').slice(1).join(' ');
			}
			if (fullTemp[0].toLowerCase() !== teacher[0].toLowerCase()) {
				// we'll make up a prefix - probably a split class
				teacher = temp = fullTemp[0] + fullTemp.substr(-1);
				temp = temp.toLowerCase();
			}
			for (var k = 0; k < teacher.length; k++) {
				var y = fullTemp.toLowerCase().indexOf(temp[k+1]);
				y = y < 0 ? undefined : y;
				var extra = fullTemp.substring(idx+1, y);
				if (k !== 0) {
					nTeach += '';
				}
				nTeach += (k === 0 ? teacher[k].toUpperCase() : teacher[k].toLowerCase()) + ''+extra.toLowerCase()+'';
				if (k !== 0) {
					nTeach += '';
				}
				idx = y;
			}
			if (cancelled) {
				room = 'N/A';
			}
			html += '
'+timetable[i].year+prefix+''+nSubj+''+suffix+'	'+nTeach+'	'+room+'
';
			cancelled = false;
			roomChanged = false;
			teacherChanged = false;
		}
	}
	html += '

';
	pane.innerHTML = html;
}

function getLoggedIn() {
	/* Are you logged in? */
	'use strict';
	return window.loggedIn;
}

function expandSubject(event, id) {
	'use strict';
	if (todayNames.timetable[id].expanded) {
		$('.subj-expand', event.currentTarget.parentNode).velocity('stop').velocity('transition.slideLeftBigOut');
		todayNames.timetable[id].expanded = false;
	}
	else {
		$('.subj-expand', event.currentTarget.parentNode).velocity('stop').velocity('transition.slideLeftBigIn');
		todayNames.timetable[id].expanded = true;
	}
}

function teacherExpand(event, id) {
	'use strict';
	var el = event.currentTarget.parentNode;
	if (el.tagName.toLowerCase() === 'span') {
		console.log('#nope');
		el = el.parentNode;
	}
	if (todayNames.timetable[id].teachExpanded) {
		$('.teach-expand', el).velocity('stop').velocity('transition.slideLeftBigOut');
		todayNames.timetable[id].teachExpanded = false;
	}
	else {
		$('.teach-expand', el).velocity('stop').velocity('transition.slideLeftBigIn');
		todayNames.timetable[id].teachExpanded = true;
	}
}

function handleTimetable() {
	/* Fill out the timetable */
	'use strict';
	/* jshint validthis: true, -W041 */
	window.timetableCached = false;
	if (window.belltimes == null || belltimes.status === 'Error') {
		reloadBelltimes(); // use today.json's date.
	}
	var res = JSON.parse(this.responseText);
	if (window.belltimes != null) {
		var lsKey = belltimes.day + belltimes.weekType;
		if (res.timetable && !res.hasVariations) {
			window.localStorage[lsKey] = this.responseText;
		}
	}
	if (!res.timetable) {
		$('#rtd-status').html('Real-time data inaccessible');
		return; // we don't want to do that... TODO refresh access token and stuff
	}
	window.todayNames = res;
	$('#rtd-status').html('Loaded real-time data');
	setTimeout(function() {
		$('#rtd-status').velocity('fadeOut');
		setTimeout(function() { $('#rtd-status').velocity('fadeOut').html('').css({'display': 'block'}); }, 1000);
	}, 3000);
	if (currentBellIndex == -1) {
		calculateUpcomingLesson();
	}
	handleLeftPane();
	if (belltimes.status !== 'Error') {
		updatePeriodLabel();
	}
	updateSidebarStatus();
}

function loadTimetable() {
	/* Get the timetable */
	'use strict';
	window.timetableCached = false;
	if (belltimes && (belltimes.day+belltimes.weekType) in window.localStorage) {
		window.timetableCached = true;
		console.log('loading from localStorage');
		window.todayNames = JSON.parse(window.localStorage[belltimes.day+belltimes.weekType]);
		setTimeout(handleLeftPane, 0);
		updateSidebarStatus();
		$('#rtd-status').html('Loading real-time data…');
	}
	else if (!getLoggedIn() && !window.todayNames) {
		console.log('umm');
		window.todayNames = {timetable: {failure: true}};
	}
	if (!getLoggedIn()) {
		$('#rtd-status').html('Log in for real-time data');
		return;
	}
	var xhr = new XMLHttpRequest();
	xhr.onload = handleTimetable;
	xhr.open('GET', '/api/today.json?stupid_proxy_caching_is_stupid', true);
	xhr.send();
}
<|endoftext|>


<commit_before>!function(d3) {
    var NODE_SIZE = 3 // XXX Sync with stairs.less
    ,RADIUS = NODE_SIZE * (3/8) //XXX
    ,UNIT = "vw"
    ,optGroupLabels = {
        'Vars' : 'Train',
        'Terms' : 'Promote'
    }

    function makeTerm(txt) {
        var s = document.createElement("span");
        s.innerHTML = txt;
        s.className = "termSpan";
        return s;
    }

    function populateSelect(specifyOptionsProvider, select) {
        var specifyOptions = specifyOptionsProvider();
        var oldValue = select.value;
        while (select.lastChild != select.firstChild) {
            select.removeChild(select.lastChild);
        }
        for (var k in specifyOptions) if (specifyOptions.hasOwnProperty(k)) {
            var og = select.appendChild(document.createElement("optGroup"));
            og.label = optGroupLabels.hasOwnProperty(k) ?
                optGroupLabels[k] : k;
            og.className = k;
            specifyOptions[k].forEach(function(o, i) {
                var opt = og.appendChild(
                    document.createElement("option"));
                opt.value = JSON.stringify([k, i]);
                if (opt.value == oldValue) {
                    opt.selected = "selected";
                }
                opt.innerHTML = o;
            });
        }
    }

    function makeVar(txt, path) {
        if (txt === undefined) throw new Error("undef");
        var s = document.createElement("select");
        s.className = "select";
        var ph = s.appendChild(document.createElement("option"));
        ph.innerHTML = txt;
        ph.className = 'placeholder';
        ph.selected = 'selected';
        ph.disabled = 'disabled';
        return s;
    }

    // Container for a mutable, d3-compatible graph-structure with mapped
    // HTML DOM nodes.
    function Node(parent, exp, argNumFromZero) {
        this.exp = exp;
        this.div = document.createElement("div");
        this.children = [];
        this.height = 0;
        this.div.className = Array.isArray(exp) ? "term" : "var";
        if (!parent) {
            this.path = [];
            return this;
        }
        this.path = parent.path.slice();
        this.path.push(argNumFromZero + 1);
        this.link = this.div.appendChild(document.createElement("div"));
        this.link.className = "link";
        parent.div.appendChild(this.div);
        parent.children.push(this);
    }

    function makeGraph(parent, exp, i) {
        var n = new Node(parent, exp, i);
        if (Array.isArray(exp)) {
            exp.slice(1).reduce(makeGraph, n);
        }
        if (parent) {
            parent.height = Math.max(parent.height, n.height + 1);
        }
        return parent || n;
    }

    // Walk tree, positioning and sizing container divs. Grows sets
    // node.divRect, and grows parentRect to contain it.
    function measureDivs(parentRect, node) {
        if (!parentRect) {
            parentRect = {left:Infinity, right:-Infinity,
                          bottom:-Infinity, top: Infinity};
        }
        var myRect = {top: node.y - NODE_SIZE / 2,
                      left: node.x - NODE_SIZE / 2,
                      right:node.x + NODE_SIZE / 2,
                      bottom:node.y + NODE_SIZE / 2};
        if (node.children) {
            myRect = node.children.reduce(measureDivs, myRect);
            node.divRect = myRect;
        } else {
            node.divRect = myRect;
        }
        parentRect.top = Math.min(parentRect.top, myRect.top);
        parentRect.left = Math.min(parentRect.left, myRect.left);
        parentRect.right = Math.max(parentRect.right, myRect.right);
        parentRect.bottom = Math.max(parentRect.bottom, myRect.bottom);
        return parentRect;
    }

    function positionDivs(origin, scale, node, index) {
        node.div.style.width = scale * (node.divRect.right - node.divRect.left) + UNIT;
        node.div.style.height = scale * (node.divRect.bottom - node.divRect.top) + UNIT;
        // TODO:imperfect. Sync 100 with css.
        node.div.style["z-index"] = 100 - node.height;
        node.div.style.left = scale * (node.divRect.left - origin.left) + UNIT;
        node.div.style.top = scale * (node.divRect.top - origin.top) + UNIT;
        if (Array.isArray(node.exp)) {
            // term nodes sized and positioned here.
            // var nodes (leaves) positiend and sized through CSS.
            node.span.style.left = scale * (node.x - RADIUS - node.divRect.left) + UNIT;
            node.span.style.top = scale * (node.y - RADIUS - node.divRect.top) + UNIT;
            node.span.style.width =
                node.span.style.height =
                scale * RADIUS * 2 + UNIT;
            if (node.children) {
                node.children.map(positionDivs.bind(null, node.divRect, scale));
            }
        }
        if (node.link) {
            node.link.style.right = scale * (node.divRect.right - node.x) + UNIT;
            //scale * (node.parent.divRect.left - origin.left) + UNIT;
            node.link.style.bottom = scale * (node.divRect.bottom - node.y) + UNIT;
            node.link.style.height = scale * (node.y - node.parent.y) + UNIT;
            // Matrix: should keep 0,0 constant, and move (0,y) to (n.left-p.left,y).
            // Requires transform-origin 100% 100%.
            var matrix = [1, 0,
                          (node.x - node.parent.x) / (node.y - node.parent.y), 1,
                          0, 0];
            node.link.style.transform = 'matrix(' + matrix.join(',') + ')';
        }
    }

    Node.prototype.decorate = function(spanMap, varMap, onclick, fact,
                                       getSpecifyOptions) {
        spanMap[this.path] = this.div;
        if (onclick) { // TODO: XXX
            this.div.addEventListener("click", function(ev) {
                onclick(ev, this.path);
            });
        }
        if (Array.isArray(this.exp)) {
            var text = fact.Skin.TermNames[this.exp[0]];
            this.div.className += " name" + cssEscape(text);
            this.span = this.div.appendChild(makeTerm(text));
        } else {
            var varNum = this.exp;
            var text = fact.Skin.VarNames[varNum];
            this.div.className += " name" + varNum;
            this.span = this.div.appendChild(makeVar(text, this.path));
            var select = this.span;
            if (!getSpecifyOptions) {
                select.disabled = "disabled";
            } else {
                if (!varMap.hasOwnProperty(varNum)) {
                    varMap[varNum] = [];
                }
                varMap[varNum].push(select);
                var populator = populateSelect.bind(null, getSpecifyOptions);
                select.addEventListener("focus", populator.bind(null, select));
                select.addEventListener("change", function(ev) {
                    //var value = JSON.parse(select.value);
                    //XXX opts.onChange(path, value[0], value[1]);
                    if (select.value !== "null") {
                        varMap[varNum].forEach(function(select2) {
                            if (select2 !== select) {
                                populator(select2);
                                select2.value = select.value;
                            }
                        });
                    }
                });
            }
        }
    };

    /**
     * Make a tree, i.e. a two-dimensional hierarchical display of an expression.
     *
     * @param opts.fact the Fact object for looking up operator names, etc.
     * @param opts.exp the expression to draw
     * @param opts.onclick
     * @param opts.size
     * @param opts.editable
     * @param opts.getSpecifyOptions
     * @return a DOM element containing the tree
     */
    var tm = function(opts) {
        var fact = opts.fact
        ,exp = opts.exp
        ,d3tree = d3.layout.tree()
        ,nodes = null
        ,root = document.createElement("div")

        opts.varMap = {} // varName -> [select node]

        root.setAttribute("class", "root");

        // Turning a term into a graph structure for d3. Also constructing
        // nested divs to mirror the graph structure.
        var graph = makeGraph(null, exp);
        root.appendChild(graph.div);

        d3tree.nodeSize([NODE_SIZE, NODE_SIZE]);
        d3tree.separation(function(a,b) {
            return a.parent == b.parent ? 1 : 1.5;
        });
        var nodes = d3tree.nodes(graph);

        root.spanMap = {};
        var varMap = {};
        nodes.forEach(function(node) {
            node.decorate(root.spanMap, varMap, opts.onclick, opts.fact,
                          opts.editable ? opts.getSpecifyOptions : null);
        });

        var rect = measureDivs(null, graph);
        rect.width = (rect.right - rect.left);
        rect.height = (rect.bottom - rect.top);
        // make fit within bounds. TODO: this is not exactly right
        var largerDim = (rect.width > rect.height) ? "width" : "height";
        var scale = opts.size / rect[largerDim];
        root.style["font-size"] = 0.5 * NODE_SIZE * scale + UNIT;
        positionDivs(rect, scale, graph);
        return root;
    };

    if (typeof define === "function" && define.amd) define(tm); else if (typeof module === "object" && module.exports) module.exports = tm;
    this.tm = tm;
}(d3);
<commit_msg>WIP: even more refactor. fixes #14<commit_after>!function(d3) {
    var NODE_SIZE = 3 // XXX Sync with stairs.less
    ,RADIUS = NODE_SIZE * (3/8) //XXX
    ,UNIT = "vw"
    ,optGroupLabels = {
        'Vars' : 'Train',
        'Terms' : 'Promote'
    }

    function makeTerm(txt) {
        var s = document.createElement("span");
        s.innerHTML = txt;
        s.className = "termSpan";
        return s;
    }

    function populateSelect(specifyOptionsProvider, select) {
        var specifyOptions = specifyOptionsProvider();
        var oldValue = select.value;
        while (select.lastChild != select.firstChild) {
            select.removeChild(select.lastChild);
        }
        for (var k in specifyOptions) if (specifyOptions.hasOwnProperty(k)) {
            var og = select.appendChild(document.createElement("optGroup"));
            og.label = optGroupLabels.hasOwnProperty(k) ?
                optGroupLabels[k] : k;
            og.className = k;
            specifyOptions[k].forEach(function(o, i) {
                var opt = og.appendChild(
                    document.createElement("option"));
                opt.value = JSON.stringify([k, i]);
                if (opt.value == oldValue) {
                    opt.selected = "selected";
                }
                opt.innerHTML = o;
            });
        }
    }

    function makeVar(txt, getSpecifyOptions) {
        if (txt === undefined) throw new Error("undef");
        var s;
        if (getSpecifyOptions) {
            s = document.createElement("select");

            var ph = s.appendChild(document.createElement("option"));
            ph.innerHTML = txt;
            ph.className = 'placeholder';
            ph.selected = 'selected';
            ph.disabled = 'disabled';
            s.addEventListener("focus", populateSelect.bind(null, getSpecifyOptions, s));
        } else {
            s = document.createElement("span");
            s.innerHTML = txt;
        }
        s.className = "select";
        return s;
    }

    // Container for a mutable, d3-compatible graph-structure with mapped
    // HTML DOM nodes.
    function Node(parent, exp, argNumFromZero) {
        this.exp = exp;
        this.div = document.createElement("div");
        this.children = [];
        this.height = 0;
        this.div.className = Array.isArray(exp) ? "term" : "var";
        if (!parent) {
            this.path = [];
            return this;
        }
        this.path = parent.path.slice();
        this.path.push(argNumFromZero + 1);
        this.link = this.div.appendChild(document.createElement("div"));
        this.link.className = "link";
        parent.div.appendChild(this.div);
        parent.children.push(this);
    }

    function makeGraph(parent, exp, i) {
        var n = new Node(parent, exp, i);
        if (Array.isArray(exp)) {
            exp.slice(1).reduce(makeGraph, n);
        }
        if (parent) {
            parent.height = Math.max(parent.height, n.height + 1);
        }
        return parent || n;
    }

    // Walk tree, positioning and sizing container divs. Grows sets
    // node.divRect, and grows parentRect to contain it.
    function measureDivs(parentRect, node) {
        if (!parentRect) {
            parentRect = {left:Infinity, right:-Infinity,
                          bottom:-Infinity, top: Infinity};
        }
        var myRect = {top: node.y - NODE_SIZE / 2,
                      left: node.x - NODE_SIZE / 2,
                      right:node.x + NODE_SIZE / 2,
                      bottom:node.y + NODE_SIZE / 2};
        if (node.children) {
            myRect = node.children.reduce(measureDivs, myRect);
            node.divRect = myRect;
        } else {
            node.divRect = myRect;
        }
        parentRect.top = Math.min(parentRect.top, myRect.top);
        parentRect.left = Math.min(parentRect.left, myRect.left);
        parentRect.right = Math.max(parentRect.right, myRect.right);
        parentRect.bottom = Math.max(parentRect.bottom, myRect.bottom);
        return parentRect;
    }

    function positionDivs(origin, scale, node, index) {
        node.div.style.width = scale * (node.divRect.right - node.divRect.left) + UNIT;
        node.div.style.height = scale * (node.divRect.bottom - node.divRect.top) + UNIT;
        // TODO:imperfect. Sync 100 with css.
        node.div.style["z-index"] = 100 - node.height;
        node.div.style.left = scale * (node.divRect.left - origin.left) + UNIT;
        node.div.style.top = scale * (node.divRect.top - origin.top) + UNIT;
        if (Array.isArray(node.exp)) {
            // term nodes sized and positioned here.
            // var nodes (leaves) positiend and sized through CSS.
            node.span.style.left = scale * (node.x - RADIUS - node.divRect.left) + UNIT;
            node.span.style.top = scale * (node.y - RADIUS - node.divRect.top) + UNIT;
            node.span.style.width =
                node.span.style.height =
                scale * RADIUS * 2 + UNIT;
            if (node.children) {
                node.children.map(positionDivs.bind(null, node.divRect, scale));
            }
        }
        if (node.link) {
            node.link.style.right = scale * (node.divRect.right - node.x) + UNIT;
            //scale * (node.parent.divRect.left - origin.left) + UNIT;
            node.link.style.bottom = scale * (node.divRect.bottom - node.y) + UNIT;
            node.link.style.height = scale * (node.y - node.parent.y) + UNIT;
            // Matrix: should keep 0,0 constant, and move (0,y) to (n.left-p.left,y).
            // Requires transform-origin 100% 100%.
            var matrix = [1, 0,
                          (node.x - node.parent.x) / (node.y - node.parent.y), 1,
                          0, 0];
            node.link.style.transform = 'matrix(' + matrix.join(',') + ')';
        }
    }

    Node.prototype.decorate = function(spanMap, varMap, onclick, fact,
                                       getSpecifyOptions) {
        spanMap[this.path] = this.div;
        if (Array.isArray(this.exp)) {
            var text = fact.Skin.TermNames[this.exp[0]];
            this.div.className += " name" + cssEscape(text);
            this.span = this.div.appendChild(makeTerm(text));
        } else {
            var varNum = this.exp;
            var text = fact.Skin.VarNames[varNum];
            this.div.className += " name" + varNum;
            this.span = this.div.appendChild(makeVar(text, getSpecifyOptions));
            if (getSpecifyOptions) {
                var select = this.span;
                if (!varMap.hasOwnProperty(varNum)) {
                    varMap[varNum] = [];
                }
                varMap[varNum].push(select);
                select.addEventListener("change", function(ev) {
                    //var value = JSON.parse(select.value);
                    //XXX opts.onChange(path, value[0], value[1]);
                    if (select.value !== "null") {
                        varMap[varNum].forEach(function(select2) {
                            if (select2 !== select) {
                                populator(select2);
                                select2.value = select.value;
                            }
                        });
                    }
                });
            }
        }
        var path = this.path;
        if (onclick) {
            this.div.addEventListener("click", function(ev) {
                onclick(ev, path);
            });
            this.span.addEventListener("click", function(ev) {
                onclick(ev, path);
            });
        }

    };

    /**
     * Make a tree, i.e. a two-dimensional hierarchical display of an expression.
     *
     * @param opts.fact the Fact object for looking up operator names, etc.
     * @param opts.exp the expression to draw
     * @param opts.onclick
     * @param opts.size
     * @param opts.editable
     * @param opts.getSpecifyOptions
     * @return a DOM element containing the tree
     */
    var tm = function(opts) {
        var fact = opts.fact
        ,exp = opts.exp
        ,d3tree = d3.layout.tree()
        ,nodes = null
        ,root = document.createElement("div")

        opts.varMap = {} // varName -> [select node]

        root.setAttribute("class", "root");

        // Turning a term into a graph structure for d3. Also constructing
        // nested divs to mirror the graph structure.
        var graph = makeGraph(null, exp);
        root.appendChild(graph.div);

        d3tree.nodeSize([NODE_SIZE, NODE_SIZE]);
        d3tree.separation(function(a,b) {
            return a.parent == b.parent ? 1 : 1.5;
        });
        var nodes = d3tree.nodes(graph);

        root.spanMap = {};
        var varMap = {};
        nodes.forEach(function(node) {
            node.decorate(root.spanMap, varMap, opts.onclick, opts.fact,
                          opts.editable ? opts.getSpecifyOptions : null);
        });

        var rect = measureDivs(null, graph);
        rect.width = (rect.right - rect.left);
        rect.height = (rect.bottom - rect.top);
        // make fit within bounds. TODO: this is not exactly right
        var largerDim = (rect.width > rect.height) ? "width" : "height";
        var scale = opts.size / rect[largerDim];
        root.style["font-size"] = 0.5 * NODE_SIZE * scale + UNIT;
        positionDivs(rect, scale, graph);
        return root;
    };

    if (typeof define === "function" && define.amd) define(tm); else if (typeof module === "object" && module.exports) module.exports = tm;
    this.tm = tm;
}(d3);
<|endoftext|>


<commit_before>const Table = require("./Table.js");
const DriverAliases = require("./drivers/DriverAliases.js");

class Database {

    static retrieveDriver() {
        let driverType = env("database.driver");

        if(DriverAliases[driverType]) {
            let driverPath = DriverAliases[driverType];

            return require("./drivers/" + driverPath);
        } else {
            return require("./drivers/MysqlDriver.js");
        }
    }

    static table(name) {
        let driver = this.retrieveDriver();

        return new Table(name, driver);
    }

}

module.exports = Database;<commit_msg>Added some more documentation comments<commit_after>const Table = require("./Table.js");
const DriverAliases = require("./drivers/DriverAliases.js");

class Database {

    /**
     * Retrieves the database driver based on what the user has set in their
     * environment JSON file. If the driver cannot be found, will default to
     * the MySQL driver.
     *
     * @returns {Driver} the database driver required to actually access the
     * database.
     */
    static retrieveDriver() {
        let driverType = env("database.driver");

        if(DriverAliases[driverType]) {
            let driverPath = DriverAliases[driverType];

            return require("./drivers/" + driverPath);
        } else {
            return require("./drivers/MysqlDriver.js");
        }
    }

    /**
     * Builds and returns a Table object that's used to access a specific table
     * or collection.
     *
     * @param {string} name the name of the table to bind on
     *
     * @returns {Table} the table object to use to make queries against the
     * table
     */
    static table(name) {
        let driver = this.retrieveDriver();

        return new Table(name, driver);
    }

}

module.exports = Database;<|endoftext|>


<commit_before>function fieldNameCounts(){
  return Zogger.getFacetObjects("fieldName", "text", "weight");
}

function contentTypeCounts(){
  return Zogger.getFacetObjects("contentType", "text", "weight");
}

$(function(){

  var $fieldsCloud = $("#fields");
  $fieldsCloud.jQCloud(fieldNameCounts());
  Zogger.onReportUpdated(function(){
    $fieldsCloud.html('');
    $('b.fields').text(Zogger.fieldNameFacet().length)
    $fieldsCloud.jQCloud(fieldNameCounts());
  });

  function countuper(div,high){
    var current = 0;
    var finish = $("."+div).text();

    var miliseconds = 3000;
    var rate = 10;

    var counter = setInterval(function(){
      if(current >= finish) clearInterval(counter);
      $("."+div).text("" + current);
      current = parseInt(current) + parseInt(rate);
    }, miliseconds / (finish / rate));
    console.log(finish)
    console.log(current)
  }

  countuper("sites");
  countuper("timespent");
  countuper("urls");
  countuper("countries");
  countuper("dangerzones");
  countuper("fields");
  countuper("people");
  countuper("passby");

  var timecapsule = $('.timecapsule');
  timecapsule.removeClass('dvadeset').removeClass('cetrdeset').removeClass('60').removeClass('80');
  timecapsule.addClass('dvadeset');

  var gdpData = {"af":16.63,"ba":11.58,"dz":158.97}
  var max = 0,
  min = Number.MAX_VALUE,
  cc,
  startColor = [200, 238, 255],
  endColor = [0, 100, 145],
  colors = {},
  hex;
  //find maximum and minimum values
  for (cc in gdpData) {
    if (parseFloat(gdpData[cc]) > max) {
      max = parseFloat(gdpData[cc]);
    }
    if (parseFloat(gdpData[cc]) < min) {
      min = parseFloat(gdpData[cc]);
    }
  }
  //set colors according to values of GDP
  for (cc in gdpData) {
    if (gdpData[cc] > 0) {
      colors[cc] = '#';
      for (var i = 0; i<3; i++) {
        hex = Math.round(startColor[i] + (endColor[i] - startColor[i])*(gdpData[cc] / (max - min))).toString(16);
        if (hex.length == 1) {
          hex = '0'+hex;
        }
        colors[cc] += (hex.length == 1 ? '0' : '') + hex;
      }
    }
  }
  $('#map').vectorMap({
    values: gdpData,
    backgroundColor: '#541304',
    scaleColors: ['#6f1805', '#f35733'],
    normalizeFunction: 'polynomial',
    hoverOpacity: 0.7,
    hoverColor: false
  });

});
<commit_msg>Removed reference to old function<commit_after>function fieldNameCounts(){
  return Zogger.getFacetObjects("fieldName", "text", "weight");
}

function contentTypeCounts(){
  return Zogger.getFacetObjects("contentType", "text", "weight");
}

$(function(){

  var $fieldsCloud = $("#fields");
  $fieldsCloud.jQCloud(fieldNameCounts());
  $('b.fields').text(fieldNameCounts().length);
  Zogger.onReportUpdated(function(){
    $fieldsCloud.html('');
    $('b.fields').text(fieldNameCounts().length);
    $fieldsCloud.jQCloud(fieldNameCounts());
  });

  function countuper(div,high){
    var current = 0;
    var finish = $("."+div).text();

    var miliseconds = 3000;
    var rate = 10;

    var counter = setInterval(function(){
      if(current >= finish) clearInterval(counter);
      $("."+div).text("" + current);
      current = parseInt(current) + parseInt(rate);
    }, miliseconds / (finish / rate));
    console.log(finish)
    console.log(current)
  }

  countuper("sites");
  countuper("timespent");
  countuper("urls");
  countuper("countries");
  countuper("dangerzones");
  countuper("fields");
  countuper("people");
  countuper("passby");

  var timecapsule = $('.timecapsule');
  timecapsule.removeClass('dvadeset').removeClass('cetrdeset').removeClass('60').removeClass('80');
  timecapsule.addClass('dvadeset');

  var gdpData = {"af":16.63,"ba":11.58,"dz":158.97}
  var max = 0,
  min = Number.MAX_VALUE,
  cc,
  startColor = [200, 238, 255],
  endColor = [0, 100, 145],
  colors = {},
  hex;
  //find maximum and minimum values
  for (cc in gdpData) {
    if (parseFloat(gdpData[cc]) > max) {
      max = parseFloat(gdpData[cc]);
    }
    if (parseFloat(gdpData[cc]) < min) {
      min = parseFloat(gdpData[cc]);
    }
  }
  //set colors according to values of GDP
  for (cc in gdpData) {
    if (gdpData[cc] > 0) {
      colors[cc] = '#';
      for (var i = 0; i<3; i++) {
        hex = Math.round(startColor[i] + (endColor[i] - startColor[i])*(gdpData[cc] / (max - min))).toString(16);
        if (hex.length == 1) {
          hex = '0'+hex;
        }
        colors[cc] += (hex.length == 1 ? '0' : '') + hex;
      }
    }
  }
  $('#map').vectorMap({
    values: gdpData,
    backgroundColor: '#541304',
    scaleColors: ['#6f1805', '#f35733'],
    normalizeFunction: 'polynomial',
    hoverOpacity: 0.7,
    hoverColor: false
  });

});
<|endoftext|>