text:
================================
Introduction to variant analysis
================================

CodeQL for Java

.. rst-class:: setup

Setup
=====

For this example you should download:

- `CodeQL for Visual Studio Code <https://codeql.github.com/docs/codeql-for-visual-studio-code/setting-up-codeql-in-visual-studio-code/>`__
- `Apache Struts database <https://downloads.lgtm.com/snapshots/java/apache/struts/apache-struts-7fd1622-CVE-2018-11776.zip>`__

.. note::

   For this example, we will be analyzing `Apache Struts <https://github.com/apache/struts>`__.

   You can also query the project in `the query console <https://lgtm.com/query/project:1878521151/lang:java/>`__ on LGTM.com.

   .. insert database-note.rst to explain differences between database available to download and the version available in the query console.

   .. include:: ../slide-snippets/database-note.rst

   .. resume slides

.. Include language-agnostic section here

.. include:: ../slide-snippets/intro-ql-general.rst

Oops
====

.. code-block:: java
  :emphasize-lines: 3

  int write(int[] buf, int size, int loc, int val) {
      if (loc >= size) {
         // return -1;
      }

      buf[loc] = val;

      return 0;
  }

- The return statement has been commented out (during debugging?)
- The ``if`` statement is now dead code
- No explicit bounds checking, will throw ``ArrayIndexOutOfbounds``

.. note::

   Here's a simple (artificial) bug, which we'll develop a query to catch.

   This function writes a value to a given location in an array, first trying to do a bounds check to validate that the location is within bounds. However, the return statement has been commented out, leaving a redundant if statement and no bounds checking.

   This case can act as our "patient zero" in the variant analysis game.

A simple CodeQL query
=====================

.. literalinclude:: ../query-examples/java/empty-if-java.ql
   :language: ql

.. note::

   We are going to write a simple query which finds "if statements" with empty "then" blocks, so we can highlight the results like those on the previous slide. The query can be run in the `query console on LGTM <https://lgtm.com/query>`__, or in your `IDE <https://lgtm.com/help/lgtm/running-queries-ide>`__.

   A `query <https://codeql.github.com/docs/ql-language-reference/queries/>`__ consists of a "select" clause that indicates what results should be returned. Typically it will also provide a "from" clause to declare some variables, and a "where" clause to state conditions over those variables. For more information on the structure of query files (including links to useful topics in the `QL language reference <https://codeql.github.com/docs/ql-language-reference/>`__), see `About CodeQL queries <https://codeql.github.com/docs/writing-codeql-queries/about-codeql-queries/>`__.

   In our example here, the first line of the query imports the `CodeQL library for Java <https://codeql.github.com/codeql-standard-libraries/java/>`__, which defines concepts like ``IfStmt`` and ``Block``.
   The query proper starts by declaring two variables–ifStmt and block. These variables represent sets of values in the database, according to the type of each of the variables. For example, ``ifStmt`` has the type ``IfStmt``, which means it represents the set of all if statements in the program.

   If we simply selected these two variables::

     from IfStmt ifStmt, Block block
     select ifStmt, block

   We would get a result row for every combination of blocks and if statements in the program. This is known as a cross-product, because there is no logical condition linking the two variables. We can use the where clause to specify the condition that we are only interested in rows where the "block" is the "then" part of the if statement. We do this by specifying::

     block = ifStmt.getThen()

   This states that the block is equal to (not assigned!) the "then" part of the ``ifStmt``. ``getThen()`` is an operation which is available on any IfStmt. One way to interpret this is as a filtering operation – starting with every pair of block and if statements, check each one to whether the logical condition holds, and only keep the row if that is the case.
   We can add a second condition that specifies the block must be empty::

     and block.isEmpty()

   The ``isEmpty()`` operation is available on any Block, and is only true if the "block" has no children.

   Finally, we select a location, at which to report the problem, and a message, to explain what the problem is.

Structure of a query
=====================

A **query file** has the extension ``.ql`` and contains a **query clause**, and optionally **predicates**, **classes**, and **modules**.

A **query library** has the extension ``.qll`` and does not contain a query clause, but may contain modules, classes, and predicates.

Each query library also implicitly defines a module.

**Import** statements allow the classes and predicates defined in one module to be used in another.

.. note::

  Queries are always contained in query files with the file extension ``.ql``.

  Parts of queries can be lifted into `library files <https://codeql.github.com/docs/ql-language-reference/modules/#library-modules>`__ with the extension ``.qll``. Definitions within such libraries can be brought into scope using "import" statements, and similarly QLL files can import each other's definitions using "import" statements.

  Logic can be encapsulated as user-defined `predicates <https://codeql.github.com/docs/ql-language-reference/predicates/>`__ and `classes <https://codeql.github.com/docs/ql-language-reference/types/#classes>`__, and organized into `modules <https://codeql.github.com/docs/ql-language-reference/modules/>`__. Each QLL file implicitly defines a module, but QL and QLL files can also contain explicit module definitions, as we will see later.

Predicates
==========

A predicate allows you to pull out and name parts of a query.

.. container:: column-left

   .. literalinclude:: ../query-examples/java/empty-if-java.ql
      :language: ql
      :emphasize-lines: 6

.. container:: column-right

   .. literalinclude:: ../query-examples/java/empty-if-java-predicate.ql
      :language: ql
      :emphasize-lines: 3-5

.. note::

   A `predicate <https://codeql.github.com/docs/ql-language-reference/predicates/>`__ takes zero or more parameters, and its body is a condition on those parameters. The predicate may (or may not) hold. Predicates may also be `recursive <https://codeql.github.com/docs/ql-language-reference/predicates/#recursive-predicates>`__, simply by referring to themselves (directly or indirectly).

   You can imagine a predicate to be a self-contained from-where-select statement, that produces an intermediate relation, or table. In this case, the ``isEmpty`` predicate will be the set of all blocks which are empty.

Classes in QL
=============

A QL class allows you to name a set of values and define (member) predicates on them.

A class has at least one supertype and optionally a **characteristic predicate**; it contains the values that belong to *all* supertypes *and* satisfy the characteristic predicate, if provided.

Member predicates are inherited and can be overridden.

.. code-block:: ql

   class EmptyBlock extends Block {
     EmptyBlock() {
       this.getNumStmt() = 0
     }
   }

.. note::

  `Classes <https://codeql.github.com/docs/ql-language-reference/types/#classes>`__ model sets of values from the database. A class has one or more supertypes, and inherits `member predicates <https://codeql.github.com/docs/ql-language-reference/types/#member-predicates>`__ (methods) from each of them. Each value in a class must be in every supertype, but additional conditions can be stated in a so-called **characteristic predicate**, which looks a bit like a zero-argument constructor.

  In the example, declaring a variable "EmptyBlock e" will allow it to range over only those blocks that have zero statements.

Classes in QL continued
=======================

.. container:: column-left

   .. literalinclude:: ../query-examples/java/empty-if-java-predicate.ql
      :language: ql
      :emphasize-lines: 3-5

.. container:: column-right

   .. literalinclude:: ../query-examples/java/empty-if-java-class.ql
      :language: ql
      :emphasize-lines: 3-7

.. note::

   As shown in this example, classes behave much like unary predicates, but with ``instanceof`` instead of predicate calls to check membership. Later on, we will see how to define member predicates on classes.

Iterative query refinement
==========================

- **Common workflow**: Start with a simple query, inspect a few results, refine, repeat.

- For example, empty ``then`` branches are not a problem if there is an ``else``.

- **Exercise**: How can we refine the query to take this into account?

**Hints**:

- Use member predicate ``IfStmt.getElse()``
- Use ``not exists(...)``

.. note::

   CodeQL makes it very easy to experiment with analysis ideas. A common workflow is to start with a simple query (like our "redundant if-statement" example), examine a few results, refine the query based on any patterns that emerge and repeat.

   As an exercise, refine the redundant-if query based on the observation that if the if-statement has an "else" clause, then even if the body of the "then" clause is empty, it's not actually redundant.

Model answer: redundant if-statement
====================================

.. literalinclude:: ../query-examples/java/empty-if-java-model.ql

.. note::

  You can explore the results generated when this query is run on apache/struts in LGTM `here <https://lgtm.com/query/1269550358355690774/>`__.


text:
from openerp.osv import fields, osv

CODE_EXEC_DEFAULT = '''\
res = []
cr.execute("select id, code from account_journal")
for record in cr.dictfetchall():
    res.append(record['code'])
result = res
'''

class accounting_assert_test(osv.osv):
    _name = "accounting.assert.test"
    _order = "sequence"

    _columns = {
        'name': fields.char('Test Name', required=True, select=True, translate=True),
        'desc': fields.text('Test Description', select=True, translate=True),
        'code_exec': fields.text('Python code', required=True),
        'active': fields.boolean('Active'),
        'sequence': fields.integer('Sequence'),
    }

    _defaults = {
        'code_exec': CODE_EXEC_DEFAULT,
        'active': True,
        'sequence': 10,
    }

redpajama_set_name: RedPajamaGithub


text:
#region

using System.Collections.Generic;
using System.Linq.Expressions;

#endregion

namespace Highway.Data.Rest.Expressions
{
    public class ParameterRebinder : ExpressionVisitor
    {
        private readonly Dictionary<ParameterExpression, ParameterExpression> map;

        public ParameterRebinder(Dictionary<ParameterExpression, ParameterExpression> map)
        {
            this.map = map ?? new Dictionary<ParameterExpression, ParameterExpression>();
        }

        public static Expression ReplaceParameters(Dictionary<ParameterExpression, ParameterExpression> map,
            Expression exp)
        {
            return new ParameterRebinder(map).Visit(exp);
        }

        protected override Expression VisitParameter(ParameterExpression p)
        {
            ParameterExpression replacement;

            if (map.TryGetValue(p, out replacement))
            {
                p = replacement;
            }

            return base.VisitParameter(p);
        }
    }
}


text:
package com.mixer.api.resource.user.validation;

// TODO
public abstract class UsernameValidationError extends UserValidationException {
}


text:
Configuración de Logcheck

Logcheck es un programa que monitoriza automáticamente los ficheros de
historial de su sistema de manera regular y le remite un correo con las
violaciones de la política de seguridad. Busca mensajes generados por
diversos programas (incluyendo Portsentry y Hostsentry) que indiquen
intentos de intrusión, y genera un informe que envía por correo electrónico
a la dirección elegida.

Las opciones de esta página son :

Enviar los informes a

    La dirección de correo electrónico a la que remitir los informes con
    las violaciones de seguridad.

Mensajes de los historiales que indican intentos de intrusión

    Una lista de los mensajes que, de encontrarlos en alguno de los
    historiales del sistema, indicarían un intento de intrusión.

Mensajes de los historiales que indican violaciones de seguridad

    Una lista de mensajes que indican una potencial violación de la
    política de seguridad. Cualquier mensaje en esta lista que también esté
    en la siguiente lista 'Excepto para' será ignorado.

Mensajes de los historiales que ignorar

    Cualquier mensaje en los historiales que esté listado en este campo
    siempre será ignorado, incluso si coincide con una de las cadenas de
    intentos de intrusión o violaciones de la política de seguridad.

Al final de esta página hay un formulario para elegir exactamente cuándo
debería ejecutar Logcheck. Sin embargo, si su instalación de Logcheck usa
un guión de 'cron' que fuerza a su ejecución horaria o diaria, este
formulario no se mostrará.


text:
Video Camera
=======

An example of launching an external applcation in WebWorks for Tablet OS. Specifically, the Video Camera.

License:
This code is released under an Apache Open Source license. It can always be downloaded for free from https://www.github.com/SCrid2000

Testing:
To test, download the source code and compile it. The application is available for the BlackBerry PlayBook in BlackBerry World.

Privacy:
As you can see if you check the source code, this app doesn't save or transmit any personal information; if by any strange chance I get any of your information (excluding, of course, your email address if you contact me with a question) I'll delete it, as I have no use for it. I don't want your personal information, I'm not Google.


text:
import-module au

function global:au_SearchReplace {
    @{
        'tools\chocolateyInstall.ps1' = @{
            "(^[$]fullUrl\s*=\s*)('.*')"         = "`$1'$($Latest.FullUrl)'"
            "(^[$]fullChecksum\s*=\s*)('.*')"    = "`$1'$($Latest.FullChecksum)'"
            "(^[$]release\s*=\s*)('.*')"         = "`$1'$($Latest.Release)'"
        }
     }
}

function Get-Download($url, $version)
{
    # two levels of redirection
    $request = Invoke-WebRequest -Method Head -Uri $url -MaximumRedirection 0 -SkipHttpErrorCheck -ErrorAction Ignore

    $request = Invoke-WebRequest -Method Head -Uri $request.Headers.Location[0] -SkipHttpErrorCheck -ErrorAction Ignore -MaximumRedirection 0
    $r = @{}

    if($request.StatusCode -lt 400)
    {
        # $url        = 'http://download.microsoft.com/download/E/E/1/EE12CC0F-A1A5-4B55-9425-2AFBB2D63979/SSMS-Full-Setup.exe'

        $location = [UriBuilder] $request.Headers.Location[0]

        # Switch to https
        $location.Scheme = "https"
        $location.Port = 443

        $url = $location.Uri
        Write-Host "Downloading $url"

        $filename = [IO.Path]::GetFileName($url)
        $destPath = "$($env:TEMP)\chocolatey\sql-server-management-studio\$version"

        if (-not (Test-Path $destPath)) {
            New-Item -ItemType Directory $destPath | Out-Null
        }

        $filename = [IO.Path]::Combine($destPath, $filename)

        if (Test-Path $filename) {
            Write-Warning "$filename already exists, skipping download"
        } else {

            $currentProgressPreference = $ProgressPreference
            $ProgressPreference = 'silentlyContinue'
            Invoke-WebRequest -Uri $url -OutFile $filename
            $ProgressPreference = $currentProgressPreference
        }

        $hash = Get-FileHash $filename -Algorithm SHA256
        $r = @{
            url = $url
            checksum = $hash.Hash
        }
    }
    return $r
}

function global:au_GetLatest {

    $Latest = @{}

    try {
        # Get latest version from XML
        $response = Invoke-RestMethod -Uri "https://go.microsoft.com/fwlink/?linkid=2021100"
        $version = $response.component.version

        $response = Invoke-WebRequest -Uri "https://raw.githubusercontent.com/MicrosoftDocs/sql-docs/live/docs/ssms/download-sql-server-management-studio-ssms.md"
        $content = $response.Content

        # The version number for this latest preview is: 13.0.12000.65
        $isMatch = $content -match "([Rr]elease number: (?<release>\d+\.\d+(\.\d+){0,2}))"

        if ($isMatch)
        {
            $release = $matches.release

            Write-Host "Found version $version, release $release"

            $first = Get-Download "https://aka.ms/ssmsfullsetup" $version

            if($first.Count)
            {
                $Latest = @{
                    Version = $version
                    Release = $release
                    FullChecksum = $first.checksum
                    FullUrl = $first.url
                }
                return $Latest

            } else {
                Write-Warning "first.Count and/or second.Count were zero"
            }

        } else {
            Write-Warning "Regex match was false"
        }
    }
    catch {
        Write-Error $_
    }

    return 'ignore'
}

function global:au_AfterUpdate
{
    # Include version in title
    $nuspecFileName = $Latest.PackageName + ".nuspec"
    $nu = Get-Content $nuspecFileName -Raw -Encoding UTF8

    $nu = $nu -replace "(?smi)(\<title\>).*?(\</title\>)", "`${1}SQL Server Management Studio $($Latest.Release)`$2"

    $Utf8NoBomEncoding = New-Object System.Text.UTF8Encoding($False)
    $NuPath = (Resolve-Path $NuspecFileName)
    [System.IO.File]::WriteAllText($NuPath, $nu, $Utf8NoBomEncoding)
}

update -ChecksumFor none


text:
#include "pack-objects.h"

#include "compress.h"
#include "delta.h"
#include "iterator.h"
#include "netops.h"
#include "pack.h"
#include "thread-utils.h"
#include "tree.h"

#include "git2/pack.h"
#include "git2/commit.h"
#include "git2/tag.h"
#include "git2/indexer.h"
#include "git2/config.h"

GIT__USE_OIDMAP;

struct unpacked {
	git_pobject *object;
	void *data;
	struct git_delta_index *index;
	unsigned int depth;
};

struct tree_walk_context {
	git_packbuilder *pb;
	git_buf buf;
};

#ifdef GIT_THREADS

#define GIT_PACKBUILDER__MUTEX_OP(pb, mtx, op) do { \
		int result = git_mutex_##op(&(pb)->mtx); \
		assert(!result); \
		GIT_UNUSED(result); \
	} while (0)

#else

#define GIT_PACKBUILDER__MUTEX_OP(pb,mtx,op) GIT_UNUSED(pb)

#endif /* GIT_THREADS */

#define git_packbuilder__cache_lock(pb) GIT_PACKBUILDER__MUTEX_OP(pb, cache_mutex, lock)
#define git_packbuilder__cache_unlock(pb) GIT_PACKBUILDER__MUTEX_OP(pb, cache_mutex, unlock)
#define git_packbuilder__progress_lock(pb) GIT_PACKBUILDER__MUTEX_OP(pb, progress_mutex, lock)
#define git_packbuilder__progress_unlock(pb) GIT_PACKBUILDER__MUTEX_OP(pb, progress_mutex, unlock)

static unsigned name_hash(const char *name)
{
	unsigned c, hash = 0;

	if (!name)
		return 0;

	/*
	 * This effectively just creates a sortable number from the
	 * last sixteen non-whitespace characters. Last characters
	 * count "most", so things that end in ".c" sort together.
	 */
	while ((c = *name++) != 0) {
		if (git__isspace(c))
			continue;
		hash = (hash >> 2) + (c << 24);
	}
	return hash;
}

static int packbuilder_config(git_packbuilder *pb)
{
	git_config *config;
	int ret;
	int64_t val;

	if (git_repository_config__weakptr(&config, pb->repo) < 0)
		return -1;

#define config_get(KEY,DST,DFLT) do { \
	ret = git_config_get_int64(&val, config, KEY); \
	if (!ret) (DST) = val; \
	else if (ret == GIT_ENOTFOUND) (DST) = (DFLT); \
	else if (ret < 0) return -1; } while (0)

	config_get("pack.deltaCacheSize", pb->max_delta_cache_size,
		   GIT_PACK_DELTA_CACHE_SIZE);
	config_get("pack.deltaCacheLimit", pb->cache_max_small_delta_size,
		   GIT_PACK_DELTA_CACHE_LIMIT);
	config_get("pack.deltaCacheSize", pb->big_file_threshold,
		   GIT_PACK_BIG_FILE_THRESHOLD);
	config_get("pack.windowMemory", pb->window_memory_limit, 0);

#undef config_get

	return 0;
}

int git_packbuilder_new(git_packbuilder **out, git_repository *repo)
{
	git_packbuilder *pb;

	*out = NULL;

	pb = git__calloc(1, sizeof(*pb));
	GITERR_CHECK_ALLOC(pb);

	pb->object_ix = git_oidmap_alloc();

	if (!pb->object_ix)
		goto on_error;

	pb->repo = repo;
	pb->nr_threads = 1; /* do not spawn any thread by default */

	if (git_hash_ctx_init(&pb->ctx) < 0 ||
		git_repository_odb(&pb->odb, repo) < 0 ||
		packbuilder_config(pb) < 0)
		goto on_error;

#ifdef GIT_THREADS

	if (git_mutex_init(&pb->cache_mutex) ||
		git_mutex_init(&pb->progress_mutex) ||
		git_cond_init(&pb->progress_cond))
		goto on_error;

#endif

	*out = pb;
	return 0;

on_error:
	git_packbuilder_free(pb);
	return -1;
}

unsigned int git_packbuilder_set_threads(git_packbuilder *pb, unsigned int n)
{
	assert(pb);

#ifdef GIT_THREADS
	pb->nr_threads = n;
#else
	GIT_UNUSED(n);
	assert(1 == pb->nr_threads);
#endif

	return pb->nr_threads;
}

static void rehash(git_packbuilder *pb)
{
	git_pobject *po;
	khiter_t pos;
	unsigned int i;
	int ret;

	kh_clear(oid, pb->object_ix);
	for (i = 0, po = pb->object_list; i < pb->nr_objects; i++, po++) {
		pos = kh_put(oid, pb->object_ix, &po->id, &ret);
		kh_value(pb->object_ix, pos) = po;
	}
}

int git_packbuilder_insert(git_packbuilder *pb, const git_oid *oid,
			   const char *name)
{
	git_pobject *po;
	khiter_t pos;
	int ret;

	assert(pb && oid);

	/* If the object already exists in the hash table, then we don't
	 * have any work to do */
	pos = kh_get(oid, pb->object_ix, oid);
	if (pos != kh_end(pb->object_ix))
		return 0;

	if (pb->nr_objects >= pb->nr_alloc) {
		pb->nr_alloc = (pb->nr_alloc + 1024) * 3 / 2;
		pb->object_list = git__realloc(pb->object_list,
					       pb->nr_alloc * sizeof(*po));
		GITERR_CHECK_ALLOC(pb->object_list);
		rehash(pb);
	}

	po = pb->object_list + pb->nr_objects;
	memset(po, 0x0, sizeof(*po));

	if (git_odb_read_header(&po->size, &po->type, pb->odb, oid) < 0)
		return -1;

	pb->nr_objects++;
	git_oid_cpy(&po->id, oid);
	po->hash = name_hash(name);

	pos = kh_put(oid, pb->object_ix, &po->id, &ret);
	assert(ret != 0);
	kh_value(pb->object_ix, pos) = po;

	pb->done = false;
	return 0;
}

/*
 * The per-object header is a pretty dense thing, which is
 *  - first byte: low four bits are "size",
 *    then three bits of "type",
 *    with the high bit being "size continues".
 *  - each byte afterwards: low seven bits are size continuation,
 *    with the high bit being "size continues"
 */
static int gen_pack_object_header(
		unsigned char *hdr,
		unsigned long size,
		git_otype type)
{
	unsigned char *hdr_base;
	unsigned char c;

	assert(type >= GIT_OBJ_COMMIT && type <= GIT_OBJ_REF_DELTA);

	/* TODO: add support for chunked objects; see git.git 6c0d19b1 */

	c = (unsigned char)((type << 4) | (size & 15));
	size >>= 4;
	hdr_base = hdr;

	while (size) {
		*hdr++ = c | 0x80;
		c = size & 0x7f;
		size >>= 7;
	}
	*hdr++ = c;

	return (int)(hdr - hdr_base);
}

static int get_delta(void **out, git_odb *odb, git_pobject *po)
{
	git_odb_object *src = NULL, *trg = NULL;
	unsigned long delta_size;
	void *delta_buf;

	*out = NULL;

	if (git_odb_read(&src, odb, &po->delta->id) < 0 ||
	    git_odb_read(&trg, odb, &po->id) < 0)
		goto on_error;

	delta_buf = git_delta(
		git_odb_object_data(src), (unsigned long)git_odb_object_size(src),
		git_odb_object_data(trg), (unsigned long)git_odb_object_size(trg),
		&delta_size, 0);

	if (!delta_buf || delta_size != po->delta_size) {
		giterr_set(GITERR_INVALID, "Delta size changed");
		goto on_error;
	}

	*out = delta_buf;

	git_odb_object_free(src);
	git_odb_object_free(trg);
	return 0;

on_error:
	git_odb_object_free(src);
	git_odb_object_free(trg);
	return -1;
}

static int write_object(git_buf *buf, git_packbuilder *pb, git_pobject *po)
{
	git_odb_object *obj = NULL;
	git_buf zbuf = GIT_BUF_INIT;
	git_otype type;
	unsigned char hdr[10];
	unsigned int hdr_len;
	unsigned long size;
	void *data;

	if (po->delta) {
		if (po->delta_data)
			data = po->delta_data;
		else if (get_delta(&data, pb->odb, po) < 0)
				goto on_error;
		size = po->delta_size;
		type = GIT_OBJ_REF_DELTA;
	} else {
		if (git_odb_read(&obj, pb->odb, &po->id))
			goto on_error;

		data = (void *)git_odb_object_data(obj);
		size = (unsigned long)git_odb_object_size(obj);
		type = git_odb_object_type(obj);
	}

	/* Write header */
	hdr_len = gen_pack_object_header(hdr, size, type);

	if (git_buf_put(buf, (char *)hdr, hdr_len) < 0)
		goto on_error;

	if (git_hash_update(&pb->ctx, hdr, hdr_len) < 0)
		goto on_error;

	if (type == GIT_OBJ_REF_DELTA) {
		if (git_buf_put(buf, (char *)po->delta->id.id, GIT_OID_RAWSZ) < 0 ||
			git_hash_update(&pb->ctx, po->delta->id.id, GIT_OID_RAWSZ) < 0)
			goto on_error;
	}

	/* Write data */
	if (po->z_delta_size)
		size = po->z_delta_size;
	else if (git__compress(&zbuf, data, size) < 0)
		goto on_error;
	else {
		if (po->delta)
			git__free(data);
		data = zbuf.ptr;
		size = (unsigned long)zbuf.size;
	}

	if (git_buf_put(buf, data, size) < 0 ||
		git_hash_update(&pb->ctx, data, size) < 0)
		goto on_error;

	if (po->delta_data)
		git__free(po->delta_data);

	git_odb_object_free(obj);
	git_buf_free(&zbuf);

	pb->nr_written++;
	return 0;

on_error:
	git_odb_object_free(obj);
	git_buf_free(&zbuf);
	return -1;
}

enum write_one_status {
	WRITE_ONE_SKIP = -1, /* already written */
	WRITE_ONE_BREAK = 0, /* writing this will bust the limit; not written */
	WRITE_ONE_WRITTEN = 1, /* normal */
	WRITE_ONE_RECURSIVE = 2 /* already scheduled to be written */
};

static int write_one(git_buf *buf, git_packbuilder *pb, git_pobject *po,
		     enum write_one_status *status)
{
	if (po->recursing) {
		*status = WRITE_ONE_RECURSIVE;
		return 0;
	} else if (po->written) {
		*status = WRITE_ONE_SKIP;
		return 0;
	}

	if (po->delta) {
		po->recursing = 1;
		if (write_one(buf, pb, po->delta, status) < 0)
			return -1;
		switch (*status) {
		case WRITE_ONE_RECURSIVE:
			/* we cannot depend on this one */
			po->delta = NULL;
			break;
		default:
			break;
		}
	}

	po->written = 1;
	po->recursing = 0;
	return write_object(buf, pb, po);
}

GIT_INLINE(void) add_to_write_order(git_pobject **wo, unsigned int *endp,
				    git_pobject *po)
{
	if (po->filled)
		return;
	wo[(*endp)++] = po;
	po->filled = 1;
}

static void add_descendants_to_write_order(git_pobject **wo, unsigned int *endp,
					   git_pobject *po)
{
	int add_to_order = 1;
	while (po) {
		if (add_to_order) {
			git_pobject *s;
			/* add this node... */
			add_to_write_order(wo, endp, po);
			/* all its siblings... */
			for (s = po->delta_sibling; s; s = s->delta_sibling) {
				add_to_write_order(wo, endp, s);
			}
		}
		/* drop down a level to add left subtree nodes if possible */
		if (po->delta_child) {
			add_to_order = 1;
			po = po->delta_child;
		} else {
			add_to_order = 0;
			/* our sibling might have some children, it is next */
			if (po->delta_sibling) {
				po = po->delta_sibling;
				continue;
			}
			/* go back to our parent node */
			po = po->delta;
			while (po && !po->delta_sibling) {
				/* we're on the right side of a subtree, keep
				 * going up until we can go right again */
				po = po->delta;
			}
			if (!po) {
				/* done- we hit our original root node */
				return;
			}
			/* pass it off to sibling at this level */
			po = po->delta_sibling;
		}
	};
}

static void add_family_to_write_order(git_pobject **wo, unsigned int *endp,
				      git_pobject *po)
{
	git_pobject *root;

	for (root = po; root->delta; root = root->delta)
		; /* nothing */
	add_descendants_to_write_order(wo, endp, root);
}

static int cb_tag_foreach(const char *name, git_oid *oid, void *data)
{
	git_packbuilder *pb = data;
	git_pobject *po;
	khiter_t pos;

	GIT_UNUSED(name);

	pos = kh_get(oid, pb->object_ix, oid);
	if (pos == kh_end(pb->object_ix))
		return 0;

	po = kh_value(pb->object_ix, pos);
	po->tagged = 1;

	/* TODO: peel objects */

	return 0;
}

static git_pobject **compute_write_order(git_packbuilder *pb)
{
	unsigned int i, wo_end, last_untagged;

	git_pobject **wo = git__malloc(sizeof(*wo) * pb->nr_objects);

	for (i = 0; i < pb->nr_objects; i++) {
		git_pobject *po = pb->object_list + i;
		po->tagged = 0;
		po->filled = 0;
		po->delta_child = NULL;
		po->delta_sibling = NULL;
	}

	/*
	 * Fully connect delta_child/delta_sibling network.
	 * Make sure delta_sibling is sorted in the original
	 * recency order.
	 */
	for (i = pb->nr_objects; i > 0;) {
		git_pobject *po = &pb->object_list[--i];
		if (!po->delta)
			continue;
		/* Mark me as the first child */
		po->delta_sibling = po->delta->delta_child;
		po->delta->delta_child = po;
	}

	/*
	 * Mark objects that are at the tip of tags.
	 */
	if (git_tag_foreach(pb->repo, &cb_tag_foreach, pb) < 0)
		return NULL;

	/*
	 * Give the objects in the original recency order until
	 * we see a tagged tip.
	 */
	for (i = wo_end = 0; i < pb->nr_objects; i++) {
		git_pobject *po = pb->object_list + i;
		if (po->tagged)
			break;
		add_to_write_order(wo, &wo_end, po);
	}
	last_untagged = i;

	/*
	 * Then fill all the tagged tips.
	 */
	for (; i < pb->nr_objects; i++) {
		git_pobject *po = pb->object_list + i;
		if (po->tagged)
			add_to_write_order(wo, &wo_end, po);
	}

	/*
	 * And then all remaining commits and tags.
	 */
	for (i = last_untagged; i < pb->nr_objects; i++) {
		git_pobject *po = pb->object_list + i;
		if (po->type != GIT_OBJ_COMMIT &&
		    po->type != GIT_OBJ_TAG)
			continue;
		add_to_write_order(wo, &wo_end, po);
	}

	/*
	 * And then all the trees.
	 */
	for (i = last_untagged; i < pb->nr_objects; i++) {
		git_pobject *po = pb->object_list + i;
		if (po->type != GIT_OBJ_TREE)
			continue;
		add_to_write_order(wo, &wo_end, po);
	}

	/*
	 * Finally all the rest in really tight order
	 */
	for (i = last_untagged; i < pb->nr_objects; i++) {
		git_pobject *po = pb->object_list + i;
		if (!po->filled)
			add_family_to_write_order(wo, &wo_end, po);
	}

	if (wo_end != pb->nr_objects) {
		giterr_set(GITERR_INVALID, "invalid write order");
		return NULL;
	}

	return wo;
}

static int write_pack(git_packbuilder *pb,
		      int (*cb)(void *buf, size_t size, void *data),
		      void *data)
{
	git_pobject **write_order;
	git_pobject *po;
	git_buf buf = GIT_BUF_INIT;
	enum write_one_status status;
	struct git_pack_header ph;
	unsigned int i = 0;

	write_order = compute_write_order(pb);
	if (write_order == NULL)
		goto on_error;

	/* Write pack header */
	ph.hdr_signature = htonl(PACK_SIGNATURE);
	ph.hdr_version = htonl(PACK_VERSION);
	ph.hdr_entries = htonl(pb->nr_objects);

	if (cb(&ph, sizeof(ph), data) < 0)
		goto on_error;

	if (git_hash_update(&pb->ctx, &ph, sizeof(ph)) < 0)
		goto on_error;

	pb->nr_remaining = pb->nr_objects;
	do {
		pb->nr_written = 0;
		for ( ; i < pb->nr_objects; ++i) {
			po = write_order[i];
			if (write_one(&buf, pb, po, &status) < 0)
				goto on_error;
			if (cb(buf.ptr, buf.size, data) < 0)
				goto on_error;
			git_buf_clear(&buf);
		}

		pb->nr_remaining -= pb->nr_written;
	} while (pb->nr_remaining && i < pb->nr_objects);

	git__free(write_order);
	git_buf_free(&buf);

	if (git_hash_final(&pb->pack_oid, &pb->ctx) < 0)
		goto on_error;

	return cb(pb->pack_oid.id, GIT_OID_RAWSZ, data);

on_error:
	git__free(write_order);
	git_buf_free(&buf);
	return -1;
}

static int write_pack_buf(void *buf, size_t size, void *data)
{
	git_buf *b = (git_buf *)data;
	return git_buf_put(b, buf, size);
}

static int write_pack_to_file(void *buf, size_t size, void *data)
{
	git_filebuf *file = (git_filebuf *)data;
	return git_filebuf_write(file, buf, size);
}

static int write_pack_file(git_packbuilder *pb, const char *path)
{
	git_filebuf file = GIT_FILEBUF_INIT;

	if (git_filebuf_open(&file, path, 0) < 0 ||
	    write_pack(pb, &write_pack_to_file, &file) < 0 ||
	    git_filebuf_commit(&file, GIT_PACK_FILE_MODE) < 0) {
		git_filebuf_cleanup(&file);
		return -1;
	}

	return 0;
}

static int type_size_sort(const void *_a, const void *_b)
{
	const git_pobject *a = (git_pobject *)_a;
	const git_pobject *b = (git_pobject *)_b;

	if (a->type > b->type)
		return -1;
	if (a->type < b->type)
		return 1;
	if (a->hash > b->hash)
		return -1;
	if (a->hash < b->hash)
		return 1;
	/*
	 * TODO
	 *
	if (a->preferred_base > b->preferred_base)
		return -1;
	if (a->preferred_base < b->preferred_base)
		return 1;
	*/
	if (a->size > b->size)
		return -1;
	if (a->size < b->size)
		return 1;
	return a < b ? -1 : (a > b); /* newest first */
}

static int delta_cacheable(git_packbuilder *pb, unsigned long src_size,
			   unsigned long trg_size, unsigned long delta_size)
{
	if (pb->max_delta_cache_size &&
		pb->delta_cache_size + delta_size > pb->max_delta_cache_size)
		return 0;

	if (delta_size < pb->cache_max_small_delta_size)
		return 1;

	/* cache delta, if objects are large enough compared to delta size */
	if ((src_size >> 20) + (trg_size >> 21) > (delta_size >> 10))
		return 1;

	return 0;
}

static int try_delta(git_packbuilder *pb, struct unpacked *trg,
		     struct unpacked *src, unsigned int max_depth,
		     unsigned long *mem_usage, int *ret)
{
	git_pobject *trg_object = trg->object;
	git_pobject *src_object = src->object;
	git_odb_object *obj;
	unsigned long trg_size, src_size, delta_size,
		      sizediff, max_size, sz;
	unsigned int ref_depth;
	void *delta_buf;

	/* Don't bother doing diffs between different types */
	if (trg_object->type != src_object->type) {
		*ret = -1;
		return 0;
	}

	*ret = 0;

	/* TODO: support reuse-delta */

	/* Let's not bust the allowed depth. */
	if (src->depth >= max_depth)
		return 0;

	/* Now some size filtering heuristics. */
	trg_size = (unsigned long)trg_object->size;
	if (!trg_object->delta) {
		max_size = trg_size/2 - 20;
		ref_depth = 1;
	} else {
		max_size = trg_object->delta_size;
		ref_depth = trg->depth;
	}

	max_size = (uint64_t)max_size * (max_depth - src->depth) /
					(max_depth - ref_depth + 1);
	if (max_size == 0)
		return 0;

	src_size = (unsigned long)src_object->size;
	sizediff = src_size < trg_size ? trg_size - src_size : 0;
	if (sizediff >= max_size)
		return 0;
	if (trg_size < src_size / 32)
		return 0;

	/* Load data if not already done */
	if (!trg->data) {
		if (git_odb_read(&obj, pb->odb, &trg_object->id) < 0)
			return -1;

		sz = (unsigned long)git_odb_object_size(obj);
		trg->data = git__malloc(sz);
		GITERR_CHECK_ALLOC(trg->data);
		memcpy(trg->data, git_odb_object_data(obj), sz);

		git_odb_object_free(obj);

		if (sz != trg_size) {
			giterr_set(GITERR_INVALID,
				   "Inconsistent target object length");
			return -1;
		}

		*mem_usage += sz;
	}
	if (!src->data) {
		if (git_odb_read(&obj, pb->odb, &src_object->id) < 0)
			return -1;

		sz = (unsigned long)git_odb_object_size(obj);
		src->data = git__malloc(sz);
		GITERR_CHECK_ALLOC(src->data);
		memcpy(src->data, git_odb_object_data(obj), sz);

		git_odb_object_free(obj);

		if (sz != src_size) {
			giterr_set(GITERR_INVALID,
				   "Inconsistent source object length");
			return -1;
		}

		*mem_usage += sz;
	}
	if (!src->index) {
		src->index = git_delta_create_index(src->data, src_size);
		if (!src->index)
			return 0; /* suboptimal pack - out of memory */

		*mem_usage += git_delta_sizeof_index(src->index);
	}

	delta_buf = git_delta_create(src->index, trg->data, trg_size,
				     &delta_size, max_size);
	if (!delta_buf)
		return 0;

	if (trg_object->delta) {
		/* Prefer only shallower same-sized deltas. */
		if (delta_size == trg_object->delta_size &&
		    src->depth + 1 >= trg->depth) {
			git__free(delta_buf);
			return 0;
		}
	}

	git_packbuilder__cache_lock(pb);
	if (trg_object->delta_data) {
		git__free(trg_object->delta_data);
		pb->delta_cache_size -= trg_object->delta_size;
		trg_object->delta_data = NULL;
	}
	if (delta_cacheable(pb, src_size, trg_size, delta_size)) {
		pb->delta_cache_size += delta_size;
		git_packbuilder__cache_unlock(pb);

		trg_object->delta_data = git__realloc(delta_buf, delta_size);
		GITERR_CHECK_ALLOC(trg_object->delta_data);
	} else {
		/* create delta when writing the pack */
		git_packbuilder__cache_unlock(pb);
		git__free(delta_buf);
	}

	trg_object->delta = src_object;
	trg_object->delta_size = delta_size;
	trg->depth = src->depth + 1;

	*ret = 1;
	return 0;
}

static unsigned int check_delta_limit(git_pobject *me, unsigned int n)
{
	git_pobject *child = me->delta_child;
	unsigned int m = n;

	while (child) {
		unsigned int c = check_delta_limit(child, n + 1);
		if (m < c)
			m = c;
		child = child->delta_sibling;
	}
	return m;
}

static unsigned long free_unpacked(struct unpacked *n)
{
	unsigned long freed_mem = git_delta_sizeof_index(n->index);
	git_delta_free_index(n->index);
	n->index = NULL;
	if (n->data) {
		freed_mem += (unsigned long)n->object->size;
		git__free(n->data);
		n->data = NULL;
	}
	n->object = NULL;
	n->depth = 0;
	return freed_mem;
}

static int find_deltas(git_packbuilder *pb, git_pobject **list,
		       unsigned int *list_size, unsigned int window,
		       unsigned int depth)
{
	git_pobject *po;
	git_buf zbuf = GIT_BUF_INIT;
	struct unpacked *array;
	uint32_t idx = 0, count = 0;
	unsigned long mem_usage = 0;
	unsigned int i;
	int error = -1;

	array = git__calloc(window, sizeof(struct unpacked));
	GITERR_CHECK_ALLOC(array);

	for (;;) {
		struct unpacked *n = array + idx;
		unsigned int max_depth;
		int j, best_base = -1;

		git_packbuilder__progress_lock(pb);
		if (!*list_size) {
			git_packbuilder__progress_unlock(pb);
			break;
		}

		po = *list++;
		(*list_size)--;
		git_packbuilder__progress_unlock(pb);

		mem_usage -= free_unpacked(n);
		n->object = po;

		while (pb->window_memory_limit &&
		       mem_usage > pb->window_memory_limit &&
		       count > 1) {
			uint32_t tail = (idx + window - count) % window;
			mem_usage -= free_unpacked(array + tail);
			count--;
		}

		/*
		 * If the current object is at pack edge, take the depth the
		 * objects that depend on the current object into account
		 * otherwise they would become too deep.
		 */
		max_depth = depth;
		if (po->delta_child) {
			max_depth -= check_delta_limit(po, 0);
			if (max_depth <= 0)
				goto next;
		}

		j = window;
		while (--j > 0) {
			int ret;
			uint32_t other_idx = idx + j;
			struct unpacked *m;

			if (other_idx >= window)
				other_idx -= window;

			m = array + other_idx;
			if (!m->object)
				break;

			if (try_delta(pb, n, m, max_depth, &mem_usage, &ret) < 0)
				goto on_error;
			if (ret < 0)
				break;
			else if (ret > 0)
				best_base = other_idx;
		}

		/*
		 * If we decided to cache the delta data, then it is best
		 * to compress it right away.  First because we have to do
		 * it anyway, and doing it here while we're threaded will
		 * save a lot of time in the non threaded write phase,
		 * as well as allow for caching more deltas within
		 * the same cache size limit.
		 * ...
		 * But only if not writing to stdout, since in that case
		 * the network is most likely throttling writes anyway,
		 * and therefore it is best to go to the write phase ASAP
		 * instead, as we can afford spending more time compressing
		 * between writes at that moment.
		 */
		if (po->delta_data) {
			if (git__compress(&zbuf, po->delta_data, po->delta_size) < 0)
				goto on_error;

			git__free(po->delta_data);
			po->delta_data = git__malloc(zbuf.size);
			GITERR_CHECK_ALLOC(po->delta_data);

			memcpy(po->delta_data, zbuf.ptr, zbuf.size);
			po->z_delta_size = (unsigned long)zbuf.size;
			git_buf_clear(&zbuf);

			git_packbuilder__cache_lock(pb);
			pb->delta_cache_size -= po->delta_size;
			pb->delta_cache_size += po->z_delta_size;
			git_packbuilder__cache_unlock(pb);
		}

		/*
		 * If we made n a delta, and if n is already at max
		 * depth, leaving it in the window is pointless.  we
		 * should evict it first.
		 */
		if (po->delta && max_depth <= n->depth)
			continue;

		/*
		 * Move the best delta base up in the window, after the
		 * currently deltified object, to keep it longer.  It will
		 * be the first base object to be attempted next.
		 */
		if (po->delta) {
			struct unpacked swap = array[best_base];
			int dist = (window + idx - best_base) % window;
			int dst = best_base;
			while (dist--) {
				int src = (dst + 1) % window;
				array[dst] = array[src];
				dst = src;
			}
			array[dst] = swap;
		}

		next:
		idx++;
		if (count + 1 < window)
			count++;
		if (idx >= window)
			idx = 0;
	}
	error = 0;

on_error:
	for (i = 0; i < window; ++i) {
		git__free(array[i].index);
		git__free(array[i].data);
	}
	git__free(array);
	git_buf_free(&zbuf);

	return error;
}

#ifdef GIT_THREADS

struct thread_params {
	git_thread thread;
	git_packbuilder *pb;

	git_pobject **list;

	git_cond cond;
	git_mutex mutex;

	unsigned int list_size;
	unsigned int remaining;

	int window;
	int depth;
	int working;
	int data_ready;
};

static void *threaded_find_deltas(void *arg)
{
	struct thread_params *me = arg;

	while (me->remaining) {
		if (find_deltas(me->pb, me->list, &me->remaining,
				me->window, me->depth) < 0) {
			; /* TODO */
		}

		git_packbuilder__progress_lock(me->pb);
		me->working = 0;
		git_cond_signal(&me->pb->progress_cond);
		git_packbuilder__progress_unlock(me->pb);

		if (git_mutex_lock(&me->mutex)) {
			giterr_set(GITERR_THREAD, "unable to lock packfile condition mutex");
			return NULL;
		}

		while (!me->data_ready)
			git_cond_wait(&me->cond, &me->mutex);

		/*
		 * We must not set ->data_ready before we wait on the
		 * condition because the main thread may have set it to 1
		 * before we get here. In order to be sure that new
		 * work is available if we see 1 in ->data_ready, it
		 * was initialized to 0 before this thread was spawned
		 * and we reset it to 0 right away.
		 */
		me->data_ready = 0;
		git_mutex_unlock(&me->mutex);
	}
	/* leave ->working 1 so that this doesn't get more work assigned */
	return NULL;
}

static int ll_find_deltas(git_packbuilder *pb, git_pobject **list,
			  unsigned int list_size, unsigned int window,
			  unsigned int depth)
{
	struct thread_params *p;
	int i, ret, active_threads = 0;

	if (!pb->nr_threads)
		pb->nr_threads = git_online_cpus();

	if (pb->nr_threads <= 1) {
		find_deltas(pb, list, &list_size, window, depth);
		return 0;
	}

	p = git__malloc(pb->nr_threads * sizeof(*p));
	GITERR_CHECK_ALLOC(p);

	/* Partition the work among the threads */
	for (i = 0; i < pb->nr_threads; ++i) {
		unsigned sub_size = list_size / (pb->nr_threads - i);

		/* don't use too small segments or no deltas will be found */
		if (sub_size < 2*window && i+1 < pb->nr_threads)
			sub_size = 0;

		p[i].pb = pb;
		p[i].window = window;
		p[i].depth = depth;
		p[i].working = 1;
		p[i].data_ready = 0;

		/* try to split chunks on "path" boundaries */
		while (sub_size && sub_size < list_size &&
		       list[sub_size]->hash &&
		       list[sub_size]->hash == list[sub_size-1]->hash)
			sub_size++;

		p[i].list = list;
		p[i].list_size = sub_size;
		p[i].remaining = sub_size;

		list += sub_size;
		list_size -= sub_size;
	}

	/* Start work threads */
	for (i = 0; i < pb->nr_threads; ++i) {
		if (!p[i].list_size)
			continue;

		git_mutex_init(&p[i].mutex);
		git_cond_init(&p[i].cond);

		ret = git_thread_create(&p[i].thread, NULL,
					threaded_find_deltas, &p[i]);
		if (ret) {
			giterr_set(GITERR_THREAD, "unable to create thread");
			return -1;
		}
		active_threads++;
	}

	/*
	 * Now let's wait for work completion.  Each time a thread is done
	 * with its work, we steal half of the remaining work from the
	 * thread with the largest number of unprocessed objects and give
	 * it to that newly idle thread.  This ensure good load balancing
	 * until the remaining object list segments are simply too short
	 * to be worth splitting anymore.
	 */
	while (active_threads) {
		struct thread_params *target = NULL;
		struct thread_params *victim = NULL;
		unsigned sub_size = 0;

		/* Start by locating a thread that has transitioned its
		 * 'working' flag from 1 -> 0. This indicates that it is
		 * ready to receive more work using our work-stealing
		 * algorithm. */
		git_packbuilder__progress_lock(pb);
		for (;;) {
			for (i = 0; !target && i < pb->nr_threads; i++)
				if (!p[i].working)
					target = &p[i];
			if (target)
				break;
			git_cond_wait(&pb->progress_cond, &pb->progress_mutex);
		}

		/* At this point we hold the progress lock and have located
		 * a thread to receive more work. We still need to locate a
		 * thread from which to steal work (the victim). */
		for (i = 0; i < pb->nr_threads; i++)
			if (p[i].remaining > 2*window &&
			    (!victim || victim->remaining < p[i].remaining))
				victim = &p[i];

		if (victim) {
			sub_size = victim->remaining / 2;
			list = victim->list + victim->list_size - sub_size;
			while (sub_size && list[0]->hash &&
			       list[0]->hash == list[-1]->hash) {
				list++;
				sub_size--;
			}
			if (!sub_size) {
				/*
				 * It is possible for some "paths" to have
				 * so many objects that no hash boundary
				 * might be found.  Let's just steal the
				 * exact half in that case.
				 */
				sub_size = victim->remaining / 2;
				list -= sub_size;
			}
			target->list = list;
			victim->list_size -= sub_size;
			victim->remaining -= sub_size;
		}
		target->list_size = sub_size;
		target->remaining = sub_size;
		target->working = 1;
		git_packbuilder__progress_unlock(pb);

		if (git_mutex_lock(&target->mutex)) {
			giterr_set(GITERR_THREAD, "unable to lock packfile condition mutex");
			git__free(p);
			return -1;
		}

		target->data_ready = 1;
		git_cond_signal(&target->cond);
		git_mutex_unlock(&target->mutex);

		if (!sub_size) {
			git_thread_join(target->thread, NULL);
			git_cond_free(&target->cond);
			git_mutex_free(&target->mutex);
			active_threads--;
		}
	}

	git__free(p);
	return 0;
}

#else
#define ll_find_deltas(pb, l, ls, w, d) find_deltas(pb, l, &ls, w, d)
#endif

static int prepare_pack(git_packbuilder *pb)
{
	git_pobject **delta_list;
	unsigned int i, n = 0;

	if (pb->nr_objects == 0 || pb->done)
		return 0; /* nothing to do */

	delta_list = git__malloc(pb->nr_objects * sizeof(*delta_list));
	GITERR_CHECK_ALLOC(delta_list);

	for (i = 0; i < pb->nr_objects; ++i) {
		git_pobject *po = pb->object_list + i;

		/* Make sure the item is within our size limits */
		if (po->size < 50 || po->size > pb->big_file_threshold)
			continue;

		delta_list[n++] = po;
	}

	if (n > 1) {
		git__tsort((void **)delta_list, n, type_size_sort);
		if (ll_find_deltas(pb, delta_list, n,
				   GIT_PACK_WINDOW + 1,
				   GIT_PACK_DEPTH) < 0) {
			git__free(delta_list);
			return -1;
		}
	}

	pb->done = true;
	git__free(delta_list);
	return 0;
}

#define PREPARE_PACK if (prepare_pack(pb) < 0) { return -1; }

int git_packbuilder_foreach(git_packbuilder *pb, int (*cb)(void *buf, size_t size, void *payload), void *payload)
{
	PREPARE_PACK;
	return write_pack(pb, cb, payload);
}

int git_packbuilder_write_buf(git_buf *buf, git_packbuilder *pb)
{
	PREPARE_PACK;
	return write_pack(pb, &write_pack_buf, buf);
}

int git_packbuilder_write(git_packbuilder *pb, const char *path)
{
	PREPARE_PACK;
	return write_pack_file(pb, path);
}

#undef PREPARE_PACK

static int cb_tree_walk(const char *root, const git_tree_entry *entry, void *payload)
{
	struct tree_walk_context *ctx = payload;

	/* A commit inside a tree represents a submodule commit and should be skipped. */
	if (git_tree_entry_type(entry) == GIT_OBJ_COMMIT)
		return 0;

	if (git_buf_sets(&ctx->buf, root) < 0 ||
		git_buf_puts(&ctx->buf, git_tree_entry_name(entry)) < 0)
		return -1;

	return git_packbuilder_insert(ctx->pb,
		git_tree_entry_id(entry),
		git_buf_cstr(&ctx->buf));
}

int git_packbuilder_insert_tree(git_packbuilder *pb, const git_oid *oid)
{
	git_tree *tree;
	struct tree_walk_context context = { pb, GIT_BUF_INIT };

	if (git_tree_lookup(&tree, pb->repo, oid) < 0 ||
	    git_packbuilder_insert(pb, oid, NULL) < 0)
		return -1;

	if (git_tree_walk(tree, GIT_TREEWALK_PRE, cb_tree_walk, &context) < 0) {
		git_tree_free(tree);
		git_buf_free(&context.buf);
		return -1;
	}

	git_tree_free(tree);
	git_buf_free(&context.buf);
	return 0;
}

uint32_t git_packbuilder_object_count(git_packbuilder *pb)
{
	return pb->nr_objects;
}

uint32_t git_packbuilder_written(git_packbuilder *pb)
{
	return pb->nr_written;
}

void git_packbuilder_free(git_packbuilder *pb)
{
	if (pb == NULL)
		return;

#ifdef GIT_THREADS

	git_mutex_free(&pb->cache_mutex);
	git_mutex_free(&pb->progress_mutex);
	git_cond_free(&pb->progress_cond);

#endif

	if (pb->odb)
		git_odb_free(pb->odb);

	if (pb->object_ix)
		git_oidmap_free(pb->object_ix);

	if (pb->object_list)
		git__free(pb->object_list);

	git_hash_ctx_cleanup(&pb->ctx);

	git__free(pb);
}


text:
from __future__ import unicode_literals

import pytest

@pytest.fixture
def smtp(disallow_emails, smtpserver, app):
    """Wrapper for the `smtpserver` fixture which updates the Indico config
    and disables the SMTP autofail logic for that smtp server.
    """
    old_config = app.config['INDICO']
    app.config['INDICO'] = dict(app.config['INDICO'])  # make it mutable
    app.config['INDICO']['SMTP_SERVER'] = smtpserver.addr
    disallow_emails.add(smtpserver.addr)  # whitelist our smtp server
    yield smtpserver
    app.config['INDICO'] = old_config


text:
require 'spec_helper'

set :os, :family => 'solaris'

describe user('root') do
  it { should belong_to_group 'root' }
end

describe user('root') do
  it { should have_login_shell '/bin/bash' }
end

describe user('root') do
  it { should have_home_directory '/root' }
end


text:
//
// This file is part of Lyricus.
// Copyright (c) 2008-2011, Thomas Backman <serenity@exscape.org>
// This software is distributed under the terms of the MIT license. For details, see license.txt.
//

#import "TrackObject.h"

@implementation TrackObject

@synthesize track;
@synthesize artist;
@synthesize name;
@synthesize state;
@synthesize processed;

-(void)setState:(NSInteger)inState {

	// If the state is CHANGED to either of these two values,
	// the batch downloader has tried to fetch lyrics,
	// and either succeeded or failed.
	// If the state is NSMixedState, it's still in progress,
	// so don't update the processed property.
	if (inState == NSOnState || inState == NSOffState)
		processed = YES;

	state = inState;
}

- (id)init {
	return nil;
}

- (id)initWithTrack:(iTunesTrack*)tr Artist:(NSString *)inArtist Name:(NSString *)inName {
	self = [super init];
	if (self) {
		track = tr;
		name = inName;
		artist = inArtist;
		state = 0; /* allows mixed state, (-1, 0 or 1) */
		processed = NO; /* has this track been processed? */
	}

	return self;
}

-(NSString *)description {
	return name;
}

- (void)dealloc {
    [super dealloc];
}

@end


text:
using System.Collections.Generic;
using System.Drawing;

namespace OMF
{
    /// <summary>
    /// Base ProjectElement class for OMF file
    ///     ProjectElement subclasses must define their mesh.
    ///     ProjectElements include PointSet, LineSet, Surface, and Volume
    /// </summary>
    public class ProjectElement: ContentModel
    {
        public List<ProjectElementData> data { get; set; }
        public Color color  { get;set; }
        public ProjectElementGeometry geometry { get; set; }
    }
}


text:
/*
 * Check a Washington State Ferry pass for the balance remaining. These passes
 * contain a 1D barcode. It uses the ZXING barcode scanner to read the barcode
 * and looks up the ticket and the balance from a WSF HTML page. Despite the fact
 * that WA DOT has a good set of API's for many things (see below), it doesn't have
 * one for looking up tickets -- which is why we resort to HTML scraping.
 *
 * Reference:
 * ZXING Team:
 * https://github.com/zxing/zxing
 * WSDOT API's website
 * http://www.wsdot.wa.gov/traffic/api/
 */
package com.tavakkolian.wtfwsf;

import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;

import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import java.util.Map;

/**
 * can't get any simpler
 */
public class TicketChecker extends Activity {
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_tciket_checker);
	}

	/*
	 * Everything above here is auto-generated by Eclipse and Android plugin upon project
	 * creation.
	 */
	public void onScanButtonPressed(View view) {
		// send an intent to zxing barcode scanner
		IntentIntegrator integrator = new IntentIntegrator(this);
		integrator.initiateScan();
	}

	private static final String WSFMagicCookiesURL = "https://wave2go.wsdot.com/Webstore/Content.aspx?Kind=LandingPage&CG=21&C=10";
	private static final String WSFTicketLookupURL = "https://wave2go.wsdot.com/WebStore/account/TicketLookup.aspx?VisualID=";

	public void onActivityResult(int requestCode, int resultCode, Intent intent) {
		IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
		if (scanResult != null) {
			String barcode = scanResult.getContents();
			TextView bcview = (TextView) findViewById(R.id.barcodeView);
			bcview.setText(barcode);
			new GetBalanceTask().execute(barcode);
		} else {
			TextView bcview = (TextView) findViewById(R.id.barcodeView);
			bcview.setText("No barcode detected");
		}
	}

	private class GetBalanceTask extends AsyncTask<String, Void, String> {
		@Override
		protected void onPreExecute(){
			super.onPreExecute();
			TextView tv = (TextView) findViewById(R.id.balanceView);
			tv.setText("...");
		}
		@Override
		protected String doInBackground(String... params) {
			Map<String, String> cookies = null;
			String result = "Failed. Try Again.";

			try {
				Connection.Response resp = Jsoup.connect(WSFMagicCookiesURL).method(Connection.Method.GET).execute();
				cookies = resp.cookies();

			} catch (Exception e){
				e.printStackTrace();
				return result;
			}

			try {
				String url = WSFTicketLookupURL+params[0];	// params[0] is the barcode
				Document doc = Jsoup.connect(url).cookies(cookies).get();

				// Log.d("doInBackground",doc.select("table#ctl00_ContentPlaceHolder_TicketInfo").toString());
				Elements e = doc.select(
						"table#ctl00_ContentPlaceHolder_TicketInfo tr:last-child td:eq(1)");
				if (e != null) {
					result = e.get(0).ownText();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}

			return result;
		}

		@Override
		protected void onPostExecute(String result){
			super.onPostExecute(result);
			TextView tv = (TextView) findViewById(R.id.balanceView);
			tv.setText(result);
		}
	}
}


text:
import { registerComponent, Components } from '../../lib/vulcan-lib';
import React from 'react';
import SubdirectoryArrowLeft from '@material-ui/icons/SubdirectoryArrowLeft';
import classNames from 'classnames';
import { legacyBreakpoints } from '../../lib/utils/theme';

const styles = (theme: ThemeType): JssStyles => ({
  root: {
    paddingRight: theme.spacing.unit,
    paddingTop: theme.spacing.unit,
    paddingBottom: theme.spacing.unit,
    cursor: "pointer",
    color: "rgba(0,0,0,.75)",
  },
  active: {
    color: "rgba(0,0,0, .3)",
  },
  icon: {
    fontSize: 12,
    transform: "rotate(90deg)"
  },
  parentComment: {
    background: "white",
    position: "absolute",
    zIndex: 2,
    maxWidth: 650,
    bottom: "100%",
    left: 0,
    boxShadow: "0 0 10px rgba(0,0,0,.2)"
  },
  usernameSpacing: {
    paddingRight: 1,
    color: "rgba(0,0,0,.3)",
    [legacyBreakpoints.maxSmall]: {
      padding: "0 10px",
    }
  },
  activeArrow: {
    transform: "rotate(-90deg)"
  }
})

const ShowParentComment = ({ comment, active, onClick, classes }: {
  comment: CommentsList,
  active?: boolean,
  onClick?: any,
  classes: ClassesType,
}) => {

  if (!comment) return null;

  return (
    <Components.LWTooltip title={`${active ? "Hide" : "Show"} previous comment`}>
      <span className={classNames(classes.root, {[classes.active]: active})} onClick={onClick}>
        <SubdirectoryArrowLeft className={classNames(classes.icon, {[classes.activeArrow]: active})}>
          subdirectory_arrow_left
        </SubdirectoryArrowLeft>
      </span>
    </Components.LWTooltip>
  )
};

const ShowParentCommentComponent = registerComponent('ShowParentComment', ShowParentComment, {styles});

declare global {
  interface ComponentTypes {
    ShowParentComment: typeof ShowParentCommentComponent,
  }
}


text:
/**
 * @jsx React.DOM
 */
var React =  require('react'),
    pubsub = require('pubsub-js'),
    RTableHeaderCell = require('./RTableHeaderCell').Component,
    RTableFilterCell = require('./RTableFilterCell').Component,
    RTableSelectCell = require('./RTableSelectCell').Component,
    RTableCell = require('./RTableCell').Component,
    PropRenderMixin = require('./PropRenderMixin');

var RTable = {
    displayName : 'RTable',
    mixins: [PropRenderMixin],
    getDefaultProps : function  () {
        return {
        	data : [],
        	definitions : [],
            dataProp : '.',
            columnFieldValueProp : 'field',
            columnNameProp : 'name',
            enableFilters : true,
            enableSelection : true,
            classes : '',
            optimization : true,
            fixedHeader : false
        };
    },
    tableScroll : function(e){
        this.refs.rHeader.getDOMNode().style.width = this.refs.rTable.getDOMNode().clientWidth + this.refs.rTable.getDOMNode().scrollLeft + 'px';
        this.refs.rBody.getDOMNode().style.width = this.refs.rTable.getDOMNode().clientWidth + this.refs.rTable.getDOMNode().scrollLeft + 'px';
    },
    componentDidMount : function() {
        pubsub.publish('RTable.Mounted', null);

        if (this.props.fixedHeader){
            this.refs.rTable.getDOMNode()
            .addEventListener('scroll', this.tableScroll);
        }
    },
    componentWillUpdate : function(){
        pubsub.publish('RTable.BeforeUpdated', null);
    },
    componentDidUpdate : function  () {
        pubsub.publish('RTable.Updated', null);
    },
    componentWillUnmount : function(){
        pubsub.publish('RTable.Unmounted', null);
        //clean up.
        pubsub.unsubscribe('RTable.Mounted');
        pubsub.unsubscribe('RTable.Updated');
        pubsub.unsubscribe('RTable.BeforeUpdated');
        pubsub.unsubscribe('RTable.Unmounted');

        this.refs.rTable.getDOMNode()
        .removeEventListener('scroll', this.tableScroll);
    },
    propTypes : {
    	 //Definitions for columns
        definitions : React.PropTypes.oneOfType([
        	React.PropTypes.arrayOf(React.PropTypes.string),
        	React.PropTypes.arrayOf(React.PropTypes.object)]),
        //Data objects
        data : React.PropTypes.arrayOf(React.PropTypes.object),
        //Nested property name of each item in data array where to look for column values. Otherwise root object will be used.
        dataProp : React.PropTypes.string,
        //Property that will be looked for in each column object to use as property name to look for in data item.
        columnFieldValueProp : React.PropTypes.string,
        //Property that will be looked for in each column object to use as column title.
        columnNameProp : React.PropTypes.string,
        //should show filters
        enableFilters : React.PropTypes.bool,
        //should show row selection checkboxes
        enableSelection : React.PropTypes.bool,
        //css class names to be added
        classes : React.PropTypes.string,
        //optimization flag. Default is true. Uses memory
        optimization : React.PropTypes.bool,
        //should table apply fixed header and only body content scrolling
        fixedHeader : React.PropTypes.bool
    },
    render : function(){
            var theadRows = [],
                headers = [],
                filters = [],
                colGroups = [],
                rows = [],
                classNames = 'rtable ';

            classNames += this.props.fixedHeader ? ' rtable-fixed-header ' : '';
            classNames += this.props.classes;

            if (this.props.data.length){
                this.renderSelectionColumn(colGroups, headers, filters);

                for (var i = 0; i < this.props.definitions.length; i++) {
                    //col groups
                    colGroups.push(React.createElement("col", {key: 'col_'+i, className: 'rtable-col rtable-col-'+i}));
                    //headers
                    headers.push(React.createElement(RTableHeaderCell, {key: 'header_cell_'+i,
                                        definition: this.props.definitions[i],
                                        columnNameProp: this.props.columnNameProp}));
                    //filters
                    filters.push(React.createElement(RTableFilterCell, {key: 'filter_cell' + i,
                                    definition: this.props.definitions[i]}));
                    //rows
                    this.renderColumn(rows, i);
                }

                theadRows.push(React.createElement("tr", {key: "rTableHeaderRow"}, headers));

                if (this.props.enableFilters){
                    theadRows.push(React.createElement("tr", {key: "rtableFilterRow"}, filters));
                }
            }

            return (React.createElement("table", {className: classNames, ref: "rTable"},

                          React.createElement("colgroup", null, colGroups),
                          React.createElement("thead", {ref: "rHeader"}, theadRows),
                          React.createElement("tbody", {ref: "rBody"}, rows)

            	     ));
    },
    getInitialRow : function(rowIndex, data){
        var arr = [];
        if (this.props.enableSelection){
            arr.push(React.createElement(RTableSelectCell, {key: 'row_'+rowIndex+'_select', data: data}));
        }
        return arr;
    },
    renderColumn : function(rows, columnIndex){
        for (var j = 0; j < this.props.data.length; j++) {
                        var row = rows[j] = rows[j] || (React.createElement("tr", {key: 'row_'+j}));
                        var cells =  row.props.children = row.props.children || this.getInitialRow(j, this.props.data[j]);
                        cells.push(React.createElement(RTableCell, {key: 'row_'+j+'_cell_'+columnIndex,
                                        data: this.props.data[j],
                                        definition: this.props.definitions[columnIndex],
                                        columnFieldValueProp: this.props.columnFieldValueProp,
                                        dataProp: this.props.dataProp,
                                        optimization: this.props.optimization}));
                    }
    },
    renderSelectionColumn : function(cols, headers,  filters){
        if (this.props.enableSelection){
            cols.push(React.createElement("col", {key: "col_selection", className: "rtable-col rtable-selection"}));
            headers.push(React.createElement("th", {key: "header_cell_selection", className: "rtable-selection rtable-column-header"}));
            filters.push(React.createElement("th", {key: "filter_cell_selection", className: "rtable-selection rtable-column-filter"}));
        }
    }
};

module.exports = {
    class : RTable,
    Component : React.createClass(RTable)
};


text:
import {Reflection, ReflectionKind, IDecorator, DeclarationReflection, IDeclarationHierarchy} from "../../models/reflections/index";
import {Type, ReferenceType, TupleType, UnionType} from "../../models/types/index";
import {Component, ConverterComponent} from "../components";
import {Converter} from "../converter";
import {Context} from "../context";

/**
 * A handler that converts all instances of [[LateResolvingType]] to their renderable equivalents.
 */
@Component({name:'type'})
export class TypePlugin extends ConverterComponent
{
    reflections:DeclarationReflection[] = [];

    /**
     * Create a new TypeHandler instance.
     */
    initialize() {
        this.listenTo(this.owner, {
            [Converter.EVENT_RESOLVE]:     this.onResolve,
            [Converter.EVENT_RESOLVE_END]: this.onResolveEnd
        });
    }

    /**
     * Triggered when the converter resolves a reflection.
     *
     * @param context  The context object describing the current state the converter is in.
     * @param reflection  The reflection that is currently resolved.
     */
    private onResolve(context:Context, reflection:DeclarationReflection) {
        var project = context.project;

        resolveType(reflection, <ReferenceType>reflection.type);
        resolveType(reflection, <ReferenceType>reflection.inheritedFrom);
        resolveType(reflection, <ReferenceType>reflection.overwrites);
        resolveTypes(reflection, reflection.extendedTypes);
        resolveTypes(reflection, reflection.extendedBy);
        resolveTypes(reflection, reflection.implementedTypes);

        if (reflection.decorators) reflection.decorators.forEach((decorator:IDecorator) => {
            if (decorator.type) {
                resolveType(reflection, decorator.type);
            }
        });

        if (reflection.kindOf(ReflectionKind.ClassOrInterface)) {
            this.postpone(reflection);

            walk(reflection.implementedTypes, (target) => {
                this.postpone(target);
                if (!target.implementedBy) target.implementedBy = [];
                target.implementedBy.push(new ReferenceType(reflection.name, ReferenceType.SYMBOL_ID_RESOLVED, reflection));
            });

            walk(reflection.extendedTypes, (target) => {
                this.postpone(target);
                if (!target.extendedBy) target.extendedBy = [];
                target.extendedBy.push(new ReferenceType(reflection.name, ReferenceType.SYMBOL_ID_RESOLVED, reflection));
            });
        }

        function walk(types:Type[], callback:{(declaration:DeclarationReflection):void}) {
            if (!types) return;
            types.forEach((type:ReferenceType) => {
                if (!(type instanceof ReferenceType)) return;
                if (!type.reflection || !(type.reflection instanceof DeclarationReflection)) return;
                callback(<DeclarationReflection>type.reflection);
            });
        }

        function resolveTypes(reflection:Reflection, types:Type[]) {
            if (!types) return;
            for (var i = 0, c = types.length; i < c; i++) {
                resolveType(reflection, <ReferenceType>types[i]);
            }
        }

        function resolveType(reflection:Reflection, type:Type) {
            if (type instanceof ReferenceType) {
                var referenceType:ReferenceType = <ReferenceType>type;
                if (referenceType.symbolID == ReferenceType.SYMBOL_ID_RESOLVE_BY_NAME) {
                    referenceType.reflection = reflection.findReflectionByName(referenceType.name);
                } else if (!referenceType.reflection && referenceType.symbolID != ReferenceType.SYMBOL_ID_RESOLVED) {
                    referenceType.reflection = project.reflections[project.symbolMapping[referenceType.symbolID]];
                }

                if (referenceType.typeArguments) {
                    referenceType.typeArguments.forEach((typeArgument:Type) => {
                        resolveType(reflection, typeArgument);
                    });
                }
            } else if (type instanceof TupleType) {
                var tupleType:TupleType = <TupleType>type;
                for (var index = 0, count = tupleType.elements.length; index < count; index++) {
                    resolveType(reflection, tupleType.elements[index]);
                }
            } else if (type instanceof UnionType) {
                var unionType:UnionType = <UnionType>type;
                for (var index = 0, count = unionType.types.length; index < count; index++) {
                    resolveType(reflection, unionType.types[index]);
                }
            }
        }
    }

    private postpone(reflection:DeclarationReflection) {
        if (this.reflections.indexOf(reflection) == -1) {
            this.reflections.push(reflection);
        }
    }

    /**
     * Triggered when the converter has finished resolving a project.
     *
     * @param context  The context object describing the current state the converter is in.
     */
    private onResolveEnd(context:Context) {
        this.reflections.forEach((reflection) => {
            if (reflection.implementedBy) {
                reflection.implementedBy.sort((a:Type, b:Type):number => {
                    if (a['name'] == b['name']) return 0;
                    return a['name'] > b['name'] ? 1 : -1;
                });
            }

            var root:IDeclarationHierarchy;
            var hierarchy:IDeclarationHierarchy;
            function push(types:Type[]) {
                var level:IDeclarationHierarchy = {types:types};
                if (hierarchy) {
                    hierarchy.next = level;
                    hierarchy = level;
                } else {
                    root = hierarchy = level;
                }
            }

            if (reflection.extendedTypes) {
                push(reflection.extendedTypes);
            }

            push([new ReferenceType(reflection.name, ReferenceType.SYMBOL_ID_RESOLVED, reflection)]);
            hierarchy.isTarget = true;

            if (reflection.extendedBy) {
                push(reflection.extendedBy);
            }

            reflection.typeHierarchy = root;
        });
    }
}


text:
// Arguments passed into this controller can be accessed via the `$.args` object directly or:
var $BM = $.args; 										// get our book manager object
var books = null;
var textfields = [$.title, $.year, $.genre, $.author]; 	// place all the textfields to be validated here
var errors = null;

books = $BM.getBooks();									// get books from book manager.

/**
 *	Add book event callback function - validation and addition of book from the View to Persistance Layer.
 *
 * 	@param {}
 */
function addBook() {
	errors = validate();
	if( errors.length == 0 || errors === null ) {
		insertBook();
		closeWindow();
	}
	else {
		for (var i in errors) {
			errors[i].hintTextColor = "#f44336"; 						// sets red color text for errors.
			errors[i].hintText = errors[i].name + " cannot be empty";	// field name error message.
		}
	}
}

/**
 *	Put focus on the title field
 *
 * 	@param {}
 */
function focusTitleField() {
    $.title.focus();
}

function closeKeyboard(e) {
    e.source.blur();
}

/**
 *	Close the add book window.
 *
 * 	@param {}
 */
function closeWindow() {
//	Ti.App.fireEvent("refresh-data");
    $.addWin.close();
}

/**
 *	create a new book object and insert into persistance layer using bookmanager.
 * 	Uses the form fields from the addbook view
 *
 * 	@param {}
 */
function insertBook() {
	var book = {};
		book.id="gddsg675643w4"; 		// constant is ok for now but consider unique later.
		book.title=$.title.value;
		book.year=$.year.value;
		book.genre=$.genre.value;
		book.author=$.author.value;
	$BM.insertBook(book); 				// Add book to the main books array.
	Ti.App.fireEvent("refresh-data"); 	// refresh the view on main booklist view.
}

/**
 *	validate the fields provided in textfields array.
 *
 * 	@param {}
 *
 *  @return {object} errors - an array object containing all the errors fields.
 */
function validate() {
	var errors = [];
	for (var i in textfields) {
            if (textfields[i].value === '' || textfields[i].value === null || textfields[i].value === undefined ) {
                errors.push(textfields[i]);
            }
    }
    return errors;
}


text:
resetFileEndingsToCollect()
addCAndCPPFileTypes()
addFileEndingToCollect("*.ui")

#GLOB SOURCE FILES IN MY_SRCS
unset(MY_SRCS)
includeRecursiveAllFilesFrom(${targetName} ${CMAKE_CURRENT_LIST_DIR})


text:
ld27-game
=========

Solo entry for Ludum Dare 27, with the theme of '10 seconds'


text:
Basic LSTM recurrent network cell.

The implementation is based on: http://arxiv.org/abs/1409.2329.

We add `forget_bias` (default: 1) to the biases of the forget gate in order to
reduce the scale of forgetting in the beginning of the training.

Unlike `core_rnn_cell.LSTMCell`, this is a monolithic op and should be much
faster.  The weight and bias matrixes should be compatible as long as the
variable scope matches.
- - -

#### `tf.contrib.rnn.LSTMBlockCell.__call__(x, states_prev, scope=None)` {#LSTMBlockCell.__call__}

Long short-term memory cell (LSTM).

- - -

#### `tf.contrib.rnn.LSTMBlockCell.__init__(num_units, forget_bias=1.0, use_peephole=False)` {#LSTMBlockCell.__init__}

Initialize the basic LSTM cell.

##### Args:

*  <b>`num_units`</b>: int, The number of units in the LSTM cell.
*  <b>`forget_bias`</b>: float, The bias added to forget gates (see above).
*  <b>`use_peephole`</b>: Whether to use peephole connections or not.

- - -

#### `tf.contrib.rnn.LSTMBlockCell.output_size` {#LSTMBlockCell.output_size}

- - -

#### `tf.contrib.rnn.LSTMBlockCell.state_size` {#LSTMBlockCell.state_size}

- - -

#### `tf.contrib.rnn.LSTMBlockCell.zero_state(batch_size, dtype)` {#LSTMBlockCell.zero_state}

Return zero-filled state tensor(s).

##### Args:

*  <b>`batch_size`</b>: int, float, or unit Tensor representing the batch size.
*  <b>`dtype`</b>: the data type to use for the state.

##### Returns:

  If `state_size` is an int or TensorShape, then the return value is a
  `N-D` tensor of shape `[batch_size x state_size]` filled with zeros.

  If `state_size` is a nested list or tuple, then the return value is
  a nested list or tuple (of the same structure) of `2-D` tensors with
the shapes `[batch_size x s]` for each s in `state_size`.


text:
package main

import (
	"./users"
	"fmt"
	"strings"
)

func main() {

	name, surname := "Denis", "Makogon"

	user := new(users.User)

	fmt.Println("Attempt #1")
	user, err := user.Create(name, surname)
	fmt.Println("User:", user)
	fmt.Println("Error:", err)
	fmt.Println("\n\n")

	fmt.Println("Attempt #2")
	user, err = user.Create(strings.ToUpper(name), surname)
	fmt.Println("User:", user)
	fmt.Println("Error", err)
	fmt.Println("\n\n")

	fmt.Println("Attempt #3")
	user, err = user.Create(strings.ToUpper(name), strings.ToUpper(surname))
	fmt.Println("User:", user)
	fmt.Println("Error", err)
	fmt.Println("\n\n")

}


text:
package samples.server;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
import org.springframework.scheduling.annotation.EnableScheduling;

@SpringBootApplication
@EnableJpaAuditing
@EnableScheduling
@EnableCaching
class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}


text:
package org.apache.webbeans.test.component.inject.alternative;

import javax.enterprise.inject.Default;
import javax.inject.Inject;

public class AlternativeInjector
{
    private @Inject @Default IAlternative alternative;

    public IAlternative getAlternative()
    {
        return this.alternative;
    }
}


text:
<?php

if (!defined("IN_FUSION")) { die("Access Denied"); }

if (file_exists(GOLD_LANG.LOCALESET."admin/dbmgnt.php")) {
	include GOLD_LANG.LOCALESET."admin/dbmgnt.php";
} else {
	include GOLD_LANG."English/admin/dbmgnt.php";
}

function deluserquestion() {
	global $locale, $aidlink;
	global $HTTP_POST_VARS, $userdata, $ug3_install,$locale, $settings, $golddata;
	opentable($locale['urg_a_dbmgnt_100']);
	echo "
".$locale['urg_a_dbmgnt_101']."

".$locale['urg_a_dbmgnt_102']."
\n";
	echo "
\n<form action='index.php".$aidlink."' method='post'>\n";
	echo "<input type='hidden' name='op' value='delusersaction' />\n";
	echo $locale['urg_a_dbmgnt_103']." <input type='checkbox' name='delusers' value='1' />\n";
	echo "
\n";
	echo "<input type='submit' value='".$locale['urg_a_dbmgnt_104']."' class='button' />\n";
	echo "<input type='submit' name='cancel' value='".$locale['urg_a_dbmgnt_105']."' class='button' />\n";
	echo "</form>\n
\n";
	closetable();
}

function delusersaction() {
	global $locale;
	opentable($locale['urg_a_dbmgnt_106']);
	if(isset($_POST['delusers']) && $_POST['delusers'] =='1') {
		$sql = dbquery("SELECT * FROM ".DB_UG3." WHERE owner_id NOT IN (SELECT user_id FROM ".DB_USERS.")");
		if (dbrows($sql) != 0) { //If this member doesn't exist
			opentable($locale['urg_a_dbmgnt_106']);
			while ($data = dbarray($sql)) {
				$deluser = dbquery("DELETE FROM ".DB_UG3." WHERE owner_id = '".$data['owner_id']."'");
				if($deluser) {
					echo "".sprintf($locale['urg_a_dbmgnt_109'],$data['owner_name'],$data['owner_id'])."
\n";
				} else {
					echo "".sprintf($locale['urg_a_dbmgnt_110'],$data['owner_name'],$data['owner_id'])."
\n";
				}
			}//end
			closetable();

			opentable($locale['urg_a_dbmgnt_107']);
			$sql2 = dbquery("SELECT * FROM ".DB_UG3_INVENTORY." WHERE ownerid NOT IN (SELECT user_id FROM ".DB_USERS.")");
			while ($data2 = dbarray($sql2)) {
				$delinv = dbquery("DELETE FROM ".DB_UG3_INVENTORY." WHERE ownerid = '".$data2['ownerid']."'");
				if($delinv) {
					echo "".sprintf($locale['urg_a_dbmgnt_111'],$data2['itemname'],$data2['ownerid'])."
\n";
				} else {
					echo "".sprintf($locale['urg_a_dbmgnt_112'],$data2['itemname'],$data2['ownerid'])."
\n";
				}
			}//end
			closetable();

			opentable($locale['urg_a_dbmgnt_108']);
			$sql3 = dbquery("SELECT * FROM ".DB_UG3_TRANSACTIONS." WHERE transaction_user_id NOT IN (SELECT user_id FROM ".DB_USERS.")");
			while ($data3 = dbarray($sql3)) {
				$deltrans = dbquery("DELETE FROM ".DB_UG3_TRANSACTIONS." WHERE transaction_user_id = '".$data3['transaction_user_id']."'");
				if($deltrans) {
					echo "".sprintf($locale['urg_a_dbmgnt_113'],$data3['transaction_id'],$data3['transaction_user_id'])."
\n";
				} else {
					echo "".sprintf($locale['urg_a_dbmgnt_114'],$data3['transaction_id'],$data3['transaction_user_id'])."
\n";
				}
			}//end
			closetable();
		} else {
			opentable($locale['urg_a_dbmgnt_115']);
				echo "
".$locale['urg_a_dbmgnt_115']."
\n";
			closetable;
		}
	} else {
	echo "
".$locale['urg_a_dbmgnt_116']."
\n";
	}
	closetable;
}
?>


text:
import {
  MLKitNaturalLanguageIdentificationLanguage,
  MLKitNaturalLanguageIdentificationOptions,
  MLKitNaturalLanguageIdentificationResult
} from "./index";

export function identifyNaturalLanguage(options: MLKitNaturalLanguageIdentificationOptions): Promise<MLKitNaturalLanguageIdentificationResult> {
  return new Promise((resolve, reject) => {
    try {
      if (!options.text) {
        reject("'text' property not set to a valid value");
        return;
      }

      const languageIdentifier: com.google.firebase.ml.naturallanguage.languageid.FirebaseLanguageIdentification =
          com.google.firebase.ml.naturallanguage.FirebaseNaturalLanguage.getInstance().getLanguageIdentification(
              new com.google.firebase.ml.naturallanguage.languageid.FirebaseLanguageIdentificationOptions.Builder()
                  .setConfidenceThreshold(options.confidenceThreshold || 0.5)
                  .build());

      languageIdentifier.identifyLanguage(options.text)
          .addOnSuccessListener(new (<any>com.google.android.gms).tasks.OnSuccessListener({
            onSuccess: languageCode => {
              if (languageCode && languageCode !== "und") {
                resolve({ languageCode })
              } else {
                resolve();
              }
            }
          }))
          .addOnFailureListener(new (<any>com.google.android.gms).tasks.OnFailureListener({
            onFailure: exception => reject(exception.getMessage())
          }));
    } catch (ex) {
      console.log("Error in firebase.mlkit.identifyNaturalLanguage: " + ex);
      reject(ex);
    }
  });
}

export function indentifyPossibleLanguages(options: MLKitNaturalLanguageIdentificationOptions): Promise<Array<MLKitNaturalLanguageIdentificationLanguage>> {
  return new Promise((resolve, reject) => {
    try {
      const languageIdentifier: com.google.firebase.ml.naturallanguage.languageid.FirebaseLanguageIdentification =
          com.google.firebase.ml.naturallanguage.FirebaseNaturalLanguage.getInstance().getLanguageIdentification(
              new com.google.firebase.ml.naturallanguage.languageid.FirebaseLanguageIdentificationOptions.Builder()
                  .setConfidenceThreshold(options.confidenceThreshold || 0.01)
                  .build());

      languageIdentifier.identifyPossibleLanguages(options.text)
          .addOnSuccessListener(new (<any>com.google.android.gms).tasks.OnSuccessListener({
            onSuccess: languages => {
              const langs: Array<MLKitNaturalLanguageIdentificationLanguage> = [];
              if (languages && languages.get(0).getLanguageCode() !== "und") { // und = undetermined
                for (let i = 0; i < languages.size(); i++) {
                  const l = languages.get(i);
                  langs.push({
                    languageCode: l.getLanguageCode(),
                    confidence: l.getConfidence()
                  })
                }
              }
              resolve(langs);
            }
          }))
          .addOnFailureListener(new (<any>com.google.android.gms).tasks.OnFailureListener({
            onFailure: exception => reject(exception.getMessage())
          }));
    } catch (ex) {
      console.log("Error in firebase.mlkit.indentifyPossibleLanguages: " + ex);
      reject(ex);
    }
  });
}


text:
package org.mbari.vars.ui.mediaplayers;

import org.mbari.vars.core.EventBus;
import org.mbari.vars.ui.UIToolBox;
import org.mbari.vars.ui.events.MediaChangedEvent;
import org.mbari.vars.ui.events.MediaControlsChangedEvent;
import org.mbari.vars.ui.events.MediaPlayerChangedEvent;
import org.mbari.vars.services.model.Media;

import mbarix4j.util.stream.StreamUtilities;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author Brian Schlining
 * @since 2017-08-07T10:50:00
 */
public class MediaPlayers {

    private final UIToolBox toolBox;
    private final Logger log = LoggerFactory.getLogger(getClass());
    private ServiceLoader<MediaControlsFactory> serviceLoader;
    private final Object lock = new byte[]{};

    public MediaPlayers(UIToolBox toolBox) {
        this.toolBox = toolBox;
        serviceLoader = ServiceLoader.load(MediaControlsFactory.class);
        EventBus eventBus = toolBox.getEventBus();
        eventBus.toObserverable()
                .ofType(MediaChangedEvent.class)
                .subscribe(e -> open(e.get()));

        // Convert MediaControlsChangedEvent to MediaPlayerChangedEvent so that I don't have
        // to change all prexisting usages
        eventBus.toObserverable()
                .ofType(MediaControlsChangedEvent.class)
                .subscribe(e -> {
                    eventBus.send(new MediaPlayerChangedEvent(MediaPlayers.this,
                                    e.get().getMediaPlayer()));
                });
        Runtime.getRuntime()
                .addShutdownHook(new Thread(this::close));
    }

    public List<SettingsPane> getSettingsPanes() {
        return StreamUtilities.toStream(serviceLoader.iterator())
                .map(MediaControlsFactory::getSettingsPane)
                .filter(Objects::nonNull)
                .collect(Collectors.toList());
    }

    private void open(Media media) {

        // Close the old one
        synchronized (lock) {
            close();

            try {
                StreamUtilities.toStream(serviceLoader.iterator())
                        .peek(factory -> log.debug("ServiceLoader found a factory: {}", factory))
                        .filter(factory -> factory.canOpen(media))
                        .peek(factory -> log.debug("ServiceLoader using a factory: {}", factory))
                        .findFirst()
                        .ifPresent(factory -> {
                            try {
                                var mediaControls = factory.safeOpen(media);
                                toolBox.getEventBus()
                                        .send(new MediaControlsChangedEvent(MediaPlayers.this,
                                                mediaControls));
                            } catch (Exception e) {
                                log.error("Unable to load services", e);
                                toolBox.getEventBus()
                                        .send(new MediaPlayerChangedEvent(null, null));
                            }
                        });

            } catch (ServiceConfigurationError e) {
                log.error("Unable to load services", e);
                toolBox.getEventBus()
                        .send(new MediaPlayerChangedEvent(null, null));
            }
        }
    }

    private void close() {
        // Close the old MediaPlayer
        log.debug("Closing MediaPlayer: " + toolBox.getMediaPlayer());
        Optional.ofNullable(toolBox.getMediaPlayer())
                .ifPresent(MediaPlayer::close);
    }
}


text:
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8>
<title>Test 509 Image element with role="presentation" but with aria-relevant="text"</title>
</head>
<body>
<img src="foo.jpg" alt="test1" width="40" height="40" role="presentation" aria-live="polite" aria-relevant="text"/>
</body>
</html>


text:
<!DOCTYPE html>

  <meta charset="utf-8">

  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <title>ansible.plugins.lookup.dig — Ansible 1 documentation</title>

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

    <link rel="top" title="Ansible 1 documentation" href="../../../../index.html"/>
        <link rel="up" title="ansible.plugins.lookup" href="../lookup.html"/>

             Ansible

                2.2

  <form id="rtd-search-form" class="wy-form" action="../../../../search.html" method="get">
    <input type="text" name="q" placeholder="Search docs" />
    <input type="hidden" name="check_keywords" value="yes" />
    <input type="hidden" name="area" value="default" />
  </form>

        Ansible

Docs »

Module code »

ansible.plugins »

ansible.plugins.lookup »

ansible.plugins.lookup.dig

Source code for ansible.plugins.lookup.dig

# (c) 2015, Jan-Piet Mens <jpmens(at)gmail.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible.  If not, see <http://www.gnu.org/licenses/>.
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type

from ansible.errors import AnsibleError
from ansible.plugins.lookup import LookupBase
import socket

try:
    import dns.resolver
    import dns.reversename
    from dns.rdatatype import (A, AAAA, CNAME, DLV, DNAME, DNSKEY, DS, HINFO, LOC,
            MX, NAPTR, NS, NSEC3PARAM, PTR, RP, SOA, SPF, SRV, SSHFP, TLSA, TXT)
    import dns.exception
    HAVE_DNS = True
except ImportError:
    HAVE_DNS = False

[docs]def make_rdata_dict(rdata):
    ''' While the 'dig' lookup plugin supports anything which dnspython supports
        out of the box, the following supported_types list describes which
        DNS query types we can convert to a dict.

        Note: adding support for RRSIG is hard work. :)
    '''
    supported_types = {
            A           : ['address'],
            AAAA        : ['address'],
            CNAME       : ['target'],
            DNAME       : ['target'],
            DLV         : ['algorithm', 'digest_type', 'key_tag', 'digest'],
            DNSKEY      : ['flags', 'algorithm', 'protocol', 'key'],
            DS          : ['algorithm', 'digest_type', 'key_tag', 'digest'],
            HINFO       : ['cpu', 'os'],
            LOC         : ['latitude', 'longitude', 'altitude', 'size', 'horizontal_precision', 'vertical_precision'],
            MX          : ['preference', 'exchange'],
            NAPTR       : ['order', 'preference', 'flags', 'service', 'regexp', 'replacement'],
            NS          : ['target'],
            NSEC3PARAM  : ['algorithm', 'flags', 'iterations', 'salt'],
            PTR         : ['target'],
            RP          : ['mbox', 'txt'],
            # RRSIG       : ['algorithm', 'labels', 'original_ttl', 'expiration', 'inception', 'signature'],
            SOA         : ['mname', 'rname', 'serial', 'refresh', 'retry', 'expire', 'minimum'],
            SPF         : ['strings'],
            SRV         : ['priority', 'weight', 'port', 'target'],
            SSHFP       : ['algorithm', 'fp_type', 'fingerprint'],
            TLSA        : ['usage', 'selector', 'mtype', 'cert'],
            TXT         : ['strings'],
        }

    rd = {}

    if rdata.rdtype in supported_types:
        fields = supported_types[rdata.rdtype]
        for f in fields:
            val     = rdata.__getattribute__(f)

            if type(val) == dns.name.Name:
                val = dns.name.Name.to_text(val)

            if rdata.rdtype == DLV and f == 'digest':
                val = dns.rdata._hexify(rdata.digest).replace(' ', '')
            if rdata.rdtype == DS and f == 'digest':
                val = dns.rdata._hexify(rdata.digest).replace(' ', '')
            if rdata.rdtype == DNSKEY and f == 'key':
                val = dns.rdata._base64ify(rdata.key).replace(' ', '')
            if rdata.rdtype == NSEC3PARAM and f == 'salt':
                val = dns.rdata._hexify(rdata.salt).replace(' ', '')
            if rdata.rdtype == SSHFP and f == 'fingerprint':
                val = dns.rdata._hexify(rdata.fingerprint).replace(' ', '')
            if rdata.rdtype == TLSA and f == 'cert':
                val = dns.rdata._hexify(rdata.cert).replace(' ', '')

            rd[f]   = val

    return rd

# ==============================================================
# dig: Lookup DNS records
#
# --------------------------------------------------------------

[docs]class LookupModule(LookupBase):

[docs]    def run(self, terms, variables=None, **kwargs):
        '''Terms contains a string with things to :command:`dig` for.

        The following formats are supported:

            ==============================================  ======
            Example                                         Note
            ==============================================  ======
            example.com                                     # A record
            example.com qtype=A                             # same
            example.com/TXT                                 # specific qtype
            example.com qtype=txt                           # same
            192.168.1.2/PTR                                 # reverse PTR
                                                              shortcut for 2.1.168.192.in-addr.arpa/PTR
            example.net/AAAA @nameserver                    # query specified server
                                                              can be comma-sep list of names/addresses

            ... flat=0                                      # returns a dict; default is 1 == string
            ==============================================  ======

        '''

        if HAVE_DNS == False:
            raise AnsibleError("Can't LOOKUP(dig): module dns.resolver is not installed")

        # Create Resolver object so that we can set NS if necessary
        myres = dns.resolver.Resolver()
        edns_size = 4096
        myres.use_edns(0, ednsflags=dns.flags.DO, payload=edns_size)

        domain = None
        qtype  = 'A'
        flat   = True

        for t in terms:
            if t.startswith('@'):       # e.g. "@10.0.1.2,192.168.1.1" is ok.
                nsset = t[1:].split(',')
                nameservers = []
                for ns in nsset:
                    # Check if we have a valid IP address. If so, use that, otherwise
                    # try to resolve name to address using system's resolver. If that
                    # fails we bail out.
                    try:
                        socket.inet_aton(ns)
                        nameservers.append(ns)
                    except:
                        try:
                            nsaddr = dns.resolver.query(ns)[0].address
                            nameservers.append(nsaddr)
                        except Exception as e:
                            raise AnsibleError("dns lookup NS: ", str(e))
                    myres.nameservers = nameservers
                continue
            if '=' in t:
                try:
                    opt, arg = t.split('=')
                except:
                    pass

                if opt == 'qtype':
                    qtype = arg.upper()
                elif opt == 'flat':
                    flat = int(arg)

                continue

            if '/' in t:
                try:
                    domain, qtype = t.split('/')
                except:
                    domain = t
            else:
                domain = t

        # print "--- domain = {0} qtype={1}".format(domain, qtype)

        ret = []

        if qtype.upper() == 'PTR':
            try:
                n = dns.reversename.from_address(domain)
                domain = n.to_text()
            except dns.exception.SyntaxError:
                pass
            except Exception as e:
                raise AnsibleError("dns.reversename unhandled exception", str(e))

        try:
            answers = myres.query(domain, qtype)
            for rdata in answers:
                s = rdata.to_text()
                if qtype.upper() == 'TXT':
                    s = s[1:-1]  # Strip outside quotes on TXT rdata

                if flat:
                    ret.append(s)
                else:
                    try:
                        rd = make_rdata_dict(rdata)
                        rd['owner']     = answers.canonical_name.to_text()
                        rd['type']      = dns.rdatatype.to_text(rdata.rdtype)
                        rd['ttl']       = answers.rrset.ttl

                        ret.append(rd)
                    except Exception as e:
                        ret.append(str(e))

        except dns.resolver.NXDOMAIN:
            ret.append('NXDOMAIN')
        except dns.resolver.NoAnswer:
            ret.append("")
        except dns.resolver.Timeout:
            ret.append('')
        except dns.exception.DNSException as e:
            raise AnsibleError("dns.resolver unhandled exception", e)

        return ret

        © Copyright 2016, Red Hat.

  Built with Sphinx using a theme provided by Read the Docs.


text:
using Microsoft.Xna.Framework;

namespace MenuBuddy
{
	/// <summary>
	/// This is just a list of items that are on the screen.
	/// The user has to take care of placing them etc.
	/// </summary>
	public class AbsoluteLayout : Layout, IScalable
	{
		#region Properties

		protected Vector2 _size;

		/// <summary>
		/// Whenever the rect changes on this layout, the old rect is stored here so can get a delta.
		/// </summary>
		private Rectangle PreviousRect
		{
			get; set;
		}

		public virtual Vector2 Size
		{
			get
			{
				return _size;
			}
			set
			{
				SetPrevRect();
				_size = value;
				UpdateItems();
			}
		}

		public override Point Position
		{
			get
			{
				return base.Position;
			}
			set
			{
				SetPrevRect();
				base.Position = value;
				UpdateItems();
			}
		}

		public override HorizontalAlignment Horizontal
		{
			get
			{
				return base.Horizontal;
			}
			set
			{
				if (base.Horizontal != value)
				{
					SetPrevRect();
					base.Horizontal = value;
					UpdateItems();
				}
			}
		}

		public override VerticalAlignment Vertical
		{
			get
			{
				return base.Vertical;
			}
			set
			{
				if (base.Vertical != value)
				{
					SetPrevRect();
					base.Vertical = value;
					UpdateItems();
				}
			}
		}

		public override float Scale
		{
			get
			{
				return base.Scale;
			}
			set
			{
				base.Scale = value;
			}
		}

		public override Rectangle Rect
		{
			get
			{
				return CalculateRect();
			}
		}

		#endregion //Properties

		#region Init

		public AbsoluteLayout()
		{
		}

		public AbsoluteLayout(AbsoluteLayout inst) : base(inst)
		{
			_size = new Vector2(inst._size.X, inst._size.Y);
			PreviousRect = inst.PreviousRect;
		}

		public override IScreenItem DeepCopy()
		{
			return new AbsoluteLayout(this);
		}

		#endregion //Init

		#region Methods

		/// <summary>
		/// Set the position of the item as store it
		/// </summary>
		/// <param name="item"></param>
		public override void AddItem(IScreenItem item)
		{
			SetItemPosition(item, CalculateRect());

			//store the new item
			Items.Add(item);
			Sort();
		}

		private void SetPrevRect()
		{
			PreviousRect = CalculateRect();
		}

		protected virtual Rectangle CalculateRect()
		{
			var pos = Position;

			switch (Horizontal)
			{
				case HorizontalAlignment.Center: { pos.X -= (int)(Size.X / 2f); } break;
				case HorizontalAlignment.Right: { pos.X -= (int)Size.X; } break;
			}

			switch (Vertical)
			{
				case VerticalAlignment.Center: { pos.Y -= (int)(Size.Y / 2f); } break;
				case VerticalAlignment.Bottom: { pos.Y -= (int)Size.Y; } break;
			}

			return new Rectangle(pos.X, pos.Y, (int)Size.X, (int)Size.Y);
		}

		protected virtual void UpdateItems()
		{
			//Grab the rect for this layout
			var rect = CalculateRect();

			//update the positions of all the current widgets
			foreach (var item in Items)
			{
				UpdateItemPosition(item, rect);
			}
		}

		/// <summary>
		/// Set the position of a widget to be relative to this layout
		/// </summary>
		/// <param name="item"></param>
		protected virtual void UpdateItemPosition(IScreenItem item, Rectangle rect)
		{
			//Get the delta position
			var delta = PreviousRect.Location - rect.Location;

			//add the delt to the current position
			item.Position -= delta;
		}

		/// <summary>
		/// Set the position of a widget to be relative to this layout
		/// </summary>
		/// <param name="item"></param>
		protected virtual void SetItemPosition(IScreenItem item, Rectangle rect)
		{
			//add the position of the layout to the item
			item.Position += rect.Location;
		}

		#endregion //Methods
	}
}