text:
[![Docker Repository on Quay.io](https://quay.io/repository/ahaasler/jira/status "Docker Repository on Quay.io")](https://quay.io/repository/ahaasler/jira)
[![Release](https://img.shields.io/github/release/ahaasler/docker-jira.svg?style=flat)](https://github.com/ahaasler/docker-jira/releases/latest)

## Features

* Runs on a production ready *OpenJDK* 8 - [Zulu](http://www.azulsystems.com/products/zulu "Zulu: Multi-platform Certified OpenJDK") by Azul Systems.
* Ready to be configured with *Nginx* as a reverse proxy (https available).
* Built on top of *Debian* for a minimal image size.

## Usage

```bash
docker run -d -p 8080:8080 ahaasler/jira
```

### Parameters

You can use this parameters to configure your jira instance:

* **-s:** Enables the connector security and sets `https` as connector scheme.
* **-n <proxyName>:** Sets the connector proxy name.
* **-p <proxyPort>:** Sets the connector proxy port.
* **-c <contextPath>:** Sets the context path (do not write the initial /).

This parameters should be given to the entrypoint (passing them after the image):

```bash
docker run -d -p 8080:8080 ahaasler/jira <parameters>
```

> If you want to execute another command instead of launching jira you should overwrite the entrypoint with `--entrypoint <command>` (docker run parameter).

### Nginx as reverse proxy

Lets say you have the following *nginx* configuration for jira:

```
server {
	listen                          80;
	server_name                     example.com;
	return                          301 https://$host$request_uri;
}
server {
	listen                          443;
	server_name                     example.com;

	ssl                             on;
	ssl_certificate                 /path/to/certificate.crt;
	ssl_certificate_key             /path/to/key.key;
	location /jira {
		proxy_set_header X-Forwarded-Host $host;
		proxy_set_header X-Forwarded-Server $host;
		proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
		proxy_pass http://127.0.0.1:8080;
		proxy_redirect off;
	}
}
```

> This is only an example, please secure you *nginx* better.

For that configuration you should run your jira container with:

```bash
docker run -d -p 8080:8080 ahaasler/jira -s -n example.com -p 443 -c jira
```

### Persistent data

The jira home is set to `/data/jira`. If you want to persist your data you should use a data volume for `/data/jira`.

#### Binding a host directory

```bash
docker run -d -p 8080:8080 -v /home/user/jira-data:/data/jira ahaasler/jira
```

Make sure that the jira user (with id 547) has read/write/execute permissions.

If security is important follow the Atlassian recommendation:

> Ensure that only the user running Jira can access the Jira home directory, and that this user has read, write and execute permissions, by setting file system permissions appropriately for your operating system.

#### Using a data-only container

1. Create the data-only container and set proper permissions:

	* **Lazy way (preferred)** - Using [docker-jira-data](https://github.com/ahaasler/docker-jira-data "A data-only container for docker-jira"):

		```bash
docker run --name jira-data ahaasler/jira-data
		```

	* *I-wan't-to-know-what-I'm-doing* way:

		```bash
docker run --name jira-data -v /data/jira busybox true
docker run --rm -it --volumes-from jira-data debian bash
		```

		The last command will open a *debian* container. Execute this inside that container:

		```bash
chown 547:root /data/jira; chmod 770 /data/jira; exit;
		```

2. Use it in the jira container:

	```bash
docker run --name jira --volumes-from jira-data -d -p 8080:8080 ahaasler/jira
	```

### PostgreSQL external database

A great way to connect your Jira instance with a PostgreSQL database is
using the [docker-jira-postgres](https://github.com/ahaasler/docker-jira-postgres "A PostgreSQL container for docker-jira")
image.

1. Create and name the database container:

	```bash
docker run --name jira-postgres -d ahaasler/jira-postgres
	```

2. Use it in the Jira container:

	```bash
docker run --name jira --link jira-postgres:jira-postgres -d -p 8080:8080 ahaasler/jira
	```

3. Connect your Jira instance following the Atlassian documentation:
[Configure your JIRA server to connect to your PostgreSQL database](https://confluence.atlassian.com/display/JIRA/Connecting+JIRA+to+PostgreSQL#ConnectingJIRAtoPostgreSQL-3.ConfigureyourJIRAservertoconnecttoyourPostgreSQLdatabase "Configure your JIRA server to connect to your PostgreSQL database").

>  See [docker-jira-postgres](https://github.com/ahaasler/docker-jira-postgres "A PostgreSQL container for docker-jira")
for more information and configuration options.

## Thanks

* [Docker](https://www.docker.com/ "Docker") for this amazing container engine.
* [PostgreSQL](http://www.postgresql.org/) for this advanced database.
* [Atlassian](https://www.atlassian.com/ "Atlassian") for making great products. Also for their work on [atlassian-docker](https://bitbucket.org/atlassianlabs/atlassian-docker "atlassian-docker repo") which inspired this.
* [Azul Systems](http://www.azulsystems.com/ "Azul Systems") for their *OpenJDK* docker base image.
* And specially to you and the entire community.

## License

This image is licensed under the Apache License, Version 2.0. See [LICENSE](LICENSE) for the full license text.


text:
<?php
/**
 * This is a Anax pagecontroller.
 *
 */
// Include the essential config-file which also creates the $swe variable with its defaults.
include(__DIR__.'/config.php');

// Do it and store it all in variables in the Anax container.
$swe['title'] = "404";
$swe['header'] = "";
$swe['main'] = "This is a Anax 404. Document is not here.";
$swe['footer'] = "";

// Send the 404 header
header("HTTP/1.0 404 Not Found");

// Finally, leave it all to the rendering phase of Anax.
include(ANAX_THEME_PATH);

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;
using System.ComponentModel.Design;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using EnvDTE;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Design;
using Microsoft.VisualStudio.Shell.Interop;
using NuPattern.VisualStudio.Properties;
using NuPattern.VisualStudio.Solution.Hierarchy;
using VSLangProj;
using Ole = Microsoft.VisualStudio.OLE.Interop;

namespace NuPattern.VisualStudio.Solution
{
    /// <summary>
    /// Provides usability methods for working with <see cref="ISolution"/>.
    /// </summary>
    public static class SolutionExtensions
    {
        /// <summary>
        /// Name of the Solutions Items folder
        /// </summary>
        public const string SolutionItemsFolderName = "Solution Items";

        /// <summary>
        /// Selects the items.
        /// </summary>
        /// <param name="solution">The solution.</param>
        /// <param name="items">The items.</param>
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "solution"), CLSCompliant(false)]
        public static void SelectItems(this ISolution solution, IEnumerable<IItemContainer> items)
        {
            Select(items.Select(item => item.As<IHierarchyNode>()));
        }

        /// <summary>
        /// Finds an existing container at the given path, or creates it.
        /// </summary>
        /// <param name="parent">The parent to start the find from.</param>
        /// <param name="pathExpression">The path to find or create.</param>
        /// <returns>Typically, a <see cref="IFolder"/> or <see cref="ISolutionFolder"/> matching the expression.</returns>
        [CLSCompliant(false)]
        public static IItemContainer FindOrCreate(this IItemContainer parent, string pathExpression)
        {
            Guard.NotNull(() => parent, parent);

            // If no path, we mean the parent.
            if ((string.IsNullOrEmpty(pathExpression)) ||
                (pathExpression.Equals(Path.DirectorySeparatorChar.ToString(), StringComparison.OrdinalIgnoreCase)))
            {
                return parent;
            }

            var targetContainer = parent.Find(pathExpression).FirstOrDefault();
            if (targetContainer != null)
            {
                return targetContainer;
            }

            var paths = pathExpression.Split(new[] { Path.DirectorySeparatorChar }, StringSplitOptions.RemoveEmptyEntries);
            var pathSeparator = Path.DirectorySeparatorChar.ToString();

            for (int targetPathIndex = paths.Length - 1; targetPathIndex >= 0; targetPathIndex--)
            {
                var currentPath = string.Join(pathSeparator, paths.Take(targetPathIndex));
                // When we have an empty path, we have reached the topmost "path" which is the received parent itself.
                targetContainer = currentPath.Length > 0 ? parent.Find(currentPath).FirstOrDefault() : parent;

                if (targetContainer != null)
                {
                    if (targetContainer.Kind == ItemKind.Project)
                    {
                        return CreateFolderPath(
                            ((IProject)targetContainer).CreateFolder(paths[targetPathIndex]),
                            string.Join(pathSeparator, paths.Skip(targetPathIndex + 1)));
                    }
                    else if (targetContainer.Kind == ItemKind.Folder)
                    {
                        return CreateFolderPath(
                            (IFolder)targetContainer,
                            string.Join(pathSeparator, paths.Skip(targetPathIndex)));
                    }
                    else if (targetContainer.Kind == ItemKind.Solution)
                    {
                        return CreateFolderPath(
                            ((ISolution)targetContainer).CreateSolutionFolder(paths[targetPathIndex]),
                            string.Join(pathSeparator, paths.Skip(targetPathIndex + 1)));
                    }
                    else if (targetContainer.Kind == ItemKind.SolutionFolder)
                    {
                        return CreateFolderPath(
                            (ISolutionFolder)targetContainer,
                            string.Join(pathSeparator, paths.Skip(targetPathIndex)));
                    }
                    else
                    {
                        throw new NotSupportedException(string.Format(
                            CultureInfo.CurrentCulture,
                            Resources.SolutionExtensions_InvalidFolderPath,
                            targetContainer.Kind,
                            currentPath,
                            pathExpression));
                    }
                }
            }

            if (targetContainer == null)
            {
                throw new NotSupportedException(string.Format(
                    CultureInfo.CurrentCulture,
                    Resources.SolutionExtensions_CouldNotFindOrCreate,
                    pathExpression));
            }

            return targetContainer;
        }

        private static IFolder CreateFolderPath(IFolder rootFolder, string folderPath)
        {
            var paths = folderPath.Split(new[] { Path.DirectorySeparatorChar }, StringSplitOptions.RemoveEmptyEntries);
            foreach (var path in paths)
            {
                rootFolder = rootFolder.CreateFolder(path);
            }

            return rootFolder;
        }

        private static ISolutionFolder CreateFolderPath(ISolutionFolder rootFolder, string folderPath)
        {
            var paths = folderPath.Split(new[] { Path.DirectorySeparatorChar }, StringSplitOptions.RemoveEmptyEntries);
            foreach (var path in paths)
            {
                rootFolder = rootFolder.CreateSolutionFolder(path);
            }

            return rootFolder;
        }

        /// <summary>
        /// Gets the available types for the given project, included declared types as well
        /// as types from referenced assemblies or projects that inherit or implement
        /// the given interface.
        /// </summary>
        [CLSCompliant(false)]
        public static IEnumerable<Type> GetAvailableTypes(this IProject project, Type baseType)
        {
            var vsProject = project.As<Project>();
            if (vsProject == null)
            {
                throw new ArgumentException(Resources.SolutionExtensions_UnsupportedProject, "project");
            }

            var provider = new ServiceProvider(vsProject.DTE as Microsoft.VisualStudio.OLE.Interop.IServiceProvider);
            var dynamicTypes = provider.GetService<DynamicTypeService>();
            if (dynamicTypes == null)
            {
                throw new InvalidOperationException(string.Format(
                    CultureInfo.CurrentCulture,
                    Resources.SolutionExtensions_MissingService,
                    typeof(DynamicTypeService).FullName));
            }

            var hierarchy = project.As<IVsHierarchy>();
            var typeDiscovery = dynamicTypes.GetTypeDiscoveryService(hierarchy);
            var availableTypes = typeDiscovery.GetTypes(typeof(object), false);
            var targetType = baseType.AssemblyQualifiedName;

            foreach (Type type in availableTypes)
            {
                if (type.Traverse(t => t.BaseType, t => t.AssemblyQualifiedName == targetType) != null)
                {
                    yield return type;
                }

                if (type.GetInterfaces().FirstOrDefault(t => t.AssemblyQualifiedName == targetType) != null)
                {
                    yield return type;
                }
            }
        }

        /// <summary>
        /// Creates a folder structure.
        /// </summary>
        /// <param name="project">The project to add the folder structure.</param>
        /// <param name="folderPath">The folder path to create.</param>
        /// <returns>A reference to the last folder in the tree.</returns>
        [CLSCompliant(false)]
        public static IFolder CreateFolderPath(this IProject project, string folderPath)
        {
            Guard.NotNull(() => project, project);
            Guard.NotNullOrEmpty(() => folderPath, folderPath);

            if (project.Find<IFolder>(folderPath).Any())
            {
                throw new InvalidOperationException(string.Format(
                    CultureInfo.CurrentCulture,
                    Resources.SolutionExtensions_FolderPathAlreadyExists,
                    folderPath));
            }

            return (IFolder)project.FindOrCreate(folderPath);
        }

        /// <summary>
        /// Creates a new solution at the given destination with the given name.
        /// </summary>
        [CLSCompliant(false)]
        public static void CreateInstance(this ISolution solution, string destination, string name)
        {
            Guard.NotNull(() => solution, solution);
            Guard.NotNullOrEmpty(() => destination, destination);
            Guard.NotNullOrEmpty(() => name, name);

            solution.As<EnvDTE.Solution>().Create(destination, name);
        }

        /// <summary>
        /// Gets the selected items that match the given type. This method, unlike the built-in <see cref="IItemContainerExtensions.GetSelection"/>
        /// works over mocked or faked solutions by taking the <see cref="IItemContainer.IsSelected"/> property into account
        /// when the solution is not a DTE solution.
        /// </summary>
        [CLSCompliant(false)]
        public static IEnumerable<T> GetSelectedItems<T>(this ISolution solution) where T : IItemContainer
        {
            Guard.NotNull(() => solution, solution);

            if (solution.As<EnvDTE.Solution>() != null)
                return solution.GetSelection<T>();
            else
                return solution
                .Traverse()
                .Concat(new[] { solution })
                .Where(item => item.IsSelected)
                .OfType<T>();
        }

        /// <summary>
        /// Gets the selected items. This method, unlike the built-in <see cref="IItemContainerExtensions.GetSelection"/>
        /// works over mocked or faked solutions by taking the <see cref="IItemContainer.IsSelected"/> property into account
        /// when the solution is not a DTE solution.
        /// </summary>
        [CLSCompliant(false)]
        public static IEnumerable<IItemContainer> GetSelectedItems(this ISolution solution)
        {
            Guard.NotNull(() => solution, solution);

            if (solution.As<EnvDTE.Solution>() != null)
                return solution.GetSelection();
            else
                return solution
                .Traverse()
                .Concat(new[] { solution })
                .Where(item => item.IsSelected);
        }

        /// <summary>
        /// Opens the given item in its default view.
        /// </summary>
        [CLSCompliant(false)]
        public static void Open(this IItem item)
        {
            Guard.NotNull(() => item, item);

            var projectItem = item.As<EnvDTE.ProjectItem>();
            if (projectItem != null)
            {
                var window = projectItem.Open(EnvDTE.Constants.vsViewKindPrimary);
                if (window != null)
                {
                    window.Activate();
                }
            }
        }

        /// <summary>
        /// Renames the given item, project or folder.
        /// </summary>
        /// <param name="item">Item to rename</param>
        /// <param name="proposedItemName">The proposed new name for the item.</param>
        /// <param name="ensureUniqueness">Whether to ensure that the new name for the item is unique within the containing parent, and if not find the next nearest unique name.</param>
        /// <param name="uiService">A UI Service to use to prompt the user if the new name requires uniqueness.</param>
        /// <returns>The actual re-named name of the item.</returns>
        [CLSCompliant(false)]
        public static string Rename(this IItemContainer item, string proposedItemName, bool ensureUniqueness = false, IVsUIShell uiService = null)
        {
            Guard.NotNull(() => item, item);
            Guard.NotNullOrEmpty(() => proposedItemName, proposedItemName);

            // Ensure new name is cleaned (i.e. valid solution name)
            var newItemName = proposedItemName;
            if (!DataFormats.IsValidSolutionItemName(proposedItemName))
            {
                newItemName = DataFormats.MakeValidSolutionItemName(proposedItemName);
            }

            // Ensure rename required
            if (newItemName.Equals(item.Name, StringComparison.OrdinalIgnoreCase))
            {
                return newItemName;
            }

            // If Item, then ensure the new name has an extension (borrowed from existing).
            if (item is IItem)
            {
                var proposedExtension = Path.GetExtension(proposedItemName);
                if (string.IsNullOrEmpty(proposedExtension))
                {
                    var existingExtension = Path.GetExtension(item.Name);
                    if (!string.IsNullOrEmpty(existingExtension))
                    {
                        newItemName = Path.ChangeExtension(newItemName, existingExtension);
                    }
                }
            }

            // Check to see if new named item already exists (within parent)
            bool newNamedItemExists =
                (item.Parent.Items.Where(i => i.Name.Equals(newItemName, StringComparison.OrdinalIgnoreCase)).FirstOrDefault() != null);
            if (newNamedItemExists)
            {
                if (ensureUniqueness)
                {
                    // Calculate new unique name
                    var uniqueItemName = string.Empty;
                    uniqueItemName = (item is IItem) ? item.Parent.CalculateNextUniqueChildItemName<IItem>(newItemName) : uniqueItemName;
                    uniqueItemName = (item is IProject) ? item.Parent.CalculateNextUniqueChildItemName<IProject>(newItemName) : uniqueItemName;
                    if (string.IsNullOrEmpty(uniqueItemName))
                    {
                        throw new InvalidOperationException(
                            string.Format(CultureInfo.CurrentCulture, Resources.SolutionExtensions_ErrorRenameUnknownType, item.Kind));
                    }

                    // Prompt user interactively
                    if (newNamedItemExists)
                    {
                        if (uiService != null)
                        {
                            uiService.ShowWarning(Resources.SolutionExtensions_PromptItemAlreadyExists_Title,
                                string.Format(CultureInfo.CurrentCulture,
                                Resources.SolutionExtensions_PromptItemAlreadyExists_Message, newItemName, uniqueItemName));
                        }
                    }

                    newItemName = uniqueItemName;
                }
                else
                {
                    throw new InvalidOperationException(
                        string.Format(CultureInfo.CurrentCulture, Resources.SolutionExtensions_ErrorRenamedItemExists, newItemName));
                }
            }

            // Rename item
            if (item is IItem || item is IFolder)
            {
                var vsItem = item.As<ProjectItem>();
                if (vsItem != null)
                {
                    vsItem.Name = newItemName;
                }
            }

            // Rename project
            var project = item as IProject;
            if (project != null)
            {
                var vsProject = project.As<Project>();
                if (vsProject != null)
                {
                    // Rename project Name
                    vsProject.Name = newItemName;

                    // Rename AssemblyName
                    if (project.Data != null)
                    {
                        if (project.Data.AssemblyName != null)
                        {
                            var assemblyName = project.Data.AssemblyName as string;

                            if (assemblyName.IndexOf(project.Name, StringComparison.OrdinalIgnoreCase) >= 0)
                            {
                                project.Data.AssemblyName = assemblyName.Replace(project.Name, newItemName);
                            }
                        }

                        // Rename Rootnamespace
                        if (project.Data.DefaultNamespace != null)
                        {
                            var defaultNamespace = project.Data.DefaultNamespace as string;

                            if (defaultNamespace.IndexOf(project.Name, StringComparison.OrdinalIgnoreCase) >= 0)
                            {
                                project.Data.DefaultNamespace = defaultNamespace.Replace(project.Name, newItemName);
                            }
                        }
                    }
                }
            }

            return newItemName;
        }

        /// <summary>
        /// Saves the given item.
        /// </summary>
        [CLSCompliant(false)]
        public static void Save(this IItem item)
        {
            Guard.NotNull(() => item, item);

            item.As<ProjectItem>().Save();
        }

        /// <summary>
        /// Checks out the item, if cource controlled.
        /// </summary>
        /// <param name="item"></param>
        [CLSCompliant(false)]
        public static void Checkout(this IItem item)
        {
            Guard.NotNull(() => item, item);

            VsHelper.CheckOut(item.PhysicalPath);
        }

        /// <summary>
        /// Deletes the given item.
        /// </summary>
        [CLSCompliant(false)]
        public static void Delete(this IItem item)
        {
            Guard.NotNull(() => item, item);

            item.As<EnvDTE.ProjectItem>().Delete();
        }

        /// <summary>
        /// Deletes the given project.
        /// </summary>
        [CLSCompliant(false)]
        public static void Delete(this IProject project)
        {
            Guard.NotNull(() => project, project);

            project.As<EnvDTE.Project>().Delete();
        }

        /// <summary>
        /// Deletes the given folder.
        /// </summary>
        [CLSCompliant(false)]
        public static void Delete(this IFolder folder)
        {
            Guard.NotNull(() => folder, folder);

            folder.As<EnvDTE.ProjectItem>().Delete();
        }

        /// <summary>
        /// Deletes the given folder.
        /// </summary>
        [CLSCompliant(false)]
        public static void Delete(this ISolutionFolder folder)
        {
            Guard.NotNull(() => folder, folder);

            var project = folder.As<EnvDTE.Project>();
            if (project != null)
            {
                var solutionFolder = project.Object as EnvDTE80.SolutionFolder;
                if (solutionFolder != null)
                {
                    project.Delete();
                }
            }
        }

        /// <summary>
        /// Deletes the given container.
        /// </summary>
        [CLSCompliant(false)]
        public static void Delete(this IItemContainer itemContainer)
        {
            Guard.NotNull(() => itemContainer, itemContainer);

            var item = itemContainer as IItem;
            if (item != null)
            {
                item.Delete();
                return;
            }
            var project = itemContainer as IProject;
            if (project != null)
            {
                project.Delete();
                return;
            }
            var projectFolder = itemContainer as IFolder;
            if (projectFolder != null)
            {
                projectFolder.Delete();
                return;
            }
            var solutionFolder = itemContainer as ISolutionFolder;
            if (solutionFolder != null)
            {
                solutionFolder.Delete();
                return;
            }
            var solution = itemContainer as ISolution;
            if (solution != null)
            {
                //Do Nothing, cannot be deleted.
                return;
            }
        }

        /// <summary>
        /// Opens the specified solution.
        /// </summary>
        [CLSCompliant(false)]
        public static void Open(this ISolution solution, string solutionFile)
        {
            Guard.NotNull(() => solution, solution);
            Guard.NotNullOrEmpty(() => solutionFile, solutionFile);

            solution.As<EnvDTE.Solution>().Open(solutionFile);
        }

        /// <summary>
        /// Closes the solution, optionally saving first.
        /// </summary>
        [SuppressMessage("Microsoft.Design", "CA1026:DefaultParametersShouldNotBeUsed")]
        [CLSCompliant(false)]
        public static void Close(this ISolution solution, bool saveFirst = true)
        {
            Guard.NotNull(() => solution, solution);

            if (solution.IsOpen)
            {
                solution.As<EnvDTE.Solution>().Close(saveFirst);
            }
        }

        /// <summary>
        /// Saves the solution.
        /// </summary>
        [CLSCompliant(false)]
        public static void SaveAs(this ISolution solution, string fileName)
        {
            Guard.NotNull(() => solution, solution);

            var dteSolution = solution.As<EnvDTE.Solution>();
            if (dteSolution != null && !dteSolution.Saved)
            {
                dteSolution.SaveAs(fileName);
            }
        }

        /// <summary>
        /// Shows the Solution Explorer window.
        /// </summary>
        /// <param name="solution"></param>
        [CLSCompliant(false)]
        public static void ShowSolutionExplorer(this ISolution solution)
        {
            Guard.NotNull(() => solution, solution);

            var vsSolution = solution.As<EnvDTE.Solution>();
            if (vsSolution != null)
            {
                var dte = vsSolution.DTE;
                if (dte != null)
                {
                    using (var provider = new ServiceProvider(dte as Ole.IServiceProvider))
                    {
                        var service = provider.GetService<IVsUIShell>();
                        if (service != null)
                        {
                            var solutionExplorer = StandardToolWindows.ProjectExplorer;
                            IVsWindowFrame frame;
                            Microsoft.VisualStudio.ErrorHandler.ThrowOnFailure(service.FindToolWindow((uint)__VSFINDTOOLWIN.FTW_fForceCreate, ref solutionExplorer, out frame));
                            if (frame != null)
                            {
                                Microsoft.VisualStudio.ErrorHandler.ThrowOnFailure(frame.Show());
                            }
                        }
                    }
                }
            }
        }

        /// <summary>
        /// Gets the logical path from this item to the given item.
        /// </summary>
        [CLSCompliant(false)]
        public static string GetLogicalPath(this IItemContainer item, IItemContainer ancestor)
        {
            var itemPath = item.GetLogicalPath();
            var ancestorPath = ancestor.GetLogicalPath();

            //Ensure the ancestor is valid
            if (itemPath.StartsWith(ancestorPath, StringComparison.OrdinalIgnoreCase))
            {
                return itemPath.Substring(ancestorPath.Length + 1);
            }

            // not related to ancestor
            return itemPath;
        }

        /// <summary>
        /// Adds a unique identifier to the given item, if not already exists.
        /// </summary>
        [CLSCompliant(false)]
        public static void AddItemIdentifier(this IItem item)
        {
            Guard.NotNull(() => item, item);

            // Ensure item is in a project (cant set MSBUILD properties on a solution item)
            var project = item.GetContainingProject();
            if (project != null)
            {
                // Prepare item for resilient identifier
                if (String.IsNullOrEmpty(item.Data.ItemGuid))
                {
                    // Add guid (in form: 000000000000-0000-0000-0000-00000000)
                    item.Data.ItemGuid = Guid.NewGuid().ToString("D");
                }
            }
        }

        private static object GetObject(SelectedItem selected)
        {
            if (selected.ProjectItem != null)
            {
                return selected.ProjectItem;
            }
            else if (selected.Project != null)
            {
                if (selected.Project.Object != null)
                {
                    return selected.Project.Object;
                }

                return selected.Project;
            }

            return selected.Collection.Cast<object>().FirstOrDefault();
        }

        /// <summary>
        /// Gets the toolkit manifest of the project where the given element is contained.
        /// </summary>
        /// <exception cref="ArgumentException">The given element is not contained in a project or
        /// the containing project does not contain an item marked with the
        /// <see cref="Constants.IsToolkitManifestItemMetadata"/> metadata flag.</exception>
        [CLSCompliant(false)]
        public static IItem GetToolkitManifest(this IItemContainer element)
        {
            Guard.NotNull(() => element, element);

            var owningProject = (IProject)element.Traverse(x => x.Parent, item => item.Kind == ItemKind.Project);
            if (owningProject == null)
            {
                throw new ArgumentException(string.Format(
                    CultureInfo.CurrentCulture,
                    Resources.SolutionExtensions_ItemNotInProject,
                    element.GetLogicalPath()));
            }

            return owningProject.GetToolkitManifest();
        }

        /// <summary>
        /// Gets the toolkit manifest of the given project.
        /// </summary>
        /// <exception cref="ArgumentException">The given project does not contain an item marked with the
        /// <see cref="Constants.IsToolkitManifestItemMetadata"/> metadata flag.</exception>
        [CLSCompliant(false)]
        public static IItem GetToolkitManifest(this IProject project)
        {
            Guard.NotNull(() => project, project);

            bool isManifest = false;
            var manifest = project.Traverse()
                .OfType<IItem>()
                .FirstOrDefault(item =>
                    item.Data.IsToolkitManifest != null &&
                    Boolean.TryParse(item.Data.IsToolkitManifest, out isManifest) &&
                    isManifest);

            if (manifest == null)
            {
                throw new ArgumentException(string.Format(
                    CultureInfo.CurrentCulture,
                    Resources.SolutionExtensions_NotToolkitProject,
                    project.GetLogicalPath(),
                    Constants.IsToolkitManifestItemMetadata));
            }

            return manifest;
        }

        /// <summary>
        /// Returns the name of the next non-existing child item of the given parent seeded with given name.
        /// </summary>
        /// <param name="parent">The parent container</param>
        /// <param name="childNameSeed">A name used to seed the name of the child.</param>
        /// <typeparam name="T">The type of the child items.</typeparam>
        /// <returns></returns>
        [CLSCompliant(false)]
        public static string CalculateNextUniqueChildItemName<T>(this IItemContainer parent, string childNameSeed) where T : IItemContainer
        {
            Guard.NotNull(() => parent, parent);
            Guard.NotNull(() => childNameSeed, childNameSeed);

            if ((typeof(T).IsAssignableFrom(typeof(ISolution)))
                || ((parent is IProject || parent is IItem || parent is IFolder) && typeof(T).IsAssignableFrom(typeof(ISolutionFolder)))
                || ((parent is IFolder || parent is IItem) && typeof(T).IsAssignableFrom(typeof(IProject)))
                || ((parent is ISolution || parent is ISolutionFolder || parent is IItem) && typeof(T).IsAssignableFrom(typeof(IFolder))))
            {
                throw new InvalidOperationException();
            }

            var extension = Path.GetExtension(childNameSeed);
            var seed = Path.GetFileNameWithoutExtension(childNameSeed);

            return String.Format(CultureInfo.CurrentCulture, @"{0}{1}",
                UniqueNameGenerator.EnsureUnique(seed,
                    newName => parent.Items.Where(item => String.IsNullOrEmpty(extension) ? item.Name.Equals(newName, StringComparison.OrdinalIgnoreCase)
                        : item.Name.Equals(Path.ChangeExtension(newName, extension), StringComparison.OrdinalIgnoreCase)).FirstOrDefault() == null), extension);
        }

        /// <summary>
        /// Runs the given command in the IDE.
        /// </summary>
        [CLSCompliant(false)]
        public static void RunCommand(this ISolution solution, string commandName)
        {
            Guard.NotNull(() => solution, solution);
            Guard.NotNull(() => commandName, commandName);

            var dteSolution = solution.As<EnvDTE.Solution>();
            if (dteSolution != null)
            {
                dteSolution.DTE.ExecuteCommand(commandName);
            }
        }

        /// <summary>
        /// Determines if the given container is the Solution Items folder of the solution.
        /// </summary>
        /// <param name="container"></param>
        /// <returns></returns>
        [CLSCompliant(false)]
        public static bool IsSolutionItemsFolder(this IItemContainer container)
        {
            return ((container is ISolutionFolder)
                && (container.Name.Equals(SolutionItemsFolderName, StringComparison.OrdinalIgnoreCase)));
        }

        /// <summary>
        /// Returns all the projects in a solution.
        /// </summary>
        /// <param name="solution"></param>
        /// <returns></returns>
        [CLSCompliant(false)]
        public static IEnumerable<IProject> GetAllProjects(this ISolution solution)
        {
            return solution.Find<IProject>();
        }

        /// <summary>
        /// Collapses all solution items in the solution.
        /// </summary>
        [CLSCompliant(false)]
        public static void CollapseAll(this ISolution solution, CollapseOptions options = CollapseOptions.All)
        {
            Guard.NotNull(() => solution, solution);

            EnvDTE.DTE dte = solution.As<EnvDTE.Solution>().DTE;
            dte.SuppressUI = true;
            try
            {
                var hier = dte.GetHierarchy();
                hier.UIHierarchyItems.Cast<EnvDTE.UIHierarchyItem>()
                            .ForEach(item =>
                            {
                                item.Collapse(options);
                            });
            }
            catch (COMException)
            {
                // Ignore exception
            }
            finally
            {
                dte.SuppressUI = false;
            }
        }

        /// <summary>
        /// Gets the nearest project to the currently selected item in the solution, or the first project in the solution.
        /// </summary>
        /// <remarks>
        /// If a project is currently selected, then that project is returned. If a file is currently opened, then its owning project is returned.
        /// Failing that the fall back is to return the first project in the solution (if any).
        /// </remarks>
        [CLSCompliant(false)]
        public static IProject GetCurrentProjectScope(this ISolution solution)
        {
            Guard.NotNull(() => solution, solution);

            var selection = ServiceProvider.GlobalProvider.GetService<SVsShellMonitorSelection, IVsMonitorSelectionFixed>();
            if (selection != null)
            {
                IVsHierarchy hierarchy;
                uint pitemid;
                IVsMultiItemSelect ppMIS;
                ISelectionContainer ppSC;

                if (selection.GetCurrentSelection(out hierarchy, out pitemid, out ppMIS, out ppSC) == Microsoft.VisualStudio.VSConstants.S_OK)
                {
                    if (hierarchy != null)
                    {
                        var project = hierarchy.ToProject();
                        if (project != null)
                        {
                            return solution.Find<IProject>(p => p.As<EnvDTE.Project>() == project).FirstOrDefault();
                        }
                    }
                }
            }

            // Use first project in the solution
            return solution.Find<IProject>().FirstOrDefault();
        }

        /// <summary>
        /// Gets the assembly references of the project
        /// </summary>
        [CLSCompliant(false)]
        public static IEnumerable<IAssemblyReference> GetAssemblyReferences(this IProject project)
        {
            Guard.NotNull(() => project, project);

            var references = new List<AssemblyReference>();

            var dteProject = project.As<EnvDTE.Project>();
            if (dteProject != null)
            {
                var vslangProject = dteProject.Object as VSProject;
                if (vslangProject != null)
                {
                    vslangProject.References.Cast<VSLangProj.Reference>()
                        .ForEach(r =>
                            {
                                if (!String.IsNullOrEmpty(r.Path))
                                {
                                    references.Add(new AssemblyReference(r.Name, r.Path));
                                }
                            });
                }
            }
            return references;
        }

        /// <summary>
        /// Determines of the two <see cref="IItemContainer"/> instances are the same solution item.
        /// </summary>
        [CLSCompliant(false)]
        public static bool Equals(this IItemContainer x, IItemContainer y)
        {
            if (x == null || y == null)
            {
                return false;
            }

            return x.PhysicalPath.Equals(y.PhysicalPath, StringComparison.OrdinalIgnoreCase);
        }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1806:DoNotIgnoreMethodResults", MessageId = "Microsoft.VisualStudio.Shell.Interop.IVsUIHierarchyWindow.ExpandItem(Microsoft.VisualStudio.Shell.Interop.IVsUIHierarchy,System.UInt32,Microsoft.VisualStudio.Shell.Interop.EXPANDFLAGS)"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1806:DoNotIgnoreMethodResults", MessageId = "Microsoft.VisualStudio.Shell.Interop.IVsWindowFrame.Show")]
        private static void Select(IEnumerable<IHierarchyNode> hierarchyNodes)
        {
            IVsWindowFrame frame;
            object obj2;
            var service = ServiceProvider.GlobalProvider.GetService<SVsUIShell, IVsUIShell>();

            if (service != null)
            {
                var rguidPersistenceSlot = new Guid(EnvDTE.Constants.vsWindowKindSolutionExplorer);
                Microsoft.VisualStudio.ErrorHandler.ThrowOnFailure(service.FindToolWindow(0x80000, ref rguidPersistenceSlot, out frame));
                Microsoft.VisualStudio.ErrorHandler.ThrowOnFailure(frame.GetProperty((int)__VSFPROPID.VSFPROPID_DocView, out obj2));
                bool flag = true;
                var window = obj2 as IVsUIHierarchyWindow;

                if (window != null)
                {
                    foreach (IHierarchyNode node in hierarchyNodes)
                    {
                        window.ExpandItem(node.GetObject<IVsHierarchy>() as IVsUIHierarchy, node.ItemId, flag ? EXPANDFLAGS.EXPF_SelectItem : EXPANDFLAGS.EXPF_AddSelectItem);

                        if (flag)
                        {
                            flag = false;
                        }
                    }
                }

                frame.Show();
            }
        }

        /// <summary>
        /// Returns the path to the given installed template
        /// </summary>
        public static string GetTemplatePath(this ISolution solution, string name, string category)
        {
            Guard.NotNull(() => solution, solution);
            Guard.NotNullOrEmpty(() => name, name);
            Guard.NotNullOrEmpty(() => category, category);

            var solution2 = solution.As<EnvDTE80.Solution2>();
            if (solution2 != null)
            {
                return solution2.GetProjectTemplate(name, category);
            }

            return null;
        }

        /// <summary>
        /// Selects the root of the solution
        /// </summary>
        /// <remarks>
        /// There is an issue in all versions of VS up to and including VS2008 SP1
        /// that won't allow the expansion of a multi-project template unless the Solution node in the Solution explorer
        /// is selected.  The code below works for any solution with less than 100,000 items
        /// </remarks>
        public static void SelectUp(this ISolution solution)
        {
            EnvDTE80.DTE2 dte2 = (EnvDTE80.DTE2)solution.As<EnvDTE.Solution>().DTE;
            dte2.ToolWindows.SolutionExplorer.SelectUp(vsUISelectionType.vsUISelectionTypeSelect, 99999);
        }

        [ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("55AB9450-F9C7-4305-94E8-BEF12065338D")]
        private interface IVsMonitorSelectionFixed
        {
            [PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
            int GetCurrentSelection([MarshalAs(UnmanagedType.Interface)] out IVsHierarchy ppHier, [ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSITEMID")] out uint pitemid, [MarshalAs(UnmanagedType.Interface)] out IVsMultiItemSelect ppMIS, [MarshalAs(UnmanagedType.Interface)] out ISelectionContainer ppSC);
            [PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
            int AdviseSelectionEvents([In, MarshalAs(UnmanagedType.Interface)] IVsSelectionEvents pSink, [ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSCOOKIE")] out uint pdwCookie);
            [PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
            int UnadviseSelectionEvents([In, ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSCOOKIE")] uint dwCookie);
            [PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
            int GetCurrentElementValue([In, ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSSELELEMID")] uint elementid, [MarshalAs(UnmanagedType.Struct)] out object pvarValue);
            [PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
            int GetCmdUIContextCookie([In, ComAliasName("Microsoft.VisualStudio.OLE.Interop.REFGUID")] ref Guid rguidCmdUI, [ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSCOOKIE")] out uint pdwCmdUICookie);
            [PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
            int IsCmdUIContextActive([In, ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSCOOKIE")] uint dwCmdUICookie, [ComAliasName("Microsoft.VisualStudio.OLE.Interop.BOOL")] out int pfActive);
            [PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
            int SetCmdUIContext([In, ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSCOOKIE")] uint dwCmdUICookie, [In, ComAliasName("Microsoft.VisualStudio.OLE.Interop.BOOL")] int fActive);
        }
    }
}


text:
require 'spec_helper'

describe Poise::Helpers::Win32User do
  let(:chefspec_options) { {platform: 'ubuntu', version: '14.04'} }
  provider(:poise_test)
  before do
    allow(Poise::Utils::Win32).to receive(:admin_user).and_return('Administrator')
  end

  context 'user property' do
    resource(:poise_test) do
      include Poise::Helpers::LWRPPolyfill
      include described_class
      attribute(:user, default: 'root')
    end

    context 'with a default' do
      recipe do
        poise_test 'test'
      end

      context 'on Linux' do
        it { is_expected.to run_poise_test('test').with(user: 'root') }
      end # /context on Linux

      context 'on Windows' do
        let(:chefspec_options) { {platform: 'windows', version: '2012R2'} }
        it { is_expected.to run_poise_test('test').with(user: 'Administrator') }
      end # /context on Windows
    end # /context with a default

    context 'with a value' do
      recipe do
        poise_test 'test' do
          user 'other'
        end
      end

      context 'on Linux' do
        it { is_expected.to run_poise_test('test').with(user: 'other') }
      end # /context on Linux

      context 'on Windows' do
        let(:chefspec_options) { {platform: 'windows', version: '2012R2'} }
        it { is_expected.to run_poise_test('test').with(user: 'other') }
      end # /context on Windows
    end # /context with a value
  end # /context user property

  context 'owner property' do
    resource(:poise_test) do
      include Poise::Helpers::LWRPPolyfill
      include described_class
      attribute(:owner, default: 'root')
    end

    context 'with a default' do
      recipe do
        poise_test 'test'
      end

      context 'on Linux' do
        it { is_expected.to run_poise_test('test').with(owner: 'root') }
      end # /context on Linux

      context 'on Windows' do
        let(:chefspec_options) { {platform: 'windows', version: '2012R2'} }
        it { is_expected.to run_poise_test('test').with(owner: 'Administrator') }
      end # /context on Windows
    end # /context with a default

    context 'with a value' do
      recipe do
        poise_test 'test' do
          owner 'other'
        end
      end

      context 'on Linux' do
        it { is_expected.to run_poise_test('test').with(owner: 'other') }
      end # /context on Linux

      context 'on Windows' do
        let(:chefspec_options) { {platform: 'windows', version: '2012R2'} }
        it { is_expected.to run_poise_test('test').with(owner: 'other') }
      end # /context on Windows
    end # /context with a value
  end # /context owner property

  context 'group property' do
    resource(:poise_test) do
      include Poise::Helpers::LWRPPolyfill
      include described_class
      attribute(:group, default: 'root')
    end

    context 'with a default' do
      recipe do
        poise_test 'test'
      end

      context 'on Linux' do
        it { is_expected.to run_poise_test('test').with(group: 'root') }
      end # /context on Linux

      context 'on Windows' do
        let(:chefspec_options) { {platform: 'windows', version: '2012R2'} }
        # This test is written to be silly because Fauxhai doesn't have
        # root_group data for Windows.
        it { is_expected.to run_poise_test('test').with(group: chef_run.node['root_group']) }
      end # /context on Windows

      context 'on AIX' do
        let(:chefspec_options) { {platform: 'aix', version: '6.1'} }
        it { is_expected.to run_poise_test('test').with(group: 'system') }
      end # /context on AIX
    end # /context with a default

    context 'with a value' do
      recipe do
        poise_test 'test' do
          group 'other'
        end
      end

      context 'on Linux' do
        it { is_expected.to run_poise_test('test').with(group: 'other') }
      end # /context on Linux

      context 'on Windows' do
        let(:chefspec_options) { {platform: 'windows', version: '2012R2'} }
        it { is_expected.to run_poise_test('test').with(group: 'other') }
      end # /context on Windows
    end # /context with a value
  end # /context group property

  describe 'interaction with lazy defaults' do
    let(:chefspec_options) { {platform: 'windows', version: '2012R2'} }
    recipe do
      poise_test 'test'
    end

    context 'with a non-lazy default' do
      resource(:poise_test) do
        include Poise::Resource
        attribute(:user, default: 'root')
      end

      it { is_expected.to run_poise_test('test').with(user: 'Administrator') }
    end # /context with a non-lazy default

    context 'with a lazy default' do
      resource(:poise_test) do
        include Poise::Resource
        attribute(:user, default: lazy { 'root' })
      end

      it { is_expected.to run_poise_test('test').with(user: 'root') }
    end # /context with a lazy default
  end # /describe interaction with lazy defaults
end


text:
function __export(m) {
    for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
Object.defineProperty(exports, "__esModule", { value: true });
var aurelia_framework_1 = require("aurelia-framework");
function configure(config) {
    config.globalResources([
        aurelia_framework_1.PLATFORM.moduleName("./value-converters/humanize-duration-vc"),
        aurelia_framework_1.PLATFORM.moduleName("./value-converters/moment-vc"),
        aurelia_framework_1.PLATFORM.moduleName("./value-converters/moment-timezone-vs"),
        aurelia_framework_1.PLATFORM.moduleName('./custom-elements/clock')
    ]);
}
exports.configure = configure;
__export(require("./custom-elements/clock"));

//# sourceMappingURL=aurelia-time.js.map


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">
    <title>Rascunho de tarefas</title>
    <link href="{{ asset('img/terminal.png') }}" rel="shortcut icon">

    <link href="{{ asset('/css/bootstrap.min.css')}}" rel="stylesheet">

    <link href="{{ asset('/css/default.css')}}" rel="stylesheet">

            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
                Toggle navigation

            </button>
            Rascunho de tarefas

Sair

Projetos

Necessidades

Tarefas

Tipos de tarefas

Status de tarefas

Relatórios:

Tarefas por responsável

Tarefas por projeto

Tarefas por status

        </fieldset>

    @yield('content')


text:
<?php

namespace HkApps\App\Http\Controllers\Admin;

use HkApps\App\Http\Controllers\Controller as BaseController;
use HkApps\App\Models\Admin;

/**
 * Class Controller.
 *
 * @package HkApps\App\Http\Controllers\Admin
 */
abstract class Controller extends BaseController
{
    /**
     * Admin instance.
     *
     * @var Admin
     */
    protected $admin;

    /**
     * Controller constructor.
     */
    public function __construct()
    {
        parent::__construct();
        $this->admin = app(Admin::class);
    }
}


text:
<?php

require_once(sfConfig::get('dm_core_dir').'/lib/config/dmModuleManagerConfigHandler.php');

class dmFrontModuleManagerConfigHandler extends dmModuleManagerConfigHandler
{

  protected function fixModuleConfig($moduleKey, $moduleConfig, $isInProject)
  {
    $moduleOptions = parent::fixModuleConfig($moduleKey, $moduleConfig, $isInProject);

    $moduleOptions['sf_name'] = dmArray::get($moduleOptions, 'sf_name', $moduleKey);

    return $moduleOptions;
  }

}


text:
namespace osu.Game.Rulesets
{
    public interface ILegacyRuleset
    {
        const int MAX_LEGACY_RULESET_ID = 3;

        /// <summary>
        /// Identifies the server-side ID of a legacy ruleset.
        /// </summary>
        int LegacyID { get; }
    }
}


text:
package se.omegapoint.facepalm.infrastructure.db;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import java.util.Date;

import static org.apache.commons.lang3.Validate.notBlank;
import static org.apache.commons.lang3.Validate.notNull;

@Entity
@Table(name = "FRIENDSHIPS")
public class Friendship {

    @Id
    @GeneratedValue
    @Column(name = "ID")
    public Long id;

    @Column(name = "USER_ID")
    public String user;

    @Column(name = "FRIEND_ID")
    public String friend;

    @Temporal(TemporalType.DATE)
    @Column(name = "FRIENDS_SINCE")
    private Date date;

    public Friendship() {
    }

    public Friendship(final String user, final String friend, final Date date) {
        this.user = notBlank(user);
        this.friend = notBlank(friend);
        this.date = notNull(date);
    }

    public Long getId() {
        return id;
    }

    public void setId(final Long id) {
        this.id = id;
    }

    public String getUser() {
        return user;
    }

    public void setUser(final String user) {
        this.user = user;
    }

    public String getFriend() {
        return friend;
    }

    public void setFriend(final String friend) {
        this.friend = friend;
    }

    public Date getDate() {
        return date;
    }

    public void setDate(final Date date) {
        this.date = date;
    }
}


text:
#include "scene.h"

#include <limits>
#include <QtCore/QPointF>
#include <QtGui/QKeyEvent>
#include <QtCore/QFile>
#include <QtCore/QDir>
#include <QtWidgets/QApplication>

using namespace qReal;

Scene::Scene(graphicsUtils::AbstractView *view, QObject * parent)
	:  AbstractScene(view, parent)
	, mItemType(none)
	, mWaitMove(false)
	, mCount(0)
	, mSelectedTextPicture(nullptr)
{
	mSizeEmptyRectX = sizeEmptyRectX;
	mSizeEmptyRectY = sizeEmptyRectY;
	setItemIndexMethod(NoIndex);
	setEmptyRect(0, 0, mSizeEmptyRectX, mSizeEmptyRectY);
	setEmptyPenBrushItems();
	mCopyPaste = nonePaste;
	mPortType = "NonTyped";

	connect(this, SIGNAL(selectionChanged()), this, SLOT(changePalette()));
	connect(this, SIGNAL(selectionChanged()), this, SLOT(changeFontPalette()));
	connect(this, SIGNAL(selectionChanged()), this, SLOT(changePortsComboBox()));

	mZValue = 0;
}

QRectF Scene::selectedItemsBoundingRect() const
{
	QRectF resBoundRect;
	QList<Item *> list = mListSelectedItemsForPaste;
	foreach (Item *graphicsItem, list)
		resBoundRect |= graphicsItem->sceneBoundingRect();
	return resBoundRect;
}

QPoint Scene::centerEmpty()
{
	return QPoint(sizeEmptyRectX / 2, sizeEmptyRectY / 2);
}

QPointF Scene::setCXandCY(QGraphicsSceneMouseEvent *event)
{
	qreal x = event->scenePos().x();
	qreal y = event->scenePos().y();
	return QPointF(x, y);
}

void Scene::reshapeLine(QGraphicsSceneMouseEvent *event)
{
	setX2andY2(event);
	mLine->setX2(mX2);
	mLine->setY2(mY2);
	if (event->modifiers() & Qt::ShiftModifier)
		mLine->reshapeRectWithShift();
}

void Scene::reshapeLinePort(QGraphicsSceneMouseEvent *event)
{
	setX2andY2(event);
	mLinePort->setX2(mX2);
	mLinePort->setY2(mY2);
	if (event->modifiers() & Qt::ShiftModifier)
		mLinePort->reshapeRectWithShift();
}

void Scene::reshapeEllipse(QGraphicsSceneMouseEvent *event)
{
	setX2andY2(event);
	mEllipse->setX2(mX2);
	mEllipse->setY2(mY2);
	if (event->modifiers() & Qt::ShiftModifier)
		mEllipse->reshapeRectWithShift();
}

void Scene::reshapeRectangle(QGraphicsSceneMouseEvent *event)
{
	setX2andY2(event);
	mRectangle->setX2(mX2);
	mRectangle->setY2(mY2);
	if (event->modifiers() & Qt::ShiftModifier)
		mRectangle->reshapeRectWithShift();
}

void Scene::reshapeStylus(QGraphicsSceneMouseEvent *event)
{
	setX2andY2(event);
	mStylus->addLine(mX2, mY2);
}

void Scene::reshapeCurveFirst(QGraphicsSceneMouseEvent *event)
{
	setX2andY2(event);
	mCurve->setX2(mX2);
	mCurve->setY2(mY2);
}

void Scene::reshapeCurveSecond(QGraphicsSceneMouseEvent *event)
{
	mC1 = setCXandCY(event);
	mCurve->setCXandCY(mC1.x(), mC1.y());
}

void Scene::setZValue(Item* item)
{
	item->setItemZValue(mZValue);
	mZValue++;
}

void Scene::setZValueSelectedItems()
{
	mListSelectedItems = selectedItems();
	foreach (QGraphicsItem *graphicsItem, mListSelectedItems) {
		Item* item = dynamic_cast<Item*>(graphicsItem);
		item->setZValue(mZValue);
		mZValue++;
	}
}

void Scene::setNullZValueItems()
{
	foreach (QGraphicsItem *graphicsItem, mListSelectedItems) {
		Item* item = dynamic_cast<Item*>(graphicsItem);
		item->setZValue(item->itemZValue());
	}
	mListSelectedItems.clear();
}

QPair<bool, Item *> Scene::checkOnResize(qreal x, qreal y)
{
	QList<Item *> list = selectedSceneItems();
	foreach (Item *item, list) {
		item->changeDragState(x, y);
		item->changeScalingPointState(x, y);
		if (item->dragState() != Item::None)  {
			mView->setDragMode(QGraphicsView::NoDrag);
			return QPair<bool, Item *>(true, item);
		}
	}
	return QPair<bool, Item *>(false, nullptr);
}

void Scene::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
	QGraphicsScene::mousePressEvent(event);
	setDragMode(mItemType);
	switch (mItemType) {
	case curve:
		if (mCount == 1)
			setX1andY1(event);
		else if (mCount == 2)
			reshapeCurveFirst(event);
		else if (mCount == 3)
			reshapeCurveSecond(event);
		removeMoveFlag(event, nullptr);
		mCount++;
		break;
	case stylus :
		setX1andY1(event);
		mStylus = new Stylus(mX1, mY1, nullptr);
		mStylus->setPenBrush(mPenStyleItems, mPenWidthItems, mPenColorItems, mBrushStyleItems, mBrushColorItems);
		addItem(mStylus);
		setZValue(mStylus);
		removeMoveFlag(event, mStylus);
		mWaitMove = true;
		break;
	case line :
		setX1andY1(event);
		mLine = new Line(mX1, mY1, mX1, mY1, nullptr);
		mLine->setPenBrush(mPenStyleItems, mPenWidthItems, mPenColorItems, mBrushStyleItems, mBrushColorItems);
		addItem(mLine);
		setZValue(mLine);
		removeMoveFlag(event, mLine);
		mWaitMove = true;
		break;
	case ellipse :
		setX1andY1(event);
		mEllipse = new QRealEllipse(mX1, mY1, mX1, mY1, nullptr);
		mEllipse->setPenBrush(mPenStyleItems, mPenWidthItems, mPenColorItems, mBrushStyleItems, mBrushColorItems);
		addItem(mEllipse);
		setZValue(mEllipse);
		removeMoveFlag(event, mEllipse);
		mWaitMove = true;
		break;
	case rectangle :
		setX1andY1(event);
		mRectangle = new QRealRectangle(mX1, mY1, mX1, mY1, nullptr);
		mRectangle->setPenBrush(mPenStyleItems, mPenWidthItems, mPenColorItems, mBrushStyleItems, mBrushColorItems);
		addItem(mRectangle);
		setZValue(mRectangle);
		removeMoveFlag(event, mRectangle);
		mWaitMove = true;
		break;
	case text:
		setX1andY1(event);
		mText = new Text(mX1, mY1, "text", false);
		addItem(mText);
		setZValue(mText);
		break;
	case dynamicText :
		setX1andY1(event);
		mText = new Text(mX1, mY1, "name", true);
		addItem(mText);
		setZValue(mText);
		break;
	case textPicture:
		setX1andY1(event);
		mTextPicture = new TextPicture(mX1, mY1, "text");
		addItem(mTextPicture);
		setZValue(mTextPicture);
		break;
	case pointPort :
		setX1andY1(event);
		mPointPort = new PointPort(mX1, mY1, nullptr);
		mPointPort->setType(mPortType);
		addItem(mPointPort);
		setZValue(mPointPort);
		break;
	case linePort :
		setX1andY1(event);
		mLinePort = new LinePort(mX1, mY1, mX1, mY1, nullptr);
		mLinePort->setType(mPortType);
		addItem(mLinePort);
		setZValue(mLinePort);
		removeMoveFlag(event, mLinePort);
		mWaitMove = true;
		break;
	case image :
		setX1andY1(event);
		mImage = new Image(mFileName, mX1, mY1, nullptr);
		addItem(mImage);
		setZValue(mImage);
		break;
	default:  // if we wait some resize
		setX1andY1(event);
		mGraphicsItem = dynamic_cast<graphicsUtils::AbstractItem *>(itemAt(event->scenePos(), QTransform()));
		if (mGraphicsItem != nullptr) {
			mGraphicsItem->changeDragState(mX1, mY1);
			Item *graphicsItem = dynamic_cast<Item *>(mGraphicsItem);
			graphicsItem->changeScalingPointState(mX1, mY1);
			forPressResize(event);
			if (graphicsItem->getScalingPointState() != Item::noneScale) {
				graphicsItem->setScalingPointColor();
				update();
			}
		}
		setZValueSelectedItems();
		break;
	}
}

void Scene::mouseMoveEvent( QGraphicsSceneMouseEvent *event)
{
	QGraphicsScene::mouseMoveEvent(event);
	setDragMode(mItemType);
	switch (mItemType) {
	case stylus :
		if (mWaitMove)
			reshapeStylus(event);
		break;
	case line :
		if (mWaitMove)
			reshapeLine(event);
		break;
	case ellipse :
		if (mWaitMove)
			reshapeEllipse(event);
		break;
	case rectangle :
		if (mWaitMove)
			reshapeRectangle(event);
		break;
	case curve:
		if (mCount == 2) {
			if (mCurve != nullptr)
				reshapeCurveFirst(event);
		} else if (mCount == 3)
			reshapeCurveSecond(event);
		break;
	case linePort :
		if (mWaitMove)
			reshapeLinePort(event);
		break;
	default:  // if we wait some resize
		forMoveResize(event);
		break;
	}
	update();
}

void Scene::mouseReleaseEvent ( QGraphicsSceneMouseEvent * event )
{
	QGraphicsScene::mouseReleaseEvent(event);
	setDragMode(mItemType);
	switch (mItemType) {
	case curve:
		if (mCount == 2) {
			setX2andY2(event);
			mCurve = new Curve(QPointF(mX1, mY1), QPointF(mX2, mY2), QPointF(mX1, mY1));
			mCurve->setPenBrush(mPenStyleItems, mPenWidthItems, mPenColorItems, mBrushStyleItems, mBrushColorItems);
			addItem(mCurve);
			setZValue(mCurve);
		} else if (mCount == 3)
			reshapeCurveSecond(event);
		break;
	case stylus :
		reshapeStylus(event);
		break;
	case line :
		reshapeLine(event);
		break;
	case ellipse :
		reshapeEllipse(event);
		break;
	case rectangle :
		reshapeRectangle(event);
		break;
	case linePort :
		reshapeLinePort(event);
		break;
	default:  // if we wait some resize
		forReleaseResize(event);
		break;
	}
	mWaitMove = false;
	setMoveFlag(event);
	setNullZValueItems();
	if (mItemType != curve || mCount > 3) {
		emit resetHighlightAllButtons();
		mItemType = none;
		mCount = 0;
		mCurve = nullptr;
	}
}

void Scene::initListSelectedItemsForPaste()
{
	mListSelectedItemsForPaste.clear();
	mListSelectedItemsForPaste = selectedSceneItems();
}

void Scene::keyPressEvent(QKeyEvent *keyEvent)
{
	QGraphicsScene::keyPressEvent(keyEvent);
	if (keyEvent->matches(QKeySequence::Cut)) {
		initListSelectedItemsForPaste();
		mCopyPaste = cut;
	} else if (keyEvent->matches(QKeySequence::Copy)) {
		initListSelectedItemsForPaste();
		mCopyPaste = copy;
	}
	else if (keyEvent->matches(QKeySequence::Paste)) {
		QPointF posCursor(mView->mapFromGlobal(QCursor::pos()));
		posCursor = mView->mapToScene(posCursor.toPoint());
		QPointF topLeftSelection(selectedItemsBoundingRect().topLeft());
		switch (mCopyPaste) {
		case copy:
			foreach(Item *item, mListSelectedItemsForPaste) {
				Item* newItem = item->clone();
				newItem->setPos(posCursor - topLeftSelection + item->scenePos());
				addItem(newItem);
				setZValue(newItem);
			}
			break;
		case cut:
			foreach(Item *item, mListSelectedItemsForPaste) {
				item->setPos(posCursor - topLeftSelection + item->scenePos());
				setZValue(item);
				mListSelectedItemsForPaste.clear();
			}
			break;
		default:
			break;
		}
	}
}

void Scene::drawLine(bool checked)
{
	if (checked)
		mItemType = line;
}

void Scene::drawEllipse(bool checked)
{
	if (checked)
		mItemType = ellipse;
}

void Scene::drawCurve(bool checked)
{
	if (checked) {
		mItemType = curve;
		mCount = 1;
		mCurve = nullptr;
	}
}

void Scene::drawRectangle(bool checked)
{
	if (checked)
		mItemType = rectangle;
}

void Scene::addText(bool checked)
{
	if (checked)
		mItemType = text;
}

void Scene::addDynamicText(bool checked)
{
	if (checked)
		mItemType = dynamicText;
}

void Scene::addTextPicture(bool checked)
{
	if (checked)
		mItemType = textPicture;
}

void Scene::addPointPort(bool checked)
{
	if (checked)
		mItemType = pointPort;
}

void Scene::addLinePort(bool checked)
{
	if (checked)
		mItemType = linePort;
}

void Scene::addStylus(bool checked)
{
	if (checked)
		mItemType = stylus;
}

void Scene::addNone(bool checked)
{
	if (checked) {
		mItemType = none;
		mCount = 0;
	}
}

void Scene::addImage(const QString &fileName)
{
	mItemType = image;
	mFileName = fileName;

	QString workingDirName = QFileInfo(QApplication::applicationFilePath()).absoluteDir().absolutePath();
	QDir dir(workingDirName);
	dir.mkdir("images");
	mFileName = workingDirName + "/images/" + fileName.section('/', -1);
	QFile::copy(fileName, mFileName);
}

void Scene::deleteItem()
{
	QList<QGraphicsItem *> list = selectedItems();
	foreach (QGraphicsItem *graphicsItem, list) {
		removeItem(graphicsItem);
		delete graphicsItem;
	}
}

void Scene::clearScene()
{
	clear();
	mEmptyRect = addRect(0, 0, sizeEmptyRectX, sizeEmptyRectY, QPen(Qt::white));
	mZValue = 0;
}

QList<Item *> Scene::selectedSceneItems()
{
	QList<Item *> resList;
	mListSelectedItems = selectedItems();
	foreach (QGraphicsItem *graphicsItem, mListSelectedItems) {
		Item* item = dynamic_cast<Item*>(graphicsItem);
		if (item != nullptr)
			resList.push_back(item);
	}
	qSort(resList.begin(), resList.end(), compareItems);
	return resList;
}

QList<TextPicture *> Scene::selectedTextPictureItems()
{
	QList<TextPicture *> resList;
	mListSelectedItems = selectedItems();
	foreach (QGraphicsItem *graphicsItem, mListSelectedItems) {
		TextPicture* item = dynamic_cast<TextPicture*>(graphicsItem);
		if (item != nullptr)
			resList.push_back(item);
	}
	return resList;
}

void Scene::changePenStyle(const QString &text)
{
	mPenStyleItems = text;
	foreach (Item *item, selectedSceneItems())
		item->setPenStyle(text);
	update();
}

void Scene::changePenWidth(int width)
{
	mPenWidthItems = width;
	foreach (Item *item, selectedSceneItems())
		item->setPenWidth(width);
	update();
}

void Scene::changePenColor(const QString &text)
{
	mPenColorItems = text;
	foreach (Item *item, selectedSceneItems())
		item->setPenColor(text);
	update();
}

void Scene::changeBrushStyle(const QString &text)
{
	mBrushStyleItems = text;
	foreach (Item *item, selectedSceneItems())
		item->setBrushStyle(text);
	update();
}

void Scene::changeBrushColor(const QString &text)
{
	mBrushColorItems = text;
	foreach (Item *item, selectedSceneItems())
		item->setBrushColor(text);
	update();
}

void Scene::changePortsType(const QString &type)
{
	mPortType = type;

	foreach (QGraphicsItem *item, selectedItems()) {
		PointPort *point = dynamic_cast<PointPort *>(item);
		if (point) {
			point->setType(type);
		} else {
			LinePort *line = dynamic_cast<LinePort *>(item);
			if (line) {
				line->setType(type);
			}
		}
	}

	update();
}

void Scene::changePalette()
{
	if(mItemType == none) {
		mListSelectedItems = selectedItems();
		if (mListSelectedItems.isEmpty()) {
			emit noSelectedItems();
			setEmptyPenBrushItems();
		}
		else {
			Item* item = dynamic_cast<Item*>(mListSelectedItems.back());
			if (item != nullptr) {
				QPen penItem = item->pen();
				QBrush brushItem = item->brush();
				emit existSelectedItems(penItem, brushItem);
				setPenBrushItems(penItem, brushItem);
			}
		}
	}
}

void Scene::changeFontPalette()
{
	mListSelectedTextPictureItems = selectedTextPictureItems();
	if (mListSelectedTextPictureItems.isEmpty())
		emit noSelectedTextPictureItems();
	else {
		TextPicture* item = dynamic_cast<TextPicture*>(mListSelectedTextPictureItems.back());
		if (item != nullptr) {
			QPen penItem = item->pen();
			QFont fontItem = item->font();
			emit existSelectedTextPictureItems(penItem, fontItem, item->name());
		}
	}
}

void Scene::changePortsComboBox()
{
	foreach (QGraphicsItem *item, selectedItems()) {
		PointPort *point = dynamic_cast<PointPort *>(item);
		if (point) {
			emit existSelectedPortItems(point->getType());
			return;
		}
		LinePort *line = dynamic_cast<LinePort *>(item);
		if (line) {
			emit existSelectedPortItems(line->getType());
			return;
		}
	}
	emit noSelectedPortItems();
}

void Scene::changeFontFamily(const QFont& font)
{
	foreach (TextPicture *item, selectedTextPictureItems())
		item->setFontFamily(font);
	update();
}

void Scene::changeFontPixelSize(int size)
{
	foreach (TextPicture *item, selectedTextPictureItems())
		item->setFontPixelSize(size);
	update();
}

void Scene::changeFontColor(const QString &text)
{
	foreach (TextPicture *item, selectedTextPictureItems())
		item->setFontColor(text);
	update();
}

void Scene::changeFontItalic(bool isChecked)
{
	foreach (TextPicture *item, selectedTextPictureItems())
		item->setFontItalic(isChecked);
	update();
}

void Scene::changeFontBold(bool isChecked)
{
	foreach (TextPicture *item, selectedTextPictureItems())
		item->setFontBold(isChecked);
	update();
}

void Scene::changeFontUnderline(bool isChecked)
{
	foreach (TextPicture *item, selectedTextPictureItems())
		item->setFontUnderline(isChecked);
	update();
}

void Scene::changeTextName(const QString &name)
{
	foreach (TextPicture *item, selectedTextPictureItems())
		item->setTextName(name);
	update();
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="TypingIndicatorView">
        <attr name="dotSize" format="dimension"/>
        <attr name="dotCount" format="integer"/>
        <attr name="dotColor" format="color"/>
        <attr name="dotSecondColor" format="color"/>
        <attr name="dotHorizontalSpacing" format="dimension"/>
        <attr name="dotMaxCompressRatio" format="fraction"/>
        <attr name="dotAnimationDuration" format="integer"/>
        <attr name="dotAnimationType" format="enum">
            <enum name="Grow" value="0"/>
            <enum name="Wink" value="1"/>
            <enum name="Disappear" value="2"/>
            <enum name="Sliding" value="3"/>
            <enum name="BouncingSliding" value="4"/>
        </attr>
        <attr name="showBackground" format="boolean"/>
        <attr name="backgroundColor" format="color"/>
        <attr name="backgroundType" format="enum">
            <enum name="square" value="0"/>
            <enum name="rounded" value="1"/>
        </attr>
        <attr name="animateFrequency" format="integer"/>
        <attr name="animationOrder" format="enum">
            <enum name="random" value="0"/>
            <enum name="sequence" value="1"/>
            <enum name="circular" value="2"/>
            <enum name="lastOneFirst" value="3"/>
            <enum name="random_no_repetition" value="4"/>
        </attr>
    </declare-styleable>
</resources>


text:
#ifndef HUMBLENET_P2P_INTERNAL
#define HUMBLENET_P2P_INTERNAL

#include "humblenet.h"
#include "libsocket.h"

#include "humblenet_p2p_signaling.h"

#include <memory>

// TODO: should have a way to disable this on release builds
#define LOG printf
#define TRACE( ... )

enum InOrOut
{
	Incoming
	, Outgoing
};

// Connection status
typedef enum ConnectionStatus {
	HUMBLENET_CONNECTION_CLOSED,
	HUMBLENET_CONNECTION_CONNECTING,
	HUMBLENET_CONNECTION_CONNECTED,
} ConnectionStatus;

struct Connection {
	InOrOut inOrOut;
	ConnectionStatus status;

	// peerId of the other peer
	// 0 if not a p2p connection
	PeerId otherPeer;

	std::vector<char> recvBuffer;

	ha_bool writable;

	struct internal_socket_t* socket;

	Connection( InOrOut inOrOut_, struct internal_socket_t *s = NULL)
	: inOrOut(inOrOut_)
	, status(HUMBLENET_CONNECTION_CONNECTING)
	, otherPeer(0)
	, writable(true)
	, socket(NULL)
	{
	}
};

typedef struct HumbleNetState {
	// established connections indexed by socket id
	// pointer not owned
	std::unordered_map<internal_socket_t *, Connection *> connections;

	// new incoming connections waiting accept
	std::unordered_set<Connection *> pendingNewConnections;

	// connections with pending data in buffer
	// pointer not owned
	std::unordered_set<Connection *> pendingDataConnections;

	// connections which have been closed by remote and need user notification
	std::unordered_set<Connection *> remoteClosedConnections;

	// pending outgoing (not established) p2p connections
	// pointer not owned (owned by whoever called humblenet_connect_peer)
	std::unordered_map<PeerId, Connection *> pendingPeerConnectionsOut;

	// pending incoming P2P connections
	// these ARE owned (until humblenet_connection_accept which removes them)
	std::unordered_map<PeerId, Connection *> pendingPeerConnectionsIn;

	// outgoing pending (not established) alias connections
	// pointer not owned
	std::unordered_map<std::string, Connection *> pendingAliasConnectionsOut;

	// map of peers that are blacklisted, value is when they they were blacklisted
	// incoming peers are added to this list when they are disconnected.
	// this is to prevent anemic connection attempts.
	std::unordered_map<PeerId, uint64_t> peerBlacklist;

	PeerId myPeerId;

	std::unique_ptr<humblenet::P2PSignalConnection> p2pConn;

	std::string signalingServerAddr;
	std::string gameToken;
	std::string gameSecret;
	std::string authToken;
	std::string reconnectToken;
	std::vector<humblenet::ICEServer> iceServers;

	ha_bool webRTCSupported;

	internal_context_t *context;

	HumbleNetState()
	:  myPeerId(0)
	, webRTCSupported(false)
	, context(NULL)
	{
	}
} HumbleNetState;

extern HumbleNetState humbleNetState;

#define INIT_GUARD( msg, check, ... ) \
if( ! (check) ) { humblenet_set_error( msg ); return __VA_ARGS__ ; }

// Initialize P2P system with websocket layer
ha_bool internal_p2p_register_protocol();

// internal...
void internal_poll_io();
void humblenet_connection_set_closed( Connection* conn );
bool is_peer_blacklisted( PeerId peer );
void blacklist_peer( PeerId peer );
void signal();

typedef void(*timer_callback_t)(void* data);
void humblenet_timer( timer_callback_t callback, int timeout, void* data);

void humblenet_lock();
void humblenet_unlock();

struct Guard {
    Guard() {
        humblenet_lock();
    }

    ~Guard() {
        humblenet_unlock();
    }
};

struct UnGuard {
    UnGuard() {
        humblenet_unlock();
    }

    ~UnGuard() {
        humblenet_lock();
    }
};

#ifdef EMSCRIPTEN
    #define HUMBLENET_GUARD()
    #define HUMBLENET_UNGUARD()
#else
    #define HUMBLENET_GUARD() Guard lock
#define HUMBLENET_UNGUARD() UnGuard unlock
#endif

/*
 * Shut down the P2P networking library
 */
HUMBLENET_API void HUMBLENET_CALL humblenet_p2p_shutdown();

/*
 * Get connection status
 */
ConnectionStatus humblenet_connection_status(Connection *connection);

/*
 * Connect to server server_addr
 */
Connection *humblenet_connect_websocket(const char *server_addr);

/*
 * Connect to peer peer_id
 */
Connection *humblenet_connect_peer(PeerId peer_id);

/*
 * Close the Connection
 */
void humblenet_connection_close(Connection *connection);

/*
 * Returns true if connection has data to read, false otherwise
 */
ha_bool humblenet_connection_is_readable(Connection *connection);

/*
 * Returns true if connection can be written into, false otherwise
 */
ha_bool humblenet_connection_is_writable(Connection *connection);

/*
 * Send data through Connection
 * Returns the number of bytes sent, -1 on error
 */
int humblenet_connection_write(Connection *connection, const void *buf, uint32_t bufsize);

/*
 * Receive data through Connection
 * Returns the number of bytes received, -1 on error
 */
int humblenet_connection_read(Connection *connection, void *buf, uint32_t bufsize);

/*
 * Receive data through Connection
 * Returns a malloc() -allocated buffer
 * You are responsible for freeing it
 * sets *retval to number of bytes in buffer or negative on error
 */
void *humblenet_connection_read_all(Connection *connection, int *retval);

/*
 * Poll all connections
 * timeout_ms Timeout in milliseconds
 * 0 = return immediately if no pending connections
 * negative = wait indefinitely
 * returns a connection with readable data, NULL if no such connections
 */
Connection *humblenet_poll_all(int timeout_ms);

/*
 * Poll a single connection
 * connection to poll
 * timeout_ms Timeout in milliseconds
 * 0 = return immediately if no pending connections
 * negative = wait indefinitely
 * returns true if readable
 */
ha_bool humblenet_connection_poll(Connection *connection, int timeout_ms);

/*
 * Accepts new connections
 * returns a new Connection (which you now own) or NULL if no new connections
 * Humblenet will include this connection in future humblenet_connection_poll calls
 */
Connection *humblenet_connection_accept();

/*
 * Get the PeerId of this connection
 * returns PeerId or 0 if not a p2p connection
 */
PeerId humblenet_connection_get_peer_id(Connection *connection);

uint64_t sys_milliseconds();

#endif // HUMBLENET_P2P_INTERNAL


text:
/**
 *
 */
package com.vaadin.demo.workoutlog;

import java.util.HashMap;
import java.util.Map;

import com.vaadin.data.Container;
import com.vaadin.data.Validator;
import com.vaadin.data.hbnutil.HbnContainer;
import com.vaadin.ui.ComboBox;
import com.vaadin.ui.Component;
import com.vaadin.ui.DateField;
import com.vaadin.ui.DefaultFieldFactory;
import com.vaadin.ui.Field;
import com.vaadin.ui.ListSelect;
import com.vaadin.ui.TextField;
import com.vaadin.ui.AbstractSelect.NewItemHandler;

public class MyFieldFactory extends DefaultFieldFactory {

    private HbnContainer<Type> trainingTypes;

    public MyFieldFactory(WorkoutLog app) {
        trainingTypes = new HbnContainer<Type>(Type.class, app);
    }

    @Override
    public Field createField(Container container, Object itemId,
            Object propertyId, Component uiContext) {

        /*
         * trainingType is manyToOne relation, give it a combobox
         */
        if (propertyId.equals("trainingType")) {
            return getTrainingTypeComboboxFor(itemId);
        }

        /*
         * Secondoarytypes is manyToMany relation, give it a multiselect list
         */
        if (propertyId.equals("secondaryTypes")) {
            return getSecondaryTypesList(itemId);
        }

        final Field f = super.createField(container, itemId, propertyId,
                uiContext);
        if (f != null) {
            if (f instanceof TextField) {
                TextField tf = (TextField) f;
                tf.setWidth("100%");
            }
            if (propertyId.equals("kilometers")) {
                f.setWidth("4em");
                f.addValidator(new Validator() {
                    public boolean isValid(Object value) {
                        try {
                            @SuppressWarnings("unused")
                            float f = Float.parseFloat((String) value);
                            return true;
                        } catch (Exception e) {
                            f.getWindow().showNotification("Bad number value");
                            f.setValue(0);
                            return false;
                        }
                    }

                    public void validate(Object value)
                            throws InvalidValueException {
                        // TODO Auto-generated method stub

                    }
                });
            }
            if (propertyId.equals("date")) {
                ((DateField) f).setResolution(DateField.RESOLUTION_MIN);
            }
        }
        return f;

    }

    private Map<Object, ListSelect> workoutIdToList = new HashMap<Object, ListSelect>();

    private Field getSecondaryTypesList(Object itemId) {
        ListSelect list = workoutIdToList.get(itemId);
        if (list == null) {
            list = new ListSelect();
            list.setMultiSelect(true);
            list.setContainerDataSource(trainingTypes);
            list.setItemCaptionPropertyId("title");
            list.setRows(4);
            workoutIdToList.put(itemId, list);
        }
        return list;
    }

    private Map<Object, ComboBox> workoutIdToCombobox = new HashMap<Object, ComboBox>();

    private Field getTrainingTypeComboboxFor(Object itemId) {
        ComboBox cb = workoutIdToCombobox.get(itemId);
        if (cb == null) {
            final ComboBox cb2 = new ComboBox();
            cb2.setContainerDataSource(trainingTypes);
            cb2.setItemCaptionPropertyId("title");
            cb2.setNewItemsAllowed(true);

            /*
             * NewItemHandler so that new training types can be added fluently
             * by typing it into combobox.
             */
            cb2.setNewItemHandler(new NewItemHandler() {
                public void addNewItem(String newItemCaption) {
                    Object identifier = trainingTypes.addItem();
                    trainingTypes.getContainerProperty(identifier, "title")
                            .setValue(newItemCaption);
                    cb2.setValue(identifier);
                }
            });
            workoutIdToCombobox.put(itemId, cb2);
            cb = cb2;
        }
        return cb;
    }

}


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

namespace MarkDownHtmlGenerator
{
    class Program
    {
        static void Main(string[] args)
        {
            var options = new CommandLineOptions();
            string[] currentMarkdownFile = { string.Empty }; // Used for passing current file to Url qualify.

            if (CommandLine.Parser.Default.ParseArguments(args, options))
            {
                if (!Directory.Exists(options.Path))
                {
                    Console.WriteLine("Path {0} NOT Exists", options.Path);
                    Environment.Exit(1);
                }
                var fileNameList = new List<string>();

                // SearchPartten Files
                if (!string.IsNullOrEmpty(options.SearchPartten))
                {
                    var searchFiles = Directory.GetFiles(options.Path, options.SearchPartten);
                    fileNameList.AddRange(searchFiles);
                }

                // Parameter Files
                if (!string.IsNullOrEmpty(options.Files))
                {
                    var paramFileList = options.Files.Split(new[] { ',', ' ' });
                    foreach (var psf in paramFileList)
                    {
                        if (!File.Exists(Path.Combine(options.Path, psf)))
                        {
                            Console.WriteLine("{0} NOT Exists. Check Files argument", psf);
                            Environment.Exit(1);
                        }

                        if (!fileNameList.Contains(psf))
                            fileNameList.Add(psf);
                        else
                            if (options.Verbose)
                                Console.WriteLine("{0} have include in Search pattern list,ignore", psf);
                    }
                }

                // No SearchPattern AND No Parameter Files, Search all .md files
                if (string.IsNullOrEmpty(options.SearchPartten) && string.IsNullOrEmpty(options.Files))
                {
                    var searchFiles = Directory.GetFiles(options.Path, "*.md");
                    fileNameList.AddRange(searchFiles);
                }

                if (fileNameList.Count == 0)
                {
                    Console.WriteLine("No Files to process");
                    Environment.Exit(0);
                }

                var markdown = new MarkdownFix()
                {
                    ExtraMode = true,
                    SafeMode = false,
                    QualifyUrl = (href) => options.ResoveLinkedMarkdown ? QualifyUrl(href, currentMarkdownFile[0], fileNameList) : href
                };

                int processCount = 0;
                foreach (var file in fileNameList)
                {
                    if (!File.Exists(file))
                    {
                        if (options.Verbose)
                            Console.WriteLine("{0} NOT Exists", file);
                        continue;
                    }

                    // Generator html
                    processCount++;
                    string htmlFile = Path.Combine(options.Output ?? options.Path,
                        Path.GetFileNameWithoutExtension(file) + ".html");
                    using (var markdownReader = new StreamReader(file))
                    {
                        currentMarkdownFile[0] = file; // Used to qualify Urls

                        string markdownContent = markdownReader.ReadToEnd();
                        string htmlContent = markdown.Transform(markdownContent);

                        using (StreamWriter sw = File.CreateText(htmlFile))
                        {
                            // html header
                            sw.WriteLine("<!Doctype html>");
                            sw.WriteLine("");
                            sw.WriteLine("<meta http-equiv=\"Content-Type\" content=\"text/html;charset=utf-8\">");
                            if (!string.IsNullOrEmpty(options.CssFile))
                            {
                                sw.WriteLine(" <link href=\"" + options.CssFile + "\" media=\"all\" rel=\"stylesheet\" type=\"text/css\" />");
                            }

                            sw.WriteLine("");
                            sw.WriteLine("");
                            sw.Write(htmlContent);
                            // html end
                            sw.WriteLine("");
                            sw.WriteLine("");
                            sw.Close();
                        }

                        if (options.Verbose)
                            Console.WriteLine("{0}:{1}", htmlFile,
                                string.IsNullOrEmpty(htmlContent) ? 0 : htmlContent.Length);

                        markdownReader.Close();
                    }

                }
                Console.WriteLine("Generated Total:{0}", processCount);
                Environment.Exit(0);
            }

            Environment.Exit(1);
        }

        private static string QualifyUrl(string href, string currentFile, IList<string> files)
        {
            if (href.StartsWith("/") || href.StartsWith("#") || href.Contains("://") || href.StartsWith("mailto:"))
                return href;

            var hrefPath = Path.GetFullPath(Path.Combine(Path.GetDirectoryName(currentFile), href));
            if (files.Contains(hrefPath))
            {
                return Path.ChangeExtension(href, ".html");
            }

            return href;
        }
    }
}


text:
PACKAGE_NAME=log4j-core
#PACKAGE_VERSION is configurable can be passed as an argument.
PACKAGE_VERSION=${1:-rel/2.17.1}
PACKAGE_URL=https://github.com/apache/logging-log4j2.git

yum install -y git maven

OS_NAME=$(cat /etc/os-release | grep ^PRETTY_NAME | cut -d= -f2)

#Check if package exists
if [ -d "$PACKAGE_NAME" ] ; then
  rm -rf $PACKAGE_NAME
  echo "$PACKAGE_NAME  | $PACKAGE_VERSION | $OS_NAME | GitHub | Removed existing package if any"

fi

if ! git clone $PACKAGE_URL $PACKAGE_NAME; then
    	echo "------------------$PACKAGE_NAME:clone_fails---------------------------------------"
		echo "$PACKAGE_URL $PACKAGE_NAME"
        echo "$PACKAGE_NAME  |  $PACKAGE_URL |  $PACKAGE_VERSION | $OS_NAME | GitHub | Fail |  Clone_Fails"
    	exit 0
fi

cd  $PACKAGE_NAME
git checkout $PACKAGE_VERSION

cd log4j-core

if ! mvn compile; then
    echo "------------------$PACKAGE_NAME:build_fails-------------------------------------"
	echo "$PACKAGE_URL $PACKAGE_NAME"
	echo "$PACKAGE_NAME  |  $PACKAGE_URL | $PACKAGE_VERSION | $OS_NAME | GitHub | Fail |  Build_Fails"
	exit 1
fi

if ! mvn test; then
	echo "------------------$PACKAGE_NAME:build_success_but_test_fails---------------------"
	echo "$PACKAGE_URL $PACKAGE_NAME"
	echo "$PACKAGE_NAME  |  $PACKAGE_URL | $PACKAGE_VERSION | $OS_NAME | GitHub | Fail |  Build_success_but_test_Fails"
	exit 1
else
	echo "------------------$PACKAGE_NAME:build_&_test_both_success-------------------------"
	echo "$PACKAGE_URL $PACKAGE_NAME"
	echo "$PACKAGE_NAME  |  $PACKAGE_URL | $PACKAGE_VERSION | $OS_NAME | GitHub  | Pass |  Both_Build_and_Test_Success"
	exit 0
fi