<commit_before>var fs = require("fs");
var http = require("http");
var os = require("os");

var ServerEnvironment = {
	address : "128.0.0.1",
	httpport : 8080,
	websocketport : 8000,
	init : function() {
	   	address = this.getIpAddress();

		console.log("address : " + address);

		// Implement String Object's replaceAll
		String.prototype.format = function() {
			var index = 0;
			var string = (typeof(this) == "function" && !(index++))? arguments[0]:this;
			for (; index < arguments.length; index++)
				string = string.replace(/\{\d+?\}/, arguments[index]);
			return string;
		}
	},
	getIpAddress : function() {
		// Get My IP Address
		var interfaces = os.networkInterfaces();
		for (name in interfaces) {
			for (ip in interfaces[name]) {
				var address = interfaces[name][ip];
				if (address.family == "IPv4" && !address.internal) {
					return this.address = address.address;
				}
			}
		}
	}
}

ServerEnvironment.init();

http.createServer(function(req, res) {
	fs.readFile('websocket_client.html', function(err, data) {
		var htmlString = data.toString();
		res.writeHead(200, {'Content-Type' : 'text/html'});
		res.end(htmlString.format(ServerEnvironment.address));
	});
}).listen(ServerEnvironment.httpport, function() {
	console.log("Server running (" + ServerEnvironment.address + ":" + ServerEnvironment.httpport + ")");
});

var WebSocketServer = require('websocket').server;
var server = http.createServer(function(request, response) {
    console.log((new Date()) + ' Received request for ' + request.url);
    response.writeHead(404);
    response.end();
});
server.listen(ServerEnvironment.websocketport, function() {
    console.log((new Date()) + ' Server is listening on (' + ServerEnvironment.address + ":" + ServerEnvironment.websocketport + ")");
});

wsServer = new WebSocketServer({
    httpServer: server,
    // You should not use autoAcceptConnections for production
    // applications, as it defeats all standard cross-origin protection
    // facilities built into the protocol and the browser.  You should
    // *always* verify the connection's origin and decide whether or not
    // to accept it.
    autoAcceptConnections: false
});

function originIsAllowed(origin) {
  // put logic here to detect whether the specified origin is allowed.
  return true;
}

wsServer.on('request', function(request) {
    if (!originIsAllowed(request.origin)) {
      // Make sure we only accept requests from an allowed origin
      request.reject();
      console.log((new Date()) + ' Connection from origin ' + request.origin + ' rejected.');
      return;
    }

    var connection = request.accept('echo-protocol', request.origin);
    console.log((new Date()) + ' Connection accepted.');

		connection.on('message', function(message) {
        if (message.type === 'utf8') {
            console.log('Received Message: ' + message.utf8Data);
            connection.sendUTF(message.utf8Data);
			var connections = wsServer.connections;
			for (var index = 0; index < connections.length; index++) {
				if (connection != connections[index]) {
					connections[index].sendUTF(message.utf8Data);
				}
			}
        }
        else if (message.type === 'binary') {
            console.log('Received Binary Message of ' + message.binaryData.length + ' bytes');
            connection.sendBytes(message.binaryData);
        }
    });

    connection.on('close', function(reasonCode, description) {
        console.log((new Date()) + ' Peer ' + connection.remoteAddress + ' disconnected.');
    });
});
<commit_msg>adopted module js files<commit_after>var fs = require("fs");
var http = require("http");
var websocket = require("websocket");
var env = require("./module/environment");

env.init();

http.createServer(function(req, res) {
	fs.readFile('websocket_client.html', function(err, data) {
		var htmlString = data.toString();
		res.writeHead(200, {'Content-Type' : 'text/html'});
		res.end(htmlString.format(env.getIpAddress()));
	});
}).listen(env.getHttpPort(), function() {
	console.log("Server running (" + env.getIpAddress() + ":" + env.getHttpPort() +")");
});

var WebSocketServer = websocket.server;
var server = http.createServer(function(request, response) {
    console.log((new Date()) + ' Received request for ' + request.url);
    response.writeHead(404);
    response.end();
});
server.listen(env.getSockPort(), function() {
    console.log((new Date()) + ' Server is listening on (' + env.getIpAddress() + ":" + env.getSockPort() + ")");
});

wsServer = new WebSocketServer({
    httpServer: server,
    // You should not use autoAcceptConnections for production
    // applications, as it defeats all standard cross-origin protection
    // facilities built into the protocol and the browser.  You should
    // *always* verify the connection's origin and decide whether or not
    // to accept it.
    autoAcceptConnections: false
});

function originIsAllowed(origin) {
  // put logic here to detect whether the specified origin is allowed.
  return true;
}

wsServer.on('request', function(request) {
    if (!originIsAllowed(request.origin)) {
      // Make sure we only accept requests from an allowed origin
      request.reject();
      console.log((new Date()) + ' Connection from origin ' + request.origin + ' rejected.');
      return;
    }

    var connection = request.accept('echo-protocol', request.origin);
    console.log((new Date()) + ' Connection accepted.');

		connection.on('message', function(message) {
        if (message.type === 'utf8') {
            console.log('Received Message: ' + message.utf8Data);
            connection.sendUTF(message.utf8Data);
			var connections = wsServer.connections;
			for (var index = 0; index < connections.length; index++) {
				if (connection != connections[index]) {
					connections[index].sendUTF(message.utf8Data);
				}
			}
        }
        else if (message.type === 'binary') {
            console.log('Received Binary Message of ' + message.binaryData.length + ' bytes');
            connection.sendBytes(message.binaryData);
        }
    });

    connection.on('close', function(reasonCode, description) {
        console.log((new Date()) + ' Peer ' + connection.remoteAddress + ' disconnected.');
    });
});
<|endoftext|>


<commit_before>/*    Copyright 2020 Firewalla INC
 *
 *    This program is free software: you can redistribute it and/or  modify
 *    it under the terms of the GNU Affero General Public License, version 3,
 *    as published by the Free Software Foundation.
 *
 *    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/>.
 */

 /*
  * Box (collect the following info)
  *   box states: just rebooted, this process crashed and connect, reconnected the socket io, scheduled update
  *   memory size
  *   mac addresses of ethX
  *   speed of each ethX
  *   Bluetooth mac address
  *   uptime
  *   uname -m
  *   box eid (if have)
  *   box license (8 char prefix only)
  *   gateway mac address (the first three bytes)
  *   cpu temp
  *   current timestamp
  *   hash of firerouter (if applicable)
  *   hash of firewalla
  */

'use strict';

const exec = require('child-process-promise').exec;
const fs = require('fs');
const io2 = require('socket.io-client');
const os = require('os');
const socket = io2(
  "https://api.firewalla.com",
  { path: "/socket",
    transports: ['websocket'],
    'upgrade': false }
);
const Promise = require('bluebird');
Promise.promisifyAll(fs);

function log(message) {
  console.log(new Date(), message);
}

async function getShellOutput(cmd) {
  try {
    const result = await exec(cmd, { encoding: 'utf8' });
    return result && result.stdout && result.stdout.replace(/\n$/,'');
  } catch(err) {
    log("ERROR: "+err);
    return "";
  }
}

async function isBooted() {
  const fwHeartbeatFile = '/dev/shm/fw_heartbeat';
  try{
    await fs.accessAsync(fwHeartbeatFile, fs.constants.F_OK);
    return false;
  } catch (err) {
    log("System was booted.");
    await exec(`touch ${fwHeartbeatFile}`);
    return true;
  }
}

async function getCpuTemperature() {
  return await getShellOutput("cat /sys/class/thermal/thermal_zone0/temp");
}

function getEthernets() {
    const ifs = os.networkInterfaces();
    const eths = {};
    const ethsNames = Object.keys(ifs).filter(name => name.match(/^eth/));
    ethsNames.forEach(e => eths[e]=ifs[e]);
    return eths;
}

async function getEthernetSpeed(ethsNames) {
    const ethSpeed = {};
    for (const eth of ethsNames) {
      ethSpeed[eth] = await getShellOutput(`sudo ethtool ${eth} | awk '/Speed:/ {print $2}'`);
    }
    return ethSpeed;
}

async function getLatestCommitHash(cwd) {
  try {
    const result = await exec("git rev-parse HEAD", { cwd: cwd, encoding: 'utf8' });
    return result && result.stdout && result.stdout.trim();
  } catch(err) {
    log(`ERROR: failed to get latest commit hash in ${cwd}`+err);
    return '';
  }
}

async function getLicenseInfo() {
  const licenseFile = "/home/pi/.firewalla/license";
  const SUUID = (await getShellOutput(`awk '/SUUID/ {print $NF}' ${licenseFile}`)).replace(/[",]/g,'');
  const EID = (await getShellOutput(`awk '/EID/ {print $NF}' ${licenseFile}`)).replace(/[",]/g,'');
  return { SUUID,EID };
}

async function getSysinfo(status) {
  const eths = getEthernets();
  const memory = os.totalmem()
  const timestamp = Date.now();
  const uptime = os.uptime();
  const [arch, booted, btmac, cpuTemp, ethSpeed, hashRouter, hashWalla, licenseInfo, mac] =
    await Promise.all([
      getShellOutput("uname -m"),
      isBooted(),
      getShellOutput("hcitool dev | awk '/hci0/ {print $2}'"),
      getCpuTemperature(),
      getEthernetSpeed(Object.keys(eths)),
      getLatestCommitHash("/home/pi/firerouter"),
      getLatestCommitHash("/home/pi/firewalla"),
      getLicenseInfo(),
      getShellOutput("cat /sys/class/net/eth0/address")
    ]);
  return {
    arch,
    booted,
    btmac,
    cpuTemp,
    eths,
    ethSpeed,
    licenseInfo,
    hashRouter,
    hashWalla,
    mac,
    memory,
    status,
    timestamp,
    uptime
  };
}

async function update(status) {
  const info = await getSysinfo(status);
  log(`DEBUG: ${JSON.stringify(info,null,2)}`);
  socket.emit('update', info);
}

const job = setTimeout(() => {
  update("schedule");
}, 30 * 3600 * 1000);

socket.on('connect', () => {
  log("Connected to heartbeat server.");
  update('connect');
});

socket.on('disconnect', () => {
  log("Disconnected from heartbeat server.");
});

socket.on("update", (data) => {
  update("cloud");
});

socket.on('reconnect', () => {
  log("Reconnected to heartbeat server.");
  update('reconnect');
});
<commit_msg>turn off debug log<commit_after>/*    Copyright 2020 Firewalla INC
 *
 *    This program is free software: you can redistribute it and/or  modify
 *    it under the terms of the GNU Affero General Public License, version 3,
 *    as published by the Free Software Foundation.
 *
 *    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/>.
 */

 /*
  * Box (collect the following info)
  *   box states: just rebooted, this process crashed and connect, reconnected the socket io, scheduled update
  *   memory size
  *   mac addresses of ethX
  *   speed of each ethX
  *   Bluetooth mac address
  *   uptime
  *   uname -m
  *   box eid (if have)
  *   box license (8 char prefix only)
  *   gateway mac address (the first three bytes)
  *   cpu temp
  *   current timestamp
  *   hash of firerouter (if applicable)
  *   hash of firewalla
  */

'use strict';

const exec = require('child-process-promise').exec;
const fs = require('fs');
const io2 = require('socket.io-client');
const os = require('os');
const socket = io2(
  "https://api.firewalla.com",
  { path: "/socket",
    transports: ['websocket'],
    'upgrade': false }
);
const Promise = require('bluebird');
Promise.promisifyAll(fs);

function log(message) {
  console.log(new Date(), message);
}

async function getShellOutput(cmd) {
  try {
    const result = await exec(cmd, { encoding: 'utf8' });
    return result && result.stdout && result.stdout.replace(/\n$/,'');
  } catch(err) {
    log("ERROR: "+err);
    return "";
  }
}

async function isBooted() {
  const fwHeartbeatFile = '/dev/shm/fw_heartbeat';
  try{
    await fs.accessAsync(fwHeartbeatFile, fs.constants.F_OK);
    return false;
  } catch (err) {
    log("System was booted.");
    await exec(`touch ${fwHeartbeatFile}`);
    return true;
  }
}

async function getCpuTemperature() {
  return await getShellOutput("cat /sys/class/thermal/thermal_zone0/temp");
}

function getEthernets() {
    const ifs = os.networkInterfaces();
    const eths = {};
    const ethsNames = Object.keys(ifs).filter(name => name.match(/^eth/));
    ethsNames.forEach(e => eths[e]=ifs[e]);
    return eths;
}

async function getEthernetSpeed(ethsNames) {
    const ethSpeed = {};
    for (const eth of ethsNames) {
      ethSpeed[eth] = await getShellOutput(`sudo ethtool ${eth} | awk '/Speed:/ {print $2}'`);
    }
    return ethSpeed;
}

async function getLatestCommitHash(cwd) {
  try {
    const result = await exec("git rev-parse HEAD", { cwd: cwd, encoding: 'utf8' });
    return result && result.stdout && result.stdout.trim();
  } catch(err) {
    log(`ERROR: failed to get latest commit hash in ${cwd}`+err);
    return '';
  }
}

async function getLicenseInfo() {
  const licenseFile = "/home/pi/.firewalla/license";
  const SUUID = (await getShellOutput(`awk '/SUUID/ {print $NF}' ${licenseFile}`)).replace(/[",]/g,'');
  const EID = (await getShellOutput(`awk '/EID/ {print $NF}' ${licenseFile}`)).replace(/[",]/g,'');
  return { SUUID,EID };
}

async function getSysinfo(status) {
  const eths = getEthernets();
  const memory = os.totalmem()
  const timestamp = Date.now();
  const uptime = os.uptime();
  const [arch, booted, btmac, cpuTemp, ethSpeed, hashRouter, hashWalla, licenseInfo, mac] =
    await Promise.all([
      getShellOutput("uname -m"),
      isBooted(),
      getShellOutput("hcitool dev | awk '/hci0/ {print $2}'"),
      getCpuTemperature(),
      getEthernetSpeed(Object.keys(eths)),
      getLatestCommitHash("/home/pi/firerouter"),
      getLatestCommitHash("/home/pi/firewalla"),
      getLicenseInfo(),
      getShellOutput("cat /sys/class/net/eth0/address")
    ]);
  return {
    arch,
    booted,
    btmac,
    cpuTemp,
    eths,
    ethSpeed,
    licenseInfo,
    hashRouter,
    hashWalla,
    mac,
    memory,
    status,
    timestamp,
    uptime
  };
}

async function update(status) {
  const info = await getSysinfo(status);
  //log(`DEBUG: ${JSON.stringify(info,null,2)}`);
  socket.emit('update', info);
}

const job = setTimeout(() => {
  update("schedule");
}, 30 * 3600 * 1000);

socket.on('connect', () => {
  log("Connected to heartbeat server.");
  update('connect');
});

socket.on('disconnect', () => {
  log("Disconnected from heartbeat server.");
});

socket.on("update", (data) => {
  update("cloud");
});

socket.on('reconnect', () => {
  log("Reconnected to heartbeat server.");
  update('reconnect');
});
<|endoftext|>


<commit_before>import React from 'react'
import { connect } from 'dva'
import styles from './MyCollection.css'

class MyCollection extends React.Component {
  render() {
    return (

collection

    )
  }
}

function mapStateToProps(state) {
  const store = state['list-store']
  const loading = state.loading.effects
  return {
    store,
    globalLoading: loading['collection/fetchCollectionList'],
    partLoading: loading['collection/toggleLike']
  }
}

export default connect(mapStateToProps)(MyCollection)
<commit_msg>test -mac<commit_after>import React from 'react'
import { connect } from 'dva'
import styles from './MyCollection.css'

class MyCollection extends React.Component {
  render() {
    return (

collection page

    )
  }
}

function mapStateToProps(state) {
  const store = state['list-store']
  const loading = state.loading.effects
  return {
    store,
    globalLoading: loading['collection/fetchCollectionList'],
    partLoading: loading['collection/toggleLike']
  }
}

export default connect(mapStateToProps)(MyCollection)
<|endoftext|>


<commit_before>/* eslint-disable react/forbid-prop-types */
/**
 * mSupply Mobile
 * Sustainable Solutions (NZ) Ltd. 2019
 */

import React from 'react';
import { TouchableOpacity as TouchableHighlight, StyleSheet, View, Text } from 'react-native';
import PropTypes from 'prop-types';

import globalStyles, { GREY } from '../globalStyles/index';

const ICON_SIZES = {
  small: 10,
  medium: 15,
  large: 20,
  xlarge: 30,
};

/**
 * Simple component rendering a button with an icon, and option text label on the right side
 *
 * @prop {Node} IconComponent An icon component to render in the center of the circle.
 * @prop {Func} onPress OnPress callback.
 * @prop {Func} onPressIn onPressIn callback.
 * @prop {Func} onPressOut  onPressOut callback.
 * @prop {Boolean} containerStyle  When true, no action on press. Disabled styling too.
 * @prop {Boolean} isDisabled  When true, no action on press. Disabled styling too.
 * @prop {String} color  Color for the icon component
 * @prop {String} size  Use size preset. "small", "medium", "large" or xlarge.
 * @prop {String} label Button label text to right of icon
 */
export const IconButton = ({
  IconComponent,
  onPress,
  onPressIn,
  onPressOut,
  containerStyle,
  isDisabled,
  color,
  size,
  label,
}) => {
  const labelStyle = [localStyles.label, globalStyles.authWindowButtonText];
  const buttonContainerStyle = [localStyles.buttonContainer, containerStyle];
  const Container = isDisabled ? View : TouchableHighlight;
  const iconSize = ICON_SIZES[size];

  return (
    <Container
      onPressIn={onPressIn}
      onPressOut={onPressOut}
      onPress={onPress}
      style={buttonContainerStyle}
    >
      <IconComponent color={color} size={iconSize} />
      {label && <Text style={labelStyle}>{label}</Text>}
    </Container>
  );
};

IconButton.defaultProps = {
  onPress: null,
  onPressIn: null,
  onPressOut: null,
  containerStyle: null,
  isDisabled: false,
  color: GREY,
  size: 'large',
  label: null,
};

IconButton.propTypes = {
  IconComponent: PropTypes.oneOfType([PropTypes.object, PropTypes.func]).isRequired,
  onPress: PropTypes.func,
  onPressIn: PropTypes.func,
  onPressOut: PropTypes.func,
  containerStyle: PropTypes.any,
  isDisabled: PropTypes.bool,
  color: PropTypes.string,
  size: PropTypes.string,
  label: PropTypes.string,
};

const localStyles = StyleSheet.create({
  label: {
    paddingHorizontal: 5,
  },
  buttonContainer: {
    flexDirection: 'row',
    alignItems: 'center',
  },
});
<commit_msg>containerStyle proptype is object<commit_after>/* eslint-disable react/forbid-prop-types */
/**
 * mSupply Mobile
 * Sustainable Solutions (NZ) Ltd. 2019
 */

import React from 'react';
import { TouchableOpacity as TouchableHighlight, StyleSheet, View, Text } from 'react-native';
import PropTypes from 'prop-types';

import globalStyles, { GREY } from '../globalStyles/index';

const ICON_SIZES = {
  small: 10,
  medium: 15,
  large: 20,
  xlarge: 30,
};

/**
 * Simple component rendering a button with an icon, and option text label on the right side
 *
 * @prop {Node} IconComponent An icon component to render in the center of the circle.
 * @prop {Func} onPress OnPress callback.
 * @prop {Func} onPressIn onPressIn callback.
 * @prop {Func} onPressOut  onPressOut callback.
 * @prop {Boolean} containerStyle  When true, no action on press. Disabled styling too.
 * @prop {Boolean} isDisabled  When true, no action on press. Disabled styling too.
 * @prop {String} color  Color for the icon component
 * @prop {String} size  Use size preset. "small", "medium", "large" or xlarge.
 * @prop {String} label Button label text to right of icon
 */
export const IconButton = ({
  IconComponent,
  onPress,
  onPressIn,
  onPressOut,
  containerStyle,
  isDisabled,
  color,
  size,
  label,
}) => {
  const labelStyle = [localStyles.label, globalStyles.authWindowButtonText];
  const buttonContainerStyle = [localStyles.buttonContainer, containerStyle];
  const Container = isDisabled ? View : TouchableHighlight;
  const iconSize = ICON_SIZES[size];

  return (
    <Container
      onPressIn={onPressIn}
      onPressOut={onPressOut}
      onPress={onPress}
      style={buttonContainerStyle}
    >
      <IconComponent color={color} size={iconSize} />
      {label && <Text style={labelStyle}>{label}</Text>}
    </Container>
  );
};

IconButton.defaultProps = {
  onPress: null,
  onPressIn: null,
  onPressOut: null,
  containerStyle: null,
  isDisabled: false,
  color: GREY,
  size: 'large',
  label: null,
};

IconButton.propTypes = {
  IconComponent: PropTypes.oneOfType([PropTypes.object, PropTypes.func]).isRequired,
  onPress: PropTypes.func,
  onPressIn: PropTypes.func,
  onPressOut: PropTypes.func,
  containerStyle: PropTypes.object,
  isDisabled: PropTypes.bool,
  color: PropTypes.string,
  size: PropTypes.string,
  label: PropTypes.string,
};

const localStyles = StyleSheet.create({
  label: {
    paddingHorizontal: 5,
  },
  buttonContainer: {
    flexDirection: 'row',
    alignItems: 'center',
  },
});
<|endoftext|>


<commit_before>#!/usr/bin/env node
'use strict';

const _ = require('lodash');
const path = require('path');
const util = require('util');
const lmdb = require('../node-lmdb');
const Filters = require('../lib/filters.js');

// Find base directory for consistency
const basedir = path.resolve(__dirname, '..');

// Config
const appcfg = _.defaultsDeep(
	{},
	require('../cfg/user.json'),
	require('../cfg/config.json')
);

// Filter setup
const filters = new Filters(appcfg);

// LMDB
var dbe = new lmdb.Env();
dbe.open({
	path: path.isAbsolute(appcfg.dbpath) ? appcfg.dbpath : path.resolve(basedir, appcfg.dbpath),
	mapSize: 1 * 1024 * 1024 * 1024,	// 1 GiB
	maxDbs: 10
});
const dbs = {};
const names = ['status', 'users', 'screennames', 'tweets', 'userdates', 'otherdates', 'favids', 'favdates', 'urls', 'media'];
for (let name of names) {
	dbs[name] = dbe.openDbi({name, create: true});
}

var txn, cur, key, val, acc, writer, prefix = '';

// TEMP
// Print db stats to console
txn = dbe.beginTxn({readOnly: true});
for (let db of names) {
	// console.log(`\nDB stats for ${db}:`);
	// console.dir(dbs[db].stat(txn));
	process.stderr.write(`\nDB stats for ${db}:\n`);
	process.stderr.write(util.inspect(dbs[db].stat(txn), {colors:true}) + '\n');
}
txn.commit();

// Output leading '['
process.stdout.write('[\n');
// TODO: output leading log summary

// Output status
txn = dbe.beginTxn({readOnly: true});
cur = new lmdb.Cursor(txn, dbs.status);

acc = {};
writer = (k, v) => _.set(acc, k, JSON.parse(v.toString()));

for (key = cur.goToFirst(); key; key = cur.goToNext()) {
	cur.getCurrentBinaryUnsafe(writer);
}

writefn('status_raw', acc);

cur.close();
txn.commit();

// Output users
txn = dbe.beginTxn({readOnly: true});
cur = new lmdb.Cursor(txn, dbs.users);

writer = (k, v) => writefn('user', JSON.parse(v.toString()));

for (key = cur.goToFirst(); key; key = cur.goToNext()) {
	cur.getCurrentBinaryUnsafe(writer);
}

cur.close();
txn.commit();

// Output tweets
txn = dbe.beginTxn({readOnly: true});
cur = new lmdb.Cursor(txn, dbs.tweets);

writer = (k, v) => {
	let t = JSON.parse(v.toString());
	if (t.deleted) {
		// Convert from stored format to broadcast format
		writefn('delete', {
			id_str: t.id_str,
			user_id_str: t.user.id_str,
			time: t.deleted
		});
	}
	else {
		writefn(filters.user(t.user) ? 'user_tweet' : 'other_tweet', t);
	}
};

for (key = cur.goToFirst(); key; key = cur.goToNext()) {
	cur.getCurrentBinaryUnsafe(writer);
}

cur.close();
txn.commit();

// Output favorites
txn = dbe.beginTxn({readOnly: true});
cur = new lmdb.Cursor(txn, dbs.favids);

writer = (k, v) => writefn('favorite', {id_str: k, time: parseInt(v)});

for (key = cur.goToFirst(); key; key = cur.goToNext()) {
	cur.getCurrentString(writer);
}

cur.close();
txn.commit();

// Output indices
writeindex(dbs.screennames, 'user_index');
writeindex(dbs.userdates, 'user_tweet_index');
writeindex(dbs.otherdates, 'other_tweet_index');
writeindex(dbs.favdates, 'favorite_index');

// Output trailing ']'
process.stdout.write('\n]\n');

// Close dbs
for (let name of names) {
	dbs[name].close();
}
dbe.close();

function writefn (type, data) {
	process.stdout.write(prefix + JSON.stringify({type, data}, null, 2));
	if (!prefix) {
		prefix = ',\n';
	}
}

function writeindex (db, type) {
	txn = dbe.beginTxn({readOnly: true});
	cur = new lmdb.Cursor(txn, db);

	key = cur.goToFirst();
	if (key !== null) {
		cur.getCurrentString((k, v) => {
			if (!v.startsWith('[')) {
				v = `"${v}"`;
			}
			acc = prefix + `{\n  "type": "${type}",\n  "data": {\n    "${k}": ${v}`;
		});

		while (cur.goToNext()) {
			cur.getCurrentString((k, v) => {
				if (!v.startsWith('[')) {
					v = `"${v}"`;
				}
				acc += `,\n    "${k}": ${v}`;
			});
		}

		acc += `\n  }\n}`;
		process.stdout.write(acc);
	}

	cur.close();
	txn.commit();
}
<commit_msg>Updated db-dump.js to use DBReader and dump reference index<commit_after>#!/usr/bin/env node
'use strict';

const _ = require('lodash');
const path = require('path');
const util = require('util');
const lmdb = require('../node-lmdb');
const Filters = require('../lib/filters.js');
const DBReader = require('../lib/dbread.js');

// Find base directory for consistency
const basedir = path.resolve(__dirname, '..');

// Config
const appcfg = _.defaultsDeep(
	{},
	require('../cfg/user.json'),
	require('../cfg/config.json')
);

// Filter setup
const filters = new Filters(appcfg);

// LMDB
var dbr = new DBReader({
	path: path.isAbsolute(appcfg.dbpath) ? appcfg.dbpath : path.resolve(basedir, appcfg.dbpath),
	user_id_str: appcfg.user.id_str
});

var txn, cur, key, val, acc, writer, prefix = '';

// TEMP
// Print db stats to console
txn = dbr.begin();
for (let name of DBReader.dbnamelist()) {
	process.stderr.write(`\nDB stats for ${name}:\n`);
	process.stderr.write(util.inspect(dbr.dbs[name].stat(txn), {colors:true}) + '\n');
}
txn.commit();

// Output leading '['
process.stdout.write('[\n');
// TODO: output leading log summary

// Output status
txn = dbr.begin();
cur = new lmdb.Cursor(txn, dbr.dbs.status);

acc = {};
writer = (k, v) => _.set(acc, k, JSON.parse(v.toString()));

for (key = cur.goToFirst(); key; key = cur.goToNext()) {
	cur.getCurrentBinaryUnsafe(writer);
}

writefn('status_raw', acc);

cur.close();
txn.commit();

// Output users
txn = dbr.begin();
cur = new lmdb.Cursor(txn, dbr.dbs.users);

writer = (k, v) => writefn('user', JSON.parse(v.toString()));

for (key = cur.goToFirst(); key; key = cur.goToNext()) {
	cur.getCurrentBinaryUnsafe(writer);
}

cur.close();
txn.commit();

// Output tweets
txn = dbr.begin();
cur = new lmdb.Cursor(txn, dbr.dbs.tweets);

writer = (k, v) => {
	let t = JSON.parse(v.toString());
	if (t.deleted) {
		// Convert from stored format to broadcast format
		writefn('delete', {
			id_str: t.id_str,
			user_id_str: t.user.id_str,
			time: t.deleted
		});
	}
	else {
		writefn(filters.user(t.user) ? 'user_tweet' : 'other_tweet', t);
	}
};

for (key = cur.goToFirst(); key; key = cur.goToNext()) {
	cur.getCurrentBinaryUnsafe(writer);
}

cur.close();
txn.commit();

// Output favorites
txn = dbr.begin();
cur = new lmdb.Cursor(txn, dbr.dbs.favids);

writer = (k, v) => writefn('favorite', {id_str: k, time: parseInt(v)});

for (key = cur.goToFirst(); key; key = cur.goToNext()) {
	cur.getCurrentString(writer);
}

cur.close();
txn.commit();

// Output indices
writeindex(dbr.dbs.names, 'user_index');
writeindex(dbr.dbs.userdates, 'user_tweet_index');
writeindex(dbr.dbs.otherdates, 'other_tweet_index');
writeindex(dbr.dbs.favdates, 'favorite_index');
writeindex(dbr.dbs.refs, 'reference_index');

// Output trailing ']'
process.stdout.write('\n]\n');

dbr.close();

function writefn (type, data) {
	process.stdout.write(prefix + JSON.stringify({type, data}, null, 2));
	if (!prefix) {
		prefix = ',\n';
	}
}

function writeindex (db, type) {
	txn = dbr.begin();
	cur = new lmdb.Cursor(txn, db);

	key = cur.goToFirst();
	if (key !== null) {
		cur.getCurrentString((k, v) => {
			if (!v.startsWith('[')) {
				v = `"${v}"`;
			}
			acc = prefix + `{\n  "type": "${type}",\n  "data": {\n    "${k}": ${v}`;
		});

		while (cur.goToNext()) {
			cur.getCurrentString((k, v) => {
				if (!v.startsWith('[')) {
					v = `"${v}"`;
				}
				acc += `,\n    "${k}": ${v}`;
			});
		}

		acc += `\n  }\n}`;
		process.stdout.write(acc);
	}

	cur.close();
	txn.commit();
}
<|endoftext|>


<commit_before>/*jshint debug:true, noarg:true, noempty:true, eqeqeq:true, bitwise:true, undef:true, curly:true, browser: true, devel: true, jquery:true, strict:false */
/*global Backbone, _, jQuery, Sail */

(function() {
  "use strict";
  var Skeletor = this.Skeletor || {};
  this.Skeletor.Mobile = this.Skeletor.Mobile || {};
  var app = this.Skeletor.Mobile;
  app.View = {};

  /**
    CollectView
  **/
  app.View.CollectView = Backbone.View.extend({
    view: this,

    initialize: function() {
      var view = this;
      console.log('Initializing CollectView...', view.el);
    },

    events: {
      'click #new-observation'  : "startNewObservation",
      'click .next-btn'         : "moveForward",
      'click .back-btn'         : "moveBack",
      'click .wiki-link'        : "openModal",
      'click .leaf-fallen-btn'  : "buttonSelected"
    },

    buttonSelected: function(ev) {
      var view = this;

      jQuery('.btn-select').removeClass("btn-select");
      jQuery(ev.target).addClass("btn-select");
    },

    startNewObservation: function() {
      var view = this;

      // delete the old observation
      app.currentObservation = {};
      app.currentObservation.leaves = [];

      jQuery('#title-page').addClass('hidden');
      jQuery('#variable-content-container').removeClass('hidden');
      jQuery('.back-btn').removeClass('hidden');
      jQuery('.next-btn').removeClass('hidden');

      // we're on page '0', the title page - this will move us to page 1
      view.determineTargetPage('next');
    },

    moveForward: function() {
      var view = this;
      view.determineTargetPage('next');
    },

    moveBack: function() {
      var view = this;
      view.determineTargetPage('prev');
    },

    determineTargetPage: function(direction) {
      var view = this;

      // decide on next or previous page, and update the page number to that
      var pageNumber = Number(view.getPageNum());
      if (direction === 'next') {
        pageNumber += 1;
      } else if (direction === 'prev') {
        pageNumber -= 1;
      } else {
        console.error('ERROR: unexpected direction');
      }

      // determine which of the 6 leaf observations we are on
      var leafCycleNum = app.currentObservation.leaves.length + 1;

      /********** PAGE 4 *********/
      if (pageNumber == 4) {
        // if user said leaf has fallen
        var checkedEl = jQuery('.current-page [type="radio"]:checked');
        if (jQuery(checkedEl).is("#id-leaf-fallen-yes")) {
          // update the observation for fallen
          app.currentObservation.leaves[leafCycleNum-1] = { "leaf_num":leafCycleNum, "fallen":"yes" };

          // if this is the last observation, go to page 6. Else go to page 3
          if (leafCycleNum === 6) {
            view.populatePage(6);
          } else {
            view.populatePage(3);
          }

        // if user said leaf has not fallen
        } else if (jQuery(checkedEl).is("#id-leaf-fallen-no")) {
          app.currentObservation.leaves[leafCycleNum-1] = { "leaf_num":leafCycleNum, "fallen":"no" };

          view.populatePage(pageNumber);
        } else {
          jQuery().toastmessage('showErrorToast', "Please select whether this leaf has fallen");
        }

      /********** PAGE 6 *********/
      } else if (pageNumber === 6) {            // special case for leaf cycle pages to loop
        // go to page 3 if the leaves aren't all done (eg array length is 6)
        if (leafCycleNum === 6) {
          view.populatePage(6);
        } else {
          view.populatePage(3);
        }

      /********** ALL OTHER PAGES *********/
      } else {
        view.populatePage(pageNumber);
      }
    },

    updateJSONObject: function() {
      var view = this;

      _.each(jQuery('.current-page .input-field'), function(i) {
        // if this is of type text take the text and put it straight up into the json
        if (i.type === "text" || i.type === "textarea" || i.type === "number") {
          // add text value to json
          app.currentObservation[jQuery(i).data().fieldName] = jQuery(i).val();

        // else if this is of type radio, capture selected
        } else if (i.type === "radio") {
          var el = jQuery('[type="radio"]:checked');
          app.currentObservation[el.data().fieldName] = jQuery(el).val();               // we need a condition here to check if el is null (this can also be used to prompt user to make a selection)
        }

      });
    },

    updateProgressBar: function() {
      // change jpg src or whatever
    },

    removePageClasses: function() {
      jQuery('.leaf-page').addClass('hidden');
      jQuery('.leaf-page').removeClass('current-page');
    },

    clearPageContent: function() {
      jQuery('.current-page .input-field').val('');
      jQuery('.current-page .leaf-fallen').prop('checked', false);
      jQuery('.current-page .btn-select').removeClass('btn-select');
    },

    populatePage: function(pageNumber) {
      var view = this;

      view.updateJSONObject();
      view.updateProgressBar();
      view.removePageClasses();
      view.clearPageContent();

      if (pageNumber === 7) {
        jQuery('.page-title').text('Review Data');
        jQuery('.next-btn').text('Finish');
        app.reviewDataView.render();
      } else {
        jQuery('.page-title').text('New Observation');
        jQuery('.next-btn').text('Next');
      }

      var pageLabel = 'leaf-';
      pageLabel = pageLabel + pageNumber;

      jQuery('#' + pageLabel).removeClass('hidden');
      jQuery('#' + pageLabel).addClass('current-page');
    },

    getPageNum: function() {
      // find the currently shown page
      var pageLabel = jQuery('.current-page').attr('id');

      // get the page number from it
      var pageNumber = 0;
      if (pageLabel) {
        pageNumber = pageLabel.substr(5, pageLabel.length - 5);
      }
      // else we're starting a new observation

      return pageNumber;
    },

    // the target of the link is an image (book icon) so .parent() targets the link
    openModal: function(ev) {
      ev.preventDefault();
      var url = jQuery(ev.target).parent().attr('href');
      jQuery('.modal-body').html('');
    },

    render: function () {
      console.log('Rendering CollectView...');
    }

  });

  /**
    TreeSpeciesView
  **/
  app.View.TreeSpeciesView = Backbone.View.extend({
    template: "#tree-species-list-template",

    initialize: function() {
      var view = this;
      console.log('Initializing TreeSpeciesView...', view.el);

      view.render()
    },

    events: {

    },

    render: function () {
      var view = this;
      console.log('Rendering TreeSpeciesView...');

      var list = jQuery('#tree-species-list');

      _.each(view.collection, function(tree) {
        var listItem = _.template(jQuery(view.template).text(),{'common_name': tree.common_name, 'latin_name': tree.latin_name, 'wikipedia_url': tree.wikipedia_url});
        list.append(listItem);
      });
    }
  });

  /**
    ReviewData
  **/
  app.View.ReviewDataView = Backbone.View.extend({
    template: "#review-data-list-template",

    initialize: function() {
      var view = this;
      console.log('Initializing ReviewDataView...', view.el);
    },

    events: {

    },

    render: function () {
      var view = this;
      console.log('Rendering ReviewDataView...');

      jQuery('.tree-number-field').text(app.currentObservation.tree_number);
      jQuery('.branch-letter-field').text(app.currentObservation.branch_letter);
      jQuery('.tree-species-field').text(app.currentObservation.tree_species);
      jQuery('.percent-colored-tree-field').text(app.currentObservation.percent_colored_tree);
      jQuery('.field-notes-field').text(app.currentObservation.additional_notes);

      var list = jQuery('#review-data-list');

      //_.each(notesToRestore, function(note){
        // OLD TEMPLATE CODE THAT MIGHT BE USEFUL
        // var option = _.template(jQuery(view.template).text(), {'option_text': note.get('body'), id: note.id});
        // jQuery('#select-note-modal').append(option);
      //});

      _.each(app.currentObservation.leaves, function(leaf) {
        console.log(leaf);

        var listItem = null;

        if (leaf.fallen === "yes") {
          listItem = _.template(jQuery(view.template).text(),{'leaf_num': leaf.leaf_num, 'leaf_length': 'fallen', 'leaf_width': 'fallen', 'percent_colored': 'fallen'});
        } else {
          listItem = _.template(jQuery(view.template).text(),{'leaf_num': leaf.leaf_num, 'leaf_length': leaf.leaf_length + ' cm', 'leaf_width': leaf.leaf_width + ' cm', 'percent_colored': leaf.percent_colored});
        }

        if (listItem !== null) {
          list.append(listItem);
        } else {
          console.error('KABOOM! review-data-view issue');
        }

      });
    }
  });

  /**
    MapView
  **/
  app.View.MapView = Backbone.View.extend({
    view: this,

    initialize: function() {
      var view = this;
      console.log('Initializing MapView...', view.el);
    },

    events: {

    },

    render: function () {
      console.log('Rendering MapView...');
    }
  });

  this.Skeletor = Skeletor;
}).call(this);
<commit_msg>radio checks added, back still a little buggy<commit_after>/*jshint debug:true, noarg:true, noempty:true, eqeqeq:true, bitwise:true, undef:true, curly:true, browser: true, devel: true, jquery:true, strict:false */
/*global Backbone, _, jQuery, Sail */

(function() {
  "use strict";
  var Skeletor = this.Skeletor || {};
  this.Skeletor.Mobile = this.Skeletor.Mobile || {};
  var app = this.Skeletor.Mobile;
  app.View = {};

  /**
    CollectView
  **/
  app.View.CollectView = Backbone.View.extend({
    view: this,

    initialize: function() {
      var view = this;
      console.log('Initializing CollectView...', view.el);
    },

    events: {
      'click #new-observation'  : "startNewObservation",
      'click .next-btn'         : "moveForward",
      'click .back-btn'         : "moveBack",
      'click .wiki-link'        : "openModal",
      'click .leaf-fallen-btn'  : "buttonSelected"
    },

    buttonSelected: function(ev) {
      var view = this;

      jQuery('.btn-select').removeClass("btn-select");
      jQuery(ev.target).addClass("btn-select");
    },

    startNewObservation: function() {
      var view = this;

      // delete the old observation
      app.currentObservation = {};
      app.currentObservation.leaves = [];

      jQuery('#title-page').addClass('hidden');
      jQuery('#variable-content-container').removeClass('hidden');
      jQuery('.back-btn').removeClass('hidden');
      jQuery('.next-btn').removeClass('hidden');

      // we're on page '0', the title page - this will move us to page 1
      view.determineTargetPage('next');
    },

    moveForward: function() {
      var view = this;
      view.determineTargetPage('next');
    },

    moveBack: function() {
      var view = this;
      view.determineTargetPage('prev');
    },

    determineTargetPage: function(direction) {
      var view = this;

      // decide on next or previous page, and update the page number to that
      var pageNumber = Number(view.getPageNum());
      if (direction === 'next') {
        pageNumber += 1;
      } else if (direction === 'prev') {
        pageNumber -= 1;
      } else {
        console.error('ERROR: unexpected direction');
      }

      // determine which of the 6 leaf observations we are on
      var leafCycleNum = app.currentObservation.leaves.length + 1;

      /********** PAGE 4 *********/
      if (pageNumber == 4) {
        // if user said leaf has fallen
        var checkedEl = jQuery('.current-page [type="radio"]:checked');
        if (jQuery(checkedEl).is("#id-leaf-fallen-yes")) {
          // update the observation for fallen
          app.currentObservation.leaves[leafCycleNum-1] = { "leaf_num":leafCycleNum, "fallen":"yes" };

          // if this is the last observation, go to page 6. Else go to page 3
          if (leafCycleNum === 6) {
            view.populatePage(6);
          } else {
            view.populatePage(3);
          }

        // if user said leaf has not fallen
        } else if (jQuery(checkedEl).is("#id-leaf-fallen-no")) {
          app.currentObservation.leaves[leafCycleNum-1] = { "leaf_num":leafCycleNum, "fallen":"no" };

          view.populatePage(pageNumber);
        } else {
          jQuery().toastmessage('showErrorToast', "Please select whether this leaf has fallen");
        }

      /********** PAGE 6 *********/
      } else if (pageNumber === 6) {            // special case for leaf cycle pages to loop
        // go to page 3 if the leaves aren't all done (eg array length is 6)
        if (leafCycleNum === 6) {
          view.populatePage(6);
        } else {
          view.populatePage(3);
        }

      /********** ALL OTHER PAGES *********/
      } else {
        // if there are radio buttons on this page, make sure they're checked
        if (jQuery('.current-page [type="radio"]').length > 0) {
          var checkedEl = jQuery('.current-page [type="radio"]:checked');
          if (checkedEl.length > 0) {
            view.populatePage(pageNumber);
          } else {
            jQuery().toastmessage('showErrorToast', "Please make a selection");
          }
        }  else {
          view.populatePage(pageNumber);
        }
      }
    },

    updateJSONObject: function() {
      var view = this;

      _.each(jQuery('.current-page .input-field'), function(i) {
        // if this is of type text take the text and put it straight up into the json
        if (i.type === "text" || i.type === "textarea" || i.type === "number") {
          // add text value to json
          app.currentObservation[jQuery(i).data().fieldName] = jQuery(i).val();

        // else if this is of type radio, capture selected
        } else if (i.type === "radio") {
          var el = jQuery('[type="radio"]:checked');
          app.currentObservation[el.data().fieldName] = jQuery(el).val();
        }
        // TODO: clean this up - way overkill, very inefficient
      });
    },

    updateProgressBar: function() {
      // change jpg src or whatever
    },

    removePageClasses: function() {
      jQuery('.leaf-page').addClass('hidden');
      jQuery('.leaf-page').removeClass('current-page');
    },

    clearPageContent: function() {
      jQuery('.current-page .input-field').text('');
      jQuery('.current-page .leaf-fallen').prop('checked', false);
      jQuery('.current-page .btn-select').removeClass('btn-select');
    },

    populatePage: function(pageNumber) {
      var view = this;

      view.updateJSONObject();
      view.updateProgressBar();
      view.removePageClasses();

      if (pageNumber === 1) {
        jQuery('.back-btn').addClass('hidden');
      } else {
        jQuery('.back-btn').removeClass('hidden');
      }

      if (pageNumber === 7) {
        jQuery('.page-title').text('Review Data');
        jQuery('.next-btn').text('Finish');
        app.reviewDataView.render();
      } else {
        jQuery('.page-title').text('New Observation');
        jQuery('.next-btn').text('Next');
      }

      var pageLabel = 'leaf-';
      pageLabel = pageLabel + pageNumber;

      jQuery('#' + pageLabel).removeClass('hidden');
      jQuery('#' + pageLabel).addClass('current-page');
      view.clearPageContent();
    },

    getPageNum: function() {
      // find the currently shown page
      var pageLabel = jQuery('.current-page').attr('id');

      // get the page number from it
      var pageNumber = 0;
      if (pageLabel) {
        pageNumber = pageLabel.substr(5, pageLabel.length - 5);
      }
      // else we're starting a new observation

      return pageNumber;
    },

    // the target of the link is an image (book icon) so .parent() targets the link
    openModal: function(ev) {
      ev.preventDefault();
      var url = jQuery(ev.target).parent().attr('href');
      jQuery('.modal-body').html('');
    },

    render: function () {
      console.log('Rendering CollectView...');
    }

  });

  /**
    TreeSpeciesView
  **/
  app.View.TreeSpeciesView = Backbone.View.extend({
    template: "#tree-species-list-template",

    initialize: function() {
      var view = this;
      console.log('Initializing TreeSpeciesView...', view.el);

      view.render()
    },

    events: {

    },

    render: function () {
      var view = this;
      console.log('Rendering TreeSpeciesView...');

      var list = jQuery('#tree-species-list');

      _.each(view.collection, function(tree) {
        var listItem = _.template(jQuery(view.template).text(),{'common_name': tree.common_name, 'latin_name': tree.latin_name, 'wikipedia_url': tree.wikipedia_url});
        list.append(listItem);
      });
    }
  });

  /**
    ReviewData
  **/
  app.View.ReviewDataView = Backbone.View.extend({
    template: "#review-data-list-template",

    initialize: function() {
      var view = this;
      console.log('Initializing ReviewDataView...', view.el);
    },

    events: {

    },

    render: function () {
      var view = this;
      console.log('Rendering ReviewDataView...');

      jQuery('.tree-number-field').text(app.currentObservation.tree_number);
      jQuery('.branch-letter-field').text(app.currentObservation.branch_letter);
      jQuery('.tree-species-field').text(app.currentObservation.tree_species);
      jQuery('.percent-colored-tree-field').text(app.currentObservation.percent_colored_tree);
      jQuery('.field-notes-field').text(app.currentObservation.additional_notes);

      var list = jQuery('#review-data-list');

      _.each(app.currentObservation.leaves, function(leaf) {
        var listItem = null;

        if (leaf.fallen === "yes") {
          listItem = _.template(jQuery(view.template).text(),{'leaf_num': leaf.leaf_num, 'leaf_length': 'fallen', 'leaf_width': 'fallen', 'percent_colored': 'fallen'});
        } else {
          listItem = _.template(jQuery(view.template).text(),{'leaf_num': leaf.leaf_num, 'leaf_length': leaf.leaf_length + ' cm', 'leaf_width': leaf.leaf_width + ' cm', 'percent_colored': leaf.percent_colored});
        }

        if (listItem !== null) {
          list.append(listItem);
        } else {
          console.error('KABOOM! review-data-view issue');
        }

      });
    }
  });

  /**
    MapView
  **/
  app.View.MapView = Backbone.View.extend({
    view: this,

    initialize: function() {
      var view = this;
      console.log('Initializing MapView...', view.el);
    },

    events: {

    },

    render: function () {
      console.log('Rendering MapView...');
    }
  });

  this.Skeletor = Skeletor;
}).call(this);
<|endoftext|>


<commit_before>$(document).ready(function(){

//local links are loaded on same window, foreign links are
//loaded in new window/tab
$("a").attr("target", function() {
if (this.host == location.host) return "_self"
else return "_blank"; });

//delay script until window loads.
  $(window).load(function(){

  //for cloud animation
    function newPos() {
       var w = $(window).width();
       var nw = Math.floor(Math.random() * w);

       var nh = Math.floor(Math.random() * 28)+'%';

       return [nw, nh];
    }

    function animateCloud(image){
       $(image).animate({
            top: newPos()[1],
            left: newPos()[0]
       }, 20000, function(){
           animateCloud(image);
       });
    }

    animateCloud($("#cloud0"));
    animateCloud($("#cloud1"));
    animateCloud($("#cloud2"));

  });
});<commit_msg>prevented memory leak<commit_after>$(document).ready(function(){

//local links are loaded on same window, foreign links are
//loaded in new window/tab
$("a").attr("target", function() {
if (this.host == location.host) return "_self"
else return "_blank"; });

  //for cloud animation
    function newPos() {
       var w = $(window).width();
       var nw = Math.floor(Math.random() * w);

       var nh = Math.floor(Math.random() * 28)+'%';

       return [nw, nh];
    }
  //stop required to prevent memory leak
    function animateCloud(image){
       $(image).stop(true).animate({
            top: newPos()[1],
            left: newPos()[0]
       }, 20000, function(){
           animateCloud(image);
       });
    }

    animateCloud($("#cloud0"));
    animateCloud($("#cloud1"));
    animateCloud($("#cloud2"));

});<|endoftext|>


<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
"use strict";

var FirefoxProfile = require("firefox-profile");
var getPrefs = require("./preferences").getPrefs;
var defer = require("when").defer;
var console = require("./utils").console;

function createProfile (options) {
  options = options || {};
  var deferred = defer();
  var profile;

  if(options.profile){
    console.log("Copying provided profile");
    profile = new FirefoxProfile(options.profile);
  }else{
    console.log("Creating a new profile");
    profile = new FirefoxProfile();

    // Set default preferences
    var prefs = getPrefs("firefox");
    Object.keys(prefs).forEach(function (pref) {
      profile.setPreference(pref, prefs[pref]);
    });
  }

  // Set any of the preferences passed via options.
  var userPrefs = options.prefs || {};
  Object.keys(userPrefs).forEach(function(key) {
    profile.setPreference(key, userPrefs[key]);
  });

  profile.updatePreferences();

  if (options.verbose) {
    console.log("Using temporary profile at " + profile.profileDir);
  }

  // Add add-on to preferences
  if (options.xpi) {
    profile.addExtension(options.xpi, function () {
      deferred.resolve(profile.profileDir);
    });
  } else {
    deferred.resolve(profile.profileDir);
  }

  return deferred.promise;
}

module.exports = createProfile;
<commit_msg>improve code style<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
"use strict";

var FirefoxProfile = require("firefox-profile");
var getPrefs = require("./preferences").getPrefs;
var defer = require("when").defer;
var console = require("./utils").console;

function createProfile (options) {
  options = options || {};
  var deferred = defer();
  var profile;

  if (options.profile) {
    console.log("Copying provided profile");
    profile = new FirefoxProfile(options.profile);
  }
  else {
    console.log("Creating a new profile");
    profile = new FirefoxProfile();

    // Set default preferences
    var prefs = getPrefs("firefox");
    Object.keys(prefs).forEach(function (pref) {
      profile.setPreference(pref, prefs[pref]);
    });
  }

  // Set any of the preferences passed via options.
  var userPrefs = options.prefs || {};
  Object.keys(userPrefs).forEach(function(key) {
    profile.setPreference(key, userPrefs[key]);
  });

  profile.updatePreferences();

  if (options.verbose) {
    console.log("Using temporary profile at " + profile.profileDir);
  }

  // Add add-on to preferences
  if (options.xpi) {
    profile.addExtension(options.xpi, function () {
      deferred.resolve(profile.profileDir);
    });
  }
  else {
    deferred.resolve(profile.profileDir);
  }

  return deferred.promise;
}

module.exports = createProfile;
<|endoftext|>


<commit_before>'use strict';

const express = require('express');
const mongoose = require('mongoose');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const cors = require('cors');
const path = require('path');
const url = require('url');

const redis = require('redis');
// const redisClient = redis.createClient();
const session = require('express-session');
const RedisStore = require('connect-redis')(session);

const logger = require('morgan');
const errorHandler = require('./lib/error_handler');

const index = require('./routes/index');
const commentsRouter = require('./routes/comments');
const coursesRouter = require('./routes/courses');
const gamesRouter = require('./routes/games');
const gameResultRouter = require('./routes/game_result');
const usersRouter = require('./routes/users');
const userStatsRouter = require('./routes/user_stats');
const friendsRouter = require('./routes/friends');

mongoose.Promise = require('bluebird');

const mongoDbOptions = {
  useMongoClient: true,
}

if (process.env.NODE_ENV === 'test')
  mongoose.connect(process.env.DB_SERVER, mongoDbOptions);

if (process.env.NODE_ENV !== 'test')
  mongoose.connect(process.env.MONGODB_URI || 'mongodb://localhost/gff-dev', mongoDbOptions);

if (process.env.REDISTOGO_URL) {
  var rtg = require('url').parse(process.env.REDISTOGO_URL);
  var redisClient = redis.createClient(rtg.port, rtg.hostname);

  redisClient.auth(rtg.auth.split(':')[1]);
} else {
  var redisClient = redis.createClient();
}

const app = express();

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');

const sessionOptions = {
  secret: '1337',
  store: new RedisStore({
    client: redisClient,
  }),
  name: 'GolfForeFriends',
  saveUninitialized: true,
  resave: true,
  cookie: {
    maxAge: 86400 * 365,
  },
};

if (process.env.NODE_ENV === 'production')
  sessionOptions.cookie.secure = true;
  sessionOptions.resave = false;

app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(session(sessionOptions));
app.use(cors());

app.use(require('node-sass-middleware')({
  src: path.join(__dirname, 'public'),
  dest: path.join(__dirname, 'public'),
  indentedSyntax: true,
  sourceMap: true
}));
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', index);
app.use('/courses', coursesRouter);
app.use('/games', gamesRouter);
app.use('/games/result', gameResultRouter);
app.use('/games/comments', commentsRouter);
app.use('/users', usersRouter);
app.use('/users/stats', userStatsRouter);
app.use('/friends', friendsRouter);

app.use(function(req, res, next) {
  const err = new Error('Not Found');
  err.status = 404;
  next(err);
});

app.use(errorHandler);

module.exports = app;
<commit_msg>Deploy changes.<commit_after>'use strict';

const express = require('express');
const mongoose = require('mongoose');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const cors = require('cors');
const path = require('path');
const url = require('url');

const redis = require('redis');
// const redisClient = redis.createClient();
const session = require('express-session');
const RedisStore = require('connect-redis')(session);

const logger = require('morgan');
const errorHandler = require('./lib/error_handler');

const index = require('./routes/index');
const commentsRouter = require('./routes/comments');
const coursesRouter = require('./routes/courses');
const gamesRouter = require('./routes/games');
const gameResultRouter = require('./routes/game_result');
const usersRouter = require('./routes/users');
const userStatsRouter = require('./routes/user_stats');
const friendsRouter = require('./routes/friends');

mongoose.Promise = require('bluebird');

const mongoDbOptions = {
  useMongoClient: true,
}

if (process.env.NODE_ENV === 'test')
  mongoose.connect(process.env.DB_SERVER, mongoDbOptions);

if (process.env.NODE_ENV !== 'test')
  mongoose.connect(process.env.MONGODB_URI || 'mongodb://localhost/gff-dev', mongoDbOptions);

if (process.env.REDISTOGO_URL) {
  var redisUrl = url.parse(process.env.REDISTOGO_URL);
  var redisClient = redis.createClient(redisUrl.port, redisUrl.hostname);
  var redisAuth = redisUrl.auth.split(':');

  // redisClient.auth(redisUrl.auth.split(':'));
} else {
  var redisClient = redis.createClient();
}

const app = express();

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');

const sessionOptions = {
  secret: '1337',
  store: new RedisStore({
    // client: redisClient,
    host: redisUrl.hostname,
    port: redisUrl.port,
    db: redisAuth[0],
    pass: redisAuth[1],
  }),
  name: 'GolfForeFriends',
  saveUninitialized: true,
  resave: true,
  cookie: {
    maxAge: 86400 * 365,
  },
};

if (process.env.NODE_ENV === 'production') {
  sessionOptions.cookie.secure = true;
  sessionOptions.resave = false;
}

app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(session(sessionOptions));
app.use(cors());

app.use(require('node-sass-middleware')({
  src: path.join(__dirname, 'public'),
  dest: path.join(__dirname, 'public'),
  indentedSyntax: true,
  sourceMap: true
}));
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', index);
app.use('/courses', coursesRouter);
app.use('/games', gamesRouter);
app.use('/games/result', gameResultRouter);
app.use('/games/comments', commentsRouter);
app.use('/users', usersRouter);
app.use('/users/stats', userStatsRouter);
app.use('/friends', friendsRouter);

app.use(function(req, res, next) {
  const err = new Error('Not Found');
  err.status = 404;
  next(err);
});

app.use(errorHandler);

module.exports = app;
<|endoftext|>


<commit_before>/*!
 * Load Dependancies
 */
var fs = require('fs'),
    path = require('path'),
    jade = require('jade'),
    path = require('path'),
    mkdirp = require('mkdirp'),
    dox = require('dox'),
    _ = require('underscore'),
    pkg = require('../package'),
    template;

/**
 * Parser name
 */
exports.name = pkg.name;

/**
 * Parser version
 */
exports.version = pkg.version;

/**
 * Template used to produce the documentation
 */
var templatePath = exports.templatePath = '../views/template.jade';

/**
  * Return a list of methods for the side navigation
  *
  * @param {Object} file
  * @return {Object} Object formatted for template nav helper
  * @api private
  */
function buildStructureForFile(file) {
  var names = [];

  if (file.dox.length === 0) { return false; }

  file.dox.forEach(function(method){
    if (method.ctx) { names.push(method.ctx.name); }
  });

  return { source: file.sourceFile, target: file.targetFile, methods: names };
}

/**
 * Parse source code to produce documentation
 */
exports.render = function(file, files, options){
    options          = options || { title: 'Documentation' };
    file.dox         = file.dox.filter(exports.shouldPass);
    options.comments = file.dox;
    templatePath     = path.resolve(__dirname, templatePath);
    template         = fs.readFileSync(templatePath).toString();

    if (files) {
      options.structure = files.map(buildStructureForFile);
    } else {
      options.structure = new Array(buildStructureForFile(file));
    }

    return jade.compile(template, { filename:templatePath })(options);
};

/**
 * Test if a method should be ignored or not
 *
 * @param  {Object} method
 * @return {Boolean} true if the method is not private nor must be ignored
 * @api private
 */
exports.shouldPass = function(method){
  if(method.isPrivate){return false;}
  if(method.ignore){return false;}

  return method.tags.filter(function(tag){
    return tag.type === "private" || tag.type === "ignore";
  }).length === 0;
};

/*
 * Create an array of all the right files in the source dir
 */
exports.collectFiles = function(source, options, callback) {
  var dirtyFiles = require('walkdir').sync(source,{follow_symlinks:true}), // tee hee!
      ignore  = options.ignore || [],
      files   = [];

  dirtyFiles.forEach(function(file){
    file = path.relative(source, file);

    var doNotIgnore = _.all(ignore, function(d){
      // return true if no part of the path is in the ignore list
      return (file.indexOf(d) === -1);
    });

    if ((file.substr(-2) === 'js') && doNotIgnore) {
      files.push(file);
    }
  });

  return files;
};

/*
 * Make sure the folder structure in target mirrors source
 */
exports.createTargetFolders = function(target, files) {
  var folders = [];

  files.forEach(function(file){
    var folder = file.substr(0, file.lastIndexOf('/'));

    if ((folder !== '') && (folders.indexOf(folder) === -1)) {
      folders.push(folder);
      mkdirp.sync(target + '/' + folder);
    }
  });
};

/*
 * Dox all the files found by collectFiles
 */
exports.doxFiles = function(source, target, options, files) {
  files = files.map(function(file) {
    try {
      var content = fs.readFileSync(source + '/' + file).toString();
      return {
        sourceFile: file,
        targetFile: file.replace(source, target) + '.html',
        dox:        dox.parseComments(content, options)
      };
    } catch(e) { console.log(e); }
  });

  return files;
};
<commit_msg>Sometimes there isn't subfolders, you probably should create the docs folder though! Closes #22<commit_after>/*!
 * Load Dependancies
 */
var fs = require('fs'),
    path = require('path'),
    jade = require('jade'),
    path = require('path'),
    mkdirp = require('mkdirp'),
    dox = require('dox'),
    _ = require('underscore'),
    pkg = require('../package'),
    template;

/**
 * Parser name
 */
exports.name = pkg.name;

/**
 * Parser version
 */
exports.version = pkg.version;

/**
 * Template used to produce the documentation
 */
var templatePath = exports.templatePath = '../views/template.jade';

/**
  * Return a list of methods for the side navigation
  *
  * @param {Object} file
  * @return {Object} Object formatted for template nav helper
  * @api private
  */
function buildStructureForFile(file) {
  var names = [];

  if (file.dox.length === 0) { return false; }

  file.dox.forEach(function(method){
    if (method.ctx) { names.push(method.ctx.name); }
  });

  return { source: file.sourceFile, target: file.targetFile, methods: names };
}

/**
 * Parse source code to produce documentation
 */
exports.render = function(file, files, options){
    options          = options || { title: 'Documentation' };
    file.dox         = file.dox.filter(exports.shouldPass);
    options.comments = file.dox;
    templatePath     = path.resolve(__dirname, templatePath);
    template         = fs.readFileSync(templatePath).toString();

    if (files) {
      options.structure = files.map(buildStructureForFile);
    } else {
      options.structure = new Array(buildStructureForFile(file));
    }

    return jade.compile(template, { filename:templatePath })(options);
};

/**
 * Test if a method should be ignored or not
 *
 * @param  {Object} method
 * @return {Boolean} true if the method is not private nor must be ignored
 * @api private
 */
exports.shouldPass = function(method){
  if(method.isPrivate){return false;}
  if(method.ignore){return false;}

  return method.tags.filter(function(tag){
    return tag.type === "private" || tag.type === "ignore";
  }).length === 0;
};

/*
 * Create an array of all the right files in the source dir
 */
exports.collectFiles = function(source, options, callback) {
  var dirtyFiles = require('walkdir').sync(source,{follow_symlinks:true}), // tee hee!
      ignore  = options.ignore || [],
      files   = [];

  dirtyFiles.forEach(function(file){
    file = path.relative(source, file);

    var doNotIgnore = _.all(ignore, function(d){
      // return true if no part of the path is in the ignore list
      return (file.indexOf(d) === -1);
    });

    if ((file.substr(-2) === 'js') && doNotIgnore) {
      files.push(file);
    }
  });

  return files;
};

/*
 * Make sure the folder structure in target mirrors source
 */
exports.createTargetFolders = function(target, files) {
  var folders = [];
  // Ensure that the target folder exists
  mkdirp.sync(target);

  files.forEach(function(file){
    var folder = file.substr(0, file.lastIndexOf('/'));

    if ((folder !== '') && (folders.indexOf(folder) === -1)) {
      folders.push(folder);
      mkdirp.sync(path.join(target, folder));
    }
  });
};

/*
 * Dox all the files found by collectFiles
 */
exports.doxFiles = function(source, target, options, files) {
  files = files.map(function(file) {
    try {
      var content = fs.readFileSync(source + '/' + file).toString();
      return {
        sourceFile: file,
        targetFile: file.replace(source, target) + '.html',
        dox:        dox.parseComments(content, options)
      };
    } catch(e) { console.log(e); }
  });

  return files;
};
<|endoftext|>


<commit_before>/// <reference types="Cypress" />

import els from '../../elements/de';
import { clearProductFromCart } from '../../helper/cart';

describe('functional tests cart page', () => {
  it('check for increase / decrease quanitity', () => {
    cy.visit('');

    cy.get(els.allProductCategory)
      .scrollIntoView()
      .should('be.visible')
      .click();
    cy.get(els.productWithManyProps4GridViewName)
      .should('be.visible')
      .click();
    cy.get(els.addToCartButton)
      .should('be.visible')
      .click();
    cy.get(els.cartButton)
      .should('be.visible')
      .click();
    cy.get(els.quantityPicker)
      .should('be.visible')
      .click()
      .type(2)
      .focus()
      .blur();
    cy.get('[data-test-id="minPrice: 0 price: 398 currency: EUR"]')
      .should('be.visible');
    cy.get(els.quantityPicker)
      .clear()
      .blur();
    cy.get('[data-test-id="minPrice: 0 price: 199 currency: EUR"]')
      .should('be.visible');
  });

  it('should add sescond product to cart and delete it', () => {
    cy.visit('');
    cy.get(els.basicCategory)
      .scrollIntoView()
      .click();
    cy.get(els.productsWithLongNamesCat)
      .last()
      .click();
    cy.get(els.productWithVeryLongName5Name)
      .last()
      .click();
    cy.get(els.addToCartButton)
      .click();
    cy.get(els.cartButton)
      .click();
  });

  it('should check for wrong coupon', () => {
    cy.get(els.couponFieldInput)
      .type('wrongCoupon {enter}');
    cy.get(els.basicDialogText)
      .contains('Coupon code "wrongCoupon" is not valid.');
    cy.get(els.basicDialogOkButton)
      .click();
  });

  it('should check for right coupon', () => {
    cy.get(els.couponFieldInput)
      .clear()
      .type('test1');
    cy.get(els.couponSubmitButton)
      .click();
    cy.get(els.basicDialogOkButton)
      .click();
    cy.get('[data-test-id="subTotal: 283"]')
      .should('be.visible');
  });

  it('should delete coupon from cart', () => {
    cy.get(els.deleteCouponButton)
      .click();
    cy.get(els.deleteCouponButton)
      .should('not.exist');
  });

  it('should check for delete product from cart', () => {
    clearProductFromCart();
  });
});
<commit_msg>PWA-584 increase stability for cart test<commit_after>/// <reference types="Cypress" />

import els from '../../elements/de';
import { clearProductFromCart } from '../../helper/cart';

describe('functional tests cart page', () => {
  it('check for increase / decrease quanitity', () => {
    cy.visit('');

    cy.get(els.allProductCategory)
      .scrollIntoView()
      .should('be.visible')
      .click();
    cy.get(els.productWithManyProps4GridViewName)
      .should('be.visible')
      .click();
    cy.get(els.addToCartButton)
      .should('be.visible')
      .click();
    cy.get(els.cartButton)
      .should('be.visible')
      .click();
    cy.get(els.quantityPicker)
      .should('be.visible')
      .click()
      .type(2)
      .focus()
      .blur();
    cy.get('[data-test-id="minPrice: 0 price: 398 currency: EUR"]')
      .should('be.visible');
    cy.get(els.quantityPicker)
      .clear()
      .type(1)
      .focus()
      .blur();
    cy.get('[data-test-id="minPrice: 0 price: 199 currency: EUR"]')
      .should('be.visible');
  });

  it('should add sescond product to cart and delete it', () => {
    cy.visit('');
    cy.get(els.basicCategory)
      .scrollIntoView()
      .click();
    cy.get(els.productsWithLongNamesCat)
      .last()
      .click();
    cy.get(els.productWithVeryLongName5Name)
      .last()
      .click();
    cy.get(els.addToCartButton)
      .click();
    cy.get(els.cartButton)
      .click();
  });

  it('should check for wrong coupon', () => {
    cy.get(els.couponFieldInput)
      .type('wrongCoupon {enter}');
    cy.get(els.basicDialogText)
      .contains('Coupon code "wrongCoupon" is not valid.');
    cy.get(els.basicDialogOkButton)
      .click();
  });

  it('should check for right coupon', () => {
    cy.get(els.couponFieldInput)
      .clear()
      .type('test1');
    cy.get(els.couponSubmitButton)
      .click();
    cy.get(els.basicDialogOkButton)
      .click();
    cy.get('[data-test-id="subTotal: 283"]')
      .should('be.visible');
  });

  it('should delete coupon from cart', () => {
    cy.get(els.deleteCouponButton)
      .click();
    cy.get(els.deleteCouponButton)
      .should('not.exist');
  });

  it('should check for delete product from cart', () => {
    clearProductFromCart();
  });
});
<|endoftext|>


<commit_before>#!/usr/bin/env node
'use strict';

const _ = require('lodash');
const fs = require('fs');
const path = require('path');
const DBWriter = require('../lib/dbwrite.js');

// Config
const appcfg = _.defaultsDeep(
	{},
	require('../cfg/user.json'),
	require('../cfg/config.json')
);

// DB
const dbpath = path.isAbsolute(appcfg.dbpath) ? appcfg.dbpath : path.resolve(__dirname, '..', appcfg.dbpath);
const dbw = new DBWriter({
	path: dbpath,
	user_id_str: appcfg.user.id_str,
	// noSync: true
});

// Get file list
const filenames = process.argv.slice(2);

// GO!
for (let fname of filenames) {
	loadfile(fname);
}

// // Sync and close
// dbw.sync(err => {
// 	if (err) {
// 		console.error(err);
// 	}
// 	dbw.close();
// });

console.log('Finished!');

// Funcs
function loadfile (name) {
	const types = ['user', 'user_tweet', 'other_tweet', 'delete', 'favorite', 'unfavorite'];
	let count = {
		'user': 0,
		'user_tweet': 0,
		'other_tweet': 0,
		'delete': 0,
		'favorite': 0,
		'unfavorite': 0
	};
	let filename = path.resolve(name);
	let ret = false;
	let total = 0;

	function writefn (type, data, txn) {
		let retw = false;

		switch (type) {
			case 'queue':
				retw = writeq(data);
				break;
			case 'status':
				retw = dbw.setstatus('', data, txn);
				break;
			case 'following':
				retw = dbw.setstatus('following', data, txn);
				break;
			case 'user':
				retw = dbw.writeuser(data, txn);
				break;
			case 'user_tweet':
				retw = dbw.writetweet(data, txn);
				break;
			case 'other_tweet':
				retw = dbw.writetweet(data, txn);
				break;
			case 'delete':
				retw = dbw.deletetweet(data, txn);
				break;
			case 'favorite':
				retw = dbw.writefav(data, txn);
				break;
			case 'unfavorite':
				retw = dbw.deletefav(data, txn);
				break;
		}

		return retw;
	}

	function writeq (queue) {
		let retq = false;

		// Open transaction
		let qtxn = dbw.begin();

		try {
			// Recursively call
			for (let i = 0; i < queue.length; i++) {
				let item = queue[i];
				if (_.has(item, 'type') && _.has(item, 'data')) {
					// Leave return value to end of queue, but return true if any write succeeds
					if (writefn(item.type, item.data, qtxn)) {
						retq = true;
						if (_.has(count, item.type)) {
							count[item.type]++;
						}
					}
				}
			}
			qtxn.commit();
		}
		catch (e) {
			qtxn.abort();
			console.error(e);
			retq = false;
		}

		return retq;
	}

	try {
		// Read file into memory
		let str = fs.readFileSync(filename, {encoding: 'utf8'});

		// Convert to JSON
		let eventlist = JSON.parse(str);

		if (eventlist.length > 0) {
			console.log(`Processing ${filename}, ${eventlist.length} items`);
			if (writeq(eventlist)) {
				let counts = [];
				for (let name of types) {
					let num = count[name];
					if (num > 0) {
						total += num;
						counts.push(`${num} ${name}${num > 1 ? 's' : ''}`);
					}
				}
				console.log(`Processed ${eventlist.length} items, updated ${total} (${counts.join(', ')})`);
			}
			else {
				console.log(`Processed ${eventlist.length} items; all items up-to-date`);
			}

		}
		else {
			console.log(`No items to process in ${filename}`);
		}
	}
	catch (e) {
		console.error(`Error processing ${filename}:`);
		console.error(e);
	}
}

<commit_msg>Updated db-load to use new DBWriter functions instead<commit_after>#!/usr/bin/env node
'use strict';

const _ = require('lodash');
const fs = require('fs');
const path = require('path');
const DBWriter = require('../lib/dbwrite.js');

// Config
const appcfg = _.defaultsDeep(
	{},
	require('../cfg/user.json'),
	require('../cfg/config.json')
);

// DB
const dbpath = path.isAbsolute(appcfg.dbpath) ? appcfg.dbpath : path.resolve(__dirname, '..', appcfg.dbpath);
const dbw = new DBWriter({
	path: dbpath,
	user_id_str: appcfg.user.id_str,
	// noSync: true
});

// Get file list
const filenames = process.argv.slice(2);

// GO!
for (let fname of filenames) {
	loadfile(fname);
}

// // Sync and close
// dbw.sync(err => {
// 	if (err) {
// 		console.error(err);
// 	}
// 	dbw.close();
// });

console.log('Finished!');

// Funcs
function loadfile (name) {
	const types = ['user', 'user_tweet', 'other_tweet', 'delete', 'favorite', 'unfavorite'];
	let filename = path.resolve(name);

	try {
		// Read file into memory
		let str = fs.readFileSync(filename, {encoding: 'utf8'});

		// Convert to JSON
		let eventlist = JSON.parse(str);

		if (eventlist.length > 0) {
			console.log(`Processing ${filename}, ${eventlist.length} items...`);
			let ret = dbw.writequeue(eventlist);
			if (ret) {
				let total = 0;
				let counts = [];
				let stastr = '';
				if (ret.status.size > 0) {
					let num = ret.status.size;
					total += num;
					stastr = '\nUpdated status items:';
					for (let st of ret.status) {
						stastr += `\n    ${st}`;
					}
					counts.push(`${num} status item${num > 1 ? 's' : ''}`);
				}
				for (let name of types) {
					let num = ret[name];
					if (num > 0) {
						total += num;
						counts.push(`${num} ${name}${num == 1 ? '' : name.endsWith('s') ? 'es' : 's'}`);
					}
				}
				console.log(`Updated ${total} items (${counts.join(', ')})` + stastr);
			}
			else {
				console.log(`All items up-to-date`);
			}
		}
		else {
			console.log(`No items to process in ${filename}`);
		}
	}
	catch (e) {
		console.error(`Error processing ${filename}:`);
		console.error(e);
	}
}

<|endoftext|>


<commit_before>"use strict";

let Chronopic = require('chronopic');
let angular = require('angular');
require('chronopic/dist/js/chronopic-i18n.min.js');

let cp = angular.module('chronopic', []);

cp.service('ChronopicService', function() {
  let options = {
    date: null,
    format: "{date}"
  };

  return {
    options
  };
});

cp.directive('chronopic', function(ChronopicService) {
  return {
    restrict: 'A',
    link: function(scope, elem, attrs) {
      let options = ChronopicService.options;

      // Try parsing any pre-existing value as a date
      let parsedDate = (options.date instanceof Date ?
        options.date : new Date(Date.parse(scope.field.value)));

      // CSS Overrides
      if (typeof options.css === "object") {
        Object.keys(options.css).forEach(key => {
          elem.css(key, options.css[key]);
        });
      }

      // Inject Chronopic instance on element
      new Chronopic(elem[0], {
        date: isNaN(parsedDate) ? null : parsedDate,
        format: (typeof options.format === "string" ? options.format : null),
        className: 'chronopic.chronopic-ext-md',
        onChange: function(elem, date) {
          let internalFormat = date.toISOString(); // ISO-8601

          if (scope.field.format === "date") {
            internalFormat = internalFormat.slice(0, 10); // yyyy-mm-dd
          }

          scope.field.value = internalFormat;

          if (typeof options.onChange === "function") {
            options.onChange(elem, date, scope);
          }

					scope.$apply();
        }
      });
    }
  };
});
<commit_msg>Fix chronopic value update<commit_after>"use strict";

let Chronopic = require('chronopic');
let angular = require('angular');
require('chronopic/dist/js/chronopic-i18n.min.js');

let cp = angular.module('chronopic', []);

cp.service('ChronopicService', function() {
  let options = {
    date: null,
    format: "{date}"
  };

  return {
    options
  };
});

cp.directive('chronopic', function($timeout, ChronopicService) {
  return {
    restrict: 'A',
    link: function(scope, elem, attrs) {
      let options = ChronopicService.options;

      // Try parsing any pre-existing value as a date
      let parsedDate = (options.date instanceof Date ?
        options.date : new Date(Date.parse(scope.field.value)));

      // CSS Overrides
      if (typeof options.css === "object") {
        Object.keys(options.css).forEach(key => {
          elem.css(key, options.css[key]);
        });
      }

      // Inject Chronopic instance on element
      new Chronopic(elem[0], {
        date: isNaN(parsedDate) ? null : parsedDate,
        format: (typeof options.format === "string" ? options.format : null),
        className: 'chronopic.chronopic-ext-md',
        onChange: function(elem, date) {
          $timeout(() => {
            let internalFormat = date.toISOString(); // ISO-8601

            if (scope.field.format === "date") {
              internalFormat = internalFormat.slice(0, 10); // yyyy-mm-dd
            }

            scope.field.value = internalFormat;

            if (typeof options.onChange === "function") {
              options.onChange(elem, date, scope);
            }
          });
        }
      });
    }
  };
});
<|endoftext|>


<commit_before>(function () {

    function unit (x) {
        return x;
    }

    var
        PENDING = -1,
        FULFILLED = 0,
        REJECTED = 1;

    function transitionTo (promise, state, value) {
        if (promise.state !== PENDING) return promise;

        promise.state = state;
        promise.value = value;

        return executeNextPromises(promise);
    }

    function resolvePromise(promise, value) {
        if (promise.state !== PENDING) return promise;

        var valType = typeof value;
        if (valType === "object" || valType === "function") {
            var then;
            try {
                then = value.then;

                if (typeof then === "function") {
                    var executed = false;
                    then.call(value, function (v) {
                        if (executed) return value;
                        executed = true;

                        return resolvePromise(promise, v);
                    }, function (reason) {
                        if (executed) return reason;
                        executed = true;

                        return transitionTo(promise, REJECTED, reason);
                    });
                    return promise;
                }

            } catch (err) {
                return transitionTo(promise, REJECTED, err);
            }

        }
        return transitionTo(promise, FULFILLED, value);
    }

    function executeNextPromises(promise) {

        if (promise.state === PENDING) return promise;

        if (promise.next) {
            var i, l;

            for (i = 0, l = promise.next.length; i < l; i = i + 1) {
                executeHandlers(promise.next[i], promise.value, promise.state);
            }
            if (l) promise.next = [];

        }

        return promise;
    }

    function executeHandlers(promise, value, state) {

        setTimeout(function () {
            try {
                var nextVal =promise.handlers[state].call(void(0), value); //
            } catch(err) {
                return transitionTo(promise, REJECTED, err);
            }
            return resolvePromise(promise, nextVal);
        }, 0);

        return promise;
    }

    function Promise(onFulfill, onRejection) {
        var self = this;

        //if an handler was passed, it is used, else the handler upon fulfillment will be according to the promise a+ specs 2.2.1

        onFulfill = (typeof onFulfill === "function" ?
                onFulfill :
                function (value) {
                    transitionTo(self, FULFILLED, value);
                });
        onRejection = (typeof onRejection === "function" ?
                onRejection :
                function (reason) {
                    transitionTo(self, REJECTED, reason);
                });

        this.handlers = [onFulfill, onRejection];
        this.next = [];
        this.state = PENDING;
        this.value = void(0);
    }

    Promise.prototype.then = function (a, b) {
        var nextPromise = new Promise(a, b);

        if (this.state !== PENDING) return executeHandlers(nextPromise, this.value, this.state);

        this.next.push(nextPromise);
        return nextPromise;
    }

	module.exports = exports = {
        "defer": function () {
            var promise = new Promise();

            return {
                "reject": function ( reason ) {
                    return transitionTo(promise, REJECTED, reason);
                },
                "resolve": function ( value ) {
                    return resolvePromise(promise, value);
                },
                "promise": promise
            };
        }
    };
} ());
<commit_msg>fix for 2.3.1<commit_after>(function () {

    function unit (x) {
        return x;
    }

    var
        PENDING = -1,
        FULFILLED = 0,
        REJECTED = 1;

    function transitionTo (promise, state, value) {
        if (promise.state !== PENDING) return promise;

        promise.state = state;
        promise.value = value;

        return executeNextPromises(promise);
    }

    function resolvePromise(promise, value) {

        if (promise === value) transitionTo(promise, REJECTED, TypeError("Error : trying to resolve a promise with itself"));
        if (promise.state !== PENDING) return promise;

        var valType = typeof value;
        if (valType === "object" || valType === "function") {
            var then;
            try {
                then = value.then;

                if (typeof then === "function") {
                    var executed = false;
                    then.call(value, function (v) {
                        if (executed) return value;
                        executed = true;

                        return resolvePromise(promise, v);
                    }, function (reason) {
                        if (executed) return reason;
                        executed = true;

                        return transitionTo(promise, REJECTED, reason);
                    });
                    return promise;
                }

            } catch (err) {
                return transitionTo(promise, REJECTED, err);
            }

        }
        return transitionTo(promise, FULFILLED, value);
    }

    function executeNextPromises(promise) {

        if (promise.state === PENDING) return promise;

        if (promise.next) {
            var i, l;

            for (i = 0, l = promise.next.length; i < l; i = i + 1) {
                executeHandlers(promise.next[i], promise.value, promise.state);
            }
            if (l) promise.next = [];

        }

        return promise;
    }

    function executeHandlers(promise, value, state) {

        setTimeout(function () {
            try {
                var nextVal =promise.handlers[state].call(void(0), value); //
            } catch(err) {
                return transitionTo(promise, REJECTED, err);
            }
            return resolvePromise(promise, nextVal);
        }, 0);

        return promise;
    }

    function Promise(onFulfill, onRejection) {
        var self = this;

        //if an handler was passed, it is used, else the handler upon fulfillment will be according to the promise a+ specs 2.2.1

        onFulfill = (typeof onFulfill === "function" ?
                onFulfill :
                function (value) {
                    transitionTo(self, FULFILLED, value);
                });
        onRejection = (typeof onRejection === "function" ?
                onRejection :
                function (reason) {
                    transitionTo(self, REJECTED, reason);
                });

        this.handlers = [onFulfill, onRejection];
        this.next = [];
        this.state = PENDING;
        this.value = void(0);
    }

    Promise.prototype.then = function (a, b) {
        var nextPromise = new Promise(a, b);

        if (this.state !== PENDING) return executeHandlers(nextPromise, this.value, this.state);

        this.next.push(nextPromise);
        return nextPromise;
    }

	module.exports = exports = {
        "defer": function () {
            var promise = new Promise();

            return {
                "reject": function ( reason ) {
                    return transitionTo(promise, REJECTED, reason);
                },
                "resolve": function ( value ) {
                    return resolvePromise(promise, value);
                },
                "promise": promise
            };
        }
    };
} ());
<|endoftext|>


<commit_before>/*global describe, before, it, after, before, beforeEach, afterEach */
/*jshint expr: true */
'use strict';
var shell = require('shelljs');
var assert = require('assert');
var sinon = require('sinon');
var proxyquire = require('proxyquire');
var file = require('../lib/actions/file');
var async = require('async');

describe('Generator.user', function () {

  it('is exposed on the Base generator', function () {
    assert.equal(require('../lib/actions/user'), require('../lib/base').prototype.user);
  });

  describe('.git', function () {

    before(function (done) {
      this.cwd = process.cwd();
      this.tmp = shell.tempdir();
      shell.cd(this.tmp);
      file.mkdir('subdir');
      async.parallel([
        shell.exec.bind(shell, 'git init --quiet'),
        shell.exec.bind(shell, 'git config --local user.name Yeoman'),
        shell.exec.bind(shell, 'git config --local user.email yo@yeoman.io'),
      ], function () { done(); });
    });

    after(function () {
      shell.cd(this.cwd);
    });

    beforeEach(function () {
      shell.cd(this.tmp);

      this.shell = shell;
      sinon.spy(this.shell, 'exec');

      this.user = proxyquire('../lib/actions/user', {
        shelljs: this.shell
      });
    });

    afterEach(function () {
      this.shell.exec.restore();
    });

    describe('.username', function () {
      it('is the username used by git', function () {
        assert.equal(this.user.git.username, 'Yeoman');
      });

      it('is read-only', function () {
        this.user.git.username = 'bar';
        assert.notEqual(this.user.git.username, 'bar');
      });

      it('cache the value', function () {
        this.user.git.username;
        this.user.git.username;
        assert.equal(this.shell.exec.callCount, 1);
      });

      it('cache is linked to the CWD', function () {
        this.user.git.username;
        shell.cd('subdir');
        this.user.git.username;
        assert.equal(this.shell.exec.callCount, 2);
      });
    });

    describe('.email', function () {
      it('is the email used by git', function () {
        assert.equal(this.user.git.email, 'yo@yeoman.io');
      });

      it('is read-only', function () {
        this.user.git.email = 'bar';
        assert.notEqual(this.user.git.email, 'bar');
      });

      it('handle cache', function () {
        this.user.git.email;
        this.user.git.email;
        assert.equal(this.shell.exec.callCount, 1);
      });

      it('cache is linked to the CWD', function () {
        this.user.git.email;
        shell.cd('subdir');
        this.user.git.email;
        assert.equal(this.shell.exec.callCount, 2);
      });
    });

  });

});
<commit_msg>Fix user module unit test<commit_after>/*global describe, before, it, after, before, beforeEach, afterEach */
/*jshint expr: true */
'use strict';
var shell = require('shelljs');
var assert = require('assert');
var sinon = require('sinon');
var proxyquire = require('proxyquire');
var file = require('../lib/actions/file');
var async = require('async');

describe('Generator.user', function () {

  it('is exposed on the Base generator', function () {
    assert.equal(require('../lib/actions/user'), require('../lib/base').prototype.user);
  });

  describe('.git', function () {

    before(function (done) {
      this.cwd = process.cwd();
      this.tmp = shell.tempdir();
      shell.cd(this.tmp);
      file.mkdir('subdir');
      async.parallel([
        shell.exec.bind(shell, 'git init --quiet'),
        shell.exec.bind(shell, 'git config --local user.name Yeoman'),
        shell.exec.bind(shell, 'git config --local user.email yo@yeoman.io'),
      ], function () { done(); });
    });

    after(function () {
      shell.cd(this.cwd);
    });

    beforeEach(function () {
      shell.cd(this.tmp);

      this.shell = shell;
      sinon.spy(this.shell, 'exec');

      this.user = proxyquire('../lib/actions/user', {
        shelljs: this.shell
      });
    });

    afterEach(function () {
      this.shell.exec.restore();
    });

    describe('.username', function () {
      it('is the username used by git', function () {
        assert.equal(this.user.git.username, 'Yeoman');
      });

      it('is read-only', function () {
        assert.throws(function () {
          this.user.git.username = 'bar';
        });
      });

      it('cache the value', function () {
        this.user.git.username;
        this.user.git.username;
        assert.equal(this.shell.exec.callCount, 1);
      });

      it('cache is linked to the CWD', function () {
        this.user.git.username;
        shell.cd('subdir');
        this.user.git.username;
        assert.equal(this.shell.exec.callCount, 2);
      });
    });

    describe('.email', function () {
      it('is the email used by git', function () {
        assert.equal(this.user.git.email, 'yo@yeoman.io');
      });

      it('is read-only', function () {
        assert.throws(function () {
          this.user.git.email = 'bar';
        });
      });

      it('handle cache', function () {
        this.user.git.email;
        this.user.git.email;
        assert.equal(this.shell.exec.callCount, 1);
      });

      it('cache is linked to the CWD', function () {
        this.user.git.email;
        shell.cd('subdir');
        this.user.git.email;
        assert.equal(this.shell.exec.callCount, 2);
      });
    });

  });

});
<|endoftext|>


<commit_before>/* eslint-disable @typescript-eslint/naming-convention */

'use strict';

const FailureOnlyReporterGroupedByBrowser = require('testem-failure-only-reporter/grouped-by-browser');

module.exports = {
  framework: 'qunit',
  test_page: 'tests/index.html?hidepassed',
  disable_watching: true,
  browser_start_timeout: 2000,
  browser_disconnect_timeout: 120,
  socket_heartbeat_timeout: 600,
  socket_server_options: {
    upgradeTimeout: 30000,
  },
  timeout: 600,
  parallel: 2,
  reporter: FailureOnlyReporterGroupedByBrowser,
  launchers: {
    BS_Chrome_Current: {
      exe: 'node_modules/.bin/browserstack-launch',
      args: [
        '--os',
        'Windows',
        '--osv',
        '10',
        '--b',
        'chrome',
        '--bv',
        'latest',
        '-t',
        '1200',
        '--u',
        '<url>',
      ],
      protocol: 'browser',
    },
    BS_Chrome_Last: {
      exe: 'node_modules/.bin/browserstack-launch',
      args: [
        '--os',
        'Windows',
        '--osv',
        '10',
        '--b',
        'chrome',
        '--bv',
        '70',
        '-t',
        '1200',
        '--u',
        '<url>',
      ],
      protocol: 'browser',
    },
    BS_Firefox_Current: {
      exe: 'node_modules/.bin/browserstack-launch',
      args: [
        '--os',
        'Windows',
        '--osv',
        '10',
        '--b',
        'firefox',
        '--bv',
        // Current breaks browserstack, so pin for now
        '78',
        '-t',
        '1200',
        '--u',
        '<url>',
      ],
      protocol: 'browser',
    },
    BS_Firefox_Last: {
      exe: 'node_modules/.bin/browserstack-launch',
      args: [
        '--os',
        'Windows',
        '--osv',
        '10',
        '--b',
        'firefox',
        '--bv',
        '63',
        '-t',
        '1200',
        '--u',
        '<url>',
      ],
      protocol: 'browser',
    },
    BS_Safari_Current: {
      exe: 'node_modules/.bin/browserstack-launch',
      args: [
        '--os',
        'OS X',
        '--osv',
        'Mojave',
        '--b',
        'safari',
        '--bv',
        'latest',
        '-t',
        '1200',
        '--u',
        '<url>',
      ],
      protocol: 'browser',
    },
    BS_Safari_Last: {
      exe: 'node_modules/.bin/browserstack-launch',
      args: [
        '--os',
        'OS X',
        '--osv',
        'High Sierra',
        '--b',
        'safari',
        '--bv',
        'latest',
        '-t',
        '1200',
        '--u',
        '<url>',
      ],
      protocol: 'browser',
    },
    BS_MS_Edge: {
      exe: 'node_modules/.bin/browserstack-launch',
      args: [
        '--os',
        'Windows',
        '--osv',
        '10',
        '--b',
        'edge',
        '--bv',
        'latest',
        '-t',
        '1200',
        '--u',
        '<url>',
      ],
      protocol: 'browser',
    },
    BS_IE_11: {
      exe: 'node_modules/.bin/browserstack-launch',
      args: [
        '--os',
        'Windows',
        '--osv',
        '10',
        '--b',
        'ie',
        '--bv',
        '11.0',
        '-t',
        '1500',
        '--u',
        '<url>',
      ],
      protocol: 'browser',
    },
  },
  launch_in_dev: [],
  launch_in_ci: [
    'BS_Chrome_Current',
    'BS_Chrome_Last',
    'BS_Firefox_Current',
    'BS_Firefox_Last',
    'BS_Safari_Current',
    'BS_Safari_Last',
    'BS_MS_Edge',
    'BS_IE_11',
  ],
};
<commit_msg>drop support for IE11<commit_after>/* eslint-disable @typescript-eslint/naming-convention */

'use strict';

const FailureOnlyReporterGroupedByBrowser = require('testem-failure-only-reporter/grouped-by-browser');

module.exports = {
  framework: 'qunit',
  test_page: 'tests/index.html?hidepassed',
  disable_watching: true,
  browser_start_timeout: 2000,
  browser_disconnect_timeout: 120,
  socket_heartbeat_timeout: 600,
  socket_server_options: {
    upgradeTimeout: 30000,
  },
  timeout: 600,
  parallel: 2,
  reporter: FailureOnlyReporterGroupedByBrowser,
  launchers: {
    BS_Chrome_Current: {
      exe: 'node_modules/.bin/browserstack-launch',
      args: [
        '--os',
        'Windows',
        '--osv',
        '10',
        '--b',
        'chrome',
        '--bv',
        'latest',
        '-t',
        '1200',
        '--u',
        '<url>',
      ],
      protocol: 'browser',
    },
    BS_Chrome_Last: {
      exe: 'node_modules/.bin/browserstack-launch',
      args: [
        '--os',
        'Windows',
        '--osv',
        '10',
        '--b',
        'chrome',
        '--bv',
        '70',
        '-t',
        '1200',
        '--u',
        '<url>',
      ],
      protocol: 'browser',
    },
    BS_Firefox_Current: {
      exe: 'node_modules/.bin/browserstack-launch',
      args: [
        '--os',
        'Windows',
        '--osv',
        '10',
        '--b',
        'firefox',
        '--bv',
        // Current breaks browserstack, so pin for now
        '78',
        '-t',
        '1200',
        '--u',
        '<url>',
      ],
      protocol: 'browser',
    },
    BS_Firefox_Last: {
      exe: 'node_modules/.bin/browserstack-launch',
      args: [
        '--os',
        'Windows',
        '--osv',
        '10',
        '--b',
        'firefox',
        '--bv',
        '63',
        '-t',
        '1200',
        '--u',
        '<url>',
      ],
      protocol: 'browser',
    },
    BS_Safari_Current: {
      exe: 'node_modules/.bin/browserstack-launch',
      args: [
        '--os',
        'OS X',
        '--osv',
        'Mojave',
        '--b',
        'safari',
        '--bv',
        'latest',
        '-t',
        '1200',
        '--u',
        '<url>',
      ],
      protocol: 'browser',
    },
    BS_Safari_Last: {
      exe: 'node_modules/.bin/browserstack-launch',
      args: [
        '--os',
        'OS X',
        '--osv',
        'High Sierra',
        '--b',
        'safari',
        '--bv',
        'latest',
        '-t',
        '1200',
        '--u',
        '<url>',
      ],
      protocol: 'browser',
    },
    BS_MS_Edge: {
      exe: 'node_modules/.bin/browserstack-launch',
      args: [
        '--os',
        'Windows',
        '--osv',
        '10',
        '--b',
        'edge',
        '--bv',
        'latest',
        '-t',
        '1200',
        '--u',
        '<url>',
      ],
      protocol: 'browser',
    },
  },
  launch_in_dev: [],
  launch_in_ci: [
    'BS_Chrome_Current',
    'BS_Chrome_Last',
    'BS_Firefox_Current',
    'BS_Firefox_Last',
    'BS_Safari_Current',
    'BS_Safari_Last',
    'BS_MS_Edge',
  ],
};
<|endoftext|>