text:
#include "postgres.h"

#include <unistd.h>
#include <signal.h>

#include "access/htup_details.h"
#include "bootstrap/bootstrap.h"
#include "catalog/index.h"
#include "catalog/pg_collation.h"
#include "catalog/pg_type.h"
#include "libpq/pqsignal.h"
#include "miscadmin.h"
#include "nodes/makefuncs.h"
#include "pg_getopt.h"
#include "postmaster/bgwriter.h"
#include "postmaster/startup.h"
#include "postmaster/walwriter.h"
#include "replication/walreceiver.h"
#include "storage/bufmgr.h"
#include "storage/bufpage.h"
#include "storage/ipc.h"
#include "storage/proc.h"
#include "tcop/tcopprot.h"
#include "utils/builtins.h"
#include "utils/fmgroids.h"
#include "utils/memutils.h"
#include "utils/ps_status.h"
#include "utils/rel.h"
#include "utils/relmapper.h"
#include "utils/tqual.h"

uint32		bootstrap_data_checksum_version = 0;		/* No checksum */

#define ALLOC(t, c)		((t *) calloc((unsigned)(c), sizeof(t)))

static void CheckerModeMain(void);
static void BootstrapModeMain(void);
static void bootstrap_signals(void);
static void ShutdownAuxiliaryProcess(int code, Datum arg);
static Form_pg_attribute AllocateAttribute(void);
static Oid	gettype(char *type);
static void cleanup(void);

/* ----------------
 *		global variables
 * ----------------
 */

AuxProcType MyAuxProcType = NotAnAuxProcess;	/* declared in miscadmin.h */

Relation	boot_reldesc;		/* current relation descriptor */

Form_pg_attribute attrtypes[MAXATTR];	/* points to attribute info */
int			numattr;			/* number of attributes for cur. rel */

/*
 * Basic information associated with each type.  This is used before
 * pg_type is filled, so it has to cover the datatypes used as column types
 * in the core "bootstrapped" catalogs.
 *
 *		XXX several of these input/output functions do catalog scans
 *			(e.g., F_REGPROCIN scans pg_proc).  this obviously creates some
 *			order dependencies in the catalog creation process.
 */
struct typinfo
{
	char		name[NAMEDATALEN];
	Oid			oid;
	Oid			elem;
	int16		len;
	bool		byval;
	char		align;
	char		storage;
	Oid			collation;
	Oid			inproc;
	Oid			outproc;
};

static const struct typinfo TypInfo[] = {
	{"bool", BOOLOID, 0, 1, true, 'c', 'p', InvalidOid,
	F_BOOLIN, F_BOOLOUT},
	{"bytea", BYTEAOID, 0, -1, false, 'i', 'x', InvalidOid,
	F_BYTEAIN, F_BYTEAOUT},
	{"char", CHAROID, 0, 1, true, 'c', 'p', InvalidOid,
	F_CHARIN, F_CHAROUT},
	{"int2", INT2OID, 0, 2, true, 's', 'p', InvalidOid,
	F_INT2IN, F_INT2OUT},
	{"int4", INT4OID, 0, 4, true, 'i', 'p', InvalidOid,
	F_INT4IN, F_INT4OUT},
	{"float4", FLOAT4OID, 0, 4, FLOAT4PASSBYVAL, 'i', 'p', InvalidOid,
	F_FLOAT4IN, F_FLOAT4OUT},
	{"name", NAMEOID, CHAROID, NAMEDATALEN, false, 'c', 'p', InvalidOid,
	F_NAMEIN, F_NAMEOUT},
	{"regclass", REGCLASSOID, 0, 4, true, 'i', 'p', InvalidOid,
	F_REGCLASSIN, F_REGCLASSOUT},
	{"regproc", REGPROCOID, 0, 4, true, 'i', 'p', InvalidOid,
	F_REGPROCIN, F_REGPROCOUT},
	{"regtype", REGTYPEOID, 0, 4, true, 'i', 'p', InvalidOid,
	F_REGTYPEIN, F_REGTYPEOUT},
	{"regrole", REGROLEOID, 0, 4, true, 'i', 'p', InvalidOid,
	F_REGROLEIN, F_REGROLEOUT},
	{"regnamespace", REGNAMESPACEOID, 0, 4, true, 'i', 'p', InvalidOid,
	F_REGNAMESPACEIN, F_REGNAMESPACEOUT},
	{"text", TEXTOID, 0, -1, false, 'i', 'x', DEFAULT_COLLATION_OID,
	F_TEXTIN, F_TEXTOUT},
	{"oid", OIDOID, 0, 4, true, 'i', 'p', InvalidOid,
	F_OIDIN, F_OIDOUT},
	{"tid", TIDOID, 0, 6, false, 's', 'p', InvalidOid,
	F_TIDIN, F_TIDOUT},
	{"xid", XIDOID, 0, 4, true, 'i', 'p', InvalidOid,
	F_XIDIN, F_XIDOUT},
	{"cid", CIDOID, 0, 4, true, 'i', 'p', InvalidOid,
	F_CIDIN, F_CIDOUT},
	{"pg_node_tree", PGNODETREEOID, 0, -1, false, 'i', 'x', DEFAULT_COLLATION_OID,
	F_PG_NODE_TREE_IN, F_PG_NODE_TREE_OUT},
	{"int2vector", INT2VECTOROID, INT2OID, -1, false, 'i', 'p', InvalidOid,
	F_INT2VECTORIN, F_INT2VECTOROUT},
	{"oidvector", OIDVECTOROID, OIDOID, -1, false, 'i', 'p', InvalidOid,
	F_OIDVECTORIN, F_OIDVECTOROUT},
	{"_int4", INT4ARRAYOID, INT4OID, -1, false, 'i', 'x', InvalidOid,
	F_ARRAY_IN, F_ARRAY_OUT},
	{"_text", 1009, TEXTOID, -1, false, 'i', 'x', DEFAULT_COLLATION_OID,
	F_ARRAY_IN, F_ARRAY_OUT},
	{"_oid", 1028, OIDOID, -1, false, 'i', 'x', InvalidOid,
	F_ARRAY_IN, F_ARRAY_OUT},
	{"_char", 1002, CHAROID, -1, false, 'i', 'x', InvalidOid,
	F_ARRAY_IN, F_ARRAY_OUT},
	{"_aclitem", 1034, ACLITEMOID, -1, false, 'i', 'x', InvalidOid,
	F_ARRAY_IN, F_ARRAY_OUT}
};

static const int n_types = sizeof(TypInfo) / sizeof(struct typinfo);

struct typmap
{								/* a hack */
	Oid			am_oid;
	FormData_pg_type am_typ;
};

static struct typmap **Typ = NULL;
static struct typmap *Ap = NULL;

static Datum values[MAXATTR];	/* current row's attribute values */
static bool Nulls[MAXATTR];

static MemoryContext nogc = NULL;		/* special no-gc mem context */

/*
 *	At bootstrap time, we first declare all the indices to be built, and
 *	then build them.  The IndexList structure stores enough information
 *	to allow us to build the indices after they've been declared.
 */

typedef struct _IndexList
{
	Oid			il_heap;
	Oid			il_ind;
	IndexInfo  *il_info;
	struct _IndexList *il_next;
} IndexList;

static IndexList *ILHead = NULL;

/*
 *	 AuxiliaryProcessMain
 *
 *	 The main entry point for auxiliary processes, such as the bgwriter,
 *	 walwriter, walreceiver, bootstrapper and the shared memory checker code.
 *
 *	 This code is here just because of historical reasons.
 */
void
AuxiliaryProcessMain(int argc, char *argv[])
{
	char	   *progname = argv[0];
	int			flag;
	char	   *userDoption = NULL;

	/*
	 * Initialize process environment (already done if under postmaster, but
	 * not if standalone).
	 */
	if (!IsUnderPostmaster)
		InitStandaloneProcess(argv[0]);

	/*
	 * process command arguments
	 */

	/* Set defaults, to be overriden by explicit options below */
	if (!IsUnderPostmaster)
		InitializeGUCOptions();

	/* Ignore the initial --boot argument, if present */
	if (argc > 1 && strcmp(argv[1], "--boot") == 0)
	{
		argv++;
		argc--;
	}

	/* If no -x argument, we are a CheckerProcess */
	MyAuxProcType = CheckerProcess;

	while ((flag = getopt(argc, argv, "B:c:d:D:Fkr:x:-:")) != -1)
	{
		switch (flag)
		{
			case 'B':
				SetConfigOption("shared_buffers", optarg, PGC_POSTMASTER, PGC_S_ARGV);
				break;
			case 'D':
				userDoption = strdup(optarg);
				break;
			case 'd':
				{
					/* Turn on debugging for the bootstrap process. */
					char	   *debugstr;

					debugstr = psprintf("debug%s", optarg);
					SetConfigOption("log_min_messages", debugstr,
									PGC_POSTMASTER, PGC_S_ARGV);
					SetConfigOption("client_min_messages", debugstr,
									PGC_POSTMASTER, PGC_S_ARGV);
					pfree(debugstr);
				}
				break;
			case 'F':
				SetConfigOption("fsync", "false", PGC_POSTMASTER, PGC_S_ARGV);
				break;
			case 'k':
				bootstrap_data_checksum_version = PG_DATA_CHECKSUM_VERSION;
				break;
			case 'r':
				strlcpy(OutputFileName, optarg, MAXPGPATH);
				break;
			case 'x':
				MyAuxProcType = static_cast<AuxProcType >(atoi(optarg));
				break;
			case 'c':
			case '-':
				{
					char	   *name,
							   *value;

					ParseLongOption(optarg, &name, &value);
					if (!value)
					{
						if (flag == '-')
							ereport(ERROR,
									(errcode(ERRCODE_SYNTAX_ERROR),
									 errmsg("--%s requires a value",
											optarg)));
						else
							ereport(ERROR,
									(errcode(ERRCODE_SYNTAX_ERROR),
									 errmsg("-c %s requires a value",
											optarg)));
					}

					SetConfigOption(name, value, PGC_POSTMASTER, PGC_S_ARGV);
					free(name);
					if (value)
						free(value);
					break;
				}
			default:
				write_stderr("Try \"%s --help\" for more information.\n",
							 progname);
				proc_exit(1);
				break;
		}
	}

	if (argc != optind)
	{
		write_stderr("%s: invalid command-line arguments\n", progname);
		proc_exit(1);
	}

	/*
	 * Identify myself via ps
	 */
	if (IsUnderPostmaster)
	{
		const char *statmsg;

		switch (MyAuxProcType)
		{
			case StartupProcess:
				statmsg = "startup process";
				break;
			case BgWriterProcess:
				statmsg = "writer process";
				break;
			case CheckpointerProcess:
				statmsg = "checkpointer process";
				break;
			case WalWriterProcess:
				statmsg = "wal writer process";
				break;
			case WalReceiverProcess:
				statmsg = "wal receiver process";
				break;
			default:
				statmsg = "??? process";
				break;
		}
		init_ps_display(statmsg, "", "", "");
	}

	/* Acquire configuration parameters, unless inherited from postmaster */
	if (!IsUnderPostmaster)
	{
		if (!SelectConfigFiles(userDoption, progname))
			proc_exit(1);
	}

	/* Validate we have been given a reasonable-looking DataDir */
	Assert(DataDir);
	ValidatePgVersion(DataDir);

	/* Change into DataDir (if under postmaster, should be done already) */
	if (!IsUnderPostmaster)
		ChangeToDataDir();

	/* If standalone, create lockfile for data directory */
	if (!IsUnderPostmaster)
		CreateDataDirLockFile(false);

	SetProcessingMode(BootstrapProcessing);
	IgnoreSystemIndexes = true;

	/* Initialize MaxBackends (if under postmaster, was done already) */
	if (!IsUnderPostmaster)
		InitializeMaxBackends();

	BaseInit();

	/*
	 * When we are an auxiliary process, we aren't going to do the full
	 * InitPostgres pushups, but there are a couple of things that need to get
	 * lit up even in an auxiliary process.
	 */
	if (IsUnderPostmaster)
	{
		/*
		 * Create a PGPROC so we can use LWLocks.  In the EXEC_BACKEND case,
		 * this was already done by SubPostmasterMain().
		 */
#ifndef EXEC_BACKEND
		InitAuxiliaryProcess();
#endif

		/*
		 * Assign the ProcSignalSlot for an auxiliary process.  Since it
		 * doesn't have a BackendId, the slot is statically allocated based on
		 * the auxiliary process type (MyAuxProcType).  Backends use slots
		 * indexed in the range from 1 to MaxBackends (inclusive), so we use
		 * MaxBackends + AuxProcType + 1 as the index of the slot for an
		 * auxiliary process.
		 *
		 * This will need rethinking if we ever want more than one of a
		 * particular auxiliary process type.
		 */
		ProcSignalInit(MaxBackends + MyAuxProcType + 1);

		/* finish setting up bufmgr.c */
		InitBufferPoolBackend();

		/* register a before-shutdown callback for LWLock cleanup */
		before_shmem_exit(ShutdownAuxiliaryProcess, 0);
	}

	/*
	 * XLOG operations
	 */
	SetProcessingMode(NormalProcessing);

	switch (MyAuxProcType)
	{
		case CheckerProcess:
			/* don't set signals, they're useless here */
			CheckerModeMain();
			proc_exit(1);		/* should never return */

		case BootstrapProcess:
			/*
			 * There was a brief instant during which mode was Normal; this is
			 * okay.  We need to be in bootstrap mode during BootStrapXLOG for
			 * the sake of multixact initialization.
			 */
			SetProcessingMode(BootstrapProcessing);
			bootstrap_signals();
			BootStrapXLOG();
			BootstrapModeMain();
			proc_exit(1);		/* should never return */

		case StartupProcess:
			/* don't set signals, startup process has its own agenda */
			StartupProcessMain();
			proc_exit(1);		/* should never return */

		case BgWriterProcess:
			/* don't set signals, bgwriter has its own agenda */
			BackgroundWriterMain();
			proc_exit(1);		/* should never return */

		case CheckpointerProcess:
			/* don't set signals, checkpointer has its own agenda */
			CheckpointerMain();
			proc_exit(1);		/* should never return */

		case WalWriterProcess:
			/* don't set signals, walwriter has its own agenda */
			InitXLOGAccess();
			WalWriterMain();
			proc_exit(1);		/* should never return */

		case WalReceiverProcess:
			/* don't set signals, walreceiver has its own agenda */
			WalReceiverMain();
			proc_exit(1);		/* should never return */

		default:
			elog(PANIC, "unrecognized process type: %d", (int) MyAuxProcType);
			proc_exit(1);
	}
}

/*
 * In shared memory checker mode, all we really want to do is create shared
 * memory and semaphores (just to prove we can do it with the current GUC
 * settings).  Since, in fact, that was already done by BaseInit(),
 * we have nothing more to do here.
 */
static void
CheckerModeMain(void)
{
	proc_exit(0);
}

/*
 *	 The main entry point for running the backend in bootstrap mode
 *
 *	 The bootstrap mode is used to initialize the ctemplate database.
 *	 The bootstrap backend doesn't speak SQL, but instead expects
 *	 commands in a special bootstrap language.
 */
static void
BootstrapModeMain(void)
{
	int			i;

	Assert(!IsUnderPostmaster);
	Assert(IsBootstrapProcessingMode());

	/*
	 * Do backend-like initialization for bootstrap mode
	 */
	InitProcess();

	InitPostgres(NULL, InvalidOid, NULL, InvalidOid, NULL);

	/* Initialize stuff for bootstrap-file processing */
	for (i = 0; i < MAXATTR; i++)
	{
		attrtypes[i] = NULL;
		Nulls[i] = false;
	}

	/*
	 * Process bootstrap input.
	 */
	boot_yyparse();

	/*
	 * We should now know about all mapped relations, so it's okay to write
	 * out the initial relation mapping files.
	 */
	RelationMapFinishBootstrap();

	/* Clean up and exit */
	cleanup();
	proc_exit(0);
}

/* ----------------------------------------------------------------
 *						misc functions
 * ----------------------------------------------------------------
 */

/*
 * Set up signal handling for a bootstrap process
 */
static void
bootstrap_signals(void)
{
	Assert(!IsUnderPostmaster);

	/* Set up appropriately for interactive use */
	pqsignal(SIGHUP, die);
	pqsignal(SIGINT, die);
	pqsignal(SIGTERM, die);
	pqsignal(SIGQUIT, die);
}

/*
 * Begin shutdown of an auxiliary process.  This is approximately the equivalent
 * of ShutdownPostgres() in postinit.c.  We can't run transactions in an
 * auxiliary process, so most of the work of AbortTransaction() is not needed,
 * but we do need to make sure we've released any LWLocks we are holding.
 * (This is only critical during an error exit.)
 */
static void
ShutdownAuxiliaryProcess(int code, Datum arg)
{
	LWLockReleaseAll();
}

/* ----------------------------------------------------------------
 *				MANUAL BACKEND INTERACTIVE INTERFACE COMMANDS
 * ----------------------------------------------------------------
 */

/* ----------------
 *		boot_openrel
 * ----------------
 */
void
boot_openrel(char *relname)
{
	int			i;
	struct typmap **app;
	Relation	rel;
	HeapScanDesc scan;
	HeapTuple	tup;

	if (strlen(relname) >= NAMEDATALEN)
		relname[NAMEDATALEN - 1] = '\0';

	if (Typ == NULL)
	{
		/* We can now load the pg_type data */
		rel = heap_open(TypeRelationId, NoLock);
		scan = heap_beginscan_catalog(rel, 0, NULL);
		i = 0;
		while ((tup = heap_getnext(scan, ForwardScanDirection)) != NULL)
			++i;
		heap_endscan(scan);
		app = Typ = ALLOC(struct typmap *, i + 1);
		while (i-- > 0)
			*app++ = ALLOC(struct typmap, 1);
		*app = NULL;
		scan = heap_beginscan_catalog(rel, 0, NULL);
		app = Typ;
		while ((tup = heap_getnext(scan, ForwardScanDirection)) != NULL)
		{
			(*app)->am_oid = HeapTupleGetOid(tup);
			memcpy((char *) &(*app)->am_typ,
				   (char *) GETSTRUCT(tup),
				   sizeof((*app)->am_typ));
			app++;
		}
		heap_endscan(scan);
		heap_close(rel, NoLock);
	}

	if (boot_reldesc != NULL)
		closerel(NULL);

	elog(DEBUG4, "open relation %s, attrsize %d",
		 relname, (int) ATTRIBUTE_FIXED_PART_SIZE);

	boot_reldesc = heap_openrv(makeRangeVar(NULL, relname, -1), NoLock);
	numattr = boot_reldesc->rd_rel->relnatts;
	for (i = 0; i < numattr; i++)
	{
		if (attrtypes[i] == NULL)
			attrtypes[i] = AllocateAttribute();
		memmove((char *) attrtypes[i],
				(char *) boot_reldesc->rd_att->attrs[i],
				ATTRIBUTE_FIXED_PART_SIZE);

		{
			Form_pg_attribute at = attrtypes[i];

			elog(DEBUG4, "create attribute %d name %s len %d num %d type %u",
				 i, NameStr(at->attname), at->attlen, at->attnum,
				 at->atttypid);
		}
	}
}

/* ----------------
 *		closerel
 * ----------------
 */
void
closerel(char *name)
{
	if (name)
	{
		if (boot_reldesc)
		{
			if (strcmp(RelationGetRelationName(boot_reldesc), name) != 0)
				elog(ERROR, "close of %s when %s was expected",
					 name, RelationGetRelationName(boot_reldesc));
		}
		else
			elog(ERROR, "close of %s before any relation was opened",
				 name);
	}

	if (boot_reldesc == NULL)
		elog(ERROR, "no open relation to close");
	else
	{
		elog(DEBUG4, "close relation %s",
			 RelationGetRelationName(boot_reldesc));
		heap_close(boot_reldesc, NoLock);
		boot_reldesc = NULL;
	}
}

/* ----------------
 * DEFINEATTR()
 *
 * define a <field,type> pair
 * if there are n fields in a relation to be created, this routine
 * will be called n times
 * ----------------
 */
void
DefineAttr(char *name, char *type, int attnum, int nullness)
{
	Oid			typeoid;

	if (boot_reldesc != NULL)
	{
		elog(WARNING, "no open relations allowed with CREATE command");
		closerel(NULL);
	}

	if (attrtypes[attnum] == NULL)
		attrtypes[attnum] = AllocateAttribute();
	MemSet(attrtypes[attnum], 0, ATTRIBUTE_FIXED_PART_SIZE);

	namestrcpy(&attrtypes[attnum]->attname, name);
	elog(DEBUG4, "column %s %s", NameStr(attrtypes[attnum]->attname), type);
	attrtypes[attnum]->attnum = attnum + 1;		/* fillatt */

	typeoid = gettype(type);

	if (Typ != NULL)
	{
		attrtypes[attnum]->atttypid = Ap->am_oid;
		attrtypes[attnum]->attlen = Ap->am_typ.typlen;
		attrtypes[attnum]->attbyval = Ap->am_typ.typbyval;
		attrtypes[attnum]->attstorage = Ap->am_typ.typstorage;
		attrtypes[attnum]->attalign = Ap->am_typ.typalign;
		attrtypes[attnum]->attcollation = Ap->am_typ.typcollation;
		/* if an array type, assume 1-dimensional attribute */
		if (Ap->am_typ.typelem != InvalidOid && Ap->am_typ.typlen < 0)
			attrtypes[attnum]->attndims = 1;
		else
			attrtypes[attnum]->attndims = 0;
	}
	else
	{
		attrtypes[attnum]->atttypid = TypInfo[typeoid].oid;
		attrtypes[attnum]->attlen = TypInfo[typeoid].len;
		attrtypes[attnum]->attbyval = TypInfo[typeoid].byval;
		attrtypes[attnum]->attstorage = TypInfo[typeoid].storage;
		attrtypes[attnum]->attalign = TypInfo[typeoid].align;
		attrtypes[attnum]->attcollation = TypInfo[typeoid].collation;
		/* if an array type, assume 1-dimensional attribute */
		if (TypInfo[typeoid].elem != InvalidOid &&
			attrtypes[attnum]->attlen < 0)
			attrtypes[attnum]->attndims = 1;
		else
			attrtypes[attnum]->attndims = 0;
	}

	attrtypes[attnum]->attstattarget = -1;
	attrtypes[attnum]->attcacheoff = -1;
	attrtypes[attnum]->atttypmod = -1;
	attrtypes[attnum]->attislocal = true;

	if (nullness == BOOTCOL_NULL_FORCE_NOT_NULL)
	{
		attrtypes[attnum]->attnotnull = true;
	}
	else if (nullness == BOOTCOL_NULL_FORCE_NULL)
	{
		attrtypes[attnum]->attnotnull = false;
	}
	else
	{
		Assert(nullness == BOOTCOL_NULL_AUTO);

		/*
		 * Mark as "not null" if type is fixed-width and prior columns are
		 * too.  This corresponds to case where column can be accessed
		 * directly via C struct declaration.
		 *
		 * oidvector and int2vector are also treated as not-nullable, even
		 * though they are no longer fixed-width.
		 */
#define MARKNOTNULL(att) \
		((att)->attlen > 0 || \
		 (att)->atttypid == OIDVECTOROID || \
		 (att)->atttypid == INT2VECTOROID)

		if (MARKNOTNULL(attrtypes[attnum]))
		{
			int			i;

			/* check earlier attributes */
			for (i = 0; i < attnum; i++)
			{
				if (!attrtypes[i]->attnotnull)
					break;
			}
			if (i == attnum)
				attrtypes[attnum]->attnotnull = true;
		}
	}
}

/* ----------------
 *		InsertOneTuple
 *
 * If objectid is not zero, it is a specific OID to assign to the tuple.
 * Otherwise, an OID will be assigned (if necessary) by heap_insert.
 * ----------------
 */
void
InsertOneTuple(Oid objectid)
{
	HeapTuple	tuple;
	TupleDesc	tupDesc;
	int			i;

	elog(DEBUG4, "inserting row oid %u, %d columns", objectid, numattr);

	tupDesc = CreateTupleDesc(numattr,
							  RelationGetForm(boot_reldesc)->relhasoids,
							  attrtypes);
	tuple = heap_form_tuple(tupDesc, values, Nulls);
	if (objectid != (Oid) 0)
		HeapTupleSetOid(tuple, objectid);
	pfree(tupDesc);				/* just free's tupDesc, not the attrtypes */

	simple_heap_insert(boot_reldesc, tuple);
	heap_freetuple(tuple);
	elog(DEBUG4, "row inserted");

	/*
	 * Reset null markers for next tuple
	 */
	for (i = 0; i < numattr; i++)
		Nulls[i] = false;
}

/* ----------------
 *		InsertOneValue
 * ----------------
 */
void
InsertOneValue(char *value, int i)
{
	Oid			typoid;
	int16		typlen;
	bool		typbyval;
	char		typalign;
	char		typdelim;
	Oid			typioparam;
	Oid			typinput;
	Oid			typoutput;

	AssertArg(i >= 0 && i < MAXATTR);

	elog(DEBUG4, "inserting column %d value \"%s\"", i, value);

	typoid = boot_reldesc->rd_att->attrs[i]->atttypid;

	boot_get_type_io_data(typoid,
						  &typlen, &typbyval, &typalign,
						  &typdelim, &typioparam,
						  &typinput, &typoutput);

	values[i] = OidInputFunctionCall(typinput, value, typioparam, -1);

	/*
	 * We use ereport not elog here so that parameters aren't evaluated unless
	 * the message is going to be printed, which generally it isn't
	 */
	ereport(DEBUG4,
			(errmsg_internal("inserted -> %s",
							 OidOutputFunctionCall(typoutput, values[i]))));
}

/* ----------------
 *		InsertOneNull
 * ----------------
 */
void
InsertOneNull(int i)
{
	elog(DEBUG4, "inserting column %d NULL", i);
	Assert(i >= 0 && i < MAXATTR);
	values[i] = PointerGetDatum(NULL);
	Nulls[i] = true;
}

/* ----------------
 *		cleanup
 * ----------------
 */
static void
cleanup(void)
{
	if (boot_reldesc != NULL)
		closerel(NULL);
}

/* ----------------
 *		gettype
 *
 * NB: this is really ugly; it will return an integer index into TypInfo[],
 * and not an OID at all, until the first reference to a type not known in
 * TypInfo[].  At that point it will read and cache pg_type in the Typ array,
 * and subsequently return a real OID (and set the global pointer Ap to
 * point at the found row in Typ).  So caller must check whether Typ is
 * still NULL to determine what the return value is!
 * ----------------
 */
static Oid
gettype(char *type)
{
	int			i;
	Relation	rel;
	HeapScanDesc scan;
	HeapTuple	tup;
	struct typmap **app;

	if (Typ != NULL)
	{
		for (app = Typ; *app != NULL; app++)
		{
			if (strncmp(NameStr((*app)->am_typ.typname), type, NAMEDATALEN) == 0)
			{
				Ap = *app;
				return (*app)->am_oid;
			}
		}
	}
	else
	{
		for (i = 0; i < n_types; i++)
		{
			if (strncmp(type, TypInfo[i].name, NAMEDATALEN) == 0)
				return i;
		}
		elog(DEBUG4, "external type: %s", type);
		rel = heap_open(TypeRelationId, NoLock);
		scan = heap_beginscan_catalog(rel, 0, NULL);
		i = 0;
		while ((tup = heap_getnext(scan, ForwardScanDirection)) != NULL)
			++i;
		heap_endscan(scan);
		app = Typ = ALLOC(struct typmap *, i + 1);
		while (i-- > 0)
			*app++ = ALLOC(struct typmap, 1);
		*app = NULL;
		scan = heap_beginscan_catalog(rel, 0, NULL);
		app = Typ;
		while ((tup = heap_getnext(scan, ForwardScanDirection)) != NULL)
		{
			(*app)->am_oid = HeapTupleGetOid(tup);
			memmove((char *) &(*app++)->am_typ,
					(char *) GETSTRUCT(tup),
					sizeof((*app)->am_typ));
		}
		heap_endscan(scan);
		heap_close(rel, NoLock);
		return gettype(type);
	}
	elog(ERROR, "unrecognized type \"%s\"", type);
	/* not reached, here to make compiler happy */
	return 0;
}

/* ----------------
 *		boot_get_type_io_data
 *
 * Obtain type I/O information at bootstrap time.  This intentionally has
 * almost the same API as lsyscache.c's get_type_io_data, except that
 * we only support obtaining the typinput and typoutput routines, not
 * the binary I/O routines.  It is exported so that array_in and array_out
 * can be made to work during early bootstrap.
 * ----------------
 */
void
boot_get_type_io_data(Oid typid,
					  int16 *typlen,
					  bool *typbyval,
					  char *typalign,
					  char *typdelim,
					  Oid *typioparam,
					  Oid *typinput,
					  Oid *typoutput)
{
	if (Typ != NULL)
	{
		/* We have the boot-time contents of pg_type, so use it */
		struct typmap **app;
		struct typmap *ap;

		app = Typ;
		while (*app && (*app)->am_oid != typid)
			++app;
		ap = *app;
		if (ap == NULL)
			elog(ERROR, "type OID %u not found in Typ list", typid);

		*typlen = ap->am_typ.typlen;
		*typbyval = ap->am_typ.typbyval;
		*typalign = ap->am_typ.typalign;
		*typdelim = ap->am_typ.typdelim;

		/* XXX this logic must match getTypeIOParam() */
		if (OidIsValid(ap->am_typ.typelem))
			*typioparam = ap->am_typ.typelem;
		else
			*typioparam = typid;

		*typinput = ap->am_typ.typinput;
		*typoutput = ap->am_typ.typoutput;
	}
	else
	{
		/* We don't have pg_type yet, so use the hard-wired TypInfo array */
		int			typeindex;

		for (typeindex = 0; typeindex < n_types; typeindex++)
		{
			if (TypInfo[typeindex].oid == typid)
				break;
		}
		if (typeindex >= n_types)
			elog(ERROR, "type OID %u not found in TypInfo", typid);

		*typlen = TypInfo[typeindex].len;
		*typbyval = TypInfo[typeindex].byval;
		*typalign = TypInfo[typeindex].align;
		/* We assume typdelim is ',' for all boot-time types */
		*typdelim = ',';

		/* XXX this logic must match getTypeIOParam() */
		if (OidIsValid(TypInfo[typeindex].elem))
			*typioparam = TypInfo[typeindex].elem;
		else
			*typioparam = typid;

		*typinput = TypInfo[typeindex].inproc;
		*typoutput = TypInfo[typeindex].outproc;
	}
}

/* ----------------
 *		AllocateAttribute
 *
 * Note: bootstrap never sets any per-column ACLs, so we only need
 * ATTRIBUTE_FIXED_PART_SIZE space per attribute.
 * ----------------
 */
static Form_pg_attribute
AllocateAttribute(void)
{
	Form_pg_attribute attribute = (Form_pg_attribute) malloc(ATTRIBUTE_FIXED_PART_SIZE);

	if (!PointerIsValid(attribute))
		elog(FATAL, "out of memory");
	MemSet(attribute, 0, ATTRIBUTE_FIXED_PART_SIZE);

	return attribute;
}

/*
 *		MapArrayTypeName
 *
 * Given a type name, produce the corresponding array type name by prepending
 * '_' and truncating as needed to fit in NAMEDATALEN-1 bytes.  This is only
 * used in bootstrap mode, so we can get away with assuming that the input is
 * ASCII and we don't need multibyte-aware truncation.
 *
 * The given string normally ends with '[]' or '[digits]'; we discard that.
 *
 * The result is a palloc'd string.
 */
char *
MapArrayTypeName(const char *s)
{
	int			i,
				j;
	char		newStr[NAMEDATALEN];

	newStr[0] = '_';
	j = 1;
	for (i = 0; i < NAMEDATALEN - 2 && s[i] != '['; i++, j++)
		newStr[j] = s[i];

	newStr[j] = '\0';

	return pstrdup(newStr);
}

/*
 *	index_register() -- record an index that has been set up for building
 *						later.
 *
 *		At bootstrap time, we define a bunch of indexes on system catalogs.
 *		We postpone actually building the indexes until just before we're
 *		finished with initialization, however.  This is because the indexes
 *		themselves have catalog entries, and those have to be included in the
 *		indexes on those catalogs.  Doing it in two phases is the simplest
 *		way of making sure the indexes have the right contents at the end.
 */
void
index_register(Oid heap,
			   Oid ind,
			   IndexInfo *indexInfo)
{
	IndexList  *newind;
	MemoryContext oldcxt;

	/*
	 * XXX mao 10/31/92 -- don't gc index reldescs, associated info at
	 * bootstrap time.  we'll declare the indexes now, but want to create them
	 * later.
	 */

	if (nogc == NULL)
		nogc = AllocSetContextCreate(NULL,
									 "BootstrapNoGC",
									 ALLOCSET_DEFAULT_MINSIZE,
									 ALLOCSET_DEFAULT_INITSIZE,
									 ALLOCSET_DEFAULT_MAXSIZE);

	oldcxt = MemoryContextSwitchTo(nogc);

	newind = (IndexList *) palloc(sizeof(IndexList));
	newind->il_heap = heap;
	newind->il_ind = ind;
	newind->il_info = (IndexInfo *) palloc(sizeof(IndexInfo));

	memcpy(newind->il_info, indexInfo, sizeof(IndexInfo));
	/* expressions will likely be null, but may as well copy it */
	newind->il_info->ii_Expressions = (List *)
		copyObject(indexInfo->ii_Expressions);
	newind->il_info->ii_ExpressionsState = NIL;
	/* predicate will likely be null, but may as well copy it */
	newind->il_info->ii_Predicate = (List *)
		copyObject(indexInfo->ii_Predicate);
	newind->il_info->ii_PredicateState = NIL;
	/* no exclusion constraints at bootstrap time, so no need to copy */
	Assert(indexInfo->ii_ExclusionOps == NULL);
	Assert(indexInfo->ii_ExclusionProcs == NULL);
	Assert(indexInfo->ii_ExclusionStrats == NULL);

	newind->il_next = ILHead;
	ILHead = newind;

	MemoryContextSwitchTo(oldcxt);
}

/*
 * build_indices -- fill in all the indexes registered earlier
 */
void
build_indices(void)
{
	for (; ILHead != NULL; ILHead = ILHead->il_next)
	{
		Relation	heap;
		Relation	ind;

		/* need not bother with locks during bootstrap */
		heap = heap_open(ILHead->il_heap, NoLock);
		ind = index_open(ILHead->il_ind, NoLock);

		index_build(heap, ind, ILHead->il_info, false, false);

		index_close(ind, NoLock);
		heap_close(heap, NoLock);
	}
}


text:
using ArragroCMS.BusinessLayer.Domains;
using ArragroCMS.BusinessLayer.Interfaces.CacheDomains;
using ArragroCMS.Core.Interfaces.Providers;
using ArragroCMS.Core.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Blob;
using System;
using System.IO;
using System.Threading.Tasks;

namespace ArragroCMS.Web.Management.Controllers
{
    [Authorize("ContentAuthors")]
    [Route("asset-controller")]
    public class AssetDownloader : Controller
    {
        private readonly ICacheAssets _assets;
        private readonly IStorageProvider _storageProvider;
        private readonly CloudStorageAccount _account;
        private readonly CloudBlobClient _client;
        private readonly CloudBlobContainer _assetContainer;

        public AssetDownloader(
            ICacheAssets assets,
            ConfigurationSettings configurationSettings,
            IStorageProvider storageProvider)
        {
            _assets = assets;
            _storageProvider = storageProvider;
            _account = CloudStorageAccount.Parse(configurationSettings.ConnectionStrings.StorageConnection);
            _client = _account.CreateCloudBlobClient();
            _assetContainer = _client.GetContainerReference("assets");
            _assetContainer.CreateIfNotExistsAsync().Wait();
        }

        [HttpGet("{assetId}")]
        public async Task<IActionResult> DownloadFileAsync(Guid assetId)
        {
            var asset = await _assets.FindAsync(assetId);
            var uri = await _storageProvider.Get(asset.SiteId, $"{asset.ContentUrlRouteId}/{assetId}/{asset.FileName}");
            var blob = await _client.GetBlobReferenceFromServerAsync(uri);

            if (asset != null && await blob.ExistsAsync())
            {
                byte[] bytes;

                using (var ms = new MemoryStream())
                {
                    await blob.DownloadToStreamAsync(ms);
                    bytes = ms.ToArray();
                }

                return File(bytes, asset.MimeType, asset.FileName);
            }

            return new NotFoundResult();
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
import numpy as np
import tensorflow as tf
from datetime import datetime

now = datetime.utcnow().strftime('%Y%m%d%H%M%S')
root_logdir = 'tf_logs'
log_dir = '{}/run-{}/'.format(root_logdir, now)

def relu(X):
    threshold = tf.get_variable("threshold", shape=(), initializer=tf.constant_initializer(0.0))
    wshape = (int(X.get_shape()[1]), 1)
    w = tf.Variable(tf.random_normal(wshape), name='weights')
    b = tf.Variable(0.0, name='bias')
    z = tf.add(tf.matmul(X, w), b, name="z")
    relu = tf.maximum(z, threshold, name="relu")
    return relu

n_features = 3
X = tf.placeholder(tf.float32, shape=(None, n_features), name='X')
relus = []
for relu_index in range(5):
    with tf.variable_scope('relu', reuse=(relu_index>0)):
        relus.append(relu(X))
output = tf.add_n(relus, name='relus')
# assign_op = threshold.assign(5)

init = tf.global_variables_initializer()

file_writer = tf.summary.FileWriter(log_dir, tf.get_default_graph())

with tf.Session() as sess:
    init.run()

    # assign_op.eval()
    res = output.eval(feed_dict={X: np.array([1, 2, 3]).reshape(1, 3)})
    print(res)

file_writer.close()


text:
package in.mused.api.service;

import org.springframework.roo.addon.layers.service.RooService;

@RooService(domainTypes = { in.mused.api.domain.Library.class })
public interface LibraryService {
}


text:
namespace Roflcopter.Sample.MismatchedFileNames.MismatchedFileNameHighlightingTests
{
    public class SingleClass
    {
        // Prove that nested classes are not considered as top level types:
        public class Nested
        {
        }
    }
}


text:
local helper = {}

local path = require "pl.path"
local dir = require "pl.dir"
local stringx = require "pl.stringx"
local posix = require "posix"
local Date = require "pl.Date"
local tablex = require "pl.tablex"
local List = require "pl.List"

local date_format = Date.Format()

function helper.rsync(source_url,target_path,previous_path, exclude)
    -- the source_url must end with a '/' otherwise another level of folders will be creted by rsync
    if not stringx.endswith(source_url,'/') then
      source_url = source_url..'/'
    end

    local exclude_string = " "
    if exclude ~= nil then
      for i,e in ipairs(exclude) do
        exclude_string = exclude_string..' --exclude="'..e..'" '
      end
    end

    if previous_path == nil then
        print('Running initial rsync from '..source_url..' to '..target_path)
        local cmd = 'rsync -a '..exclude_string..' "'..source_url..'" "'..target_path..'"'
        assert( os.execute(cmd) )
    else
        print('Running incremental rsync from '..source_url..' to '..target_path)
        print('Using '..previous_path..' as baseline.')
        local cmd = 'rsync -a --delete --link-dest="'..previous_path..'" '..exclude_string..' "'..source_url..'" "'..target_path..'"'
        assert( os.execute(cmd) )
    end
end

function helper.find_latest(target_root)
  local latest = nil
  for entry in path.dir(target_root) do
    if entry ~= '.' and entry ~= '..' and (latest == nil or entry > latest) then
      latest = entry
    end
  end
  if latest == nil then
    return nil
  end
  return path.join(target_root,latest)
end

function helper.is_mounted(mount_point)
  f = assert( io.open( '/proc/mounts','r' ) )
  for line in f:lines() do

    words = string.gmatch(line, '%S+')
    device = words()
    target = helper.normpath(words())
    if target == helper.normpath(mount_point) then
      return true
    end
  end
  return false
end

function helper.select_for_deletion(dirs,now,young_limit,old_limit,young_retention,old_retention)
  local to_delete = List()
  dirs:sort()
  local last_date = helper.string_to_date(dirs[1])
  for current in dirs:iter() do
    local current_date = helper.string_to_date(current)
    local age = now - last_date
    local retention = Date.Interval(
      helper.retention_time(age.time,young_limit,old_limit,young_retention,old_retention))
    --print(last_date, retention, current_date)
    if last_date + retention > current_date then
      to_delete:append( current )
    else
      last_date = current_date
    end
  end
  return to_delete
end

--[[
  all parameters are required in seconds, NOT as Interval objects!
  Interval objects do not support the division operator.
]]
function helper.retention_time(age,young_limit,old_limit,young_retention,old_retention)
  assert(type(age) == "number", "age must be a number")
  assert(type(young_limit) == "number", "young_limit must be a number")
  assert(type(old_limit) == "number", "old_limit must be a number")
  assert(type(young_retention) == "number", "young_retention must be a number")
  assert(type(old_retention) == "number", "old_retention must be a number")

  if age <= young_limit then
    return 0
  elseif age >= old_limit then
    return old_retention
  end
  -- linear interpolation of the retention time
  return young_retention+( (old_retention-young_retention)*(age-young_limit)/(old_limit-young_limit) )
end

function helper.normpath(p)
  return path.normpath( path.abspath( p ))
end

function helper.string_to_date(dstr)
  return date_format:parse(tostring(dstr))
end

function helper.date_to_string(d)
  return date_format:tostring(d)
end

return helper


text:
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using Microsoft.CodeAnalysis.CSharp.CodeRefactorings.EncapsulateField;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;

namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings.EncapsulateField
{
    public class EncapsulateFieldTests : AbstractCSharpCodeActionTest
    {
        protected override object CreateCodeRefactoringProvider(Workspace workspace)
        {
            return new EncapsulateFieldRefactoringProvider();
        }

        [Fact, Trait(Traits.Feature, Traits.Features.EncapsulateField)]
        public void PrivateFieldToPropertyIgnoringReferences()
        {
            var text = @"
class foo
{
    private int b[|a|]r;

    void baz()
    {
        var q = bar;
    }
}
";

            var expected = @"
class foo
{
    private int bar;

    public int Bar
    {
        get
        {
            return bar;
        }

        set
        {
            bar = value;
        }
    }

    void baz()
    {
        var q = bar;
    }
}
";
            Test(text, expected, compareTokens: false, index: 1);
        }

        [Fact, Trait(Traits.Feature, Traits.Features.EncapsulateField)]
        public void PrivateFieldToPropertyUpdatingReferences()
        {
            var text = @"
class foo
{
    private int b[|a|]r;

    void baz()
    {
        var q = Bar;
    }
}
";

            var expected = @"
class foo
{
    private int bar;

    public int Bar
    {
        get
        {
            return bar;
        }

        set
        {
            bar = value;
        }
    }

    void baz()
    {
        var q = Bar;
    }
}
";
            Test(text, expected, compareTokens: false, index: 0);
        }

        [Fact, Trait(Traits.Feature, Traits.Features.EncapsulateField)]
        public void PublicFieldIntoPublicPropertyIgnoringReferences()
        {
            var text = @"
class foo
{
    public int b[|a|]r;

    void baz()
    {
        var q = bar;
    }
}
";

            var expected = @"
class foo
{
    private int bar;

    public int Bar
    {
        get
        {
            return bar;
        }

        set
        {
            bar = value;
        }
    }

    void baz()
    {
        var q = bar;
    }
}
";
            Test(text, expected, compareTokens: false, index: 1);
        }

        [Fact, Trait(Traits.Feature, Traits.Features.EncapsulateField)]
        public void PublicFieldIntoPublicPropertyUpdatingReferences()
        {
            var text = @"
class foo
{
    public int b[|a|]r;

    void baz()
    {
        var q = bar;
    }
}
";

            var expected = @"
class foo
{
    private int bar;

    public int Bar
    {
        get
        {
            return bar;
        }

        set
        {
            bar = value;
        }
    }

    void baz()
    {
        var q = Bar;
    }
}
";
            Test(text, expected, compareTokens: false, index: 0);
        }

        [Fact, Trait(Traits.Feature, Traits.Features.EncapsulateField)]
        public void StaticPreserved()
        {
            var text = @"class Program
{
    static int [|foo|];
}";

            var expected = @"class Program
{
    static int foo;

    public static int Foo
    {
        get
        {
            return foo;
        }

        set
        {
            foo = value;
        }
    }
}";
            Test(text, expected, compareTokens: false);
        }

        [Fact, Trait(Traits.Feature, Traits.Features.EncapsulateField)]
        public void UniqueNameGenerated()
        {
            var text = @"
class Program
{
    [|int foo|];
    string Foo;
}";

            var expected = @"
class Program
{
    int foo;
    string Foo;

    public int Foo1
    {
        get
        {
            return foo;
        }

        set
        {
            foo = value;
        }
    }
}";
            Test(text, expected, compareTokens: false);
        }

        [Fact, Trait(Traits.Feature, Traits.Features.EncapsulateField)]
        public void GenericField()
        {
            var text = @"
class C<T>
{
    private [|T foo|];
}";

            var expected = @"
class C<T>
{
    private T foo;

    public T Foo
    {
        get
        {
            return foo;
        }

        set
        {
            foo = value;
        }
    }
}";
            Test(text, expected, compareTokens: false);
        }

        [Fact, Trait(Traits.Feature, Traits.Features.EncapsulateField)]
        public void NewFieldNameIsUnique()
        {
            var text = @"
class foo
{
    public [|int X|];
    private string x;
}";

            var expected = @"
class foo
{
    private int x1;
    private string x;

    public int X
    {
        get
        {
            return x1;
        }

        set
        {
            x1 = value;
        }
    }
}";
            Test(text, expected, compareTokens: false, index: 0);
        }

        [Fact, Trait(Traits.Feature, Traits.Features.EncapsulateField)]
        public void RespectReadonly()
        {
            var text = @"
class foo
{
    private readonly [|int x|];
}";

            var expected = @"
class foo
{
    private readonly int x;

    public int X
    {
        get
        {
            return x;
        }
    }
}";
            Test(text, expected, compareTokens: false, index: 0);
        }

        [Fact, Trait(Traits.Feature, Traits.Features.EncapsulateField)]
        public void PreserveNewAndConsiderBaseMemberNames()
        {
            var text = @"
class c
{
    protected int foo;

    protected int Foo { get; set; }
}

class d : c
{
    protected new int [|foo|];
}";

            var expected = @"
class c
{
    protected int foo;

    protected int Foo { get; set; }
}

class d : c
{
    private new int foo;

    protected int Foo1
    {
        get
        {
            return foo;
        }

        set
        {
            foo = value;
        }
    }
}";
            Test(text, expected, compareTokens: false, index: 0);
        }

        [Fact, Trait(Traits.Feature, Traits.Features.EncapsulateField)]
        public void EncapsulateMultiplePrivateFields()
        {
            var text = @"
class foo
{
    private int [|x, y|];

    void bar()
    {
        x = 1;
        y = 2;
    }
}";

            var expected = @"
class foo
{
    private int x, y;

    public int X
    {
        get
        {
            return x;
        }

        set
        {
            x = value;
        }
    }

    public int Y
    {
        get
        {
            return y;
        }

        set
        {
            y = value;
        }
    }

    void bar()
    {
        X = 1;
        Y = 2;
    }
}";
            Test(text, expected, compareTokens: false, index: 0);
        }

        [Fact, Trait(Traits.Feature, Traits.Features.EncapsulateField)]
        public void EncapsulateMultiplePrivateFields2()
        {
            var text = @"
class foo
{
    [|private int x;
    private int y|];

    void bar()
    {
        x = 1;
        y = 2;
    }
}";

            var expected = @"
class foo
{
    private int x;
    private int y;

    public int X
    {
        get
        {
            return x;
        }

        set
        {
            x = value;
        }
    }

    public int Y
    {
        get
        {
            return y;
        }

        set
        {
            y = value;
        }
    }

    void bar()
    {
        X = 1;
        Y = 2;
    }
}";
            Test(text, expected, compareTokens: false, index: 0);
        }

        [Fact, Trait(Traits.Feature, Traits.Features.EncapsulateField)]
        public void EncapsulateSinglePublicFieldInMultipleVariableDeclarationAndUpdateReferences()
        {
            var text = @"
class foo
{
    public int [|x|], y;

    void bar()
    {
        x = 1;
        y = 2;
    }
}";

            var expected = @"
class foo
{
    public int y;
    private int x;

    public int X
    {
        get
        {
            return x;
        }

        set
        {
            x = value;
        }
    }

    void bar()
    {
        X = 1;
        y = 2;
    }
}";
            Test(text, expected, compareTokens: false, index: 0);
        }

        [WorkItem(694057)]
        [Fact, Trait(Traits.Feature, Traits.Features.EncapsulateField)]
        public void ConstFieldNoGetter()
        {
            var text = @"
class Program
{
    private const int [|bar|] = 3;
}
";

            var expected = @"
class Program
{
    private const int bar = 3;

    public static int Bar
    {
        get
        {
            return bar;
        }
    }
}
";
            Test(text, expected, compareTokens: false, index: 0);
        }

        [WorkItem(694276)]
        [Fact, Trait(Traits.Feature, Traits.Features.EncapsulateField)]
        public void EncapsulateFieldNamedValue()
        {
            var text = @"
class Program
{
    private const int [|bar|] = 3;
}
";

            var expected = @"
class Program
{
    private const int bar = 3;

    public static int Bar
    {
        get
        {
            return bar;
        }
    }
}
";
            Test(text, expected, compareTokens: false, index: 0);
        }

        [WorkItem(694276)]
        [Fact, Trait(Traits.Feature, Traits.Features.EncapsulateField)]
        public void PublicFieldNamed__()
        {
            var text = @"
class Program
{
    public int [|__|];
}
";

            var expected = @"
class Program
{
    private int __1;

    public int __
    {
        get
        {
            return __1;
        }

        set
        {
            __1 = value;
        }
    }
}
";
            Test(text, expected, compareTokens: false, index: 0);
        }

        [WorkItem(695046)]
        [Fact, Trait(Traits.Feature, Traits.Features.EncapsulateField)]
        public void AvailableNotJustOnVariableName()
        {
            var text = @"
class Program
{
    pri[||]vate int x;
}
";

            TestActionCount(text, 2);
        }

        [WorkItem(705898)]
        [Fact, Trait(Traits.Feature, Traits.Features.EncapsulateField)]
        public void CopyFieldAccessibility()
        {
            var text = @"
class Program
{
    protected const int [|bar|] = 3;
}
";

            var expected = @"
class Program
{
    private const int bar = 3;

    protected static int Bar
    {
        get
        {
            return bar;
        }
    }
}
";
            Test(text, expected, compareTokens: false, index: 0);
        }

        [Fact, Trait(Traits.Feature, Traits.Features.EncapsulateField)]
        public void UpdateReferencesCrossProject()
        {
            var text = @"
<Workspace>
    <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
        <Document>
public class C
{
    public int [|foo|];
}
        </Document>
    </Project>
    <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true"">
        <ProjectReference>Assembly1</ProjectReference>
        <Document>
public class D
{
    void bar()
    {
        var c = new C;
        c.foo = 3;
    }
}
        </Document>
    </Project>
</Workspace>";

            var expected = @"
<Workspace>
    <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
        <Document>
public class C
{
    private int foo;

    public int Foo
    {
        get
        {
            return foo;
        }

        set
        {
            foo = value;
        }
    }
}
        </Document>
    </Project>
    <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true"">
        <ProjectReference>Assembly1</ProjectReference>
        <Document>
public class D
{
    void bar()
    {
        var c = new C;
        c.Foo = 3;
    }
}
        </Document>
    </Project>
</Workspace>";
            Test(text, expected, new CodeAnalysis.CSharp.CSharpParseOptions(), TestOptions.ReleaseExe, compareTokens: false);
        }

        [WorkItem(713269)]
        [Fact, Trait(Traits.Feature, Traits.Features.EncapsulateField)]
        public void PreserveUnsafe()
        {
            var text = @"
class C
{
    unsafe int* [|foo|];
}
";

            var expected = @"
class C
{
    unsafe int* foo;

    public unsafe int* Foo
    {
        get
        {
            return foo;
        }

        set
        {
            foo = value;
        }
    }
}
";
            Test(text, expected, compareTokens: false, index: 0);
        }

        [WorkItem(713240)]
        [Fact, Trait(Traits.Feature, Traits.Features.EncapsulateField)]
        public void ConsiderReturnTypeAccessibility()
        {
            var text = @"
public class Program
{
    private State [|state|];
}

internal enum State
{
    WA
}
";

            var expected = @"
public class Program
{
    private State state;

    internal State State
    {
        get
        {
            return state;
        }

        set
        {
            state = value;
        }
    }
}

internal enum State
{
    WA
}
";
            Test(text, expected, compareTokens: false, index: 0);
        }

        [WorkItem(713191)]
        [Fact, Trait(Traits.Feature, Traits.Features.EncapsulateField)]
        public void DoNotReferToReadOnlyPropertyInConstructor()
        {
            var text = @"
class Program
{
    public readonly int [|Field|];

    public Program(int f)
    {
        this.Field = f;
    }
}";

            var expected = @"
class Program
{
    private readonly int field;

    public Program(int f)
    {
        this.field = f;
    }

    public int Field
    {
        get
        {
            return field;
        }
    }
}";
            Test(text, expected, compareTokens: false, index: 0);
        }

        [WorkItem(713191)]
        [Fact, Trait(Traits.Feature, Traits.Features.EncapsulateField)]
        public void DoNotReferToStaticReadOnlyPropertyInConstructor()
        {
            var text = @"
class Program
{
    public static readonly int [|Field|];

    static Program()
    {
        Field = 3;
    }
}";

            var expected = @"
class Program
{
    private static readonly int field;

    static Program()
    {
        field = 3;
    }

    public static int Field
    {
        get
        {
            return field;
        }
    }
}";
            Test(text, expected, compareTokens: false, index: 0);
        }

        [WorkItem(765959)]
        [Fact, Trait(Traits.Feature, Traits.Features.EncapsulateField)]
        public void GenerateInTheCorrectPart()
        {
            var text = @"
partial class Program {}

partial class Program {
   private int [|x|];
}
";
            var expected = @"
partial class Program {}

partial class Program {
    private int x;

    public int X
    {
        get
        {
            return x;
        }
        set
        {
            x = value;
        }
    }
}
";
            Test(text, expected);
        }

        [WorkItem(829178)]
        [Fact, Trait(Traits.Feature, Traits.Features.EncapsulateField)]
        public void ErrorTolerance()
        {
            var text = @"class Program
{
    a b c [|b|]
}";

            using (var workspace = CreateWorkspaceFromFile(text, null, null))
            {
                var result = GetCodeRefactoring(workspace, nodeLocator: null);
                Assert.NotNull(result);
            }
        }

        [WorkItem(834072)]
        [Fact, Trait(Traits.Feature, Traits.Features.EncapsulateField)]
        public void DuplicateFieldErrorTolerance()
        {
            var text = @"
class Program
{
    public const string [|s|] = ""S"";
    public const string s = ""S"";
    }
";

            using (var workspace = CreateWorkspaceFromFile(text, null, null))
            {
                var result = GetCodeRefactoring(workspace, nodeLocator: null);
                Assert.NotNull(result);
            }
        }

        [WorkItem(862517)]
        [Fact, Trait(Traits.Feature, Traits.Features.EncapsulateField)]
        public void Trivia()
        {
            var text = @"
namespace ConsoleApplication1
{
    class Program
    {
        // Some random comment
        public int myI[||]nt;
    }
}
";

            var expected = @"
namespace ConsoleApplication1
{
    class Program
    {
        // Some random comment
        private int myInt;

        public int MyInt
        {
            get
            {
                return myInt;
            }

            set
            {
                myInt = value;
            }
        }
    }
}";

            Test(text, expected);
        }

        [WorkItem(1096007, "https://github.com/dotnet/roslyn/issues/282")]
        [Fact, Trait(Traits.Feature, Traits.Features.EncapsulateField)]
        public void DoNotEncapsulateOutsideTypeDeclaration()
        {
            TestMissing(@"
var [|x|] = 1;");

            TestMissing(@"
namespace N
{
    var [|x|] = 1;
}");

            TestMissing(@"
enum E
{
    [|x|] = 1;
}");
        }
    }
}


text:
using PokemonUnity;
using PokemonUnity.Monster;
using PokemonUnity.UX;
using System;

namespace PokemonEssentials.Interface
{
	/// <summary>
	/// Logic that's used by Game while player is in `Overworld_Field`
	/// </summary>
	public interface IInterpreterFieldMixin
	{
		//object[] pbParams { get; }

		object getVariable(params int[] arg);
		PokemonEssentials.Interface.PokeBattle.IPokemon pbGetPokemon(int id);
		bool pbHeadbutt();
		bool pbPushThisBoulder();
		void pbPushThisEvent();
		void pbSetEventTime(params int[] arg);
		/// <summary>
		/// Used when player encounters a trainer, and battle logic get triggered
		/// </summary>
		/// <param name="symbol"></param>
		/// <returns>Plays TrainerType Audio Theme and returns true</returns>
		bool pbTrainerIntro(TrainerTypes symbol);
		void pbTrainerEnd();
		void setTempSwitchOff(string c);
		void setTempSwitchOn(string c);
		void setVariable(params int[] arg);
		bool tsOff(string c);
		bool tsOn(string c);
	}
}


text:
title: PapljMultiplicativeExpr.getAsterisk - aesi-intellij
---

[aesi-intellij](../../index.html) / [org.metaborg.paplj.psi](../index.html) / [PapljMultiplicativeExpr](index.html) / [getAsterisk](.)

# getAsterisk

`@Nullable abstract fun getAsterisk(): @Nullable PsiElement?`


text:
<?php

namespace Tmdb\Tests\Repository;

use Tmdb\Repository\CollectionRepository;

class CollectionRepositoryTest extends TestCase
{
    const COLLECTION_ID = 120;

    /**
     * @test
     */
    public function shouldLoadCollection()
    {
        $repository = $this->getRepositoryWithMockedHttpAdapter();

        $this->getAdapter()->expects($this->once())
            ->method('get')
            ->with($this->getRequest('https://api.themoviedb.org/3/collection/'.self::COLLECTION_ID,['append_to_response'=>'images']))
        ;

        $repository->load(self::COLLECTION_ID);
    }

    /**
     * @test
     */
    public function shouldGetImages()
    {
        $repository = $this->getRepositoryWithMockedHttpAdapter();

        $this->getAdapter()->expects($this->once())
            ->method('get')
            ->with($this->getRequest('https://api.themoviedb.org/3/collection/'.self::COLLECTION_ID.'/images'))
        ;

        $repository->getImages(self::COLLECTION_ID);
    }

    /**
     * @test
     */
    public function shouldBeAbleToSetFactories()
    {
        /**
         * @var CollectionRepository $repository
         */
        $repository = $this->getRepositoryWithMockedHttpClient();
        $class      = new \stdClass();

        $repository->setImageFactory($class);

        $this->assertInstanceOf('stdClass', $repository->getImageFactory());
    }

    protected function getApiClass()
    {
        return 'Tmdb\Api\Collections';
    }

    protected function getRepositoryClass()
    {
        return 'Tmdb\Repository\CollectionRepository';
    }
}


text:
package com.valtech.source.ag.cla;

import java.util.Arrays;

/**
 * @author Dietmar Menges (dietmar.menges@valtech.de)
 */
class OrCombinedOption extends ArgumentOption
{
   private String[] m_Or;

   // private String m_Choosen;
   private boolean m_WrongOrArgument = true;

   private boolean isOrOptionValid()
   {
      assert m_Or != null;
      assert m_Or.length > 0;
      for (int i = 0; i < m_Or.length; ++i)
      {
         String next = m_Or[i];
         assert next != null;
         assert next.length() > 0;
      }

      return true;
   }

   OrCombinedOption(String option, String[] or, String description, boolean mandatory)
   {
      super(option, description, mandatory);
      m_Or = Arrays.copyOf( or, or.length );
      assert isOrOptionValid();
   }

   protected int process(String[] args, int index)
   {
      assert args != null;
      assert args.length > 0;
      assert index >= 0;
      assert index < args.length;

      int resultingIndex = -1;

      if (args[index].equals(getOptionIdentifier()))
      {
         if (alreadyProcessed())
         {
            setDuplicateOption();
            if (index + 1 >= args.length || args[index + 1].startsWith(HYPHEN))
            {
               resultingIndex = index;
            }
            else
            {
               resultingIndex = index + 1;
            }
         }
         else
         {
            if (index + 1 >= args.length || args[index + 1].startsWith(HYPHEN))
            {
               setMissingArgument();
               resultingIndex = index;
            }
            else
            {
               resultingIndex = index + 1;
               String arg = args[resultingIndex];
               for (int i = 0; i < m_Or.length; ++i)
               {
                  if (m_Or[i].equals(arg))
                  {
                     m_WrongOrArgument = false;
                     break;
                  }
               }

               if (!m_WrongOrArgument)
               {
                  setArgument(args[resultingIndex]);
               }
            }

            setProcessed();
         }
      }

      return resultingIndex;
   }

   protected boolean isStateValid(CallbackIf cb)
   {
      if (m_WrongOrArgument)
      {
         cb.wrongArgumentForOrCombinedOption(getOptionIdentifier());
      }

      return super.isStateValid(cb) && !m_WrongOrArgument;
   }
}


text:
export const INIT_GAME = 'INIT_GAME'
export const PLAY = 'PLAY'
export const DISCARD = 'DISCARD'


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;

namespace BeProductive.Api
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var config = new ConfigurationBuilder()
                .AddCommandLine(args)
                .AddEnvironmentVariables(prefix: "ASPNETCORE_")
                .Build();

            var host = new WebHostBuilder()
                .UseConfiguration(config)
                .UseKestrel()
                .UseContentRoot(Directory.GetCurrentDirectory())
                .UseIISIntegration()
                .UseStartup<Startup>()
                .Build();

            host.Run();
        }
    }
}


text:
/****

 activequant - activestocks.eu

 This program is free software; you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation; either version 2 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License along
 with this program; if not, write to the Free Software Foundation, Inc.,
 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

 contact  : contact@activestocks.eu
 homepage : http://www.activestocks.eu

 ****/
package org.activequant.util;

import java.util.ArrayList;
import java.util.List;

import org.activequant.core.domainmodel.InstrumentSpecification;
import org.activequant.core.domainmodel.data.Quote;
import org.activequant.dao.ISpecificationDao;
import org.activequant.data.retrieval.IQuoteSubscriptionSource;
import org.activequant.data.retrieval.ISubscription;
import org.activequant.util.spring.ServiceLocator;

/**
 * Simple class that subscribes for a live feed and puts the incoming events
 * (quotes) in the database.
 *

 * Required properties are :

 * - IQuoteSubscriptionSource instance

 * - QuoteDao

 *
 *
 *

 * Use {@link #getFlushTimeout() flushTimeout} to determine how often the
 * collected data is flushed out to the database. Default value is 1000 millis.
 *

 * History:

 * - [14.08.2007] Created (GhostRider)

 * - [26.10.2007] Added fifo queueing. Some cleanup (Mike Kroutikov)

 * - [01.04.2010] Added vendor identifier, adapted it for P2 (GhostRider)

 *
 * @author GhostRider
 * @author Mike Kroutikov
 */
public class QuoteRecorder extends MarketDataEntityRecorder<Quote> {

	private IQuoteSubscriptionSource source;
	private ISpecificationDao specDao;
	private String vendorIdentifier;

	/**
	 * Injecter for the specification dao.
	 *
	 * @param specDao
	 */
	public void setSpecDao(ISpecificationDao specDao) {
		this.specDao = specDao;
	}

	/**
	 * Quote event source.
	 *
	 * @return quote event source.
	 */
	public IQuoteSubscriptionSource getSource() {
		return source;
	}

	/**
	 * can be used to drill down on specific vendors ...
	 * @return
	 */
	public String getVendorIdentifier() {
		return vendorIdentifier;
	}

	public void setVendorIdentifier(String vendorIdentifier) {
		this.vendorIdentifier = vendorIdentifier;
	}

	/**
	 * Sets quote event source.
	 *
	 * @param quoteSource
	 *            quote event source.
	 */
	public void setSource(IQuoteSubscriptionSource source) {
		this.source = source;
	}

	@Override
	protected ISubscription<Quote> subscribe(InstrumentSpecification spec) throws Exception {
		return source.subscribe(spec);
	}

	/**
	 * Method that loads the to-be-recorded instruments from the database and subscribes to them.
	 * @throws Exception
	 */
	protected void buildSubscriptions() throws Exception{
		InstrumentSpecification[] specs = specDao.findAll();

		List<InstrumentSpecification> specsList = new ArrayList<InstrumentSpecification>();
		for(InstrumentSpecification spec : specs)
		{
			if(vendorIdentifier!=null)
			{
				if(spec.getVendor().equals(vendorIdentifier))
					specsList.add(spec);
			}
			else
				specsList.add(spec);
		}

		log.info("Subscribing to "+specsList.size()+" specs.");
		super.setInstrumentsToSubscribeTo(specsList.toArray(new InstrumentSpecification[]{}));
	}

	/**
	 * Overrides record function to build dynamically the list of instruments to which to subscribe to.
	 */
	@Override
	public void record() throws Exception {
		buildSubscriptions();
		super.record();
	}

	/**
	 * Starter. By default uses the following resource for configuration:
	 *
	 *

	 * applications / quoterecorder / factory.xml
	 *

	 *
	 * You can pass any configuration file by specifying it as this program's
	 * first (and only) parameter.
	 *
	 * @param args
	 *            parameters.
	 */
	public static void main(String[] args) {
		try {
			if (args.length == 0) {
				ServiceLocator.instance("data/quoterecorder.xml").getContext();
			} else {
				ServiceLocator.instance(args[0]).getContext();
			}
		} catch (Exception x) {
			x.printStackTrace();
			System.exit(0);
		}
	}

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project name="birf-core">
	<property name="core.MAX_MEMORY" value="512m" />
	<property name="core.STRICT" value="true" />
	<property name="core.SHOW_DEPRECATION_WARNINGS" value="false" />
	<property name="core.SWF_VERSION" value="10" />
	<property name="core.TARGET_PLAYER_VERSION" value="10.0.0" />
	<property name="core.LIB_DEPENDENCIES" value="as3-signals-v0.9-BETA.swc,Swiftsuspenders-v2.0.0rc2stray2.swc" />

	<target name="compile-release" description="Compile release build of BiRF core.">
		<echo message="__[ COMPILING CORE RELEASE SWC ]__" />
		<echo message="__[ Target player: ${core.TARGET_PLAYER_VERSION} ]__" />
		<echo message="__[ Swf version: ${core.SWF_VERSION} ]__" />
		<compc output="${OUT_DIR}/birf-v${BUILD_VERSION}.swc"
				optimize="true"
				debug="false"
				compiler.as3="true"
				incremental="true"
				maxmemory="${core.MAX_MEMORY}"
				strict="${core.STRICT}"
				compiler.show-deprecation-warnings="${core.SHOW_DEPRECATION_WARNINGS}"
				swf-version="${core.SWF_VERSION}"
				target-player="${core.TARGET_PLAYER_VERSION}">
			<load-config filename="${FLEX_HOME}/frameworks/flex-config.xml" />
			<compiler.define name="CONFIG::VERSION" value="'${BUILD_VERSION}'" />
			<compiler.define name="CONFIG::DEBUG" value="false" />
			<!-- Source code to compile. -->
			<include-sources dir="${SRC_DIR}" includes="*" />
			<!-- Libs to use during compilation (not included in final SWC). -->
			<external-library-path dir="${RELEASE_LIB_DIR}" append="true" includes="${core.LIB_DEPENDENCIES}" />
		</compc>
	</target>

	<target name="compile" description="Compile debug build of BiRF core.">
		<echo message="__[ COMPILING CORE DEBUG SWC ]__" />
		<echo message="__[ Target player: ${core.TARGET_PLAYER_VERSION} ]__" />
		<echo message="__[ Swf version: ${core.SWF_VERSION} ]__" />
		<compc output="${OUT_DIR}/birf-v${BUILD_VERSION}-debug.swc"
				optimize="false"
				debug="true"
				compiler.as3="true"
				incremental="true"
				maxmemory="${core.MAX_MEMORY}"
				strict="${core.STRICT}"
				compiler.show-deprecation-warnings="${core.SHOW_DEPRECATION_WARNINGS}"
				swf-version="${core.SWF_VERSION}"
				target-player="${core.TARGET_PLAYER_VERSION}">
			<load-config filename="${FLEX_HOME}/frameworks/flex-config.xml" />
			<compiler.define name="CONFIG::VERSION" value="'${BUILD_VERSION}'" />
			<compiler.define name="CONFIG::DEBUG" value="true" />
			<!-- Source code to compile. -->
			<source-path path-element="${SRC_DIR}" />
			<include-sources dir="${SRC_DIR}" includes="*" />
			<!-- Libs to use during compilation (not included in final SWC). -->
			<external-library-path dir="${LIB_DIR}" append="true" includes="${core.LIB_DEPENDENCIES}" />
		</compc>
	</target>

	<target name="compile-baked" description="Compile baked debug build of BiRF core.">
		<echo message="__[ COMPILING BAKED CORE DEBUG SWC ]__" />
		<echo message="__[ Target player: ${core.TARGET_PLAYER_VERSION} ]__" />
		<echo message="__[ Swf version: ${core.SWF_VERSION} ]__" />
		<compc output="${OUT_DIR}/birf-v${BUILD_VERSION}-baked-debug.swc"
				optimize="false"
				debug="true"
				compiler.as3="true"
				incremental="true"
				maxmemory="${core.MAX_MEMORY}"
				strict="${core.STRICT}"
				compiler.show-deprecation-warnings="${core.SHOW_DEPRECATION_WARNINGS}"
				swf-version="${core.SWF_VERSION}"
				target-player="${core.TARGET_PLAYER_VERSION}">
			<load-config filename="${FLEX_HOME}/frameworks/flex-config.xml" />
			<compiler.define name="CONFIG::VERSION" value="'${BUILD_VERSION}'" />
			<compiler.define name="CONFIG::DEBUG" value="true" />
			<!-- Source code to compile. -->
			<source-path path-element="${SRC_DIR}" />
			<include-sources dir="${SRC_DIR}" includes="*" />
			<!-- Libs to include in final SWC. -->
			<include-libraries dir="${LIB_DIR}" includes="${core.LIB_DEPENDENCIES}" />
		</compc>
	</target>

	<target name="compile-baked-release" description="Compile baked release build of BiRF core.">
		<echo message="__[ COMPILING BAKED CORE RELEASE SWC ]__" />
		<echo message="__[ Target player: ${core.TARGET_PLAYER_VERSION} ]__" />
		<echo message="__[ Swf version: ${core.SWF_VERSION} ]__" />
		<compc output="${OUT_DIR}/birf-v${BUILD_VERSION}-baked.swc"
				optimize="true"
				debug="false"
				compiler.as3="true"
				incremental="true"
				maxmemory="${core.MAX_MEMORY}"
				strict="${core.STRICT}"
				compiler.show-deprecation-warnings="${core.SHOW_DEPRECATION_WARNINGS}"
				swf-version="${core.SWF_VERSION}"
				target-player="${core.TARGET_PLAYER_VERSION}">
			<load-config filename="${FLEX_HOME}/frameworks/flex-config.xml" />
			<compiler.define name="CONFIG::VERSION" value="'${BUILD_VERSION}'" />
			<compiler.define name="CONFIG::DEBUG" value="false" />
			<!-- Source code to compile. -->
			<source-path path-element="${SRC_DIR}" />
			<include-sources dir="${SRC_DIR}" includes="*" />
			<!-- Libs to include in final SWC. -->
			<include-libraries dir="${RELEASE_LIB_DIR}" includes="${core.LIB_DEPENDENCIES}" />
		</compc>
	</target>
</project>


text:
package com.gemstone.gemfire.internal;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.List;

/**
 * This class contains static methods for manipulating files and directories,
 * such as recursively copying or deleting files.
 *
 * TODO A lot of this functionality is probably duplicating apache commons io,
 * maybe we should switch to that.
 *
 * @author dsmith
 *
 */
public class FileUtil {
  public static final long MAX_TRANSFER_SIZE = Long.getLong("gemfire.FileUtil.MAX_TRANSFER_SIZE", 1024 * 1024).longValue();
  public static final boolean USE_NIO = !Boolean.getBoolean("gemfire.FileUtil.USE_OLD_IO");
  public static final String extSeparator = ".";

  /**
   * Copy a file from the source file to the destination file.
   * If the source is a directory, it will be copied recursively.
   *
   * Note that unlike unix cp, if the destination is directory,
   * the source *contents* will be copied to the destination *contents*,
   * not as a subdirectory of dest.
   *
   * @param source the source file or directory
   * @param dest the destination file or directory.
   * @throws IOException
   */
  public static void copy(File source, File dest) throws IOException {
    if(source.isDirectory()) {
      dest.mkdir();
      for(File child: listFiles(source)) {
        copy(child, new File(dest, child.getName()));
      }
    } else {
      if(source.exists()) {
        long lm = source.lastModified();
        if(dest.isDirectory()) {
          dest = new File(dest, source.getName());
        }
        FileOutputStream fos = new FileOutputStream(dest);
        try {
          FileInputStream fis = new FileInputStream(source);
          try {
            if(USE_NIO) {
              nioCopy(fos, fis);
            } else {
              oioCopy(source, fos, fis);
            }
          } finally {
            fis.close();
          }
        } finally {
          fos.close();
        }
        dest.setExecutable(source.canExecute(), true);
        dest.setLastModified(lm);
      }
    }
  }

  /**
   * Basically just like {@link File#listFiles()} but instead of returning null
   * returns an empty array. This fixes bug 43729
   */
  public static File[] listFiles(File dir) {
    File[] result = dir.listFiles();
    if (result == null) {
      result = new File[0];
    }
    return result;
  }
  /**
   * Basically just like {@link File#listFiles(FilenameFilter)} but instead of returning null
   * returns an empty array. This fixes bug 43729
   */
  public static File[] listFiles(File dir, FilenameFilter filter) {
    File[] result = dir.listFiles(filter);
    if (result == null) {
      result = new File[0];
    }
    return result;
  }
  /**
   * Copy a single file using NIO.
   * @throws IOException
   */
  private static void nioCopy(FileOutputStream fos, FileInputStream fis)
      throws IOException {
    FileChannel outChannel = fos.getChannel();
    FileChannel inChannel = fis.getChannel();
    long length = inChannel.size();
    long offset = 0;
    while(true) {
      long remaining = length - offset;

      long toTransfer = remaining < MAX_TRANSFER_SIZE ? remaining : MAX_TRANSFER_SIZE;
      long transferredBytes = inChannel.transferTo(offset, toTransfer, outChannel);
      offset += transferredBytes;
      length = inChannel.size();
      if(offset >= length) {
        break;
      }
    }
  }

  /**
   * Copy a single file using the java.io.
   * @throws IOException
   */
  private static void oioCopy(File source, FileOutputStream fos, FileInputStream fis)
  throws IOException {
    int size = (int) (source.length() < MAX_TRANSFER_SIZE ? source.length() : MAX_TRANSFER_SIZE);
    byte[] buffer = new byte[size];
    int read;
    while((read = fis.read(buffer)) > 0) {
      fos.write(buffer, 0, read);
    }

  }

  /**
   * Recursively delete a file or directory.
   *
   * @throws IOException
   *           if the file or directory couldn't be deleted. Unlike File.delete,
   *           which just returns false.
   */
  public static void delete(File file) throws IOException {
    if(file.exists() && file.isDirectory()) {
      for(File child: listFiles(file)) {
        delete(child);
      }
    }

    if(file.exists() && !file.delete()) {
      throw new IOException("Could not delete " + file);
    }
  }

  /**
   * Recursively delete a file or directory.
   * A description of any files or directories
   * that can not be deleted will be added to failures
   * if failures is non-null.
   * This method tries to delete as much as possible.
   */
  public static void delete(File file, StringBuilder failures) {
    if(file.exists() && file.isDirectory()) {
      for(File child: listFiles(file)) {
        delete(child, failures);
      }
    }

    if(file.exists() && !file.delete()) {
      if (failures != null) {
        failures.append("Could not delete ").append(file).append('\n');
      }
    }
  }

  /**
   * Find the file whose name matches the given regular
   * expression. The regex is matched against the absolute
   * path of the file.
   *
   * This could probably use a lot of optimization!
   */
  public static File find(File baseFile, String regex) {
    if(baseFile.getAbsolutePath().matches(regex)) {
      return baseFile;
    }
    if(baseFile.exists() && baseFile.isDirectory()) {
      for(File child: listFiles(baseFile)) {
        File foundFile =  find(child, regex);
        if(foundFile != null) {
          return foundFile;
        }
      }
    }
    return null;
  }

  /**
   * Find a files in a given base directory that match
   * a the given regex. The regex is matched against the
   * full path of the file.
   */
  public static List<File> findAll(File baseFile, String regex) {
    ArrayList<File> found = new ArrayList<File>();
    findAll(baseFile, regex, found);
    return found;
  }

  /**
   * Destroys all files that match the given regex that
   * are in the given directory.
   * If a destroy fails it is ignored and an attempt is
   * made to destroy any other files that match.
   */
  public static void deleteMatching(File baseFile, String regex) {
    if(baseFile.exists() && baseFile.isDirectory()) {
      for(File child: listFiles(baseFile)) {
        if (child.getName().matches(regex)) {
          try {
            delete(child);
          } catch (IOException ignore) {
          }
        }
      }
    }
  }

  /** Implementation of findAll. */
  private static void findAll(File baseFile, String regex, List<File> found) {
    if(baseFile.getAbsolutePath().matches(regex)) {
      found.add(baseFile);
    }
    if(baseFile.exists() && baseFile.isDirectory()) {
      for(File child: listFiles(baseFile)) {
        findAll(child, regex, found);
      }
    }
  }

  /**
   * Convert a file into a relative path from a given parent. This is useful if
   * you want to write out the file name into that parent directory.
   *
   * @param parent
   *          The parent directory.
   * @param file
   *          The file we want to covert to a relative file.
   * @return A file, such that new File(parent, returnValue) == file. Note that
   *         if file does not have the parent in it's path, an the absolute
   *         version if the file is returned.
   */
  public static File removeParent(File parent, File file) {
    String absolutePath = file.getAbsolutePath();
    String parentAbsolutePath = parent.getAbsolutePath();
    String newPath = absolutePath.replace(parentAbsolutePath + "/", "");
    return new File(newPath);
  }

  /**
   * Copy a URL to a file.
   * @throws IOException
   */
  public static void copy(URL url, File file) throws IOException {
    InputStream is = url.openStream();
    try {
      OutputStream os = new FileOutputStream(file);
      try {
        byte[] buffer = new byte[8192];
        int read;
        while((read = is.read(buffer)) > 0) {
          os.write(buffer, 0, read);
        }
      } finally {
        os.close();
      }
    } finally {
      is.close();
    }

  }

  /**
   * A safer version of File.mkdirs, which works around
   * a race in the 1.5 JDK where two VMs creating the same
   * directory chain at the same time could end up in one
   * VM failing to create a subdirectory.
   * @param file
   */
  public static boolean mkdirs(File file) {
    final File parentFile = file.getAbsoluteFile().getParentFile();
    if(! parentFile.exists()) {
      mkdirs(parentFile);
    }
    //As long as someone successfully created the parent file
    //go ahead and create the child directory.
    if(parentFile.exists()) {
      return file.mkdir();
    } else {
      return false;
    }
  }

  /**
   * Returns the file name with the extension stripped off (if it has one).
   *
   * @param fileName the file name
   * @return the file name with the extension stripped off (if it had one)
   */
  public static String stripOffExtension(final String fileName) {
    if (fileName.contains(extSeparator)) {
      // strip off the extension and right-most "."
      return fileName.substring(0, fileName.lastIndexOf(extSeparator));
    }
    return fileName;
  }
}


text:
package com.abewy.android.apps.contacts.util;

import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import android.support.v4.util.LongSparseArray;
import com.abewy.android.apps.contacts.R;
import com.abewy.android.apps.contacts.core.CorePrefs;
import com.abewy.android.apps.contacts.model.Contact;
import com.abewy.android.apps.contacts.model.ContactEmail;
import com.abewy.android.apps.contacts.model.ContactPhone;
import com.abewy.android.extended.items.BaseType;

public class ContactsUtil
{
	private static LongSparseArray<Integer>	map			= new LongSparseArray<Integer>();

	private static int[]					circleBgds	= new int[] {
					R.drawable.circle_bgd_1,
					R.drawable.circle_bgd_2,
					R.drawable.circle_bgd_3,
					R.drawable.circle_bgd_4,
					R.drawable.circle_bgd_5,
					R.drawable.circle_bgd_6,
					R.drawable.circle_bgd_7,
					R.drawable.circle_bgd_8,
					R.drawable.circle_bgd_9,
					R.drawable.circle_bgd_10,
					R.drawable.circle_bgd_11,
					R.drawable.circle_bgd_12,
					R.drawable.circle_bgd_13,
					R.drawable.circle_bgd_14,
					R.drawable.circle_bgd_15,
					R.drawable.circle_bgd_16			};

	private static int[]					squareBgds	= new int[] {
					R.drawable.square_bgd_1,
					R.drawable.square_bgd_2,
					R.drawable.square_bgd_3,
					R.drawable.square_bgd_4,
					R.drawable.square_bgd_5,
					R.drawable.square_bgd_6,
					R.drawable.square_bgd_7,
					R.drawable.square_bgd_8,
					R.drawable.square_bgd_9,
					R.drawable.square_bgd_10,
					R.drawable.square_bgd_11,
					R.drawable.square_bgd_12,
					R.drawable.square_bgd_13,
					R.drawable.square_bgd_14,
					R.drawable.square_bgd_15,
					R.drawable.square_bgd_16			};

	private static int						current		= 0;

	private static final int				BGD_COUNT	= squareBgds.length;

	public static int getSquarePlaceHolder(long id)
	{
		if (map.indexOfKey(id) < 0)
			map.append(id, getNextIndex());

		int index = map.get(id);

		return squareBgds[index % BGD_COUNT];
	}

	public static int getCirclePlaceHolder(long id)
	{
		if (map.indexOfKey(id) < 0)
			map.append(id, getNextIndex());

		int index = map.get(id);

		return circleBgds[index % BGD_COUNT];
	}

	public static int getDrawable(long id)
	{
		if (CorePrefs.isRoundedPictures())
			return getCirclePlaceHolder(id);
		else
			return getSquarePlaceHolder(id);
	}

	private static int getNextIndex()
	{
		if (current >= squareBgds.length)
			current = 0;

		return current++;
	}

	public static ArrayList<BaseType> filter(String query, List<BaseType> lookingInto)
	{
		ArrayList<BaseType> list = new ArrayList<BaseType>();
		query = query.toLowerCase();

		for (BaseType baseType : lookingInto)
		{
			Contact contact = (Contact) baseType;

			if (StringUtils.startsWith(contact.getName().toLowerCase(), query))
			{
				list.add(contact);
				continue;
			}

			if (StringUtils.startsWith(contact.getFirstName().toLowerCase(), query))
			{
				list.add(contact);
				continue;
			}

			if (StringUtils.startsWith(contact.getLastName().toLowerCase(), query))
			{
				list.add(contact);
				continue;
			}

			if (contact.getEmailAddresses().size() > 0)
			{
				for (int i = 0, n = contact.getPhoneNumbers().size(); i < n; i++)
				{
					ArrayList<ContactEmail> emails = contact.getEmailAddresses().valueAt(i);

					for (ContactEmail email : emails)
					{
						if (email.email.toLowerCase().indexOf(query) != -1)
						{
							Contact c = new Contact();
							c.setId(contact.getId());
							c.setLookupKey(contact.getLookupKey());
							c.setName(contact.getName());
							c.setFirstName(contact.getFirstName());
							c.setLastName(contact.getLastName());
							c.addEmailAddress(contact.getEmailAddresses().keyAt(i), email.email);
							list.add(c);
							continue;
						}
					}
				}
			}

			if (contact.getPhoneNumbers().size() > 0)
			{
				for (int i = 0, n = contact.getPhoneNumbers().size(); i < n; i++)
				{
					ArrayList<ContactPhone> phones = contact.getPhoneNumbers().valueAt(i);

					for (ContactPhone phone : phones)
					{
						if (phone.phoneNumber.toLowerCase().indexOf(query) != -1)
						{
							Contact c = new Contact();
							c.setId(contact.getId());
							c.setLookupKey(contact.getLookupKey());
							c.setName(contact.getName());
							c.setFirstName(contact.getFirstName());
							c.setLastName(contact.getLastName());
							c.addPhoneNumber(contact.getPhoneNumbers().keyAt(i), phone.phoneNumber);
							list.add(c);
							continue;
						}
					}
				}
			}
		}

		return list;
	}
}


text:
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Threading;
using MS.WindowsAPICodePack.Internal;
using Microsoft.WindowsAPICodePack.Shell.Interop;
using Microsoft.WindowsAPICodePack.Shell.Resources;

namespace Microsoft.WindowsAPICodePack.Shell
{
    internal class MessageListener : IDisposable
    {
        public const uint CreateWindowMessage = (uint)WindowMessage.User + 1;
        public const uint DestroyWindowMessage = (uint)WindowMessage.User + 2;
        public const uint BaseUserMessage = (uint)WindowMessage.User + 5;

        private const string MessageWindowClassName = "MessageListenerClass";

        private static readonly object _threadlock = new object();
        private static uint _atom;
        private static Thread _windowThread = null;
        private static volatile bool _running = false;

        private static ShellObjectWatcherNativeMethods.WndProcDelegate wndProc = WndProc;
        // Dictionary relating window's hwnd to its message window
        private static Dictionary<IntPtr, MessageListener> _listeners = new Dictionary<IntPtr, MessageListener>();
        private static IntPtr _firstWindowHandle = IntPtr.Zero;

        private static readonly object _crossThreadWindowLock = new object();
        private static IntPtr _tempHandle = IntPtr.Zero;

        public event EventHandler<WindowMessageEventArgs> MessageReceived;

        public MessageListener()
        {
            lock (_threadlock)
            {
                if (_windowThread == null)
                {
                    _windowThread = new Thread(ThreadMethod);
                    _windowThread.SetApartmentState(ApartmentState.STA);
                    _windowThread.Name = "ShellObjectWatcherMessageListenerHelperThread";

                    lock (_crossThreadWindowLock)
                    {
                        _windowThread.Start();
                        Monitor.Wait(_crossThreadWindowLock);
                    }

                    _firstWindowHandle = WindowHandle;
                }
                else
                {
                    CrossThreadCreateWindow();
                }

                if (WindowHandle == IntPtr.Zero)
                {
                    throw new ShellException(LocalizedMessages.MessageListenerCannotCreateWindow,
                        Marshal.GetExceptionForHR(Marshal.GetHRForLastWin32Error()));
                }

                _listeners.Add(WindowHandle, this);
            }
        }

        private void CrossThreadCreateWindow()
        {
            if (_firstWindowHandle == IntPtr.Zero)
            {
                throw new InvalidOperationException(LocalizedMessages.MessageListenerNoWindowHandle);
            }

            lock (_crossThreadWindowLock)
            {
                CoreNativeMethods.PostMessage(_firstWindowHandle, (WindowMessage)CreateWindowMessage, IntPtr.Zero, IntPtr.Zero);
                Monitor.Wait(_crossThreadWindowLock);
            }

            WindowHandle = _tempHandle;
        }

        private static void RegisterWindowClass()
        {
            WindowClassEx classEx = new WindowClassEx();
            classEx.ClassName = MessageWindowClassName;
            classEx.WndProc = wndProc;

            classEx.Size = (uint)Marshal.SizeOf(typeof(WindowClassEx));

            var atom = ShellObjectWatcherNativeMethods.RegisterClassEx(ref classEx);
            if (atom == 0)
            {
                throw new ShellException(LocalizedMessages.MessageListenerClassNotRegistered,
                    Marshal.GetExceptionForHR(Marshal.GetHRForLastWin32Error()));
            }
            _atom = atom;
        }

        private static IntPtr CreateWindow()
        {
            IntPtr handle = ShellObjectWatcherNativeMethods.CreateWindowEx(
                0, //extended style
                MessageWindowClassName, //class name
                "MessageListenerWindow", //title
                0, //style
                0, 0, 0, 0, // x,y,width,height
                new IntPtr(-3), // -3 = Message-Only window
                IntPtr.Zero, IntPtr.Zero, IntPtr.Zero);

            return handle;
        }

        private void ThreadMethod() // Message Loop
        {
            lock (_crossThreadWindowLock)
            {
                _running = true;
                if (_atom == 0)
                {
                    RegisterWindowClass();
                }
                WindowHandle = CreateWindow();

                Monitor.Pulse(_crossThreadWindowLock);
            }

            while (_running)
            {
                Message msg;
                if (ShellObjectWatcherNativeMethods.GetMessage(out msg, IntPtr.Zero, 0, 0))
                {
                    ShellObjectWatcherNativeMethods.DispatchMessage(ref msg);
                }
            }
        }

        private static int WndProc(IntPtr hwnd, uint msg, IntPtr wparam, IntPtr lparam)
        {
            switch (msg)
            {
                case CreateWindowMessage:
                    lock (_crossThreadWindowLock)
                    {
                        _tempHandle = CreateWindow();
                        Monitor.Pulse(_crossThreadWindowLock);
                    }
                    break;
                case (uint)WindowMessage.Destroy:
                    break;
                default:
                    MessageListener listener;
                    if (_listeners.TryGetValue(hwnd, out listener))
                    {
                        Message message = new Message(hwnd, msg, wparam, lparam, 0, new NativePoint());
                        listener.MessageReceived.SafeRaise(listener, new WindowMessageEventArgs(message));
                    }
                    break;
            }

            return ShellObjectWatcherNativeMethods.DefWindowProc(hwnd, msg, wparam, lparam);
        }

        public IntPtr WindowHandle { get; private set; }
        public static bool Running { get { return _running; } }

        #region IDisposable Members

        ~MessageListener()
        {
            Dispose(false);
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                lock (_threadlock)
                {
                    _listeners.Remove(WindowHandle);
                    if (_listeners.Count == 0)
                    {
                        CoreNativeMethods.PostMessage(WindowHandle, WindowMessage.Destroy, IntPtr.Zero, IntPtr.Zero);
                    }
                }
            }
        }

        #endregion
    }

    /// <summary>
    /// Encapsulates the data about a window message
    /// </summary>
    public class WindowMessageEventArgs : EventArgs
    {
        /// <summary>
        /// Received windows message.
        /// </summary>
        public Message Message { get; private set; }

        internal WindowMessageEventArgs(Message msg)
        {
            Message = msg;
        }
    }

}


text:
Clazz.declarePackage ("J.adapter.readers.xtal");
Clazz.load (["J.adapter.smarter.AtomSetCollectionReader", "java.util.Hashtable", "JU.Lst", "$.SB"], "J.adapter.readers.xtal.MagresReader", ["java.lang.Double", "JU.PT", "J.adapter.smarter.Atom", "JU.Escape", "$.Logger", "$.Tensor"], function () {
c$ = Clazz.decorateAsClass (function () {
this.currentBlock = -1;
this.cellParams = null;
this.magresUnits = null;
this.interactionTensors = null;
this.header = null;
Clazz.instantialize (this, arguments);
}, J.adapter.readers.xtal, "MagresReader", J.adapter.smarter.AtomSetCollectionReader);
Clazz.prepareFields (c$, function () {
this.magresUnits =  new java.util.Hashtable ();
this.interactionTensors =  new JU.Lst ();
this.header =  new JU.SB ();
});
Clazz.overrideMethod (c$, "initializeReader",
function () {
this.setFractionalCoordinates (false);
this.ignoreFileSpaceGroupName = true;
});
Clazz.overrideMethod (c$, "finalizeReader",
function () {
this.asc.setInfo ("fileHeader", this.header.toString ());
this.finalizeReaderASCR ();
if (this.interactionTensors.size () > 0) this.asc.setAtomSetAuxiliaryInfo ("interactionTensors", this.interactionTensors);
});
Clazz.overrideMethod (c$, "checkLine",
function () {
if (!this.trimLine ()) return true;
switch (this.checkBlock ()) {
case 0:
this.header.append (this.line).append ("\n");
this.appendLoadNote (this.line);
break;
case 1:
if (this.cellParams == null && this.line.startsWith ("lattice")) return this.readCellParams ();
if (this.line.startsWith ("symmetry")) return this.readSymmetry ();
if (this.line.startsWith ("units")) return this.setUnits (false);
if (this.line.startsWith ("atom")) return this.readAtom ();
break;
case 2:
if (this.line.startsWith ("units")) return this.setUnits (true);
return this.readTensor ();
}
return true;
});
Clazz.defineMethod (c$, "trimLine",
 function () {
var pt = this.line.indexOf ("#");
if (pt >= 0) this.line = this.line.substring (0, pt);
this.line = this.line.trim ();
return (this.line.length > 0);
});
Clazz.defineMethod (c$, "checkBlock",
 function () {
if (!(this.line.startsWith ("<") && this.line.endsWith (">")) && !(this.line.startsWith ("[") && this.line.endsWith ("]"))) return this.currentBlock;
this.line = JU.PT.rep (this.line, "<", "[");
this.line = JU.PT.rep (this.line, ">", "]");
switch (Clazz.doubleToInt (("...............[calculation]..[/calculation].[atoms]........[/atoms].......[magres].......[/magres]......").indexOf (this.line + ".") / 15)) {
case 0:
JU.Logger.info ("block indicator ignored: " + this.line);
break;
case 1:
if (this.currentBlock == -1) this.currentBlock = 0;
break;
case 2:
if (this.currentBlock == 0) this.currentBlock = -1;
break;
case 3:
if (this.currentBlock == -1) {
this.currentBlock = 1;
this.asc.newAtomSet ();
this.magresUnits =  new java.util.Hashtable ();
}break;
case 4:
if (this.currentBlock == 1) this.currentBlock = -1;
break;
case 5:
if (this.currentBlock == -1) {
this.currentBlock = 2;
this.magresUnits =  new java.util.Hashtable ();
this.asc.setAtomSetAuxiliaryInfo ("magresUnits", this.magresUnits);
}break;
case 6:
if (this.currentBlock == 2) this.currentBlock = -1;
break;
}
return -2;
});
Clazz.defineMethod (c$, "setUnits",
 function (isMagresBlock) {
var tokens = this.getTokens ();
var id = tokens[1];
if (isMagresBlock) this.appendLoadNote ("Ellipsoid set " + JU.PT.esc (id) + ": " + (id.startsWith ("ms") ? "Magnetic Shielding" : id.startsWith ("efg") ? "Electric Field Gradient" : id.startsWith ("isc") ? "J-Coupling" : "?"));
this.magresUnits.put (id, tokens[2]);
return true;
}, "~B");
Clazz.defineMethod (c$, "readSymmetry",
 function () {
this.setSymmetryOperator (this.getTokens ()[1]);
return true;
});
Clazz.defineMethod (c$, "readCellParams",
 function () {
var tokens = this.getTokens ();
this.cellParams =  Clazz.newFloatArray (9, 0);
for (var i = 0; i < 9; i++) this.cellParams[i] = this.parseFloatStr (tokens[i + 1]);

this.addPrimitiveLatticeVector (0, this.cellParams, 0);
this.addPrimitiveLatticeVector (1, this.cellParams, 3);
this.addPrimitiveLatticeVector (2, this.cellParams, 6);
this.setSpaceGroupName ("P1");
return true;
});
Clazz.defineMethod (c$, "readAtom",
 function () {
var units = this.magresUnits.get ("atom");
if (units == null) return true;
var f = (units.startsWith ("A") ? 1 : 0.5291772);
var tokens = this.getTokens ();
var atom =  new J.adapter.smarter.Atom ();
var pt = 1;
atom.elementSymbol = tokens[pt++];
atom.atomName = J.adapter.readers.xtal.MagresReader.getAtomName (tokens[pt++], tokens[pt++]);
this.asc.addAtomWithMappedName (atom);
var x = this.parseFloatStr (tokens[pt++]) * f;
var y = this.parseFloatStr (tokens[pt++]) * f;
var z = this.parseFloatStr (tokens[pt++]) * f;
atom.set (x, y, z);
this.setAtomCoord (atom);
return true;
});
c$.getAtomName = Clazz.defineMethod (c$, "getAtomName",
 function (name, index) {
return name + "_" + index;
}, "~S,~S");
Clazz.defineMethod (c$, "readTensor",
 function () {
var tokens = this.getTokens ();
var type = tokens[0];
var units = this.magresUnits.get (type);
if (units == null) {
JU.Logger.warn (type + " ignored; no units defined; line: " + this.line);
return true;
}var isIsc = type.startsWith ("isc");
if (tokens.length == 10) {
this.magresUnits.remove (type);
var data =  Clazz.newFloatArray (9, 0);
for (var i = 0; i < 9; ) data[i] = this.parseFloatStr (tokens[++i]);

JU.Logger.info ("Magres reader creating magres_" + type + ": " + JU.Escape.eAF (data));
this.asc.setAtomSetAuxiliaryInfo ("magres_" + type, data);
}var atomName1 = J.adapter.readers.xtal.MagresReader.getAtomName (tokens[1], tokens[2]);
var pt = 3;
var atomName2 = (isIsc ? J.adapter.readers.xtal.MagresReader.getAtomName (tokens[pt++], tokens[pt++]) : null);
if (atomName1.equals (atomName2)) {
JU.Logger.warn (type + " ignored; atom1 == atom2 for " + atomName1 + " line: " + this.line);
return true;
}var id = atomName1;
if (atomName2 != null) id += "//" + atomName2;
var a =  Clazz.newDoubleArray (3, 3, 0);
for (var i = 0; i < 3; i++) for (var j = 0; j < 3; j++) a[i][j] = Double.$valueOf (tokens[pt++]).doubleValue ();

var a1 = this.asc.getAtomFromName (atomName1);
if (a1 == null) return true;
var a2 = null;
var t =  new JU.Tensor ().setFromAsymmetricTensor (a, type, id);
if (atomName2 == null) {
a1.addTensor (t, null, false);
} else {
a2 = this.asc.getAtomFromName (atomName2);
if (a2 == null) return true;
this.interactionTensors.addLast (t);
}t.setAtomIndexes (a1.index, (a2 == null ? -1 : a2.index));
return true;
});
Clazz.defineStatics (c$,
"BLOCK_NEW", -2,
"BLOCK_NONE", -1,
"BLOCK_CALC", 0,
"BLOCK_ATOMS", 1,
"BLOCK_MAGRES", 2);
});


text:
require 'spec_helper'

RSpec.describe 'Trello::CustomField#find' do
  include IntegrationHelpers

  before { setup_trello }

  it 'find with id and get all fields' do
    VCR.use_cassette('custom_field_find_with_id_and_get_all_fields') do
      custom_field = Trello::CustomField.find('5f60e443555b8432d959ae94')
      expect(custom_field).to be_a(Trello::CustomField)

      expect(custom_field.id).not_to be_nil
      expect(custom_field.name).not_to be_nil
      expect(custom_field.model_id).not_to be_nil
      expect(custom_field.model_type).not_to be_nil
      expect(custom_field.field_group).not_to be_nil
      expect(custom_field.enable_display_on_card).not_to be_nil
      expect(custom_field.position).not_to be_nil
      expect(custom_field.type).not_to be_nil
    end
  end

  it 'find with id and get specific fields' do
    VCR.use_cassette('custom_field_find_with_id_and_get_specific_fields') do
      custom_field = Trello::CustomField.find('5f60e443555b8432d959ae94', fields: 'name,type')
      expect(custom_field).to be_a(Trello::CustomField)

      expect(custom_field.id).not_to be_nil
      expect(custom_field.name).not_to be_nil
      expect(custom_field.type).not_to be_nil

      expect(custom_field.model_id).to be_nil
      expect(custom_field.model_type).to be_nil
      expect(custom_field.field_group).to be_nil
      expect(custom_field.enable_display_on_card).to be_nil
      expect(custom_field.position).to be_nil
    end
  end

end


text:
namespace ChilliSource
{
    //------------------------------------------------------------------------------
    u32 GetIndexSize(IndexFormat indexFormat) noexcept
    {
        switch (indexFormat)
        {
            case IndexFormat::k_short:
                return 2;
            default:
                CS_LOG_FATAL("Invalid index format.");
                return 0;
        }
    }
}