text:
#if !defined(lint) && !defined(LINT)
static char rcsid[] = "$Id: database.c,v 2.8 1994/01/15 20:43:43 vixie Exp $";
#endif

/* vix 26jan87 [RCS has the log]
 */

#include "cron.h"
#define __USE_GNU /* For O_NOFOLLOW */
#include <fcntl.h>
#undef __USE_GNU
#include <sys/stat.h>
#include <sys/file.h>
#include <time.h>

#define TMAX(a,b) ((a)>(b)?(a):(b))

/* Try to get maximum path name -- this isn't really correct, but we're
going to be lazy */

#ifndef PATH_MAX

#ifdef MAXPATHLEN
#define PATH_MAX MAXPATHLEN
#else
#define PATH_MAX 2048
#endif

#endif /* ifndef PATH_MAX */

static	void		process_crontab __P((char *, char *, char *,
					     struct stat *,
					     cron_db *, cron_db *));
#ifdef DEBIAN
static int valid_name (char *filename);
static user *get_next_system_crontab __P((user *));
#endif

void force_rescan_user(cron_db *old_db, cron_db *new_db, const char *fname, time_t old_mtime);

static void add_orphan(const char *uname, const char *fname, const char *tabname);
static void free_orphan(orphan *o);

void
load_database(old_db)
	cron_db		*old_db;
{
        DIR		*dir;
	struct stat	statbuf;
	struct stat	syscron_stat;
	DIR_T   	*dp;
	cron_db		new_db;
	user		*u, *nu;
#ifdef DEBIAN
	struct stat     syscrond_stat;
	struct stat     syscrond_file_stat;

        char            syscrond_fname[PATH_MAX+1];
	int             syscrond_change = 0;
#endif

	Debug(DLOAD, ("[%d] load_database()\n", getpid()))

	/* before we start loading any data, do a stat on SPOOL_DIR
	 * so that if anything changes as of this moment (i.e., before we've
	 * cached any of the database), we'll see the changes next time.
	 */
	if (stat(SPOOL_DIR, &statbuf) < OK) {
		log_it("CRON", getpid(), "STAT FAILED", SPOOL_DIR);
		statbuf.st_mtime = 0;
	}

	/* track system crontab file
	 */
	if (stat(SYSCRONTAB, &syscron_stat) < OK) {
		log_it("CRON", getpid(), "STAT FAILED", SYSCRONTAB);
		syscron_stat.st_mtime = 0;
	}

#ifdef DEBIAN
	/* Check mod time of SYSCRONDIR. This won't tell us if a file
         * in it changed, but will capture deletions, which the individual
         * file check won't
	 */
	if (stat(SYSCRONDIR, &syscrond_stat) < OK) {
		log_it("CRON", getpid(), "STAT FAILED", SYSCRONDIR);
		syscrond_stat.st_mtime = 0;
	}

	/* If SYSCRONDIR was modified, we know that something is changed and
	 * there is no need for any further checks. If it wasn't, we should
	 * pass through the old list of files in SYSCRONDIR and check their
	 * mod time. Therefore a stopped hard drive won't be spun up, since
	 * we avoid reading of SYSCRONDIR and don't change its access time.
	 * This is especially important on laptops with APM.
	 */
	if (old_db->sysd_mtime != syscrond_stat.st_mtime) {
	        syscrond_change = 1;
	} else {
	        /* Look through the individual files */
		user *systab;

		Debug(DLOAD, ("[%d] system dir mtime unch, check files now.\n",
			      getpid()))

		for (systab = old_db->head;
		     (systab = get_next_system_crontab (systab)) != NULL;
		     systab = systab->next) {

			sprintf(syscrond_fname, "%s/%s", SYSCRONDIR,
							 systab->name + 8);

			Debug(DLOAD, ("\t%s:", syscrond_fname))

			if (stat(syscrond_fname, &syscrond_file_stat) < OK)
				syscrond_file_stat.st_mtime = 0;

			if (syscrond_file_stat.st_mtime != systab->mtime ||
				systab->mtime == 0) {
			        syscrond_change = 1;
                        }

			Debug(DLOAD, (" [checked]\n"))
		}
	}
#endif /* DEBIAN */

	/* if spooldir's mtime has not changed, we don't need to fiddle with
	 * the database.
	 *
	 * Note that old_db->mtime is initialized to 0 in main(), and
	 * so is guaranteed to be different than the stat() mtime the first
	 * time this function is called.
	 */
#ifdef DEBIAN
	if ((old_db->user_mtime == statbuf.st_mtime) &&
	    (old_db->sys_mtime == syscron_stat.st_mtime) &&
	    (!syscrond_change)) {
#else
	if ((old_db->user_mtime == statbuf.st_mtime) &&
	    (old_db->sys_mtime == syscron_stat.st_mtime)) {
#endif
		Debug(DLOAD, ("[%d] spool dir mtime unch, no load needed.\n",
			      getpid()))
		return;
	}

	/* something's different.  make a new database, moving unchanged
	 * elements from the old database, reloading elements that have
	 * actually changed.  Whatever is left in the old database when
	 * we're done is chaff -- crontabs that disappeared.
	 */
	new_db.user_mtime = statbuf.st_mtime;
	new_db.sys_mtime = syscron_stat.st_mtime;
#ifdef DEBIAN
	new_db.sysd_mtime = syscrond_stat.st_mtime;
#endif
	new_db.head = new_db.tail = NULL;

	if (syscron_stat.st_mtime) {
		process_crontab(SYSUSERNAME, "*system*",
				SYSCRONTAB, &syscron_stat,
				&new_db, old_db);
	}

#ifdef DEBIAN
	/* Read all the package crontabs. */
	if (!(dir = opendir(SYSCRONDIR))) {
		log_it("CRON", getpid(), "OPENDIR FAILED", SYSCRONDIR);
	}

	while (dir != NULL && NULL != (dp = readdir(dir))) {
		char	fname[MAXNAMLEN+1],
		        tabname[PATH_MAX+1];

		/* avoid file names beginning with ".".  this is good
		 * because we would otherwise waste two guaranteed calls
		 * to stat() for . and .., and also because package names
		 * starting with a period are just too nasty to consider.
		 */
		if (dp->d_name[0] == '.')
			continue;

		/* skipfile names with letters outside the set
		 * [A-Za-z0-9_-], like run-parts.
		 */
		if (!valid_name(dp->d_name))
		  continue;

		/* Generate the "fname" */
		(void) strcpy(fname,"*system*");
		(void) strcat(fname, dp->d_name);
		sprintf(tabname,"%s/%s", SYSCRONDIR, dp->d_name);

		/* statbuf is used as working storage by process_crontab() --
		   current contents are irrelevant */
		process_crontab(SYSUSERNAME, fname, tabname,
				&statbuf, &new_db, old_db);

	}
	if (dir)
		closedir(dir);
#endif

	/* we used to keep this dir open all the time, for the sake of
	 * efficiency.  however, we need to close it in every fork, and
	 * we fork a lot more often than the mtime of the dir changes.
	 */
	if (!(dir = opendir(SPOOL_DIR))) {
		log_it("CRON", getpid(), "OPENDIR FAILED", SPOOL_DIR);
	}

	while (dir != NULL && NULL != (dp = readdir(dir))) {
		char	fname[MAXNAMLEN+1],
			tabname[PATH_MAX+1];

		/* avoid file names beginning with ".".  this is good
		 * because we would otherwise waste two guaranteed calls
		 * to getpwnam() for . and .., and also because user names
		 * starting with a period are just too nasty to consider.
		 */
		if (dp->d_name[0] == '.')
			continue;

		(void) strcpy(fname, dp->d_name);
		snprintf(tabname, PATH_MAX+1, CRON_TAB(fname));

		process_crontab(fname, fname, tabname,
				&statbuf, &new_db, old_db);
	}
	if (dir)
		closedir(dir);

	/* if we don't do this, then when our children eventually call
	 * getpwnam() in do_command.c's child_process to verify MAILTO=,
	 * they will screw us up (and v-v).
	 */
	endpwent();

	/* whatever's left in the old database is now junk.
	 */
	Debug(DLOAD, ("unlinking old database:\n"))
	for (u = old_db->head;  u != NULL;  u = nu) {
		Debug(DLOAD, ("\t%s\n", u->name))
		nu = u->next;
		unlink_user(old_db, u);
		free_user(u);
	}

	/* overwrite the database control block with the new one.
	 */
	*old_db = new_db;
	Debug(DLOAD, ("load_database is done\n"))
}

void
link_user(db, u)
	cron_db	*db;
	user	*u;
{
	if (db->head == NULL)
		db->head = u;
	if (db->tail)
		db->tail->next = u;
	u->prev = db->tail;
	u->next = NULL;
	db->tail = u;
}

void
unlink_user(db, u)
	cron_db	*db;
	user	*u;
{
	if (u->prev == NULL)
		db->head = u->next;
	else
		u->prev->next = u->next;

	if (u->next == NULL)
		db->tail = u->prev;
	else
		u->next->prev = u->prev;
}

user *
find_user(db, name)
	cron_db	*db;
	char	*name;
{
	char	*env_get();
	user	*u;

	for (u = db->head;  u != NULL;  u = u->next)
		if (!strcmp(u->name, name))
			break;
	return u;
}

static void
process_crontab(uname, fname, tabname, statbuf, new_db, old_db)
	char		*uname;
	char		*fname;
	char		*tabname;
	struct stat	*statbuf;
	cron_db		*new_db;
	cron_db		*old_db;
{
	struct passwd	*pw = NULL;
	int		crontab_fd = OK - 1;
	user		*u = NULL;

#ifdef DEBIAN
	/* If the name begins with *system*, don't worry about password -
	 it's part of the system crontab */
	if (strncmp(fname, "*system*", 8) && !(pw = getpwnam(uname))) {
#else
	if (strcmp(fname, "*system*") && !(pw = getpwnam(uname))) {
#endif
		/* file doesn't have a user in passwd file.
		 */
		if (strncmp(fname, "tmp.", 4)) {
			/* don't log these temporary files */
			log_it(fname, getpid(), "ORPHAN", "no passwd entry");
			add_orphan(uname, fname, tabname);
		}
		goto next_crontab;
	}

        if (pw) {
            /* Path for user crontabs (including root's!) */
            if ((crontab_fd = open(tabname, O_RDONLY|O_NOFOLLOW, 0)) < OK) {
		/* crontab not accessible?
		 */
		log_it(fname, getpid(), "CAN'T OPEN", tabname);
		goto next_crontab;
            }

            if (fstat(crontab_fd, statbuf) < OK) {
		log_it(fname, getpid(), "FSTAT FAILED", tabname);
		goto next_crontab;
            }
            /* Check to make sure that the crontab is owned by the correct user
               (or root) */
            if (statbuf->st_uid != pw->pw_uid && statbuf->st_uid != ROOT_UID) {
                log_it(fname, getpid(), "WRONG FILE OWNER", tabname);
                force_rescan_user(old_db, new_db, fname, 0);
		goto next_crontab;
            }

	    /* Check to make sure that the crontab is a regular file */
            if (!S_ISREG(statbuf->st_mode)) {
		log_it(fname, getpid(), "NOT A REGULAR FILE", tabname);
		goto next_crontab;
	    }

	    /* Check to make sure that the crontab's permissions are secure */
            if ((statbuf->st_mode & 07777) != 0600) {
		log_it(fname, getpid(), "INSECURE MODE (mode 0600 expected)", tabname);
                force_rescan_user(old_db, new_db, fname, 0);
		goto next_crontab;
	    }

	    /* Check to make sure that there are no hardlinks to the crontab */
            if (statbuf->st_nlink != 1) {
		log_it(fname, getpid(), "NUMBER OF HARD LINKS > 1", tabname);
                force_rescan_user(old_db, new_db, fname, 0);
		goto next_crontab;
	    }
        } else {
            /* System crontab path. These can be symlinks, but the
               symlink and the target must be owned by root. */
            if (lstat(tabname, statbuf) < OK) {
		log_it(fname, getpid(), "LSTAT FAILED", tabname);
		goto next_crontab;
            }
            if (S_ISLNK(statbuf->st_mode) && statbuf->st_uid != ROOT_UID) {
                log_it(fname, getpid(), "WRONG SYMLINK OWNER", tabname);
                force_rescan_user(old_db, new_db, fname, 0);
		goto next_crontab;
            }
            if ((crontab_fd = open(tabname, O_RDONLY, 0)) < OK) {
		/* crontab not accessible?

		   If tabname is a symlink, it's most probably just broken, so
		   we force a rescan. Once the link is fixed, it will get picked
		   up and processed again. If tabname is a regular file, this
		   error is bad so we skip it instead.
		 */
		if (S_ISLNK(statbuf->st_mode)) {
                    log_it(fname, getpid(), "CAN'T OPEN SYMLINK", tabname);
                    force_rescan_user(old_db, new_db, fname, 0);
                    goto next_crontab;
                } else {
		    log_it(fname, getpid(), "CAN'T OPEN", tabname);
		    goto next_crontab;
		}
            }

            if (fstat(crontab_fd, statbuf) < OK) {
		log_it(fname, getpid(), "FSTAT FAILED", tabname);
		goto next_crontab;
            }

            /* Check to make sure that the crontab is owned by root */
            if (statbuf->st_uid != ROOT_UID) {
                log_it(fname, getpid(), "WRONG FILE OWNER", tabname);
                force_rescan_user(old_db, new_db, fname, 0);
		goto next_crontab;
            }

            /* Check to make sure that the crontab is a regular file */
            if (!S_ISREG(statbuf->st_mode)) {
		log_it(fname, getpid(), "NOT A REGULAR FILE", tabname);
		goto next_crontab;
	    }

            /* Check to make sure that the crontab is writable only by root
	     * This should really be in sync with the check for users above
	     * (mode 0600). An upgrade path could be implemented for 4.1
	     */
	    if ((statbuf->st_mode & S_IWGRP) || (statbuf->st_mode & S_IWOTH)) {
		log_it(fname, getpid(), "INSECURE MODE (group/other writable)", tabname);
                force_rescan_user(old_db, new_db, fname, 0);
		goto next_crontab;
	    }
            /* Technically, we should also check whether the parent dir is
 	     * writable, and so on. This would only make proper sense for
 	     * regular files; we can't realistically check all possible
 	     * security issues resulting from symlinks. We'll just assume that
 	     * root will handle responsible when creating them.
	     */

	    /* Check to make sure that there are no hardlinks to the crontab */
            if (statbuf->st_nlink != 1) {
		log_it(fname, getpid(), "NUMBER OF HARD LINKS > 1", tabname);
                force_rescan_user(old_db, new_db, fname, 0);
		goto next_crontab;
	    }
        }
        /*
         * The link count check is not sufficient (the owner may
         * delete their original link, reducing the link count back to
         * 1), but this is all we've got.
         */
	Debug(DLOAD, ("\t%s:", fname))

	if (old_db != NULL)
		u = find_user(old_db, fname);

	if (u != NULL) {
		/* if crontab has not changed since we last read it
		 * in, then we can just use our existing entry.
		 */
		if (u->mtime == statbuf->st_mtime) {
			Debug(DLOAD, (" [no change, using old data]"))
			unlink_user(old_db, u);
			link_user(new_db, u);
			goto next_crontab;
		}

		/* before we fall through to the code that will reload
		 * the user, let's deallocate and unlink the user in
		 * the old database.  This is more a point of memory
		 * efficiency than anything else, since all leftover
		 * users will be deleted from the old database when
		 * we finish with the crontab...
		 */
		Debug(DLOAD, (" [delete old data]"))
		unlink_user(old_db, u);
		free_user(u);
		log_it(fname, getpid(), "RELOAD", tabname);
	}

	u = load_user(crontab_fd, pw, uname, fname, tabname);
	if (u != NULL) {
		u->mtime = statbuf->st_mtime;
		link_user(new_db, u);
        } else {
                /* The crontab we attempted to load contains a syntax error. A
                 * fix won't get picked up by the regular change detection
                 * code, so we force a rescan. statbuf->st_mtime still contains
                 * the file's mtime, so we use it to rescan only when an update
                 * has actually taken place.
                 */
                force_rescan_user(old_db, new_db, fname, statbuf->st_mtime);
        }

next_crontab:
	if (crontab_fd >= OK) {
		Debug(DLOAD, (" [done]\n"))
		close(crontab_fd);
	}
}

#ifdef DEBIAN

#include <regex.h>

/* True or false? Is this a valid filename? */

/* Taken from Clint Adams 'run-parts' version to support lsb style
   names, originally GPL, but relicensed to cron license per e-mail of
   27 September 2003. I've changed it to do regcomp() only once. */

static int
valid_name(char *filename)
{
  static regex_t hierre, tradre, excsre, classicalre;
  static int donere = 0;

  if (!donere) {
      donere = 1;
      if (regcomp(&hierre, "^_?([a-z0-9_.]+-)+[a-z0-9]+$",
                  REG_EXTENDED | REG_NOSUB)
          || regcomp(&excsre, "^[a-z0-9-].*dpkg-(old|dist)$",
                     REG_EXTENDED | REG_NOSUB)
          || regcomp(&tradre, "^[a-z0-9][a-z0-9-]*$", REG_NOSUB)
          || regcomp(&classicalre, "^[a-zA-Z0-9_-]+$",
                     REG_EXTENDED | REG_NOSUB)) {
          log_it("CRON", getpid(), "REGEX FAILED", "valid_name");
          (void) exit(ERROR_EXIT);
      }
  }
  if (lsbsysinit_mode) {
      if (!regexec(&hierre, filename, 0, NULL, 0)) {
          return regexec(&excsre, filename, 0, NULL, 0);
      } else {
          return !regexec(&tradre, filename, 0, NULL, 0);
      }
  }
  /* Old standard style */
  return !regexec(&classicalre, filename, 0, NULL, 0);
}

static user *
get_next_system_crontab (curtab)
	user	*curtab;
{
	for ( ; curtab != NULL; curtab = curtab->next)
		if (!strncmp(curtab->name, "*system*", 8) && curtab->name [8])
			break;
	return curtab;
}

#endif

/* Force rescan of a crontab the next time cron wakes up
 *
 * cron currently only detects changes caused by an mtime update; it does not
 * detect other attribute changes such as UID or mode. To allow cron to recover
 * from errors of that nature as well, this function removes the crontab from
 * the old DB (if present there) and adds an empty crontab to the new DB with
 * a given mtime. Specifying mtime as 0 will force a rescan the next time the
 * daemon wakes up.
 */
void
force_rescan_user(cron_db *old_db, cron_db *new_db, const char *fname, time_t old_mtime)
{
        user *u;

	/* Remove from old DB and free resources */
	u = find_user(old_db, fname);
	if (u != NULL) {
		Debug(DLOAD, (" [delete old data]"))
		unlink_user(old_db, u);
		free_user(u);
	}

	/* Allocate an empty crontab with the specified mtime, add it to new DB */
        if ((u = (user *) malloc(sizeof(user))) == NULL) {
                errno = ENOMEM;
        }
        if ((u->name = strdup(fname)) == NULL) {
                free(u);
                errno = ENOMEM;
        }
        u->mtime = old_mtime;
        u->crontab = NULL;
#ifdef WITH_SELINUX
        u->scontext = NULL;
#endif
        Debug(DLOAD, ("\t%s: [added empty placeholder to force rescan]\n", fname))
	link_user(new_db, u);
}

/* This fix was taken from Fedora cronie */
static orphan *orphans;

static void
free_orphan(orphan *o) {
        free(o->tabname);
        free(o->fname);
        free(o->uname);
        free(o);
}

void
check_orphans(cron_db *db) {
        orphan *prev_orphan = NULL;
        orphan *o = orphans;
	struct stat statbuf;

        while (o != NULL) {
                if (getpwnam(o->uname) != NULL) {
                        orphan *next = o->next;

                        if (prev_orphan == NULL) {
                                orphans = next;
                        } else {
                                prev_orphan->next = next;
                        }

                        process_crontab(o->uname, o->fname, o->tabname,
                                &statbuf, db, NULL);

                        /* process_crontab could have added a new orphan */
                        if (prev_orphan == NULL && orphans != next) {
                                prev_orphan = orphans;
                        }
                        free_orphan(o);
                        o = next;
                } else {
                        prev_orphan = o;
                        o = o->next;
                }
        }
}

static void
add_orphan(const char *uname, const char *fname, const char *tabname) {
        orphan *o;

        o = calloc(1, sizeof(*o));
        if (o == NULL)
                return;

        if (uname)
                if ((o->uname=strdup(uname)) == NULL)
                        goto cleanup;

        if (fname)
                if ((o->fname=strdup(fname)) == NULL)
                        goto cleanup;

        if (tabname)
                if ((o->tabname=strdup(tabname)) == NULL)
                        goto cleanup;

        o->next = orphans;
        orphans = o;
        return;

cleanup:
        free_orphan(o);
}


text:
ExchangeDialog::ExchangeDialog(QtDataSync::AccountManager *manager, QWidget *parent) :
	QDialog(parent),
	ui(new Ui::ExchangeDialog),
	_manager(new QtDataSync::UserExchangeManager(manager, this))
{
	ui->setupUi(this);
	ui->portSpinBox->setValue(QtDataSync::UserExchangeManager::DataExchangePort);

	connect(_manager, &QtDataSync::UserExchangeManager::activeChanged,
			ui->activeCheckBox, &QCheckBox::setChecked);
	connect(_manager, &QtDataSync::UserExchangeManager::devicesChanged,
			this, &ExchangeDialog::devicesChanged);
	connect(_manager, &QtDataSync::UserExchangeManager::userDataReceived,
			this, &ExchangeDialog::userDataReceived);
	connect(_manager, &QtDataSync::UserExchangeManager::exchangeError,
			this, &ExchangeDialog::exchangeError);
}

ExchangeDialog::~ExchangeDialog()
{
	delete ui;
}

void ExchangeDialog::exec(QtDataSync::AccountManager *manager, QWidget *parent)
{
	ExchangeDialog dialog(manager, parent);
	dialog.QDialog::exec();
}

void ExchangeDialog::devicesChanged(QList<QtDataSync::UserInfo> devices)
{
	ui->treeWidget->clear();
	for(auto dev : devices) {
		auto item = new QTreeWidgetItem(ui->treeWidget);
		item->setText(0, dev.name());
		item->setText(1, QStringLiteral("%1:%2").arg(dev.address().toString()).arg(dev.port()));
		item->setData(1, Qt::UserRole + 1, QVariant::fromValue(dev));
	}
}

void ExchangeDialog::userDataReceived(const QtDataSync::UserInfo &userInfo, bool trusted)
{
	if(trusted) {
		auto ok = false;
		auto pw = QInputDialog::getText(this,
										tr("Import trusted data"),
										tr("Import data from %1. Enter the shared password:").arg(userInfo.name()),
										QLineEdit::Password,
										QString(),
										&ok);
		if(ok)
			_manager->importTrustedFrom(userInfo, pw, [this](bool ok, QString e) {
				if(ok)
					QMessageBox::information(this, tr("Import trusted data"), tr("Import succeeded!"));
				else
					QMessageBox::critical(this, tr("Import trusted data"), tr("Import failed with error:\n%1").arg(e));
			});
	} else {
		auto ok = QMessageBox::question(this,
										tr("Import untrusted data"),
										tr("Import data from %1?").arg(userInfo.name()));
		if(ok == QMessageBox::Yes)
			_manager->importFrom(userInfo, [this](bool ok, QString e) {
				if(ok)
					QMessageBox::information(this, tr("Import untrusted data"), tr("Import succeeded!"));
				else
					QMessageBox::critical(this, tr("Import untrusted data"), tr("Import failed with error:\n%1").arg(e));
			});
	}
}

void ExchangeDialog::exchangeError(const QString &errorString)
{
	QMessageBox::critical(this, tr("Exchange error"), errorString);
}

void ExchangeDialog::on_treeWidget_itemActivated(QTreeWidgetItem *item, int column)
{
	Q_UNUSED(column)
	if(item) {
		auto dev = item->data(1, Qt::UserRole + 1).value<QtDataSync::UserInfo>();
		auto pw = QInputDialog::getText(this,
										tr("Secure export data"),
										tr("Export data to %1. Enter a password or send untrusted:").arg(dev.name()),
										QLineEdit::Password);
		if(pw.isEmpty())
			_manager->exportTo(dev, false);
		else
			_manager->exportTrustedTo(dev, false, pw);
	}
}

void ExchangeDialog::on_activeCheckBox_clicked(bool checked)
{
	if(checked){
		if(_manager->startExchange(QHostAddress::Any, (quint16)ui->portSpinBox->value()))
			ui->portSpinBox->setValue(_manager->port());
		else
			ui->activeCheckBox->setChecked(false);
	} else
		_manager->stopExchange();
}

redpajama_set_name: RedPajamaGithub


text:
async function projectFolders(): Promise<void> {
  const { showFolder, warn } = await import('../util');

  const projectPaths: string[] = atom.project.getPaths();

  if (projectPaths.length === 0) {
    return warn('Editor has no projects');
  }

  projectPaths.map( projectPath => {
    if (!projectPath.startsWith('atom://')) {
      showFolder({
        name: 'Project Folder',
        path: projectPath
      });
    }
  });
}

export {
  projectFolders
};


text:
import React from 'react';
import _ from 'lodash';
import { shallow } from 'enzyme';
import * as stat from '../../src/utils/stat';
import {
  BG_COLORS,
  MS_IN_DAY,
  MS_IN_HOUR,
  MS_IN_MIN,
  MGDL_UNITS,
  MMOLL_UNITS,
} from '../../src/utils/constants';

/* eslint-disable max-len */

describe('stat', () => {
  const {
    commonStats,
    dailyDoseUnitOptions,
    statFormats,
    statTypes,
  } = stat;

  describe('dailyDoseUnitOptions', () => {
    it('should export the `dailyDoseUnitOptions`', () => {
      expect(stat.dailyDoseUnitOptions).to.be.an('array').and.have.length(2);

      expect(stat.dailyDoseUnitOptions[0]).to.eql({
        label: 'kg',
        value: 'kg',
      });

      expect(stat.dailyDoseUnitOptions[1]).to.eql({
        label: 'lb',
        value: 'lb',
      });
    });
  });

  describe('statTypes', () => {
    it('should export the `statTypes`', () => {
      expect(stat.statTypes).to.eql({
        barHorizontal: 'barHorizontal',
        barBg: 'barBg',
        input: 'input',
        simple: 'simple',
      });
    });
  });

  describe('statBgSourceLabels', () => {
    it('should export the `statBgSourceLabels`', () => {
      expect(stat.statBgSourceLabels).to.eql({
        cbg: 'CGM',
        smbg: 'BGM',
      });
    });
  });

  describe('statFormats', () => {
    it('should export the `statFormats`', () => {
      expect(stat.statFormats).to.eql({
        bgCount: 'bgCount',
        bgRange: 'bgRange',
        bgValue: 'bgValue',
        cv: 'cv',
        carbs: 'carbs',
        duration: 'duration',
        gmi: 'gmi',
        percentage: 'percentage',
        standardDevRange: 'standardDevRange',
        standardDevValue: 'standardDevValue',
        units: 'units',
        unitsPerKg: 'unitsPerKg',
      });
    });
  });

  describe('commonStats', () => {
    it('should export the `commonStats`', () => {
      expect(stat.commonStats).to.eql({
        averageGlucose: 'averageGlucose',
        averageDailyDose: 'averageDailyDose',
        bgExtents: 'bgExtents',
        carbs: 'carbs',
        coefficientOfVariation: 'coefficientOfVariation',
        glucoseManagementIndicator: 'glucoseManagementIndicator',
        readingsInRange: 'readingsInRange',
        sensorUsage: 'sensorUsage',
        standardDev: 'standardDev',
        timeInAuto: 'timeInAuto',
        timeInOverride: 'timeInOverride',
        timeInRange: 'timeInRange',
        totalInsulin: 'totalInsulin',
      });
    });
  });

  describe('statFetchMethods', () => {
    it('should export the common `statFetchMethods`', () => {
      expect(stat.statFetchMethods).to.eql({
        averageGlucose: 'getAverageGlucoseData',
        averageDailyDose: 'getTotalInsulinData',
        bgExtents: 'getBgExtentsData',
        carbs: 'getCarbsData',
        coefficientOfVariation: 'getCoefficientOfVariationData',
        glucoseManagementIndicator: 'getGlucoseManagementIndicatorData',
        readingsInRange: 'getReadingsInRangeData',
        sensorUsage: 'getSensorUsage',
        standardDev: 'getStandardDevData',
        timeInAuto: 'getTimeInAutoData',
        timeInOverride: 'getTimeInOverrideData',
        timeInRange: 'getTimeInRangeData',
        totalInsulin: 'getBasalBolusData',
      });
    });
  });

  describe('getSum', () => {
    it('should sum up datum values by their `value` key', () => {
      const data = [
        {
          value: 1,
        },
        {
          value: 2,
        },
        {
          value: 3.5,
        },
      ];
      expect(stat.getSum(data)).to.equal(6.5);
    });
  });

  describe('ensureNumeric', () => {
    it('should parse incoming values as floats', () => {
      expect(stat.ensureNumeric('6.5')).to.equal(6.5);
      expect(stat.ensureNumeric(6.0)).to.equal(6);
    });

    it('should convert `NaN`, `null`, or `undefined` to `-1`', () => {
      expect(stat.ensureNumeric(NaN)).to.equal(-1);
      expect(stat.ensureNumeric(null)).to.equal(-1);
      expect(stat.ensureNumeric(undefined)).to.equal(-1);
    });
  });

  describe('formatDatum', () => {
    const defaultData = {
      data: [
        {
          value: 60,
          id: 'low',
        },
        {
          value: 120,
        },
      ],
      total: {
        value: 2,
      },
    };

    const defaultOpts = {
      data: defaultData,
    };

    const opts = overrides => _.assign({}, defaultOpts, overrides);

    context('bgCount format', () => {
      it('should return correctly formatted data when `value >= 0.05`', () => {
        expect(stat.formatDatum({
          value: 2.67777777,
        }, statFormats.bgCount)).to.include({
          value: 2.7,
        });

        expect(stat.formatDatum({
          value: 0.05,
        }, statFormats.bgCount)).to.include({
          value: 0.1,
        });

        // Want 0 decimal places if would end in `.0`
        expect(stat.formatDatum({
          value: 3.0000001,
        }, statFormats.bgCount)).to.include({
          value: 3,
        });
      });

      it('should return correctly formatted data when `value < 0.05`', () => {
        expect(stat.formatDatum({
          value: 0.035,
        }, statFormats.bgCount)).to.include({
          value: 0.04,
        });
      });

      it('should return the empty placeholder text and id when `value < 0`', () => {
        expect(stat.formatDatum({
          value: -1,
        }, statFormats.bgCount)).to.include({
          id: 'statDisabled',
          value: '--',
        });
      });
    });

    context('bgRange format', () => {
      const customOpts = opts({
          bgPrefs: {
            bgUnits: MGDL_UNITS,
            bgBounds: {
              veryLowThreshold: 39,
              targetLowerBound: 70,
              targetUpperBound: 180,
              veryHighThreshold: 250,
            },
          },
        });

      it('should return correctly formatted bg range for a given `datum.id`', () => {
        expect(stat.formatDatum({
          id: 'veryLow',
        }, statFormats.bgRange, customOpts)).to.include({
          value: '<39',
        });

        expect(stat.formatDatum({
          id: 'low',
        }, statFormats.bgRange, customOpts)).to.include({
          value: '39-70',
        });

        expect(stat.formatDatum({
          id: 'target',
        }, statFormats.bgRange, customOpts)).to.include({
          value: '70-180',
        });

        expect(stat.formatDatum({
          id: 'high',
        }, statFormats.bgRange, customOpts)).to.include({
          value: '180-250',
        });

        expect(stat.formatDatum({
          id: 'veryHigh',
        }, statFormats.bgRange, customOpts)).to.include({
          value: '>250',
        });
      });
    });

    context('bgValue format', () => {
      it('should classify and format a datum when `value >= 0` for mg/dL units', () => {
        const customOpts = opts({
          bgPrefs: {
            bgUnits: MGDL_UNITS,
            bgBounds: {
              veryLowThreshold: 39,
              targetLowerBound: 70,
              targetUpperBound: 180,
              veryHighThreshold: 250,
            },
          },
        });

        // Using 3-way classification, so both `low` and `veryLow` are classified as `low`
        expect(stat.formatDatum({
          value: 35.8,
        }, statFormats.bgValue, customOpts)).to.include({
          id: 'low',
          value: '36',
        });

        expect(stat.formatDatum({
          value: 68.2,
        }, statFormats.bgValue, customOpts)).to.include({
          id: 'low',
          value: '68',
        });

        expect(stat.formatDatum({
          value: 100,
        }, statFormats.bgValue, customOpts)).to.include({
          id: 'target',
          value: '100',
        });

        // Using 3-way classification, so both `high` and `veryHigh` are classified as `high`
        expect(stat.formatDatum({
          value: 200,
        }, statFormats.bgValue, customOpts)).to.include({
          id: 'high',
          value: '200',
        });

        expect(stat.formatDatum({
          value: 252,
        }, statFormats.bgValue, customOpts)).to.include({
          id: 'high',
          value: '252',
        });
      });

      it('should classify and format a datum when `value >= 0` for mmol/L units', () => {
        const customOpts = opts({
          bgPrefs: {
            bgUnits: MMOLL_UNITS,
            bgBounds: {
              veryLowThreshold: 3.0,
              targetLowerBound: 3.9,
              targetUpperBound: 10.0,
              veryHighThreshold: 13.9,
            },
          },
        });

        // Using 3-way classification, so both `low` and `veryLow` are classified as `low`
        expect(stat.formatDatum({
          value: 2.86,
        }, statFormats.bgValue, customOpts)).to.include({
          id: 'low',
          value: '2.9',
        });

        expect(stat.formatDatum({
          value: 3.62,
        }, statFormats.bgValue, customOpts)).to.include({
          id: 'low',
          value: '3.6',
        });

        expect(stat.formatDatum({
          value: 7,
        }, statFormats.bgValue, customOpts)).to.include({
          id: 'target',
          value: '7.0',
        });

        // Using 3-way classification, so both `high` and `veryHigh` are classified as `high`
        expect(stat.formatDatum({
          value: 12.3,
        }, statFormats.bgValue, customOpts)).to.include({
          id: 'high',
          value: '12.3',
        });

        expect(stat.formatDatum({
          value: 14.1,
        }, statFormats.bgValue, customOpts)).to.include({
          id: 'high',
          value: '14.1',
        });
      });

      it('should return the empty placeholder text and id when `value < 0`', () => {
        expect(stat.formatDatum({
          value: -1,
        }, statFormats.bgValue)).to.include({
          id: 'statDisabled',
          value: '--',
        });
      });
    });

    context('carbs format', () => {
      it('should return correctly formatted carb data in grams or exchanges when `value > 0`', () => {
        const onlyGrams = stat.formatDatum({
          value: {
            grams: 84.645,
            exchanges: 0,
          },
        }, statFormats.carbs);

        expect(onlyGrams.suffix).to.be.an('array').and.have.members(['g']);
        expect(onlyGrams.value).to.be.an('array').and.have.members(['85']);

        const onlyExchanges = stat.formatDatum({
          value: {
            grams: 0,
            exchanges: 6.25,
          },
        }, statFormats.carbs);

        expect(onlyExchanges.suffix).to.be.an('array').and.have.members(['exch']);
        expect(onlyExchanges.value).to.be.an('array').and.have.members([6.3]);

        const carbsAndExchanges = stat.formatDatum({
          value: {
            grams: 84.645,
            exchanges: 2,
          },
        }, statFormats.carbs);

        expect(carbsAndExchanges.suffix).to.be.an('array').and.have.members(['g', 'exch']);
        expect(carbsAndExchanges.value).to.be.an('array').and.have.members(['85', 2]);
      });

      it('should return the empty placeholder text and id when neither grams nor exchange values are > 0', () => {
        expect(stat.formatDatum({
          value: {
            grams: 0,
            exchanges: 0,
          },
        }, statFormats.carbs)).to.include({
          id: 'statDisabled',
          value: '--',
        });
      });
    });

    context('cv format', () => {
      it('should return correctly classified and formatted data when `value >= 0`', () => {
        expect(stat.formatDatum({
          value: 35.8,
        }, statFormats.cv)).to.include({
          id: 'target',
          suffix: '%',
          value: '36',
        });

        expect(stat.formatDatum({
          value: 36.2,
        }, statFormats.cv)).to.include({
          id: 'high',
          suffix: '%',
          value: '36',
        });
      });

      it('should return the empty placeholder text and id when `value < 0`', () => {
        expect(stat.formatDatum({
          value: -1,
        }, statFormats.cv)).to.include({
          id: 'statDisabled',
          value: '--',
        });
      });
    });

    context('duration format', () => {
      it('should return correctly formatted data when `value >= 0`', () => {
        expect(stat.formatDatum({
          value: MS_IN_DAY + MS_IN_HOUR + MS_IN_MIN,
        }, statFormats.duration)).to.include({
          value: '1d 1h 1m',
        });

        expect(stat.formatDatum({
          value: MS_IN_HOUR * 3 + MS_IN_MIN,
        }, statFormats.duration)).to.include({
          value: '3h 1m',
        });

        expect(stat.formatDatum({
          value: MS_IN_MIN * 48,
        }, statFormats.duration)).to.include({
          value: '48m',
        });

        // show seconds only when less than a minute
        expect(stat.formatDatum({
          value: 6000,
        }, statFormats.duration)).to.include({
          value: '6s',
        });

        // show 0m for 0
        expect(stat.formatDatum({
          value: 0,
        }, statFormats.duration)).to.include({
          value: '0m',
        });
      });

      it('should return the empty placeholder text and id when `value < 0`', () => {
        expect(stat.formatDatum({
          value: -1,
        }, statFormats.duration)).to.include({
          id: 'statDisabled',
          value: '--',
        });
      });
    });

    context('gmi format', () => {
      it('should return correctly formatted data when `value >= 0`', () => {
        expect(stat.formatDatum({
          value: 35.85,
        }, statFormats.gmi)).to.include({
          suffix: '%',
          value: '35.9',
        });
      });

      it('should return the empty placeholder text and id when `value < 0`', () => {
        expect(stat.formatDatum({
          value: -1,
        }, statFormats.gmi)).to.include({
          id: 'statDisabled',
          value: '--',
        });
      });
    });

    context('percentage format', () => {
      it('should return correctly formatted data when `total` prop is `>= 0`', () => {
        const customOpts = opts({
          data: {
            total: {
              value: 10,
            },
          },
        });

        // No decimal places when `% >= 0.5`
        expect(stat.formatDatum({
          value: 3.95,
        }, statFormats.percentage, customOpts)).to.include({
          value: '40',
          suffix: '%',
        });

        // 1 decimal place when `% < 0.5` and `% >= 0.05`
        expect(stat.formatDatum({
          value: 0.049,
        }, statFormats.percentage, customOpts)).to.include({
          value: '0.5',
          suffix: '%',
        });

        // 1 decimal places when `% < 0.05`
        expect(stat.formatDatum({
          value: 0.0049,
        }, statFormats.percentage, customOpts)).to.include({
          value: '0.05',
          suffix: '%',
        });
      });

      it('should return the empty placeholder text and id when `value < 0`', () => {
        const customOpts = opts({
          data: {
            total: {
              value: -1,
            },
          },
        });

        expect(stat.formatDatum({
          value: 10,
        }, statFormats.percentage, customOpts)).to.include({
          id: 'statDisabled',
          value: '--',
        });
      });
    });

    context('standardDevRange format', () => {
      const renderResult = result => {
        const Component = () => result.value;
        const render = shallow(<Component />);

        return {
          lower: {
            color: render.childAt(0).props().style.color,
            value: render.childAt(0).props().children,
          },
          upper: {
            color: render.childAt(2).props().style.color,
            value: render.childAt(2).props().children,
          },
        };
      };

      it('should return correctly formatted html when `value >= 0` && `deviation.value >= 0` for mg/dL units', () => {
        const customOpts = opts({
          bgPrefs: {
            bgUnits: MGDL_UNITS,
            bgBounds: {
              veryLowThreshold: 39,
              targetLowerBound: 70,
              targetUpperBound: 180,
              veryHighThreshold: 250,
            },
          },
        });

        expect(renderResult(stat.formatDatum({
          value: 56,
          deviation: { value: 20 },
        }, statFormats.standardDevRange, customOpts))).to.eql({
          lower: {
            color: BG_COLORS.low,
            value: '36',
          },
          upper: {
            color: BG_COLORS.target,
            value: '76',
          },
        });

        expect(renderResult(stat.formatDatum({
          value: 160,
          deviation: { value: 30 },
        }, statFormats.standardDevRange, customOpts))).to.eql({
          lower: {
            color: BG_COLORS.target,
            value: '130',
          },
          upper: {
            color: BG_COLORS.high,
            value: '190',
          },
        });
      });

      it('should return correctly formatted html when `value >= 0` && `deviation.value >= 0` for mg/dL units', () => {
        const customOpts = opts({
          bgPrefs: {
            bgUnits: MMOLL_UNITS,
            bgBounds: {
              veryLowThreshold: 3.0,
              targetLowerBound: 3.9,
              targetUpperBound: 10.0,
              veryHighThreshold: 13.9,
            },
          },
        });

        expect(renderResult(stat.formatDatum({
          value: 3.8,
          deviation: { value: 1 },
        }, statFormats.standardDevRange, customOpts))).to.eql({
          lower: {
            color: BG_COLORS.low,
            value: '2.8',
          },
          upper: {
            color: BG_COLORS.target,
            value: '4.8',
          },
        });

        expect(renderResult(stat.formatDatum({
          value: 10.2,
          deviation: { value: 1.5 },
        }, statFormats.standardDevRange, customOpts))).to.eql({
          lower: {
            color: BG_COLORS.target,
            value: '8.7',
          },
          upper: {
            color: BG_COLORS.high,
            value: '11.7',
          },
        });
      });

      it('should return the empty placeholder text and id when `value < 0` || `deviation.value < 0`', () => {
        expect(stat.formatDatum({
          value: -1,
          deviation: { value: 10 },
        }, statFormats.standardDevRange)).to.include({
          id: 'statDisabled',
          value: '--',
        });

        expect(stat.formatDatum({
          value: 10,
          deviation: { value: -1 },
        }, statFormats.standardDevRange)).to.include({
          id: 'statDisabled',
          value: '--',
        });
      });
    });

    context('standardDevValue format', () => {
      it('should return correctly formatted data when `value >= 0` for mg/dL units', () => {
        const customOpts = opts({
          bgPrefs: {
            bgUnits: MGDL_UNITS,
          },
        });

        expect(stat.formatDatum({
          value: 42.85,
        }, statFormats.standardDevValue, customOpts)).to.include({
          value: '43',
        });
      });

      it('should return correctly formatted data when `value >= 0` for mmol/L units', () => {
        const customOpts = opts({
          bgPrefs: {
            bgUnits: MMOLL_UNITS,
          },
        });

        expect(stat.formatDatum({
          value: 15.86,
        }, statFormats.standardDevValue, customOpts)).to.include({
          value: '15.9',
        });
      });

      it('should return the empty placeholder text and id when `value < 0`', () => {
        expect(stat.formatDatum({
          value: -1,
        }, statFormats.standardDevValue)).to.include({
          id: 'statDisabled',
          value: '--',
        });
      });
    });

    context('units format', () => {
      it('should return correctly formatted data when `value >= 0`', () => {
        expect(stat.formatDatum({
          value: 47.234,
        }, statFormats.units)).to.include({
          value: '47.2',
          suffix: 'U',
        });
      });

      it('should return the empty placeholder text and id when `value < 0`', () => {
        expect(stat.formatDatum({
          value: -1,
        }, statFormats.units)).to.include({
          id: 'statDisabled',
          value: '--',
        });
      });
    });

    context('unitsPerKg format', () => {
      it('should return correctly formatted data when `value >= 0`', () => {
        expect(stat.formatDatum({
          value: 10.678,
          suffix: 'kg',
        }, statFormats.unitsPerKg)).to.include({
          value: '10.68',
          suffix: 'U/kg',
        });

        expect(stat.formatDatum({
          value: 11,
          suffix: 'kg',
        }, statFormats.unitsPerKg)).to.include({
          value: '11.00',
          suffix: 'U/kg',
        });
      });

      it('should convert `lb` values to `kg` by multiplying 2.2046226218, and format to 2 decimal places', () => {
        expect(stat.formatDatum({
          value: 1,
          suffix: 'lb',
        }, statFormats.unitsPerKg)).to.include({
          value: '2.20',
          suffix: 'U/kg',
        });
      });

      it('should return the empty placeholder text and id when `value < 0`', () => {
        expect(stat.formatDatum({
          value: -1,
        }, statFormats.unitsPerKg)).to.include({
          id: 'statDisabled',
          value: '--',
        });
      });
    });
  });

  describe('getStatAnnotations', () => {
    const defaultOpts = {
      manufacturer: 'medtronic',
    };

    const opts = overrides => _.assign({}, defaultOpts, overrides);

    const cbgOpts = opts({ bgSource: 'cbg' });
    const smbgOpts = opts({ bgSource: 'smbg' });
    const singleDayOpts = opts({ days: 1 });
    const multiDayOpts = opts({ days: 14 });

    const data = { total: 10 };

    describe('averageGlucose', () => {
      it('should return annotations for `averageGlucose` stat when bgSource is `smgb`', () => {
        expect(stat.getStatAnnotations(data, commonStats.averageGlucose, smbgOpts)).to.have.ordered.members([
          '**Avg. Glucose (BGM):** All BGM glucose values added together, divided by the number of readings.',
          'Derived from _**10**_ BGM readings.',
        ]);
      });

      it('should return annotations for `averageGlucose` stat when bgSource is `cbg`', () => {
        expect(stat.getStatAnnotations(data, commonStats.averageGlucose, cbgOpts)).to.have.ordered.members([
          '**Avg. Glucose (CGM):** All CGM glucose values added together, divided by the number of readings.',
        ]);
      });
    });

    describe('averageDailyDose', () => {
      it('should return annotations for `averageDailyDose` stat when viewing a single day of data', () => {
        expect(stat.getStatAnnotations(data, commonStats.averageDailyDose, singleDayOpts)).to.have.ordered.members([
          '**Daily Insulin:** All basal and bolus insulin delivery (in Units) added together.',
        ]);
      });

      it('should return annotations for `averageDailyDose` stat when viewing multiple days of data', () => {
        expect(stat.getStatAnnotations(data, commonStats.averageDailyDose, multiDayOpts)).to.have.ordered.members([
          '**Avg. Daily Insulin:** All basal and bolus insulin delivery (in Units) added together, divided by the number of days in this view.',
        ]);
      });
    });

    describe('carbs', () => {
      it('should return annotations for `carbs` stat when viewing a single day of data', () => {
        expect(stat.getStatAnnotations(data, commonStats.carbs, singleDayOpts)).to.have.ordered.members([
          '**Total Carbs**: All carb entries from bolus wizard events or Apple Health records added together.',
          'Derived from _**10**_ carb entries.',
        ]);
      });

      it('should return annotations for `carbs` stat when viewing multiple days of data', () => {
        expect(stat.getStatAnnotations(data, commonStats.carbs, multiDayOpts)).to.have.ordered.members([
          '**Avg. Daily Carbs**: All carb entries added together, then divided by the number of days in this view. Note, these entries come from either bolus wizard events, or Apple Health records.',
          'Derived from _**10**_ carb entries.',
        ]);
      });
    });

    describe('coefficientOfVariation', () => {
      it('should return annotations for `coefficientOfVariation` stat when bgSource is `smgb`', () => {
        expect(stat.getStatAnnotations(data, commonStats.coefficientOfVariation, smbgOpts)).to.have.ordered.members([
          '**CV (Coefficient of Variation):** How far apart (wide) glucose values are; research suggests a target of 36% or lower.',
          'Derived from _**10**_ BGM readings.',
        ]);
      });

      it('should return annotations for `coefficientOfVariation` stat when bgSource is `cbg`', () => {
        expect(stat.getStatAnnotations(data, commonStats.coefficientOfVariation, cbgOpts)).to.have.ordered.members([
          '**CV (Coefficient of Variation):** How far apart (wide) glucose values are; research suggests a target of 36% or lower.',
        ]);
      });

      it('should return insufficient dataannotation for `standardDev` stat when not enough data was present for a calculation', () => {
        const insufficientData = {
          ...data,
          insufficientData: true,
        };

        expect(stat.getStatAnnotations(insufficientData, commonStats.coefficientOfVariation, cbgOpts)).to.have.include.members([
          '**Why is this stat empty?**\n\nThere is not enough data present in this view to calculate it.',
        ]);
      });
    });

    describe('glucoseManagementIndicator', () => {
      it('should return annotations for `glucoseManagementIndicator` stat when bgSource is `cbg`', () => {
        expect(stat.getStatAnnotations(data, commonStats.glucoseManagementIndicator, cbgOpts)).to.have.ordered.members([
          '**GMI (Glucose Management Indicator):** Tells you what your approximate A1C level is likely to be, based on the average glucose level from your CGM readings.',
        ]);
      });

      it('should return insufficient dataannotation for `standardDev` stat when not enough data was present for a calculation', () => {
        const insufficientData = {
          ...data,
          insufficientData: true,
        };

        expect(stat.getStatAnnotations(insufficientData, commonStats.glucoseManagementIndicator, cbgOpts)).to.have.include.members([
          '**Why is this stat empty?**\n\nThere is not enough data present in this view to calculate it.',
        ]);
      });
    });

    describe('readingsInRange', () => {
      it('should return annotations for `readingsInRange` stat', () => {
        expect(stat.getStatAnnotations(data, commonStats.readingsInRange, smbgOpts)).to.have.ordered.members([
          '**Readings In Range:** Daily average of the number of BGM readings.',
          'Derived from _**10**_ BGM readings.',
        ]);
      });
    });

    describe('sensorUsage', () => {
      it('should return annotations for `sensorUsage` stat', () => {
        expect(stat.getStatAnnotations(data, commonStats.sensorUsage)).to.have.ordered.members([
          '**Sensor Usage:** Time the CGM collected data, divided by the total time represented in this view.',
        ]);
      });
    });

    describe('standardDev', () => {
      it('should return annotations for `standardDev` stat when bgSource is `smgb`', () => {
        expect(stat.getStatAnnotations(data, commonStats.standardDev, smbgOpts)).to.have.ordered.members([
          '**SD (Standard Deviation):** How far values are from the average.',
          'Derived from _**10**_ BGM readings.',
        ]);
      });

      it('should return annotations for `standardDev` stat when bgSource is `cbg`', () => {
        expect(stat.getStatAnnotations(data, commonStats.standardDev, cbgOpts)).to.have.ordered.members([
          '**SD (Standard Deviation):** How far values are from the average.',
        ]);
      });

      it('should return insufficient dataannotation for `standardDev` stat when not enough data was present for a calculation', () => {
        const insufficientData = {
          ...data,
          insufficientData: true,
        };

        expect(stat.getStatAnnotations(insufficientData, commonStats.standardDev, cbgOpts)).to.have.include.members([
          '**Why is this stat empty?**\n\nThere is not enough data present in this view to calculate it.',
        ]);
      });
    });

    describe('timeInAuto', () => {
      it('should return annotations for `timeInAuto` stat when viewing a single day of data', () => {
        expect(stat.getStatAnnotations(data, commonStats.timeInAuto, singleDayOpts)).to.have.ordered.members([
          '**Time In Auto Mode:** Time spent in automated basal delivery.',
          '**How we calculate this:**\n\n**(%)** is the duration in Auto Mode divided by the total duration of basals for this time period.\n\n**(time)** is total duration of time in Auto Mode.',
        ]);
      });

      it('should return annotations for `timeInAuto` stat when viewing multiple days of data', () => {
        expect(stat.getStatAnnotations(data, commonStats.timeInAuto, multiDayOpts)).to.have.ordered.members([
          '**Time In Auto Mode:** Daily average of the time spent in automated basal delivery.',
          '**How we calculate this:**\n\n**(%)** is the duration in Auto Mode divided by the total duration of basals for this time period.\n\n**(time)** is 24 hours multiplied by % in Auto Mode.',
        ]);
      });
    });

    describe('timeInOverride', () => {
      it('should return annotations for `timeInOverride` stat when viewing a single day of data', () => {
        expect(stat.getStatAnnotations(data, commonStats.timeInOverride, singleDayOpts)).to.have.ordered.members([
          '**Time In Settings Override:** Time spent in a settings override.',
          '**How we calculate this:**\n\n**(%)** is the duration in Settings Override divided by the total duration of settings overrides for this time period.\n\n**(time)** is total duration of time in Settings Override.',
        ]);
      });

      it('should return annotations for `timeInOverride` stat when viewing multiple days of data', () => {
        expect(stat.getStatAnnotations(data, commonStats.timeInOverride, multiDayOpts)).to.have.ordered.members([
          '**Time In Settings Override:** Daily average of the time spent in a settings override.',
          '**How we calculate this:**\n\n**(%)** is the duration in Settings Override divided by the total duration of settings overrides for this time period.\n\n**(time)** is 24 hours multiplied by % in Settings Override.',
        ]);
      });
    });

    describe('timeInRange', () => {
      it('should return annotations for `timeInRange` stat when viewing a single day of data', () => {
        expect(stat.getStatAnnotations(data, commonStats.timeInRange, singleDayOpts)).to.have.ordered.members([
          '**Time In Range:** Time spent in range, based on CGM readings.',
          '**How we calculate this:**\n\n**(%)** is the number of readings in range divided by all readings for this time period.\n\n**(time)** is number of readings in range multiplied by the CGM sample frequency.',
        ]);
      });

      it('should return annotations for `timeInRange` stat when viewing multiple days of data', () => {
        expect(stat.getStatAnnotations(data, commonStats.timeInRange, multiDayOpts)).to.have.ordered.members([
          '**Time In Range:** Daily average of the time spent in range, based on CGM readings.',
          '**How we calculate this:**\n\n**(%)** is the number of readings in range divided by all readings for this time period.\n\n**(time)** is 24 hours multiplied by % in range.',
        ]);
      });
    });

    describe('totalInsulin', () => {
      it('should return annotations for `totalInsulin` stat when viewing a single day of data', () => {
        expect(stat.getStatAnnotations(data, commonStats.totalInsulin, singleDayOpts)).to.have.ordered.members([
          '**Total Insulin:** All basal and bolus insulin delivery (in Units) added together',
          '**How we calculate this:**\n\n**(%)** is the respective total of basal or bolus delivery divided by total insulin delivered for this time period.',
        ]);
      });

      it('should return annotations for `totalInsulin` stat when viewing multiple days of data', () => {
        expect(stat.getStatAnnotations(data, commonStats.totalInsulin, multiDayOpts)).to.have.ordered.members([
          '**Total Insulin:** All basal and bolus insulin delivery (in Units) added together, divided by the number of days in this view',
          '**How we calculate this:**\n\n**(%)** is the respective total of basal or bolus delivery divided by total insulin delivered for this time period.',
        ]);
      });
    });

    describe('insufficientData', () => {
      it('should return annotation for `insufficientData` stat when insufficient data was present', () => {
        expect(stat.getStatAnnotations({ insufficientData: true }, null, singleDayOpts)).to.have.ordered.members([
          '**Why is this stat empty?**\n\nThere is not enough data present in this view to calculate it.',
        ]);
      });
    });
  });

  describe('getStatData', () => {
    const opts = {
      manufacturer: 'medtronic',
      bgPrefs: {
        bgBounds: {
          veryHighThreshold: 250,
          targetUpperBound: 180,
          targetLowerBound: 70,
          veryLowThreshold: 54,
        },
        bgUnits: MGDL_UNITS,
      },
    };

    it('should return the raw stat data as provided', () => {
      const data = {
        averageGlucose: 100,
      };

      const statData = stat.getStatData(data, commonStats.averageGlucose, opts);

      expect(statData.raw.averageGlucose).to.eql(100);
    });

    it('should return the raw days option as provided', () => {
      const data = {
        averageGlucose: 100,
      };

      const statData = stat.getStatData(data, commonStats.averageGlucose, { ...opts, days: 123 });

      expect(statData.raw.days).to.eql(123);
    });

    it('should format and return `averageGlucose` data', () => {
      const data = {
        averageGlucose: 100,
      };

      const statData = stat.getStatData(data, commonStats.averageGlucose, opts);

      expect(statData.data).to.eql([
        {
          value: 100,
        },
      ]);

      expect(statData.dataPaths).to.eql({
        summary: 'data.0',
      });
    });

    it('should format and return default `averageDailyDose` data', () => {
      const data = {
        totalInsulin: 80,
      };

      const statData = stat.getStatData(data, commonStats.averageDailyDose, opts);

      expect(statData.data).to.eql([
        {
          id: 'insulin',
          input: {
            id: 'weight',
            label: 'Weight',
            suffix: {
              id: 'units',
              options: dailyDoseUnitOptions,
              value: dailyDoseUnitOptions[0],
            },
            type: 'number',
            value: undefined,
          },
          output: {
            label: 'Daily Dose ÷ Weight',
            type: 'divisor',
            dataPaths: {
              dividend: 'data.0',
            },
          },
          value: 80,
        },
      ]);
    });

    it('should format and return `averageDailyDose` data with provided input value', () => {
      const data = {
        totalInsulin: 80,
      };

      const valueOpts = _.assign({}, opts, {
        inputValue: '300',
      });

      const statData = stat.getStatData(data, commonStats.averageDailyDose, valueOpts);

      expect(statData.data).to.eql([
        {
          id: 'insulin',
          input: {
            id: 'weight',
            label: 'Weight',
            suffix: {
              id: 'units',
              options: dailyDoseUnitOptions,
              value: dailyDoseUnitOptions[0],
            },
            type: 'number',
            value: 300,
          },
          output: {
            label: 'Daily Dose ÷ Weight',
            type: 'divisor',
            dataPaths: {
              dividend: 'data.0',
            },
          },
          value: 80,
        },
      ]);
    });

    it('should format and return `averageDailyDose` data with provided suffix value', () => {
      const data = {
        totalInsulin: 80,
      };

      const valueOpts = _.assign({}, opts, {
        suffixValue: dailyDoseUnitOptions[1],
      });

      const statData = stat.getStatData(data, commonStats.averageDailyDose, valueOpts);

      expect(statData.data).to.eql([
        {
          id: 'insulin',
          input: {
            id: 'weight',
            label: 'Weight',
            suffix: {
              id: 'units',
              options: dailyDoseUnitOptions,
              value: dailyDoseUnitOptions[1],
            },
            type: 'number',
            value: undefined,
          },
          output: {
            label: 'Daily Dose ÷ Weight',
            type: 'divisor',
            dataPaths: {
              dividend: 'data.0',
            },
          },
          value: 80,
        },
      ]);
    });

    it('should format and return `bgExtents` data', () => {
      const data = {
        bgMax: 350,
        bgMin: 50,
      };

      const statData = stat.getStatData(data, commonStats.bgExtents, opts);

      expect(statData.data).to.eql([
        {
          id: 'bgMax',
          value: 350,
          title: 'Max BG',
        },
        {
          id: 'bgMin',
          value: 50,
          title: 'Min BG',
        },
      ]);
    });

    it('should format and return `carbs` data', () => {
      const data = {
        carbs: { grams: 30, exchanges: 2 },
      };

      const statData = stat.getStatData(data, commonStats.carbs, opts);
      expect(statData.data).to.eql([
        {
          value: { grams: 30, exchanges: 2 },
        },
      ]);

      expect(statData.dataPaths).to.eql({
        summary: 'data.0',
      });
    });

    it('should format and return `coefficientOfVariation` data', () => {
      const data = {
        coefficientOfVariation: 40,
      };

      const statData = stat.getStatData(data, commonStats.coefficientOfVariation, opts);

      expect(statData.data).to.eql([
        {
          id: 'cv',
          value: 40,
        },
      ]);

      expect(statData.dataPaths).to.eql({
        summary: 'data.0',
      });
    });

    it('should format and return `glucoseManagementIndicator` data', () => {
      const data = {
        glucoseManagementIndicator: 36,
      };

      const statData = stat.getStatData(data, commonStats.glucoseManagementIndicator, opts);

      expect(statData.data).to.eql([
        {
          id: 'gmi',
          value: 36,
        },
      ]);

      expect(statData.dataPaths).to.eql({
        summary: 'data.0',
      });
    });

    it('should format and return `readingsInRange` data', () => {
      const data = {
        veryLow: 10,
        low: 20,
        target: 30,
        high: 40,
        veryHigh: 50,
      };

      const statData = stat.getStatData(data, commonStats.readingsInRange, opts);

      expect(statData.data).to.eql([
        {
          id: 'veryLow',
          value: 10,
          title: 'Readings Below Range',
          legendTitle: '<54',
        },
        {
          id: 'low',
          value: 20,
          title: 'Readings Below Range',
          legendTitle: '54-70',
        },
        {
          id: 'target',
          value: 30,
          title: 'Readings In Range',
          legendTitle: '70-180',
        },
        {
          id: 'high',
          value: 40,
          title: 'Readings Above Range',
          legendTitle: '180-250',
        },
        {
          id: 'veryHigh',
          value: 50,
          title: 'Readings Above Range',
          legendTitle: '>250',
        },
      ]);

      expect(statData.total).to.eql({ value: 150 });

      expect(statData.dataPaths).to.eql({
        summary: ['data', 2],
      });
    });

    it('should format and return `sensorUsage` data', () => {
      const data = {
        sensorUsage: 80,
        total: 200,
      };

      const statData = stat.getStatData(data, commonStats.sensorUsage, opts);

      expect(statData.data).to.eql([
        {
          value: 80,
        },
      ]);

      expect(statData.total).to.eql({ value: 200 });

      expect(statData.dataPaths).to.eql({
        summary: 'data.0',
      });
    });

    it('should format and return `standardDev` data', () => {
      const data = {
        averageGlucose: 120,
        standardDeviation: 32,
      };

      const statData = stat.getStatData(data, commonStats.standardDev, opts);

      expect(statData.data).to.eql([
        {
          value: 120,
          deviation: {
            value: 32,
          },
        },
      ]);

      expect(statData.dataPaths).to.eql({
        summary: 'data.0.deviation',
        title: 'data.0',
      });
    });

    it('should format and return `timeInAuto` data', () => {
      const data = {
        automated: 100000,
        manual: 20000,
      };

      const statData = stat.getStatData(data, commonStats.timeInAuto, opts);

      expect(statData.data).to.eql([
        {
          id: 'basalAutomated',
          value: 100000,
          title: 'Time In Auto Mode',
          legendTitle: 'Auto Mode',
        },
        {
          id: 'basal',
          value: 20000,
          title: 'Time In Manual',
          legendTitle: 'Manual',
        },
      ]);

      expect(statData.total).to.eql({ value: 120000 });

      expect(statData.dataPaths).to.eql({
        summary: ['data', 0],
      });
    });

    it('should format and return `timeInOverride` data', () => {
      const data = {
        physicalActivity: 20000,
        sleep: 100000,
      };

      const statData = stat.getStatData(data, commonStats.timeInOverride, opts);

      expect(statData.data).to.eql([
        {
          id: 'physicalActivity',
          value: 20000,
          title: 'Time In Exercise',
          legendTitle: 'Exercise',
        },
        {
          id: 'sleep',
          value: 100000,
          title: 'Time In Sleep',
          legendTitle: 'Sleep',
        },
      ]);

      expect(statData.sum).to.eql({ value: 120000 });
      expect(statData.total).to.eql({ value: MS_IN_DAY });

      expect(statData.dataPaths).to.eql({
        summary: 'sum',
      });
    });

    it('should format and return `timeInRange` data', () => {
      const data = {
        veryLow: 10000,
        low: 20000,
        target: 30000,
        high: 40000,
        veryHigh: 50000,
      };

      const statData = stat.getStatData(data, commonStats.timeInRange, opts);

      expect(statData.data).to.eql([
        {
          id: 'veryLow',
          value: 10000,
          title: 'Time Below Range',
          legendTitle: '<54',
        },
        {
          id: 'low',
          value: 20000,
          title: 'Time Below Range',
          legendTitle: '54-70',
        },
        {
          id: 'target',
          value: 30000,
          title: 'Time In Range',
          legendTitle: '70-180',
        },
        {
          id: 'high',
          value: 40000,
          title: 'Time Above Range',
          legendTitle: '180-250',
        },
        {
          id: 'veryHigh',
          value: 50000,
          title: 'Time Above Range',
          legendTitle: '>250',
        },
      ]);

      expect(statData.total).to.eql({ value: 150000 });

      expect(statData.dataPaths).to.eql({
        summary: ['data', 2],
      });
    });

    it('should format and return `totalInsulin` data', () => {
      const data = {
        bolus: 9,
        basal: 6,
      };

      const statData = stat.getStatData(data, commonStats.totalInsulin, opts);

      expect(statData.data).to.eql([
        {
          id: 'bolus',
          value: 9,
          title: 'Bolus Insulin',
          legendTitle: 'Bolus',
        },
        {
          id: 'basal',
          value: 6,
          title: 'Basal Insulin',
          legendTitle: 'Basal',
        },
      ]);

      expect(statData.total).to.eql({ id: 'insulin', value: 15 });

      expect(statData.dataPaths).to.eql({
        summary: 'total',
        title: 'total',
      });
    });
  });

  describe('getStatTitle', () => {
    const defaultOpts = {
      manufacturer: 'medtronic',
    };

    const opts = overrides => _.assign({}, defaultOpts, overrides);

    const cbgOpts = opts({ bgSource: 'cbg' });
    const smbgOpts = opts({ bgSource: 'smbg' });
    const singleDayOpts = opts({ days: 1 });
    const multiDayOpts = opts({ days: 14 });

    describe('averageGlucose', () => {
      it('should return title for `averageGlucose` stat when bgSource is `smgb`', () => {
        expect(stat.getStatTitle(commonStats.averageGlucose, smbgOpts)).to.equal('Avg. Glucose (BGM)');
      });

      it('should return title for `averageGlucose` stat when bgSource is `cbg`', () => {
        expect(stat.getStatTitle(commonStats.averageGlucose, cbgOpts)).to.equal('Avg. Glucose (CGM)');
      });
    });

    describe('averageDailyDose', () => {
      it('should return title for `averageDailyDose` stat when viewing a single day of data', () => {
        expect(stat.getStatTitle(commonStats.averageDailyDose, singleDayOpts)).to.equal('Total Insulin');
      });

      it('should return title for `averageDailyDose` stat when viewing multiple days of data', () => {
        expect(stat.getStatTitle(commonStats.averageDailyDose, multiDayOpts)).to.equal('Avg. Daily Insulin');
      });
    });

    describe('bgExtents', () => {
      it('should return title for `bgExtents` stat when bgSource is `smgb`', () => {
        expect(stat.getStatTitle(commonStats.bgExtents, smbgOpts)).to.equal('BG Extents (BGM)');
      });

      it('should return title for `bgExtents` stat when bgSource is `cbg`', () => {
        expect(stat.getStatTitle(commonStats.bgExtents, cbgOpts)).to.equal('BG Extents (CGM)');
      });
    });

    describe('carbs', () => {
      it('should return title for `carbs` stat when viewing a single day of data', () => {
        expect(stat.getStatTitle(commonStats.carbs, singleDayOpts)).to.equal('Total Carbs');
      });

      it('should return title for `carbs` stat when viewing multiple days of data', () => {
        expect(stat.getStatTitle(commonStats.carbs, multiDayOpts)).to.equal('Avg. Daily Carbs');
      });
    });

    describe('coefficientOfVariation', () => {
      it('should return title for `coefficientOfVariation` stat when bgSource is `smgb`', () => {
        expect(stat.getStatTitle(commonStats.coefficientOfVariation, smbgOpts)).to.equal('CV (BGM)');
      });

      it('should return title for `coefficientOfVariation` stat when bgSource is `cbg`', () => {
        expect(stat.getStatTitle(commonStats.coefficientOfVariation, cbgOpts)).to.equal('CV (CGM)');
      });
    });

    describe('glucoseManagementIndicator', () => {
      it('should return title for `glucoseManagementIndicator` stat when bgSource is `smgb`', () => {
        expect(stat.getStatTitle(commonStats.glucoseManagementIndicator, smbgOpts)).to.equal('GMI (BGM)');
      });

      it('should return title for `glucoseManagementIndicator` stat when bgSource is `cbg`', () => {
        expect(stat.getStatTitle(commonStats.glucoseManagementIndicator, cbgOpts)).to.equal('GMI (CGM)');
      });
    });

    describe('readingsInRange', () => {
      it('should return title for `readingsInRange` stat when viewing a single day of data', () => {
        expect(stat.getStatTitle(commonStats.readingsInRange, singleDayOpts)).to.equal('Readings In Range');
      });

      it('should return title for `readingsInRange` stat when viewing multiple days of data', () => {
        expect(stat.getStatTitle(commonStats.readingsInRange, multiDayOpts)).to.equal('Avg. Daily Readings In Range');
      });
    });

    describe('sensorUsage', () => {
      it('should return title for `sensorUsage` stat', () => {
        expect(stat.getStatTitle(commonStats.sensorUsage)).to.equal('Sensor Usage');
      });
    });

    describe('standardDev', () => {
      it('should return title for `standardDev` stat when bgSource is `smgb`', () => {
        expect(stat.getStatTitle(commonStats.standardDev, smbgOpts)).to.equal('Std. Deviation (BGM)');
      });

      it('should return title for `standardDev` stat when bgSource is `cbg`', () => {
        expect(stat.getStatTitle(commonStats.standardDev, cbgOpts)).to.equal('Std. Deviation (CGM)');
      });
    });

    describe('timeInAuto', () => {
      it('should return title for `timeInAuto` stat when viewing a single day of data', () => {
        expect(stat.getStatTitle(commonStats.timeInAuto, singleDayOpts)).to.equal('Time In Auto Mode');
      });

      it('should return title for `timeInAuto` stat when viewing multiple days of data', () => {
        expect(stat.getStatTitle(commonStats.timeInAuto, multiDayOpts)).to.equal('Avg. Daily Time In Auto Mode');
      });
    });

    describe('timeInOverride', () => {
      it('should return title for `timeInOverride` stat when viewing a single day of data', () => {
        expect(stat.getStatTitle(commonStats.timeInOverride, singleDayOpts)).to.equal('Time In Settings Override');
      });

      it('should return title for `timeInOverride` stat when viewing multiple days of data', () => {
        expect(stat.getStatTitle(commonStats.timeInOverride, multiDayOpts)).to.equal('Avg. Daily Time In Settings Override');
      });
    });

    describe('timeInRange', () => {
      it('should return title for `timeInRange` stat when viewing a single day of data', () => {
        expect(stat.getStatTitle(commonStats.timeInRange, singleDayOpts)).to.equal('Time In Range');
      });

      it('should return title for `timeInRange` stat when viewing multiple days of data', () => {
        expect(stat.getStatTitle(commonStats.timeInRange, multiDayOpts)).to.equal('Avg. Daily Time In Range');
      });
    });

    describe('totalInsulin', () => {
      it('should return title for `totalInsulin` stat when viewing a single day of data', () => {
        expect(stat.getStatTitle(commonStats.totalInsulin, singleDayOpts)).to.equal('Total Insulin');
      });

      it('should return title for `totalInsulin` stat when viewing multiple days of data', () => {
        expect(stat.getStatTitle(commonStats.totalInsulin, multiDayOpts)).to.equal('Avg. Daily Total Insulin');
      });
    });
  });

  describe('getStatDefinition', () => {
    const data = { total: 10 };

    const opts = {
      manufacturer: 'medtronic',
      bgPrefs: {
        bgBounds: {
          veryHighThreshold: 250,
          targetUpperBound: 180,
          targetLowerBound: 70,
          veryLowThreshold: 54,
        },
        bgUnits: MGDL_UNITS,
      },
    };

    const commonStatProperties = [
      'annotations',
      'collapsible',
      'data',
      'dataFormat',
      'id',
      'title',
      'type',
    ];

    it('should define the `averageGlucose` stat', () => {
      const def = stat.getStatDefinition(data, commonStats.averageGlucose, opts);
      expect(def).to.include.all.keys(commonStatProperties);
      expect(def.id).to.equal(commonStats.averageGlucose);
      expect(def.type).to.equal(statTypes.barBg);
      expect(def.dataFormat).to.eql({
        label: statFormats.bgValue,
        summary: statFormats.bgValue,
      });
    });

    it('should define the `bgExtents` stat', () => {
      const def = stat.getStatDefinition(data, commonStats.bgExtents, opts);
      expect(def).to.include.all.keys(commonStatProperties);
      expect(def.id).to.equal(commonStats.bgExtents);
      expect(def.dataFormat).to.eql({
        label: statFormats.bgValue,
        summary: statFormats.bgValue,
      });
    });

    it('should define the `carbs` stat', () => {
      const def = stat.getStatDefinition(data, commonStats.carbs, opts);
      expect(def).to.include.all.keys(commonStatProperties);
      expect(def.id).to.equal(commonStats.carbs);
      expect(def.type).to.equal(statTypes.simple);
      expect(def.dataFormat).to.eql({
        summary: statFormats.carbs,
      });
    });

    it('should define the `averageDailyDose` stat', () => {
      const def = stat.getStatDefinition(data, commonStats.averageDailyDose, opts);
      expect(def).to.include.all.keys(commonStatProperties);
      expect(def.id).to.equal(commonStats.averageDailyDose);
      expect(def.alwaysShowSummary).to.be.true;
      expect(def.type).to.equal(statTypes.input);
      expect(def.dataFormat).to.eql({
        output: statFormats.unitsPerKg,
        summary: statFormats.units,
      });
    });

    it('should define the `coefficientOfVariation` stat', () => {
      const def = stat.getStatDefinition(data, commonStats.coefficientOfVariation, opts);
      expect(def).to.include.all.keys(commonStatProperties);
      expect(def.id).to.equal(commonStats.coefficientOfVariation);
      expect(def.type).to.equal(statTypes.simple);
      expect(def.dataFormat).to.eql({
        summary: statFormats.cv,
      });
    });

    it('should define the `glucoseManagementIndicator` stat', () => {
      const def = stat.getStatDefinition(data, commonStats.glucoseManagementIndicator, opts);
      expect(def).to.include.all.keys(commonStatProperties);
      expect(def.id).to.equal(commonStats.glucoseManagementIndicator);
      expect(def.type).to.equal(statTypes.simple);
      expect(def.dataFormat).to.eql({
        summary: statFormats.gmi,
      });
    });

    it('should define the `readingsInRange` stat', () => {
      const def = stat.getStatDefinition(data, commonStats.readingsInRange, opts);
      expect(def).to.include.all.keys(commonStatProperties);
      expect(def.id).to.equal(commonStats.readingsInRange);
      expect(def.type).to.equal(statTypes.barHorizontal);
      expect(def.dataFormat).to.eql({
        label: statFormats.percentage,
        summary: statFormats.percentage,
        tooltip: statFormats.bgCount,
        tooltipTitle: statFormats.bgRange,
      });
      expect(def.alwaysShowTooltips).to.be.true;
    });

    it('should define the `sensorUsage` stat', () => {
      const def = stat.getStatDefinition(data, commonStats.sensorUsage, opts);
      expect(def).to.include.all.keys(commonStatProperties);
      expect(def.id).to.equal(commonStats.sensorUsage);
      expect(def.type).to.equal(statTypes.simple);
      expect(def.dataFormat).to.eql({
        summary: statFormats.percentage,
      });
    });

    it('should define the `standardDev` stat', () => {
      const def = stat.getStatDefinition(data, commonStats.standardDev, opts);
      expect(def).to.include.all.keys(commonStatProperties);
      expect(def.id).to.equal(commonStats.standardDev);
      expect(def.type).to.equal(statTypes.barBg);
      expect(def.dataFormat).to.eql({
        label: statFormats.standardDevValue,
        summary: statFormats.standardDevValue,
        title: statFormats.standardDevRange,
      });
    });

    it('should define the `timeInAuto` stat', () => {
      const def = stat.getStatDefinition(data, commonStats.timeInAuto, opts);
      expect(def).to.include.all.keys(commonStatProperties);
      expect(def.id).to.equal(commonStats.timeInAuto);
      expect(def.type).to.equal(statTypes.barHorizontal);
      expect(def.dataFormat).to.eql({
        label: statFormats.percentage,
        summary: statFormats.percentage,
        tooltip: statFormats.duration,
      });
      expect(def.alwaysShowTooltips).to.be.true;
    });

    it('should define the `timeInOverride` stat', () => {
      const def = stat.getStatDefinition(data, commonStats.timeInOverride, opts);
      expect(def).to.include.all.keys(commonStatProperties);
      expect(def.id).to.equal(commonStats.timeInOverride);
      expect(def.type).to.equal(statTypes.barHorizontal);
      expect(def.dataFormat).to.eql({
        label: statFormats.percentage,
        summary: statFormats.percentage,
        tooltip: statFormats.duration,
      });
      expect(def.alwaysShowTooltips).to.be.true;
    });

    it('should define the `timeInRange` stat', () => {
      const def = stat.getStatDefinition(data, commonStats.timeInRange, opts);
      expect(def).to.include.all.keys(commonStatProperties);
      expect(def.id).to.equal(commonStats.timeInRange);
      expect(def.type).to.equal(statTypes.barHorizontal);
      expect(def.dataFormat).to.eql({
        label: statFormats.percentage,
        summary: statFormats.percentage,
        tooltip: statFormats.duration,
        tooltipTitle: statFormats.bgRange,
      });
      expect(def.alwaysShowTooltips).to.be.true;
    });

    it('should define the `totalInsulin` stat', () => {
      const def = stat.getStatDefinition(data, commonStats.totalInsulin, opts);
      expect(def).to.include.all.keys(commonStatProperties);
      expect(def.id).to.equal(commonStats.totalInsulin);
      expect(def.type).to.equal(statTypes.barHorizontal);
      expect(def.dataFormat).to.eql({
        label: statFormats.percentage,
        summary: statFormats.units,
        title: statFormats.units,
        tooltip: statFormats.units,
      });
      expect(def.alwaysShowTooltips).to.be.true;
    });
  });

  describe('statsText', () => {
    const textUtil = {
      buildTextTable: sinon.stub().returns('text table'),
      buildTextLine: sinon.stub().returns('text line'),
    };

    const defaultBgPrefs = {
      bgClasses: {
        'very-high': { boundary: 600 },
        high: { boundary: 300 },
        target: { boundary: 180 },
        low: { boundary: 70 },
        'very-low': { boundary: 54 },
      },
      bgUnits: MGDL_UNITS,
    };

    const defaultStat = {
      title: 'My Stat',
      data: {
        data: [{ value: 5, id: 'myStat' }],
        dataPaths: { summary: 'data.0' },
      },
      dataFormat: { summary: 'myFormat' },
    };

    // Stats formatted as tables
    const timeInRange = { ...defaultStat, id: 'timeInRange', title: 'timeInRange' };
    const readingsInRange = { ...defaultStat, id: 'readingsInRange', title: 'readingsInRange' };
    const totalInsulin = { ...defaultStat, id: 'totalInsulin', title: 'totalInsulin' };
    const timeInAuto = { ...defaultStat, id: 'timeInAuto', title: 'timeInAuto' };
    const timeInOverride = { ...defaultStat, id: 'timeInOverride', title: 'timeInOverride' };
    const bgExtents = { ...defaultStat, id: 'bgExtents', title: 'bgExtents' };

    // Stats formatted as lines
    const averageGlucose = { ...defaultStat, id: 'averageGlucose', title: 'averageGlucose' };
    const averageDailyDose = { ...defaultStat, id: 'averageDailyDose', title: 'averageDailyDose' };
    const carbs = { ...defaultStat, id: 'carbs', title: 'carbs' };
    const coefficientOfVariation = { ...defaultStat, id: 'coefficientOfVariation', title: 'coefficientOfVariation' };
    const glucoseManagementIndicator = { ...defaultStat, id: 'glucoseManagementIndicator', title: 'glucoseManagementIndicator' };
    const sensorUsage = { ...defaultStat, id: 'sensorUsage', title: 'sensorUsage' };
    const standardDev = { ...defaultStat, id: 'standardDev', title: 'standardDev' };

    const stats = [
      timeInRange,
      readingsInRange,
      totalInsulin,
      timeInAuto,
      timeInOverride,
      bgExtents,
      averageGlucose,
      averageDailyDose,
      carbs,
      coefficientOfVariation,
      glucoseManagementIndicator,
      sensorUsage,
      standardDev,
    ];

    const defaultOpts = { bgPrefs: defaultBgPrefs, data: defaultStat.data, forcePlainTextValues: true };

    afterEach(() => {
      textUtil.buildTextTable.resetHistory();
      textUtil.buildTextLine.resetHistory();
    });

    it('should reshape provided tideline-style bgPrefs to the viz format', () => {
      const bgPrefs = { ...defaultBgPrefs };
      expect(bgPrefs.bgBounds).to.be.undefined;

      stat.statsText(stats, textUtil, bgPrefs);
      expect(bgPrefs.bgBounds).to.eql({
        veryLowThreshold: bgPrefs.bgClasses['very-low'].boundary,
        targetLowerBound: bgPrefs.bgClasses.low.boundary,
        targetUpperBound: bgPrefs.bgClasses.target.boundary,
        veryHighThreshold: bgPrefs.bgClasses.high.boundary,
        clampThreshold: 600,
      });
    });

    it('should render all horizontal bar stats as tables', () => {
      const result = stat.statsText([
        timeInRange,
        readingsInRange,
        totalInsulin,
        timeInAuto,
        timeInOverride,
        bgExtents,
      ], textUtil, defaultBgPrefs);

      sinon.assert.callCount(textUtil.buildTextTable, 6);
      sinon.assert.callCount(textUtil.buildTextLine, 0);
      sinon.assert.calledWith(textUtil.buildTextTable, 'timeInRange');
      sinon.assert.calledWith(textUtil.buildTextTable, 'readingsInRange');
      sinon.assert.calledWith(textUtil.buildTextTable, 'totalInsulin');
      sinon.assert.calledWith(textUtil.buildTextTable, 'timeInAuto');
      sinon.assert.calledWith(textUtil.buildTextTable, 'timeInOverride');
      sinon.assert.calledWith(textUtil.buildTextTable, 'bgExtents');

      expect(result).to.be.a('string').and.include('text table');
    });

    it('should render all other stats as simple lines', () => {
      const result = stat.statsText([
        averageGlucose,
        averageDailyDose,
        carbs,
        coefficientOfVariation,
        glucoseManagementIndicator,
        sensorUsage,
        standardDev,
      ], textUtil, defaultBgPrefs);

      sinon.assert.callCount(textUtil.buildTextTable, 0);
      sinon.assert.callCount(textUtil.buildTextLine, 7);
      sinon.assert.calledWith(textUtil.buildTextLine, sinon.match({ label: 'averageGlucose' }));
      sinon.assert.calledWith(textUtil.buildTextLine, sinon.match({ label: 'averageDailyDose' }));
      sinon.assert.calledWith(textUtil.buildTextLine, sinon.match({ label: 'carbs' }));
      sinon.assert.calledWith(textUtil.buildTextLine, sinon.match({ label: 'coefficientOfVariation' }));
      sinon.assert.calledWith(textUtil.buildTextLine, sinon.match({ label: 'glucoseManagementIndicator' }));
      sinon.assert.calledWith(textUtil.buildTextLine, sinon.match({ label: 'sensorUsage' }));
      sinon.assert.calledWith(textUtil.buildTextLine, sinon.match({ label: 'standardDev' }));

      expect(result).to.be.a('string').and.include('text line');
    });

    it('should call formatDatum on each stat with appropriate args', () => {
      const formatDatumSpy = sinon.spy(stat, 'formatDatum');

      stat.statsText(stats, textUtil, defaultBgPrefs, formatDatumSpy);

      // 13 stats, but readingsInRange, timeInAuto, timeInOverride, timeInRange are called an extra time for the secondary value
      sinon.assert.callCount(formatDatumSpy, 17);
      sinon.assert.calledWith(formatDatumSpy, defaultStat.data.data[0], 'myFormat', sinon.match(defaultOpts));

      formatDatumSpy.restore();
    });
  });
});


text:
FactoryGirl.define do
  factory :setting do
    key "MyString"
    value "MyString"
  end
end


text:
namespace _03.FirstBeforeLast
{
    using System;
    using System.Linq;
    using System.Text;
    using System.Collections.Generic;

    public class Student
    {
        public Student(string firstName, string lastName,int age)

        {
            this.FirstName = firstName;
            this.LastName = lastName;
            this.Age = age;
        }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public int Age { get; set; }

    }
}


text:
'use strict';

var should = require('should'),
    request = require('supertest'),
    path = require('path'),
    mongoose = require('mongoose'),
    User = mongoose.model('User'),
    Order = mongoose.model('Order'),
    express = require(path.resolve('./config/lib/express'));

var app, agent, credentials, user, order;

describe('Admin Payment CRUD tests', function () {
    before(function (done) {
        app = express.init(mongoose);
        agent = request.agent(app);

        done();
    });

    beforeEach(function (done) {
        credentials = {
            username: 'username4tests',
            password: 'M3@n.jsI$Aw3$0m3'
        };

        user = new User({
            firstName: 'firstName',
            lastName: 'lastName',
            displayName: 'firstName lastName',
            email: 'test@test.com',
            username: credentials.username,
            password: credentials.password,
            provider: 'local',
            roles: [ "admin" ]
        });

        order = new Order({
            cart: [],
            paypal_create_res: [],
            paypal_get_res: [],
            paypal_execute_res: [],
            open: true
        });

        user.save(function () {
            order.save(done);
        });
    });

    it('should not be able to get the list when not logged in to an admin acc', function (done) {
        agent.get('/api/order/adminctl')
            .expect(403)
            .end(done);
    });

    it('should be able to get the list as an admin', function (done) {
        agent.post('/api/auth/signin')
            .send(credentials)
            .expect(200)
            .end(function (signinErr, signinRes) {
                if (signinErr) {
                    return done(signinErr);
                }

                agent.get('/api/order/adminctl')
                    .expect(200)
                    .end(done);
            });
    });

    it('should not update when not an admin', function (done) {
        agent.put('/api/order/adminctl/' + order._id)
            .expect(403)
            .end(done);
    });

    it('should update when on an admin acc', function (done) {
        agent.post('/api/auth/signin')
            .send(credentials)
            .expect(200)
            .end(function (signinErr, signinRes) {
                if (signinErr) {
                    return done(signinErr);
                }

                agent.put('/api/order/adminctl/' + order._id)
                    .send({ newStatus: 'new status' })
                    .expect(200)
                    .end(function () {
                        agent.get('/api/order/adminctl')
                            .expect(200)
                            .end(done);
                    });
            });
    });

    afterEach(function (done) {
        User.remove().exec(function () {
            Order.remove().exec(done);
        });
    });
});


text:
package org.eclipse.swt.snippets;

/*
 * Menu example snippet: show a popup menu (wait for it to close)
 *
 * For a list of all SWT example snippets see
 * http://www.eclipse.org/swt/snippets/
 *
 * @since 3.0
 */
import org.eclipse.swt.*;
import org.eclipse.swt.widgets.*;

public class Snippet131 {
public static void main (String [] args) {
	final Display display = new Display ();
	final Shell shell = new Shell (display);
	shell.addListener (SWT.MenuDetect, new Listener () {
		@Override
		public void handleEvent (Event event) {
			Menu menu = new Menu (shell, SWT.POP_UP);
			MenuItem item = new MenuItem (menu, SWT.PUSH);
			item.setText ("Menu Item");
			item.addListener (SWT.Selection, new Listener () {
				@Override
				public void handleEvent (Event e) {
					System.out.println ("Item Selected");
				}
			});
			menu.setLocation (event.x, event.y);
			menu.setVisible (true);
			while (!menu.isDisposed () && menu.isVisible ()) {
				if (!display.readAndDispatch ()) display.sleep ();
			}
			menu.dispose ();
		}
	});
	shell.pack ();
	shell.open ();
	while (!shell.isDisposed ()) {
		if (!display.readAndDispatch ()) display.sleep ();
	}
	display.dispose ();
}
}


text:
package com.profitbricks.rest.test;

import com.profitbricks.rest.client.RestClientException;
import com.profitbricks.rest.domain.*;
import static com.profitbricks.rest.test.DatacenterTest.waitTillProvisioned;
import com.profitbricks.rest.test.resource.CommonResource;
import com.profitbricks.rest.test.resource.DataCenterResource;
import com.profitbricks.rest.test.resource.LanResource;
import com.profitbricks.sdk.ProfitbricksApi;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.junit.AfterClass;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import org.junit.BeforeClass;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;

/**
 * @author jasmin@stackpointcloud.com
 */
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class LanTest {

    static ProfitbricksApi profitbricksApi;

    static {
        try {
            profitbricksApi = new ProfitbricksApi();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static String dataCenterId;
    private static String lanId;
    private static String ipBlockId;

    @BeforeClass
    public static void t1_createDataCenter() throws RestClientException, IOException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, InterruptedException {

        profitbricksApi.setCredentials(System.getenv("PROFITBRICKS_USERNAME"), System.getenv("PROFITBRICKS_PASSWORD"));

        DataCenter newDatacenter = profitbricksApi.getDataCenter().createDataCenter(DataCenterResource.getDataCenter());
        dataCenterId = newDatacenter.getId();
        assertEquals(newDatacenter.getProperties().getName(), DataCenterResource.getDataCenter().getProperties().getName());
        waitTillProvisioned(newDatacenter.getRequestId());

        Lan newLan = profitbricksApi.getLan().createLan(dataCenterId, LanResource.getLan());
        lanId = newLan.getId();
        assertNotNull(newLan);
        assertEquals(newLan.getProperties().getName(), LanResource.getLan().getProperties().getName());
        assertEquals(newLan.getProperties().isIsPublic(), LanResource.getLan().getProperties().isIsPublic());
        waitTillProvisioned(newLan.getRequestId());

        IPBlock ipb = new IPBlock();
        ipb.getProperties().setLocation("us/las");
        ipb.getProperties().setSize(1);
        IPBlock iPBlock = profitbricksApi.getIpBlock().createIPBlock(ipb);
        ipBlockId = iPBlock.getId();
    }

    @Test
    public void t2_getAllLans() throws RestClientException, IOException {
        Lans lans = profitbricksApi.getLan().getAllLans(dataCenterId);
        assertNotNull(lans);
    }

    @Test
    public void t3_getLan() throws RestClientException, IOException {
        Lan lan = profitbricksApi.getLan().getLan(dataCenterId, lanId);
        assertNotNull(lan);
        assertEquals(lan.getId(), lanId);
        assertEquals(lan.getProperties().getName(), LanResource.getLan().getProperties().getName());
        assertEquals(lan.getProperties().isIsPublic(), LanResource.getLan().getProperties().isIsPublic());
    }

    @Test
    public void t4_getLanFail() throws RestClientException, IOException {
        try {
            Lan lan = profitbricksApi.getLan().getLan(dataCenterId, CommonResource.getBadId());
        } catch (RestClientException ex) {
            assertEquals(ex.response().getStatusLine().getStatusCode(), 404);
        }
    }

    @Test
    public void t5_updateLan() throws RestClientException, IOException, InterruptedException, NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
        Lan updatedLan = profitbricksApi.getLan().updateLan(dataCenterId, lanId, LanResource.getEditLan().getProperties().getName(), LanResource.getEditLan().getProperties().isIsPublic());
        waitTillProvisioned(updatedLan.getRequestId());
        assertEquals(updatedLan.getProperties().getName(), LanResource.getEditLan().getProperties().getName());
        assertEquals(updatedLan.getProperties().isIsPublic(), LanResource.getEditLan().getProperties().isIsPublic());
    }

    @Test
    public void t6_createLanComposite() throws InvocationTargetException, NoSuchMethodException, IllegalAccessException, RestClientException, IOException, InterruptedException {
        DataCenter datacenter = new DataCenter();

        datacenter.getProperties().setName("SDK TEST DC - Composite Data center");
        datacenter.getProperties().setLocation("us/las");
        datacenter.getProperties().setDescription("SDK TEST Description");

        Lan lan = new Lan();

        lan.getProperties().setName("SDK TEST Lan - Lan");
        lan.getProperties().setIsPublic(false);

        Lans lans = new Lans();
        List<Lan> lanList = new ArrayList<Lan>();
        lanList.add(lan);
        lans.setItems(lanList);
        datacenter.getEntities().setLans(lans);

        DataCenter newDatacenter = profitbricksApi.getDataCenter().createDataCenter(datacenter);

        waitTillProvisioned(newDatacenter.getRequestId());

        profitbricksApi.getDataCenter().deleteDataCenter(newDatacenter.getId());
    }

    @Test
    public void t7_createLanFail() throws RestClientException, IOException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, InterruptedException {
        try {
            Lan lan = profitbricksApi.getLan().createLan(dataCenterId,LanResource.getBadLan());
        }catch (RestClientException ex){
            assertEquals(ex.response().getStatusLine().getStatusCode(), 422);
        }
    }

    @Test
    public void t8_updateLanWithFailover() throws RestClientException, IOException, InterruptedException, NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
        Server server1 = new Server();
        server1.getProperties().setName("SDK TEST SERVER - Server Failover 1");
        server1.getProperties().setRam(1024);
        server1.getProperties().setCores(1);
        Server newServer1 = profitbricksApi.getServer().createServer(dataCenterId, server1);
        waitTillProvisioned(newServer1.getRequestId());
        String server1Id = newServer1.getId();

        Lan lan1 = new Lan();
        lan1.getProperties().setName("SDK TEST Lan - Lan");
        lan1.getProperties().setIsPublic(false);
        Lan newLan1 = profitbricksApi.getLan().createLan(dataCenterId, lan1);
        String lan1Id = newLan1.getId();
        waitTillProvisioned(newLan1.getRequestId());

        IPBlock iPBlock = profitbricksApi.getIpBlock().getIPBlock(ipBlockId);

        Nic nic = new Nic();
        nic.getProperties().setName("SDK TEST NIC - Nic");
        nic.getProperties().setLan(lan1Id);
        nic.getProperties().setNat(Boolean.FALSE);
        nic.getProperties().setIps(iPBlock.getProperties().getIps());
        nic.getEntities().setFirewallrules(null);
        Nic newNic = profitbricksApi.getNic().createNic(dataCenterId, server1Id, nic);
        waitTillProvisioned(newNic.getRequestId());

        IpFailover ipFailover = new IpFailover();
        ipFailover.setIp(iPBlock.getProperties().getIps().get(0));
        ipFailover.setNicUuid(newNic.getId());

        List<IpFailover> failovers = new ArrayList<IpFailover>();
        failovers.add(ipFailover);

        Lan updatedLan = profitbricksApi.getLan().updateLan(dataCenterId, lan1Id, Boolean.TRUE, failovers);
        waitTillProvisioned(updatedLan.getRequestId());

        Server server2 = new Server();
        server2.getProperties().setName("SDK TEST SERVER - Server Failover 2");
        server2.getProperties().setRam(1024);
        server2.getProperties().setCores(1);
        Server newServer2 = profitbricksApi.getServer().createServer(dataCenterId, server2);
        waitTillProvisioned(newServer2.getRequestId());
        String server2Id = newServer2.getId();

        Nic nic2 = new Nic();
        nic2.getProperties().setName("SDK TEST NIC - Nic2");
        nic2.getProperties().setLan(lan1Id);
        nic2.getProperties().setNat(Boolean.FALSE);
        nic2.getProperties().setIps(iPBlock.getProperties().getIps());
        nic2.getEntities().setFirewallrules(null);
        Nic newNic2 = profitbricksApi.getNic().createNic(dataCenterId, server2Id, nic2);
        waitTillProvisioned(newNic2.getRequestId());
    }

    @AfterClass
    public static void cleanup() throws RestClientException, IOException {
        profitbricksApi.getDataCenter().deleteDataCenter(dataCenterId);

        try {
            TimeUnit.MINUTES.sleep(1);
        }
        catch (Exception ex) {}

        profitbricksApi.getIpBlock().deleteIPBlock(ipBlockId);
    }
}