<commit_before>(function(module) {
  function Inspection (options) {
    Object.keys(options).forEach(function(element, index, keys){
      this[element] = options[element];
    },this);
  }
  Inspection.current =[];
  Inspection.names =[];

  Inspection.createTable = function(callback) {
    webDB.execute(
      'CREATE TABLE IF NOT EXISTS recentInspect (' +
      'id INTEGER PRIMARY KEY, ' +
      'name VARCHAR(255), ' +
      'inspection_date DATETIME, ' +
      'inspection_score INTEGER, ' +
      'latitude DECIMAL(18,12), ' +
      'longitude DECIMAL(18,12));',
      callback
    );
  };
  Inspection.buildNames = function (anything) {
    $.get('/data/resource/gkhn-e8mn.json?$select=name&$group=name&$order=name&$limit=50000')
    .done(function(data, message, xhr) {
      Inspection.names = data.map(function(element){
        return element.name;
      });
      console.log('generated array for inspeciton.names');
      anything();
    });
  };

  Inspection.prototype.insertData = function(callback) {
    webDB.execute(
      [
        {
          'sql': 'INSERT INTO recentInspect (name, inspection_date, inspection_score, latitude, longitude) VALUES (?, ?, ?, ?, ?);',
          'data': [this.name, this.inspection_date, this.inspection_score, this.latitude, this.longitude],
        }
      ],
      callback
    );
  };

  Inspection.createTable();

  Inspection.requestInspectionData = function(place, callback) {

    $.get('/data/resource/gkhn-e8mn.json?$select=name,inspection_date,inspection_score,latitude,longitude&$order=inspection_date%20DESC&inspection_type=Routine%20Inspection/Field%20Review&$q=' + place + '&$limit=1')
      .done(function(data, message, xhr) {
        Inspection.current = data;
        data.forEach(function (item) {
          var total = new Inspection(item);
          console.log('item:' + item);
          //cache the data into the currently empty array
          total.insertData();
        });
        mapView.updateMap();
        inspectionView.displayResults();
      }).done(callback);
  };

  Inspection.with = function(attr) {
    console.log('inspection function');
    return Inspection.current.filter(function(inspection){
      return inspection[attr];
      console.log(Inspection.current);
    });
  };

  Inspection.inputOptions = function() {
    $('#search-input').autocomplete({
      source: Inspection.names,
      minLength: 3
    });
  };

  $('.restaurant-search').on('submit', function(event) {
    event.preventDefault();
    var restName = $('#search-input').val();
    restName = restName.replace(/[^\w\s]/gi, ' ');
    console.log('This is the restName:' + restName);
    Inspection.requestInspectionData(restName, Inspection.with);
    historyInit.requestHistoryData(restName);
  });
  Inspection.buildNames(Inspection.inputOptions);

  module.Inspection = Inspection;
})(window);
<commit_msg>updating database calls<commit_after>(function(module) {
  function Inspection (options) {
    Object.keys(options).forEach(function(element, index, keys){
      this[element] = options[element];
    },this);
  }
  Inspection.current =[];
  Inspection.names =[];

  Inspection.createTable = function(callback) {
    webDB.execute(
      'CREATE TABLE IF NOT EXISTS recentInspect (' +
      'id INTEGER PRIMARY KEY, ' +
      'name VARCHAR(255), ' +
      'inspection_date DATETIME, ' +
      'inspection_score INTEGER, ' +
      'address VARCHAR(255), ' +
      'city VARCHAR(255), ' +
      'zip_code VARCHAR(255), ' +
      'phone VARCHAR(255), ' +
      'latitude DECIMAL(18,12), ' +
      'longitude DECIMAL(18,12));',
      callback
    );
  };
  Inspection.buildNames = function (anything) {
    $.get('/data/resource/gkhn-e8mn.json?$select=name&$group=name&$order=name&$limit=50000')
    .done(function(data, message, xhr) {
      Inspection.names = data.map(function(element){
        return element.name;
      });
      console.log('generated array for inspeciton.names');
      anything();
    });
  };

  Inspection.prototype.insertData = function(callback) {
    webDB.execute(
      [
        {
          'sql': 'INSERT INTO recentInspect (name, inspection_date, inspection_score, address, city, zip_code, phone, latitude, longitude) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?);',
          'data': [this.name, this.inspection_date, this.inspection_score, this.address, this. city, this.zip_code, this.phone, this.latitude, this.longitude],
        }
      ],
      callback
    );
  };

  Inspection.createTable();

  Inspection.requestInspectionData = function(place, callback) {

    $.get('/data/resource/gkhn-e8mn.json?$select=name,inspection_date,inspection_score,address,city,zip_code,phone,latitude,longitude&$order=inspection_date%20DESC&inspection_type=Routine%20Inspection/Field%20Review&$q=' + place + '&$limit=1')
      .done(function(data, message, xhr) {
        Inspection.current = data;
        data.forEach(function (item) {
          var total = new Inspection(item);
          console.log('item:' + item);
          //cache the data into the currently empty array
          total.insertData();
        });
        mapView.updateMap();
        inspectionView.displayResults();
      }).done(callback);
  };

  Inspection.with = function(attr) {
    console.log('inspection function');
    return Inspection.current.filter(function(inspection){
      return inspection[attr];
      console.log(Inspection.current);
    });
  };

  Inspection.inputOptions = function() {
    $('#search-input').autocomplete({
      source: Inspection.names,
      minLength: 3
    });
  };

  $('.restaurant-search').on('submit', function(event) {
    event.preventDefault();
    var restName = $('#search-input').val();
    restName = restName.replace(/[^\w\s]/gi, ' ');
    console.log('This is the restName:' + restName);
    Inspection.requestInspectionData(restName, Inspection.with);
    historyInit.requestHistoryData(restName);
  });
  Inspection.buildNames(Inspection.inputOptions);

  module.Inspection = Inspection;
})(window);
<|endoftext|>


<commit_before>var encryption = require('./encryption');
var winston = require('winston');
var MongoDB = require('winston-mongodb')//.MongoDB;
var logger = new (winston.Logger)({
    transports: [
      new (winston.transports.Console)(),
      new (winston.transports.File)({ filename: 'requests.log', json:false })
    ]
});

var researchLogger = new (winston.Logger)({
    transports: [
      new (winston.transports.Console)()
    ]
});
researchLogger.add(winston.transports.MongoDB, { db: 'log', collection: 'log'});

Pending = require('../models').Pending;
Friendship = require('../models').Friendship;

function downloadHandler(req, res) {

    var requestMac = req.body.mac;
    var requestFileHash = req.body.filehash;
    var requestFileName = req.body.filename;
    var requestFileSize = req.body.filesize;
    var requestType = req.body.type;

    User = require('../models').User;

    User.find({ 'ip': req.ip }, function (error, users) {

        if (error) {
            logger.warn('download.js-downloadHandler: Download request not completed. Reason - Cannot find user with IP ' + req.ip);
            res.send({ 'status': 'Error', 'text': error });
            return;
        }

        var requestDownloader = users[0].mac;

        var newPending = new Pending();

        newPending.fileHash = requestFileHash;
        newPending.fileName = requestFileName;
        newPending.fileSize = requestFileSize;
        newPending.uploader = requestMac;
        newPending.downloader = requestDownloader;
        newPending.transferID = encryption.generateNewId();
        newPending.symKey = encryption.generateNewKey();
        newPending.uploaderIP = "invalid";
        newPending.nick = 'He Who Must Not Be Named';
        newPending.type = "direct";

        // Now behaviour will diverge depending on whether this is an online
        // or offline transfer

        var bounced = []; // Will hold the firstleg pendings

        if (requestType.toLowerCase() == "bounced") {

            // Find all the people with whom the downloader is friends
            Friendship.find({ $or: [{ 'friend1': requestDownloader }, { 'friend2': requestDownloader}] }, {}, { limit: 5, sort: [['count', 'desc']] }, function (error, friends) {

                //logger.info('download.js-downloadHandler: friends are  ' + friends);

                for (var i = 0; i < friends.length; i++) {

                    var bouncedPending = new Pending();

                    bouncedPending.fileHash = requestFileHash;
                    bouncedPending.fileName = requestFileName;
                    bouncedPending.transferID = newPending.transferID;
                    bouncedPending.fileSize = requestFileSize;
                    bouncedPending.uploader = requestMac;

                    if (friends[i].friend1 == requestDownloader) {
                        bouncedPending.downloader = friends[i].friend2;
                    } else {
                        bouncedPending.downloader = friends[i].friend1;
                    }

                    // Make sure downloader and uploader are not the same person
                    if (bouncedPending.downloader == requestMac)
                        continue;

                    bouncedPending.uploaderIP = "invalid";
                    bouncedPending.nick = 'He Who Must Not Named';
                    bouncedPending.type = "firstleg";
                    bounced.push(bouncedPending);
                }

                //logger.info("download.js-downloadHandler:  List of firstleg pendings " + bounced);

                // To ensure duplicate download requests are not processed
                Pending.find({ 'fileHash': newPending.fileHash, 'uploader': newPending.uploader, 'type': newPending.type }, function (error, pendingUsers) {
                    if (error == null) {
                        if (pendingUsers.length == 0) {
                            newPending.save();

                            for (var i = 0; i < bounced.length; i++) {
                                bounced[i].save();
                            }

                            logger.info('download.js-downloadHandler:Download request completed. Added pending to  ' + users[0].nick + ' with type = direct and ' + bounced.length + ' pending(s) with type = firstleg ');
                            res.send({ 'status': 'OK', 'text': 'Download request accepted' });

                        } else {

                            logger.info('download.js-downloadHandler: Download request not completed. Reason - This download has already been requested');
                            res.send({ 'status': 'Error', 'text': 'This download request already exists' });
                            return;
                        }

                    } else {
                        logger.error('download.js-downloadHandler: Download request not completed. Reason -  Could not read pendings from DB. IP', req.ip);
                        res.send({ 'status': 'Error', 'text': error });
                        return;
                    }
                });
            });

        } else {

            Pending.find({ 'fileHash': newPending.fileHash, 'uploader': newPending.uploader, 'type': newPending.type }, function (error, pendingUsers) {
                if (error != null) {
                    logger.error('download.js-downloadHandler: Download request not completed. Reason -  Could not read pendings from DB. IP', req.ip);
                    res.send({ 'status': 'Error', 'text': error });
                    return;
                }

                // To ensure duplicate download requests are not processed
                if (pendingUsers.length == 0) {
                    newPending.save();

                    for (var i = 0; i < bounced.length; i++)
                        bounced[i].save();

                    logger.info('download.js-downloadHandler: Download request complete Added pending to  ' + users[0].nick + ' with type = direct and ' + bounced.length + ' pending(s) with type = firstleg ');
                    var downloadLog = {}
                    downloadLog["tID"] = newPending.transferID;
                    downloadLog["downloader"] = newPending.downloader;
                    downloadLog["uploader"] = newPending.uploader;
                    downloadHandler["fileSize"] = newPending.fileSize;
                    researchLogger.info(downloadHandler);
                    res.send({ 'status': 'OK', 'text': 'Download request accepted' });

                } else {
                    logger.info('download.js-downloadHandler: Download request not completed. Reason - This download has already been requested');
                    res.send({ 'status': 'Error', 'text': 'This download request already exists' });
                    return;
                }
            });
        }
    });
}

exports.downloadHandler = downloadHandler;<commit_msg>testing git commit<commit_after>//test comment
var encryption = require('./encryption');
var winston = require('winston');
var MongoDB = require('winston-mongodb')//.MongoDB;
var logger = new (winston.Logger)({
    transports: [
      new (winston.transports.Console)(),
      new (winston.transports.File)({ filename: 'requests.log', json:false })
    ]
});

var researchLogger = new (winston.Logger)({
    transports: [
      new (winston.transports.Console)()
    ]
});
researchLogger.add(winston.transports.MongoDB, { db: 'log', collection: 'log'});

Pending = require('../models').Pending;
Friendship = require('../models').Friendship;

function downloadHandler(req, res) {

    var requestMac = req.body.mac;
    var requestFileHash = req.body.filehash;
    var requestFileName = req.body.filename;
    var requestFileSize = req.body.filesize;
    var requestType = req.body.type;

    User = require('../models').User;

    User.find({ 'ip': req.ip }, function (error, users) {

        if (error) {
            logger.warn('download.js-downloadHandler: Download request not completed. Reason - Cannot find user with IP ' + req.ip);
            res.send({ 'status': 'Error', 'text': error });
            return;
        }

        var requestDownloader = users[0].mac;

        var newPending = new Pending();

        newPending.fileHash = requestFileHash;
        newPending.fileName = requestFileName;
        newPending.fileSize = requestFileSize;
        newPending.uploader = requestMac;
        newPending.downloader = requestDownloader;
        newPending.transferID = encryption.generateNewId();
        newPending.symKey = encryption.generateNewKey();
        newPending.uploaderIP = "invalid";
        newPending.nick = 'He Who Must Not Be Named';
        newPending.type = "direct";

        // Now behaviour will diverge depending on whether this is an online
        // or offline transfer

        var bounced = []; // Will hold the firstleg pendings

        if (requestType.toLowerCase() == "bounced") {

            // Find all the people with whom the downloader is friends
            Friendship.find({ $or: [{ 'friend1': requestDownloader }, { 'friend2': requestDownloader}] }, {}, { limit: 5, sort: [['count', 'desc']] }, function (error, friends) {

                //logger.info('download.js-downloadHandler: friends are  ' + friends);

                for (var i = 0; i < friends.length; i++) {

                    var bouncedPending = new Pending();

                    bouncedPending.fileHash = requestFileHash;
                    bouncedPending.fileName = requestFileName;
                    bouncedPending.transferID = newPending.transferID;
                    bouncedPending.fileSize = requestFileSize;
                    bouncedPending.uploader = requestMac;

                    if (friends[i].friend1 == requestDownloader) {
                        bouncedPending.downloader = friends[i].friend2;
                    } else {
                        bouncedPending.downloader = friends[i].friend1;
                    }

                    // Make sure downloader and uploader are not the same person
                    if (bouncedPending.downloader == requestMac)
                        continue;

                    bouncedPending.uploaderIP = "invalid";
                    bouncedPending.nick = 'He Who Must Not Named';
                    bouncedPending.type = "firstleg";
                    bounced.push(bouncedPending);
                }

                //logger.info("download.js-downloadHandler:  List of firstleg pendings " + bounced);

                // To ensure duplicate download requests are not processed
                Pending.find({ 'fileHash': newPending.fileHash, 'uploader': newPending.uploader, 'type': newPending.type }, function (error, pendingUsers) {
                    if (error == null) {
                        if (pendingUsers.length == 0) {
                            newPending.save();

                            for (var i = 0; i < bounced.length; i++) {
                                bounced[i].save();
                            }

                            logger.info('download.js-downloadHandler:Download request completed. Added pending to  ' + users[0].nick + ' with type = direct and ' + bounced.length + ' pending(s) with type = firstleg ');
                            res.send({ 'status': 'OK', 'text': 'Download request accepted' });

                        } else {

                            logger.info('download.js-downloadHandler: Download request not completed. Reason - This download has already been requested');
                            res.send({ 'status': 'Error', 'text': 'This download request already exists' });
                            return;
                        }

                    } else {
                        logger.error('download.js-downloadHandler: Download request not completed. Reason -  Could not read pendings from DB. IP', req.ip);
                        res.send({ 'status': 'Error', 'text': error });
                        return;
                    }
                });
            });

        } else {

            Pending.find({ 'fileHash': newPending.fileHash, 'uploader': newPending.uploader, 'type': newPending.type }, function (error, pendingUsers) {
                if (error != null) {
                    logger.error('download.js-downloadHandler: Download request not completed. Reason -  Could not read pendings from DB. IP', req.ip);
                    res.send({ 'status': 'Error', 'text': error });
                    return;
                }

                // To ensure duplicate download requests are not processed
                if (pendingUsers.length == 0) {
                    newPending.save();

                    for (var i = 0; i < bounced.length; i++)
                        bounced[i].save();

                    logger.info('download.js-downloadHandler: Download request complete Added pending to  ' + users[0].nick + ' with type = direct and ' + bounced.length + ' pending(s) with type = firstleg ');
                    var downloadLog = {}
                    downloadLog["tID"] = newPending.transferID;
                    downloadLog["downloader"] = newPending.downloader;
                    downloadLog["uploader"] = newPending.uploader;
                    downloadHandler["fileSize"] = newPending.fileSize;
                    researchLogger.info(downloadHandler);
                    res.send({ 'status': 'OK', 'text': 'Download request accepted' });

                } else {
                    logger.info('download.js-downloadHandler: Download request not completed. Reason - This download has already been requested');
                    res.send({ 'status': 'Error', 'text': 'This download request already exists' });
                    return;
                }
            });
        }
    });
}

exports.downloadHandler = downloadHandler;<|endoftext|>


<commit_before>import React, { PropTypes } from 'react';
import { ItemTypes } from '../Constants.js';
import { DragLayer } from 'react-dnd';

const layerStyles = {
    position: 'fixed',
    pointerEvents: 'none',
    zIndex: 100,
    left: 0,
    top: 0,
    width: '100%',
    height: '100%'
};

function getItemStyles(props) {
    const { currentOffset } = props;
    if (!currentOffset) {
        return {
            display: 'none'
        };
    }

    const { x, y } = currentOffset;
    const transform = `translate(${x}px, ${y}px)`;
    return {
        transform: transform,
        WebkitTransform: transform
    };
}

var CustomDragLayer = React.createClass({

    propTypes: {
        item: PropTypes.object,
        itemType: PropTypes.string,
        currentOffset: PropTypes.shape({
            x: PropTypes.number.isRequired,
            y: PropTypes.number.isRequired
        }),
        isDragging: PropTypes.bool.isRequired
    },

    renderItem(type, item) {
        switch (type) {
            case ItemTypes.COMPONENT:
                return (

 Fuck it I'm a drag layer

                );
        }
    },

    render() {
        const { item, itemType, isDragging } = this.props;

        if (!isDragging) {
            return null;
        }

        return (

                    {this.renderItem(itemType, item)}

        );
    }
});

function collect(monitor) {
    return {
        item: monitor.getItem(),
        itemType: monitor.getItemType(),
        currentOffset: monitor.getSourceClientOffset(),
        isDragging: monitor.isDragging()
    };
}

export default DragLayer(collect)(CustomDragLayer);<commit_msg>Custom drag layer is finished<commit_after>import React, { PropTypes } from 'react';
import { ItemTypes } from '../Constants.js';
import { DragLayer } from 'react-dnd';

const layerStyles = {
    position: 'fixed',
    pointerEvents: 'none',
    zIndex: 100,
    left: 0,
    top: 0,
    width: '100%',
    height: '100%'
};

var CustomDragLayer = React.createClass({

    propTypes: {
        item: PropTypes.object,
        itemType: PropTypes.string,
        currentOffset: PropTypes.shape({
            x: PropTypes.number.isRequired,
            y: PropTypes.number.isRequired
        }),
        isDragging: PropTypes.bool.isRequired
    },

    renderItem(type, item) {
        switch (type) {
            case ItemTypes.COMPONENT:
                return (

                );
        }
    },

    render() {
        const { item, itemType, isDragging } = this.props;

        if (!isDragging) {
            return null;
        }

        function getItemStyles(props) {
            const { currentOffset, initialOffset, sourceOffset } = props;
            if (!currentOffset) {
                return {
                    display: 'none'
                };
            }

            const x = currentOffset.x + initialOffset.x - sourceOffset.x;
            const y = currentOffset.y + initialOffset.y - sourceOffset.y;

            const transform = `translate(${x}px, ${y}px)`;
            return {
                transform: transform,
                WebkitTransform: transform
            };
        }

        return (

                    {this.renderItem(itemType, item)}

        );
    }
});

function collect(monitor) {
    return {
        item: monitor.getItem(),
        itemType: monitor.getItemType(),
        currentOffset: monitor.getSourceClientOffset(),
        initialOffset: monitor.getInitialClientOffset(),
        sourceOffset: monitor.getInitialSourceClientOffset(),
        isDragging: monitor.isDragging()
    };
}

export default DragLayer(collect)(CustomDragLayer);<|endoftext|>


<commit_before>/* eslint-disable no-console, @typescript-eslint/no-var-requires */
// Karma configuration
const path = require("path");
const argv = require("yargs")
	.alias("i", "file")
	.alias("d", "dir")
	.argv;

let BROWSERS = ["HeadlessChrome", "HeadlessFirefox", "Safari"];

// get the entry point files
let entryPoints = undefined;
if (typeof argv.file === "string") {
	entryPoints = RegExp(`.*\\/${argv.file}\\.test\\.ts$`);
	console.log(`testing file "${argv.file}"`);
} else if (typeof argv.dir === "string") {
	entryPoints = RegExp(`.*${argv.dir}.*\\/.*\\.test\\.ts$`);
	console.log(`testing directory "${argv.dir}"`);
}

if (process.env.BROWSER === "chrome") {
	BROWSERS = ["HeadlessChrome"];
} else if (process.env.BROWSER === "firefox") {
	BROWSERS = ["HeadlessFirefox"];
} else if (process.env.BROWSER === "safari") {
	BROWSERS = ["Safari"];
} else {
	BROWSERS = ["HeadlessChrome", "HeadlessFirefox"];
}

module.exports = function(config) {
	const configuration = {

		// base path that will be used to resolve all patterns (eg. files, exclude)
		basePath: "../",

		// frameworks to use
		// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
		frameworks: ["mocha", "karma-typescript"],

		// list of files / patterns to load in the browser
		files: [
			"test/**/*.ts",
			"Tone/**/*.ts",
			{ pattern: "test/audio/**", included: false },
			{ pattern: "test/html/**", included: false },
		],

		// Karma Typescript compiler options
		karmaTypescriptConfig: {
			compilerOptions: {
				module: "commonjs",
			},
			bundlerOptions: {
				resolve: {
					directories: ["Tone", "node_modules", "test"],
				},
				entrypoints: entryPoints
			},
			coverageOptions: {
				exclude: /(.*\.test\.ts|test\/.*\.ts)$/i,
			},
			reports: {
				html: path.resolve(__dirname, "../coverage"),
				lcovonly: {
					directory: path.resolve(__dirname, "../coverage"),
					filename: "coverage.lcov",
				},
			},
			tsconfig: "./tsconfig.json",
		},

		// list of files to exclude
		exclude: [
			"node_modules/*",
		],

		// preprocess matching files before serving them to the browser
		// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
		preprocessors: {
			"**/*.ts": "karma-typescript",
			// "Tone/**/*.ts": "coverage",
		},

		// test results reporter to use
		// possible values: 'dots', 'progress'
		// available reporters: https://npmjs.org/browse/keyword/karma-reporter
		reporters: ["dots", "karma-typescript"],

		// coverageReporter : {
		// 	type : "lcov",
		// 	dir: path.resolve(__dirname, "../coverage"),
		// },

		// plugins
		plugins: [
			"karma-typescript",
			// "karma-coverage",
			"karma-mocha",
			"karma-chrome-launcher",
			"karma-firefox-launcher",
			"karma-safari-launcher",
			// "karma-sourcemap-loader",
		],

		client: {
			mocha: {
				reporter: "html",
				timeout: 10000,
				retries: 2,
				ui: "bdd",
			},
		},

		// web server port
		port: 9876,

		// enable / disable colors in the output (reporters and logs)
		colors: true,

		// set the inactivity level to longer
		browserNoActivityTimeout: 40000,

		// level of logging
		// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
		logLevel: config.LOG_ERROR,

		// enable / disable watching file and executing tests whenever any file changes
		autoWatch: false,
		// restartOnFileChange : true,

		// start these browsers
		// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
		browsers: BROWSERS,

		// Continuous Integration mode
		// if true, Karma captures browsers, runs the tests and exits
		singleRun: false,

		// Concurrency level
		// how many browser should be started simultaneous
		// concurrency: process.env.TRAVIS ? 1 : Infinity,
		concurrency: Infinity,

		// custom launcher for travis
		customLaunchers: {
			HeadlessChrome: {
				base: "ChromeHeadless",
				flags: ["--no-sandbox", "--use-fake-ui-for-media-stream", "--use-fake-device-for-media-stream",
					"--autoplay-policy=no-user-gesture-required"],
			},
			HeadlessFirefox: {
				base: "Firefox",
				flags: ["-headless"],
				prefs: {
					"focusmanager.testmode": true,
					"media.navigator.permission.disabled": true,
				},
			},
			OnlineChrome: {
				base: "Chrome",
				flags: ["--no-sandbox", "--use-fake-ui-for-media-stream", "--use-fake-device-for-media-stream",
					"--autoplay-policy=no-user-gesture-required"],
			},
		},
	};

	config.set(configuration);
};
<commit_msg>using es6 export<commit_after>/* eslint-disable no-console, @typescript-eslint/no-var-requires */
// Karma configuration
const path = require("path");
const argv = require("yargs")
	.alias("i", "file")
	.alias("d", "dir")
	.argv;

let BROWSERS = ["HeadlessChrome", "HeadlessFirefox", "Safari"];

// get the entry point files
let entryPoints = undefined;
if (typeof argv.file === "string") {
	entryPoints = RegExp(`.*\\/${argv.file}\\.test\\.ts$`);
	console.log(`testing file "${argv.file}"`);
} else if (typeof argv.dir === "string") {
	entryPoints = RegExp(`.*${argv.dir}.*\\/.*\\.test\\.ts$`);
	console.log(`testing directory "${argv.dir}"`);
}

if (process.env.BROWSER === "chrome") {
	BROWSERS = ["HeadlessChrome"];
} else if (process.env.BROWSER === "firefox") {
	BROWSERS = ["HeadlessFirefox"];
} else if (process.env.BROWSER === "safari") {
	BROWSERS = ["Safari"];
} else {
	BROWSERS = ["HeadlessChrome", "HeadlessFirefox"];
}

module.exports = function(config) {
	const configuration = {

		// base path that will be used to resolve all patterns (eg. files, exclude)
		basePath: "../",

		// frameworks to use
		// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
		frameworks: ["mocha", "karma-typescript"],

		// list of files / patterns to load in the browser
		files: [
			"test/**/*.ts",
			"Tone/**/*.ts",
			{ pattern: "test/audio/**", included: false },
			{ pattern: "test/html/**", included: false },
		],

		// Karma Typescript compiler options
		karmaTypescriptConfig: {
			compilerOptions: {
				target: "es6",
				module: "commonjs",
			},
			bundlerOptions: {
				resolve: {
					directories: ["Tone", "node_modules", "test"],
				},
				entrypoints: entryPoints
			},
			coverageOptions: {
				exclude: /(.*\.test\.ts|test\/.*\.ts)$/i,
			},
			reports: {
				html: path.resolve(__dirname, "../coverage"),
				lcovonly: {
					directory: path.resolve(__dirname, "../coverage"),
					filename: "coverage.lcov",
				},
			},
			tsconfig: "./tsconfig.json",
		},

		// list of files to exclude
		exclude: [
			"node_modules/*",
		],

		// preprocess matching files before serving them to the browser
		// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
		preprocessors: {
			"**/*.ts": "karma-typescript",
			// "Tone/**/*.ts": "coverage",
		},

		// test results reporter to use
		// possible values: 'dots', 'progress'
		// available reporters: https://npmjs.org/browse/keyword/karma-reporter
		reporters: ["dots", "karma-typescript"],

		// coverageReporter : {
		// 	type : "lcov",
		// 	dir: path.resolve(__dirname, "../coverage"),
		// },

		// plugins
		plugins: [
			"karma-typescript",
			// "karma-coverage",
			"karma-mocha",
			"karma-chrome-launcher",
			"karma-firefox-launcher",
			"karma-safari-launcher",
			// "karma-sourcemap-loader",
		],

		client: {
			mocha: {
				reporter: "html",
				timeout: 10000,
				retries: 2,
				ui: "bdd",
			},
		},

		// web server port
		port: 9876,

		// enable / disable colors in the output (reporters and logs)
		colors: true,

		// set the inactivity level to longer
		browserNoActivityTimeout: 40000,

		// level of logging
		// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
		logLevel: config.LOG_ERROR,

		// enable / disable watching file and executing tests whenever any file changes
		autoWatch: false,
		// restartOnFileChange : true,

		// start these browsers
		// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
		browsers: BROWSERS,

		// Continuous Integration mode
		// if true, Karma captures browsers, runs the tests and exits
		singleRun: false,

		// Concurrency level
		// how many browser should be started simultaneous
		// concurrency: process.env.TRAVIS ? 1 : Infinity,
		concurrency: Infinity,

		// custom launcher for travis
		customLaunchers: {
			HeadlessChrome: {
				base: "ChromeHeadless",
				flags: ["--no-sandbox", "--use-fake-ui-for-media-stream", "--use-fake-device-for-media-stream",
					"--autoplay-policy=no-user-gesture-required"],
			},
			HeadlessFirefox: {
				base: "Firefox",
				flags: ["-headless"],
				prefs: {
					"focusmanager.testmode": true,
					"media.navigator.permission.disabled": true,
				},
			},
			OnlineChrome: {
				base: "Chrome",
				flags: ["--no-sandbox", "--use-fake-ui-for-media-stream", "--use-fake-device-for-media-stream",
					"--autoplay-policy=no-user-gesture-required"],
			},
		},
	};

	config.set(configuration);
};
<|endoftext|>


<commit_before>{
        "translatorID": "d84574f1-e4d6-4337-934f-bf9d01173bf0",
        "label": "taz.de",
        "creator": "Martin Meyerhoff",
        "target": "^https?://www\\.taz\\.de",
        "minVersion": "1.0",
        "maxVersion": "",
        "priority": 100,
        "inRepository": "1",
        "translatorType": 4,
        "lastUpdated": "2011-03-26 17:18:22"
}

/*
taz.de Translator
Copyright (C) 2011 Martin Meyerhoff

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU 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 General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/

/*
This site is rather heterogenous when it comes to where the author is and all that.
Whenever the script doesn't find something it just returns an empty field.
Try on:
http://www.taz.de/
http://www.taz.de/1/archiv/detailsuche/?tx_hptazsearch_pi1[search_term]=Krise&tx_hptazsearch_pi2[submit_button].x=0&tx_hptazsearch_pi2[submit_button].y=0
http://www.taz.de/1/debatte/kolumnen/artikel/1/haengt-sie-hoeher-1/
*/

function detectWeb(doc, url) {

	// I use XPaths. Therefore, I need the following block.

	var namespace = doc.documentElement.namespaceURI;
	var nsResolver = namespace ? function(prefix) {
		if (prefix == 'x') return namespace; else return null;
	} : null;

	var taz_ArticleTitle_XPath = ".//h1";
	var taz_Multiple_XPath = ".//*[@id='hauptspalte']/div/ul/li/a/h3";
	var taz_Search_XPath = ".//*[@id='hauptspalte']/div/div/ul/li/a/h3";
	if (doc.evaluate(taz_ArticleTitle_XPath, doc, null, XPathResult.ANY_TYPE, null).iterateNext() ){
		Zotero.debug("newspaperArticle");
		return "newspaperArticle";
	} else if (doc.evaluate(taz_Multiple_XPath, doc, null, XPathResult.ANY_TYPE, null).iterateNext() ){
		Zotero.debug("multiple");
		return "multiple";
	}  else if (doc.evaluate(taz_Search_XPath, doc, null, XPathResult.ANY_TYPE, null).iterateNext() ){
		Zotero.debug("multiple");
		return "multiple";
	}
}

function authorCase(author) { // Turns All-Uppercase-Authors to normally cased Authors
	var words = author.split(/\s|-/);
	var authorFixed = '';
	for (var i in words) {
		words[i] = words[i][0].toUpperCase() + words[i].substr(1).toLowerCase();
		authorFixed = authorFixed + words[i] + ' ';
	}
	return(authorFixed);
}

function scrape(doc, url) {
	var namespace = doc.documentElement.namespaceURI;
	var nsResolver = namespace ? function(prefix) {
		if (prefix == 'x') return namespace; else return null;
	} : null;

	var newItem = new Zotero.Item("newspaperArticle");
	newItem.url = doc.location.href;

	// This is for the title!

	var title_XPath = '//title';
	var title = doc.evaluate(title_XPath, doc, nsResolver, XPathResult.ANY_TYPE, null).iterateNext().textContent;
	newItem.title = title.split(" - ")[0];

	// Summary
	var description_XPath = '//meta[contains(@name, "description")]';
	var description = doc.evaluate(description_XPath, doc, nsResolver, XPathResult.ANY_TYPE, null).iterateNext().content;
	summary = description.replace(/\sVON.*$/g, '');
	newItem.abstractNote = summary.replace(/KOMMENTAR|KOLUMNE.*$/g, '');

	// Authors
	var author_XPath = "//*[contains(@class, 'sectbody')]/*/span[contains(@class, 'author')]";
	if (doc.evaluate(author_XPath, doc, null, XPathResult.ANY_TYPE, null).iterateNext() ) {
		var author = doc.evaluate(author_XPath, doc, nsResolver, XPathResult.ANY_TYPE, null).iterateNext().textContent;
	} else if (description.match(/^(KOMMENTAR)|(KOLUMNE)\sVON/)){
		Zotero.debug(description);
		author = description.replace(/^(KOMMENTAR)|(KOLUMNE)\sVON\s/, '');
	} else {
		var author = "";
	}
	author = author.replace(/^\s*|\s*$/g, '');
	author = author.replace(".", ". "); // in case a space is missing.
	author = author.replace("VON ", '');
	author = author.replace(/\s+/g, ' ');
	author = author.split(/\sund\s|\su\.\s|\,\s|\&/);
	for (var i in author) {
		if (author[i].match(/\s/)) { // only names that contain a space!
			author[i] = author[i].replace(/^\s*|\s*$/g, '');
			author[i] = authorCase(author[i]);
			newItem.creators.push(Zotero.Utilities.cleanAuthor(author[i], "author"));
		}
	}

	// Section
	var section_XPath = ".//*[contains(@class, 'selected')]/ul/li[contains(@class, 'selected')]";
	if (doc.evaluate(section_XPath, doc, null, XPathResult.ANY_TYPE, null).iterateNext() ) {
		var section= doc.evaluate(section_XPath, doc, nsResolver, XPathResult.ANY_TYPE, null).iterateNext().textContent;
		newItem.section = section;
	}

	// Date
	var date_XPath = ".//div[contains(@class, 'secthead')]";
	var date = doc.evaluate(date_XPath, doc, nsResolver, XPathResult.ANY_TYPE, null).iterateNext().textContent;
	date = date.replace(/^\s*|\s*$/g, '');
	date = date.substr(0,10);
	newItem.date = date;

	newItem.attachments.push({url:doc.location.href, title:doc.title, mimeType:"text/html"});
	newItem.publicationTitle = "die tageszeitung"

	newItem.complete();

}

function doWeb(doc, url) {
	var namespace = doc.documentElement.namespaceURI;
	var nsResolver = namespace ? function(prefix) {
		if (prefix == 'x') return namespace; else return null;
	} : null;
	var articles = new Array();

	if (detectWeb(doc, url) == "multiple") {
		var items = new Object();
		var taz_Multiple_XPath = ".//*[@id='hauptspalte']/div/ul/li/a";
		var taz_Search_XPath = ".//*[@id='hauptspalte']/div/div/ul/li/a";

		 if (doc.evaluate(taz_Multiple_XPath, doc, null, XPathResult.ANY_TYPE, null).iterateNext() ){
			var titles = doc.evaluate(taz_Multiple_XPath, doc, nsResolver, XPathResult.ANY_TYPE, null);
		}  else if (doc.evaluate(taz_Search_XPath, doc, null, XPathResult.ANY_TYPE, null).iterateNext() ){
			var titles = doc.evaluate(taz_Search_XPath, doc, nsResolver, XPathResult.ANY_TYPE, null);
		}

		var next_title;
		while (next_title = titles.iterateNext()) {
			items[next_title.href] = next_title.innerHTML;
			items[next_title.href] = items[next_title.href].replace(/(\<h4.*?\>.*?\<\/h4\>\<h3.*?\>)(.*)\<\/h3\>.*/, '$2');
		}
		items = Zotero.selectItems(items);
		for (var i in items) {
			articles.push(i);
		}
		Zotero.Utilities.processDocuments(articles, scrape, function() {Zotero.done();});
		Zotero.wait();
	} else {
		scrape(doc, url);
	}
}
<commit_msg>Trans: Loosen TAZ target<commit_after>{
        "translatorID": "d84574f1-e4d6-4337-934f-bf9d01173bf0",
        "label": "taz.de",
        "creator": "Martin Meyerhoff",
        "target": "^https?://(?:www\\.)?taz\\.de",
        "minVersion": "1.0",
        "maxVersion": "",
        "priority": 100,
        "inRepository": "1",
        "translatorType": 4,
        "lastUpdated": "2011-06-14 17:18:22"
}

/*
taz.de Translator
Copyright (C) 2011 Martin Meyerhoff

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU 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 General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/

/*
This site is rather heterogenous when it comes to where the author is and all that.
Whenever the script doesn't find something it just returns an empty field.
Try on:
http://www.taz.de/
http://www.taz.de/1/archiv/detailsuche/?tx_hptazsearch_pi1[search_term]=Krise&tx_hptazsearch_pi2[submit_button].x=0&tx_hptazsearch_pi2[submit_button].y=0
http://www.taz.de/1/debatte/kolumnen/artikel/1/haengt-sie-hoeher-1/
*/

function detectWeb(doc, url) {

	// I use XPaths. Therefore, I need the following block.

	var namespace = doc.documentElement.namespaceURI;
	var nsResolver = namespace ? function(prefix) {
		if (prefix == 'x') return namespace; else return null;
	} : null;

	var taz_ArticleTitle_XPath = ".//h1";
	var taz_Multiple_XPath = ".//*[@id='hauptspalte']/div/ul/li/a/h3";
	var taz_Search_XPath = ".//*[@id='hauptspalte']/div/div/ul/li/a/h3";
	if (doc.evaluate(taz_ArticleTitle_XPath, doc, null, XPathResult.ANY_TYPE, null).iterateNext() ){
		Zotero.debug("newspaperArticle");
		return "newspaperArticle";
	} else if (doc.evaluate(taz_Multiple_XPath, doc, null, XPathResult.ANY_TYPE, null).iterateNext() ){
		Zotero.debug("multiple");
		return "multiple";
	}  else if (doc.evaluate(taz_Search_XPath, doc, null, XPathResult.ANY_TYPE, null).iterateNext() ){
		Zotero.debug("multiple");
		return "multiple";
	}
}

function authorCase(author) { // Turns All-Uppercase-Authors to normally cased Authors
	var words = author.split(/\s|-/);
	var authorFixed = '';
	for (var i in words) {
		words[i] = words[i][0].toUpperCase() + words[i].substr(1).toLowerCase();
		authorFixed = authorFixed + words[i] + ' ';
	}
	return(authorFixed);
}

function scrape(doc, url) {
	var namespace = doc.documentElement.namespaceURI;
	var nsResolver = namespace ? function(prefix) {
		if (prefix == 'x') return namespace; else return null;
	} : null;

	var newItem = new Zotero.Item("newspaperArticle");
	newItem.url = doc.location.href;

	// This is for the title!

	var title_XPath = '//title';
	var title = doc.evaluate(title_XPath, doc, nsResolver, XPathResult.ANY_TYPE, null).iterateNext().textContent;
	newItem.title = title.split(" - ")[0];

	// Summary
	var description_XPath = '//meta[contains(@name, "description")]';
	var description = doc.evaluate(description_XPath, doc, nsResolver, XPathResult.ANY_TYPE, null).iterateNext().content;
	summary = description.replace(/\sVON.*$/g, '');
	newItem.abstractNote = summary.replace(/KOMMENTAR|KOLUMNE.*$/g, '');

	// Authors
	var author_XPath = "//*[contains(@class, 'sectbody')]/*/span[contains(@class, 'author')]";
	if (doc.evaluate(author_XPath, doc, null, XPathResult.ANY_TYPE, null).iterateNext() ) {
		var author = doc.evaluate(author_XPath, doc, nsResolver, XPathResult.ANY_TYPE, null).iterateNext().textContent;
	} else if (description.match(/^(KOMMENTAR)|(KOLUMNE)\sVON/)){
		Zotero.debug(description);
		author = description.replace(/^(KOMMENTAR)|(KOLUMNE)\sVON\s/, '');
	} else {
		var author = "";
	}
	author = author.replace(/^\s*|\s*$/g, '');
	author = author.replace(".", ". "); // in case a space is missing.
	author = author.replace("VON ", '');
	author = author.replace(/\s+/g, ' ');
	author = author.split(/\sund\s|\su\.\s|\,\s|\&/);
	for (var i in author) {
		if (author[i].match(/\s/)) { // only names that contain a space!
			author[i] = author[i].replace(/^\s*|\s*$/g, '');
			author[i] = authorCase(author[i]);
			newItem.creators.push(Zotero.Utilities.cleanAuthor(author[i], "author"));
		}
	}

	// Section
	var section_XPath = ".//*[contains(@class, 'selected')]/ul/li[contains(@class, 'selected')]";
	if (doc.evaluate(section_XPath, doc, null, XPathResult.ANY_TYPE, null).iterateNext() ) {
		var section= doc.evaluate(section_XPath, doc, nsResolver, XPathResult.ANY_TYPE, null).iterateNext().textContent;
		newItem.section = section;
	}

	// Date
	var date_XPath = ".//div[contains(@class, 'secthead')]";
	var date = doc.evaluate(date_XPath, doc, nsResolver, XPathResult.ANY_TYPE, null).iterateNext().textContent;
	date = date.replace(/^\s*|\s*$/g, '');
	date = date.substr(0,10);
	newItem.date = date;

	newItem.attachments.push({url:doc.location.href, title:doc.title, mimeType:"text/html"});
	newItem.publicationTitle = "die tageszeitung"

	newItem.complete();

}

function doWeb(doc, url) {
	var namespace = doc.documentElement.namespaceURI;
	var nsResolver = namespace ? function(prefix) {
		if (prefix == 'x') return namespace; else return null;
	} : null;
	var articles = new Array();

	if (detectWeb(doc, url) == "multiple") {
		var items = new Object();
		var taz_Multiple_XPath = ".//*[@id='hauptspalte']/div/ul/li/a";
		var taz_Search_XPath = ".//*[@id='hauptspalte']/div/div/ul/li/a";

		 if (doc.evaluate(taz_Multiple_XPath, doc, null, XPathResult.ANY_TYPE, null).iterateNext() ){
			var titles = doc.evaluate(taz_Multiple_XPath, doc, nsResolver, XPathResult.ANY_TYPE, null);
		}  else if (doc.evaluate(taz_Search_XPath, doc, null, XPathResult.ANY_TYPE, null).iterateNext() ){
			var titles = doc.evaluate(taz_Search_XPath, doc, nsResolver, XPathResult.ANY_TYPE, null);
		}

		var next_title;
		while (next_title = titles.iterateNext()) {
			items[next_title.href] = next_title.innerHTML;
			items[next_title.href] = items[next_title.href].replace(/(\<h4.*?\>.*?\<\/h4\>\<h3.*?\>)(.*)\<\/h3\>.*/, '$2');
		}
		items = Zotero.selectItems(items);
		for (var i in items) {
			articles.push(i);
		}
		Zotero.Utilities.processDocuments(articles, scrape, function() {Zotero.done();});
		Zotero.wait();
	} else {
		scrape(doc, url);
	}
}
<|endoftext|>


<commit_before>const test = require('tape')
const mock = require('mock-fs')
const Promise = require('bluebird')
const sbsFactory = require('../dist/blob-store.js')
const streamToString = require('./test-streamtostring')
const crispyStream = require('crispy-stream')
const data = 'The quick brown fox jumped over the lazy dog'
const readStream = crispyStream.createReadStream(data)

const options = {
  blobStoreRoot: '/tmp/blobs',
  idType: 'cuid',
  dirDepth: 5,
  dirWidth: 10
}
const blobStore = sbsFactory.create(options)
var testBlobPath = ''

test('blob-store api callback tests', (t) => {
  mock()

  t.plan(11)
  blobStore.createWriteStream((err1, result) => {
    if (err1) { t.fail(err1.message) }
    t.ok(result.blobPath, 'createWriteStream blob path created')
    t.ok(result.writeStream, 'createWriteStream writeStream created')
    testBlobPath = result.blobPath
    result.writeStream.on('finish', () => {
      t.pass('blob file write succeeded')
      var blobReadStream = blobStore.createReadStream(result.blobPath)
      streamToString(blobReadStream, (err2, readData) => {
        if (err2) { t.fail(err2.message) }
        t.equal(readData, data, 'blob file read succeeded')
        blobStore.exists(testBlobPath, (err3, exists) => {
          if (err3) { t.fail(err3.message) }
          t.ok(exists, 'blob file exists succeeded')
          blobStore.stat(testBlobPath, (err4, statData) => {
            if (err4) { t.fail(err4.message) }
            t.equal(statData.size, 44, 'blob file stat succeeded')
            blobStore.remove(testBlobPath, (err5) => {
              if (err5) { t.fail(err5.message) }
              t.deepEqual(err5, undefined, 'blob file remove succeeded')
              blobStore.exists(testBlobPath, (err6, existsNot) => {
                if (err6) { t.fail(err6.message) }
                t.notOk(existsNot, 'blob file no longer exists')
                var invalidReadStream = blobStore.createReadStream('/invalidread')
                invalidReadStream.on('error', (err7) => {
                  t.ok(err7, 'createReadStream on invalid path raises error event')
                  blobStore.stat('/invalidstat', (err8, invalidStat) => {
                    t.ok(err8, 'stat on invalid path throws error')
                    blobStore.remove('/invalidremove', (err9) => {
                      if (err9) { t.fail(err9.message) }
                      t.deepEqual(err9, undefined, 'remove on invalid path returns undefined')
                      return mock.restore()
                    })
                  })
                })
              })
            })
          })
        })
      })
    })
    result.writeStream.on('error', console.log.bind(console))
    readStream.pipe(result.writeStream)
  })
})
<commit_msg>Removed Promise variable<commit_after>const test = require('tape')
const mock = require('mock-fs')
const sbsFactory = require('../dist/blob-store.js')
const streamToString = require('./test-streamtostring')
const crispyStream = require('crispy-stream')
const data = 'The quick brown fox jumped over the lazy dog'
const readStream = crispyStream.createReadStream(data)

const options = {
  blobStoreRoot: '/tmp/blobs',
  idType: 'cuid',
  dirDepth: 5,
  dirWidth: 10
}
const blobStore = sbsFactory.create(options)
var testBlobPath = ''

test('blob-store api callback tests', (t) => {
  mock()

  t.plan(11)
  blobStore.createWriteStream((err1, result) => {
    if (err1) { t.fail(err1.message) }
    t.ok(result.blobPath, 'createWriteStream blob path created')
    t.ok(result.writeStream, 'createWriteStream writeStream created')
    testBlobPath = result.blobPath
    result.writeStream.on('finish', () => {
      t.pass('blob file write succeeded')
      var blobReadStream = blobStore.createReadStream(result.blobPath)
      streamToString(blobReadStream, (err2, readData) => {
        if (err2) { t.fail(err2.message) }
        t.equal(readData, data, 'blob file read succeeded')
        blobStore.exists(testBlobPath, (err3, exists) => {
          if (err3) { t.fail(err3.message) }
          t.ok(exists, 'blob file exists succeeded')
          blobStore.stat(testBlobPath, (err4, statData) => {
            if (err4) { t.fail(err4.message) }
            t.equal(statData.size, 44, 'blob file stat succeeded')
            blobStore.remove(testBlobPath, (err5) => {
              if (err5) { t.fail(err5.message) }
              t.deepEqual(err5, undefined, 'blob file remove succeeded')
              blobStore.exists(testBlobPath, (err6, existsNot) => {
                if (err6) { t.fail(err6.message) }
                t.notOk(existsNot, 'blob file no longer exists')
                var invalidReadStream = blobStore.createReadStream('/invalidread')
                invalidReadStream.on('error', (err7) => {
                  t.ok(err7, 'createReadStream on invalid path raises error event')
                  blobStore.stat('/invalidstat', (err8, invalidStat) => {
                    t.ok(err8, 'stat on invalid path throws error')
                    blobStore.remove('/invalidremove', (err9) => {
                      if (err9) { t.fail(err9.message) }
                      t.deepEqual(err9, undefined, 'remove on invalid path returns undefined')
                      return mock.restore()
                    })
                  })
                })
              })
            })
          })
        })
      })
    })
    result.writeStream.on('error', console.log.bind(console))
    readStream.pipe(result.writeStream)
  })
})
<|endoftext|>


<commit_before>
// try to login

// create texts and co-ments
// collect newly created URLs

// Get workspace name, public texts…

// unlog

// check that public texts still work while unlogged
// check that non public texts are unavailable

// Is the workspace name correctly displayed ?
// Are the public texts displayed in the login page ?

var w = __karma__.config.w;

suite ('comt', function () {

	this.timeout(150000);

	suite ('contact page', function () {
		test_page_loading ('/contact/', 'Contact');
		test_unlogged_header ();
		test_val ('form#profile[action="."]'); // the form exists
		test_count ('form#profile .label', 5); // it has no more than 5 labels (may be no more fields)
		test_form_field ('id_name', 'text', 'Your name', true); // the field id_name is…
		test_form_field ('id_email', 'text', 'Your email address', true);
		test_form_field ('id_title', 'text', 'Subject of the message', true);
		test_form_field ('id_body', 'textarea', 'Body of the message', true);
		test_form_field ('id_copy', 'checkbox', 'Send me a copy of the email', false);
		test_val ('#profile input[type=submit]','Send'); // test that a the .val() of the element is
		test_val ('input#cancel_button[type=button]', 'Cancel');
		test_unlogged_footer ();
		test ('to check that toBeDefined test still works', dsl(function () {
			expect (elt ('#header_controls a[href="/xxx/"]').val ()).not ().toBeDefined ();
		}));
		test ('get back to / to avoid bugging next page load', dsl(function () {
			browser.navigateTo ('/');
		}));
	});

	suite ('help page', function () {
		test_page_loading ('/help/', 'Help');
		test_unlogged_header ();
		test_unlogged_footer ();
	});

	suite ('reset password page', function () {
		test_page_loading ('/password_reset/', 'Reset my password');
		test_unlogged_header ();
		test_val ('form#profile[action="."]');
		test_count ('form#profile .label', 1);
		test_form_field ('id_email', 'text', 'E-mail', true);
		test_val ('#profile input[type=submit]', 'Reset my password');
		test_unlogged_footer ();
	});

	suite ('login page', function () {
		test_page_loading ('/', 'Home');
		test_unlogged_header ();
		test_val ('form#login[action="/login/"]');
		test_count ('form#login[action="/login/"] .label', 2);
		test_form_field ('id_username', 'text', 'Username', true);
		test_form_field ('id_password', 'password', 'Password', true);
		test_val ('form#login input[type=submit]', 'Login');
		test_text ('form#login a[href="/password_reset/"]', 'Forgot password?');
		test_unlogged_footer ();
		// test_i18n ();
		test ('logs an admin in', dsl(function () {
			input ('#id_username').enter (w.USER_ADMIN);
			input ('#id_password').enter (w.PASS_ADMIN);
			elt ('#login input[type=submit]').click ();
			// Must be done here in this test() block
			browser.waitForPageLoad ();
			browser.navigateTo ('/');
			expect (element ('title').text ()).toMatch (/Dashboard/m);
		}));
	});

	suite ('admin dashboard', function () {
		// Should starts with :
		// test_page_loading ('/', 'Dashboard');
		// But its the last thing we did in the previous test
		test_logged_header (w.USER_ADMIN);
		test_default_tabs ();
		test_count ('table.dash_table', 5);
		test_text ('table.dash_table th:eq(0)', 'Actions', 0);
		test_text ('table.dash_table th:eq(1)', 'Recent texts (all)', 2);
		test_text ('table.dash_table th:eq(2)', 'Recent comments', 1);
		test_match ('table.dash_table th:eq(3)', /^Workspace activity\n\s+\(month\/week\/24 hours\)$/m);
		test_text ('table.dash_table th:eq(4) span.em', 'Activities', 4);
		test_unlogged_footer ();
	});
});

function test_default_tabs () {
	test_count ('#main-tabs a', 5);
	test_text ('#main-tabs li:nth-of-type(1) a[href="/"]', 'Dashboard');
	test_match ('#main-tabs li:nth-of-type(2) a[href="/text/"]', /^Texts \(\d+\) $/);
	test_match ('#main-tabs li:nth-of-type(3) a[href="/user/"]', /^People  \(\d+\)$/);
	test_text ('#main-tabs li:nth-of-type(4) a[href="/settings/"]', 'Settings');
	test_text ('#main-tabs li:nth-of-type(5) a[href="/followup/"]', 'Followup');
}

function test_logged_header (username) {
	test_text	('#header_controls b', username)
	test_count	('#header_controls a', 6);
	test_text	('#header_controls a:nth-of-type(1)[href="/"]',					'Home');
	test_text	('#header_controls a:nth-of-type(2)[href="/create/content/"]',	'Create a text');
	test_text	('#header_controls a:nth-of-type(3)[href="/create/upload/"]',	'Upload a text');
	test_text	('#header_controls a:nth-of-type(4)[href="/create/import/"]',	'Import a co-mented text');
	test_text	('#header_controls a:nth-of-type(5)[href="/profile/"]',			'Profile');
	test_text	('#header_controls a:nth-of-type(6)[href="/logout/"]',			'Logout');
}

function test_unlogged_header () {
	test_count	('#header_controls a', 2);
	test_text	('#header_controls a[href="/"]', 'Home');
	test_text	('#header_controls a[href="/login/"]', 'Login');
}

function test_unlogged_footer (url) {
	test_count	('#footer a', 9);
	test_text	('#footer a:nth-of-type(1)[href="/contact/"]', 'Contact');
	test_match	('#footer #comentlink[href="http://www.co-ment.com"]', /Powered by/m);
	test_text	('#footer a:nth-of-type(3)[href="/help/"]', 'Help');
	test_text	('#footer a:nth-of-type(4)[href="/i18n/setlang/fr/"]', 'Français');
	test_text	('#footer a:nth-of-type(5)[href="/i18n/setlang/no/"]', 'Norsk');
	test_text	('#footer a:nth-of-type(6)[href="/i18n/setlang/pt_BR/"]', 'Português Brasileiro');
	test_text	('#footer a:nth-of-type(7)[href="/i18n/setlang/es/"]', 'Español');
	test_text	('#footer a:nth-of-type(8)[href="/i18n/setlang/bg/"]', 'Български');
	test_text	('#footer a:nth-of-type(9)[href="/i18n/setlang/it/"]', 'Italiano');
}

function test_i18n () {
	test ('can change lang to french', dsl(function () {
		element ('#footer a[href="/i18n/setlang/fr/"]').click ();
//		browser.waitForPageLoad ();
//		browser.navigateTo ('/');
//		browser.reload ();
		expect (elt ('#footer a[href="/help/"]').text ()).toBe ('Aide');
		element ('#footer a[href="/i18n/setlang/en/"]').click ();
//		browser.waitForPageLoad ();
//		browser.navigateTo ('/');
	}));
}

function test_page_loading (url, title) {
	test ('loads', dsl(function () {
		// here we are in Karma page
		browser.navigateTo (url);
		expect (element ('title').text ()).toMatch (new RegExp (title,'m'));
		// The same test agin vaniller javascript
		element ('title').text (function (page_title) {
			// here we got a value from the test iframe
			// to display the tested value : console.log (page_title);
			if (!(new RegExp (title, 'm').test (page_title))) throw 'got page '+page_title+' instead';
		});
	}));
}

/** Test if the selected DOM element is defined or has a given value : .val()
 *  s : CSS selector
 *  e : expected value, if omited, test existence
 */
function test_val (s, e) {
	e = typeof e == 'undefined' ? '' : e; // .val() returns defined ? '' : undefined; // if no value
	test (s+' is '+e, dsl(function () {
		expect (elt (s).val ()).toBe (e);
	}));
}

/** Test if the selected DOM element has the given text : .text()
 *  s : CSS selector
 *  e : expected value
 */
function test_text (s, e) {
	test (s+' has text '+e, dsl(function () {
		expect (elt (s).text ()).toBe (e);
	}));
}

/** Test if the selected DOM element .text() value match the given regexp
 *  s : CSS selector
 *  r : regexp to match
 */
function test_match (s, r) {
	test (s+' text match '+r, dsl(function () {
		expect (elt (s).text ()).toMatch (r);
	}));
}

/** Count selector occurences
 *  s : CSS selector
 *  e : expected count
 */
function test_count (s, e) {
	test (s+' count is '+e, dsl(function () {
		expect (elt (s).count ()).toBe (e);
	}));
}

/** Test Django form field presence
 */
function test_form_field (id, type, label, mandatory) {
	test ('has a '+label+' field', dsl(function () {
		var s = type == 'textarea' ? 'textarea#'+id : 'input#'+id+'[type='+type+']';
		expect (elt (s).val ()).toBeDefined ();
		expect (elt ('label[for='+id+']').text ()).toBe (label);

		if (mandatory)
			expect (elt ('label[for='+id+'] + span.required_star').val ()).toBeDefined ();
	}));
}

/** Ensure the given element is visible
 *  s : CSS selector of the DOM element to check
 */
function elt (s) {
	return element (s + ':visible');
}
<commit_msg>rewritting and new tests<commit_after>
// try to login

// create texts and co-ments
// collect newly created URLs

// Get workspace name, public texts…

// unlog

// check that public texts still work while unlogged
// check that non public texts are unavailable

// Is the workspace name correctly displayed ?
// Are the public texts displayed in the login page ?

var w = __karma__.config.w;

suite ('comt', function () {

	this.timeout(150000);

	suite ('contact page', function () {
		test_page_loading ('/contact/', 'Contact');
		test_unlogged_header ();
		test_val ('form#profile[action="."]'); // the form exists
		test_count ('form#profile .label', 5); // it has no more than 5 labels (may be no more fields)
		test_form_field ('profile', 'id_name', 'text', 0, 'Your name', true); // the field id_name is…
		test_form_field ('profile', 'id_email', 'text', 1, 'Your email address', true);
		test_form_field ('profile', 'id_title', 'text', 2, 'Subject of the message', true);
		test_form_field ('profile', 'id_body', 'textarea', 3, 'Body of the message', true);
		test_form_field ('profile', 'id_copy', 'checkbox', 4, 'Send me a copy of the email', false);
		test_val ('#profile input[type=submit]','Send'); // test that a the .val() of the element is
		test_val ('input#cancel_button[type=button]', 'Cancel');
		test_unlogged_footer ();
		test ('to check that toBeDefined test still works', dsl(function () {
			expect (elt ('#header_controls a[href="/xxx/"]').val ()).not ().toBeDefined ();
		}));
		test ('get back to / to avoid bugging next page load', dsl(function () {
			browser.navigateTo ('/');
		}));
	});

	suite ('help page', function () {
		test_page_loading ('/help/', 'Help');
		test_unlogged_header ();
		test_unlogged_footer ();
	});

	suite ('reset password page', function () {
		test_page_loading ('/password_reset/', 'Reset my password');
		test_unlogged_header ();
		test_val ('form#profile[action="."]');
		test_count ('form#profile .label', 1);
		test_form_field ('profile', 'id_email', 'text', 1, 'E-mail', true);
		test_val ('#profile input[type=submit]', 'Reset my password');
		test_unlogged_footer ();
	});

	suite ('login page', function () {
		test_page_loading ('/', 'Home');
		test_unlogged_header ();
		test_val ('form#login[action="/login/"]');
		test_count ('form#login[action="/login/"] .label', 2);
		test_form_field ('login', 'id_username', 'text', 0, 'Username', true);
		test_form_field ('login', 'id_password', 'password', 1, 'Password', true);
		test_val ('form#login input[type=submit]', 'Login');
		test_text ('form#login a[href="/password_reset/"]', 'Forgot password?');
		test_unlogged_footer ();
		// test_i18n ();
		test ('logs an admin in', dsl(function () {
			input ('#id_username').enter (w.USER_ADMIN);
			input ('#id_password').enter (w.PASS_ADMIN);
			elt ('#login input[type=submit]').click ();
			// Must be done here in this test() block
			browser.waitForPageLoad ();
			browser.navigateTo ('/');
			expect (element ('title').text ()).toMatch (/Dashboard/m);
		}));
	});

	suite ('admin dashboard', function () {
		// Should starts with :
		// test_page_loading ('/', 'Dashboard');
		// But its the last thing we did in the previous test
		test_logged_header (w.USER_ADMIN);
		test_default_tabs ();
		test_count	('table.dash_table', 5);
		test_text	('table.dash_table th:eq(0)', 'Actions');
		test_match	('table.dash_table:eq(0) a:eq(0)[href="/create/content/"]', /\sCreate a text/);
		test_text	('table.dash_table:eq(0) a:eq(1).tip[href="#"]', ' ');
		test_match	('table.dash_table:eq(0) a:eq(2)[href="/create/upload/"]', /\sUpload a text/);
		test_text	('table.dash_table:eq(0) a:eq(3).tip[href="#"]', ' ');
		test_match	('table.dash_table:eq(0) a:eq(4)[href="/create/import/"]', /\sImport a co-mented text/);
		test_text	('table.dash_table:eq(0) a:eq(5).tip[href="#"]', ' ');
		test_match	('table.dash_table:eq(0) a:eq(6)[href="/user/add/"]', /\sInvite user/);
		test_match	('table.dash_table:eq(0) a:eq(7)[href="/profile/"]', /\sEdit your profile/);
		test_match	('table.dash_table:eq(0) a:eq(8)[href="/text/"]', /\sView text list/);
		test_match	('table.dash_table:eq(0) a:eq(9)[href="/settings/"]', /\sConfigure workspace/);
		test_text	('table.dash_table th:eq(1)', 'Recent texts (all)');
		test_text	('table.dash_table:eq(1) a:eq(0)[href="/text/"]', 'all');
		test_text	('table.dash_table th:eq(2)', 'Recent comments');
		test_match	('table.dash_table th:eq(3)', /^Workspace activity\n\s+\(month\/week\/24 hours\)$/m);
		test_text	('table.dash_table:eq(3) a:eq(0)[href="?span=month"]', 'month');
		test_text	('table.dash_table:eq(3) a:eq(1)[href="?span=day"]', '24 hours');
		test_text	('table.dash_table th:eq(4) span.em', 'Activities');
		test_unlogged_footer ();
	});

	suite ('followup', function () {
		test_page_loading ('/followup/', 'Followup');
		test_text	('#followup a:eq(0)[href="/help/#public_private_feed"]', '?');
		test_match	('#followup a:eq(1)[href$="/feed/"]', new RegExp (w.WORKSPACE_URL+'feed/', 'm'));
		test_text	('#followup a:eq(2)[href="/help/#public_private_feed"]', '?');
		test_count	('form#followup_form[action="."] input', 3);
		test_val	('form#followup_form input[type=submit]', '(Activate private feed|Reset private feed url)');
		test_val	('form#followup_form input#workspace_notify_check[type=checkbox]', 'on');
		test_val	('form#followup_form input#own_notify_check[type=checkbox]', 'on');

		// tester qu'une fois cliqué, le bouton à le nvo label, et qu'une adresse est disponible
		// tester que si on reclique l'adresse est changée

	});
});

function test_default_tabs () {
	test_count	('#main-tabs a', 5);
	test_text	('#main-tabs li:nth-of-type(1) a[href="/"]', 'Dashboard');
	test_match	('#main-tabs li:nth-of-type(2) a[href="/text/"]', /^Texts \(\d+\) $/);
	test_match	('#main-tabs li:nth-of-type(3) a[href="/user/"]', /^People  \(\d+\)$/);
	test_text	('#main-tabs li:nth-of-type(4) a[href="/settings/"]', 'Settings');
	test_text	('#main-tabs li:nth-of-type(5) a[href="/followup/"]', 'Followup');
}

function test_logged_header (username) {
	test_text	('#header_controls b', username)
	test_count	('#header_controls a', 6);
	test_text	('#header_controls a:nth-of-type(1)[href="/"]',					'Home');
	test_text	('#header_controls a:nth-of-type(2)[href="/create/content/"]',	'Create a text');
	test_text	('#header_controls a:nth-of-type(3)[href="/create/upload/"]',	'Upload a text');
	test_text	('#header_controls a:nth-of-type(4)[href="/create/import/"]',	'Import a co-mented text');
	test_text	('#header_controls a:nth-of-type(5)[href="/profile/"]',			'Profile');
	test_text	('#header_controls a:nth-of-type(6)[href="/logout/"]',			'Logout');
}

function test_unlogged_header () {
	test_count	('#header_controls a', 2);
	test_text	('#header_controls a[href="/"]', 'Home');
	test_text	('#header_controls a[href="/login/"]', 'Login');
}

function test_unlogged_footer (url) {
	test_count	('#footer a', 9);
	test_text	('#footer a:nth-of-type(1)[href="/contact/"]', 'Contact');
	test_match	('#footer #comentlink[href="http://www.co-ment.com"]', /Powered by/m);
	test_text	('#footer a:nth-of-type(3)[href="/help/"]', 'Help');
	test_text	('#footer a:nth-of-type(4)[href="/i18n/setlang/fr/"]', 'Français');
	test_text	('#footer a:nth-of-type(5)[href="/i18n/setlang/no/"]', 'Norsk');
	test_text	('#footer a:nth-of-type(6)[href="/i18n/setlang/pt_BR/"]', 'Português Brasileiro');
	test_text	('#footer a:nth-of-type(7)[href="/i18n/setlang/es/"]', 'Español');
	test_text	('#footer a:nth-of-type(8)[href="/i18n/setlang/bg/"]', 'Български');
	test_text	('#footer a:nth-of-type(9)[href="/i18n/setlang/it/"]', 'Italiano');
}

function test_i18n () {
	test ('can change lang to french', dsl(function () {
		element ('#footer a[href="/i18n/setlang/fr/"]').click ();
//		browser.waitForPageLoad ();
//		browser.navigateTo ('/');
//		browser.reload ();
		expect (elt ('#footer a[href="/help/"]').text ()).toBe ('Aide');
		element ('#footer a[href="/i18n/setlang/en/"]').click ();
//		browser.waitForPageLoad ();
//		browser.navigateTo ('/');
	}));
}

function test_page_loading (url, title) {
	test ('loads', dsl(function () {
		// here we are in Karma page
		browser.navigateTo (url);
		expect (element ('title').text ()).toMatch (new RegExp (title,'m'));
		// The same test agin vaniller javascript
		element ('title').text (function (page_title) {
			// here we got a value from the test iframe
			// to display the tested value : console.log (page_title);
			if (!(new RegExp (title, 'm').test (page_title))) throw 'got page '+page_title+' instead';
		});
	}));
}

/** Test if the selected DOM element is defined or has a given value : .val()
 *  s : CSS selector
 *  e : expected value, if omited, test existence
 */
function test_val (s, e) {
	e = typeof e == 'undefined' ? '' : e; // .val() returns defined ? '' : undefined; // if no value
	test (s+' is '+e, dsl(function () {
		expect (elt (s).val ()).toMatch (new RegExp (e, 'm'));
	}));
}

/** Test if the selected DOM element has the given text : .text()
 *  s : CSS selector
 *  e : expected value
 */
function test_text (s, e) {
	test (s+' has text '+e, dsl(function () {
		expect (elt (s).text ()).toBe (e);
	}));
}

/** Test if the selected DOM element .text() value match the given regexp
 *  s : CSS selector
 *  r : regexp to match
 */
function test_match (s, r) {
	test (s+' text match '+r, dsl(function () {
		expect (elt (s).text ()).toMatch (r);
	}));
}

/** Count selector occurences
 *  s : CSS selector
 *  e : expected count
 */
function test_count (s, e) {
	test (s+' count is '+e, dsl(function () {
		expect (elt (s).count ()).toBe (e);
	}));
}

/** Test Django form field presence
 */
function test_form_field (form_id, field_id, type, position, label, mandatory) {
	test ('has a '+label+' form field', dsl(function () {
		var s = type == 'textarea' ? 'textarea#'+field_id : 'input#'+field_id+'[type='+type+']';
		expect (elt (s).val ()).toBeDefined ();
		expect (elt ('#'+form_id+' :input:eq('+position+')#'+field_id).val ()).toBeDefined ();
		expect (elt ('label[for='+field_id+']').text ()).toBe (label);

		if (mandatory)
			expect (elt ('label[for='+field_id+'] + span.required_star').val ()).toBeDefined ();
	}));
}

/** Ensure the given element is visible
 *  s : CSS selector of the DOM element to check
 */
function elt (s) {
	return element (s + ':visible');
}
<|endoftext|>


<commit_before>// Stores the width of each bar in pixels
var barWidth = 15;
// Stores the spacing between each line bar in pixels
var barSpacing = 10;

// Quotes about wastage of time
var timeQuotes = ["when you kill time, remember that it has no resurrection",
    "the trouble is, you think you have time",
    "time is what we want most, but what we use worst",
    "wasting your time is the subtlest form of suicide"
];

$(document).ready(function(){

    var backgroundPage = chrome.extension.getBackgroundPage();
    while(backgroundPage === null){
      backgroundPage = chrome.extension.getBackgroundPage();
    }

    if(backgroundPage !== null && backgroundPage.isFirstRun) {
        $('.settingsPanel').addClass('is-visible');
        $('.tracksiteInput').addClass('inputEnabled');
        $('.buttonsContainer').append("");
    } else {
        $('.done').remove();
        $('.tracksiteInput').css({"border": "none"});
        $('.tracksiteInput').prop("disabled", true);
        $('.tracksiteInput').addClass('inputDisabled');
        $('.buttonsContainer').append("");
    }

    $('.editBtn').on('click', function(){
        $('.tracksiteInput').prop("disabled", false);
        $('.tracksiteInput').addClass("inputEnabled");
        $('.editBtn').remove();
        $('.buttonsContainer').append("");
    });

    // Try to update the data from the localStorage if we can about the sites that are being tracked
    if(chrome.extension.getBackgroundPage().isFirstRun){
        chrome.storage.local.get("trackData", function(result){
               var sitesBeingTracked = JSON.parse(result.trackData);
               document.getElementById("firstSite").value = sitesBeingTracked[0];
               document.getElementById("secondSite").value = sitesBeingTracked[1];
               document.getElementById("thirdSite").value = sitesBeingTracked[2];
               document.getElementById("fourthSite").value = (sitesBeingTracked[3] === undefined) ? "" : sitesBeingTracked[3];
               document.getElementById("fifthSite").value = (sitesBeingTracked[4] === undefined) ? "" : sitesBeingTracked[4];
        });
    } else {
        chrome.storage.local.get("trackData", function(result){
            var sitesBeingTracked = JSON.parse(result.trackData);
            var inputFieldIds = ["firstSite", "secondSite", "thirdSite", "fourthSite", "fifthSite"];
            var inputIdPos = 0;
            for(var i = 0 ; i < 5 ;i++){
                if(sitesBeingTracked[i] != "") {
                    document.getElementById(inputFieldIds[inputIdPos]).value = sitesBeingTracked[i];
                    inputIdPos++;
                }
            }
        });
    }

    displayFacebookAndTwitterTime();

    // Updates the visible time in real time
    setInterval(function(){
         displayFacebookAndTwitterTime();
     }, 1000);

    // For the settings panel to become visible
    $('.settings').on('click', function(event){
        $('.settingsPanel').addClass('is-visible');
    });

    $('.settingsPanel').on('click', function(event){
        // This function registers click on the side panel
        if($(event.target).is('.done')) {
            $('.settingsPanel').removeClass('is-visible');
            $('.editBtn').remove();

            var firstSiteBeingTracked = document.getElementById("firstSite").value;
            var secondSiteBeingTracked = document.getElementById("secondSite").value;
            var thirdSiteBeingTracked = document.getElementById("thirdSite").value;
            var fourthSiteBeingTracked = document.getElementById("fourthSite").value;
            var fifthSiteBeingTracked = document.getElementById("fifthSite").value;

            // Now whoever of them are not null we will need to push there value into the array
            var sitesBeingTracked = [firstSiteBeingTracked, secondSiteBeingTracked, thirdSiteBeingTracked, fourthSiteBeingTracked, fifthSiteBeingTracked];
            var sitesBeingTrackedStorable = JSON.stringify(sitesBeingTracked);
            chrome.storage.local.set({"trackData" : sitesBeingTrackedStorable}, function(){});
            chrome.extension.getBackgroundPage().isFirstRun = false;
            $('.tracksiteInput').removeClass('inputEnabled');
            $('.tracksiteInput').addClass('inputDisabled');
            $('.tracksiteInput').prop("disabled", true);
            $('.done').remove();
            $('.settingsContainer').append("").on('click', function(){
                $('.tracksiteInput').prop("disabled", false);
                $('.tracksiteInput').addClass("inputEnabled");
                $('.done').remove();
                $('.editBtn').remove();
                $('.settingsContainer').append("");
            });

        }

        if($(event.target).is('.settingsPanel') && !chrome.extension.getBackgroundPage().isFirstRun) {
            $('.settingsPanel').removeClass('is-visible');
        }
    });

    // Reposition the elements on the page
    var windowHeight = $(window).height();
    $(".container").css({
        "height" : windowHeight * 0.36,
        "margin-top" : windowHeight * 0.25
    });

    // Update the page with a random quote on each reload
    if(chrome.extension.getBackgroundPage().totalTimeOnWebsites > 0){
        var randomQuote = timeQuotes[Math.floor(Math.random() * timeQuotes.length)];
        var trackerDisplay = document.getElementById("websites");
        trackerDisplay.innerHTML = randomQuote;
    }else{
        var trackerDisplay = document.getElementById("websites");
        trackerDisplay.innerHTML = "going great!";
    }

    var forLabels = [];
    var forValues = [];
    // Get the data from the chrome local storage thing
    chrome.storage.local.get(null, function(extDatas){
        for(var prop in extDatas){
            if(prop.lastIndexOf("timeData", 0) === 0){
                forLabels.push(prop);
                forValues.push(extDatas[prop]);
            }
        }

        console.log(forValues.toString());

        var barChartData = {
                labels : [].concat(forLabels),
                datasets : [
                    {
                        fillColor : "rgba(220,220,220,0.6)",
                        data : [].concat(forValues)
                    }
                ],

                getNumData : function(){
                    return Number(this.labels.length);
                }
        }

        var chartView = document.getElementById("myChart");
        var ctx = chartView.getContext("2d");
        window.myBar = new Chart(ctx).Bar(barChartData, {
            responsive : false,
            barShowStroke : false,
            scaleShowGridLines : false,
            showScale : false,
            showTooltips :false,
            barValueSpacing  : 13
        });

        var totalWidthBars = barWidth * barChartData.getNumData();
        var totalWidthSpacing = barSpacing * (barChartData.getNumData() - 1);
        var totalWidthChart = totalWidthBars + totalWidthSpacing;
        var left = ($(window).width() - totalWidthChart)/2;

        $("#myChart").css({
            "width": totalWidthChart,
            "height" : "50%",
            "left" : left
        });
    });

});

$(window).resize(function(){
    var totalWidthChart = $("#myChart").width();
    var left = ($(window).width() - totalWidthChart)/2;

    var windowHeight = $(window).height();
    var windowWidth  = $(window).width();

    $("#myChart").css({
        "width": totalWidthChart,
        "height" :  windowHeight * 0.5,
        "left" : left
    });

    $(".container").css({
        "height" : windowHeight * 0.36,
        "margin-top" : windowHeight * 0.25
    });
});

/*
* Function : displayFacebookAndTwitterTime();
* -------------------------------------------
* This function has a little name problem the thing is that this function
* shows the time for facebook twitter and google plus but due to
* evolution over the times the name has stuck
*/
function displayFacebookAndTwitterTime() {
    var backgroundPage = chrome.extension.getBackgroundPage();
    if(backgroundPage != null){
        var totalTimeSpent = chrome.extension.getBackgroundPage().totalTimeOnWebsites;
        var div = document.getElementById("actualTime");
        div.innerHTML = getReadableTime(totalTimeSpent);
        var storageName = "timeData" + chrome.extension.getBackgroundPage().numDaysSinceUTC();
        var dataToBeWritten = {};
        dataToBeWritten[storageName] = totalTimeSpent;
        dataToBeWritten["today"] = chrome.extension.getBackgroundPage().numDaysSinceUTC();
        chrome.storage.local.set(dataToBeWritten, function(){});
    }
}

/*
* Function : getReadableTime();
* Usage : var readableTime = getReadableTime(2000);
* --------------------------------------------------
* This function takes in the number of seconds as arguments and then
* converts those number of seconds into hours and minutes respectively
* and returns a string that holds the proper time in the format of '3 hours 45 minutes and 3 seconds'
*/
function getReadableTime(totalSeconds) {
    var seconds = totalSeconds % 60;
    var minutes = (Math.floor(totalSeconds/60))%60;
    var hours = (Math.floor(totalSeconds/3600));
    var readableTime = '';
    if (hours > 1)
        readableTime += hours + ' hours ';
    else if(hours == 1)
        readableTime += hours + ' hour '
    if (minutes > 1)
        readableTime += minutes + ' minutes and ' ;
    else if(minutes == 1)
        readableTime += minutes + ' minute and '
    if(seconds == 1){
        readableTime += seconds + ' second ';
    }else{
        readableTime += seconds + ' seconds ';
    }
    return readableTime;
}<commit_msg>Fixed few bugs with the buttons showing up at wrong positions<commit_after>// Stores the width of each bar in pixels
var barWidth = 15;
// Stores the spacing between each line bar in pixels
var barSpacing = 10;

// Quotes about wastage of time
var timeQuotes = ["when you kill time, remember that it has no resurrection",
    "the trouble is, you think you have time",
    "time is what we want most, but what we use worst",
    "wasting your time is the subtlest form of suicide"
];

$(document).ready(function(){

    var backgroundPage = chrome.extension.getBackgroundPage();
    while(backgroundPage === null){
      backgroundPage = chrome.extension.getBackgroundPage();
    }

    if(backgroundPage !== null && backgroundPage.isFirstRun) {
        $('.settingsPanel').addClass('is-visible');
        $('.tracksiteInput').addClass('inputEnabled');
        $('.buttonsContainer').append("");
    } else {
        $('.done').remove();
        $('.tracksiteInput').css({"border": "none"});
        $('.tracksiteInput').prop("disabled", true);
        $('.tracksiteInput').addClass('inputDisabled');
        $('.buttonsContainer').append("");
    }

    $('.editBtn').on('click', function(){
        $('.tracksiteInput').prop("disabled", false);
        $('.tracksiteInput').addClass("inputEnabled");
        $('.editBtn').remove();
        $('.buttonsContainer').append("");
    });

    // Try to update the data from the localStorage if we can about the sites that are being tracked
    if(chrome.extension.getBackgroundPage().isFirstRun){
        chrome.storage.local.get("trackData", function(result){
               var sitesBeingTracked = JSON.parse(result.trackData);
               document.getElementById("firstSite").value = sitesBeingTracked[0];
               document.getElementById("secondSite").value = sitesBeingTracked[1];
               document.getElementById("thirdSite").value = sitesBeingTracked[2];
               document.getElementById("fourthSite").value = (sitesBeingTracked[3] === undefined) ? "" : sitesBeingTracked[3];
               document.getElementById("fifthSite").value = (sitesBeingTracked[4] === undefined) ? "" : sitesBeingTracked[4];
        });
    } else {
        chrome.storage.local.get("trackData", function(result){
            var sitesBeingTracked = JSON.parse(result.trackData);
            var inputFieldIds = ["firstSite", "secondSite", "thirdSite", "fourthSite", "fifthSite"];
            var inputIdPos = 0;
            for(var i = 0 ; i < 5 ;i++){
                if(sitesBeingTracked[i] != "") {
                    document.getElementById(inputFieldIds[inputIdPos]).value = sitesBeingTracked[i];
                    inputIdPos++;
                }
            }
        });
    }

    displayFacebookAndTwitterTime();

    // Updates the visible time in real time
    setInterval(function(){
         displayFacebookAndTwitterTime();
     }, 1000);

    // For the settings panel to become visible
    $('.settings').on('click', function(event){
        $('.settingsPanel').addClass('is-visible');
    });

    $('.settingsPanel').on('click', function(event){
        // This function registers click on the side panel
        if($(event.target).is('.done')) {
            $('.settingsPanel').removeClass('is-visible');
            $('.editBtn').remove();

            var firstSiteBeingTracked = document.getElementById("firstSite").value;
            var secondSiteBeingTracked = document.getElementById("secondSite").value;
            var thirdSiteBeingTracked = document.getElementById("thirdSite").value;
            var fourthSiteBeingTracked = document.getElementById("fourthSite").value;
            var fifthSiteBeingTracked = document.getElementById("fifthSite").value;

            // Now whoever of them are not null we will need to push there value into the array
            var sitesBeingTracked = [firstSiteBeingTracked, secondSiteBeingTracked, thirdSiteBeingTracked, fourthSiteBeingTracked, fifthSiteBeingTracked];
            var sitesBeingTrackedStorable = JSON.stringify(sitesBeingTracked);
            chrome.storage.local.set({"trackData" : sitesBeingTrackedStorable}, function(){});
            chrome.extension.getBackgroundPage().isFirstRun = false;
            $('.tracksiteInput').removeClass('inputEnabled');
            $('.tracksiteInput').addClass('inputDisabled');
            $('.tracksiteInput').prop("disabled", true);
            $('.done').remove();
            $('.lockBtn').remove();
            $('.buttonsContainer').append("").on('click', function(){
                $('.tracksiteInput').prop("disabled", false);
                $('.tracksiteInput').addClass("inputEnabled");
                $('.done').remove();
                $('.editBtn').remove();
                $('.buttonsContainer').append("");
            });

        }

        if($(event.target).is('.settingsPanel') && !chrome.extension.getBackgroundPage().isFirstRun) {
            $('.settingsPanel').removeClass('is-visible');
        }
    });

    // Reposition the elements on the page
    var windowHeight = $(window).height();
    $(".container").css({
        "height" : windowHeight * 0.36,
        "margin-top" : windowHeight * 0.25
    });

    // Update the page with a random quote on each reload
    if(chrome.extension.getBackgroundPage().totalTimeOnWebsites > 0){
        var randomQuote = timeQuotes[Math.floor(Math.random() * timeQuotes.length)];
        var trackerDisplay = document.getElementById("websites");
        trackerDisplay.innerHTML = randomQuote;
    }else{
        var trackerDisplay = document.getElementById("websites");
        trackerDisplay.innerHTML = "going great!";
    }

    var forLabels = [];
    var forValues = [];
    // Get the data from the chrome local storage thing
    chrome.storage.local.get(null, function(extDatas){
        for(var prop in extDatas){
            if(prop.lastIndexOf("timeData", 0) === 0){
                forLabels.push(prop);
                forValues.push(extDatas[prop]);
            }
        }

        console.log(forValues.toString());

        var barChartData = {
                labels : [].concat(forLabels),
                datasets : [
                    {
                        fillColor : "rgba(220,220,220,0.6)",
                        data : [].concat(forValues)
                    }
                ],

                getNumData : function(){
                    return Number(this.labels.length);
                }
        }

        var chartView = document.getElementById("myChart");
        var ctx = chartView.getContext("2d");
        window.myBar = new Chart(ctx).Bar(barChartData, {
            responsive : false,
            barShowStroke : false,
            scaleShowGridLines : false,
            showScale : false,
            showTooltips :false,
            barValueSpacing  : 13
        });

        var totalWidthBars = barWidth * barChartData.getNumData();
        var totalWidthSpacing = barSpacing * (barChartData.getNumData() - 1);
        var totalWidthChart = totalWidthBars + totalWidthSpacing;
        var left = ($(window).width() - totalWidthChart)/2;

        $("#myChart").css({
            "width": totalWidthChart,
            "height" : "50%",
            "left" : left
        });
    });

});

$(window).resize(function(){
    var totalWidthChart = $("#myChart").width();
    var left = ($(window).width() - totalWidthChart)/2;

    var windowHeight = $(window).height();
    var windowWidth  = $(window).width();

    $("#myChart").css({
        "width": totalWidthChart,
        "height" :  windowHeight * 0.5,
        "left" : left
    });

    $(".container").css({
        "height" : windowHeight * 0.36,
        "margin-top" : windowHeight * 0.25
    });
});

/*
* Function : displayFacebookAndTwitterTime();
* -------------------------------------------
* This function has a little name problem the thing is that this function
* shows the time for facebook twitter and google plus but due to
* evolution over the times the name has stuck
*/
function displayFacebookAndTwitterTime() {
    var backgroundPage = chrome.extension.getBackgroundPage();
    if(backgroundPage != null){
        var totalTimeSpent = chrome.extension.getBackgroundPage().totalTimeOnWebsites;
        var div = document.getElementById("actualTime");
        div.innerHTML = getReadableTime(totalTimeSpent);
        var storageName = "timeData" + chrome.extension.getBackgroundPage().numDaysSinceUTC();
        var dataToBeWritten = {};
        dataToBeWritten[storageName] = totalTimeSpent;
        dataToBeWritten["today"] = chrome.extension.getBackgroundPage().numDaysSinceUTC();
        chrome.storage.local.set(dataToBeWritten, function(){});
    }
}

/*
* Function : getReadableTime();
* Usage : var readableTime = getReadableTime(2000);
* --------------------------------------------------
* This function takes in the number of seconds as arguments and then
* converts those number of seconds into hours and minutes respectively
* and returns a string that holds the proper time in the format of '3 hours 45 minutes and 3 seconds'
*/
function getReadableTime(totalSeconds) {
    var seconds = totalSeconds % 60;
    var minutes = (Math.floor(totalSeconds/60))%60;
    var hours = (Math.floor(totalSeconds/3600));
    var readableTime = '';
    if (hours > 1)
        readableTime += hours + ' hours ';
    else if(hours == 1)
        readableTime += hours + ' hour '
    if (minutes > 1)
        readableTime += minutes + ' minutes and ' ;
    else if(minutes == 1)
        readableTime += minutes + ' minute and '
    if(seconds == 1){
        readableTime += seconds + ' second ';
    }else{
        readableTime += seconds + ' seconds ';
    }
    return readableTime;
}<|endoftext|>