text:
#include <fcntl.h>
#include <git2.h>
#include <kdberrors.h>
#include <kdbhelper.h>
#include <kdbproposal.h>
#include <libgen.h>
#include <openssl/md5.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <unistd.h>

#include "../resolver/shared.h"
#include <kdbinvoke.h>

#include "gitresolver.h"

#define TV_MAX_DIGITS 26
#define DEFAULT_CHECKOUT_LOCATION "/tmp/"
#define REFSTRING "refs/heads/"

typedef enum {
	OBJECT,
	HEAD,
} Tracking;

typedef struct
{
	char * tmpFile;				   // temporary filename for checkout
	char * repo;				   // path to repo (currently only local)
	char * workdir;				   // repository workdir
	char * subdirs;				   // subdirectores between file and workdir
	char * branch;				   // branchname
	char * file;				   // filename
	char * refName;				   // git reference name e.g. refs/heads/master
	char * headID;				   // id of the most recent commit
	char * objID;				   // most recent id of the file
	Tracking tracking;			   // track commit ids or object ids
	int setPhase;				   // Set phase counter, 0 setresolver, 1 commit
	mode_t dirmode;				   //
	unsigned char lastHash[MD5_DIGEST_LENGTH]; // hash of the checkdout file
	short checkout;				   // 1 = checkout file to repo, 0 = checkout to temporary file
	short pull;				   // 0 = don't pull repo, 1 = pull repo
} GitData;

static int elektraResolveFilename (Key * parentKey, ElektraResolveTempfile tmpFile)
{
	int rc = 0;
	ElektraInvokeHandle * handle = elektraInvokeOpen ("resolver", 0, 0);
	if (!handle)
	{
		rc = -1;
		goto RESOLVE_FAILED;
	}
	ElektraResolved * resolved = NULL;
	typedef ElektraResolved * (*resolveFileFunc) (elektraNamespace, const char *, ElektraResolveTempfile, Key *);
	resolveFileFunc resolveFunc = *(resolveFileFunc *) elektraInvokeGetFunction (handle, "filename");

	if (!resolveFunc)
	{
		rc = -1;
		goto RESOLVE_FAILED;
	}

	typedef void (*freeHandleFunc) (ElektraResolved *);
	freeHandleFunc freeHandle = *(freeHandleFunc *) elektraInvokeGetFunction (handle, "freeHandle");

	if (!freeHandle)
	{
		rc = -1;
		goto RESOLVE_FAILED;
	}

	resolved = resolveFunc (keyGetNamespace (parentKey), keyString (parentKey), tmpFile, parentKey);

	if (!resolved)
	{
		rc = -1;
		goto RESOLVE_FAILED;
	}
	else
	{
		keySetString (parentKey, resolved->fullPath);
		freeHandle (resolved);
	}

RESOLVE_FAILED:
	elektraInvokeClose (handle, 0);
	return rc;
}
int elektraGitresolverCheckFile (const char * filename)
{
	if (filename[0] == '/') return 0;

	return 1;
}

static void genCheckoutFileName (GitData * data)
{
	// generate temp filename: /tmp/branch_filename_tv_sec:tv_usec
	struct timeval tv;
	gettimeofday (&tv, 0);
	const char * fileName = strrchr (data->file, '/');
	if (!fileName)
		fileName = data->file;
	else
		fileName += 1;
	size_t len = strlen (DEFAULT_CHECKOUT_LOCATION) + strlen (data->branch) + strlen (fileName) + TV_MAX_DIGITS + 1;
	data->tmpFile = elektraCalloc (len);
	snprintf (data->tmpFile, len, "%s%s_%s_%lu:" ELEKTRA_TIME_USEC_F, DEFAULT_CHECKOUT_LOCATION, data->branch, fileName, tv.tv_sec,
		  tv.tv_usec);
}

static unsigned char * hashBuffer (const void * buffer, size_t size)
{
	MD5_CTX c;
	unsigned char * out = elektraMalloc (MD5_DIGEST_LENGTH);
	MD5_Init (&c);
	MD5_Update (&c, buffer, size);
	MD5_Final (out, &c);
	return out;
}

int elektraGitresolverOpen (Plugin * handle ELEKTRA_UNUSED, Key * errorKey ELEKTRA_UNUSED)
{
	// plugin initialization logic
	// this function is optional
	return 1; // success
}

int elektraGitresolverClose (Plugin * handle ELEKTRA_UNUSED, Key * errorKey ELEKTRA_UNUSED)
{
	// free all plugin resources and shut it down
	// this function is optional
	GitData * data = elektraPluginGetData (handle);
	if (!data) return 0;
	if (data->headID) elektraFree (data->headID);
	if (data->tmpFile)
	{
		unlink (data->tmpFile); // remove temporary checked out file when closing
		elektraFree (data->tmpFile);
	}
	if (data->repo) elektraFree (data->repo);
	if (data->workdir) elektraFree (data->workdir);
	if (data->subdirs) elektraFree (data->subdirs);
	if (data->file) elektraFree (data->file);
	if (data->refName) elektraFree (data->refName);
	elektraFree (data);
	elektraPluginSetData (handle, NULL);
	return 1; // success
}
static int initData (Plugin * handle, Key * parentKey)
{

	GitData * data = elektraPluginGetData (handle);
	if (!data)
	{
		KeySet * config = elektraPluginGetConfig (handle);
		data = elektraCalloc (sizeof (GitData));

		Key * key = ksLookupByName (config, "/path", KDB_O_NONE);
		keySetString (parentKey, keyString (key));
		if (elektraResolveFilename (parentKey, ELEKTRA_RESOLVER_TEMPFILE_NONE) == -1)
		{
			return -1;
		}
		data->repo = elektraStrDup (keyString (parentKey));

		// default to master branch when no branchname is supplied
		const char * defaultBranch = "master";
		key = ksLookupByName (config, "/branch", KDB_O_NONE);
		if (!key)
			data->branch = (char *) defaultBranch;
		else
			data->branch = (char *) keyString (key);

		key = ksLookupByName (config, "/tracking", KDB_O_NONE);
		if (!key)
			data->tracking = HEAD;
		else
		{
			if (!strcmp (keyString (key), "object"))
				data->tracking = OBJECT;
			else
				data->tracking = HEAD;
		}
		key = ksLookupByName (config, "/pull", KDB_O_NONE);
		if (!key)
		{
			data->pull = 0;
		}
		else
		{
			data->pull = 1;
		}
		size_t refLen = strlen (REFSTRING) + strlen (data->branch) + 1;
		data->refName = elektraCalloc (refLen);
		snprintf (data->refName, refLen, "%s%s", REFSTRING, data->branch);
		key = ksLookupByName (config, "/checkout", KDB_O_NONE);
		if (!key)
		{
			data->checkout = 0;
		}
		else
		{
			data->checkout = 1;
		}
		elektraPluginSetData (handle, data);
	}
	return 0;
}

static git_buf * discover_repo (char * path)
{
	if (!strcmp (path, "/")) return NULL;

	git_buf * buf = elektraCalloc (sizeof (git_buf));
	int rc = git_repository_discover (buf, path, 0, NULL);
	if (rc)
	{
		git_buf_free (buf);
		elektraFree (buf);
		buf = discover_repo (dirname (path));
		return buf;
	}
	else
	{
		return buf;
	}
}

static git_repository * connectToLocalRepo (GitData * data)
{
	git_libgit2_init ();
	git_repository * repo;
	int rc;
	git_buf buf = GIT_BUF_INIT_CONST (NULL, 0);
	rc = git_repository_discover (&buf, data->repo, 0, NULL);
	if (rc)
	{
		char * repoCopy = elektraStrDup (data->repo);
		git_buf * discovered = discover_repo (dirname (repoCopy));
		if (discovered)
		{
			if (data->workdir) elektraFree (data->workdir);
			data->workdir = elektraStrDup (discovered->ptr);
			elektraFree (repoCopy);
			git_buf_free (discovered);
			elektraFree (discovered);
		}
		else
		{
			git_buf_free (&buf);
			elektraFree (repoCopy);
			return NULL;
		}
	}
	else
	{
		if (data->workdir) elektraFree (data->workdir);
		data->workdir = elektraStrDup (buf.ptr);
	}
	git_buf_free (&buf);
	rc = git_repository_open_ext (&(repo), data->workdir, 0, NULL);
	if (rc)
	{
		return NULL;
	}
	const char * repoPath = git_repository_workdir (repo);
	if (data->workdir) elektraFree (data->workdir);
	data->workdir = elektraStrDup (repoPath);
	struct stat buffer;
	if (stat (data->workdir, &buffer) == -1)
	{
		data->dirmode = 0100;
	}
	else
	{
		data->dirmode = buffer.st_mode;
	}
	char * repoCopy = elektraStrDup (data->repo);
	char * dir = dirname (repoCopy);
	if (data->subdirs) elektraFree (data->subdirs);
	data->subdirs = elektraStrDup (dir + elektraStrLen (data->workdir) - 2);
	if (!strcmp (data->subdirs, ""))
	{
		elektraFree (data->subdirs);
		data->subdirs = NULL;
	}
	elektraFree (repoCopy);
	repoCopy = elektraStrDup (data->repo);
	if (data->file) elektraFree (data->file);
	data->file = elektraStrDup (basename (data->repo));
	elektraFree (repoCopy);
	return repo;
}

static git_reference * getHeadRef (GitData * data, git_repository * repo)
{
	git_reference * headRef;
	int rc = git_reference_lookup (&headRef, repo, data->refName);
	if (rc)
	{
		git_reference_free (headRef);
		return NULL;
	}

	// compare newest commit id to last saved commit id
	// only update if there's a newer commit

	// const git_oid * headObj = git_reference_target (headRef);
	// git_reference_free (headRef);
	//    return headObj;
	return headRef;
}

static char * hasNewCommit (GitData * data, const git_oid * headObj)
{
	size_t IDSize = GIT_OID_HEXSZ + 1;
	char * commitID = elektraCalloc (IDSize);
	git_oid_tostr (commitID, IDSize, headObj);
	if (!data->headID)
	{
		return commitID;
	}
	else
	{
		if (!strcmp (data->headID, commitID))
		{
			elektraFree (commitID);
			return NULL;
		}
		else
		{
			return commitID;
		}
	}
}
static char * hasNewObjectCommit (GitData * data, git_object * blob)
{
	size_t IDSize = GIT_OID_HEXSZ + 1;
	char * objID = elektraCalloc (IDSize);
	git_oid_tostr (objID, IDSize, git_object_id (blob));
	if (!data->objID)
	{
		return objID;
	}
	else
	{
		if (!strcmp (data->objID, objID))
		{
			elektraFree (objID);
			return NULL;
		}
		else
		{
			return objID;
		}
	}
}

static git_object * getBlob (GitData * data, git_repository * repo)
{
	git_object * blob;
	size_t specSize = strlen (data->refName) + strlen (data->file) + 3;
	if (data->subdirs) specSize += strlen (data->subdirs);
	char spec[specSize];
	if (!data->subdirs)
	{
		snprintf (spec, sizeof (spec), "%s:%s", data->refName, data->file);
	}
	else
	{
		snprintf (spec, sizeof (spec), "%s:%s/%s", data->refName, (data->subdirs) + 1, data->file);
	}
	int rc = git_revparse_single (&blob, repo, spec);
	if (rc)
	{
		// file doesn't exist in repo
		return NULL;
	}
	return blob;
}

// inspired by bash make_path
static void makePath (GitData * data)
{
	if (!data->subdirs) return;
	char * path = elektraStrDup (data->repo);
	char * ptr = strrchr (path, '/');
	*ptr = '\0';
	ptr = path + strlen (data->workdir) - 2;
	struct stat sb;
	while ((ptr = strchr (ptr, '/')) != NULL)
	{
		*ptr = '\0';
		if (stat (path, &sb) != 0)
		{
			if (mkdir (path, data->dirmode))
			{
				elektraFree (path);
				return;
			}
		}
		else if (S_ISDIR (sb.st_mode) == 0)
		{
			elektraFree (path);
			return;
		}
		*ptr++ = '/';
	}
	if (stat (path, &sb) && mkdir (path, data->dirmode)) elektraFree (path);
	return;
	elektraFree (path);
}

typedef struct
{
	char * branchName;
	git_oid * oid;
} fetch_cb_data;

static int fetchhead_ref_cb (const char * name, const char * url ELEKTRA_UNUSED, const git_oid * oid, unsigned int is_merge, void * payload)
{
	if (is_merge)
	{
		fetch_cb_data * data = payload;
		data->branchName = elektraStrDup (name);
		data->oid = elektraCalloc (sizeof (git_oid));
		memcpy (data->oid, oid, sizeof (git_oid));
	}
	return 0;
}

typedef enum {
	ERROR,
	NONE,
	NORMAL,
	UPTODATE,
	FASTFORWARD,
	UNBORN,
} MergeAnalysis;

static MergeAnalysis mergeAnalysis (git_repository * repo, const git_annotated_commit ** heads)
{
	git_merge_analysis_t analysis;
	git_merge_preference_t preference;
	int rc = git_merge_analysis (&analysis, &preference, repo, (const git_annotated_commit **) heads, 1);
	if (rc < 0)
	{
		return ERROR;
	}
	if (analysis & GIT_MERGE_ANALYSIS_FASTFORWARD)
	{
		return FASTFORWARD;
	}
	else if (analysis & GIT_MERGE_ANALYSIS_UP_TO_DATE)
	{
		return UPTODATE;
	}
	else if (analysis & GIT_MERGE_ANALYSIS_NORMAL)
	{
		return NORMAL;
	}
	else if (analysis & GIT_MERGE_ANALYSIS_NONE)
	{
		return NONE;
	}
	else if (analysis & GIT_MERGE_ANALYSIS_UNBORN)
	{
		return UNBORN;
	}
	else
	{
		return ERROR;
	}
}

static int doMerge (git_repository * repo, const git_annotated_commit ** heads)
{
	git_merge_options mergeOpts = { GIT_MERGE_OPTIONS_VERSION, .flags = GIT_MERGE_FAIL_ON_CONFLICT };
	git_checkout_options checkoutOpts = { GIT_CHECKOUT_OPTIONS_VERSION, .checkout_strategy = GIT_CHECKOUT_FORCE };

	int rc = git_merge (repo, (const git_annotated_commit **) heads, 1, &mergeOpts, &checkoutOpts);
	if (rc < 0)
	{
		return -1;
	}
	return 0;
}

static int setFFTarget (git_repository * repo, git_oid * oid)
{
	git_reference * out;
	git_reference * ref;
	git_repository_head (&ref, repo);

	int rc = git_reference_set_target (&out, ref, oid, "fastforward");
	if (rc)
	{
		return -1;
	}
	return 0;
}

static int ELEKTRA_UNUSED hasMergeConflicts (git_repository * repo)
{
	git_index * cIdx;
	int hasConflicts = 0;
	git_repository_index (&cIdx, repo);
	hasConflicts = git_index_has_conflicts (cIdx);
	git_index_free (cIdx);
	if (hasConflicts)
	{
		return -1;
	}
	return 0;
}

static int pullFromRemote (GitData * data ELEKTRA_UNUSED, git_repository * repo)
{
	git_remote * remote;
	int rc = git_remote_lookup (&remote, repo, "origin");
	if (rc < 0)
	{
		return -1;
	}
	rc = git_remote_fetch (remote, NULL, NULL, NULL);
	if (rc < 0)
	{
		return -1;
	}
	fetch_cb_data * cb_data = elektraCalloc (sizeof (fetch_cb_data));

	git_repository_fetchhead_foreach (repo, fetchhead_ref_cb, cb_data);

	git_annotated_commit * heads[1];
	rc = git_annotated_commit_lookup (&heads[0], repo, cb_data->oid);
	if (rc < 0)
	{
		return -1;
	}

	MergeAnalysis res = mergeAnalysis (repo, (const git_annotated_commit **) heads);
	rc = 0;
	switch (res)
	{
	case ERROR:
	case UNBORN:
		rc = -1;
		goto PULL_CLEANUP;
		break;
	case NONE:
		goto PULL_CLEANUP;
		break;
	case UPTODATE:
		goto PULL_CLEANUP;
		break;
	case FASTFORWARD:
		rc = doMerge (repo, (const git_annotated_commit **) heads);
		if (rc)
		{
			goto PULL_CLEANUP;
		}
		rc = setFFTarget (repo, cb_data->oid);
		if (rc)
		{
			goto PULL_CLEANUP;
		}
		rc = 0;
		break;
	case NORMAL:
		// rc = doMerge(repo, heads);
		// if(rc)
		//{
		//    goto PULL_CLEANUP;
		//}
		// rc = hasMergeConflicts(repo);
		// if(rc)
		//{
		//    goto PULL_CLEANUP;
		//}
		rc = -1;
		goto PULL_CLEANUP;
		break;
	default:
		rc = -1;
		goto PULL_CLEANUP;
		break;
	}

PULL_CLEANUP:
	git_annotated_commit_free (heads[0]);
	git_repository_state_cleanup (repo);

	return rc;
}

int elektraGitresolverGet (Plugin * handle ELEKTRA_UNUSED, KeySet * returned ELEKTRA_UNUSED, Key * parentKey)
{
	if (!elektraStrCmp (keyName (parentKey), "system/elektra/modules/gitresolver"))
	{
		KeySet * contract = ksNew (
			30, keyNew ("system/elektra/modules/gitresolver", KEY_VALUE, "gitresolver plugin waits for your orders", KEY_END),
			keyNew ("system/elektra/modules/gitresolver/exports", KEY_END),
			keyNew ("system/elektra/modules/gitresolver/exports/open", KEY_FUNC, elektraGitresolverOpen, KEY_END),
			keyNew ("system/elektra/modules/gitresolver/exports/close", KEY_FUNC, elektraGitresolverClose, KEY_END),
			keyNew ("system/elektra/modules/gitresolver/exports/get", KEY_FUNC, elektraGitresolverGet, KEY_END),
			keyNew ("system/elektra/modules/gitresolver/exports/set", KEY_FUNC, elektraGitresolverSet, KEY_END),
			keyNew ("system/elektra/modules/gitresolver/exports/error", KEY_FUNC, elektraGitresolverError, KEY_END),
			keyNew ("system/elektra/modules/gitresolver/exports/checkfile", KEY_FUNC, elektraGitresolverCheckFile, KEY_END),

#include ELEKTRA_README (gitresolver)
			keyNew ("system/elektra/modules/gitresolver/infos/version", KEY_VALUE, PLUGINVERSION, KEY_END), KS_END);
		ksAppend (returned, contract);
		ksDel (contract);

		return 1; // success
	}
	// get all keys

	if (initData (handle, parentKey)) return -1;
	GitData * data = elektraPluginGetData (handle);
	git_repository * repo = connectToLocalRepo (data);
	if (!repo)
	{
		ELEKTRA_SET_ERRORF (ELEKTRA_ERROR_GITRESOLVER_RESOLVING_ISSUE, parentKey, "Failed to open Repository %s\n", data->repo);
		git_libgit2_shutdown ();
		return -1;
	}

	genCheckoutFileName (data);

	// TODO: check for empty repo and initialize repo
	git_reference * headRef = getHeadRef (data, repo);
	if (!headRef)
	{
		ELEKTRA_SET_ERRORF (ELEKTRA_ERROR_GITRESOLVER_RESOLVING_ISSUE, parentKey, "Failed to get reference %s\n", data->refName);
		git_repository_free (repo);
		git_libgit2_shutdown ();
		return -1;
	}
	if (data->pull)
	{
		int rc = pullFromRemote (data, repo);
		if (rc)
		{
			ELEKTRA_SET_ERROR (ELEKTRA_ERROR_GITRESOLVER_CONFLICT, parentKey,
					   "Fast-forward pull failed, please pull manually\n");
			git_repository_free (repo);
			git_libgit2_shutdown ();
			return -1;
		}
	}
	const git_oid * headObj = git_reference_target (headRef);
	if (!headObj)
	{
		ELEKTRA_SET_ERRORF (ELEKTRA_ERROR_GITRESOLVER_RESOLVING_ISSUE, parentKey, "Failed to get reference %s\n", data->refName);
		git_reference_free (headRef);
		git_repository_free (repo);
		git_libgit2_shutdown ();
		return -1;
	}
	if (data->tracking == HEAD)
	{
		char * newCommit = hasNewCommit (data, headObj);
		if (data->headID && !newCommit)
		{
			// still newest commit, no need to update
			git_reference_free (headRef);
			git_repository_free (repo);
			git_libgit2_shutdown ();
			return 0;
		}
		else if (data->headID && newCommit)
		{
			elektraFree (data->headID);
			data->headID = newCommit;
		}
		else
		{
			data->headID = newCommit;
		}
		elektraPluginSetData (handle, data);
		data = elektraPluginGetData (handle);
	}
	git_reference_free (headRef);
	git_object * blob = getBlob (data, repo);
	if (!blob)
	{
		ELEKTRA_ADD_WARNINGF (83, parentKey, "File %s not found in repository %s\n", data->file, data->repo);
		git_repository_free (repo);
		git_libgit2_shutdown ();
		return 0;
	}
	if (data->tracking == OBJECT)
	{
		char * newObj = hasNewObjectCommit (data, blob);
		if (!newObj)
		{
			git_object_free (blob);
			git_repository_free (repo);
			git_libgit2_shutdown ();
			return 0;
		}
		else
		{
			if (data->objID)
			{
				elektraFree (data->objID);
				data->objID = newObj;
			}
			else
			{
				data->objID = newObj;
			}
		}
		elektraPluginSetData (handle, data);
		data = elektraPluginGetData (handle);
	}
	FILE * outFile;
	if (!data->checkout)
	{
		keySetString (parentKey, data->tmpFile);
	}
	else
	{
		keySetString (parentKey, data->repo);
		if (data->subdirs) makePath (data);
	}
	outFile = fopen (keyString (parentKey), "w+");
	if (!outFile)
	{
		ELEKTRA_SET_ERRORF (ELEKTRA_ERROR_COULD_NOT_OPEN, parentKey, "Failed to check out file %s to %s\n", data->file,
				    keyString (parentKey));
		git_object_free (blob);
		git_repository_free (repo);
		git_libgit2_shutdown ();
		return -1;
	}
	fwrite (git_blob_rawcontent ((git_blob *) blob), (size_t) git_blob_rawsize ((git_blob *) blob), 1, outFile);
	unsigned char * hash = hashBuffer (git_blob_rawcontent ((git_blob *) blob), git_blob_rawsize ((git_blob *) blob));
	if (!*(data->lastHash)) memcpy (data->lastHash, hash, MD5_DIGEST_LENGTH);
	elektraFree (hash);
	fclose (outFile);
	git_object_free (blob);
	git_repository_free (repo);
	git_libgit2_shutdown ();
	return 1; // success
}

static git_blob * addFileToIndex (git_repository * repo, GitData * data, git_index * index)
{
	git_blob * blob = NULL;
	git_oid blobID;
	memset (&blobID, 0, sizeof (git_oid));
	git_index_entry ie;
	memset (&ie, 0, sizeof (git_index_entry));
	ie.path = data->repo + elektraStrLen (data->workdir) - 1;
	ie.mode = GIT_FILEMODE_BLOB;
	git_blob_create_fromdisk (&blobID, repo, data->tmpFile);
	git_blob_lookup (&blob, repo, &blobID);
	git_index_add_frombuffer (index, &ie, git_blob_rawcontent (blob), git_blob_rawsize (blob));
	return blob;
}

static int moveFile (const char * source, const char * dest)
{
	FILE * inFile = NULL;
	FILE * outFile = NULL;
	struct stat buf;
	if (stat (source, &buf) == -1) return -1;
	size_t fileSize = buf.st_size;
	char * buffer = elektraMalloc (fileSize);
	inFile = fopen (source, "rb");
	size_t bytesRead = 0;
	while (bytesRead < fileSize)
	{
		size_t bytes = fread (buffer + bytesRead, 1, (size_t) fileSize, inFile);
		if (bytes == 0) break;
		bytesRead += bytes;
	}
	if (bytesRead < fileSize)
	{
		elektraFree (buffer);
		fclose (inFile);
		return -1;
	}
	fclose (inFile);
	outFile = fopen (dest, "wb+");

	size_t bytesWritten = 0;
	while (bytesWritten < fileSize)
	{
		size_t bytes = fwrite (buffer, 1, fileSize, outFile);
		if (bytes == 0) break;
		bytesWritten += bytes;
	}
	fclose (outFile);
	elektraFree (buffer);

	if (bytesWritten < fileSize)
	{
		return -1;
	}
	unlink (source);
	return 0;
}

int elektraGitresolverSet (Plugin * handle ELEKTRA_UNUSED, KeySet * returned ELEKTRA_UNUSED, Key * parentKey ELEKTRA_UNUSED)
{
	// get all keys
	// this function is optional
	GitData * data = elektraPluginGetData (handle);
	if (!data) return -1;
	keySetString (parentKey, data->tmpFile);
	git_repository * repo = connectToLocalRepo (data);
	if (!repo)
	{
		ELEKTRA_SET_ERRORF (ELEKTRA_ERROR_GITRESOLVER_RESOLVING_ISSUE, parentKey, "Failed to open Repository %s\n", data->repo);
		git_libgit2_shutdown ();
		return -1;
	}
	git_reference * headRef = getHeadRef (data, repo);
	if (!headRef)
	{
		ELEKTRA_SET_ERRORF (ELEKTRA_ERROR_GITRESOLVER_RESOLVING_ISSUE, parentKey, "Failed to get reference %s\n", data->refName);
		git_repository_free (repo);
		git_libgit2_shutdown ();
		return -1;
	}
	const git_oid * headObj = git_reference_target (headRef);
	if (!headObj)
	{
		ELEKTRA_SET_ERRORF (ELEKTRA_ERROR_GITRESOLVER_RESOLVING_ISSUE, parentKey, "Failed to get reference %s\n", data->refName);
		git_reference_free (headRef);
		git_repository_free (repo);
		git_libgit2_shutdown ();
		return -1;
	}

	if (data->tracking == HEAD)
	{
		char * newCommit = hasNewCommit (data, headObj);
		if (newCommit)
		{
			// newer commit in repo - abort
			ELEKTRA_SET_ERROR (ELEKTRA_ERROR_GITRESOLVER_CONFLICT, parentKey,
					   "The repository has been updated and is ahead of you");
			elektraFree (newCommit);
			git_reference_free (headRef);
			git_repository_free (repo);
			git_libgit2_shutdown ();
			return -1;
		}
		elektraFree (newCommit);
	}
	git_reference_free (headRef);
	if (data->tracking == OBJECT)
	{
		git_object * blob = getBlob (data, repo);
		if (blob)
		{
			char * newObj = hasNewObjectCommit (data, blob);
			if (newObj)
			{
				ELEKTRA_SET_ERROR (ELEKTRA_ERROR_GITRESOLVER_CONFLICT, parentKey,
						   "The repository has been updated and is ahead of you");
				elektraFree (newObj);
				git_object_free (blob);
				git_repository_free (repo);
				git_libgit2_shutdown ();
				return -1;
			}
			git_object_free (blob);
		}
	}
	if (!data->setPhase)
	{
		++(data->setPhase);
	}
	else if (data->setPhase == 1)
	{
		// get repo index
		git_index * index;
		git_repository_index (&index, repo);

		// add file
		git_blob * buffer = addFileToIndex (repo, data, index);
		unsigned char * hash = hashBuffer ((unsigned char *) git_blob_rawcontent (buffer), git_blob_rawsize (buffer));
		if (!strncmp ((char *) data->lastHash, (char *) hash, MD5_DIGEST_LENGTH))
		{
			elektraFree (hash);
			git_index_free (index);
			git_blob_free (buffer);
			git_repository_free (repo);
			git_libgit2_shutdown ();
			return 0;
		}
		elektraFree (hash);

		git_index_write (index);

		// get tree id
		git_oid treeID;
		git_index_write_tree (&treeID, index);

		// get parent commit
		git_oid parentID;
		git_commit * parent;
		git_reference_name_to_id (&parentID, repo, "HEAD");
		git_commit_lookup (&parent, repo, &parentID);

		// extract default git user
		git_signature * sig;
		int rc = git_signature_default (&sig, repo);
		if (rc == GIT_ENOTFOUND)
		{
			git_signature_now (&sig, "Elektra", "@libelektra.org");
		}

		// get git tree
		git_tree * tree;
		git_tree_lookup (&tree, repo, &treeID);

		// create default commit
		git_oid commitID;
		git_commit_create (&commitID, repo, "HEAD", sig, sig, NULL, "kdb git autocommit", tree, 1, (const git_commit **) &parent);

		git_signature_free (sig);
		git_tree_free (tree);
		git_index_free (index);
		git_blob_free (buffer);
		git_commit_free (parent);
		if (data->checkout)
		{
			moveFile (data->tmpFile, data->repo);
		}
	}
	elektraPluginSetData (handle, data);
	git_repository_free (repo);
	git_libgit2_shutdown ();
	return 1; // success
}

int elektraGitresolverError (Plugin * handle ELEKTRA_UNUSED, KeySet * returned ELEKTRA_UNUSED, Key * parentKey ELEKTRA_UNUSED)
{
	// set all keys
	// this function is optional

	return 1; // success
}

Plugin * ELEKTRA_PLUGIN_EXPORT (gitresolver)
{
	// clang-format off
    return elektraPluginExport ("gitresolver",
            ELEKTRA_PLUGIN_OPEN,	&elektraGitresolverOpen,
            ELEKTRA_PLUGIN_CLOSE,	&elektraGitresolverClose,
            ELEKTRA_PLUGIN_GET,	&elektraGitresolverGet,
            ELEKTRA_PLUGIN_SET,	&elektraGitresolverSet,
            ELEKTRA_PLUGIN_ERROR,	&elektraGitresolverError,
            ELEKTRA_PLUGIN_END);
}


text:
using System.Windows;
using System.Xml;

namespace Tailviewer.Settings
{
	public interface IMainWindowSettings
	{
		/// <summary>
		///     The height of the window.
		/// </summary>
		double Height { get; set; }

		/// <summary>
		///     The left coordinate of the window's position.
		/// </summary>
		double Left { get; set; }

		/// <summary>
		///     The state of the window (i.e. normal, minimized, maximized, etc...).
		/// </summary>
		WindowState State { get; set; }

		/// <summary>
		///     The top coordinate of the window's position.
		/// </summary>
		double Top { get; set; }

		/// <summary>
		///     The width of the window.
		/// </summary>
		double Width { get; set; }

		/// <summary>
		///     Whether or not the window is always on top of other windows.
		/// </summary>
		bool AlwaysOnTop { get; set; }

		string SelectedSidePanel { get; set; }

		/// <summary>
		///    When set to true, then the left-side panel is collapsed to
		///    reduce space requirements.
		/// </summary>
		bool IsLeftSidePanelVisible { get; set; }

		string SelectedMainPanel { get; set; }

		void Save(XmlWriter writer);
		void Restore(XmlReader reader);
		void UpdateFrom(Window window);
		void ClipToBounds(Desktop desktop);
		void RestoreTo(Window window);
	}
}

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Hosting;

namespace Alba
{
    public static class AlbaHostExtensions
    {

        /// <summary>
        /// Start an AlbaHost for a configured WebApplicationBuilder and WebApplication
        /// </summary>
        /// <param name="builder"></param>
        /// <param name="configureRoutes">Configure the WebApplication for routing and/or middleware</param>
        /// <param name="extensions"></param>
        /// <returns></returns>
        public static Task<IAlbaHost> StartAlbaAsync(this WebApplicationBuilder builder,
            Action<WebApplication> configureRoutes,
            params IAlbaExtension[] extensions)
        {
            return AlbaHost.For(builder, configureRoutes, extensions);
        }

        /// <summary>
        /// Start an AlbaHost for the supplied IHostBuilder
        /// </summary>
        /// <param name="builder"></param>
        /// <param name="extensions"></param>
        /// <returns></returns>
        public static Task<IAlbaHost> StartAlbaAsync(this IHostBuilder builder, params IAlbaExtension[] extensions)
        {
            return AlbaHost.For(builder, extensions);
        }

        public static IAlbaHost StartAlba(this IHostBuilder builder, params IAlbaExtension[] extensions)
        {
            return new AlbaHost(builder, extensions);
        }

        /// <summary>
        ///     Shortcut to issue a POST with a Json serialized request body and a Json serialized
        ///     response body
        /// </summary>
        /// <param name="system"></param>
        /// <param name="request"></param>
        /// <param name="url"></param>
        /// <param name="jsonStyle"></param>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static ResponseExpression PostJson<T>(this IAlbaHost system, T request, string url, JsonStyle? jsonStyle = null) where T : class
        {
            return new(system, s =>
            {
                s.WriteJson(request, jsonStyle);
                s.Post.Json(request, jsonStyle).ToUrl(url);
            });
        }

        /// <summary>
        ///     Shortcut to issue a PUT with a Json serialized request body and a Json serialized
        ///     response body
        /// </summary>
        /// <param name="system"></param>
        /// <param name="request"></param>
        /// <param name="url"></param>
        /// <param name="jsonStyle"></param>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static ResponseExpression PutJson<T>(this IAlbaHost system, T request, string url, JsonStyle? jsonStyle = null) where T : class
        {
            return new(system, s => { s.Put.Json(request, jsonStyle).ToUrl(url); });
        }

        /// <summary>
        ///     Shortcut to just retrieve the contents of an HTTP GET as JSON and deserialize the resulting
        ///     response to the type "T"
        /// </summary>
        /// <param name="system"></param>
        /// <param name="url"></param>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static async Task<T?> GetAsJson<T>(this IAlbaHost system, string url)
        {
            var response = await system.Scenario(x => x.Get.Url(url).Accepts("application/json;text/json"));
            return await response.ReadAsJsonAsync<T>();
        }

        /// <summary>
        /// Issue a GET to the supplied url and read the response text as a string
        /// </summary>
        /// <param name="host"></param>
        /// <param name="url"></param>
        /// <returns></returns>
        public static async Task<string> GetAsText(this IAlbaHost host, string url)
        {
            var response = await host.Scenario(x =>
            {
                x.Get.Url(url);
            });

            return await response.ReadAsTextAsync();
        }

        public class ResponseExpression
        {
            private readonly Action<Scenario> _configure;
            private readonly IAlbaHost _system;

            public ResponseExpression(IAlbaHost system, Action<Scenario> configure)
            {
                _system = system;
                _configure = configure;
            }

            public async Task<TResponse?> Receive<TResponse>()
            {
                var response = await _system.Scenario(_configure);
                return await response.ReadAsJsonAsync<TResponse>();
            }
        }
    }
}


text:
//
//  Copyright (c) 2016 Google Inc.
//
//  Licensed under the Apache License, Version 2.0 (the "License");
//  you may not use this file except in compliance with the License.
//  You may obtain a copy of the License at
//
//  http://www.apache.org/licenses/LICENSE-2.0
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
//

#import <FirebaseAuthUI/FUIAuth.h>

NS_ASSUME_NONNULL_BEGIN

/** @class FUIPhoneAuth
    @brief AuthUI components for Phone Sign In.
 */
@interface FUIPhoneAuth : NSObject <FUIAuthProvider>

/** @fn init
    @brief Please use @c initWithAuthUI: .
 */
- (instancetype)init NS_UNAVAILABLE;

/** @fn initWithAuthUI:
    @param authUI The @c FUIAuth instance that manages controllers of this provider.
 */
- (instancetype)initWithAuthUI:(FUIAuth *)authUI NS_DESIGNATED_INITIALIZER;

/** @fn signInWithPresentingViewController:
    @brief Signs in with phone auth provider. @see FUIAuthDelegate.authUI:didSignInWithUser:error:
        for method callback.
    @param presentingViewController The view controller used to present the UI.
 */
- (void)signInWithPresentingViewController:(UIViewController *)presentingViewController;

@end

NS_ASSUME_NONNULL_END


text:
layout: page_api
title: Perl Guide
action: Get Started
action_url: /get_started
permalink: /api/perl
tag: perl
---
<!--- Licensed to the Apache Software Foundation (ASF) under one -->
<!--- or more contributor license agreements.  See the NOTICE file -->
<!--- distributed with this work for additional information -->
<!--- regarding copyright ownership.  The ASF licenses this file -->
<!--- to you under the Apache License, Version 2.0 (the -->
<!--- "License"); you may not use this file except in compliance -->
<!--- with the License.  You may obtain a copy of the License at -->

<!---   http://www.apache.org/licenses/LICENSE-2.0 -->

<!--- Unless required by applicable law or agreed to in writing, -->
<!--- software distributed under the License is distributed on an -->
<!--- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -->
<!--- KIND, either express or implied.  See the License for the -->
<!--- specific language governing permissions and limitations -->
<!--- under the License. -->

# MXNet - Perl API

MXNet supports the Perl programming language. The MXNet Perl package brings flexible and efficient GPU
computing and state-of-art deep learning to Perl. It enables you to write seamless tensor/matrix computation with multiple GPUs in Perl.
It also lets you construct and customize the state-of-art deep learning models in Perl,
  and apply them to tasks, such as image classification and data science challenges.

One important thing to internalize is that Perl interface is written to be as close as possible to the Python's API,
so most if not all of Python's documentation and examples should just work in Perl after making few
changes in order to make the code a bit more Perlish. In nutshell just add $ sigils and replace . = \n with -> => ; and in 99% of cases
that's all that is needed there.
In addition please refer to [excellent metacpan doc interface](https://metacpan.org/release/AI-MXNet) and to very detailed
[MXNet Python API Documentation]({{'/api/python' | relative_url}}).

AI::MXNet supports new imperative PyTorch like Gluon MXNet interface. Please get acquainted with this new interface
at [Dive into Deep Learning](https://www.d2l.ai/).

For specific Perl Gluon usage please refer to Perl examples and tests directories on github, but be assured that the Python and Perl usage
are extremely close in order to make the use of the Python Gluon docs and examples as easy as possible.

AI::MXNet is seamlessly glued with [PDL](https://metacpan.org/release/PDL), the C++ level state can be easily initialized from PDL and the results can be
transferred to PDL objects in order to allow you to use all the glory and power of the PDL!

Here is how you can perform tensor or matrix computation in Perl with AI::MXNet and PDL:

```perl
pdl> use AI::MXNet qw(mx); # creates 'mx' module on the fly with the interface close to the Python's API

pdl> print $arr = mx->nd->ones([2, 3])
<AI::MXNet::NDArray 2x3 @cpu(0)>

pdl> print Data::Dumper::Dumper($arr->shape)
$VAR1 = [
          2,
          3
        ];

pdl> print (($arr*2)->aspdl) ## converts AI::MXNet::NDArray object to PDL object

[
 [2 2 2]
 [2 2 2]
]

pdl> print $arr = mx->nd->array([[1,2],[3,4]]) ## init the NDArray from Perl array ref given in PDL::pdl constructor format
<AI::MXNet::NDArray 2x2 @cpu(0)>
pdl> print $arr->aspdl

[
 [1 2]
 [3 4]
]

## init the NDArray from PDL but be aware that PDL methods expect the dimensions order in column major format
## AI::MXNet::NDArray is row major
pdl> print mx->nd->array(sequence(2,3))->aspdl ## 3 rows, 2 columns

[
 [0 1]
 [2 3]
 [4 5]
]
```

Export/import to/from sparse MXNet tensors are supported via [PDL::CCS](https://metacpan.org/release/PDL-CCS).
Please check out the examples directory for the examples on how to use the sparse matrices.


text:
from functools import wraps
def my_logging(original_function):
    import logging
    logging.basicConfig(filename='{}.log'.format(original_function.__name__),level=logging.INFO)

    @wraps(original_function)
    def wrapper_function(*args,**kwargs):
        logging.info('{} function ran with args: {} and kwargs: {}'.format(original_function.__name__,args,kwargs))
        return original_function(*args,**kwargs)
    return wrapper_function

@my_logging
def display_info(name,age):
    print('display_info function ran with {} and {} arguments'.format(name,age))

display_info('John',25)
print(display_info.__name__)


text:
module Nsque
  class Error < RuntimeError
  end

  class ChannelRequiredError < Error; end
  class ProducerCantBeNilError < Error; end
end


text:
from __future__ import unicode_literals

from django.db import migrations, models
import colorful.fields

class Migration(migrations.Migration):

    dependencies = [
        ('icekit_events', '0016_auto_20161208_0030'),
    ]

    operations = [
        migrations.AddField(
            model_name='eventtype',
            name='color',
            field=colorful.fields.RGBColorField(default=b'#cccccc'),
        ),
    ]


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Hypoderma ptarmicola Fairm.

### Remarks
null


text:
'use strict';

var chai   = require('chai');
var expect = chai.expect;

var AVFSError = require('lib/common/avfs-error');

describe('common/avfs-error', function () {

  it('should expose a constructor', function () {
    expect(AVFSError).to.be.a('function');
    expect(new AVFSError()).to.be.an.instanceOf(AVFSError);
  });

  it('should extends Error', function () {
    expect(new AVFSError()).to.be.an.instanceOf(Error);
  });

  it('should set code', function () {
    expect(new AVFSError('ENOENT')).to.have.property('code', 'ENOENT');
    expect(new AVFSError('EEXIST')).to.have.property('code', 'EEXIST');
  });

  it('should set additional data', function () {
    var error = new AVFSError('ENOENT', {
      a: 'a',
      b: 10,
      c: false
    });

    expect(error).to.have.property('a', 'a');
    expect(error).to.have.property('b', 10);
    expect(error).to.have.property('c', false);
  });

});


text:
from setuptools import setup

setup(
    name='knitter',
    version='1.0.0',

    author='Henry Wang',
    author_email='outsidematrix@126.com',
    maintainer='Henry Wang',
    maintainer_email='outsidematrix@126.com',

    url='https://github.com/hw712/knitter',

    description='A Web Automation Test Framework Based On Selenium WebDriver',
    long_description="Knitter['nitə] is a web automation test framework, with which you can develop "
                     "the web ui automation with good maintainability and extendability.",

    # https://pypi.org/classifiers/
    classifiers=['License :: OSI Approved :: GNU General Public License v3 (GPLv3)',
                 'Topic :: Software Development :: Testing',
                 'Topic :: Software Development :: Quality Assurance',
                 'Topic :: Software Development :: Libraries :: Application Frameworks'],

    platforms=['linux', 'windows'],

    license='BSD License',

    packages=['knitter'],

    install_requires=['selenium', 'xlrd'],
)


text:
import {encrypt, generateRandomBase64, IV_SIZE} from "../private/util";
import {ErrorCode, TypedError} from "./common";
import * as Args from "./args";

export enum Type {
    TestAssosiate = "test-associate",
    Associate = "associate",
    GetLogins = "get-logins",
    GetLoginsCount = "get-logins-count",
    SetLogin = "set-login",
}

export interface Request {
    Nonce: string;
    Verifier: string;
}

export class Base implements Request {
    public TriggerUnlock = false;
    public Nonce: string;
    public Verifier: string;
    protected encryptValue: (value: string) => string;

    constructor(key: string) {
        this.encryptValue = (value: string) => encrypt(key, this.Nonce, value);
        this.Nonce = generateRandomBase64(IV_SIZE);
        this.Verifier = this.encryptValue(this.Nonce);
    }
}

export class TestAssosiate extends Base {
    public RequestType = Type.TestAssosiate;
    public Id?: string;

    constructor(key: string, id?: string) {
        super(key);

        if (typeof id !== "undefined") {
            this.Id = id;
        }
    }
}

export class Associate extends Base {
    public RequestType = Type.Associate;
    public Key: string;

    constructor(key: string) {
        super(key);
        this.Key = key;
    }
}

export class RequiredId extends Base {
    public Id: string;

    constructor(key: string, id: string) {
        super(key);

        if (!id) {
            throw new TypedError(
                [
                    `The "id" field must be defined to request/save a password records. `,
                    `Call the "associate" method to get the "id" wired into the client instance. `,
                    `Request constructor name: ${this.constructor.name}.`,
                ].join(""),
                ErrorCode.IdUndefined,
            );
        }

        this.Id = id;
    }
}

export class Logins extends RequiredId {
    public SortSelection = false;
    public Url: string;

    constructor(key: string, id: string, args: Args.Minimum) {
        super(key, id);
        this.Url = this.encryptValue(args.url);
    }
}

export class GetLogins extends Logins {
    public RequestType = Type.GetLogins;
    public SubmitUrl?: string;
    public Realm?: string;

    constructor(key: string, id: string, args: Args.Base) {
        super(key, id, args);

        if (args.submitUrl) {
            this.SubmitUrl = this.encryptValue(args.submitUrl);

            if (args.realm) {
                this.Realm = this.encryptValue(args.realm);
            }
        }
    }
}

export class GetLoginsCount extends GetLogins {
    public RequestType = Type.GetLoginsCount;
}

export class ModifyLogin extends Logins {
    public RequestType = Type.SetLogin;
    public Login: string;
    public Password: string;

    constructor(key: string, id: string, args: Args.Modify) {
        super(key, id, args);

        this.Login = this.encryptValue(args.login);
        this.Password = this.encryptValue(args.password);
    }
}

export class CreateLogin extends ModifyLogin {
    public SubmitUrl?: string;
    public Realm?: string;

    constructor(key: string, id: string, args: Args.Create) {
        super(key, id, args);

        if (args.submitUrl) {
            this.SubmitUrl = this.encryptValue(args.submitUrl);
        }

        if (args.realm) {
            this.Realm = this.encryptValue(args.realm);
        }
    }
}

export class UpdateLogin extends ModifyLogin {
    public Uuid: string;

    constructor(key: string, id: string, args: Args.Update) {
        super(key, id, args);

        this.Uuid = this.encryptValue(args.uuid);
    }
}


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Journal of Plant Protection, Tokyo 18: 52 (1931)

#### Original name
Thyrospora lycopersici Enjoji, 1931

### Remarks
null


text:
[![Ubuntu](https://github.com/gunrock/gunrock/actions/workflows/ubuntu.yml/badge.svg)](https://github.com/gunrock/gunrock/actions/workflows/ubuntu.yml) [![Windows](https://github.com/gunrock/gunrock/actions/workflows/windows.yml/badge.svg)](https://github.com/gunrock/gunrock/actions/workflows/windows.yml) [![Code Quality](https://github.com/gunrock/gunrock/actions/workflows/codeql-analysis.yml/badge.svg)](https://github.com/gunrock/gunrock/actions/workflows/codeql-analysis.yml)

| [**Examples**](https://github.com/gunrock/gunrock/tree/main/examples/algorithms) | [**Project Template**](https://github.com/gunrock/template) | [**Documentation**](https://github.com/gunrock/gunrock/wiki) | [**GitHub Actions**](https://github.com/gunrock/gunrock/actions) |
|--------------|----------------------|-------------------|-------------------|

**Gunrock**[^1] is a CUDA library for graph-processing designed specifically for the GPU. It uses a **high-level**, **bulk-synchronous/asynchronous**, **data-centric abstraction** focused on operations on vertex or edge frontiers. Gunrock achieves a balance between performance and expressiveness by coupling high-performance GPU computing primitives and optimization strategies, particularly in the area of fine-grained load balancing, with a high-level programming model that allows programmers to quickly develop new graph primitives that scale from one to many GPUs on a node with small code size and minimal GPU programming knowledge.

## Quick Start Guide
Before building Gunrock make sure you have **CUDA Toolkit**[^2] installed on your system. Other external dependencies such as `NVIDIA/thrust`, `NVIDIA/cub`, etc. are automatically fetched using `cmake`.

```shell
git clone https://github.com/gunrock/gunrock.git
cd gunrock
mkdir build && cd build
cmake ..
make sssp # or for all algorithms, use: make -j$(nproc)
bin/sssp ../datasets/chesapeake/chesapeake.mtx
```

## Implementing Graph Algorithms
For a detailed explanation, please see the full [documentation](https://github.com/gunrock/gunrock/wiki/How-to-write-a-new-graph-algorithm). The following example shows simple APIs using Gunrock's data-centric, bulk-synchronous programming model, we implement Breadth-First Search on GPUs. This example skips the setup phase of creating a `problem_t` and `enactor_t` struct and jumps straight into the actual algorithm.

We first prepare our frontier with the initial source vertex to begin
push-based BFS traversal. A simple `f->push_back(source)` places
the initial vertex we will use for our first iteration.
```cpp
void prepare_frontier(frontier_t* f,
                      gcuda::multi_context_t& context) override {
  auto P = this->get_problem();
  f->push_back(P->param.single_source);
}
```
We then begin our iterative loop, which iterates until a convergence condition has been met. If no condition has been specified, the loop converges when the frontier is empty.
```cpp
void loop(gcuda::multi_context_t& context) override {
  auto E = this->get_enactor();   // Pointer to enactor interface.
  auto P = this->get_problem();   // Pointer to problem (data) interface.
  auto G = P->get_graph();        // Graph that we are processing.

  auto single_source = P->param.single_source;  // Initial source node.
  auto distances = P->result.distances;         // Distances array for BFS.
  auto visited = P->visited.data().get();       // Visited map.
  auto iteration = this->iteration;             // Iteration we are on.

  // Following lambda expression is applied on every source,
  // neighbor, edge, weight tuple during the traversal.
  // Our intent here is to find and update the minimum distance when found.
  // And return which neighbor goes in the output frontier after traversal.
  auto search = [=] __host__ __device__(
                      vertex_t const& source,    // ... source
                      vertex_t const& neighbor,  // neighbor
                      edge_t const& edge,        // edge
                      weight_t const& weight     // weight (tuple).
                      ) -> bool {
    auto old_distance =
      math::atomic::min(&distances[neighbor], iteration + 1);
    return (iteration + 1 < old_distance);
  };

  // Execute advance operator on the search lambda expression.
  // Uses load_balance_t::block_mapped algorithm (try others for perf. tuning.)
  operators::advance::execute<operators::load_balance_t::block_mapped>(
    G, E, search, context);
}
```
[include/gunrock/algorithms/bfs.hxx](include/gunrock/algorithms/bfs.hxx)

## How to Cite Gunrock & Essentials
Thank you for citing our work.

```bibtex
@article{Wang:2017:GGG,
  author =	 {Yangzihao Wang and Yuechao Pan and Andrew Davidson
                  and Yuduo Wu and Carl Yang and Leyuan Wang and
                  Muhammad Osama and Chenshan Yuan and Weitang Liu and
                  Andy T. Riffel and John D. Owens},
  title =	 {{G}unrock: {GPU} Graph Analytics},
  journal =	 {ACM Transactions on Parallel Computing},
  year =	 2017,
  volume =	 4,
  number =	 1,
  month =	 aug,
  pages =	 {3:1--3:49},
  doi =		 {10.1145/3108140},
  ee =		 {http://arxiv.org/abs/1701.01170},
  acmauthorize = {https://dl.acm.org/doi/10.1145/3108140?cid=81100458295},
  url =		 {http://escholarship.org/uc/item/9gj6r1dj},
  code =	 {https://github.com/gunrock/gunrock},
  ucdcite =	 {a115},
}
```

```bibtex
@InProceedings{Osama:2022:EOP,
  author =	 {Muhammad Osama and Serban D. Porumbescu and John D. Owens},
  title =	 {Essentials of Parallel Graph Analytics},
  booktitle =	 {Proceedings of the Workshop on Graphs,
                  Architectures, Programming, and Learning},
  year =	 2022,
  series =	 {GrAPL 2022},
  month =	 may,
  pages =	 {314--317},
  doi =		 {10.1109/IPDPSW55747.2022.00061},
  url =          {https://escholarship.org/uc/item/2p19z28q},
}
```

## Copyright & License

Gunrock is copyright The Regents of the University of California. The library, examples, and all source code are released under [Apache 2.0](https://github.com/gunrock/gunrock/blob/main/LICENSE).

[^1]: This repository has been moved from https://github.com/gunrock/essentials and the previous history is preserved with tags and under `master` branch. Read more about gunrock and essentials in our vision paper: [Essentials of Parallel Graph Analytics](https://escholarship.org/content/qt2p19z28q/qt2p19z28q_noSplash_38a658bccc817ba025517311a776840f.pdf).
[^2]: Recommended **CUDA v11.5.1 or higher** due to support for stream ordered memory allocators.


text:
caffe_root = '/home/haitham/sources/caffe-master/'  # this file is expected to be in {caffe_root}/examples
import sys

sys.path.insert(0, caffe_root + 'python')


text:
require "somatica/version"

module Somatica
  require 'somatica/railtie' if defined?(Rails)
end


text:
package de.contentreich.lambdalf.repo;

import java.util.List;
import clojure.java.api.Clojure;
import org.alfresco.repo.action.executer.ActionExecuterAbstractBase;
import org.alfresco.service.cmr.action.Action;
import org.alfresco.service.cmr.action.ParameterDefinition;
import org.alfresco.service.cmr.repository.NodeRef;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by deas on 1/16/15.
 * Can't reify abstract class, but delegation is not that bad
 * http://dev.clojure.org/jira/browse/CLJ-1255
 */
public class CljAction extends ActionExecuterAbstractBase {
    private static Logger logger = LoggerFactory.getLogger(CljAction.class);
    // By name because function can be redefined
    String ns = null;
    String fn = null;
    List<ParameterDefinition> paramDefs = null;

    public String getNs() {
        return ns;
    }

    public void setNs(String ns) {
        this.ns = ns;
    }

    public String getFn() {
        return fn;
    }

    public void setFn(String fn) {
        this.fn = fn;
    }

    public void setParamDefs(List<ParameterDefinition> paramDefs) {
        this.paramDefs = paramDefs;
    }

    @Override
    protected void executeImpl(Action action, NodeRef nodeRef) {
        logger.info("Executing action {}/{} against {}", ns, fn, nodeRef);
        Object sym = Clojure.var("clojure.core", "symbol").invoke(ns);
        Clojure.var("clojure.core", "require").invoke(sym);
        Clojure.var(ns, fn).invoke(action, nodeRef);

    }

    @Override
    protected void addParameterDefinitions(List<ParameterDefinition> list) {
        if (this.paramDefs != null) {
            list.addAll(this.paramDefs);
        }
    }

    // Abstract base registers, ActionServiceImpl does not have unregister functionality

}


text:
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('richtigTanken', '0001_initial'),
    ]

    operations = [
        migrations.CreateModel(
            name='UserPositions',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('zeit', models.DateTimeField(auto_now=True)),
                ('position_x', models.IntegerField()),
                ('position_y', models.IntegerField()),
            ],
            options={
            },
            bases=(models.Model,),
        ),
    ]


text:
"""Graph utilities."""

import logging
from io import open
from time import time
from itertools import izip
from collections import defaultdict, Iterable
import math
import random
import numpy as np
from scipy.io import loadmat
from scipy.sparse import issparse
import scipy.sparse as sparse

__author__ = "Bryan Perozzi"
__email__ = "bperozzi@acm.org"
__version__ = "0.0.1"

logger = logging.getLogger("magicgraph")

class DiGraph(defaultdict):
  """Efficient basic implementation of undirected graphs with self loops"""
  def __init__(self, node_class=list):
    super(DiGraph, self).__init__(node_class)

  def nodes(self):
    return self.keys()

  def adjacency_iter(self):
    return self.iteritems()

  def subgraph(self, nodes={}):
    subgraph = Graph()

    for n in nodes:
      if n in self:
        subgraph[n] = [x for x in self[n] if x in nodes]

    return subgraph

  def make_undirected(self):

    t0 = time()

    for v in self.keys():
      for other in self[v]:
        if v != other:
          self[other].append(v)

    t1 = time()
    logger.info('make_undirected: added missing edges {}s'.format(t1-t0))

    self.make_consistent()
    return self

  def make_consistent(self):
    t0 = time()
    for k in self.iterkeys():
      self[k] = list(sorted(set(self[k])))

    t1 = time()
    logger.info('make_consistent: made consistent in {}s'.format(t1-t0))

    self.remove_self_loops()

    return self

  def remove_self_loops(self):

    removed = 0
    t0 = time()

    for x in self:
      if x in self[x]:
        self[x].remove(x)
        removed += 1

    t1 = time()

    logger.info('remove_self_loops: removed {} loops in {}s'.format(removed, (t1-t0)))
    return self

  def check_self_loops(self):
    for x in self:
      for y in self[x]:
        if x == y:
          return True

    return False

  def has_edge(self, v1, v2):
    if v2 in self[v1] or v1 in self[v2]:
      return True
    return False

  def degree(self, nodes=None):
    if isinstance(nodes, Iterable):
      return {v: len(self[v]) for v in nodes}
    else:
      return len(self[nodes])

  def number_of_edges(self):
    """Returns the number of directed edges in the graph"""
    #return sum([self.degree(x) for x in self.iterkeys()]) / 2.0
    return sum([self.degree(x) for x in self.iterkeys()])

  def number_of_nodes(self):
    """Returns the number of nodes in the graph"""
    return self.order()

  def order(self):
    """Returns the number of nodes in the graph"""
    return len(self)

  def random_walk(self, path_length, alpha=0, rand=random.Random(), start=None):
    """ Returns a truncated random walk.

        path_length: Length of the random walk.
        alpha: probability of restarts.
        start: the start node of the random walk.
    """
    G = self
    if start:
      path = [start]
    else:
      # Sampling is uniform w.r.t V, and not w.r.t E
      path = [rand.choice(G.keys())]

    while len(path) < path_length:
      cur = path[-1]
      if len(G[cur]) > 0:
        if rand.random() >= alpha:
          path.append(rand.choice(G[cur]))
        else:
          path.append(path[0])
      else:
        break
    return path

class Graph(DiGraph):

  def number_of_edges(self):
    """Returns the number of undirected edges in the graph"""
    return super(Graph, self).number_of_edges() / 2.0

class WeightedNode(list):
  """A class which overrides a list to keep a companion list of weights."""
  def __init__(self, **kwargs):
    super(WeightedNode, self).__init__(kwargs)
    self.weights = []
    self.total_weight = None

  def weight(self, index):
    return self.weights[index]

  def append(self, to_append, weight=None):
    super(WeightedNode, self).append(to_append)

    if weight is not None:
      self.weights.append(weight)
    else:
      self.weights.append(1.0)

  def extend(self, iterable, weights=None):

    l_iterable = list(iterable)

    super(WeightedNode, self).extend(l_iterable)

    if weights is not None:
      assert len(l_iterable) == len(weights)
      self.weights.extend(weights)
    else:
      self.weights.extend([1.0 for x in l_iterable])

  def insert(self, index, p_object, weight=None):
    super(WeightedNode, self).insert(index, p_object)

    if weight is not None:
      self.weights.insert(index, weight)
    else:
      self.weights.insert(index, 1.0)

  def pop(self, index=None):
    ret = super(WeightedNode, self).pop(index)
    w = self.weights.pop(index)

    return ret,w

  def remove(self, value):
    idx = self.index(value)

    super(WeightedNode, self).pop(idx)
    self.weights.pop(idx)

  def reverse(self):
    super(WeightedNode, self).reverse()
    self.weights.reverse()

  def sort(self, cmp=None, key=None, reverse=False):

    if key is None:
      key = lambda z: z

    zipped = zip(self, self.weights)
    zipped_sorted = sorted(zipped, cmp=cmp, key=lambda y: key(y[0]), reverse=reverse)

    for idx, x in enumerate(zipped_sorted):
      nid, weight = x
      self[idx] = nid
      self.weights[idx] = weight

  def choice(self, rand):
    upper = self.total_weight
    if upper is None:
      upper = sum(self.weights)
      self.total_weight = upper

    stop = rand.uniform(0., upper)

    total = 0.
    for idx, x in enumerate(self.weights):
      total += x
      if total >= stop:
        #print idx, ':', total, self[idx]
        return self[idx]

    # floating point summations :/
    return self[-1]

class WeightedDiGraph(DiGraph):
  """A weighted directed graph"""
  def __init__(self):
    super(WeightedDiGraph, self).__init__(node_class=WeightedNode)

  def make_undirected(self):
    t0 = time()
    for v in self.keys():
      for edge_no, other in enumerate(self[v]):
        if v != other:
          self[other].append(v, weight=self[v].weight(edge_no))

    t1 = time()
    logger.info('make_undirected: added missing edges {}s'.format(t1-t0))

    self.make_consistent()
    return self

  def make_consistent(self):
    t0 = time()
    for k in self.iterkeys():
      unique_self, unique_indices = np.unique(self[k], return_index=True)
      unique_weights = [self[k].weights[i] for i in unique_indices]
      temp = WeightedNode()
      temp.extend(list(unique_self), list(unique_weights))
      self[k] = temp

    t1 = time()
    logger.info('make_consistent: made consistent in {}s'.format(t1-t0))

    self.remove_self_loops()

    return self

  def random_walk(self, path_length, alpha=0, rand=random.Random(), start=None):
    """ Returns a truncated random walk.

        path_length: Length of the random walk.
        alpha: probability of restarts.
        start: the start node of the random walk.
    """
    G = self
    if start:
      path = [start]
    else:
      # Sampling is uniform w.r.t V, and not w.r.t E
      path = [rand.choice(G.keys())]

    while len(path) < path_length:
      cur = path[-1]
      if len(G[cur]) > 0:
        if rand.random() >= alpha:
          path.append(G[cur].choice(rand))
        else:
          path.append(path[0])
      else:
        break
    return path

def save_edgelist(G, file_, sep=u'\t'):

  t0 = time()

  edges = 0

  with open(file_, 'w') as f:

    for src in G:
      for dst in G[src]:
        f.write(str(src))
        f.write(sep)
        f.write(str(dst))
        f.write(u'\n')
        edges += 1

  t1 = time()

  logger.info('Wrote {} edges from edge list in {}s'.format(edges,  t1-t0))

def save_weighted_edgelist(G, file_, sep=u'\t'):

  t0 = time()

  edges = 0

  with open(file_, 'w') as f:

    for src in G:
      for edge_no, dst in enumerate(G[src]):
        f.write(unicode(src))
        f.write(sep)
        f.write(unicode(dst))
        f.write(sep)
        f.write(unicode(G[src].weight(edge_no)))
        f.write(u'\n')
        edges += 1

  t1 = time()

  logger.info('Wrote {} edges from edge list in {}s'.format(edges,  t1-t0))

def load_edgelist(file_, undirected=False, leftIsSource=True):

  if undirected == False:
    G = DiGraph()
  else:
    G = Graph()

  t0 = time()

  edges = 0

  with open(file_) as f:
    for l in f:
      x, y = l.strip().split()[:2]
      x = int(x)
      y = int(y)

      if leftIsSource:
        G[x].append(y)
        edges += 1
        if undirected:
          G[y].append(x)
      else:
        G[y].append(x)
        edges += 1
        if undirected:
          G[x].append(y)

  t1 = time()

  logger.info('Parsed {} edges from edge list in {}s'.format(edges,  t1-t0))

  G.make_consistent()
  return G

def load_weighted_edgelist(file_, undirected=False):

  G = WeightedDiGraph()
  t0 = time()

  edges = 0

  with open(file_) as f:
    for l in f:
      x, y, w = l.strip().split()[:3]
      x = int(x)
      y = int(y)
      w = int(w)
      G[x].append(y, weight=w)
      edges += 1
      if undirected:
        G[y].append(x, weight=w)

  t1 = time()

  logger.info('Parsed {} edges from edge list in {}s'.format(edges,  t1-t0))

  return G

def load_multigraph_edgelist(file_, second_seperator=':', undirected=False):

  G = WeightedDiGraph()
  t0 = time()

  edges = 0

  with open(file_) as f:
    for l in f:
      x, y, w = l.strip().split()[:3]
      x = int(x)
      y = int(y)
      w = sum([float(a) for a in w.split(second_seperator)])
      G[x].append(y, weight=w)
      edges += 1
      if undirected:
        G[y].append(x, weight=w)

  t1 = time()

  logger.info('Parsed {} edges from edge list in {}s'.format(edges,  t1-t0))

  return G

def load_matfile(file_, variable_name="network", undirected=False, weighted=False):
    mat_variables = loadmat(file_)
    mat_matrix = mat_variables[variable_name]
    return from_numpy(mat_matrix, undirected, weighted)

def from_networkx(G_input, undirected=False):
    G = Graph()
    for idx, x in enumerate(G_input.nodes_iter()):
        for y in G_input[x].iterkeys():
            G[x].append(y)

    if undirected:
        G.make_undirected()

    return G

def from_numpy(x, undirected=False, weighted=False):
    if weighted:
        print "G is weighted"
        G = WeightedDiGraph()
    else:
        G = Graph()

    # TODO add handling for dense numpy too
    cx = x.tocoo()
    for i,j,v in izip(cx.row, cx.col, cx.data):
        if weighted:
           G[i].append(j, weight=v)
        else:
           G[i].append(j)

    if undirected:
        G.make_undirected()

    G.make_consistent()
    return G

def from_adjlist(adjlist):
    G = Graph()

    total_lines = 0
    total_edges = 0

    for row in adjlist:
        node = row[0]
        neighbors = row[1:]
        G[node] = list(sorted(set(neighbors)))
        total_lines += 1
        total_edges += len(neighbors)

    if total_edges == total_lines:
        logger.warn('WARN: May be parsing edge list as adjacency list (# lines == # edges)')

    return G

def to_adjacency_matrix(G, nodelist=None, dtype=None):
    """Inspired by the NetworkX equivalent."""

    if nodelist is None:
        nodelist = sorted(G.nodes())

    nodeset = set(nodelist)
    if len(nodelist) != len(nodeset):
        raise ValueError("Ambiguous ordering: `nodelist` contained duplicates.")

    nlen=len(nodelist)
    index=dict(zip(nodelist,range(nlen)))

    I = []
    J = []
    A_ij = []

    # TODO support weights
    for i,nbrs in G.adjacency_iter():
        for j in nbrs:
            try:
                I.append(index[i])
                J.append(index[j])
                A_ij.append(1)
            except KeyError:
                pass

    A = sparse.coo_matrix((A_ij, (I, J)), shape=(nlen, nlen), dtype=dtype).tocsr()

    return A

def to_laplacian(G, nodelist=None):
    A = to_adjacency_matrix(G, nodelist=nodelist)
    I = sparse.identity(A.shape[0])

    A_sum = sparse.csr_matrix(A.sum(axis=1))
    D = I.multiply(A_sum)
    L = D - A

    return L, D


text:
set -e

source $(dirname $0)/common.sh

verify-prereqs
build-image
run-build-command build/build-image/make-binaries.sh "integration"
run-build-command build/build-image/run-integration.sh


text:
describe FbGraph::Connections::AdConnectionObjects, '#ad_connection_objects' do
  context 'when included by FbGraph::AdAccount' do
    context 'when access_token is given' do
      it 'should return ad_connection_objects as FbGraph::AdConnectionObject' do
        mock_graph :get, 'act_11223344/connectionobjects', 'ad_accounts/ad_connection_objects/test_connection_objects', :access_token => 'access_token' do
          ad_connections = FbGraph::AdAccount.new("act_11223344", :access_token => 'access_token').connection_objects
          ad_connections.size.should == 3

          ad_connections.first.identifier.should == 354545238888
          ad_connections.first.name.should == "MyPage"
          ad_connections.first.url.should == "http://www.facebook.com/MyPage"
          ad_connections.first.type.should == 1
          ad_connections.first.picture.should == "http://profile.ak.fbcdn.net/hprofile-ak-snc4/41591_354545238178_3195000_s.jpg"
          ad_connections.first.tabs.keys.size.should == 5
          ad_connections.first.tabs["http://www.facebook.com/MyPage?sk=wall"].should == "Wall"
        end
      end
    end
  end
end


text:
namespace Labs.Infraestrutura.Migrations
{
    using System;
    using System.Data.Entity.Migrations;

    public partial class Inicial : DbMigration
    {
        public override void Up()
        {
            CreateTable(
                "dbo.Curso",
                c => new
                    {
                        ID = c.Int(nullable: false, identity: true),
                        Titulo = c.String(nullable: false, maxLength: 30),
                        ProfessorID = c.Int(),
                        DataCriacao = c.DateTime(nullable: false, precision: 7, storeType: "datetime2"),
                        DataModificacao = c.DateTime(nullable: false, precision: 7, storeType: "datetime2"),
                        DataExclusao = c.DateTime(precision: 7, storeType: "datetime2"),
                        RowVersion = c.Binary(nullable: false, fixedLength: true, timestamp: true, storeType: "rowversion"),
                    })
                .PrimaryKey(t => t.ID)
                .ForeignKey("dbo.Professor", t => t.ProfessorID)
                .Index(t => t.ProfessorID);

            CreateTable(
                "dbo.Matricula",
                c => new
                    {
                        CursoID = c.Int(nullable: false),
                        EstudanteID = c.Int(nullable: false),
                        DataCriacao = c.DateTime(nullable: false, precision: 7, storeType: "datetime2"),
                        DataModificacao = c.DateTime(nullable: false, precision: 7, storeType: "datetime2"),
                        DataExclusao = c.DateTime(precision: 7, storeType: "datetime2"),
                        RowVersion = c.Binary(nullable: false, fixedLength: true, timestamp: true, storeType: "rowversion"),
                    })
                .PrimaryKey(t => new { t.CursoID, t.EstudanteID })
                .ForeignKey("dbo.Curso", t => t.CursoID, cascadeDelete: true)
                .ForeignKey("dbo.Estudante", t => t.EstudanteID, cascadeDelete: true)
                .Index(t => t.CursoID)
                .Index(t => t.EstudanteID);

            CreateTable(
                "dbo.Estudante",
                c => new
                    {
                        ID = c.Int(nullable: false, identity: true),
                        Nome = c.String(nullable: false, maxLength: 30),
                        Idade = c.Short(nullable: false),
                        Sexo = c.Byte(),
                        DataCriacao = c.DateTime(nullable: false, precision: 7, storeType: "datetime2"),
                        DataModificacao = c.DateTime(nullable: false, precision: 7, storeType: "datetime2"),
                        DataExclusao = c.DateTime(precision: 7, storeType: "datetime2"),
                        RowVersion = c.Binary(nullable: false, fixedLength: true, timestamp: true, storeType: "rowversion"),
                    })
                .PrimaryKey(t => t.ID);

            CreateTable(
                "dbo.Nota",
                c => new
                    {
                        ID = c.Int(nullable: false, identity: true),
                        MatriculaID = c.Int(nullable: false),
                        Valor = c.Decimal(nullable: false, precision: 18, scale: 2),
                        DataCriacao = c.DateTime(nullable: false, precision: 7, storeType: "datetime2"),
                        DataModificacao = c.DateTime(nullable: false, precision: 7, storeType: "datetime2"),
                        DataExclusao = c.DateTime(precision: 7, storeType: "datetime2"),
                        RowVersion = c.Binary(nullable: false, fixedLength: true, timestamp: true, storeType: "rowversion"),
                        Matricula_CursoID = c.Int(),
                        Matricula_EstudanteID = c.Int(),
                    })
                .PrimaryKey(t => t.ID)
                .ForeignKey("dbo.Matricula", t => new { t.Matricula_CursoID, t.Matricula_EstudanteID })
                .Index(t => new { t.Matricula_CursoID, t.Matricula_EstudanteID });

            CreateTable(
                "dbo.Professor",
                c => new
                    {
                        ID = c.Int(nullable: false, identity: true),
                        Salario = c.Decimal(nullable: false, precision: 18, scale: 2),
                        Nome = c.String(nullable: false, maxLength: 30),
                        Idade = c.Short(nullable: false),
                        Sexo = c.Byte(),
                        DataCriacao = c.DateTime(nullable: false, precision: 7, storeType: "datetime2"),
                        DataModificacao = c.DateTime(nullable: false, precision: 7, storeType: "datetime2"),
                        DataExclusao = c.DateTime(precision: 7, storeType: "datetime2"),
                        RowVersion = c.Binary(nullable: false, fixedLength: true, timestamp: true, storeType: "rowversion"),
                    })
                .PrimaryKey(t => t.ID);

        }

        public override void Down()
        {
            DropForeignKey("dbo.Curso", "ProfessorID", "dbo.Professor");
            DropForeignKey("dbo.Nota", new[] { "Matricula_CursoID", "Matricula_EstudanteID" }, "dbo.Matricula");
            DropForeignKey("dbo.Matricula", "EstudanteID", "dbo.Estudante");
            DropForeignKey("dbo.Matricula", "CursoID", "dbo.Curso");
            DropIndex("dbo.Nota", new[] { "Matricula_CursoID", "Matricula_EstudanteID" });
            DropIndex("dbo.Matricula", new[] { "EstudanteID" });
            DropIndex("dbo.Matricula", new[] { "CursoID" });
            DropIndex("dbo.Curso", new[] { "ProfessorID" });
            DropTable("dbo.Professor");
            DropTable("dbo.Nota");
            DropTable("dbo.Estudante");
            DropTable("dbo.Matricula");
            DropTable("dbo.Curso");
        }
    }
}


text:
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use App\Models\Types\TowChargeType;

class Organisation extends Model
{
    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'organisations';

    /**
     * Indicates if the model should be timestamped.
     *
     * @var bool
     */
    public $timestamps = false;

    /**
     * Get the members for the organisation.
     */
    public function members()
    {
        return $this->hasMany('App\Models\Member', 'org');
    }

    public function users()
    {
        return $this->hasMany('App\Models\User', 'org');
    }

    public function membershipClasses()
    {
        return $this->hasMany('App\Models\MembershipClass', 'org');
    }

    public function vectors()
    {
        return $this->hasMany(Vector::class);
    }

    /**
     * If timezone is missing we default to UTC
     */
    public function getTimezoneAttribute($value)
    {
        $timezone = trim($value);
        if(empty($timezone)) {
            return 'UTC';
        }

        return $timezone;
    }

    public function getTowChargeType()
    {
        if($this->tow_height_charging) {
          return TowChargeType::heightBased();
        }

        if($this->tow_time_based) {
          return TowChargeType::timeBased();
        }

        return TowChargeType::notDefined();
    }
}


text:
ERROR: could not establish a connection to mongo db
Cannot connect to database default :
[Errno 61] Connection refused
**********************************************************************
Manual Pages
**********************************************************************

reservation
======================================================================

::

         ::

           Usage:
               reservation --rst
               reservation --version
               reservation find [all]
                                [--user=USER_ID]
                                [--label=ID]
                                [--cm_id=ID]
               reservation list [--cm_id=CM_ID]
                                [--user=USER_ID]
                                [--project=PROJECT_ID]
                                [--label=STRING]
                                [--start=TIME_START]
                                [--end=TIME_END]
                                [--host=HOST]
                                [--summary=SUMMARY]
               reservation duration [--cm_id=CM_ID]
               reservation delete [all]
                                  [--cm_id=CM_ID]
                                  [--user=USER_ID]
                                  [--project=PROJECT_ID]
                                  [--label=STRING]
                                  [--start=TIME_START]
                                  [--end=TIME_END]
                                  [--host=HOST]
               reservation update [--cm_id=CM_ID]
                                  [--user=USER_ID]
                                  [--project=PROJECT_ID]
                                  [--label=STRING]
                                  [--start=TIME_START]
                                  [--end=TIME_END]
                                  [--host=HOST]
                                  [--summary=SUMMARY]
                                  [--cm_id=CM_ID]
               reservation add --cm_id=CM_ID --user=USER_ID --project=PROJECT_ID --label=STRING --start=TIME_START --end=TIME_END --host=HOST --summary=SUMMARY
               reservation add --file=FILE

           Options:
               --rst                 print an rst manul page
               --version             print the version
               --label=STRING        label id reservation
               --cm_id=CM_ID         reservation cloudmesh id
               --user=USER_ID        user id
               --project=PROJECT_ID  project id
               --start=TIME_START    Start time of the reservation, in
                                     YYYY/MM/DD HH:MM:SS format. [default: 1901-01-01]
               --end=TIME_END        End time of the reservation, in
                                     YYYY/MM/DD HH:MM:SS format. In addition a duration
                                     can be specified if the + sign is the first sign.
                                     The duration will than be added to
                                     the start time. [default: 2100-12-31]
               --host=HOST           host number
               --summary=SUMMARY     summary of the reservation
               --file=FILE           Adding multiple reservations from one file

generate
======================================================================

::

       ::

           Usage:
               generate -h | --help | --rst
               generate clean
               generate SERVERS RESERVATIONS DURATION START
               generate list [--json|--table|--calendar]

           Arguments:
               SERVERS       Number of servers for which we generate
                             reservations

               RESERVATIONS  Number of reservations per server

               DURATION      The maximum duration of a reservation
                             (determined randomly)

               START         The start date. if now is specified, the current
                             time is used, otherwise an offset is used in the
                             form of 1m, or 1h, or 1w[default: now]

           Description:
               This program generates a number of reservations so they can be
               used to test the reservation package.

               generate clean
                   deletes all reservations from the reservation database

               generate SERVERS RESERVATIONS DURATION
                   generates a number of reservations where the servers are
                   specified as hostlist (e.g. i[001-003]. The reservations
                   specifies how many reservations there will be for each
                   server. The duration is a random number between [0,duration]
                   that specified not only a duration, but also the time delta
                   between two reservations on the same host.

               generate list
                   retiurns the list of reservations in the specified
                   format. Thoe format can be list, table, or calendar

           Bugs:
               Not implemented:

               * clean
               * list
               * the generation function does not yet have a start date

           See Also:
               * https://pypi.python.org/pypi/pytimeparse/1.1.0


text: <script type="text/javascript" src="/app/ui.js"></script>


text:
var child = require('child_process');
var http = require('http');
var test = require('tape');
var fs = require('fs');
var path = require('path');
var url = require('url');
var sculpt = require('sculpt');

var bin = require('../package.json').bin['amok'];

var browsers = [
  'chrome',
  'chromium',
];

browsers.forEach(function (browser) {
  test('print watch events with file url in ' + browser, function (test) {
    test.plan(5);

    var args = [
      bin,
      '--cwd',
      'test/fixture/watch-events',
      '--watch',
      '*.txt',
      '--browser',
      browser,
      url.resolve('file://', path.join('/' + __dirname, '/fixture/watch-events/index.html'))
    ];

    var ps = child.spawn('node', args);
    ps.stderr.pipe(process.stderr);
    ps.on('close', function () {
      test.pass('close');
    });

    var messages = [
      'ready',
      'add file.txt',
      'change file.txt',
      'unlink file.txt'
    ];

    ps.stdout.setEncoding('utf-8');
    ps.stdout.pipe(sculpt.split(/\r?\n/)).on('data', function (line) {
      if (line.length === 0) {
        return;
      }

      test.equal(line, messages.shift(), line);

      if (line === 'ready') {
        fs.writeFileSync('test/fixture/watch-events/file.txt', 'hello', 'utf-8');
      } else if (line === 'add file.txt') {
        fs.writeFileSync('test/fixture/watch-events/file.txt', 'hello world', 'utf-8');
      } else if (line === 'change file.txt') {
        fs.unlinkSync('test/fixture/watch-events/file.txt');
      }

      if (messages.length === 0) {
        ps.kill();
      }
    });
  });
});

browsers.forEach(function (browser) {
  test('print watch events with server in ' + browser, function (test) {
    test.plan(5);

    var args = [
      bin,
      '--watch',
      '**/*.txt',
      '--browser',
      browser,
      'test/fixture/watch-events/index.js',
    ];

    var ps = child.spawn('node', args);
    ps.stderr.pipe(process.stderr);
    ps.on('close', function () {
      test.pass('close');
    });

    var messages = [
      'ready',
      'add test/fixture/watch-events/file.txt',
      'change test/fixture/watch-events/file.txt',
      'unlink test/fixture/watch-events/file.txt'
    ];

    ps.stdout.setEncoding('utf-8');
    ps.stdout.pipe(sculpt.split(/\r?\n/)).on('data', function (line) {
      if (line.length === 0) {
        return;
      }

      test.equal(line, messages.shift(), line);

      if (line === 'ready') {
        fs.writeFileSync('test/fixture/watch-events/file.txt', 'hello', 'utf-8');
      } else if (line === 'add test/fixture/watch-events/file.txt') {
        fs.writeFileSync('test/fixture/watch-events/file.txt', 'hello world', 'utf-8');
      } else if (line === 'change test/fixture/watch-events/file.txt') {
        fs.unlinkSync('test/fixture/watch-events/file.txt');
      }

      if (messages.length === 0) {
        ps.kill();
      }
    });
  });
});


text:
import Util from 'util';
import Punycode from 'punycode';
import Random from 'random-js';
import UnicodeBlocks from '../data/unicode-8.0.0-blocks.json';

const DEFAULT_BLOCK = 'Basic Latin';

export default class RandomScript
{
  /**
   * @see https://github.com/ckknight/random-js/tree/v1.0.8#engines
   * @param {object} engine Engine of random-js: nativeMath, browserCrypto, mt19937()
   */
  constructor(engine = Random.engines.nativeMath)
  {
    this.blocks = UnicodeBlocks;
    this.engine = engine;
  }

  static create(engine)
  {
    return new RandomScript(engine);
  }

  /**
   * @see http://ftp.unicode.org/Public/8.0.0/ucd/Blocks.txt
   * @param {int} length
   * @param {string} name Block name
   */
  string(length = 1, name = DEFAULT_BLOCK)
  {
    length = parseInt(length, 10);
    if (1 > length || Number.isNaN(length)) {
      throw new RangeError('Argument length should be 1 or greater.');
    }
    const key = RandomScript.standardizeKey(name);
    if (!this.blocks.hasOwnProperty(key)) {
      throw new Error(Util.format(
        'Unknown name of Unicode block "%s". Choose from http://ftp.unicode.org/Public/8.0.0/ucd/Blocks.txt',
        name));
    }
    const range = this.blocks[key];
    const random = Random.integer(range[0], range[1]);
    const cue = [];
    for (let i = 0; i < length; ++i) {
      cue.push(random(this.engine));
    }
    return Punycode.ucs2.encode(cue);
  }

  static standardizeKey(key)
  {
    const normalized = key.replace(/[\s\-_]/g, '');
    return RandomScript.manualLowercase(normalized);
  }

  static manualLowercase(string)
  {
    return string.replace(/[A-Z]/g, function(ch) {
      return String.fromCharCode(ch.charCodeAt(0) | 32);
    });
  }
}


text:
<?php

namespace WidgetsNL\DoctrineEncryptionBundle\DependencyInjection;

use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;

/**
 * This is the class that validates and merges configuration from your app/config files.
 *
 * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/configuration.html}
 */
class Configuration implements ConfigurationInterface
{
    /**
     * {@inheritdoc}
     */
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder();
        $rootNode    = $treeBuilder->root('widgetsnl');

        $rootNode
            ->children()
            ->arrayNode('doctrine_encryptor')
            ->children()
            ->scalarNode('secret_key')
            ->end()
            ->scalarNode('algorithm')
            ->defaultValue('WidgetsNL\\DoctrineEncryptionBundle\\Algorithm\\Aes')
            ->end()
            ->end()
            ->end();

        return $treeBuilder;
    }
}


text:
(window.webpackJsonp=window.webpackJsonp||[]).push([[10],[]]);
//# sourceMappingURL=styles-755093da0c07f4b49226.js.map


text:
find . -name '*.qtreslot' | while read file; do
    dir=$(dirname "$file")
    name=$(basename "$file" .qtreslot)
    mv "$file" "$dir/$name"
done


text:
@interface XLButtonBarPagerTabStripViewController : XLPagerTabStripViewController{
    @protected
    XLButtonBarView* _buttonBarView;
}

@property (copy) void (^changeCurrentIndexProgressiveBlock)(XLButtonBarViewCell* oldCell, XLButtonBarViewCell *newCell, CGFloat progressPercentage, BOOL indexWasChanged, BOOL fromCellRowAtIndex);
@property (copy) void (^changeCurrentIndexBlock)(XLButtonBarViewCell* oldCell, XLButtonBarViewCell *newCell, BOOL animated);

@property (readonly, nonatomic) XLButtonBarView * buttonBarView;

@end


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  Copyright 2014 International Business Machines Corp.

  See the NOTICE file distributed with this work for additional information
  regarding copyright ownership. Licensed under the Apache License,
  Version 2.0 (the "License"); you may not use this file except in compliance
  with the License. You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
-->
<job id="partitionCtxPropagation" xmlns="http://xmlns.jcp.org/xml/ns/javaee" version="1.0">
	<properties>
		<property name="topLevelJobProperty" value="topLevelJobProperty.value" />
	</properties>
	<step id="step1">
		<properties>
			<property name="topLevelStepProperty" value="topLevelStepProperty.value" />
		</properties>
		<batchlet ref="test.junit.ParallelContextPropagationTest$PB"/>
		<partition>
			<plan partitions="3"/>
			<collector ref="test.junit.ParallelContextPropagationTest$C" />
			<analyzer ref="test.junit.ParallelContextPropagationTest$A" />
		</partition>
	</step>
</job>


text:
<?php

/**
 * Exception for the event that a connection configuration is malformed.
 */
class Db_Connection_MissingBindParameterException extends Db_Exception
{
	/**
	 * The name of the missing parameter.
	 *
	 * @var string
	 */
	protected $name;

	function __construct($config_name, $message)
	{
		parent::__construct('Missing Bind Parameter "'.$name.'"');

		$this->name = $name;
	}

	// ------------------------------------------------------------------------

	/**
	 * Returns the name of the parameter that is missing.
	 *
	 * @return string
	 */
	public function getParameterName()
	{
		return $this->name;
	}
}

/* End of file MissingBindParameterException.php */
/* Location: ./lib/Db/Connection */


text:
from django.shortcuts import render, redirect
from django.http import HttpResponse

from models import Stock, Portfolio
from helpers import get_portfolio_from_id, get_stock_from_symbol, yahoo_get_hist

import json
import time

def home(request):
    return render(request, 'stock_portfolio/home.html', {'portfolios': Portfolio.objects.all()})

@get_portfolio_from_id(fatal=True)
def portfolio(request, portfolio_id, portfolio):
    return render(request, 'stock_portfolio/portfolio.html', {'portfolio': portfolio})

@get_portfolio_from_id(fatal=True)
@get_stock_from_symbol()
def portfolio_add_stock(request, portfolio_id, portfolio, symbol, stock):
    if stock is None:
        stock = Stock(yahoo_symbol=symbol)
        stock.save()
    portfolio.stocks.add(stock)
    portfolio.save()
    return HttpResponse('')

@get_stock_from_symbol(fatal=True)
def stock(request, symbol, stock):
    hist = yahoo_get_hist(symbol)['query']['results']['quote']
    stock_data = [[int(time.mktime(time.strptime(d['Date'], '%Y-%m-%d')) * 1000),
                   float(d['Adj_Close'])] for d in hist]
    stock_data.sort(key=lambda x: x[0])
    import pprint ; pprint.pprint(hist)
    return render(request, 'stock_portfolio/stock.html', {'stock': stock,
                                                          'stock_data': json.dumps(stock_data)})


text:
<?php

namespace common\modules\lead\entities;

interface DialerConfigInterface {

	public function getDailyAttemptsLimit(): ?int;

	public function getGloballyAttemptsLimit(): ?int;

	public function getNextCallInterval(): int;
}


text:
using System;
using FooFramework;

namespace TemperatureAlarm
{
  public class Alarm : Component
  {
    enum AlarmState
    {
      Idle, TempNotOk, AlarmTriggered, TempOk
    }

    readonly InPort<TempData> tempPort;
    readonly OutPort<Notification> notificationPort;
    readonly OutPort<StatCollectorData> statData;

    float maxTemp;
    float minTemp;
    TimeSpan histeresis;

    DateTime tempOkTimeStamp;
    DateTime tempNokTimestamp;
    AlarmState state;
    bool wrongTemp;
    TempData currentData;

    public Alarm (string name = "Alarm", Component parent = null) : base(name,parent)
    {
      tempPort = new StdInPort<TempData>("TempPort", this, HandleTempData);
      notificationPort = new StdOutPort<Notification>("NotificationPort", this);
      statData = new StdOutPort<StatCollectorData>("StatData", this);
    }

    public override void Configure(ConfigurationProvider cp)
    {
      base.Configure(cp);
      maxTemp = cp.GetElement<float>(this, "MaxTemp");
      minTemp = cp.GetElement<float>(this, "MinTemp");
      histeresis = new TimeSpan(cp.GetElement<int>(this, "Histeresis/Hour"),
                                cp.GetElement<int>(this, "Histeresis/Minute"),
                                cp.GetElement<int>(this, "Histeresis/Second"));
    }

    public override void Initialize ()
    {
      base.Initialize();
      state = AlarmState.Idle;
    }

    public InPort<TempData> TempPort
    {
      get {return tempPort;}
    }

    public OutPort<Notification> NotificationPort
    {
      get {return notificationPort;}
    }

    public OutPort<StatCollectorData> StatData
    {
      get { return statData;}
    }

    void Alert()
    {
      AlarmNotification res = new AlarmNotification();
      res.Data = currentData;
      res.Type = AlarmNotificationType.NotOK;
      notificationPort.PutData(res);
    }
    void CancelAlert()
    {
      AlarmNotification res = new AlarmNotification();
      res.Data = currentData;
      res.Type = AlarmNotificationType.OK;
      notificationPort.PutData(res);
    }

    void PublishStatData(AlarmStatData.AlarmStatDataType type, TimeSpan span)
    {
      AlarmStatData res = new AlarmStatData();
      res.Span = span;
      res.Type = type;
      statData.PutData(res);
    }

    void HandleIdleState()
    {
      if (wrongTemp)
      {
         Log(string.Format("Temperature is not OK - {0}",currentData));
         tempNokTimestamp = currentData.Timestamp;
         state = AlarmState.TempNotOk;
      }
    }

    void HandleTempNotOkState()
    {
      TimeSpan span = currentData.Timestamp - tempNokTimestamp;
      if (wrongTemp && span >= histeresis)
      {
        Log(string.Format("Calling alarm - {0}", currentData),
          LogLevel.Medium);
        Alert();
        state = AlarmState.AlarmTriggered;
      }
      else if (!wrongTemp)
      {
        Log(string.Format("Temperature is back to normal - {0}", currentData));
        state = AlarmState.Idle;
        PublishStatData(AlarmStatData.AlarmStatDataType.TempNotOk, span);
      }
    }

    void HandleAlarmTriggeredState()
    {
      if (!wrongTemp)
      {
        Log(string.Format("Temperature is back to normal - {0}", currentData));
        state = AlarmState.TempOk;
        tempOkTimeStamp = currentData.Timestamp;
      }
    }

    void HandleTempOkState()
    {
      TimeSpan span = currentData.Timestamp - tempOkTimeStamp;
      if (!wrongTemp && span >= histeresis)
      {
        Log(string.Format("Cancelling alarm - {0}", currentData),
            LogLevel.Medium);
        CancelAlert();
        state = AlarmState.Idle;
        PublishStatData(AlarmStatData.AlarmStatDataType.AlarmOn, currentData.Timestamp-tempNokTimestamp);
      }
      else if (wrongTemp)
        state = AlarmState.AlarmTriggered;
    }

    bool CheckTemperature(TempData data)
    {
      foreach (float temp in data.Temperature)
        if (temp > maxTemp || temp < minTemp)
          return true;
      return false;
    }

    void HandleTempData(TempData data)
    {
      currentData = data;
      wrongTemp = CheckTemperature(data);
      switch (state)
      {
        case AlarmState.Idle:
          HandleIdleState();
          break;
        case AlarmState.TempNotOk:
          HandleTempNotOkState();
          break;
        case AlarmState.AlarmTriggered:
          HandleAlarmTriggeredState();
          break;
        case AlarmState.TempOk:
          HandleTempOkState();
          break;
      }
    }
  }
}


text:
package play.libs.concurrent;

import java.util.concurrent.Executor;
import javax.inject.Inject;
import javax.inject.Singleton;

/**
 * Execution context for managing the ClassLoader scope.
 *
 *
This is essentially a factory for getting an executor for the current ClassLoader. Tasks
 * executed by that executor will have the same ClassLoader in scope.
 *
 *
For example, it may be used in combination with CompletionStage.thenApplyAsync,
 * to ensure the callbacks executed when the completion stage is redeemed have the correct
 * ClassLoader:
 *
 *

 *     CompletionStage<WSResponse> response = ws.url(...).get();
 *     CompletionStage<Result> result = response.thenApplyAsync(response -> {
 *         return ok("Got response body " + ws.body() + " while executing request " + request().uri());
 *     }, httpExecutionContext.current());
 *

 *
 * Note, this is not a Scala execution context, and is not intended to be used where Scala execution
 * contexts are required.
 */
@Singleton
public class HttpExecutionContext {

  private final Executor delegate;

  @Inject
  public HttpExecutionContext(Executor delegate) {
    this.delegate = delegate;
  }

  /**
   * Get the current executor associated with the current ClassLoader.
   *
   *
Note that the returned executor is only valid for the current ClassLoader. It should be used
   * in a transient fashion, long lived references to it should not be kept.
   *
   * @return An executor that will execute its tasks with the current ClassLoader.
   */
  public Executor current() {
    return HttpExecution.fromThread(delegate);
  }
}


text:
{-# LANGUAGE OverloadedStrings #-}
module Coreutils ( unescape
                 , unrange
                 , split
                 , bsContents
                 , bsContents'
                 , bsUnlines
                 , bsUnlines'
                 , versionOption
                 ) where

import Data.Char (chr, isOctDigit, ord)
import Options.Applicative
import Numeric (readOct)
import qualified Data.Map.Strict as M
import qualified Data.ByteString.Lazy.Char8 as B
import qualified Data.ByteString.Char8 as B'
import Data.Version (showVersion, Version)

bsContents :: FilePath -> IO B.ByteString
bsContents "-" = B.getContents
bsContents f   = B.readFile f

bsContents' :: FilePath -> IO B'.ByteString
bsContents' "-" = B'.getContents
bsContents' f   = B'.readFile f

bsUnlines :: [B.ByteString] -> B.ByteString
bsUnlines = B.intercalate "\n"

bsUnlines' :: [B'.ByteString] -> B'.ByteString
bsUnlines' = B'.intercalate "\n"

split :: Eq a => a -> [a] -> [[a]]
split e s
    | null s    = []
    | s == [e]  = [[],[]]
    | otherwise = p : split e s' where
        (p,s') = case break (== e) s of
                      (x,[]) -> (x, [])
                      (x,xs) -> (x, tail xs)

escapeSequences :: M.Map String Char
escapeSequences = M.fromList [("\\\\", '\\'),("\\a", chr 7),("\\b", chr 8),("\\f", chr 12),("\\n", chr 10),("\\r", chr 13),("\\t", chr 9),("\\v", chr 11)]

versionOption :: String -> Version -> Parser (a -> a)
versionOption n v =
    infoOption (n ++ " (Mrak coreutils) " ++ showVersion v)
    ( long "version"
    <> help "output version information and exit"
    )

unrange :: String -> String
unrange [] = []
unrange s@[_] = s
unrange s@[_,_] = s
unrange (x:'\\':'-':cs) = x : '-' : unrange cs
unrange (x:'-':y:cs)
    | ord x >= ord y = x : '-' : y : unrange cs
    | otherwise = [chr c | c <- [(ord x)..(ord y)]] ++ unrange cs

unrange (h:t) = h : unrange t

unescape :: String -> String
unescape [] = []
unescape s@[_] = s
unescape ('\\':'-':zs) = '\\' : '-' : unescape zs
unescape ('\\':y:zs)
    | isOctDigit y = let os = (take 2 . takeWhile isOctDigit) zs
                         zs' = drop (length os) zs
                      in octToChar (y : os) : unescape zs'
    | otherwise = case M.lookup ['\\',y] escapeSequences of
                       Nothing -> unescape (y : zs)
                       Just c -> c : unescape zs

unescape s = head s : unescape (tail s)

octToChar :: String -> Char
octToChar = chr . fst . head . readOct


text:
extern crate recursive_reexports;

fn f() -> recursive_reexports::S {} //~ ERROR cannot find type `S` in module `recursive_reexports`

fn main() {}