text:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "db.h"

#ifndef lint
static const char copyright[] =
    "Copyright (c) 2011, 2020 Oracle and/or its affiliates.  All rights reserved.\n";
#endif

#define	BUFFER_LEN		30     /* Buffer size to hold data */
#define	NS_PER_MS		1000000/* Nanoseconds in a millisecond*/
#define	NS_PER_US		1000   /* Nanoseconds in a microsecond*/
#define	DEF_INIT_RECS		10000  /* Default initial records */
#define	DEF_RECS_PER_REP	10000  /* Default records per repeat. */
#define	DEF_REPEATS		1      /* Default repetition value */

/*
 * Average space each record needs, based on the data generated.
 * The ideal heap size for this example should be set as (bytes):
 * AVG_SPACE_PER_RECORD * (DEF_INIT_RECS + records inserted each repetition)
 */
#define	AVG_SPACE_PER_RECORD	36

#ifdef _WIN32
#include <sys/timeb.h>
#include <time.h>
#include <winsock2.h>
extern int getopt(int, char * const *, const char *);

/* Implement a basic high-resolution timer with a POSIX interface for Windows.*/
int gettimeofday(struct timeval *tv, struct timezone *tz)
{
	struct _timeb now;
	_ftime(&now);
	tv->tv_sec = (long)now.time;
	tv->tv_usec = now.millitm * NS_PER_US;
	return (0);
}
#else
#include <sys/time.h>
#include <unistd.h>
#endif

int	compare_int(DB *, const DBT *, const DBT *, size_t *);
int	delete_recs __P((DB *, DB_ENV *, int));
int	file_size __P((DB *, DBTYPE, int *));
int	generate_data __P((char [], int, int));
int	insert_btree __P((DB *, DB_ENV *, int, int, int));
int	insert_heap __P((DB *, DB_ENV *, int, int, int));
int	open_db __P((
    DB **, DB_ENV *, DBTYPE, char *, u_int32_t, u_int32_t, u_int32_t));
int	open_env __P((DB_ENV **, char *, u_int32_t));
int	run_workload __P((DB *, int, int, int));
void	usage __P((void));

const char *progname = "ex_heap"; /* Program name. */

int
main(argc, argv)
	int argc;
	char *argv[];
{
	extern char *optarg;	/* Set by getopt(): the argv being processed. */
	DB_ENV *dbenv;		/* The environment handle. */
	DB *dbp;		/* The database handle. */
	u_int32_t cachesize;	/* The size of cache set for the environment. */
	u_int32_t ghpsize;	/* The heap size (gbytes) for the heap database. */
	u_int32_t hpsize;	/* The heap size (bytes) for the heap database. */
	u_int32_t pgsize;	/* The page size of database. */
	char *home;		/* The home directory for the program. */
	int ch;			/* The current command line option char. */
	int ret;		/* Return code from call into Berkeley DB. */
	int ret_t;		/* Return code from close operation. */
	int set_ghpsize;	/* Flag for setting gphsize. */
	int set_hpsize;		/* Flag for setting hpsize. */
	int test_btree;		/* Flag for running sample application using a btree database. */
	int test_var_data;	/* Flag for testing variable-length data. */

	int recs_per_rep;	/* Number of records per repetition. */
	int repeats;		/* Repetition value. */

	dbenv = NULL;
	dbp = NULL;
	cachesize = 0;
	ret = ret_t = set_ghpsize = set_hpsize = test_btree = 0;
	home = NULL;

	recs_per_rep = DEF_RECS_PER_REP;
	ghpsize = hpsize = pgsize = 0;
	repeats = DEF_REPEATS;
	test_var_data = 0; /* Default as fix-length data. */

	/* Parse the command line arguments */
	while ((ch = getopt(argc, argv, "bc:dh:n:p:r:S:s:")) != EOF)
		switch (ch) {
		case 'b':		/* Run sample application using a btree database. */
			test_btree = 1;
			break;
		case 'c':		/* Specify the cache size for the environment. */
			cachesize = atoi(optarg);
			break;
		case 'd':		/* Test on variable-length data. */
			test_var_data = 1;
			break;
		case 'h':		/* Specify the home directory for the environment. */
			home = optarg;
			break;
		case 'n':		/* Specify the number of records per repetition. */
			recs_per_rep = atoi(optarg);
			break;
		case 'p':		/* Specify the pgsize of database. */
			pgsize = atoi(optarg);
			break;
		case 'r':		/* Set number of repetition. */
			repeats = atoi(optarg);
			break;
		case 's':		/* Specify the heap size (bytes) for the heap database. */
			set_hpsize = 1;
			hpsize = atoi(optarg);
			break;
		case 'S':		/* Specify the heap size (gbytes) for the heap database. */
			set_ghpsize = 1;
			ghpsize = atoi(optarg);
			break;
		default:
			usage();
		}

	if (!home)
		usage();

	srand((int)time(NULL));

	/*
	 * If heap size is not specified, then use our default configuration
	 * as follows.
	 */
	if (!set_hpsize && !set_ghpsize)
		hpsize = AVG_SPACE_PER_RECORD * (DEF_INIT_RECS + recs_per_rep);

	/* Open the evnironment for usage. */
	if ((ret = open_env(&dbenv, home, cachesize)) != 0) {
		fprintf(stderr, "%s: open_env: %s", progname, db_strerror(ret));
		goto err;
	}
	/* Open a heap database for insert/delete operations. */
	if ((ret = open_db(&dbp, dbenv, DB_HEAP, home,
	    ghpsize, hpsize, pgsize)) != 0) {
		dbenv->err(dbenv, ret, "Failed to open heap database.");
		goto err;
	}

	/*
	 * Perform requested rounds of insert/delete operations
	 * using heap database.
	 */
	if ((ret =
	    run_workload(dbp, repeats, recs_per_rep, test_var_data)) != 0) {
		dbenv->err(dbenv, ret,
		    "Failed to perform operations on heap database.");
		goto err;
	}

	if (test_btree) {
		/* Close the DB handle for heap. */
		if ((ret = dbp->close(dbp, 0)) != 0) {
			dbenv->err(dbenv, ret, "DB->close");
			goto err;
		}
		dbp = NULL;
		/* Open a b-tree database for insert/delete operations. */
		if ((ret =
		    open_db(&dbp, dbenv, DB_BTREE, home, 0, 0, pgsize)) != 0) {
			dbenv->err(dbenv, ret,
			    "Failed to open btree database.");
			goto err;
		}

		/*
		 * Perform requested rounds of insert/delete operations
		 * using btree database.
		 */
		if ((ret = run_workload(dbp,
		    repeats, recs_per_rep, test_var_data)) != 0) {
			dbenv->err(dbenv, ret,
			    "Failed to perform operations on btree database.");
			goto err;
		}
	}
err:
	if (dbp != NULL && (ret_t = dbp->close(dbp, 0)) != 0) {
		dbenv->err(dbenv, ret_t, "DB->close");
		ret = (ret == 0 ? ret_t : ret);
	}

	if (dbenv != NULL && (ret_t = dbenv->close(dbenv, 0)) != 0) {
		fprintf(stderr, "%s: dbenv->close: %s", progname,
		    db_strerror(ret_t));
		ret = (ret == 0 ? ret_t : ret);
	}

	return (ret);
}

/*
 * run_workload --
 * 	Perform requested rounds of insert/delete operations.
 *
 * Parameters:
 *	dbp		the database handle
 *	repeats		the number of repetition (a pair of insertion and deletion)
 *	recs_per_rep	the number of records per repetition
 *	test_var	test on variable-length data flag
 */
int
run_workload(dbp, repeats, recs_per_rep, test_var)
	DB *dbp;
	int repeats, recs_per_rep, test_var;
{
	DB_ENV *dbenv;			/* The environment handle. */
	DBTYPE dbtype;			/* The access method used by the database. */
	u_int32_t ghpsize;		/* The heap size (gbytes). */
	u_int32_t hpsize;		/* The heap size (bytes). */
	struct timeval end_time;	/* The end time of each iteration. */
	struct timeval start_time;	/* The start time of each iteration. */
	double *time_secs;		/* The array of each iteration's run time. */
	int *db_file_sizes;		/* The array of file sizes after each iteration. */
	int fsize;			/* The file size after the current iteration. */
	int i;				/* Iteration number. */
	int ret;			/* The return value. */

	dbenv = dbp->dbenv;
	fsize = 0;
	time_secs = NULL;
	db_file_sizes = NULL;

	/* Get the access method of the database. */
	if ((ret = dbp->get_type(dbp, &dbtype)) != 0) {
		dbenv->err(dbenv, ret, "DB->get_type");
		goto err;
	}

	/* Get the heap size if the database uses the heap access method. */
	if (dbtype == DB_HEAP &&
	    (ret = dbp->get_heapsize(dbp, &ghpsize, &hpsize)) != 0) {
		dbenv->err(dbenv, ret, "DB->get_heapsize");
		goto err;
	}

	/* Initialize the array holding file sizes after each iteration. */
	if ((db_file_sizes =
	    (int *)malloc((repeats + 1) * sizeof(int))) == NULL) {
		fprintf(stderr,
		    "%s: Unable to allocate space for array db_file_sizes.\n",
		    progname);
		goto err;
	}
	memset(db_file_sizes, 0, (repeats + 1) * sizeof(int));

	/* Initialize the array holding each iteration's run time. */
	if ((time_secs =
	    (double *)malloc((repeats + 1) * sizeof(double))) == NULL) {
		fprintf(stderr,
		    "%s: Unable to allocate space for array time_secs.\n",
		    progname);
		goto err;
	}
	memset(time_secs, 0, (repeats + 1) * sizeof(double));

	printf("\n\n======================================================");
	printf("\nAbout to enter the insert phase.");
	printf("\n\tDatabase type: %s \t",
	    dbtype == DB_HEAP ? "Heap" : "Btree");
	if (dbtype == DB_HEAP)
		printf("with configured heapsize = %d gbytes and %d bytes.",
		    ghpsize, hpsize);
	printf("\n\tPagesize: %d", dbp->pgsize);
	printf("\n\tInitial records number: %d", DEF_INIT_RECS);
	printf("\n\tNumber of repetitions: %d", repeats);
	printf("\n\tNumber of inserts per repetition: %d\n", recs_per_rep);

	/*
	 * Insert records to the database and delete the same number from
	 * the database, then check the change of the physical database file.
	 *
	 * Don't delete after the first insertion to leave some data
	 * in the tables for subsequent iterations.
	 */
	for (i = 0; i <= repeats; i++) {
		/* Get the start time. */
		(void)gettimeofday(&start_time, NULL);

		/*
		 * Insert records into the database. Depending on the type
		 * of the database, different types of keys are used. Calling
		 * different functions to perform insertions.
		 */
		if ((dbtype == DB_HEAP) && (ret = insert_heap(dbp, dbenv,
		    i == 0 ? DEF_INIT_RECS : recs_per_rep,
		    i == 0 ? 0 : (DEF_INIT_RECS + (i - 1) * recs_per_rep),
		    test_var)) != 0) {
			dbenv->err(dbenv, ret,
			    "Failed to insert records to heap database.");
			goto err;
		}

		if ((dbtype == DB_BTREE) && (ret = insert_btree(dbp, dbenv,
		    i == 0 ? DEF_INIT_RECS : recs_per_rep,
		    i == 0 ? 0 : (DEF_INIT_RECS + (i - 1) * recs_per_rep),
		    test_var)) != 0) {
			dbenv->err(dbenv, ret,
			    "Failed to insert records to btree database.");
			goto err;
		}

		/*
		 * Delete the same number of records except for the first
		 * iteration.
		 */
		if (i > 0 &&
		    (ret = delete_recs(dbp, dbenv, recs_per_rep)) != 0) {
			dbenv->err(dbenv, ret, "Failed to delete records.");
			goto err;
		}

		/* Get the end time. */
		(void)gettimeofday(&end_time, NULL);

		/* Calculate the runtime. */
		time_secs[i] =
		    (((double)end_time.tv_sec * NS_PER_MS +
		    end_time.tv_usec) -
		    ((double)start_time.tv_sec * NS_PER_MS +
		    start_time.tv_usec)) / NS_PER_MS;

		/* Calculate the physical file size. */
		if ((ret = file_size(dbp, dbtype, &fsize)) != 0) {
			dbenv->err(dbenv, ret, "Failed to calculate "
			    "the file size on repeat %d.\n", i);
			goto err;
		}
		db_file_sizes[i] = fsize;
	}
	printf("\n------------------------------------------------------\n");
	printf("%5s \t %10s \t %10s\n", "repetition", "physical file size",
	    "running time");
	for (i = 0; i <= repeats; i++)
		printf("%5d \t\t %10d \t\t %.2f seconds\n",
		    i, db_file_sizes[i], time_secs[i]);

err:
	if (db_file_sizes != NULL)
		free(db_file_sizes);
	if (time_secs != NULL)
		free(time_secs);

	return (ret);
}

/*
 * file_size --
 * 	Calculate the physical file size of the given database.
 *
 * Parameters:
 *	dbp	the database handle
 *	dbtype	the database type
 *	fsize	the physical file size of database
 */
int
file_size(dbp, dbtype, fsize)
	DB *dbp;
	DBTYPE dbtype;
	int *fsize;
{
	DB_ENV *dbenv;		/* The environment handle. */
	u_int32_t pgcnt;	/* The number of pages in the database. */
	u_int32_t pgsize;	/* The page size. */
	int ret;		/* The return value. */
	int size;		/* The file size. */
	void *statp;		/* The statistic pointer for database size. */

	dbenv = dbp->dbenv;
	pgsize = dbp->pgsize;
	ret = size = 0;

	/* Retrieve the database's statistics. */
	if ((ret = dbp->stat(dbp, NULL, &statp, DB_FAST_STAT)) != 0) {
		dbenv->err(dbenv, ret, "DB->stat");
		return (ret);
	}

	/* Get the page count. */
	pgcnt = (dbtype == DB_HEAP ? ((DB_HEAP_STAT *)statp)->heap_pagecnt :
	    ((DB_BTREE_STAT *)statp)->bt_pagecnt);

	/* the file size is the value of page count multiplied by the page size. */
	size = pgcnt * pgsize;
	*fsize = size;

	free(statp);

	return (ret);
}

/*
 * insert_heap --
 * 	Insert a specified number of records to a heap database,
 *  with keys beginning with a specified value.
 *
 * Parameters:
 *	dbp		the database handle
 *	dbenv		the database environment
 *	numrecs		the number of records to insert
 *	start		the start position to insert records
 *	test_var	test on variable-length data flag
 */

int
insert_heap(dbp, dbenv, numrecs, start, test_var)
	DB *dbp;
	DB_ENV *dbenv;
	int numrecs, start, test_var;
{
	DB_HEAP_RID rid;	/* The returned record id. */
	DBT key, data;		/* The key/data pair. */
	char buf[BUFFER_LEN];	/* The data buffer. */
	int cnt, ret;

	memset(&rid, 0, sizeof(DB_HEAP_RID));
	memset(&key, 0, sizeof(DBT));
	memset(&data, 0, sizeof(DBT));

	ret = 0;

	/* For a heap database, the key must be an empty DB_HEAP_RID. */
	key.data = &rid;
	key.size = key.ulen = sizeof(DB_HEAP_RID);
	key.flags = DB_DBT_USERMEM;
	data.data = buf;
	data.flags = DB_DBT_USERMEM;

	/*
	 * Insert a certain number of records into btree database,
	 * the data to insert is generated randomly.
	 */
	for (cnt = start; cnt < (numrecs + start) &&
	    (ret = generate_data(buf, cnt, test_var)) == 0; ++cnt) {
		data.size = data.ulen = (u_int32_t)strlen(buf) + 1;

		/* Require DB_APPEND flag to add new data to the database.*/
		if ((ret = dbp->put(dbp, NULL, &key, &data, DB_APPEND)) != 0) {
			dbenv->err(dbenv, ret, "insert_heap:DB->put");
			break;
		}
	}

	return (ret);
}

/*
 * insert_btree --
 * 	Insert a specified number of records to a btree database,
 *  with keys beginning with a specified value.
 *
 * Parameters:
 *	dbp		the database handle
 *	dbenv		the database environment
 *	numrecs		the number of records to insert
 *	start		the start position to insert records
 *	test_var	test on variable-length data flag
 */

int
insert_btree(dbp, dbenv, numrecs, start, test_var)
	DB *dbp;
	DB_ENV *dbenv;
	int numrecs, start, test_var;
{
	DBT key, data;
	char buf[BUFFER_LEN];
	int cnt, ret;

	memset(&key, 0, sizeof(DBT));
	memset(&data, 0, sizeof(DBT));

	ret = 0;

	key.data = &cnt;
	key.size = key.ulen = sizeof(int);
	key.flags = DB_DBT_USERMEM;
	data.data = buf;
	data.flags = DB_DBT_USERMEM;

	/*
	 * Insert a certain number of records into btree database,
	 * the data to insert is generated by randomly.
	 */
	for (cnt = start; cnt < (numrecs + start) &&
	    (ret = generate_data(buf, cnt, test_var)) == 0; ++cnt) {
		data.size = data.ulen = (u_int32_t)strlen(buf) + 1;

		if ((ret = dbp->put(dbp, NULL, &key, &data, 0)) != 0) {
			dbenv->err(dbenv, ret, "insert_btree:DB->put");
			break;
		}
	}

	return (ret);
}

/*
 * generate_data --
 * 	Generate data for the specified record.
 *
 * Parameters:
 *	buf		the buffer variable to hold data
 *	rec_no		the record number
 *	test_var	test on variable-length data flag
 */

int
generate_data(buf, rec_no, test_var)
	char *buf;
	int rec_no, test_var;
{
	const char *str = "abcdefghijklmnopqrst";
	int len = (int)strlen(str);

	/*
	 * Default use the fix-length data,
	 * if required then use variable-length data.
	 */
	if (test_var == 1)
		len = rand() % (len - 2) + 1;

	(void)sprintf(buf, "%04d_%*s", rec_no, len, str);

	return (0);
}

/*
 * delete_recs --
 * 	Delete a specified number of records.
 *
 * Parameters:
 *	dbp	the database handle
 *	dbenv	the database environment handle
 *	numrecs	number of records to delete
 */

int
delete_recs(dbp, dbenv, numrecs)
	DB *dbp;
	DB_ENV *dbenv;
	int numrecs;
{
	DBC *dbcp;
	DBT key, data;
	int cnt, ret;

	memset(&key, 0, sizeof(DBT));
	memset(&data, 0, sizeof(DBT));

	dbcp = NULL;
	cnt = ret = 0;

	/* Create a cursor to delete records. */
	if ((ret = dbp->cursor(dbp, NULL, &dbcp, 0)) != 0) {
		dbenv->err(dbenv, ret, "delete_recs:DB->cursor");
		goto err;
	}

	/* Delete the first numrecs records. */
	while ((ret = dbcp->get(dbcp, &key, &data, DB_NEXT)) == 0 &&
	    cnt < numrecs) {
		if ((ret = dbcp->del(dbcp, 0)) != 0) {
			dbenv->err(dbenv, ret, "delete_recs:DBCursor->del");
			break;
		} else
			++cnt;
	}

err:
	if (dbcp != NULL && (ret = dbcp->close(dbcp)) != 0)
		dbenv->err(dbenv, ret, "delete_recs:DBCursor->close");

	return (ret);
}

/*
 * usage --
 *	Describe this program's command line options, then exit.
 */
void
usage()
{
	fprintf(stderr, "usage: %s:\n%s \n %s\n", progname,
	    "\t[-b][-c cachesize][-d] -h home [-n recs_per_rep]",
	    "\t[-p pgsize][-r repeats][-S ghpsize][-s hpsize]");

	fprintf(stderr, "-b: run sample application using a btree database.\n");
	fprintf(stderr, "-c: specify the cache size for the environment.\n");
	fprintf(stderr, "-d: test on variable-length data "
	    "(default: fix-length).\n");
	fprintf(stderr, "-h: specify the home directory for "
	    "the environment (required).\n");
	fprintf(stderr, "-n: specify the num. of records "
	    "per repetition (default: %d).\n", DEF_RECS_PER_REP);
	fprintf(stderr, "-p: specify the pgsize of database.\n");
	fprintf(stderr, "-r: number of repetition (a pair of "
	    "insertion and deletion (default: %d)).\n", DEF_REPEATS);
	fprintf(stderr,
	    "-S: specify the heap size (gbytes) for the heap database.\n");
	fprintf(stderr,
	    "-s: specify the heap size (bytes) for the heap database.\n");

	exit(EXIT_FAILURE);
}

/*
 * open_env --
 * 	Open the environment before insert/delete operation
 *
 * Parameters:
 *	dbenvp		the database environment handle
 *	home		the home directory for the environment
 *	cachesize	the cache size for the environment
 */

int
open_env(dbenvp, home, cachesize)
	DB_ENV **dbenvp;
	char *home;
	u_int32_t cachesize;
{
	DB_ENV *dbenv;
	int ret = 0;

	/* Create an environment handle and open an environment. */
	if ((ret = db_env_create(&dbenv, 0)) != 0) {
		fprintf(stderr, "%s: db_env_create: %s\n",
		    progname, db_strerror(ret));
		return (ret);
	}

	*dbenvp = dbenv;

	/*
	 * Prefix any error messages with the name of this program and a ':'.
	 * Setting the errfile to stderr is not necessary, since that is the
	 * default; it is provided here as a placeholder showing where one
	 * could direct error messages to an application-specific log file.
	 */
	dbenv->set_errfile(dbenv, stderr);
	dbenv->set_errpfx(dbenv, progname);

	/* Set cachesize for the database environment. */
	if ((cachesize > 0) && (ret =
	    dbenv->set_cachesize(dbenv, (u_int32_t)0, cachesize, 1)) != 0) {
		dbenv->err(dbenv, ret, "DB_ENV->set_cachesize");
		return (ret);
	}

	if ((ret = dbenv->open(dbenv, home, DB_CREATE | DB_INIT_MPOOL, 0)) != 0)
		dbenv->err(dbenv, ret, "DB_ENV->open");

	return (ret);
}

/*
 * open_db --
 * 	Open the database before insert/delete operation.
 *
 * Parameters:
 *	dbpp	the database handle
 *	dbenv	the database environment
 *	dbtype	the database type
 *	home	the home directory for the environment
 *	gphsize	the heap size (gbytes) for the heap database
 *	hpsize	the heap size (bytes) for the heap database
 *	pgsize	the page size for the heap database
 */
int
open_db(dbpp, dbenv, dbtype, home, ghpsize, hpsize, pgsize)
	DB **dbpp;
	DB_ENV *dbenv;
	DBTYPE dbtype;
	char *home;
	u_int32_t ghpsize, hpsize, pgsize;
{
	DB *dbp;
	u_int32_t dbflags = 0;
	char *dbname;
	int ret = 0;

	dbname = (dbtype == DB_HEAP) ? "heap.db" : "btree.db";

	/* Create a database handle and open a database. */
	if ((ret = db_create(&dbp, dbenv, 0)) != 0) {
		dbenv->err(dbenv, ret, "db_create : %s", dbname);
		goto err;
	}

	*dbpp = dbp;

	/* Set the record compare function for the btree database. */
	if ((dbtype == DB_BTREE) &&
	    (ret = dbp->set_bt_compare(dbp, compare_int)) != 0) {
		dbp->err(dbp, ret, "DB->set_bt_compare");
		goto err;
	}

	/* Set heap size for the heap database. */
	if ((dbtype == DB_HEAP) && (ghpsize > 0 || hpsize > 0) &&
	    (ret = dbp->set_heapsize(dbp, ghpsize, hpsize, 0)) != 0) {
		dbenv->err(dbenv, ret, "DB->set_heapsize");
		return (ret);
	}
	/* Set page size for the database. */
	if ((pgsize > 0) && (ret = dbp->set_pagesize(dbp, pgsize)) != 0) {
		dbenv->err(dbenv, ret, "DB->set_pagesize");
		return (ret);
	}

	if ((ret =
	    dbp->open(dbp, NULL, dbname, NULL, dbtype, DB_CREATE, 0)) != 0)
		dbenv->err(dbenv, ret, "DB->open");
err:

	return (ret);
}

/*
 * compare_int --
 * 	Compare two data value for btree database.
 *
 * Parameters:
 *	dbp	the database handle
 *	a	one of the data value use to compare
 *	b	another data value use to compare
 *	locp	lock handle
 */
int
compare_int(dbp, a, b, locp)
	DB *dbp;
	const DBT *a, *b;
	size_t *locp;
{
	int ai, bi;

	dbp = NULL;
	locp = NULL;

	/*
	 * Returns:
	 *	< 0 if a < b
	 *	= 0 if a = b
	 *	> 0 if a > b
	 */
	memcpy(&ai, a->data, sizeof(int));
	memcpy(&bi, b->data, sizeof(int));
	return (ai - bi);
}


text:
<?php

/**
 * Defines a decorator to handle form field errors
 *
 * @category Form
 * @package Twitter_Bootstrap_Form
 * @subpackage Decorator
 * @author Christian Soronellas <csoronellas@emagister.com>
 */

/**
 * A decorator to render the form element errors
 *
 * @category Form
 * @package Twitter_Bootstrap_Form
 * @subpackage Decorator
 * @author Christian Soronellas <csoronellas@emagister.com>
 */
class Twitter_Bootstrap_Form_Decorator_PopoverElementErrors extends Zend_Form_Decorator_Abstract
{

    /**
     * Decorate content and/or elementRender the element
     *
     * @param string $content
     * @return string
     */
    public function render ($content)
    {
        if (! $this->getElement()->hasErrors()) {
            return $content;
        }

        $errors = implode('
', $this->getElement()->getMessages());

        return '' . $content . '';
    }
}

redpajama_set_name: RedPajamaGithub


text:
Ever wanted your notes to be accesible from everywhere and be able to share them? Say hello to mrnote.
## In action
Currently down.
Just clone the repo and try it!
## Usage
It's simple.
On the start site, you can create a new noteboard.
Give it a cool name, a not too complicated key and you are ready to go.
You can decide if you want to make your board publicly available or not.
What's the difference? If it's public, at entrance no key is requested.

Later on, if you want to edit your board, you need to enter the correct URL:
	mrnote.xyz/:yourBoardName/:yourBoardPassword
Now you can add, remove or edit notes.

If the password is left away, the board can't be edited, but only viewed (if it's public).

Now, share your board by a link!

## Stack

### Frontend
- React for UI
- MobX for reactive state managment
- Webpack for bundling

### Backend
- nodejs
- express
- mongodb


text:
local ImageClassFactory, parent = torch.class("dp.ImageClassFactory", "dp.DatasourceFactory")
ImageClassFactory.isImageClassFactory = true

function ImageClassFactory:__init(...)
   parent.__init(self, {name='ImageClass'})
end

function ImageClassFactory:build(opt)
   local datasource
   if self._cache[opt.datasource] then
      datasource = self._cache[opt.datasource]
      assert(torch.typename(datasource))
   else
      datasource = dp[opt.datasource]{
         valid_ratio=opt.valid_ratio,
         input_preprocess=self:buildInputPreprocess(opt)
      }
      self._cache[opt.datasource] = datasource
   end
   opt.feature_size = datasource:featureSize()
   opt.nClasses = #datasource:classes()
   return datasource
end

function ImageClassFactory:buildInputPreprocess(opt)
   local input_preprocess
   if opt.zca_gcn then
      input_preprocess = {dp.GCN(),dp.ZCA()} --order is important
   elseif opt.standardize then
      input_preprocess = dp.Standardize()
   elseif opt.lecunlcn then
      input_preprocess = dp.LeCunLCN()
   end
   return input_preprocess
end


text:
const AppConstants = {
  api: 'http://localhost:3000/api',
  appName: 'skillGardener'
};

export default AppConstants;


text:
import config from '../../../../config';
import objectPool from '../../../../object-pool';
import { load } from '../../../../save';
import { tileToPixel } from '../../../../tiles';

import Tree from '../../../../sprites/object/Tree';
import PineCone from '../../../../sprites/object/PineCone';
import Log from '../../../../sprites/object/Log';
import Water from '../../../../sprites/object/Water';
import House from '../../../../sprites/object/House';

import Chopper from '../../../../sprites/character/Chopper';
import Collector from '../../../../sprites/character/Collector';

const objectTypes = {
  tree: Tree,
  'pine-cone': PineCone,
  log: Log,
  water: Water,
  house: House,
  chopper: Chopper,
  collector: Collector,
};

export default function loadFromSave() {
  const fastMap = load('world.fastMap');

  for (let tileY = 0; tileY < config.mapHeight; tileY++) {
    for (let tileX = 0; tileX < config.mapWidth; tileX++) {
      if (fastMap[tileY][tileX].length === 0) continue;

      for (let i = 0; i < fastMap[tileY][tileX].length; i++) {
        spawnObject.call(this, fastMap[tileY][tileX][i], tileX, tileY);
      }
    }
  }
}

function spawnObject(objectType, tileX, tileY) {
  if (objectType === 'player') return;

  const start = tileToPixel(tileX, tileY);

  const props = {
    game: this.game,
    x: start.x,
    y: start.y,
  };

  if (objectType === 'planted-pine-cone') {
    props.placed = true;
    objectType = 'pine-cone';
  }

  const object = objectPool.new(objectType, objectTypes[objectType], props);

  if (props.placed && object.hasOwnProperty('place')) object.place();
}


text:
/* global beforeEach, describe, it */

var _ = require('lodash');
var expect = require('salinity').expect;

var ObjectBuilder = require('../lib/objectBuilder.js');

describe('objectBuilder.js', function(){
  var objBuilder = null;
  var REQUIRED = '**REQUIRED**';
  var OPTIONAL = '**OPTIONAL**';
  var bob;

  beforeEach(function(){
    bob = ObjectBuilder();
  });

  describe('setDefaults', function(){
    it('works', function(){

      var defaults = {deviceId:'123-gg-33-4rrr'};

      bob.setDefaults(defaults);

      var dualBolus = bob.makeDualBolus();

      expect(dualBolus.deviceId).to.equal(defaults.deviceId);

    });
  });

  describe('makeBloodKetone', function(){

    var defaults = {deviceId:'makeBloodKetone'};

    beforeEach(function(){
      bob = ObjectBuilder();
      bob.setDefaults(defaults);
    });

    it('works', function(){
      var bk = bob.makeBloodKetone();

      expect(bk.deviceId).to.equal(defaults.deviceId);
      expect(bk.type).to.equal('bloodKetone');
      expect(bk.time).to.equal(REQUIRED);
      expect(bk.timezoneOffset).to.equal(REQUIRED);
      expect(bk.conversionOffset).to.equal(REQUIRED);
      expect(bk.deviceTime).to.equal(REQUIRED);
      expect(bk.value).to.equal(REQUIRED);
      expect(bk.units).to.equal('mmol/L');

      expect(bk.payload).to.equal(OPTIONAL);
    });
  });

  describe('makeCBG', function(){

    var defaults = {deviceId:'makeCBG'};

    beforeEach(function(){
      bob = ObjectBuilder();
      bob.setDefaults(defaults);
    });

    it('works', function(){
      var cbg = bob.makeCBG();

      expect(cbg.deviceId).to.equal(defaults.deviceId);
      expect(cbg.type).to.equal('cbg');
      expect(cbg.time).to.equal(REQUIRED);
      expect(cbg.timezoneOffset).to.equal(REQUIRED);
      expect(cbg.conversionOffset).to.equal(REQUIRED);
      expect(cbg.deviceTime).to.equal(REQUIRED);
      expect(cbg.value).to.equal(REQUIRED);
      expect(cbg.units).to.equal(REQUIRED);

      expect(cbg.payload).to.equal(OPTIONAL);
    });
  });

  describe('makeCGMSettings', function(){

    var defaults = {deviceId:'makeCGMSettings'};

    beforeEach(function(){
      bob = ObjectBuilder();
      bob.setDefaults(defaults);
    });

    it('works', function(){
      var settings = bob.makeCGMSettings();

      expect(settings.deviceId).to.equal(defaults.deviceId);
      expect(settings.type).to.equal('cgmSettings');
      expect(settings.time).to.equal(REQUIRED);
      expect(settings.timezoneOffset).to.equal(REQUIRED);
      expect(settings.conversionOffset).to.equal(REQUIRED);
      expect(settings.deviceTime).to.equal(REQUIRED);
      expect(settings.transmitterId).to.equal(REQUIRED);
      expect(settings.units).to.equal(REQUIRED);
      expect(settings.lowAlerts).to.equal(REQUIRED);
      expect(settings.highAlerts).to.equal(REQUIRED);
      expect(settings.rateOfChangeAlerts).to.equal(REQUIRED);

      expect(settings.outOfRangeAlerts).to.equal(OPTIONAL);
      expect(settings.predictiveAlerts).to.equal(OPTIONAL);
      expect(settings.displayUnits).to.equal(OPTIONAL);
      expect(settings.calibrationAlerts).to.equal(OPTIONAL);
      expect(settings.payload).to.equal(OPTIONAL);
    });
  });

  describe('makeDeviceEventAlarm', function(){

    var defaults = {deviceId:'makeDeviceEventAlarm'};

    beforeEach(function(){
      bob = ObjectBuilder();
      bob.setDefaults(defaults);
    });

    it('works', function(){
      var alarm = bob.makeDeviceEventAlarm();

      expect(alarm.deviceId).to.equal(defaults.deviceId);
      expect(alarm.type).to.equal('deviceEvent');
      expect(alarm.subType).to.equal('alarm');
      expect(alarm.time).to.equal(REQUIRED);
      expect(alarm.timezoneOffset).to.equal(REQUIRED);
      expect(alarm.conversionOffset).to.equal(REQUIRED);
      expect(alarm.deviceTime).to.equal(REQUIRED);
      expect(alarm.alarmType).to.equal(REQUIRED);

      expect(alarm.status).to.equal(OPTIONAL);
      expect(alarm.payload).to.equal(OPTIONAL);
    });
  });

  describe('makeDeviceEventCalibration', function(){

    var defaults = {deviceId:'makeDeviceEventCalibration'};

    beforeEach(function(){
      bob = ObjectBuilder();
      bob.setDefaults(defaults);
    });

    it('works', function(){
      var cal = bob.makeDeviceEventCalibration();

      expect(cal.deviceId).to.equal(defaults.deviceId);
      expect(cal.type).to.equal('deviceEvent');
      expect(cal.subType).to.equal('calibration');
      expect(cal.time).to.equal(REQUIRED);
      expect(cal.timezoneOffset).to.equal(REQUIRED);
      expect(cal.conversionOffset).to.equal(REQUIRED);
      expect(cal.deviceTime).to.equal(REQUIRED);
      expect(cal.value).to.equal(REQUIRED);
      expect(cal.units).to.equal(REQUIRED);

      expect(cal.payload).to.equal(OPTIONAL);
    });
  });

  describe('makeDeviceEventReservoirChange', function(){

    var defaults = {deviceId:'makeDeviceEventReservoirChange'};

    beforeEach(function(){
      bob = ObjectBuilder();
      bob.setDefaults(defaults);
    });

    it('works', function(){
      var reschange = bob.makeDeviceEventReservoirChange();

      expect(reschange.deviceId).to.equal(defaults.deviceId);
      expect(reschange.type).to.equal('deviceEvent');
      expect(reschange.subType).to.equal('reservoirChange');
      expect(reschange.time).to.equal(REQUIRED);
      expect(reschange.timezoneOffset).to.equal(REQUIRED);
      expect(reschange.conversionOffset).to.equal(REQUIRED);
      expect(reschange.deviceTime).to.equal(REQUIRED);

      expect(reschange.status).to.equal(OPTIONAL);
      expect(reschange.payload).to.equal(OPTIONAL);
    });
  });

  describe('makedeviceEventResume', function(){

    var defaults = {deviceId:'makeDeviceEventResume'};

    beforeEach(function(){
      bob = ObjectBuilder();
      bob.setDefaults(defaults);
    });

    it('works', function(){
      var resumeMeta = bob.makeDeviceEventResume();

      expect(resumeMeta.deviceId).to.equal(defaults.deviceId);
      expect(resumeMeta.type).to.equal('deviceEvent');
      expect(resumeMeta.subType).to.equal('status');
      expect(resumeMeta.time).to.equal(REQUIRED);
      expect(resumeMeta.timezoneOffset).to.equal(REQUIRED);
      expect(resumeMeta.conversionOffset).to.equal(REQUIRED);
      expect(resumeMeta.deviceTime).to.equal(REQUIRED);
      expect(resumeMeta.status).to.equal('resumed');
      expect(resumeMeta.reason).to.equal(REQUIRED);

      expect(resumeMeta.previous).to.equal(OPTIONAL);
      expect(resumeMeta.payload).to.equal(OPTIONAL);
    });
  });

  describe('makedeviceEventSuspend', function(){

    var defaults = {deviceId:'makeDeviceEventSuspend'};

    beforeEach(function(){
      bob = ObjectBuilder();
      bob.setDefaults(defaults);
    });

    it('works', function(){
      var suspendMeta = bob.makeDeviceEventSuspend();

      expect(suspendMeta.deviceId).to.equal(defaults.deviceId);
      expect(suspendMeta.type).to.equal('deviceEvent');
      expect(suspendMeta.subType).to.equal('status');
      expect(suspendMeta.time).to.equal(REQUIRED);
      expect(suspendMeta.timezoneOffset).to.equal(REQUIRED);
      expect(suspendMeta.conversionOffset).to.equal(REQUIRED);
      expect(suspendMeta.deviceTime).to.equal(REQUIRED);
      expect(suspendMeta.status).to.equal('suspended');
      expect(suspendMeta.reason).to.equal(REQUIRED);

      expect(suspendMeta.previous).to.equal(OPTIONAL);
      expect(suspendMeta.payload).to.equal(OPTIONAL);
    });
  });

  describe('makeDeviceEventTimeChange', function(){

    var defaults = {deviceId:'makeDeviceEventTimeChange'};

    beforeEach(function(){
      bob = ObjectBuilder();
      bob.setDefaults(defaults);
    });

    it('works', function(){
      var timechange = bob.makeDeviceEventTimeChange();

      expect(timechange.deviceId).to.equal(defaults.deviceId);
      expect(timechange.type).to.equal('deviceEvent');
      expect(timechange.subType).to.equal('timeChange');
      expect(timechange.time).to.equal(REQUIRED);
      expect(timechange.timezoneOffset).to.equal(REQUIRED);
      expect(timechange.conversionOffset).to.equal(REQUIRED);
      expect(timechange.deviceTime).to.equal(REQUIRED);
      expect(timechange.change).to.equal(REQUIRED);

      expect(timechange.payload).to.equal(OPTIONAL);
    });
  });

  describe('makeDualBolus', function(){

    var defaults = {deviceId:'makeDualBolus'};

    beforeEach(function(){
      bob = ObjectBuilder();
      bob.setDefaults(defaults);
    });

    it('works', function(){
      var dualBolus = bob.makeDualBolus();

      expect(dualBolus.deviceId).to.equal(defaults.deviceId);
      expect(dualBolus.type).to.equal('bolus');
      expect(dualBolus.subType).to.equal('dual/square');
      expect(dualBolus.time).to.equal(REQUIRED);
      expect(dualBolus.timezoneOffset).to.equal(REQUIRED);
      expect(dualBolus.conversionOffset).to.equal(REQUIRED);
      expect(dualBolus.deviceTime).to.equal(REQUIRED);
      expect(dualBolus.normal).to.equal(REQUIRED);
      expect(dualBolus.extended).to.equal(REQUIRED);
      expect(dualBolus.duration).to.equal(REQUIRED);

      expect(dualBolus.payload).to.equal(OPTIONAL);
    });
  });

  describe('makeFood', function(){

    var defaults = {deviceId:'makeFood'};

    beforeEach(function(){
      bob = ObjectBuilder();
      bob.setDefaults(defaults);
    });

    it('works', function(){
      var food = bob.makeFood();

      expect(food.deviceId).to.equal(defaults.deviceId);
      expect(food.type).to.equal('food');
      expect(food.time).to.equal(REQUIRED);
      expect(food.timezoneOffset).to.equal(REQUIRED);
      expect(food.conversionOffset).to.equal(REQUIRED);
      expect(food.deviceTime).to.equal(REQUIRED);
      expect(food.carbs).to.equal(REQUIRED);

      expect(food.payload).to.equal(OPTIONAL);
    });
  });

  describe('makeNormalBolus', function(){

    var defaults = {deviceId:'makeNormalBolus'};

    beforeEach(function(){
      bob = ObjectBuilder();
      bob.setDefaults(defaults);
    });

    it('works', function(){
      var normal = bob.makeNormalBolus();

      expect(normal.deviceId).to.equal(defaults.deviceId);
      expect(normal.type).to.equal('bolus');
      expect(normal.subType).to.equal('normal');
      expect(normal.time).to.equal(REQUIRED);
      expect(normal.timezoneOffset).to.equal(REQUIRED);
      expect(normal.conversionOffset).to.equal(REQUIRED);
      expect(normal.deviceTime).to.equal(REQUIRED);
      expect(normal.normal).to.equal(REQUIRED);

      expect(normal.payload).to.equal(OPTIONAL);
    });
  });

  describe('makeNote', function(){

    var defaults = {deviceId:'makeNormalBolus'};

    beforeEach(function(){
      bob = ObjectBuilder();
      bob.setDefaults(defaults);
    });

    it('works', function(){
      var note = bob.makeNote();

      expect(note.deviceId).to.equal(defaults.deviceId);
      expect(note.type).to.equal('note');
      expect(note.time).to.equal(REQUIRED);
      expect(note.timezoneOffset).to.equal(REQUIRED);
      expect(note.conversionOffset).to.equal(REQUIRED);
      expect(note.deviceTime).to.equal(REQUIRED);
      expect(note.value).to.equal(REQUIRED);

      expect(note.payload).to.equal(OPTIONAL);
    });
  });

  describe('makePumpSettings', function(){

    var defaults = {deviceId:'makePumpSettings'};

    beforeEach(function(){
      bob = ObjectBuilder();
      bob.setDefaults(defaults);
    });

    it('works', function(){
      var settings = bob.makePumpSettings();

      expect(settings.deviceId).to.equal(defaults.deviceId);
      expect(settings.type).to.equal('pumpSettings');
      expect(settings.time).to.equal(REQUIRED);
      expect(settings.timezoneOffset).to.equal(REQUIRED);
      expect(settings.conversionOffset).to.equal(REQUIRED);
      expect(settings.deviceTime).to.equal(REQUIRED);
      expect(settings.activeSchedule).to.equal(REQUIRED);
      expect(settings.units).to.equal(REQUIRED);
      expect(settings.basalSchedules).to.deep.equal({});
      expect(settings.carbRatio).to.deep.equal([]);
      expect(settings.insulinSensitivity).to.deep.equal([]);
      expect(settings.bgTarget).to.deep.equal([]);

      expect(settings.payload).to.equal(OPTIONAL);
    });
  });

  describe('makeScheduledBasal', function(){

    var defaults = {deviceId:'makeScheduledBasal'};

    beforeEach(function(){
      bob = ObjectBuilder();
      bob.setDefaults(defaults);
    });

    it('works', function(){
      var schedBasal = bob.makeScheduledBasal();

      expect(schedBasal.deviceId).to.equal(defaults.deviceId);
      expect(schedBasal.deliveryType).to.equal('scheduled');
      expect(schedBasal.type).to.equal('basal');
      expect(schedBasal.time).to.equal(REQUIRED);
      expect(schedBasal.timezoneOffset).to.equal(REQUIRED);
      expect(schedBasal.conversionOffset).to.equal(REQUIRED);
      expect(schedBasal.deviceTime).to.equal(REQUIRED);
      expect(schedBasal.duration).to.equal(REQUIRED);

      expect(schedBasal.previous).to.equal(OPTIONAL);
      expect(schedBasal.payload).to.equal(OPTIONAL);
    });
  });

  describe('makeSMBG', function(){

    var defaults = {deviceId:'makeSMBG'};

    beforeEach(function(){
      bob = ObjectBuilder();
      bob.setDefaults(defaults);
    });

    it('works', function(){
      var smbg = bob.makeSMBG();

      expect(smbg.deviceId).to.equal(defaults.deviceId);
      expect(smbg.type).to.equal('smbg');
      expect(smbg.time).to.equal(REQUIRED);
      expect(smbg.timezoneOffset).to.equal(REQUIRED);
      expect(smbg.conversionOffset).to.equal(REQUIRED);
      expect(smbg.deviceTime).to.equal(REQUIRED);
      expect(smbg.value).to.equal(REQUIRED);
      expect(smbg.units).to.equal(REQUIRED);

      expect(smbg.subType).to.equal(OPTIONAL);
      expect(smbg.payload).to.equal(OPTIONAL);
    });
  });

  describe('makeSquareBolus', function(){

    var defaults = {deviceId:'makeSquareBolus'};

    beforeEach(function(){
      bob = ObjectBuilder();
      bob.setDefaults(defaults);
    });

    it('works', function(){
      var square = bob.makeSquareBolus();

      expect(square.deviceId).to.equal(defaults.deviceId);
      expect(square.type).to.equal('bolus');
      expect(square.subType).to.equal('square');
      expect(square.time).to.equal(REQUIRED);
      expect(square.timezoneOffset).to.equal(REQUIRED);
      expect(square.conversionOffset).to.equal(REQUIRED);
      expect(square.deviceTime).to.equal(REQUIRED);
      expect(square.extended).to.equal(REQUIRED);
      expect(square.duration).to.equal(REQUIRED);

      expect(square.payload).to.equal(OPTIONAL);
    });
  });

  describe('makeSuspendBasal', function(){

    var defaults = {deviceId:'makeSuspendBasal'};

    beforeEach(function(){
      bob = ObjectBuilder();
      bob.setDefaults(defaults);
    });

    it('works', function(){
      var suspendBasal = bob.makeSuspendBasal();

      expect(suspendBasal.deviceId).to.equal(defaults.deviceId);
      expect(suspendBasal.deliveryType).to.equal('suspend');
      expect(suspendBasal.type).to.equal('basal');
      expect(suspendBasal.time).to.equal(REQUIRED);
      expect(suspendBasal.timezoneOffset).to.equal(REQUIRED);
      expect(suspendBasal.conversionOffset).to.equal(REQUIRED);
      expect(suspendBasal.deviceTime).to.equal(REQUIRED);

      expect(suspendBasal.duration).to.equal(OPTIONAL);
      expect(suspendBasal.suppressed).to.equal(OPTIONAL);
      expect(suspendBasal.previous).to.equal(OPTIONAL);
      expect(suspendBasal.payload).to.equal(OPTIONAL);
    });
  });

  describe('makeTempBasal', function(){

    var defaults = {deviceId:'makeTempBasal'};

    beforeEach(function(){
      bob = ObjectBuilder();
      bob.setDefaults(defaults);
    });

    it('works', function(){
      var temp = bob.makeTempBasal();

      expect(temp.deviceId).to.equal(defaults.deviceId);
      expect(temp.type).to.equal('basal');
      expect(temp.deliveryType).to.equal('temp');
      expect(temp.time).to.equal(REQUIRED);
      expect(temp.timezoneOffset).to.equal(REQUIRED);
      expect(temp.conversionOffset).to.equal(REQUIRED);
      expect(temp.deviceTime).to.equal(REQUIRED);
      expect(temp.duration).to.equal(REQUIRED);

      expect(temp.rate).to.equal(OPTIONAL);
      expect(temp.percent).to.equal(OPTIONAL);
      expect(temp.previous).to.equal(OPTIONAL);
      expect(temp.suppressed).to.equal(OPTIONAL);
      expect(temp.payload).to.equal(OPTIONAL);
    });
  });

  describe('makeWizard', function(){

    var defaults = {deviceId:'makeWizard'};

    beforeEach(function(){
      bob = ObjectBuilder();
      bob.setDefaults(defaults);
    });

    it('works', function(){
      var wiz = bob.makeWizard();

      expect(wiz.deviceId).to.equal(defaults.deviceId);
      expect(wiz.type).to.equal('wizard');
      expect(wiz.time).to.equal(REQUIRED);
      expect(wiz.timezoneOffset).to.equal(REQUIRED);
      expect(wiz.conversionOffset).to.equal(REQUIRED);
      expect(wiz.deviceTime).to.equal(REQUIRED);
      expect(wiz.insulinOnBoard).to.equal(REQUIRED);
      expect(wiz.insulinCarbRatio).to.equal(REQUIRED);
      expect(wiz.insulinSensitivity).to.equal(REQUIRED);
      expect(wiz.bgTarget).to.equal(REQUIRED);
      expect(wiz.bolus).to.equal(REQUIRED);
      expect(wiz.recommended).to.equal(REQUIRED);
      expect(wiz.units).to.equal(REQUIRED);

      expect(wiz.bgInput).to.equal(OPTIONAL);
      expect(wiz.carbInput).to.equal(OPTIONAL);
      expect(wiz.payload).to.equal(OPTIONAL);
    });
  });

  describe('makeUpload', function(){

    var defaults = {};

    beforeEach(function(){
      bob = ObjectBuilder();
      bob.setDefaults(defaults);
    });

    it('works', function(){
      var upload = bob.makeUpload();

      expect(upload.deviceId).to.equal(REQUIRED);
      expect(upload.type).to.equal('upload');
      expect(upload.time).to.equal(REQUIRED);
      expect(upload.timezoneOffset).to.equal(REQUIRED);
      expect(upload.conversionOffset).to.equal(REQUIRED);
      expect(upload.computerTime).to.equal(REQUIRED);
      expect(upload.timezone).to.equal(REQUIRED);
      expect(upload.timeProcessing).to.equal(REQUIRED);
      expect(upload.version).to.equal(REQUIRED);
      expect(upload.timezone).to.equal(REQUIRED);
      expect(upload.guid).to.equal(REQUIRED);
      expect(upload.uploadId).to.equal(REQUIRED);
      expect(upload.byUser).to.equal(REQUIRED);
      expect(upload.deviceTags).to.equal(REQUIRED);
      expect(upload.deviceManufacturers).to.equal(REQUIRED);
      expect(upload.deviceModel).to.equal(REQUIRED);
      expect(upload.deviceSerialNumber).to.equal(REQUIRED);

      expect(upload.source).to.equal(OPTIONAL);
      expect(upload.payload).to.equal(OPTIONAL);
    });
  });

});


text:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:layout_marginStart="@dimen/clip_overlay_margin_horizontal"
    android:layout_marginEnd="@dimen/clip_overlay_margin_horizontal"
    android:layout_marginTop="@dimen/clip_overlay_margin_vertical"
    android:layout_marginBottom="@dimen/clip_overlay_margin_vertical"
    app:cardCornerRadius="0dp"
    app:cardElevation="8dp">

    <ImageView
        android:id="@+id/poster"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:minHeight="@dimen/clip_overlay_height_min"
        android:contentDescription="@null"
        android:scaleType="centerCrop"
        android:alpha="0.08" />

    <TextView
        android:id="@+id/transcript"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="@dimen/clip_overlay_text_margin_horizontal"
        android:layout_marginEnd="@dimen/clip_overlay_text_margin_horizontal"
        android:layout_marginTop="@dimen/clip_overlay_text_margin_vertical"
        android:layout_marginBottom="@dimen/clip_overlay_text_margin_vertical"
        android:layout_gravity="center_vertical"
        style="@style/TextAppearance.AppCompat.Title" />

</android.support.v7.widget.CardView>


text:
module DocxGenerator
  module DSL
    # Represent the docx document.
    class Document
      # Filename of the document (without the docx extension).
      attr_reader :filename

      # Create a new docx document.
      # @param filename [String] The filename of the docx file, without the docx extension.
      def initialize(filename, &block)
        @filename = filename + ".docx"
        @objects = [] # It contains all the DSL elements
        yield self if block
      end

      # Save the docx document to the target location.
      def save
        generate_archive(generate_content_types, generate_rels, generate_document)
      end

      # Add a new paragraph to the document.
      # @param options [Hash] Formatting options for the paragraph. See the full list in DocxGenerator::DSL::Paragraph.
      def paragraph(options = {}, &block)
        par = DocxGenerator::DSL::Paragraph.new(options)
        yield par if block
        @objects << par
      end

      # Add other objects to the document.
      # @param objects [Object] Objects (like paragraphs).
      # @return [DocxGenerator::DSL::Document] The document object.
      def add(*objects)
        objects.each do |object|
          @objects << object
        end
        self
      end

      private

        def generate_content_types
          <<EOF
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">
  <Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>
  <Default Extension="xml" ContentType="application/xml"/>
  <Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/>
</Types>
EOF
        end

        def generate_rels
          <<EOF
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
  <Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/>
</Relationships>
EOF
        end

        def generate_document
          content = []
          @objects.each do |object|
            content << object.generate
          end

          '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' +
          Word::Document.new({ "xmlns:w" => "http://schemas.openxmlformats.org/wordprocessingml/2006/main" },
            [ Word::Body.new(content) ]).to_s
        end

        def generate_archive(content_types, rels, document)
          File.delete(@filename) if File.exists?(@filename)
          Zip::File.open(@filename, Zip::File::CREATE) do |docx|
            docx.mkdir('_rels')
            docx.mkdir('word')
            docx.get_output_stream('[Content_Types].xml') { |f| f.puts content_types }
            docx.get_output_stream('_rels/.rels') { |f| f.puts rels }
            docx.get_output_stream('word/document.xml') { |f| f.puts document }
          end
        end
    end
  end
end


text:
package org.apache.oodt.cas.workflow.repository;

//JDK imports
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.sql.SQLException;
import javax.sql.DataSource;

//OODT imports
import org.apache.oodt.commons.database.DatabaseConnectionBuilder;
import org.apache.oodt.commons.database.SqlScript;
import org.apache.oodt.cas.metadata.Metadata;
import org.apache.oodt.cas.workflow.structs.Workflow;
import org.apache.oodt.cas.workflow.structs.WorkflowCondition;
import org.apache.oodt.cas.workflow.structs.WorkflowConditionInstance;
import org.apache.oodt.cas.workflow.structs.exceptions.RepositoryException;
import org.apache.oodt.cas.workflow.util.GenericWorkflowObjectFactory;

//Junit imports
import junit.framework.TestCase;

/**
 * @author mattmann
 * @version $Revision$
 *
 * <p>
 * Test suite for the {@link DataSourceCatalog} and
 * {@link DataSourceCatalogFactory}.
 * </p>.
 */
public class TestWorkflowDataSourceRepository extends TestCase {

    private String tmpDirPath = null;

    private DataSource ds;

    public TestWorkflowDataSourceRepository() throws SQLException, FileNotFoundException {
        // set the log levels
        System.setProperty("java.util.logging.config.file", new File(
                "./src/main/resources/logging.properties").getAbsolutePath());

        // first load the example configuration
        try {
            System.getProperties().load(
                    new FileInputStream("./src/main/resources/workflow.properties"));
        } catch (Exception e) {
            fail(e.getMessage());
        }

        // get a temp directory
        File tempDir = null;
        File tempFile = null;

        try {
            tempFile = File.createTempFile("foo", "bar");
            tempFile.deleteOnExit();
            tempDir = tempFile.getParentFile();
        } catch (Exception e) {
            fail(e.getMessage());
        }

        tmpDirPath = tempDir.getAbsolutePath();
    }

    /*
     * (non-Javadoc)
     *
     * @see junit.framework.TestCase#setUp()
     */
    protected void setUp() throws Exception {
        ds = DatabaseConnectionBuilder.buildDataSource("sa", "", "org.hsqldb.jdbcDriver", "jdbc:hsqldb:file:" + tmpDirPath + "/testCat;shutdown=true");
        SqlScript coreSchemaScript = new SqlScript("src/test/resources/workflow.sql", ds);
        coreSchemaScript.loadScript();
        coreSchemaScript.execute();
        ds.getConnection().commit();
    }

    /*
     * (non-Javadoc)
     *
     * @see junit.framework.TestCase#tearDown()
     */
    protected void tearDown() throws Exception {
        ds.getConnection().close();
    }

    /**
     * @since OODT-205
     */
    public void testWorkflowConditions(){
      DataSourceWorkflowRepository repo = new DataSourceWorkflowRepository(ds);

      Workflow w = null;
      try{
        w = repo.getWorkflowById("1");
      }
      catch(Exception e){
        fail(e.getMessage());
      }

      assertNotNull(w);
      assertNotNull(w.getConditions());
      assertTrue(w.getConditions().size() > 0);
      assertEquals(w.getConditions().size(), 1);
    }

    public void testDataSourceRepo() throws SQLException, RepositoryException {
        DataSourceWorkflowRepository repo = new DataSourceWorkflowRepository(ds);

        //test id 1
        WorkflowCondition wc = repo.getWorkflowConditionById("1");
        assertEquals(wc.getConditionName(), "CheckCond");
        WorkflowConditionInstance condInst = GenericWorkflowObjectFactory.getConditionObjectFromClassName(wc.getConditionInstanceClassName());
        Metadata m = new Metadata();
        m.addMetadata("Met1", "Val1");
        m.addMetadata("Met2", "Val2");
        m.addMetadata("Met3", "Val3");
        assertTrue(condInst.evaluate(m, wc.getTaskConfig()));

        //test id 2
        wc = repo.getWorkflowConditionById("2");
        assertEquals(wc.getConditionName(), "FalseCond");
        condInst = GenericWorkflowObjectFactory.getConditionObjectFromClassName(wc.getConditionInstanceClassName());
        assertFalse(condInst.evaluate(m, wc.getTaskConfig()));

        //test id 3
        wc = repo.getWorkflowConditionById("3");
        assertEquals(wc.getConditionName(), "TrueCond");
        condInst = GenericWorkflowObjectFactory.getConditionObjectFromClassName(wc.getConditionInstanceClassName());
        assertTrue(condInst.evaluate(m, wc.getTaskConfig()));
    }

}


text:
module Rails
  class GemDependency
    attr_accessor :name, :requirement, :version, :lib, :source

    def self.unpacked_path
      @unpacked_path ||= File.join(RAILS_ROOT, 'vendor', 'gems')
    end

    def initialize(name, options = {})
      require 'rubygems' unless Object.const_defined?(:Gem)

      if options[:requirement]
        @requirement = options[:requirement]
      elsif options[:version]
        @requirement = Gem::Requirement.create(options[:version])
      end

      @version  = @requirement.instance_variable_get("@requirements").first.last if @requirement
      @name     = name.to_s
      @lib      = options[:lib]
      @source   = options[:source]
      @loaded   = @frozen = @load_paths_added = false
      @unpack_directory = nil
    end

    def add_load_paths
      return if @loaded || @load_paths_added
      unpacked_paths = Dir[File.join(self.class.unpacked_path, "#{@name}-#{@version || "*"}")]
      if unpacked_paths.empty?
        args = [@name]
        args << @requirement.to_s if @requirement
        gem *args
      else
        $LOAD_PATH << File.join(unpacked_paths.first, 'lib')
        @frozen = true
      end
      @load_paths_added = true
    rescue Gem::LoadError
      puts $!.to_s
    end

    def dependencies
      all_dependencies = specification.dependencies.map do |dependency|
        GemDependency.new(dependency.name, :requirement => dependency.version_requirements)
      end
      all_dependencies += all_dependencies.map(&:dependencies).flatten
      all_dependencies.uniq
    end

    def gem_dir(base_directory)
      File.join(base_directory, specification.full_name)
    end

    def load
      return if @loaded || @load_paths_added == false
      require(@lib || @name)
      @loaded = true
    rescue LoadError
      puts $!.to_s
      $!.backtrace.each { |b| puts b }
    end

    def frozen?
      @frozen
    end

    def loaded?
      @loaded
    end

    def load_paths_added?
      @load_paths_added
    end

    def install
      Gem::GemRunner.new.run(install_command)
    end

    def unpack_to(directory)
      FileUtils.mkdir_p directory
      Dir.chdir directory do
        Gem::GemRunner.new.run(unpack_command)
      end

      # copy the gem's specification into GEMDIR/.specification so that
      # we can access information about the gem on deployment systems
      # without having the gem installed
      spec_filename = File.join(gem_dir(directory), '.specification')
      File.open(spec_filename, 'w') do |file|
        file.puts specification.to_yaml
      end
    end

    def ==(other)
      self.name == other.name && self.requirement == other.requirement
    end

private ###################################################################

    def specification
      @spec ||= Gem.source_index.search(Gem::Dependency.new(@name, @requirement)).sort_by { |s| s.version }.last
    end

    def install_command
      cmd = %w(install) << @name
      cmd << "--version" << "#{@requirement.to_s}" if @requirement
      cmd << "--source"  << @source  if @source
      cmd
    end

    def unpack_command
      cmd = %w(unpack) << @name
      cmd << "--version" << "#{@requirement.to_s}" if @requirement
      cmd
    end
  end
end


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta name="collection" content="api">

<TITLE>
HashMap (Java 2 Platform SE 5.0)
</TITLE>

<META NAME="keywords" CONTENT="java.util.HashMap class">
<META NAME="keywords" CONTENT="size()">
<META NAME="keywords" CONTENT="isEmpty()">
<META NAME="keywords" CONTENT="get()">
<META NAME="keywords" CONTENT="containsKey()">
<META NAME="keywords" CONTENT="put()">
<META NAME="keywords" CONTENT="putAll()">
<META NAME="keywords" CONTENT="remove()">
<META NAME="keywords" CONTENT="clear()">
<META NAME="keywords" CONTENT="containsValue()">
<META NAME="keywords" CONTENT="clone()">
<META NAME="keywords" CONTENT="keySet()">
<META NAME="keywords" CONTENT="values()">
<META NAME="keywords" CONTENT="entrySet()">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

JavaTM 2 Platform
Standard Ed. 5.0

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

java.util

Class HashMap<K,V>

java.lang.Object
  java.util.AbstractMap<K,V>
      java.util.HashMap<K,V>

All Implemented Interfaces:
Serializable, Cloneable, Map<K,V>

Direct Known Subclasses:
LinkedHashMap, PrinterStateReasons

public class HashMap<K,V>
extends AbstractMap<K,V>
implements Map<K,V>, Cloneable, Serializable

Hash table based implementation of the <tt>Map</tt> interface.  This
 implementation provides all of the optional map operations, and permits
 <tt>null</tt> values and the <tt>null</tt> key.  (The <tt>HashMap</tt>
 class is roughly equivalent to <tt>Hashtable</tt>, except that it is
 unsynchronized and permits nulls.)  This class makes no guarantees as to
 the order of the map; in particular, it does not guarantee that the order
 will remain constant over time.

This implementation provides constant-time performance for the basic
 operations (<tt>get</tt> and <tt>put</tt>), assuming the hash function
 disperses the elements properly among the buckets.  Iteration over
 collection views requires time proportional to the "capacity" of the
 <tt>HashMap</tt> instance (the number of buckets) plus its size (the number
 of key-value mappings).  Thus, it's very important not to set the initial
 capacity too high (or the load factor too low) if iteration performance is
 important.

An instance of <tt>HashMap</tt> has two parameters that affect its
 performance: initial capacity and load factor.  The
 capacity is the number of buckets in the hash table, and the initial
 capacity is simply the capacity at the time the hash table is created.  The
 load factor is a measure of how full the hash table is allowed to
 get before its capacity is automatically increased.  When the number of
 entries in the hash table exceeds the product of the load factor and the
 current capacity, the capacity is roughly doubled by calling the
 <tt>rehash</tt> method.

As a general rule, the default load factor (.75) offers a good tradeoff
 between time and space costs.  Higher values decrease the space overhead
 but increase the lookup cost (reflected in most of the operations of the
 <tt>HashMap</tt> class, including <tt>get</tt> and <tt>put</tt>).  The
 expected number of entries in the map and its load factor should be taken
 into account when setting its initial capacity, so as to minimize the
 number of <tt>rehash</tt> operations.  If the initial capacity is greater
 than the maximum number of entries divided by the load factor, no
 <tt>rehash</tt> operations will ever occur.

If many mappings are to be stored in a <tt>HashMap</tt> instance,
 creating it with a sufficiently large capacity will allow the mappings to
 be stored more efficiently than letting it perform automatic rehashing as
 needed to grow the table.

Note that this implementation is not synchronized. If multiple
 threads access this map concurrently, and at least one of the threads
 modifies the map structurally, it must be synchronized externally.
 (A structural modification is any operation that adds or deletes one or
 more mappings; merely changing the value associated with a key that an
 instance already contains is not a structural modification.)  This is
 typically accomplished by synchronizing on some object that naturally
 encapsulates the map.  If no such object exists, the map should be
 "wrapped" using the <tt>Collections.synchronizedMap</tt> method.  This is
 best done at creation time, to prevent accidental unsynchronized access to
 the map:
 Map m = Collections.synchronizedMap(new HashMap(...));

The iterators returned by all of this class's "collection view methods"
 are fail-fast: if the map is structurally modified at any time after
 the iterator is created, in any way except through the iterator's own
 <tt>remove</tt> or <tt>add</tt> methods, the iterator will throw a
 <tt>ConcurrentModificationException</tt>.  Thus, in the face of concurrent
 modification, the iterator fails quickly and cleanly, rather than risking
 arbitrary, non-deterministic behavior at an undetermined time in the
 future.

Note that the fail-fast behavior of an iterator cannot be guaranteed
 as it is, generally speaking, impossible to make any hard guarantees in the
 presence of unsynchronized concurrent modification.  Fail-fast iterators
 throw <tt>ConcurrentModificationException</tt> on a best-effort basis.
 Therefore, it would be wrong to write a program that depended on this
 exception for its correctness: the fail-fast behavior of iterators
 should be used only to detect bugs.

This class is a member of the

 Java Collections Framework.

Since:

1.2

See Also:
Object.hashCode(),
Collection,
Map,
TreeMap,
Hashtable,
Serialized Form

Constructor Summary

HashMap()

          Constructs an empty <tt>HashMap</tt> with the default initial capacity
 (16) and the default load factor (0.75).

HashMap(int initialCapacity)

          Constructs an empty <tt>HashMap</tt> with the specified initial
 capacity and the default load factor (0.75).

HashMap(int initialCapacity,
        float loadFactor)

          Constructs an empty <tt>HashMap</tt> with the specified initial
 capacity and load factor.

HashMap(Map<? extends K,? extends V> m)

          Constructs a new <tt>HashMap</tt> with the same mappings as the
 specified <tt>Map</tt>.

Method Summary

 void
clear()

          Removes all mappings from this map.

 Object
clone()

          Returns a shallow copy of this <tt>HashMap</tt> instance: the keys and
 values themselves are not cloned.

 boolean
containsKey(Object key)

          Returns <tt>true</tt> if this map contains a mapping for the
 specified key.

 boolean
containsValue(Object value)

          Returns <tt>true</tt> if this map maps one or more keys to the
 specified value.

 Set<Map.Entry<K,V>>
entrySet()

          Returns a collection view of the mappings contained in this map.

 V
get(Object key)

          Returns the value to which the specified key is mapped in this identity
 hash map, or <tt>null</tt> if the map contains no mapping for this key.

 boolean
isEmpty()

          Returns <tt>true</tt> if this map contains no key-value mappings.

 Set<K>
keySet()

          Returns a set view of the keys contained in this map.

 V
put(K key,
    V value)

          Associates the specified value with the specified key in this map.

 void
putAll(Map<? extends K,? extends V> m)

          Copies all of the mappings from the specified map to this map
 These mappings will replace any mappings that
 this map had for any of the keys currently in the specified map.

 V
remove(Object key)

          Removes the mapping for this key from this map if present.

 int
size()

          Returns the number of key-value mappings in this map.

 Collection<V>
values()

          Returns a collection view of the values contained in this map.

Methods inherited from class java.util.AbstractMap

equals, hashCode, toString

Methods inherited from class java.lang.Object

finalize, getClass, notify, notifyAll, wait, wait, wait

Methods inherited from interface java.util.Map

equals, hashCode

Constructor Detail

HashMap

public HashMap(int initialCapacity,
               float loadFactor)

Constructs an empty <tt>HashMap</tt> with the specified initial
 capacity and load factor.

Parameters:
initialCapacity - The initial capacity.
loadFactor - The load factor.

Throws:

IllegalArgumentException - if the initial capacity is negative
         or the load factor is nonpositive.

HashMap

public HashMap(int initialCapacity)

Constructs an empty <tt>HashMap</tt> with the specified initial
 capacity and the default load factor (0.75).

Parameters:
initialCapacity - the initial capacity.

Throws:

IllegalArgumentException - if the initial capacity is negative.

HashMap

public HashMap()

Constructs an empty <tt>HashMap</tt> with the default initial capacity
 (16) and the default load factor (0.75).

HashMap

public HashMap(Map<? extends K,? extends V> m)

Constructs a new <tt>HashMap</tt> with the same mappings as the
 specified <tt>Map</tt>.  The <tt>HashMap</tt> is created with
 default load factor (0.75) and an initial capacity sufficient to
 hold the mappings in the specified <tt>Map</tt>.

Parameters:
m - the map whose mappings are to be placed in this map.

Throws:

NullPointerException - if the specified map is null.

Method Detail

size

public int size()

Returns the number of key-value mappings in this map.

Specified by:
size in interface Map<K,V>
Overrides:
size in class AbstractMap<K,V>

Returns:
the number of key-value mappings in this map.

isEmpty

public boolean isEmpty()

Returns <tt>true</tt> if this map contains no key-value mappings.

Specified by:
isEmpty in interface Map<K,V>
Overrides:
isEmpty in class AbstractMap<K,V>

Returns:
<tt>true</tt> if this map contains no key-value mappings.

get

public V get(Object key)

Returns the value to which the specified key is mapped in this identity
 hash map, or <tt>null</tt> if the map contains no mapping for this key.
 A return value of <tt>null</tt> does not necessarily indicate
 that the map contains no mapping for the key; it is also possible that
 the map explicitly maps the key to <tt>null</tt>. The
 <tt>containsKey</tt> method may be used to distinguish these two cases.

Specified by:
get in interface Map<K,V>
Overrides:
get in class AbstractMap<K,V>

Parameters:
key - the key whose associated value is to be returned.

Returns:
the value to which this map maps the specified key, or
          <tt>null</tt> if the map contains no mapping for this key.
See Also:
put(Object, Object)

containsKey

public boolean containsKey(Object key)

Returns <tt>true</tt> if this map contains a mapping for the
 specified key.

Specified by:
containsKey in interface Map<K,V>
Overrides:
containsKey in class AbstractMap<K,V>

Parameters:
key - The key whose presence in this map is to be tested

Returns:
<tt>true</tt> if this map contains a mapping for the specified
 key.

put

public V put(K key,
             V value)

Associates the specified value with the specified key in this map.
 If the map previously contained a mapping for this key, the old
 value is replaced.

Specified by:
put in interface Map<K,V>
Overrides:
put in class AbstractMap<K,V>

Parameters:
key - key with which the specified value is to be associated.
value - value to be associated with the specified key.

Returns:
previous value associated with specified key, or <tt>null</tt>
               if there was no mapping for key.  A <tt>null</tt> return can
               also indicate that the HashMap previously associated
               <tt>null</tt> with the specified key.

putAll

public void putAll(Map<? extends K,? extends V> m)

Copies all of the mappings from the specified map to this map
 These mappings will replace any mappings that
 this map had for any of the keys currently in the specified map.

Specified by:
putAll in interface Map<K,V>
Overrides:
putAll in class AbstractMap<K,V>

Parameters:
m - mappings to be stored in this map.

Throws:

NullPointerException - if the specified map is null.

remove

public V remove(Object key)

Removes the mapping for this key from this map if present.

Specified by:
remove in interface Map<K,V>
Overrides:
remove in class AbstractMap<K,V>

Parameters:
key - key whose mapping is to be removed from the map.

Returns:
previous value associated with specified key, or <tt>null</tt>
               if there was no mapping for key.  A <tt>null</tt> return can
               also indicate that the map previously associated <tt>null</tt>
               with the specified key.

clear

public void clear()

Removes all mappings from this map.

Specified by:
clear in interface Map<K,V>
Overrides:
clear in class AbstractMap<K,V>

containsValue

public boolean containsValue(Object value)

Returns <tt>true</tt> if this map maps one or more keys to the
 specified value.

Specified by:
containsValue in interface Map<K,V>
Overrides:
containsValue in class AbstractMap<K,V>

Parameters:
value - value whose presence in this map is to be tested.

Returns:
<tt>true</tt> if this map maps one or more keys to the
         specified value.

clone

public Object clone()

Returns a shallow copy of this <tt>HashMap</tt> instance: the keys and
 values themselves are not cloned.

Overrides:
clone in class AbstractMap<K,V>

Returns:
a shallow copy of this map.
See Also:
Cloneable

keySet

public Set<K> keySet()

Returns a set view of the keys contained in this map.  The set is
 backed by the map, so changes to the map are reflected in the set, and
 vice-versa.  The set supports element removal, which removes the
 corresponding mapping from this map, via the <tt>Iterator.remove</tt>,
 <tt>Set.remove</tt>, <tt>removeAll</tt>, <tt>retainAll</tt>, and
 <tt>clear</tt> operations.  It does not support the <tt>add</tt> or
 <tt>addAll</tt> operations.

Specified by:
keySet in interface Map<K,V>
Overrides:
keySet in class AbstractMap<K,V>

Returns:
a set view of the keys contained in this map.

values

public Collection<V> values()

Returns a collection view of the values contained in this map.  The
 collection is backed by the map, so changes to the map are reflected in
 the collection, and vice-versa.  The collection supports element
 removal, which removes the corresponding mapping from this map, via the
 <tt>Iterator.remove</tt>, <tt>Collection.remove</tt>,
 <tt>removeAll</tt>, <tt>retainAll</tt>, and <tt>clear</tt> operations.
 It does not support the <tt>add</tt> or <tt>addAll</tt> operations.

Specified by:
values in interface Map<K,V>
Overrides:
values in class AbstractMap<K,V>

Returns:
a collection view of the values contained in this map.

entrySet

public Set<Map.Entry<K,V>> entrySet()

Returns a collection view of the mappings contained in this map.  Each
 element in the returned collection is a <tt>Map.Entry</tt>.  The
 collection is backed by the map, so changes to the map are reflected in
 the collection, and vice-versa.  The collection supports element
 removal, which removes the corresponding mapping from the map, via the
 <tt>Iterator.remove</tt>, <tt>Collection.remove</tt>,
 <tt>removeAll</tt>, <tt>retainAll</tt>, and <tt>clear</tt> operations.
 It does not support the <tt>add</tt> or <tt>addAll</tt> operations.

Specified by:
entrySet in interface Map<K,V>
Specified by:
entrySet in class AbstractMap<K,V>

Returns:
a collection view of the mappings contained in this map.
See Also:
Map.Entry

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

JavaTM 2 Platform
Standard Ed. 5.0

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

Submit a bug or feature
For further API reference and developer documentation, see Java 2 SDK SE Developer Documentation. That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples.
Copyright © 2004, 2010 Oracle and/or its affiliates. All rights reserved. Use is subject to license terms. Also see the documentation redistribution policy.


text: from .views import panels_bp


text:
package org.jfl2.fx.controller.adapter;

import javafx.event.Event;
import javafx.event.EventType;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import org.jfl2.fx.controller.event.input.*;
import org.jfl2.fx.controller.event.input.trash.Jfl2KeyCharEventAction;
import org.jfl2.fx.controller.event.input.trash.Jfl2KeyCodeEventAction;

import java.util.function.Consumer;
import static org.jfl2.fx.controller.event.input.EventTargetComponentType.*;

/**
 * jfl2Controllerの操作分離クラス基本
 */
public interface EventAdapter<T extends EventAdapter> extends Jfl2Adapter<T> {
    EventTargetComponentManager getEventTargetComponentManager();

    /**
     * イベント登録とNodeのマッピング作成
     *
     * @return
     */
    default EventTargetComponentManager getDefaultTargetComponentManager() {
        EventTargetComponentManager manager = new EventTargetComponentManager();
        manager.addNode(getJfl2().getLeft(), FILELIST, LEFT_FILELIST);
        manager.addNode(getJfl2().getLeft().getTableView(), FILELIST_TABLEVIEW, LEFT_FILELIST_TABLEVIEW);
        manager.addNode(getJfl2().getLeft().getComboBox(), FILELIST_COMBOBOX, LEFT_FILELIST_COMBOBOX);

        manager.addNode(getJfl2().getRight(), FILELIST, RIGHT_FILELIST);
        manager.addNode(getJfl2().getRight().getTableView(), FILELIST_TABLEVIEW, RIGHT_FILELIST_TABLEVIEW);
        manager.addNode(getJfl2().getRight().getComboBox(), FILELIST_COMBOBOX, RIGHT_FILELIST_COMBOBOX);

        manager.addNode(getJfl2().getMenuPane(), MENU);
        manager.addNode(getJfl2().getMenuPane().getRadioBox(), MENU_ITEMS);
        return manager;
    }

    /**
     * イベント追加
     * Groovyから以下のように使う
     *

     * jfl2.addEvent(FILELIST_COMBOBOX, { eReg ->
     *     eReg.add( KeyCode.ENTER, { jfl2.current.setPath(jfl2.current.getComboBoxValue()) });
     * });
     *

     *
     * @param type    KeyCode
     * @param operate Execution content
     * @return
     */
    default T addEvent(EventTargetComponentType type, Consumer<EventRegister> operate) {
        operate.accept(EventRegister.getInstance(getEventTargetComponentManager(), type));
        return getInstance();
    }

    /**
     * イベント追加
     *  EventRegister経由で登録するようになったので使っていない
     *
     * @return
     */
    default T addEvent(KeyCode code, EventType<KeyEvent> keyEvent, int modifier, EventTargetComponentType target, boolean consume, Consumer<Event> operate) {
        Jfl2KeyCodeEventAction ev = new Jfl2KeyCodeEventAction(code, keyEvent, modifier, target, getEventTargetComponentManager(), consume, operate);
        getEventTargetComponentManager().addEvent(ev);
        return getInstance();
    }

    /**
     * イベント追加
     *  EventRegister経由で登録するようになったので使っていない
     *
     * @return
     */
    default T addEvent(String character, EventType<KeyEvent> keyEvent, int modifier, EventTargetComponentType target, boolean consume, Consumer<Event> operate) {
        Jfl2KeyCharEventAction ev = new Jfl2KeyCharEventAction(character, keyEvent, modifier, target, getEventTargetComponentManager(), consume, operate);
        getEventTargetComponentManager().addEvent(ev);
        return getInstance();
    }

}


text:
package git.rahulparihar.materialdesignshowcase;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityOptions;
import android.content.Intent;
import android.os.Bundle;
import android.transition.Slide;
import android.util.Pair;
import android.view.Gravity;
import android.view.View;

@SuppressLint("NewApi")
public class TransitionFirstActivity extends Activity {

	private View mFabButton;
	private View mHeader;

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_transition_first);

		mFabButton = findViewById(R.id.fab_button);
		mHeader = findViewById(R.id.activity_transition_header);

		Slide slideExitTransition = new Slide(Gravity.BOTTOM);
		slideExitTransition.excludeTarget(android.R.id.navigationBarBackground,
				true);
		slideExitTransition.excludeTarget(android.R.id.statusBarBackground,
				true);
		slideExitTransition
				.excludeTarget(R.id.activity_transition_header, true);
		getWindow().setExitTransition(slideExitTransition);
	}

	public void onFabPressed(View view) {

		Intent i = new Intent(TransitionFirstActivity.this,
				TransitionSecondActivity.class);

		@SuppressWarnings("unchecked")
		ActivityOptions transitionActivityOptions = ActivityOptions
				.makeSceneTransitionAnimation(TransitionFirstActivity.this,
						Pair.create(mFabButton, "fab"),
						Pair.create(mHeader, "holder1"));

		startActivity(i, transitionActivityOptions.toBundle());
	}
}


text:
// <copyright file="InstaGalleryPage.xaml.cs" company="Christoph Nienaber, https://github.com/zuckerthoben">
// Copyright (c) Christoph Nienaber, https://github.com/zuckerthoben. All rights reserved.
// </copyright>

namespace SafeOrizer.Pages
{
    using Xamarin.Forms;

    public partial class InstaGalleryPage : ContentPage
    {
        public InstaGalleryPage()
        {
            this.InitializeComponent();
        }
    }
}


text:
import {
  createControlledPromise,
  FlipperServerForServerAddOn,
  ServerAddOn,
} from 'flipper-plugin';
import path from 'path';
import {WebSocketServer, WebSocket} from 'ws';
import {rollup} from 'rollup';
import resolve from '@rollup/plugin-node-resolve';
import commonjs from '@rollup/plugin-commonjs';
import {Events, Methods} from './contract';

const DEV_TOOLS_PORT = 8097; // hardcoded in RN

async function findGlobalDevTools(
  flipperServer: FlipperServerForServerAddOn,
): Promise<string | undefined> {
  try {
    const {stdout: basePath} = await flipperServer.exec(
      'node-api-exec',
      'npm root -g',
    );
    console.debug(
      'flipper-plugin-react-devtools.findGlobalDevTools -> npm root',
      basePath,
    );
    const devToolsPath = path.join(
      basePath.trim(),
      'react-devtools-inline',
      'frontend.js',
    );
    await flipperServer.exec('node-api-fs-stat', devToolsPath);
    return devToolsPath;
  } catch (error) {
    console.warn('Failed to find globally installed React DevTools: ' + error);
    return undefined;
  }
}

const serverAddOn: ServerAddOn<Events, Methods> = async (
  connection,
  {flipperServer},
) => {
  console.debug('flipper-plugin-react-devtools.serverAddOn -> starting');

  const startServer = async () => {
    console.debug('flipper-plugin-react-devtools.serverAddOn -> startServer');

    const wss = new WebSocketServer({port: DEV_TOOLS_PORT});

    const startedPromise = createControlledPromise<void>();
    wss.on('listening', () => startedPromise.resolve());
    wss.on('error', (err) => {
      if (startedPromise.state === 'pending') {
        startedPromise.reject(err);
        return;
      }

      console.error('flipper-plugin-react-devtools.serverAddOn -> error', err);
    });

    await startedPromise.promise;

    console.debug(
      'flipper-plugin-react-devtools.serverAddOn -> started server',
    );

    wss.on('connection', (ws) => {
      connection.send('connected');
      console.debug(
        'flipper-plugin-react-devtools.serverAddOn -> connected a client',
      );

      ws.on('message', (data) => {
        connection.send('message', JSON.parse(data.toString()));
        console.debug(
          'flipper-plugin-react-devtools.serverAddOn -> client sent a message',
          data.toString(),
        );
      });

      ws.on('error', (err) => {
        console.error(
          'flipper-plugin-react-devtools.serverAddOn -> client error',
          err,
        );
      });

      ws.on('close', () => {
        connection.send('disconnected');
        console.debug(
          'flipper-plugin-react-devtools.serverAddOn -> client left',
        );
      });
    });

    connection.receive('message', (data) => {
      console.debug(
        'flipper-plugin-react-devtools.serverAddOn -> desktop sent a message',
        data,
      );
      wss!.clients.forEach((ws) => {
        if (ws.readyState === WebSocket.OPEN) {
          ws.send(JSON.stringify(data));
        }
      });
    });

    return wss;
  };

  const wss = await startServer();

  connection.receive('globalDevTools', async () => {
    const globalDevToolsPath = await findGlobalDevTools(flipperServer);
    if (!globalDevToolsPath) {
      console.info(
        'flipper-plugin-react-devtools.serverAddOn -> not found global React DevTools',
      );
      return;
    }
    console.info(
      'flipper-plugin-react-devtools.serverAddOn -> found global React DevTools: ',
      globalDevToolsPath,
    );

    const bundle = await rollup({
      input: globalDevToolsPath,
      plugins: [resolve(), commonjs()],
      external: ['react', 'react-is', 'react-dom/client', 'react-dom'],
    });

    try {
      const {output} = await bundle.generate({
        format: 'iife',
        globals: {
          react: 'global.React',
          'react-is': 'global.ReactIs',
          'react-dom/client': 'global.ReactDOMClient',
          'react-dom': 'global.ReactDOM',
        },
      });
      return output[0].code;
    } finally {
      await bundle.close();
    }
  });

  return async () => {
    console.debug('flipper-plugin-react-devtools.serverAddOn -> stopping');
    if (wss) {
      console.debug(
        'flipper-plugin-react-devtools.serverAddOn -> stopping wss',
      );
      await new Promise<void>((resolve, reject) =>
        wss!.close((err) => (err ? reject(err) : resolve())),
      );
      console.debug('flipper-plugin-react-devtools.serverAddOn -> stopped wss');
    }
  };
};

export default serverAddOn;


text:
{-# OPTIONS_GHC -fno-warn-tabs #-}

import System.Exit
import System.IO.Unsafe()
import Data.IORef()
import Data.Maybe()
import Development.Shake
import Development.Shake.Command
import Development.Shake.FilePath
import Development.Shake.Util

main :: IO()

sysroot		= "build/sysroot" :: [Char]
prefix		= "usr/local" :: [Char]
outputBin	= "flaxc" :: [Char]

finalOutput	= sysroot </> prefix </> "bin" </> outputBin :: [Char]

llvmConfig	= "llvm-config"
disableWarn	= "-Wno-unused-parameter -Wno-sign-conversion -Wno-padded -Wno-c++98-compat -Wno-weak-vtables -Wno-documentation-unknown-command -Wno-old-style-cast -Wno-c++98-compat-pedantic -Wno-conversion -Wno-shadow -Wno-global-constructors -Wno-exit-time-destructors -Wno-missing-noreturn -Wno-unused-macros -Wno-switch-enum -Wno-deprecated -Wno-shift-sign-overflow -Wno-format-nonliteral -Wno-gnu-zero-variadic-macro-arguments -Wno-trigraphs -Wno-extra-semi -Wno-reserved-id-macro"

compiledTest		= "build/test"
testSource			= "build/test.flx"
flaxcNormFlags		= "-O3 -no-lowercase-builtin -o '" ++ compiledTest ++ "'"
flaxcJitFlags		= "-Ox -no-lowercase-builtin -run"

main = shakeArgs shakeOptions { shakeFiles = "build", shakeVerbosity = Quiet } $ do
	want ["build"]

	phony "build" $ do
		need [finalOutput]
		putNormal "======================================="
		cmd Shell finalOutput [flaxcJitFlags] testSource

	phony "compile" $ do
		need [compiledTest]

	phony "clean" $ do
		putQuiet "Cleaning files"
		removeFilesAfter "source" ["//*.o"]

	compiledTest %> \out -> do
		need [finalOutput]
		alwaysRerun

		Exit code <- cmd Shell finalOutput [flaxcNormFlags] testSource

		putNormal "======================================="
		cmd Shell (if code == ExitSuccess then [compiledTest] else ["echo Test failed"])

	"//*.flx" %> \out -> do
		let fnp = "libs" </> (takeFileName out)
		need [fnp]

		let ut = (sysroot </> prefix </> "lib" </> "flaxLibs/")
		quietly $ cmd Shell "cp" [fnp] [ut]

	phony "copyLibraries" $ do
		() <- quietly $ cmd Shell "cp" ("libs/*.flx") (sysroot </> prefix </> "lib" </> "flaxlibs/")

		--- copy the libs to the prefix.
		() <- quietly $ cmd Shell "mkdir" "-p" ("/" </> prefix </> "lib" </> "flaxlibs")
		quietly $ cmd Shell "cp" ("libs/*.flx") ("/" </> prefix </> "lib" </> "flaxlibs/")

	finalOutput %> \out -> do
		cs <- getDirectoryFiles "" ["source//*.cpp"]
		let os = [c ++ ".o" | c <- cs]
		need os

		maybelconf <- getEnvWithDefault llvmConfig "LLVM_CONFIG"
		let lconf = maybelconf

		let llvmConfigInvoke = "`" ++ lconf ++ " --cxxflags --ldflags --system-libs --libs core engine native linker bitwriter`"

		() <- cmd Shell "clang++ -Xclang -fcolor-diagnostics -g -o" [out] [llvmConfigInvoke] os
		putQuiet ("\x1b[0m" ++ "# built " ++ out)

		need ["copyLibraries"]

	"source//*.cpp.o" %> \out -> do
		let c = dropExtension out
		let m = out ++ ".m"

		maybelconf <- getEnvWithDefault llvmConfig "LLVM_CONFIG"
		let lconf = maybelconf

		let cxxFlags = "-std=gnu++11 -O0 -g -Wall -Weverything " ++ disableWarn ++ " -frtti -fexceptions -fno-omit-frame-pointer -I`" ++ lconf ++ " --includedir` -Isource/include" ++ " -Xclang -fcolor-diagnostics"

		putQuiet ("\x1b[0m" ++ "# compiling " ++ c)
		() <- cmd Shell "clang++ -c" [c] [cxxFlags] "-o" [out] "-MMD -MF" [m]

		needMakefileDependencies m


text:
namespace xwalk {
namespace application {

class ApplicationTizen :  // NOLINT
#if defined(USE_OZONE)
  public ui::PlatformEventObserver,
#endif
  public Application {
 public:
  virtual ~ApplicationTizen();
  void Hide();
  void Suspend();
  void Resume();

 private:
  friend class Application;
  ApplicationTizen(scoped_refptr<ApplicationData> data,
                   RuntimeContext* context);
  virtual bool Launch(const LaunchParams& launch_params) OVERRIDE;

  virtual base::FilePath GetSplashScreenPath() OVERRIDE;

#if defined(USE_OZONE)
  virtual void WillProcessEvent(const ui::PlatformEvent& event) OVERRIDE;
  virtual void DidProcessEvent(const ui::PlatformEvent& event) OVERRIDE;
#endif

  bool is_suspended_;
};

inline ApplicationTizen* ToApplicationTizen(Application* app) {
  return static_cast<ApplicationTizen*>(app);
}

}  // namespace application
}  // namespace xwalk

#endif  // XWALK_APPLICATION_BROWSER_APPLICATION_TIZEN_H_


text:
require_relative 'storage_manager'

class DbInstanceManager < StorageManager

  def initialize(repo_url, service_folder)
    super(repo_url, service_folder)
  end

  def remote_installation_commands(worker_node, ssh_connection)
    # check if instance is already running
    instance_is_running = service_running?('instance', ssh_connection)
    Rails.logger.debug("Instance is running : #{instance_is_running}")
    return if instance_is_running

    #check if config is running
    download_manager(worker_node, ssh_connection) unless service_running?('config', ssh_connection)

    # start the instance
    cmd = [
      "source .rvm/environments/default",
      "ruby --version",
      "cd #{@service_folder}",
      "bundle install",
      "bundle exec rake db_instance:start"
    ].join(';')

    Rails.logger.debug(ssh_connection.exec!(cmd))
  end

  def manager_url(worker_node)
    "#{worker_node.url}:#{@db_instance_port}"
  end

  def stop_service
    # start the instance
    cmd = [
      "source .rvm/environments/default",
      "ruby --version",
      "cd #{@service_folder}",
      "bundle exec rake db_instance:stop"
    ].join(';')
  end

end


text:
require 'spec_helper'

describe 'micktagger command line interface' do
  it 'allows me to add tags to a file, list the files of for tag and remove tags' do
    readme_full_path = File.expand_path('../../../README.md', __FILE__)

    MickTagger::CLI.dance!(['-a', 'important', 'README.md'])

    dotfile = read_and_parse_fake_dotfile
    dotfile[readme_full_path].should == ['important']

    output = capture_stdout do
      MickTagger::CLI.dance!(['-l', 'important'])
    end
    output.string.should match(readme_full_path)

    MickTagger::CLI.dance!(['-a', 'markdown', 'README.md'])

    dotfile = read_and_parse_fake_dotfile
    dotfile[readme_full_path].should include('important')
    dotfile[readme_full_path].should include('markdown')

    MickTagger::CLI.dance!(['-d', 'important', 'README.md'])

    dotfile = read_and_parse_fake_dotfile
    dotfile[readme_full_path].should_not include('important')

    MickTagger::CLI.dance!(['-d', 'markdown', 'README.md'])

    dotfile = read_and_parse_fake_dotfile
    dotfile.should_not include(readme_full_path)
  end

  it 'allows me to tag files piped to STDIN' do
    dir   = "#{ENV['HOME']}"
    stdin = "#{dir}/readme.md\n#{dir}/delete_after_reading.txt"

    in_stdin(stdin) do
      MickTagger::CLI.dance!(['-a', 'important'])
    end

    dotfile = read_and_parse_fake_dotfile
    dotfile["#{dir}/readme.md"].should include('important')
    dotfile["#{dir}/delete_after_reading.txt"].should include('important')
  end

  it 'allows me to remove files that have been deleted' do
    readme_full_path = File.expand_path('../../../README.md', __FILE__)
    MickTagger::CLI.dance!(['-a', 'important', 'README.md'])

    File.stub(exists?: true)
    File.stub(:exists?).with(readme_full_path).and_return(false)

    output = capture_stdout do
      MickTagger::CLI.dance!(['-c'])
    end
    output.string.should match("Deleted files:\n#{readme_full_path}\n")

    dotfile = read_and_parse_fake_dotfile
    dotfile.should_not include(readme_full_path)
  end
end


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>31.3. modulefinder — Find modules used by a script — Python 3.5.2 documentation</title>

    <link rel="stylesheet" href="../_static/pydoctheme.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />

    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 3.5.2 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="top" title="Python 3.5.2 documentation" href="../contents.html" />
    <link rel="up" title="31. Importing Modules" href="modules.html" />
    <link rel="next" title="31.4. runpy — Locating and executing Python modules" href="runpy.html" />
    <link rel="prev" title="31.2. pkgutil — Package extension utility" href="pkgutil.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />

Navigation

          index

          modules |

          next |

          previous |

Python »

          3.5.2
          Documentation  »

The Python Standard Library »

31. Importing Modules »

        <form class="inline-search" action="../search.html" method="get">
          <input placeholder="Quick search" type="text" name="q" />
          <input type="submit" value="Go" />
          <input type="hidden" name="check_keywords" value="yes" />
          <input type="hidden" name="area" value="default" />
        </form>

         |

31.3. modulefinder — Find modules used by a script¶

Source code: Lib/modulefinder.py

This module provides a ModuleFinder class that can be used to determine
the set of modules imported by a script. modulefinder.py can also be run as
a script, giving the filename of a Python script as its argument, after which a
report of the imported modules will be printed.

modulefinder.AddPackagePath(pkg_name, path)¶

Record that the package named pkg_name can be found in the specified path.

modulefinder.ReplacePackage(oldname, newname)¶

Allows specifying that the module named oldname is in fact the package named
newname.

class modulefinder.ModuleFinder(path=None, debug=0, excludes=[], replace_paths=[])¶

This class provides run_script() and report() methods to determine
the set of modules imported by a script. path can be a list of directories to
search for modules; if not specified, sys.path is used.  debug sets the
debugging level; higher values make the class print debugging messages about
what it’s doing. excludes is a list of module names to exclude from the
analysis. replace_paths is a list of (oldpath, newpath) tuples that will
be replaced in module paths.

report()¶

Print a report to standard output that lists the modules imported by the
script and their paths, as well as modules that are missing or seem to be
missing.

run_script(pathname)¶

Analyze the contents of the pathname file, which must contain Python
code.

modules¶

A dictionary mapping module names to modules. See
Example usage of ModuleFinder.

31.3.1. Example usage of ModuleFinder¶

The script that is going to get analyzed later on (bacon.py):

import re, itertools

try:
    import baconhameggs
except ImportError:
    pass

try:
    import guido.python.ham
except ImportError:
    pass

The script that will output the report of bacon.py:

from modulefinder import ModuleFinder

finder = ModuleFinder()
finder.run_script('bacon.py')

print('Loaded modules:')
for name, mod in finder.modules.items():
    print('%s: ' % name, end='')
    print(','.join(list(mod.globalnames.keys())[:3]))

print('-'*50)
print('Modules not imported:')
print('\n'.join(finder.badmodules.keys()))

Sample output (may vary depending on the architecture):

Loaded modules:
_types:
copyreg:  _inverted_registry,_slotnames,__all__
sre_compile:  isstring,_sre,_optimize_unicode
_sre:
sre_constants:  REPEAT_ONE,makedict,AT_END_LINE
sys:
re:  __module__,finditer,_expand
itertools:
__main__:  re,itertools,baconhameggs
sre_parse:  _PATTERNENDERS,SRE_FLAG_UNICODE
array:
types:  __module__,IntType,TypeType
---------------------------------------------------
Modules not imported:
guido.python.ham
baconhameggs

Table Of Contents

31.3. modulefinder — Find modules used by a script

31.3.1. Example usage of ModuleFinder

Previous topic

31.2. pkgutil — Package extension utility

Next topic

31.4. runpy — Locating and executing Python modules

This Page

Report a Bug

Show Source

Navigation

          index

          modules |

          next |

          previous |

Python »

          3.5.2
          Documentation  »

The Python Standard Library »

31. Importing Modules »

        <form class="inline-search" action="../search.html" method="get">
          <input placeholder="Quick search" type="text" name="q" />
          <input type="submit" value="Go" />
          <input type="hidden" name="check_keywords" value="yes" />
          <input type="hidden" name="area" value="default" />
        </form>

         |

    © Copyright 2001-2016, Python Software Foundation.

    The Python Software Foundation is a non-profit corporation.
    Please donate.

    Last updated on Dec 08, 2016.
    Found a bug?

    Created using Sphinx 1.3.3.


text:
var $=require("../ansuz");

/* chain is a higher level wrapper around gen.cons
  it accepts an array of lazy functions
  and reduces it into a single function
  which will fall through to the next function in the array
  at the 'end' of the current function */

var chain=$.chain(
  [$.either([1,2,3,4,5])
  ,$.either([2,3,4,5])
  ,$.either([9,4,7,3])
  ]
);

console.log($.listall(chain)); // list every element in the chain of generators


text:
using System;
using System.Numerics;
using System.Collections.Generic;
using System.Runtime.CompilerServices;

using SharpFont;

namespace MSDFGen {
    public static partial class MSDF {
        struct Context {
            public Vector2 position;
            public Shape shape;
            public Contour contour;
        }

        static Vector2 ToVector2(FTVector vector) {
            return new Vector2(vector.X.Value / 64f, vector.Y.Value / 64f);
        }

        static int MoveTo(ref FTVector to, IntPtr user) {
            unsafe
            {
                Context context = Unsafe.Read<Context>((void*)user);
                Contour contour = new Contour();
                context.shape.Contours.Add(contour);
                context.contour = contour;
                context.position = ToVector2(to);
                Unsafe.Write((void*)user, context);
                return 0;
            }
        }

        static int LineTo(ref FTVector to, IntPtr user) {
            unsafe
            {
                Context context = Unsafe.Read<Context>((void*)user);
                context.contour.Edges.Add(new LinearSegment(context.position, ToVector2(to), EdgeColor.White));
                context.position = ToVector2(to);
                Unsafe.Write((void*)user, context);
                return 0;
            }
        }

        static int ConicTo(ref FTVector control, ref FTVector to, IntPtr user) {
            unsafe
            {
                Context context = Unsafe.Read<Context>((void*)user);
                context.contour.Edges.Add(new QuadraticSegment(context.position, ToVector2(control), ToVector2(to), EdgeColor.White));
                context.position = ToVector2(to);
                Unsafe.Write((void*)user, context);
                return 0;
            }
        }

        static int CubicTo(ref FTVector control1, ref FTVector control2, ref FTVector to, IntPtr user) {
            unsafe
            {
                Context context = Unsafe.Read<Context>((void*)user);
                context.contour.Edges.Add(new CubicSegment(context.position, ToVector2(control1), ToVector2(control2), ToVector2(to), EdgeColor.White));
                context.position = ToVector2(to);
                Unsafe.Write((void*)user, context);
                return 0;
            }
        }

        public static Shape LoadGlyph(Face face, int unicode) {
            if (face == null) throw new ArgumentNullException(nameof(face));

            face.LoadChar((uint)unicode, LoadFlags.NoScale, LoadTarget.Normal);

            Shape output = new Shape();

            Context context = new Context {
                shape = output
            };

            OutlineFuncs funcs = new OutlineFuncs();
            funcs.MoveFunction = MoveTo;
            funcs.LineFunction = LineTo;
            funcs.ConicFunction = ConicTo;
            funcs.CubicFunction = CubicTo;
            unsafe
            {
                face.Glyph.Outline.Decompose(funcs, (IntPtr)Unsafe.AsPointer(ref context));
            }
            return output;
        }
    }
}


text:
cd $HOME
qreal --config /etc/trikStudio.config


text:
<?php
namespace Helmich\EventBroker\Broker;

/**
 * Interface definition for a message broker.
 *
 * @author     Martin Helmich <typo3@martin-helmich.de>
 * @package    Helmich\EventBroker
 * @subpackage Annotations
 *
 * @api
 */
interface BrokerInterface
{

    /**
     * Enqueues an arbitrary event.
     *
     * @param mixed $event The event object to publish.
     * @return void
     */
    public function queueEvent($event);

    /**
     * Publishes queued events.
     *
     * @return void
     */
    public function flush();

}